human/dist/human.esm.js

46864 lines
1.8 MiB

/*
Human
homepage: <https://github.com/vladmandic/human>
author: <https://github.com/vladmandic>'
*/
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, b10) => (typeof require !== "undefined" ? require : a)[b10]
}) : 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, all2) => {
__markAsModule(target);
for (var name in all2)
__defProp(target, name, { get: all2[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 dt2 = new Date();
const ts2 = `${dt2.getHours().toString().padStart(2, "0")}:${dt2.getMinutes().toString().padStart(2, "0")}:${dt2.getSeconds().toString().padStart(2, "0")}.${dt2.getMilliseconds().toString().padStart(3, "0")}`;
if (msg)
console.log(ts2, "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: () => ti,
Acos: () => Mi,
Acosh: () => Li,
AdadeltaOptimizer: () => Hu,
AdagradOptimizer: () => qu,
AdamOptimizer: () => Ku,
AdamaxOptimizer: () => Xu,
Add: () => jn,
AddN: () => $o,
All: () => zi,
Any: () => Bi,
ArgMax: () => Ro,
ArgMin: () => ml,
Asin: () => Vi,
Asinh: () => Gi,
Atan: () => Wi,
Atan2: () => ji,
Atanh: () => Ui,
AvgPool: () => Fo,
AvgPool3D: () => fl,
AvgPool3DGrad: () => Uc,
AvgPoolGrad: () => Wc,
BackendWasm: () => xb,
BatchMatMul: () => Oo,
BatchToSpaceND: () => ri,
Bincount: () => jc,
BroadcastArgs: () => Hc,
BroadcastTo: () => rN,
Callback: () => Sv,
CallbackList: () => Lk,
Cast: () => eo,
Ceil: () => Po,
ClipByValue: () => to,
Complex: () => qc,
ComplexAbs: () => dl,
Concat: () => ni,
Conv2D: () => Mo,
Conv2DBackpropFilter: () => Kc,
Conv2DBackpropInput: () => Lo,
Conv3D: () => hl,
Conv3DBackpropFilterV2: () => Xc,
Conv3DBackpropInputV2: () => Yc,
Cos: () => zo,
Cosh: () => Bo,
CropAndResize: () => Hi,
Cumsum: () => Vo,
CustomCallback: () => Bk,
DataStorage: () => pl,
DenseBincount: () => Zc,
DepthToSpace: () => qi,
DepthwiseConv2dNative: () => Go,
DepthwiseConv2dNativeBackpropFilter: () => Jc,
DepthwiseConv2dNativeBackpropInput: () => Qc,
Diag: () => ep,
Dilation2D: () => gl,
Dilation2DBackpropFilter: () => rf,
Dilation2DBackpropInput: () => tf,
ENV: () => Xw,
EarlyStopping: () => Nv,
Einsum: () => tp,
Elu: () => Uo,
EluGrad: () => rp,
Environment: () => Eg,
Equal: () => Xi,
Erf: () => Ki,
Exp: () => jo,
ExpandDims: () => oi,
Expm1: () => Yi,
FFT: () => np,
Fill: () => xl,
FlipLeftRight: () => Zi,
Floor: () => Ho,
FloorDiv: () => qo,
FromPixels: () => nf,
FusedBatchNorm: () => Ko,
FusedConv2D: () => xi,
FusedDepthwiseConv2D: () => yi,
GPGPUContext: () => Xy,
GatherNd: () => Ji,
GatherV2: () => si,
GraphModel: () => ly,
Greater: () => Qi,
GreaterEqual: () => Xo,
History: () => zk,
IFFT: () => op,
Identity: () => ro,
Imag: () => sp,
InputSpec: () => Tt,
IsFinite: () => ea,
IsInf: () => ta,
IsNan: () => ra,
KernelBackend: () => Js,
LRN: () => yl,
LRNGrad: () => ap,
LayerVariable: () => Ex,
LayersModel: () => Yn,
LeakyRelu: () => Yo,
Less: () => na,
LessEqual: () => oa,
LinSpace: () => ip,
Log: () => Zo,
Log1p: () => sa,
LogSoftmax: () => nN,
LogicalAnd: () => ia,
LogicalNot: () => au,
LogicalOr: () => lu,
MathBackendWebGL: () => _c,
Max: () => Jo,
MaxPool: () => es,
MaxPool3D: () => bl,
MaxPool3DGrad: () => up,
MaxPoolGrad: () => lp,
MaxPoolWithArgmax: () => cp,
Maximum: () => Qo,
Mean: () => ts,
Min: () => rs,
Minimum: () => ns,
MirrorPad: () => os,
Mod: () => aa,
MomentumOptimizer: () => Yu,
Multinomial: () => pp,
Multiply: () => ss,
Neg: () => ii,
NonMaxSuppressionV3: () => ua,
NonMaxSuppressionV4: () => ca,
NonMaxSuppressionV5: () => pa,
NotEqual: () => la,
OP_SCOPE_SUFFIX: () => $N,
OneHot: () => is,
OnesLike: () => ai,
Optimizer: () => qr,
Pack: () => li,
PadV2: () => as,
Pool: () => hse,
Pow: () => ls,
Prelu: () => us,
Prod: () => ma,
RMSPropOptimizer: () => Zu,
RNN: () => Ln,
Range: () => wl,
Rank: () => s_,
Real: () => mp,
RealDiv: () => Wo,
Reciprocal: () => fa,
Reduction: () => Yt,
Relu: () => cs,
Relu6: () => ms,
Reshape: () => ui,
ResizeBilinear: () => ps,
ResizeBilinearGrad: () => dp,
ResizeNearestNeighbor: () => _l,
ResizeNearestNeighborGrad: () => fp,
Reverse: () => fs,
RotateWithOffset: () => ka,
Round: () => ds,
Rsqrt: () => hs,
SGDOptimizer: () => Ga,
ScatterNd: () => da,
Select: () => ci,
Selu: () => ha,
Sequential: () => qa,
Sigmoid: () => xs,
Sign: () => xa,
Sin: () => gs,
Sinh: () => ga,
Slice: () => pi,
Softmax: () => ws,
Softplus: () => ya,
SpaceToBatchND: () => mi,
SparseFillEmptyRows: () => hp,
SparseReshape: () => gp,
SparseSegmentMean: () => xp,
SparseSegmentSum: () => yp,
SparseToDense: () => bp,
SplitV: () => fi,
Sqrt: () => ys,
Square: () => kl,
SquaredDifference: () => _s,
Step: () => no,
StridedSlice: () => ba,
StringNGrams: () => wp,
StringSplit: () => _p,
StringToHashBucketFast: () => kp,
Sub: () => ks,
Sum: () => bs,
SymbolicTensor: () => cn,
Tan: () => vs,
Tanh: () => Cs,
Tensor: () => Le,
TensorBuffer: () => mt,
Tile: () => Hn,
TopK: () => wa,
Transform: () => _a,
Transpose: () => Is,
Unique: () => vp,
Unpack: () => di,
UnsortedSegmentSum: () => vl,
Variable: () => Sl,
ZerosLike: () => hi,
_FusedMatMul: () => gi,
abs: () => Ct,
acos: () => df,
acosh: () => hf,
add: () => Z,
addN: () => F_,
all: () => wu,
any: () => El,
argMax: () => As,
argMin: () => gf,
asin: () => xf,
asinh: () => yf,
atan: () => bf,
atan2: () => wf,
atanh: () => _f,
avgPool: () => Ta,
avgPool3d: () => kf,
backend: () => A1,
backend_util: () => I,
basicLSTMCell: () => IU,
batchNorm: () => lo,
batchNorm2d: () => L_,
batchNorm3d: () => z_,
batchNorm4d: () => B_,
batchToSpaceND: () => Ea,
bincount: () => vf,
booleanMaskAsync: () => JSe,
broadcastArgs: () => V_,
broadcastTo: () => Aa,
browser: () => Gg,
buffer: () => Ie,
callbacks: () => PX,
cast: () => Y,
ceil: () => Cf,
clipByValue: () => gr,
clone: () => wn,
complex: () => Pn,
concat: () => tt,
concat1d: () => G_,
concat2d: () => W_,
concat3d: () => U_,
concat4d: () => j_,
constraints: () => W2,
conv1d: () => vu,
conv2d: () => nn,
conv2dTranspose: () => Cu,
conv3d: () => If,
conv3dTranspose: () => H_,
copyRegisteredKernels: () => kse,
cos: () => Da,
cosh: () => Iu,
cosineWindow: () => sx,
cumsum: () => Su,
customGrad: () => on,
data: () => v$,
denseBincount: () => q_,
deprecationWarn: () => R_,
depthToSpace: () => Sf,
depthwiseConv2d: () => $s,
deregisterOp: () => LX,
device_util: () => xu,
diag: () => ej,
dilation2d: () => Nf,
disableDeprecationWarnings: () => sue,
dispose: () => De,
disposeVariables: () => iue,
div: () => ce,
divNoNan: () => Tf,
dot: () => K_,
dropout: () => eT,
einsum: () => X_,
elu: () => Rs,
enableDebugMode: () => oue,
enableProdMode: () => nue,
enclosingPowerOfTwo: () => tT,
engine: () => Es,
env: () => U,
equal: () => kr,
erf: () => Ef,
exp: () => Kt,
expandDims: () => mr,
expm1: () => Af,
eye: () => Lp,
fft: () => Ba,
fill: () => Fs,
findBackend: () => mue,
findBackendFactory: () => fue,
floor: () => Os,
floorDiv: () => bu,
forceHalfFloat: () => XP,
fused: () => fo,
gather: () => uo,
gatherND: () => J1,
gather_util: () => Wg,
getBackend: () => cue,
getGradient: () => Jw,
getKernel: () => sf,
getKernelsForBackend: () => Ag,
getThreadsCount: () => Koe,
gpgpu_util: () => XO,
grad: () => Aj,
grads: () => Dj,
greater: () => zt,
greaterEqual: () => kn,
ifft: () => _i,
imag: () => Nu,
image: () => Cn,
inTopKAsync: () => l1e,
initializers: () => uA,
input: () => Xk,
io: () => Lr,
irfft: () => zu,
isFinite: () => Y_,
isInf: () => Z_,
isNaN: () => Df,
keep: () => Ft,
kernel_impls: () => Gr,
layers: () => UA,
leakyRelu: () => $a,
less: () => Tu,
lessEqual: () => vn,
linalg: () => BT,
linspace: () => J_,
loadGraphModel: () => m7,
loadLayersModel: () => K5,
localResponseNormalization: () => $f,
log: () => xr,
log1p: () => Ra,
logSigmoid: () => Q_,
logSoftmax: () => Eu,
logSumExp: () => Ff,
logicalAnd: () => Cr,
logicalNot: () => Fa,
logicalOr: () => Au,
logicalXor: () => nk,
losses: () => oFe,
matMul: () => ze,
math: () => p1,
max: () => Rr,
maxPool: () => Oa,
maxPool3d: () => Of,
maxPoolWithArgmax: () => ok,
maximum: () => sn,
mean: () => xt,
memory: () => ff,
meshgrid: () => Qj,
metrics: () => jA,
min: () => Al,
minimum: () => Ps,
mirrorPad: () => Pf,
mod: () => Mf,
model: () => H5,
models: () => HA,
moments: () => zp,
movingAverage: () => CNe,
mul: () => O,
multiRNNCell: () => aH,
multinomial: () => sk,
neg: () => He,
nextFrame: () => wk,
norm: () => Wp,
notEqual: () => mo,
oneHot: () => Ts,
ones: () => or,
onesLike: () => fr,
op: () => N,
outerProduct: () => mH,
pad: () => jr,
pad1d: () => hH,
pad2d: () => xH,
pad3d: () => bH,
pad4d: () => _H,
pool: () => ik,
pow: () => Hr,
prelu: () => Ma,
print: () => C_,
prod: () => Du,
profile: () => aue,
rand: () => AH,
randomGamma: () => LH,
randomNormal: () => tx,
randomUniform: () => Ms,
range: () => La,
ready: () => uue,
real: () => Dl,
reciprocal: () => Lf,
registerBackend: () => Op,
registerCallbackConstructor: () => X5,
registerGradient: () => oN,
registerKernel: () => uu,
registerOp: () => MX,
regularizers: () => qA,
relu: () => Ir,
relu6: () => Ru,
removeBackend: () => pue,
reshape: () => F,
reverse: () => er,
reverse1d: () => qH,
reverse2d: () => XH,
reverse3d: () => ZH,
reverse4d: () => QH,
rfft: () => Va,
round: () => Fu,
rsqrt: () => Ou,
scalar: () => pe,
scatterND: () => Y1,
scatter_util: () => jg,
selu: () => Pu,
separableConv2d: () => zf,
sequential: () => q5,
serialization: () => ee,
setBackend: () => q4,
setPlatform: () => due,
setThreadsCount: () => qoe,
setWasmPath: () => joe,
setWasmPaths: () => Hoe,
setWebGLContext: () => tC,
setdiff1dAsync: () => xk,
sigmoid: () => zr,
sign: () => Bf,
signal: () => DRe,
sin: () => Mu,
sinh: () => Lu,
slice: () => Oe,
slice1d: () => Vf,
slice2d: () => rx,
slice3d: () => Gf,
slice4d: () => Vp,
slice_util: () => pr,
softmax: () => za,
softplus: () => co,
spaceToBatchND: () => Pa,
sparse: () => Kf,
sparseToDense: () => ox,
spectral: () => SRe,
split: () => sr,
sqrt: () => bt,
square: () => Ve,
squaredDifference: () => Bu,
squeeze: () => Br,
stack: () => Xt,
step: () => Ls,
stridedSlice: () => Wf,
string: () => hx,
sub: () => le,
sum: () => me,
sumOutType: () => hu,
tan: () => Uf,
tanh: () => Ds,
tensor: () => Dr,
tensor1d: () => $t,
tensor2d: () => ki,
tensor3d: () => T_,
tensor4d: () => Iq,
tensor5d: () => Sq,
tensor6d: () => Nq,
tensor_util: () => ao,
test_util: () => T1,
tidy: () => V,
tile: () => vr,
time: () => lue,
topk: () => jf,
train: () => Ju,
transpose: () => Be,
truncatedNormal: () => Vu,
unique: () => Gp,
unregisterGradient: () => _se,
unregisterKernel: () => wse,
unsortedSegmentSum: () => Hf,
unstack: () => yr,
upcastType: () => hr,
util: () => b,
valueAndGrad: () => $j,
valueAndGrads: () => Rj,
variable: () => yk,
variableGrads: () => Zg,
version: () => sse,
version_converter: () => SD,
version_core: () => E1,
version_layers: () => lm,
version_wasm: () => Xoe,
version_webgl: () => KP,
webgl: () => LTt,
webgl_util: () => zO,
where: () => St,
whereAsync: () => qf,
zeros: () => yt,
zerosLike: () => Se
});
var sW = Object.create;
var Sg = Object.defineProperty;
var iW = Object.getOwnPropertyDescriptor;
var aW = Object.getOwnPropertyNames;
var lW = Object.getPrototypeOf;
var uW = Object.prototype.hasOwnProperty;
var XS = (r) => Sg(r, "__esModule", { value: true });
var Lc = ((r) => typeof __require != "undefined" ? __require : typeof Proxy != "undefined" ? new Proxy(r, { get: (e, t) => (typeof __require != "undefined" ? __require : e)[t] }) : r)(function(r) {
if (typeof __require != "undefined")
return __require.apply(this, arguments);
throw new Error('Dynamic require of "' + r + '" is not supported');
});
var qt = (r, e) => () => (e || r((e = { exports: {} }).exports, e), e.exports);
var qe = (r, e) => {
XS(r);
for (var t in e)
Sg(r, t, { get: e[t], enumerable: true });
};
var cW = (r, e, t) => {
if (e && typeof e == "object" || typeof e == "function")
for (let n of aW(e))
!uW.call(r, n) && n !== "default" && Sg(r, n, { get: () => e[n], enumerable: !(t = iW(e, n)) || t.enumerable });
return r;
};
var ou = (r) => cW(XS(Sg(r != null ? sW(lW(r)) : {}, "default", r && r.__esModule && "default" in r ? { get: () => r.default, enumerable: true } : { value: r, enumerable: true })), r);
var hN = qt((Cse, dN) => {
dN.exports = Wt;
var oo = null;
try {
oo = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
} catch (r) {
}
function Wt(r, e, t) {
this.low = r | 0, this.high = e | 0, this.unsigned = !!t;
}
Wt.prototype.__isLong__;
Object.defineProperty(Wt.prototype, "__isLong__", { value: true });
function Fn(r) {
return (r && r.__isLong__) === true;
}
Wt.isLong = Fn;
var sN = {}, iN = {};
function cu(r, e) {
var t, n, o;
return e ? (r >>>= 0, (o = 0 <= r && r < 256) && (n = iN[r], n) ? n : (t = Ut(r, (r | 0) < 0 ? -1 : 0, true), o && (iN[r] = t), t)) : (r |= 0, (o = -128 <= r && r < 128) && (n = sN[r], n) ? n : (t = Ut(r, r < 0 ? -1 : 0, false), o && (sN[r] = t), t));
}
Wt.fromInt = cu;
function so(r, e) {
if (isNaN(r))
return e ? pu : io;
if (e) {
if (r < 0)
return pu;
if (r >= lN)
return fN;
} else {
if (r <= -uN)
return On;
if (r + 1 >= uN)
return mN;
}
return r < 0 ? so(-r, e).neg() : Ut(r % Ip | 0, r / Ip | 0, e);
}
Wt.fromNumber = so;
function Ut(r, e, t) {
return new Wt(r, e, t);
}
Wt.fromBits = Ut;
var Dg = Math.pow;
function e_(r, e, t) {
if (r.length === 0)
throw Error("empty string");
if (r === "NaN" || r === "Infinity" || r === "+Infinity" || r === "-Infinity")
return io;
if (typeof e == "number" ? (t = e, e = false) : e = !!e, t = t || 10, t < 2 || 36 < t)
throw RangeError("radix");
var n;
if ((n = r.indexOf("-")) > 0)
throw Error("interior hyphen");
if (n === 0)
return e_(r.substring(1), e, t).neg();
for (var o = so(Dg(t, 8)), s = io, a = 0; a < r.length; a += 8) {
var i = Math.min(8, r.length - a), l = parseInt(r.substring(a, a + i), t);
if (i < 8) {
var u = so(Dg(t, i));
s = s.mul(u).add(so(l));
} else
s = s.mul(o), s = s.add(so(l));
}
return s.unsigned = e, s;
}
Wt.fromString = e_;
function Ss(r, e) {
return typeof r == "number" ? so(r, e) : typeof r == "string" ? e_(r, e) : Ut(r.low, r.high, typeof e == "boolean" ? e : r.unsigned);
}
Wt.fromValue = Ss;
var aN = 1 << 16, RW = 1 << 24, Ip = aN * aN, lN = Ip * Ip, uN = lN / 2, cN = cu(RW), io = cu(0);
Wt.ZERO = io;
var pu = cu(0, true);
Wt.UZERO = pu;
var Sp = cu(1);
Wt.ONE = Sp;
var pN = cu(1, true);
Wt.UONE = pN;
var t_ = cu(-1);
Wt.NEG_ONE = t_;
var mN = Ut(4294967295 | 0, 2147483647 | 0, false);
Wt.MAX_VALUE = mN;
var fN = Ut(4294967295 | 0, 4294967295 | 0, true);
Wt.MAX_UNSIGNED_VALUE = fN;
var On = Ut(0, 2147483648 | 0, false);
Wt.MIN_VALUE = On;
var we = Wt.prototype;
we.toInt = function() {
return this.unsigned ? this.low >>> 0 : this.low;
};
we.toNumber = function() {
return this.unsigned ? (this.high >>> 0) * Ip + (this.low >>> 0) : this.high * Ip + (this.low >>> 0);
};
we.toString = function(e) {
if (e = e || 10, e < 2 || 36 < e)
throw RangeError("radix");
if (this.isZero())
return "0";
if (this.isNegative())
if (this.eq(On)) {
var t = so(e), n = this.div(t), o = n.mul(t).sub(this);
return n.toString(e) + o.toInt().toString(e);
} else
return "-" + this.neg().toString(e);
for (var s = so(Dg(e, 6), this.unsigned), a = this, i = ""; ; ) {
var l = a.div(s), u = a.sub(l.mul(s)).toInt() >>> 0, c = u.toString(e);
if (a = l, a.isZero())
return c + i;
for (; c.length < 6; )
c = "0" + c;
i = "" + c + i;
}
};
we.getHighBits = function() {
return this.high;
};
we.getHighBitsUnsigned = function() {
return this.high >>> 0;
};
we.getLowBits = function() {
return this.low;
};
we.getLowBitsUnsigned = function() {
return this.low >>> 0;
};
we.getNumBitsAbs = function() {
if (this.isNegative())
return this.eq(On) ? 64 : this.neg().getNumBitsAbs();
for (var e = this.high != 0 ? this.high : this.low, t = 31; t > 0 && (e & 1 << t) == 0; t--)
;
return this.high != 0 ? t + 33 : t + 1;
};
we.isZero = function() {
return this.high === 0 && this.low === 0;
};
we.eqz = we.isZero;
we.isNegative = function() {
return !this.unsigned && this.high < 0;
};
we.isPositive = function() {
return this.unsigned || this.high >= 0;
};
we.isOdd = function() {
return (this.low & 1) == 1;
};
we.isEven = function() {
return (this.low & 1) == 0;
};
we.equals = function(e) {
return Fn(e) || (e = Ss(e)), this.unsigned !== e.unsigned && this.high >>> 31 == 1 && e.high >>> 31 == 1 ? false : this.high === e.high && this.low === e.low;
};
we.eq = we.equals;
we.notEquals = function(e) {
return !this.eq(e);
};
we.neq = we.notEquals;
we.ne = we.notEquals;
we.lessThan = function(e) {
return this.comp(e) < 0;
};
we.lt = we.lessThan;
we.lessThanOrEqual = function(e) {
return this.comp(e) <= 0;
};
we.lte = we.lessThanOrEqual;
we.le = we.lessThanOrEqual;
we.greaterThan = function(e) {
return this.comp(e) > 0;
};
we.gt = we.greaterThan;
we.greaterThanOrEqual = function(e) {
return this.comp(e) >= 0;
};
we.gte = we.greaterThanOrEqual;
we.ge = we.greaterThanOrEqual;
we.compare = function(e) {
if (Fn(e) || (e = Ss(e)), this.eq(e))
return 0;
var t = this.isNegative(), n = e.isNegative();
return t && !n ? -1 : !t && n ? 1 : this.unsigned ? e.high >>> 0 > this.high >>> 0 || e.high === this.high && e.low >>> 0 > this.low >>> 0 ? -1 : 1 : this.sub(e).isNegative() ? -1 : 1;
};
we.comp = we.compare;
we.negate = function() {
return !this.unsigned && this.eq(On) ? On : this.not().add(Sp);
};
we.neg = we.negate;
we.add = function(e) {
Fn(e) || (e = Ss(e));
var t = this.high >>> 16, n = this.high & 65535, o = this.low >>> 16, s = this.low & 65535, a = e.high >>> 16, i = e.high & 65535, l = e.low >>> 16, u = e.low & 65535, c = 0, p = 0, m = 0, f = 0;
return f += s + u, m += f >>> 16, f &= 65535, m += o + l, p += m >>> 16, m &= 65535, p += n + i, c += p >>> 16, p &= 65535, c += t + a, c &= 65535, Ut(m << 16 | f, c << 16 | p, this.unsigned);
};
we.subtract = function(e) {
return Fn(e) || (e = Ss(e)), this.add(e.neg());
};
we.sub = we.subtract;
we.multiply = function(e) {
if (this.isZero())
return io;
if (Fn(e) || (e = Ss(e)), oo) {
var t = oo.mul(this.low, this.high, e.low, e.high);
return Ut(t, oo.get_high(), this.unsigned);
}
if (e.isZero())
return io;
if (this.eq(On))
return e.isOdd() ? On : io;
if (e.eq(On))
return this.isOdd() ? On : io;
if (this.isNegative())
return e.isNegative() ? this.neg().mul(e.neg()) : this.neg().mul(e).neg();
if (e.isNegative())
return this.mul(e.neg()).neg();
if (this.lt(cN) && e.lt(cN))
return so(this.toNumber() * e.toNumber(), this.unsigned);
var n = this.high >>> 16, o = this.high & 65535, s = this.low >>> 16, a = this.low & 65535, i = e.high >>> 16, l = e.high & 65535, u = e.low >>> 16, c = e.low & 65535, p = 0, m = 0, f = 0, d = 0;
return d += a * c, f += d >>> 16, d &= 65535, f += s * c, m += f >>> 16, f &= 65535, f += a * u, m += f >>> 16, f &= 65535, m += o * c, p += m >>> 16, m &= 65535, m += s * u, p += m >>> 16, m &= 65535, m += a * l, p += m >>> 16, m &= 65535, p += n * c + o * u + s * l + a * i, p &= 65535, Ut(f << 16 | d, p << 16 | m, this.unsigned);
};
we.mul = we.multiply;
we.divide = function(e) {
if (Fn(e) || (e = Ss(e)), e.isZero())
throw Error("division by zero");
if (oo) {
if (!this.unsigned && this.high === -2147483648 && e.low === -1 && e.high === -1)
return this;
var t = (this.unsigned ? oo.div_u : oo.div_s)(this.low, this.high, e.low, e.high);
return Ut(t, oo.get_high(), this.unsigned);
}
if (this.isZero())
return this.unsigned ? pu : io;
var n, o, s;
if (this.unsigned) {
if (e.unsigned || (e = e.toUnsigned()), e.gt(this))
return pu;
if (e.gt(this.shru(1)))
return pN;
s = pu;
} else {
if (this.eq(On)) {
if (e.eq(Sp) || e.eq(t_))
return On;
if (e.eq(On))
return Sp;
var a = this.shr(1);
return n = a.div(e).shl(1), n.eq(io) ? e.isNegative() ? Sp : t_ : (o = this.sub(e.mul(n)), s = n.add(o.div(e)), s);
} else if (e.eq(On))
return this.unsigned ? pu : io;
if (this.isNegative())
return e.isNegative() ? this.neg().div(e.neg()) : this.neg().div(e).neg();
if (e.isNegative())
return this.div(e.neg()).neg();
s = io;
}
for (o = this; o.gte(e); ) {
n = Math.max(1, Math.floor(o.toNumber() / e.toNumber()));
for (var i = Math.ceil(Math.log(n) / Math.LN2), l = i <= 48 ? 1 : Dg(2, i - 48), u = so(n), c = u.mul(e); c.isNegative() || c.gt(o); )
n -= l, u = so(n, this.unsigned), c = u.mul(e);
u.isZero() && (u = Sp), s = s.add(u), o = o.sub(c);
}
return s;
};
we.div = we.divide;
we.modulo = function(e) {
if (Fn(e) || (e = Ss(e)), oo) {
var t = (this.unsigned ? oo.rem_u : oo.rem_s)(this.low, this.high, e.low, e.high);
return Ut(t, oo.get_high(), this.unsigned);
}
return this.sub(this.div(e).mul(e));
};
we.mod = we.modulo;
we.rem = we.modulo;
we.not = function() {
return Ut(~this.low, ~this.high, this.unsigned);
};
we.and = function(e) {
return Fn(e) || (e = Ss(e)), Ut(this.low & e.low, this.high & e.high, this.unsigned);
};
we.or = function(e) {
return Fn(e) || (e = Ss(e)), Ut(this.low | e.low, this.high | e.high, this.unsigned);
};
we.xor = function(e) {
return Fn(e) || (e = Ss(e)), Ut(this.low ^ e.low, this.high ^ e.high, this.unsigned);
};
we.shiftLeft = function(e) {
return Fn(e) && (e = e.toInt()), (e &= 63) == 0 ? this : e < 32 ? Ut(this.low << e, this.high << e | this.low >>> 32 - e, this.unsigned) : Ut(0, this.low << e - 32, this.unsigned);
};
we.shl = we.shiftLeft;
we.shiftRight = function(e) {
return Fn(e) && (e = e.toInt()), (e &= 63) == 0 ? this : e < 32 ? Ut(this.low >>> e | this.high << 32 - e, this.high >> e, this.unsigned) : Ut(this.high >> e - 32, this.high >= 0 ? 0 : -1, this.unsigned);
};
we.shr = we.shiftRight;
we.shiftRightUnsigned = function(e) {
if (Fn(e) && (e = e.toInt()), e &= 63, e === 0)
return this;
var t = this.high;
if (e < 32) {
var n = this.low;
return Ut(n >>> e | t << 32 - e, t >>> e, this.unsigned);
} else
return e === 32 ? Ut(t, 0, this.unsigned) : Ut(t >>> e - 32, 0, this.unsigned);
};
we.shru = we.shiftRightUnsigned;
we.shr_u = we.shiftRightUnsigned;
we.toSigned = function() {
return this.unsigned ? Ut(this.low, this.high, false) : this;
};
we.toUnsigned = function() {
return this.unsigned ? this : Ut(this.low, this.high, true);
};
we.toBytes = function(e) {
return e ? this.toBytesLE() : this.toBytesBE();
};
we.toBytesLE = function() {
var e = this.high, t = this.low;
return [t & 255, t >>> 8 & 255, t >>> 16 & 255, t >>> 24, e & 255, e >>> 8 & 255, e >>> 16 & 255, e >>> 24];
};
we.toBytesBE = function() {
var e = this.high, t = this.low;
return [e >>> 24, e >>> 16 & 255, e >>> 8 & 255, e & 255, t >>> 24, t >>> 16 & 255, t >>> 8 & 255, t & 255];
};
Wt.fromBytes = function(e, t, n) {
return n ? Wt.fromBytesLE(e, t) : Wt.fromBytesBE(e, t);
};
Wt.fromBytesLE = function(e, t) {
return new Wt(e[0] | e[1] << 8 | e[2] << 16 | e[3] << 24, e[4] | e[5] << 8 | e[6] << 16 | e[7] << 24, t);
};
Wt.fromBytesBE = function(e, t) {
return new Wt(e[4] << 24 | e[5] << 16 | e[6] << 8 | e[7], e[0] << 24 | e[1] << 16 | e[2] << 8 | e[3], t);
};
});
var QN = qt(() => {
});
var P1 = qt((O1, ak) => {
(function(r, e, t) {
function n(i) {
var l = this, u = a();
l.next = function() {
var c = 2091639 * l.s0 + l.c * 23283064365386963e-26;
return l.s0 = l.s1, l.s1 = l.s2, l.s2 = c - (l.c = c | 0);
}, l.c = 1, l.s0 = u(" "), l.s1 = u(" "), l.s2 = u(" "), l.s0 -= u(i), l.s0 < 0 && (l.s0 += 1), l.s1 -= u(i), l.s1 < 0 && (l.s1 += 1), l.s2 -= u(i), l.s2 < 0 && (l.s2 += 1), u = null;
}
function o(i, l) {
return l.c = i.c, l.s0 = i.s0, l.s1 = i.s1, l.s2 = i.s2, l;
}
function s(i, l) {
var u = new n(i), c = l && l.state, p = u.next;
return p.int32 = function() {
return u.next() * 4294967296 | 0;
}, p.double = function() {
return p() + (p() * 2097152 | 0) * 11102230246251565e-32;
}, p.quick = p, c && (typeof c == "object" && o(c, u), p.state = function() {
return o(u, {});
}), p;
}
function a() {
var i = 4022871197, l = function(u) {
u = u.toString();
for (var c = 0; c < u.length; c++) {
i += u.charCodeAt(c);
var p = 0.02519603282416938 * i;
i = p >>> 0, p -= i, p *= i, i = p >>> 0, p -= i, i += p * 4294967296;
}
return (i >>> 0) * 23283064365386963e-26;
};
return l;
}
e && e.exports ? e.exports = s : t && t.amd ? t(function() {
return s;
}) : this.alea = s;
})(O1, typeof ak == "object" && ak, typeof define == "function" && define);
});
var L1 = qt((M1, lk) => {
(function(r, e, t) {
function n(a) {
var i = this, l = "";
i.x = 0, i.y = 0, i.z = 0, i.w = 0, i.next = function() {
var c = i.x ^ i.x << 11;
return i.x = i.y, i.y = i.z, i.z = i.w, i.w ^= i.w >>> 19 ^ c ^ c >>> 8;
}, a === (a | 0) ? i.x = a : l += a;
for (var u = 0; u < l.length + 64; u++)
i.x ^= l.charCodeAt(u) | 0, i.next();
}
function o(a, i) {
return i.x = a.x, i.y = a.y, i.z = a.z, i.w = a.w, i;
}
function s(a, i) {
var l = new n(a), u = i && i.state, c = function() {
return (l.next() >>> 0) / 4294967296;
};
return c.double = function() {
do
var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21);
while (f === 0);
return f;
}, c.int32 = l.next, c.quick = c, u && (typeof u == "object" && o(u, l), c.state = function() {
return o(l, {});
}), c;
}
e && e.exports ? e.exports = s : t && t.amd ? t(function() {
return s;
}) : this.xor128 = s;
})(M1, typeof lk == "object" && lk, typeof define == "function" && define);
});
var B1 = qt((z1, uk) => {
(function(r, e, t) {
function n(a) {
var i = this, l = "";
i.next = function() {
var c = i.x ^ i.x >>> 2;
return i.x = i.y, i.y = i.z, i.z = i.w, i.w = i.v, (i.d = i.d + 362437 | 0) + (i.v = i.v ^ i.v << 4 ^ (c ^ c << 1)) | 0;
}, i.x = 0, i.y = 0, i.z = 0, i.w = 0, i.v = 0, a === (a | 0) ? i.x = a : l += a;
for (var u = 0; u < l.length + 64; u++)
i.x ^= l.charCodeAt(u) | 0, u == l.length && (i.d = i.x << 10 ^ i.x >>> 4), i.next();
}
function o(a, i) {
return i.x = a.x, i.y = a.y, i.z = a.z, i.w = a.w, i.v = a.v, i.d = a.d, i;
}
function s(a, i) {
var l = new n(a), u = i && i.state, c = function() {
return (l.next() >>> 0) / 4294967296;
};
return c.double = function() {
do
var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21);
while (f === 0);
return f;
}, c.int32 = l.next, c.quick = c, u && (typeof u == "object" && o(u, l), c.state = function() {
return o(l, {});
}), c;
}
e && e.exports ? e.exports = s : t && t.amd ? t(function() {
return s;
}) : this.xorwow = s;
})(z1, typeof uk == "object" && uk, typeof define == "function" && define);
});
var G1 = qt((V1, ck) => {
(function(r, e, t) {
function n(a) {
var i = this;
i.next = function() {
var u = i.x, c = i.i, p, m, f;
return p = u[c], p ^= p >>> 7, m = p ^ p << 24, p = u[c + 1 & 7], m ^= p ^ p >>> 10, p = u[c + 3 & 7], m ^= p ^ p >>> 3, p = u[c + 4 & 7], m ^= p ^ p << 7, p = u[c + 7 & 7], p = p ^ p << 13, m ^= p ^ p << 9, u[c] = m, i.i = c + 1 & 7, m;
};
function l(u, c) {
var p, m, f = [];
if (c === (c | 0))
m = f[0] = c;
else
for (c = "" + c, p = 0; p < c.length; ++p)
f[p & 7] = f[p & 7] << 15 ^ c.charCodeAt(p) + f[p + 1 & 7] << 13;
for (; f.length < 8; )
f.push(0);
for (p = 0; p < 8 && f[p] === 0; ++p)
;
for (p == 8 ? m = f[7] = -1 : m = f[p], u.x = f, u.i = 0, p = 256; p > 0; --p)
u.next();
}
l(i, a);
}
function o(a, i) {
return i.x = a.x.slice(), i.i = a.i, i;
}
function s(a, i) {
a == null && (a = +new Date());
var l = new n(a), u = i && i.state, c = function() {
return (l.next() >>> 0) / 4294967296;
};
return c.double = function() {
do
var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21);
while (f === 0);
return f;
}, c.int32 = l.next, c.quick = c, u && (u.x && o(u, l), c.state = function() {
return o(l, {});
}), c;
}
e && e.exports ? e.exports = s : t && t.amd ? t(function() {
return s;
}) : this.xorshift7 = s;
})(V1, typeof ck == "object" && ck, typeof define == "function" && define);
});
var U1 = qt((W1, pk) => {
(function(r, e, t) {
function n(a) {
var i = this;
i.next = function() {
var u = i.w, c = i.X, p = i.i, m, f;
return i.w = u = u + 1640531527 | 0, f = c[p + 34 & 127], m = c[p = p + 1 & 127], f ^= f << 13, m ^= m << 17, f ^= f >>> 15, m ^= m >>> 12, f = c[p] = f ^ m, i.i = p, f + (u ^ u >>> 16) | 0;
};
function l(u, c) {
var p, m, f, d, h, g = [], x = 128;
for (c === (c | 0) ? (m = c, c = null) : (c = c + "\0", m = 0, x = Math.max(x, c.length)), f = 0, d = -32; d < x; ++d)
c && (m ^= c.charCodeAt((d + 32) % c.length)), d === 0 && (h = m), m ^= m << 10, m ^= m >>> 15, m ^= m << 4, m ^= m >>> 13, d >= 0 && (h = h + 1640531527 | 0, p = g[d & 127] ^= m + h, f = p == 0 ? f + 1 : 0);
for (f >= 128 && (g[(c && c.length || 0) & 127] = -1), f = 127, d = 4 * 128; d > 0; --d)
m = g[f + 34 & 127], p = g[f = f + 1 & 127], m ^= m << 13, p ^= p << 17, m ^= m >>> 15, p ^= p >>> 12, g[f] = m ^ p;
u.w = h, u.X = g, u.i = f;
}
l(i, a);
}
function o(a, i) {
return i.i = a.i, i.w = a.w, i.X = a.X.slice(), i;
}
function s(a, i) {
a == null && (a = +new Date());
var l = new n(a), u = i && i.state, c = function() {
return (l.next() >>> 0) / 4294967296;
};
return c.double = function() {
do
var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21);
while (f === 0);
return f;
}, c.int32 = l.next, c.quick = c, u && (u.X && o(u, l), c.state = function() {
return o(l, {});
}), c;
}
e && e.exports ? e.exports = s : t && t.amd ? t(function() {
return s;
}) : this.xor4096 = s;
})(W1, typeof pk == "object" && pk, typeof define == "function" && define);
});
var H1 = qt((j1, mk) => {
(function(r, e, t) {
function n(a) {
var i = this, l = "";
i.next = function() {
var c = i.b, p = i.c, m = i.d, f = i.a;
return c = c << 25 ^ c >>> 7 ^ p, p = p - m | 0, m = m << 24 ^ m >>> 8 ^ f, f = f - c | 0, i.b = c = c << 20 ^ c >>> 12 ^ p, i.c = p = p - m | 0, i.d = m << 16 ^ p >>> 16 ^ f, i.a = f - c | 0;
}, i.a = 0, i.b = 0, i.c = 2654435769 | 0, i.d = 1367130551, a === Math.floor(a) ? (i.a = a / 4294967296 | 0, i.b = a | 0) : l += a;
for (var u = 0; u < l.length + 20; u++)
i.b ^= l.charCodeAt(u) | 0, i.next();
}
function o(a, i) {
return i.a = a.a, i.b = a.b, i.c = a.c, i.d = a.d, i;
}
function s(a, i) {
var l = new n(a), u = i && i.state, c = function() {
return (l.next() >>> 0) / 4294967296;
};
return c.double = function() {
do
var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21);
while (f === 0);
return f;
}, c.int32 = l.next, c.quick = c, u && (typeof u == "object" && o(u, l), c.state = function() {
return o(l, {});
}), c;
}
e && e.exports ? e.exports = s : t && t.amd ? t(function() {
return s;
}) : this.tychei = s;
})(j1, typeof mk == "object" && mk, typeof define == "function" && define);
});
var fk = qt(() => {
});
var q1 = qt((Zke, Qg) => {
(function(r, e) {
var t = this, n = 256, o = 6, s = 52, a = "random", i = e.pow(n, o), l = e.pow(2, s), u = l * 2, c = n - 1, p;
function m(w, _, C) {
var A = [];
_ = _ == true ? { entropy: true } : _ || {};
var D = g(h(_.entropy ? [w, y(r)] : w == null ? x() : w, 3), A), R = new f(A), P = function() {
for (var L = R.g(o), G = i, W = 0; L < l; )
L = (L + W) * n, G *= n, W = R.g(1);
for (; L >= u; )
L /= 2, G /= 2, W >>>= 1;
return (L + W) / G;
};
return P.int32 = function() {
return R.g(4) | 0;
}, P.quick = function() {
return R.g(4) / 4294967296;
}, P.double = P, g(y(R.S), r), (_.pass || C || function(L, G, W, j) {
return j && (j.S && d(j, R), L.state = function() {
return d(R, {});
}), W ? (e[a] = L, G) : L;
})(P, D, "global" in _ ? _.global : this == e, _.state);
}
e["seed" + a] = m;
function f(w) {
var _, C = w.length, A = this, D = 0, R = A.i = A.j = 0, P = A.S = [];
for (C || (w = [C++]); D < n; )
P[D] = D++;
for (D = 0; D < n; D++)
P[D] = P[R = c & R + w[D % C] + (_ = P[D])], P[R] = _;
(A.g = function(L) {
for (var G, W = 0, j = A.i, H = A.j, q = A.S; L--; )
G = q[j = c & j + 1], W = W * n + q[c & (q[j] = q[H = c & H + G]) + (q[H] = G)];
return A.i = j, A.j = H, W;
})(n);
}
function d(w, _) {
return _.i = w.i, _.j = w.j, _.S = w.S.slice(), _;
}
function h(w, _) {
var C = [], A = typeof w, D;
if (_ && A == "object")
for (D in w)
try {
C.push(h(w[D], _ - 1));
} catch (R) {
}
return C.length ? C : A == "string" ? w : w + "\0";
}
function g(w, _) {
for (var C = w + "", A, D = 0; D < C.length; )
_[c & D] = c & (A ^= _[c & D] * 19) + C.charCodeAt(D++);
return y(_);
}
function x() {
try {
var w;
return p && (w = p.randomBytes) ? w = w(n) : (w = new Uint8Array(n), (t.crypto || t.msCrypto).getRandomValues(w)), y(w);
} catch (A) {
var _ = t.navigator, C = _ && _.plugins;
return [+new Date(), t, C, t.screen, y(r)];
}
}
function y(w) {
return String.fromCharCode.apply(0, w);
}
if (g(e.random(), r), typeof Qg == "object" && Qg.exports) {
Qg.exports = m;
try {
p = fk();
} catch (w) {
}
} else
typeof define == "function" && define.amd && define(function() {
return m;
});
})([], Math);
});
var dk = qt((Jke, K1) => {
var DH = P1(), $H = L1(), RH = B1(), FH = G1(), OH = U1(), PH = H1(), $u = q1();
$u.alea = DH;
$u.xor128 = $H;
$u.xorwow = RH;
$u.xorshift7 = FH;
$u.xor4096 = OH;
$u.tychei = PH;
K1.exports = $u;
});
var TD = qt((ND, n0) => {
(function(r, e, t) {
function n(i) {
var l = this, u = a();
l.next = function() {
var c = 2091639 * l.s0 + l.c * 23283064365386963e-26;
return l.s0 = l.s1, l.s1 = l.s2, l.s2 = c - (l.c = c | 0);
}, l.c = 1, l.s0 = u(" "), l.s1 = u(" "), l.s2 = u(" "), l.s0 -= u(i), l.s0 < 0 && (l.s0 += 1), l.s1 -= u(i), l.s1 < 0 && (l.s1 += 1), l.s2 -= u(i), l.s2 < 0 && (l.s2 += 1), u = null;
}
function o(i, l) {
return l.c = i.c, l.s0 = i.s0, l.s1 = i.s1, l.s2 = i.s2, l;
}
function s(i, l) {
var u = new n(i), c = l && l.state, p = u.next;
return p.int32 = function() {
return u.next() * 4294967296 | 0;
}, p.double = function() {
return p() + (p() * 2097152 | 0) * 11102230246251565e-32;
}, p.quick = p, c && (typeof c == "object" && o(c, u), p.state = function() {
return o(u, {});
}), p;
}
function a() {
var i = 4022871197, l = function(u) {
u = String(u);
for (var c = 0; c < u.length; c++) {
i += u.charCodeAt(c);
var p = 0.02519603282416938 * i;
i = p >>> 0, p -= i, p *= i, i = p >>> 0, p -= i, i += p * 4294967296;
}
return (i >>> 0) * 23283064365386963e-26;
};
return l;
}
e && e.exports ? e.exports = s : t && t.amd ? t(function() {
return s;
}) : this.alea = s;
})(ND, typeof n0 == "object" && n0, typeof define == "function" && define);
});
var AD = qt((ED, o0) => {
(function(r, e, t) {
function n(a) {
var i = this, l = "";
i.x = 0, i.y = 0, i.z = 0, i.w = 0, i.next = function() {
var c = i.x ^ i.x << 11;
return i.x = i.y, i.y = i.z, i.z = i.w, i.w ^= i.w >>> 19 ^ c ^ c >>> 8;
}, a === (a | 0) ? i.x = a : l += a;
for (var u = 0; u < l.length + 64; u++)
i.x ^= l.charCodeAt(u) | 0, i.next();
}
function o(a, i) {
return i.x = a.x, i.y = a.y, i.z = a.z, i.w = a.w, i;
}
function s(a, i) {
var l = new n(a), u = i && i.state, c = function() {
return (l.next() >>> 0) / 4294967296;
};
return c.double = function() {
do
var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21);
while (f === 0);
return f;
}, c.int32 = l.next, c.quick = c, u && (typeof u == "object" && o(u, l), c.state = function() {
return o(l, {});
}), c;
}
e && e.exports ? e.exports = s : t && t.amd ? t(function() {
return s;
}) : this.xor128 = s;
})(ED, typeof o0 == "object" && o0, typeof define == "function" && define);
});
var $D = qt((DD, s0) => {
(function(r, e, t) {
function n(a) {
var i = this, l = "";
i.next = function() {
var c = i.x ^ i.x >>> 2;
return i.x = i.y, i.y = i.z, i.z = i.w, i.w = i.v, (i.d = i.d + 362437 | 0) + (i.v = i.v ^ i.v << 4 ^ (c ^ c << 1)) | 0;
}, i.x = 0, i.y = 0, i.z = 0, i.w = 0, i.v = 0, a === (a | 0) ? i.x = a : l += a;
for (var u = 0; u < l.length + 64; u++)
i.x ^= l.charCodeAt(u) | 0, u == l.length && (i.d = i.x << 10 ^ i.x >>> 4), i.next();
}
function o(a, i) {
return i.x = a.x, i.y = a.y, i.z = a.z, i.w = a.w, i.v = a.v, i.d = a.d, i;
}
function s(a, i) {
var l = new n(a), u = i && i.state, c = function() {
return (l.next() >>> 0) / 4294967296;
};
return c.double = function() {
do
var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21);
while (f === 0);
return f;
}, c.int32 = l.next, c.quick = c, u && (typeof u == "object" && o(u, l), c.state = function() {
return o(l, {});
}), c;
}
e && e.exports ? e.exports = s : t && t.amd ? t(function() {
return s;
}) : this.xorwow = s;
})(DD, typeof s0 == "object" && s0, typeof define == "function" && define);
});
var FD = qt((RD, i0) => {
(function(r, e, t) {
function n(a) {
var i = this;
i.next = function() {
var u = i.x, c = i.i, p, m, f;
return p = u[c], p ^= p >>> 7, m = p ^ p << 24, p = u[c + 1 & 7], m ^= p ^ p >>> 10, p = u[c + 3 & 7], m ^= p ^ p >>> 3, p = u[c + 4 & 7], m ^= p ^ p << 7, p = u[c + 7 & 7], p = p ^ p << 13, m ^= p ^ p << 9, u[c] = m, i.i = c + 1 & 7, m;
};
function l(u, c) {
var p, m, f = [];
if (c === (c | 0))
m = f[0] = c;
else
for (c = "" + c, p = 0; p < c.length; ++p)
f[p & 7] = f[p & 7] << 15 ^ c.charCodeAt(p) + f[p + 1 & 7] << 13;
for (; f.length < 8; )
f.push(0);
for (p = 0; p < 8 && f[p] === 0; ++p)
;
for (p == 8 ? m = f[7] = -1 : m = f[p], u.x = f, u.i = 0, p = 256; p > 0; --p)
u.next();
}
l(i, a);
}
function o(a, i) {
return i.x = a.x.slice(), i.i = a.i, i;
}
function s(a, i) {
a == null && (a = +new Date());
var l = new n(a), u = i && i.state, c = function() {
return (l.next() >>> 0) / 4294967296;
};
return c.double = function() {
do
var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21);
while (f === 0);
return f;
}, c.int32 = l.next, c.quick = c, u && (u.x && o(u, l), c.state = function() {
return o(l, {});
}), c;
}
e && e.exports ? e.exports = s : t && t.amd ? t(function() {
return s;
}) : this.xorshift7 = s;
})(RD, typeof i0 == "object" && i0, typeof define == "function" && define);
});
var PD = qt((OD, a0) => {
(function(r, e, t) {
function n(a) {
var i = this;
i.next = function() {
var u = i.w, c = i.X, p = i.i, m, f;
return i.w = u = u + 1640531527 | 0, f = c[p + 34 & 127], m = c[p = p + 1 & 127], f ^= f << 13, m ^= m << 17, f ^= f >>> 15, m ^= m >>> 12, f = c[p] = f ^ m, i.i = p, f + (u ^ u >>> 16) | 0;
};
function l(u, c) {
var p, m, f, d, h, g = [], x = 128;
for (c === (c | 0) ? (m = c, c = null) : (c = c + "\0", m = 0, x = Math.max(x, c.length)), f = 0, d = -32; d < x; ++d)
c && (m ^= c.charCodeAt((d + 32) % c.length)), d === 0 && (h = m), m ^= m << 10, m ^= m >>> 15, m ^= m << 4, m ^= m >>> 13, d >= 0 && (h = h + 1640531527 | 0, p = g[d & 127] ^= m + h, f = p == 0 ? f + 1 : 0);
for (f >= 128 && (g[(c && c.length || 0) & 127] = -1), f = 127, d = 4 * 128; d > 0; --d)
m = g[f + 34 & 127], p = g[f = f + 1 & 127], m ^= m << 13, p ^= p << 17, m ^= m >>> 15, p ^= p >>> 12, g[f] = m ^ p;
u.w = h, u.X = g, u.i = f;
}
l(i, a);
}
function o(a, i) {
return i.i = a.i, i.w = a.w, i.X = a.X.slice(), i;
}
function s(a, i) {
a == null && (a = +new Date());
var l = new n(a), u = i && i.state, c = function() {
return (l.next() >>> 0) / 4294967296;
};
return c.double = function() {
do
var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21);
while (f === 0);
return f;
}, c.int32 = l.next, c.quick = c, u && (u.X && o(u, l), c.state = function() {
return o(l, {});
}), c;
}
e && e.exports ? e.exports = s : t && t.amd ? t(function() {
return s;
}) : this.xor4096 = s;
})(OD, typeof a0 == "object" && a0, typeof define == "function" && define);
});
var LD = qt((MD, l0) => {
(function(r, e, t) {
function n(a) {
var i = this, l = "";
i.next = function() {
var c = i.b, p = i.c, m = i.d, f = i.a;
return c = c << 25 ^ c >>> 7 ^ p, p = p - m | 0, m = m << 24 ^ m >>> 8 ^ f, f = f - c | 0, i.b = c = c << 20 ^ c >>> 12 ^ p, i.c = p = p - m | 0, i.d = m << 16 ^ p >>> 16 ^ f, i.a = f - c | 0;
}, i.a = 0, i.b = 0, i.c = 2654435769 | 0, i.d = 1367130551, a === Math.floor(a) ? (i.a = a / 4294967296 | 0, i.b = a | 0) : l += a;
for (var u = 0; u < l.length + 20; u++)
i.b ^= l.charCodeAt(u) | 0, i.next();
}
function o(a, i) {
return i.a = a.a, i.b = a.b, i.c = a.c, i.d = a.d, i;
}
function s(a, i) {
var l = new n(a), u = i && i.state, c = function() {
return (l.next() >>> 0) / 4294967296;
};
return c.double = function() {
do
var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21);
while (f === 0);
return f;
}, c.int32 = l.next, c.quick = c, u && (typeof u == "object" && o(u, l), c.state = function() {
return o(l, {});
}), c;
}
e && e.exports ? e.exports = s : t && t.amd ? t(function() {
return s;
}) : this.tychei = s;
})(MD, typeof l0 == "object" && l0, typeof define == "function" && define);
});
var BD = qt((zD, uy) => {
(function(r, e, t) {
var n = 256, o = 6, s = 52, a = "random", i = t.pow(n, o), l = t.pow(2, s), u = l * 2, c = n - 1, p;
function m(w, _, C) {
var A = [];
_ = _ == true ? { entropy: true } : _ || {};
var D = g(h(_.entropy ? [w, y(e)] : w == null ? x() : w, 3), A), R = new f(A), P = function() {
for (var L = R.g(o), G = i, W = 0; L < l; )
L = (L + W) * n, G *= n, W = R.g(1);
for (; L >= u; )
L /= 2, G /= 2, W >>>= 1;
return (L + W) / G;
};
return P.int32 = function() {
return R.g(4) | 0;
}, P.quick = function() {
return R.g(4) / 4294967296;
}, P.double = P, g(y(R.S), e), (_.pass || C || function(L, G, W, j) {
return j && (j.S && d(j, R), L.state = function() {
return d(R, {});
}), W ? (t[a] = L, G) : L;
})(P, D, "global" in _ ? _.global : this == t, _.state);
}
function f(w) {
var _, C = w.length, A = this, D = 0, R = A.i = A.j = 0, P = A.S = [];
for (C || (w = [C++]); D < n; )
P[D] = D++;
for (D = 0; D < n; D++)
P[D] = P[R = c & R + w[D % C] + (_ = P[D])], P[R] = _;
(A.g = function(L) {
for (var G, W = 0, j = A.i, H = A.j, q = A.S; L--; )
G = q[j = c & j + 1], W = W * n + q[c & (q[j] = q[H = c & H + G]) + (q[H] = G)];
return A.i = j, A.j = H, W;
})(n);
}
function d(w, _) {
return _.i = w.i, _.j = w.j, _.S = w.S.slice(), _;
}
function h(w, _) {
var C = [], A = typeof w, D;
if (_ && A == "object")
for (D in w)
try {
C.push(h(w[D], _ - 1));
} catch (R) {
}
return C.length ? C : A == "string" ? w : w + "\0";
}
function g(w, _) {
for (var C = w + "", A, D = 0; D < C.length; )
_[c & D] = c & (A ^= _[c & D] * 19) + C.charCodeAt(D++);
return y(_);
}
function x() {
try {
var w;
return p && (w = p.randomBytes) ? w = w(n) : (w = new Uint8Array(n), (r.crypto || r.msCrypto).getRandomValues(w)), y(w);
} catch (A) {
var _ = r.navigator, C = _ && _.plugins;
return [+new Date(), r, C, r.screen, y(e)];
}
}
function y(w) {
return String.fromCharCode.apply(0, w);
}
if (g(t.random(), e), typeof uy == "object" && uy.exports) {
uy.exports = m;
try {
p = fk();
} catch (w) {
}
} else
typeof define == "function" && define.amd ? define(function() {
return m;
}) : t["seed" + a] = m;
})(typeof self != "undefined" ? self : zD, [], Math);
});
var u0 = qt((Yct, VD) => {
var f7 = TD(), d7 = AD(), h7 = $D(), g7 = FD(), x7 = PD(), y7 = LD(), cc = BD();
cc.alea = f7;
cc.xor128 = d7;
cc.xorwow = h7;
cc.xorshift7 = g7;
cc.xor4096 = x7;
cc.tychei = y7;
VD.exports = cc;
});
var c0 = qt(() => {
});
var Lm = qt(() => {
});
var nG = qt(() => {
});
var oG = qt(() => {
});
var sG = qt((hb, AS) => {
var ES = function() {
var r = typeof document != "undefined" && document.currentScript ? document.currentScript.src : void 0;
return typeof __filename != "undefined" && (r = r || __filename), function(e) {
e = e || {};
function t() {
return ne.buffer != Ke && Tr(ne.buffer), ht;
}
function n() {
return ne.buffer != Ke && Tr(ne.buffer), Mt;
}
function o() {
return ne.buffer != Ke && Tr(ne.buffer), gn;
}
function s() {
return ne.buffer != Ke && Tr(ne.buffer), Or;
}
function a() {
return ne.buffer != Ke && Tr(ne.buffer), Zr;
}
var i = typeof e != "undefined" ? e : {}, l, u;
i.ready = new Promise(function(S, $) {
l = S, u = $;
});
var c = {}, p;
for (p in i)
i.hasOwnProperty(p) && (c[p] = i[p]);
var m = [], f = "./this.program", d = function(S, $) {
throw $;
}, h = false, g = false, x = false, y = false;
h = typeof window == "object", g = typeof importScripts == "function", x = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string", y = !h && !x && !g;
var w = i.ENVIRONMENT_IS_PTHREAD || false;
w && (Ke = i.buffer);
var _ = "";
function C(S) {
return i.locateFile ? i.locateFile(S, _) : _ + S;
}
var A, D, R, P, L, G;
if (x) {
g ? _ = Lm().dirname(_) + "/" : _ = __dirname + "/", A = function($, B) {
return L || (L = Lc("fs")), G || (G = Lm()), $ = G.normalize($), L.readFileSync($, B ? null : "utf8");
}, R = function($) {
var B = A($, true);
return B.buffer || (B = new Uint8Array(B)), de(B.buffer), B;
}, process.argv.length > 1 && (f = process.argv[1].replace(/\\/g, "/")), m = process.argv.slice(2), process.on("uncaughtException", function(S) {
if (!(S instanceof Ym))
throw S;
}), process.on("unhandledRejection", Fi), d = function(S) {
process.exit(S);
}, i.inspect = function() {
return "[Emscripten Module object]";
};
var W;
try {
W = nG();
} catch (S) {
throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'), S;
}
global.Worker = W.Worker;
} else
y ? (typeof read != "undefined" && (A = function($) {
return read($);
}), R = function($) {
var B;
return typeof readbuffer == "function" ? new Uint8Array(readbuffer($)) : (B = read($, "binary"), de(typeof B == "object"), B);
}, typeof scriptArgs != "undefined" ? m = scriptArgs : typeof arguments != "undefined" && (m = arguments), typeof quit == "function" && (d = function(S) {
quit(S);
}), typeof print != "undefined" && (typeof console == "undefined" && (console = {}), console.log = print, console.warn = console.error = typeof printErr != "undefined" ? printErr : print)) : (h || g) && (g ? _ = self.location.href : typeof document != "undefined" && document.currentScript && (_ = document.currentScript.src), typeof r != "undefined" && r && (_ = r), _.indexOf("blob:") !== 0 ? _ = _.substr(0, _.lastIndexOf("/") + 1) : _ = "", x ? (A = function($, B) {
return L || (L = Lc("fs")), G || (G = Lm()), $ = G.normalize($), L.readFileSync($, B ? null : "utf8");
}, R = function($) {
var B = A($, true);
return B.buffer || (B = new Uint8Array(B)), de(B.buffer), B;
}) : (A = function(S) {
var $ = new XMLHttpRequest();
return $.open("GET", S, false), $.send(null), $.responseText;
}, g && (R = function(S) {
var $ = new XMLHttpRequest();
return $.open("GET", S, false), $.responseType = "arraybuffer", $.send(null), new Uint8Array($.response);
}), D = function(S, $, B) {
var K = new XMLHttpRequest();
K.open("GET", S, true), K.responseType = "arraybuffer", K.onload = function() {
if (K.status == 200 || K.status == 0 && K.response) {
$(K.response);
return;
}
B();
}, K.onerror = B, K.send(null);
}), P = function(S) {
document.title = S;
});
x && typeof performance == "undefined" && (global.performance = oG().performance);
var j = i.print || console.log.bind(console), H = i.printErr || console.warn.bind(console);
for (p in c)
c.hasOwnProperty(p) && (i[p] = c[p]);
c = null, i.arguments && (m = i.arguments), i.thisProgram && (f = i.thisProgram), i.quit && (d = i.quit);
function q(S) {
q.shown || (q.shown = {}), q.shown[S] || (q.shown[S] = 1, H(S));
}
var X = Atomics.load, re = Atomics.store, J = Atomics.compareExchange, oe;
i.wasmBinary && (oe = i.wasmBinary);
var se = i.noExitRuntime || true;
typeof WebAssembly != "object" && Fi("no native wasm support detected");
var ne, fe, ae = false, ge;
function de(S, $) {
S || Fi("Assertion failed: " + $);
}
function ye(S) {
var $ = i["_" + S];
return de($, "Cannot call unknown function " + S + ", make sure it is exported"), $;
}
function _e(S, $, B, K, be) {
var he = { string: function(Jr) {
var Mc = 0;
if (Jr != null && Jr !== 0) {
var KS = (Jr.length << 2) + 1;
Mc = Fc(KS), ut(Jr, Mc, KS);
}
return Mc;
}, array: function(Jr) {
var Mc = Fc(Jr.length);
return Dt(Jr, Mc), Mc;
} };
function xe(Jr) {
return $ === "string" ? Fe(Jr) : $ === "boolean" ? Boolean(Jr) : Jr;
}
var Te = ye(S), vt = [], Er = 0;
if (K)
for (var _r = 0; _r < K.length; _r++) {
var cl = he[B[_r]];
cl ? (Er === 0 && (Er = Xm()), vt[_r] = cl(K[_r])) : vt[_r] = K[_r];
}
var Pc = Te.apply(null, vt);
return Pc = xe(Pc), Er !== 0 && Rc(Er), Pc;
}
function Re(S, $, B, K) {
B = B || [];
var be = B.every(function(xe) {
return xe === "number";
}), he = $ !== "string";
return he && be && !K ? ye(S) : function() {
return _e(S, $, B, arguments, K);
};
}
function Ee(S, $, B) {
for (var K = $ + B, be = ""; !($ >= K); ) {
var he = S[$++];
if (!he)
return be;
if (!(he & 128)) {
be += String.fromCharCode(he);
continue;
}
var xe = S[$++] & 63;
if ((he & 224) == 192) {
be += String.fromCharCode((he & 31) << 6 | xe);
continue;
}
var Te = S[$++] & 63;
if ((he & 240) == 224 ? he = (he & 15) << 12 | xe << 6 | Te : he = (he & 7) << 18 | xe << 12 | Te << 6 | S[$++] & 63, he < 65536)
be += String.fromCharCode(he);
else {
var vt = he - 65536;
be += String.fromCharCode(55296 | vt >> 10, 56320 | vt & 1023);
}
}
return be;
}
function Fe(S, $) {
return S ? Ee(n(), S, $) : "";
}
function Ye(S, $, B, K) {
if (!(K > 0))
return 0;
for (var be = B, he = B + K - 1, xe = 0; xe < S.length; ++xe) {
var Te = S.charCodeAt(xe);
if (Te >= 55296 && Te <= 57343) {
var vt = S.charCodeAt(++xe);
Te = 65536 + ((Te & 1023) << 10) | vt & 1023;
}
if (Te <= 127) {
if (B >= he)
break;
$[B++] = Te;
} else if (Te <= 2047) {
if (B + 1 >= he)
break;
$[B++] = 192 | Te >> 6, $[B++] = 128 | Te & 63;
} else if (Te <= 65535) {
if (B + 2 >= he)
break;
$[B++] = 224 | Te >> 12, $[B++] = 128 | Te >> 6 & 63, $[B++] = 128 | Te & 63;
} else {
if (B + 3 >= he)
break;
$[B++] = 240 | Te >> 18, $[B++] = 128 | Te >> 12 & 63, $[B++] = 128 | Te >> 6 & 63, $[B++] = 128 | Te & 63;
}
}
return $[B] = 0, B - be;
}
function ut(S, $, B) {
return Ye(S, n(), $, B);
}
function At(S) {
for (var $ = 0, B = 0; B < S.length; ++B) {
var K = S.charCodeAt(B);
K >= 55296 && K <= 57343 && (K = 65536 + ((K & 1023) << 10) | S.charCodeAt(++B) & 1023), K <= 127 ? ++$ : K <= 2047 ? $ += 2 : K <= 65535 ? $ += 3 : $ += 4;
}
return $;
}
function Dt(S, $) {
t().set(S, $);
}
function ft(S, $) {
return S % $ > 0 && (S += $ - S % $), S;
}
var Ke, ht, Mt, Dn, lr, gn, Or, To, Zr;
function Tr(S) {
Ke = S, i.HEAP8 = ht = new Int8Array(S), i.HEAP16 = Dn = new Int16Array(S), i.HEAP32 = gn = new Int32Array(S), i.HEAPU8 = Mt = new Uint8Array(S), i.HEAPU16 = lr = new Uint16Array(S), i.HEAPU32 = Or = new Uint32Array(S), i.HEAPF32 = To = new Float32Array(S), i.HEAPF64 = Zr = new Float64Array(S);
}
var Gn = i.INITIAL_MEMORY || 16777216;
if (w)
ne = i.wasmMemory, Ke = i.buffer;
else if (i.wasmMemory)
ne = i.wasmMemory;
else if (ne = new WebAssembly.Memory({ initial: Gn / 65536, maximum: 2147483648 / 65536, shared: true }), !(ne.buffer instanceof SharedArrayBuffer))
throw H("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"), x && console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"), Error("bad memory");
ne && (Ke = ne.buffer), Gn = Ke.byteLength, Tr(Ke);
var ur, xn = [], $n = [], Jl = [], Ql = [], Eo = [], Ri = false, zm = false;
w || $n.push({ func: function() {
yg();
} });
function Ec() {
if (!w) {
if (i.preRun)
for (typeof i.preRun == "function" && (i.preRun = [i.preRun]); i.preRun.length; )
bb(i.preRun.shift());
Ac(xn);
}
}
function rg() {
Ri = true, !w && Ac($n);
}
function ng() {
w || Ac(Jl);
}
function yn() {
w || (zm = true);
}
function og() {
if (!w) {
if (i.postRun)
for (typeof i.postRun == "function" && (i.postRun = [i.postRun]); i.postRun.length; )
wb(i.postRun.shift());
Ac(Eo);
}
}
function bb(S) {
xn.unshift(S);
}
function wb(S) {
Eo.unshift(S);
}
var Jn = 0, Bm = null, eu = null;
function _b(S) {
de(!w, "addRunDependency cannot be used in a pthread worker"), Jn++, i.monitorRunDependencies && i.monitorRunDependencies(Jn);
}
function kb(S) {
if (Jn--, i.monitorRunDependencies && i.monitorRunDependencies(Jn), Jn == 0 && (Bm !== null && (clearInterval(Bm), Bm = null), eu)) {
var $ = eu;
eu = null, $();
}
}
i.preloadedImages = {}, i.preloadedAudios = {};
function Fi(S) {
i.onAbort && i.onAbort(S), w && console.error("Pthread aborting at " + new Error().stack), S += "", H(S), ae = true, ge = 1, S = "abort(" + S + "). Build with -s ASSERTIONS=1 for more info.";
var $ = new WebAssembly.RuntimeError(S);
throw u($), $;
}
function tu(S, $) {
return String.prototype.startsWith ? S.startsWith($) : S.indexOf($) === 0;
}
var vb = "data:application/octet-stream;base64,";
function sg(S) {
return tu(S, vb);
}
var Cb = "file://";
function ig(S) {
return tu(S, Cb);
}
var bn = "tfjs-backend-wasm-threaded-simd.wasm";
sg(bn) || (bn = C(bn));
function ag(S) {
try {
if (S == bn && oe)
return new Uint8Array(oe);
if (R)
return R(S);
throw "both async and sync fetching of the wasm failed";
} catch ($) {
Fi($);
}
}
function Ib() {
if (!oe && (h || g)) {
if (typeof fetch == "function" && !ig(bn))
return fetch(bn, { credentials: "same-origin" }).then(function(S) {
if (!S.ok)
throw "failed to load wasm binary file at '" + bn + "'";
return S.arrayBuffer();
}).catch(function() {
return ag(bn);
});
if (D)
return new Promise(function(S, $) {
D(bn, function(B) {
S(new Uint8Array(B));
}, $);
});
}
return Promise.resolve().then(function() {
return ag(bn);
});
}
function Sb() {
var S = { a: yw };
function $(xe, Te) {
var vt = xe.exports;
if (i.asm = vt, ur = i.asm.I, fe = Te, !w) {
var Er = Ae.unusedWorkers.length;
Ae.unusedWorkers.forEach(function(_r) {
Ae.loadWasmModuleToWorker(_r, function() {
--Er || kb("wasm-instantiate");
});
});
}
}
w || _b("wasm-instantiate");
function B(xe) {
$(xe.instance, xe.module);
}
function K(xe) {
return Ib().then(function(Te) {
return WebAssembly.instantiate(Te, S);
}).then(xe, function(Te) {
H("failed to asynchronously prepare wasm: " + Te), Fi(Te);
});
}
function be() {
return !oe && typeof WebAssembly.instantiateStreaming == "function" && !sg(bn) && !ig(bn) && typeof fetch == "function" ? fetch(bn, { credentials: "same-origin" }).then(function(xe) {
var Te = WebAssembly.instantiateStreaming(xe, S);
return Te.then(B, function(vt) {
return H("wasm streaming compile failed: " + vt), H("falling back to ArrayBuffer instantiation"), K(B);
});
}) : K(B);
}
if (i.instantiateWasm)
try {
var he = i.instantiateWasm(S, $);
return he;
} catch (xe) {
return H("Module.instantiateWasm callback failed with error: " + xe), false;
}
return be().catch(u), {};
}
var Nb = { 10520: function() {
throw "Canceled!";
}, 10538: function(S, $) {
setTimeout(function() {
GS(S, $);
}, 0);
} };
function lg() {
Ae.initRuntime();
}
function Ac(S) {
for (; S.length > 0; ) {
var $ = S.shift();
if (typeof $ == "function") {
$(i);
continue;
}
var B = $.func;
typeof B == "number" ? $.arg === void 0 ? ur.get(B)() : ur.get(B)($.arg) : B($.arg === void 0 ? null : $.arg);
}
}
var sl = { 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 Vm(S, $) {
if (S <= 0 || S > t().length || S & true || $ < 0)
return -28;
if ($ == 0)
return 0;
$ >= 2147483647 && ($ = 1 / 0);
var B = Atomics.load(o(), Oc >> 2), K = 0;
if (B == S) {
var be = Atomics.compareExchange(o(), Oc >> 2, B, 0);
if (be == B && (--$, K = 1, $ <= 0))
return 1;
}
var he = Atomics.notify(o(), S >> 2, $);
if (he >= 0)
return he + K;
throw "Atomics.notify returned an unexpected value " + he;
}
i._emscripten_futex_wake = Vm;
function Tb(S) {
if (w)
throw "Internal Error! killThread() can only ever be called from main application thread!";
if (!S)
throw "Internal Error! Null pthread_ptr in killThread!";
o()[S + 12 >> 2] = 0;
var $ = Ae.pthreads[S];
$.worker.terminate(), Ae.freeThreadData($), Ae.runningWorkers.splice(Ae.runningWorkers.indexOf($.worker), 1), $.worker.pthread = void 0;
}
function Eb(S) {
if (w)
throw "Internal Error! cancelThread() can only ever be called from main application thread!";
if (!S)
throw "Internal Error! Null pthread_ptr in cancelThread!";
var $ = Ae.pthreads[S];
$.worker.postMessage({ cmd: "cancel" });
}
function ug(S) {
if (w)
throw "Internal Error! cleanupThread() can only ever be called from main application thread!";
if (!S)
throw "Internal Error! Null pthread_ptr in cleanupThread!";
var $ = Ae.pthreads[S];
if ($) {
o()[S + 12 >> 2] = 0;
var B = $.worker;
Ae.returnWorkerToPool(B);
}
}
var Ae = { unusedWorkers: [], runningWorkers: [], initMainThreadBlock: function() {
for (var S = 8, $ = 0; $ < S; ++$)
Ae.allocateUnusedWorker();
}, initRuntime: function() {
for (var S = nu(228), $ = 0; $ < 228 / 4; ++$)
s()[S / 4 + $] = 0;
o()[S + 12 >> 2] = S;
var B = S + 152;
o()[B >> 2] = B;
for (var K = nu(512), $ = 0; $ < 128; ++$)
s()[K / 4 + $] = 0;
Atomics.store(s(), S + 100 >> 2, K), Atomics.store(s(), S + 40 >> 2, S), Vw(S, !g, 1), BS(S);
}, initWorker: function() {
}, pthreads: {}, threadExitHandlers: [], setThreadStatus: function() {
}, runExitHandlers: function() {
for (; Ae.threadExitHandlers.length > 0; )
Ae.threadExitHandlers.pop()();
w && ul() && zS();
}, runExitHandlersAndDeinitThread: function(S, $) {
Atomics.store(s(), S + 56 >> 2, 1), Atomics.store(s(), S + 60 >> 2, 0), Ae.runExitHandlers(), Atomics.store(s(), S + 4 >> 2, $), Atomics.store(s(), S + 0 >> 2, 1), Vm(S + 0, 2147483647), Vw(0, 0, 0);
}, threadExit: function(S) {
var $ = ul();
$ && (Ae.runExitHandlersAndDeinitThread($, S), w && postMessage({ cmd: "exit" }));
}, threadCancel: function() {
Ae.runExitHandlersAndDeinitThread(ul(), -1), postMessage({ cmd: "cancelDone" });
}, terminateAllThreads: function() {
for (var S in Ae.pthreads) {
var $ = Ae.pthreads[S];
$ && $.worker && Ae.returnWorkerToPool($.worker);
}
Ae.pthreads = {};
for (var B = 0; B < Ae.unusedWorkers.length; ++B) {
var K = Ae.unusedWorkers[B];
K.terminate();
}
Ae.unusedWorkers = [];
for (var B = 0; B < Ae.runningWorkers.length; ++B) {
var K = Ae.runningWorkers[B], $ = K.pthread;
Ae.freeThreadData($), K.terminate();
}
Ae.runningWorkers = [];
}, freeThreadData: function(S) {
if (!!S) {
if (S.threadInfoStruct) {
var $ = o()[S.threadInfoStruct + 100 >> 2];
o()[S.threadInfoStruct + 100 >> 2] = 0, Km($), Km(S.threadInfoStruct);
}
S.threadInfoStruct = 0, S.allocatedOwnStack && S.stackBase && Km(S.stackBase), S.stackBase = 0, S.worker && (S.worker.pthread = null);
}
}, returnWorkerToPool: function(S) {
Ae.runWithoutMainThreadQueuedCalls(function() {
delete Ae.pthreads[S.pthread.threadInfoStruct], Ae.unusedWorkers.push(S), Ae.runningWorkers.splice(Ae.runningWorkers.indexOf(S), 1), Ae.freeThreadData(S.pthread), S.pthread = void 0;
});
}, runWithoutMainThreadQueuedCalls: function(S) {
o()[qS >> 2] = 0;
try {
S();
} finally {
o()[qS >> 2] = 1;
}
}, receiveObjectTransfer: function(S) {
}, loadWasmModuleToWorker: function(S, $) {
S.onmessage = function(B) {
var K = B.data, be = K.cmd;
if (S.pthread && (Ae.currentProxiedOperationCallerThread = S.pthread.threadInfoStruct), K.targetThread && K.targetThread != ul()) {
var he = Ae.pthreads[K.targetThread];
he ? he.worker.postMessage(B.data, K.transferList) : console.error('Internal error! Worker sent a message "' + be + '" to target pthread ' + K.targetThread + ", but that thread no longer exists!"), Ae.currentProxiedOperationCallerThread = void 0;
return;
}
if (be === "processQueuedMainThreadWork")
Cg();
else if (be === "spawnThread")
gg(B.data);
else if (be === "cleanupThread")
ug(K.thread);
else if (be === "killThread")
Tb(K.thread);
else if (be === "cancelThread")
Eb(K.thread);
else if (be === "loaded")
S.loaded = true, $ && $(S), S.runPthread && (S.runPthread(), delete S.runPthread);
else if (be === "print")
j("Thread " + K.threadId + ": " + K.text);
else if (be === "printErr")
H("Thread " + K.threadId + ": " + K.text);
else if (be === "alert")
alert("Thread " + K.threadId + ": " + K.text);
else if (be === "exit") {
var xe = S.pthread && Atomics.load(s(), S.pthread.threadInfoStruct + 64 >> 2);
xe && Ae.returnWorkerToPool(S);
} else if (be === "exitProcess")
try {
oW(K.returnCode);
} catch (Te) {
if (Te instanceof Ym)
return;
throw Te;
}
else
be === "cancelDone" ? Ae.returnWorkerToPool(S) : be === "objectTransfer" ? Ae.receiveObjectTransfer(B.data) : B.data.target === "setimmediate" ? S.postMessage(B.data) : H("worker sent an unknown command " + be);
Ae.currentProxiedOperationCallerThread = void 0;
}, S.onerror = function(B) {
H("pthread sent an error! " + B.filename + ":" + B.lineno + ": " + B.message);
}, x && (S.on("message", function(B) {
S.onmessage({ data: B });
}), S.on("error", function(B) {
S.onerror(B);
}), S.on("exit", function(B) {
})), S.postMessage({ cmd: "load", urlOrBlob: i.mainScriptUrlOrBlob || r, wasmMemory: ne, wasmModule: fe });
}, allocateUnusedWorker: function() {
var S = C("tfjs-backend-wasm-threaded-simd.worker.js");
Ae.unusedWorkers.push(new Worker(S));
}, getNewWorker: function() {
return Ae.unusedWorkers.length == 0 && (Ae.allocateUnusedWorker(), Ae.loadWasmModuleToWorker(Ae.unusedWorkers[0])), Ae.unusedWorkers.length > 0 ? Ae.unusedWorkers.pop() : null;
}, busySpinWait: function(S) {
for (var $ = performance.now() + S; performance.now() < $; )
;
} };
function Ab(S, $) {
jS(S, $), Rc(S);
}
i.establishStackSpace = Ab;
function Db() {
return se;
}
i.getNoExitRuntime = Db;
function $b(S, $) {
return ur.get(S)($);
}
i.invokeEntryPoint = $b;
function Rb(S, $, B, K) {
Fi("Assertion failed: " + Fe(S) + ", at: " + [$ ? Fe($) : "unknown filename", B, K ? Fe(K) : "unknown function"]);
}
function Fb(S, $) {
var B = _main(S, $);
}
var ru;
x ? ru = function() {
var S = process.hrtime();
return S[0] * 1e3 + S[1] / 1e6;
} : w ? ru = function() {
return performance.now() - i.__performance_now_clock_drift;
} : typeof dateNow != "undefined" ? ru = dateNow : ru = function() {
return performance.now();
};
function Ob(S) {
return o()[MS() >> 2] = S, S;
}
function Pb(S, $) {
if (w)
return il(1, 1, S, $);
}
function Mb(S, $) {
if (S == $)
postMessage({ cmd: "processQueuedMainThreadWork" });
else if (w)
postMessage({ targetThread: S, cmd: "processThreadQueue" });
else {
var B = Ae.pthreads[S], K = B && B.worker;
if (!K)
return;
K.postMessage({ cmd: "processThreadQueue" });
}
return 1;
}
function Lb() {
Fi();
}
function zb(S, $, B) {
var K = Wb($, B);
return Nb[S].apply(null, K);
}
function Bb(S, $) {
}
function cg(S, $, B) {
if (S <= 0 || S > t().length || S & true)
return -28;
if (h) {
if (Atomics.load(o(), S >> 2) != $)
return -6;
for (var be = performance.now(), he = be + B, xe = Atomics.exchange(o(), Oc >> 2, S); ; ) {
if (be = performance.now(), be > he)
return xe = Atomics.exchange(o(), Oc >> 2, 0), -73;
if (xe = Atomics.exchange(o(), Oc >> 2, 0), xe == 0)
break;
if (Cg(), Atomics.load(o(), S >> 2) != $)
return -6;
xe = Atomics.exchange(o(), Oc >> 2, S);
}
return 0;
} else {
var K = Atomics.wait(o(), S >> 2, $, B);
if (K === "timed-out")
return -73;
if (K === "not-equal")
return -6;
if (K === "ok")
return 0;
throw "Atomics.wait returned an unexpected value " + K;
}
}
function Vb(S, $, B) {
n().copyWithin(S, $, $ + B);
}
function Gb() {
return x ? Lc("os").cpus().length : navigator.hardwareConcurrency;
}
function il(S, $) {
for (var B = arguments.length - 2, K = Xm(), be = B, he = Fc(be * 8), xe = he >> 3, Te = 0; Te < B; Te++) {
var vt = arguments[2 + Te];
a()[xe + Te] = vt;
}
var Er = US(S, be, he, $);
return Rc(K), Er;
}
var Gm = [], Wm = [];
function Wb(S, $) {
Wm.length = 0;
var B;
for ($ >>= 2; B = n()[S++]; ) {
var K = B < 105;
K && $ & 1 && $++, Wm.push(K ? a()[$++ >> 1] : o()[$]), ++$;
}
return Wm;
}
function Ub(S, $, B) {
Gm.length = $;
for (var K = B >> 3, be = 0; be < $; be++)
Gm[be] = a()[K + be];
var he = S < 0, xe = he ? Nb[-S - 1] : xw[S];
return xe.apply(null, Gm);
}
function jb() {
return n().length;
}
function Hb(S) {
try {
return ne.grow(S - Ke.byteLength + 65535 >>> 16), Tr(ne.buffer), 1;
} catch ($) {
}
}
function qb(S) {
var $ = jb();
if (S <= $)
return false;
var B = 2147483648;
if (S > B)
return false;
for (var K = 1; K <= 4; K *= 2) {
var be = $ * (1 + 0.2 / K);
be = Math.min(be, S + 100663296);
var he = Math.min(B, ft(Math.max(S, be), 65536)), xe = Hb(he);
if (xe)
return true;
}
return false;
}
var Qe = { inEventHandler: 0, removeAllEventListeners: function() {
for (var S = Qe.eventHandlers.length - 1; S >= 0; --S)
Qe._removeHandler(S);
Qe.eventHandlers = [], Qe.deferredCalls = [];
}, registerRemoveEventListeners: function() {
Qe.removeEventListenersRegistered || (Ql.push(Qe.removeAllEventListeners), Qe.removeEventListenersRegistered = true);
}, deferredCalls: [], deferCall: function(S, $, B) {
function K(xe, Te) {
if (xe.length != Te.length)
return false;
for (var vt in xe)
if (xe[vt] != Te[vt])
return false;
return true;
}
for (var be in Qe.deferredCalls) {
var he = Qe.deferredCalls[be];
if (he.targetFunction == S && K(he.argsList, B))
return;
}
Qe.deferredCalls.push({ targetFunction: S, precedence: $, argsList: B }), Qe.deferredCalls.sort(function(xe, Te) {
return xe.precedence < Te.precedence;
});
}, removeDeferredCalls: function(S) {
for (var $ = 0; $ < Qe.deferredCalls.length; ++$)
Qe.deferredCalls[$].targetFunction == S && (Qe.deferredCalls.splice($, 1), --$);
}, canPerformEventHandlerRequests: function() {
return Qe.inEventHandler && Qe.currentEventHandler.allowsDeferredCalls;
}, runDeferredCalls: function() {
if (!!Qe.canPerformEventHandlerRequests())
for (var S = 0; S < Qe.deferredCalls.length; ++S) {
var $ = Qe.deferredCalls[S];
Qe.deferredCalls.splice(S, 1), --S, $.targetFunction.apply(null, $.argsList);
}
}, eventHandlers: [], removeAllHandlersOnTarget: function(S, $) {
for (var B = 0; B < Qe.eventHandlers.length; ++B)
Qe.eventHandlers[B].target == S && (!$ || $ == Qe.eventHandlers[B].eventTypeString) && Qe._removeHandler(B--);
}, _removeHandler: function(S) {
var $ = Qe.eventHandlers[S];
$.target.removeEventListener($.eventTypeString, $.eventListenerFunc, $.useCapture), Qe.eventHandlers.splice(S, 1);
}, registerOrRemoveHandler: function(S) {
var $ = function(be) {
++Qe.inEventHandler, Qe.currentEventHandler = S, Qe.runDeferredCalls(), S.handlerFunc(be), Qe.runDeferredCalls(), --Qe.inEventHandler;
};
if (S.callbackfunc)
S.eventListenerFunc = $, S.target.addEventListener(S.eventTypeString, $, S.useCapture), Qe.eventHandlers.push(S), Qe.registerRemoveEventListeners();
else
for (var B = 0; B < Qe.eventHandlers.length; ++B)
Qe.eventHandlers[B].target == S.target && Qe.eventHandlers[B].eventTypeString == S.eventTypeString && Qe._removeHandler(B--);
}, queueEventHandlerOnThread_iiii: function(S, $, B, K, be) {
var he = Xm(), xe = Fc(12);
o()[xe >> 2] = B, o()[xe + 4 >> 2] = K, o()[xe + 8 >> 2] = be, Bw(0, S, 637534208, $, K, xe), Rc(he);
}, getTargetThreadForEventCallback: function(S) {
switch (S) {
case 1:
return 0;
case 2:
return Ae.currentProxiedOperationCallerThread;
default:
return S;
}
}, getNodeNameForTarget: function(S) {
return S ? S == window ? "#window" : S == screen ? "#screen" : S && S.nodeName ? S.nodeName : "" : "";
}, fullscreenEnabled: function() {
return document.fullscreenEnabled || document.webkitFullscreenEnabled;
} };
function Kb(S) {
var $ = At(S) + 1, B = nu($);
return ut(S, B, $), B;
}
function Xb(S, $, B, K) {
var be = Xm(), he = Fc(12), xe = 0;
$ && (xe = Kb($)), o()[he >> 2] = xe, o()[he + 4 >> 2] = B, o()[he + 8 >> 2] = K, Bw(0, S, 657457152, 0, xe, he), Rc(be);
}
function Yb(S, $, B, K) {
$ = $ ? Fe($) : "", Xb(S, $, B, K);
}
function Zb(S) {
return S > 2 ? Fe(S) : S;
}
var Jb = [0, typeof document != "undefined" ? document : 0, typeof window != "undefined" ? window : 0];
function Qb(S) {
S = Zb(S);
var $ = Jb[S] || (typeof document != "undefined" ? document.querySelector(S) : void 0);
return $;
}
function Um(S) {
return Qb(S);
}
function pg(S, $, B) {
var K = Um(S);
if (!K)
return -4;
if (K.canvasSharedPtr && (o()[K.canvasSharedPtr >> 2] = $, o()[K.canvasSharedPtr + 4 >> 2] = B), K.offscreenCanvas || !K.controlTransferredOffscreen) {
K.offscreenCanvas && (K = K.offscreenCanvas);
var be = false;
if (K.GLctxObject && K.GLctxObject.GLctx) {
var he = K.GLctxObject.GLctx.getParameter(2978);
be = he[0] === 0 && he[1] === 0 && he[2] === K.width && he[3] === K.height;
}
K.width = $, K.height = B, be && K.GLctxObject.GLctx.viewport(0, 0, $, B);
} else if (K.canvasSharedPtr) {
var xe = o()[K.canvasSharedPtr + 8 >> 2];
return Yb(xe, S, $, B), 1;
} else
return -4;
return 0;
}
function mg(S, $, B) {
return w ? il(2, 1, S, $, B) : pg(S, $, B);
}
function ew(S, $, B) {
var K = Um(S);
return K ? pg(S, $, B) : mg(S, $, B);
}
function tw(S) {
}
function rw(S, $) {
}
function nw(S) {
var $ = S.getExtension("ANGLE_instanced_arrays");
if ($)
return S.vertexAttribDivisor = function(B, K) {
$.vertexAttribDivisorANGLE(B, K);
}, S.drawArraysInstanced = function(B, K, be, he) {
$.drawArraysInstancedANGLE(B, K, be, he);
}, S.drawElementsInstanced = function(B, K, be, he, xe) {
$.drawElementsInstancedANGLE(B, K, be, he, xe);
}, 1;
}
function ow(S) {
var $ = S.getExtension("OES_vertex_array_object");
if ($)
return S.createVertexArray = function() {
return $.createVertexArrayOES();
}, S.deleteVertexArray = function(B) {
$.deleteVertexArrayOES(B);
}, S.bindVertexArray = function(B) {
$.bindVertexArrayOES(B);
}, S.isVertexArray = function(B) {
return $.isVertexArrayOES(B);
}, 1;
}
function sw(S) {
var $ = S.getExtension("WEBGL_draw_buffers");
if ($)
return S.drawBuffers = function(B, K) {
$.drawBuffersWEBGL(B, K);
}, 1;
}
function iw(S) {
return !!(S.multiDrawWebgl = S.getExtension("WEBGL_multi_draw"));
}
var gt = { counter: 1, buffers: [], programs: [], framebuffers: [], renderbuffers: [], textures: [], uniforms: [], shaders: [], vaos: [], contexts: {}, offscreenCanvases: {}, timerQueriesEXT: [], programInfos: {}, stringCache: {}, unpackAlignment: 4, recordError: function($) {
gt.lastError || (gt.lastError = $);
}, getNewId: function(S) {
for (var $ = gt.counter++, B = S.length; B < $; B++)
S[B] = null;
return $;
}, getSource: function(S, $, B, K) {
for (var be = "", he = 0; he < $; ++he) {
var xe = K ? o()[K + he * 4 >> 2] : -1;
be += Fe(o()[B + he * 4 >> 2], xe < 0 ? void 0 : xe);
}
return be;
}, createContext: function(S, $) {
var B = S.getContext("webgl", $);
if (!B)
return 0;
var K = gt.registerContext(B, $);
return K;
}, registerContext: function(S, $) {
var B = nu(8);
o()[B + 4 >> 2] = ul();
var K = { handle: B, attributes: $, version: $.majorVersion, GLctx: S };
return S.canvas && (S.canvas.GLctxObject = K), gt.contexts[B] = K, (typeof $.enableExtensionsByDefault == "undefined" || $.enableExtensionsByDefault) && gt.initExtensions(K), B;
}, makeContextCurrent: function(S) {
return gt.currentContext = gt.contexts[S], i.ctx = al = gt.currentContext && gt.currentContext.GLctx, !(S && !al);
}, getContext: function(S) {
return gt.contexts[S];
}, deleteContext: function(S) {
gt.currentContext === gt.contexts[S] && (gt.currentContext = null), typeof Qe == "object" && Qe.removeAllHandlersOnTarget(gt.contexts[S].GLctx.canvas), gt.contexts[S] && gt.contexts[S].GLctx.canvas && (gt.contexts[S].GLctx.canvas.GLctxObject = void 0), Km(gt.contexts[S].handle), gt.contexts[S] = null;
}, initExtensions: function(S) {
if (S || (S = gt.currentContext), !S.initExtensionsDone) {
S.initExtensionsDone = true;
var $ = S.GLctx;
nw($), ow($), sw($), $.disjointTimerQueryExt = $.getExtension("EXT_disjoint_timer_query"), iw($);
var B = $.getSupportedExtensions() || [];
B.forEach(function(K) {
K.indexOf("lose_context") < 0 && K.indexOf("debug") < 0 && $.getExtension(K);
});
}
}, populateUniformTable: function(S) {
for (var $ = gt.programs[S], B = gt.programInfos[S] = { uniforms: {}, maxUniformLength: 0, maxAttributeLength: -1, maxUniformBlockNameLength: -1 }, K = B.uniforms, be = al.getProgramParameter($, 35718), he = 0; he < be; ++he) {
var xe = al.getActiveUniform($, he), Te = xe.name;
B.maxUniformLength = Math.max(B.maxUniformLength, Te.length + 1), Te.slice(-1) == "]" && (Te = Te.slice(0, Te.lastIndexOf("[")));
var vt = al.getUniformLocation($, Te);
if (vt) {
var Er = gt.getNewId(gt.uniforms);
K[Te] = [xe.size, Er], gt.uniforms[Er] = vt;
for (var _r = 1; _r < xe.size; ++_r) {
var cl = Te + "[" + _r + "]";
vt = al.getUniformLocation($, cl), Er = gt.getNewId(gt.uniforms), gt.uniforms[Er] = vt;
}
}
}
} }, aw = ["default", "low-power", "high-performance"];
function lw(S, $) {
var B = $ >> 2, K = o()[B + (24 >> 2)], be = { alpha: !!o()[B + (0 >> 2)], depth: !!o()[B + (4 >> 2)], stencil: !!o()[B + (8 >> 2)], antialias: !!o()[B + (12 >> 2)], premultipliedAlpha: !!o()[B + (16 >> 2)], preserveDrawingBuffer: !!o()[B + (20 >> 2)], powerPreference: aw[K], failIfMajorPerformanceCaveat: !!o()[B + (28 >> 2)], majorVersion: o()[B + (32 >> 2)], minorVersion: o()[B + (36 >> 2)], enableExtensionsByDefault: o()[B + (40 >> 2)], explicitSwapControl: o()[B + (44 >> 2)], proxyContextToMainThread: o()[B + (48 >> 2)], renderViaOffscreenBackBuffer: o()[B + (52 >> 2)] }, he = Um(S);
if (!he || be.explicitSwapControl)
return 0;
var xe = gt.createContext(he, be);
return xe;
}
function uw(S, $) {
return lw(S, $);
}
var Dc = { mappings: {}, buffers: [null, [], []], printChar: function(S, $) {
var B = Dc.buffers[S];
$ === 0 || $ === 10 ? ((S === 1 ? j : H)(Ee(B, 0)), B.length = 0) : B.push($);
}, varargs: void 0, get: function() {
Dc.varargs += 4;
var S = o()[Dc.varargs - 4 >> 2];
return S;
}, getStr: function(S) {
var $ = Fe(S);
return $;
}, get64: function(S, $) {
return S;
} };
function fg(S) {
return w ? il(3, 1, S) : 0;
}
function dg(S, $, B, K, be) {
if (w)
return il(4, 1, S, $, B, K, be);
}
function hg(S, $, B, K) {
if (w)
return il(5, 1, S, $, B, K);
for (var be = 0, he = 0; he < B; he++) {
for (var xe = o()[$ + he * 8 >> 2], Te = o()[$ + (he * 8 + 4) >> 2], vt = 0; vt < Te; vt++)
Dc.printChar(S, n()[xe + vt]);
be += Te;
}
return o()[K >> 2] = be, 0;
}
function cw(S) {
var $ = Ae.threadExitHandlers.pop();
S && $();
}
function pw(S, $) {
Ae.threadExitHandlers.push(function() {
ur.get(S)($);
});
}
function gg(S) {
if (w)
throw "Internal Error! spawnThread() can only ever be called from main application thread!";
var $ = Ae.getNewWorker();
if ($.pthread !== void 0)
throw "Internal error!";
if (!S.pthread_ptr)
throw "Internal error, no pthread ptr!";
Ae.runningWorkers.push($);
for (var B = nu(128 * 4), K = 0; K < 128; ++K)
o()[B + K * 4 >> 2] = 0;
var be = S.stackBase + S.stackSize, he = Ae.pthreads[S.pthread_ptr] = { worker: $, stackBase: S.stackBase, stackSize: S.stackSize, allocatedOwnStack: S.allocatedOwnStack, threadInfoStruct: S.pthread_ptr }, xe = he.threadInfoStruct >> 2;
Atomics.store(s(), xe + (64 >> 2), S.detached), Atomics.store(s(), xe + (100 >> 2), B), Atomics.store(s(), xe + (40 >> 2), he.threadInfoStruct), Atomics.store(s(), xe + (80 >> 2), S.stackSize), Atomics.store(s(), xe + (76 >> 2), be), Atomics.store(s(), xe + (104 >> 2), S.stackSize), Atomics.store(s(), xe + (104 + 8 >> 2), be), Atomics.store(s(), xe + (104 + 12 >> 2), S.detached);
var Te = LS(), vt = Te + 40;
Atomics.store(s(), xe + (172 >> 2), vt), $.pthread = he;
var Er = { cmd: "run", start_routine: S.startRoutine, arg: S.arg, threadInfoStruct: S.pthread_ptr, stackBase: S.stackBase, stackSize: S.stackSize };
$.runPthread = function() {
Er.time = performance.now(), $.postMessage(Er, S.transferList);
}, $.loaded && ($.runPthread(), delete $.runPthread);
}
function mw(S, $, B, K) {
if (typeof SharedArrayBuffer == "undefined")
return H("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6;
if (!S)
return H("pthread_create called with a null thread pointer!"), 28;
var be = [], he = 0;
if (w && (be.length === 0 || he))
return WS(687865856, S, $, B, K);
if (he)
return he;
var xe = 0, Te = 0, vt = 0;
$ && $ != -1 ? (xe = o()[$ >> 2], xe += 81920, Te = o()[$ + 8 >> 2], vt = o()[$ + 12 >> 2] !== 0) : xe = 2097152;
var Er = Te == 0;
Er ? Te = HS(16, xe) : (Te -= xe, de(Te > 0));
for (var _r = nu(228), cl = 0; cl < 228 >> 2; ++cl)
s()[(_r >> 2) + cl] = 0;
o()[S >> 2] = _r, o()[_r + 12 >> 2] = _r;
var Pc = _r + 152;
o()[Pc >> 2] = Pc;
var Jr = { stackBase: Te, stackSize: xe, allocatedOwnStack: Er, detached: vt, startRoutine: B, pthread_ptr: _r, arg: K, transferList: be };
return w ? (Jr.cmd = "spawnThread", postMessage(Jr, be)) : gg(Jr), 0;
}
function fw() {
if (!!w) {
var S = ul();
if (!!S) {
var $ = Atomics.load(s(), S + 56 >> 2);
if (!$) {
var B = Atomics.load(s(), S + 0 >> 2);
if (B == 2)
throw "Canceled!";
}
}
}
}
function dw() {
x || g || q("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread");
}
function hw(S, $, B) {
if (!S)
return H("pthread_join attempted on a null thread pointer!"), sl.ESRCH;
if (w && ul() == S)
return H("PThread " + S + " is attempting to join to itself!"), sl.EDEADLK;
if (!w && VS() == S)
return H("Main thread " + S + " is attempting to join to itself!"), sl.EDEADLK;
var K = o()[S + 12 >> 2];
if (K !== S)
return H("pthread_join attempted on thread " + S + ", which does not point to a valid thread, or does not exist anymore!"), sl.ESRCH;
var be = Atomics.load(s(), S + 64 >> 2);
if (be)
return H("Attempted to join thread " + S + ", which was already detached!"), sl.EINVAL;
for (B && dw(); ; ) {
var he = Atomics.load(s(), S + 0 >> 2);
if (he == 1) {
var xe = Atomics.load(s(), S + 4 >> 2);
return $ && (o()[$ >> 2] = xe), Atomics.store(s(), S + 64 >> 2, 1), w ? postMessage({ cmd: "cleanupThread", thread: S }) : ug(S), 0;
}
if (!B)
return sl.EBUSY;
fw(), w || Cg(), cg(S + 0, he, w ? 100 : 1);
}
}
function gw(S, $) {
return hw(S, $, true);
}
function xg(S) {
if (w)
return il(6, 1, S);
switch (S) {
case 30:
return 16384;
case 85:
var $ = 2147483648;
return $ / 16384;
case 132:
case 133:
case 12:
case 137:
case 138:
case 15:
case 235:
case 16:
case 17:
case 18:
case 19:
case 20:
case 149:
case 13:
case 10:
case 236:
case 153:
case 9:
case 21:
case 22:
case 159:
case 154:
case 14:
case 77:
case 78:
case 139:
case 82:
case 68:
case 67:
case 164:
case 11:
case 29:
case 47:
case 48:
case 95:
case 52:
case 51:
case 46:
return 200809;
case 27:
case 246:
case 127:
case 128:
case 23:
case 24:
case 160:
case 161:
case 181:
case 182:
case 242:
case 183:
case 184:
case 243:
case 244:
case 245:
case 165:
case 178:
case 179:
case 49:
case 50:
case 168:
case 169:
case 175:
case 170:
case 171:
case 172:
case 97:
case 76:
case 32:
case 173:
case 35:
case 80:
case 81:
case 79:
return -1;
case 176:
case 177:
case 7:
case 155:
case 8:
case 157:
case 125:
case 126:
case 92:
case 93:
case 129:
case 130:
case 131:
case 94:
case 91:
return 1;
case 74:
case 60:
case 69:
case 70:
case 4:
return 1024;
case 31:
case 42:
case 72:
return 32;
case 87:
case 26:
case 33:
return 2147483647;
case 34:
case 1:
return 47839;
case 38:
case 36:
return 99;
case 43:
case 37:
return 2048;
case 0:
return 2097152;
case 3:
return 65536;
case 28:
return 32768;
case 44:
return 32767;
case 75:
return 16384;
case 39:
return 1e3;
case 89:
return 700;
case 71:
return 256;
case 40:
return 255;
case 2:
return 100;
case 180:
return 64;
case 25:
return 20;
case 5:
return 16;
case 6:
return 6;
case 73:
return 4;
case 84:
return typeof navigator == "object" && navigator.hardwareConcurrency || 1;
}
return Ob(28), -1;
}
w || Ae.initMainThreadBlock();
var al, xw = [null, Pb, mg, fg, dg, hg, xg], yw = { e: Rb, r: Fb, x: Mb, b: Lb, y: zb, j: Bb, d: cg, c: Vm, f: ru, p: Vb, A: Gb, u: Ub, q: qb, v: ew, i: tw, s: rw, w: uw, l: fg, n: dg, g: hg, o: lg, a: ne || i.wasmMemory, z: cw, k: pw, h: mw, m: gw, t: xg }, PS = Sb(), yg = i.___wasm_call_ctors = function() {
return (yg = i.___wasm_call_ctors = i.asm.B).apply(null, arguments);
}, bw = i._init = function() {
return (bw = i._init = i.asm.C).apply(null, arguments);
}, ww = i._init_with_threads_count = function() {
return (ww = i._init_with_threads_count = i.asm.D).apply(null, arguments);
}, _w = i._get_threads_count = function() {
return (_w = i._get_threads_count = i.asm.E).apply(null, arguments);
}, kw = i._register_tensor = function() {
return (kw = i._register_tensor = i.asm.F).apply(null, arguments);
}, vw = i._dispose_data = function() {
return (vw = i._dispose_data = i.asm.G).apply(null, arguments);
}, Cw = i._dispose = function() {
return (Cw = i._dispose = i.asm.H).apply(null, arguments);
}, Iw = i._Abs = function() {
return (Iw = i._Abs = i.asm.J).apply(null, arguments);
}, Sw = i._Add = function() {
return (Sw = i._Add = i.asm.K).apply(null, arguments);
}, Nw = i._AddN = function() {
return (Nw = i._AddN = i.asm.L).apply(null, arguments);
}, Tw = i._All = function() {
return (Tw = i._All = i.asm.M).apply(null, arguments);
}, Ew = i._Any = function() {
return (Ew = i._Any = i.asm.N).apply(null, arguments);
}, Aw = i._ArgMax = function() {
return (Aw = i._ArgMax = i.asm.O).apply(null, arguments);
}, Dw = i._AvgPool = function() {
return (Dw = i._AvgPool = i.asm.P).apply(null, arguments);
}, $w = i._BatchMatMul = function() {
return ($w = i._BatchMatMul = i.asm.Q).apply(null, arguments);
}, Rw = i._Ceil = function() {
return (Rw = i._Ceil = i.asm.R).apply(null, arguments);
}, Fw = i._ClipByValue = function() {
return (Fw = i._ClipByValue = i.asm.S).apply(null, arguments);
}, Ow = i._Conv2D = function() {
return (Ow = i._Conv2D = i.asm.T).apply(null, arguments);
}, Pw = i._Conv2DBackpropInput = function() {
return (Pw = i._Conv2DBackpropInput = i.asm.U).apply(null, arguments);
}, Mw = i._Cos = function() {
return (Mw = i._Cos = i.asm.V).apply(null, arguments);
}, Lw = i._Cosh = function() {
return (Lw = i._Cosh = i.asm.W).apply(null, arguments);
}, bg = i._CropAndResize = function() {
return (bg = i._CropAndResize = i.asm.X).apply(null, arguments);
}, wg = i._Cumsum = function() {
return (wg = i._Cumsum = i.asm.Y).apply(null, arguments);
}, _g = i._DepthToSpace = function() {
return (_g = i._DepthToSpace = i.asm.Z).apply(null, arguments);
}, jm = i._DepthwiseConv2dNative = function() {
return (jm = i._DepthwiseConv2dNative = i.asm._).apply(null, arguments);
}, $c = i._Elu = function() {
return ($c = i._Elu = i.asm.$).apply(null, arguments);
}, zw = i._Equal = function() {
return (zw = i._Equal = i.asm.aa).apply(null, arguments);
}, Hm = i._Exp = function() {
return (Hm = i._Exp = i.asm.ba).apply(null, arguments);
}, Q = i._FlipLeftRight = function() {
return (Q = i._FlipLeftRight = i.asm.ca).apply(null, arguments);
}, ie = i._Floor = function() {
return (ie = i._Floor = i.asm.da).apply(null, arguments);
}, Ce = i._FloorDiv = function() {
return (Ce = i._FloorDiv = i.asm.ea).apply(null, arguments);
}, pt = i._FusedBatchNorm = function() {
return (pt = i._FusedBatchNorm = i.asm.fa).apply(null, arguments);
}, nr = i._FusedConv2D = function() {
return (nr = i._FusedConv2D = i.asm.ga).apply(null, arguments);
}, Ht = i._FusedDepthwiseConv2D = function() {
return (Ht = i._FusedDepthwiseConv2D = i.asm.ha).apply(null, arguments);
}, nt = i._Gather = function() {
return (nt = i._Gather = i.asm.ia).apply(null, arguments);
}, ot = i._GatherNd = function() {
return (ot = i._GatherNd = i.asm.ja).apply(null, arguments);
}, Pr = i._Greater = function() {
return (Pr = i._Greater = i.asm.ka).apply(null, arguments);
}, Oi = i._GreaterEqual = function() {
return (Oi = i._GreaterEqual = i.asm.la).apply(null, arguments);
}, Pi = i._LeakyRelu = function() {
return (Pi = i._LeakyRelu = i.asm.ma).apply(null, arguments);
}, kg = i._Less = function() {
return (kg = i._Less = i.asm.na).apply(null, arguments);
}, qm = i._LessEqual = function() {
return (qm = i._LessEqual = i.asm.oa).apply(null, arguments);
}, Rn = i._Log = function() {
return (Rn = i._Log = i.asm.pa).apply(null, arguments);
}, ll = i._LogicalAnd = function() {
return (ll = i._LogicalAnd = i.asm.qa).apply(null, arguments);
}, vg = i._Max = function() {
return (vg = i._Max = i.asm.ra).apply(null, arguments);
}, mG = i._MaxPool = function() {
return (mG = i._MaxPool = i.asm.sa).apply(null, arguments);
}, fG = i._Maximum = function() {
return (fG = i._Maximum = i.asm.ta).apply(null, arguments);
}, dG = i._Mean = function() {
return (dG = i._Mean = i.asm.ua).apply(null, arguments);
}, hG = i._Min = function() {
return (hG = i._Min = i.asm.va).apply(null, arguments);
}, gG = i._Minimum = function() {
return (gG = i._Minimum = i.asm.wa).apply(null, arguments);
}, xG = i._MirrorPad = function() {
return (xG = i._MirrorPad = i.asm.xa).apply(null, arguments);
}, yG = i._Multiply = function() {
return (yG = i._Multiply = i.asm.ya).apply(null, arguments);
}, bG = i._Neg = function() {
return (bG = i._Neg = i.asm.za).apply(null, arguments);
}, wG = i._NonMaxSuppressionV3 = function() {
return (wG = i._NonMaxSuppressionV3 = i.asm.Aa).apply(null, arguments);
}, _G = i._NonMaxSuppressionV4 = function() {
return (_G = i._NonMaxSuppressionV4 = i.asm.Ba).apply(null, arguments);
}, kG = i._NonMaxSuppressionV5 = function() {
return (kG = i._NonMaxSuppressionV5 = i.asm.Ca).apply(null, arguments);
}, vG = i._NotEqual = function() {
return (vG = i._NotEqual = i.asm.Da).apply(null, arguments);
}, CG = i._OneHot = function() {
return (CG = i._OneHot = i.asm.Ea).apply(null, arguments);
}, IG = i._PadV2 = function() {
return (IG = i._PadV2 = i.asm.Fa).apply(null, arguments);
}, SG = i._Pow = function() {
return (SG = i._Pow = i.asm.Ga).apply(null, arguments);
}, NG = i._Prelu = function() {
return (NG = i._Prelu = i.asm.Ha).apply(null, arguments);
}, TG = i._Prod = function() {
return (TG = i._Prod = i.asm.Ia).apply(null, arguments);
}, EG = i._RealDiv = function() {
return (EG = i._RealDiv = i.asm.Ja).apply(null, arguments);
}, AG = i._Relu = function() {
return (AG = i._Relu = i.asm.Ka).apply(null, arguments);
}, DG = i._Relu6 = function() {
return (DG = i._Relu6 = i.asm.La).apply(null, arguments);
}, $G = i._ResizeBilinear = function() {
return ($G = i._ResizeBilinear = i.asm.Ma).apply(null, arguments);
}, RG = i._Reverse = function() {
return (RG = i._Reverse = i.asm.Na).apply(null, arguments);
}, FG = i._RotateWithOffset = function() {
return (FG = i._RotateWithOffset = i.asm.Oa).apply(null, arguments);
}, OG = i._Round = function() {
return (OG = i._Round = i.asm.Pa).apply(null, arguments);
}, PG = i._Rsqrt = function() {
return (PG = i._Rsqrt = i.asm.Qa).apply(null, arguments);
}, MG = i._ScatterNd = function() {
return (MG = i._ScatterNd = i.asm.Ra).apply(null, arguments);
}, LG = i._SelectV2 = function() {
return (LG = i._SelectV2 = i.asm.Sa).apply(null, arguments);
}, zG = i._Sigmoid = function() {
return (zG = i._Sigmoid = i.asm.Ta).apply(null, arguments);
}, BG = i._Sin = function() {
return (BG = i._Sin = i.asm.Ua).apply(null, arguments);
}, VG = i._Softmax = function() {
return (VG = i._Softmax = i.asm.Va).apply(null, arguments);
}, GG = i._Sqrt = function() {
return (GG = i._Sqrt = i.asm.Wa).apply(null, arguments);
}, WG = i._Square = function() {
return (WG = i._Square = i.asm.Xa).apply(null, arguments);
}, UG = i._SquaredDifference = function() {
return (UG = i._SquaredDifference = i.asm.Ya).apply(null, arguments);
}, jG = i._Step = function() {
return (jG = i._Step = i.asm.Za).apply(null, arguments);
}, HG = i._StridedSlice = function() {
return (HG = i._StridedSlice = i.asm._a).apply(null, arguments);
}, qG = i._Sub = function() {
return (qG = i._Sub = i.asm.$a).apply(null, arguments);
}, KG = i._Sum = function() {
return (KG = i._Sum = i.asm.ab).apply(null, arguments);
}, XG = i._Tan = function() {
return (XG = i._Tan = i.asm.bb).apply(null, arguments);
}, YG = i._Tanh = function() {
return (YG = i._Tanh = i.asm.cb).apply(null, arguments);
}, ZG = i._Tile = function() {
return (ZG = i._Tile = i.asm.db).apply(null, arguments);
}, JG = i._TopK = function() {
return (JG = i._TopK = i.asm.eb).apply(null, arguments);
}, QG = i._Transform = function() {
return (QG = i._Transform = i.asm.fb).apply(null, arguments);
}, eW = i._Transpose = function() {
return (eW = i._Transpose = i.asm.gb).apply(null, arguments);
}, tW = i.__FusedMatMul = function() {
return (tW = i.__FusedMatMul = i.asm.hb).apply(null, arguments);
}, nu = i._malloc = function() {
return (nu = i._malloc = i.asm.ib).apply(null, arguments);
}, Km = i._free = function() {
return (Km = i._free = i.asm.jb).apply(null, arguments);
}, MS = i.___errno_location = function() {
return (MS = i.___errno_location = i.asm.kb).apply(null, arguments);
}, LS = i._emscripten_get_global_libc = function() {
return (LS = i._emscripten_get_global_libc = i.asm.lb).apply(null, arguments);
}, ul = i._pthread_self = function() {
return (ul = i._pthread_self = i.asm.mb).apply(null, arguments);
}, zS = i.___pthread_tsd_run_dtors = function() {
return (zS = i.___pthread_tsd_run_dtors = i.asm.nb).apply(null, arguments);
}, Cg = i._emscripten_main_thread_process_queued_calls = function() {
return (Cg = i._emscripten_main_thread_process_queued_calls = i.asm.ob).apply(null, arguments);
}, rW = i._emscripten_current_thread_process_queued_calls = function() {
return (rW = i._emscripten_current_thread_process_queued_calls = i.asm.pb).apply(null, arguments);
}, BS = i._emscripten_register_main_browser_thread_id = function() {
return (BS = i._emscripten_register_main_browser_thread_id = i.asm.qb).apply(null, arguments);
}, VS = i._emscripten_main_browser_thread_id = function() {
return (VS = i._emscripten_main_browser_thread_id = i.asm.rb).apply(null, arguments);
}, GS = i.__emscripten_do_dispatch_to_thread = function() {
return (GS = i.__emscripten_do_dispatch_to_thread = i.asm.sb).apply(null, arguments);
}, WS = i._emscripten_sync_run_in_main_thread_4 = function() {
return (WS = i._emscripten_sync_run_in_main_thread_4 = i.asm.tb).apply(null, arguments);
}, US = i._emscripten_run_in_main_runtime_thread_js = function() {
return (US = i._emscripten_run_in_main_runtime_thread_js = i.asm.ub).apply(null, arguments);
}, Bw = i.__emscripten_call_on_thread = function() {
return (Bw = i.__emscripten_call_on_thread = i.asm.vb).apply(null, arguments);
}, nW = i._emscripten_tls_init = function() {
return (nW = i._emscripten_tls_init = i.asm.wb).apply(null, arguments);
}, Vw = i.__emscripten_thread_init = function() {
return (Vw = i.__emscripten_thread_init = i.asm.xb).apply(null, arguments);
}, Xm = i.stackSave = function() {
return (Xm = i.stackSave = i.asm.yb).apply(null, arguments);
}, Rc = i.stackRestore = function() {
return (Rc = i.stackRestore = i.asm.zb).apply(null, arguments);
}, Fc = i.stackAlloc = function() {
return (Fc = i.stackAlloc = i.asm.Ab).apply(null, arguments);
}, jS = i._emscripten_stack_set_limits = function() {
return (jS = i._emscripten_stack_set_limits = i.asm.Bb).apply(null, arguments);
}, HS = i._memalign = function() {
return (HS = i._memalign = i.asm.Cb).apply(null, arguments);
}, qS = i.__emscripten_allow_main_runtime_queued_calls = 10512, Oc = i.__emscripten_main_thread_futex = 12148;
i.cwrap = Re, i.PThread = Ae, i.PThread = Ae, i.wasmMemory = ne, i.ExitStatus = Ym;
var Ig;
function Ym(S) {
this.name = "ExitStatus", this.message = "Program terminated with exit(" + S + ")", this.status = S;
}
eu = function S() {
Ig || Gw(), Ig || (eu = S);
};
function Gw(S) {
if (S = S || m, Jn > 0)
return;
if (w) {
l(i), rg(), postMessage({ cmd: "loaded" });
return;
}
if (Ec(), Jn > 0)
return;
function $() {
Ig || (Ig = true, i.calledRun = true, !ae && (rg(), ng(), l(i), i.onRuntimeInitialized && i.onRuntimeInitialized(), og()));
}
i.setStatus ? (i.setStatus("Running..."), setTimeout(function() {
setTimeout(function() {
i.setStatus("");
}, 1), $();
}, 1)) : $();
}
i.run = Gw;
function oW(S, $) {
if (!($ && se && S === 0)) {
if (!$ && w)
throw postMessage({ cmd: "exitProcess", returnCode: S }), new Ym(S);
se || (Ae.terminateAllThreads(), ge = S, yn(), i.onExit && i.onExit(S), ae = true), d(S, new Ym(S));
}
}
if (i.preInit)
for (typeof i.preInit == "function" && (i.preInit = [i.preInit]); i.preInit.length > 0; )
i.preInit.pop()();
return w && (se = false, Ae.initWorker()), Gw(), e.ready;
};
}();
typeof hb == "object" && typeof AS == "object" ? AS.exports = ES : typeof define == "function" && define.amd ? define([], function() {
return ES;
}) : typeof hb == "object" && (hb.WasmBackendModuleThreadedSimd = ES);
});
var aG = qt((gb, $S) => {
var DS = function() {
var r = typeof document != "undefined" && document.currentScript ? document.currentScript.src : void 0;
return typeof __filename != "undefined" && (r = r || __filename), function(e) {
e = e || {};
var t = typeof e != "undefined" ? e : {}, n, o;
t.ready = new Promise(function(Q, ie) {
n = Q, o = ie;
});
var s = {}, a;
for (a in t)
t.hasOwnProperty(a) && (s[a] = t[a]);
var i = [], l = "./this.program", u = function(Q, ie) {
throw ie;
}, c = false, p = false, m = false, f = false;
c = typeof window == "object", p = typeof importScripts == "function", m = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string", f = !c && !m && !p;
var d = "";
function h(Q) {
return t.locateFile ? t.locateFile(Q, d) : d + Q;
}
var g, x, y, w, _, C;
m ? (p ? d = Lm().dirname(d) + "/" : d = __dirname + "/", g = function(ie, Ce) {
return _ || (_ = Lc("fs")), C || (C = Lm()), ie = C.normalize(ie), _.readFileSync(ie, Ce ? null : "utf8");
}, y = function(ie) {
var Ce = g(ie, true);
return Ce.buffer || (Ce = new Uint8Array(Ce)), j(Ce.buffer), Ce;
}, process.argv.length > 1 && (l = process.argv[1].replace(/\\/g, "/")), i = process.argv.slice(2), process.on("uncaughtException", function(Q) {
if (!(Q instanceof zw))
throw Q;
}), process.on("unhandledRejection", Eo), u = function(Q) {
process.exit(Q);
}, t.inspect = function() {
return "[Emscripten Module object]";
}) : f ? (typeof read != "undefined" && (g = function(ie) {
return read(ie);
}), y = function(ie) {
var Ce;
return typeof readbuffer == "function" ? new Uint8Array(readbuffer(ie)) : (Ce = read(ie, "binary"), j(typeof Ce == "object"), Ce);
}, typeof scriptArgs != "undefined" ? i = scriptArgs : typeof arguments != "undefined" && (i = arguments), typeof quit == "function" && (u = function(Q) {
quit(Q);
}), typeof print != "undefined" && (typeof console == "undefined" && (console = {}), console.log = print, console.warn = console.error = typeof printErr != "undefined" ? printErr : print)) : (c || p) && (p ? d = self.location.href : typeof document != "undefined" && document.currentScript && (d = document.currentScript.src), r && (d = r), d.indexOf("blob:") !== 0 ? d = d.substr(0, d.lastIndexOf("/") + 1) : d = "", g = function(Q) {
var ie = new XMLHttpRequest();
return ie.open("GET", Q, false), ie.send(null), ie.responseText;
}, p && (y = function(Q) {
var ie = new XMLHttpRequest();
return ie.open("GET", Q, false), ie.responseType = "arraybuffer", ie.send(null), new Uint8Array(ie.response);
}), x = function(Q, ie, Ce) {
var pt = new XMLHttpRequest();
pt.open("GET", Q, true), pt.responseType = "arraybuffer", pt.onload = function() {
if (pt.status == 200 || pt.status == 0 && pt.response) {
ie(pt.response);
return;
}
Ce();
}, pt.onerror = Ce, pt.send(null);
}, w = function(Q) {
document.title = Q;
});
var A = t.print || console.log.bind(console), D = t.printErr || console.warn.bind(console);
for (a in s)
s.hasOwnProperty(a) && (t[a] = s[a]);
s = null, t.arguments && (i = t.arguments), t.thisProgram && (l = t.thisProgram), t.quit && (u = t.quit);
var R;
t.wasmBinary && (R = t.wasmBinary);
var P = t.noExitRuntime || true;
typeof WebAssembly != "object" && Eo("no native wasm support detected");
var L, G = false, W;
function j(Q, ie) {
Q || Eo("Assertion failed: " + ie);
}
function H(Q) {
var ie = t["_" + Q];
return j(ie, "Cannot call unknown function " + Q + ", make sure it is exported"), ie;
}
function q(Q, ie, Ce, pt, nr) {
var Ht = { string: function(Rn) {
var ll = 0;
if (Rn != null && Rn !== 0) {
var vg = (Rn.length << 2) + 1;
ll = jm(vg), ne(Rn, ll, vg);
}
return ll;
}, array: function(Rn) {
var ll = jm(Rn.length);
return fe(Rn, ll), ll;
} };
function nt(Rn) {
return ie === "string" ? oe(Rn) : ie === "boolean" ? Boolean(Rn) : Rn;
}
var ot = H(Q), Pr = [], Oi = 0;
if (pt)
for (var Pi = 0; Pi < pt.length; Pi++) {
var kg = Ht[Ce[Pi]];
kg ? (Oi === 0 && (Oi = wg()), Pr[Pi] = kg(pt[Pi])) : Pr[Pi] = pt[Pi];
}
var qm = ot.apply(null, Pr);
return qm = nt(qm), Oi !== 0 && _g(Oi), qm;
}
function X(Q, ie, Ce, pt) {
Ce = Ce || [];
var nr = Ce.every(function(nt) {
return nt === "number";
}), Ht = ie !== "string";
return Ht && nr && !pt ? H(Q) : function() {
return q(Q, ie, Ce, arguments, pt);
};
}
var re = typeof TextDecoder != "undefined" ? new TextDecoder("utf8") : void 0;
function J(Q, ie, Ce) {
for (var pt = ie + Ce, nr = ie; Q[nr] && !(nr >= pt); )
++nr;
if (nr - ie > 16 && Q.subarray && re)
return re.decode(Q.subarray(ie, nr));
for (var Ht = ""; ie < nr; ) {
var nt = Q[ie++];
if (!(nt & 128)) {
Ht += String.fromCharCode(nt);
continue;
}
var ot = Q[ie++] & 63;
if ((nt & 224) == 192) {
Ht += String.fromCharCode((nt & 31) << 6 | ot);
continue;
}
var Pr = Q[ie++] & 63;
if ((nt & 240) == 224 ? nt = (nt & 15) << 12 | ot << 6 | Pr : nt = (nt & 7) << 18 | ot << 12 | Pr << 6 | Q[ie++] & 63, nt < 65536)
Ht += String.fromCharCode(nt);
else {
var Oi = nt - 65536;
Ht += String.fromCharCode(55296 | Oi >> 10, 56320 | Oi & 1023);
}
}
return Ht;
}
function oe(Q, ie) {
return Q ? J(ye, Q, ie) : "";
}
function se(Q, ie, Ce, pt) {
if (!(pt > 0))
return 0;
for (var nr = Ce, Ht = Ce + pt - 1, nt = 0; nt < Q.length; ++nt) {
var ot = Q.charCodeAt(nt);
if (ot >= 55296 && ot <= 57343) {
var Pr = Q.charCodeAt(++nt);
ot = 65536 + ((ot & 1023) << 10) | Pr & 1023;
}
if (ot <= 127) {
if (Ce >= Ht)
break;
ie[Ce++] = ot;
} else if (ot <= 2047) {
if (Ce + 1 >= Ht)
break;
ie[Ce++] = 192 | ot >> 6, ie[Ce++] = 128 | ot & 63;
} else if (ot <= 65535) {
if (Ce + 2 >= Ht)
break;
ie[Ce++] = 224 | ot >> 12, ie[Ce++] = 128 | ot >> 6 & 63, ie[Ce++] = 128 | ot & 63;
} else {
if (Ce + 3 >= Ht)
break;
ie[Ce++] = 240 | ot >> 18, ie[Ce++] = 128 | ot >> 12 & 63, ie[Ce++] = 128 | ot >> 6 & 63, ie[Ce++] = 128 | ot & 63;
}
}
return ie[Ce] = 0, Ce - nr;
}
function ne(Q, ie, Ce) {
return se(Q, ye, ie, Ce);
}
function fe(Q, ie) {
de.set(Q, ie);
}
function ae(Q, ie) {
return Q % ie > 0 && (Q += ie - Q % ie), Q;
}
var ge, de, ye, _e, Re, Ee, Fe, Ye, ut;
function At(Q) {
ge = Q, t.HEAP8 = de = new Int8Array(Q), t.HEAP16 = _e = new Int16Array(Q), t.HEAP32 = Ee = new Int32Array(Q), t.HEAPU8 = ye = new Uint8Array(Q), t.HEAPU16 = Re = new Uint16Array(Q), t.HEAPU32 = Fe = new Uint32Array(Q), t.HEAPF32 = Ye = new Float32Array(Q), t.HEAPF64 = ut = new Float64Array(Q);
}
var Dt = t.INITIAL_MEMORY || 16777216, ft, Ke = [], ht = [], Mt = [], Dn = [], lr = false;
ht.push({ func: function() {
lg();
} });
function gn() {
if (t.preRun)
for (typeof t.preRun == "function" && (t.preRun = [t.preRun]); t.preRun.length; )
Tr(t.preRun.shift());
Jn(Ke);
}
function Or() {
lr = true, Jn(ht);
}
function To() {
Jn(Mt);
}
function Zr() {
if (t.postRun)
for (typeof t.postRun == "function" && (t.postRun = [t.postRun]); t.postRun.length; )
Gn(t.postRun.shift());
Jn(Dn);
}
function Tr(Q) {
Ke.unshift(Q);
}
function Gn(Q) {
Dn.unshift(Q);
}
var ur = 0, xn = null, $n = null;
function Jl(Q) {
ur++, t.monitorRunDependencies && t.monitorRunDependencies(ur);
}
function Ql(Q) {
if (ur--, t.monitorRunDependencies && t.monitorRunDependencies(ur), ur == 0 && (xn !== null && (clearInterval(xn), xn = null), $n)) {
var ie = $n;
$n = null, ie();
}
}
t.preloadedImages = {}, t.preloadedAudios = {};
function Eo(Q) {
t.onAbort && t.onAbort(Q), Q += "", D(Q), G = true, W = 1, Q = "abort(" + Q + "). Build with -s ASSERTIONS=1 for more info.";
var ie = new WebAssembly.RuntimeError(Q);
throw o(ie), ie;
}
function Ri(Q, ie) {
return String.prototype.startsWith ? Q.startsWith(ie) : Q.indexOf(ie) === 0;
}
var zm = "data:application/octet-stream;base64,";
function Ec(Q) {
return Ri(Q, zm);
}
var rg = "file://";
function ng(Q) {
return Ri(Q, rg);
}
var yn = "tfjs-backend-wasm.wasm";
Ec(yn) || (yn = h(yn));
function og(Q) {
try {
if (Q == yn && R)
return new Uint8Array(R);
if (y)
return y(Q);
throw "both async and sync fetching of the wasm failed";
} catch (ie) {
Eo(ie);
}
}
function bb() {
if (!R && (c || p)) {
if (typeof fetch == "function" && !ng(yn))
return fetch(yn, { credentials: "same-origin" }).then(function(Q) {
if (!Q.ok)
throw "failed to load wasm binary file at '" + yn + "'";
return Q.arrayBuffer();
}).catch(function() {
return og(yn);
});
if (x)
return new Promise(function(Q, ie) {
x(yn, function(Ce) {
Q(new Uint8Array(Ce));
}, ie);
});
}
return Promise.resolve().then(function() {
return og(yn);
});
}
function wb() {
var Q = { a: Sb };
function ie(nt, ot) {
var Pr = nt.exports;
t.asm = Pr, L = t.asm.j, At(L.buffer), ft = t.asm.r, Ql("wasm-instantiate");
}
Jl("wasm-instantiate");
function Ce(nt) {
ie(nt.instance);
}
function pt(nt) {
return bb().then(function(ot) {
return WebAssembly.instantiate(ot, Q);
}).then(nt, function(ot) {
D("failed to asynchronously prepare wasm: " + ot), Eo(ot);
});
}
function nr() {
return !R && typeof WebAssembly.instantiateStreaming == "function" && !Ec(yn) && !ng(yn) && typeof fetch == "function" ? fetch(yn, { credentials: "same-origin" }).then(function(nt) {
var ot = WebAssembly.instantiateStreaming(nt, Q);
return ot.then(Ce, function(Pr) {
return D("wasm streaming compile failed: " + Pr), D("falling back to ArrayBuffer instantiation"), pt(Ce);
});
}) : pt(Ce);
}
if (t.instantiateWasm)
try {
var Ht = t.instantiateWasm(Q, ie);
return Ht;
} catch (nt) {
return D("Module.instantiateWasm callback failed with error: " + nt), false;
}
return nr().catch(o), {};
}
function Jn(Q) {
for (; Q.length > 0; ) {
var ie = Q.shift();
if (typeof ie == "function") {
ie(t);
continue;
}
var Ce = ie.func;
typeof Ce == "number" ? ie.arg === void 0 ? ft.get(Ce)() : ft.get(Ce)(ie.arg) : Ce(ie.arg === void 0 ? null : ie.arg);
}
}
function Bm() {
Eo();
}
function eu(Q, ie, Ce) {
ye.copyWithin(Q, ie, ie + Ce);
}
function _b() {
return ye.length;
}
function kb(Q) {
try {
return L.grow(Q - ge.byteLength + 65535 >>> 16), At(L.buffer), 1;
} catch (ie) {
}
}
function Fi(Q) {
var ie = _b(), Ce = 2147483648;
if (Q > Ce)
return false;
for (var pt = 1; pt <= 4; pt *= 2) {
var nr = ie * (1 + 0.2 / pt);
nr = Math.min(nr, Q + 100663296);
var Ht = Math.min(Ce, ae(Math.max(Q, nr), 65536)), nt = kb(Ht);
if (nt)
return true;
}
return false;
}
var tu = { mappings: {}, buffers: [null, [], []], printChar: function(Q, ie) {
var Ce = tu.buffers[Q];
ie === 0 || ie === 10 ? ((Q === 1 ? A : D)(J(Ce, 0)), Ce.length = 0) : Ce.push(ie);
}, varargs: void 0, get: function() {
tu.varargs += 4;
var Q = Ee[tu.varargs - 4 >> 2];
return Q;
}, getStr: function(Q) {
var ie = oe(Q);
return ie;
}, get64: function(Q, ie) {
return Q;
} };
function vb(Q) {
return 0;
}
function sg(Q, ie, Ce, pt, nr) {
}
function Cb(Q, ie, Ce, pt) {
for (var nr = 0, Ht = 0; Ht < Ce; Ht++) {
for (var nt = Ee[ie + Ht * 8 >> 2], ot = Ee[ie + (Ht * 8 + 4) >> 2], Pr = 0; Pr < ot; Pr++)
tu.printChar(Q, ye[nt + Pr]);
nr += ot;
}
return Ee[pt >> 2] = nr, 0;
}
function ig() {
return 6;
}
function bn() {
return 28;
}
function ag(Q) {
return Ee[bg() >> 2] = Q, Q;
}
function Ib(Q) {
switch (Q) {
case 30:
return 16384;
case 85:
var ie = 2147483648;
return ie / 16384;
case 132:
case 133:
case 12:
case 137:
case 138:
case 15:
case 235:
case 16:
case 17:
case 18:
case 19:
case 20:
case 149:
case 13:
case 10:
case 236:
case 153:
case 9:
case 21:
case 22:
case 159:
case 154:
case 14:
case 77:
case 78:
case 139:
case 82:
case 68:
case 67:
case 164:
case 11:
case 29:
case 47:
case 48:
case 95:
case 52:
case 51:
case 46:
return 200809;
case 27:
case 246:
case 127:
case 128:
case 23:
case 24:
case 160:
case 161:
case 181:
case 182:
case 242:
case 183:
case 184:
case 243:
case 244:
case 245:
case 165:
case 178:
case 179:
case 49:
case 50:
case 168:
case 169:
case 175:
case 170:
case 171:
case 172:
case 97:
case 76:
case 32:
case 173:
case 35:
case 80:
case 81:
case 79:
return -1;
case 176:
case 177:
case 7:
case 155:
case 8:
case 157:
case 125:
case 126:
case 92:
case 93:
case 129:
case 130:
case 131:
case 94:
case 91:
return 1;
case 74:
case 60:
case 69:
case 70:
case 4:
return 1024;
case 31:
case 42:
case 72:
return 32;
case 87:
case 26:
case 33:
return 2147483647;
case 34:
case 1:
return 47839;
case 38:
case 36:
return 99;
case 43:
case 37:
return 2048;
case 0:
return 2097152;
case 3:
return 65536;
case 28:
return 32768;
case 44:
return 32767;
case 75:
return 16384;
case 39:
return 1e3;
case 89:
return 700;
case 71:
return 256;
case 40:
return 255;
case 2:
return 100;
case 180:
return 64;
case 25:
return 20;
case 5:
return 16;
case 6:
return 6;
case 73:
return 4;
case 84:
return typeof navigator == "object" && navigator.hardwareConcurrency || 1;
}
return ag(28), -1;
}
var Sb = { a: Bm, d: eu, e: Fi, f: vb, c: sg, b: Cb, h: ig, g: bn, i: Ib }, Nb = wb(), lg = t.___wasm_call_ctors = function() {
return (lg = t.___wasm_call_ctors = t.asm.k).apply(null, arguments);
}, Ac = t._init = function() {
return (Ac = t._init = t.asm.l).apply(null, arguments);
}, sl = t._init_with_threads_count = function() {
return (sl = t._init_with_threads_count = t.asm.m).apply(null, arguments);
}, Vm = t._get_threads_count = function() {
return (Vm = t._get_threads_count = t.asm.n).apply(null, arguments);
}, Tb = t._register_tensor = function() {
return (Tb = t._register_tensor = t.asm.o).apply(null, arguments);
}, Eb = t._dispose_data = function() {
return (Eb = t._dispose_data = t.asm.p).apply(null, arguments);
}, ug = t._dispose = function() {
return (ug = t._dispose = t.asm.q).apply(null, arguments);
}, Ae = t._Abs = function() {
return (Ae = t._Abs = t.asm.s).apply(null, arguments);
}, Ab = t._Add = function() {
return (Ab = t._Add = t.asm.t).apply(null, arguments);
}, Db = t._AddN = function() {
return (Db = t._AddN = t.asm.u).apply(null, arguments);
}, $b = t._All = function() {
return ($b = t._All = t.asm.v).apply(null, arguments);
}, Rb = t._Any = function() {
return (Rb = t._Any = t.asm.w).apply(null, arguments);
}, Fb = t._ArgMax = function() {
return (Fb = t._ArgMax = t.asm.x).apply(null, arguments);
}, ru = t._AvgPool = function() {
return (ru = t._AvgPool = t.asm.y).apply(null, arguments);
}, Ob = t._BatchMatMul = function() {
return (Ob = t._BatchMatMul = t.asm.z).apply(null, arguments);
}, Pb = t._Ceil = function() {
return (Pb = t._Ceil = t.asm.A).apply(null, arguments);
}, Mb = t._ClipByValue = function() {
return (Mb = t._ClipByValue = t.asm.B).apply(null, arguments);
}, Lb = t._Conv2D = function() {
return (Lb = t._Conv2D = t.asm.C).apply(null, arguments);
}, zb = t._Conv2DBackpropInput = function() {
return (zb = t._Conv2DBackpropInput = t.asm.D).apply(null, arguments);
}, Bb = t._Cos = function() {
return (Bb = t._Cos = t.asm.E).apply(null, arguments);
}, cg = t._Cosh = function() {
return (cg = t._Cosh = t.asm.F).apply(null, arguments);
}, Vb = t._CropAndResize = function() {
return (Vb = t._CropAndResize = t.asm.G).apply(null, arguments);
}, Gb = t._Cumsum = function() {
return (Gb = t._Cumsum = t.asm.H).apply(null, arguments);
}, il = t._DepthToSpace = function() {
return (il = t._DepthToSpace = t.asm.I).apply(null, arguments);
}, Gm = t._DepthwiseConv2dNative = function() {
return (Gm = t._DepthwiseConv2dNative = t.asm.J).apply(null, arguments);
}, Wm = t._Elu = function() {
return (Wm = t._Elu = t.asm.K).apply(null, arguments);
}, Wb = t._Equal = function() {
return (Wb = t._Equal = t.asm.L).apply(null, arguments);
}, Ub = t._Exp = function() {
return (Ub = t._Exp = t.asm.M).apply(null, arguments);
}, jb = t._FlipLeftRight = function() {
return (jb = t._FlipLeftRight = t.asm.N).apply(null, arguments);
}, Hb = t._Floor = function() {
return (Hb = t._Floor = t.asm.O).apply(null, arguments);
}, qb = t._FloorDiv = function() {
return (qb = t._FloorDiv = t.asm.P).apply(null, arguments);
}, Qe = t._FusedBatchNorm = function() {
return (Qe = t._FusedBatchNorm = t.asm.Q).apply(null, arguments);
}, Kb = t._FusedConv2D = function() {
return (Kb = t._FusedConv2D = t.asm.R).apply(null, arguments);
}, Xb = t._FusedDepthwiseConv2D = function() {
return (Xb = t._FusedDepthwiseConv2D = t.asm.S).apply(null, arguments);
}, Yb = t._Gather = function() {
return (Yb = t._Gather = t.asm.T).apply(null, arguments);
}, Zb = t._GatherNd = function() {
return (Zb = t._GatherNd = t.asm.U).apply(null, arguments);
}, Jb = t._Greater = function() {
return (Jb = t._Greater = t.asm.V).apply(null, arguments);
}, Qb = t._GreaterEqual = function() {
return (Qb = t._GreaterEqual = t.asm.W).apply(null, arguments);
}, Um = t._LeakyRelu = function() {
return (Um = t._LeakyRelu = t.asm.X).apply(null, arguments);
}, pg = t._Less = function() {
return (pg = t._Less = t.asm.Y).apply(null, arguments);
}, mg = t._LessEqual = function() {
return (mg = t._LessEqual = t.asm.Z).apply(null, arguments);
}, ew = t._Log = function() {
return (ew = t._Log = t.asm._).apply(null, arguments);
}, tw = t._LogicalAnd = function() {
return (tw = t._LogicalAnd = t.asm.$).apply(null, arguments);
}, rw = t._Max = function() {
return (rw = t._Max = t.asm.aa).apply(null, arguments);
}, nw = t._MaxPool = function() {
return (nw = t._MaxPool = t.asm.ba).apply(null, arguments);
}, ow = t._Maximum = function() {
return (ow = t._Maximum = t.asm.ca).apply(null, arguments);
}, sw = t._Mean = function() {
return (sw = t._Mean = t.asm.da).apply(null, arguments);
}, iw = t._Min = function() {
return (iw = t._Min = t.asm.ea).apply(null, arguments);
}, gt = t._Minimum = function() {
return (gt = t._Minimum = t.asm.fa).apply(null, arguments);
}, aw = t._MirrorPad = function() {
return (aw = t._MirrorPad = t.asm.ga).apply(null, arguments);
}, lw = t._Multiply = function() {
return (lw = t._Multiply = t.asm.ha).apply(null, arguments);
}, uw = t._Neg = function() {
return (uw = t._Neg = t.asm.ia).apply(null, arguments);
}, Dc = t._NonMaxSuppressionV3 = function() {
return (Dc = t._NonMaxSuppressionV3 = t.asm.ja).apply(null, arguments);
}, fg = t._NonMaxSuppressionV4 = function() {
return (fg = t._NonMaxSuppressionV4 = t.asm.ka).apply(null, arguments);
}, dg = t._NonMaxSuppressionV5 = function() {
return (dg = t._NonMaxSuppressionV5 = t.asm.la).apply(null, arguments);
}, hg = t._NotEqual = function() {
return (hg = t._NotEqual = t.asm.ma).apply(null, arguments);
}, cw = t._OneHot = function() {
return (cw = t._OneHot = t.asm.na).apply(null, arguments);
}, pw = t._PadV2 = function() {
return (pw = t._PadV2 = t.asm.oa).apply(null, arguments);
}, gg = t._Pow = function() {
return (gg = t._Pow = t.asm.pa).apply(null, arguments);
}, mw = t._Prelu = function() {
return (mw = t._Prelu = t.asm.qa).apply(null, arguments);
}, fw = t._Prod = function() {
return (fw = t._Prod = t.asm.ra).apply(null, arguments);
}, dw = t._RealDiv = function() {
return (dw = t._RealDiv = t.asm.sa).apply(null, arguments);
}, hw = t._Relu = function() {
return (hw = t._Relu = t.asm.ta).apply(null, arguments);
}, gw = t._Relu6 = function() {
return (gw = t._Relu6 = t.asm.ua).apply(null, arguments);
}, xg = t._ResizeBilinear = function() {
return (xg = t._ResizeBilinear = t.asm.va).apply(null, arguments);
}, al = t._Reverse = function() {
return (al = t._Reverse = t.asm.wa).apply(null, arguments);
}, xw = t._RotateWithOffset = function() {
return (xw = t._RotateWithOffset = t.asm.xa).apply(null, arguments);
}, yw = t._Round = function() {
return (yw = t._Round = t.asm.ya).apply(null, arguments);
}, PS = t._Rsqrt = function() {
return (PS = t._Rsqrt = t.asm.za).apply(null, arguments);
}, yg = t._ScatterNd = function() {
return (yg = t._ScatterNd = t.asm.Aa).apply(null, arguments);
}, bw = t._SelectV2 = function() {
return (bw = t._SelectV2 = t.asm.Ba).apply(null, arguments);
}, ww = t._Sigmoid = function() {
return (ww = t._Sigmoid = t.asm.Ca).apply(null, arguments);
}, _w = t._Sin = function() {
return (_w = t._Sin = t.asm.Da).apply(null, arguments);
}, kw = t._Softmax = function() {
return (kw = t._Softmax = t.asm.Ea).apply(null, arguments);
}, vw = t._Sqrt = function() {
return (vw = t._Sqrt = t.asm.Fa).apply(null, arguments);
}, Cw = t._Square = function() {
return (Cw = t._Square = t.asm.Ga).apply(null, arguments);
}, Iw = t._SquaredDifference = function() {
return (Iw = t._SquaredDifference = t.asm.Ha).apply(null, arguments);
}, Sw = t._Step = function() {
return (Sw = t._Step = t.asm.Ia).apply(null, arguments);
}, Nw = t._StridedSlice = function() {
return (Nw = t._StridedSlice = t.asm.Ja).apply(null, arguments);
}, Tw = t._Sub = function() {
return (Tw = t._Sub = t.asm.Ka).apply(null, arguments);
}, Ew = t._Sum = function() {
return (Ew = t._Sum = t.asm.La).apply(null, arguments);
}, Aw = t._Tan = function() {
return (Aw = t._Tan = t.asm.Ma).apply(null, arguments);
}, Dw = t._Tanh = function() {
return (Dw = t._Tanh = t.asm.Na).apply(null, arguments);
}, $w = t._Tile = function() {
return ($w = t._Tile = t.asm.Oa).apply(null, arguments);
}, Rw = t._TopK = function() {
return (Rw = t._TopK = t.asm.Pa).apply(null, arguments);
}, Fw = t._Transform = function() {
return (Fw = t._Transform = t.asm.Qa).apply(null, arguments);
}, Ow = t._Transpose = function() {
return (Ow = t._Transpose = t.asm.Ra).apply(null, arguments);
}, Pw = t.__FusedMatMul = function() {
return (Pw = t.__FusedMatMul = t.asm.Sa).apply(null, arguments);
}, Mw = t._malloc = function() {
return (Mw = t._malloc = t.asm.Ta).apply(null, arguments);
}, Lw = t._free = function() {
return (Lw = t._free = t.asm.Ua).apply(null, arguments);
}, bg = t.___errno_location = function() {
return (bg = t.___errno_location = t.asm.Va).apply(null, arguments);
}, wg = t.stackSave = function() {
return (wg = t.stackSave = t.asm.Wa).apply(null, arguments);
}, _g = t.stackRestore = function() {
return (_g = t.stackRestore = t.asm.Xa).apply(null, arguments);
}, jm = t.stackAlloc = function() {
return (jm = t.stackAlloc = t.asm.Ya).apply(null, arguments);
};
t.cwrap = X;
var $c;
function zw(Q) {
this.name = "ExitStatus", this.message = "Program terminated with exit(" + Q + ")", this.status = Q;
}
$n = function Q() {
$c || Hm(), $c || ($n = Q);
};
function Hm(Q) {
if (Q = Q || i, ur > 0 || (gn(), ur > 0))
return;
function ie() {
$c || ($c = true, t.calledRun = true, !G && (Or(), To(), n(t), t.onRuntimeInitialized && t.onRuntimeInitialized(), Zr()));
}
t.setStatus ? (t.setStatus("Running..."), setTimeout(function() {
setTimeout(function() {
t.setStatus("");
}, 1), ie();
}, 1)) : ie();
}
if (t.run = Hm, t.preInit)
for (typeof t.preInit == "function" && (t.preInit = [t.preInit]); t.preInit.length > 0; )
t.preInit.pop()();
return Hm(), e.ready;
};
}();
typeof gb == "object" && typeof $S == "object" ? $S.exports = DS : typeof define == "function" && define.amd ? define([], function() {
return DS;
}) : typeof gb == "object" && (gb.WasmBackendModule = DS);
});
var pW = 1e-7;
var mW = 1e-4;
var pl = class {
constructor(e, t) {
this.backend = e, this.dataMover = t, this.data = new WeakMap(), this.dataIdsCount = 0;
}
get(e) {
return this.data.has(e) || this.dataMover.moveData(this.backend, e), this.data.get(e);
}
set(e, t) {
this.dataIdsCount++, this.data.set(e, t);
}
has(e) {
return this.data.has(e);
}
delete(e) {
return this.dataIdsCount--, this.data.delete(e);
}
numDataIds() {
return this.dataIdsCount;
}
};
var Js = class {
refCount(e) {
return Qn("refCount");
}
incRef(e) {
return Qn("incRef");
}
timerAvailable() {
return true;
}
time(e) {
return Qn("time");
}
read(e) {
return Qn("read");
}
readSync(e) {
return Qn("readSync");
}
numDataIds() {
return Qn("numDataIds");
}
disposeData(e, t) {
return Qn("disposeData");
}
write(e, t, n) {
return Qn("write");
}
move(e, t, n, o, s) {
return Qn("move");
}
memory() {
return Qn("memory");
}
floatPrecision() {
return Qn("floatPrecision");
}
epsilon() {
return this.floatPrecision() === 32 ? pW : mW;
}
dispose() {
return Qn("dispose");
}
};
function Qn(r) {
throw new Error(`'${r}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`);
}
function YS(r) {
let e = r.length, t = 0;
for (; e > 0; )
t = Math.random() * e | 0, e--, Ng(r, e, t);
}
function fW(r, e) {
if (r.length !== e.length)
throw new Error(`Array sizes must match to be shuffled together First array length was ${r.length}Second array length was ${e.length}`);
let t = r.length, n = 0;
for (; t > 0; )
n = Math.random() * t | 0, t--, Ng(r, t, n), Ng(e, t, n);
}
function zc(r, e, t) {
return Math.max(r, Math.min(e, t));
}
function dW(r) {
return r % 2 == 0 ? r : r + 1;
}
function Ng(r, e, t) {
let n = r[e];
r[e] = r[t], r[t] = n;
}
function hW(r) {
let e = 0;
for (let t = 0; t < r.length; t++)
e += r[t];
return e;
}
function gW(r, e) {
let t = Math.random();
return e * t + (1 - t) * r;
}
function xW(r, e) {
let t = 0;
for (let n = 0; n < r.length; n++) {
let o = Number(r[n]) - Number(e[n]);
t += o * o;
}
return t;
}
function E(r, e) {
if (!r)
throw new Error(typeof e == "string" ? e : e());
}
function Rt(r, e, t = "") {
E(Qr(r, e), () => t + ` Shapes ${r} and ${e} must match`);
}
function Wn(r) {
E(r != null, () => "The input to the tensor constructor must be a non-null value.");
}
function Ao(r, e = [], t = false) {
if (e == null && (e = []), Array.isArray(r) || dr(r) && !t)
for (let n = 0; n < r.length; ++n)
Ao(r[n], e, t);
else
e.push(r);
return e;
}
function st(r) {
if (r.length === 0)
return 1;
let e = r[0];
for (let t = 1; t < r.length; t++)
e *= r[t];
return e;
}
function yW(r) {
return r.length === 0;
}
function Qr(r, e) {
if (r === e)
return true;
if (r == null || e == null || r.length !== e.length)
return false;
for (let t = 0; t < r.length; t++)
if (r[t] !== e[t])
return false;
return true;
}
function it(r) {
return r % 1 == 0;
}
function bW(r) {
if (Math.tanh != null)
return Math.tanh(r);
if (r === 1 / 0)
return 1;
if (r === -1 / 0)
return -1;
{
let e = Math.exp(2 * r);
return (e - 1) / (e + 1);
}
}
function wW(r) {
let e = Math.ceil(Math.sqrt(r));
return [e, Math.ceil(r / e)];
}
function _W(r) {
let e = new Uint32Array(r);
for (let t = 0; t < r; ++t)
e[t] = t;
return YS(e), e;
}
function su(r, e) {
return e <= r.length ? r : r + " ".repeat(e - r.length);
}
function kW(r, e = (n) => 0, t) {
return new Promise((n, o) => {
let s = 0, a = () => {
if (r()) {
n();
return;
}
s++;
let i = e(s);
if (t != null && s >= t) {
o();
return;
}
setTimeout(a, i);
};
a();
});
}
function vW(r, e) {
let t = 1, n = -1;
for (let s = 0; s < r.length; ++s)
if (r[s] >= 0)
t *= r[s];
else if (r[s] === -1) {
if (n !== -1)
throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${n} and dim ${s}`);
n = s;
} else if (r[s] < 0)
throw Error(`Shapes can not be < 0. Found ${r[s]} at dim ${s}`);
if (n === -1) {
if (e > 0 && e !== t)
throw Error(`Size(${e}) must match the product of shape ${r}`);
return r;
}
if (t === 0)
throw Error(`Cannot infer the missing size in [${r}] when there are 0 elements`);
if (e % t != 0)
throw Error(`The implicit shape can't be a fractional number. Got ${e} / ${t}`);
let o = r.slice();
return o[n] = e / t, o;
}
function cr(r, e) {
let t = e.length;
return r = r == null ? e.map((n, o) => o) : [].concat(r), E(r.every((n) => n >= -t && n < t), () => `All values in axis param must be in range [-${t}, ${t}) but got axis ${r}`), E(r.every((n) => it(n)), () => `All values in axis param must be integers but got axis ${r}`), r.map((n) => n < 0 ? t + n : n);
}
function Ww(r, e) {
let t = [], n = [], o = e != null && Array.isArray(e) && e.length === 0, s = e == null || o ? null : cr(e, r).sort(), a = 0;
for (let i = 0; i < r.length; ++i) {
if (s != null) {
if (s[a] === i && r[i] !== 1)
throw new Error(`Can't squeeze axis ${i} since its dim '${r[i]}' is not 1`);
(s[a] == null || s[a] > i) && r[i] === 1 && (t.push(r[i]), n.push(i)), s[a] <= i && a++;
}
r[i] !== 1 && (t.push(r[i]), n.push(i));
}
return { newShape: t, keptDims: n };
}
function Uw(r, e) {
let t = null;
if (r == null || r === "float32")
t = new Float32Array(e);
else if (r === "int32")
t = new Int32Array(e);
else if (r === "bool")
t = new Uint8Array(e);
else
throw new Error(`Unknown data type ${r}`);
return t;
}
function jw(r, e) {
let t = null;
if (r == null || r === "float32")
t = new Float32Array(e);
else if (r === "int32")
t = new Int32Array(e);
else if (r === "bool")
t = new Uint8Array(e);
else if (r === "string")
t = new Array(e);
else
throw new Error(`Unknown data type ${r}`);
return t;
}
function Hw(r, e) {
for (let t = 0; t < r.length; t++) {
let n = r[t];
if (isNaN(n) || !isFinite(n))
throw Error(`A tensor of type ${e} being uploaded contains ${n}.`);
}
}
function qw(r) {
return r === "bool" || r === "complex64" || r === "float32" || r === "int32" || r === "string";
}
function CW(r, e) {
return !(e === "complex64" || e === "float32" && r !== "complex64" || e === "int32" && r !== "float32" && r !== "complex64" || e === "bool" && r === "bool");
}
function dr(r) {
return r instanceof Float32Array || r instanceof Int32Array || r instanceof Uint8Array || r instanceof Uint8ClampedArray;
}
function Tg(r) {
if (r === "float32" || r === "int32")
return 4;
if (r === "complex64")
return 8;
if (r === "bool")
return 1;
throw new Error(`Unknown dtype ${r}`);
}
function Kw(r) {
if (r == null)
return 0;
let e = 0;
return r.forEach((t) => e += t.length), e;
}
function Do(r) {
return typeof r == "string" || r instanceof String;
}
function ZS(r) {
return typeof r == "boolean";
}
function JS(r) {
return typeof r == "number";
}
function Bc(r) {
return Array.isArray(r) ? Bc(r[0]) : r instanceof Float32Array ? "float32" : r instanceof Int32Array || r instanceof Uint8Array || r instanceof Uint8ClampedArray ? "int32" : JS(r) ? "float32" : Do(r) ? "string" : ZS(r) ? "bool" : "float32";
}
function Qs(r) {
return !!(r && r.constructor && r.call && r.apply);
}
function Vc(r, e) {
for (let t = e; t < r; ++t)
if (r % t == 0)
return t;
return r;
}
function ei(r) {
let e = r.length;
if (e < 2)
return [];
let t = new Array(e - 1);
t[e - 2] = r[e - 1];
for (let n = e - 3; n >= 0; --n)
t[n] = t[n + 1] * r[n + 1];
return t;
}
function QS(r, e, t, n = false) {
let o = new Array();
if (e.length === 1) {
let s = e[0] * (n ? 2 : 1);
for (let a = 0; a < s; a++)
o[a] = t[r + a];
} else {
let s = e[0], a = e.slice(1), i = a.reduce((l, u) => l * u) * (n ? 2 : 1);
for (let l = 0; l < s; l++)
o[l] = QS(r + l * i, a, t, n);
}
return o;
}
function iu(r, e, t = false) {
if (r.length === 0)
return e[0];
let n = r.reduce((o, s) => o * s) * (t ? 2 : 1);
if (n === 0)
return [];
if (n !== e.length)
throw new Error(`[${r}] does not match the input size ${e.length}${t ? " for a complex tensor" : ""}.`);
return QS(0, r, e, t);
}
function Zm(r, e) {
let t = Gc(r, e);
for (let n = 0; n < t.length; n++)
t[n] = 1;
return t;
}
function Gc(r, e) {
if (e == null || e === "float32" || e === "complex64")
return new Float32Array(r);
if (e === "int32")
return new Int32Array(r);
if (e === "bool")
return new Uint8Array(r);
throw new Error(`Unknown data type ${e}`);
}
function IW(r, e) {
let t = r.reduce((n, o) => n * o, 1);
if (e == null || e === "float32")
return iu(r, new Float32Array(t));
if (e === "int32")
return iu(r, new Int32Array(t));
if (e === "bool")
return iu(r, new Uint8Array(t));
throw new Error(`Unknown data type ${e}`);
}
function Jm(r) {
r.forEach((e) => {
E(Number.isInteger(e) && e >= 0, () => `Tensor must have a shape comprised of positive integers but got shape [${r}].`);
});
}
function SW(r, e, t) {
if (e === 0)
return 0;
if (e === 1)
return r[0];
let n = r[r.length - 1];
for (let o = 0; o < r.length - 1; ++o)
n += t[o] * r[o];
return n;
}
function NW(r, e, t) {
if (e === 0)
return [];
if (e === 1)
return [r];
let n = new Array(e);
for (let o = 0; o < n.length - 1; ++o)
n[o] = Math.floor(r / t[o]), r -= n[o] * t[o];
return n[n.length - 1] = r, n;
}
function Qm(r) {
return r && r.then && typeof r.then == "function";
}
function Un(...r) {
U().getBool("IS_TEST") || U().getBool("PROD") || console.warn(...r);
}
function TW(...r) {
U().getBool("IS_TEST") || U().getBool("PROD") || console.log(...r);
}
var eN = "tfjsflags";
var Eg = class {
constructor(e) {
this.global = e, this.flags = {}, this.flagRegistry = {}, this.urlFlags = {}, this.getQueryParams = EW, this.populateURLFlags();
}
setPlatform(e, t) {
this.platform != null && Un(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`), this.platformName = e, this.platform = t;
}
registerFlag(e, t, n) {
if (this.flagRegistry[e] = { evaluationFn: t, setHook: n }, this.urlFlags[e] != null) {
let o = this.urlFlags[e];
Un(`Setting feature override from URL ${e}: ${o}.`), this.set(e, o);
}
}
async getAsync(e) {
return e in this.flags ? this.flags[e] : (this.flags[e] = await this.evaluateFlag(e), this.flags[e]);
}
get(e) {
if (e in this.flags)
return this.flags[e];
let t = this.evaluateFlag(e);
if (Qm(t))
throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);
return this.flags[e] = t, this.flags[e];
}
getNumber(e) {
return this.get(e);
}
getBool(e) {
return this.get(e);
}
getFlags() {
return this.flags;
}
get features() {
return this.flags;
}
set(e, t) {
if (this.flagRegistry[e] == null)
throw new Error(`Cannot set flag ${e} as it has not been registered.`);
this.flags[e] = t, this.flagRegistry[e].setHook != null && this.flagRegistry[e].setHook(t);
}
evaluateFlag(e) {
if (this.flagRegistry[e] == null)
throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);
return this.flagRegistry[e].evaluationFn();
}
setFlags(e) {
this.flags = Object.assign({}, e);
}
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;
let e = this.getQueryParams(this.global.location.search);
eN in e && e[eN].split(",").forEach((n) => {
let [o, s] = n.split(":");
this.urlFlags[o] = DW(o, s);
});
}
};
function EW(r) {
let e = {};
return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (t, ...n) => (AW(e, n[0], n[1]), n.join("="))), e;
}
function AW(r, e, t) {
r[decodeURIComponent(e)] = decodeURIComponent(t || "");
}
function DW(r, e) {
if (e = e.toLowerCase(), e === "true" || e === "false")
return e === "true";
if (`${+e}` === e)
return +e;
throw new Error(`Could not parse value flag value ${e} for flag ${r}.`);
}
function U() {
return Xw;
}
var Xw = null;
function tN(r) {
Xw = r;
}
var Yw;
function Zw() {
if (Yw == null) {
let r;
if (typeof window != "undefined")
r = window;
else if (typeof global != "undefined")
r = global;
else if (typeof process != "undefined")
r = process;
else if (typeof self != "undefined")
r = self;
else
throw new Error("Could not find a global object");
Yw = r;
}
return Yw;
}
function $W() {
let r = Zw();
return r._tfGlobals == null && (r._tfGlobals = new Map()), r._tfGlobals;
}
function ef(r, e) {
let t = $W();
if (t.has(r))
return t.get(r);
{
let n = e();
return t.set(r, n), t.get(r);
}
}
var ti = "Abs";
var Mi = "Acos";
var Li = "Acosh";
var jn = "Add";
var $o = "AddN";
var zi = "All";
var Bi = "Any";
var Ro = "ArgMax";
var ml = "ArgMin";
var Vi = "Asin";
var Gi = "Asinh";
var Wi = "Atan";
var Ui = "Atanh";
var ji = "Atan2";
var Fo = "AvgPool";
var Wc = "AvgPoolGrad";
var fl = "AvgPool3D";
var Uc = "AvgPool3DGrad";
var Oo = "BatchMatMul";
var ri = "BatchToSpaceND";
var jc = "Bincount";
var rN = "BroadcastTo";
var Hc = "BroadcastArgs";
var eo = "Cast";
var Po = "Ceil";
var to = "ClipByValue";
var qc = "Complex";
var dl = "ComplexAbs";
var ni = "Concat";
var Mo = "Conv2D";
var Kc = "Conv2DBackpropFilter";
var Lo = "Conv2DBackpropInput";
var hl = "Conv3D";
var Xc = "Conv3DBackpropFilterV2";
var Yc = "Conv3DBackpropInputV2";
var zo = "Cos";
var Bo = "Cosh";
var Vo = "Cumsum";
var Hi = "CropAndResize";
var Zc = "DenseBincount";
var qi = "DepthToSpace";
var Go = "DepthwiseConv2dNative";
var Jc = "DepthwiseConv2dNativeBackpropFilter";
var Qc = "DepthwiseConv2dNativeBackpropInput";
var ep = "Diag";
var gl = "Dilation2D";
var tf = "Dilation2DBackpropInput";
var rf = "Dilation2DBackpropFilter";
var Wo = "RealDiv";
var tp = "Einsum";
var Uo = "Elu";
var rp = "EluGrad";
var Ki = "Erf";
var Xi = "Equal";
var jo = "Exp";
var oi = "ExpandDims";
var Yi = "Expm1";
var np = "FFT";
var xl = "Fill";
var Zi = "FlipLeftRight";
var Ho = "Floor";
var qo = "FloorDiv";
var Ko = "FusedBatchNorm";
var si = "GatherV2";
var Ji = "GatherNd";
var Qi = "Greater";
var Xo = "GreaterEqual";
var ro = "Identity";
var op = "IFFT";
var sp = "Imag";
var ea = "IsFinite";
var ta = "IsInf";
var ra = "IsNan";
var Yo = "LeakyRelu";
var na = "Less";
var oa = "LessEqual";
var ip = "LinSpace";
var Zo = "Log";
var sa = "Log1p";
var ia = "LogicalAnd";
var au = "LogicalNot";
var lu = "LogicalOr";
var nN = "LogSoftmax";
var yl = "LRN";
var ap = "LRNGrad";
var Jo = "Max";
var Qo = "Maximum";
var es = "MaxPool";
var lp = "MaxPoolGrad";
var bl = "MaxPool3D";
var up = "MaxPool3DGrad";
var cp = "MaxPoolWithArgmax";
var ts = "Mean";
var rs = "Min";
var ns = "Minimum";
var os = "MirrorPad";
var aa = "Mod";
var pp = "Multinomial";
var ss = "Multiply";
var ii = "Neg";
var la = "NotEqual";
var ua = "NonMaxSuppressionV3";
var ca = "NonMaxSuppressionV4";
var pa = "NonMaxSuppressionV5";
var ai = "OnesLike";
var is = "OneHot";
var li = "Pack";
var as = "PadV2";
var hse = "Pool";
var ls = "Pow";
var us = "Prelu";
var ma = "Prod";
var wl = "Range";
var mp = "Real";
var fa = "Reciprocal";
var cs = "Relu";
var ui = "Reshape";
var _l = "ResizeNearestNeighbor";
var fp = "ResizeNearestNeighborGrad";
var ps = "ResizeBilinear";
var dp = "ResizeBilinearGrad";
var ms = "Relu6";
var fs = "Reverse";
var ds = "Round";
var hs = "Rsqrt";
var da = "ScatterNd";
var ci = "Select";
var ha = "Selu";
var pi = "Slice";
var gs = "Sin";
var ga = "Sinh";
var xa = "Sign";
var xs = "Sigmoid";
var ya = "Softplus";
var ys = "Sqrt";
var bs = "Sum";
var mi = "SpaceToBatchND";
var fi = "SplitV";
var ws = "Softmax";
var hp = "SparseFillEmptyRows";
var gp = "SparseReshape";
var xp = "SparseSegmentMean";
var yp = "SparseSegmentSum";
var bp = "SparseToDense";
var _s = "SquaredDifference";
var kl = "Square";
var ba = "StridedSlice";
var wp = "StringNGrams";
var _p = "StringSplit";
var kp = "StringToHashBucketFast";
var ks = "Sub";
var vs = "Tan";
var Cs = "Tanh";
var Hn = "Tile";
var wa = "TopK";
var _a = "Transform";
var Is = "Transpose";
var vp = "Unique";
var di = "Unpack";
var vl = "UnsortedSegmentSum";
var hi = "ZerosLike";
var no = "Step";
var nf = "FromPixels";
var ka = "RotateWithOffset";
var gi = "_FusedMatMul";
var xi = "FusedConv2D";
var yi = "FusedDepthwiseConv2D";
var Cp = ef("kernelRegistry", () => new Map());
var of = ef("gradRegistry", () => new Map());
function sf(r, e) {
let t = Qw(r, e);
return Cp.get(t);
}
function Jw(r) {
return of.get(r);
}
function Ag(r) {
let e = Cp.entries(), t = [];
for (; ; ) {
let { done: n, value: o } = e.next();
if (n)
break;
let [s, a] = o, [i] = s.split("_");
i === r && t.push(a);
}
return t;
}
function uu(r) {
let { kernelName: e, backendName: t } = r, n = Qw(e, t);
Cp.has(n) && Un(`The kernel '${e}' for backend '${t}' is already registered`), Cp.set(n, r);
}
function oN(r) {
let { kernelName: e } = r;
of.has(e) && U().getBool("DEBUG") && Un(`Overriding the gradient for '${e}'`), of.set(e, r);
}
function wse(r, e) {
let t = Qw(r, e);
if (!Cp.has(t))
throw new Error(`The kernel '${r}' for backend '${e}' is not registered`);
Cp.delete(t);
}
function _se(r) {
if (!of.has(r))
throw new Error(`The gradient '${r}' for backend is not registered`);
of.delete(r);
}
function kse(r, e) {
Ag(r).forEach((n) => {
let o = Object.assign({}, n, { backendName: e });
uu(o);
});
}
function Qw(r, e) {
return `${e}_${r}`;
}
var b = {};
qe(b, { arraysEqual: () => Qr, assert: () => E, assertNonNegativeIntegerDimensions: () => Jm, assertNonNull: () => Wn, assertShapesMatch: () => Rt, bytesFromStringArray: () => Kw, bytesPerElement: () => Tg, checkConversionForErrors: () => Hw, clamp: () => zc, computeStrides: () => ei, createScalarValue: () => zW, createShuffledIndices: () => _W, decodeString: () => Tp, distSquared: () => xW, encodeString: () => Il, fetch: () => VW, fingerPrint64: () => LW, flatten: () => Ao, getArrayFromDType: () => jw, getTypedArrayFromDType: () => Uw, hasEncodingLoss: () => CW, hexToLong: () => af, indexToLoc: () => NW, inferDtype: () => Bc, inferFromImplicitShape: () => vW, isBoolean: () => ZS, isFunction: () => Qs, isInt: () => it, isNumber: () => JS, isPromise: () => Qm, isScalarShape: () => yW, isString: () => Do, isTypedArray: () => dr, isValidDtype: () => qw, locToIndex: () => SW, makeOnesTypedArray: () => Zm, makeZerosNestedTypedArray: () => IW, makeZerosTypedArray: () => Gc, nearestDivisor: () => Vc, nearestLargerEven: () => dW, now: () => du, parseAxisParam: () => cr, randUniform: () => gW, repeatedTry: () => kW, rightPad: () => su, shuffle: () => YS, shuffleCombo: () => fW, sizeFromShape: () => st, sizeToSquarishShape: () => wW, squeezeShape: () => Ww, sum: () => hW, swap: () => Ng, tanh: () => bW, toNestedArray: () => iu, toTypedArray: () => Np });
var gN = ou(hN());
var mu = gN.default || gN;
function af(r) {
return mu.fromString(r, true, 16);
}
var xN = af("c3a5c85c97cb3127");
var fu = af("b492b66fbe98f273");
var en = af("9ae16a3b2f90404f");
function r_(r) {
return r.xor(r.shru(47));
}
function yN(r, e, t) {
let n = r.slice(e, e + t);
return mu.fromBytes(Array.from(n), true, true);
}
function Lt(r, e) {
return yN(r, e, 8);
}
function bN(r, e) {
return yN(r, e, 4);
}
function Ar(r, e) {
return e === 0 ? r : r.shru(e).or(r.shl(64 - e));
}
function Cl(r, e, t = af("9ddfea08eb382d69")) {
let n = r.xor(e).mul(t);
n = n.xor(n.shru(47));
let o = e.xor(n).mul(t);
return o = o.xor(o.shru(47)), o = o.mul(t), o;
}
function FW(r, e, t, n, o, s) {
o = o.add(r), s = Ar(s.add(o).add(n), 21);
let a = o;
return o = o.add(e), o = o.add(t), s = s.add(Ar(o, 44)), [o.add(n), s.add(a)];
}
function $g(r, e, t, n) {
return FW(Lt(r, e), Lt(r, e + 8), Lt(r, e + 16), Lt(r, e + 24), t, n);
}
function OW(r, e = r.length) {
if (e >= 8) {
let t = en.add(e * 2), n = Lt(r, 0).add(en), o = Lt(r, e - 8), s = Ar(o, 37).mul(t).add(n), a = Ar(n, 25).add(o).mul(t);
return Cl(s, a, t);
}
if (e >= 4) {
let t = en.add(e * 2), n = bN(r, 0);
return Cl(n.shl(3).add(e), bN(r, e - 4), t);
}
if (e > 0) {
let t = r[0], n = r[e >> 1], o = r[e - 1], s = t + (n << 8), a = e + (o << 2);
return r_(en.mul(s).xor(xN.mul(a))).mul(en);
}
return en;
}
function PW(r, e = r.length) {
let t = en.add(e * 2), n = Lt(r, 0).mul(fu), o = Lt(r, 8), s = Lt(r, e - 8).mul(t), a = Lt(r, e - 16).mul(en);
return Cl(Ar(n.add(o), 43).add(Ar(s, 30)).add(a), n.add(Ar(o.add(en), 18)).add(s), t);
}
function MW(r, e = r.length) {
let t = en.add(e * 2), n = Lt(r, 0).mul(en), o = Lt(r, 8), s = Lt(r, e - 8).mul(t), a = Lt(r, e - 16).mul(en), i = Ar(n.add(o), 43).add(Ar(s, 30)).add(a), l = Cl(i, n.add(Ar(o.add(en), 18)).add(s), t), u = Lt(r, 16).mul(t), c = Lt(r, 24), p = i.add(Lt(r, e - 32)).mul(t), m = l.add(Lt(r, e - 24)).mul(t);
return Cl(Ar(u.add(c), 43).add(Ar(p, 30)).add(m), u.add(Ar(c.add(n), 18)).add(p), t);
}
function LW(r, e = r.length) {
let t = mu.fromNumber(81, true);
if (e <= 32)
return e <= 16 ? OW(r, e) : PW(r, e);
if (e <= 64)
return MW(r, e);
let n = t, o = t.mul(fu).add(113), s = r_(o.mul(en).add(113)).mul(en), a = [mu.UZERO, mu.UZERO], i = [mu.UZERO, mu.UZERO];
n = n.mul(en).add(Lt(r, 0));
let l = 0, u = (e - 1 >> 6) * 64, c = u + (e - 1 & 63) - 63;
do
n = Ar(n.add(o).add(a[0]).add(Lt(r, l + 8)), 37).mul(fu), o = Ar(o.add(a[1]).add(Lt(r, l + 48)), 42).mul(fu), n = n.xor(i[1]), o = o.add(a[0]).add(Lt(r, l + 40)), s = Ar(s.add(i[0]), 33).mul(fu), a = $g(r, l, a[1].mul(fu), n.add(i[0])), i = $g(r, l + 32, s.add(i[1]), o.add(Lt(r, l + 16))), [s, n] = [n, s], l += 64;
while (l !== u);
let p = fu.add(s.and(255).shl(1));
return l = c, i[0] = i[0].add(e - 1 & 63), a[0] = a[0].add(i[0]), i[0] = i[0].add(a[0]), n = Ar(n.add(o).add(a[0]).add(Lt(r, l + 8)), 37).mul(p), o = Ar(o.add(a[1]).add(Lt(r, l + 48)), 42).mul(p), n = n.xor(i[1].mul(9)), o = o.add(a[0].mul(9).add(Lt(r, l + 40))), s = Ar(s.add(i[0]), 33).mul(p), a = $g(r, l, a[1].mul(p), n.add(i[0])), i = $g(r, l + 32, s.add(i[1]), o.add(Lt(r, l + 16))), [s, n] = [n, s], Cl(Cl(a[0], i[0], p).add(r_(o).mul(xN)).add(s), Cl(a[1], i[1], p).add(n), p);
}
function zW(r, e) {
return e === "string" ? Il(r) : Np([r], e);
}
function BW(r, e) {
return r instanceof Float32Array && e === "float32" || r instanceof Int32Array && e === "int32" || r instanceof Uint8Array && e === "bool";
}
function Np(r, e) {
if (e === "string")
throw new Error("Cannot convert a string[] to a TypedArray");
if (Array.isArray(r) && (r = Ao(r)), U().getBool("DEBUG") && Hw(r, e), BW(r, e))
return r;
if (e == null || e === "float32" || e === "complex64")
return new Float32Array(r);
if (e === "int32")
return new Int32Array(r);
if (e === "bool") {
let t = new Uint8Array(r.length);
for (let n = 0; n < t.length; ++n)
Math.round(r[n]) !== 0 && (t[n] = 1);
return t;
} else
throw new Error(`Unknown data type ${e}`);
}
function du() {
return U().platform.now();
}
function VW(r, e) {
return U().platform.fetch(r, e);
}
function Il(r, e = "utf-8") {
return e = e || "utf-8", U().platform.encode(r, e);
}
function Tp(r, e = "utf-8") {
return e = e || "utf-8", U().platform.decode(r, e);
}
var n_ = class {
constructor(e, t) {
this.backendTimer = e, this.logger = t, t == null && (this.logger = new wN());
}
profileKernel(e, t, n) {
let o, s = () => {
o = n();
}, a, i = du();
if (this.backendTimer.timerAvailable())
a = this.backendTimer.time(s);
else {
s();
for (let u of o)
u.dataSync();
a = Promise.resolve({ kernelMs: du() - i });
}
if (U().getBool("CHECK_COMPUTATION_FOR_ERRORS"))
for (let u = 0; u < o.length; u++) {
let c = o[u];
c.data().then((p) => {
GW(p, c.dtype, e);
});
}
return { kernelName: e, outputs: o, inputs: t, timeMs: a.then((u) => u.kernelMs), extraInfo: a.then((u) => u.getExtraProfileInfo != null ? u.getExtraProfileInfo() : "") };
}
logKernelProfile(e) {
let { kernelName: t, outputs: n, timeMs: o, inputs: s, extraInfo: a } = e;
n.forEach((i) => {
Promise.all([i.data(), o, a]).then((l) => {
this.logger.logKernelProfile(t, i, l[0], l[1], s, l[2]);
});
});
}
};
function GW(r, e, t) {
if (e !== "float32")
return false;
for (let n = 0; n < r.length; n++) {
let o = r[n];
if (isNaN(o) || !isFinite(o))
return console.warn(`Found ${o} in the result of '${t}'`), true;
}
return false;
}
var wN = class {
logKernelProfile(e, t, n, o, s, a) {
let i = typeof o == "number" ? su(`${o}ms`, 9) : o.error, l = su(e, 25), u = t.rank, c = t.size, p = su(t.shape.toString(), 14), m = "";
for (let f in s) {
let d = s[f];
if (d != null) {
let h = d.shape || t.shape, g = h.length;
m += `${f}: ${g}D ${g > 0 ? h : ""} `;
}
}
console.log(`%c${l} %c${i} %c${u}D ${p} %c${c} %c${m} %c${a}`, "font-weight:bold", "color:red", "color:blue", "color: orange", "color: green", "color: steelblue");
}
};
function _N(r, e, t) {
let n = {}, o = {};
for (let l = 0; l < e.length; l++)
n[e[l].id] = true;
for (let l = 0; l < r.length; l++) {
let u = r[l], c = u.inputs;
for (let p in c) {
let m = c[p], f = false;
for (let d = 0; d < e.length; d++)
if (n[m.id]) {
u.outputs.forEach((h) => n[h.id] = true), f = true, o[u.id] = true;
break;
}
if (f)
break;
}
}
let s = {};
s[t.id] = true;
let a = {};
for (let l = r.length - 1; l >= 0; l--) {
let u = r[l], c = u.inputs;
for (let p = 0; p < u.outputs.length; p++)
if (s[u.outputs[p].id]) {
for (let m in c)
s[c[m].id] = true, a[u.id] = true;
break;
}
}
let i = [];
for (let l = 0; l < r.length; l++) {
let u = r[l];
if (o[u.id] && a[u.id]) {
let c = {};
for (let m in u.inputs) {
let f = u.inputs[m];
n[f.id] && (c[m] = f);
}
let p = Object.assign({}, u);
p.inputs = c, p.outputs = u.outputs, i.push(p);
}
}
return i;
}
function kN(r, e, t, n) {
for (let o = e.length - 1; o >= 0; o--) {
let s = e[o], a = [];
if (s.outputs.forEach((l) => {
let u = r[l.id];
u != null ? a.push(u) : a.push(null);
}), s.gradient == null)
throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);
let i = s.gradient(a);
for (let l in s.inputs) {
if (!(l in i))
throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`);
let u = t(() => i[l]());
if (u.dtype !== "float32")
throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);
let c = s.inputs[l];
if (!Qr(u.shape, c.shape))
throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${c.shape}'`);
if (r[c.id] == null)
r[c.id] = u;
else {
let p = r[c.id];
r[c.id] = n(p, u), p.dispose();
}
}
}
}
var vN = 20;
var lf = 3;
var o_ = 7;
function CN(r, e, t, n) {
let o = ei(e), s = WW(r, e, t, o), a = e.length, i = Rg(r, e, t, o, s), l = ["Tensor"];
return n && (l.push(` dtype: ${t}`), l.push(` rank: ${a}`), l.push(` shape: [${e}]`), l.push(" values:")), l.push(i.map((u) => " " + u).join(`
`)), l.join(`
`);
}
function WW(r, e, t, n) {
let o = st(e), s = n[n.length - 1], a = new Array(s).fill(0), i = e.length, l = t === "complex64" ? cf(r) : r;
if (i > 1)
for (let u = 0; u < o / s; u++) {
let c = u * s;
for (let p = 0; p < s; p++)
a[p] = Math.max(a[p], uf(l[c + p], 0, t).length);
}
return a;
}
function uf(r, e, t) {
let n;
return Array.isArray(r) ? n = `${parseFloat(r[0].toFixed(o_))} + ${parseFloat(r[1].toFixed(o_))}j` : Do(r) ? n = `'${r}'` : t === "bool" ? n = IN(r) : n = parseFloat(r.toFixed(o_)).toString(), su(n, e);
}
function IN(r) {
return r === 0 ? "false" : "true";
}
function Rg(r, e, t, n, o, s = true) {
let a = t === "complex64" ? 2 : 1, i = e[0], l = e.length;
if (l === 0) {
if (t === "complex64") {
let h = cf(r);
return [uf(h[0], 0, t)];
}
return t === "bool" ? [IN(r[0])] : [r[0].toString()];
}
if (l === 1) {
if (i > vN) {
let g = lf * a, x = Array.from(r.slice(0, g)), y = Array.from(r.slice((i - lf) * a, i * a));
return t === "complex64" && (x = cf(x), y = cf(y)), ["[" + x.map((w, _) => uf(w, o[_], t)).join(", ") + ", ..., " + y.map((w, _) => uf(w, o[i - lf + _], t)).join(", ") + "]"];
}
let h = t === "complex64" ? cf(r) : Array.from(r);
return ["[" + h.map((g, x) => uf(g, o[x], t)).join(", ") + "]"];
}
let u = e.slice(1), c = n.slice(1), p = n[0] * a, m = [];
if (i > vN) {
for (let h = 0; h < lf; h++) {
let g = h * p, x = g + p;
m.push(...Rg(r.slice(g, x), u, t, c, o, false));
}
m.push("...");
for (let h = i - lf; h < i; h++) {
let g = h * p, x = g + p;
m.push(...Rg(r.slice(g, x), u, t, c, o, h === i - 1));
}
} else
for (let h = 0; h < i; h++) {
let g = h * p, x = g + p;
m.push(...Rg(r.slice(g, x), u, t, c, o, h === i - 1));
}
let f = l === 2 ? "," : "";
m[0] = "[" + m[0] + f;
for (let h = 1; h < m.length - 1; h++)
m[h] = " " + m[h] + f;
let d = `,
`;
for (let h = 2; h < l; h++)
d += `
`;
return m[m.length - 1] = " " + m[m.length - 1] + "]" + (s ? "" : d), m;
}
function cf(r) {
let e = [];
for (let t = 0; t < r.length; t += 2)
e.push([r[t], r[t + 1]]);
return e;
}
var mt = class {
constructor(e, t, n) {
if (this.dtype = t, this.shape = e.slice(), this.size = st(e), n != null) {
let o = n.length;
E(o === this.size, () => `Length of values '${o}' does not match the size inferred by the shape '${this.size}'.`);
}
if (t === "complex64")
throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");
this.values = n || jw(t, this.size), this.strides = ei(e);
}
set(e, ...t) {
t.length === 0 && (t = [0]), E(t.length === this.rank, () => `The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);
let n = this.locToIndex(t);
this.values[n] = e;
}
get(...e) {
e.length === 0 && (e = [0]);
let t = 0;
for (let o of e) {
if (o < 0 || o >= this.shape[t]) {
let s = `Requested out of range element at ${e}. Buffer shape=${this.shape}`;
throw new Error(s);
}
t++;
}
let n = e[e.length - 1];
for (let o = 0; o < e.length - 1; ++o)
n += this.strides[o] * e[o];
return this.values[n];
}
locToIndex(e) {
if (this.rank === 0)
return 0;
if (this.rank === 1)
return e[0];
let t = e[e.length - 1];
for (let n = 0; n < e.length - 1; ++n)
t += this.strides[n] * e[n];
return t;
}
indexToLoc(e) {
if (this.rank === 0)
return [];
if (this.rank === 1)
return [e];
let t = new Array(this.shape.length);
for (let n = 0; n < t.length - 1; ++n)
t[n] = Math.floor(e / this.strides[n]), e -= t[n] * this.strides[n];
return t[t.length - 1] = e, t;
}
get rank() {
return this.shape.length;
}
toTensor() {
return bi().makeTensor(this.values, this.shape, this.dtype);
}
};
var bi = null;
var Ep = null;
var UW = null;
function SN(r) {
bi = r;
}
function NN(r) {
Ep = r;
}
function TN(r) {
UW = r;
}
var Le = class {
constructor(e, t, n, o) {
this.kept = false, this.isDisposedInternal = false, this.shape = e.slice(), this.dtype = t || "float32", this.size = st(e), this.strides = ei(e), this.dataId = n, this.id = o, this.rankType = this.rank < 5 ? this.rank.toString() : "higher";
}
get rank() {
return this.shape.length;
}
async buffer() {
let e = await this.data();
return Ep.buffer(this.shape, this.dtype, e);
}
bufferSync() {
return Ep.buffer(this.shape, this.dtype, this.dataSync());
}
async array() {
let e = await this.data();
return iu(this.shape, e, this.dtype === "complex64");
}
arraySync() {
return iu(this.shape, this.dataSync(), this.dtype === "complex64");
}
async data() {
this.throwIfDisposed();
let e = bi().read(this.dataId);
if (this.dtype === "string") {
let t = await e;
try {
return t.map((n) => Tp(n));
} catch (n) {
throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
}
}
return e;
}
dataSync() {
this.throwIfDisposed();
let e = bi().readSync(this.dataId);
if (this.dtype === "string")
try {
return e.map((t) => Tp(t));
} catch (t) {
throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
}
return e;
}
async bytes() {
this.throwIfDisposed();
let e = await bi().read(this.dataId);
return this.dtype === "string" ? e : new Uint8Array(e.buffer);
}
dispose() {
this.isDisposed || (bi().disposeTensor(this), this.isDisposedInternal = true);
}
get isDisposed() {
return this.isDisposedInternal;
}
throwIfDisposed() {
if (this.isDisposed)
throw new Error("Tensor is disposed.");
}
print(e = false) {
return Ep.print(this, e);
}
clone() {
return this.throwIfDisposed(), Ep.clone(this);
}
toString(e = false) {
let t = this.dataSync();
return CN(t, this.shape, this.dtype, e);
}
cast(e) {
return this.throwIfDisposed(), Ep.cast(this, e);
}
variable(e = true, t, n) {
return this.throwIfDisposed(), bi().makeVariable(this, e, t, n);
}
};
Object.defineProperty(Le, Symbol.hasInstance, { value: (r) => !!r && r.data != null && r.dataSync != null && r.throwIfDisposed != null });
function M() {
return ef("Tensor", () => Le);
}
M();
var Sl = class extends Le {
constructor(e, t, n, o) {
super(e.shape, e.dtype, e.dataId, o);
this.trainable = t, this.name = n;
}
assign(e) {
if (e.dtype !== this.dtype)
throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);
if (!Qr(e.shape, this.shape))
throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);
bi().disposeTensor(this), this.dataId = e.dataId, bi().incRef(this, null);
}
dispose() {
bi().disposeVariable(this), this.isDisposedInternal = true;
}
};
Object.defineProperty(Sl, Symbol.hasInstance, { value: (r) => r instanceof Le && r.assign != null && r.assign instanceof Function });
var ao = {};
qe(ao, { assertTypesMatch: () => c_, getTensorsInContainer: () => pf, isTensorInList: () => HW, makeTypesMatch: () => je });
var s_;
(function(r) {
r.R0 = "R0", r.R1 = "R1", r.R2 = "R2", r.R3 = "R3", r.R4 = "R4", r.R5 = "R5", r.R6 = "R6";
})(s_ || (s_ = {}));
var i_;
(function(r) {
r.float32 = "float32", r.int32 = "int32", r.bool = "int32", r.complex64 = "complex64";
})(i_ || (i_ = {}));
var a_;
(function(r) {
r.float32 = "float32", r.int32 = "int32", r.bool = "bool", r.complex64 = "complex64";
})(a_ || (a_ = {}));
var l_;
(function(r) {
r.float32 = "float32", r.int32 = "float32", r.bool = "float32", r.complex64 = "complex64";
})(l_ || (l_ = {}));
var u_;
(function(r) {
r.float32 = "complex64", r.int32 = "complex64", r.bool = "complex64", r.complex64 = "complex64";
})(u_ || (u_ = {}));
var jW = { float32: l_, int32: i_, bool: a_, complex64: u_ };
function hr(r, e) {
if (r === "string" || e === "string") {
if (r === "string" && e === "string")
return "string";
throw new Error(`Can not upcast ${r} with ${e}`);
}
return jW[r][e];
}
function hu(r) {
return hr(r, "int32");
}
function je(r, e) {
if (r.dtype === e.dtype)
return [r, e];
let t = hr(r.dtype, e.dtype);
return [r.cast(t), e.cast(t)];
}
function c_(r, e) {
E(r.dtype === e.dtype, () => `The dtypes of the first(${r.dtype}) and second(${e.dtype}) input must match`);
}
function HW(r, e) {
return e.some((t) => t.id === r.id);
}
function pf(r) {
let e = [], t = new Set();
return EN(r, e, t), e;
}
function EN(r, e, t) {
if (r == null)
return;
if (r instanceof Le) {
e.push(r);
return;
}
if (!qW(r))
return;
let n = r;
for (let o in n) {
let s = n[o];
t.has(s) || (t.add(s), EN(s, e, t));
}
}
function qW(r) {
return Array.isArray(r) || typeof r == "object";
}
function p_(r) {
return r.kernelName != null;
}
var m_ = 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((e) => e.name)));
} };
}
dispose() {
for (let e in this.registeredVariables)
this.registeredVariables[e].dispose();
}
};
var gu = class {
constructor(e) {
this.ENV = e, this.registry = {}, this.registryFactory = {}, this.pendingBackendInitId = 0, this.state = new m_();
}
async ready() {
if (this.pendingBackendInit != null)
return this.pendingBackendInit.then(() => {
});
if (this.backendInstance != null)
return;
let e = this.getSortedBackends();
for (let t = 0; t < e.length; t++) {
let n = e[t];
if (await this.initializeBackend(n).success) {
await this.setBackend(n);
return;
}
}
throw new Error("Could not initialize any backends, all backend initializations failed.");
}
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) {
let { name: e, asyncInit: t } = this.initializeBackendsAndReturnBest();
if (t)
throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);
this.setBackend(e);
}
return this.backendInstance;
}
backendNames() {
return Object.keys(this.registryFactory);
}
findBackend(e) {
if (!(e in this.registry))
if (e in this.registryFactory) {
let { asyncInit: t } = this.initializeBackend(e);
if (t)
return null;
} else
return null;
return this.registry[e];
}
findBackendFactory(e) {
return e in this.registryFactory ? this.registryFactory[e].factory : null;
}
registerBackend(e, t, n = 1) {
return e in this.registryFactory ? (Un(`${e} backend was already registered. Reusing existing backend factory.`), false) : (this.registryFactory[e] = { factory: t, priority: n }, true);
}
async setBackend(e) {
if (this.registryFactory[e] == null)
throw new Error(`Backend name '${e}' not found in registry`);
if (this.backendName = e, this.registry[e] == null) {
this.backendInstance = null;
let { success: t, asyncInit: n } = this.initializeBackend(e);
if (!(n ? await t : t))
return false;
}
return this.backendInstance = this.registry[e], this.setupRegisteredKernels(), this.profiler = new n_(this.backendInstance), true;
}
setupRegisteredKernels() {
Ag(this.backendName).forEach((t) => {
t.setupFunc != null && t.setupFunc(this.backendInstance);
});
}
disposeRegisteredKernels(e) {
Ag(e).forEach((n) => {
n.disposeFunc != null && n.disposeFunc(this.registry[e]);
});
}
initializeBackend(e) {
let t = this.registryFactory[e];
if (t == null)
throw new Error(`Cannot initialize backend ${e}, no registration found.`);
try {
let n = t.factory();
if (n && !(n instanceof Js) && typeof n.then == "function") {
let o = ++this.pendingBackendInitId, s = n.then((a) => o < this.pendingBackendInitId ? false : (this.registry[e] = a, this.pendingBackendInit = null, true)).catch((a) => (o < this.pendingBackendInitId || (this.pendingBackendInit = null, Un(`Initialization of backend ${e} failed`), Un(a.stack || a.message)), false));
return this.pendingBackendInit = s, { success: s, asyncInit: true };
} else
return this.registry[e] = n, { success: true, asyncInit: false };
} catch (n) {
return Un(`Initialization of backend ${e} failed`), Un(n.stack || n.message), { success: false, asyncInit: false };
}
}
removeBackend(e) {
if (!(e in this.registryFactory))
throw new Error(`${e} backend not found in registry`);
this.backendName === e && this.pendingBackendInit != null && this.pendingBackendInitId++, e in this.registry && (this.disposeRegisteredKernels(e), this.registry[e].dispose(), delete this.registry[e]), delete this.registryFactory[e], this.backendName === e && (this.pendingBackendInit = null, this.backendName = null, this.backendInstance = null);
}
getSortedBackends() {
if (Object.keys(this.registryFactory).length === 0)
throw new Error("No backend found in registry.");
return Object.keys(this.registryFactory).sort((e, t) => this.registryFactory[t].priority - this.registryFactory[e].priority);
}
initializeBackendsAndReturnBest() {
let e = this.getSortedBackends();
for (let t = 0; t < e.length; t++) {
let n = e[t], { success: o, asyncInit: s } = this.initializeBackend(n);
if (s || o)
return { name: n, asyncInit: s };
}
throw new Error("Could not initialize any backends, all backend initializations failed.");
}
moveData(e, t) {
let n = this.state.tensorInfo.get(t), o = n.backend, s = this.readSync(t), a = o.refCount(t);
o.disposeData(t, true), n.backend = e, e.move(t, s, n.shape, n.dtype, a), this.shouldCheckForMemLeaks() && this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;
}
tidy(e, t) {
let n = null;
if (t == null) {
if (typeof e != "function")
throw new Error("Please provide a function to tidy()");
t = e;
} else {
if (typeof e != "string" && !(e instanceof String))
throw new Error("When calling with two arguments, the first argument to tidy() must be a string");
if (typeof t != "function")
throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");
n = e;
}
let o;
return this.scopedRun(() => this.startScope(n), () => this.endScope(o), () => (o = t(), o instanceof Promise && console.error("Cannot return a Promise inside of tidy."), o));
}
scopedRun(e, t, n) {
e();
try {
let o = n();
return t(), o;
} catch (o) {
throw t(), o;
}
}
nextTensorId() {
return gu.nextTensorId++;
}
nextVariableId() {
return gu.nextVariableId++;
}
clone(e) {
let t = T.runKernel(ro, { x: e }), n = { x: e }, o = (a) => ({ x: () => {
let i = "float32", l = { x: a }, u = { dtype: i };
return T.runKernel(eo, l, u);
} }), s = [];
return this.addTapeNode(this.state.activeScope.name, n, [t], o, s, {}), t;
}
runKernel(e, t, n) {
if (this.backendName == null && this.backend, !(sf(e, this.backendName) != null))
throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);
return this.runKernelFunc({ kernelName: e, inputs: t, attrs: n });
}
shouldCheckForMemLeaks() {
return this.ENV.getBool("IS_TEST");
}
checkKernelForMemLeak(e, t, n) {
let o = this.backend.numDataIds(), s = 0;
n.forEach((l) => {
s += l.dtype === "complex64" ? 3 : 1;
});
let a = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1], i = o - t - s - a;
if (i > 0)
throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`);
}
runKernelFunc(e) {
let t, n = [], o = this.isTapeOn(), s = this.state.numBytes, a = this.state.numTensors;
this.shouldCheckForMemLeaks() && this.state.numDataMovesStack.push(0);
let i;
this.backendName == null && this.backend;
let l, u = p_(e) ? e.kernelName : this.state.activeScope != null ? this.state.activeScope.name : "";
if (p_(e)) {
let { kernelName: d, inputs: h, attrs: g } = e;
this.backendName == null && this.backend;
let x = sf(d, this.backendName);
E(x != null, () => `Cannot find registered kernel '${d}' for backend '${this.backendName}'`), i = () => {
let y = this.backend.numDataIds();
l = x.kernelFunc({ inputs: h, attrs: g, backend: this.backend });
let w = Array.isArray(l) ? l : [l];
this.shouldCheckForMemLeaks() && this.checkKernelForMemLeak(d, y, w);
let _ = w.map((C) => {
if (C.rank != null)
return C;
let { dataId: A, shape: D, dtype: R } = C;
return this.makeTensorFromDataId(A, D, R);
});
if (o) {
let C = this.getTensorsForGradient(d, h, _);
n = this.saveTensorsForBackwardMode(C);
}
return _;
};
} else {
let { forwardFunc: d } = e, h = (g) => {
!o || (n = g.map((x) => this.keep(this.clone(x))));
};
i = () => {
let g = this.backend.numDataIds();
l = this.tidy(() => d(this.backend, h));
let x = Array.isArray(l) ? l : [l];
return this.shouldCheckForMemLeaks() && this.checkKernelForMemLeak(u, g, x), x;
};
}
let { inputs: c, attrs: p } = e, m = p_(e) ? null : e.backwardsFunc, f;
return this.scopedRun(() => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {
!this.ENV.getBool("DEBUG") && !this.state.profiling ? t = i() : (f = this.profiler.profileKernel(u, c, () => i()), this.ENV.getBool("DEBUG") && this.profiler.logKernelProfile(f), t = f.outputs);
}), o && this.addTapeNode(u, c, t, m, n, p), this.state.profiling && this.state.activeProfile.kernels.push({ name: u, bytesAdded: this.state.numBytes - s, totalBytesSnapshot: this.state.numBytes, tensorsAdded: this.state.numTensors - a, totalTensorsSnapshot: this.state.numTensors, inputShapes: Object.keys(c).map((d) => c[d] != null ? c[d].shape : null), outputShapes: t.map((d) => d.shape), kernelTimeMs: f.timeMs, extraInfo: f.extraInfo }), Array.isArray(l) ? t : t[0];
}
saveTensorsForBackwardMode(e) {
return e.map((n) => this.keep(this.clone(n)));
}
getTensorsForGradient(e, t, n) {
let o = Jw(e);
if (o != null) {
let s = o.inputsToSave || [], a = o.outputsToSave || [], i;
o.saveAllInputs ? (E(Array.isArray(t), () => "saveAllInputs is true, expected inputs to be an array."), i = Object.keys(t).map((u) => t[u])) : i = s.map((u) => t[u]);
let l = n.filter((u, c) => a[c]);
return i.concat(l);
}
return [];
}
makeTensor(e, t, n, o) {
if (e == null)
throw new Error("Values passed to engine.makeTensor() are null");
n = n || "float32", o = o || this.backend;
let s = e;
n === "string" && Do(e[0]) && (s = e.map((l) => Il(l)));
let a = o.write(s, t, n), i = new Le(t, n, a, this.nextTensorId());
if (this.trackTensor(i, o), n === "string") {
let l = this.state.tensorInfo.get(a), u = Kw(s);
this.state.numBytes += u - l.bytes, l.bytes = u;
}
return i;
}
makeTensorFromDataId(e, t, n, o) {
n = n || "float32";
let s = new Le(t, n, e, this.nextTensorId());
return this.trackTensor(s, o), s;
}
makeVariable(e, t = true, n, o) {
n = n || this.nextVariableId().toString(), o != null && o !== e.dtype && (e = e.cast(o));
let s = new Sl(e, t, n, this.nextTensorId());
if (this.state.registeredVariables[s.name] != null)
throw new Error(`Variable with name ${s.name} was already registered`);
return this.state.registeredVariables[s.name] = s, this.incRef(s, this.backend), s;
}
trackTensor(e, t) {
this.state.numTensors++, e.dtype === "string" && this.state.numStringTensors++;
let n = 0;
e.dtype !== "complex64" && e.dtype !== "string" && (n = e.size * Tg(e.dtype)), this.state.numBytes += n, this.state.tensorInfo.has(e.dataId) || (this.state.numDataBuffers++, this.state.tensorInfo.set(e.dataId, { backend: t || this.backend, dtype: e.dtype, shape: e.shape, bytes: n })), e instanceof Sl || this.track(e);
}
incRef(e, t) {
this.trackTensor(e, t), this.backend.incRef(e.dataId);
}
removeDataId(e, t) {
this.state.tensorInfo.has(e) && this.state.tensorInfo.get(e).backend === t && (this.state.tensorInfo.delete(e), this.state.numDataBuffers--);
}
disposeTensor(e) {
if (!this.state.tensorInfo.has(e.dataId))
return;
let t = this.state.tensorInfo.get(e.dataId);
if (this.state.numTensors--, e.dtype === "string" && (this.state.numStringTensors--, this.state.numBytes -= t.bytes), e.dtype !== "complex64" && e.dtype !== "string") {
let n = e.size * Tg(e.dtype);
this.state.numBytes -= n;
}
t.backend.disposeData(e.dataId) && this.removeDataId(e.dataId, t.backend);
}
disposeVariables() {
for (let e in this.state.registeredVariables) {
let t = this.state.registeredVariables[e];
this.disposeVariable(t);
}
}
disposeVariable(e) {
this.disposeTensor(e), this.state.registeredVariables[e.name] != null && delete this.state.registeredVariables[e.name];
}
memory() {
let e = this.backend.memory();
return e.numTensors = this.state.numTensors, e.numDataBuffers = this.state.numDataBuffers, e.numBytes = this.state.numBytes, this.state.numStringTensors > 0 && (e.unreliable = true, e.reasons == null && (e.reasons = []), e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")), e;
}
async profile(e) {
this.state.profiling = true;
let t = this.state.numBytes, n = this.state.numTensors;
this.state.activeProfile.kernels = [], this.state.activeProfile.result = await e(), this.state.profiling = false, this.state.activeProfile.peakBytes = Math.max(...this.state.activeProfile.kernels.map((o) => o.totalBytesSnapshot)), this.state.activeProfile.newBytes = this.state.numBytes - t, this.state.activeProfile.newTensors = this.state.numTensors - n;
for (let o of this.state.activeProfile.kernels)
o.kernelTimeMs = await o.kernelTimeMs, o.extraInfo = await o.extraInfo;
return this.state.activeProfile;
}
isTapeOn() {
return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;
}
addTapeNode(e, t, n, o, s, a) {
let i = { id: this.state.nextTapeNodeId++, kernelName: e, inputs: t, outputs: n, saved: s }, l = Jw(e);
l != null && (o = l.gradFunc), o != null && (i.gradient = (u) => (u = u.map((c, p) => {
if (c == null) {
let m = n[p], f = Gc(m.size, m.dtype);
return this.makeTensor(f, m.shape, m.dtype);
}
return c;
}), o(u.length > 1 ? u : u[0], s, a))), this.state.activeTape.push(i);
}
keep(e) {
return e.kept = true, e;
}
startTape() {
this.state.gradientDepth === 0 && (this.state.activeTape = []), this.state.gradientDepth++;
}
endTape() {
this.state.gradientDepth--;
}
startScope(e) {
let t = { track: [], name: "unnamed scope", id: this.state.nextScopeId++ };
e && (t.name = e), this.state.scopeStack.push(t), this.state.activeScope = t;
}
endScope(e) {
let t = pf(e), n = new Set(t.map((s) => s.id));
for (let s = 0; s < this.state.activeScope.track.length; s++) {
let a = this.state.activeScope.track[s];
!a.kept && !n.has(a.id) && a.dispose();
}
let o = this.state.scopeStack.pop();
this.state.activeScope = this.state.scopeStack.length === 0 ? null : this.state.scopeStack[this.state.scopeStack.length - 1], t.forEach((s) => {
!s.kept && s.scopeId === o.id && this.track(s);
});
}
gradients(e, t, n, o = false) {
if (E(t.length > 0, () => "gradients() received an empty list of xs."), n != null && n.dtype !== "float32")
throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);
let s = this.scopedRun(() => this.startTape(), () => this.endTape(), () => this.tidy("forward", e));
E(s instanceof Le, () => "The result y returned by f() must be a tensor.");
let a = _N(this.state.activeTape, t, s);
if (!o && a.length === 0 && t.length > 0)
throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");
return this.tidy("backward", () => {
let i = {};
i[s.id] = n == null ? KW(s.shape) : n, kN(i, a, (u) => this.tidy(u), XW);
let l = t.map((u) => i[u.id]);
return this.state.gradientDepth === 0 && (this.state.activeTape.forEach((u) => {
for (let c of u.saved)
c.dispose();
}), this.state.activeTape = null), { value: s, grads: l };
});
}
customGrad(e) {
return E(Qs(e), () => "The f passed in customGrad(f) must be a function."), (...t) => {
E(t.every((i) => i instanceof Le), () => "The args passed in customGrad(f)(x1, x2,...) must all be tensors");
let n, o = {};
t.forEach((i, l) => {
o[l] = i;
});
let s = (i, l) => (n = e(...t, l), E(n.value instanceof Le, () => "The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"), E(Qs(n.gradFunc), () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."), n.value), a = (i, l) => {
let u = n.gradFunc(i, l), c = Array.isArray(u) ? u : [u];
E(c.length === t.length, () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."), E(c.every((m) => m instanceof Le), () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");
let p = {};
return c.forEach((m, f) => {
p[f] = () => m;
}), p;
};
return this.runKernelFunc({ forwardFunc: s, backwardsFunc: a, inputs: o });
};
}
readSync(e) {
return this.state.tensorInfo.get(e).backend.readSync(e);
}
read(e) {
return this.state.tensorInfo.get(e).backend.read(e);
}
async time(e) {
let t = du(), n = await this.backend.time(e);
return n.wallMs = du() - t, n;
}
track(e) {
return this.state.activeScope != null && (e.scopeId = this.state.activeScope.id, this.state.activeScope.track.push(e)), e;
}
get registeredVariables() {
return this.state.registeredVariables;
}
reset() {
this.pendingBackendInitId++, this.state.dispose(), this.ENV.reset(), this.state = new m_();
for (let e in this.registry)
this.disposeRegisteredKernels(e), this.registry[e].dispose(), delete this.registry[e];
this.backendName = null, this.backendInstance = null, this.pendingBackendInit = null;
}
};
gu.nextTensorId = 0;
gu.nextVariableId = 0;
function KW(r) {
let e = Zm(st(r), "float32");
return T.makeTensor(e, r, "float32");
}
function f_() {
let r = Zw();
if (r._tfengine == null) {
let e = new Eg(r);
r._tfengine = new gu(e);
}
return tN(r._tfengine.ENV), SN(() => r._tfengine), r._tfengine;
}
var T = f_();
function XW(r, e) {
let t = { a: r, b: e };
return T.runKernel(jn, t);
}
var xu = {};
qe(xu, { isBrowser: () => h_, isMobile: () => JW, mockIsMobile: () => ZW });
function YW() {
return typeof navigator != "undefined" && navigator != null;
}
var d_;
function ZW(r) {
d_ = r;
}
function JW(r) {
if (d_ !== void 0)
return d_;
if (r || YW()) {
if (r || (r = navigator), r.product === "ReactNative")
return true;
let e = r.userAgent || r.vendor || (typeof window != "undefined" ? window.opera : "");
if (!e) {
let t = r;
return t.userAgentData && t.userAgentData.mobile;
}
return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0, 4));
}
return false;
}
function h_() {
return typeof window != "undefined" && window.document != null || typeof WorkerGlobalScope != "undefined";
}
var Ns = U();
Ns.registerFlag("DEBUG", () => false, (r) => {
r && console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.");
});
Ns.registerFlag("IS_BROWSER", () => h_());
Ns.registerFlag("IS_NODE", () => typeof process != "undefined" && typeof process.versions != "undefined" && typeof process.versions.node != "undefined");
Ns.registerFlag("IS_CHROME", () => typeof navigator != "undefined" && navigator != null && navigator.userAgent != null && /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor));
Ns.registerFlag("PROD", () => false);
Ns.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", () => Ns.getBool("DEBUG"));
Ns.registerFlag("DEPRECATION_WARNINGS_ENABLED", () => true);
Ns.registerFlag("IS_TEST", () => false);
Ns.registerFlag("CHECK_COMPUTATION_FOR_ERRORS", () => true);
Ns.registerFlag("WRAP_TO_IMAGEBITMAP", () => false);
function Mr(r, e) {
let t = r;
if (dr(r))
return e === "string" ? [] : [r.length];
if (!Array.isArray(r))
return [];
let n = [];
for (; Array.isArray(t) || dr(t) && e !== "string"; )
n.push(t.length), t = t[0];
return Array.isArray(r) && U().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY") && AN(r, n, []), n;
}
function AN(r, e, t) {
if (t = t || [], !Array.isArray(r) && !dr(r)) {
E(e.length === 0, () => `Element arr[${t.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`);
return;
}
E(e.length > 0, () => `Element arr[${t.join("][")}] should be a primitive, but is an array of ${r.length} elements`), E(r.length === e[0], () => `Element arr[${t.join("][")}] should have ${e[0]} elements, but has ${r.length} elements`);
let n = e.slice(1);
for (let o = 0; o < r.length; ++o)
AN(r[o], n, t.concat(o));
}
function DN(r, e, t, n) {
if (r !== "string_or_numeric") {
if (r == null)
throw new Error("Expected dtype cannot be null.");
if (r !== "numeric" && r !== e || r === "numeric" && e === "string")
throw new Error(`Argument '${t}' passed to '${n}' must be ${r} tensor, but got ${e} tensor`);
}
}
function k(r, e, t, n = "numeric") {
if (r instanceof Le)
return DN(n, r.dtype, e, t), r;
let o = Bc(r);
if (o !== "string" && ["bool", "int32", "float32"].indexOf(n) >= 0 && (o = n), DN(n, o, e, t), r == null || !dr(r) && !Array.isArray(r) && typeof r != "number" && typeof r != "boolean" && typeof r != "string") {
let l = r == null ? "null" : r.constructor.name;
throw new Error(`Argument '${e}' passed to '${t}' must be a Tensor or TensorLike, but got '${l}'`);
}
let s = Mr(r, o);
!dr(r) && !Array.isArray(r) && (r = [r]);
let i = o !== "string" ? Np(r, o) : Ao(r, [], true);
return T.makeTensor(i, s, o);
}
function va(r, e, t, n = "numeric") {
if (!Array.isArray(r))
throw new Error(`Argument ${e} passed to ${t} must be a \`Tensor[]\` or \`TensorLike[]\``);
return r.map((s, a) => k(s, `${e}[${a}]`, t, n));
}
var $N = "__op";
function N(r) {
let e = Object.keys(r);
if (e.length !== 1)
throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${e.length} keys.`);
let t = e[0], n = r[t];
t.endsWith("_") && (t = t.substring(0, t.length - 1)), t = t + $N;
let o = (...s) => {
T.startScope(t);
try {
let a = n(...s);
return Qm(a) && console.error("Cannot return a Promise inside of tidy."), T.endScope(a), a;
} catch (a) {
throw T.endScope(null), a;
}
};
return Object.defineProperty(o, "name", { value: t, configurable: true }), o;
}
function QW(r, e) {
let t = k(r, "real", "complex"), n = k(e, "imag", "complex");
Rt(t.shape, n.shape, `real and imag shapes, ${t.shape} and ${n.shape}, must match in call to tf.complex().`);
let o = { real: t, imag: n };
return T.runKernel(qc, o);
}
var Pn = N({ complex_: QW });
function tn(r, e, t, n) {
if (n == null && (n = Bc(r)), n === "complex64")
throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");
if (!dr(r) && !Array.isArray(r) && typeof r != "number" && typeof r != "boolean" && typeof r != "string")
throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");
if (e != null) {
Jm(e);
let o = st(e), s = st(t);
E(o === s, () => `Based on the provided shape, [${e}], the tensor should have ${o} values but has ${s}`);
for (let a = 0; a < t.length; ++a) {
let i = t[a], l = a === t.length - 1 ? i !== st(e.slice(a)) : true;
E(t[a] === e[a] || !l, () => `Error creating a new Tensor. Inferred shape (${t}) does not match the provided shape (${e}). `);
}
}
return !dr(r) && !Array.isArray(r) && (r = [r]), e = e || t, r = n !== "string" ? Np(r, n) : Ao(r, [], true), T.makeTensor(r, e, n);
}
function Dr(r, e, t) {
let n = Mr(r, t);
return tn(r, e, n, t);
}
var mf = { float32: 4, float16: 2, int32: 4, uint16: 2, uint8: 1, bool: 1, complex64: 8 };
var Fg = 4;
async function RN(r, e) {
let t = [], n = [], o = Array.isArray(r) ? r.map((a) => a.name) : Object.keys(r);
for (let a = 0; a < o.length; ++a) {
let i = o[a], l = Array.isArray(r) ? r[a].tensor : r[i];
if (l.dtype !== "float32" && l.dtype !== "int32" && l.dtype !== "bool" && l.dtype !== "string" && l.dtype !== "complex64")
throw new Error(`Unsupported dtype in weight '${i}': ${l.dtype}`);
let u = { name: i, shape: l.shape, dtype: l.dtype };
if (l.dtype === "string") {
let c = new Promise(async (p) => {
let m = await l.bytes(), f = m.reduce((g, x) => g + x.length, 0) + Fg * m.length, d = new Uint8Array(f), h = 0;
for (let g = 0; g < m.length; g++) {
let x = m[g], y = new Uint8Array(new Uint32Array([x.length]).buffer);
d.set(y, h), h += Fg, d.set(x, h), h += x.length;
}
p(d);
});
n.push(c);
} else
n.push(l.data());
e != null && (u.group = e), t.push(u);
}
let s = await Promise.all(n);
return { data: e4(s), specs: t };
}
function Og(r, e) {
let t = {}, n, o = 0;
for (let s of e) {
let a = s.name, i = s.dtype, l = s.shape, u = st(l), c;
if ("quantization" in s) {
let p = s.quantization;
if (p.dtype === "uint8" || p.dtype === "uint16") {
if (!("min" in p && "scale" in p))
throw new Error(`Weight ${s.name} with quantization ${p.dtype} doesn't have corresponding metadata min and scale.`);
} else if (p.dtype === "float16") {
if (i !== "float32")
throw new Error(`Weight ${s.name} is quantized with ${p.dtype} which only supports weights of type float32 not ${i}.`);
} else
throw new Error(`Weight ${s.name} has unknown quantization dtype ${p.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);
let m = mf[p.dtype], f = r.slice(o, o + u * m), d = p.dtype === "uint8" ? new Uint8Array(f) : new Uint16Array(f);
if (i === "float32")
if (p.dtype === "uint8" || p.dtype === "uint16") {
c = new Float32Array(d.length);
for (let h = 0; h < d.length; h++) {
let g = d[h];
c[h] = g * p.scale + p.min;
}
} else if (p.dtype === "float16")
n === void 0 && (n = o4()), c = n(d);
else
throw new Error(`Unsupported quantization type ${p.dtype} for weight type float32.`);
else if (i === "int32") {
if (p.dtype !== "uint8" && p.dtype !== "uint16")
throw new Error(`Unsupported quantization type ${p.dtype} for weight type int32.`);
c = new Int32Array(d.length);
for (let h = 0; h < d.length; h++) {
let g = d[h];
c[h] = Math.round(g * p.scale + p.min);
}
} else
throw new Error(`Unsupported dtype in weight '${a}': ${i}`);
o += u * m;
} else if (i === "string") {
let p = st(s.shape);
c = [];
for (let m = 0; m < p; m++) {
let f = new Uint32Array(r.slice(o, o + Fg))[0];
o += Fg;
let d = new Uint8Array(r.slice(o, o + f));
c.push(d), o += f;
}
} else {
let p = mf[i], m = r.slice(o, o + u * p);
if (i === "float32")
c = new Float32Array(m);
else if (i === "int32")
c = new Int32Array(m);
else if (i === "bool")
c = new Uint8Array(m);
else if (i === "complex64") {
c = new Float32Array(m);
let f = new Float32Array(c.length / 2), d = new Float32Array(c.length / 2);
for (let x = 0; x < f.length; x++)
f[x] = c[x * 2], d[x] = c[x * 2 + 1];
let h = Dr(f, l, "float32"), g = Dr(d, l, "float32");
t[a] = Pn(h, g), h.dispose(), g.dispose();
} else
throw new Error(`Unsupported dtype in weight '${a}': ${i}`);
o += u * p;
}
i !== "complex64" && (t[a] = Dr(c, l, i));
}
return t;
}
function e4(r) {
if (r === null)
throw new Error(`Invalid input value: ${JSON.stringify(r)}`);
let e = 0, t = [];
r.forEach((s) => {
if (e += s.byteLength, t.push(s.byteLength === s.buffer.byteLength ? s : new s.constructor(s)), !(s instanceof Float32Array || s instanceof Int32Array || s instanceof Uint8Array))
throw new Error(`Unsupported TypedArray subtype: ${s.constructor.name}`);
});
let n = new Uint8Array(e), o = 0;
return t.forEach((s) => {
n.set(new Uint8Array(s.buffer), o), o += s.byteLength;
}), n.buffer;
}
var g_ = typeof Buffer != "undefined" && (typeof Blob == "undefined" || typeof atob == "undefined" || typeof btoa == "undefined");
function FN(r) {
return g_ ? Buffer.byteLength(r) : new Blob([r]).size;
}
function ON(r) {
if (g_)
return Buffer.from(r).toString("base64");
let e = new Uint8Array(r), t = "";
for (let n = 0, o = e.length; n < o; n++)
t += String.fromCharCode(e[n]);
return btoa(t);
}
function PN(r) {
if (g_) {
let n = Buffer.from(r, "base64");
return n.buffer.slice(n.byteOffset, n.byteOffset + n.byteLength);
}
let e = atob(r), t = new Uint8Array(e.length);
for (let n = 0; n < e.length; ++n)
t.set([e.charCodeAt(n)], n);
return t.buffer;
}
function Ap(r) {
if (r.length === 1)
return r[0];
let e = 0;
r.forEach((o) => {
e += o.byteLength;
});
let t = new Uint8Array(e), n = 0;
return r.forEach((o) => {
t.set(new Uint8Array(o), n), n += o.byteLength;
}), t.buffer;
}
function x_(r) {
let e = "/";
for (r = r.trim(); r.endsWith(e); )
r = r.slice(0, r.length - 1);
let t = r.split(e);
return t[t.length - 1];
}
function Pg(r, e) {
let t = { modelTopology: r.modelTopology, format: r.format, generatedBy: r.generatedBy, convertedBy: r.convertedBy, weightsManifest: e };
return r.signature != null && (t.signature = r.signature), r.userDefinedMetadata != null && (t.userDefinedMetadata = r.userDefinedMetadata), r.modelInitializer != null && (t.modelInitializer = r.modelInitializer), r.trainingConfig != null && (t.trainingConfig = r.trainingConfig), t;
}
async function Dp(r, e) {
let t = { modelTopology: r.modelTopology, format: r.format, generatedBy: r.generatedBy, convertedBy: r.convertedBy };
if (r.trainingConfig != null && (t.trainingConfig = r.trainingConfig), r.weightsManifest != null) {
let [n, o] = await e(r.weightsManifest);
t.weightSpecs = n, t.weightData = o;
}
return r.signature != null && (t.signature = r.signature), r.userDefinedMetadata != null && (t.userDefinedMetadata = r.userDefinedMetadata), r.modelInitializer != null && (t.modelInitializer = r.modelInitializer), t;
}
function wi(r) {
if (r.modelTopology instanceof ArrayBuffer)
throw new Error("Expected JSON model topology, received ArrayBuffer.");
return { dateSaved: new Date(), modelTopologyType: "JSON", modelTopologyBytes: r.modelTopology == null ? 0 : FN(JSON.stringify(r.modelTopology)), weightSpecsBytes: r.weightSpecs == null ? 0 : FN(JSON.stringify(r.weightSpecs)), weightDataBytes: r.weightData == null ? 0 : r.weightData.byteLength };
}
function t4() {
let r = (t) => {
let n = t << 13, o = 0;
for (; (n & 8388608) == 0; )
o -= 8388608, n <<= 1;
return n &= ~8388608, o += 947912704, n | o;
}, e = new Uint32Array(2048);
e[0] = 0;
for (let t = 1; t < 1024; t++)
e[t] = r(t);
for (let t = 1024; t < 2048; t++)
e[t] = 939524096 + (t - 1024 << 13);
return e;
}
function r4() {
let r = new Uint32Array(64);
r[0] = 0, r[31] = 1199570944, r[32] = 2147483648, r[63] = 3347054592;
for (let e = 1; e < 31; e++)
r[e] = e << 23;
for (let e = 33; e < 63; e++)
r[e] = 2147483648 + (e - 32 << 23);
return r;
}
function n4() {
let r = new Uint32Array(64);
for (let e = 0; e < 64; e++)
r[e] = 1024;
return r[0] = r[32] = 0, r;
}
function o4() {
let r = t4(), e = r4(), t = n4();
return (n) => {
let o = new ArrayBuffer(4 * n.length), s = new Uint32Array(o);
for (let a = 0; a < n.length; a++) {
let i = n[a], l = r[t[i >> 10] + (i & 1023)] + e[i >> 10];
s[a] = l;
}
return new Float32Array(o);
};
}
var Et = class {
constructor() {
this.saveRouters = [], this.loadRouters = [];
}
static getInstance() {
return Et.instance == null && (Et.instance = new Et()), Et.instance;
}
static registerSaveRouter(e) {
Et.getInstance().saveRouters.push(e);
}
static registerLoadRouter(e) {
Et.getInstance().loadRouters.push(e);
}
static getSaveHandlers(e) {
return Et.getHandlers(e, "save");
}
static getLoadHandlers(e, t) {
return Et.getHandlers(e, "load", t);
}
static getHandlers(e, t, n) {
let o = [];
return (t === "load" ? Et.getInstance().loadRouters : Et.getInstance().saveRouters).forEach((a) => {
let i = a(e, n);
i !== null && o.push(i);
}), o;
}
};
var MN = (r) => Et.registerSaveRouter(r);
var LN = (r) => Et.registerLoadRouter(r);
var zN = (r) => Et.getSaveHandlers(r);
var BN = (r, e) => Et.getLoadHandlers(r, e);
var y_ = "tensorflowjs";
var b_ = 1;
var yu = "models_store";
var Nl = "model_info_store";
function VN() {
if (!U().getBool("IS_BROWSER"))
throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");
let r = typeof window == "undefined" ? self : window, e = r.indexedDB || r.mozIndexedDB || r.webkitIndexedDB || r.msIndexedDB || r.shimIndexedDB;
if (e == null)
throw new Error("The current browser does not appear to support IndexedDB.");
return e;
}
function w_(r) {
let e = r.result;
e.createObjectStore(yu, { keyPath: "modelPath" }), e.createObjectStore(Nl, { keyPath: "modelPath" });
}
var Ca = class {
constructor(e) {
if (this.indexedDB = VN(), e == null || !e)
throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");
this.modelPath = e;
}
async save(e) {
if (e.modelTopology instanceof ArrayBuffer)
throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");
return this.databaseAction(this.modelPath, e);
}
async load() {
return this.databaseAction(this.modelPath);
}
databaseAction(e, t) {
return new Promise((n, o) => {
let s = this.indexedDB.open(y_, b_);
s.onupgradeneeded = () => w_(s), s.onsuccess = () => {
let a = s.result;
if (t == null) {
let i = a.transaction(yu, "readonly"), u = i.objectStore(yu).get(this.modelPath);
u.onsuccess = () => {
if (u.result == null)
return a.close(), o(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));
n(u.result.modelArtifacts);
}, u.onerror = (c) => (a.close(), o(u.error)), i.oncomplete = () => a.close();
} else {
let i = wi(t), l = a.transaction(Nl, "readwrite"), u = l.objectStore(Nl), c = u.put({ modelPath: this.modelPath, modelArtifactsInfo: i }), p;
c.onsuccess = () => {
p = a.transaction(yu, "readwrite");
let f = p.objectStore(yu).put({ modelPath: this.modelPath, modelArtifacts: t, modelArtifactsInfo: i });
f.onsuccess = () => n({ modelArtifactsInfo: i }), f.onerror = (d) => {
u = l.objectStore(Nl);
let h = u.delete(this.modelPath);
h.onsuccess = () => (a.close(), o(f.error)), h.onerror = (g) => (a.close(), o(f.error));
};
}, c.onerror = (m) => (a.close(), o(c.error)), l.oncomplete = () => {
p == null ? a.close() : p.oncomplete = () => a.close();
};
}
}, s.onerror = (a) => o(s.error);
});
}
};
Ca.URL_SCHEME = "indexeddb://";
var GN = (r) => U().getBool("IS_BROWSER") && !Array.isArray(r) && r.startsWith(Ca.URL_SCHEME) ? s4(r.slice(Ca.URL_SCHEME.length)) : null;
Et.registerSaveRouter(GN);
Et.registerLoadRouter(GN);
function s4(r) {
return new Ca(r);
}
function i4(r) {
return r.startsWith(Ca.URL_SCHEME) ? r.slice(Ca.URL_SCHEME.length) : r;
}
var __ = class {
constructor() {
this.indexedDB = VN();
}
async listModels() {
return new Promise((e, t) => {
let n = this.indexedDB.open(y_, b_);
n.onupgradeneeded = () => w_(n), n.onsuccess = () => {
let o = n.result, s = o.transaction(Nl, "readonly"), i = s.objectStore(Nl).getAll();
i.onsuccess = () => {
let l = {};
for (let u of i.result)
l[u.modelPath] = u.modelArtifactsInfo;
e(l);
}, i.onerror = (l) => (o.close(), t(i.error)), s.oncomplete = () => o.close();
}, n.onerror = (o) => t(n.error);
});
}
async removeModel(e) {
return e = i4(e), new Promise((t, n) => {
let o = this.indexedDB.open(y_, b_);
o.onupgradeneeded = () => w_(o), o.onsuccess = () => {
let s = o.result, a = s.transaction(Nl, "readwrite"), i = a.objectStore(Nl), l = i.get(e), u;
l.onsuccess = () => {
if (l.result == null)
return s.close(), n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));
{
let c = i.delete(e), p = () => {
u = s.transaction(yu, "readwrite");
let f = u.objectStore(yu).delete(e);
f.onsuccess = () => t(l.result.modelArtifactsInfo), f.onerror = (d) => n(l.error);
};
c.onsuccess = p, c.onerror = (m) => (p(), s.close(), n(l.error));
}
}, l.onerror = (c) => (s.close(), n(l.error)), a.oncomplete = () => {
u == null ? s.close() : u.oncomplete = () => s.close();
};
}, o.onerror = (s) => n(o.error);
});
}
};
var Ia = "/";
var $p = "tensorflowjs_models";
var WN = "info";
var a4 = "model_topology";
var l4 = "weight_specs";
var u4 = "weight_data";
var c4 = "model_metadata";
function UN(r) {
return { info: [$p, r, WN].join(Ia), topology: [$p, r, a4].join(Ia), weightSpecs: [$p, r, l4].join(Ia), weightData: [$p, r, u4].join(Ia), modelMetadata: [$p, r, c4].join(Ia) };
}
function jN(r) {
for (let e of Object.values(r))
window.localStorage.removeItem(e);
}
function p4(r) {
let e = r.split(Ia);
if (e.length < 3)
throw new Error(`Invalid key format: ${r}`);
return e.slice(1, e.length - 1).join(Ia);
}
function m4(r) {
return r.startsWith(Sa.URL_SCHEME) ? r.slice(Sa.URL_SCHEME.length) : r;
}
var Sa = class {
constructor(e) {
if (!U().getBool("IS_BROWSER") || typeof window == "undefined" || typeof window.localStorage == "undefined")
throw new Error("The current environment does not support local storage.");
if (this.LS = window.localStorage, e == null || !e)
throw new Error("For local storage, modelPath must not be null, undefined or empty.");
this.modelPath = e, this.keys = UN(this.modelPath);
}
async save(e) {
if (e.modelTopology instanceof ArrayBuffer)
throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");
{
let t = JSON.stringify(e.modelTopology), n = JSON.stringify(e.weightSpecs), o = wi(e);
try {
this.LS.setItem(this.keys.info, JSON.stringify(o)), this.LS.setItem(this.keys.topology, t), this.LS.setItem(this.keys.weightSpecs, n), this.LS.setItem(this.keys.weightData, ON(e.weightData));
let s = { format: e.format, generatedBy: e.generatedBy, convertedBy: e.convertedBy, signature: e.signature != null ? e.signature : void 0, userDefinedMetadata: e.userDefinedMetadata != null ? e.userDefinedMetadata : void 0, modelInitializer: e.modelInitializer != null ? e.modelInitializer : void 0, trainingConfig: e.trainingConfig != null ? e.trainingConfig : void 0 };
return this.LS.setItem(this.keys.modelMetadata, JSON.stringify(s)), { modelArtifactsInfo: o };
} catch (s) {
throw jN(this.keys), new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${o.modelTopologyBytes}, weightSpecsBytes=${o.weightSpecsBytes}, weightDataBytes=${o.weightDataBytes}.`);
}
}
}
async load() {
let e = JSON.parse(this.LS.getItem(this.keys.info));
if (e == null)
throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);
if (e.modelTopologyType !== "JSON")
throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");
let t = {}, n = JSON.parse(this.LS.getItem(this.keys.topology));
if (n == null)
throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);
t.modelTopology = n;
let o = JSON.parse(this.LS.getItem(this.keys.weightSpecs));
if (o == null)
throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);
t.weightSpecs = o;
let s = this.LS.getItem(this.keys.modelMetadata);
if (s != null) {
let i = JSON.parse(s);
t.format = i.format, t.generatedBy = i.generatedBy, t.convertedBy = i.convertedBy, i.signature != null && (t.signature = i.signature), i.userDefinedMetadata != null && (t.userDefinedMetadata = i.userDefinedMetadata), i.modelInitializer != null && (t.modelInitializer = i.modelInitializer), i.trainingConfig != null && (t.trainingConfig = i.trainingConfig);
}
let a = this.LS.getItem(this.keys.weightData);
if (a == null)
throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);
return t.weightData = PN(a), t;
}
};
Sa.URL_SCHEME = "localstorage://";
var HN = (r) => U().getBool("IS_BROWSER") && !Array.isArray(r) && r.startsWith(Sa.URL_SCHEME) ? f4(r.slice(Sa.URL_SCHEME.length)) : null;
Et.registerSaveRouter(HN);
Et.registerLoadRouter(HN);
function f4(r) {
return new Sa(r);
}
var k_ = class {
constructor() {
E(U().getBool("IS_BROWSER"), () => "Current environment is not a web browser"), E(typeof window == "undefined" || typeof window.localStorage != "undefined", () => "Current browser does not appear to support localStorage"), this.LS = window.localStorage;
}
async listModels() {
let e = {}, t = $p + Ia, n = Ia + WN;
for (let o = 0; o < this.LS.length; ++o) {
let s = this.LS.key(o);
if (s.startsWith(t) && s.endsWith(n)) {
let a = p4(s);
e[a] = JSON.parse(this.LS.getItem(s));
}
}
return e;
}
async removeModel(e) {
e = m4(e);
let t = UN(e);
if (this.LS.getItem(t.info) == null)
throw new Error(`Cannot find model at path '${e}'`);
let n = JSON.parse(this.LS.getItem(t.info));
return jN(t), n;
}
};
var Rp = "://";
var rn = class {
constructor() {
this.managers = {};
}
static getInstance() {
return rn.instance == null && (rn.instance = new rn()), rn.instance;
}
static registerManager(e, t) {
E(e != null, () => "scheme must not be undefined or null."), e.endsWith(Rp) && (e = e.slice(0, e.indexOf(Rp))), E(e.length > 0, () => "scheme must not be an empty string.");
let n = rn.getInstance();
E(n.managers[e] == null, () => `A model store manager is already registered for scheme '${e}'.`), n.managers[e] = t;
}
static getManager(e) {
let t = this.getInstance().managers[e];
if (t == null)
throw new Error(`Cannot find model manager for scheme '${e}'`);
return t;
}
static getSchemes() {
return Object.keys(this.getInstance().managers);
}
};
function Mg(r) {
if (r.indexOf(Rp) === -1)
throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${rn.getSchemes().join(",")}`);
return { scheme: r.split(Rp)[0], path: r.split(Rp)[1] };
}
async function qN(r, e, t = false) {
E(r !== e, () => `Old path and new path are the same: '${r}'`);
let n = Et.getLoadHandlers(r);
E(n.length > 0, () => `Copying failed because no load handler is found for source URL ${r}.`), E(n.length < 2, () => `Copying failed because more than one (${n.length}) load handlers for source URL ${r}.`);
let o = n[0], s = Et.getSaveHandlers(e);
E(s.length > 0, () => `Copying failed because no save handler is found for destination URL ${e}.`), E(s.length < 2, () => `Copying failed because more than one (${n.length}) save handlers for destination URL ${e}.`);
let a = s[0], i = Mg(r).scheme, l = Mg(r).path, u = i === Mg(r).scheme, c = await o.load();
t && u && await rn.getManager(i).removeModel(l);
let p = await a.save(c);
return t && !u && await rn.getManager(i).removeModel(l), p.modelArtifactsInfo;
}
async function KN() {
let r = rn.getSchemes(), e = {};
for (let t of r) {
let n = await rn.getManager(t).listModels();
for (let o in n) {
let s = t + Rp + o;
e[s] = n[o];
}
}
return e;
}
async function XN(r) {
let e = Mg(r);
return rn.getManager(e.scheme).removeModel(e.path);
}
async function YN(r, e) {
return qN(r, e, false);
}
async function ZN(r, e) {
return qN(r, e, true);
}
var JN = class {
fetch(e, t) {
return fetch(e, t);
}
now() {
return performance.now();
}
encode(e, t) {
if (t !== "utf-8" && t !== "utf8")
throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);
return this.textEncoder == null && (this.textEncoder = new TextEncoder()), this.textEncoder.encode(e);
}
decode(e, t) {
return new TextDecoder(t).decode(e);
}
};
if (U().get("IS_BROWSER")) {
U().setPlatform("browser", new JN());
try {
rn.registerManager(Sa.URL_SCHEME, new k_());
} catch (r) {
}
try {
rn.registerManager(Ca.URL_SCHEME, new __());
} catch (r) {
}
}
var d4 = { importFetch: () => QN() };
var v_;
var e1 = class {
constructor() {
this.util = Lc("util"), this.textEncoder = new this.util.TextEncoder();
}
fetch(e, t) {
return U().global.fetch != null ? U().global.fetch(e, t) : (v_ == null && (v_ = d4.importFetch()), v_(e, t));
}
now() {
let e = process.hrtime();
return e[0] * 1e3 + e[1] / 1e6;
}
encode(e, t) {
if (t !== "utf-8" && t !== "utf8")
throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);
return this.textEncoder.encode(e);
}
decode(e, t) {
return e.length === 0 ? "" : new this.util.TextDecoder(t).decode(e);
}
};
U().get("IS_NODE") && U().setPlatform("node", new e1());
function Ie(r, e = "float32", t) {
return e = e || "float32", Jm(r), new mt(r, e, t);
}
function h4(r, e) {
let t = k(r, "x", "cast");
if (!qw(e))
throw new Error(`Failed to cast to unknown dtype ${e}`);
if (e === "string" && t.dtype !== "string" || e !== "string" && t.dtype === "string")
throw new Error("Only strings can be casted to strings");
let n = { x: t }, o = { dtype: e };
return T.runKernel(eo, n, o);
}
var Y = N({ cast_: h4 });
function g4(r) {
let t = { x: k(r, "x", "clone", "string_or_numeric") };
return T.runKernel(ro, t);
}
var wn = N({ clone_: g4 });
function C_(r, e = false) {
console.log(r.toString(e));
}
f_();
var x4 = { buffer: Ie, cast: Y, clone: wn, print: C_ };
NN(x4);
var Lr = {};
qe(Lr, { browserFiles: () => n1, browserHTTPRequest: () => i1, concatenateArrayBuffers: () => Ap, copyModel: () => YN, decodeWeights: () => Og, encodeWeights: () => RN, fromMemory: () => l1, getLoadHandlers: () => BN, getModelArtifactsForJSON: () => Dp, getModelArtifactsInfoForJSON: () => wi, getSaveHandlers: () => zN, http: () => Bg, isHTTPScheme: () => zg, listModels: () => KN, loadWeights: () => o1, moveModel: () => ZN, registerLoadRouter: () => LN, registerSaveRouter: () => MN, removeModel: () => XN, weightsLoaderFactory: () => N_, withSaveHandler: () => u1 });
var y4 = "model";
var b4 = ".json";
var w4 = ".weights.bin";
function t1(r) {
return new Promise((e) => setTimeout(e)).then(r);
}
var Tl = class {
constructor(e) {
if (!U().getBool("IS_BROWSER"))
throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");
e.startsWith(Tl.URL_SCHEME) && (e = e.slice(Tl.URL_SCHEME.length)), (e == null || e.length === 0) && (e = y4), this.modelJsonFileName = e + b4, this.weightDataFileName = e + w4;
}
async save(e) {
if (typeof document == "undefined")
throw new Error("Browser downloads are not supported in this environment since `document` is not present");
let t = window.URL.createObjectURL(new Blob([e.weightData], { type: "application/octet-stream" }));
if (e.modelTopology instanceof ArrayBuffer)
throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");
{
let n = [{ paths: ["./" + this.weightDataFileName], weights: e.weightSpecs }], o = Pg(e, n), s = window.URL.createObjectURL(new Blob([JSON.stringify(o)], { type: "application/json" })), a = this.modelJsonAnchor == null ? document.createElement("a") : this.modelJsonAnchor;
if (a.download = this.modelJsonFileName, a.href = s, await t1(() => a.dispatchEvent(new MouseEvent("click"))), e.weightData != null) {
let i = this.weightDataAnchor == null ? document.createElement("a") : this.weightDataAnchor;
i.download = this.weightDataFileName, i.href = t, await t1(() => i.dispatchEvent(new MouseEvent("click")));
}
return { modelArtifactsInfo: wi(e) };
}
}
};
Tl.URL_SCHEME = "downloads://";
var r1 = class {
constructor(e) {
if (e == null || e.length < 1)
throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);
this.jsonFile = e[0], this.weightsFiles = e.slice(1);
}
async load() {
return new Promise((e, t) => {
let n = new FileReader();
n.onload = (o) => {
let s = JSON.parse(o.target.result), a = s.modelTopology;
if (a == null) {
t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));
return;
}
if (s.weightsManifest == null) {
t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));
return;
}
if (this.weightsFiles.length === 0) {
e({ modelTopology: a });
return;
}
let l = Dp(s, (u) => this.loadWeights(u));
e(l);
}, n.onerror = (o) => t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`), n.readAsText(this.jsonFile);
});
}
loadWeights(e) {
let t = [], n = [];
for (let a of e)
t.push(...a.weights), n.push(...a.paths);
let o = this.checkManifestAndWeightFiles(e), s = n.map((a) => this.loadWeightsFile(a, o[a]));
return Promise.all(s).then((a) => [t, Ap(a)]);
}
loadWeightsFile(e, t) {
return new Promise((n, o) => {
let s = new FileReader();
s.onload = (a) => {
let i = a.target.result;
n(i);
}, s.onerror = (a) => o(`Failed to weights data from file of path '${e}'.`), s.readAsArrayBuffer(t);
});
}
checkManifestAndWeightFiles(e) {
let t = [], n = this.weightsFiles.map((s) => x_(s.name)), o = {};
for (let s of e)
s.paths.forEach((a) => {
let i = x_(a);
if (t.indexOf(i) !== -1)
throw new Error(`Duplicate file basename found in weights manifest: '${i}'`);
if (t.push(i), n.indexOf(i) === -1)
throw new Error(`Weight file with basename '${i}' is not provided.`);
o[a] = this.weightsFiles[n.indexOf(i)];
});
if (t.length !== this.weightsFiles.length)
throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);
return o;
}
};
var _4 = (r) => U().getBool("IS_BROWSER") && !Array.isArray(r) && r.startsWith(Tl.URL_SCHEME) ? k4(r.slice(Tl.URL_SCHEME.length)) : null;
Et.registerSaveRouter(_4);
function k4(r = "model") {
return new Tl(r);
}
function n1(r) {
return new r1(r);
}
function I_(r, e, t, n) {
a(r), t = t == null ? 0 : t, n = n == null ? 1 : n, i(t, n);
let o = 0, s = (l) => (l.then((u) => {
let c = t + ++o / r.length * (n - t);
return e(c), u;
}), l);
function a(l) {
E(l != null && Array.isArray(l) && l.length > 0, () => "promises must be a none empty array");
}
function i(l, u) {
E(l >= 0 && l <= 1, () => `Progress fraction must be in range [0, 1], but got startFraction ${l}`), E(u >= 0 && u <= 1, () => `Progress fraction must be in range [0, 1], but got endFraction ${u}`), E(u >= l, () => `startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`);
}
return Promise.all(r.map(s));
}
async function S_(r, e) {
e == null && (e = {});
let t = e.fetchFunc == null ? U().platform.fetch : e.fetchFunc, n = r.map((p) => t(p, e.requestInit, { isBinary: true })), o = 0, s = 0.5, i = (e.onProgress == null ? await Promise.all(n) : await I_(n, e.onProgress, o, s)).map((p) => p.arrayBuffer()), l = 0.5, u = 1;
return e.onProgress == null ? await Promise.all(i) : await I_(i, e.onProgress, l, u);
}
async function o1(r, e = "", t, n) {
return N_((a) => S_(a, { requestInit: n }))(r, e, t);
}
function N_(r) {
return async (e, t = "", n) => {
let o = e.map(() => false), s = {}, a = n != null ? n.map(() => false) : [], i = [];
if (e.forEach((f, d) => {
let h = 0;
f.weights.forEach((g) => {
let x = "quantization" in g ? g.quantization.dtype : g.dtype, y = mf[x] * st(g.shape), w = () => {
o[d] = true, s[d] == null && (s[d] = []), s[d].push({ manifestEntry: g, groupOffset: h, sizeBytes: y });
};
n != null ? n.forEach((_, C) => {
_ === g.name && (w(), a[C] = true);
}) : w(), i.push(g.name), h += y;
});
}), !a.every((f) => f)) {
let f = n.filter((d, h) => !a[h]);
throw new Error(`Could not find weights in manifest with names: ${f.join(", ")}.
Manifest JSON has weights with names: ${i.join(", ")}.`);
}
let l = o.reduce((f, d, h) => (d && f.push(h), f), []), u = [];
l.forEach((f) => {
e[f].paths.forEach((d) => {
let h = t + (t.endsWith("/") ? "" : "/") + d;
u.push(h);
});
});
let c = await r(u), p = {}, m = 0;
return l.forEach((f) => {
let d = e[f].paths.length, h = 0;
for (let _ = 0; _ < d; _++)
h += c[m + _].byteLength;
let g = new ArrayBuffer(h), x = new Uint8Array(g), y = 0;
for (let _ = 0; _ < d; _++) {
let C = new Uint8Array(c[m + _]);
x.set(C, y), y += C.byteLength;
}
s[f].forEach((_) => {
let C = g.slice(_.groupOffset, _.groupOffset + _.sizeBytes), A = Og(C, [_.manifestEntry]);
for (let D in A)
p[D] = A[D];
}), m += d;
}), p;
};
}
var v4 = "application/octet-stream";
var C4 = "application/json";
var Lg = class {
constructor(e, t) {
if (this.DEFAULT_METHOD = "POST", t == null && (t = {}), this.weightPathPrefix = t.weightPathPrefix, this.onProgress = t.onProgress, this.weightUrlConverter = t.weightUrlConverter, t.fetchFunc != null ? (E(typeof t.fetchFunc == "function", () => "Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"), this.fetch = t.fetchFunc) : this.fetch = U().platform.fetch, E(e != null && e.length > 0, () => "URL path for http must not be null, undefined or empty."), Array.isArray(e) && E(e.length === 2, () => `URL paths for http must have a length of 2, (actual length is ${e.length}).`), this.path = e, t.requestInit != null && t.requestInit.body != null)
throw new Error("requestInit is expected to have no pre-existing body, but has one.");
this.requestInit = t.requestInit || {};
}
async save(e) {
if (e.modelTopology instanceof ArrayBuffer)
throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");
let t = Object.assign({ method: this.DEFAULT_METHOD }, this.requestInit);
t.body = new FormData();
let n = [{ paths: ["./model.weights.bin"], weights: e.weightSpecs }], o = Pg(e, n);
t.body.append("model.json", new Blob([JSON.stringify(o)], { type: C4 }), "model.json"), e.weightData != null && t.body.append("model.weights.bin", new Blob([e.weightData], { type: v4 }), "model.weights.bin");
let s = await this.fetch(this.path, t);
if (s.ok)
return { modelArtifactsInfo: wi(e), responses: [s] };
throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.status}.`);
}
async load() {
let e = await this.fetch(this.path, this.requestInit);
if (!e.ok)
throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);
let t;
try {
t = await e.json();
} catch (s) {
let a = `Failed to parse model JSON of response from ${this.path}.`;
throw this.path.endsWith(".pb") ? a += " Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository." : a += " Please make sure the server is serving valid JSON for this request.", new Error(a);
}
let n = t.modelTopology, o = t.weightsManifest;
if (n == null && o == null)
throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);
return Dp(t, (s) => this.loadWeights(s));
}
async loadWeights(e) {
let t = Array.isArray(this.path) ? this.path[1] : this.path, [n, o] = I4(t), s = this.weightPathPrefix || n, a = [];
for (let c of e)
a.push(...c.weights);
let i = [], l = [];
for (let c of e)
for (let p of c.paths)
this.weightUrlConverter != null ? l.push(this.weightUrlConverter(p)) : i.push(s + p + o);
this.weightUrlConverter && i.push(...await Promise.all(l));
let u = await S_(i, { requestInit: this.requestInit, fetchFunc: this.fetch, onProgress: this.onProgress });
return [a, Ap(u)];
}
};
Lg.URL_SCHEME_REGEX = /^https?:\/\//;
function I4(r) {
let e = r.lastIndexOf("/"), t = r.lastIndexOf("?"), n = r.substring(0, e), o = t > e ? r.substring(t) : "";
return [n + "/", o];
}
function zg(r) {
return r.match(Lg.URL_SCHEME_REGEX) != null;
}
var s1 = (r, e) => {
if (typeof fetch == "undefined" && (e == null || e.fetchFunc == null))
return null;
{
let t = true;
if (Array.isArray(r) ? t = r.every((n) => zg(n)) : t = zg(r), t)
return Bg(r, e);
}
return null;
};
Et.registerSaveRouter(s1);
Et.registerLoadRouter(s1);
function Bg(r, e) {
return new Lg(r, e);
}
function i1(r, e) {
return Bg(r, e);
}
var Vg = class {
constructor(e) {
this.modelArtifacts = e;
}
async load() {
return this.modelArtifacts;
}
};
var a1 = class {
constructor(e) {
this.saveHandler = e;
}
async save(e) {
return this.saveHandler(e);
}
};
function l1(r, e, t, n) {
return arguments.length === 1 ? r.modelTopology != null || r.weightSpecs != null ? new Vg(r) : (console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."), new Vg({ modelTopology: r })) : (console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."), new Vg({ modelTopology: r, weightSpecs: e, weightData: t, trainingConfig: n }));
}
function u1(r) {
return new a1(r);
}
var p1 = {};
qe(p1, { confusionMatrix: () => c1 });
function S4(r, e, t = false, n = false) {
let o = k(r, "a", "matMul"), s = k(e, "b", "matMul");
[o, s] = je(o, s);
let a = { a: o, b: s }, i = { transposeA: t, transposeB: n };
return T.runKernel(Oo, a, i);
}
var ze = N({ matMul_: S4 });
function N4(r, e, t = 1, n = 0) {
if (e < 2)
throw new Error(`Error in oneHot: depth must be >=2, but it is ${e}`);
let s = { indices: k(r, "indices", "oneHot", "int32") }, a = { depth: e, onValue: t, offValue: n };
return T.runKernel(is, s, a);
}
var Ts = N({ oneHot_: N4 });
function T4(r, e) {
let t = k(r, "x", "transpose");
if (e == null && (e = t.shape.map((s, a) => a).reverse()), E(t.rank === e.length, () => `Error in transpose: rank of input ${t.rank} must match length of perm ${e}.`), e.forEach((s) => {
E(s >= 0 && s < t.rank, () => `All entries in 'perm' must be between 0 and ${t.rank - 1} but got ${e}`);
}), t.rank <= 1)
return t.clone();
let n = { x: t }, o = { perm: e };
return T.runKernel(Is, n, o);
}
var Be = N({ transpose_: T4 });
function E4(r, e, t) {
let n = k(r, "labels", "confusionMatrix"), o = k(e, "predictions", "confusionMatrix");
E(t == null || t > 0 && Number.isInteger(t), () => `If provided, numClasses must be a positive integer, but got ${t}`), E(n.rank === 1, () => `Expected the rank of labels to be 1, but got ${n.rank}`), E(o.rank === 1, () => `Expected the rank of predictions to be 1, but got ${o.rank}`), E(n.shape[0] === o.shape[0], () => `Mismatch in the number of examples: ${n.shape[0]} vs. ${o.shape[0]}. Labels and predictions should have the same number of elements.`), E(t > 0 && Number.isInteger(t), () => `numClasses is required to be a positive integer, but got ${t}`);
let s = Ts(Y(n, "int32"), t), a = Ts(Y(o, "int32"), t), i = Be(s), l = ze(i, a);
return Y(l, "int32");
}
var c1 = N({ confusionMatrix_: E4 });
var Gg = {};
qe(Gg, { fromPixels: () => P4, fromPixelsAsync: () => F4, toPixels: () => O4 });
function T_(r, e, t) {
if (Wn(r), e != null && e.length !== 3)
throw new Error("tensor3d() requires shape to have three numbers");
let n = Mr(r, t);
if (n.length !== 3 && n.length !== 1)
throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");
if (n.length === 1 && e == null)
throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");
return tn(r, e, n, t);
}
var Fp;
function m1(r, e = 3) {
if (e > 4)
throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");
if (r == null)
throw new Error("pixels passed to tf.browser.fromPixels() can not be null");
let t = false, n = false, o = false, s = false, a = false, i = false;
if (r.data instanceof Uint8Array)
t = true;
else if (typeof ImageData != "undefined" && r instanceof ImageData)
n = true;
else if (typeof HTMLVideoElement != "undefined" && r instanceof HTMLVideoElement)
o = true;
else if (typeof HTMLImageElement != "undefined" && r instanceof HTMLImageElement)
s = true;
else if (r.getContext != null)
a = true;
else if (typeof ImageBitmap != "undefined" && r instanceof ImageBitmap)
i = true;
else
throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${r.constructor.name}`);
if (o) {
let d = 2;
if (o && r.readyState < d)
throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");
}
if (sf(nf, T.backendName) != null) {
let d = { pixels: r }, h = { numChannels: e };
return T.runKernel(nf, d, h);
}
let [u, c] = o ? [r.videoWidth, r.videoHeight] : [r.width, r.height], p;
a ? p = r.getContext("2d").getImageData(0, 0, u, c).data : n || t ? p = r.data : (s || o || i) && (Fp == null && (Fp = document.createElement("canvas").getContext("2d")), Fp.canvas.width = u, Fp.canvas.height = c, Fp.drawImage(r, 0, 0, u, c), p = Fp.getImageData(0, 0, u, c).data);
let m;
if (e === 4)
m = new Int32Array(p);
else {
let d = u * c;
m = new Int32Array(d * e);
for (let h = 0; h < d; h++)
for (let g = 0; g < e; ++g)
m[h * e + g] = p[h * 4 + g];
}
return T_(m, [c, u, e], "int32");
}
function A4(r) {
return r != null && r.data instanceof Uint8Array;
}
function D4() {
return typeof window != "undefined" && typeof ImageBitmap != "undefined" && window.hasOwnProperty("createImageBitmap");
}
function $4(r) {
return r != null && r.width !== 0 && r.height !== 0;
}
function R4(r) {
return D4() && !(r instanceof ImageBitmap) && $4(r) && !A4(r);
}
async function F4(r, e = 3) {
let t = null;
if (U().getBool("WRAP_TO_IMAGEBITMAP") && R4(r)) {
let n;
try {
n = await createImageBitmap(r, { premultiplyAlpha: "none" });
} catch (o) {
n = null;
}
n != null && n.width === r.width && n.height === r.height ? t = n : t = r;
} else
t = r;
return m1(t, e);
}
async function O4(r, e) {
let t = k(r, "img", "toPixels");
if (!(r instanceof Le)) {
let u = t;
t = Y(u, "int32"), u.dispose();
}
if (t.rank !== 2 && t.rank !== 3)
throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${t.rank}.`);
let [n, o] = t.shape.slice(0, 2), s = t.rank === 2 ? 1 : t.shape[2];
if (s > 4 || s === 2)
throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${s}`);
if (t.dtype !== "float32" && t.dtype !== "int32")
throw new Error(`Unsupported type for toPixels: ${t.dtype}. Please use float32 or int32 tensors.`);
let a = await t.data(), i = t.dtype === "float32" ? 255 : 1, l = new Uint8ClampedArray(o * n * 4);
for (let u = 0; u < n * o; ++u) {
let c = [0, 0, 0, 255];
for (let m = 0; m < s; m++) {
let f = a[u * s + m];
if (t.dtype === "float32") {
if (f < 0 || f > 1)
throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${f}.`);
} else if (t.dtype === "int32" && (f < 0 || f > 255))
throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${f}.`);
s === 1 ? (c[0] = f * i, c[1] = f * i, c[2] = f * i) : c[m] = f * i;
}
let p = u * 4;
l[p + 0] = Math.round(c[0]), l[p + 1] = Math.round(c[1]), l[p + 2] = Math.round(c[2]), l[p + 3] = Math.round(c[3]);
}
if (e != null) {
e.width = o, e.height = n;
let u = e.getContext("2d"), c = new ImageData(l, o, n);
u.putImageData(c, 0, 0);
}
return t !== r && t.dispose(), l;
}
var P4 = N({ fromPixels_: m1 });
var Wg = {};
qe(Wg, { prepareAndValidate: () => f1 });
function f1(r, e) {
let t = r.shape.length, n = e.shape.length;
if (t < 1)
throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${t}.`);
if (n < 1)
throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${n}.`);
if (e.dtype !== "int32")
throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);
if (e.shape[n - 1] > t)
throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${e.shape[n - 1]} vs. ${t}`);
if (st(r.shape) === 0)
throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${r.shape}.`);
let o = e.shape, s = o[o.length - 1], a = 1;
for (let p = 0; p < o.length - 1; ++p)
a *= o[p];
let i = r.shape, l = o.slice();
l.pop();
let u = 1;
for (let p = s; p < t; ++p)
u *= i[p], l.push(i[p]);
let c = [...ei(r.shape).map((p) => p / u), 1].slice(0, s);
return [l, a, u, c];
}
var jg = {};
qe(jg, { calculateShapes: () => d1, validateInput: () => Ug, validateUpdateShape: () => E_ });
function E_(r, e, t) {
let n = e.rank > 1 ? e.shape[e.rank - 1] : 1, o = e.rank > 1 ? e.rank - 1 : 1, s = `Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${t.shape}, indices.shape: ${e.shape}, shape: ${r}, sliceDim: ${n}, and batchDim: ${o}.`;
if (t.rank < o)
throw new Error(s + ` update.rank < ${o}. `);
if (r.length < n + (t.rank - o))
throw new Error(s + ` Output shape length < ${n + (t.rank - o)}`);
if (t.rank !== o + r.length - n)
throw new Error(s + ` update.rank != ${o + r.length - n}`);
for (let a = 0; a < o; ++a)
if (t.shape[a] !== e.shape[a])
throw new Error(s + ` updates.shape[${a}] (${t.shape[a]}) != indices.shape[${a}] (${e.shape[a]}).`);
for (let a = 0; a < t.rank - o; ++a)
if (t.shape[a + o] !== r[a + n])
throw new Error(s + ` updates.shape[${a + o}] (${t.shape[a + o]}) != shape[${a + o}] (${r[a + o]})`);
}
function Ug(r, e, t) {
if (e.rank < 1)
throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${e.rank}.`);
if (r.rank < 1)
throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${r.rank}.`);
if (e.dtype !== "int32")
throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${e.dtype}`);
if (t.length < 1)
throw new Error(`Output rank must be greater or equal to 1, but got shape: ${t}`);
if (t.length === 0) {
if (e.size === 0)
throw new Error(`Indices specified for empty output. indices shape: ${e.shape}`);
if (r.size === 0)
throw new Error(`Updates specified for empty output. updates shape: ${r.shape}`);
}
E_(t, e, r);
}
function d1(r, e, t) {
let n = e.shape.length, o = n > 1 ? e.shape[n - 1] : 1, s = t.length, a = 1;
for (let p = o; p < s; ++p)
a *= t[p];
let i = o < 1 ? 1 : o, l = st(e.shape) / i, u = [...ei(t.slice(0, o)), 1], c = st(t);
return { sliceRank: o, numUpdates: l, sliceSize: a, strides: u, outputSize: c };
}
var pr = {};
qe(pr, { assertParamsValid: () => M4, computeFlatOffset: () => z4, computeOutShape: () => h1, getNormalizedAxes: () => b1, isSliceContinous: () => L4, maskToAxes: () => Hg, parseSliceParams: () => A_, sliceInfo: () => B4, startForAxis: () => v1, startIndicesWithElidedDims: () => w1, stopForAxis: () => C1, stopIndicesWithElidedDims: () => _1, stridesForAxis: () => k1, stridesWithElidedDims: () => g1 });
function M4(r, e, t) {
let n = r.shape.length;
E(n === e.length, () => `Error in slice${n}D: Length of begin ${e} must match the rank of the array (${n}).`), E(n === t.length, () => `Error in slice${n}D: Length of size ${t} must match the rank of the array (${n}).`);
for (let o = 0; o < n; ++o)
E(e[o] + t[o] <= r.shape[o], () => `Error in slice${n}D: begin[${o}] + size[${o}] (${e[o] + t[o]}) would overflow input.shape[${o}] (${r.shape[o]})`);
}
function Hg(r) {
let e = [], t = 0;
for (; r > 0; )
r & 1 && e.push(t), r /= 2, t++;
return e;
}
function h1(r, e, t) {
let n = [];
for (let o = 0; o < r.length; o++)
n[o] = Math.ceil((e[o] - r[o]) / t[o]);
return n;
}
function g1(r, e, t, n) {
let o = [...r];
for (let s = o.length; s < n.length; s++)
o.push(1);
for (let s = 0; s < t; s++)
s === 0 ? o[e] = 1 : (o.splice(e, 0, 1), o.pop());
return o;
}
function x1(r, e, t) {
return t <= r ? t : t - (e - 1);
}
function y1(r, e) {
let t = [];
for (let n = 0; n < r; n++)
t.push(e + n);
return t;
}
function b1(r, e, t, n, o, s, a, i, l) {
let u = r.length, c = new Array(u), p = new Array(u), m = new Array(u);
if (e.length && t > 0) {
let f = e[0], d = t + 1;
c = w1(a, f, d, n, r), p = _1(i, f, d, o, r), m = g1(s, f, d, r);
} else
for (let f = 0; f < u; f++)
c[f] = v1(a, n, s, r, f, l), p[f] = C1(i, o, s, r, f, l), m[f] = k1(s, f, l);
return { begin: c, end: p, strides: m };
}
function w1(r, e, t, n, o) {
let s = [...o], a = y1(t, e);
for (let i = 0; i < s.length; i++)
if (a.indexOf(i) > -1)
s[i] = 0;
else {
let l = x1(e, t, i), u = n[l];
r & 1 << l && (u = 0), s[i] = u;
}
return s;
}
function _1(r, e, t, n, o) {
let s = [...o], a = y1(t, e);
for (let i = 0; i < s.length; i++)
if (a.indexOf(i) > -1)
s[i] = Number.MAX_SAFE_INTEGER;
else {
let l = x1(e, t, i), u = n[l];
r & 1 << l && (u = Number.MAX_SAFE_INTEGER), s[i] = u;
}
for (let i = 0; i < s.length; i++) {
let l = o[i];
s[i] < 0 && (s[i] += l), s[i] = zc(0, s[i], o[i]);
}
return s;
}
function k1(r, e, t) {
let n = r[e];
return (t & 1 << e || n == null) && (n = 1), n;
}
function v1(r, e, t, n, o, s) {
let a = e[o], i = t[o] || 1;
(r & 1 << o || s & 1 << o || a == null) && (i > 0 ? a = Number.MIN_SAFE_INTEGER : a = Number.MAX_SAFE_INTEGER);
let l = n[o];
return a < 0 && (a += l), a = zc(0, a, l - 1), a;
}
function C1(r, e, t, n, o, s) {
let a = e[o], i = t[o] || 1;
(r & 1 << o || s & 1 << o || a == null) && (i > 0 ? a = Number.MAX_SAFE_INTEGER : a = Number.MIN_SAFE_INTEGER);
let l = n[o];
return a < 0 && (a += l), i > 0 ? a = zc(0, a, l) : a = zc(-1, a, l - 1), a;
}
function L4(r, e, t) {
let n = t.length;
for (let o = 0; o < t.length; o++)
if (t[o] > 1) {
n = o;
break;
}
for (let o = n + 1; o < t.length; o++)
if (e[o] > 0 || t[o] !== r[o])
return false;
return true;
}
function z4(r, e) {
let t = r.length > 0 ? r[r.length - 1] : 1;
for (let n = 0; n < r.length - 1; n++)
t += r[n] * e[n];
return t;
}
function A_(r, e, t) {
let n, o = r.shape.length;
typeof e == "number" ? n = [e, ...new Array(o - 1).fill(0)] : e.length < o ? n = e.concat(new Array(o - e.length).fill(0)) : n = e.slice(), n.forEach((a) => {
E(a !== -1, () => "slice() does not support negative begin indexing.");
});
let s;
return t == null ? s = new Array(o).fill(-1) : typeof t == "number" ? s = [t, ...new Array(o - 1).fill(-1)] : t.length < o ? s = t.concat(new Array(o - t.length).fill(-1)) : s = t, s = s.map((a, i) => a >= 0 ? a : (E(a === -1, () => `Negative size values should be exactly -1 but got ${a} for the slice() size at index ${i}.`), r.shape[i] - n[i])), [n, s];
}
function B4(r, e, t, n, o, s, a, i, l) {
let u = e.slice(), c = t.slice(), p = n;
n == null && (p = new Array(u.length));
let m = Hg(a);
if (m.length > 1)
throw new Error("Multiple ellipses in slice is not allowed.");
if (a !== 0 && i !== 0)
throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");
if (a !== 0 && l !== 0)
throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");
let f = r.length - u.length, d = Hg(i), h = r.slice();
d.forEach((D) => {
u[D] = 0, c[D] = 1, h.splice(D, 0, 1);
});
let { begin: g, end: x, strides: y } = b1(h, m, f, u, c, p, o, s, a);
u = g, c = x, p = y;
let w = Hg(l);
w.forEach((D) => {
c[D] = u[D] + 1, p[D] = 1;
});
let _ = h1(u, c, p), C = _.filter((D, R) => w.indexOf(R) === -1);
return { nonStrided: p.every((D) => D === 1), $begin: u, $end: c, $strides: p, size: _, newShape: h, outShape: C };
}
var ee = {};
qe(ee, { Serializable: () => qg, SerializationMap: () => Na, registerClass: () => _n });
var qg = class {
getClassName() {
return this.constructor.className;
}
static fromConfig(e, t) {
return new e(t);
}
};
var Na = class {
constructor() {
this.classNameMap = {};
}
static getMap() {
return Na.instance == null && (Na.instance = new Na()), Na.instance;
}
static register(e) {
Na.getMap().classNameMap[e.className] = [e, e.fromConfig];
}
};
function _n(r) {
E(r.className != null, () => "Class being registered does not have the static className property defined."), E(typeof r.className == "string", () => "className is required to be a string, but got type " + typeof r.className), E(r.className.length > 0, () => "Class being registered has an empty-string as its className, which is disallowed."), Na.register(r);
}
var T1 = {};
qe(T1, { TEST_EPSILON_FLOAT16: () => I1, encodeStrings: () => N1, expectArrayBuffersEqual: () => H4, expectArraysClose: () => G4, expectArraysEqual: () => U4, expectNumbersClose: () => S1, expectPromiseToFail: () => W4, expectValuesInRange: () => j4, testEpsilon: () => Kg });
var V4 = 1e-3;
var I1 = 0.1;
function G4(r, e, t) {
return t == null && (t = Kg()), D_(r, e, (n, o) => $_(n, o, t));
}
function Kg() {
return T.backend.floatPrecision() === 32 ? V4 : I1;
}
function D_(r, e, t) {
let n = true;
if ((dr(r) || dr(e)) && (n = false), dr(r) && dr(e) && (n = true), n) {
let a = r.constructor.name, i = e.constructor.name;
if (a !== i)
throw new Error(`Arrays are of different type. Actual: ${a}. Expected: ${i}`);
}
if (Array.isArray(r) && Array.isArray(e)) {
let a = Mr(r), i = Mr(e);
if (!Qr(a, i))
throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${i}]`);
}
let o = dr(r) ? r : Ao(r), s = dr(e) ? e : Ao(e);
if (o.length !== s.length)
throw new Error(`Arrays have different lengths actual: ${o.length} vs expected: ${s.length}.
Actual: ${o}.
Expected: ${s}.`);
for (let a = 0; a < s.length; ++a) {
let i = o[a], l = s[a];
if (!t(i, l))
throw new Error(`Arrays differ: actual[${a}] = ${i}, expected[${a}] = ${l}.
Actual: ${o}.
Expected: ${s}.`);
}
}
function W4(r, e) {
r().then(() => e.fail(), () => e());
}
function U4(r, e) {
let t = typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? [e] : e;
return Do(r) || Do(r[0]) || Do(e) || Do(e[0]) ? D_(r, t, (n, o) => n == o) : D_(r, e, (n, o) => $_(n, o, 0));
}
function S1(r, e, t) {
if (t == null && (t = Kg()), !$_(r, e, t))
throw new Error(`Numbers differ: actual === ${r}, expected === ${e}`);
}
function $_(r, e, t) {
return !isFinite(r) && !isFinite(e) ? true : !(isNaN(r) || isNaN(e) || Math.abs(r - e) > t);
}
function j4(r, e, t) {
for (let n = 0; n < r.length; n++)
if (r[n] < e || r[n] > t)
throw new Error(`Value out of range:${r[n]} low: ${e}, high: ${t}`);
}
function H4(r, e) {
expect(new Float32Array(r)).toEqual(new Float32Array(e));
}
function N1(r) {
for (let e = 0; e < r.length; e++) {
let t = r[e];
Array.isArray(t) ? N1(t) : r[e] = Il(t);
}
return r;
}
var E1 = "3.10.0";
function nue() {
U().set("PROD", true);
}
function oue() {
U().set("DEBUG", true);
}
function sue() {
U().set("DEPRECATION_WARNINGS_ENABLED", false), console.warn("TensorFlow.js deprecation warnings have been disabled.");
}
function R_(r) {
U().getBool("DEPRECATION_WARNINGS_ENABLED") && console.warn(r + " You can disable deprecation warnings with tf.disableDeprecationWarnings().");
}
TN(R_);
function iue() {
T.disposeVariables();
}
function Es() {
return T;
}
function ff() {
return T.memory();
}
function aue(r) {
return T.profile(r);
}
function V(r, e) {
return T.tidy(r, e);
}
function De(r) {
pf(r).forEach((t) => t.dispose());
}
function Ft(r) {
return T.keep(r);
}
function lue(r) {
return T.time(r);
}
function q4(r) {
return T.setBackend(r);
}
function uue() {
return T.ready();
}
function cue() {
return T.backendName;
}
function pue(r) {
T.removeBackend(r);
}
function mue(r) {
return T.findBackend(r);
}
function fue(r) {
return T.findBackendFactory(r);
}
function Op(r, e, t = 1) {
return T.registerBackend(r, e, t);
}
function A1() {
return T.backend;
}
function due(r, e) {
U().setPlatform(r, e);
}
function K4(r, e) {
let t = k(r, "a", "add"), n = k(e, "b", "add");
[t, n] = je(t, n);
let o = { a: t, b: n };
return T.runKernel(jn, o);
}
var Z = N({ add_: K4 });
function X4(r, e) {
let t = k(r, "a", "floorDiv"), n = k(e, "b", "floorDiv");
[t, n] = je(t, n);
let o = { a: t, b: n };
return T.runKernel(qo, o);
}
var bu = N({ floorDiv_: X4 });
function Y4(r, e) {
let t = k(r, "a", "div"), n = k(e, "b", "div");
if ([t, n] = je(t, n), t.dtype === "int32" && n.dtype === "int32")
return bu(t, n);
let o = { a: t, b: n }, s = {};
return T.runKernel(Wo, o, s);
}
var ce = N({ div_: Y4 });
function Z4(r, e) {
let t = k(r, "a", "mul"), n = k(e, "b", "mul");
[t, n] = je(t, n);
let o = { a: t, b: n };
return T.runKernel(ss, o);
}
var O = N({ mul_: Z4 });
function J4(r) {
let e = k(r, "x", "abs");
if (e.dtype === "complex64") {
let t = { x: e };
return T.runKernel(dl, t);
} else {
let t = { x: e };
return T.runKernel(ti, t);
}
}
var Ct = N({ abs_: J4 });
function Q4(r) {
let t = { x: k(r, "x", "acos") };
return T.runKernel(Mi, t);
}
var df = N({ acos_: Q4 });
function eU(r) {
let t = { x: k(r, "x", "acosh") };
return T.runKernel(Li, t);
}
var hf = N({ acosh_: eU });
function tU(r) {
E(Array.isArray(r), () => "The argument passed to tf.addN() must be a list of tensors"), E(r.length >= 1, () => `Must pass at least one tensor to tf.addN(), but got ${r.length}`);
let e = r.map((o, s) => k(o, `tensors${s}`, "addN")), t = e[0];
e.forEach((o) => {
if (o.dtype !== t.dtype)
throw new Error("All tensors passed to tf.addN() must have the same dtype");
}), e.forEach((o) => {
if (!Qr(o.shape, t.shape))
throw new Error("All tensors passed to tf.addN() must have the same shape");
});
let n = e;
return T.runKernel($o, n);
}
var F_ = N({ addN_: tU });
function rU(r, e = null, t = false) {
let o = { x: k(r, "x", "all", "bool") }, s = { axis: e, keepDims: t };
return T.runKernel(zi, o, s);
}
var wu = N({ all_: rU });
function nU(r, e = null, t = false) {
let o = { x: k(r, "x", "any", "bool") }, s = { axis: e, keepDims: t };
return T.runKernel(Bi, o, s);
}
var El = N({ any_: nU });
function oU(r, e = 0) {
let n = { x: k(r, "x", "argMax") }, o = { axis: e };
return T.runKernel(Ro, n, o);
}
var As = N({ argMax_: oU });
function sU(r, e = 0) {
let n = { x: k(r, "x", "argMin") }, o = { axis: e };
return T.runKernel(ml, n, o);
}
var gf = N({ argMin_: sU });
function iU(r) {
let t = { x: k(r, "x", "asin") };
return T.runKernel(Vi, t);
}
var xf = N({ asin_: iU });
function aU(r) {
let t = { x: k(r, "x", "asinh") };
return T.runKernel(Gi, t);
}
var yf = N({ asinh_: aU });
function lU(r) {
let t = { x: k(r, "x", "atan") };
return T.runKernel(Wi, t);
}
var bf = N({ atan_: lU });
function uU(r, e) {
let t = k(r, "a", "atan2"), n = k(e, "b", "atan2");
[t, n] = je(t, n);
let o = { a: t, b: n };
return T.runKernel(ji, o);
}
var wf = N({ atan2_: uU });
function cU(r) {
let t = { x: k(r, "x", "atanh") };
return T.runKernel(Ui, t);
}
var _f = N({ atanh_: cU });
function pU(r, e, t, n, o = "NHWC", s) {
let a = r[3], i = [...e, a], l = $1(o);
return _u(r, i, t, s, n, null, null, l);
}
function O_(r, e, t, n, o, s, a = "channelsLast") {
let [i, l] = Xg(e), u;
if (a === "channelsLast")
u = [i, l, r[3], r[3]];
else if (a === "channelsFirst")
u = [i, l, r[1], r[1]];
else
throw new Error(`Unknown dataFormat ${a}`);
return _u(r, u, t, n, o, s, false, a);
}
function mU(r, e, t, n, o, s, a = "NDHWC") {
let [i, l, u] = M_(e), c, p;
if (a === "NDHWC")
p = "channelsLast", c = [i, l, u, r[4], r[4]];
else if (a === "NCDHW")
p = "channelsFirst", c = [i, l, u, r[1], r[1]];
else
throw new Error(`Unknown dataFormat ${a}`);
return D1(r, c, t, n, o, false, p, s);
}
function _u(r, e, t, n, o, s, a = false, i = "channelsLast") {
let [l, u, c, p] = [-1, -1, -1, -1];
if (i === "channelsLast")
[l, u, c, p] = r;
else if (i === "channelsFirst")
[l, p, u, c] = r;
else
throw new Error(`Unknown dataFormat ${i}`);
let [m, f, , d] = e, [h, g] = Xg(t), [x, y] = Xg(n), w = Pp(m, x), _ = Pp(f, y), { padInfo: C, outHeight: A, outWidth: D } = hU(o, u, c, h, g, w, _, s, i), R = a ? d * p : d, P;
return i === "channelsFirst" ? P = [l, R, A, D] : i === "channelsLast" && (P = [l, A, D, R]), { batchSize: l, dataFormat: i, inHeight: u, inWidth: c, inChannels: p, outHeight: A, outWidth: D, outChannels: R, padInfo: C, strideHeight: h, strideWidth: g, filterHeight: m, filterWidth: f, effectiveFilterHeight: w, effectiveFilterWidth: _, dilationHeight: x, dilationWidth: y, inShape: r, outShape: P, filterShape: e };
}
function D1(r, e, t, n, o, s = false, a = "channelsLast", i) {
let [l, u, c, p, m] = [-1, -1, -1, -1, -1];
if (a === "channelsLast")
[l, u, c, p, m] = r;
else if (a === "channelsFirst")
[l, m, u, c, p] = r;
else
throw new Error(`Unknown dataFormat ${a}`);
let [f, d, h, , g] = e, [x, y, w] = M_(t), [_, C, A] = M_(n), D = Pp(f, _), R = Pp(d, C), P = Pp(h, A), { padInfo: L, outDepth: G, outHeight: W, outWidth: j } = gU(o, u, c, p, x, y, w, D, R, P, i), H = s ? g * m : g, q;
return a === "channelsFirst" ? q = [l, H, G, W, j] : a === "channelsLast" && (q = [l, G, W, j, H]), { batchSize: l, dataFormat: a, inDepth: u, inHeight: c, inWidth: p, inChannels: m, outDepth: G, outHeight: W, outWidth: j, outChannels: H, padInfo: L, strideDepth: x, strideHeight: y, strideWidth: w, filterDepth: f, filterHeight: d, filterWidth: h, effectiveFilterDepth: D, effectiveFilterHeight: R, effectiveFilterWidth: P, dilationDepth: _, dilationHeight: C, dilationWidth: A, inShape: r, outShape: q, filterShape: e };
}
function fU(r, e, t, n, o) {
n == null && (n = P_(r, e, t));
let s = r[0], a = r[1], i = ku((s - e + 2 * n) / t + 1, o), l = ku((a - e + 2 * n) / t + 1, o);
return [i, l];
}
function dU(r, e, t, n, o, s) {
o == null && (o = P_(r, e, n));
let a = r[0], i = r[1], l = r[2], u = ku((a - e + 2 * o) / n + 1, s), c = ku((i - e + 2 * o) / n + 1, s), p = ku((l - e + 2 * o) / n + 1, s);
return [u, c, p, t];
}
function P_(r, e, t, n = 1) {
let o = Pp(e, n);
return Math.floor((r[0] * (t - 1) - t + o) / 2);
}
function Xg(r) {
return typeof r == "number" ? [r, r, r] : r.length === 2 ? [r[0], r[1], 1] : r;
}
function M_(r) {
return typeof r == "number" ? [r, r, r] : r;
}
function Pp(r, e) {
return e <= 1 ? r : r + (r - 1) * (e - 1);
}
function hU(r, e, t, n, o, s, a, i, l) {
let u, c, p;
if (typeof r == "number") {
u = { top: r, bottom: r, left: r, right: r, type: r === 0 ? "VALID" : "NUMBER" };
let f = fU([e, t], s, n, r, i);
c = f[0], p = f[1];
} else if (r === "same") {
c = Math.ceil(e / n), p = Math.ceil(t / o);
let m = Math.max(0, (c - 1) * n + s - e), f = Math.max(0, (p - 1) * o + a - t), d = Math.floor(m / 2), h = m - d, g = Math.floor(f / 2), x = f - g;
u = { top: d, bottom: h, left: g, right: x, type: "SAME" };
} else if (r === "valid")
u = { top: 0, bottom: 0, left: 0, right: 0, type: "VALID" }, c = Math.ceil((e - s + 1) / n), p = Math.ceil((t - a + 1) / o);
else if (typeof r == "object") {
let m = l === "channelsLast" ? r[1][0] : r[2][0], f = l === "channelsLast" ? r[1][1] : r[2][1], d = l === "channelsLast" ? r[2][0] : r[3][0], h = l === "channelsLast" ? r[2][1] : r[3][1];
u = { top: m, bottom: f, left: d, right: h, type: m === 0 && f === 0 && d === 0 && h === 0 ? "VALID" : "EXPLICIT" }, c = ku((e - s + m + f) / n + 1, i), p = ku((t - a + d + h) / o + 1, i);
} else
throw Error(`Unknown padding parameter: ${r}`);
return { padInfo: u, outHeight: c, outWidth: p };
}
function gU(r, e, t, n, o, s, a, i, l, u, c) {
let p, m, f, d;
if (typeof r == "number") {
p = { top: r, bottom: r, left: r, right: r, front: r, back: r, type: r === 0 ? "VALID" : "NUMBER" };
let g = dU([e, t, n, 1], i, 1, o, r, c);
m = g[0], f = g[1], d = g[2];
} else if (r === "same") {
m = Math.ceil(e / o), f = Math.ceil(t / s), d = Math.ceil(n / a);
let h = (m - 1) * o + i - e, g = (f - 1) * s + l - t, x = (d - 1) * a + u - n, y = Math.floor(h / 2), w = h - y, _ = Math.floor(g / 2), C = g - _, A = Math.floor(x / 2), D = x - A;
p = { top: _, bottom: C, left: A, right: D, front: y, back: w, type: "SAME" };
} else if (r === "valid")
p = { top: 0, bottom: 0, left: 0, right: 0, front: 0, back: 0, type: "VALID" }, m = Math.ceil((e - i + 1) / o), f = Math.ceil((t - l + 1) / s), d = Math.ceil((n - u + 1) / a);
else
throw Error(`Unknown padding parameter: ${r}`);
return { padInfo: p, outDepth: m, outHeight: f, outWidth: d };
}
function ku(r, e) {
if (!e)
return Math.trunc(r);
switch (e) {
case "round":
return Math.round(r);
case "ceil":
return Math.ceil(r);
case "floor":
return Math.floor(r);
default:
throw new Error(`Unknown roundingMode ${e}`);
}
}
function qn(r) {
let [e, t, n] = Xg(r);
return e === 1 && t === 1 && n === 1;
}
function $r(r, e) {
return qn(r) || qn(e);
}
function $1(r) {
if (r === "NHWC")
return "channelsLast";
if (r === "NCHW")
return "channelsFirst";
throw new Error(`Unknown dataFormat ${r}`);
}
function xU(r, e) {
let n = { x: k(r, "x", "reshape", "string_or_numeric") }, o = { shape: e };
return T.runKernel(ui, n, o);
}
var F = N({ reshape_: xU });
function yU(r, e, t, n, o) {
let s = k(r, "x", "avgPool", "float32"), a = 1;
E($r(t, a), () => `Error in avgPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`);
let i = s, l = false;
s.rank === 3 && (l = true, i = F(s, [1, s.shape[0], s.shape[1], s.shape[2]])), E(i.rank === 4, () => `Error in avgPool: x must be rank 4 but got rank ${i.rank}.`), o != null && E(it(n), () => `Error in avgPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);
let u = { x: i }, c = { filterSize: e, strides: t, pad: n, dimRoundingMode: o }, p = T.runKernel(Fo, u, c);
return p = Y(p, s.dtype), l ? F(p, [p.shape[1], p.shape[2], p.shape[3]]) : p;
}
var Ta = N({ avgPool_: yU });
function bU(r, e, t, n, o, s = "NDHWC") {
let a = k(r, "x", "avgPool3d", "float32"), i = a, l = false;
a.rank === 4 && (l = true, i = F(a, [1, a.shape[0], a.shape[1], a.shape[2], a.shape[3]])), E(i.rank === 5, () => `Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`), E(s === "NDHWC", () => `Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`), o != null && E(it(n), () => `Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);
let u = { x: i }, c = { filterSize: e, strides: t, pad: n, dimRoundingMode: o, dataFormat: s }, p = T.runKernel(fl, u, c);
return p = Y(p, i.dtype), l ? F(p, [p.shape[1], p.shape[2], p.shape[3], p.shape[4]]) : p;
}
var kf = N({ avgPool3d_: bU });
function wU(r, e = 0) {
E(r.length >= 1, () => "Pass at least one tensor to concat");
let t = va(r, "tensors", "concat", "string_or_numeric");
if (t[0].dtype === "complex64" && t.forEach((s) => {
if (s.dtype !== "complex64")
throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${s.dtype}. `);
}), t.length === 1)
return wn(t[0]);
let n = t, o = { axis: e };
return T.runKernel(ni, n, o);
}
var tt = N({ concat_: wU });
function _U(r) {
let t = { x: k(r, "x", "sigmoid", "float32") };
return T.runKernel(xs, t);
}
var zr = N({ sigmoid_: _U });
function kU(r, e, t) {
let n = k(r, "x", "slice", "string_or_numeric");
if (n.rank === 0)
throw new Error("Slicing scalar is not possible");
let o = { x: n }, s = { begin: e, size: t };
return T.runKernel(pi, o, s);
}
var Oe = N({ slice_: kU });
function vU(r) {
let t = { x: k(r, "x", "tanh", "float32") };
return T.runKernel(Cs, t);
}
var Ds = N({ tanh_: vU });
function CU(r, e, t, n, o, s) {
let a = k(r, "forgetBias", "basicLSTMCell"), i = k(e, "lstmKernel", "basicLSTMCell"), l = k(t, "lstmBias", "basicLSTMCell"), u = k(n, "data", "basicLSTMCell"), c = k(o, "c", "basicLSTMCell"), p = k(s, "h", "basicLSTMCell"), m = tt([u, p], 1), f = ze(m, i), d = Z(f, l), h = d.shape[0], g = d.shape[1] / 4, x = [h, g], y = Oe(d, [0, 0], x), w = Oe(d, [0, g], x), _ = Oe(d, [0, g * 2], x), C = Oe(d, [0, g * 3], x), A = Z(O(zr(y), Ds(w)), O(c, zr(Z(a, _)))), D = O(Ds(A), zr(C));
return [A, D];
}
var IU = N({ basicLSTMCell_: CU });
function SU(r, e, t) {
let n = k(r, "x", "batchToSpaceND"), o = e.reduce((i, l) => i * l);
E(n.rank >= 1 + e.length, () => `input rank is ${n.rank} but should be > than blockShape.length ${e.length}`), E(t.length === e.length, () => `crops.length is ${t.length} but should be equal to blockShape.length ${e.length}`), E(n.shape[0] % o == 0, () => `input tensor batch is ${n.shape[0]} but is not divisible by the product of the elements of blockShape ${e.join(" * ")} === ${o}`);
let s = { x: n }, a = { blockShape: e, crops: t };
return T.runKernel(ri, s, a);
}
var Ea = N({ batchToSpaceND_: SU });
function R1(r) {
let e;
return r.rank === 0 || r.rank === 1 ? e = F(r, [1, 1, 1, r.size]) : r.rank === 2 ? e = F(r, [1, 1, r.shape[0], r.shape[1]]) : r.rank === 3 ? e = F(r, [1, r.shape[0], r.shape[1], r.shape[2]]) : e = r, e;
}
function NU(r, e, t, n, o, s) {
s == null && (s = 1e-3);
let a = k(r, "x", "batchNorm"), i = k(e, "mean", "batchNorm"), l = k(t, "variance", "batchNorm"), u;
o != null && (u = k(o, "scale", "batchNorm"));
let c;
n != null && (c = k(n, "offset", "batchNorm")), E(i.rank === l.rank, () => "Batch normalization gradient requires mean and variance to have equal ranks."), E(c == null || i.rank === c.rank, () => "Batch normalization gradient requires mean and offset to have equal ranks."), E(u == null || i.rank === u.rank, () => "Batch normalization gradient requires mean and scale to have equal ranks.");
let m = { x: R1(a), scale: u, offset: c, mean: i, variance: l }, f = { varianceEpsilon: s }, d = T.runKernel(Ko, m, f);
return F(d, a.shape);
}
var lo = N({ batchNorm_: NU });
function TU(r, e, t, n, o, s) {
let a = k(r, "x", "batchNorm"), i = k(e, "mean", "batchNorm"), l = k(t, "variance", "batchNorm"), u;
o != null && (u = k(o, "scale", "batchNorm"));
let c;
return n != null && (c = k(n, "offset", "batchNorm")), E(a.rank === 2, () => `Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`), E(i.rank === 2 || i.rank === 1, () => `Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`), E(l.rank === 2 || l.rank === 1, () => `Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`), u != null && E(u.rank === 2 || u.rank === 1, () => `Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`), c != null && E(c.rank === 2 || c.rank === 1, () => `Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`), lo(a, i, l, c, u, s);
}
var L_ = N({ batchNorm2d_: TU });
function EU(r, e, t, n, o, s) {
let a = k(r, "x", "batchNorm"), i = k(e, "mean", "batchNorm"), l = k(t, "variance", "batchNorm"), u;
o != null && (u = k(o, "scale", "batchNorm"));
let c;
return n != null && (c = k(n, "offset", "batchNorm")), E(a.rank === 3, () => `Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`), E(i.rank === 3 || i.rank === 1, () => `Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`), E(l.rank === 3 || l.rank === 1, () => `Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`), u != null && E(u.rank === 3 || u.rank === 1, () => `Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`), c != null && E(c.rank === 3 || c.rank === 1, () => `Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`), lo(a, i, l, c, u, s);
}
var z_ = N({ batchNorm3d_: EU });
function AU(r, e, t, n, o, s) {
let a = k(r, "x", "batchNorm"), i = k(e, "mean", "batchNorm"), l = k(t, "variance", "batchNorm"), u;
o != null && (u = k(o, "scale", "batchNorm"));
let c;
return n != null && (c = k(n, "offset", "batchNorm")), E(a.rank === 4, () => `Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`), E(i.rank === 4 || i.rank === 1, () => `Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`), E(l.rank === 4 || l.rank === 1, () => `Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`), u != null && E(u.rank === 4 || u.rank === 1, () => `Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`), c != null && E(c.rank === 4 || c.rank === 1, () => `Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`), lo(a, i, l, c, u, s);
}
var B_ = N({ batchNorm4d_: AU });
function DU(r, e, t) {
let n = k(r, "x", "bincount"), o = k(e, "weights", "bincount");
E(n.dtype === "int32", () => `Error in bincount: input dtype must be int32, but got ${n.dtype}`), E(t >= 0, () => `size must be non-negative, but got ${t}.`), E(o.size === n.size || o.size === 0, () => `Error in bincount: weights must have the same size as input or0-length, but got input shape: ${n.shape}, weights shape: ${o.shape}.`);
let s = { x: n, weights: o }, a = { size: t };
return T.runKernel(jc, s, a);
}
var vf = N({ bincount_: DU });
function $U(r, e) {
let t = k(r, "s0", "broadcastArgs", "int32"), n = k(e, "s1", "broadcastArgs", "int32");
if (t.rank !== 1)
throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${t.rank}`);
if (n.rank !== 1)
throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${n.rank}`);
let o = { s0: t, s1: n };
return T.runKernel(Hc, o);
}
var V_ = N({ broadcastArgs_: $U });
function RU(r, e) {
let t = k(r, "broadcastTo", "x"), n = t.shape;
if (e.some((u) => !(u > 0) || u % 1 != 0))
throw new Error(`broadcastTo(): Invalid broadcast shape [${e}].`);
if (e.length < t.rank)
throw new Error(`broadcastTo(): shape.length=${e.length} < input.rank=${t.rank}.`);
if (e.length > t.rank) {
let u = t.shape.slice();
for (; u.length < e.length; )
u.unshift(1);
t = F(t, u);
}
let o = t.shape, s = Array.from(e);
for (let u = e.length - 1; u >= 0; u--)
if (o[u] === e[u])
s[u] = 1;
else if (t.shape[u] !== 1)
throw new Error(`broadcastTo(): [${n}] cannot be broadcast to [${e}].`);
if (s.map((u, c) => u > 1 ? c : -1).filter((u) => u >= 0).length === 0)
return wn(t);
let i = { x: t }, l = { reps: s };
return T.runKernel(Hn, i, l);
}
var Aa = N({ broadcastTo_: RU });
function FU(r) {
let t = { x: k(r, "x", "ceil", "float32") };
return T.runKernel(Po, t);
}
var Cf = N({ ceil_: FU });
function OU(r, e, t) {
let n = k(r, "x", "clipByValue");
E(e <= t, () => `Error in clip: min (${e}) must be less than or equal to max (${t}).`);
let o = { x: n }, s = { clipValueMin: e, clipValueMax: t };
return T.runKernel(to, o, s);
}
var gr = N({ clipByValue_: OU });
function PU(r) {
return tt(r, 0);
}
var G_ = N({ concat1d_: PU });
function MU(r, e) {
return tt(r, e);
}
var W_ = N({ concat2d_: MU });
function LU(r, e) {
return tt(r, e);
}
var U_ = N({ concat3d_: LU });
function zU(r, e) {
return tt(r, e);
}
var j_ = N({ concat4d_: zU });
function BU(r, e, t, n, o = "NHWC", s = [1, 1], a) {
let i = k(r, "x", "conv2d", "float32"), l = k(e, "filter", "conv2d", "float32"), u = i, c = false;
i.rank === 3 && (c = true, u = F(i, [1, i.shape[0], i.shape[1], i.shape[2]])), E(u.rank === 4, () => `Error in conv2d: input must be rank 4, but got rank ${u.rank}.`), E(l.rank === 4, () => `Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`), a != null && E(it(n), () => `Error in conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${n}.`);
let p = o === "NHWC" ? u.shape[3] : u.shape[1];
E(p === l.shape[2], () => `Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`), E($r(t, s), () => `Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`);
let m = { x: u, filter: l }, f = { strides: t, pad: n, dataFormat: o, dilations: s, dimRoundingMode: a }, d = T.runKernel(Mo, m, f);
return c ? F(d, [d.shape[1], d.shape[2], d.shape[3]]) : d;
}
var nn = N({ conv2d_: BU });
function VU(r, e, t, n, o = "NWC", s = 1, a) {
let i = k(r, "x", "conv1d"), l = k(e, "filter", "conv1d"), u = i, c = false;
i.rank === 2 && (c = true, u = F(i, [1, i.shape[0], i.shape[1]])), E(u.rank === 3, () => `Error in conv1d: input must be rank 3, but got rank ${u.rank}.`), E(l.rank === 3, () => `Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`), a != null && E(it(n), () => `Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${n}.`), E(u.shape[2] === l.shape[1], () => `Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`), E($r(t, s), () => `Error in conv1D: Either stride or dilation must be 1. Got stride ${t} and dilation '${s}'`), E(o === "NWC", () => `Error in conv1d: got dataFormat of ${o} but only NWC is currently supported.`);
let p = F(l, [1, l.shape[0], l.shape[1], l.shape[2]]), m = F(u, [u.shape[0], 1, u.shape[1], u.shape[2]]), g = nn(m, p, [1, t], n, "NHWC", [1, s], a);
return c ? F(g, [g.shape[2], g.shape[3]]) : F(g, [g.shape[0], g.shape[2], g.shape[3]]);
}
var vu = N({ conv1d_: VU });
function GU(r, e, t, n, o, s = "NHWC", a) {
E(r.length === e.rank, () => `Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);
let i = r, l = e, u = false;
e.rank === 3 && (u = true, l = F(e, [1, e.shape[0], e.shape[1], e.shape[2]]), i = [1, r[0], r[1], r[2]]), E(i.length === 4, () => `Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`), E(l.rank === 4, () => `Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`), E(t.rank === 4, () => `Error in conv2dDerInput: filter must be rank 4, but got rank ${t.rank}`);
let c = s === "NHWC" ? i[3] : i[1], p = s === "NHWC" ? l.shape[3] : l.shape[1];
E(c === t.shape[2], () => `Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${t.shape[2]}.`), E(p === t.shape[3], () => `Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${t.shape[3]}.`), a != null && E(it(o), () => `Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);
let m = { dy: l, filter: t }, f = { strides: n, pad: o, dataFormat: s, dimRoundingMode: a, inputShape: i }, d = T.runKernel(Lo, m, f);
return u ? F(d, [d.shape[1], d.shape[2], d.shape[3]]) : d;
}
var Mp = N({ conv2DBackpropInput_: GU });
function WU(r, e, t, n, o, s) {
let a = k(r, "x", "conv2dTranspose"), i = k(e, "filter", "conv2dTranspose");
return Mp(t, a, i, n, o, "NHWC", s);
}
var Cu = N({ conv2dTranspose_: WU });
function UU(r, e, t, n, o = "NDHWC", s = [1, 1, 1]) {
let a = k(r, "x", "conv3d"), i = k(e, "filter", "conv3d"), l = a, u = false;
a.rank === 4 && (u = true, l = F(a, [1, a.shape[0], a.shape[1], a.shape[2], a.shape[3]])), E(l.rank === 5, () => `Error in conv3d: input must be rank 5, but got rank ${l.rank}.`), E(i.rank === 5, () => `Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`), E(l.shape[4] === i.shape[3], () => `Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`), E($r(t, s), () => `Error in conv3D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`), E(o === "NDHWC", () => `Error in conv3d: got dataFormat of ${o} but only NDHWC is currently supported.`);
let c = { x: l, filter: i }, p = { strides: t, pad: n, dataFormat: o, dilations: s }, m = T.runKernel(hl, c, p);
return u ? F(m, [m.shape[1], m.shape[2], m.shape[3], m.shape[4]]) : m;
}
var If = N({ conv3d_: UU });
function jU(r, e, t, n, o) {
E(r.length === e.rank, () => `Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);
let s = r, a = e, i = false;
e.rank === 4 && (i = true, a = F(e, [1, e.shape[0], e.shape[1], e.shape[2], e.shape[3]]), s = [1, r[0], r[1], r[2], r[3]]);
let l = s[4], u = a.shape[4];
E(s.length === 5, () => `Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`), E(a.rank === 5, () => `Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`), E(t.rank === 5, () => `Error in conv3dDerInput: filter must be rank 5, but got rank ${t.rank}`), E(l === t.shape[3], () => `Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${t.shape[3]}.`), E(u === t.shape[4], () => `Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${t.shape[4]}.`);
let c = { dy: a, filter: t }, p = { pad: o, strides: n, inputShape: s }, m = T.runKernel(Yc, c, p);
return i ? F(m, [m.shape[1], m.shape[2], m.shape[3], m.shape[4]]) : m;
}
var Yg = N({ conv3DBackpropInput_: jU });
function HU(r, e, t, n, o) {
let s = k(r, "x", "conv3dTranspose"), a = k(e, "filter", "conv3dTranspose");
return Yg(t, s, a, n, o);
}
var H_ = N({ conv3dTranspose_: HU });
function qU(r) {
let t = { x: k(r, "x", "cos", "float32") };
return T.runKernel(zo, t);
}
var Da = N({ cos_: qU });
function KU(r) {
let t = { x: k(r, "x", "cosh", "float32") };
return T.runKernel(Bo, t);
}
var Iu = N({ cosh_: KU });
function XU(r, e = 0, t = false, n = false) {
let s = { x: k(r, "x", "cumsum") }, a = { axis: e, exclusive: t, reverse: n };
return T.runKernel(Vo, s, a);
}
var Su = N({ cumsum_: XU });
function YU(r, e, t, n = false) {
let o = k(r, "x", "denseBincount"), s = k(e, "weights", "denseBincount");
E(o.dtype === "int32", () => `Error in denseBincount: input dtype must be int32, but got ${o.dtype}`), E(o.rank <= 2, () => `Error in denseBincount: input must be at most rank 2, but got rank ${o.rank}.`), E(t >= 0, () => `size must be non-negative, but got ${t}.`), E(s.size === o.size || s.size === 0, () => `Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${o.shape}, weights shape: ${s.shape}.`);
let a = { x: o, weights: s }, i = { size: t, binaryOutput: n };
return T.runKernel(Zc, a, i);
}
var q_ = N({ denseBincount_: YU });
function ZU(r, e, t = "NHWC") {
let n = k(r, "x", "depthToSpace", "float32"), o = t === "NHWC" ? n.shape[1] : n.shape[2], s = t === "NHWC" ? n.shape[2] : n.shape[3], a = t === "NHWC" ? n.shape[3] : n.shape[1];
E(e > 1, () => `blockSize should be > 1 for depthToSpace, but was: ${e}`), E(o * e >= 0, () => `Negative dimension size caused by overflow when multiplying
${o} and ${e} for depthToSpace with input shape
${n.shape}`), E(s * e >= 0, () => `Negative dimension size caused by overflow when multiplying
${s} and ${e} for depthToSpace with input shape
${n.shape}`), E(a % (e * e) == 0, () => `Dimension size must be evenly divisible by ${e * e} but is ${a} for depthToSpace with input shape ${n.shape}`);
let i = { x: n }, l = { blockSize: e, dataFormat: t };
return T.runKernel(qi, i, l);
}
var Sf = N({ depthToSpace_: ZU });
function JU(r, e, t, n, o = "NHWC", s = [1, 1], a) {
let i = k(r, "x", "depthwiseConv2d", "float32"), l = k(e, "filter", "depthwiseConv2d", "float32"), u = i, c = false;
i.rank === 3 && (c = true, u = F(i, [1, i.shape[0], i.shape[1], i.shape[2]])), E(u.rank === 4, () => `Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`), E(l.rank === 4, () => `Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`), E(u.shape[3] === l.shape[2], () => `Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`), a != null && E(it(n), () => `Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${n}.`);
let p = { x: u, filter: l }, m = { strides: t, pad: n, dataFormat: o, dilations: s, dimRoundingMode: a }, f = T.runKernel(Go, p, m);
return c ? F(f, [f.shape[1], f.shape[2], f.shape[3]]) : f;
}
var $s = N({ depthwiseConv2d_: JU });
function QU(r) {
let t = { x: k(r, "x", "diag") };
return T.runKernel(ep, t);
}
var ej = N({ diag_: QU });
function tj(r, e, t, n, o = [1, 1], s = "NHWC") {
let a = k(r, "x", "dilation2d"), i = k(e, "filter", "dilation2d");
E(a.rank === 3 || a.rank === 4, () => `Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`), E(i.rank === 3, () => `Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`), E(s === "NHWC", () => `Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);
let l = a, u = false;
a.rank === 3 && (l = F(a, [1, a.shape[0], a.shape[1], a.shape[2]]), u = true);
let c = { x: l, filter: i }, p = { strides: t, pad: n, dilations: o }, m = T.runKernel(gl, c, p);
return u ? F(m, [m.shape[1], m.shape[2], m.shape[3]]) : m;
}
var Nf = N({ dilation2d_: tj });
function rj(r, e) {
let t = r.length, n = [];
for (let o = 0; o < t; o++) {
let s = t - 1 - o, a = r[s] || 1;
(e[e.length - 1 - o] || 1) > 1 && a === 1 && n.unshift(s);
}
return n;
}
function It(r, e) {
let t = [];
for (let n = 0; n < e.length; n++) {
let o = r[r.length - n - 1], s = e.length - n - 1, a = e[s];
(o == null || o === 1 && a > 1) && t.unshift(s);
}
return t;
}
function We(r, e) {
let t = [], n = Math.max(r.length, e.length);
for (let o = 0; o < n; o++) {
let s = r[r.length - o - 1];
s == null && (s = 1);
let a = e[e.length - o - 1];
if (a == null && (a = 1), s === 1)
t.unshift(a);
else if (a === 1)
t.unshift(s);
else if (s !== a) {
let i = `Operands could not be broadcast together with shapes ${r} and ${e}.`;
throw Error(i);
} else
t.unshift(s);
}
return t;
}
function nj(r, e) {
let t = k(r, "a", "equal", "string_or_numeric"), n = k(e, "b", "equal", "string_or_numeric");
[t, n] = je(t, n), We(t.shape, n.shape);
let o = { a: t, b: n };
return T.runKernel(Xi, o);
}
var kr = N({ equal_: nj });
function oj(r, e, t) {
let n = k(e, "a", "where"), o = k(t, "b", "where"), s = k(r, "condition", "where", "bool"), a = We(We(s.shape, n.shape), o.shape), i = Aa(s, a), l = Aa(n, a), u = Aa(o, a), c = { condition: i, t: l, e: u };
return T.runKernel(ci, c);
}
var St = N({ where_: oj });
function sj(r) {
let t = { x: k(r, "x", "zerosLike") };
return T.runKernel(hi, t);
}
var Se = N({ zerosLike_: sj });
function ij(r, e) {
let t = k(r, "a", "div"), n = k(e, "b", "div");
[t, n] = je(t, n);
let o = ce(t, n), s = Se(o), a = kr(n, s);
return St(a, s, o);
}
var Tf = N({ divNoNan_: ij });
function aj(r, e) {
let t = k(r, "t1", "dot"), n = k(e, "t2", "dot");
E((t.rank === 1 || t.rank === 2) && (n.rank === 1 || n.rank === 2), () => `Error in dot: inputs must all be rank 1 or 2, but got ranks ${t.rank} and ${n.rank}.`);
let o = t.rank === 1 ? t.size : t.shape[1], s = n.rank === 1 ? n.size : n.shape[0];
if (E(o === s, () => `Error in dot: inner dimensions of inputs must match, but got ${o} and ${s}.`), t.rank === 1 && n.rank === 1) {
let a = F(t, [1, -1]), i = F(n, [-1, 1]), l = ze(a, i);
return F(l, []);
} else if (t.rank === 1 && n.rank === 2) {
let a = F(t, [1, -1]), i = F(n, [n.shape[0], n.shape[1]]), l = ze(a, i);
return F(l, [l.size]);
} else if (t.rank === 2 && n.rank === 1) {
let a = F(n, [-1, 1]), i = ze(t, a);
return F(i, [i.size]);
} else {
let a = F(n, [n.shape[0], n.shape[1]]);
return ze(t, a);
}
}
var K_ = N({ dot_: aj });
function lj(r, ...e) {
let t = e.map((o, s) => k(o, `tensors${s}`, "einsum")), n = { equation: r };
return T.runKernel(tp, t, n);
}
var X_ = N({ einsum_: lj });
function uj(r) {
let t = { x: k(r, "x", "elu", "float32") };
return T.runKernel(Uo, t);
}
var Rs = N({ elu_: uj });
function cj(r) {
let e = k(r, "x", "erf");
E(e.dtype === "int32" || e.dtype === "float32", () => "Input dtype must be `int32` or `float32`."), e.dtype === "int32" && (e = Y(e, "float32"));
let t = { x: e };
return T.runKernel(Ki, t);
}
var Ef = N({ erf_: cj });
function pj(r) {
let t = { x: k(r, "x", "exp") };
return T.runKernel(jo, t);
}
var Kt = N({ exp_: pj });
function mj(r, e = 0) {
let t = k(r, "x", "expandDims", "string_or_numeric");
E(e <= t.rank, () => "Axis must be <= rank of the tensor");
let n = { input: t }, o = { dim: e };
return T.runKernel(oi, n, o);
}
var mr = N({ expandDims_: mj });
function fj(r) {
let t = { x: k(r, "x", "expm1") };
return T.runKernel(Yi, t);
}
var Af = N({ expm1_: fj });
function dj(r, e) {
let t = k(r, "x", "tile", "string_or_numeric");
E(t.rank === e.length, () => `Error in transpose: rank of input ${t.rank} must match length of reps ${e}.`);
let n = { x: t }, o = { reps: e };
return T.runKernel(Hn, n, o);
}
var vr = N({ tile_: dj });
function hj(r, e, t, n = "float32") {
e == null && (e = r);
let o = Ie([r, e], n), s = r <= e ? r : e;
for (let i = 0; i < s; ++i)
o.set(1, i, i);
let a = F(o.toTensor(), [r, e]);
if (t == null)
return a;
if (t.length === 1)
return vr(mr(a, 0), [t[0], 1, 1]);
if (t.length === 2)
return vr(mr(mr(a, 0), 0), [t[0], t[1], 1, 1]);
if (t.length === 3)
return vr(mr(mr(mr(a, 0), 0), 0), [t[0], t[1], t[2], 1, 1]);
throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${t.length}D.`);
}
var Lp = N({ eye_: hj });
function Fs(r, e, t) {
let n = { shape: r, value: e, dtype: t };
return T.runKernel(xl, {}, n);
}
function gj(r) {
let t = { x: k(r, "x", "floor", "float32") };
return T.runKernel(Ho, t);
}
var Os = N({ floor_: gj });
function xj(r, e, t = 0, n = 0) {
let o = k(r, "x", "gather"), s = k(e, "indices", "gather", "int32"), a = { x: o, indices: s }, i = { axis: t, batchDims: n };
return T.runKernel(si, a, i);
}
var uo = N({ gather_: xj });
function yj(r, e) {
let t = k(r, "a", "greater", "string_or_numeric"), n = k(e, "b", "greater", "string_or_numeric");
[t, n] = je(t, n), We(t.shape, n.shape);
let o = { a: t, b: n };
return T.runKernel(Qi, o);
}
var zt = N({ greater_: yj });
function bj(r, e) {
let t = k(r, "a", "greaterEqual", "string_or_numeric"), n = k(e, "b", "greaterEqual", "string_or_numeric");
[t, n] = je(t, n), We(t.shape, n.shape);
let o = { a: t, b: n };
return T.runKernel(Xo, o);
}
var kn = N({ greaterEqual_: bj });
function wj(r) {
let t = { input: k(r, "input", "imag") };
return T.runKernel(sp, t);
}
var Nu = N({ imag_: wj });
function _j(r) {
let t = { x: k(r, "x", "isFinite") };
return T.runKernel(ea, t);
}
var Y_ = N({ isFinite_: _j });
function kj(r) {
let t = { x: k(r, "x", "isInf") };
return T.runKernel(ta, t);
}
var Z_ = N({ isInf_: kj });
function vj(r) {
let t = { x: k(r, "x", "isNaN") };
return T.runKernel(ra, t);
}
var Df = N({ isNaN_: vj });
function Cj(r, e = 0.2) {
let n = { x: k(r, "x", "leakyRelu") }, o = { alpha: e };
return T.runKernel(Yo, n, o);
}
var $a = N({ leakyRelu_: Cj });
function Ij(r, e) {
let t = k(r, "a", "less", "string_or_numeric"), n = k(e, "b", "less", "string_or_numeric");
[t, n] = je(t, n), We(t.shape, n.shape);
let o = { a: t, b: n };
return T.runKernel(na, o);
}
var Tu = N({ less_: Ij });
function Sj(r, e) {
let t = k(r, "a", "lessEqual", "string_or_numeric"), n = k(e, "b", "lessEqual", "string_or_numeric");
[t, n] = je(t, n), We(t.shape, n.shape);
let o = { a: t, b: n };
return T.runKernel(oa, o);
}
var vn = N({ lessEqual_: Sj });
function J_(r, e, t) {
if (t <= 0)
throw new Error("The number of values should be positive.");
let n = { start: r, stop: e, num: t };
return T.runKernel(ip, {}, n);
}
function Nj(r, e = 5, t = 1, n = 1, o = 0.5) {
let s = k(r, "x", "localResponseNormalization");
E(s.rank === 4 || s.rank === 3, () => `Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${s.rank}.`), E(it(e), () => `Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${e}.`);
let a = s, i = false;
s.rank === 3 && (i = true, a = F(s, [1, s.shape[0], s.shape[1], s.shape[2]]));
let l = { x: a }, u = { depthRadius: e, bias: t, alpha: n, beta: o }, c = T.runKernel(yl, l, u);
return i ? F(c, [c.shape[1], c.shape[2], c.shape[3]]) : c;
}
var $f = N({ localResponseNormalization_: Nj });
function Tj(r) {
let t = { x: k(r, "x", "log", "float32") };
return T.runKernel(Zo, t);
}
var xr = N({ log_: Tj });
function Ej(r) {
let t = { x: k(r, "x", "log1p") };
return T.runKernel(sa, t);
}
var Ra = N({ log1p_: Ej });
function Aj(r) {
return E(Qs(r), () => "The f passed in grad(f) must be a function"), (e, t) => {
let n = k(e, "x", "tf.grad", "string_or_numeric"), o = t != null ? k(t, "dy", "tf.grad") : null;
return T.tidy(() => {
let { value: s, grads: a } = T.gradients(() => r(n), [n], o);
return o != null && Rt(s.shape, o.shape, "The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"), Jg(a), a[0];
});
};
}
function Dj(r) {
return E(Qs(r), () => "The f passed in grads(f) must be a function"), (e, t) => {
E(Array.isArray(e), () => "The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");
let n = va(e, "args", "tf.grads", "string_or_numeric"), o = t != null ? k(t, "dy", "tf.grads") : null;
return T.tidy(() => {
let { value: s, grads: a } = T.gradients(() => r(...n), n, o);
return o != null && Rt(s.shape, o.shape, "The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"), Jg(a), a;
});
};
}
function $j(r) {
return E(Qs(r), () => "The f passed in valueAndGrad(f) must be a function"), (e, t) => {
E(e instanceof Le, () => "The x passed in valueAndGrad(f)(x) must be a tensor"), E(t == null || t instanceof Le, () => "The dy passed in valueAndGrad(f)(x, dy) must be a tensor");
let { grads: n, value: o } = T.gradients(() => r(e), [e], t);
return Jg(n), { grad: n[0], value: o };
};
}
function Rj(r) {
return E(Qs(r), () => "The f passed in valueAndGrads(f) must be a function"), (e, t) => {
E(Array.isArray(e) && e.every((o) => o instanceof Le), () => "The args passed in valueAndGrads(f)(args) must be array of tensors"), E(t == null || t instanceof Le, () => "The dy passed in valueAndGrads(f)(args, dy) must be a tensor");
let n = T.gradients(() => r(...e), e, t);
return t != null && Rt(n.value.shape, t.shape, "The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"), Jg(n.grads), n;
};
}
function Zg(r, e) {
E(Qs(r), () => "The f passed in variableGrads(f) must be a function"), E(e == null || Array.isArray(e) && e.every((u) => u instanceof Sl), () => "The varList passed in variableGrads(f, varList) must be an array of variables");
let t = e != null;
if (!t) {
e = [];
for (let u in T.registeredVariables)
e.push(T.registeredVariables[u]);
}
let n = t ? e.filter((u) => !u.trainable) : null, o = e.length;
e = e.filter((u) => u.trainable), E(e.length > 0, () => `variableGrads() expects at least one of the input variables to be trainable, but none of the ${o} variables is trainable.`);
let s = true, { value: a, grads: i } = T.gradients(r, e, null, s);
E(i.some((u) => u != null), () => "Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."), E(a.rank === 0, () => `The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);
let l = {};
return e.forEach((u, c) => {
i[c] != null && (l[u.name] = i[c]);
}), n != null && n.forEach((u) => l[u.name] = null), { value: a, grads: l };
}
function on(r) {
return T.customGrad(r);
}
function Jg(r) {
if (r.filter((t) => t == null).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.`);
}
function Fj(r) {
let t = { x: k(r, "x", "neg") };
return T.runKernel(ii, t);
}
var He = N({ neg_: Fj });
function Oj(r) {
let t = { x: k(r, "x", "softplus") };
return T.runKernel(ya, t);
}
var co = N({ softplus_: Oj });
function Pj(r) {
let e = k(r, "x", "logSigmoid");
return on((n) => ({ value: He(co(He(n))), gradFunc: (a) => O(a, zr(He(n))) }))(e);
}
var Q_ = N({ logSigmoid_: Pj });
function Mj(r, e = null, t = false) {
let o = { x: k(r, "x", "max") }, s = { reductionIndices: e, keepDims: t };
return T.runKernel(Jo, o, s);
}
var Rr = N({ max_: Mj });
function Lj(r, e) {
let t = k(r, "a", "sub"), n = k(e, "b", "sub");
[t, n] = je(t, n);
let o = { a: t, b: n };
return T.runKernel(ks, o);
}
var le = N({ sub_: Lj });
function zj(r, e = null, t = false) {
let n = k(r, "x", "sum");
n.dtype === "bool" && (n = Y(n, "int32"));
let o = { x: n }, s = { axis: e, keepDims: t };
return T.runKernel(bs, o, s);
}
var me = N({ sum_: zj });
function Bj(r, e = -1) {
let t = k(r, "logits", "logSoftmax");
if (e === -1 && (e = t.rank - 1), e !== t.rank - 1)
throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and axis was ${e}`);
return on((o, s) => {
let a = true, i = Rr(o, e, true), l = le(o, i), u = le(Y(l, "float32"), xr(me(Kt(l), e, a)));
return s([u]), { value: u, gradFunc: (p, m) => {
let [f] = m, d = true, h = Kt(f);
return le(p, O(me(p, e, d), h));
} };
})(t);
}
var Eu = N({ logSoftmax_: Bj });
function ek(r, e) {
for (let t = 0; t < r.length; ++t)
if (r[r.length - t - 1] !== e - 1 - t)
return false;
return true;
}
function F1(r, e, t) {
let n = r.length + e.length, o = [], s = 0, a = 0;
for (let i = 0; i < n; i++)
t.indexOf(i) === -1 ? o.push(r[s++]) : o.push(e[a++]);
return o;
}
function tk(r, e) {
let t = [], n = r.length;
for (let s = 0; s < n; s++)
e.indexOf(s) === -1 && t.push(r[s]);
let o = e.map((s) => r[s]);
return [t, o];
}
function po(r, e) {
let t = e.map((n) => 1);
return F1(r, t, e);
}
function Vj(r, e, t) {
E(ek(e, t), () => `${r} supports only inner-most axes for now. Got axes ${e} and rank-${t} input.`);
}
function rk(r, e) {
if (ek(r, e))
return null;
let t = [];
for (let n = 0; n < e; ++n)
r.indexOf(n) === -1 && t.push(n);
return r.forEach((n) => t.push(n)), t;
}
function Rf(r) {
return r.map((e, t) => [t, e]).sort((e, t) => e[1] - t[1]).map((e) => e[0]);
}
function Gj(r, e) {
let t = [];
for (let n = e - r; n < e; ++n)
t.push(n);
return t;
}
function Wj(r, e = null, t = false) {
let n = k(r, "x", "logSumExp"), o = cr(e, n.shape), s = Rr(n, o, true), a = le(n, s), i = Kt(a), l = me(i, o), u = xr(l), c = Z(F(s, u.shape), u);
if (t) {
let p = po(c.shape, o);
return F(c, p);
}
return c;
}
var Ff = N({ logSumExp_: Wj });
function Uj(r, e) {
let t = k(r, "a", "logicalAnd", "bool"), n = k(e, "b", "logicalAnd", "bool");
We(t.shape, n.shape);
let o = { a: t, b: n };
return T.runKernel(ia, o);
}
var Cr = N({ logicalAnd_: Uj });
function jj(r) {
let t = { x: k(r, "x", "logicalNot", "bool") };
return T.runKernel(au, t);
}
var Fa = N({ logicalNot_: jj });
function Hj(r, e) {
let t = k(r, "a", "logicalOr", "bool"), n = k(e, "b", "logicalOr", "bool");
We(t.shape, n.shape);
let o = { a: t, b: n };
return T.runKernel(lu, o);
}
var Au = N({ logicalOr_: Hj });
function qj(r, e) {
let t = k(r, "a", "logicalXor", "bool"), n = k(e, "b", "logicalXor", "bool");
return We(t.shape, n.shape), Cr(Au(r, e), Fa(Cr(r, e)));
}
var nk = N({ logicalXor_: qj });
function Kj(r, e, t, n, o) {
let s = k(r, "x", "maxPool"), a = 1, i = s, l = false;
s.rank === 3 && (l = true, i = F(s, [1, s.shape[0], s.shape[1], s.shape[2]])), E(i.rank === 4, () => `Error in maxPool: input must be rank 4 but got rank ${i.rank}.`), E($r(t, a), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`), o != null && E(it(n), () => `Error in maxPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);
let u = { x: i }, c = { filterSize: e, strides: t, pad: n, dimRoundingMode: o }, p = T.runKernel(es, u, c);
return l ? F(p, [p.shape[1], p.shape[2], p.shape[3]]) : p;
}
var Oa = N({ maxPool_: Kj });
function Xj(r, e = [1, 1, 1], t, n, o, s = "NDHWC") {
let a = k(r, "x", "maxPool3d"), i = a, l = false;
a.rank === 4 && (l = true, i = F(a, [1, a.shape[0], a.shape[1], a.shape[2], a.shape[3]])), E(i.rank === 5, () => `Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`), E(s === "NDHWC", () => `Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`), o != null && E(it(n), () => `Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);
let u = { x: i }, c = { filterSize: e, strides: t, pad: n, dimRoundingMode: o, dataFormat: s }, p = T.runKernel(bl, u, c);
return l ? F(p, [p.shape[1], p.shape[2], p.shape[3], p.shape[4]]) : p;
}
var Of = N({ maxPool3d_: Xj });
function Yj(r, e, t, n, o = false) {
let a = { x: k(r, "x", "maxPoolWithArgmax") }, i = { filterSize: e, strides: t, pad: n, includeBatchInIndex: o }, l = T.runKernel(cp, a, i);
return { result: l[0], indexes: l[1] };
}
var ok = N({ maxPoolWithArgmax_: Yj });
function Zj(r, e) {
let t = k(r, "a", "maximum"), n = k(e, "b", "maximum");
[t, n] = je(t, n), t.dtype === "bool" && (t = Y(t, "int32"), n = Y(n, "int32")), We(t.shape, n.shape);
let o = { a: t, b: n };
return T.runKernel(Qo, o);
}
var sn = N({ maximum_: Zj });
function Jj(r, e = null, t = false) {
let o = { x: k(r, "x", "mean") }, s = { axis: e, keepDims: t };
return T.runKernel(ts, o, s);
}
var xt = N({ mean_: Jj });
function yt(r, e = "float32") {
if (e === "complex64") {
let n = yt(r, "float32"), o = yt(r, "float32");
return Pn(n, o);
}
let t = Gc(st(r), e);
return T.makeTensor(t, r, e);
}
function or(r, e = "float32") {
if (e === "complex64") {
let n = or(r, "float32"), o = yt(r, "float32");
return Pn(n, o);
}
let t = Zm(st(r), e);
return T.makeTensor(t, r, e);
}
function Qj(r, e, { indexing: t = "xy" } = {}) {
if (t !== "xy" && t !== "ij")
throw new TypeError(`${t} is not a valid third argument to meshgrid`);
if (r === void 0)
return [];
let n = k(r, "x", "meshgrid", r instanceof Le ? r.dtype : "float32");
if (e === void 0)
return [n];
let o = k(e, "y", "meshgrid", e instanceof Le ? e.dtype : "float32"), s = st(n.shape), a = st(o.shape);
return t === "xy" ? (n = F(n, [1, -1]), o = F(o, [-1, 1]), [ze(or([a, 1], n.dtype), n), ze(o, or([1, s], o.dtype))]) : (n = F(n, [-1, 1]), o = F(o, [1, -1]), [ze(n, or([1, a], n.dtype)), ze(or([s, 1], o.dtype), o)]);
}
function eH(r, e = null, t = false) {
let o = { x: k(r, "x", "min") }, s = { axis: e, keepDims: t };
return T.runKernel(rs, o, s);
}
var Al = N({ min_: eH });
function tH(r, e) {
let t = k(r, "a", "minimum"), n = k(e, "b", "minimum");
[t, n] = je(t, n), t.dtype === "bool" && (t = Y(t, "int32"), n = Y(n, "int32")), We(t.shape, n.shape);
let o = { a: t, b: n };
return T.runKernel(ns, o);
}
var Ps = N({ minimum_: tH });
function rH(r, e, t) {
E(t === "reflect" || t === "symmetric", () => `Invalid mode. Mode must be either reflect or symmetric. Got ${t}.`);
let n = k(r, "x", "mirrorPad");
if (n.rank === 0)
throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");
E(e.length === n.rank, () => `Padding doesn't match input. Must be ${n.rank}. Got ${e.length}.`);
let o = t === "reflect" ? 1 : 0;
for (let i = 0; i < n.rank; i++)
E(e[i].length === 2, () => "Invalid number of paddings. Must be length of 2 each."), E(e[i][0] >= 0 && e[i][0] <= n.shape[i] - o && e[i][1] >= 0 && e[i][1] <= n.shape[i] - o, () => `Padding in dimension ${i} cannot be greater than or equal to ${n.shape[i] - o} or less than 0 for input of shape ${n.shape}`);
let s = { paddings: e, mode: t }, a = { x: n };
return T.runKernel(os, a, s);
}
var Pf = N({ mirrorPad_: rH });
function nH(r, e) {
let t = k(r, "a", "mod"), n = k(e, "b", "mod");
[t, n] = je(t, n);
let o = { a: t, b: n };
return T.runKernel(aa, o);
}
var Mf = N({ mod_: nH });
function oH(r) {
let e = k(r, "x", "square"), t = {};
return T.runKernel("Square", { x: e }, t);
}
var Ve = N({ square_: oH });
function sH(r, e = null, t = false) {
r = k(r, "x", "moments");
let n = cr(e, r.shape), o = xt(r, n, t), s = o.shape;
t || (s = po(o.shape, n));
let a = Ve(le(Y(r, "float32"), F(o, s))), i = xt(a, n, t);
return { mean: o, variance: i };
}
var zp = N({ moments_: sH });
function iH(r, e, t, n) {
let o = k(e, "data", "multiRNNCell"), s = va(t, "c", "multiRNNCell"), a = va(n, "h", "multiRNNCell"), i = o, l = [];
for (let p = 0; p < r.length; p++) {
let m = r[p](i, s[p], a[p]);
l.push(m[0]), l.push(m[1]), i = m[1];
}
let u = [], c = [];
for (let p = 0; p < l.length; p += 2)
u.push(l[p]), c.push(l[p + 1]);
return [u, c];
}
var aH = N({ multiRNNCell_: iH });
function lH(r, e, t, n = false) {
let o = k(r, "logits", "multinomial"), s = o.size, a = o.rank;
if (s < 2)
throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);
if (a > 2)
throw new Error(`Rank of probabilities must be 1 or 2, but is ${a}`);
t = t || Math.random();
let l = { logits: a === 1 ? F(o, [1, -1]) : o }, u = { numSamples: e, seed: t, normalized: n }, c = T.runKernel(pp, l, u);
return a === 1 ? F(c, [c.size]) : c;
}
var sk = N({ multinomial_: lH });
function uH(r, e) {
let t = k(r, "a", "notEqual", "string_or_numeric"), n = k(e, "b", "notEqual", "string_or_numeric");
[t, n] = je(t, n), We(t.shape, n.shape);
let o = { a: t, b: n };
return T.runKernel(la, o);
}
var mo = N({ notEqual_: uH });
function cH(r) {
let t = { x: k(r, "x", "onesLike") };
return T.runKernel(ai, t);
}
var fr = N({ onesLike_: cH });
function pH(r, e) {
let t = k(r, "v1", "outerProduct"), n = k(e, "v2", "outerProduct");
E(t.rank === 1 && n.rank === 1, () => `Error in outerProduct: inputs must be rank 1, but got ranks ${t.rank} and ${n.rank}.`);
let o = F(t, [-1, 1]), s = F(n, [1, -1]);
return ze(o, s);
}
var mH = N({ outerProduct_: pH });
function fH(r, e, t = 0) {
let n = k(r, "x", "pad");
if (n.rank === 0)
throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");
let o = { paddings: e, constantValue: t }, s = { x: n };
return T.runKernel(as, s, o);
}
var jr = N({ pad_: fH });
function dH(r, e, t = 0) {
return E(e.length === 2, () => "Invalid number of paddings. Must be length of 2."), jr(r, [e], t);
}
var hH = N({ pad1d_: dH });
function gH(r, e, t = 0) {
return E(e.length === 2 && e[0].length === 2 && e[1].length === 2, () => "Invalid number of paddings. Must be length of 2 each."), jr(r, e, t);
}
var xH = N({ pad2d_: gH });
function yH(r, e, t = 0) {
return E(e.length === 3 && e[0].length === 2 && e[1].length === 2 && e[2].length === 2, () => "Invalid number of paddings. Must be length of 2 each."), jr(r, e, t);
}
var bH = N({ pad3d_: yH });
function wH(r, e, t = 0) {
return E(e.length === 4 && e[0].length === 2 && e[1].length === 2 && e[2].length === 2 && e[3].length === 2, () => "Invalid number of paddings. Must be length of 2 each."), jr(r, e, t);
}
var _H = N({ pad4d_: wH });
function kH(r, e, t) {
let n = k(r, "x", "spaceToBatchND");
E(n.rank >= 1 + e.length, () => `input rank ${n.rank} should be > than [blockShape] ${e.length}`), E(t.length === e.length, () => `paddings.shape[0] ${t.length} must be equal to [blockShape] ${e.length}`), E(n.shape.reduce((a, i, l) => l > 0 && l <= e.length ? a && (i + t[l - 1][0] + t[l - 1][1]) % e[l - 1] == 0 : a, true), () => `input spatial dimensions ${n.shape.slice(1)} with paddings ${t.toString()} must be divisible by blockShapes ${e.toString()}`);
let o = { x: n }, s = { blockShape: e, paddings: t };
return T.runKernel(mi, o, s);
}
var Pa = N({ spaceToBatchND_: kH });
function vH(r, e, t, n, o, s) {
o == null && (o = [1, 1]), s == null && (s = 1), n === 0 && (n = "valid");
let a = k(r, "x", "maxPool"), i = a, l = false;
a.rank === 3 && (l = true, i = F(a, [1, a.shape[0], a.shape[1], a.shape[2]])), E($r(s, o), () => `Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`);
let u = O_(i.shape, e, s, o, n), c = [u.dilationHeight, u.dilationWidth], p;
n === "same" ? p = IH([u.filterHeight, u.filterWidth], c) : p = [[0, 0], [0, 0]];
let m = c[0] === 1 && c[1] === 1, [f, d] = CH([u.inHeight, u.inWidth], c, p), h = m ? n : "valid", g = m ? i : Pa(i, c, f), y = (t === "avg" ? () => Ta(g, e, s, h) : () => Oa(g, e, s, h))(), w = m ? y : Ea(y, c, d);
return l ? F(w, [w.shape[1], w.shape[2], w.shape[3]]) : w;
}
function CH(r, e, t) {
let n = t.map((c) => c[0]), o = t.map((c) => c[1]), s = r.concat(n, o), a = e.map((c, p) => (c - s[p] % c) % c), i = o.map((c, p) => c + a[p]), l = e.map((c, p) => [n[p], i[p]]), u = e.map((c, p) => [0, a[p]]);
return [l, u];
}
function IH(r, e) {
let n = r.map((a, i) => a + (a - 1) * (e[i] - 1)).map((a) => a - 1), o = n.map((a) => Math.floor(a / 2)), s = n.map((a, i) => a - o[i]);
return n.map((a, i) => [o[i], s[i]]);
}
var ik = N({ pool_: vH });
function SH(r, e) {
let t = k(r, "base", "pow"), n = k(e, "exp", "pow");
[t, n] = je(t, n);
let o = { a: t, b: n };
return T.runKernel(ls, o);
}
var Hr = N({ pow_: SH });
function NH(r, e) {
let t = k(r, "x", "prelu"), n = k(e, "alpha", "prelu"), o = { x: t, alpha: n };
return T.runKernel(us, o);
}
var Ma = N({ prelu_: NH });
function TH(r, e = null, t = false) {
let n = k(r, "x", "prod");
n.dtype === "bool" && (n = Y(n, "int32"));
let o = { x: n }, s = { axis: e, keepDims: t };
return T.runKernel(ma, o, s);
}
var Du = N({ prod_: TH });
function EH(r, e, t) {
let n = st(r), o = null;
if (t == null || t === "float32")
o = new Float32Array(n);
else if (t === "int32")
o = new Int32Array(n);
else if (t === "bool")
o = new Uint8Array(n);
else
throw new Error(`Unknown data type ${t}`);
for (let s = 0; s < n; s++)
o[s] = e();
return T.makeTensor(o, r, t);
}
var AH = N({ rand_: EH });
var ex = ou(dk());
var Bp = class {
constructor(e, t, n, o, s) {
this.mean = e, this.stdDev = t, this.dtype = n, this.nextVal = NaN, this.truncated = o, this.truncated && (this.upper = this.mean + this.stdDev * 2, this.lower = this.mean - this.stdDev * 2);
let a = s || Math.random();
this.random = ex.alea(a.toString());
}
nextValue() {
if (!isNaN(this.nextVal)) {
let o = this.nextVal;
return this.nextVal = NaN, o;
}
let e, t, n = false;
for (; !n; ) {
let o, s, a;
do
o = 2 * this.random() - 1, s = 2 * this.random() - 1, a = o * o + s * s;
while (a >= 1 || a === 0);
let i = Math.sqrt(-2 * Math.log(a) / a);
e = this.mean + this.stdDev * o * i, t = this.mean + this.stdDev * s * i, (!this.truncated || this.isValidTruncated(e)) && (n = true);
}
return (!this.truncated || this.isValidTruncated(t)) && (this.nextVal = this.convertValue(t)), this.convertValue(e);
}
convertValue(e) {
return this.dtype == null || this.dtype === "float32" ? e : Math.round(e);
}
isValidTruncated(e) {
return e <= this.upper && e >= this.lower;
}
};
var hk = class {
constructor(e, t, n, o) {
this.alpha = e, this.beta = 1 / t, this.dtype = n;
let s = o || Math.random();
this.randu = ex.alea(s.toString()), this.randn = new Bp(0, 1, n, false, this.randu()), e < 1 ? this.d = e + 2 / 3 : this.d = e - 1 / 3, this.c = 1 / Math.sqrt(9 * this.d);
}
nextValue() {
let e, t, n, o, s, a;
for (; ; ) {
do
o = this.randn.nextValue(), a = 1 + this.c * o;
while (a <= 0);
if (a *= a * a, e = o * o, t = 1 - 0.331 * e * e, n = 0.5 * e + this.d * (1 - a + Math.log(a)), s = this.randu(), s < t || Math.log(s) < n)
break;
}
return a = 1 / this.beta * this.d * a, this.alpha < 1 && (a *= Math.pow(this.randu(), 1 / this.alpha)), this.convertValue(a);
}
convertValue(e) {
return this.dtype === "float32" ? e : Math.round(e);
}
};
var gk = class {
constructor(e = 0, t = 1, n, o) {
if (this.canReturnFloat = () => this.dtype == null || this.dtype === "float32", this.min = e, this.range = t - e, this.dtype = n, o == null && (o = Math.random()), typeof o == "number" && (o = o.toString()), !this.canReturnFloat() && this.range <= 1)
throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);
this.random = ex.alea(o);
}
convertValue(e) {
return this.canReturnFloat() ? e : Math.round(e);
}
nextValue() {
return this.convertValue(this.min + this.range * this.random());
}
};
function MH(r, e, t = 1, n = "float32", o) {
if (t == null && (t = 1), n == null && (n = "float32"), n !== "float32" && n !== "int32")
throw new Error(`Unsupported data type ${n}`);
let s = new hk(e, t, n, o), a = Ie(r, n);
for (let i = 0; i < a.values.length; i++)
a.values[i] = s.nextValue();
return a.toTensor();
}
var LH = N({ randomGamma_: MH });
function zH(r, e = 0, t = 1, n, o) {
if (n != null && n === "bool")
throw new Error(`Unsupported data type ${n}`);
let s = new Bp(e, t, n, false, o), a = Ie(r, n);
for (let i = 0; i < a.values.length; i++)
a.values[i] = s.nextValue();
return a.toTensor();
}
var tx = N({ randomNormal_: zH });
function BH(r, e = 0, t = 1, n = "float32", o) {
let s = Ie(r, n), a = new gk(e, t, null, o);
for (let i = 0; i < s.values.length; i++)
s.values[i] = a.nextValue();
return s.toTensor();
}
var Ms = N({ randomUniform_: BH });
function La(r, e, t = 1, n = "float32") {
if (t === 0)
throw new Error("Cannot have a step of zero");
let o = { start: r, stop: e, step: t, dtype: n };
return T.runKernel(wl, {}, o);
}
function VH(r) {
let t = { input: k(r, "input", "real") };
return T.runKernel(mp, t);
}
var Dl = N({ real_: VH });
function GH(r) {
let t = { x: k(r, "x", "reciprocal") };
return T.runKernel(fa, t);
}
var Lf = N({ reciprocal_: GH });
function WH(r) {
let t = { x: k(r, "x", "relu") };
return T.runKernel(cs, t);
}
var Ir = N({ relu_: WH });
function UH(r) {
let t = { x: k(r, "x", "relu6") };
return T.runKernel(ms, t);
}
var Ru = N({ relu6_: UH });
function jH(r, e) {
let n = { x: k(r, "x", "reverse") }, o = { dims: e };
return T.runKernel(fs, n, o);
}
var er = N({ reverse_: jH });
function HH(r) {
let e = k(r, "x", "reverse");
return E(e.rank === 1, () => `Error in reverse1D: x must be rank 1 but got rank ${e.rank}.`), er(e, 0);
}
var qH = N({ reverse1d_: HH });
function KH(r, e) {
let t = k(r, "x", "reverse");
return E(t.rank === 2, () => `Error in reverse2D: x must be rank 2 but got rank ${t.rank}.`), er(t, e);
}
var XH = N({ reverse2d_: KH });
function YH(r, e) {
let t = k(r, "x", "reverse");
return E(t.rank === 3, () => `Error in reverse3D: x must be rank 3 but got rank ${t.rank}.`), er(t, e);
}
var ZH = N({ reverse3d_: YH });
function JH(r, e) {
let t = k(r, "x", "reverse");
return E(t.rank === 4, () => `Error in reverse4D: x must be rank 4 but got rank ${t.rank}.`), er(t, e);
}
var QH = N({ reverse4d_: JH });
function eq(r) {
let t = { x: k(r, "x", "round") };
return T.runKernel(ds, t);
}
var Fu = N({ round_: eq });
function tq(r) {
let t = { x: k(r, "x", "rsqrt", "float32") };
return T.runKernel(hs, t);
}
var Ou = N({ rsqrt_: tq });
function pe(r, e) {
if ((dr(r) && e !== "string" || Array.isArray(r)) && e !== "complex64")
throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");
if (e === "string" && dr(r) && !(r instanceof Uint8Array))
throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");
return tn(r, [], [], e);
}
function rq(r) {
let t = { x: k(r, "x", "selu") };
return T.runKernel(ha, t);
}
var Pu = N({ selu_: rq });
function nq(r, e, t, n, o, s = [1, 1], a = "NHWC") {
let i = k(r, "x", "separableConv2d"), l = k(e, "depthwiseFilter", "separableConv2d"), u = k(t, "pointwiseFilter", "separableConv2d"), c = i, p = false;
if (i.rank === 3 && (p = true, c = F(i, [1, i.shape[0], i.shape[1], i.shape[2]])), a === "NCHW")
throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");
E(c.rank === 4, () => `Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`), E(l.rank === 4, () => `Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`), E(u.rank === 4, () => `Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`), E(u.shape[0] === 1, () => `Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`), E(u.shape[1] === 1, () => `Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);
let m = l.shape[2], f = l.shape[3];
E(u.shape[2] === m * f, () => `Error in separableConv2d: the third dimension of pointwise filter must be ${m * f}, but got ${u.shape[2]}.`);
let d = $s(c, l, n, o, a, s), g = nn(d, u, 1, "valid", a);
return p ? F(g, [g.shape[1], g.shape[2], g.shape[3]]) : g;
}
var zf = N({ separableConv2d_: nq });
async function oq(r, e) {
let t = k(r, "x", "setdiff1d"), n = k(e, "y", "setdiff1d");
E(t.dtype === n.dtype, () => `x and y should have the same dtype, but got x (${t.dtype}) and y (${n.dtype}).`), E(t.rank === 1, () => `x should be 1D tensor, but got x (${t.shape}).`), E(n.rank === 1, () => `y should be 1D tensor, but got y (${n.shape}).`);
let o = await t.data(), s = await n.data(), a = new Set(s), i = 0;
for (let c = 0; c < o.length; c++)
a.has(o[c]) || i++;
let l = new mt([i], t.dtype), u = new mt([i], "int32");
for (let c = 0, p = 0; c < o.length; c++)
a.has(o[c]) || (l.values[p] = o[c], u.values[p] = c, p++);
return [l.toTensor(), u.toTensor()];
}
var xk = oq;
function sq(r) {
let t = { x: k(r, "x", "sign") };
return T.runKernel(xa, t);
}
var Bf = N({ sign_: sq });
function iq(r) {
let t = { x: k(r, "x", "sin", "float32") };
return T.runKernel(gs, t);
}
var Mu = N({ sin_: iq });
function aq(r) {
let t = { x: k(r, "x", "sinh") };
return T.runKernel(ga, t);
}
var Lu = N({ sinh_: aq });
function lq(r, e, t) {
let n = k(r, "x", "slice1d");
return E(n.rank === 1, () => `slice1d expects a rank-1 tensor, but got a rank-${n.rank} tensor`), Oe(n, [e], [t]);
}
var Vf = N({ slice1d_: lq });
function uq(r, e, t) {
let n = k(r, "x", "slice2d");
return E(n.rank === 2, () => `slice2d expects a rank-2 tensor, but got a rank-${n.rank} tensor`), Oe(n, e, t);
}
var rx = N({ slice2d_: uq });
function cq(r, e, t) {
let n = k(r, "x", "slice3d");
return E(n.rank === 3, () => `slice3d expects a rank-3 tensor, but got a rank-${n.rank} tensor`), Oe(n, e, t);
}
var Gf = N({ slice3d_: cq });
function pq(r, e, t) {
let n = k(r, "x", "slice4d");
return E(n.rank === 4, () => `slice4d expects a rank-4 tensor, but got a rank-${n.rank} tensor`), Oe(n, e, t);
}
var Vp = N({ slice4d_: pq });
function mq(r, e = -1) {
let t = k(r, "logits", "softmax", "float32");
if (e === -1 && (e = t.rank - 1), e !== t.rank - 1)
throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and dim was ${e}`);
let n = { logits: t }, o = { dim: e };
return T.runKernel(ws, n, o);
}
var za = N({ softmax_: mq });
function fq(r) {
E(r.dtype === "complex64", () => `The dtype for tf.spectral.fft() must be complex64 but got ${r.dtype}.`);
let e = { input: r };
return T.runKernel(np, e);
}
var Ba = N({ fft_: fq });
function dq(r) {
E(r.dtype === "complex64", () => `The dtype for tf.spectral.ifft() must be complex64 but got ${r.dtype}.`);
let e = { input: r };
return T.runKernel(op, e);
}
var _i = N({ ifft_: dq });
function hq(r) {
let e = r.shape[r.shape.length - 1], t = r.size / e, n;
if (e <= 2) {
let o = F(r, [t, e]);
n = _i(o);
} else {
let o = [t, 2 * (e - 1)], s = F(Dl(r), [t, e]), a = F(Nu(r), [t, e]), i = er(Oe(s, [0, 1], [t, e - 2]), 1), l = O(er(Oe(a, [0, 1], [t, e - 2]), 1), pe(-1)), u = tt([s, i], 1), c = tt([a, l], 1), p = F(Pn(u, c), [o[0], o[1]]);
n = _i(p);
}
if (n = Dl(n), r.rank === 3 && r.shape[0] !== 0) {
let o = n, s = r.shape[0];
n = F(n, [s, n.shape[0] / s, n.shape[1]]), o.dispose();
}
return n;
}
var zu = N({ irfft_: hq });
function gq(r, e, t = 0) {
let o = { x: k(r, "x", "split") }, s = { numOrSizeSplits: e, axis: t };
return T.runKernel(fi, o, s);
}
var sr = N({ split_: gq });
function xq(r, e) {
E(r.dtype === "float32", () => `The dtype for rfft() must be real value but got ${r.dtype}`);
let t = r.shape[r.shape.length - 1], n = r.size / t, o;
if (e != null && e < t) {
let d = r.shape.map((g) => 0), h = r.shape.map((g) => g);
h[r.shape.length - 1] = e, o = Oe(r, d, h), t = e;
} else if (e != null && e > t) {
let d = r.shape.map((h) => h);
d[r.shape.length - 1] = e - t, o = tt([r, yt(d)], r.shape.length - 1), t = e;
} else
o = r;
let s = Se(o), a = F(Pn(o, s), [n, t]), i = Ba(a), l = Math.floor(t / 2) + 1, u = Dl(i), c = Nu(i), p = sr(u, [l, t - l], u.shape.length - 1), m = sr(c, [l, t - l], c.shape.length - 1), f = o.shape.slice();
return f[o.shape.length - 1] = l, F(Pn(p[0], m[0]), f);
}
var Va = N({ rfft_: xq });
function yq(r) {
let t = { x: k(r, "x", "sqrt", "float32") };
return T.runKernel(ys, t);
}
var bt = N({ sqrt_: yq });
function bq(r, e) {
let t = k(r, "a", "squaredDifference"), n = k(e, "b", "squaredDifference");
[t, n] = je(t, n), We(t.shape, n.shape);
let o = { a: t, b: n }, s = {};
return T.runKernel(_s, o, s);
}
var Bu = N({ squaredDifference_: bq });
function wq(r, e) {
let t = k(r, "x", "squeeze");
return F(t, Ww(t.shape, e).newShape);
}
var Br = N({ squeeze_: wq });
function _q(r, e = 0) {
let t = va(r, "tensors", "stack", "string_or_numeric");
E(t.length >= 1, () => "Pass at least one tensor to tf.stack"), t.length > 0 && E(e <= t[0].rank, () => "Axis must be <= rank of the tensor");
let n = t, o = { axis: e };
return T.runKernel(li, n, o);
}
var Xt = N({ stack_: _q });
function kq(r, e = 0) {
let n = { x: k(r, "x", "step") }, o = { alpha: e };
return T.runKernel(no, n, o);
}
var Ls = N({ step_: kq });
function vq(r, e, t, n, o = 0, s = 0, a = 0, i = 0, l = 0) {
let c = { x: k(r, "x", "stridedSlice", "string_or_numeric") }, p = { begin: e, end: t, strides: n, beginMask: o, endMask: s, ellipsisMask: a, newAxisMask: i, shrinkAxisMask: l };
return T.runKernel(ba, c, p);
}
var Wf = N({ stridedSlice_: vq });
function Cq(r) {
let t = { x: k(r, "x", "tan", "float32") };
return T.runKernel(vs, t);
}
var Uf = N({ tan_: Cq });
function $t(r, e) {
Wn(r);
let t = Mr(r, e);
if (t.length !== 1)
throw new Error("tensor1d() requires values to be a flat/TypedArray");
return tn(r, null, t, e);
}
function ki(r, e, t) {
if (Wn(r), e != null && e.length !== 2)
throw new Error("tensor2d() requires shape to have two numbers");
let n = Mr(r, t);
if (n.length !== 2 && n.length !== 1)
throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");
if (n.length === 1 && e == null)
throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");
return tn(r, e, n, t);
}
function Iq(r, e, t) {
if (Wn(r), e != null && e.length !== 4)
throw new Error("tensor4d() requires shape to have four numbers");
let n = Mr(r, t);
if (n.length !== 4 && n.length !== 1)
throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");
if (n.length === 1 && e == null)
throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");
return tn(r, e, n, t);
}
function Sq(r, e, t) {
if (Wn(r), e != null && e.length !== 5)
throw new Error("tensor5d() requires shape to have five numbers");
let n = Mr(r, t);
if (n.length !== 5 && n.length !== 1)
throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");
if (n.length === 1 && e == null)
throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");
return tn(r, e, n, t);
}
function Nq(r, e, t) {
if (Wn(r), e != null && e.length !== 6)
throw new Error("tensor6d() requires shape to have six numbers");
let n = Mr(r, t);
if (n.length !== 6 && n.length !== 1)
throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");
if (n.length === 1 && e == null)
throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");
return e = e || n, tn(r, e, n, t);
}
function Tq(r, e = 1, t = true) {
let n = k(r, "x", "topk");
if (n.rank === 0)
throw new Error("topk() expects the input to be of rank 1 or higher");
let o = n.shape[n.shape.length - 1];
if (e < 0)
throw new Error(`'k' passed to topk() must be >= 0 but got ${e}`);
if (e > o)
throw new Error(`'k' passed to topk() must be <= the last dimension (${o}) but got ${e}`);
let s = { x: n }, a = { k: e, sorted: t }, [i, l] = T.runKernel(wa, s, a);
return { values: i, indices: l };
}
var jf = N({ topk_: Tq });
function Eq(r, e = 0, t = 1, n, o) {
if (n != null && n === "bool")
throw new Error("Unsupported data type $ { dtype }");
let s = new Bp(e, t, n, true, o), a = Ie(r, n);
for (let i = 0; i < a.values.length; i++)
a.values[i] = s.nextValue();
return a.toTensor();
}
var Vu = N({ truncatedNormal_: Eq });
function Aq(r, e = 0) {
let t = k(r, "x", "unique", "string_or_numeric");
E(t.rank > 0, () => "The input tensor must be at least 1D");
let n = { x: t }, o = { axis: e }, [s, a] = T.runKernel(vp, n, o);
return { values: s, indices: a };
}
var Gp = N({ unique_: Aq });
function Dq(r, e, t) {
let n = k(r, "x", "unsortedSegmentSum"), o = k(e, "segmentIds", "unsortedSegmentSum", "int32");
E(it(t), () => "numSegments must be of dtype int");
let s = { x: n, segmentIds: o }, a = { numSegments: t };
return T.runKernel(vl, s, a);
}
var Hf = N({ unsortedSegmentSum_: Dq });
function $q(r, e = 0) {
let t = k(r, "x", "unstack", "string_or_numeric");
E(e >= -t.shape.length && e < t.shape.length, () => `Axis = ${e} is not in [-${t.shape.length}, ${t.shape.length})`);
let n = { value: t }, o = { axis: e };
return T.runKernel(di, n, o);
}
var yr = N({ unstack_: $q });
function yk(r, e = true, t, n) {
return T.makeVariable(r, e, t, n);
}
function nx(r, e) {
let t = [];
for (let s = 0; s < e.length; s++)
e[s] && t.push(s);
let n = Ie(r, "int32"), o = Ie([t.length, r.length], "int32");
for (let s = 0; s < t.length; s++) {
let a = n.indexToLoc(t[s]), i = s * r.length;
o.values.set(a, i);
}
return o.toTensor();
}
async function Rq(r) {
let e = k(r, "condition", "whereAsync", "bool"), t = await e.data(), n = nx(e.shape, t);
return r !== e && e.dispose(), n;
}
var qf = Rq;
async function Fq(r, e, t) {
let n = k(r, "tensor", "boolMask"), o = k(e, "mask", "boolMask", "bool"), s = t == null ? 0 : t, a = o.rank, i = n.shape;
E(a > 0, () => "mask cannot be scalar"), Rt(i.slice(s, s + a), o.shape, "mask's shape must match the first K dimensions of tensor's shape,");
let l = 1;
for (let h = s; h < s + a; h++)
l *= i[h];
let u = i.slice(0, s).concat([l], i.slice(s + a)), c = F(n, u), p = F(o, [-1]), m = await qf(p), f = Br(m, [1]), d = uo(c, f, s);
return r !== n && n.dispose(), e !== o && o.dispose(), f.dispose(), c.dispose(), p.dispose(), m.dispose(), d;
}
var JSe = Fq;
function Oq(r, e = "euclidean", t = null, n = false) {
r = k(r, "x", "norm");
let o = X1(r, e, t), s = o.shape;
if (n) {
let a = cr(t, r.shape);
s = po(o.shape, a);
}
return F(o, s);
}
function X1(r, e, t = null) {
if (r.rank === 0)
return Ct(r);
if (r.rank !== 1 && t === null)
return X1(F(r, [-1]), e, t);
if (r.rank === 1 || typeof t == "number" || Array.isArray(t) && t.length === 1) {
if (e === 1)
return me(Ct(r), t);
if (e === 1 / 0)
return Rr(Ct(r), t);
if (e === -1 / 0)
return Al(Ct(r), t);
if (e === "euclidean" || e === 2)
return bt(me(Hr(Ct(r), pe(2, "int32")), t));
throw new Error(`Error in norm: invalid ord value: ${e}`);
}
if (Array.isArray(t) && t.length === 2) {
if (e === 1)
return Rr(me(Ct(r), t[0]), t[1] - 1);
if (e === 1 / 0)
return Rr(me(Ct(r), t[1]), t[0]);
if (e === -1 / 0)
return Al(me(Ct(r), t[1]), t[0]);
if (e === "fro" || e === "euclidean")
return bt(me(Ve(r), t));
throw new Error(`Error in norm: invalid ord value: ${e}`);
}
throw new Error(`Error in norm: invalid axis: ${t}`);
}
var Wp = N({ norm_: Oq });
function Pq(r, e, t, n, o = true) {
let s = k(r, "v", "movingAverage"), a = k(e, "x", "movingAverage"), i = k(t, "decay", "movingAverage");
c_(s, a), E(Qr(s.shape, a.shape), () => "Shape mismatch in v and x");
let l = pe(1), u = le(l, i), c = O(le(a, s), u);
if (o) {
E(n != null, () => "When using zeroDebias: true, step is required.");
let p = k(n, "step", "movingAverage");
c = ce(c, le(l, Hr(i, p)));
}
return Z(s, c);
}
var CNe = N({ movingAverage_: Pq });
function Mq(r, e, t) {
let n = k(r, "indices", "scatterND", "int32"), o = k(e, "updates", "scatterND");
Ug(o, n, t);
let s = { indices: n, updates: o }, a = { shape: t };
return T.runKernel(da, s, a);
}
var Y1 = N({ scatterND_: Mq });
function Z1(r, e, t, n) {
if (r.dtype !== "int32")
throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${r.dtype}.`);
if (r.rank > 2)
throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${r.shape}.`);
let o = r.rank > 0 ? r.shape[0] : 1, s = r.rank > 1 ? r.shape[1] : 1;
if (t.length !== s)
throw new Error(`outputShape has incorrect number of elements:, ${t.length}, should be: ${s}.`);
let a = e.size;
if (!(e.rank === 0 || e.rank === 1 && a === o))
throw new Error(`sparseValues has incorrect shape ${e.shape}, should be [] or [${o}]`);
if (e.dtype !== n.dtype)
throw new Error("sparseValues.dtype must match defaultValues.dtype");
}
function Lq(r, e, t, n = 0) {
let o = k(r, "sparseIndices", "sparseToDense", "int32"), s = k(e, "sparseValues", "sparseToDense"), a = k(n, "defaultValue", "sparseToDense", s.dtype);
Z1(o, s, t, a);
let i = { sparseIndices: o, sparseValues: s, defaultValue: a }, l = { outputShape: t };
return T.runKernel(bp, i, l);
}
var ox = N({ sparseToDense_: Lq });
function zq(r, e) {
let t = k(e, "indices", "gatherND", "int32"), o = { params: k(r, "x", "gatherND", "string_or_numeric"), indices: t };
return T.runKernel(Ji, o);
}
var J1 = N({ gatherND_: zq });
function Q1(r, e) {
if (e == null)
return r.shape.slice();
if (Qr(r.shape, e))
return e;
if (r.shape.length === e.length) {
let t = [];
for (let n = 0; n < r.shape.length; n++)
e[n] == null && r.shape[n] != null ? t.push(r.shape[n]) : t.push(e[n]);
return t;
}
return e;
}
function Bq(r, e, t, n) {
let o = k(r, "x", "dropout");
if (E(o.dtype === "float32", () => `x has to be a floating point tensor since it's going to be scaled, but got a ${o.dtype} tensor instead.`), E(e >= 0 && e < 1, () => `rate must be a float in the range [0, 1), but got ${e}.`), e === 0)
return r instanceof Le ? o.clone() : o;
let s = Q1(o, t), a = 1 - e, i = ce(Os(Z(Ms(s, 0, 1, "float32", n), a)), a);
return O(o, i);
}
var eT = N({ dropout_: Bq });
function tT(r) {
return Math.floor(Math.pow(2, Math.ceil(Math.log(r) / Math.log(2))));
}
function sx(r, e, t) {
let n = 1 - r % 2, o = new Float32Array(r);
for (let s = 0; s < r; ++s) {
let a = 2 * Math.PI * s / (r + n - 1);
o[s] = e - t * Math.cos(a);
}
return $t(o, "float32");
}
async function Vq(r, e, t = 1) {
let n = k(r, "predictions", "inTopK"), o = k(e, "targets", "inTopK");
E(n.rank > 1, () => `inTopK() expects the predictions to be of rank 2 or higher, but got ${n.rank}`), E(n.rank - 1 === o.rank, () => `predictions rank should be 1 larger than targets rank, but got predictions rank ${n.rank} and targets rank ${o.rank}`), Rt(n.shape.slice(0, n.shape.length - 1), o.shape, "predictions's shape should be align with the targets' shape, except the last dimension.");
let s = n.shape[n.shape.length - 1];
E(t > 0 && t <= s, () => `'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${t}`);
let a = await n.data(), i = await o.data(), [l, u] = [a.length / s, s], c = Uw("bool", l);
for (let p = 0; p < l; p++) {
let m = p * u, f = a.subarray(m, m + u), d = [];
for (let h = 0; h < f.length; h++)
d.push({ value: f[h], index: h });
d.sort((h, g) => g.value - h.value), c[p] = 0;
for (let h = 0; h < t; h++)
if (d[h].index === i[p]) {
c[p] = 1;
break;
}
}
return r !== n && n.dispose(), e !== o && o.dispose(), Dr(c, o.shape, "bool");
}
var l1e = Vq;
var fo = {};
qe(fo, { conv2d: () => rT, depthwiseConv2d: () => nT, matMul: () => oT });
function Gq(r, e, t, n, o, s = "NHWC", a) {
let i = r;
r.rank === 3 && (i = F(r, [1, r.shape[0], r.shape[1], r.shape[2]]));
let l = e;
l.rank === 3 && (l = F(e, [1, e.shape[0], e.shape[1], e.shape[2]])), E(i.rank === 4, () => `Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`), E(l.rank === 4, () => `Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`), E(t.length === 4, () => `Error in conv2dDerFilter: filterShape must be length 4, but got ${t}.`);
let u = s === "NHWC" ? i.shape[3] : i.shape[1], c = s === "NHWC" ? l.shape[3] : l.shape[1];
E(u === t[2], () => `Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${t[2]}.`), E(c === t[3], () => `Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${t[3]}).`), a != null && E(it(o), () => `Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);
let p = { x: i, dy: l }, m = { strides: n, pad: o, dataFormat: s, dimRoundingMode: a, filterShape: t };
return T.runKernel(Kc, p, m);
}
var Up = N({ conv2DBackpropFilter_: Gq });
function Gu(r, e, t) {
if (t == null || t === "linear")
return r;
if (t === "relu")
return O(r, Ls(e));
throw new Error(`Cannot compute gradient for fused activation ${t}.`);
}
function Wu(r, e) {
let t = e, n = It(r.shape, e.shape);
return n.length > 0 && (t = me(t, n)), F(t, r.shape);
}
function Uu(r, e, t, n) {
if (e === "linear")
return r;
if (e === "relu")
return Ir(r);
if (e === "elu")
return Rs(r);
if (e === "relu6")
return Ru(r);
if (e === "prelu")
return Ma(r, t);
if (e === "leakyrelu")
return $a(r, n);
if (e === "sigmoid")
return zr(r);
throw new Error(`Unknown fused activation ${e}.`);
}
var ju = (r, e) => !(r > 0) || e === "linear";
function Wq({ x: r, filter: e, strides: t, pad: n, dataFormat: o = "NHWC", dilations: s = [1, 1], dimRoundingMode: a, bias: i, activation: l = "linear", preluActivationWeights: u, leakyreluAlpha: c }) {
if (l = l || "linear", ju(T.state.gradientDepth, l) === false) {
let C = nn(r, e, t, n, o, s, a);
return i != null && (C = Z(C, i)), Uu(C, l, u, c);
}
let p = k(r, "x", "conv2d", "float32"), m = k(e, "filter", "conv2d", "float32"), f = p, d = false;
p.rank === 3 && (d = true, f = F(p, [1, p.shape[0], p.shape[1], p.shape[2]])), E(f.rank === 4, () => `Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`), E(m.rank === 4, () => `Error in fused conv2d: filter must be rank 4, but got rank ${m.rank}.`), a != null && E(it(n), () => `Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${n}.`), E(f.shape[3] === m.shape[2], () => `Error in conv2d: depth of input (${f.shape[3]}) must match input depth for filter ${m.shape[2]}.`), E($r(t, s), () => `Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`), E(o === "NHWC", () => `Error in conv2d: got dataFormat of ${o} but only NHWC is currently supported.`);
let h = _u(f.shape, m.shape, t, s, n, a), g;
i != null && (g = k(i, "bias", "fused conv2d"), [g] = je(g, p), We(h.outShape, g.shape));
let x;
u != null && (x = k(u, "prelu weights", "fused conv2d"));
let y = (C, A) => {
let [D, R, P, L] = A, G = Gu(C, P, l);
E(qn(s), () => `Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);
let W = Mp(R.shape, G, D, t, n), j = Up(R, G, D.shape, t, n), H = [W, j];
if (L != null) {
let q = Wu(L, G);
H.push(q);
}
return H;
}, w = { x: f, filter: m, bias: g, preluActivationWeights: x }, _ = { strides: t, pad: n, dataFormat: o, dilations: s, dimRoundingMode: a, activation: l, leakyreluAlpha: c };
return i == null ? on((A, D, R) => {
let P = T.runKernel(xi, w, _);
return R([D, A, P]), d && (P = F(P, [P.shape[1], P.shape[2], P.shape[3]])), { value: P, gradFunc: y };
})(f, m) : on((A, D, R, P) => {
let L = T.runKernel(xi, w, _);
return P([D, A, L, R]), d && (L = F(L, [L.shape[1], L.shape[2], L.shape[3]])), { value: L, gradFunc: y };
})(f, m, g);
}
var rT = N({ fusedConv2d_: Wq });
function Uq(r, e, t, n, o, s = [1, 1], a) {
let i = r;
r.rank === 3 && (i = F(r, [1, r.shape[0], r.shape[1], r.shape[2]]));
let l = e;
l.rank === 3 && (l = F(e, [1, e.shape[0], e.shape[1], e.shape[2]]));
let u = { x: i, dy: l }, c = { strides: n, pad: o, dimRoundingMode: a, dilations: s, filterShape: t };
return T.runKernel(Jc, u, c);
}
var ix = N({ depthwiseConv2dNativeBackpropFilter_: Uq });
function jq(r, e, t, n, o, s = [1, 1], a) {
let i = e, l = false;
e.rank === 3 && (l = true, i = F(e, [1, e.shape[0], e.shape[1], e.shape[2]]));
let u = { dy: i, filter: t }, c = { strides: n, pad: o, dimRoundingMode: a, dilations: s, inputShape: r }, p = T.runKernel(Qc, u, c);
return l ? F(p, [p.shape[1], p.shape[2], p.shape[3]]) : p;
}
var ax = N({ depthwiseConv2dNativeBackpropInput_: jq });
function Hq({ x: r, filter: e, strides: t, pad: n, dataFormat: o = "NHWC", dilations: s = [1, 1], dimRoundingMode: a, bias: i, activation: l = "linear", preluActivationWeights: u, leakyreluAlpha: c }) {
if (ju(T.state.gradientDepth, l) === false) {
let C = $s(r, e, t, n, o, s, a);
return i != null && (C = Z(C, i)), Uu(C, l, u, c);
}
let p = k(r, "x", "depthwiseConv2d", "float32"), m = k(e, "filter", "depthwiseConv2d", "float32"), f = p, d = false;
p.rank === 3 && (d = true, f = F(p, [1, p.shape[0], p.shape[1], p.shape[2]])), E(f.rank === 4, () => `Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`), E(m.rank === 4, () => `Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${m.rank}.`), E(f.shape[3] === m.shape[2], () => `Error in fused depthwiseConv2d: number of input channels (${f.shape[3]}) must match the inChannels dimension in filter ${m.shape[2]}.`), s == null && (s = [1, 1]), E($r(t, s), () => `Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`), a != null && E(it(n), () => `Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${a} but got pad ${n}.`);
let h = _u(f.shape, m.shape, t, s, n, a, true), g;
i != null && (g = k(i, "bias", "fused conv2d"), [g] = je(g, p), We(h.outShape, g.shape));
let x;
u != null && (x = k(u, "prelu weights", "fused depthwiseConv2d"));
let y = (C, A) => {
E(qn(s), () => `Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);
let [D, R, P, L] = A, G = Gu(C, P, l), W = ax(R.shape, G, D, t, n, s, a), j = ix(R, G, D.shape, t, n, s, a);
if (L != null) {
let H = Wu(g, G);
return [W, j, H];
}
return [W, j];
}, w = { x: f, filter: m, bias: g, preluActivationWeights: x }, _ = { strides: t, pad: n, dataFormat: o, dilations: s, dimRoundingMode: a, activation: l, leakyreluAlpha: c };
return i == null ? on((A, D, R) => {
let P = T.runKernel(yi, w, _);
return R([D, A, P]), d && (P = F(P, [P.shape[1], P.shape[2], P.shape[3]])), { value: P, gradFunc: y };
})(f, m) : on((A, D, R, P) => {
let L = T.runKernel(yi, w, _);
return P([D, A, L, R]), d && (L = F(L, [L.shape[1], L.shape[2], L.shape[3]])), { value: L, gradFunc: y };
})(f, m, g);
}
var nT = N({ fusedDepthwiseConv2d_: Hq });
function qq({ a: r, b: e, transposeA: t = false, transposeB: n = false, bias: o, activation: s = "linear", preluActivationWeights: a, leakyreluAlpha: i }) {
if (ju(T.state.gradientDepth, s) === false) {
let L = ze(r, e, t, n);
return o != null && (L = Z(L, o)), Uu(L, s, a, i);
}
let l = k(r, "a", "fused matMul"), u = k(e, "b", "fused matMul");
[l, u] = je(l, u);
let c = t ? l.shape[l.rank - 2] : l.shape[l.rank - 1], p = n ? u.shape[u.rank - 1] : u.shape[u.rank - 2], m = t ? l.shape[l.rank - 1] : l.shape[l.rank - 2], f = n ? u.shape[u.rank - 2] : u.shape[u.rank - 1], d = l.shape.slice(0, -2), h = u.shape.slice(0, -2), g = st(d), x = st(h);
E(l.rank >= 2 && u.rank >= 2 && l.rank === u.rank, () => `Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${u.rank}.`), E(Qr(d, h), () => `Error in fused matMul: outer dimensions (${d}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} must match.`), E(c === p, () => `Error in fused matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${t} and transposeB=${n} must match.`);
let y = l.shape.slice(0, -2).concat([m, f]), w = t ? F(l, [g, c, m]) : F(l, [g, m, c]), _ = n ? F(u, [x, f, p]) : F(u, [x, p, f]), C;
o != null && (C = k(o, "bias", "fused matMul"), [C] = je(C, l), We(y, C.shape));
let A;
a != null && (A = k(a, "prelu weights", "fused matMul"));
let D = (L, G) => {
let [W, j, H, q] = G, X = Gu(F(L, H.shape), H, s), re, J;
if (!t && !n ? (re = ze(X, j, false, true), J = ze(W, X, true, false)) : !t && n ? (re = ze(X, j, false, false), J = ze(X, W, true, false)) : t && !n ? (re = ze(j, X, false, true), J = ze(W, X, false, false)) : (re = ze(j, X, true, true), J = ze(X, W, true, true)), o != null) {
let oe = Wu(q, X);
return [re, J, oe];
} else
return [re, J];
}, R = { a: w, b: _, bias: C, preluActivationWeights: A }, P = { transposeA: t, transposeB: n, activation: s, leakyreluAlpha: i };
return o == null ? on((G, W, j) => {
let H = T.runKernel(gi, R, P);
return j([G, W, H]), { value: F(H, y), gradFunc: D };
})(w, _) : on((G, W, j, H) => {
let q = T.runKernel(gi, R, P);
return H([G, W, q, j]), { value: F(q, y), gradFunc: D };
})(w, _, C);
}
var oT = N({ fusedMatMul_: qq });
function Kq(r) {
return sx(r, 0.54, 0.46);
}
var sT = N({ hammingWindow_: Kq });
function Xq(r) {
return sx(r, 0.5, 0.5);
}
var lx = N({ hannWindow_: Xq });
function Yq(r, e, t, n = false, o = 0) {
let s = 0, a = [];
for (; s + e <= r.size; )
a.push(Oe(r, s, e)), s += t;
if (n)
for (; s < r.size; ) {
let i = s + e - r.size, l = tt([Oe(r, s, e - i), Fs([i], o)]);
a.push(l), s += t;
}
return a.length === 0 ? ki([], [0, e]) : F(tt(a), [a.length, e]);
}
var ux = N({ frame_: Yq });
function Zq(r, e, t, n, o = lx) {
n == null && (n = tT(e));
let s = ux(r, e, t), a = O(s, o(e));
return Va(a, n);
}
var iT = N({ stft_: Zq });
function Jq(r, e, t, n, o = "bilinear", s = 0) {
let a = k(r, "image", "cropAndResize"), i = k(e, "boxes", "cropAndResize", "float32"), l = k(t, "boxInd", "cropAndResize", "int32"), u = i.shape[0];
E(a.rank === 4, () => `Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`), E(i.rank === 2 && i.shape[1] === 4, () => `Error in cropAndResize: boxes must be have size [${u},4] but had shape ${i.shape}.`), E(l.rank === 1 && l.shape[0] === u, () => `Error in cropAndResize: boxInd must be have size [${u}] but had shape ${i.shape}.`), E(n.length === 2, () => `Error in cropAndResize: cropSize must be of length 2, but got length ${n.length}.`), E(n[0] >= 1 && n[1] >= 1, () => `cropSize must be atleast [1,1], but was ${n}`), E(o === "bilinear" || o === "nearest", () => `method must be bilinear or nearest, but was ${o}`);
let c = { image: a, boxes: i, boxInd: l }, p = { method: o, extrapolationValue: s, cropSize: n };
return T.runKernel(Hi, c, p);
}
var aT = N({ cropAndResize_: Jq });
function Qq(r) {
let e = k(r, "image", "flipLeftRight", "float32");
E(e.rank === 4, () => `Error in flipLeftRight: image must be rank 4,but got rank ${e.rank}.`);
let t = { image: e };
return T.runKernel(Zi, t, {});
}
var lT = N({ flipLeftRight_: Qq });
function eK(r) {
let e = k(r, "image", "grayscaleToRGB"), t = e.rank - 1, n = e.shape[t];
E(e.rank >= 2, () => `Error in grayscaleToRGB: images must be at least rank 2, but got rank ${e.rank}.`), E(n === 1, () => `Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${n}.`);
let o = new Array(e.rank);
return o.fill(1, 0, t), o[t] = 3, vr(e, o);
}
var uT = N({ grayscaleToRGB_: eK });
function tK(r, e, t = 0, n = 0.5) {
let o = k(r, "image", "rotateWithOffset", "float32");
E(o.rank === 4, () => `Error in rotateWithOffset: image must be rank 4,but got rank ${o.rank}.`);
let s = { image: o }, a = { radians: e, fillValue: t, center: n };
return T.runKernel(ka, s, a);
}
var cT = N({ rotateWithOffset_: tK });
function ho(r, e, t, n, o, s) {
n == null && (n = 0.5), o == null && (o = Number.NEGATIVE_INFINITY), s == null && (s = 0);
let a = r.shape[0];
return t = Math.min(t, a), E(0 <= n && n <= 1, () => `iouThreshold must be in [0, 1], but was '${n}'`), E(r.rank === 2, () => `boxes must be a 2D tensor, but was of rank '${r.rank}'`), E(r.shape[1] === 4, () => `boxes must have 4 columns, but 2nd dimension was ${r.shape[1]}`), E(e.rank === 1, () => "scores must be a 1D tensor"), E(e.shape[0] === a, () => `scores has incompatible shape with boxes. Expected ${a}, but was ${e.shape[0]}`), E(0 <= s && s <= 1, () => `softNmsSigma must be in [0, 1], but was '${s}'`), { maxOutputSize: t, iouThreshold: n, scoreThreshold: o, softNmsSigma: s };
}
function rK(r, e, t, n = 0.5, o = Number.NEGATIVE_INFINITY) {
let s = k(r, "boxes", "nonMaxSuppression", "float32"), a = k(e, "scores", "nonMaxSuppression", "float32"), i = ho(s, a, t, n, o);
t = i.maxOutputSize, n = i.iouThreshold, o = i.scoreThreshold;
let l = { maxOutputSize: t, iouThreshold: n, scoreThreshold: o };
return T.runKernel(ua, { boxes: s, scores: a }, l);
}
var pT = N({ nonMaxSuppression_: rK });
function mT(r, e, t) {
let n = nK(r, e, t), o = n < 0 ? -(n + 1) : n;
r.splice(o, 0, e);
}
function nK(r, e, t) {
return sK(r, e, t || oK);
}
function oK(r, e) {
return r > e ? 1 : r < e ? -1 : 0;
}
function sK(r, e, t) {
let n = 0, o = r.length, s = 0, a = false;
for (; n < o; ) {
s = n + (o - n >>> 1);
let i = t(e, r[s]);
i > 0 ? n = s + 1 : (o = s, a = !i);
}
return a ? n : -n - 1;
}
function cx(r, e, t, n, o) {
return bk(r, e, t, n, o, 0);
}
function px(r, e, t, n, o, s) {
return bk(r, e, t, n, o, 0, false, s, true);
}
function mx(r, e, t, n, o, s) {
return bk(r, e, t, n, o, s, true);
}
function bk(r, e, t, n, o, s, a = false, i = false, l = false) {
let u = [];
for (let g = 0; g < e.length; g++)
e[g] > o && u.push({ score: e[g], boxIndex: g, suppressBeginIndex: 0 });
u.sort(fT);
let c = s > 0 ? -0.5 / s : 0, p = [], m = [];
for (; p.length < t && u.length > 0; ) {
let g = u.pop(), { score: x, boxIndex: y, suppressBeginIndex: w } = g;
if (x < o)
break;
let _ = false;
for (let C = p.length - 1; C >= w; --C) {
let A = iK(r, y, p[C]);
if (A >= n) {
_ = true;
break;
}
if (g.score = g.score * aK(n, c, A), g.score <= o)
break;
}
g.suppressBeginIndex = p.length, _ || (g.score === x ? (p.push(y), m.push(g.score)) : g.score > o && mT(u, g, fT));
}
let f = p.length, d = t - f;
i && d > 0 && (p.push(...new Array(d).fill(0)), m.push(...new Array(d).fill(0)));
let h = { selectedIndices: p };
return a && (h.selectedScores = m), l && (h.validOutputs = f), h;
}
function iK(r, e, t) {
let n = r.subarray(e * 4, e * 4 + 4), o = r.subarray(t * 4, t * 4 + 4), s = Math.min(n[0], n[2]), a = Math.min(n[1], n[3]), i = Math.max(n[0], n[2]), l = Math.max(n[1], n[3]), u = Math.min(o[0], o[2]), c = Math.min(o[1], o[3]), p = Math.max(o[0], o[2]), m = Math.max(o[1], o[3]), f = (i - s) * (l - a), d = (p - u) * (m - c);
if (f <= 0 || d <= 0)
return 0;
let h = Math.max(s, u), g = Math.max(a, c), x = Math.min(i, p), y = Math.min(l, m), w = Math.max(x - h, 0) * Math.max(y - g, 0);
return w / (f + d - w);
}
function aK(r, e, t) {
let n = Math.exp(e * t * t);
return t <= r ? n : 0;
}
function fT(r, e) {
return r.score - e.score || r.score === e.score && e.boxIndex - r.boxIndex;
}
async function lK(r, e, t, n = 0.5, o = Number.NEGATIVE_INFINITY) {
let s = k(r, "boxes", "nonMaxSuppressionAsync"), a = k(e, "scores", "nonMaxSuppressionAsync"), i = ho(s, a, t, n, o);
t = i.maxOutputSize, n = i.iouThreshold, o = i.scoreThreshold;
let l = await Promise.all([s.data(), a.data()]), u = l[0], c = l[1], { selectedIndices: p } = cx(u, c, t, n, o);
return s !== r && s.dispose(), a !== e && a.dispose(), $t(p, "int32");
}
var dT = lK;
function uK(r, e, t, n = 0.5, o = Number.NEGATIVE_INFINITY, s = 0) {
let a = k(r, "boxes", "nonMaxSuppression"), i = k(e, "scores", "nonMaxSuppression"), l = ho(a, i, t, n, o, s);
t = l.maxOutputSize, n = l.iouThreshold, o = l.scoreThreshold, s = l.softNmsSigma;
let u = { boxes: a, scores: i }, c = { maxOutputSize: t, iouThreshold: n, scoreThreshold: o, softNmsSigma: s }, p = T.runKernel(pa, u, c);
return { selectedIndices: p[0], selectedScores: p[1] };
}
var hT = N({ nonMaxSuppressionWithScore_: uK });
async function cK(r, e, t, n = 0.5, o = Number.NEGATIVE_INFINITY, s = 0) {
let a = k(r, "boxes", "nonMaxSuppressionAsync"), i = k(e, "scores", "nonMaxSuppressionAsync"), l = ho(a, i, t, n, o, s);
t = l.maxOutputSize, n = l.iouThreshold, o = l.scoreThreshold, s = l.softNmsSigma;
let u = await Promise.all([a.data(), i.data()]), c = u[0], p = u[1], { selectedIndices: m, selectedScores: f } = mx(c, p, t, n, o, s);
return a !== r && a.dispose(), i !== e && i.dispose(), { selectedIndices: $t(m, "int32"), selectedScores: $t(f) };
}
var gT = cK;
function pK(r, e, t, n = 0.5, o = Number.NEGATIVE_INFINITY, s = false) {
let a = k(r, "boxes", "nonMaxSuppression"), i = k(e, "scores", "nonMaxSuppression"), l = ho(a, i, t, n, o, null), u = l.maxOutputSize, c = l.iouThreshold, p = l.scoreThreshold, m = { boxes: a, scores: i }, f = { maxOutputSize: u, iouThreshold: c, scoreThreshold: p, padToMaxOutputSize: s }, d = T.runKernel(ca, m, f);
return { selectedIndices: d[0], validOutputs: d[1] };
}
var xT = N({ nonMaxSuppressionPadded_: pK });
async function mK(r, e, t, n = 0.5, o = Number.NEGATIVE_INFINITY, s = false) {
let a = k(r, "boxes", "nonMaxSuppressionAsync"), i = k(e, "scores", "nonMaxSuppressionAsync"), l = ho(a, i, t, n, o, null), u = l.maxOutputSize, c = l.iouThreshold, p = l.scoreThreshold, [m, f] = await Promise.all([a.data(), i.data()]), { selectedIndices: d, validOutputs: h } = px(m, f, u, c, p, s);
return a !== r && a.dispose(), i !== e && i.dispose(), { selectedIndices: $t(d, "int32"), validOutputs: pe(h, "int32") };
}
var yT = mK;
function fK(r, e, t = false, n = false) {
let o = k(r, "images", "resizeBilinear");
E(o.rank === 3 || o.rank === 4, () => `Error in resizeBilinear: x must be rank 3 or 4, but got rank ${o.rank}.`), E(e.length === 2, () => `Error in resizeBilinear: new shape must 2D, but got shape ${e}.`), E(n === false || t === false, () => "Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");
let s = o, a = false;
o.rank === 3 && (a = true, s = F(o, [1, o.shape[0], o.shape[1], o.shape[2]]));
let [] = e, i = { images: s }, l = { alignCorners: t, halfPixelCenters: n, size: e }, u = T.runKernel(ps, i, l);
return a ? F(u, [u.shape[1], u.shape[2], u.shape[3]]) : u;
}
var fx = N({ resizeBilinear_: fK });
function dK(r, e, t = false, n = false) {
let o = k(r, "images", "resizeNearestNeighbor");
E(o.rank === 3 || o.rank === 4, () => `Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${o.rank}.`), E(e.length === 2, () => `Error in resizeNearestNeighbor: new shape must 2D, but got shape ${e}.`), E(o.dtype === "float32" || o.dtype === "int32", () => "`images` must have `int32` or `float32` as dtype"), E(n === false || t === false, () => "Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");
let s = o, a = false;
o.rank === 3 && (a = true, s = F(o, [1, o.shape[0], o.shape[1], o.shape[2]]));
let [] = e, i = { images: s }, l = { alignCorners: t, halfPixelCenters: n, size: e }, u = T.runKernel(_l, i, l);
return a ? F(u, [u.shape[1], u.shape[2], u.shape[3]]) : u;
}
var dx = N({ resizeNearestNeighbor_: dK });
function hK(r, e = "binary", t = false, n = 0.5) {
let o = k(r, "image", "threshold"), s = 0.2989, a = 0.587, i = 0.114, l = o.shape[0] * o.shape[1], u = O($t([n]), 255), c, p, m, f;
if (E(o.rank === 3, () => `Error in threshold: image must be rank 3,but got rank ${o.rank}.`), E(o.shape[2] === 3 || o.shape[2] === 1, () => `Error in threshold: image color channel must be equal to 3 or 1but got ${o.shape[2]}.`), E(o.dtype === "int32" || o.dtype === "float32", () => `Error in dtype: image dtype must be int32 or float32,but got dtype ${o.dtype}.`), E(e === "otsu" || e === "binary", () => `Method must be binary or otsu, but was ${e}`), o.shape[2] === 3) {
[c, p, m] = sr(o, [1, 1, 1], -1);
let g = O(c, s), x = O(p, a), y = O(m, i);
f = Z(Z(g, x), y);
} else
f = r;
if (e === "otsu") {
let g = vf(Y(Fu(f), "int32"), Dr([]), 256);
u = gK(g, l);
}
let d = t ? vn(f, u) : zt(f, u);
return Y(O(d, 255), "int32");
}
function gK(r, e) {
let t = $t([-1]), n = $t([0]), o = $t([0]), s, a, i, l, u, c;
for (let p = 0; p < r.size - 1; p++) {
s = Oe(r, 0, p + 1), a = Oe(r, p + 1), u = ce(me(s), e), c = ce(me(a), e);
let m = me(O(s, La(0, s.size)));
i = ce(m, me(s));
let f = Fs(a.shape, s.size), d = Z(La(0, a.size), f), h = O(a, d);
l = ce(me(h), me(a));
let g = le(i, l), x = le(i, l), y = O(u, c);
o = O(O(y, g), x);
let w = zt(o, n);
n = St(w, o, n), t = St(w, $t([p]), t);
}
return t;
}
var bT = N({ threshold_: hK });
function xK(r, e, t = "nearest", n = "constant", o = 0, s) {
let a = k(r, "image", "transform", "float32"), i = k(e, "transforms", "transform", "float32");
E(a.rank === 4, () => `Error in transform: image must be rank 4,but got rank ${a.rank}.`), E(i.rank === 2 && (i.shape[0] === a.shape[0] || i.shape[0] === 1) && i.shape[1] === 8, () => "Error in transform: Input transform should be batch x 8 or 1 x 8"), E(s == null || s.length === 2, () => `Error in transform: outputShape must be [height, width] or null, but got ${s}.`);
let l = { image: a, transforms: i }, u = { interpolation: t, fillMode: n, fillValue: o, outputShape: s };
return T.runKernel(_a, l, u);
}
var wT = N({ transform_: xK });
function yK(r, e, t) {
E(e % 1 == 0, () => `bandPart(): numLower must be an integer, got ${e}.`), E(t % 1 == 0, () => `bandPart(): numUpper must be an integer, got ${t}.`);
let n = k(r, "a", "bandPart");
E(n.rank >= 2, () => `bandPart(): Rank must be at least 2, got ${n.rank}.`);
let o = n.shape, [s, a] = n.shape.slice(-2);
if (!(e <= s))
throw new Error(`bandPart(): numLower (${e}) must not be greater than the number of rows (${s}).`);
if (!(t <= a))
throw new Error(`bandPart(): numUpper (${t}) must not be greater than the number of columns (${a}).`);
e < 0 && (e = s), t < 0 && (t = a);
let i = F(La(0, s, 1, "int32"), [-1, 1]), l = La(0, a, 1, "int32"), u = le(i, l), c = Cr(vn(u, pe(+e, "int32")), kn(u, pe(-t, "int32"))), p = yt([s, a], n.dtype);
return F(Xt(yr(F(n, [-1, s, a])).map((m) => St(c, m, p))), o);
}
var _T = N({ bandPart_: yK });
function bK(r) {
let e;
if (Array.isArray(r)) {
e = false, E(r != null && r.length > 0, () => "Gram-Schmidt process: input must not be null, undefined, or empty");
let o = r[0].shape[0];
for (let s = 1; s < r.length; ++s)
E(r[s].shape[0] === o, () => `Gram-Schmidt: Non-unique lengths found in the input vectors: (${r[s].shape[0]} vs. ${o})`);
} else
e = true, r = sr(r, r.shape[0], 0).map((o) => Br(o, [0]));
E(r.length <= r[0].shape[0], () => `Gram-Schmidt: Number of vectors (${r.length}) exceeds number of dimensions (${r[0].shape[0]}).`);
let t = [], n = r;
for (let o = 0; o < r.length; ++o)
t.push(T.tidy(() => {
let s = n[o];
if (o > 0)
for (let a = 0; a < o; ++a) {
let i = O(me(O(t[a], s)), t[a]);
s = le(s, i);
}
return ce(s, Wp(s, "euclidean"));
}));
return e ? Xt(t, 0) : t;
}
var kT = N({ gramSchmidt_: bK });
function wK(r, e = false) {
if (E(r.rank >= 2, () => `qr() requires input tensor to have a rank >= 2, but got rank ${r.rank}`), r.rank === 2)
return vT(r, e);
{
let t = r.shape.slice(0, r.shape.length - 2).reduce((l, u) => l * u), n = yr(F(r, [t, r.shape[r.shape.length - 2], r.shape[r.shape.length - 1]]), 0), o = [], s = [];
n.forEach((l) => {
let [u, c] = vT(l, e);
o.push(u), s.push(c);
});
let a = F(Xt(o, 0), r.shape), i = F(Xt(s, 0), r.shape);
return [a, i];
}
}
function vT(r, e = false) {
return T.tidy(() => {
E(r.shape.length === 2, () => `qr2d() requires a 2D Tensor, but got a ${r.shape.length}D Tensor.`);
let t = r.shape[0], n = r.shape[1], o = Lp(t), s = wn(r), a = ki([[1]], [1, 1]), i = wn(a), l = t >= n ? n : t;
for (let u = 0; u < l; ++u) {
let c = s, p = i, m = o;
[i, s, o] = T.tidy(() => {
let f = Oe(s, [u, u], [t - u, 1]), d = Wp(f), h = Oe(s, [u, u], [1, 1]), g = St(zt(h, 0), ki([[-1]]), ki([[1]])), x = le(h, O(g, d)), y = ce(f, x);
y.shape[0] === 1 ? i = wn(a) : i = tt([a, Oe(y, [1, 0], [y.shape[0] - 1, y.shape[1]])], 0);
let w = He(ce(ze(g, x), d)), _ = Oe(s, [u, 0], [t - u, n]), C = O(w, i), A = Be(i);
if (u === 0)
s = le(_, ze(C, ze(A, _)));
else {
let P = le(_, ze(C, ze(A, _)));
s = tt([Oe(s, [0, 0], [u, n]), P], 0);
}
let D = Be(C), R = Oe(o, [0, u], [t, o.shape[1] - u]);
if (u === 0)
o = le(R, ze(ze(R, i), D));
else {
let P = le(R, ze(ze(R, i), D));
o = tt([Oe(o, [0, 0], [t, u]), P], 1);
}
return [i, s, o];
}), De([c, p, m]);
}
return !e && t > n && (o = Oe(o, [0, 0], [t, n]), s = Oe(s, [0, 0], [n, n])), [o, s];
});
}
var CT = N({ qr_: wK });
var Yt;
(function(r) {
r[r.NONE = 0] = "NONE", r[r.MEAN = 1] = "MEAN", r[r.SUM = 2] = "SUM", r[r.SUM_BY_NONZERO_WEIGHTS = 3] = "SUM_BY_NONZERO_WEIGHTS";
})(Yt || (Yt = {}));
function _K(r, e, t = Yt.SUM_BY_NONZERO_WEIGHTS) {
let n = k(r, "losses", "computeWeightedLoss"), o = null;
e != null && (o = k(e, "weights", "computeWeightedLoss"));
let s = o == null ? n : O(n, o);
if (t === Yt.NONE)
return s;
if (t === Yt.SUM)
return me(s);
if (t === Yt.MEAN) {
if (o == null)
return xt(s);
{
let a = n.size / o.size, i = ce(me(s), me(o));
return a > 1 ? ce(i, pe(a)) : i;
}
}
if (t === Yt.SUM_BY_NONZERO_WEIGHTS) {
if (o == null)
return ce(me(s), pe(n.size));
{
let a = O(o, or(n.shape)), i = Y(me(mo(a, pe(0))), "float32");
return ce(me(s), i);
}
}
throw Error(`Unknown reduction: ${t}`);
}
var Vr = N({ computeWeightedLoss_: _K });
function kK(r, e, t, n = Yt.SUM_BY_NONZERO_WEIGHTS) {
let o = k(r, "labels", "absoluteDifference"), s = k(e, "predictions", "absoluteDifference"), a = null;
t != null && (a = k(t, "weights", "absoluteDifference")), Rt(o.shape, s.shape, "Error in absoluteDifference: ");
let i = Ct(le(o, s));
return Vr(i, a, n);
}
var IT = N({ absoluteDifference_: kK });
function vK(r, e, t, n, o = Yt.SUM_BY_NONZERO_WEIGHTS) {
let s = k(r, "labels", "cosineDistance"), a = k(e, "predictions", "cosineDistance"), i = null;
n != null && (i = k(n, "weights", "cosineDistance")), Rt(s.shape, a.shape, "Error in cosineDistance: ");
let l = pe(1), u = le(l, me(O(s, a), t, true));
return Vr(u, i, o);
}
var ST = N({ cosineDistance_: vK });
function CK(r, e, t, n = Yt.SUM_BY_NONZERO_WEIGHTS) {
let o = k(r, "labels", "hingeLoss"), s = k(e, "predictions", "hingeLoss"), a = null;
t != null && (a = k(t, "weights", "hingeLoss")), Rt(o.shape, s.shape, "Error in hingeLoss: ");
let i = pe(1);
o = le(O(pe(2), o), i);
let l = Ir(le(i, O(o, s)));
return Vr(l, a, n);
}
var NT = N({ hingeLoss_: CK });
function IK(r, e, t, n = 1, o = Yt.SUM_BY_NONZERO_WEIGHTS) {
let s = k(r, "labels", "huberLoss"), a = k(e, "predictions", "huberLoss"), i = null;
t != null && (i = k(t, "weights", "huberLoss")), Rt(s.shape, a.shape, "Error in huberLoss: ");
let l = pe(n), u = Ct(le(a, s)), c = Ps(u, l), p = le(u, c), m = Z(O(pe(0.5), Ve(c)), O(l, p));
return Vr(m, i, o);
}
var TT = N({ huberLoss_: IK });
function SK(r, e, t, n = 1e-7, o = Yt.SUM_BY_NONZERO_WEIGHTS) {
let s = k(r, "labels", "logLoss"), a = k(e, "predictions", "logLoss"), i = null;
t != null && (i = k(t, "weights", "logLoss")), Rt(s.shape, a.shape, "Error in logLoss: ");
let l = pe(1), u = pe(n), c = He(O(s, xr(Z(a, u)))), p = O(le(l, s), xr(Z(le(l, a), u))), m = le(c, p);
return Vr(m, i, o);
}
var ET = N({ logLoss_: SK });
function NK(r, e, t, n = Yt.SUM_BY_NONZERO_WEIGHTS) {
let o = k(r, "labels", "meanSquaredError"), s = k(e, "predictions", "meanSquaredError"), a = null;
t != null && (a = k(t, "weights", "meanSquaredError")), Rt(o.shape, s.shape, "Error in meanSquaredError: ");
let i = Bu(o, s);
return Vr(i, a, n);
}
var AT = N({ meanSquaredError_: NK });
function TK(r, e) {
let t = k(r, "labels", "sigmoidCrossEntropyWithLogits"), n = k(e, "logits", "sigmoidCrossEntropyWithLogits");
Rt(t.shape, n.shape, "Error in sigmoidCrossEntropyWithLogits: ");
let o = Ir(n), s = O(n, t), a = Ra(Kt(He(Ct(n))));
return Z(le(o, s), a);
}
function EK(r, e, t, n = 0, o = Yt.SUM_BY_NONZERO_WEIGHTS) {
let s = k(r, "multiClassLabels", "sigmoidCrossEntropy"), a = k(e, "logits", "sigmoidCrossEntropy"), i = null;
if (t != null && (i = k(t, "weights", "sigmoidCrossEntropy")), Rt(s.shape, a.shape, "Error in sigmoidCrossEntropy: "), n > 0) {
let u = pe(n), c = pe(1), p = pe(0.5);
s = Z(O(s, le(c, u)), O(p, u));
}
let l = TK(s, a);
return Vr(l, i, o);
}
var DT = N({ sigmoidCrossEntropy_: EK });
function AK(r, e, t = -1) {
if (t === -1 && (t = e.rank - 1), t !== e.rank - 1)
throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${e.rank} and dim was ${t}`);
return on((o, s, a) => {
let l = Ff(s, [t], true), u = le(Y(s, "float32"), l);
a([o, u]);
let c = He(O(u, o));
return { value: me(c, [t]), gradFunc: (f, d) => {
let [h, g] = d, x = po(f.shape, [t]);
return [O(F(f, x), le(Y(h, "float32"), Kt(g))), O(F(f, x), le(Kt(g), Y(h, "float32")))];
} };
})(r, e);
}
function DK(r, e, t, n = 0, o = Yt.SUM_BY_NONZERO_WEIGHTS) {
let s = k(r, "onehotLabels", "softmaxCrossEntropy"), a = k(e, "logits", "softmaxCrossEntropy"), i = null;
if (t != null && (i = k(t, "weights", "softmaxCrossEntropy")), Rt(s.shape, a.shape, "Error in softmaxCrossEntropy: "), n > 0) {
let u = pe(n), c = pe(1), p = pe(s.shape[1]);
s = Z(O(s, le(c, u)), ce(u, p));
}
let l = AK(s, a);
return Vr(l, i, o);
}
var $T = N({ softmaxCrossEntropy_: DK });
function $K(r, e, t, n) {
let o = k(r, "indices", "sparseFillEmptyRows"), s = k(e, "values", "sparseFillEmptyRows"), a = k(t, "denseShape", "sparseFillEmptyRows"), i = k(n, "defaultValue", "sparseFillEmptyRows", s.dtype);
if (o.rank !== 2)
throw new Error(`Indices should be Tensor2D but received shape
${o.shape}`);
if (s.rank !== 1)
throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);
if (a.rank !== 1)
throw new Error(`Dense shape should be Tensor1D but received shape ${a.shape}`);
if (i.rank !== 0)
throw new Error(`Default value should be a scalar but received shape ${i.shape}`);
let l = { indices: o, values: s, denseShape: a, defaultValue: i }, u = T.runKernel(hp, l);
return { outputIndices: u[0], outputValues: u[1], emptyRowIndicator: u[2], reverseIndexMap: u[3] };
}
var RT = N({ sparseFillEmptyRows_: $K });
function RK(r, e, t) {
let n = k(r, "inputIndices", "sparseReshape"), o = k(e, "inputShape", "sparseReshape"), s = k(t, "newShape", "sparseReshape");
if (n.rank !== 2)
throw new Error(`Input indices should be Tensor2D but received shape
${n.shape}`);
if (o.rank !== 1)
throw new Error(`Input shape should be Tensor1D but received shape ${o.shape}`);
if (s.rank !== 1)
throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);
let a = { inputIndices: n, inputShape: o, newShape: s }, i = T.runKernel(gp, a);
return { outputIndices: i[0], outputShape: i[1] };
}
var FT = N({ sparseReshape_: RK });
function FK(r, e, t) {
let n = k(r, "data", "sparseSegmentMean"), o = k(e, "indices", "sparseSegmentMean"), s = k(t, "segmentIds", "sparseSegmentMean");
if (n.rank < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (o.rank !== 1)
throw new Error(`Indices should be Tensor1D but received shape
${o.shape}`);
if (s.rank !== 1)
throw new Error(`Segment ids should be Tensor1D but received shape
${s.shape}`);
let a = { data: n, indices: o, segmentIds: s };
return T.runKernel(xp, a);
}
var OT = N({ sparseSegmentMean_: FK });
function OK(r, e, t) {
let n = k(r, "data", "sparseSegmentSum"), o = k(e, "indices", "sparseSegmentSum"), s = k(t, "segmentIds", "sparseSegmentSum");
if (n.rank < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (o.rank !== 1)
throw new Error(`Indices should be Tensor1D but received shape
${o.shape}`);
if (s.rank !== 1)
throw new Error(`Segment ids should be Tensor1D but received shape
${s.shape}`);
let a = { data: n, indices: o, segmentIds: s };
return T.runKernel(yp, a);
}
var PT = N({ sparseSegmentSum_: OK });
function PK(r, e, t, n, o, s, a, i) {
let l = k(r, "data", "stringNGrams", "string");
if (l.dtype !== "string")
throw new Error("Data must be of datatype string");
if (l.shape.length !== 1)
throw new Error(`Data must be a vector, saw: ${l.shape}`);
let u = k(e, "dataSplits", "stringNGrams");
if (u.dtype !== "int32")
throw new Error("Data splits must be of datatype int32");
let c = { separator: t, nGramWidths: n, leftPad: o, rightPad: s, padWidth: a, preserveShortSequences: i }, p = { data: l, dataSplits: u }, m = T.runKernel(wp, p, c);
return { nGrams: m[0], nGramsSplits: m[1] };
}
var MT = N({ stringNGrams_: PK });
function MK(r, e, t = true) {
let n = k(r, "input", "stringSplit", "string"), o = k(e, "delimiter", "stringSplit", "string");
if (n.rank !== 1)
throw new Error(`Input should be Tensor1D but received shape ${n.shape}`);
if (o.rank !== 0)
throw new Error(`Delimiter should be a scalar but received shape ${o.shape}`);
let s = { skipEmpty: t }, a = { input: n, delimiter: o }, i = T.runKernel(_p, a, s);
return { indices: i[0], values: i[1], shape: i[2] };
}
var LT = N({ stringSplit_: MK });
function LK(r, e) {
let t = k(r, "input", "stringToHashBucketFast", "string"), n = { numBuckets: e };
if (e <= 0)
throw new Error("Number of buckets must be at least 1");
let o = { input: t };
return T.runKernel(kp, o, n);
}
var zT = N({ stringToHashBucketFast_: LK });
var SRe = { fft: Ba, ifft: _i, rfft: Va, irfft: zu };
var DRe = { hammingWindow: sT, hannWindow: lx, frame: ux, stft: iT };
var Cn = { flipLeftRight: lT, grayscaleToRGB: uT, resizeNearestNeighbor: dx, resizeBilinear: fx, rotateWithOffset: cT, cropAndResize: aT, nonMaxSuppression: pT, nonMaxSuppressionAsync: dT, nonMaxSuppressionWithScore: hT, nonMaxSuppressionWithScoreAsync: gT, nonMaxSuppressionPadded: xT, nonMaxSuppressionPaddedAsync: yT, threshold: bT, transform: wT };
var BT = { bandPart: _T, gramSchmidt: kT, qr: CT };
var oFe = { absoluteDifference: IT, computeWeightedLoss: Vr, cosineDistance: ST, hingeLoss: NT, huberLoss: TT, logLoss: ET, meanSquaredError: AT, sigmoidCrossEntropy: DT, softmaxCrossEntropy: $T };
var Kf = { sparseFillEmptyRows: RT, sparseReshape: FT, sparseSegmentMean: OT, sparseSegmentSum: PT };
var hx = { stringNGrams: MT, stringSplit: LT, stringToHashBucketFast: zT };
var qr = class extends qg {
minimize(e, t = false, n) {
let { value: o, grads: s } = this.computeGradients(e, n);
if (n != null) {
let a = n.map((i) => ({ name: i.name, tensor: s[i.name] }));
this.applyGradients(a);
} else
this.applyGradients(s);
return De(s), t ? o : (o.dispose(), null);
}
get iterations() {
return this.iterations_ == null && (this.iterations_ = 0), this.iterations_;
}
incrementIterations() {
this.iterations_ = this.iterations + 1;
}
computeGradients(e, t) {
return Zg(e, t);
}
dispose() {
this.iterations_ != null && De(this.iterations_);
}
async saveIterations() {
return this.iterations_ == null && (this.iterations_ = 0), { name: "iter", tensor: pe(this.iterations_, "int32") };
}
async getWeights() {
throw new Error("getWeights() is not implemented for this optimizer yet.");
}
async setWeights(e) {
throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`);
}
async extractIterations(e) {
return this.iterations_ = (await e[0].tensor.data())[0], e.slice(1);
}
};
Object.defineProperty(qr, Symbol.hasInstance, { value: (r) => r.minimize != null && r.computeGradients != null && r.applyGradients != null });
var Hu = class extends qr {
constructor(e, t, n = null) {
super();
this.learningRate = e, this.rho = t, this.epsilon = n, this.accumulatedGrads = [], this.accumulatedUpdates = [], n == null && (this.epsilon = T.backend.epsilon());
}
applyGradients(e) {
(Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e)).forEach((n, o) => {
let s = T.registeredVariables[n], a = false;
this.accumulatedGrads[o] == null && (this.accumulatedGrads[o] = { originalName: `${n}/accum_grad`, variable: V(() => Se(s).variable(a)) }), this.accumulatedUpdates[o] == null && (this.accumulatedUpdates[o] = { originalName: `${n}/accum_var`, variable: V(() => Se(s).variable(a)) });
let i = Array.isArray(e) ? e[o].tensor : e[n];
if (i == null)
return;
let l = this.accumulatedGrads[o].variable, u = this.accumulatedUpdates[o].variable;
V(() => {
let c = Z(O(l, this.rho), O(Ve(i), 1 - this.rho)), p = O(ce(bt(Z(u, this.epsilon)), bt(Z(l, this.epsilon))), i), m = Z(O(u, this.rho), O(Ve(p), 1 - this.rho));
l.assign(c), u.assign(m);
let f = Z(O(p, -this.learningRate), s);
s.assign(f);
});
}), this.incrementIterations();
}
dispose() {
this.accumulatedUpdates != null && (De(this.accumulatedGrads.map((e) => e.variable)), De(this.accumulatedUpdates.map((e) => e.variable)));
}
async getWeights() {
let e = [...this.accumulatedGrads, ...this.accumulatedUpdates];
return [await this.saveIterations()].concat(e.map((t) => ({ name: t.originalName, tensor: t.variable })));
}
async setWeights(e) {
e = await this.extractIterations(e);
let t = e.length / 2, n = false;
this.accumulatedGrads = e.slice(0, t).map((o) => ({ originalName: o.name, variable: o.tensor.variable(n) })), this.accumulatedUpdates = e.slice(t, t * 2).map((o) => ({ originalName: o.name, variable: o.tensor.variable(n) }));
}
getConfig() {
return { learningRate: this.learningRate, rho: this.rho, epsilon: this.epsilon };
}
static fromConfig(e, t) {
return new e(t.learningRate, t.rho, t.epsilon);
}
};
Hu.className = "Adadelta";
_n(Hu);
var qu = class extends qr {
constructor(e, t = 0.1) {
super();
this.learningRate = e, this.initialAccumulatorValue = t, this.accumulatedGrads = [];
}
applyGradients(e) {
(Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e)).forEach((n, o) => {
let s = T.registeredVariables[n];
if (this.accumulatedGrads[o] == null) {
let l = false;
this.accumulatedGrads[o] = { originalName: `${n}/accumulator`, variable: V(() => Fs(s.shape, this.initialAccumulatorValue).variable(l)) };
}
let a = Array.isArray(e) ? e[o].tensor : e[n];
if (a == null)
return;
let i = this.accumulatedGrads[o].variable;
V(() => {
let l = Z(i, Ve(a));
i.assign(l);
let u = Z(O(ce(a, bt(Z(l, T.backend.epsilon()))), -this.learningRate), s);
s.assign(u);
});
}), this.incrementIterations();
}
dispose() {
this.accumulatedGrads != null && De(this.accumulatedGrads.map((e) => e.variable));
}
async getWeights() {
return [await this.saveIterations()].concat(this.accumulatedGrads.map((e) => ({ name: e.originalName, tensor: e.variable })));
}
async setWeights(e) {
e = await this.extractIterations(e);
let t = false;
this.accumulatedGrads = e.map((n) => ({ originalName: n.name, variable: n.tensor.variable(t) }));
}
getConfig() {
return { learningRate: this.learningRate, initialAccumulatorValue: this.initialAccumulatorValue };
}
static fromConfig(e, t) {
return new e(t.learningRate, t.initialAccumulatorValue);
}
};
qu.className = "Adagrad";
_n(qu);
var Ku = class extends qr {
constructor(e, t, n, o = null) {
super();
this.learningRate = e, this.beta1 = t, this.beta2 = n, this.epsilon = o, this.accumulatedFirstMoment = [], this.accumulatedSecondMoment = [], V(() => {
this.accBeta1 = pe(t).variable(), this.accBeta2 = pe(n).variable();
}), o == null && (this.epsilon = T.backend.epsilon());
}
applyGradients(e) {
let t = Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e);
V(() => {
let n = le(1, this.accBeta1), o = le(1, this.accBeta2);
t.forEach((s, a) => {
let i = T.registeredVariables[s], l = false;
this.accumulatedFirstMoment[a] == null && (this.accumulatedFirstMoment[a] = { originalName: `${s}/m`, variable: V(() => Se(i).variable(l)) }), this.accumulatedSecondMoment[a] == null && (this.accumulatedSecondMoment[a] = { originalName: `${s}/v`, variable: V(() => Se(i).variable(l)) });
let u = Array.isArray(e) ? e[a].tensor : e[s];
if (u == null)
return;
let c = this.accumulatedFirstMoment[a].variable, p = this.accumulatedSecondMoment[a].variable, m = Z(O(c, this.beta1), O(u, 1 - this.beta1)), f = Z(O(p, this.beta2), O(Ve(u), 1 - this.beta2)), d = ce(m, n), h = ce(f, o);
c.assign(m), p.assign(f);
let g = Z(O(ce(d, Z(bt(h), this.epsilon)), -this.learningRate), i);
i.assign(g);
}), this.accBeta1.assign(O(this.accBeta1, this.beta1)), this.accBeta2.assign(O(this.accBeta2, this.beta2));
}), this.incrementIterations();
}
dispose() {
this.accBeta1.dispose(), this.accBeta2.dispose(), this.accumulatedFirstMoment != null && De(this.accumulatedFirstMoment.map((e) => e.variable)), this.accumulatedSecondMoment != null && De(this.accumulatedSecondMoment.map((e) => e.variable));
}
async getWeights() {
let e = [...this.accumulatedFirstMoment, ...this.accumulatedSecondMoment];
return [await this.saveIterations()].concat(e.map((t) => ({ name: t.originalName, tensor: t.variable })));
}
async setWeights(e) {
e = await this.extractIterations(e), V(() => {
this.accBeta1.assign(Hr(this.beta1, this.iterations_ + 1)), this.accBeta2.assign(Hr(this.beta2, this.iterations_ + 1));
});
let t = e.length / 2, n = false;
this.accumulatedFirstMoment = e.slice(0, t).map((o) => ({ originalName: o.name, variable: o.tensor.variable(n) })), this.accumulatedSecondMoment = e.slice(t, t * 2).map((o) => ({ originalName: o.name, variable: o.tensor.variable(n) }));
}
getConfig() {
return { learningRate: this.learningRate, beta1: this.beta1, beta2: this.beta2, epsilon: this.epsilon };
}
static fromConfig(e, t) {
return new e(t.learningRate, t.beta1, t.beta2, t.epsilon);
}
};
Ku.className = "Adam";
_n(Ku);
var Xu = class extends qr {
constructor(e, t, n, o = null, s = 0) {
super();
this.learningRate = e, this.beta1 = t, this.beta2 = n, this.epsilon = o, this.decay = s, this.accumulatedFirstMoment = [], this.accumulatedWeightedInfNorm = [], V(() => {
this.iteration = pe(0).variable(), this.accBeta1 = pe(t).variable();
}), o == null && (this.epsilon = T.backend.epsilon());
}
applyGradients(e) {
let t = Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e);
V(() => {
let n = le(1, this.accBeta1), o = ce(-this.learningRate, Z(O(this.iteration, this.decay), 1));
t.forEach((s, a) => {
let i = T.registeredVariables[s], l = false;
this.accumulatedFirstMoment[a] == null && (this.accumulatedFirstMoment[a] = { originalName: `${s}/m`, variable: Se(i).variable(l) }), this.accumulatedWeightedInfNorm[a] == null && (this.accumulatedWeightedInfNorm[a] = { originalName: `${s}/v`, variable: Se(i).variable(l) });
let u = Array.isArray(e) ? e[a].tensor : e[s];
if (u == null)
return;
let c = this.accumulatedFirstMoment[a].variable, p = this.accumulatedWeightedInfNorm[a].variable, m = Z(O(c, this.beta1), O(u, 1 - this.beta1)), f = O(p, this.beta2), d = Ct(u), h = sn(f, d);
c.assign(m), p.assign(h);
let g = Z(O(ce(o, n), ce(m, Z(h, this.epsilon))), i);
i.assign(g);
}), this.iteration.assign(Z(this.iteration, 1)), this.accBeta1.assign(O(this.accBeta1, this.beta1));
}), this.incrementIterations();
}
dispose() {
this.accBeta1.dispose(), this.iteration.dispose(), this.accumulatedFirstMoment != null && De(this.accumulatedFirstMoment.map((e) => e.variable)), this.accumulatedWeightedInfNorm != null && De(this.accumulatedWeightedInfNorm.map((e) => e.variable));
}
async getWeights() {
throw new Error("getWeights() is not implemented for Adamax yet.");
}
async setWeights(e) {
throw new Error("setWeights() is not implemented for Adamax yet.");
}
getConfig() {
return { learningRate: this.learningRate, beta1: this.beta1, beta2: this.beta2, epsilon: this.epsilon, decay: this.decay };
}
static fromConfig(e, t) {
return new e(t.learningRate, t.beta1, t.beta2, t.epsilon, t.decay);
}
};
Xu.className = "Adamax";
_n(Xu);
var Ga = class extends qr {
constructor(e) {
super();
this.learningRate = e, this.setLearningRate(e);
}
applyGradients(e) {
(Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e)).forEach((n, o) => {
let s = Array.isArray(e) ? e[o].tensor : e[n];
if (s == null)
return;
let a = T.registeredVariables[n];
V(() => {
let i = Z(O(this.c, s), a);
a.assign(i);
});
}), this.incrementIterations();
}
setLearningRate(e) {
this.learningRate = e, this.c != null && this.c.dispose(), this.c = Ft(pe(-e));
}
dispose() {
this.c.dispose();
}
async getWeights() {
return [await this.saveIterations()];
}
async setWeights(e) {
if (e = await this.extractIterations(e), e.length !== 0)
throw new Error("SGD optimizer does not have settable weights.");
}
getConfig() {
return { learningRate: this.learningRate };
}
static fromConfig(e, t) {
return new e(t.learningRate);
}
};
Ga.className = "SGD";
_n(Ga);
var Yu = class extends Ga {
constructor(e, t, n = false) {
super(e);
this.learningRate = e, this.momentum = t, this.useNesterov = n, this.accumulations = [], this.m = pe(this.momentum);
}
applyGradients(e) {
(Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e)).forEach((n, o) => {
let s = T.registeredVariables[n];
if (this.accumulations[o] == null) {
let l = false;
this.accumulations[o] = { originalName: `${n}/momentum`, variable: V(() => Se(s).variable(l)) };
}
let a = this.accumulations[o].variable, i = Array.isArray(e) ? e[o].tensor : e[n];
i != null && V(() => {
let l, u = Z(O(this.m, a), i);
this.useNesterov ? l = Z(O(this.c, Z(i, O(u, this.m))), s) : l = Z(O(this.c, u), s), a.assign(u), s.assign(l);
});
}), this.incrementIterations();
}
dispose() {
this.m.dispose(), this.accumulations != null && De(this.accumulations.map((e) => e.variable));
}
setMomentum(e) {
this.momentum = e;
}
async getWeights() {
return [await this.saveIterations()].concat(this.accumulations.map((e) => ({ name: e.originalName, tensor: e.variable })));
}
async setWeights(e) {
e = await this.extractIterations(e);
let t = false;
this.accumulations = e.map((n) => ({ originalName: n.name, variable: n.tensor.variable(t) }));
}
getConfig() {
return { learningRate: this.learningRate, momentum: this.momentum, useNesterov: this.useNesterov };
}
static fromConfig(e, t) {
return new e(t.learningRate, t.momentum, t.useNesterov);
}
};
Yu.className = "Momentum";
_n(Yu);
var Zu = class extends qr {
constructor(e, t = 0.9, n = 0, o = null, s = false) {
super();
if (this.learningRate = e, this.decay = t, this.momentum = n, this.epsilon = o, this.accumulatedMeanSquares = [], this.accumulatedMoments = [], this.accumulatedMeanGrads = [], this.centered = s, o == null && (this.epsilon = T.backend.epsilon()), e == null)
throw new Error("learningRate for RMSPropOptimizer must be defined.");
}
applyGradients(e) {
(Array.isArray(e) ? e.map((n) => n.name) : Object.keys(e)).forEach((n, o) => {
let s = T.registeredVariables[n], a = false;
this.accumulatedMeanSquares[o] == null && (this.accumulatedMeanSquares[o] = { originalName: `${n}/rms`, variable: V(() => Se(s).variable(a)) }), this.accumulatedMoments[o] == null && (this.accumulatedMoments[o] = { originalName: `${n}/momentum`, variable: V(() => Se(s).variable(a)) }), this.accumulatedMeanGrads[o] == null && this.centered && (this.accumulatedMeanGrads[o] = { originalName: `${n}/mg`, variable: V(() => Se(s).variable(a)) });
let i = Array.isArray(e) ? e[o].tensor : e[n];
if (i == null)
return;
let l = this.accumulatedMeanSquares[o].variable, u = this.accumulatedMoments[o].variable;
V(() => {
let c = Z(O(l, this.decay), O(Ve(i), 1 - this.decay));
if (this.centered) {
let p = this.accumulatedMeanGrads[o].variable, m = Z(O(p, this.decay), O(i, 1 - this.decay)), f = ce(O(i, this.learningRate), bt(le(c, Z(Ve(m), this.epsilon)))), d = Z(O(u, this.momentum), f);
l.assign(c), p.assign(m), u.assign(d);
let h = le(s, d);
s.assign(h);
} else {
let p = Z(O(l, this.decay), O(Ve(i), 1 - this.decay)), m = Z(O(u, this.momentum), ce(O(i, this.learningRate), bt(Z(p, this.epsilon))));
l.assign(p), u.assign(m);
let f = le(s, m);
s.assign(f);
}
});
}), this.incrementIterations();
}
dispose() {
this.accumulatedMeanSquares != null && De(this.accumulatedMeanSquares.map((e) => e.variable)), this.accumulatedMeanGrads != null && this.centered && De(this.accumulatedMeanGrads.map((e) => e.variable)), this.accumulatedMoments != null && De(this.accumulatedMoments.map((e) => e.variable));
}
async getWeights() {
let e = [...this.accumulatedMeanSquares, ...this.accumulatedMoments];
return this.centered && e.push(...this.accumulatedMeanGrads), [await this.saveIterations()].concat(e.map((t) => ({ name: t.originalName, tensor: t.variable })));
}
async setWeights(e) {
e = await this.extractIterations(e);
let t = this.centered ? e.length / 3 : e.length / 2, n = false;
this.accumulatedMeanSquares = e.slice(0, t).map((o) => ({ originalName: o.name, variable: o.tensor.variable(n) })), this.accumulatedMoments = e.slice(t, t * 2).map((o) => ({ originalName: o.name, variable: o.tensor.variable(n) })), this.centered && (this.accumulatedMeanGrads = e.slice(t * 2, t * 3).map((o) => ({ originalName: o.name, variable: o.tensor.variable(n) })));
}
getConfig() {
return { learningRate: this.learningRate, decay: this.decay, momentum: this.momentum, epsilon: this.epsilon, centered: this.centered };
}
static fromConfig(e, t) {
return new e(t.learningRate, t.decay, t.momentum, t.epsilon, t.centered);
}
};
Zu.className = "RMSProp";
_n(Zu);
var Wa = class {
static sgd(e) {
return new Ga(e);
}
static momentum(e, t, n = false) {
return new Yu(e, t, n);
}
static rmsprop(e, t = 0.9, n = 0, o = null, s = false) {
return new Zu(e, t, n, o, s);
}
static adam(e = 1e-3, t = 0.9, n = 0.999, o = null) {
return new Ku(e, t, n, o);
}
static adadelta(e = 1e-3, t = 0.95, n = null) {
return new Hu(e, t, n);
}
static adamax(e = 2e-3, t = 0.9, n = 0.999, o = null, s = 0) {
return new Xu(e, t, n, o, s);
}
static adagrad(e, t = 0.1) {
return new qu(e, t);
}
};
var Ju = { sgd: Wa.sgd, momentum: Wa.momentum, adadelta: Wa.adadelta, adagrad: Wa.adagrad, rmsprop: Wa.rmsprop, adamax: Wa.adamax, adam: Wa.adam };
var zK = (() => typeof requestAnimationFrame != "undefined" ? requestAnimationFrame : typeof setImmediate != "undefined" ? setImmediate : (r) => r())();
function wk() {
return new Promise((r) => zK(() => r()));
}
var I = {};
qe(I, { ERF_A1: () => YK, ERF_A2: () => ZK, ERF_A3: () => JK, ERF_A4: () => QK, ERF_A5: () => e6, ERF_P: () => XK, PARALLELIZE_THRESHOLD: () => gx, SELU_SCALE: () => kk, SELU_SCALEALPHA: () => _k, applyActivation: () => Uu, assertAndGetBroadcastShape: () => We, assertAxesAreInnerMostDims: () => Vj, assertParamsConsistent: () => BK, assignToTypedArray: () => i6, axesAreInnerMostDims: () => ek, calculateShapes: () => d1, checkEinsumDimSizes: () => m6, combineLocations: () => F1, complexWithEvenIndex: () => n6, complexWithOddIndex: () => o6, computeConv2DInfo: () => _u, computeConv3DInfo: () => D1, computeDefaultPad: () => P_, computeDilation2DInfo: () => pU, computeOptimalWindowSize: () => GK, computeOutAndReduceShapes: () => tk, computeOutShape: () => VK, computePool2DInfo: () => O_, computePool3DInfo: () => mU, convertConv2DDataFormat: () => $1, decodeEinsumEquation: () => c6, eitherStridesOrDilationsAreOne: () => $r, expandShapeToKeepDim: () => po, exponent: () => l6, exponents: () => a6, fromStringArrayToUint8: () => _6, fromUint8ToStringArray: () => w6, getAxesPermutation: () => rk, getBroadcastDims: () => rj, getComplexWithIndex: () => s6, getEinsumComputePath: () => f6, getEinsumPermutation: () => p6, getFusedBiasGradient: () => Wu, getFusedDyActivation: () => Gu, getImageCenter: () => WK, getInnerMostAxes: () => Gj, getPermuted: () => jK, getReductionAxes: () => It, getReshaped: () => UK, getReshapedPermuted: () => HK, getSliceBeginCoords: () => qK, getSliceSize: () => KK, getUndoAxesPermutation: () => Rf, isIdentityPermutation: () => d6, log: () => TW, mergeRealAndImagArrays: () => t6, prepareAndValidate: () => f1, prepareSplitSize: () => g6, segment_util: () => Ck, shouldFuse: () => ju, slice_util: () => pr, splitRealAndImagArrays: () => r6, tupleValuesAreOne: () => qn, upcastType: () => hr, validateInput: () => Ug, validateUpdateShape: () => E_, warn: () => Un });
function BK(r, e) {
let t = r[0].length;
r.forEach((o, s) => {
E(o.length === t, () => `Error in concat${t}D: rank of tensors[${s}] must be the same as the rank of the rest (${t})`);
}), E(e >= 0 && e < t, () => `Error in concat${t}D: axis must be between 0 and ${t - 1}.`);
let n = r[0];
r.forEach((o, s) => {
for (let a = 0; a < t; a++)
E(a === e || o[a] === n[a], () => `Error in concat${t}D: Shape of tensors[${s}] (${o}) does not match the shape of the rest (${n}) along the non-concatenated axis ${s}.`);
});
}
function VK(r, e) {
let t = r[0].slice();
for (let n = 1; n < r.length; n++)
t[e] += r[n][e];
return t;
}
var gx = 30;
function GK(r) {
return r <= gx ? r : Vc(r, Math.floor(Math.sqrt(r)));
}
function WK(r, e, t) {
let n = t * (typeof r == "number" ? r : r[0]), o = e * (typeof r == "number" ? r : r[1]);
return [n, o];
}
function UK(r, e, t, n = true) {
let o = [];
if (n)
o = o.concat(e.slice(0)), o.push(r[0] / t), o = o.concat(r.slice(1));
else {
o = o.concat(r[0]);
let s = e.length;
for (let a = 0; a < s; ++a)
o = o.concat([r[a + 1] / e[a], e[a]]);
o = o.concat(r.slice(s + 1));
}
return o;
}
function jK(r, e, t = true) {
let n = [];
if (t) {
n.push(e);
for (let o = e + 1; o < r; ++o)
o <= 2 * e ? (n.push(o), n.push(o - (e + 1))) : n.push(o);
} else {
let o = [], s = [];
for (let a = 1; a < r; ++a)
a >= e * 2 + 1 || a % 2 == 1 ? s.push(a) : o.push(a);
n.push(...o), n.push(0), n.push(...s);
}
return n;
}
function HK(r, e, t, n = true) {
let o = [];
n ? o.push(r[0] / t) : o.push(r[0] * t);
for (let s = 1; s < r.length; ++s)
s <= e.length ? n ? o.push(e[s - 1] * r[s]) : o.push(r[s] / e[s - 1]) : o.push(r[s]);
return o;
}
function qK(r, e) {
let t = [0];
for (let n = 0; n < e; ++n)
t.push(r[n][0]);
return t;
}
function KK(r, e, t) {
let n = r.slice(0, 1);
for (let o = 0; o < t; ++o)
n.push(r[o + 1] - e[o][0] - e[o][1]);
return n;
}
var _k = 1.7580993408473768;
var kk = 1.0507009873554805;
var XK = 0.3275911;
var YK = 0.254829592;
var ZK = -0.284496736;
var JK = 1.421413741;
var QK = -1.453152027;
var e6 = 1.061405429;
function t6(r, e) {
if (r.length !== e.length)
throw new Error(`Cannot merge real and imag arrays of different lengths. real:${r.length}, imag: ${e.length}.`);
let t = new Float32Array(r.length * 2);
for (let n = 0; n < t.length; n += 2)
t[n] = r[n / 2], t[n + 1] = e[n / 2];
return t;
}
function r6(r) {
let e = new Float32Array(r.length / 2), t = new Float32Array(r.length / 2);
for (let n = 0; n < r.length; n += 2)
e[n / 2] = r[n], t[n / 2] = r[n + 1];
return { real: e, imag: t };
}
function n6(r) {
let e = Math.ceil(r.length / 4), t = new Float32Array(e), n = new Float32Array(e);
for (let o = 0; o < r.length; o += 4)
t[Math.floor(o / 4)] = r[o], n[Math.floor(o / 4)] = r[o + 1];
return { real: t, imag: n };
}
function o6(r) {
let e = Math.floor(r.length / 4), t = new Float32Array(e), n = new Float32Array(e);
for (let o = 2; o < r.length; o += 4)
t[Math.floor(o / 4)] = r[o], n[Math.floor(o / 4)] = r[o + 1];
return { real: t, imag: n };
}
function s6(r, e) {
let t = r[e * 2], n = r[e * 2 + 1];
return { real: t, imag: n };
}
function i6(r, e, t, n) {
r[n * 2] = e, r[n * 2 + 1] = t;
}
function a6(r, e) {
let t = new Float32Array(r / 2), n = new Float32Array(r / 2);
for (let o = 0; o < Math.ceil(r / 2); o++) {
let s = (e ? 2 : -2) * Math.PI * (o / r);
t[o] = Math.cos(s), n[o] = Math.sin(s);
}
return { real: t, imag: n };
}
function l6(r, e, t) {
let n = (t ? 2 : -2) * Math.PI * (r / e), o = Math.cos(n), s = Math.sin(n);
return { real: o, imag: s };
}
var vk = "->";
var u6 = /->/g;
var VT = ",";
var GT = "...";
function c6(r, e) {
r = r.replace(/\s/g, "");
let t = (r.length - r.replace(u6, "").length) / vk.length;
if (t < 1)
throw new Error("Equations without an arrow are not supported.");
if (t > 1)
throw new Error(`Equation must contain exactly one arrow ("${vk}").`);
let [n, o] = r.split(vk);
E(n.indexOf(GT) === -1, () => `The ellipsis notation ("${GT}") is not supported yet.`);
let s = n.split(VT), a = s.length;
if (e !== a)
throw new Error(`Expected ${a} input tensors, received ${e}`);
if (a > 2)
throw new Error("Support for more than 2 input tensors is not implemented yet.");
let i = [];
for (let m = 0; m < o.length; ++m) {
let f = o[m];
if (!s.some((d) => d.indexOf(f) !== -1))
throw new Error(`Output subscripts contain the label ${f} not present in the input subscripts.`);
i.indexOf(f) === -1 && i.push(f);
}
for (let m = 0; m < n.length; ++m) {
let f = n[m];
i.indexOf(f) === -1 && f !== VT && i.push(f);
}
let l = new Array(s.length);
for (let m = 0; m < a; ++m) {
if (new Set(s[m].split("")).size !== s[m].length)
throw new Error(`Found duplicate axes in input component ${s[m]}. Support for duplicate axes in input is not implemented yet.`);
l[m] = [];
for (let f = 0; f < s[m].length; ++f)
l[m].push(i.indexOf(s[m][f]));
}
let u = i.length, c = o.length, p = [];
for (let m = c; m < u; ++m)
p.push(m);
return { allDims: i, summedDims: p, idDims: l };
}
function p6(r, e) {
let t = new Array(r);
t.fill(-1);
for (let o = 0; o < e.length; ++o)
t[e[o]] = o;
let n = [];
for (let o = 0; o < r; ++o)
t[o] === -1 && n.push(o);
return t = t.filter((o) => o !== -1), { permutationIndices: t, expandDims: n };
}
function m6(r, e, t) {
let n = new Array(r);
for (let o = 0; o < t.length; ++o) {
let s = t[o].shape;
for (let a = 0; a < e[o].length; ++a)
n[e[o][a]] === void 0 ? n[e[o][a]] = s[a] : E(n[e[o][a]] === s[a], () => `Expected dimension ${n[e[o][a]]} at axis ${a} of input shaped ${JSON.stringify(s)}, but got dimension ${s[a]}`);
}
}
function f6(r, e) {
let t = r, n = [], o = 0;
r.length === 0 && t.push(-1), o = r.length + 1;
for (let a = 0; a < o; ++a)
n.push([]);
let s = [];
for (let a = 0; a < t.length; ++a) {
let i = t[a], l = h6(e, i);
for (let u of l)
s.indexOf(u) === -1 && (n[a].push(u), s.push(u));
}
return { path: t, steps: n };
}
function d6(r) {
return r.every((e, t) => e === t);
}
function h6(r, e) {
let t = [];
for (let n = 0; n < r.length; ++n)
(r[n].length === 0 || r[n].indexOf(e) !== -1 || e === -1) && t.push(n);
return t;
}
function g6(r, e, t = 0) {
let n = [];
if (typeof e == "number")
E(r.shape[t] % e == 0, () => "Number of splits must evenly divide the axis."), n = new Array(e).fill(r.shape[t] / e);
else {
let o = e.reduce((a, i) => (i === -1 && (a += 1), a), 0);
E(o <= 1, () => "There should be only one negative value in split array.");
let s = e.indexOf(-1);
if (s !== -1) {
let a = e.reduce((i, l) => l > 0 ? i + l : i);
e[s] = r.shape[t] - a;
}
E(r.shape[t] === e.reduce((a, i) => a + i), () => "The sum of sizes must match the size of the axis dimension."), n = e;
}
return n;
}
var Ck = {};
qe(Ck, { collectGatherOpShapeInfo: () => b6, computeOutShape: () => y6, segOpComputeOptimalWindowSize: () => x6 });
function x6(r, e) {
let t = false, n;
for (r <= gx ? (n = r, t = true) : n = Vc(r, Math.floor(Math.sqrt(r))); !t; )
n > e || n === r ? t = true : n = Vc(r, n + 1);
return n;
}
function y6(r, e, t) {
let n = [], o = r.length;
for (let s = 0; s < o; s++)
s !== e ? n.push(r[s]) : n.push(t);
return n;
}
function b6(r, e, t, n) {
let o = e.shape.length, s = r.shape.length;
if (n !== 0 && (n < -o || n > o))
throw new Error(`Expect batchDims in the range of [-${o}, ${o}], but got ${n}`);
if (n < 0 && (n += o), n > s)
throw new Error(`batchDims (${n}) must be less than rank(x) (
${s}).`);
if (t < n)
throw new Error(`batchDims (${n}) must be less than or equal to axis (${t}).`);
for (let p = 0; p < n; ++p)
if (r.shape[p] !== e.shape[p])
throw new Error(`x.shape[${p}]: ${r.shape[p]} should be equal to indices.shape[${p}]: ${e.shape[p]}.`);
let a = r.shape[t], i = [], l = 1, u = 1, c = 1;
for (let p = 0; p < n; ++p)
i.push(r.shape[p]), l *= r.shape[p];
for (let p = n; p < t; p++)
i.push(r.shape[p]), u *= r.shape[p];
for (let p = n; p < o; p++)
i.push(e.shape[p]);
for (let p = t + 1; p < s; p++)
i.push(r.shape[p]), c *= r.shape[p];
return { batchSize: l, sliceSize: c, outerSize: u, dimSize: a, outputShape: i };
}
function w6(r) {
try {
return r.map((e) => Tp(e));
} catch (e) {
throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`);
}
}
function _6(r) {
return r.map((e) => Il(e));
}
var Gr = {};
qe(Gr, { nonMaxSuppressionV3Impl: () => cx, nonMaxSuppressionV4Impl: () => px, nonMaxSuppressionV5Impl: () => mx, whereImpl: () => nx });
var xx = { kernelName: ti, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => O(r, Ls(Y(t, "float32"), -1)) };
} };
var WT = { kernelName: Mi, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => {
let n = Ve(Y(t, "float32")), o = bt(le(pe(1), n));
return He(ce(r, o));
} };
} };
var UT = { kernelName: Li, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => {
let n = bt(le(Ve(Y(t, "float32")), 1));
return ce(r, n);
} };
} };
var jT = { kernelName: jn, inputsToSave: ["a", "b"], gradFunc: (r, e) => {
let [t, n] = e, o = We(t.shape, n.shape);
return { a: () => {
let i = r, l = It(t.shape, o);
return l.length > 0 && (i = me(i, l)), F(i, t.shape);
}, b: () => {
let i = r, l = It(n.shape, o);
return l.length > 0 && (i = me(i, l)), F(i, n.shape);
} };
} };
var HT = { kernelName: $o, saveAllInputs: true, gradFunc: (r, e) => {
let t = {};
return e.forEach((n, o) => {
t[o] = () => r.clone();
}), t;
} };
var qT = { kernelName: Ro, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => Se(t) };
} };
var KT = { kernelName: ml, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => Se(t) };
} };
var XT = { kernelName: Vi, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => ce(r, bt(le(pe(1), Ve(Y(t, "float32"))))) };
} };
var YT = { kernelName: Gi, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => {
let n = bt(Z(pe(1), Ve(Y(t, "float32"))));
return ce(r, n);
} };
} };
var ZT = { kernelName: ji, inputsToSave: ["a", "b"], gradFunc: (r, e) => {
let [t, n] = e, o = We(t.shape, n.shape);
return { a: () => {
let i = Z(Ve(t), Ve(n)), l = O(r, ce(n, i)), u = It(t.shape, o);
return u.length > 0 && (l = me(l, u)), F(l, t.shape);
}, b: () => {
let i = Z(Ve(t), Ve(n)), l = He(O(r, ce(t, i))), u = It(n.shape, o);
return u.length > 0 && (l = me(l, u)), F(l, n.shape);
} };
} };
var JT = { kernelName: Wi, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => ce(r, Z(Ve(Y(t, "float32")), 1)) };
} };
var QT = { kernelName: Ui, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => ce(r, le(pe(1), Ve(Y(t, "float32")))) };
} };
function k6(r, e, t, n, o, s) {
let a = k(r, "dy", "avgPool3dGrad"), i = k(e, "input", "avgPool3dGrad"), l = a, u = i, c = false;
i.rank === 4 && (c = true, l = F(a, [1, a.shape[0], a.shape[1], a.shape[2], a.shape[3]]), u = F(i, [1, i.shape[0], i.shape[1], i.shape[2], i.shape[3]])), E(l.rank === 5, () => `Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`), E(u.rank === 5, () => `Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`), s != null && E(it(o), () => `Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${s} but got pad ${o}.`);
let p = { dy: l, input: u }, m = { filterSize: t, strides: n, pad: o, dimRoundingMode: s }, f = T.runKernel(Uc, p, m);
return c ? F(f, [f.shape[1], f.shape[2], f.shape[3], f.shape[4]]) : f;
}
var eE = N({ avgPool3dGrad_: k6 });
var tE = { kernelName: fl, inputsToSave: ["x"], gradFunc: (r, e, t) => {
let [n] = e, { filterSize: o, strides: s, pad: a, dimRoundingMode: i } = t;
return { x: () => eE(r, n, o, s, a, i) };
} };
function v6(r, e, t, n, o) {
let s = k(r, "dy", "avgPoolGrad"), a = k(e, "input", "avgPoolGrad");
E(a.rank === s.rank, () => `Rank of input (${a.rank}) does not match rank of dy (${s.rank})`);
let i = a, l = s, u = false;
a.rank === 3 && (u = true, i = F(a, [1, a.shape[0], a.shape[1], a.shape[2]]), l = F(s, [1, s.shape[0], s.shape[1], s.shape[2]])), E(l.rank === 4, () => `Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`), E(i.rank === 4, () => `Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);
let c = { dy: l, input: i }, p = { filterSize: t, strides: n, pad: o }, m = T.runKernel(Wc, c, p);
return u ? F(m, [m.shape[1], m.shape[2], m.shape[3]]) : m;
}
var rE = N({ avgPoolGrad_: v6 });
var nE = { kernelName: Fo, inputsToSave: ["x"], gradFunc: (r, e, t) => {
let [n] = e, { filterSize: o, strides: s, pad: a } = t;
return { x: () => rE(r, n, o, s, a) };
} };
var oE = { kernelName: Oo, inputsToSave: ["a", "b"], gradFunc: (r, e, t) => {
let [n, o] = e, { transposeA: s, transposeB: a } = t;
return !s && !a ? { a: () => ze(r, o, false, true), b: () => ze(n, r, true, false) } : !s && a ? { a: () => ze(r, o, false, false), b: () => ze(r, n, true, false) } : s && !a ? { a: () => ze(o, r, false, true), b: () => ze(n, r, false, false) } : { a: () => ze(o, r, true, true), b: () => ze(r, n, true, true) };
} };
var sE = { kernelName: ri, gradFunc: (r, e, t) => {
let { blockShape: n, crops: o } = t;
return { x: () => Pa(r, n, o) };
} };
var iE = { kernelName: rN, gradFunc: (r, e, t) => {
let n = t, o = n.inputShape, s = n.shape, a = Array.from(s);
for (let l = o.length - 1; l >= 0; l--)
if (o[l] === s[l])
a[l] = 1;
else if (o[l] !== 1)
throw new Error(`broadcastTo(): [${o}] cannot be broadcast to [${s}].`);
let i = [];
for (let l = 0; l < a.length; l++)
a[l] > 1 && i.push(l);
return { x: () => me(r, i, true) };
} };
var aE = { kernelName: eo, gradFunc: (r) => ({ x: () => r.clone() }) };
var lE = { kernelName: Po, gradFunc: (r) => ({ x: () => Se(r) }) };
var uE = { kernelName: to, inputsToSave: ["x"], gradFunc: (r, e, t) => {
let [n] = e, { clipValueMin: o, clipValueMax: s } = t;
return { x: () => St(Cr(kn(n, o), vn(n, s)), r, Se(r)) };
} };
var cE = { kernelName: dl, inputsToSave: ["x"], gradFunc: xx.gradFunc };
var pE = { kernelName: ni, saveAllInputs: true, gradFunc: (r, e, t) => {
let n = e.map((l) => l.shape), { axis: o } = t, s = cr(o, e[0].shape)[0], a = n.map((l) => l[s]);
return sr(r, a, s).map((l) => () => l);
} };
var mE = { kernelName: Mo, inputsToSave: ["x", "filter"], gradFunc: (r, e, t) => {
let [n, o] = e, { dilations: s, strides: a, pad: i, dataFormat: l } = t;
return E(qn(s), () => `Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`), { x: () => Mp(n.shape, r, o, a, i, l), filter: () => Up(n, r, o.shape, a, i, l) };
} };
var fE = { kernelName: Lo, inputsToSave: ["dy", "filter"], gradFunc: (r, e, t) => {
let [n, o] = e, { strides: s, pad: a, dataFormat: i, dimRoundingMode: l } = t;
return { dy: () => nn(r, o, s, a, i, 1, l), filter: () => Up(r, n, o.shape, s, a, i, l) };
} };
function C6(r, e, t, n, o) {
let s = r;
r.rank === 4 && (s = F(r, [1, r.shape[0], r.shape[1], r.shape[2], r.shape[3]]));
let a = e;
a.rank === 4 && (a = F(e, [1, e.shape[0], e.shape[1], e.shape[2], e.shape[3]])), E(s.rank === 5, () => `Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`), E(a.rank === 5, () => `Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`), E(t.length === 5, () => `Error in conv3dDerFilter: filterShape must be length 5, but got ${t}.`), E(s.shape[4] === t[3], () => `Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${t[3]}.`), E(a.shape[4] === t[4], () => `Error in conv3dDerFilter: depth of dy (${a.shape[4]}) must match output depth for filter (${t[4]}).`);
let i = { x: s, dy: a }, l = { strides: n, pad: o, filterShape: t };
return T.runKernel(Xc, i, l);
}
var dE = N({ conv3DBackpropFilter_: C6 });
var hE = { kernelName: hl, inputsToSave: ["x", "filter"], gradFunc: (r, e, t) => {
let { dilations: n, strides: o, pad: s } = t;
E(qn(n), () => `Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${n}'`);
let [a, i] = e;
return { x: () => Yg(a.shape, r, i, o, s), filter: () => dE(a, r, i.shape, o, s) };
} };
var gE = { kernelName: zo, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => O(He(Mu(Y(t, "float32"))), r) };
} };
var xE = { kernelName: Bo, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => O(Lu(Y(t, "float32")), r) };
} };
var yE = { kernelName: Vo, inputsToSave: ["x"], gradFunc: (r, e, t) => {
let [n] = e, { axis: o, exclusive: s, reverse: a } = t;
return { x: () => {
let i = rk([o], n.rank), l = Su(r, o, s, !a);
return i != null && (l = Be(l, i)), l;
} };
} };
var bE = { kernelName: Go, inputsToSave: ["x", "filter"], gradFunc: (r, e, t) => {
let { dilations: n, strides: o, pad: s, dimRoundingMode: a } = t, i = n == null ? [1, 1] : n;
E(qn(i), () => `Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);
let [l, u] = e;
return E(l.rank === 4, () => `Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`), E(u.rank === 4, () => `Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`), E(l.shape[3] === u.shape[2], () => `Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`), E($r(o, i), () => `Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${i}'.`), a != null && E(it(s), () => `Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`), { x: () => ax(l.shape, r, u, o, s, i, a), filter: () => ix(l, r, u.shape, o, s, i, a) };
} };
var wE = { kernelName: gl, inputsToSave: ["x", "filter"], gradFunc: (r, e, t) => {
let [n, o] = e, s = { x: n, filter: o, dy: r }, a = { x: n, filter: o, dy: r };
return { x: () => T.runKernel(tf, s, t), filter: () => T.runKernel(rf, a, t) };
} };
var _E = { kernelName: Uo, outputsToSave: [true], gradFunc: (r, e) => {
let [t] = e, n = { dy: r, y: t };
return { x: () => T.runKernel(rp, n) };
} };
var kE = { kernelName: Ki, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e, n = O(Kt(He(Ve(t))), 2 / Math.sqrt(Math.PI));
return { x: () => O(r, n) };
} };
var vE = { kernelName: jo, outputsToSave: [true], gradFunc: (r, e) => {
let [t] = e;
return { x: () => O(r, t) };
} };
var CE = { kernelName: oi, inputsToSave: ["input"], gradFunc: (r, e) => {
let [t] = e;
return { input: () => F(r, t.shape) };
} };
var IE = { kernelName: Yi, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => O(r, Kt(t)) };
} };
var SE = { kernelName: Ho, gradFunc: (r) => ({ x: () => Se(r) }) };
var NE = { kernelName: qo, inputsToSave: ["a", "b"], gradFunc: (r, e) => {
let [t, n] = e, o = We(t.shape, n.shape);
return { a: () => {
let i = ce(r, Y(n, "float32")), l = It(t.shape, o);
return l.length > 0 ? F(me(i, l), t.shape) : i;
}, b: () => {
let i = O(r, Y(t, "float32")), l = It(n.shape, o);
l.length > 0 && (i = F(me(i, l), n.shape));
let u = Ve(n);
return He(ce(i, Y(u, "float32")));
} };
} };
var TE = { kernelName: Ko, inputsToSave: ["x", "mean", "variance", "scale"], gradFunc: (r, e, t) => {
let { varianceEpsilon: n } = t, [o, s, a, i] = e, l = i == null ? pe(1) : i, u = It(s.shape, o.shape), c = [];
if (s.rank === 1) {
for (let _ = 0; _ < o.shape.length - 1; ++_)
c.push(o.shape[_]);
c.push(1);
}
let p = le(o, s), m = O(r, l), f = Ou(Z(a, pe(n))), d = O(O(O(f, f), f), pe(-0.5));
return { x: () => s.rank === 1 ? F(O(O(r, vr(F(f, [1, 1, 1, s.shape[0]]), c)), l), o.shape) : F(O(O(r, f), l), o.shape), mean: () => {
let _ = O(O(f, pe(-1)), m);
return s.rank === 1 && (_ = me(_, u)), F(_, s.shape);
}, variance: () => {
let _ = O(O(d, p), m);
return s.rank === 1 && (_ = me(_, u)), F(_, s.shape);
}, scale: () => {
let _ = O(p, f), C = O(r, _);
return s.rank === 1 && (C = me(C, u)), F(C, s.shape);
}, offset: () => {
let _ = r;
return s.rank === 1 && (_ = me(_, u)), F(_, s.shape);
} };
} };
var EE = { kernelName: si, inputsToSave: ["x", "indices"], gradFunc: (r, e, t) => {
let [n, o] = e, { axis: s } = t, a = cr(s, n.shape)[0];
return { x: () => {
let l = n.shape, u = o.size, c = l.slice(0, a), p = c.length, m = l.slice(s, l.length).slice(1), f = m.length, d = AE(0, p), h = AE(p + 1, p + 1 + f), g = DE([c, [u], m]), x = F(r, g), y = F(o, [u]), w = DE([[p], d, h]), _ = Be(x, w), C = Hf(_, y, n.shape[a]), A = Rf(w);
return C = Be(C, A), C;
}, indices: () => o };
} };
function AE(r, e) {
let t = [];
for (let n = r; n < e; ++n)
t.push(n);
return t;
}
function DE(r) {
let e = [];
for (let t = 0; t < r.length; ++t)
for (let n = 0; n < r[t].length; ++n)
e.push(r[t][n]);
return e;
}
var $E = { kernelName: Xo, inputsToSave: ["a", "b"], gradFunc: (r, e) => {
let [t, n] = e;
return { a: () => Se(t), b: () => Se(n) };
} };
var RE = { kernelName: ro, gradFunc: (r) => ({ x: () => Y(r, "float32") }) };
var FE = { kernelName: ea, gradFunc: (r) => ({ x: () => Se(r) }) };
var OE = { kernelName: ta, gradFunc: (r) => ({ x: () => Se(r) }) };
var PE = { kernelName: ra, gradFunc: (r) => ({ x: () => Se(r) }) };
var ME = { kernelName: Yo, inputsToSave: ["x"], gradFunc: (r, e, t) => {
let [n] = e, { alpha: o } = t, s = zt(n, 0);
return { x: () => St(s, r, O(r, o)) };
} };
var LE = { kernelName: sa, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => ce(r, Z(t, 1)) };
} };
var zE = { kernelName: Zo, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => ce(r, Y(t, "float32")) };
} };
var BE = { kernelName: nN, inputsToSave: [], outputsToSave: [true], gradFunc: (r, e, t) => {
let [n] = e, { axis: o } = t;
return { logits: () => {
let s = true, a = Kt(n);
return le(r, O(me(r, o, s), a));
} };
} };
function I6(r, e, t, n = 5, o = 1, s = 1, a = 0.5) {
let i = { x: r, y: e, dy: t }, l = { depthRadius: n, bias: o, alpha: s, beta: a };
return T.runKernel(ap, i, l);
}
var VE = N({ localResponseNormalizationBackprop_: I6 });
var GE = { kernelName: yl, inputsToSave: ["x"], outputsToSave: [true], gradFunc: (r, e, t) => {
let [n, o] = e, { depthRadius: s, bias: a, alpha: i, beta: l } = t;
return { x: () => VE(n, o, r, s, a, i, l) };
} };
function yx(r, e, t, n) {
return e.rank < t.rank && (e = F(e, po(e.shape, n))), r.rank < t.rank && (r = F(r, po(r.shape, n))), { x: () => O(r, Y(kr(t, e), r.dtype)) };
}
var Ik = { kernelName: Jo, inputsToSave: ["x"], outputsToSave: [true], gradFunc: (r, e, t) => {
let n = t, { reductionIndices: o } = n, s = e[0], a = e[1], i = cr(o, s.shape), l = yx(r, a, s, i);
return { x: () => l.x() };
} };
var WE = { kernelName: Qo, inputsToSave: ["a", "b"], gradFunc: (r, e) => {
let [t, n] = e;
return { a: () => O(r, Y(kn(t, n), "float32")), b: () => O(r, Y(Tu(t, n), "float32")) };
} };
function S6(r, e, t, n, o, s, a) {
let i = k(r, "dy", "maxPool3dGrad"), l = k(e, "input", "maxPool3dGrad"), u = k(t, "output", "maxPool3dGrad"), c = i, p = l, m = u, f = false;
l.rank === 4 && (f = true, c = F(i, [1, i.shape[0], i.shape[1], i.shape[2], i.shape[3]]), p = F(l, [1, l.shape[0], l.shape[1], l.shape[2], l.shape[3]]), m = F(u, [1, u.shape[0], u.shape[1], u.shape[2], u.shape[3]])), E(c.rank === 5, () => `Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`), E(p.rank === 5, () => `Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`), E(m.rank === 5, () => `Error in maxPool3dGrad: output must be rank 5 but got rank ${m.rank}.`), a != null && E(it(s), () => `Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);
let d = { dy: c, input: p, output: m }, h = { filterSize: n, strides: o, pad: s, dimRoundingMode: a }, g = T.runKernel(up, d, h);
return f ? F(g, [g.shape[1], g.shape[2], g.shape[3], g.shape[4]]) : g;
}
var UE = N({ maxPool3dGrad_: S6 });
var jE = { kernelName: bl, inputsToSave: ["x"], outputsToSave: [true], gradFunc: (r, e, t) => {
let [n, o] = e, { filterSize: s, strides: a, pad: i, dimRoundingMode: l } = t;
return { x: () => UE(r, n, o, s, a, i, l) };
} };
function N6(r, e, t, n, o, s, a) {
let i = k(r, "dy", "maxPoolGrad"), l = k(e, "input", "maxPoolGrad"), u = k(t, "output", "maxPoolGrad");
E(l.rank === i.rank, () => `Rank of input (${l.rank}) does not match rank of dy (${i.rank})`), E(i.rank === 4, () => `Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`), E(l.rank === 4, () => `Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`), a != null && E(it(s), () => `Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);
let c = { dy: i, input: l, output: u }, p = { filterSize: n, strides: o, pad: s, dimRoundingMode: a };
return T.runKernel(lp, c, p);
}
var HE = N({ maxPoolGrad_: N6 });
var qE = { kernelName: es, inputsToSave: ["x"], outputsToSave: [true], gradFunc: (r, e, t) => {
let [n, o] = e, { filterSize: s, strides: a, pad: i } = t;
return { x: () => HE(r, n, o, s, a, i) };
} };
var KE = { kernelName: ts, inputsToSave: ["x"], gradFunc: (r, e, t) => {
let [n] = e, { axis: o } = t, s = cr(o, n.shape), i = tk(n.shape, s)[1], l = st(i);
return { x: () => {
let c = n.shape.slice();
s.forEach((f) => {
c[f] = 1;
});
let p = F(r, c);
return ce(O(p, or(n.shape, "float32")), l);
} };
} };
var XE = { kernelName: rs, inputsToSave: ["x"], outputsToSave: [true], gradFunc: (r, e, t) => {
let n = t, { axis: o } = n, [s, a] = e, i = cr(o, s.shape), l = yx(r, a, s, i);
return { x: () => l.x() };
} };
var YE = { kernelName: ns, inputsToSave: ["a", "b"], gradFunc: (r, e) => {
let [t, n] = e;
return { a: () => O(r, Y(vn(t, n), "float32")), b: () => O(r, Y(zt(t, n), "float32")) };
} };
var ZE = { kernelName: os, inputsToSave: ["x"], gradFunc: (r, e, t) => {
let n = e[0], { paddings: o } = t, s = o.map((a) => a[0]);
return { x: () => Oe(r, s, n.shape) };
} };
var JE = { kernelName: aa, inputsToSave: ["a", "b"], gradFunc: (r, e) => {
let [t, n] = e, o = We(t.shape, n.shape);
return { a: () => {
let i = It(t.shape, o);
return i.length > 0 ? F(me(r, i), t.shape) : r;
}, b: () => {
let i = O(r, He(Os(ce(t, n)))), l = It(n.shape, o);
return l.length > 0 ? F(me(i, l), n.shape) : i;
} };
} };
var QE = { kernelName: ss, inputsToSave: ["a", "b"], gradFunc: (r, e) => {
let [t, n] = e, o = We(t.shape, n.shape);
return { a: () => {
let i = O(r, Y(n, "float32")), l = It(t.shape, o);
return l.length > 0 ? F(me(i, l), t.shape) : i;
}, b: () => {
let i = O(r, Y(t, "float32")), l = It(n.shape, o);
return l.length > 0 ? F(me(i, l), n.shape) : i;
} };
} };
var e2 = { kernelName: ii, gradFunc: (r) => ({ x: () => He(r) }) };
var t2 = { kernelName: is, inputsToSave: ["indices"], gradFunc: (r, e) => {
let t = e[0];
return { indices: () => yt(t.shape, "float32") };
} };
var r2 = { kernelName: ai, gradFunc: (r) => ({ x: () => Se(r) }) };
var n2 = { kernelName: li, saveAllInputs: true, gradFunc: (r, e, t) => {
let { axis: n } = t;
return yr(r, n).map((s) => () => s);
} };
var Sk = { kernelName: as, inputsToSave: ["x"], gradFunc: (r, e, t) => {
let n = e[0], { paddings: o } = t, s = o.map((a) => a[0]);
return { x: () => Oe(r, s, n.shape) };
} };
var o2 = { kernelName: ls, inputsToSave: ["a", "b"], outputsToSave: [true], gradFunc: (r, e) => {
let [t, n, o] = e, s = t, a = n, i = We(s.shape, a.shape);
return { a: () => {
let c = Y(a, "float32"), p = O(r, O(c, Hr(s, le(c, pe(1))))), m = It(s.shape, i);
return m.length > 0 && (p = me(p, m)), F(p, s.shape);
}, b: () => {
let c = zt(s, 0), p = St(c, xr(s), Se(s)), m = O(r, O(o, p)), f = It(a.shape, i);
return f.length > 0 && (m = me(m, f)), F(m, a.shape);
} };
} };
var s2 = { kernelName: us, inputsToSave: ["x", "alpha"], gradFunc: (r, e) => {
let [t, n] = e, o = zt(t, 0);
return { x: () => St(o, r, O(r, n)), alpha: () => {
let s = St(o, Se(r), O(r, t)), a = It(n.shape, r.shape);
return a.length > 0 && (s = me(s, a)), F(s, n.shape);
} };
} };
var i2 = { kernelName: Wo, inputsToSave: ["a", "b"], gradFunc: (r, e) => {
let [t, n] = e, o = We(t.shape, n.shape);
return { a: () => {
let i = ce(r, Y(n, "float32")), l = It(t.shape, o);
return l.length > 0 ? F(me(i, l), t.shape) : i;
}, b: () => {
let i = O(r, Y(t, "float32")), l = It(n.shape, o);
l.length > 0 && (i = F(me(i, l), n.shape));
let u = Ve(n);
return He(ce(i, Y(u, "float32")));
} };
} };
var a2 = { kernelName: fa, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => ce(r, He(Ve(t))) };
} };
var l2 = { kernelName: ms, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e, n = O(vn(t, 6), Ls(t));
return { x: () => O(r, Y(n, "float32")) };
} };
var u2 = { kernelName: cs, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => O(r, Y(Ls(t), "float32")) };
} };
var c2 = { kernelName: ui, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => F(r, t.shape) };
} };
var p2 = { kernelName: ps, inputsToSave: ["images"], gradFunc: (r, e, t) => {
let [n] = e, o = { dy: r, images: n };
return { images: () => T.runKernel(dp, o, t) };
} };
var m2 = { kernelName: _l, inputsToSave: ["images"], gradFunc: (r, e, t) => {
let [n] = e, o = { dy: r, images: n };
return { images: () => T.runKernel(fp, o, t) };
} };
var f2 = { kernelName: fs, gradFunc: (r, e, t) => {
let { dims: n } = t, o = cr(n, r.shape);
return { x: () => er(r, o) };
} };
var d2 = { kernelName: ds, gradFunc: (r) => ({ x: () => Se(r) }) };
var h2 = { kernelName: hs, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => He(ce(r, O(Hr(t, 1.5), 2))) };
} };
var g2 = { kernelName: ci, inputsToSave: ["condition"], gradFunc: (r, e) => {
let [t] = e;
return { condition: () => Y(Se(t), "float32"), t: () => O(r, Y(t, r.dtype)), e: () => O(r, Y(Fa(t), r.dtype)) };
} };
var x2 = { kernelName: ha, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => {
let n = zt(t, pe(0)), o = pe(_k), s = pe(kk), a = O(r, s), i = O(O(r, o), Kt(Y(t, "float32")));
return St(n, a, i);
} };
} };
var y2 = { kernelName: xs, outputsToSave: [true], gradFunc: (r, e) => {
let [t] = e;
return { x: () => O(r, O(t, le(pe(1), t))) };
} };
var b2 = { kernelName: xa, gradFunc: (r) => ({ x: () => Se(r) }) };
var w2 = { kernelName: gs, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => O(Da(Y(t, "float32")), r) };
} };
var _2 = { kernelName: ga, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => O(Iu(Y(t, "float32")), r) };
} };
var k2 = { kernelName: pi, inputsToSave: ["x"], gradFunc: (r, e, t) => {
let [n] = e, { begin: o, size: s } = t, a = n.shape, [i, l] = A_(n, o, s), u = [];
for (let c = 0; c < r.rank; c++)
u.push([i[c], a[c] - i[c] - l[c]]);
return { x: () => jr(r, u) };
} };
var v2 = { kernelName: ws, outputsToSave: [true], gradFunc: (r, e, t) => {
let [n] = e, { dim: o } = t, s = true, a = O(r, n);
return { logits: () => le(a, O(me(a, [o], s), n)) };
} };
var C2 = { kernelName: ya, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => O(r, zr(t)) };
} };
var Nk = { kernelName: mi, gradFunc: (r, e, t) => {
let { blockShape: n, paddings: o } = t;
return { x: () => Ea(r, n, o) };
} };
var Tk = { kernelName: fi, gradFunc: (r, e, t) => {
let { axis: n } = t;
return { x: () => tt(r, n) };
} };
var I2 = { kernelName: ys, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => ce(r, O(bt(Y(t, "float32")), 2)) };
} };
var S2 = { kernelName: kl, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => O(r, O(Y(t, "float32"), 2)) };
} };
var N2 = { kernelName: _s, inputsToSave: ["a", "b"], gradFunc: (r, e) => {
let [t, n] = e, o = pe(2);
return { a: () => O(r, O(o, le(t, n))), b: () => O(r, O(o, le(n, t))) };
} };
var T2 = { kernelName: no, gradFunc: (r) => ({ x: () => Se(r) }) };
var E2 = { kernelName: ks, inputsToSave: ["a", "b"], gradFunc: (r, e) => {
let [t, n] = e, o = We(t.shape, n.shape);
return { a: () => {
let i = r, l = It(t.shape, o);
return l.length > 0 && (i = me(i, l)), F(i, t.shape);
}, b: () => {
let i = r, l = It(n.shape, o);
return l.length > 0 && (i = me(i, l)), F(He(i), n.shape);
} };
} };
var A2 = { kernelName: bs, inputsToSave: ["x"], gradFunc: (r, e, t) => {
let [n] = e, o = n.shape.slice(), { axis: s } = t;
cr(s, n.shape).forEach((u) => {
o[u] = 1;
});
let i = F(r, o), l = O(i, or(n.shape, "float32"));
return { x: () => l };
} };
var D2 = { kernelName: vs, inputsToSave: ["x"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => ce(r, Ve(Da(t))) };
} };
var $2 = { kernelName: Cs, outputsToSave: [true], gradFunc: (r, e) => {
let [t] = e;
return { x: () => O(le(pe(1), Ve(t)), r) };
} };
var R2 = { kernelName: Hn, inputsToSave: ["x"], gradFunc: (r, e, t) => {
let [n] = e, { reps: o } = t;
return { x: () => {
let a = Se(n);
if (n.rank === 1)
for (let i = 0; i < o[0]; ++i)
a = Z(a, Oe(r, [i * n.shape[0]], [n.shape[0]]));
else if (n.rank === 2)
for (let i = 0; i < o[0]; ++i)
for (let l = 0; l < o[1]; ++l)
a = Z(a, Oe(r, [i * n.shape[0], l * n.shape[1]], [n.shape[0], n.shape[1]]));
else if (n.rank === 3)
for (let i = 0; i < o[0]; ++i)
for (let l = 0; l < o[1]; ++l)
for (let u = 0; u < o[2]; ++u)
a = Z(a, Oe(r, [i * n.shape[0], l * n.shape[1], u * n.shape[2]], [n.shape[0], n.shape[1], n.shape[2]]));
else if (n.rank === 4)
for (let i = 0; i < o[0]; ++i)
for (let l = 0; l < o[1]; ++l)
for (let u = 0; u < o[2]; ++u)
for (let c = 0; c < o[3]; ++c)
a = Z(a, Oe(r, [i * n.shape[0], l * n.shape[1], u * n.shape[2], c * n.shape[3]], [n.shape[0], n.shape[1], n.shape[2], n.shape[3]]));
else
throw new Error(`Gradient for tile operation is not implemented for rank-${n.rank} tensors yet.`);
return a;
} };
} };
var F2 = { kernelName: Is, gradFunc: (r, e, t) => {
let n = t, { perm: o } = n, s = Rf(o);
return { x: () => Be(r, s) };
} };
var O2 = { kernelName: di, gradFunc: (r, e, t) => {
let n = t, { axis: o } = n;
return { value: () => Xt(r, o) };
} };
var P2 = { kernelName: vl, inputsToSave: ["segmentIds"], gradFunc: (r, e) => {
let [t] = e;
return { x: () => T6(r, t) };
} };
function T6(r, e) {
let t = sn(e, Se(e)), n = uo(r, t), o = kn(e, pe(0, "int32")), s = n.rank - o.rank;
for (let i = 0; i < s; ++i)
o = mr(o, i + 1);
o = Cr(o, or(n.shape, "bool"));
let a = Se(n);
return St(o, n, a);
}
var M2 = { kernelName: hi, gradFunc: (r) => ({ x: () => Se(r) }) };
var E6 = [xx, WT, UT, jT, HT, qT, KT, XT, YT, ZT, JT, QT, tE, nE, oE, sE, iE, aE, lE, uE, cE, pE, fE, mE, hE, gE, xE, yE, bE, wE, i2, _E, kE, vE, CE, IE, NE, SE, TE, EE, $E, RE, FE, OE, PE, ME, LE, zE, BE, GE, Ik, Ik, WE, jE, qE, KE, XE, YE, ZE, JE, QE, e2, t2, r2, n2, Sk, Sk, o2, s2, a2, l2, u2, c2, p2, m2, f2, d2, h2, g2, x2, y2, b2, w2, _2, k2, v2, C2, Nk, Nk, Tk, Tk, I2, N2, S2, T2, E2, A2, D2, $2, R2, F2, O2, P2, M2];
for (let r of E6)
oN(r);
M().prototype.abs = function() {
return this.throwIfDisposed(), Ct(this);
};
M().prototype.acos = function() {
return this.throwIfDisposed(), df(this);
};
M().prototype.acosh = function() {
return this.throwIfDisposed(), hf(this);
};
M().prototype.add = function(r) {
return this.throwIfDisposed(), Z(this, r);
};
M().prototype.all = function(r, e) {
return this.throwIfDisposed(), wu(this, r, e);
};
M().prototype.any = function(r, e) {
return this.throwIfDisposed(), El(this, r, e);
};
M().prototype.argMax = function(r) {
return this.throwIfDisposed(), As(this, r);
};
M().prototype.argMin = function(r) {
return this.throwIfDisposed(), gf(this, r);
};
M().prototype.asScalar = function() {
return this.throwIfDisposed(), E(this.size === 1, () => "The array must have only 1 element."), F(this, []);
};
M().prototype.asType = function(r) {
return this.throwIfDisposed(), Y(this, r);
};
M().prototype.as1D = function() {
return this.throwIfDisposed(), F(this, [this.size]);
};
M().prototype.as2D = function(r, e) {
return this.throwIfDisposed(), F(this, [r, e]);
};
M().prototype.as3D = function(r, e, t) {
return this.throwIfDisposed(), F(this, [r, e, t]);
};
M().prototype.as4D = function(r, e, t, n) {
return this.throwIfDisposed(), F(this, [r, e, t, n]);
};
M().prototype.as5D = function(r, e, t, n, o) {
return this.throwIfDisposed(), F(this, [r, e, t, n, o]);
};
M().prototype.asin = function() {
return this.throwIfDisposed(), xf(this);
};
M().prototype.asinh = function() {
return this.throwIfDisposed(), yf(this);
};
M().prototype.atan = function() {
return this.throwIfDisposed(), bf(this);
};
M().prototype.atan2 = function(r) {
return this.throwIfDisposed(), wf(this, r);
};
M().prototype.atanh = function() {
return this.throwIfDisposed(), _f(this);
};
M().prototype.avgPool = function(r, e, t, n) {
return this.throwIfDisposed(), Ta(this, r, e, t, n);
};
M().prototype.batchToSpaceND = function(r, e) {
return this.throwIfDisposed(), Ea(this, r, e);
};
M().prototype.batchNorm = function(r, e, t, n, o) {
return this.throwIfDisposed(), lo(this, r, e, t, n, o);
};
M().prototype.broadcastTo = function(r) {
return this.throwIfDisposed(), Aa(this, r);
};
M().prototype.cast = function(r) {
return this.throwIfDisposed(), Y(this, r);
};
M().prototype.ceil = function() {
return this.throwIfDisposed(), Cf(this);
};
M().prototype.clipByValue = function(r, e) {
return this.throwIfDisposed(), gr(this, r, e);
};
M().prototype.concat = function(r, e) {
return this.throwIfDisposed(), r instanceof Le && (r = [r]), tt([this, ...r], e);
};
M().prototype.conv1d = function(r, e, t, n, o, s) {
return this.throwIfDisposed(), vu(this, r, e, t, n, o, s);
};
M().prototype.conv2dTranspose = function(r, e, t, n, o) {
return this.throwIfDisposed(), Cu(this, r, e, t, n, o);
};
M().prototype.conv2d = function(r, e, t, n, o, s) {
return this.throwIfDisposed(), nn(this, r, e, t, n, o, s);
};
M().prototype.cos = function() {
return this.throwIfDisposed(), Da(this);
};
M().prototype.cosh = function() {
return this.throwIfDisposed(), Iu(this);
};
M().prototype.cumsum = function(r, e, t) {
return this.throwIfDisposed(), Su(this, r, e, t);
};
M().prototype.depthToSpace = function(r, e) {
return this.throwIfDisposed(), Sf(this, r, e);
};
M().prototype.depthwiseConv2d = function(r, e, t, n, o, s) {
return this.throwIfDisposed(), $s(this, r, e, t, n, o, s);
};
M().prototype.dilation2d = function(r, e, t, n, o) {
return this.throwIfDisposed(), Nf(this, r, e, t, n, o);
};
M().prototype.divNoNan = function(r) {
return this.throwIfDisposed(), Tf(this, r);
};
M().prototype.div = function(r) {
return this.throwIfDisposed(), ce(this, r);
};
M().prototype.dot = function(r) {
return this.throwIfDisposed(), K_(this, r);
};
M().prototype.elu = function() {
return this.throwIfDisposed(), Rs(this);
};
M().prototype.equal = function(r) {
return this.throwIfDisposed(), kr(this, r);
};
M().prototype.erf = function() {
return this.throwIfDisposed(), Ef(this);
};
M().prototype.exp = function() {
return this.throwIfDisposed(), Kt(this);
};
M().prototype.expandDims = function(r) {
return this.throwIfDisposed(), mr(this, r);
};
M().prototype.expm1 = function() {
return this.throwIfDisposed(), Af(this);
};
M().prototype.fft = function() {
return this.throwIfDisposed(), Ba(this);
};
M().prototype.flatten = function() {
return this.throwIfDisposed(), F(this, [this.size]);
};
M().prototype.floor = function() {
return this.throwIfDisposed(), Os(this);
};
M().prototype.floorDiv = function(r) {
return this.throwIfDisposed(), bu(this, r);
};
M().prototype.gather = function(r, e) {
return this.throwIfDisposed(), uo(this, r, e);
};
M().prototype.greaterEqual = function(r) {
return this.throwIfDisposed(), kn(this, r);
};
M().prototype.greater = function(r) {
return this.throwIfDisposed(), zt(this, r);
};
M().prototype.ifft = function() {
return this.throwIfDisposed(), _i(this);
};
M().prototype.irfft = function() {
return this.throwIfDisposed(), zu(this);
};
M().prototype.isFinite = function() {
return this.throwIfDisposed(), Y_(this);
};
M().prototype.isInf = function() {
return this.throwIfDisposed(), Z_(this);
};
M().prototype.isNaN = function() {
return this.throwIfDisposed(), Df(this);
};
M().prototype.leakyRelu = function(r) {
return this.throwIfDisposed(), $a(this, r);
};
M().prototype.lessEqual = function(r) {
return this.throwIfDisposed(), vn(this, r);
};
M().prototype.less = function(r) {
return this.throwIfDisposed(), Tu(this, r);
};
M().prototype.localResponseNormalization = function(r, e, t, n) {
return this.throwIfDisposed(), $f(this, r, e, t, n);
};
M().prototype.logSigmoid = function() {
return this.throwIfDisposed(), Q_(this);
};
M().prototype.logSoftmax = function(r) {
return this.throwIfDisposed(), Eu(this, r);
};
M().prototype.logSumExp = function(r, e) {
return this.throwIfDisposed(), Ff(this, r, e);
};
M().prototype.log = function() {
return this.throwIfDisposed(), xr(this);
};
M().prototype.log1p = function() {
return this.throwIfDisposed(), Ra(this);
};
M().prototype.logicalAnd = function(r) {
return this.throwIfDisposed(), Cr(this, r);
};
M().prototype.logicalNot = function() {
return this.throwIfDisposed(), Fa(this);
};
M().prototype.logicalOr = function(r) {
return this.throwIfDisposed(), Au(this, r);
};
M().prototype.logicalXor = function(r) {
return this.throwIfDisposed(), nk(this, r);
};
M().prototype.matMul = function(r, e, t) {
return this.throwIfDisposed(), ze(this, r, e, t);
};
M().prototype.maxPool = function(r, e, t, n) {
return this.throwIfDisposed(), Oa(this, r, e, t, n);
};
M().prototype.max = function(r, e) {
return this.throwIfDisposed(), Rr(this, r, e);
};
M().prototype.maximum = function(r) {
return this.throwIfDisposed(), sn(this, r);
};
M().prototype.mean = function(r, e) {
return this.throwIfDisposed(), xt(this, r, e);
};
M().prototype.min = function(r, e) {
return this.throwIfDisposed(), Al(this, r, e);
};
M().prototype.minimum = function(r) {
return this.throwIfDisposed(), Ps(this, r);
};
M().prototype.mirrorPad = function(r, e) {
return this.throwIfDisposed(), Pf(this, r, e);
};
M().prototype.mod = function(r) {
return this.throwIfDisposed(), Mf(this, r);
};
M().prototype.mul = function(r) {
return this.throwIfDisposed(), O(this, r);
};
M().prototype.neg = function() {
return this.throwIfDisposed(), He(this);
};
M().prototype.norm = function(r, e, t) {
return this.throwIfDisposed(), Wp(this, r, e, t);
};
M().prototype.notEqual = function(r) {
return this.throwIfDisposed(), mo(this, r);
};
M().prototype.oneHot = function(r, e = 1, t = 0) {
return this.throwIfDisposed(), Ts(this, r, e, t);
};
M().prototype.onesLike = function() {
return this.throwIfDisposed(), fr(this);
};
M().prototype.pad = function(r, e) {
return this.throwIfDisposed(), jr(this, r, e);
};
M().prototype.pool = function(r, e, t, n, o) {
return this.throwIfDisposed(), ik(this, r, e, t, n, o);
};
M().prototype.pow = function(r) {
return this.throwIfDisposed(), Hr(this, r);
};
M().prototype.prelu = function(r) {
return this.throwIfDisposed(), Ma(this, r);
};
M().prototype.prod = function(r, e) {
return this.throwIfDisposed(), Du(this, r, e);
};
M().prototype.reciprocal = function() {
return this.throwIfDisposed(), Lf(this);
};
M().prototype.relu = function() {
return this.throwIfDisposed(), Ir(this);
};
M().prototype.relu6 = function() {
return this.throwIfDisposed(), Ru(this);
};
M().prototype.reshapeAs = function(r) {
return this.throwIfDisposed(), F(this, r.shape);
};
M().prototype.reshape = function(r) {
return this.throwIfDisposed(), F(this, r);
};
M().prototype.resizeBilinear = function(r, e, t) {
return this.throwIfDisposed(), fx(this, r, e, t);
};
M().prototype.resizeNearestNeighbor = function(r, e, t) {
return this.throwIfDisposed(), dx(this, r, e, t);
};
M().prototype.reverse = function(r) {
return this.throwIfDisposed(), er(this, r);
};
M().prototype.rfft = function() {
return this.throwIfDisposed(), Va(this);
};
M().prototype.round = function() {
return this.throwIfDisposed(), Fu(this);
};
M().prototype.rsqrt = function() {
return this.throwIfDisposed(), Ou(this);
};
M().prototype.selu = function() {
return this.throwIfDisposed(), Pu(this);
};
M().prototype.separableConv2d = function(r, e, t, n, o, s) {
return this.throwIfDisposed(), zf(this, r, e, t, n, o, s);
};
M().prototype.sigmoid = function() {
return this.throwIfDisposed(), zr(this);
};
M().prototype.sign = function() {
return this.throwIfDisposed(), Bf(this);
};
M().prototype.sin = function() {
return this.throwIfDisposed(), Mu(this);
};
M().prototype.sinh = function() {
return this.throwIfDisposed(), Lu(this);
};
M().prototype.slice = function(r, e) {
return this.throwIfDisposed(), Oe(this, r, e);
};
M().prototype.softmax = function(r) {
return this.throwIfDisposed(), za(this, r);
};
M().prototype.softplus = function() {
return this.throwIfDisposed(), co(this);
};
M().prototype.spaceToBatchND = function(r, e) {
return this.throwIfDisposed(), Pa(this, r, e);
};
M().prototype.split = function(r, e) {
return this.throwIfDisposed(), sr(this, r, e);
};
M().prototype.sqrt = function() {
return this.throwIfDisposed(), bt(this);
};
M().prototype.square = function() {
return this.throwIfDisposed(), Ve(this);
};
M().prototype.squaredDifference = function(r) {
return this.throwIfDisposed(), Bu(this, r);
};
M().prototype.squeeze = function(r) {
return this.throwIfDisposed(), Br(this, r);
};
M().prototype.stack = function(r, e) {
this.throwIfDisposed();
let t = r instanceof Le ? [this, r] : [this, ...r];
return Xt(t, e);
};
M().prototype.step = function(r) {
return this.throwIfDisposed(), Ls(this, r);
};
M().prototype.stridedSlice = function(r, e, t, n, o, s, a, i) {
return this.throwIfDisposed(), Wf(this, r, e, t, n, o, s, a, i);
};
M().prototype.sub = function(r) {
return this.throwIfDisposed(), le(this, r);
};
M().prototype.sum = function(r, e) {
return this.throwIfDisposed(), me(this, r, e);
};
M().prototype.tan = function() {
return this.throwIfDisposed(), Uf(this);
};
M().prototype.tanh = function() {
return this.throwIfDisposed(), Ds(this);
};
M().prototype.tile = function(r) {
return this.throwIfDisposed(), vr(this, r);
};
M().prototype.toBool = function() {
return this.throwIfDisposed(), Y(this, "bool");
};
M().prototype.toFloat = function() {
return this.throwIfDisposed(), Y(this, "float32");
};
M().prototype.toInt = function() {
return this.throwIfDisposed(), Y(this, "int32");
};
M().prototype.topk = function(r, e) {
return this.throwIfDisposed(), jf(this, r, e);
};
M().prototype.transpose = function(r) {
return this.throwIfDisposed(), Be(this, r);
};
M().prototype.unique = function(r) {
return this.throwIfDisposed(), Gp(this, r);
};
M().prototype.unsortedSegmentSum = function(r, e) {
return this.throwIfDisposed(), Hf(this, r, e);
};
M().prototype.unstack = function(r) {
return this.throwIfDisposed(), yr(this, r);
};
M().prototype.where = function(r, e) {
return this.throwIfDisposed(), St(r, this, e);
};
M().prototype.zerosLike = function() {
return this.throwIfDisposed(), Se(this);
};
var W2 = {};
qe(W2, { maxNorm: () => D6, minMaxNorm: () => F6, nonNeg: () => R6, unitNorm: () => $6 });
var Ek;
function ir() {
return Ek == null && (Ek = A1().epsilon()), Ek;
}
function an() {
return "channelsLast";
}
var Mn = class extends Error {
constructor(e) {
super(e);
Object.setPrototypeOf(this, Mn.prototype);
}
};
var Kr = class extends Error {
constructor(e) {
super(e);
Object.setPrototypeOf(this, Kr.prototype);
}
};
var z = class extends Error {
constructor(e) {
super(e);
Object.setPrototypeOf(this, z.prototype);
}
};
var Ne = class extends Error {
constructor(e) {
super(e);
Object.setPrototypeOf(this, Ne.prototype);
}
};
var Xf = class extends Error {
constructor(e) {
super(e);
Object.setPrototypeOf(this, Xf.prototype);
}
};
function go(r, e) {
if (Array.isArray(r)) {
let t = [];
for (let n = 0; n < e; n++)
t = t.concat(r);
return t;
} else {
let t = new Array(e);
return t.fill(r), t;
}
}
function Kn(r, e) {
if (!r)
throw new Xf(e);
}
function Ak(r, e) {
let t = 0;
for (let n of r)
n === e && t++;
return t;
}
function Sr(r) {
return r.length === 1 ? r[0] : r;
}
function wt(r) {
return Array.isArray(r) ? r : [r];
}
function xo(r) {
let t = r.replace(/(.)([A-Z][a-z0-9]+)/g, "$1_$2").replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
return t[0] !== "_" ? t : "private" + t;
}
function Ua(r) {
return r.length <= 1 || r.indexOf("_") === -1 ? r : r.replace(/[_]+(\w|$)/g, (e, t) => t.toUpperCase());
}
var yo = {};
function jp(r) {
if (r == null)
return null;
let e = {};
return e.className = r.getClassName(), e.config = r.getConfig(), e;
}
function Dk(r) {
if (!(r == null || typeof r != "object"))
if (Array.isArray(r))
r.forEach((e) => Dk(e));
else {
let e = Object.keys(r);
for (let t of e) {
let n = r[t];
n != null && typeof n == "object" && (!Array.isArray(n) && n.type === "ndarray" && typeof n.value == "number" ? r[t] = n.value : Dk(n));
}
}
}
function vi(r, e = {}, t = {}, n = "object", o = false) {
if (typeof r == "string") {
let s = r, a;
if (s in t)
a = t[s];
else if (s in yo)
a = yo[s];
else if (a = e[s], a == null)
throw new z(`Unknown ${n}: ${r}. This may be due to one of the following reasons:
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);
return a;
} else {
let s = r;
if (s.className == null || s.config == null)
throw new z(`${n}: Improper config format: ${JSON.stringify(s)}.
'className' and 'config' must set.`);
let a = s.className, i, l;
if (a in t ? [i, l] = t[a] : a in yo ? [i, l] = yo.className : a in e && ([i, l] = e[a]), i == null)
throw new z(`Unknown ${n}: ${a}. This may be due to one of the following reasons:
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);
if (l != null) {
let u = {};
for (let f of Object.keys(yo))
u[f] = yo[f];
for (let f of Object.keys(t))
u[f] = t[f];
let c = s.config;
c.customObjects = u;
let p = Object.assign({}, yo);
for (let f of Object.keys(t))
yo[f] = t[f];
Dk(s.config);
let m = l(i, s.config, t, o);
return yo = Object.assign({}, p), m;
} else {
let u = Object.assign({}, yo);
for (let p of Object.keys(t))
yo[p] = t[p];
let c = new i(s.config);
return yo = Object.assign({}, u), c;
}
}
}
function A6(r, e) {
return r < e ? -1 : r > e ? 1 : 0;
}
function Yf(r, e) {
return -1 * A6(r, e);
}
function bo(r) {
if (r == null)
return r;
let e = [];
for (let t of r)
e.indexOf(t) === -1 && e.push(t);
return e;
}
function L2(r) {
if (r == null)
throw new z(`Invalid value in obj: ${JSON.stringify(r)}`);
for (let e in r)
if (r.hasOwnProperty(e))
return false;
return true;
}
function Ci(r, e, t) {
if (t != null && r.indexOf(t) < 0)
throw new z(`${t} is not a valid ${e}. Valid values are ${r} or null/undefined.`);
}
function bx(r, e, t = 0, n = 1 / 0) {
return Kn(t >= 0), Kn(n >= t), Array.isArray(r) && r.length >= t && r.length <= n && r.every((o) => typeof o === e);
}
function Zt(r, e) {
Array.isArray(r) ? (b.assert(r.length > 0, () => `${e} is unexpectedly an empty array.`), r.forEach((t, n) => Zt(t, `element ${n + 1} of ${e}`))) : b.assert(Number.isInteger(r) && r > 0, () => `Expected ${e} to be a positive integer, but got ${z2(r)}.`);
}
function z2(r) {
return r === null ? "null" : Array.isArray(r) ? "[" + r.map((e) => z2(e)).join(",") + "]" : typeof r == "string" ? `"${r}"` : `${r}`;
}
function B2(r, e, t) {
let n = t != null ? t() : b.now(), o;
return (...a) => {
let i = t != null ? t() : b.now();
return i - n < e || (n = i, o = r(...a)), o;
};
}
function wx(r) {
return r === "relu" ? "relu" : r === "linear" ? "linear" : r === "elu" ? "elu" : null;
}
function $k(r, e) {
return V(() => bt(me(O(r, r), e, true)));
}
var Hp = class extends ee.Serializable {
getConfig() {
return {};
}
};
var Zf = class extends Hp {
constructor(e) {
super();
this.defaultMaxValue = 2, this.defaultAxis = 0, this.maxValue = e.maxValue != null ? e.maxValue : this.defaultMaxValue, this.axis = e.axis != null ? e.axis : this.defaultAxis;
}
apply(e) {
return V(() => {
let t = $k(e, this.axis), n = gr(t, 0, this.maxValue);
return O(e, ce(n, Z(ir(), t)));
});
}
getConfig() {
return { maxValue: this.maxValue, axis: this.axis };
}
};
Zf.className = "MaxNorm";
ee.registerClass(Zf);
var Jf = class extends Hp {
constructor(e) {
super();
this.defaultAxis = 0, this.axis = e.axis != null ? e.axis : this.defaultAxis;
}
apply(e) {
return V(() => ce(e, Z(ir(), $k(e, this.axis))));
}
getConfig() {
return { axis: this.axis };
}
};
Jf.className = "UnitNorm";
ee.registerClass(Jf);
var Qf = class extends Hp {
apply(e) {
return Ir(e);
}
};
Qf.className = "NonNeg";
ee.registerClass(Qf);
var ed = class extends Hp {
constructor(e) {
super();
this.defaultMinValue = 0, this.defaultMaxValue = 1, this.defaultRate = 1, this.defaultAxis = 0, this.minValue = e.minValue != null ? e.minValue : this.defaultMinValue, this.maxValue = e.maxValue != null ? e.maxValue : this.defaultMaxValue, this.rate = e.rate != null ? e.rate : this.defaultRate, this.axis = e.axis != null ? e.axis : this.defaultAxis;
}
apply(e) {
return V(() => {
let t = $k(e, this.axis), n = Z(O(this.rate, gr(t, this.minValue, this.maxValue)), O(1 - this.rate, t));
return O(e, ce(n, Z(ir(), t)));
});
}
getConfig() {
return { minValue: this.minValue, maxValue: this.maxValue, rate: this.rate, axis: this.axis };
}
};
ed.className = "MinMaxNorm";
ee.registerClass(ed);
var V2 = { maxNorm: "MaxNorm", minMaxNorm: "MinMaxNorm", nonNeg: "NonNeg", unitNorm: "UnitNorm" };
function Bt(r) {
return jp(r);
}
function G2(r, e = {}) {
return vi(r, ee.SerializationMap.getMap().classNameMap, e, "constraint");
}
function Vt(r) {
if (r == null)
return null;
if (typeof r == "string") {
let t = { className: r in V2 ? V2[r] : r, config: {} };
return G2(t);
} else
return r instanceof Hp ? r : G2(r);
}
function D6(r) {
return new Zf(r);
}
function $6(r) {
return new Jf(r);
}
function R6() {
return new Qf();
}
function F6(r) {
return new ed(r);
}
var uA = {};
qe(uA, { constant: () => G6, glorotNormal: () => X6, glorotUniform: () => K6, heNormal: () => Y6, heUniform: () => Z6, identity: () => H6, leCunNormal: () => J6, leCunUniform: () => Q6, ones: () => V6, orthogonal: () => e5, randomNormal: () => U6, randomUniform: () => W6, truncatedNormal: () => j6, varianceScaling: () => q6, zeros: () => B6 });
var U2 = ["channelsFirst", "channelsLast"];
var j2 = ["nearest", "bilinear"];
var H2 = ["valid", "same", "causal"];
var q2 = ["max", "avg"];
var K2 = ["sum", "mul", "concat", "ave"];
var qp = new Map();
function Ot(r) {
Ci(U2, "DataFormat", r);
}
function X2(r) {
Ci(j2, "InterpolationFormat", r);
}
function ln(r) {
Ci(H2, "PaddingMode", r);
}
function Rk(r) {
Ci(q2, "PoolMode", r);
}
var td = [];
var Y2 = "/";
function zs(r, e) {
td.push(r);
try {
let t = e();
return td.pop(), t;
} catch (t) {
throw td.pop(), t;
}
}
function O6() {
return td.length === 0 ? "" : td.join(Y2) + Y2;
}
function _x(r) {
if (!Z2(r))
throw new Error("Not a valid tensor name: '" + r + "'");
return O6() + r;
}
function kx(r) {
if (!Z2(r))
throw new Error("Not a valid tensor name: '" + r + "'");
qp.has(r) || qp.set(r, 0);
let e = qp.get(r);
if (qp.set(r, qp.get(r) + 1), e > 0) {
let t = `${r}_${e}`;
return qp.set(t, 1), t;
} else
return r;
}
var P6 = new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);
function Z2(r) {
return !!r.match(P6);
}
function J2(r) {
return r === parseInt(r.toString(), 10);
}
function wo(r, e, t) {
e == null && (e = 0), t == null && (t = r.length);
let n = 1;
for (let o = e; o < t; ++o)
n *= r[o];
return n;
}
function Qu(r) {
if (r.length === 0)
return Number.NaN;
let e = Number.POSITIVE_INFINITY;
for (let t = 0; t < r.length; t++) {
let n = r[t];
n < e && (e = n);
}
return e;
}
function Bs(r) {
if (r.length === 0)
return Number.NaN;
let e = Number.NEGATIVE_INFINITY;
for (let t = 0; t < r.length; t++) {
let n = r[t];
n > e && (e = n);
}
return e;
}
function Xr(r, e) {
if (e < r)
throw new z(`end (${e}) < begin (${r}) is forbidden.`);
let t = [];
for (let n = r; n < e; ++n)
t.push(n);
return t;
}
function ec(r, e) {
return Y(r, e);
}
function ja(r, e = -1) {
let t = r.shape.slice();
return e < 0 && (e = t.length + e + 1), t.splice(e, 0, 1), F(r, t);
}
function Q2(r, e) {
return V(() => {
if (r.shape.length !== 2)
throw new z(`repeat() expects a rank-2 tensor, but received a rank-${r.shape.length} tensor.`);
let t = ja(r, 1);
return vx(t, [1, e, 1]);
});
}
function eA(r) {
let e = [wo(r.shape)];
return F(r, e);
}
function tA(r) {
if (r.rank <= 1)
throw new z(`batchFlatten requires a minimum rank of 2. Got rank: ${r.rank}.`);
let e = [r.shape[0], wo(r.shape, 1)];
return F(r, e);
}
function Ha(r, e, t) {
return V(() => {
switch (r.rank) {
case 1:
return Vf(r, e, t);
case 2:
return rx(r, [e, 0], [t, r.shape[1]]);
case 3:
return Gf(r, [e, 0, 0], [t, r.shape[1], r.shape[2]]);
case 4:
return Vp(r, [e, 0, 0, 0], [t, r.shape[1], r.shape[2], r.shape[3]]);
case 5:
return Oe(r, [e, 0, 0, 0, 0], [t, r.shape[1], r.shape[2], r.shape[3], r.shape[4]]);
case 6:
return Oe(r, [e, 0, 0, 0, 0, 0], [t, r.shape[1], r.shape[2], r.shape[3], r.shape[4], r.shape[5]]);
default:
throw new z(`sliceAlongFirstAxis() received an unsupported tensor rank: ${r.rank}`);
}
});
}
function Fk(r, e, t) {
return V(() => {
switch (r.rank) {
case 1:
return Vf(r, e, t);
case 2:
return rx(r, [0, e], [r.shape[0], t]);
case 3:
return Gf(r, [0, 0, e], [r.shape[0], r.shape[1], t]);
case 4:
return Vp(r, [0, 0, 0, e], [r.shape[0], r.shape[1], r.shape[2], t]);
default:
throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${r.rank}`);
}
});
}
function rd(r, e, t, n) {
return V(() => {
switch (r.rank) {
case 1:
return Vf(r, e, t);
case 2:
switch (n) {
case 1:
return Ha(r, e, t);
case 2:
return Fk(r, e, t);
default:
throw new z(`The axis is not within the rank of the tensor ${n}`);
}
case 3:
switch (n) {
case 1:
return Ha(r, e, t);
case 2:
return Gf(r, [0, e, 0], [r.shape[0], t, r.shape[2]]);
case 3:
return Fk(r, e, t);
default:
throw new z(`The axis is not within the rank of the tensor ${n}`);
}
case 4:
switch (n) {
case 1:
return Ha(r, e, t);
case 2:
return Vp(r, [0, e, 0, 0], [r.shape[0], t, r.shape[2], r.shape[3]]);
case 3:
return Vp(r, [0, 0, e, 0], [r.shape[0], r.shape[1], t, r.shape[3]]);
case 4:
return Fk(r, e, t);
default:
throw new z(`The axis is not within the rank of the tensor ${n}`);
}
default:
throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${r.rank}`);
}
});
}
function Kp(r, e = -1) {
let t;
return e < 0 && (t = r[0].rank, t !== 0 ? e = t : e = 0), e === r[0].rank && (e = -1), tt(r, e);
}
function Ok(r, e) {
switch (r.rank) {
case 1:
return G_([r, e]);
case 2:
return W_([r, e], 0);
case 3:
return U_([r, e], 0);
case 4:
return j_([r, e], 0);
default:
throw new z(`concatAlongFirstAxis() received an unsupported tensor rank: ${r.rank}`);
}
}
function vx(r, e) {
if (Array.isArray(e) || (e = [e]), r.rank !== e.length)
throw new z(`The length of input n (${e.length}) does not match the number of dimensions in input x (${r.rank})`);
return vr(r, e);
}
function Xp(r, e = 0, t = 1, n, o) {
return tx(r, e, t, n, o);
}
function _o(r, e, t, n) {
if (r.rank < 2 || e.rank < 2)
throw new Ne(`dot requires both inputs to be rank >= 2 but got x shape = ${r.shape} and y shape = ${e.shape}`);
if (e.rank >= 3) {
let o = r.shape.slice(-1)[0], s = e.shape.slice(-2)[0];
if (o !== s)
throw new Ne(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${r.shape} and y shape = ${e.shape}`);
}
if (r.rank === 2 && e.rank === 2) {
let o = false, s = false;
return fo.matMul({ a: r, b: e, transposeA: o, transposeB: s, bias: n ? Pk(r.rank, n, an()) : null, activation: t });
} else {
let o = r.shape.slice(), s = o.pop();
r = F(r, [-1, s]);
let a = e.shape.slice(), i = a.pop(), l = a.pop(), u = [...a, i], c = Array.from({ length: e.rank }, (d, h) => h === 0 ? e.rank - 2 : h <= e.rank - 2 ? h - 1 : h);
e = F(Be(e, c), [l, -1]);
let p = [...o, ...u], m = false, f = false;
return F(fo.matMul({ a: r, b: e, transposeA: m, transposeB: f, bias: n ? Pk(r.rank, n, an()) : null, activation: t }), p);
}
}
function Cx(r, e, t) {
return V(() => (Array.isArray(e) ? e = $t(e, "int32") : e = Y(e, "int32"), uo(r, e, t)));
}
function tc(r) {
return O(r, r);
}
function Pk(r, e, t) {
let n = e.shape;
if (e.rank !== 1 && e.rank !== r)
throw new z(`Unexpected bias dimensions: ${e.rank}; expected it to be 1 or ${r}`);
if (r === 5) {
if (t === "channelsFirst")
return n.length === 1 ? F(e, [1, n[0], 1, 1, 1]) : F(e, [1, n[3], n[0], n[1], n[2]]);
if (t === "channelsLast")
return n.length === 1 ? F(e, [1, 1, 1, 1, n[0]]) : F(e, [1].concat(n));
} else if (r === 4) {
if (t === "channelsFirst")
return n.length === 1 ? F(e, [1, n[0], 1, 1]) : F(e, [1, n[2], n[0], n[1]]);
if (t === "channelsLast")
return n.length === 1 ? F(e, [1, 1, 1, n[0]]) : F(e, [1].concat(n));
} else if (r === 3) {
if (t === "channelsFirst")
return n.length === 1 ? F(e, [1, n[0], 1]) : F(e, [1, n[1], n[0]]);
if (t === "channelsLast")
return n.length === 1 ? F(e, [1, 1, n[0]]) : F(e, [1].concat(n));
} else if (r < 3)
return e;
throw new z(`Unsupported input rank by biasAdd: ${e.rank}`);
}
function un(r, e, t) {
return V(() => (t == null && (t = an()), Ot(t), Z(r, Pk(r.rank, e, t))));
}
function rA(r, e = 1) {
if (e !== 1)
throw new Ne(`Support for alpha values other than 1 (${e}) is not implemented yet.`);
return Rs(r);
}
function nA(r) {
return V(() => ce(r, Z(Ct(r), 1)));
}
function Ix(r, e, t, n) {
return V(() => eT(r, e, t, n));
}
function oA(r) {
return V(() => {
let e = Z(0.5, O(0.2, r));
return gr(e, 0, 1);
});
}
function $l(r, e, t = false) {
return t ? r() : e();
}
var sA = ["fanIn", "fanOut", "fanAvg"];
var iA = ["normal", "uniform", "truncatedNormal"];
function M6(r) {
Ci(sA, "FanMode", r);
}
function L6(r) {
Ci(iA, "Distribution", r);
}
var In = class extends ee.Serializable {
fromConfigUsesCustomObjects() {
return false;
}
getConfig() {
return {};
}
};
var nd = class extends In {
apply(e, t) {
return yt(e, t);
}
};
nd.className = "Zeros";
ee.registerClass(nd);
var rc = class extends In {
apply(e, t) {
return or(e, t);
}
};
rc.className = "Ones";
ee.registerClass(rc);
var od = class extends In {
constructor(e) {
super();
if (typeof e != "object")
throw new z(`Expected argument of type ConstantConfig but got ${e}`);
if (e.value === void 0)
throw new z(`config must have value set but got ${e}`);
this.value = e.value;
}
apply(e, t) {
return V(() => O(pe(this.value), or(e, t)));
}
getConfig() {
return { value: this.value };
}
};
od.className = "Constant";
ee.registerClass(od);
var sd = class extends In {
constructor(e) {
super();
this.DEFAULT_MINVAL = -0.05, this.DEFAULT_MAXVAL = 0.05, this.minval = e.minval || this.DEFAULT_MINVAL, this.maxval = e.maxval || this.DEFAULT_MAXVAL, this.seed = e.seed;
}
apply(e, t) {
return Ms(e, this.minval, this.maxval, t);
}
getConfig() {
return { minval: this.minval, maxval: this.maxval, seed: this.seed };
}
};
sd.className = "RandomUniform";
ee.registerClass(sd);
var id = class extends In {
constructor(e) {
super();
this.DEFAULT_MEAN = 0, this.DEFAULT_STDDEV = 0.05, this.mean = e.mean || this.DEFAULT_MEAN, this.stddev = e.stddev || this.DEFAULT_STDDEV, this.seed = e.seed;
}
apply(e, t) {
if (t = t || "float32", t !== "float32" && t !== "int32")
throw new Ne(`randomNormal does not support dType ${t}.`);
return Xp(e, this.mean, this.stddev, t, this.seed);
}
getConfig() {
return { mean: this.mean, stddev: this.stddev, seed: this.seed };
}
};
id.className = "RandomNormal";
ee.registerClass(id);
var ad = class extends In {
constructor(e) {
super();
this.DEFAULT_MEAN = 0, this.DEFAULT_STDDEV = 0.05, this.mean = e.mean || this.DEFAULT_MEAN, this.stddev = e.stddev || this.DEFAULT_STDDEV, this.seed = e.seed;
}
apply(e, t) {
if (t = t || "float32", t !== "float32" && t !== "int32")
throw new Ne(`truncatedNormal does not support dType ${t}.`);
return Vu(e, this.mean, this.stddev, t, this.seed);
}
getConfig() {
return { mean: this.mean, stddev: this.stddev, seed: this.seed };
}
};
ad.className = "TruncatedNormal";
ee.registerClass(ad);
var ld = class extends In {
constructor(e) {
super();
this.gain = e.gain != null ? e.gain : 1;
}
apply(e, t) {
return V(() => {
if (e.length !== 2 || e[0] !== e[1])
throw new z("Identity matrix initializer can only be used for 2D square matrices.");
return O(this.gain, Lp(e[0]));
});
}
getConfig() {
return { gain: this.gain };
}
};
ld.className = "Identity";
ee.registerClass(ld);
function z6(r, e = "channelsLast") {
let t, n;
if (Ot(e), r.length === 2)
t = r[0], n = r[1];
else if ([3, 4, 5].indexOf(r.length) !== -1) {
if (e === "channelsFirst") {
let o = wo(r, 2);
t = r[1] * o, n = r[0] * o;
} else if (e === "channelsLast") {
let o = wo(r, 0, r.length - 2);
t = r[r.length - 2] * o, n = r[r.length - 1] * o;
}
} else {
let o = wo(r);
t = Math.sqrt(o), n = Math.sqrt(o);
}
return [t, n];
}
var Yr = class extends In {
constructor(e) {
super();
if (e.scale < 0)
throw new z(`scale must be a positive float. Got: ${e.scale}`);
this.scale = e.scale == null ? 1 : e.scale, this.mode = e.mode == null ? "fanIn" : e.mode, M6(this.mode), this.distribution = e.distribution == null ? "normal" : e.distribution, L6(this.distribution), this.seed = e.seed;
}
apply(e, t) {
let n = z6(e), o = n[0], s = n[1], a = this.scale;
if (this.mode === "fanIn" ? a /= Math.max(1, o) : this.mode === "fanOut" ? a /= Math.max(1, s) : a /= Math.max(1, (o + s) / 2), this.distribution === "normal") {
let i = Math.sqrt(a);
if (t = t || "float32", t !== "float32" && t !== "int32")
throw new Ne(`${this.getClassName()} does not support dType ${t}.`);
return Vu(e, 0, i, t, this.seed);
} else {
let i = Math.sqrt(3 * a);
return Ms(e, -i, i, t);
}
}
getConfig() {
return { scale: this.scale, mode: this.mode, distribution: this.distribution, seed: this.seed };
}
};
Yr.className = "VarianceScaling";
ee.registerClass(Yr);
var Yp = class extends Yr {
constructor(e) {
super({ scale: 1, mode: "fanAvg", distribution: "uniform", seed: e == null ? null : e.seed });
}
getClassName() {
return Yr.className;
}
};
Yp.className = "GlorotUniform";
ee.registerClass(Yp);
var Zp = class extends Yr {
constructor(e) {
super({ scale: 1, mode: "fanAvg", distribution: "normal", seed: e == null ? null : e.seed });
}
getClassName() {
return Yr.className;
}
};
Zp.className = "GlorotNormal";
ee.registerClass(Zp);
var Jp = class extends Yr {
constructor(e) {
super({ scale: 2, mode: "fanIn", distribution: "normal", seed: e == null ? null : e.seed });
}
getClassName() {
return Yr.className;
}
};
Jp.className = "HeNormal";
ee.registerClass(Jp);
var Qp = class extends Yr {
constructor(e) {
super({ scale: 2, mode: "fanIn", distribution: "uniform", seed: e == null ? null : e.seed });
}
getClassName() {
return Yr.className;
}
};
Qp.className = "HeUniform";
ee.registerClass(Qp);
var em = class extends Yr {
constructor(e) {
super({ scale: 1, mode: "fanIn", distribution: "normal", seed: e == null ? null : e.seed });
}
getClassName() {
return Yr.className;
}
};
em.className = "LeCunNormal";
ee.registerClass(em);
var tm = class extends Yr {
constructor(e) {
super({ scale: 1, mode: "fanIn", distribution: "uniform", seed: e == null ? null : e.seed });
}
getClassName() {
return Yr.className;
}
};
tm.className = "LeCunNormal";
ee.registerClass(tm);
var ud = class extends In {
constructor(e) {
super();
if (this.DEFAULT_GAIN = 1, this.gain = e.gain == null ? this.DEFAULT_GAIN : e.gain, this.seed = e.seed, this.seed != null)
throw new Ne("Random seed is not implemented for Orthogonal Initializer yet.");
}
apply(e, t) {
return V(() => {
if (e.length < 2)
throw new Ne("Shape must be at least 2D.");
e[0] * e[1] > 2e3 && console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0] * e[1]}) elements: Slowness may result.`);
let n = e[0] > e[1] ? [e[1], e[0]] : e, o = Xp(n, 0, 1, "float32"), s = BT.gramSchmidt(o);
return e[0] > e[1] && (s = Be(s)), O(this.gain, s);
});
}
getConfig() {
return { gain: this.gain, seed: this.seed };
}
};
ud.className = "Orthogonal";
ee.registerClass(ud);
var aA = { constant: "Constant", glorotNormal: "GlorotNormal", glorotUniform: "GlorotUniform", heNormal: "HeNormal", heUniform: "HeUniform", identity: "Identity", leCunNormal: "LeCunNormal", leCunUniform: "LeCunUniform", ones: "Ones", orthogonal: "Orthogonal", randomNormal: "RandomNormal", randomUniform: "RandomUniform", truncatedNormal: "TruncatedNormal", varianceScaling: "VarianceScaling", zeros: "Zeros" };
function lA(r, e = {}) {
return vi(r, ee.SerializationMap.getMap().classNameMap, e, "initializer");
}
function Nt(r) {
return jp(r);
}
function dt(r) {
if (typeof r == "string") {
let e = r in aA ? aA[r] : r;
if (e === "GlorotNormal")
return new Zp();
if (e === "GlorotUniform")
return new Yp();
if (e === "HeNormal")
return new Jp();
if (e === "HeUniform")
return new Qp();
if (e === "LeCunNormal")
return new em();
if (e === "LeCunUniform")
return new tm();
{
let t = {};
return t.className = e, t.config = {}, lA(t);
}
} else
return r instanceof In ? r : lA(r);
}
function B6() {
return new nd();
}
function V6() {
return new rc();
}
function G6(r) {
return new od(r);
}
function W6(r) {
return new sd(r);
}
function U6(r) {
return new id(r);
}
function j6(r) {
return new ad(r);
}
function H6(r) {
return new ld(r);
}
function q6(r) {
return new Yr(r);
}
function K6(r) {
return new Yp(r);
}
function X6(r) {
return new Zp(r);
}
function Y6(r) {
return new Jp(r);
}
function Z6(r) {
return new Qp(r);
}
function J6(r) {
return new em(r);
}
function Q6(r) {
return new tm(r);
}
function e5(r) {
return new ud(r);
}
var UA = {};
qe(UA, { Layer: () => Ge, RNN: () => Ln, RNNCell: () => Vl, activation: () => v8, add: () => $8, alphaDropout: () => hX, average: () => R8, averagePooling1d: () => vv, averagePooling2d: () => Cv, averagePooling3d: () => Iv, avgPool1d: () => G8, avgPool2d: () => U8, avgPool3d: () => H8, avgPooling1d: () => W8, avgPooling2d: () => j8, avgPooling3d: () => q8, batchNormalization: () => z8, bidirectional: () => aX, concatenate: () => F8, conv1d: () => d8, conv2d: () => h8, conv2dTranspose: () => g8, conv3d: () => x8, conv3dTranspose: () => y8, convLstm2d: () => nX, convLstm2dCell: () => oX, cropping2D: () => w8, dense: () => C8, depthwiseConv2d: () => k8, dot: () => L8, dropout: () => I8, elu: () => l8, embedding: () => D8, flatten: () => N8, gaussianDropout: () => dX, gaussianNoise: () => fX, globalAveragePooling1d: () => K8, globalAveragePooling2d: () => X8, globalMaxPool1d: () => uX, globalMaxPool2d: () => cX, globalMaxPooling1d: () => BA, globalMaxPooling2d: () => VA, gru: () => Z8, gruCell: () => J8, input: () => Xk, inputLayer: () => a8, layerNormalization: () => B8, leakyReLU: () => c8, lstm: () => Q8, lstmCell: () => eX, masking: () => gX, maxPool1d: () => pX, maxPool2d: () => mX, maxPooling1d: () => GA, maxPooling2d: () => WA, maxPooling3d: () => Y8, maximum: () => O8, minimum: () => P8, multiply: () => M8, permute: () => A8, prelu: () => p8, reLU: () => u8, repeatVector: () => T8, reshape: () => E8, rnn: () => sX, separableConv2d: () => b8, simpleRNN: () => tX, simpleRNNCell: () => rX, softmax: () => m8, spatialDropout1d: () => S8, stackedRNNCells: () => iX, thresholdedReLU: () => f8, timeDistributed: () => lX, upSampling2d: () => _8, zeroPadding2d: () => V8 });
var t5 = 0;
function Sx() {
return t5++;
}
var Nx = {};
function Rl(r = "") {
return r in Nx || (Nx[r] = 0), Nx[r] += 1, r + Nx[r].toString();
}
function Tx(r) {
return Array.isArray(r) && Array.isArray(r[0]);
}
function rm(r) {
return r.length === 0 ? [] : Array.isArray(r[0]) ? r : [r];
}
function Me(r) {
let e;
if (Array.isArray(r)) {
if (r.length !== 1)
throw new z(`Expected Tensor length to be 1; got ${r.length}`);
e = r[0];
} else
e = r;
return e;
}
function Xe(r) {
if (Array.isArray(r) && Array.isArray(r[0])) {
if (r.length === 1)
return r = r, r[0];
throw new z(`Expected exactly 1 Shape; got ${r.length}`);
} else
return r;
}
function nm(r) {
let e = 0;
for (let t of r)
t.shape.length === 0 ? e += 1 : e += t.shape.reduce((n, o) => n * o);
return e;
}
var cA = "Variable";
var Ex = class {
constructor(e, t = "float32", n = cA, o = true, s = null) {
this.dtype = t == null ? "float32" : t, this.shape = e.shape, this.id = Sx(), n = n == null ? cA : n, this.originalName = _x(n), this.name = kx(this.originalName), this.trainable_ = o, this.constraint = s, this.val = yk(e, this.trainable_, this.name, this.dtype);
}
read() {
return this.assertNotDisposed(), this.val;
}
write(e) {
return this.assertNotDisposed(), r5(this.val, e), this.val.id !== e.id && (this.val.assign(e), this.constraint != null && this.val.assign(this.constraint.apply(this.val))), this;
}
dispose() {
this.assertNotDisposed(), this.val.dispose();
}
assertNotDisposed() {
if (this.val.isDisposed)
throw new Error(`LayersVariable ${this.name} is already disposed.`);
}
get trainable() {
return this.trainable_;
}
set trainable(e) {
this.trainable_ = e, this.val.trainable = e;
}
};
function r5(r, e) {
if (r.shape.toString() !== e.shape.toString())
throw new Error("Shape mismatch: " + JSON.stringify(r.shape) + " vs. " + JSON.stringify(e.shape));
}
function cd(r) {
return r.map((e) => e.read());
}
function om(r) {
r.forEach((e) => {
e[0].write(e[1]);
});
}
var Tt = class {
constructor(e) {
this.dtype = e.dtype, this.shape = e.shape, e.shape != null ? this.ndim = e.shape.length : this.ndim = e.ndim, this.maxNDim = e.maxNDim, this.minNDim = e.minNDim, this.axes = e.axes || {};
}
};
var cn = class {
constructor(e, t, n, o, s, a, i) {
this.dtype = e, this.shape = t, this.sourceLayer = n, this.inputs = o, this.callArgs = s, this.outputTensorIndex = i, this.id = Sx(), a != null && (this.originalName = _x(a), this.name = kx(this.originalName)), this.rank = t.length;
}
};
var n5 = 0;
var Fl = class {
constructor(e, t) {
this.callArgs = t, this.id = n5++, this.outboundLayer = e.outboundLayer, this.inboundLayers = e.inboundLayers, this.nodeIndices = e.nodeIndices, this.tensorIndices = e.tensorIndices, this.inputTensors = e.inputTensors, this.outputTensors = e.outputTensors, this.inputMasks = e.inputMasks, this.outputMasks = e.outputMasks, this.inputShapes = e.inputShapes, this.outputShapes = e.outputShapes;
for (let n of e.inboundLayers)
n != null && n.outboundNodes.push(this);
e.outboundLayer.inboundNodes.push(this);
}
getConfig() {
let e = [];
for (let t of this.inboundLayers)
t != null ? e.push(t.name) : e.push(null);
return { outboundLayer: this.outboundLayer ? this.outboundLayer.name : null, inboundLayers: e, nodeIndices: this.nodeIndices, tensorIndices: this.tensorIndices };
}
};
var o5 = 0;
var Ge = class extends ee.Serializable {
constructor(e = {}) {
super();
this._callHook = null, this._addedWeightNames = [], this._stateful = false, this.id = o5++, this.activityRegularizer = null, this.inputSpec = null, this.supportsMasking = false, this._trainableWeights = [], this._nonTrainableWeights = [], this._losses = [], this._updates = [], this._built = false, this.inboundNodes = [], this.outboundNodes = [];
let t = e.name;
if (!t) {
let n = this.getClassName();
t = xo(n) + "_" + Rl(n);
}
if (this.name = t, this.trainable_ = e.trainable == null ? true : e.trainable, e.inputShape != null || e.batchInputShape != null) {
let n;
if (e.batchInputShape != null)
n = e.batchInputShape;
else if (e.inputShape != null) {
let s = null;
e.batchSize != null && (s = e.batchSize), n = [s].concat(e.inputShape);
}
this.batchInputShape = n;
let o = e.dtype;
o == null && (o = e.inputDType), o == null && (o = "float32"), this.dtype = o;
}
e.weights != null ? this.initialWeights = e.weights : this.initialWeights = null, this._refCount = null, this.fastWeightInitDuringBuild = false;
}
static nodeKey(e, t) {
return e.name + "_ib-" + t.toString();
}
getNodeAtIndex(e, t) {
if (this.inboundNodes.length === 0)
throw new Kr(`The layer has never been called and thus has no defined ${t}.`);
if (this.inboundNodes.length <= e)
throw new z(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);
return this.inboundNodes[e];
}
getInputAt(e) {
return Sr(this.getNodeAtIndex(e, "input").inputTensors);
}
getOutputAt(e) {
return Sr(this.getNodeAtIndex(e, "output").outputTensors);
}
get input() {
if (this.inboundNodes.length > 1)
throw new Mn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);
if (this.inboundNodes.length === 0)
throw new Mn(`Layer ${this.name} is not connected, no input to return.`);
return Sr(this.getNodeAtIndex(0, "input").inputTensors);
}
get output() {
if (this.inboundNodes.length === 0)
throw new Mn(`Layer ${this.name} has no inbound nodes.`);
if (this.inboundNodes.length > 1)
throw new Mn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);
return Sr(this.getNodeAtIndex(0, "output").outputTensors);
}
get losses() {
return this._losses;
}
calculateLosses() {
return this.losses.map((e) => e());
}
get updates() {
return this._updates;
}
get built() {
return this._built;
}
set built(e) {
this._built = e;
}
get trainable() {
return this.trainable_;
}
set trainable(e) {
this._trainableWeights.forEach((t) => t.trainable = e), this.trainable_ = e;
}
get trainableWeights() {
return this.trainable_ ? this._trainableWeights.filter((e) => e.trainable) : [];
}
set trainableWeights(e) {
this._trainableWeights = e;
}
get nonTrainableWeights() {
return this.trainable ? this._trainableWeights.filter((e) => !e.trainable).concat(this._nonTrainableWeights) : this._trainableWeights.concat(this._nonTrainableWeights);
}
set nonTrainableWeights(e) {
this._nonTrainableWeights = e;
}
get weights() {
return this.trainableWeights.concat(this.nonTrainableWeights);
}
get stateful() {
return this._stateful;
}
resetStates() {
if (!this.stateful)
throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.");
}
assertInputCompatibility(e) {
if (e = wt(e), this.inputSpec == null || this.inputSpec.length === 0)
return;
let t = wt(this.inputSpec);
if (e.length !== t.length)
throw new z(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);
for (let n = 0; n < e.length; n++) {
let o = e[n], s = t[n];
if (s == null)
continue;
let a = o.rank;
if (s.ndim != null && a !== s.ndim)
throw new z(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${s.ndim}, found ndim=${a}`);
if (s.maxNDim != null && a > s.maxNDim)
throw new z(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${s.maxNDim}, found ndim=${a}`);
if (s.minNDim != null && a < s.minNDim)
throw new z(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${s.minNDim}, found ndim=${a}.`);
if (s.dtype != null && o.dtype !== s.dtype)
throw new z(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${s.dtype}, found dtype=${o.dtype}.`);
if (s.axes) {
let i = o.shape;
for (let l in s.axes) {
let u = Number(l), c = s.axes[l], p = u >= 0 ? i[u] : i[i.length + u];
if (c != null && [c, null].indexOf(p) === -1)
throw new z(`Input ${n} is incompatible with layer ${this.name}: expected axis ${u} of input shape to have value ${c} but got shape ${i}.`);
}
}
if (s.shape != null)
for (let i = 0; i < s.shape.length; ++i) {
let l = s.shape[i], u = o.shape[i];
if (l != null && u != null && l !== u)
throw new z(`Input ${n} is incompatible with layer ${this.name}: expected shape=${s.shape}, found shape=${o.shape}.`);
}
}
}
call(e, t) {
return e;
}
invokeCallHook(e, t) {
this._callHook != null && this._callHook(e, t);
}
setCallHook(e) {
this._callHook = e;
}
clearCallHook() {
this._callHook = null;
}
apply(e, t) {
t = t || {}, this.assertNotDisposed();
let n = wt(e), o = true;
for (let a of n)
if (!(a instanceof cn)) {
o = false;
break;
}
let s = true;
for (let a of n)
if (a instanceof cn) {
s = false;
break;
}
if (o === s)
throw new z("Arguments to apply() must be all SymbolicTensors or all Tensors");
return zs(this.name, () => {
if (!this.built) {
this.assertInputCompatibility(e);
let a = [];
for (let i of wt(e))
a.push(i.shape);
this.build(Sr(a)), this.built = true, this.initialWeights && this.setWeights(this.initialWeights), this._refCount === null && s && (this._refCount = 1);
}
if (this.assertInputCompatibility(e), s) {
let a = this.call(e, t), i = wt(a), l = [];
for (let u of i)
n.indexOf(u) !== -1 && (u = u.clone()), l.push(u);
if (a = Sr(l), this.activityRegularizer != null)
throw new Ne("Layer invocation in the presence of activity regularizer(s) is not supported yet.");
return a;
} else {
let a = s5(e), i = this.computeOutputShape(a), l, u = i5(e);
if (this.warnOnIncompatibleInputShape(Array.isArray(e) ? a[0] : a), i != null && i.length > 0 && Array.isArray(i[0]) ? l = i.map((c, p) => new cn(u, c, this, wt(e), t, this.name, p)) : l = new cn(u, i, this, wt(e), t, this.name), this.addInboundNode(e, l, null, null, a, i, t), this._refCount++, this.activityRegularizer != null)
throw new Ne("Layer invocation in the presence of activity regularizer(s) is not supported yet.");
return l;
}
});
}
warnOnIncompatibleInputShape(e) {
if (this.batchInputShape != null)
if (e.length !== this.batchInputShape.length)
console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);
else {
let t = false;
this.batchInputShape.forEach((n, o) => {
n != null && e[o] != null && e[o] !== n && (t = true);
}), t && console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`);
}
}
get outputShape() {
if (this.inboundNodes == null || this.inboundNodes.length === 0)
throw new Mn(`The layer ${this.name} has never been called and thus has no defined output shape.`);
let e = [];
for (let t of this.inboundNodes) {
let n = JSON.stringify(t.outputShapes);
e.indexOf(n) === -1 && e.push(n);
}
if (e.length === 1) {
let t = this.inboundNodes[0].outputShapes;
return Array.isArray(t) && Array.isArray(t[0]) && t.length === 1 ? t[0] : t;
} else
throw new Mn(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`);
}
countParams() {
if (!this.built)
throw new Kr(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);
return nm(this.weights);
}
build(e) {
this.built = true;
}
getWeights(e = false) {
return cd(e ? this.trainableWeights : this.weights);
}
setWeights(e) {
V(() => {
let t = this.weights;
if (t.length !== e.length)
throw new z(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);
if (t.length === 0)
return;
let n = [], o = cd(t);
for (let s = 0; s < o.length; ++s) {
let a = o[s], i = t[s], l = e[s];
if (!b.arraysEqual(a.shape, l.shape))
throw new z(`Layer weight shape ${a.shape} not compatible with provided weight shape ${l.shape}`);
n.push([i, l]);
}
om(n);
});
}
addWeight(e, t, n, o, s, a, i, l) {
if (this._addedWeightNames.indexOf(e) !== -1)
throw new z(`Duplicate weight name ${e} for layer ${this.name}`);
this._addedWeightNames.push(e), n == null && (n = "float32"), this.fastWeightInitDuringBuild && (o = l != null ? l() : dt("zeros"));
let u = o.apply(t, n), c = new Ex(u, n, e, a, i);
return u.dispose(), s != null && this.addLoss(() => s.apply(c.read())), a == null && (a = true), a ? this._trainableWeights.push(c) : this._nonTrainableWeights.push(c), c;
}
setFastWeightInitDuringBuild(e) {
this.fastWeightInitDuringBuild = e;
}
addLoss(e) {
e == null || Array.isArray(e) && e.length === 0 || (e = wt(e), this._losses !== void 0 && this._losses !== null && this.losses.push(...e));
}
computeOutputShape(e) {
return e;
}
computeMask(e, t) {
if (!this.supportsMasking) {
if (t != null)
if (Array.isArray(t))
t.forEach((n) => {
if (n != null)
throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);
});
else
throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);
return null;
}
return t;
}
addInboundNode(e, t, n, o, s, a, i = null) {
let l = wt(e);
t = wt(t), n = wt(n), o = wt(o), s = rm(s), a = rm(a);
let u = [], c = [], p = [];
for (let m of l)
u.push(m.sourceLayer), c.push(m.nodeIndex), p.push(m.tensorIndex);
new Fl({ outboundLayer: this, inboundLayers: u, nodeIndices: c, tensorIndices: p, inputTensors: l, outputTensors: t, inputMasks: n, outputMasks: o, inputShapes: s, outputShapes: a }, i);
for (let m = 0; m < t.length; m++)
t[m].sourceLayer = this, t[m].nodeIndex = this.inboundNodes.length - 1, t[m].tensorIndex = m;
}
getConfig() {
let e = { name: this.name, trainable: this.trainable };
return this.batchInputShape != null && (e.batchInputShape = this.batchInputShape), this.dtype != null && (e.dtype = this.dtype), e;
}
disposeWeights() {
return this.weights.forEach((e) => e.dispose()), this.weights.length;
}
assertNotDisposed() {
if (this._refCount === 0)
throw new Error(`Layer '${this.name}' is already disposed.`);
}
dispose() {
if (!this.built)
throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);
if (this._refCount === null)
throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);
this.assertNotDisposed();
let e = 0;
return --this._refCount == 0 && (e = this.disposeWeights()), { refCountAfterDispose: this._refCount, numDisposedVariables: e };
}
};
function s5(r) {
r = wt(r);
let e = [];
for (let t of r)
e.push(t.shape);
return Sr(e);
}
function i5(r) {
return "float32";
}
function Mk(r, e, t) {
if ((e == null || t != null && t > 0) && (e = r.sourceLayer, t = r.nodeIndex), e.inboundNodes.length === 0)
return [r];
{
let n = e.inboundNodes[t];
if (n.inboundLayers.length === 0)
return n.inputTensors;
{
let o = [];
for (let s = 0; s < n.inboundLayers.length; s++) {
let a = n.inputTensors[s], i = n.inboundLayers[s], l = n.nodeIndices[s], u = Mk(a, i, l);
for (let c of u)
o.indexOf(c) === -1 && o.push(c);
}
return o;
}
}
}
var Ii = class extends Ge {
constructor(e) {
super({ dtype: e.dtype, name: e.name != null ? e.name : Rl("input").toString() });
if (e.batchSize == null && (e.batchSize = null), e.sparse == null && (e.sparse = false), this.trainable = false, this.built = true, this.sparse = e.sparse, e.inputShape != null && e.batchInputShape != null)
throw new z("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");
let t = e.batchInputShape;
if (t == null) {
if (e.inputShape == null)
throw new z("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");
t = [e.batchSize].concat(e.inputShape);
} else if (e.batchSize != null)
throw new z("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");
let n = e.dtype || "float32";
this.batchInputShape = t, this.dtype = n, this.inputSpec = [{ shape: t }];
let o = new cn(this.dtype, this.batchInputShape, this, [], {}, this.name);
o.nodeIndex = 0, o.tensorIndex = 0, new Fl({ outboundLayer: this, inboundLayers: [], nodeIndices: [], tensorIndices: [], inputTensors: [o], outputTensors: [o], inputMasks: [null], outputMasks: [null], inputShapes: [t], outputShapes: [t] });
}
apply(e, t) {
throw new z(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`);
}
dispose() {
return { refCountAfterDispose: this._refCount, numDisposedVariables: 0 };
}
getConfig() {
return { batchInputShape: this.batchInputShape, dtype: this.dtype, sparse: this.sparse, name: this.name };
}
};
Ii.className = "InputLayer";
ee.registerClass(Ii);
function Ax(r) {
if (r.batchShape == null && r.shape == null)
throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");
if (r.batchShape != null && r.shape != null)
throw new z("Please provide either a `shape` or `batchShape` argument to Input, but not both.");
let e = r.batchShape;
r.shape != null && e == null && (e = [null].concat(r.shape));
let t = r.dtype;
return t == null && (t = "float32"), new Ii({ batchInputShape: e, name: r.name, dtype: t, sparse: r.sparse }).inboundNodes[0].outputTensors[0];
}
async function Si(r) {
if (r == null)
return;
let e = [], t = [], n = [];
for (let o in r) {
let s = r[o];
if (typeof s != "number") {
let a = s;
e.push(a.data()), t.push(o), n.push(a);
}
}
if (e.length > 0) {
let o = await Promise.all(e);
for (let s = 0; s < o.length; ++s)
r[t[s]] = o[s][0];
De(n);
}
}
function Dx(r) {
if (r != null)
for (let e in r) {
let t = r[e];
typeof t != "number" && t.dispose();
}
}
var pA;
(function(r) {
r[r.SILENT = 0] = "SILENT", r[r.VERBOSE = 1] = "VERBOSE";
})(pA || (pA = {}));
var a5 = 125;
var Ol = class {
constructor() {
this.validationData = null;
}
setParams(e) {
this.params = e;
}
async onEpochBegin(e, t) {
}
async onEpochEnd(e, t) {
}
async onBatchBegin(e, t) {
}
async onBatchEnd(e, t) {
}
async onTrainBegin(e) {
}
async onTrainEnd(e) {
}
setModel(e) {
}
};
var Lk = class {
constructor(e, t = 10) {
e == null && (e = []), this.callbacks = e, this.queueLength = t;
}
append(e) {
this.callbacks.push(e);
}
setParams(e) {
for (let t of this.callbacks)
t.setParams(e);
}
setModel(e) {
for (let t of this.callbacks)
t.setModel(e);
}
async onEpochBegin(e, t) {
t == null && (t = {});
for (let n of this.callbacks)
await n.onEpochBegin(e, t);
}
async onEpochEnd(e, t) {
t == null && (t = {});
for (let n of this.callbacks)
await n.onEpochEnd(e, t);
}
async onBatchBegin(e, t) {
t == null && (t = {});
for (let n of this.callbacks)
await n.onBatchBegin(e, t);
}
async onBatchEnd(e, t) {
t == null && (t = {});
for (let n of this.callbacks)
await n.onBatchEnd(e, t);
}
async onTrainBegin(e) {
e == null && (e = {});
for (let t of this.callbacks)
await t.onTrainBegin(e);
}
async onTrainEnd(e) {
e == null && (e = {});
for (let t of this.callbacks)
await t.onTrainEnd(e);
}
};
var mA = class extends Ol {
constructor() {
super();
}
async onEpochBegin(e) {
this.seen = 0, this.totals = {};
}
async onBatchEnd(e, t) {
t == null && (t = {});
let n = t.size == null ? 0 : t.size;
this.seen += n;
for (let o in t) {
let s = t[o];
if (typeof s == "number")
this.totals.hasOwnProperty(o) || (this.totals[o] = 0), this.totals[o] = this.totals[o] + s * n;
else {
let a;
o in this.totals ? a = this.totals[o] : this.totals[o] = 0;
let i = V(() => Z(this.totals[o], O(s, n)));
this.totals[o] = i, a != null && a.dispose();
}
}
}
async onEpochEnd(e, t) {
if (t != null)
for (let n of this.params.metrics)
this.totals[n] != null && (typeof this.totals[n] == "number" ? t[n] = this.totals[n] / this.seen : V(() => {
let o = O(ce(1, this.seen), this.totals[n]);
t[n] = o, this.totals[n].dispose(), Ft(t[n]);
}));
}
};
var zk = class extends Ol {
async onTrainBegin(e) {
this.epoch = [], this.history = {};
}
async onEpochEnd(e, t) {
t == null && (t = {}), this.epoch.push(e);
for (let n in t)
this.history[n] == null && (this.history[n] = []), this.history[n].push(t[n]);
}
async syncData() {
let e = [], t = [], n = [];
for (let s in this.history) {
let a = this.history[s];
for (let i = 0; i < a.length; ++i)
if (typeof a[i] != "number") {
let l = a[i];
e.push(l.data()), t.push(s), n.push(i);
}
}
let o = await Promise.all(e);
for (let s = 0; s < o.length; ++s)
this.history[t[s]][n[s]].dispose(), this.history[t[s]][n[s]] = o[s][0];
}
};
var Bk = class extends Ol {
constructor(e, t) {
super();
if (this.currentEpoch = 0, this.nowFunc = e.nowFunc, this.nextFrameFunc = e.nextFrameFunc || wk, this.yieldEvery = t || "auto", this.yieldEvery === "auto" && (this.yieldEvery = a5), this.yieldEvery === "never" && e.onYield != null)
throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");
b.isNumber(this.yieldEvery) && (this.maybeWait = B2(this.maybeWait.bind(this), this.yieldEvery, this.nowFunc)), this.trainBegin = e.onTrainBegin, this.trainEnd = e.onTrainEnd, this.epochBegin = e.onEpochBegin, this.epochEnd = e.onEpochEnd, this.batchBegin = e.onBatchBegin, this.batchEnd = e.onBatchEnd, this.yield = e.onYield;
}
async maybeWait(e, t, n) {
let o = [];
this.yield != null && (await Si(n), o.push(this.yield(e, t, n))), o.push(this.nextFrameFunc()), await Promise.all(o);
}
async onEpochBegin(e, t) {
this.currentEpoch = e, this.epochBegin != null && (await Si(t), await this.epochBegin(e, t));
}
async onEpochEnd(e, t) {
let n = [];
this.epochEnd != null && (await Si(t), n.push(this.epochEnd(e, t))), this.yieldEvery === "epoch" && n.push(this.nextFrameFunc()), await Promise.all(n);
}
async onBatchBegin(e, t) {
this.batchBegin != null && (await Si(t), await this.batchBegin(e, t));
}
async onBatchEnd(e, t) {
let n = [];
this.batchEnd != null && (await Si(t), n.push(this.batchEnd(e, t))), this.yieldEvery === "batch" ? n.push(this.nextFrameFunc()) : b.isNumber(this.yieldEvery) && n.push(this.maybeWait(this.currentEpoch, e, t)), await Promise.all(n);
}
async onTrainBegin(e) {
this.trainBegin != null && (await Si(e), await this.trainBegin(e));
}
async onTrainEnd(e) {
this.trainEnd != null && (await Si(e), await this.trainEnd(e));
}
};
function $x(r, e) {
return r == null && (r = {}), r instanceof Ol ? [r] : Array.isArray(r) && r[0] instanceof Ol ? r : wt(r).map((n) => new Bk(n, e));
}
var Sn = class {
constructor() {
}
static registerCallbackConstructor(e, t) {
b.assert(e >= 0 && Number.isInteger(e), () => `Verbosity level is expected to be an integer >= 0, but got ${e}`), Sn.checkForDuplicate(t), Sn.constructors[e] == null && (Sn.constructors[e] = []), Sn.constructors[e].push(t);
}
static checkForDuplicate(e) {
for (let t in Sn.constructors)
Sn.constructors[+t].forEach((o) => {
if (o === e)
throw new z("Duplicate callback constructor.");
});
}
static clear() {
Sn.constructors = {};
}
static createCallbacks(e) {
let t = [];
for (let n in Sn.constructors) {
let o = +n;
e >= o && t.push(...Sn.constructors[o]);
}
return t.map((n) => new n());
}
};
Sn.constructors = {};
function Rx(r, e, t, n, o, s, a, i, l) {
let u = new zk(), c = [new mA(), ...Sn.createCallbacks(e)];
r != null && c.push(...r), c.push(u);
let p = new Lk(c);
return p.setParams({ epochs: t, initialEpoch: n, samples: o, steps: s, batchSize: a, verbose: e, doValidation: i, metrics: l }), { callbackList: p, history: u };
}
function pn(r, e = {}, t = false) {
return vi(r, ee.SerializationMap.getMap().classNameMap, e, "layer", t);
}
function pd(r, e) {
return V(() => {
r.dtype !== "float32" && (r = Y(r, "float32"));
let t = me(tc(r), e, true), n = Fs(t.shape, ir()), o = bt(sn(t, n));
return ce(r, o);
});
}
function Ni(r, e) {
return V(() => xt(tc(le(e, r)), -1));
}
function sm(r, e) {
return V(() => xt(Ct(le(e, r)), -1));
}
function Pl(r, e) {
return V(() => {
let t = le(r, e), n = gr(Ct(r), ir(), Number.MAX_VALUE), o = Ct(ce(t, n));
return O(100, xt(o, -1));
});
}
function l5(r, e) {
return V(() => {
let t = gr(e, ir(), Number.MAX_VALUE), n = xr(Z(1, t)), o = gr(r, ir(), Number.MAX_VALUE), s = xr(Z(1, o));
return xt(tc(le(n, s)), -1);
});
}
function u5(r, e) {
return V(() => {
let t = sn(0, le(1, O(r, e)));
return xt(tc(t), -1);
});
}
function c5(r, e) {
return V(() => {
let t = sn(0, le(1, O(r, e)));
return xt(t, -1);
});
}
function p5(r, e) {
return V(() => {
let t = me(O(r, e), -1), n = Rr(O(le(1, r), e), -1);
return sn(0, Z(1, le(n, t)));
});
}
function m5(r, e) {
return V(() => {
let t = Math.log(2), n = le(e, r), o = le(Z(n, co(O(-2, n))), t);
return xt(o, -1);
});
}
function nc(r, e, t = false) {
return V(() => {
if (t)
e = za(e);
else {
let n = me(e, e.shape.length - 1, true);
e = ce(e, n);
}
return e = gr(e, ir(), 1 - ir()), He(me(O(Y(r, "float32"), xr(e)), e.shape.length - 1));
});
}
function im(r, e, t = false) {
return V(() => {
let n = Y(Os(eA(r)), "int32");
e = gr(e, ir(), 1 - ir());
let o = e.shape, s = F(Ts(n, o[o.length - 1]), o);
return nc(s, e, t);
});
}
function f5(r, e) {
if (!b.arraysEqual(r.shape, e.shape))
throw new z(`logits and labels must have the same shape, but got shapes ${JSON.stringify(r.shape)} and ${JSON.stringify(e.shape)}`);
return V(() => {
let t = Ir(e), n = He(Ct(e));
return Z(le(t, O(e, r)), Ra(Kt(n)));
});
}
function am(r, e) {
return V(() => {
let t;
return t = gr(e, ir(), 1 - ir()), t = xr(ce(t, le(1, t))), xt(f5(r, t), -1);
});
}
function d5(r, e) {
return V(() => {
let t = gr(r, ir(), 1), n = gr(e, ir(), 1);
return me(O(r, xr(ce(t, n))), -1);
});
}
function h5(r, e) {
return V(() => {
let t = xr(Z(ir(), e));
return xt(le(e, O(r, t)), -1);
});
}
function md(r, e) {
return V(() => {
let t = pd(r, -1), n = pd(e, -1), o = O(t, n);
return He(me(o, -1));
});
}
var fd = { meanSquaredError: Ni, meanAbsoluteError: sm, meanAbsolutePercentageError: Pl, meanSquaredLogarithmicError: l5, squaredHinge: u5, hinge: c5, categoricalHinge: p5, logcosh: m5, categoricalCrossentropy: nc, sparseCategoricalCrossentropy: im, binaryCrossentropy: am, kullbackLeiblerDivergence: d5, poisson: h5, cosineProximity: md };
function Fx(r) {
if (typeof r == "string") {
if (r in fd)
return fd[r];
let e = `Unknown loss ${r}`;
throw r.toLowerCase().includes("softmaxcrossentropy") && (e = `Unknown loss ${r}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`), new z(e);
} else
return r;
}
function dd(r, e) {
return V(() => {
let t = O(0.5, fr(e)), n = ec(zt(e, t), r.dtype);
return xt(kr(r, n), -1);
});
}
function hd(r, e) {
return V(() => ec(kr(As(r, -1), As(e, -1)), "float32"));
}
function fA(r, e) {
return V(() => Y(me(Cr(kr(r, 1), kr(e, 1))), "float32"));
}
function g5(r, e) {
return V(() => Y(me(Cr(kr(r, 1), kr(e, 0))), "float32"));
}
function x5(r, e) {
return V(() => Y(me(Cr(kr(r, 0), kr(e, 1))), "float32"));
}
function Vk(r, e) {
return V(() => {
let t = fA(r, e), n = x5(r, e), o = Z(t, n);
return Y(St(zt(o, 0), ce(t, o), 0), "float32");
});
}
function dA(r, e) {
return V(() => {
let t = fA(r, e), n = g5(r, e), o = Z(t, n);
return Y(St(zt(o, 0), ce(t, o), 0), "float32");
});
}
function Ox(r, e) {
return am(r, e);
}
function Px(r, e) {
return r.rank === e.rank && (r = Br(r, [r.rank - 1])), e = As(e, -1), e.dtype !== r.dtype && (e = Y(e, r.dtype)), Y(kr(r, e), "float32");
}
var y5 = Ni;
var b5 = Ni;
var w5 = sm;
var _5 = sm;
var k5 = Pl;
var v5 = Pl;
var gd = nc;
var C5 = md;
var Gk = im;
var Mx = { binaryAccuracy: dd, categoricalAccuracy: hd, precision: Vk, categoricalCrossentropy: gd, sparseCategoricalCrossentropy: Gk, mse: y5, MSE: b5, mae: w5, MAE: _5, mape: k5, MAPE: v5, cosine: C5 };
function hA(r) {
if (typeof r == "string" && r in Mx)
return Mx[r];
if (typeof r != "string" && r != null)
return r;
throw new z(`Unknown metric ${r}`);
}
function xd(r) {
if (Kn(r !== null, `Unknown LossOrMetricFn ${r}`), typeof r == "string")
return r;
{
let e;
for (let t of Object.keys(fd))
if (fd[t] === r) {
e = t;
break;
}
if (e !== void 0)
return e;
for (let t of Object.keys(Mx))
if (Mx[t] === r) {
e = t;
break;
}
return e !== void 0 ? e : r.name;
}
}
function gA(r) {
let e = { Adagrad: () => Ju.adagrad(0.01), Adadelta: () => Ju.adadelta(1, 0.95, ir()), Adam: () => Ju.adam(1e-3, 0.9, 0.999, ir()), Adamax: () => Ju.adamax(2e-3, 0.9, 0.999, ir(), 0), RMSProp: () => Ju.rmsprop(1e-3, 0.9, 0, ir()), SGD: () => Ju.sgd(0.01) };
if (e.adagrad = e.Adagrad, e.adadelta = e.Adadelta, e.adam = e.Adam, e.adamax = e.Adamax, e.rmsprop = e.RMSProp, e.sgd = e.SGD, r in e)
return e[r]();
throw new z(`Unknown Optimizer ${r}`);
}
var xA = 1 * 1024 * 1024;
function Wk(r, e, t = false) {
if (r == null || typeof r != "object" || Object.getPrototypeOf(r) !== Object.prototype || !Uk(r))
throw new Error("User-defined metadata is expected to be a JSON object, but is not.");
if (t) {
let n = JSON.stringify(r);
n.length > xA && console.warn(`User-defined metadata of model "${e}" is too large in size (length=${n.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${xA}.`);
}
}
function Uk(r) {
if (r === null)
return true;
if (typeof r == "object")
if (Object.getPrototypeOf(r) === Object.prototype) {
let e = Object.keys(r);
for (let t of e)
if (typeof t != "string" || !Uk(r[t]))
return false;
return true;
} else if (Array.isArray(r)) {
for (let e of r)
if (!Uk(e))
return false;
return true;
} else
return false;
else {
let e = typeof r;
return e === "string" || e === "number" || e === "boolean";
}
}
function yA(r, e, t, n = console.log) {
let o = S5(r), s = ["Layer (type)", "Output shape", "Param #"];
o ? (e = e || 65, t = t || [0.45, 0.85, 1]) : (e = e || 98, t = t || [0.33, 0.55, 0.67, 1]), t[t.length - 1] <= 1 && (t = t.map((c) => Math.floor(e * c)));
let a;
if (!o) {
s.push("Receives inputs"), a = [];
for (let c in r.nodesByDepth)
a.push(...r.nodesByDepth[c]);
}
n("_".repeat(e)), Lx(s, t, n), n("=".repeat(e));
let i = r.layers;
for (let c = 0; c < i.length; ++c)
o ? N5(i[c], t, n) : T5(i[c], t, a, n), n((c === i.length - 1 ? "=" : "_").repeat(e));
r.checkTrainableWeightsConsistency();
let l = I5(r), u = nm(r.nonTrainableWeights);
n(`Total params: ${l + u}`), n(`Trainable params: ${l}`), n(`Non-trainable params: ${u}`), n("_".repeat(e));
}
function I5(r) {
let e;
return r.collectedTrainableWeights != null ? e = nm(r.collectedTrainableWeights) : e = nm(r.trainableWeights), e;
}
function S5(r) {
let e = true, t = [], n = [];
for (let o in r.nodesByDepth)
t.push(r.nodesByDepth[o]);
for (let o of t) {
if (o.length > 1 || o.length === 1 && o[0].inboundLayers.length > 1) {
e = false;
break;
}
n.push(...o);
}
if (e)
for (let o of r.layers) {
let s = false;
for (let a of o.inboundNodes)
if (n.indexOf(a) !== -1)
if (s) {
e = false;
break;
} else
s = true;
if (!e)
break;
}
return e;
}
function Lx(r, e, t = console.log) {
let n = "";
for (let o = 0; o < r.length; ++o)
o > 0 && (n = n.slice(0, n.length - 1) + " "), n += r[o], n = n.slice(0, e[o]), n += " ".repeat(e[o] - n.length);
t(n);
}
function N5(r, e, t) {
let n;
try {
n = JSON.stringify(r.outputShape);
} catch (i) {
n = "multiple";
}
let o = r.name, s = r.getClassName(), a = [`${o} (${s})`, n, r.countParams().toString()];
Lx(a, e, t);
}
function T5(r, e, t, n) {
let o;
try {
o = JSON.stringify(r.outputShape);
} catch (c) {
o = "multiple";
}
let s = [];
for (let c of r.inboundNodes)
if (!(t != null && t.length > 0 && t.indexOf(c) === -1))
for (let p = 0; p < c.inboundLayers.length; ++p) {
let m = c.inboundLayers[p].name, f = c.nodeIndices[p], d = c.tensorIndices[p];
s.push(`${m}[${f}][${d}]`);
}
let a = r.name, i = r.getClassName(), l = s.length === 0 ? "" : s[0], u = [`${a} (${i})`, o, r.countParams().toString(), l];
Lx(u, e, n);
for (let c = 1; c < s.length; ++c)
Lx(["", "", "", s[c]], e, n);
}
function bA(r, e, t) {
return (r === "inboundNodes" || r === "outputLayers" || r === "inputLayers") && e === 0 && typeof t == "string";
}
function oc(r, e) {
if (r === null)
return null;
if (typeof r == "string")
return Ua(r);
if (typeof r == "number" || typeof r == "boolean")
return r;
if (r instanceof Array) {
let t = [], n = r.length;
for (let o = 0; o < n; ++o) {
let s = r[o];
bA(e, o, s) ? t.push(s) : t.push(oc(s, e));
}
return t;
} else {
let t = {};
for (let n of Object.keys(r)) {
let o = r[n];
if (n === "name" && typeof o == "string")
t[n] = o;
else {
let s = Ua(n);
t[s] = oc(o, s);
}
}
return t;
}
}
function zx(r, e) {
if (r == null)
return null;
if (typeof r == "string")
return xo(r);
if (typeof r == "number" || typeof r == "boolean")
return r;
if (r instanceof Array) {
let t = [], n = r.length;
for (let o = 0; o < n; ++o) {
let s = r[o];
bA(e, o, s) ? t.push(s) : t.push(zx(s, e));
}
return t;
} else {
let t = {};
for (let n of Object.keys(r)) {
let o = r[n], s = xo(n);
(n === "name" || n === "className") && typeof o == "string" ? t[s] = o : t[s] = zx(o, n);
}
return t;
}
}
var lm = "3.10.0";
function E5(r, e) {
if (r.dtype == null || r.dtype === e.dtype)
return e;
try {
return Y(e, r.dtype);
} catch (t) {
throw new z(`The dtype of the feed (${e.dtype}) can not be cast to the dtype of the key '${r.name}' (${r.dtype}).`);
}
}
var Vs = class {
constructor(e) {
if (this.id2Value = {}, this.id2Mask = {}, this.name2Id = {}, e instanceof Vs)
for (let t in e.id2Value)
this.id2Value[t] = e.id2Value[t], t in e.id2Mask && (this.id2Mask[t] = e.id2Mask[t]);
else {
if (e == null)
return;
for (let t of e)
this.add(t.key, t.value);
}
}
add(e, t, n) {
if (this.id2Value[e.id] == null)
this.id2Value[e.id] = E5(e, t), this.name2Id[e.name] = e.id, n != null && (this.id2Mask[e.id] = n);
else
throw new z(`Duplicate key: name=${e.name}, id=${e.id}`);
return this;
}
addFeed(e) {
this.add(e.key, e.value);
}
hasKey(e) {
return this.id2Value[e.id] != null;
}
names() {
return Object.keys(this.name2Id);
}
getValue(e) {
if (e instanceof cn) {
if (this.id2Value[e.id] == null)
throw new z(`Nonexistent key: ${e.name}`);
return this.id2Value[e.id];
} else {
let t = this.name2Id[e];
if (t == null)
throw new z(`Feed dict has no SymbolicTensor name: ${e}`);
return this.id2Value[t];
}
}
getMask(e) {
if (e instanceof cn) {
if (this.id2Value[e.id] == null)
throw new z(`Nonexistent key: ${e.name}`);
return this.id2Mask[e.id];
} else {
let t = this.name2Id[e];
if (t == null)
throw new z(`Feed dict has no SymbolicTensor name: ${e}`);
return this.id2Mask[t];
}
}
disposeMasks() {
this.id2Mask != null && De(this.id2Mask);
}
};
var jk = {};
var wA = {};
function sc(r, e, t, n) {
let o = t == null ? false : t.training, s = Array.isArray(r), a = s ? r : [r], i = a.map((d) => d.name), l = [], u = e.names();
for (let d of i)
u.indexOf(d) !== -1 ? l.push(e.getValue(d)) : l.push(null);
n != null && (n.maxNumTensors = -1 / 0, n.minNumTensors = 1 / 0);
let c = i.join(",") + "|" + e.names().join(","), p, m;
if (jk[c] == null) {
let d = A5(a, e);
p = d.sorted, m = d.recipientCounts, jk[c] = p, wA[c] = m;
}
p = jk[c], m = {}, o || Object.assign(m, wA[c]);
let f = new Vs(e);
for (let d = 0; d < p.length; ++d) {
if (n != null) {
let P = ff().numTensors;
P > n.maxNumTensors && (n.maxNumTensors = P), P < n.minNumTensors && (n.minNumTensors = P);
}
let h = p[d], g = h.sourceLayer;
if (g instanceof Ii)
continue;
let x = [], y = [], w = [], _ = false;
for (let P of h.inputs) {
let L = f.getValue(P), G = f.getMask(P);
x.push(L), y.push(G), G != null && (_ = true), o || (m[P.name]--, m[P.name] === 0 && !e.hasKey(P) && i.indexOf(P.name) === -1 && !L.isDisposed && P.sourceLayer.stateful !== true && w.push(L));
}
_ && (t = t || {}, t.mask = y[0]);
let C = wt(g.apply(x, t)), A = null;
g.supportsMasking && (A = g.computeMask(x, y));
let D = $5(h), R = Array.isArray(D) ? D : [D];
for (let P = 0; P < R.length; ++P) {
f.hasKey(R[P]) || f.add(R[P], C[P], Array.isArray(A) ? A[0] : A);
let L = i.indexOf(R[P].name);
L !== -1 && (l[L] = C[P]);
}
o || De(w);
}
return f.disposeMasks(), s ? l : l[0];
}
function A5(r, e) {
b.assert(r != null && r.length > 0, () => "Expected at least one fetch, got none");
let t = [], n = {};
if (r.length === 1) {
let o = _A(r[0], e);
t = o.sorted, n = o.recipientMap;
} else {
let o = new Set();
for (let s of r) {
let { sorted: a, recipientMap: i } = _A(s, e);
for (let l of a)
o.has(l.name) || (t.push(l), o.add(l.name));
for (let l in i)
n[l] == null && (n[l] = new Set()), i[l].forEach((u) => n[l].add(u));
}
}
return { sorted: t, recipientCounts: D5(n) };
}
function D5(r) {
let e = {};
for (let t in r)
e[t] = r[t].size;
return e;
}
function _A(r, e) {
let t = new Set(), n = [], o = {};
for (let i of e.names())
t.add(i);
let s = [], a = [];
for (s.push(r); s.length > 0; ) {
let i = s[s.length - 1];
if (t.has(i.name)) {
s.pop();
continue;
}
let l = a[a.length - 1] === s.length - 1;
if (i.inputs.length === 0 || l)
s.pop(), n.push(i), t.add(i.name), l && a.pop();
else {
a.push(s.length - 1);
for (let u of i.inputs)
o[u.name] == null && (o[u.name] = new Set()), o[u.name].add(i.name), !t.has(u.name) && s.push(u);
}
}
return { sorted: n, recipientMap: o };
}
function $5(r) {
let e;
if (r.sourceLayer.inboundNodes.length === 1)
e = r.sourceLayer.output;
else {
let t = null;
for (let n = 0; n < r.sourceLayer.inboundNodes.length; ++n)
for (let o of r.sourceLayer.inboundNodes[n].outputTensors)
if (o.id === r.id) {
t = n;
break;
}
e = r.sourceLayer.getOutputAt(t);
}
return e;
}
var Xn = class extends Ge {
constructor(e) {
super({});
if (this.containerNodes = new Set(), this.name = e.name, this.name == null) {
let y = this.getClassName().toLowerCase();
this.name = Rl(y);
}
if (this.supportsMasking = false, this.trainable_ = true, Array.isArray(e.inputs) ? this.inputs = e.inputs.slice() : this.inputs = [e.inputs], Array.isArray(e.outputs) ? this.outputs = e.outputs.slice() : this.outputs = [e.outputs], bo(this.inputs).length !== this.inputs.length)
throw new z(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map((y) => y.name)}`);
bo(this.outputs).length !== this.outputs.length && console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map((y) => y.name)}`), this.inputLayers = [], this.inputLayersNodeIndices = [], this.inputLayersTensorIndices = [], this.outputLayers = [], this.outputLayersNodeIndices = [], this.outputLayersTensorIndices = [], this.layers = [], this.internalContainerRefs = [];
for (let y of this.outputs) {
let w = y.sourceLayer, _ = y.nodeIndex, C = y.tensorIndex;
this.outputLayers.push(w), this.outputLayersNodeIndices.push(_), this.outputLayersTensorIndices.push(C);
}
for (let y of this.inputs) {
let w = y.sourceLayer, _ = y.nodeIndex, C = y.tensorIndex;
Kn(_ === 0, "input layer has >1 nodes"), Kn(C === 0, "input layer has >1 tensors"), this.inputLayers.push(w), this.inputLayersNodeIndices.push(_), this.inputLayersTensorIndices.push(C);
}
this.inputNames = [], this.outputNames = [], this.feedInputShapes = [], this.feedInputNames = [], this.feedOutputNames = [];
for (let y = 0; y < this.inputLayers.length; y++) {
let w = this.inputLayers[y];
if (!(w instanceof Ii))
throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${y} (0-based) originates from layer type ${w.getClassName()}.`);
this.inputNames.push(w.name), this.feedInputShapes.push(w.batchInputShape), this.feedInputNames.push(w.name);
}
for (let y of this.outputLayers)
this.outputNames.push(y.name);
this.internalInputShapes = this.inputs.map((y) => y.shape), this.internalOutputShapes = this.outputs.map((y) => y.shape);
let t = {}, n = {}, o = {}, s = {}, a = {}, i = [], l = (y, w, _, C, A, D) => {
(C == null || A == null || D == null) && (C = y.sourceLayer, A = y.nodeIndex, D = y.tensorIndex);
let R = C.inboundNodes[A];
if (_.indexOf(R) !== -1)
throw new Kr(`The tensor ${y.name} at layer "${C.name}" is part of a cycle.`);
if (w.indexOf(R) !== -1)
return;
this.containerNodes.add(Xn.nodeKey(C, A)), C.id in a || (a[C.id] = Object.keys(a).length), _.indexOf(R) === -1 && _.push(R);
let P = R.inboundLayers.length;
for (let L = 0; L < P; L++) {
let G = R.inputTensors[L], W = R.inboundLayers[L], j = R.nodeIndices[L], H = R.tensorIndices[L];
l(G, w, _, W, j, H);
}
for (w.push(R); _.indexOf(R) >= 0; )
_.splice(_.indexOf(R), 1);
i.push(R);
}, u = [], c = [];
for (let y of this.outputs)
l(y, u, c);
let p = i.slice().reverse();
for (let y of p) {
n[y.id] = y, y.id in t || (t[y.id] = 0);
let w = t[y.id], _ = o[y.outboundLayer.id] == null ? 0 : o[y.outboundLayer.id];
w = Math.max(w, _), o[y.outboundLayer.id] = w, s[y.outboundLayer.id] = y.outboundLayer, t[y.id] = w;
for (let C = 0; C < y.inboundLayers.length; C++) {
let A = y.inboundLayers[C], D = y.nodeIndices[C], R = A.inboundNodes[D], P = t[R.id] == null ? 0 : t[R.id];
t[R.id] = Math.max(w + 1, P), n[R.id] = R;
}
}
let m = {};
for (let y in t) {
let w = t[y];
w in m || (m[w] = []), m[w].push(n[y]);
}
let f = {};
for (let y in o) {
let w = o[y];
w in f || (f[w] = []), f[w].push(s[y]);
}
let d = Object.keys(f).map((y) => parseInt(y, 10)).sort(Yf);
this.layers = [];
for (let y of d) {
let w = f[y];
w.sort((_, C) => {
let A = a[_.id], D = a[C.id];
return A < D ? -1 : A > D ? 1 : 0;
});
for (let _ of w)
_ instanceof Xn && this.internalContainerRefs.push(_), this.layers.push(_);
}
this.layersByDepth = f, d = Object.keys(m).map((y) => parseInt(y, 10)).sort(Yf);
let h = this.inputs.slice(), g = [];
for (let y of d)
for (let w of m[y]) {
let _ = w.outboundLayer;
if (_ != null) {
for (let C of w.inputTensors)
if (h.indexOf(C) === -1)
throw new Kr(`Graph disconnected: cannot obtain value for tensor ${C} at layer "${_.name}". The following previous layers were accessed without issue: ${g}`);
for (let C of w.outputTensors)
h.push(C);
g.push(_.name);
}
}
this.nodesByDepth = m;
let x = this.layers.map((y) => y.name);
for (let y of x) {
let w = x.filter((_) => _ === y).length;
if (w !== 1)
throw new Kr(`The name "${y}" is used ${w} times in the model. All layer names should be unique. Layer names: ` + JSON.stringify(x));
}
this.outboundNodes = [], this.inboundNodes = [], new Fl({ outboundLayer: this, inboundLayers: [], nodeIndices: [], tensorIndices: [], inputTensors: this.inputs, outputTensors: this.outputs, inputMasks: this.inputs.map((y) => null), outputMasks: this.outputs.map((y) => null), inputShapes: this.inputs.map((y) => y.shape), outputShapes: this.outputs.map((y) => y.shape) }), this.built = true, this._refCount = 1;
}
assertNotDisposed() {
if (this._refCount === 0)
throw new Error(`Container '${this.name}' is already disposed.`);
}
dispose() {
this.assertNotDisposed();
let e = { refCountAfterDispose: null, numDisposedVariables: 0 };
if (--this._refCount == 0) {
for (let t of this.layers)
e.numDisposedVariables += t.dispose().numDisposedVariables;
for (let t of this.internalContainerRefs)
e.numDisposedVariables += t.dispose().numDisposedVariables;
}
return e.refCountAfterDispose = this._refCount, e;
}
get trainable() {
return this.trainable_;
}
set trainable(e) {
this.layers.forEach((t) => {
t._trainableWeights.forEach((n) => n.trainable = e);
}), this.trainable_ = e;
}
get trainableWeights() {
if (this._trainableWeights.length > 0)
throw new z("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");
if (!this.trainable)
return [];
let e = [];
for (let t of this.layers)
e = e.concat(t.trainableWeights);
return e;
}
get nonTrainableWeights() {
let e = [];
for (let t of this.layers)
e.push(...t.nonTrainableWeights);
if (!this.trainable) {
let t = [];
for (let n of this.layers)
t.push(...n.trainableWeights);
return t.concat(e);
}
return e;
}
get weights() {
return this.trainableWeights.concat(this.nonTrainableWeights);
}
loadWeights(e, t = true) {
let n = {}, o = 0;
for (let a of this.layers)
for (let i of a.weights) {
if (n[i.originalName] != null)
throw new z(`Duplicate weight name: ${i.originalName}`);
n[i.originalName] = i, o++;
}
let s = [];
for (let a in e) {
let i = a;
if (n[a] == null) {
let l = a.split("/");
i = l.slice(0, -2).concat([l[l.length - 1]]).join("/");
}
if (n[i] != null)
s.push([n[i], e[a]]);
else if (t)
throw new z(`Provided weight data has no target variable: ${a}`);
delete n[i];
}
if (t) {
let a = [];
for (let i in n)
a.push(i);
if (a.length > 0)
throw new z(`${a.length} of ${o} weights are not set: ${a}`);
}
om(s);
}
updatedConfig() {
let e = this.getConfig(), t = {};
return t.className = this.getClassName(), t.config = e, t.kerasVersion = `tfjs-layers ${lm}`, t.backend = "TensorFlow.js", t;
}
toJSON(e, t = true) {
let n = zx(this.updatedConfig());
return t ? JSON.stringify(n) : n;
}
call(e, t) {
return V(() => {
e = wt(e);
let n = new Vs();
for (let o = 0; o < this.inputs.length; ++o)
n.add(this.inputs[o], e[o]);
return sc(this.outputs, n, t);
});
}
computeMask(e, t) {
return V(() => {
e = wt(e);
let n;
return t == null ? n = go(null, e.length) : n = wt(t), this.runInternalGraph(e, n)[1];
});
}
computeOutputShape(e) {
let t = rm(e);
if (t.length !== this.inputLayers.length)
throw new z(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);
let n = {};
for (let i = 0; i < t.length; i++) {
let l = this.inputLayers[i], u = t[i], c = l.name + "_0_0";
n[c] = u;
}
let o = Object.keys(this.nodesByDepth).map((i) => parseInt(i, 10)).sort(Yf);
if (o.length > 1)
for (let i of o) {
let l = this.nodesByDepth[i];
for (let u of l) {
let c = u.outboundLayer;
if (this.inputLayers.map((h) => h.id).indexOf(c.id) !== -1)
continue;
let p = [];
for (let h = 0; h < u.inboundLayers.length; h++) {
let g = u.inboundLayers[h], x = u.nodeIndices[h], y = u.tensorIndices[h], w = `${g.name}_${x}_${y}`, _ = n[w];
p.push(_);
}
let m = c.computeOutputShape(Sr(p)), f = rm(m), d = c.inboundNodes.indexOf(u);
for (let h = 0; h < f.length; h++) {
let g = `${c.name}_${d}_${h}`;
n[g] = f[h];
}
}
}
let s = [], a = [];
for (let i = 0; i < this.outputLayers.length; i++) {
let l = this.outputLayers[i], u = this.outputLayersNodeIndices[i], c = this.outputLayersTensorIndices[i], p = `${l.name}_${u}_${c}`;
a.push(p);
}
for (let i = 0; i < a.length; i++) {
let l = a[i];
Kn(l in n), s.push(n[l]);
}
return Sr(s);
}
runInternalGraph(e, t) {
t == null && (t = go(null, e.length));
let n = {};
for (let l = 0; l < this.inputs.length; ++l) {
let u = this.inputs[l], c = e[l], p = t[l];
n[u.id] = [c, p];
}
let o = Object.keys(this.nodesByDepth).map((l) => parseInt(l, 10)).sort(Yf);
for (let l of o) {
let u = this.nodesByDepth[l];
for (let c of u) {
let p = c.outboundLayer, m = c.inputTensors, f = c.outputTensors, d = new Array();
for (let h of m)
h.id in n && d.push(n[h.id]);
if (d.length === m.length) {
let h = {}, g, x, y, w;
if (c.callArgs != null && (h = c.callArgs), d.length === 1) {
let [_, C] = d[0];
h.mask == null && (h.mask = C), y = wt(p.call(_, h)), w = wt(p.computeMask(_, C)), g = [_], x = [C];
} else
g = d.map((_) => _[0]), x = d.map((_) => _[1]), h.mask == null && (h.mask = x), y = wt(p.call(g, h)), w = wt(p.computeMask(g, x));
if (p.activityRegularizer)
throw new Ne("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");
for (let _ = 0; _ < f.length; ++_) {
let C = f[_], A = y[_], D = w[_];
n[C.id] = [A, D];
}
}
}
}
let s = [], a = [], i = [];
for (let l of this.outputs) {
Kn(l.id in n, `Could not compute output ${l.name} : ${l.id}`);
let [u, c] = n[l.id];
i.push(u.shape), s.push(u), a.push(c);
}
return [s, a, i];
}
buildNodeConversionMap(e) {
let t = {}, n;
for (let o of this.layers) {
n = o instanceof Xn ? 1 : 0;
for (let s = 0; s < o.inboundNodes.length; s++) {
let a = Xn.nodeKey(o, s);
this.containerNodes.has(a) && (t[a] = n, n += 1);
}
}
return t;
}
getLayer(e, t) {
if (t != null) {
if (this.layers.length <= t)
throw new z(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);
return this.layers[t];
} else if (e == null)
throw new z("Provide either a layer name or layer index");
for (let n of this.layers)
if (n.name === e)
return n;
throw new z(`No such layer: ${e}`);
}
calculateLosses() {
return V(() => {
let e = [];
for (let t of this.layers)
for (let n = 0; n < t.inboundNodes.length; ++n) {
let o = Xn.nodeKey(t, n);
this.containerNodes.has(o) && e.push(...t.calculateLosses());
}
return e;
});
}
getConfig() {
let e = { name: this.name }, t = this.buildNodeConversionMap(this.layers), n = [];
for (let a of this.layers) {
let i = a.getClassName(), l = a.getConfig(), u = [];
for (let p = 0; p < a.inboundNodes.length; p++) {
let m = a.inboundNodes[p], f = Xn.nodeKey(a, p), d = {};
if (this.containerNodes.has(f)) {
if (m.callArgs)
try {
JSON.stringify(m.callArgs), d = m.callArgs;
} catch (h) {
console.warn(`Layer ${a.name} was passed non-serializable keyword arguments: ${m.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`), d = {};
}
if (m.inboundLayers.length > 0) {
let h = [];
for (let g = 0; g < m.inboundLayers.length; g++) {
let x = m.inboundLayers[g], y = m.nodeIndices[g], w = m.tensorIndices[g], _ = Xn.nodeKey(x, y), C = t[_];
C == null && (C = 0), h.push([x.name, C, w, d]);
}
u.push(h);
}
}
}
let c = {};
c.name = a.name, c.className = i, c.config = l, c.inboundNodes = u, n.push(c);
}
e.layers = n;
let o = [];
for (let a = 0; a < this.inputLayers.length; a++) {
let i = this.inputLayers[a], l = this.inputLayersNodeIndices[a], u = Xn.nodeKey(i, l);
if (!this.containerNodes.has(u))
continue;
let c = t[u];
c == null && (c = 0);
let p = this.inputLayersTensorIndices[a];
o.push([i.name, c, p]);
}
e.inputLayers = o;
let s = [];
for (let a = 0; a < this.outputLayers.length; a++) {
let i = this.outputLayers[a], l = this.outputLayersNodeIndices[a], u = Xn.nodeKey(i, l);
if (!this.containerNodes.has(u))
continue;
let c = t[u];
c == null && (c = 0);
let p = this.outputLayersTensorIndices[a];
s.push([i.name, c, p]);
}
return e.outputLayers = s, e;
}
static fromConfig(e, t, n = {}, o = false) {
let s = {}, a = {};
function i(g, x) {
g.name in a ? a[g.name].push(x) : a[g.name] = [x];
}
function l(g, x) {
let y = [], w;
for (let _ of x) {
let C = _[0], A = _[1], D = _[2];
if (w = _[3] == null ? {} : _[3], !(C in s)) {
i(g, x);
return;
}
let R = s[C];
if (R.inboundNodes.length <= A) {
i(g, x);
return;
}
let P = R.inboundNodes[A];
y.push(P.outputTensors[D]);
}
y.length > 0 && g.apply(Sr(y), w);
}
function u(g) {
let x = g.name, y = pn(g, t.customObjects != null ? t.customObjects : {});
y.setFastWeightInitDuringBuild(o), s[x] = y, g.inboundNodes.forEach((_) => {
if (!(_ instanceof Array))
throw new z(`Corrupted configuration, expected array for nodeData: ${_}`);
i(y, _);
});
}
let c = t.name, p = t.layers;
for (let g of p)
u(g);
for (; !L2(a); )
for (let g of p) {
let x = s[g.name];
if (x.name in a) {
let y = a[x.name];
delete a[x.name];
for (let w of y)
l(x, w);
}
}
let m = [], f = [], d = t.inputLayers;
for (let g of d) {
let x = g[0], y = g[1], w = g[2];
Kn(x in s);
let C = s[x].inboundNodes[y].outputTensors;
m.push(C[w]);
}
let h = t.outputLayers;
for (let g of h) {
let x = g[0], y = g[1], w = g[2];
Kn(x in s);
let C = s[x].inboundNodes[y].outputTensors;
f.push(C[w]);
}
return new e({ inputs: m, outputs: f, name: c });
}
get stateful() {
if (this._stateful)
throw new z("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");
for (let e of this.layers)
if (e.stateful)
return true;
return false;
}
resetStates() {
V(() => {
this.layers.forEach((e) => {
e.stateful && e.resetStates();
});
});
}
};
function R5(r, e, t) {
let n = e.length;
if (r == null || Array.isArray(r) && r.length === 0)
return e.map((o) => null);
if (n === 1)
return Array.isArray(r) && r.length === 1 ? r : typeof r == "object" && e[0] in r ? [r[e[0]]] : [r];
if (Array.isArray(r)) {
if (r.length !== n)
throw new Error(`Provided ${t} is an array of ${r.length} element(s), but the model has ${n} outputs. Make sure a set of weights is provided for each model output.`);
return r;
} else if (typeof r == "object" && Object.keys(r).length > 0 && typeof r[Object.keys(r)[0]] == "object") {
let o = [];
return e.forEach((s) => {
s in r ? o.push(r[s]) : o.push(null);
}), o;
} else
throw new Error(`The model has multiple (${n}) outputs, so ${t} must be either an array with ${n} elements or an object with ${e} keys. Provided ${t} not understood: ${JSON.stringify(r)}`);
}
function Bx(r, e) {
return R5(r, e, "classWeight");
}
async function Vx(r, e, t, n) {
if (e != null || n != null)
throw new Error("Support sampleWeight is not implemented yet");
if (t != null) {
let o = V(() => {
if (r.shape.length === 1)
return wn(r);
if (r.shape.length === 2) {
if (r.shape[1] > 1)
return As(r, 1);
if (r.shape[1] === 1)
return F(r, [r.shape[0]]);
throw new Error(`Encountered unexpected last-dimension size (${r.shape[1]}) during handling of class weights. The size is expected to be >= 1.`);
} else
throw new Error(`Unexpected rank of target (y) tensor (${r.rank}) during handling of class weights. The rank is expected to be 1 or 2.`);
}), s = Array.from(await o.data());
De(o);
let a = [];
return s.forEach((i) => {
if (t[i] == null)
throw new Error(`classWeight must contain all classes in the training data. The class ${i} exists in the data but not in classWeight`);
a.push(t[i]);
}), $t(a, "float32");
} else
return null;
}
function kA(r, e) {
return O(r, e);
}
var F5 = 32;
function vA(r, e) {
let t, n, o = e;
t = o.xs, n = o.ys, b.assert(t != null && n != null, () => `A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${e}`);
let s = CA("input", r.inputNames, t), a = CA("output", r.outputNames, n), i = s[0].shape[0];
b.assert(s.length === r.inputs.length, () => `LayersModel has ${r.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(r.inputNames)})`), b.assert(a.length === r.outputs.length, () => `LayersModel has ${r.outputs.length} outputs, but the dataset provides ${a.length} outputs. (Expected output keys: ${JSON.stringify(r.outputNames)})`);
for (let l = 0; l < s.length; l++)
b.assert(s[l].shape[0] === i, () => `Batch size mismatch: input ${r.inputNames[l]} has ${s[l].shape[0]}; expected ${i} based on input ${r.inputNames[0]}.`);
for (let l = 0; l < a.length; l++)
b.assert(a[l].shape[0] === i, () => `Batch size mismatch: output ${r.outputNames[l]} has ${a[l].shape[0]}; expected ${i} based on input ${r.inputNames[0]}.`);
return { xs: s, ys: a };
}
function CA(r, e, t) {
if (t instanceof Le)
return [t];
if (Array.isArray(t))
return b.assert(t.length === e.length, () => `Received an array of ${t.length} Tensors, but expected ${e.length} to match the ${r} keys ${e}.`), t;
{
let n = [];
for (let o of e) {
if (t[o] == null)
throw new z(`The feature data generated by the dataset lacks the required ${r} key '${o}'.`);
n.push(t[o]);
}
return n;
}
}
function O5(r) {
if (r.length === 3)
throw new Ne("Validation with sample weights is not implemented yet.");
return { xs: r[0], ys: r[1] };
}
async function IA(r, e, t) {
let n = t.batchesPerEpoch != null;
if (b.assert(r.optimizer != null, () => "You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."), b.assert(t != null, () => "For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."), b.assert(t.epochs != null && t.epochs > 0 && Number.isInteger(t.epochs), () => `For fitDataset(), config.epochs is expected to be a positive integer, but got ${t.epochs}`), b.assert(!n || t.batchesPerEpoch > 0 && Number.isInteger(t.batchesPerEpoch), () => `For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${t.batchesPerEpoch}`), b.assert(t.validationSplit == null, () => "`validationSplit` is not supported by `fitDataset()`. Use validationData instead."), r.isTraining)
throw new Error("Cannot start training because another fit() call is ongoing.");
r.isTraining = true;
try {
let o = t.validationData != null, s, a;
if (o)
if (SA(t.validationData))
b.assert(t.validationBatches == null || t.validationBatches > 0 && Number.isInteger(t.validationBatches), () => `For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${t.validationBatches}`);
else {
let g = O5(t.validationData);
s = g.xs, a = g.ys;
}
let i = r.makeTrainFunction(), l = r.getDedupedMetricsNames(), u;
o ? u = l.slice().concat(l.map((g) => "val_" + g)) : u = l.slice();
let c = $x(t.callbacks, t.yieldEvery), p = t.verbose == null ? 1 : t.verbose, { callbackList: m, history: f } = Rx(c, p, t.epochs, null, null, P5(e, t), null, o, u);
m.setModel(r), r.history = f, await m.onTrainBegin(), r.stopTraining_ = false;
let d = t.initialEpoch == null ? 0 : t.initialEpoch, h = await e.iterator();
for (; d < t.epochs; ) {
let g = {};
await m.onEpochBegin(d);
let x = 0, y = 0;
for (n || (h = await e.iterator()); n ? x < t.batchesPerEpoch : true; ) {
let w = await h.next();
if (n && w.done) {
console.warn(`You provided \`batchesPerEpoch\` as ${t.batchesPerEpoch}, but your dataset iterator ran out of data after ${x} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${t.batchesPerEpoch * t.epochs} batches). You may need to use the repeat() function when building your dataset.`);
break;
}
if (w.value != null) {
let { xs: _, ys: C } = vA(r, w.value), A = {};
A.batch = y, A.size = _[0].shape[0], await m.onBatchBegin(y, A);
let D = [];
if (t.classWeight != null) {
let L = Bx(t.classWeight, r.outputNames);
for (let G = 0; G < L.length; ++G)
D.push(await Vx(C[G], null, L[G]));
}
let R = _.concat(C).concat(D), P = i(R);
De(R);
for (let L = 0; L < l.length; ++L) {
let G = l[L], W = P[L];
A[G] = W, Ft(W);
}
await m.onBatchEnd(y, A), Dx(A), y++, x++;
}
if (n ? x >= t.batchesPerEpoch : w.done) {
if (o) {
let _;
SA(t.validationData) ? _ = wt(await r.evaluateDataset(t.validationData, { batches: t.validationBatches })) : _ = wt(r.evaluate(s, a, { batchSize: t.validationBatchSize == null ? F5 : t.validationBatchSize, verbose: 0 }));
for (let C = 0; C < r.metricsNames.length; ++C)
g[`val_${r.metricsNames[C]}`] = _[C];
}
break;
}
if (r.stopTraining_)
break;
}
if (await m.onEpochEnd(d, g), d++, r.stopTraining_)
break;
}
return await m.onTrainEnd(), await r.history.syncData(), r.history;
} finally {
r.isTraining = false;
}
}
function P5(r, e) {
let t = null;
return e.batchesPerEpoch != null ? t = e.batchesPerEpoch : Number.isFinite(r.size) && (t = r.size), t;
}
function SA(r) {
return typeof r.iterator == "function";
}
function M5(r) {
return typeof r.next == "function";
}
async function NA(r, e, t) {
t = t || {};
let n = t.batches != null, o = r.testFunction, s = [];
if (t.verbose > 0)
throw new Ne("Verbose mode is not implemented yet.");
b.assert(!n || t.batches > 0 && Number.isInteger(t.batches), () => `Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(t.batches)}`);
let a = M5(e) ? e : await e.iterator(), i = 0, l = 0;
for (; n ? l < t.batches : true; ) {
let u = await a.next();
if (s = V(() => {
if (u.value) {
let { xs: c, ys: p } = vA(r, u.value), m = c.concat(p), f = V(() => o(m));
if (De(m), l === 0)
for (let h = 0; h < f.length; ++h)
s.push(pe(0));
let d = m[0].shape[0];
for (let h = 0; h < f.length; ++h) {
let g = f[h], x = s[h];
s[h] = V(() => Z(s[h], O(d, g))), l > 0 && De(x);
}
De(f), i += d, ++l;
}
return s;
}), u.done) {
n && console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${t.batches} batches). You may need to use the repeat() function when building your dataset.`);
break;
}
}
for (let u = 0; u < s.length; ++u) {
let c = s[u];
s[u] = ce(s[u], i), De(c);
}
return Sr(s);
}
function Gx(r) {
b.assert(r > 0 && Number.isInteger(r), () => `batchSize is required to be a positive integer, but got ${r}`);
}
function um(r, e, t) {
return r == null ? [null] : Array.isArray(r) ? r.map((n) => Ha(n, e, t - e)) : Ha(r, e, t - e);
}
function Wx(r, e) {
return V(() => r == null ? null : Array.isArray(r) ? r.map((t) => Wx(t, e)) : Cx(r, e.dtype === "int32" ? e : Y(e, "int32")));
}
function Ux(r, e) {
let t = [], n = 0, o = null;
for (; n < r; )
o = n + e, o >= r && (o = r), t.push([n, o]), n = o;
return t;
}
async function L5(r, e, t, n, o, s, a, i, l, u, c, p, m, f, d) {
o == null && (o = 32), s == null && (s = 1), c == null && (c = true), m == null && (m = 0);
let h = false;
if (l != null && u != null && (h = true), d != null && (h = true, f == null))
throw new z("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");
let g = r.checkNumSamples(t, o, f, "steps_per_epoch"), x;
g != null && (x = Xr(0, g)), a == null && (a = 1);
let { callbackList: y, history: w } = Rx(i, a, s, m, g, f, o, h, p);
y.setModel(r), r.history = w, await y.onTrainBegin(), r.stopTraining_ = false;
for (let _ = m; _ < s; ++_) {
await y.onEpochBegin(_);
let C = {};
if (f != null)
throw new Ne("stepsPerEpoch mode is not implemented yet.");
{
if (c === "batch")
throw new Ne("batch shuffling is not implemneted yet");
c && b.shuffle(x);
let A = $t(x), D = Ux(g, o);
for (let R = 0; R < D.length; ++R) {
let P = {};
if (await y.onBatchBegin(R, P), V(() => {
let L = D[R][0], G = D[R][1], W = Ha(A, L, G - L);
P.batch = R, P.size = G - L;
let j = Wx(t, W), H = e(j);
for (let q = 0; q < n.length; ++q) {
let X = n[q], re = H[q];
P[X] = re, Ft(re);
}
if (R === D.length - 1 && h) {
let q = r.testLoop(l, u, o);
for (let X = 0; X < n.length; ++X) {
let re = n[X], J = q[X];
Ft(J), C["val_" + re] = J;
}
}
}), await y.onBatchEnd(R, P), Dx(P), r.stopTraining_)
break;
}
A.dispose();
}
if (await y.onEpochEnd(_, C), r.stopTraining_)
break;
}
return await y.onTrainEnd(), await r.history.syncData(), r.history;
}
async function TA(r, e, t, n = {}) {
if (r.isTraining)
throw new Error("Cannot start training because another fit() call is ongoing.");
r.isTraining = true;
let o, s, a, i, l, u, c;
try {
let p = n.batchSize == null ? 32 : n.batchSize;
Gx(p);
let m = false, f = await r.standardizeUserData(e, t, n.sampleWeight, n.classWeight, m, p);
o = f[0], s = f[1], c = f[2];
let d = false, h;
if (n.validationData != null && n.validationData.length > 0) {
if (d = true, n.validationData.length === 2)
a = n.validationData[0], i = n.validationData[1];
else
throw n.validationData.length === 3 ? new Ne("validationData including sample weights is not supported yet.") : new z(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);
let D = true, R = await r.standardizeUserData(a, i, null, null, D, p);
l = R[0], u = R[1], h = l.concat(u);
} else if (n.validationSplit != null && n.validationSplit > 0 && n.validationSplit < 1) {
d = true;
let D = Math.floor(o[0].shape[0] * (1 - n.validationSplit)), R = o[0].shape[0];
l = um(o, D, R), o = um(o, 0, D), u = um(s, D, R), s = um(s, 0, D), h = l.concat(u);
} else
n.validationSteps != null && (d = true);
let g = o.concat(s).concat(c);
r.checkTrainableWeightsConsistency();
let x = r.makeTrainFunction(), y = r.getDedupedMetricsNames(), w, _;
d ? (r.makeTestFunction(), w = r.testFunction, _ = y.slice().concat(y.map((D) => "val_" + D))) : (w = null, h = [], _ = y.slice());
let C = $x(n.callbacks, n.yieldEvery);
return await L5(r, x, g, y, p, n.epochs, n.verbose, C, w, h, n.shuffle, _, n.initialEpoch, null, null);
} finally {
r.isTraining = false, Ml(o, e), Ml(s, t), Ml(l, a), Ml(u, i), c != null && De(c);
}
}
function Hk(r) {
let e = [];
r instanceof Le && (r = [r]);
for (let t = 0; t < r.length; ++t) {
let n = r[t];
if (n.rank === 1)
e.push(ja(n, 1));
else {
if (n.rank === 0)
throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");
e.push(n);
}
}
return e;
}
function Ml(r, e) {
if (r == null)
return;
let t = [];
if (e instanceof Le)
t.push(e.id);
else if (Array.isArray(e))
e.forEach((o) => t.push(o.id));
else if (e != null)
for (let o in e) {
let s = e[o];
t.push(s.id);
}
let n = [];
if (r instanceof Le)
t.indexOf(r.id) === -1 && n.push(r);
else if (Array.isArray(r))
r.forEach((o) => {
t.indexOf(o.id) === -1 && n.push(o);
});
else if (r != null)
for (let o in r) {
let s = r[o];
t.indexOf(s.id) === -1 && n.push(s);
}
n.forEach((o) => {
o.isDisposed || o.dispose();
});
}
function z5(r) {
return r instanceof Le;
}
function qk(r) {
return Array.isArray(r);
}
function EA(r) {
return !z5(r) && !qk(r);
}
function AA(r, e, t, n = true, o = "") {
if (e == null || e.length === 0) {
if (r != null) {
let a = false;
if (qk(r) && r.length > 0)
a = true;
else if (EA(r)) {
for (let i in r)
if (r.hasOwnProperty(i)) {
a = true;
break;
}
} else
a = true;
if (a)
throw new z(`Error when checking model ${o} expected no data, but got ${r}`);
}
return [];
}
if (r == null)
return e.map((a) => null);
let s;
if (EA(r)) {
r = r, s = [];
for (let a of e) {
if (r[a] == null)
throw new z(`No data provided for "${a}". Need data for each key in: ${e}`);
s.push(r[a]);
}
} else if (qk(r)) {
if (r = r, r.length !== e.length)
throw new z(`Error when checking model ${o}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${e.length} Tensor(s), but instead got the following list of Tensor(s): ${r}`);
s = r;
} else {
if (r = r, e.length > 1)
throw new z(`The model ${o} expects ${e.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${r.shape}`);
s = [r];
}
if (s = Hk(s), t != null)
for (let a = 0; a < e.length; ++a) {
if (t[a] == null)
continue;
let i = s[a];
if (i.shape.length !== t[a].length)
throw new z(`Error when checking ${o}: expected ${e[a]} to have ${t[a].length} dimension(s). but got array with shape ${i.shape}`);
for (let l = 0; l < t[a].length; ++l) {
if (l === 0 && !n)
continue;
let u = i.shape[l], c = t[a][l];
if (c != null && c >= 0 && u !== c)
throw new z(`${o} expected a batch of elements where each example has shape [${t[a].slice(1, t[a].length)}] (i.e.,tensor shape [*,${t[a].slice(1, t[a].length)}]) but the ${o} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1, i.shape.length)}] (tensor shape [${i.shape}])`);
}
}
return s;
}
function B5(r, e, t) {
let n = bo(r.map((s) => s.shape[0]));
n.sort();
let o = bo(e.map((s) => s.shape[0]));
if (o.sort(), n.length > 1)
throw new z(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(r.map((s) => s.shape))}`);
if (o.length > 1)
throw new z(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map((s) => s.shape))}`);
if (n.length > 0 && o.length > 0 && !b.arraysEqual(n, o))
throw new z(`Input Tensors should have the same number of samples as target Tensors. Found ${n[0]} input sample(s) and ${o[0]} target sample(s).`);
}
function V5(r, e, t) {
let n = [Ni, am, nc];
for (let o = 0; o < r.length; ++o) {
let s = r[o], a = e[o], i = t[o];
if (a != null) {
if (a === nc && s.shape[s.shape.length - 1] === 1)
throw new z(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);
if (n.indexOf(a) !== -1) {
let l = s.shape.slice(1), u = i.slice(1);
for (let c = 0; c < l.length; ++c) {
let p = l[c], m = u[c];
if (m != null && p !== m)
throw new z(`A target Tensor with shape ${s.shape} was passed for an output of shape ${i}, while using a loss function that expects targets to have the same shape as the output.`);
}
}
}
}
}
function DA(r, e, t, n = true, o = "") {
let s;
if (Array.isArray(r)) {
if (r.length !== e.length)
throw new z(`Error when checking model ${o}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${e.length} Tensor(s), but instead got ${r.length} Tensors(s).`);
s = r;
} else {
if (e.length > 1)
throw new z(`The model expects ${e.length} ${o} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(r.shape)}.`);
s = [r];
}
if (t != null)
for (let a = 0; a < e.length; ++a) {
if (t[a] == null)
continue;
let i = s[a];
if (i.shape.length !== t[a].length)
throw new z(`Error when checking ${o}: expected ${e[a]} to have ${t[a].length} dimension(s), but got array with shape ${JSON.stringify(i.shape)}`);
for (let l = 0; l < t[a].length; ++l) {
if (l === 0 && !n)
continue;
let u = i.shape[l], c = t[a][l];
if (c != null && c !== u)
throw new z(`Error when checking ${o}: expected ${e[a]} to have shape ${JSON.stringify(t[a])} but got array with shape ${JSON.stringify(i.shape)}.`);
}
}
}
function G5(r, e) {
if (r == null || Array.isArray(r) && r.length === 0)
return e.map((n) => []);
let t;
if (typeof r == "string" || typeof r == "function")
t = [r];
else if (Array.isArray(r) || typeof r == "object")
t = r;
else
throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${r}`);
if (Array.isArray(t))
return e.map((n) => t);
{
let n = [];
for (let o of e) {
let s = t.hasOwnProperty(o) ? t[o] : [];
Array.isArray(s) || (s = [s]), n.push(s);
}
return n;
}
}
var W5 = "layers-model";
var Yn = class extends Xn {
constructor(e) {
super(e);
this.isTraining = false;
}
summary(e, t, n = console.log) {
if (!this.built)
throw new z("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");
yA(this, e, t, n);
}
compile(e) {
if (e.loss == null && (e.loss = []), this.loss = e.loss, typeof e.optimizer == "string")
this.optimizer_ = gA(e.optimizer), this.isOptimizerOwned = true;
else {
if (!(e.optimizer instanceof qr))
throw new z("User-defined optimizer must be an instance of tf.Optimizer.");
this.optimizer_ = e.optimizer, this.isOptimizerOwned = false;
}
let t = [];
if (!Array.isArray(e.loss) && typeof e.loss != "string" && typeof e.loss != "function") {
e.loss = e.loss;
for (let a in e.loss)
if (this.outputNames.indexOf(a) === -1)
throw new z(`Unknown entry in loss dictionary: "${a}". Only expected the following keys: ${this.outputNames}`);
for (let a of this.outputNames)
e.loss[a] == null && console.warn(`Output "${a}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${a} during training`), t.push(Fx(e.loss[a]));
} else if (Array.isArray(e.loss)) {
if (e.loss.length !== this.outputs.length)
throw new z(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);
t = e.loss.map((i) => Fx(i));
} else {
let a = Fx(e.loss);
this.outputs.forEach((i) => {
t.push(a);
});
}
this.lossFunctions = t, this.feedOutputNames = [], this.feedOutputShapes = [], this.feedLossFns = [];
for (let a = 0; a < this.outputs.length; ++a) {
let i = this.internalOutputShapes[a], l = this.outputNames[a];
this.feedOutputNames.push(l), this.feedOutputShapes.push(i), this.feedLossFns.push(this.lossFunctions[a]);
}
let n = [];
this.metrics = e.metrics, this.metricsNames = ["loss"], this.metricsTensors = [], zs("loss", () => {
for (let a = 0; a < this.outputs.length; ++a) {
if (n.indexOf(a) !== -1)
continue;
let i = this.lossFunctions[a];
this.outputs.length > 1 && (this.metricsTensors.push([i, a]), this.metricsNames.push(this.outputNames[a] + "_loss"));
}
});
let o = G5(e.metrics, this.outputNames), s = (a, i, l) => {
this.outputNames.length > 1 && (i = this.outputNames[a] + "_" + i), this.metricsNames.push(i), this.metricsTensors.push([l, a]);
};
zs("metric", () => {
for (let a = 0; a < this.outputs.length; ++a) {
if (n.indexOf(a) !== -1)
continue;
let i = o[a];
((u) => {
let c = "", p, m, f;
for (let d of u) {
if (typeof d == "string" && ["accuracy", "acc", "crossentropy", "ce"].indexOf(d) !== -1) {
let g = this.internalOutputShapes[a];
g[g.length - 1] === 1 || this.lossFunctions[a] === am ? ["accuracy", "acc"].indexOf(d) !== -1 ? m = dd : ["crossentropy", "ce"].indexOf(d) !== -1 && (m = Ox) : this.lossFunctions[a] === im ? ["accuracy", "acc"].indexOf(d) !== -1 ? m = Px : ["crossentropy", "ce"].indexOf(d) !== -1 && (m = Gk) : ["accuracy", "acc"].indexOf(d) !== -1 ? m = hd : ["crossentropy", "ce"].indexOf(d) !== -1 && (m = gd);
let x;
["accuracy", "acc"].indexOf(d) !== -1 ? x = "acc" : ["crossentropy", "ce"].indexOf(d) !== -1 && (x = "ce"), f = m, p = c + x;
} else
f = hA(d), p = c + xd(d);
let h;
zs(p, () => {
h = f;
}), s(a, p, h);
}
})(i);
}
}), this.collectedTrainableWeights = this.trainableWeights;
}
checkTrainableWeightsConsistency() {
this.collectedTrainableWeights != null && this.trainableWeights.length !== this.collectedTrainableWeights.length && console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?");
}
evaluate(e, t, n = {}) {
let o = n.batchSize == null ? 32 : n.batchSize;
Gx(o);
let s = true, a = this.standardizeUserDataXY(e, t, s, o);
try {
let i = a[0].concat(a[1]);
this.makeTestFunction();
let l = this.testFunction, u = this.testLoop(l, i, o, n.verbose, n.steps);
return Sr(u);
} finally {
Ml(a[0], e), Ml(a[1], t);
}
}
async evaluateDataset(e, t) {
return this.makeTestFunction(), NA(this, e, t);
}
checkNumSamples(e, t, n, o = "steps") {
let s;
if (n != null) {
if (s = null, t != null)
throw new z(`If ${o} is set, batchSize must be null or undefined.Got batchSize = ${t}`);
} else if (e != null)
Array.isArray(e) ? s = e[0].shape[0] : s = e.shape[0];
else
throw new z(`Either the input data should have a defined shape, or ${o} shoud be specified.`);
return s;
}
execute(e, t) {
if (Array.isArray(t) && t.length === 0)
throw new z("`outputs` is an empty Array, which is not allowed.");
let n = Array.isArray(t), o = n ? t : [t], s = this.retrieveSymbolicTensors(o), a = new Vs();
if (e instanceof Le && (e = [e]), Array.isArray(e)) {
if (e.length !== this.inputs.length)
throw new z(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);
for (let l = 0; l < this.inputs.length; ++l)
a.add(this.inputs[l], e[l]);
} else
for (let l of this.inputs) {
let u = e[l.name];
if (u == null)
throw new z(`No value is provided for the model's input ${l.name}`);
a.add(l, u);
}
let i = sc(s, a);
return n ? i : i[0];
}
retrieveSymbolicTensors(e) {
let t = go(null, e.length), n = e.length;
for (let o of this.layers) {
let s = Array.isArray(o.output) ? o.output : [o.output], a = s.map((i) => i.name);
for (let i = 0; i < e.length; ++i) {
let l = a.indexOf(e[i]);
if (l !== -1 && (t[i] = s[l], n--), n === 0)
break;
}
if (n === 0)
break;
}
if (n > 0) {
let o = [];
throw t.forEach((s, a) => {
s == null && o.push(e[a]);
}), new z(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(o)}`);
}
return t;
}
predictLoop(e, t = 32, n = false) {
return V(() => {
let o = this.checkNumSamples(e);
if (n)
throw new Ne("Verbose predictLoop() is not implemented yet.");
let s = Ux(o, t), a = this.outputs.map((i) => []);
for (let i = 0; i < s.length; ++i)
V(() => {
let u = s[i][0], c = s[i][1], p = um(e, u, c), m = [];
if (Array.isArray(p))
for (let d = 0; d < p.length; ++d)
m.push({ key: this.inputs[d], value: p[d] });
else
m.push({ key: this.inputs[0], value: p });
let f = new Vs(m);
return sc(this.outputs, f);
}).forEach((u, c) => a[c].push(u));
return Sr(a.map((i) => tt(i, 0)));
});
}
predict(e, t = {}) {
let n = Hk(e);
DA(n, this.inputNames, this.feedInputShapes, false);
try {
let o = t.batchSize == null ? 32 : t.batchSize;
return Gx(o), this.predictLoop(n, o);
} finally {
Ml(n, e);
}
}
predictOnBatch(e) {
DA(e, this.inputNames, this.feedInputShapes, true);
let t = (Array.isArray(e) ? e[0] : e).shape[0];
return this.predictLoop(e, t);
}
standardizeUserDataXY(e, t, n = true, o) {
if (this.optimizer_ == null)
throw new Kr("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");
let s = [];
for (let a = 0; a < this.feedOutputShapes.length; ++a) {
let i = this.feedOutputShapes[a];
this.feedLossFns[a] === im ? s.push(i.slice(0, i.length - 1).concat([1])) : s.push(i);
}
if (e = AA(e, this.feedInputNames, this.feedInputShapes, false, "input"), t = AA(t, this.feedOutputNames, s, false, "target"), B5(e, t, null), V5(t, this.feedLossFns, this.feedOutputShapes), this.stateful && o != null && o > 0 && e[0].shape[0] % o != 0)
throw new z(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${o}. Found: ${e[0].shape[0]} sample(s).`);
return [e, t];
}
async standardizeUserData(e, t, n, o, s = true, a) {
let [i, l] = this.standardizeUserDataXY(e, t, s, a);
if (n != null)
throw new Error("sample weight is not supported yet.");
let u = null;
if (o != null) {
let c = Bx(o, this.outputNames);
u = [];
for (let p = 0; p < c.length; ++p)
u.push(await Vx(l[p], null, c[p]));
}
return [i, l, u];
}
testLoop(e, t, n, o = 0, s) {
return V(() => {
let a = this.checkNumSamples(t, n, s, "steps"), i = [];
if (o > 0)
throw new Ne("Verbose mode is not implemented yet.");
if (s != null)
throw new Ne("steps mode in testLoop() is not implemented yet");
{
let l = Ux(a, n), u = $t(Xr(0, a));
for (let c = 0; c < l.length; ++c) {
let p = l[c][0], m = l[c][1], f = Ha(u, p, m - p), d = Wx(t, f), h = e(d);
if (c === 0)
for (let g = 0; g < h.length; ++g)
i.push(pe(0));
for (let g = 0; g < h.length; ++g) {
let x = h[g];
i[g] = Z(i[g], O(m - p, x));
}
}
for (let c = 0; c < i.length; ++c)
i[c] = ce(i[c], a);
}
return i;
});
}
getDedupedMetricsNames() {
let e = this.metricsNames, t = [];
for (let n = 0; n < e.length; ++n) {
let o = e[n], s = o;
Ak(e, o) > 1 && (s += `_${Ak(e.slice(0, n), o)}`), t.push(s);
}
return t;
}
makeTrainFunction() {
return (e) => {
let t = [], n = e.slice(0, this.inputs.length), o = e.slice(this.inputs.length, this.inputs.length + this.outputs.length), s = e.slice(this.inputs.length + this.outputs.length, this.inputs.length + this.outputs.length * 2), a = [], i = () => {
let p = [];
for (let h = 0; h < this.inputs.length; ++h)
p.push({ key: this.inputs[h], value: n[h] });
let m = new Vs(p), f = sc(this.outputs, m, { training: true }), d;
for (let h = 0; h < this.lossFunctions.length; ++h) {
let x = this.lossFunctions[h](o[h], f[h]);
s[h] != null && (x = kA(x, s[h]));
let y = xt(x);
t.push(y), h === 0 ? d = x : d = Z(d, x);
}
for (let h = 0; h < this.metricsTensors.length; ++h) {
let g;
if (this.outputs.length > 1 && h < this.outputs.length)
g = t[h];
else {
let x = this.metricsTensors[h][0], y = this.metricsTensors[h][1];
g = xt(x(o[y], f[y]));
}
Ft(g), a.push(g);
}
return d = xt(d), this.calculateLosses().forEach((h) => {
d = Z(d, h);
}), d;
}, l = this.collectedTrainableWeights.map((p) => p.read()), u = true;
return [this.optimizer_.minimize(i, u, l)].concat(a);
};
}
makeTestFunction() {
this.testFunction = (e) => V(() => {
let t = [], n, o = e.slice(0, this.inputs.length), s = e.slice(this.inputs.length, this.inputs.length + this.outputs.length), a = [];
for (let u = 0; u < this.inputs.length; ++u)
a.push({ key: this.inputs[u], value: o[u] });
let i = new Vs(a), l = sc(this.outputs, i);
for (let u = 0; u < this.lossFunctions.length; ++u) {
let c = this.lossFunctions[u], p = xt(c(s[u], l[u]));
u === 0 ? n = p : n = Z(n, p), t.push(n);
}
for (let u = 0; u < this.metricsTensors.length; ++u) {
let c = this.metricsTensors[u][0], p = this.metricsTensors[u][1], m = xt(c(s[p], l[p]));
t.push(m);
}
return t;
});
}
async fit(e, t, n = {}) {
return TA(this, e, t, n);
}
async fitDataset(e, t) {
return IA(this, e, t);
}
async trainOnBatch(e, t) {
let n = await this.standardizeUserData(e, t), o = n[0], s = n[1], i = this.makeTrainFunction()(o.concat(s)), l = [];
for (let u of i) {
let c = await u.data();
l.push(c[0]);
}
return De(i), Sr(l);
}
getNamedWeights(e) {
let t = [], n = e != null && e.trainableOnly, o = n ? this.trainableWeights : this.weights, s = this.getWeights(n);
for (let a = 0; a < o.length; ++a)
n && !o[a].trainable || t.push({ name: o[a].originalName, tensor: s[a] });
return t;
}
set stopTraining(e) {
this.stopTraining_ = e;
}
get stopTraining() {
return this.stopTraining_;
}
get optimizer() {
return this.optimizer_;
}
set optimizer(e) {
this.optimizer_ !== e && (this.optimizer_ = e, this.isOptimizerOwned = false);
}
dispose() {
let e = super.dispose();
if (e.refCountAfterDispose === 0 && this.optimizer != null && this.isOptimizerOwned) {
let t = ff().numTensors;
this.optimizer_.dispose(), e.numDisposedVariables += t - ff().numTensors;
}
return e;
}
getLossIdentifiers() {
let e;
if (typeof this.loss == "string")
e = xo(this.loss);
else if (Array.isArray(this.loss)) {
for (let t of this.loss)
if (typeof t != "string")
throw new Error("Serialization of non-string loss is not supported.");
e = this.loss.map((t) => xo(t));
} else {
let t = Object.keys(this.loss);
e = {};
let n = this.loss;
for (let o of t)
if (typeof n[o] == "string")
e[o] = xo(n[o]);
else
throw new Error("Serialization of non-string loss is not supported.");
}
return e;
}
getMetricIdentifiers() {
if (typeof this.metrics == "string" || typeof this.metrics == "function")
return [xo(xd(this.metrics))];
if (Array.isArray(this.metrics))
return this.metrics.map((e) => xo(xd(e)));
{
let e = {};
for (let t in this.metrics)
e[t] = xo(xd(this.metrics[t]));
return e;
}
}
getTrainingConfig() {
return { loss: this.getLossIdentifiers(), metrics: this.getMetricIdentifiers(), optimizer_config: { class_name: this.optimizer.getClassName(), config: this.optimizer.getConfig() } };
}
loadTrainingConfig(e) {
if (e.weighted_metrics != null)
throw new Error("Loading weight_metrics is not supported yet.");
if (e.loss_weights != null)
throw new Error("Loading loss_weights is not supported yet.");
if (e.sample_weight_mode != null)
throw new Error("Loading sample_weight_mode is not supported yet.");
let t = oc(e.optimizer_config), n = pn(t), o;
if (typeof e.loss == "string")
o = Ua(e.loss);
else if (Array.isArray(e.loss))
o = e.loss.map((a) => Ua(a));
else if (e.loss != null) {
o = {};
for (let a in e.loss)
o[a] = Ua(e.loss[a]);
}
let s;
if (Array.isArray(e.metrics))
s = e.metrics.map((a) => Ua(a));
else if (e.metrics != null) {
s = {};
for (let a in e.metrics)
s[a] = Ua(e.metrics[a]);
}
this.compile({ loss: o, metrics: s, optimizer: n });
}
async save(e, t) {
if (typeof e == "string") {
let u = Lr.getSaveHandlers(e);
if (u.length === 0)
throw new z(`Cannot find any save handlers for URL '${e}'`);
if (u.length > 1)
throw new z(`Found more than one (${u.length}) save handlers for URL '${e}'`);
e = u[0];
}
if (e.save == null)
throw new z("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");
let n = await Lr.encodeWeights(this.getNamedWeights(t)), o = false, s = null, i = { modelTopology: this.toJSON(s, o), format: W5, generatedBy: `TensorFlow.js tfjs-layers v${lm}`, convertedBy: null };
if ((t == null ? false : t.includeOptimizer) && this.optimizer != null) {
i.trainingConfig = this.getTrainingConfig();
let u = "optimizer", { data: c, specs: p } = await Lr.encodeWeights(await this.optimizer.getWeights(), u);
n.specs.push(...p), n.data = Lr.concatenateArrayBuffers([n.data, c]);
}
if (this.userDefinedMetadata != null) {
let u = true;
Wk(this.userDefinedMetadata, this.name, u), i.userDefinedMetadata = this.userDefinedMetadata;
}
return i.weightData = n.data, i.weightSpecs = n.specs, e.save(i);
}
setUserDefinedMetadata(e) {
Wk(e, this.name), this.userDefinedMetadata = e;
}
getUserDefinedMetadata() {
return this.userDefinedMetadata;
}
};
Yn.className = "Model";
ee.registerClass(Yn);
var Kk = class extends Yn {
};
Kk.className = "Functional";
ee.registerClass(Kk);
async function $A(r, e) {
"modelTopology" in r || (r = { modelTopology: r }), r = r;
let t = r.modelTopology;
t.model_config != null && (t = t.model_config);
let n = oc(t), o = pn(n, e);
if (r.weightsManifest != null) {
let s = await Lr.loadWeights(r.weightsManifest, r.pathPrefix, o.weights.map((i) => i.originalName)), a = {};
for (let i of o.weights)
a[i.originalName] = s[i.originalName];
o.loadWeights(a), De(s);
}
return o;
}
async function RA(r, e) {
if (e == null && (e = {}), typeof r == "string") {
let t = Lr.getLoadHandlers(r, e);
if (t.length === 0)
t.push(Lr.browserHTTPRequest(r, e));
else if (t.length > 1)
throw new z(`Found more than one (${t.length}) load handlers for URL '${r}'`);
r = t[0];
}
return U5(r, void 0, e);
}
async function U5(r, e, t) {
if (t == null && (t = {}), r.load == null)
throw new z("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");
let n = await r.load(), o = n.modelTopology;
o.model_config != null && (o = o.model_config);
let s = t.strict == null ? true : t.strict, a = n.weightData != null && n.weightSpecs != null && s, i = pn(oc(o), e, a), l = n.trainingConfig;
if (l != null && i.loadTrainingConfig(l), n.userDefinedMetadata != null && i.setUserDefinedMetadata(n.userDefinedMetadata), n.weightData != null) {
if (n.weightSpecs == null)
throw new z("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");
let { modelWeights: u, optimizerWeights: c } = j5(n.weightData, n.weightSpecs);
i.loadWeights(u, s), i.optimizer != null && c.length > 0 && await i.optimizer.setWeights(c), De(u), De(c.map((p) => p.tensor));
}
return i;
}
function j5(r, e) {
let t = Lr.decodeWeights(r, e), n = {}, o = [];
return e.forEach((s) => {
s.group === "optimizer" ? o.push({ name: s.name, tensor: t[s.name] }) : n[s.name] = t[s.name];
}), { modelWeights: n, optimizerWeights: o };
}
var qa = class extends Yn {
constructor(e) {
super({ inputs: [], outputs: [] });
if (e = e || {}, this.trainable = true, this.built = false, this.name = e.name != null ? e.name : Rl("sequential_"), e.layers != null)
for (let t of e.layers)
this.add(t);
}
checkShape(e) {
if (e.inboundNodes[0].outputTensors[0].shape.some((n) => n < 0))
throw new z(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`);
}
add(e) {
let t = e instanceof qa || e instanceof Yn, n;
if (t) {
if (n = e, n.outputs.length !== 1)
throw new z("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");
if (n.inputs.length !== 1)
throw new z("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.");
}
if (this.outputs.length === 0) {
if (e.inboundNodes.length === 0) {
if (e.batchInputShape == null)
throw new z("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");
let o = Ax({ batchShape: e.batchInputShape, dtype: e.dtype, name: e.name + "_input" });
e.apply(o);
}
if (t)
this.outputs = n.outputs, this.inputs = n.inputs;
else {
if (e.inboundNodes.length !== 1)
throw new z(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);
if (e.inboundNodes[0].outputTensors.length !== 1)
throw new z("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");
this.checkShape(e), this.outputs = [e.inboundNodes[0].outputTensors[0]], this.inputs = Mk(this.outputs[0]);
}
this.inboundNodes = [], new Fl({ outboundLayer: this, inboundLayers: [], nodeIndices: [], tensorIndices: [], inputTensors: this.inputs, outputTensors: this.outputs, inputMasks: go(null, this.inputs.length), outputMasks: [null], inputShapes: this.inputs.map((o) => o.shape), outputShapes: this.outputs[0].shape });
} else {
let o = e.apply(this.outputs[0]);
if (Array.isArray(o))
throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");
this.checkShape(e), this.outputs = [o], this.inboundNodes[0].outputTensors = this.outputs, this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
}
this.layers.push(e), this.built = false;
}
pop() {
if (this.layers.length === 0)
throw new TypeError("There are no layers in the model.");
if (this.layers.pop(), this.layers.length === 0)
this.outputs = [], this.inboundNodes = [], this.outboundNodes = [];
else {
let e = this.layers.length - 1;
this.layers[e].outboundNodes = [], this.outputs = [this.layers[e].output], this.inboundNodes[0].outputTensors = this.outputs, this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
}
}
call(e, t) {
return this.model == null && this.build(), this.model.call(e, t);
}
build(e) {
if (Xe(e), this.inputs.length === 0 || this.outputs.length === 0)
throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");
this.model = new Yn({ inputs: this.inputs, outputs: this.outputs[0], name: this.name + "_model" }), this.model.trainable = this.trainable, this.supportsMasking = this.model.supportsMasking, this.inputLayers = this.model.inputLayers, this.inputLayersNodeIndices = this.model.inputLayersNodeIndices, this.inputLayersTensorIndices = this.model.inputLayersTensorIndices, this.outputLayers = this.model.outputLayers, this.outputLayersNodeIndices = this.model.outputLayersNodeIndices, this.outputLayersTensorIndices = this.model.outputLayersTensorIndices, this.nodesByDepth = this.model.nodesByDepth, this.containerNodes = this.model.containerNodes, this.outputNames = this.model.outputNames, this.inputNames = this.model.inputNames, this.built = true;
}
countParams() {
return this.built || this.build(), super.countParams();
}
summary(e, t, n = console.log) {
this.built || this.build(), super.summary(e, t, n);
}
setWeights(e) {
this.model == null && this.build(), this.model.setWeights(e);
}
evaluate(e, t, n = {}) {
if (!this.built)
throw new Kr("The model needs to be compiled before being used.");
return this.model.evaluate(e, t, n);
}
async evaluateDataset(e, t) {
if (!this.built)
throw new Kr("The model needs to be compiled before being used.");
return this.model.evaluateDataset(e, t);
}
predict(e, t = {}) {
return this.model == null && this.build(), this.model.predict(e, t);
}
predictOnBatch(e) {
return this.model == null && this.build(), this.model.predictOnBatch(e);
}
compile(e) {
this.build(), this.model.compile(e), this.optimizer_ = this.model.optimizer, this.isOptimizerOwned = this.model.isOptimizerOwned, this.loss = this.model.loss, this.metrics = this.model.metrics, this.metricsTensors = this.model.metricsTensors, this.metricsNames = this.model.metricsNames;
}
get optimizer() {
return this.model == null ? void 0 : this.model.optimizer;
}
set optimizer(e) {
this.model.optimizer = e;
}
async fit(e, t, n = {}) {
if (!this.built)
throw new Kr("The model needs to be compiled before being used.");
return this.model.fit(e, t, n);
}
async fitDataset(e, t) {
if (!this.built)
throw new Kr("The model needs to be compiled before being used.");
return this.model.fitDataset(e, t);
}
async trainOnBatch(e, t) {
return this.model.trainOnBatch(e, t);
}
static fromConfig(e, t, n = {}, o = false) {
let s, a = {};
if (t instanceof Array) {
if (t[0].className == null || t[0].className === "Merge")
throw new z("Legacy serialization format not supported yet.");
s = t;
} else
b.assert(t.layers != null, () => "When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."), s = t.layers, delete t.layers, a = t;
let i = new e(a);
if (!(i instanceof qa))
throw new Ne(`Sequential.fromConfig called on non-Sequential input: ${i}`);
for (let l of s) {
let c = pn(l, void 0, o);
o && c.setFastWeightInitDuringBuild(true), i.add(c);
}
return i;
}
set stopTraining(e) {
if (this.model == null)
throw new z("Cannot set the stopTraining property of a sequential model before it is compiled.");
this.model.stopTraining = e;
}
get stopTraining() {
if (this.model == null)
throw new z("Cannot get the stopTraining property of a sequential model before it is compiled.");
return this.model.stopTraining;
}
getConfig() {
let e = [];
for (let t of this.layers) {
let n = {};
n.className = t.getClassName(), n.config = t.getConfig(), e.push(n);
}
return { name: this.name, layers: e };
}
};
qa.className = "Sequential";
ee.registerClass(qa);
function H5(r) {
return new Yn(r);
}
function q5(r) {
return new qa(r);
}
function K5(r, e) {
return e == null && (e = {}), RA(r, e);
}
function Xk(r) {
return Ax(r);
}
function X5(r, e) {
Sn.registerCallbackConstructor(r, e);
}
var mn = class extends ee.Serializable {
getConfig() {
return {};
}
};
var Yk = class extends mn {
apply(e, t = 1) {
return rA(e, t);
}
};
Yk.className = "elu";
ee.registerClass(Yk);
var Zk = class extends mn {
apply(e) {
return Pu(e);
}
};
Zk.className = "selu";
ee.registerClass(Zk);
var Jk = class extends mn {
apply(e) {
return Ir(e);
}
};
Jk.className = "relu";
ee.registerClass(Jk);
var Qk = class extends mn {
apply(e) {
return V(() => Ps(6, Ir(e)));
}
};
Qk.className = "relu6";
ee.registerClass(Qk);
var ev = class extends mn {
apply(e) {
return e;
}
};
ev.className = "linear";
ee.registerClass(ev);
var tv = class extends mn {
apply(e) {
return zr(e);
}
};
tv.className = "sigmoid";
ee.registerClass(tv);
var rv = class extends mn {
apply(e) {
return oA(e);
}
};
rv.className = "hardSigmoid";
ee.registerClass(rv);
var nv = class extends mn {
apply(e) {
return co(e);
}
};
nv.className = "softplus";
ee.registerClass(nv);
var ov = class extends mn {
apply(e) {
return nA(e);
}
};
ov.className = "softsign";
ee.registerClass(ov);
var sv = class extends mn {
apply(e) {
return Ds(e);
}
};
sv.className = "tanh";
ee.registerClass(sv);
var yd = class extends mn {
apply(e, t = -1) {
return za(e, t);
}
};
yd.className = "softmax";
ee.registerClass(yd);
var iv = class extends mn {
apply(e, t = -1) {
return Eu(e, t);
}
};
iv.className = "logSoftmax";
ee.registerClass(iv);
var av = class extends mn {
apply(e, t = 1) {
return V(() => O(zr(O(e, t)), e));
}
};
av.className = "swish";
ee.registerClass(av);
var lv = class extends mn {
apply(e) {
return V(() => O(e, Ds(co(e))));
}
};
lv.className = "mish";
ee.registerClass(lv);
function Gs(r) {
return r.getClassName();
}
function uv(r, e = {}) {
return vi(r, ee.SerializationMap.getMap().classNameMap, e, "activation");
}
function Ws(r) {
if (r == null) {
let e = {};
return e.className = "linear", e.config = {}, uv(e);
}
if (typeof r == "string") {
let e = {};
return e.className = r, e.config = {}, uv(e);
} else
return r instanceof mn ? r : uv(r);
}
function cv(r) {
if (r != null && typeof r != "object")
throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${r}`);
}
var pv = class extends ee.Serializable {
};
var ic = class extends pv {
constructor(e) {
super();
cv(e), this.l1 = e == null || e.l1 == null ? 0.01 : e.l1, this.l2 = e == null || e.l2 == null ? 0.01 : e.l2, this.hasL1 = this.l1 !== 0, this.hasL2 = this.l2 !== 0;
}
apply(e) {
return V(() => {
let t = yt([1]);
return this.hasL1 && (t = Z(t, me(O(this.l1, Ct(e))))), this.hasL2 && (t = Z(t, me(O(this.l2, tc(e))))), F(t, []);
});
}
getConfig() {
return { l1: this.l1, l2: this.l2 };
}
static fromConfig(e, t) {
return new e({ l1: t.l1, l2: t.l2 });
}
};
ic.className = "L1L2";
ee.registerClass(ic);
function FA(r) {
return cv(r), new ic({ l1: r != null ? r.l1 : null, l2: 0 });
}
function OA(r) {
return cv(r), new ic({ l2: r != null ? r.l2 : null, l1: 0 });
}
var PA = { l1l2: "L1L2" };
function ct(r) {
return jp(r);
}
function MA(r, e = {}) {
return vi(r, ee.SerializationMap.getMap().classNameMap, e, "regularizer");
}
function _t(r) {
if (r == null)
return null;
if (typeof r == "string") {
let t = { className: r in PA ? PA[r] : r, config: {} };
return MA(t);
} else
return r instanceof pv ? r : MA(r);
}
var bd = class extends Ge {
constructor(e) {
super(e == null ? {} : e);
this.supportsMasking = true, e != null && (this.maxValue = e.maxValue);
}
call(e, t) {
e = Me(e);
let n = Ir(e);
return this.maxValue != null && (n = gr(n, 0, this.maxValue)), n;
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = { maxValue: this.maxValue }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
bd.className = "ReLU";
ee.registerClass(bd);
var wd = class extends Ge {
constructor(e) {
super(e == null ? {} : e);
this.DEFAULT_ALPHA = 0.3, e == null && (e = {}), this.alpha = e.alpha == null ? this.DEFAULT_ALPHA : e.alpha;
}
call(e, t) {
let n = Me(e);
return $a(n, this.alpha);
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = { alpha: this.alpha }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
wd.className = "LeakyReLU";
ee.registerClass(wd);
var _d = class extends Ge {
constructor(e) {
super(e == null ? {} : e);
if (this.DEFAULT_ALPHA_INITIALIZER = "zeros", e == null && (e = {}), this.supportsMasking = true, this.alphaInitializer = dt(e.alphaInitializer || this.DEFAULT_ALPHA_INITIALIZER), this.alphaRegularizer = _t(e.alphaRegularizer), this.alphaConstraint = Vt(e.alphaConstraint), e.sharedAxes == null)
this.sharedAxes = null;
else if (Array.isArray(e.sharedAxes))
this.sharedAxes = e.sharedAxes;
else if (typeof e.sharedAxes == "number")
this.sharedAxes = [e.sharedAxes];
else
throw new z(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);
}
build(e) {
e = Xe(e);
let t = e.slice(1);
if (this.sharedAxes != null)
for (let o of this.sharedAxes)
t[o - 1] = 1;
this.alpha = this.addWeight("alpha", t, "float32", this.alphaInitializer, this.alphaRegularizer, true, this.alphaConstraint);
let n = {};
if (this.sharedAxes != null)
for (let o = 1; o < e.length; ++o)
n[o] = e[o];
this.inputSpec = [new Tt({ ndim: e.length, axes: n })], this.built = true;
}
call(e, t) {
return e = Me(e), Ma(e, this.alpha.read());
}
getConfig() {
let e = { alphaInitializer: Nt(this.alphaInitializer), alphaRegularizer: ct(this.alphaRegularizer), alphaConstraint: Bt(this.alphaConstraint), sharedAxes: this.sharedAxes }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
_d.className = "PReLU";
ee.registerClass(_d);
var kd = class extends Ge {
constructor(e) {
super(e == null ? {} : e);
if (this.DEFAULT_ALPHA = 1, e == null && (e = {}), e.alpha != null && e.alpha !== this.DEFAULT_ALPHA)
throw new Ne(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);
this.alpha = e.alpha == null ? this.DEFAULT_ALPHA : e.alpha;
}
call(e, t) {
let n = Me(e);
return Rs(n);
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = { alpha: this.alpha }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
kd.className = "ELU";
ee.registerClass(kd);
var vd = class extends Ge {
constructor(e) {
super(e == null ? {} : e);
this.DEFAULT_THETA = 1, e == null && (e = {}), this.theta = e.theta == null ? this.DEFAULT_THETA : e.theta;
}
call(e, t) {
let n = Me(e);
return O(n, Y(zt(n, this.theta), "float32"));
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = { theta: this.theta }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
vd.className = "ThresholdedReLU";
ee.registerClass(vd);
var Cd = class extends Ge {
constructor(e) {
super(e == null ? {} : e);
this.DEFAULT_AXIS = 1, e == null && (e = {}), this.softmax = new yd().apply, this.axis = e.axis == null ? this.DEFAULT_AXIS : e.axis;
}
call(e, t) {
let n = Me(e);
return this.softmax(n, this.axis);
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = { axis: this.axis }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Cd.className = "Softmax";
ee.registerClass(Cd);
function Ll(r, e, t) {
if (typeof r == "number")
return go(r, e);
if (r.length !== e)
throw new z(`The ${t} argument must be an integer or tuple of ${e} integers. Received: ${r.length} elements.`);
for (let n = 0; n < e; ++n) {
let o = r[n];
if (!J2(o))
throw new z(`The ${t} argument must be an integer or tuple of ${e} integers. Received: ${JSON.stringify(r)} including a non-integer number ${o}`);
}
return r;
}
function Nn(r, e, t, n, o = 1) {
if (r == null)
return r;
let s = e + (e - 1) * (o - 1), a;
return t === "same" ? a = r : a = r - s + 1, Math.floor((a + n - 1) / n);
}
function Us(r, e, t, n) {
if (r == null)
return null;
if (n === "valid")
r = r * e + Bs([t - e, 0]);
else if (n === "same")
r = r * e;
else
throw new z(`Unsupport padding mode: ${n}.`);
return r;
}
function Id(r, e) {
return V(() => (Ot(e), e === "channelsFirst" ? Be(r, [0, 2, 3, 1]) : r));
}
function mv(r, e) {
return V(() => (Ot(e), e === "channelsFirst" ? Be(r, [0, 2, 3, 4, 1]) : r));
}
function Y5(r, e, t, n = 1, o = "valid", s, a = 1) {
return V(() => {
if (s == null && (s = an()), Ot(s), r.shape.length !== 3)
throw new z(`The input of a conv1dWithBias operation should be 3, but is ${r.shape.length} instead.`);
if (e.shape.length !== 3)
throw new z(`The kernel for a conv1dWithBias operation should be 3, but is ${e.shape.length} instead`);
if (t != null && t.shape.length !== 1)
throw new z(`The bias for a conv1dWithBias operation should be 1, but is ${e.shape.length} instead`);
if (s === "channelsFirst" && (r = Be(r, [0, 2, 1])), o === "causal")
throw new Ne("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");
let i = vu(r, e, n, o === "same" ? "same" : "valid", "NWC", a);
return t != null && (i = un(i, t)), i;
});
}
function LA(r, e, t, n = [1, 1], o = "valid", s, a, i = null) {
return V(() => {
if (s == null && (s = an()), Ot(s), r.rank !== 3 && r.rank !== 4)
throw new z(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${r.rank}.`);
if (e.rank !== 3 && e.rank !== 4)
throw new z(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${r.rank}.`);
let l = Id(r, s);
if (o === "causal")
throw new Ne("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");
return l = fo.conv2d({ x: l, filter: e, strides: n, pad: o === "same" ? "same" : "valid", dilations: a, dataFormat: "NHWC", bias: t, activation: i }), s === "channelsFirst" && (l = Be(l, [0, 3, 1, 2])), l;
});
}
function Z5(r, e, t, n = [1, 1, 1], o = "valid", s, a) {
return V(() => {
if (s == null && (s = an()), Ot(s), r.rank !== 4 && r.rank !== 5)
throw new z(`conv3dWithBias expects input to be of rank 4 or 5, but received ${r.rank}.`);
if (e.rank !== 4 && e.rank !== 5)
throw new z(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${r.rank}.`);
let i = mv(r, s);
if (o === "causal")
throw new Ne("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");
return i = If(i, e, n, o === "same" ? "same" : "valid", "NDHWC", a), t != null && (i = un(i, t)), s === "channelsFirst" && (i = Be(i, [0, 4, 1, 2, 3])), i;
});
}
var cm = class extends Ge {
constructor(e, t) {
super(t);
if (this.bias = null, this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_BIAS_INITIALIZER = "zeros", cm.verifyArgs(t), this.rank = e, Zt(this.rank, "rank"), this.rank !== 1 && this.rank !== 2 && this.rank !== 3)
throw new Ne(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);
if (this.kernelSize = Ll(t.kernelSize, e, "kernelSize"), this.strides = Ll(t.strides == null ? 1 : t.strides, e, "strides"), this.padding = t.padding == null ? "valid" : t.padding, ln(this.padding), this.dataFormat = t.dataFormat == null ? "channelsLast" : t.dataFormat, Ot(this.dataFormat), this.activation = Ws(t.activation), this.useBias = t.useBias == null ? true : t.useBias, this.biasInitializer = dt(t.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.biasConstraint = Vt(t.biasConstraint), this.biasRegularizer = _t(t.biasRegularizer), this.activityRegularizer = _t(t.activityRegularizer), this.dilationRate = Ll(t.dilationRate == null ? 1 : t.dilationRate, e, "dilationRate"), this.rank === 1 && Array.isArray(this.dilationRate) && this.dilationRate.length !== 1)
throw new z(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);
if (this.rank === 2) {
if (typeof this.dilationRate == "number")
this.dilationRate = [this.dilationRate, this.dilationRate];
else if (this.dilationRate.length !== 2)
throw new z(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`);
} else if (this.rank === 3) {
if (typeof this.dilationRate == "number")
this.dilationRate = [this.dilationRate, this.dilationRate, this.dilationRate];
else if (this.dilationRate.length !== 3)
throw new z(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`);
}
}
static verifyArgs(e) {
if (Kn("kernelSize" in e, "required key 'kernelSize' not in config"), typeof e.kernelSize != "number" && !bx(e.kernelSize, "number", 1, 3))
throw new z(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`);
}
getConfig() {
let e = { kernelSize: this.kernelSize, strides: this.strides, padding: this.padding, dataFormat: this.dataFormat, dilationRate: this.dilationRate, activation: Gs(this.activation), useBias: this.useBias, biasInitializer: Nt(this.biasInitializer), biasRegularizer: ct(this.biasRegularizer), activityRegularizer: ct(this.activityRegularizer), biasConstraint: Bt(this.biasConstraint) }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
var ac = class extends cm {
constructor(e, t) {
super(e, t);
this.kernel = null, ac.verifyArgs(t), this.filters = t.filters, Zt(this.filters, "filters"), this.kernelInitializer = dt(t.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.kernelConstraint = Vt(t.kernelConstraint), this.kernelRegularizer = _t(t.kernelRegularizer);
}
build(e) {
e = Xe(e);
let t = this.dataFormat === "channelsFirst" ? 1 : e.length - 1;
if (e[t] == null)
throw new z(`The channel dimension of the input should be defined. Found ${e[t]}`);
let n = e[t], o = this.kernelSize.concat([n, this.filters]);
this.kernel = this.addWeight("kernel", o, null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.filters], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint)), this.inputSpec = [{ ndim: this.rank + 2, axes: { [t]: n } }], this.built = true;
}
call(e, t) {
return V(() => {
e = Me(e);
let n, o = this.bias == null ? null : this.bias.read(), s = wx(this.activation.getClassName());
if (s != null && this.rank === 2)
n = LA(e, this.kernel.read(), o, this.strides, this.padding, this.dataFormat, this.dilationRate, s);
else {
if (this.rank === 1)
n = Y5(e, this.kernel.read(), o, this.strides[0], this.padding, this.dataFormat, this.dilationRate[0]);
else if (this.rank === 2)
n = LA(e, this.kernel.read(), o, this.strides, this.padding, this.dataFormat, this.dilationRate);
else if (this.rank === 3)
n = Z5(e, this.kernel.read(), o, this.strides, this.padding, this.dataFormat, this.dilationRate);
else
throw new Ne("convolutions greater than 3D are not implemented yet.");
this.activation != null && (n = this.activation.apply(n));
}
return n;
});
}
computeOutputShape(e) {
e = Xe(e);
let t = [], n = this.dataFormat === "channelsLast" ? e.slice(1, e.length - 1) : e.slice(2);
for (let s = 0; s < n.length; ++s) {
let a = Nn(n[s], this.kernelSize[s], this.padding, this.strides[s], typeof this.dilationRate == "number" ? this.dilationRate : this.dilationRate[s]);
t.push(a);
}
let o = [e[0]];
return this.dataFormat === "channelsLast" ? (o = o.concat(t), o.push(this.filters)) : (o.push(this.filters), o = o.concat(t)), o;
}
getConfig() {
let e = { filters: this.filters, kernelInitializer: Nt(this.kernelInitializer), kernelRegularizer: ct(this.kernelRegularizer), kernelConstraint: Bt(this.kernelConstraint) }, t = super.getConfig();
return Object.assign(e, t), e;
}
static verifyArgs(e) {
if (!("filters" in e) || typeof e.filters != "number" || e.filters < 1)
throw new z(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`);
}
};
var zl = class extends ac {
constructor(e) {
super(2, e);
zl.verifyArgs(e);
}
getConfig() {
let e = super.getConfig();
return delete e.rank, e;
}
static verifyArgs(e) {
if (typeof e.kernelSize != "number" && !bx(e.kernelSize, "number", 1, 2))
throw new z(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`);
}
};
zl.className = "Conv2D";
ee.registerClass(zl);
var Bl = class extends ac {
constructor(e) {
super(3, e);
Bl.verifyArgs(e);
}
getConfig() {
let e = super.getConfig();
return delete e.rank, e;
}
static verifyArgs(e) {
if (typeof e.kernelSize != "number" && !(Array.isArray(e.kernelSize) && (e.kernelSize.length === 1 || e.kernelSize.length === 3)))
throw new z(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`);
}
};
Bl.className = "Conv3D";
ee.registerClass(Bl);
var Sd = class extends zl {
constructor(e) {
super(e);
if (this.inputSpec = [new Tt({ ndim: 4 })], this.padding !== "same" && this.padding !== "valid")
throw new z(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`);
}
build(e) {
if (e = Xe(e), e.length !== 4)
throw new z("Input should have rank 4; Received input shape: " + JSON.stringify(e));
let t = this.dataFormat === "channelsFirst" ? 1 : e.length - 1;
if (e[t] == null)
throw new z("The channel dimension of the inputs should be defined. Found `None`.");
let n = e[t], o = this.kernelSize.concat([this.filters, n]);
this.kernel = this.addWeight("kernel", o, "float32", this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.filters], "float32", this.biasInitializer, this.biasRegularizer, true, this.biasConstraint)), this.inputSpec = [new Tt({ ndim: 4, axes: { [t]: n } })], this.built = true;
}
call(e, t) {
return V(() => {
let n = Me(e);
if (n.shape.length !== 4)
throw new z(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);
let o = n.shape, s = o[0], a, i;
this.dataFormat === "channelsFirst" ? (a = 2, i = 3) : (a = 1, i = 2);
let l = o[a], u = o[i], c = this.kernelSize[0], p = this.kernelSize[1], m = this.strides[0], f = this.strides[1], d = Us(l, m, c, this.padding), h = Us(u, f, p, this.padding), g = [s, d, h, this.filters];
this.dataFormat !== "channelsLast" && (n = Be(n, [0, 2, 3, 1]));
let x = Cu(n, this.kernel.read(), g, this.strides, this.padding);
return this.dataFormat !== "channelsLast" && (x = Be(x, [0, 3, 1, 2])), this.bias != null && (x = un(x, this.bias.read(), this.dataFormat)), this.activation != null && (x = this.activation.apply(x)), x;
});
}
computeOutputShape(e) {
e = Xe(e);
let t = e.slice(), n, o, s;
this.dataFormat === "channelsFirst" ? (n = 1, o = 2, s = 3) : (n = 3, o = 1, s = 2);
let a = this.kernelSize[0], i = this.kernelSize[1], l = this.strides[0], u = this.strides[1];
return t[n] = this.filters, t[o] = Us(t[o], l, a, this.padding), t[s] = Us(t[s], u, i, this.padding), t;
}
getConfig() {
let e = super.getConfig();
return delete e.dilationRate, e;
}
};
Sd.className = "Conv2DTranspose";
ee.registerClass(Sd);
var Nd = class extends Bl {
constructor(e) {
super(e);
if (this.inputSpec = [new Tt({ ndim: 5 })], this.padding !== "same" && this.padding !== "valid")
throw new z(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`);
}
build(e) {
if (e = Xe(e), e.length !== 5)
throw new z("Input should have rank 5; Received input shape: " + JSON.stringify(e));
let t = this.dataFormat === "channelsFirst" ? 1 : e.length - 1;
if (e[t] == null)
throw new z("The channel dimension of the inputs should be defined. Found `None`.");
let n = e[t], o = this.kernelSize.concat([this.filters, n]);
this.kernel = this.addWeight("kernel", o, "float32", this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.filters], "float32", this.biasInitializer, this.biasRegularizer, true, this.biasConstraint)), this.inputSpec = [new Tt({ ndim: 5, axes: { [t]: n } })], this.built = true;
}
call(e, t) {
return V(() => {
let n = Me(e);
if (n.shape.length !== 5)
throw new z(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);
let o = n.shape, s = o[0], a, i, l;
this.dataFormat === "channelsFirst" ? (l = 2, a = 3, i = 4) : (l = 1, a = 2, i = 3);
let u = o[l], c = o[a], p = o[i], m = this.kernelSize[0], f = this.kernelSize[1], d = this.kernelSize[2], h = this.strides[0], g = this.strides[1], x = this.strides[2], y = Us(u, h, m, this.padding), w = Us(c, g, f, this.padding), _ = Us(p, x, d, this.padding), C = [s, y, w, _, this.filters];
this.dataFormat !== "channelsLast" && (n = Be(n, [0, 2, 3, 4, 1]));
let A = H_(n, this.kernel.read(), C, this.strides, this.padding);
return this.dataFormat !== "channelsLast" && (A = Be(A, [0, 4, 1, 2, 3])), this.bias !== null && (A = un(A, this.bias.read(), this.dataFormat)), this.activation !== null && (A = this.activation.apply(A)), A;
});
}
computeOutputShape(e) {
e = Xe(e);
let t = e.slice(), n, o, s, a;
this.dataFormat === "channelsFirst" ? (n = 1, o = 2, s = 3, a = 4) : (n = 4, o = 1, s = 2, a = 3);
let i = this.kernelSize[0], l = this.kernelSize[1], u = this.kernelSize[2], c = this.strides[0], p = this.strides[1], m = this.strides[2];
return t[n] = this.filters, t[o] = Us(t[o], c, i, this.padding), t[s] = Us(t[s], p, l, this.padding), t[a] = Us(t[a], m, u, this.padding), t;
}
getConfig() {
let e = super.getConfig();
return delete e.dilationRate, e;
}
};
Nd.className = "Conv3DTranspose";
ee.registerClass(Nd);
var fv = class extends ac {
constructor(e, t) {
super(e, t);
if (this.DEFAULT_DEPTHWISE_INITIALIZER = "glorotUniform", this.DEFAULT_POINTWISE_INITIALIZER = "glorotUniform", this.depthwiseKernel = null, this.pointwiseKernel = null, t.filters == null)
throw new z("The `filters` configuration field is required by SeparableConv, but is unspecified.");
if (t.kernelInitializer != null || t.kernelRegularizer != null || t.kernelConstraint != null)
throw new z("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");
if (t.padding != null && t.padding !== "same" && t.padding !== "valid")
throw new z(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);
this.depthMultiplier = t.depthMultiplier == null ? 1 : t.depthMultiplier, this.depthwiseInitializer = dt(t.depthwiseInitializer || this.DEFAULT_DEPTHWISE_INITIALIZER), this.depthwiseRegularizer = _t(t.depthwiseRegularizer), this.depthwiseConstraint = Vt(t.depthwiseConstraint), this.pointwiseInitializer = dt(t.depthwiseInitializer || this.DEFAULT_POINTWISE_INITIALIZER), this.pointwiseRegularizer = _t(t.pointwiseRegularizer), this.pointwiseConstraint = Vt(t.pointwiseConstraint);
}
build(e) {
if (e = Xe(e), e.length < this.rank + 2)
throw new z(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank + 2}, but received input shape: ${JSON.stringify(e)}`);
let t = this.dataFormat === "channelsFirst" ? 1 : e.length - 1;
if (e[t] == null || e[t] < 0)
throw new z(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);
let n = e[t], o = this.kernelSize.concat([n, this.depthMultiplier]), s = [];
for (let i = 0; i < this.rank; ++i)
s.push(1);
s.push(n * this.depthMultiplier, this.filters);
let a = true;
this.depthwiseKernel = this.addWeight("depthwise_kernel", o, "float32", this.depthwiseInitializer, this.depthwiseRegularizer, a, this.depthwiseConstraint), this.pointwiseKernel = this.addWeight("pointwise_kernel", s, "float32", this.pointwiseInitializer, this.pointwiseRegularizer, a, this.pointwiseConstraint), this.useBias ? this.bias = this.addWeight("bias", [this.filters], "float32", this.biasInitializer, this.biasRegularizer, a, this.biasConstraint) : this.bias = null, this.inputSpec = [new Tt({ ndim: this.rank + 2, axes: { [t]: n } })], this.built = true;
}
call(e, t) {
return V(() => {
e = Me(e);
let n;
if (this.rank === 1)
throw new Ne("1D separable convolution is not implemented yet.");
return this.rank === 2 && (this.dataFormat === "channelsFirst" && (e = Be(e, [0, 2, 3, 1])), n = zf(e, this.depthwiseKernel.read(), this.pointwiseKernel.read(), this.strides, this.padding, this.dilationRate, "NHWC")), this.useBias && (n = un(n, this.bias.read(), this.dataFormat)), this.activation != null && (n = this.activation.apply(n)), this.dataFormat === "channelsFirst" && (n = Be(n, [0, 3, 1, 2])), n;
});
}
getConfig() {
let e = super.getConfig();
return delete e.rank, delete e.kernelInitializer, delete e.kernelRegularizer, delete e.kernelConstraint, e.depthwiseInitializer = Nt(this.depthwiseInitializer), e.pointwiseInitializer = Nt(this.pointwiseInitializer), e.depthwiseRegularizer = ct(this.depthwiseRegularizer), e.pointwiseRegularizer = ct(this.pointwiseRegularizer), e.depthwiseConstraint = Bt(this.depthwiseConstraint), e.pointwiseConstraint = Bt(this.pointwiseConstraint), e;
}
};
fv.className = "SeparableConv";
var Td = class extends fv {
constructor(e) {
super(2, e);
}
};
Td.className = "SeparableConv2D";
ee.registerClass(Td);
var lc = class extends ac {
constructor(e) {
super(1, e);
lc.verifyArgs(e), this.inputSpec = [{ ndim: 3 }];
}
getConfig() {
let e = super.getConfig();
return delete e.rank, delete e.dataFormat, e;
}
static verifyArgs(e) {
if (typeof e.kernelSize != "number" && !bx(e.kernelSize, "number", 1, 1))
throw new z(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`);
}
};
lc.className = "Conv1D";
ee.registerClass(lc);
var Ed = class extends Ge {
constructor(e) {
super(e);
typeof e.cropping == "number" ? this.cropping = [[e.cropping, e.cropping], [e.cropping, e.cropping]] : typeof e.cropping[0] == "number" ? this.cropping = [[e.cropping[0], e.cropping[0]], [e.cropping[1], e.cropping[1]]] : this.cropping = e.cropping, this.dataFormat = e.dataFormat === void 0 ? "channelsLast" : e.dataFormat, this.inputSpec = [{ ndim: 4 }];
}
computeOutputShape(e) {
return this.dataFormat === "channelsFirst" ? [e[0], e[1], e[2] - this.cropping[0][0] - this.cropping[0][1], e[3] - this.cropping[1][0] - this.cropping[1][1]] : [e[0], e[1] - this.cropping[0][0] - this.cropping[0][1], e[2] - this.cropping[1][0] - this.cropping[1][1], e[3]];
}
call(e, t) {
return V(() => {
if (e = Me(e), this.dataFormat === "channelsLast") {
let n = rd(e, this.cropping[0][0], e.shape[1] - this.cropping[0][0] - this.cropping[0][1], 2);
return rd(n, this.cropping[1][0], e.shape[2] - this.cropping[1][1] - this.cropping[1][0], 3);
} else {
let n = rd(e, this.cropping[0][0], e.shape[2] - this.cropping[0][0] - this.cropping[0][1], 3);
return rd(n, this.cropping[1][0], e.shape[3] - this.cropping[1][1] - this.cropping[1][0], 4);
}
});
}
getConfig() {
let e = { cropping: this.cropping, dataFormat: this.dataFormat }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Ed.className = "Cropping2D";
ee.registerClass(Ed);
var Ad = class extends Ge {
constructor(e) {
super(e);
this.DEFAULT_SIZE = [2, 2], this.inputSpec = [{ ndim: 4 }], this.size = e.size == null ? this.DEFAULT_SIZE : e.size, this.dataFormat = e.dataFormat == null ? "channelsLast" : e.dataFormat, Ot(this.dataFormat), this.interpolation = e.interpolation == null ? "nearest" : e.interpolation, X2(this.interpolation);
}
computeOutputShape(e) {
if (this.dataFormat === "channelsFirst") {
let t = e[2] == null ? null : this.size[0] * e[2], n = e[3] == null ? null : this.size[1] * e[3];
return [e[0], e[1], t, n];
} else {
let t = e[1] == null ? null : this.size[0] * e[1], n = e[2] == null ? null : this.size[1] * e[2];
return [e[0], t, n, e[3]];
}
}
call(e, t) {
return V(() => {
let n = Me(e), o = n.shape;
if (this.dataFormat === "channelsFirst") {
n = Be(n, [0, 2, 3, 1]);
let s = this.size[0] * o[2], a = this.size[1] * o[3], i = this.interpolation === "nearest" ? Cn.resizeNearestNeighbor(n, [s, a]) : Cn.resizeBilinear(n, [s, a]);
return Be(i, [0, 3, 1, 2]);
} else {
let s = this.size[0] * o[1], a = this.size[1] * o[2];
return this.interpolation === "nearest" ? Cn.resizeNearestNeighbor(n, [s, a]) : Cn.resizeBilinear(n, [s, a]);
}
});
}
getConfig() {
let e = { size: this.size, dataFormat: this.dataFormat }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Ad.className = "UpSampling2D";
ee.registerClass(Ad);
function J5(r, e, t = [1, 1], n = "valid", o, s) {
return V(() => {
o == null && (o = an()), Ot(o);
let a = Id(r, o);
if (r.rank !== 4)
throw new z(`Input for depthwiseConv2d is required to be 4-D, but is instead ${r.rank}-D`);
if (e.rank !== 4)
throw new z(`depthwiseKernel is required to be 4-D, but is instead ${e.rank}-D`);
return a = $s(a, e, t, n === "same" ? "same" : "valid", "NHWC", s), o === "channelsFirst" && (a = Be(a, [0, 3, 1, 2])), a;
});
}
var Dd = class extends cm {
constructor(e) {
super(2, e);
this.depthwiseKernel = null, this.depthMultiplier = e.depthMultiplier == null ? 1 : e.depthMultiplier, this.depthwiseInitializer = dt(e.depthwiseInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.depthwiseConstraint = Vt(e.depthwiseConstraint), this.depthwiseRegularizer = _t(e.depthwiseRegularizer);
}
build(e) {
if (e = Xe(e), e.length < 4)
throw new z(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);
let t = this.dataFormat === "channelsFirst" ? 1 : 3;
if (e[t] == null || e[t] < 0)
throw new z(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);
let n = e[t], o = [this.kernelSize[0], this.kernelSize[1], n, this.depthMultiplier];
this.depthwiseKernel = this.addWeight("depthwise_kernel", o, null, this.depthwiseInitializer, this.depthwiseRegularizer, true, this.depthwiseConstraint), this.useBias ? this.bias = this.addWeight("bias", [n * this.depthMultiplier], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint) : this.bias = null, this.built = true;
}
call(e, t) {
return V(() => {
e = Me(e);
let n = J5(e, this.depthwiseKernel.read(), this.strides, this.padding, this.dataFormat, null);
return this.useBias && (n = un(n, this.bias.read(), this.dataFormat)), this.activation != null && (n = this.activation.apply(n)), n;
});
}
computeOutputShape(e) {
e = Xe(e);
let t = this.dataFormat === "channelsFirst" ? e[2] : e[1], n = this.dataFormat === "channelsFirst" ? e[3] : e[2], o = this.dataFormat === "channelsFirst" ? e[1] * this.depthMultiplier : e[3] * this.depthMultiplier, s = Nn(t, this.kernelSize[0], this.padding, this.strides[0]), a = Nn(n, this.kernelSize[1], this.padding, this.strides[1]);
return this.dataFormat === "channelsFirst" ? [e[0], o, s, a] : [e[0], s, a, o];
}
getConfig() {
let e = super.getConfig();
return e.depthMultiplier = this.depthMultiplier, e.depthwiseInitializer = Nt(this.depthwiseInitializer), e.depthwiseRegularizer = ct(this.depthwiseRegularizer), e.depthwiseConstraint = Bt(this.depthwiseRegularizer), e;
}
};
Dd.className = "DepthwiseConv2D";
ee.registerClass(Dd);
function dv(r, e, t, n) {
if (Array.isArray(r)) {
if (e != null || t != null)
throw new z("When inputs is an array, neither initialState or constants should be provided");
n != null && (t = r.slice(r.length - n, r.length), r = r.slice(0, r.length - n)), r.length > 1 && (e = r.slice(1, r.length)), r = r[0];
}
function o(s) {
return s == null || Array.isArray(s) ? s : [s];
}
return e = o(e), t = o(t), { inputs: r, initialState: e, constants: t };
}
function hv(r, e, t, n = false, o, s, a = false, i = false) {
return V(() => {
let l = e.shape.length;
if (l < 3)
throw new z(`Input should be at least 3D, but is ${l}D.`);
let u = [1, 0].concat(Xr(2, l));
if (e = Be(e, u), s != null)
throw new Ne("The rnn() functoin of the deeplearn.js backend does not support constants yet.");
a && console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."), o != null && (o = Y(Y(o, "bool"), "float32"), o.rank === l - 1 && (o = mr(o, -1)), o = Be(o, u)), n && (e = er(e, 0), o != null && (o = er(o, 0)));
let c = [], p, m = t, f = e.shape[0], d = yr(e), h;
o != null && (h = yr(o));
for (let x = 0; x < f; ++x) {
let y = d[x], w = V(() => r(y, m));
if (o == null)
p = w[0], m = w[1];
else {
let _ = V(() => {
let C = h[x], A = le(fr(C), C), D = Z(O(w[0], C), O(m[0], A)), R = m.map((P, L) => Z(O(w[1][L], C), O(P, A)));
return { output: D, newStates: R };
});
p = _.output, m = _.newStates;
}
i && c.push(p);
}
let g;
return i && (g = Xt(c, 1)), [p, g, m];
});
}
var Ln = class extends Ge {
constructor(e) {
super(e);
let t;
if (e.cell == null)
throw new z("cell property is missing for the constructor of RNN.");
if (Array.isArray(e.cell) ? t = new fm({ cells: e.cell }) : t = e.cell, t.stateSize == null)
throw new z("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");
this.cell = t, this.returnSequences = e.returnSequences == null ? false : e.returnSequences, this.returnState = e.returnState == null ? false : e.returnState, this.goBackwards = e.goBackwards == null ? false : e.goBackwards, this._stateful = e.stateful == null ? false : e.stateful, this.unroll = e.unroll == null ? false : e.unroll, this.supportsMasking = true, this.inputSpec = [new Tt({ ndim: 3 })], this.stateSpec = null, this.states_ = null, this.numConstants = null, this.keptStates = [];
}
getStates() {
if (this.states_ == null) {
let e = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
return Xr(0, e).map((t) => null);
} else
return this.states_;
}
setStates(e) {
this.states_ = e;
}
computeOutputShape(e) {
Tx(e) && (e = e[0]), e = e;
let t = this.cell.stateSize;
Array.isArray(t) || (t = [t]);
let n = t[0], o;
if (this.returnSequences ? o = [e[0], e[1], n] : o = [e[0], n], this.returnState) {
let s = [];
for (let a of t)
s.push([e[0], a]);
return [o].concat(s);
} else
return o;
}
computeMask(e, t) {
return V(() => {
Array.isArray(t) && (t = t[0]);
let n = this.returnSequences ? t : null;
if (this.returnState) {
let o = this.states.map((s) => null);
return [n].concat(o);
} else
return n;
});
}
get states() {
if (this.states_ == null) {
let e = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1, t = [];
for (let n = 0; n < e; ++n)
t.push(null);
return t;
} else
return this.states_;
}
set states(e) {
this.states_ = e;
}
build(e) {
let t = null;
if (this.numConstants != null)
throw new Ne("Constants support is not implemented in RNN yet.");
Tx(e) && (e = e[0]), e = e;
let n = this.stateful ? e[0] : null, o = e.slice(2);
this.inputSpec[0] = new Tt({ shape: [n, null, ...o] });
let s = [e[0]].concat(e.slice(2));
if (t != null)
throw new Ne("Constants support is not implemented in RNN yet.");
this.cell.build(s);
let a;
if (Array.isArray(this.cell.stateSize) ? a = this.cell.stateSize : a = [this.cell.stateSize], this.stateSpec != null) {
if (!b.arraysEqual(this.stateSpec.map((i) => i.shape[i.shape.length - 1]), a))
throw new z(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`);
} else
this.stateSpec = a.map((i) => new Tt({ shape: [null, i] }));
this.stateful && this.resetStates();
}
resetStates(e, t = false) {
V(() => {
if (!this.stateful)
throw new Mn("Cannot call resetStates() on an RNN Layer that is not stateful.");
let n = this.inputSpec[0].shape[0];
if (n == null)
throw new z("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");
if (this.states_ == null)
Array.isArray(this.cell.stateSize) ? this.states_ = this.cell.stateSize.map((o) => yt([n, o])) : this.states_ = [yt([n, this.cell.stateSize])];
else if (e == null)
De(this.states_), this.keptStates != null && (De(this.keptStates), this.keptStates = []), Array.isArray(this.cell.stateSize) ? this.states_ = this.cell.stateSize.map((o) => yt([n, o])) : this.states_[0] = yt([n, this.cell.stateSize]);
else {
if (Array.isArray(e) || (e = [e]), e.length !== this.states_.length)
throw new z(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);
t === true ? this.keptStates.push(this.states_.slice()) : De(this.states_);
for (let o = 0; o < this.states_.length; ++o) {
let s = e[o], a = Array.isArray(this.cell.stateSize) ? this.cell.stateSize[o] : this.cell.stateSize, i = [n, a];
if (!b.arraysEqual(s.shape, i))
throw new z(`State ${o} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${s.shape}`);
this.states_[o] = s;
}
}
this.states_ = this.states_.map((o) => Ft(o.clone()));
});
}
apply(e, t) {
let n = t == null ? null : t.initialState, o = t == null ? null : t.constants;
t == null && (t = {});
let s = dv(e, n, o, this.numConstants);
e = s.inputs, n = s.initialState, o = s.constants;
let a = [], i = [];
if (n != null) {
t.initialState = n, a = a.concat(n), this.stateSpec = [];
for (let u of n)
this.stateSpec.push(new Tt({ shape: u.shape }));
i = i.concat(this.stateSpec);
}
if (o != null && (t.constants = o, a = a.concat(o), this.numConstants = o.length), a[0] instanceof cn) {
let u = [e].concat(a), c = this.inputSpec.concat(i), p = this.inputSpec;
this.inputSpec = c;
let m = super.apply(u, t);
return this.inputSpec = p, m;
} else
return super.apply(e, t);
}
call(e, t) {
return V(() => {
let n = t == null ? null : t.mask, o = t == null ? null : t.training, s = t == null ? null : t.initialState;
e = Me(e), s == null && (this.stateful ? s = this.states_ : s = this.getInitialState(e));
let a = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;
if (s.length !== a)
throw new z(`RNN Layer has ${a} state(s) but was passed ${s.length} initial state(s).`);
this.unroll && console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");
let i = { training: o }, u = hv((d, h) => {
let g = this.cell.call([d].concat(h), i);
return [g[0], g.slice(1)];
}, e, s, this.goBackwards, n, null, this.unroll, this.returnSequences), c = u[0], p = u[1], m = u[2];
this.stateful && this.resetStates(m, o);
let f = this.returnSequences ? p : c;
return this.returnState ? [f].concat(m) : f;
});
}
getInitialState(e) {
return V(() => {
let t = yt(e.shape);
return t = me(t, [1, 2]), t = ja(t), Array.isArray(this.cell.stateSize) ? this.cell.stateSize.map((n) => n > 1 ? vx(t, [1, n]) : t) : this.cell.stateSize > 1 ? [vx(t, [1, this.cell.stateSize])] : [t];
});
}
get trainableWeights() {
return this.trainable ? this.cell.trainableWeights : [];
}
get nonTrainableWeights() {
return this.trainable ? this.cell.nonTrainableWeights : this.cell.weights;
}
setFastWeightInitDuringBuild(e) {
super.setFastWeightInitDuringBuild(e), this.cell != null && this.cell.setFastWeightInitDuringBuild(e);
}
getConfig() {
let e = super.getConfig(), t = { returnSequences: this.returnSequences, returnState: this.returnState, goBackwards: this.goBackwards, stateful: this.stateful, unroll: this.unroll };
this.numConstants != null && (t.numConstants = this.numConstants);
let n = this.cell.getConfig();
return this.getClassName() === Ln.className && (t.cell = { className: this.cell.getClassName(), config: n }), Object.assign({}, n, e, t);
}
static fromConfig(e, t, n = {}) {
let o = t.cell, s = pn(o, n);
return new e(Object.assign(t, { cell: s }));
}
};
Ln.className = "RNN";
ee.registerClass(Ln);
var Vl = class extends Ge {
};
var pm = class extends Vl {
constructor(e) {
super(e);
this.DEFAULT_ACTIVATION = "tanh", this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal", this.DEFAULT_BIAS_INITIALIZER = "zeros", this.units = e.units, Zt(this.units, "units"), this.activation = Ws(e.activation == null ? this.DEFAULT_ACTIVATION : e.activation), this.useBias = e.useBias == null ? true : e.useBias, this.kernelInitializer = dt(e.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.recurrentInitializer = dt(e.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER), this.biasInitializer = dt(e.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.kernelRegularizer = _t(e.kernelRegularizer), this.recurrentRegularizer = _t(e.recurrentRegularizer), this.biasRegularizer = _t(e.biasRegularizer), this.kernelConstraint = Vt(e.kernelConstraint), this.recurrentConstraint = Vt(e.recurrentConstraint), this.biasConstraint = Vt(e.biasConstraint), this.dropout = Qu([1, Bs([0, e.dropout == null ? 0 : e.dropout])]), this.recurrentDropout = Qu([1, Bs([0, e.recurrentDropout == null ? 0 : e.recurrentDropout])]), this.dropoutFunc = e.dropoutFunc, this.stateSize = this.units, this.dropoutMask = null, this.recurrentDropoutMask = null;
}
build(e) {
e = Xe(e), this.kernel = this.addWeight("kernel", [e[e.length - 1], this.units], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, this.units], null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint), this.useBias ? this.bias = this.addWeight("bias", [this.units], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint) : this.bias = null, this.built = true;
}
call(e, t) {
return V(() => {
if (e = e, e.length !== 2)
throw new z(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);
let n = e[1];
e = e[0];
let o = t.training == null ? false : t.training;
0 < this.dropout && this.dropout < 1 && this.dropoutMask == null && (this.dropoutMask = Ka({ ones: () => fr(e), rate: this.dropout, training: o, dropoutFunc: this.dropoutFunc })), 0 < this.recurrentDropout && this.recurrentDropout < 1 && this.recurrentDropoutMask == null && (this.recurrentDropoutMask = Ka({ ones: () => fr(n), rate: this.recurrentDropout, training: o, dropoutFunc: this.dropoutFunc }));
let s, a = this.dropoutMask, i = this.recurrentDropoutMask;
a != null ? s = _o(O(e, a), this.kernel.read()) : s = _o(e, this.kernel.read()), this.bias != null && (s = un(s, this.bias.read())), i != null && (n = O(n, i));
let l = Z(s, _o(n, this.recurrentKernel.read()));
return this.activation != null && (l = this.activation.apply(l)), [l, l];
});
}
getConfig() {
let e = super.getConfig(), t = { units: this.units, activation: Gs(this.activation), useBias: this.useBias, kernelInitializer: Nt(this.kernelInitializer), recurrentInitializer: Nt(this.recurrentInitializer), biasInitializer: Nt(this.biasInitializer), kernelRegularizer: ct(this.kernelRegularizer), recurrentRegularizer: ct(this.recurrentRegularizer), biasRegularizer: ct(this.biasRegularizer), activityRegularizer: ct(this.activityRegularizer), kernelConstraint: Bt(this.kernelConstraint), recurrentConstraint: Bt(this.recurrentConstraint), biasConstraint: Bt(this.biasConstraint), dropout: this.dropout, recurrentDropout: this.recurrentDropout };
return Object.assign({}, e, t);
}
};
pm.className = "SimpleRNNCell";
ee.registerClass(pm);
var $d = class extends Ln {
constructor(e) {
e.cell = new pm(e);
super(e);
}
call(e, t) {
return V(() => {
this.cell.dropoutMask != null && (De(this.cell.dropoutMask), this.cell.dropoutMask = null), this.cell.recurrentDropoutMask != null && (De(this.cell.recurrentDropoutMask), this.cell.recurrentDropoutMask = null);
let n = t == null ? null : t.mask, o = t == null ? null : t.training, s = t == null ? null : t.initialState;
return super.call(e, { mask: n, training: o, initialState: s });
});
}
static fromConfig(e, t) {
return new e(t);
}
};
$d.className = "SimpleRNN";
ee.registerClass($d);
var mm = class extends Vl {
constructor(e) {
super(e);
if (this.DEFAULT_ACTIVATION = "tanh", this.DEFAULT_RECURRENT_ACTIVATION = "hardSigmoid", this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal", this.DEFAULT_BIAS_INITIALIZER = "zeros", e.resetAfter)
throw new z("GRUCell does not support reset_after parameter set to true.");
this.units = e.units, Zt(this.units, "units"), this.activation = Ws(e.activation === void 0 ? this.DEFAULT_ACTIVATION : e.activation), this.recurrentActivation = Ws(e.recurrentActivation === void 0 ? this.DEFAULT_RECURRENT_ACTIVATION : e.recurrentActivation), this.useBias = e.useBias == null ? true : e.useBias, this.kernelInitializer = dt(e.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.recurrentInitializer = dt(e.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER), this.biasInitializer = dt(e.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.kernelRegularizer = _t(e.kernelRegularizer), this.recurrentRegularizer = _t(e.recurrentRegularizer), this.biasRegularizer = _t(e.biasRegularizer), this.kernelConstraint = Vt(e.kernelConstraint), this.recurrentConstraint = Vt(e.recurrentConstraint), this.biasConstraint = Vt(e.biasConstraint), this.dropout = Qu([1, Bs([0, e.dropout == null ? 0 : e.dropout])]), this.recurrentDropout = Qu([1, Bs([0, e.recurrentDropout == null ? 0 : e.recurrentDropout])]), this.dropoutFunc = e.dropoutFunc, this.implementation = e.implementation, this.stateSize = this.units, this.dropoutMask = null, this.recurrentDropoutMask = null;
}
build(e) {
e = Xe(e);
let t = e[e.length - 1];
this.kernel = this.addWeight("kernel", [t, this.units * 3], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, this.units * 3], null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint), this.useBias ? this.bias = this.addWeight("bias", [this.units * 3], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint) : this.bias = null, this.built = true;
}
call(e, t) {
return V(() => {
if (e = e, e.length !== 2)
throw new z(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);
let n = t.training == null ? false : t.training, o = e[1];
e = e[0], 0 < this.dropout && this.dropout < 1 && this.dropoutMask == null && (this.dropoutMask = Ka({ ones: () => fr(e), rate: this.dropout, training: n, count: 3, dropoutFunc: this.dropoutFunc })), 0 < this.recurrentDropout && this.recurrentDropout < 1 && this.recurrentDropoutMask == null && (this.recurrentDropoutMask = Ka({ ones: () => fr(o), rate: this.recurrentDropout, training: n, count: 3, dropoutFunc: this.dropoutFunc }));
let s = this.dropoutMask, a = this.recurrentDropoutMask, i, l, u;
0 < this.dropout && this.dropout < 1 && (e = O(e, s[0]));
let c = _o(e, this.kernel.read());
this.useBias && (c = un(c, this.bias.read())), 0 < this.recurrentDropout && this.recurrentDropout < 1 && (o = O(o, a[0]));
let p = this.recurrentKernel.read(), [m, f] = sr(p, [2 * this.units, this.units], p.rank - 1), d = _o(o, m), [h, g, x] = sr(c, 3, c.rank - 1), [y, w] = sr(d, 2, d.rank - 1);
i = this.recurrentActivation.apply(Z(h, y)), l = this.recurrentActivation.apply(Z(g, w));
let _ = _o(O(l, o), f);
u = this.activation.apply(Z(x, _));
let C = Z(O(i, o), O(Z(1, He(i)), u));
return [C, C];
});
}
getConfig() {
let e = super.getConfig(), t = { units: this.units, activation: Gs(this.activation), recurrentActivation: Gs(this.recurrentActivation), useBias: this.useBias, kernelInitializer: Nt(this.kernelInitializer), recurrentInitializer: Nt(this.recurrentInitializer), biasInitializer: Nt(this.biasInitializer), kernelRegularizer: ct(this.kernelRegularizer), recurrentRegularizer: ct(this.recurrentRegularizer), biasRegularizer: ct(this.biasRegularizer), activityRegularizer: ct(this.activityRegularizer), kernelConstraint: Bt(this.kernelConstraint), recurrentConstraint: Bt(this.recurrentConstraint), biasConstraint: Bt(this.biasConstraint), dropout: this.dropout, recurrentDropout: this.recurrentDropout, implementation: this.implementation, resetAfter: false };
return Object.assign({}, e, t);
}
};
mm.className = "GRUCell";
ee.registerClass(mm);
var Rd = class extends Ln {
constructor(e) {
e.implementation === 0 && console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."), e.cell = new mm(e);
super(e);
}
call(e, t) {
return V(() => {
this.cell.dropoutMask != null && (De(this.cell.dropoutMask), this.cell.dropoutMask = null), this.cell.recurrentDropoutMask != null && (De(this.cell.recurrentDropoutMask), this.cell.recurrentDropoutMask = null);
let n = t == null ? null : t.mask, o = t == null ? null : t.training, s = t == null ? null : t.initialState;
return super.call(e, { mask: n, training: o, initialState: s });
});
}
static fromConfig(e, t) {
return t.implmentation === 0 && (t.implementation = 1), new e(t);
}
};
Rd.className = "GRU";
ee.registerClass(Rd);
var Gl = class extends Vl {
constructor(e) {
super(e);
this.DEFAULT_ACTIVATION = "tanh", this.DEFAULT_RECURRENT_ACTIVATION = "hardSigmoid", this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_RECURRENT_INITIALIZER = "orthogonal", this.DEFAULT_BIAS_INITIALIZER = "zeros", this.units = e.units, Zt(this.units, "units"), this.activation = Ws(e.activation === void 0 ? this.DEFAULT_ACTIVATION : e.activation), this.recurrentActivation = Ws(e.recurrentActivation === void 0 ? this.DEFAULT_RECURRENT_ACTIVATION : e.recurrentActivation), this.useBias = e.useBias == null ? true : e.useBias, this.kernelInitializer = dt(e.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.recurrentInitializer = dt(e.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER), this.biasInitializer = dt(e.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.unitForgetBias = e.unitForgetBias, this.kernelRegularizer = _t(e.kernelRegularizer), this.recurrentRegularizer = _t(e.recurrentRegularizer), this.biasRegularizer = _t(e.biasRegularizer), this.kernelConstraint = Vt(e.kernelConstraint), this.recurrentConstraint = Vt(e.recurrentConstraint), this.biasConstraint = Vt(e.biasConstraint), this.dropout = Qu([1, Bs([0, e.dropout == null ? 0 : e.dropout])]), this.recurrentDropout = Qu([1, Bs([0, e.recurrentDropout == null ? 0 : e.recurrentDropout])]), this.dropoutFunc = e.dropoutFunc, this.implementation = e.implementation, this.stateSize = [this.units, this.units], this.dropoutMask = null, this.recurrentDropoutMask = null;
}
build(e) {
var t;
e = Xe(e);
let n = e[e.length - 1];
this.kernel = this.addWeight("kernel", [n, this.units * 4], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, this.units * 4], null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint);
let o;
if (this.useBias) {
if (this.unitForgetBias) {
let s = this.biasInitializer, a = this.units;
o = new (t = class extends In {
apply(l, u) {
let c = s.apply([a]), p = new rc().apply([a]), m = s.apply([a * 2]);
return Ok(Ok(c, p), m);
}
}, t.className = "CustomInit", t)();
} else
o = this.biasInitializer;
this.bias = this.addWeight("bias", [this.units * 4], null, o, this.biasRegularizer, true, this.biasConstraint);
} else
this.bias = null;
this.built = true;
}
call(e, t) {
return V(() => {
let n = t.training == null ? false : t.training;
if (e = e, e.length !== 3)
throw new z(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);
let o = e[1], s = e[2];
e = e[0], 0 < this.dropout && this.dropout < 1 && this.dropoutMask == null && (this.dropoutMask = Ka({ ones: () => fr(e), rate: this.dropout, training: n, count: 4, dropoutFunc: this.dropoutFunc })), 0 < this.recurrentDropout && this.recurrentDropout < 1 && this.recurrentDropoutMask == null && (this.recurrentDropoutMask = Ka({ ones: () => fr(o), rate: this.recurrentDropout, training: n, count: 4, dropoutFunc: this.dropoutFunc }));
let a = this.dropoutMask, i = this.recurrentDropoutMask, l, u, c, p;
0 < this.dropout && this.dropout < 1 && (e = O(e, a[0]));
let m = _o(e, this.kernel.read());
0 < this.recurrentDropout && this.recurrentDropout < 1 && (o = O(o, i[0])), m = Z(m, _o(o, this.recurrentKernel.read())), this.useBias && (m = un(m, this.bias.read()));
let [f, d, h, g] = sr(m, 4, m.rank - 1);
l = this.recurrentActivation.apply(f), u = this.recurrentActivation.apply(d), c = Z(O(u, s), O(l, this.activation.apply(h))), p = this.recurrentActivation.apply(g);
let x = O(p, this.activation.apply(c));
return [x, x, c];
});
}
getConfig() {
let e = super.getConfig(), t = { units: this.units, activation: Gs(this.activation), recurrentActivation: Gs(this.recurrentActivation), useBias: this.useBias, kernelInitializer: Nt(this.kernelInitializer), recurrentInitializer: Nt(this.recurrentInitializer), biasInitializer: Nt(this.biasInitializer), unitForgetBias: this.unitForgetBias, kernelRegularizer: ct(this.kernelRegularizer), recurrentRegularizer: ct(this.recurrentRegularizer), biasRegularizer: ct(this.biasRegularizer), activityRegularizer: ct(this.activityRegularizer), kernelConstraint: Bt(this.kernelConstraint), recurrentConstraint: Bt(this.recurrentConstraint), biasConstraint: Bt(this.biasConstraint), dropout: this.dropout, recurrentDropout: this.recurrentDropout, implementation: this.implementation };
return Object.assign({}, e, t);
}
};
Gl.className = "LSTMCell";
ee.registerClass(Gl);
var Fd = class extends Ln {
constructor(e) {
e.implementation === 0 && console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."), e.cell = new Gl(e);
super(e);
}
call(e, t) {
return V(() => {
this.cell.dropoutMask != null && (De(this.cell.dropoutMask), this.cell.dropoutMask = null), this.cell.recurrentDropoutMask != null && (De(this.cell.recurrentDropoutMask), this.cell.recurrentDropoutMask = null);
let n = t == null ? null : t.mask, o = t == null ? null : t.training, s = t == null ? null : t.initialState;
return super.call(e, { mask: n, training: o, initialState: s });
});
}
static fromConfig(e, t) {
return t.implmentation === 0 && (t.implementation = 1), new e(t);
}
};
Fd.className = "LSTM";
ee.registerClass(Fd);
var fm = class extends Vl {
constructor(e) {
super(e);
this.cells = e.cells;
}
get stateSize() {
let e = [];
for (let t of this.cells.slice().reverse())
Array.isArray(t.stateSize) ? e.push(...t.stateSize) : e.push(t.stateSize);
return e;
}
call(e, t) {
return V(() => {
e = e;
let n = e.slice(1), o = [];
for (let i of this.cells.slice().reverse())
Array.isArray(i.stateSize) ? o.push(n.splice(0, i.stateSize.length)) : o.push(n.splice(0, 1));
o.reverse();
let s = [], a;
for (let i = 0; i < this.cells.length; ++i) {
let l = this.cells[i];
n = o[i], i === 0 ? a = [e[0]].concat(n) : a = [a[0]].concat(n), a = l.call(a, t), s.push(a.slice(1));
}
n = [];
for (let i of s.slice().reverse())
n.push(...i);
return [a[0]].concat(n);
});
}
build(e) {
Tx(e) && (e = e[0]), e = e;
let t;
this.cells.forEach((n, o) => {
zs(`RNNCell_${o}`, () => {
n.build(e), Array.isArray(n.stateSize) ? t = n.stateSize[0] : t = n.stateSize, e = [e[0], t];
});
}), this.built = true;
}
getConfig() {
let e = super.getConfig(), t = (s) => ({ className: s.getClassName(), config: s.getConfig() }), o = { cells: this.cells.map(t) };
return Object.assign({}, e, o);
}
static fromConfig(e, t, n = {}) {
let o = [];
for (let s of t.cells)
o.push(pn(s, n));
return new e({ cells: o });
}
get trainableWeights() {
if (!this.trainable)
return [];
let e = [];
for (let t of this.cells)
e.push(...t.trainableWeights);
return e;
}
get nonTrainableWeights() {
let e = [];
for (let t of this.cells)
e.push(...t.nonTrainableWeights);
if (!this.trainable) {
let t = [];
for (let n of this.cells)
t.push(...n.trainableWeights);
return t.concat(e);
}
return e;
}
getWeights() {
let e = [];
for (let t of this.cells)
e.push(...t.weights);
return cd(e);
}
setWeights(e) {
let t = [];
for (let n of this.cells) {
let o = n.weights.length, s = e.splice(o);
for (let a = 0; a < n.weights.length; ++a)
t.push([n.weights[a], s[a]]);
}
om(t);
}
};
fm.className = "StackedRNNCells";
ee.registerClass(fm);
function Ka(r) {
let { ones: e, rate: t, training: n = false, count: o = 1, dropoutFunc: s } = r, a = () => s != null ? s(e(), t) : Ix(e(), t), i = () => $l(a, e, n);
return !o || o <= 1 ? Ft(i().clone()) : Array(o).fill(void 0).map(i).map((u) => Ft(u.clone()));
}
var Q5 = function(r, e) {
var t = {};
for (var n in r)
Object.prototype.hasOwnProperty.call(r, n) && e.indexOf(n) < 0 && (t[n] = r[n]);
if (r != null && typeof Object.getOwnPropertySymbols == "function")
for (var o = 0, n = Object.getOwnPropertySymbols(r); o < n.length; o++)
e.indexOf(n[o]) < 0 && Object.prototype.propertyIsEnumerable.call(r, n[o]) && (t[n[o]] = r[n[o]]);
return t;
};
var gv = class extends Ln {
constructor(e) {
if (e.unroll)
throw new Ne("Unrolling is not possible with convolutional RNNs.");
if (Array.isArray(e.cell))
throw new Ne("It is not possible at the moment to stack convolutional cells.");
super(e);
this.inputSpec = [new Tt({ ndim: 5 })];
}
call(e, t) {
return V(() => {
if (this.cell.dropoutMask != null && (De(this.cell.dropoutMask), this.cell.dropoutMask = null), this.cell.recurrentDropoutMask != null && (De(this.cell.recurrentDropoutMask), this.cell.recurrentDropoutMask = null), t && t.constants)
throw new z("ConvRNN2D cell does not support constants");
let n = t == null ? null : t.mask, o = t == null ? null : t.training, s = t == null ? null : t.initialState;
return super.call(e, { mask: n, training: o, initialState: s });
});
}
computeOutputShape(e) {
let t = this.computeSingleOutputShape(e);
return this.returnSequences || (t = [t[0], ...t.slice(2)]), this.returnState && (t = [t, ...Array(2).fill([e[0], ...t.slice(-3)])]), t;
}
getInitialState(e) {
return V(() => {
let { stateSize: t } = this.cell, n = e.shape, o = this.computeSingleOutputShape(n), s = [o[0], ...o.slice(2)], a = yt(s);
return Array.isArray(t) ? Array(t.length).fill(a) : [a];
});
}
resetStates(e, t = false) {
V(() => {
if (!this.stateful)
throw new Mn("Cannot call resetStates() on an RNN Layer that is not stateful.");
let n = this.inputSpec[0].shape, o = this.computeSingleOutputShape(n), s = [o[0], ...o.slice(2)];
if (n[0] == null)
throw new z("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");
if (this.getStates() == null)
Array.isArray(this.cell.stateSize) ? this.states_ = this.cell.stateSize.map(() => yt(s)) : this.states_ = [yt(s)];
else if (e == null)
De(this.states_), this.keptStates != null && (De(this.keptStates), this.keptStates = []), Array.isArray(this.cell.stateSize) ? this.states_ = this.cell.stateSize.map(() => yt(s)) : this.states_[0] = yt(s);
else {
if (Array.isArray(e) || (e = [e]), e.length !== this.states_.length)
throw new z(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);
t ? this.keptStates.push(this.states_.slice()) : De(this.states_);
for (let i = 0; i < this.states_.length; ++i) {
let l = e[i], u = s;
if (!b.arraysEqual(l.shape, u))
throw new z(`State ${i} is incompatible with layer ${this.name}: expected shape=${u}, received shape=${l.shape}`);
this.states_[i] = l;
}
}
this.states_ = this.states_.map((i) => Ft(i.clone()));
});
}
computeSingleOutputShape(e) {
let { dataFormat: t, filters: n, kernelSize: o, padding: s, strides: a, dilationRate: i } = this.cell, l = t === "channelsFirst", u = e[l ? 3 : 2], c = e[l ? 4 : 3], p = Nn(u, o[0], s, a[0], i[0]), m = Nn(c, o[1], s, a[1], i[1]);
return [...e.slice(0, 2), ...l ? [n, p, m] : [p, m, n]];
}
};
gv.className = "ConvRNN2D";
var dm = class extends Gl {
constructor(e) {
let { filters: t, kernelSize: n, strides: o, padding: s, dataFormat: a, dilationRate: i } = e;
super(Object.assign({}, e, { units: t }));
this.filters = t, Zt(this.filters, "filters"), this.kernelSize = Ll(n, 2, "kernelSize"), this.kernelSize.forEach((l) => Zt(l, "kernelSize")), this.strides = Ll(o || 1, 2, "strides"), this.strides.forEach((l) => Zt(l, "strides")), this.padding = s || "valid", ln(this.padding), this.dataFormat = a || "channelsLast", Ot(this.dataFormat), this.dilationRate = Ll(i || 1, 2, "dilationRate"), this.dilationRate.forEach((l) => Zt(l, "dilationRate"));
}
build(e) {
var t;
e = Xe(e);
let n = this.dataFormat === "channelsFirst" ? 1 : e.length - 1;
if (e[n] == null)
throw new z(`The channel dimension of the input should be defined. Found ${e[n]}`);
let o = e[n], s = 4, a = this.kernelSize.concat([o, this.filters * s]);
this.kernel = this.addWeight("kernel", a, null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint);
let i = this.kernelSize.concat([this.filters, this.filters * s]);
if (this.recurrentKernel = this.addWeight("recurrent_kernel", i, null, this.recurrentInitializer, this.recurrentRegularizer, true, this.recurrentConstraint), this.useBias) {
let l;
if (this.unitForgetBias) {
let u = this.biasInitializer, c = this.filters;
l = new (t = class extends In {
apply(m, f) {
let d = u.apply([c]), h = or([c]), g = u.apply([c * 2]);
return Kp([d, h, g]);
}
}, t.className = "CustomInit", t)();
} else
l = this.biasInitializer;
this.bias = this.addWeight("bias", [this.filters * s], null, l, this.biasRegularizer, true, this.biasConstraint);
}
this.built = true;
}
call(e, t) {
return V(() => {
if (e.length !== 3)
throw new z(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);
let n = t.training || false, o = e[0], s = e[1], a = e[2], i = 4;
0 < this.dropout && this.dropout < 1 && this.dropoutMask == null && (this.dropoutMask = Ka({ ones: () => fr(o), rate: this.dropout, training: n, count: i, dropoutFunc: this.dropoutFunc }));
let l = this.dropoutMask, u = (se, ne, fe) => !ne || !ne[fe] ? se : O(ne[fe], se), c = u(o, l, 0), p = u(o, l, 1), m = u(o, l, 2), f = u(o, l, 3);
0 < this.recurrentDropout && this.recurrentDropout < 1 && this.recurrentDropoutMask == null && (this.recurrentDropoutMask = Ka({ ones: () => fr(s), rate: this.recurrentDropout, training: n, count: i, dropoutFunc: this.dropoutFunc }));
let d = this.recurrentDropoutMask, h = u(s, d, 0), g = u(s, d, 1), x = u(s, d, 2), y = u(s, d, 3), w = 3, [_, C, A, D] = sr(this.kernel.read(), i, w), [R, P, L, G] = this.useBias ? sr(this.bias.read(), i) : [null, null, null, null];
c = this.inputConv(c, _, R, this.padding), p = this.inputConv(p, C, P, this.padding), m = this.inputConv(m, A, L, this.padding), f = this.inputConv(f, D, G, this.padding);
let [W, j, H, q] = sr(this.recurrentKernel.read(), i, w);
h = this.recurrentConv(h, W), g = this.recurrentConv(g, j), x = this.recurrentConv(x, H), y = this.recurrentConv(y, q);
let X = this.recurrentActivation.apply(Z(c, h)), re = this.recurrentActivation.apply(Z(p, g)), J = Z(O(re, a), O(X, this.activation.apply(Z(m, x)))), oe = O(this.recurrentActivation.apply(Z(f, y)), this.activation.apply(J));
return [oe, oe, J];
});
}
getConfig() {
let e = super.getConfig(), { units: t } = e, n = Q5(e, ["units"]), o = { filters: this.filters, kernelSize: this.kernelSize, padding: this.padding, dataFormat: this.dataFormat, dilationRate: this.dilationRate, strides: this.strides };
return Object.assign({}, n, o);
}
inputConv(e, t, n, o) {
let s = nn(e, t, this.strides, o || "valid", this.dataFormat === "channelsFirst" ? "NCHW" : "NHWC", this.dilationRate);
return n ? un(s, n, this.dataFormat) : s;
}
recurrentConv(e, t) {
return nn(e, t, 1, "same", this.dataFormat === "channelsFirst" ? "NCHW" : "NHWC");
}
};
dm.className = "ConvLSTM2DCell";
ee.registerClass(dm);
var Od = class extends gv {
constructor(e) {
let t = new dm(e);
super(Object.assign({}, e, { cell: t }));
}
static fromConfig(e, t) {
return new e(t);
}
};
Od.className = "ConvLSTM2D";
ee.registerClass(Od);
var hm = class extends Ge {
constructor(e) {
super(e);
this.rate = Math.max(Math.min(e.rate, 1), 0), this.noiseShape = e.noiseShape, this.seed = e.seed, this.supportsMasking = true;
}
getNoiseShape(e) {
if (this.noiseShape == null)
return this.noiseShape;
let t = e.shape, n = [];
for (let o = 0; o < this.noiseShape.length; ++o)
n.push(this.noiseShape[o] == null ? t[o] : this.noiseShape[o]);
return n;
}
call(e, t) {
return V(() => {
this.invokeCallHook(e, t);
let n = Me(e);
if (0 < this.rate && this.rate < 1) {
let o = t.training == null ? false : t.training, s = this.getNoiseShape(n);
return $l(() => Ix(n, this.rate, s, this.seed), () => n, o);
}
return e;
});
}
getConfig() {
let e = { rate: this.rate, noiseShape: this.noiseShape, seed: this.seed }, t = super.getConfig();
return Object.assign(e, t), e;
}
dispose() {
return super.dispose();
}
};
hm.className = "Dropout";
ee.registerClass(hm);
var Pd = class extends hm {
constructor(e) {
super(e);
this.inputSpec = [{ ndim: 3 }];
}
getNoiseShape(e) {
let t = e.shape;
return [t[0], 1, t[2]];
}
};
Pd.className = "SpatialDropout1D";
ee.registerClass(Pd);
var Md = class extends Ge {
constructor(e) {
super(e);
if (this.activation = null, this.useBias = true, this.kernel = null, this.bias = null, this.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", this.DEFAULT_BIAS_INITIALIZER = "zeros", e.batchInputShape == null && e.inputShape == null && e.inputDim != null) {
let t = null;
e.batchSize != null && (t = e.batchSize), this.batchInputShape = [t, e.inputDim];
}
this.units = e.units, Zt(this.units, "units"), this.activation = Ws(e.activation), e.useBias != null && (this.useBias = e.useBias), this.kernelInitializer = dt(e.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER), this.biasInitializer = dt(e.biasInitializer || this.DEFAULT_BIAS_INITIALIZER), this.kernelConstraint = Vt(e.kernelConstraint), this.biasConstraint = Vt(e.biasConstraint), this.kernelRegularizer = _t(e.kernelRegularizer), this.biasRegularizer = _t(e.biasRegularizer), this.activityRegularizer = _t(e.activityRegularizer), this.supportsMasking = true, this.inputSpec = [{ minNDim: 2 }];
}
build(e) {
e = Xe(e);
let t = e[e.length - 1];
this.kernel == null && (this.kernel = this.addWeight("kernel", [t, this.units], null, this.kernelInitializer, this.kernelRegularizer, true, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.units], null, this.biasInitializer, this.biasRegularizer, true, this.biasConstraint))), this.inputSpec = [{ minNDim: 2, axes: { [-1]: t } }], this.built = true;
}
computeOutputShape(e) {
e = Xe(e);
let t = e.slice();
return t[t.length - 1] = this.units, t;
}
call(e, t) {
return V(() => {
this.invokeCallHook(e, t);
let n = Me(e), o = wx(this.activation.getClassName()), s;
return o != null ? s = _o(n, this.kernel.read(), o, this.bias ? this.bias.read() : null) : (s = _o(n, this.kernel.read()), this.bias != null && (s = un(s, this.bias.read())), this.activation != null && (s = this.activation.apply(s))), s;
});
}
getConfig() {
let e = { units: this.units, activation: Gs(this.activation), useBias: this.useBias, kernelInitializer: Nt(this.kernelInitializer), biasInitializer: Nt(this.biasInitializer), kernelRegularizer: ct(this.kernelRegularizer), biasRegularizer: ct(this.biasRegularizer), activityRegularizer: ct(this.activityRegularizer), kernelConstraint: Bt(this.kernelConstraint), biasConstraint: Bt(this.biasConstraint) }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Md.className = "Dense";
ee.registerClass(Md);
var Ld = class extends Ge {
constructor(e) {
e = e || {};
super(e);
this.inputSpec = [{ minNDim: 3 }], this.dataFormat = e.dataFormat;
}
computeOutputShape(e) {
e = Xe(e);
for (let t of e.slice(1))
if (t == null)
throw new z(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);
return [e[0], wo(e, 1)];
}
call(e, t) {
return V(() => {
this.invokeCallHook(e, t);
let n = Me(e);
if (this.dataFormat === "channelsFirst" && n.rank > 1) {
let o = [0];
for (let s = 2; s < n.rank; ++s)
o.push(s);
o.push(1), n = Be(n, o);
}
return tA(n);
});
}
getConfig() {
let e = {};
this.dataFormat != null && (e.dataFormat = this.dataFormat);
let t = super.getConfig();
return Object.assign(e, t), e;
}
};
Ld.className = "Flatten";
ee.registerClass(Ld);
var zd = class extends Ge {
constructor(e) {
super(e);
this.supportsMasking = true, this.activation = Ws(e.activation);
}
call(e, t) {
return V(() => {
this.invokeCallHook(e, t);
let n = Me(e);
return this.activation.apply(n);
});
}
getConfig() {
let e = { activation: Gs(this.activation) }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
zd.className = "Activation";
ee.registerClass(zd);
var Bd = class extends Ge {
constructor(e) {
super(e);
this.n = e.n, this.inputSpec = [{ ndim: 2 }];
}
computeOutputShape(e) {
return [e[0], this.n, e[1]];
}
call(e, t) {
return V(() => (e = Me(e), Q2(e, this.n)));
}
getConfig() {
let e = { n: this.n }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Bd.className = "RepeatVector";
ee.registerClass(Bd);
var Vd = class extends Ge {
constructor(e) {
super(e);
this.targetShape = e.targetShape;
for (let t = 0; t < this.targetShape.length; ++t)
this.isUnknown(this.targetShape[t]) && (this.targetShape[t] = null);
}
isUnknown(e) {
return e < 0 || e == null;
}
fixUnknownDimension(e, t) {
let n = "Total size of new array must be unchanged.", o = t.slice(), s = 1, a = null;
for (let l = 0; l < o.length; ++l) {
let u = o[l];
if (this.isUnknown(u))
if (a === null)
a = l;
else
throw new z("Can only specifiy one unknown dimension.");
else
s *= u;
}
let i = wo(e);
if (a !== null) {
if (s === 0 || i % s != 0)
throw new z(n);
o[a] = i / s;
} else if (i !== s)
throw new z(n);
return o;
}
computeOutputShape(e) {
let t = false;
for (let n = 0; n < e.length; ++n)
if (this.isUnknown(e[n])) {
t = true;
break;
}
return t ? e.slice(0, 1).concat(this.targetShape) : e.slice(0, 1).concat(this.fixUnknownDimension(e.slice(1), this.targetShape));
}
call(e, t) {
return V(() => {
this.invokeCallHook(e, t);
let n = Me(e), o = n.shape, s = o.slice(0, 1).concat(this.fixUnknownDimension(o.slice(1), this.targetShape));
return F(n, s);
});
}
getConfig() {
let e = { targetShape: this.targetShape }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Vd.className = "Reshape";
ee.registerClass(Vd);
var Gd = class extends Ge {
constructor(e) {
super(e);
if (e.dims == null)
throw new Error("Required configuration field `dims` is missing during Permute constructor call.");
if (!Array.isArray(e.dims))
throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);
let t = Xr(1, e.dims.length + 1);
if (!b.arraysEqual(e.dims.slice().sort(), t))
throw new Error("Invalid permutation `dims`: " + JSON.stringify(e.dims) + " `dims` must contain consecutive integers starting from 1.");
this.dims = e.dims, this.dimsIncludingBatch = [0].concat(this.dims), this.inputSpec = [new Tt({ ndim: this.dims.length + 1 })];
}
computeOutputShape(e) {
e = Xe(e);
let t = e.slice();
return this.dims.forEach((n, o) => {
t[o + 1] = e[n];
}), t;
}
call(e, t) {
return Be(Me(e), this.dimsIncludingBatch);
}
getConfig() {
let e = { dims: this.dims }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Gd.className = "Permute";
ee.registerClass(Gd);
var Wd = class extends Ge {
constructor(e) {
super(e == null ? {} : e);
this.supportsMasking = true, e != null ? this.maskValue = e.maskValue == null ? 0 : e.maskValue : this.maskValue = 0;
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = super.getConfig(), t = { maskValue: this.maskValue };
return Object.assign(t, e), t;
}
computeMask(e, t) {
let n = Me(e), o = -1;
return El(mo(n, this.maskValue), o);
}
call(e, t) {
return V(() => {
this.invokeCallHook(e, t);
let n = Me(e), o = -1, s = true, a = El(mo(n, this.maskValue), o, s);
return O(n, Y(a, n.dtype));
});
}
};
Wd.className = "Masking";
ee.registerClass(Wd);
var Ud = class extends Ge {
constructor(e) {
super(e);
if (this.embeddings = null, this.DEFAULT_EMBEDDINGS_INITIALIZER = "randomUniform", e.batchInputShape == null && e.inputShape == null) {
let t = null;
e.batchSize != null && (t = e.batchSize), e.inputLength == null ? this.batchInputShape = [t, null] : this.batchInputShape = [t].concat(wt(e.inputLength));
}
this.inputDim = e.inputDim, Zt(this.inputDim, "inputDim"), this.outputDim = e.outputDim, Zt(this.outputDim, "outputDim"), this.embeddingsInitializer = dt(e.embeddingsInitializer || this.DEFAULT_EMBEDDINGS_INITIALIZER), this.embeddingsRegularizer = _t(e.embeddingsRegularizer), this.activityRegularizer = _t(e.activityRegularizer), this.embeddingsConstraint = Vt(e.embeddingsConstraint), this.maskZero = e.maskZero, this.supportsMasking = e.maskZero, this.inputLength = e.inputLength;
}
build(e) {
this.embeddings = this.addWeight("embeddings", [this.inputDim, this.outputDim], this.dtype, this.embeddingsInitializer, this.embeddingsRegularizer, true, this.embeddingsConstraint), this.built = true;
}
warnOnIncompatibleInputShape(e) {
}
computeMask(e, t) {
return V(() => this.maskZero ? (e = Me(e), mo(e, Se(e))) : null);
}
computeOutputShape(e) {
if (e = Xe(e), this.inputLength == null)
return [...e, this.outputDim];
let t = wt(this.inputLength);
if (t.length !== e.length - 1)
throw new z(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);
{
let n = 0;
for (let o = 0; o < t.length; ++o) {
let s = t[o], a = e[o + 1];
if (s != null && a != null && s !== a)
throw new z(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);
s == null && (t[n] = a), n++;
}
}
return [e[0], ...t, this.outputDim];
}
call(e, t) {
return V(() => {
this.invokeCallHook(e, t);
let n = Me(e);
n.dtype !== "int32" && (n = ec(n, "int32"));
let o = Cx(this.embeddings.read(), F(n, [n.size]));
return F(o, Xe(this.computeOutputShape(n.shape)));
});
}
getConfig() {
let e = { inputDim: this.inputDim, outputDim: this.outputDim, embeddingsInitializer: Nt(this.embeddingsInitializer), embeddingsRegularizer: ct(this.embeddingsRegularizer), activityRegularizer: ct(this.activityRegularizer), embeddingsConstraint: Bt(this.embeddingsConstraint), maskZero: this.maskZero, inputLength: this.inputLength }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Ud.className = "Embedding";
ee.registerClass(Ud);
var Wl = class extends Ge {
constructor(e) {
super(e || {});
this.supportsMasking = true;
}
mergeFunction(e) {
throw new Ne();
}
computeElementwiseOpOutputShape(e, t) {
if (e == null || t == null)
return null;
if (e.length < t.length)
return this.computeElementwiseOpOutputShape(t, e);
if (t.length === 0)
return e;
let n = e.slice(0, e.length - t.length);
for (let o = 0; o < t.length; ++o) {
let s = e[e.length - t.length + o], a = t[o];
if (s == null || a == null || s < 0 || a < 0)
n.push(null);
else if (s === 1)
n.push(a);
else if (a === 1)
n.push(s);
else {
if (s !== a)
throw new z("Operands could not be broadcast together with shapes " + JSON.stringify(e) + " " + JSON.stringify(t));
n.push(s);
}
}
return n;
}
build(e) {
if (Array.isArray(e) && !Array.isArray(e[0]) && (e = [Xe(e)]), e = e, e.length < 2)
throw new z(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);
let t = [];
for (let s of e)
s != null && s[0] !== null && t.push(s[0]);
if (t = bo(t), t.length > 1)
throw new z(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);
let n = e[0] == null ? null : e[0].slice(1);
for (let s = 1; s < e.length; ++s) {
let a = e[s] == null ? null : e[s].slice(1);
n = this.computeElementwiseOpOutputShape(n, a);
}
let o = e.map((s) => s.length);
e.indexOf(null) === -1 && bo(o).length === 1 ? this.reshapeRequired = false : this.reshapeRequired = true;
}
call(e, t) {
return V(() => {
if (e = e, this.reshapeRequired) {
let n = [], o = e.map((s) => s.rank);
if (o.indexOf(null) === -1) {
let s = Bs(o);
for (let a of e) {
let i = a.rank;
for (let l = 0; l < s - i; ++l)
a = ja(a, 1);
n.push(a);
}
return this.mergeFunction(n);
} else {
let s = false;
for (let l of e) {
let u = l.rank;
if (u == null) {
let c = l.shape, p = c[0], m = c.slice(1).concat([p]), f = F(l, [p].concat(wo(c.slice(1))));
f = Be(f, [1, 0]), f = F(f, m), n.push(f), s = true;
} else if (u > 1) {
let c = Xr(1, u).concat([0]);
n.push(Be(l, c)), s = true;
} else
n.push(l);
}
let a = this.mergeFunction(n), i = a.rank;
if (s) {
if (i == null) {
let l = a.shape, u = l.length, c = l[u - 1], p = [c].concat(l.slice(0, l.length - 1));
a = F(Be(F(a, [-1, c]), [1, 0]), p);
} else if (i > 1) {
let l = [i - 1].concat(Xr(0, i - 1));
a = Be(a, l);
}
}
return a;
}
} else
return this.mergeFunction(e);
});
}
computeOutputShape(e) {
e = e;
let t;
e[0] == null ? t = null : t = e[0].slice(1);
for (let o = 1; o < e.length; ++o) {
let s = e[o] == null ? null : e[o].slice(1);
t = this.computeElementwiseOpOutputShape(t, s);
}
let n = [];
for (let o of e)
o != null && o[0] !== null && n.push(o[0]);
return n = bo(n), n.length === 1 ? t = n.concat(t) : t = [null].concat(t), t;
}
computeMask(e, t) {
return V(() => {
if (t == null)
return null;
if (!Array.isArray(t))
throw new z("`mask` should be an Array");
if (!Array.isArray(e))
throw new z("`inputs` should be an Array");
if (t.length !== e.length)
throw new z(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);
if (t.every((o) => o == null))
return null;
t = t.map((o) => o == null ? o : mr(o, 0));
let n = t[0];
for (let o = 1; o < t.length - 1; ++o)
n = Cr(n, t[o]);
return n;
});
}
};
var jd = class extends Wl {
constructor(e) {
super(e);
}
mergeFunction(e) {
return V(() => {
let t = e[0].clone();
for (let n = 1; n < e.length; ++n)
t = Z(t, e[n]);
return t;
});
}
};
jd.className = "Add";
ee.registerClass(jd);
var Hd = class extends Wl {
constructor(e) {
super(e);
}
mergeFunction(e) {
return V(() => {
let t = e[0].clone();
for (let n = 1; n < e.length; ++n)
t = O(t, e[n]);
return t;
});
}
};
Hd.className = "Multiply";
ee.registerClass(Hd);
var qd = class extends Wl {
constructor(e) {
super(e);
}
mergeFunction(e) {
return V(() => {
let t = e[0].clone();
for (let n = 1; n < e.length; ++n)
t = Z(t, e[n]);
return O(1 / e.length, t);
});
}
};
qd.className = "Average";
ee.registerClass(qd);
var Kd = class extends Wl {
constructor(e) {
super(e);
}
mergeFunction(e) {
return V(() => {
let t = e[0];
for (let n = 1; n < e.length; ++n)
t = sn(t, e[n]);
return t;
});
}
};
Kd.className = "Maximum";
ee.registerClass(Kd);
var Xd = class extends Wl {
constructor(e) {
super(e);
}
mergeFunction(e) {
return V(() => {
let t = e[0];
for (let n = 1; n < e.length; ++n)
t = Ps(t, e[n]);
return t;
});
}
};
Xd.className = "Minimum";
ee.registerClass(Xd);
var Yd = class extends Wl {
constructor(e) {
super(e);
this.DEFAULT_AXIS = -1, e == null && (e = {}), this.axis = e.axis == null ? this.DEFAULT_AXIS : e.axis, this.supportsMasking = true, this.reshapeRequired = false;
}
build(e) {
if (!(Array.isArray(e) && Array.isArray(e[0])) || e.length === 1)
throw new z("A `Concatenate` layer should be called on a list of at least 2 inputs");
e = e;
let t = true;
for (let o of e)
if (o != null) {
t = false;
break;
}
if (t)
return;
let n = [];
for (let o = 0; o < e.length; ++o) {
let s = e[o].slice();
s.splice(this.axis, 1);
let a = false;
for (let i of n)
if (b.arraysEqual(i, s)) {
a = true;
break;
}
a || n.push(s);
}
if (n.length > 1)
throw new z("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: " + JSON.stringify(e));
}
mergeFunction(e) {
return V(() => Kp(e, this.axis));
}
computeOutputShape(e) {
if (!(Array.isArray(e) && Array.isArray(e[0])))
throw new z("A `Concatenate` layer should be called on a list of inputs.");
let t = e, n = t[0].slice(), o = this.axis < 0 ? n.length + this.axis : this.axis;
for (let s of t.slice(1)) {
if (n[o] == null || s[o] == null) {
n[o] = null;
break;
}
n[o] += s[o];
}
return n;
}
computeMask(e, t) {
if (t == null)
return null;
if (!Array.isArray(t))
throw new z("`mask` should be an array for Concatenate");
if (!Array.isArray(e))
throw new z("`inputs` should be an array for Concatenate");
if (t.length !== e.length)
throw new z(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);
return V(() => {
let n = true;
if (t.forEach((a) => {
if (a != null) {
n = false;
return;
}
}), n)
return null;
let o = [];
for (let a = 0; a < e.length; ++a)
t[a] == null ? o.push(Y(fr(e[a]), "bool")) : t[a].rank < e[a].rank ? o.push(mr(t[a], -1)) : o.push(t[a]);
let s = tt(o, this.axis);
return wu(s, -1, false);
});
}
getConfig() {
let e = { axis: this.axis }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Yd.className = "Concatenate";
ee.registerClass(Yd);
function Zd(r, e) {
for (; r < 0; )
r += e;
return r;
}
function e8(r, e, t) {
if (r.shape.length > 3 || e.shape.length > 3)
throw new Ne("batchDot is not implemented for tensors of 4D or higher rank yet");
if (b.assert(r.shape.length >= 2, () => `batchDot requires the rank of x to be >= 2, but got ${r.shape.length}`), b.assert(r.shape.length >= 2, () => `batchDot requires the rank of y to be >= 2, but got ${e.shape.length}`), typeof t == "number" && (t = [t, t]), r.dtype === "complex64" || e.dtype === "complex64")
throw new Ne("batchDot is not implemented for complex64-type Tensors yet.");
let n = r.shape.length, o = e.shape.length;
t == null && (t = [n - 1, o - 2]);
let s = t;
return V(() => {
let a;
if (n > o) {
a = n - o;
let l = [];
for (let u = 0; u < a; ++u)
l.push(1);
e = F(e, e.shape.concat(l));
} else if (o > n) {
a = o - n;
let l = [];
for (let u = 0; u < a; ++u)
l.push(1);
r = F(r, r.shape.concat(l));
} else
a = 0;
let i;
if (r.shape.length === 2 && e.shape.length === 2)
s[0] === s[1] ? i = me(O(r, e), s[0]) : i = me(O(Be(r, [1, 0]), e), s[1]);
else {
let l = s[0] !== r.shape.length - 1, u = s[1] === e.shape.length - 1;
i = ze(r, e, l, u);
}
if (a > 0) {
let l;
n > o ? l = n + o - 3 : l = n - 1;
let u = [];
for (let c = l; c < l + a; ++c)
u.push(c);
i = Br(i, u);
}
return i.shape.length === 1 && (i = mr(i, 1)), i;
});
}
var Jd = class extends Wl {
constructor(e) {
super(e);
this.axes = e.axes, this.normalize = e.normalize == null ? false : e.normalize, this.supportsMasking = true, this.reshapeRequired = false;
}
build(e) {
b.assert(Array.isArray(e) && e.length === 2 && Array.isArray(e[0]) && Array.isArray(e[1]), () => "A `Dot` layer should be called on a list of exactly 2 inputs.");
let t = e[0], n = e[1];
if (t.length > 3 || n.length > 3)
throw new Ne("Dot layer does not support tensors of 4D or higher rank yet.");
let o = this.interpretAxes(t, n);
if (t[o[0]] !== n[o[1]])
throw new z(`Dimension incompatibility: ${t[o[0]]} !== ${n[o[1]]}`);
}
mergeFunction(e) {
if (e.length !== 2)
throw new z(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);
let t = e[0], n = e[1], o;
return Array.isArray(this.axes) ? o = this.axes.map((s, a) => Zd(s, e[a].shape.length)) : o = [Zd(this.axes, t.shape.length), Zd(this.axes, n.shape.length)], this.normalize && (t = pd(t, o[0]), n = pd(n, o[1])), e8(t, n, o);
}
interpretAxes(e, t) {
let n;
return Array.isArray(this.axes) ? n = this.axes : n = [Zd(this.axes, e.length), Zd(this.axes, t.length)], n;
}
computeOutputShape(e) {
b.assert(Array.isArray(e) && e.length === 2 && Array.isArray(e[0]) && Array.isArray(e[1]), () => "A `Dot` layer should be called on a list of exactly 2 inputs.");
let t = e[0].slice(), n = e[1].slice();
if (t.length > 3 || n.length > 3)
throw new Ne("Dot layer does not support tensors of 4D or higher rank yet.");
let o = this.interpretAxes(t, n);
t.splice(o[0], 1), n.splice(o[1], 1), n.splice(0, 1);
let s = t.concat(n);
return s.length === 1 && s.push(1), s;
}
computeMask(e, t) {
return null;
}
getConfig() {
let e = { axes: this.axes, normalize: this.normalize }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
Jd.className = "Dot";
ee.registerClass(Jd);
var Qd = class extends Ge {
constructor(e) {
super(e);
this.supportsMasking = true, this.stddev = e.stddev;
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = super.getConfig(), t = { stddev: this.stddev };
return Object.assign(t, e), t;
}
call(e, t) {
return V(() => {
this.invokeCallHook(e, t);
let n = Me(e);
return $l(() => Z(Xp(n.shape, 0, this.stddev), n), () => n, t.training || false);
});
}
};
Qd.className = "GaussianNoise";
ee.registerClass(Qd);
var eh = class extends Ge {
constructor(e) {
super(e);
this.supportsMasking = true, this.rate = e.rate;
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = super.getConfig(), t = { rate: this.rate };
return Object.assign(t, e), t;
}
call(e, t) {
return V(() => {
this.invokeCallHook(e, t);
let n = Me(e);
return this.rate > 0 && this.rate < 1 ? $l(() => {
let s = Math.sqrt(this.rate / (1 - this.rate));
return O(n, Xp(n.shape, 1, s));
}, () => n, t.training || false) : n;
});
}
};
eh.className = "GaussianDropout";
ee.registerClass(eh);
var th = class extends Ge {
constructor(e) {
super(e);
this.supportsMasking = true, this.rate = e.rate, this.noiseShape = e.noiseShape;
}
_getNoiseShape(e) {
return this.noiseShape || Me(e).shape;
}
computeOutputShape(e) {
return e;
}
getConfig() {
let e = super.getConfig(), t = { rate: this.rate };
return Object.assign(t, e), t;
}
call(e, t) {
return V(() => {
if (this.rate < 1 && this.rate > 0) {
let n = this._getNoiseShape(e);
return $l(() => {
let s = Me(e), a = 1.6732632423543772, i = 1.0507009873554805, l = -a * i, u = kn(Ms(n), this.rate);
u = ec(u, "float32");
let c = ((1 - this.rate) * (1 + this.rate * l ** 2)) ** -0.5, p = -c * l * this.rate, m = Z(O(s, u), O(Z(u, -1), l));
return Z(O(m, c), p);
}, () => Me(e), t.training || false);
}
return e;
});
}
};
th.className = "AlphaDropout";
ee.registerClass(th);
function rh(r, e, t, n, o, s = 1e-3) {
let a;
if (r.rank === 2)
a = L_(r, e, t, n, o, s);
else if (r.rank === 3)
a = z_(r, e, t, n, o, s);
else if (r.rank === 4)
a = B_(r, e, t, n, o, s);
else
throw new Ne(`batchNormalization is not implemented for array of rank ${r.rank} yet`);
return a;
}
function t8(r, e, t, n, o = 1e-3) {
return V(() => {
let s = zp(r, n), a = s.mean, i = s.variance;
return [rh(r, a, i, t, e, o), a, i];
});
}
function r8(r, e, t, n, o = 1e-3) {
return V(() => {
let s = zp(r, n), a = s.mean, i = s.variance, l = [];
for (let d of Xr(0, r.rank))
n.indexOf(d) !== -1 ? l.push(1) : l.push(r.shape[d]);
let u = F(a, l), c = F(i, l), p = e == null ? null : F(e, l), m = t == null ? null : F(t, l);
return [rh(r, u, c, m, p, o), a, i];
});
}
function n8(r, e, t, n, o = 1e-3) {
return b.arraysEqual(n.slice().sort(), Xr(0, r.rank - 1)) ? t8(r, e, t, n, o) : r8(r, e, t, n, o);
}
var nh = class extends Ge {
constructor(e) {
e == null && (e = {});
super(e);
this.supportsMasking = true, this.axis = e.axis == null ? -1 : e.axis, this.momentum = e.momentum == null ? 0.99 : e.momentum, this.epsilon = e.epsilon == null ? 1e-3 : e.epsilon, this.center = e.center == null ? true : e.center, this.scale = e.scale == null ? true : e.scale, this.betaInitializer = dt(e.betaInitializer || "zeros"), this.gammaInitializer = dt(e.gammaInitializer || "ones"), this.movingMeanInitializer = dt(e.movingMeanInitializer || "zeros"), this.movingVarianceInitializer = dt(e.movingVarianceInitializer || "ones"), this.betaConstraint = Vt(e.betaConstraint), this.gammaConstraint = Vt(e.gammaConstraint), this.betaRegularizer = _t(e.betaRegularizer), this.gammaRegularizer = _t(e.gammaRegularizer);
}
build(e) {
e = Xe(e);
let t = this.axis >= 0 ? this.axis : this.axis + e.length, n = e[t];
if (n == null)
throw new z(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);
this.inputSpec = [new Tt({ ndim: e.length, axes: { [t]: n } })];
let o = [n];
this.scale && (this.gamma = this.addWeight("gamma", o, null, this.gammaInitializer, this.gammaRegularizer, true, this.gammaConstraint)), this.center && (this.beta = this.addWeight("beta", o, null, this.betaInitializer, this.betaRegularizer, true, this.betaConstraint)), this.movingMean = this.addWeight("moving_mean", o, null, this.movingMeanInitializer, null, false), this.movingVariance = this.addWeight("moving_variance", o, null, this.movingVarianceInitializer, null, false), this.built = true;
}
call(e, t) {
return V(() => {
let n = t.training == null ? false : t.training, o = Me(e), s = o.shape, a = s.length, i = Xr(0, a), l = this.axis >= 0 ? this.axis : this.axis + a;
i.splice(l, 1);
let u = go(1, a);
u[l] = s[l];
let c = i.slice();
c.sort();
let p = !b.arraysEqual(c, Xr(0, a).slice(0, a - 1)), m = () => {
if (p) {
let y = F(this.movingMean.read(), u), w = F(this.movingVariance.read(), u), _ = this.center ? F(this.beta.read(), u) : null, C = this.scale ? F(this.gamma.read(), u) : null;
return rh(o, y, w, _, C, this.epsilon);
} else
return rh(o, this.movingMean.read(), this.movingVariance.read(), this.beta == null ? null : this.beta.read(), this.gamma == null ? null : this.gamma.read(), this.epsilon);
};
if (!n)
return m();
let [f, d, h] = n8(o, this.gamma.read(), this.beta.read(), i, this.epsilon), g = (y, w, _) => {
V(() => {
let C = 1 - _, A = y.read(), D = O(le(A, w), C);
y.write(le(A, D));
});
};
return (() => {
g(this.movingMean, d, this.momentum), g(this.movingVariance, h, this.momentum);
})(), f;
});
}
getConfig() {
let e = { axis: this.axis, momentum: this.momentum, epsilon: this.epsilon, center: this.center, scale: this.scale, betaInitializer: Nt(this.betaInitializer), gammaInitializer: Nt(this.gammaInitializer), movingMeanInitializer: Nt(this.movingMeanInitializer), movingVarianceInitializer: Nt(this.movingVarianceInitializer), betaRegularizer: ct(this.betaRegularizer), gammaRegularizer: ct(this.gammaRegularizer), betaConstraint: Bt(this.betaConstraint), gammaConstraint: Bt(this.gammaConstraint) }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
nh.className = "BatchNormalization";
ee.registerClass(nh);
var oh = class extends Ge {
constructor(e) {
e == null && (e = {});
super(e);
if (this.axis = e.axis == null ? -1 : e.axis, typeof this.axis == "number") {
if (!Number.isInteger(this.axis))
throw new Error(`Expected axis to be an integer, but received ${this.axis}`);
} else if (Array.isArray(this.axis)) {
for (let t of this.axis)
if (!Number.isInteger(t))
throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`);
} else
throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);
this.epsilon = e.epsilon == null ? 1e-3 : e.epsilon, this.center = e.center == null ? true : e.center, this.scale = e.scale == null ? true : e.scale, this.betaInitializer = dt(e.betaInitializer || "zeros"), this.gammaInitializer = dt(e.gammaInitializer || "ones"), this.betaRegularizer = _t(e.betaRegularizer), this.gammaRegularizer = _t(e.gammaRegularizer), this.supportsMasking = true;
}
build(e) {
e = Xe(e);
let t = e.length;
typeof this.axis == "number" && (this.axis = [this.axis]);
for (let s = 0; s < this.axis.length; ++s)
this.axis[s] < 0 && (this.axis[s] += t);
for (let s of this.axis)
if (s < 0 || s >= t)
throw new Error(`Invalid axis: ${s}`);
if (this.axis.length !== bo(this.axis).length)
throw new Error(`Found duplicate axes in: ${this.axis}`);
let n = this.axis.map((s) => e[s]), o = true;
this.scale ? this.gamma = this.addWeight("gamma", n, "float32", this.gammaInitializer, this.gammaRegularizer, o) : this.gamma = null, this.center ? this.beta = this.addWeight("beta", n, "float32", this.betaInitializer, this.betaRegularizer, o) : this.beta = null, this.built = true;
}
call(e, t) {
let n = Me(e), o = n.shape, s = o.length;
return V(() => {
let a = true, { mean: i, variance: l } = zp(n, this.axis, a), u = go(1, s);
for (let h of this.axis)
u[h] = o[h];
let c = (h) => h != null && h.shape.length !== s ? F(h, u) : h, p = c(this.gamma.read()), m = c(this.beta.read()), f = [], d = [];
for (let h = 0; h < s; ++h)
this.axis.indexOf(h) !== -1 ? (f.push(o[h]), d.push(1)) : (f.push(1), d.push(o[h]));
return i = vr(i, f), l = vr(l, f), p = vr(p, d), m = vr(m, d), rh(n, i, l, m, p, this.epsilon);
});
}
getConfig() {
let e = { axis: this.axis, epsilon: this.epsilon, center: this.center, scale: this.scale, betaInitializer: Nt(this.betaInitializer), gammaInitializer: Nt(this.gammaInitializer), betaRegularizer: ct(this.betaRegularizer), gammaRegularizer: ct(this.gammaRegularizer) }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
oh.className = "LayerNormalization";
ee.registerClass(oh);
function o8(r, e, t) {
return V(() => {
if (r.rank !== 4)
throw new z(`temporalPadding expects input tensor to be 4-D, but received a ${r.rank}-D tensor.`);
if (e == null && (e = [[1, 1], [1, 1]]), e.length !== 2 || e[0].length !== 2 || e[1].length !== 2)
throw new z("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");
if (t == null && (t = an()), t !== "channelsLast" && t !== "channelsFirst")
throw new z(`Unknown data format: ${t}. Supported data formats are 'channelsLast' and 'channelsFirst.`);
let n;
return t === "channelsFirst" ? n = [[0, 0], [0, 0], e[0], e[1]] : n = [[0, 0], e[0], e[1], [0, 0]], jr(r, n);
});
}
var sh = class extends Ge {
constructor(e) {
e == null && (e = {});
super(e);
if (this.dataFormat = e.dataFormat == null ? an() : e.dataFormat, e.padding == null)
this.padding = [[1, 1], [1, 1]];
else if (typeof e.padding == "number")
this.padding = [[e.padding, e.padding], [e.padding, e.padding]];
else {
if (e.padding = e.padding, e.padding.length !== 2)
throw new z(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);
let t, n;
if (typeof e.padding[0] == "number")
t = [e.padding[0], e.padding[0]], n = [e.padding[1], e.padding[1]];
else {
if (e.padding = e.padding, e.padding[0].length !== 2)
throw new z(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);
if (t = e.padding[0], e.padding[1].length !== 2)
throw new z(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);
n = e.padding[1];
}
this.padding = [t, n];
}
this.inputSpec = [new Tt({ ndim: 4 })];
}
computeOutputShape(e) {
e = Xe(e);
let t, n;
return this.dataFormat === "channelsFirst" ? (e[2] != null && e[2] >= 0 ? t = e[2] + this.padding[0][0] + this.padding[0][1] : t = null, e[3] != null && e[3] >= 0 ? n = e[3] + this.padding[1][0] + this.padding[1][1] : n = null, [e[0], e[1], t, n]) : (e[1] != null && e[1] >= 0 ? t = e[1] + this.padding[0][0] + this.padding[0][1] : t = null, e[2] != null && e[2] >= 0 ? n = e[2] + this.padding[1][0] + this.padding[1][1] : n = null, [e[0], t, n, e[3]]);
}
call(e, t) {
return V(() => o8(Me(e), this.padding, this.dataFormat));
}
getConfig() {
let e = { padding: this.padding, dataFormat: this.dataFormat }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
sh.className = "ZeroPadding2D";
ee.registerClass(sh);
function jx(r, e, t, n, o, s) {
return V(() => {
Ot(o), Rk(s), ln(n), t == null && (t = [1, 1]), n == null && (n = "valid"), o == null && (o = an()), s == null && (s = "max"), r = Id(r, o);
let a, i = n === "same" ? "same" : "valid";
return s === "max" ? a = Oa(r, e, t, i) : a = Ta(r, e, t, i), o === "channelsFirst" && (a = Be(a, [0, 3, 1, 2])), a;
});
}
function zA(r, e, t, n, o, s) {
return V(() => {
Ot(o), Rk(s), ln(n), t == null && (t = [1, 1, 1]), n == null && (n = "valid"), o == null && (o = an()), s == null && (s = "max"), r = mv(r, o);
let a, i = n === "same" ? "same" : "valid";
return s === "max" ? a = Of(r, e, t, i) : a = kf(r, e, t, i), o === "channelsFirst" && (a = Be(a, [0, 4, 1, 2, 3])), a;
});
}
var xv = class extends Ge {
constructor(e) {
e.poolSize == null && (e.poolSize = 2);
super(e);
if (typeof e.poolSize == "number")
this.poolSize = [e.poolSize];
else if (Array.isArray(e.poolSize) && e.poolSize.length === 1 && typeof e.poolSize[0] == "number")
this.poolSize = e.poolSize;
else
throw new z(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);
if (Zt(this.poolSize, "poolSize"), e.strides == null)
this.strides = this.poolSize;
else if (typeof e.strides == "number")
this.strides = [e.strides];
else if (Array.isArray(e.strides) && e.strides.length === 1 && typeof e.strides[0] == "number")
this.strides = e.strides;
else
throw new z(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);
Zt(this.strides, "strides"), this.padding = e.padding == null ? "valid" : e.padding, ln(this.padding), this.inputSpec = [new Tt({ ndim: 3 })];
}
computeOutputShape(e) {
e = Xe(e);
let t = Nn(e[1], this.poolSize[0], this.padding, this.strides[0]);
return [e[0], t, e[2]];
}
call(e, t) {
return V(() => {
this.invokeCallHook(e, t), e = ja(Me(e), 2);
let n = this.poolingFunction(Me(e), [this.poolSize[0], 1], [this.strides[0], 1], this.padding, "channelsLast");
return Br(n, [2]);
});
}
getConfig() {
let e = { poolSize: this.poolSize, padding: this.padding, strides: this.strides }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
var ih = class extends xv {
constructor(e) {
super(e);
}
poolingFunction(e, t, n, o, s) {
return Ot(s), ln(o), jx(e, t, n, o, s, "max");
}
};
ih.className = "MaxPooling1D";
ee.registerClass(ih);
var ah = class extends xv {
constructor(e) {
super(e);
}
poolingFunction(e, t, n, o, s) {
return Ot(s), ln(o), jx(e, t, n, o, s, "avg");
}
};
ah.className = "AveragePooling1D";
ee.registerClass(ah);
var yv = class extends Ge {
constructor(e) {
e.poolSize == null && (e.poolSize = [2, 2]);
super(e);
if (this.poolSize = Array.isArray(e.poolSize) ? e.poolSize : [e.poolSize, e.poolSize], e.strides == null)
this.strides = this.poolSize;
else if (Array.isArray(e.strides)) {
if (e.strides.length !== 2)
throw new z(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);
this.strides = e.strides;
} else
this.strides = [e.strides, e.strides];
Zt(this.poolSize, "poolSize"), Zt(this.strides, "strides"), this.padding = e.padding == null ? "valid" : e.padding, this.dataFormat = e.dataFormat == null ? "channelsLast" : e.dataFormat, Ot(this.dataFormat), ln(this.padding), this.inputSpec = [new Tt({ ndim: 4 })];
}
computeOutputShape(e) {
e = Xe(e);
let t = this.dataFormat === "channelsFirst" ? e[2] : e[1], n = this.dataFormat === "channelsFirst" ? e[3] : e[2];
return t = Nn(t, this.poolSize[0], this.padding, this.strides[0]), n = Nn(n, this.poolSize[1], this.padding, this.strides[1]), this.dataFormat === "channelsFirst" ? [e[0], e[1], t, n] : [e[0], t, n, e[3]];
}
call(e, t) {
return V(() => (this.invokeCallHook(e, t), this.poolingFunction(Me(e), this.poolSize, this.strides, this.padding, this.dataFormat)));
}
getConfig() {
let e = { poolSize: this.poolSize, padding: this.padding, strides: this.strides, dataFormat: this.dataFormat }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
var lh = class extends yv {
constructor(e) {
super(e);
}
poolingFunction(e, t, n, o, s) {
return Ot(s), ln(o), jx(e, t, n, o, s, "max");
}
};
lh.className = "MaxPooling2D";
ee.registerClass(lh);
var uh = class extends yv {
constructor(e) {
super(e);
}
poolingFunction(e, t, n, o, s) {
return Ot(s), ln(o), jx(e, t, n, o, s, "avg");
}
};
uh.className = "AveragePooling2D";
ee.registerClass(uh);
var bv = class extends Ge {
constructor(e) {
e.poolSize == null && (e.poolSize = [2, 2, 2]);
super(e);
if (this.poolSize = Array.isArray(e.poolSize) ? e.poolSize : [e.poolSize, e.poolSize, e.poolSize], e.strides == null)
this.strides = this.poolSize;
else if (Array.isArray(e.strides)) {
if (e.strides.length !== 3)
throw new z(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);
this.strides = e.strides;
} else
this.strides = [e.strides, e.strides, e.strides];
Zt(this.poolSize, "poolSize"), Zt(this.strides, "strides"), this.padding = e.padding == null ? "valid" : e.padding, this.dataFormat = e.dataFormat == null ? "channelsLast" : e.dataFormat, Ot(this.dataFormat), ln(this.padding), this.inputSpec = [new Tt({ ndim: 5 })];
}
computeOutputShape(e) {
e = Xe(e);
let t = this.dataFormat === "channelsFirst" ? e[2] : e[1], n = this.dataFormat === "channelsFirst" ? e[3] : e[2], o = this.dataFormat === "channelsFirst" ? e[4] : e[3];
return t = Nn(t, this.poolSize[0], this.padding, this.strides[0]), n = Nn(n, this.poolSize[1], this.padding, this.strides[1]), o = Nn(o, this.poolSize[2], this.padding, this.strides[2]), this.dataFormat === "channelsFirst" ? [e[0], e[1], t, n, o] : [e[0], t, n, o, e[4]];
}
call(e, t) {
return V(() => (this.invokeCallHook(e, t), this.poolingFunction(Me(e), this.poolSize, this.strides, this.padding, this.dataFormat)));
}
getConfig() {
let e = { poolSize: this.poolSize, padding: this.padding, strides: this.strides, dataFormat: this.dataFormat }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
var ch = class extends bv {
constructor(e) {
super(e);
}
poolingFunction(e, t, n, o, s) {
return Ot(s), ln(o), zA(e, t, n, o, s, "max");
}
};
ch.className = "MaxPooling3D";
ee.registerClass(ch);
var ph = class extends bv {
constructor(e) {
super(e);
}
poolingFunction(e, t, n, o, s) {
return Ot(s), ln(o), zA(e, t, n, o, s, "avg");
}
};
ph.className = "AveragePooling3D";
ee.registerClass(ph);
var wv = class extends Ge {
constructor(e) {
super(e);
this.inputSpec = [new Tt({ ndim: 3 })];
}
computeOutputShape(e) {
return [e[0], e[2]];
}
call(e, t) {
throw new Ne();
}
};
var mh = class extends wv {
constructor(e) {
super(e || {});
}
call(e, t) {
return V(() => {
let n = Me(e);
return xt(n, 1);
});
}
};
mh.className = "GlobalAveragePooling1D";
ee.registerClass(mh);
var fh = class extends wv {
constructor(e) {
super(e || {});
}
call(e, t) {
return V(() => {
let n = Me(e);
return Rr(n, 1);
});
}
};
fh.className = "GlobalMaxPooling1D";
ee.registerClass(fh);
var _v = class extends Ge {
constructor(e) {
super(e);
this.dataFormat = e.dataFormat == null ? "channelsLast" : e.dataFormat, Ot(this.dataFormat), this.inputSpec = [new Tt({ ndim: 4 })];
}
computeOutputShape(e) {
return e = e, this.dataFormat === "channelsLast" ? [e[0], e[3]] : [e[0], e[1]];
}
call(e, t) {
throw new Ne();
}
getConfig() {
let e = { dataFormat: this.dataFormat }, t = super.getConfig();
return Object.assign(e, t), e;
}
};
var dh = class extends _v {
call(e, t) {
return V(() => {
let n = Me(e);
return this.dataFormat === "channelsLast" ? xt(n, [1, 2]) : xt(n, [2, 3]);
});
}
};
dh.className = "GlobalAveragePooling2D";
ee.registerClass(dh);
var hh = class extends _v {
call(e, t) {
return V(() => {
let n = Me(e);
return this.dataFormat === "channelsLast" ? Rr(n, [1, 2]) : Rr(n, [2, 3]);
});
}
};
hh.className = "GlobalMaxPooling2D";
ee.registerClass(hh);
var kv = class extends Ge {
constructor(e) {
super(e);
this.layer = e.layer;
}
build(e) {
this.built = true;
}
get trainable() {
return this.layer != null ? this.layer.trainable : false;
}
set trainable(e) {
this.layer != null && (this.layer.trainable = e);
}
get trainableWeights() {
return this.layer.trainableWeights;
}
get nonTrainableWeights() {
return this.layer.nonTrainableWeights;
}
get updates() {
return this.layer._updates;
}
get losses() {
return this.layer.losses;
}
getWeights() {
return this.layer.getWeights();
}
setWeights(e) {
this.layer.setWeights(e);
}
getConfig() {
let e = { layer: { className: this.layer.getClassName(), config: this.layer.getConfig() } }, t = super.getConfig();
return Object.assign(e, t), e;
}
setFastWeightInitDuringBuild(e) {
super.setFastWeightInitDuringBuild(e), this.layer != null && this.layer.setFastWeightInitDuringBuild(e);
}
static fromConfig(e, t, n = {}) {
let o = t.layer, s = pn(o, n);
delete t.layer;
let a = { layer: s };
return Object.assign(a, t), new e(a);
}
};
var gh = class extends kv {
constructor(e) {
super(e);
this.supportsMasking = true;
}
build(e) {
if (e = Xe(e), e.length < 3)
throw new z(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);
this.inputSpec = [{ shape: e }];
let t = [e[0]].concat(e.slice(2));
this.layer.built || (this.layer.build(t), this.layer.built = true), super.build(e);
}
computeOutputShape(e) {
e = Xe(e);
let t = [e[0]].concat(e.slice(2)), n = this.layer.computeOutputShape(t), o = e[1];
return [n[0], o].concat(n.slice(1));
}
call(e, t) {
return V(() => (e = Me(e), hv((a, i) => [Me(this.layer.call(a, t)), []], e, [], false, null, null, false, true)[1]));
}
};
gh.className = "TimeDistributed";
ee.registerClass(gh);
function s8(r) {
Ci(K2, "BidirectionalMergeMode", r);
}
var i8 = "concat";
var xh = class extends kv {
constructor(e) {
super(e);
let t = e.layer.getConfig(), n = {};
n.className = e.layer.getClassName(), n.config = t, this.forwardLayer = pn(n), t.goBackwards = t.goBackwards !== true;
let o = {};
if (o.className = e.layer.getClassName(), o.config = t, this.backwardLayer = pn(o), this.forwardLayer.name = "forward_" + this.forwardLayer.name, this.backwardLayer.name = "backward_" + this.backwardLayer.name, this.mergeMode = e.mergeMode === void 0 ? i8 : e.mergeMode, s8(this.mergeMode), e.weights)
throw new Ne("weights support is not implemented for Bidirectional layer yet.");
this._stateful = e.layer.stateful, this.returnSequences = e.layer.returnSequences, this.returnState = e.layer.returnState, this.supportsMasking = true, this._trainable = true, this.inputSpec = e.layer.inputSpec, this.numConstants = null;
}
get trainable() {
return this._trainable;
}
set trainable(e) {
this._trainable = e, this.forwardLayer != null && (this.forwardLayer.trainable = e), this.backwardLayer != null && (this.backwardLayer.trainable = e);
}
getWeights() {
return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights());
}
setWeights(e) {
let t = e.length, n = Math.floor(t / 2);
this.forwardLayer.setWeights(e.slice(0, n)), this.backwardLayer.setWeights(e.slice(n));
}
computeOutputShape(e) {
let t = this.forwardLayer.computeOutputShape(e);
Array.isArray(t) && Array.isArray(t[0]) || (t = [t]), t = t;
let n, o, s;
return this.returnState && (s = t.slice(1)), n = t[0], n = n, this.mergeMode === "concat" ? (n[n.length - 1] *= 2, o = [n]) : this.mergeMode == null ? o = [n, n.slice()] : o = [n], this.returnState ? this.mergeMode == null ? o.concat(s).concat(s.slice()) : [n].concat(s).concat(s.slice()) : Sr(o);
}
apply(e, t) {
let n = t == null ? null : t.initialState, o = t == null ? null : t.constants;
t == null && (t = {});
let s = dv(e, n, o, this.numConstants);
if (e = s.inputs, n = s.initialState, o = s.constants, Array.isArray(e) && (n = e.slice(1), e = e[0]), (n == null || n.length === 0) && o == null)
return super.apply(e, t);
let a = [], i = [];
if (n != null) {
let u = n.length;
if (u % 2 > 0)
throw new z("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");
t.initialState = n, a.push(...n);
let c = n.map((p) => new Tt({ shape: p.shape }));
this.forwardLayer.stateSpec = c.slice(0, u / 2), this.backwardLayer.stateSpec = c.slice(u / 2), i.push(...c);
}
if (o != null)
throw new Ne("Support for constants in Bidirectional layers is not implemented yet.");
let l = a[0] instanceof cn;
for (let u of a)
if (u instanceof cn !== l)
throw new z("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");
if (l) {
let u = [e].concat(a), c = this.inputSpec.concat(i), p = this.inputSpec;
this.inputSpec = c;
let m = super.apply(u, t);
return this.inputSpec = p, m;
} else
return super.apply(e, t);
}
call(e, t) {
return V(() => {
let n = t.initialState, o, s;
if (n == null)
o = this.forwardLayer.call(e, t), s = this.backwardLayer.call(e, t);
else {
let l = n.slice(0, n.length / 2), u = n.slice(n.length / 2);
o = this.forwardLayer.call(e, Object.assign(t, { initialState: l })), s = this.backwardLayer.call(e, Object.assign(t, { initialState: u }));
}
let a;
this.returnState && (Array.isArray(o) && (a = o.slice(1).concat(s.slice(1))), o = o[0], s = s[0]), this.returnSequences && (s = er(s, 1));
let i;
return this.mergeMode === "concat" ? i = Kp([o, s]) : this.mergeMode === "sum" ? i = Z(o, s) : this.mergeMode === "ave" ? i = O(0.5, Z(o, s)) : this.mergeMode === "mul" ? i = O(o, s) : this.mergeMode == null && (i = [o, s]), this.returnState ? this.mergeMode == null ? i.concat(a) : [i].concat(a) : i;
});
}
resetStates(e) {
this.forwardLayer.resetStates(), this.backwardLayer.resetStates();
}
build(e) {
zs(this.forwardLayer.name, () => {
this.forwardLayer.build(e);
}), zs(this.backwardLayer.name, () => {
this.backwardLayer.build(e);
}), this.built = true;
}
computeMask(e, t) {
Array.isArray(t) && (t = t[0]);
let n;
if (this.returnSequences ? this.mergeMode == null ? n = [t, t] : n = t : this.mergeMode == null ? n = [null, null] : n = null, this.returnState) {
let s = this.forwardLayer.states.map((a) => null);
return Array.isArray(n) ? n.concat(s).concat(s) : [n].concat(s).concat(s);
} else
return n;
}
get trainableWeights() {
return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights);
}
get nonTrainableWeights() {
return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights);
}
setFastWeightInitDuringBuild(e) {
super.setFastWeightInitDuringBuild(e), this.forwardLayer != null && this.forwardLayer.setFastWeightInitDuringBuild(e), this.backwardLayer != null && this.backwardLayer.setFastWeightInitDuringBuild(e);
}
getConfig() {
let e = { mergeMode: this.mergeMode }, t = super.getConfig();
return Object.assign(e, t), e;
}
static fromConfig(e, t) {
let n = pn(t.layer);
if (delete t.layer, t.numConstants != null)
throw new Ne("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");
let o = t;
return o.layer = n, new e(o);
}
};
xh.className = "Bidirectional";
ee.registerClass(xh);
function a8(r) {
return new Ii(r);
}
function l8(r) {
return new kd(r);
}
function u8(r) {
return new bd(r);
}
function c8(r) {
return new wd(r);
}
function p8(r) {
return new _d(r);
}
function m8(r) {
return new Cd(r);
}
function f8(r) {
return new vd(r);
}
function d8(r) {
return new lc(r);
}
function h8(r) {
return new zl(r);
}
function g8(r) {
return new Sd(r);
}
function x8(r) {
return new Bl(r);
}
function y8(r) {
return new Nd(r);
}
function b8(r) {
return new Td(r);
}
function w8(r) {
return new Ed(r);
}
function _8(r) {
return new Ad(r);
}
function k8(r) {
return new Dd(r);
}
function v8(r) {
return new zd(r);
}
function C8(r) {
return new Md(r);
}
function I8(r) {
return new hm(r);
}
function S8(r) {
return new Pd(r);
}
function N8(r) {
return new Ld(r);
}
function T8(r) {
return new Bd(r);
}
function E8(r) {
return new Vd(r);
}
function A8(r) {
return new Gd(r);
}
function D8(r) {
return new Ud(r);
}
function $8(r) {
return new jd(r);
}
function R8(r) {
return new qd(r);
}
function F8(r) {
return new Yd(r);
}
function O8(r) {
return new Kd(r);
}
function P8(r) {
return new Xd(r);
}
function M8(r) {
return new Hd(r);
}
function L8(r) {
return new Jd(r);
}
function z8(r) {
return new nh(r);
}
function B8(r) {
return new oh(r);
}
function V8(r) {
return new sh(r);
}
function vv(r) {
return new ah(r);
}
function G8(r) {
return vv(r);
}
function W8(r) {
return vv(r);
}
function Cv(r) {
return new uh(r);
}
function U8(r) {
return Cv(r);
}
function j8(r) {
return Cv(r);
}
function Iv(r) {
return new ph(r);
}
function H8(r) {
return Iv(r);
}
function q8(r) {
return Iv(r);
}
function K8(r) {
return new mh(r);
}
function X8(r) {
return new dh(r);
}
function BA(r) {
return new fh(r);
}
function VA(r) {
return new hh(r);
}
function GA(r) {
return new ih(r);
}
function WA(r) {
return new lh(r);
}
function Y8(r) {
return new ch(r);
}
function Z8(r) {
return new Rd(r);
}
function J8(r) {
return new mm(r);
}
function Q8(r) {
return new Fd(r);
}
function eX(r) {
return new Gl(r);
}
function tX(r) {
return new $d(r);
}
function rX(r) {
return new pm(r);
}
function nX(r) {
return new Od(r);
}
function oX(r) {
return new dm(r);
}
function sX(r) {
return new Ln(r);
}
function iX(r) {
return new fm(r);
}
function aX(r) {
return new xh(r);
}
function lX(r) {
return new gh(r);
}
var uX = BA;
var cX = VA;
var pX = GA;
var mX = WA;
function fX(r) {
return new Qd(r);
}
function dX(r) {
return new eh(r);
}
function hX(r) {
return new th(r);
}
function gX(r) {
return new Wd(r);
}
var jA = {};
qe(jA, { MAPE: () => NX, MSE: () => AX, binaryAccuracy: () => xX, binaryCrossentropy: () => yX, categoricalAccuracy: () => wX, categoricalCrossentropy: () => _X, cosineProximity: () => CX, mape: () => TX, meanAbsoluteError: () => IX, meanAbsolutePercentageError: () => SX, meanSquaredError: () => EX, mse: () => DX, precision: () => kX, recall: () => vX, sparseCategoricalAccuracy: () => bX });
function xX(r, e) {
return dd(r, e);
}
function yX(r, e) {
return Ox(r, e);
}
function bX(r, e) {
return Px(r, e);
}
function wX(r, e) {
return hd(r, e);
}
function _X(r, e) {
return gd(r, e);
}
function kX(r, e) {
return Vk(r, e);
}
function vX(r, e) {
return dA(r, e);
}
function CX(r, e) {
return md(r, e);
}
function IX(r, e) {
return sm(r, e);
}
function SX(r, e) {
return Pl(r, e);
}
function NX(r, e) {
return Pl(r, e);
}
function TX(r, e) {
return Pl(r, e);
}
function EX(r, e) {
return Ni(r, e);
}
function AX(r, e) {
return Ni(r, e);
}
function DX(r, e) {
return Ni(r, e);
}
var HA = {};
qe(HA, { modelFromJSON: () => $A });
var qA = {};
qe(qA, { l1: () => RX, l1l2: () => $X, l2: () => FX });
function $X(r) {
return new ic(r);
}
function RX(r) {
return FA(r);
}
function FX(r) {
return OA(r);
}
var Sv = class extends Ol {
constructor() {
super(...arguments);
this.model = null;
}
setModel(e) {
if (!(e instanceof Yn))
throw new Error("model must be a LayersModel, not some other Container");
this.model = e;
}
};
function Hx(r, e) {
return r < e;
}
function KA(r, e) {
return r > e;
}
var Nv = class extends Sv {
constructor(e) {
super();
if (e == null && (e = {}), e.restoreBestWeights)
throw new Ne("restoreBestWeights = True is not implemented in EarlyStopping yet.");
this.monitor = e.monitor || "val_loss", this.minDelta = Math.abs(e.minDelta || 0), this.patience = e.patience || 0, this.verbose = e.verbose || 0, this.mode = e.mode || "auto", this.baseline = e.baseline, ["auto", "min", "max"].indexOf(this.mode) === -1 && (console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`), this.mode = "auto"), this.mode === "min" ? this.monitorFunc = Hx : this.mode === "max" ? this.monitorFunc = KA : this.monitor.indexOf("acc") !== -1 ? this.monitorFunc = KA : this.monitorFunc = Hx, this.monitorFunc === Hx && (this.minDelta *= -1);
}
async onTrainBegin(e) {
this.wait = 0, this.stoppedEpoch = 0, this.baseline != null ? this.best = this.baseline : this.best = this.monitorFunc === Hx ? 1 / 0 : -1 / 0;
}
async onEpochEnd(e, t) {
await Si(t);
let n = this.getMonitorValue(t);
n != null && (this.monitorFunc(n - this.minDelta, this.best) ? (this.best = n, this.wait = 0) : (this.wait++, this.wait >= this.patience && (this.stoppedEpoch = e, this.model.stopTraining = true)));
}
async onTrainEnd(e) {
this.stoppedEpoch > 0 && this.verbose && console.log(`Epoch ${this.stoppedEpoch}: early stopping.`);
}
getMonitorValue(e) {
e == null && (e = {});
let t = e[this.monitor];
return t == null && console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`), t;
}
};
function OX(r) {
return new Nv(r);
}
var PX = { earlyStopping: OX };
var ko;
(function(r) {
r[r.DT_INVALID = 0] = "DT_INVALID", r[r.DT_FLOAT = 1] = "DT_FLOAT", r[r.DT_DOUBLE = 2] = "DT_DOUBLE", r[r.DT_INT32 = 3] = "DT_INT32", r[r.DT_UINT8 = 4] = "DT_UINT8", r[r.DT_INT16 = 5] = "DT_INT16", r[r.DT_INT8 = 6] = "DT_INT8", r[r.DT_STRING = 7] = "DT_STRING", r[r.DT_COMPLEX64 = 8] = "DT_COMPLEX64", r[r.DT_INT64 = 9] = "DT_INT64", r[r.DT_BOOL = 10] = "DT_BOOL", r[r.DT_QINT8 = 11] = "DT_QINT8", r[r.DT_QUINT8 = 12] = "DT_QUINT8", r[r.DT_QINT32 = 13] = "DT_QINT32", r[r.DT_BFLOAT16 = 14] = "DT_BFLOAT16", r[r.DT_FLOAT_REF = 101] = "DT_FLOAT_REF", r[r.DT_DOUBLE_REF = 102] = "DT_DOUBLE_REF", r[r.DT_INT32_REF = 103] = "DT_INT32_REF", r[r.DT_UINT8_REF = 104] = "DT_UINT8_REF", r[r.DT_INT16_REF = 105] = "DT_INT16_REF", r[r.DT_INT8_REF = 106] = "DT_INT8_REF", r[r.DT_STRING_REF = 107] = "DT_STRING_REF", r[r.DT_COMPLEX64_REF = 108] = "DT_COMPLEX64_REF", r[r.DT_INT64_REF = 109] = "DT_INT64_REF", r[r.DT_BOOL_REF = 110] = "DT_BOOL_REF", r[r.DT_QINT8_REF = 111] = "DT_QINT8_REF", r[r.DT_QUINT8_REF = 112] = "DT_QUINT8_REF", r[r.DT_QINT32_REF = 113] = "DT_QINT32_REF", r[r.DT_BFLOAT16_REF = 114] = "DT_BFLOAT16_REF";
})(ko || (ko = {}));
var XA;
(function(r) {
let e;
(function(t) {
t[t.LEGACY = 0] = "LEGACY", t[t.V1 = 1] = "V1", t[t.V2 = 2] = "V2";
})(e = r.CheckpointFormatVersion || (r.CheckpointFormatVersion = {}));
})(XA || (XA = {}));
var Tv = {};
function MX(r, e) {
let t = { tfOpName: r, category: "custom", inputs: [], attrs: [], customExecutor: e };
Tv[r] = t;
}
function qx(r) {
return Tv[r];
}
function LX(r) {
delete Tv[r];
}
function v(r, e, t, n, o) {
let s = e.inputParams[r];
if (s && s.inputIndexStart !== void 0) {
let i = s.inputIndexStart, l = s.inputIndexEnd === 0 ? void 0 : s.inputIndexEnd === void 0 ? i + 1 : s.inputIndexEnd;
if (s.type === "tensor")
return br(e.inputNames[s.inputIndexStart], t, n, o);
if (s.type === "tensors")
return e.inputNames.slice(i, l).map((m) => br(m, t, n, o));
let u = br(e.inputNames.slice(i)[0], t, n, o), c = u.dataSync();
return s.type === "number" ? c[0] : b.toNestedArray(u.shape, c);
}
let a = e.attrParams[r];
return a && a.value;
}
function br(r, e, t, n) {
let [o, s] = fn(r);
if (n != null) {
let i = n.getHashTableHandleByName(o);
if (i != null)
return i;
}
let a = t.currentContextIds.find((i) => !!e[Kx(o, i)]);
return a !== void 0 ? e[Kx(o, a)][s] : void 0;
}
function YA(r, e, t) {
return e[Kx(r, t.currentContextId)];
}
function js(r, e) {
let [t, n, o] = fn(r);
return [Kx(t, e && e.currentContextId), n, o];
}
function Kx(r, e) {
return e ? `${r}-${e}` : r;
}
function fn(r) {
let e = r.split(":");
if (e.length === 1)
return [r, 0, void 0];
let t = e[0], n = e.length === 3 ? e[1] : void 0, o = Number(e[e.length - 1]);
return [t, o, n];
}
function yh(r, e, t) {
let n = v("pad", r, e, t);
if (n === "explicit") {
n = v("explicitPaddings", r, e, t);
let o = [[0, 0], [0, 0], [0, 0], [0, 0]];
for (let s = 0; s < 4; s++)
o[s][0] = n[s * 2], o[s][1] = n[s * 2 + 1];
return o;
}
return n;
}
function Hs(r) {
return r.kept ? r : wn(r);
}
var Ev = {};
qe(Ev, { json: () => zX });
var zX = [{ tfOpName: "Add", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "AddV2", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "AddN", category: "arithmetic", inputs: [{ start: 0, end: 0, name: "tensors", type: "tensors" }] }, { tfOpName: "BiasAdd", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }, { tfName: "data_format", name: "dataFormat", type: "string", notSupported: true }] }, { tfOpName: "Sub", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "RealDiv", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Div", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "DivNoNan", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "FloorDiv", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Mul", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Maximum", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Minimum", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Pow", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "SquaredDifference", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Mod", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "FloorMod", category: "arithmetic", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }];
var Av = {};
qe(Av, { json: () => BX });
var BX = [{ tfOpName: "Abs", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Acos", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Asin", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Atan", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Atan2", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "y", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Ceil", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "ClipByValue", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "clipValueMin", type: "number" }, { start: 2, name: "clipValueMax", type: "number" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Complex", category: "basic_math", inputs: [{ start: 0, name: "real", type: "tensor" }, { start: 1, name: "imag", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "ComplexAbs", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Cos", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Cosh", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Elu", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Exp", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Floor", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Log", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Imag", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }, { tfName: "Tout", name: "outputType", type: "dtype", notSupported: true }] }, { tfOpName: "Neg", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Real", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }, { tfName: "Tout", name: "outputType", type: "dtype", notSupported: true }] }, { tfOpName: "Prelu", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "alpha", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Relu", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Relu6", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Selu", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Sigmoid", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Sin", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Sinh", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Sqrt", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Rsqrt", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Square", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Tan", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Tanh", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Sign", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Round", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Expm1", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Log1p", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Reciprocal", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Softplus", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Asinh", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Acosh", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Atanh", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Erf", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Prod", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axes", type: "number[]" }], attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool", notSupported: true }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "LeakyRelu", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "alpha", name: "alpha", type: "number", defaultValue: 0.2 }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "IsNan", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }];
var Dv = {};
qe(Dv, { json: () => VX });
var VX = [{ tfOpName: "EmptyTensorList", category: "control", inputs: [{ start: 0, name: "elementShape", type: "shape" }, { start: 1, name: "maxNumElements", type: "number" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "LoopCond", category: "control", inputs: [{ start: 0, name: "pred", type: "tensor" }] }, { tfOpName: "Switch", category: "control", inputs: [{ start: 0, name: "data", type: "tensor" }, { start: 1, name: "pred", type: "tensor" }] }, { tfOpName: "Merge", category: "control", inputs: [{ start: 0, end: 0, name: "tensors", type: "tensors" }] }, { tfOpName: "Enter", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }, { tfName: "frame_name", name: "frameName", type: "string" }, { tfName: "is_constant", name: "isConstant", type: "bool" }] }, { tfOpName: "Exit", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "NextIteration", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "TensorArrayV3", category: "control", inputs: [{ start: 0, name: "size", type: "number" }], attrs: [{ tfName: "dtype", name: "dtype", type: "dtype" }, { tfName: "element_shape", name: "elementShape", type: "shape" }, { tfName: "dynamic_size", name: "dynamicSize", type: "bool" }, { tfName: "clear_after_read", name: "clearAfterRead", type: "bool" }, { tfName: "identical_element_shapes", name: "identicalElementShapes", type: "bool" }, { tfName: "tensor_array_name", name: "name", type: "string" }] }, { tfOpName: "TensorArrayWriteV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "index", type: "number" }, { start: 2, name: "tensor", type: "tensor" }, { start: 3, name: "flowIn", type: "number" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "TensorArrayReadV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "index", type: "number" }, { start: 2, name: "flowIn", type: "number" }], attrs: [{ tfName: "dtype", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "TensorArrayGatherV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "indices", type: "number[]" }, { start: 2, name: "flowIn", type: "number" }], attrs: [{ tfName: "dtype", name: "dtype", type: "dtype" }, { tfName: "element_shape", name: "elementShape", type: "shape" }] }, { tfOpName: "TensorArrayScatterV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "indices", type: "number[]" }, { start: 2, name: "tensor", type: "tensor" }, { start: 3, name: "flowIn", type: "number" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype" }] }, { tfOpName: "TensorArrayConcatV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "flowIn", type: "number" }], attrs: [{ tfName: "dtype", name: "dtype", type: "dtype" }, { tfName: "element_shape_except0", name: "elementShapeExcept0", type: "shape", notSupported: true }] }, { tfOpName: "TensorArraySplitV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "tensor", type: "tensor" }, { start: 2, name: "lengths", type: "number[]" }, { start: 3, name: "flowIn", type: "number" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype" }] }, { tfOpName: "TensorArraySizeV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }, { start: 1, name: "flowIn", type: "number" }] }, { tfOpName: "TensorArrayCloseV3", category: "control", inputs: [{ start: 0, name: "tensorArrayId", type: "tensor" }] }, { tfOpName: "StatelessIf", category: "control", inputs: [{ start: 0, name: "cond", type: "tensor" }, { start: 1, end: 0, name: "args", type: "tensors" }], attrs: [{ tfName: "then_branch", name: "thenBranch", type: "func" }, { tfName: "else_branch", name: "elseBranch", type: "func" }] }, { tfOpName: "If", category: "control", inputs: [{ start: 0, name: "cond", type: "tensor" }, { start: 1, end: 0, name: "args", type: "tensors" }], attrs: [{ tfName: "then_branch", name: "thenBranch", type: "func" }, { tfName: "else_branch", name: "elseBranch", type: "func" }] }, { tfOpName: "StatelessWhile", category: "control", inputs: [{ start: 0, end: 0, name: "args", type: "tensors" }], attrs: [{ tfName: "cond", name: "cond", type: "func" }, { tfName: "body", name: "body", type: "func" }] }, { tfOpName: "While", category: "control", inputs: [{ start: 0, end: 0, name: "args", type: "tensors" }], attrs: [{ tfName: "cond", name: "cond", type: "func" }, { tfName: "body", name: "body", type: "func" }] }, { tfOpName: "TensorListScatter", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }, { start: 1, name: "indices", type: "number[]" }, { start: 2, name: "elementShape", type: "shape" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListScatterV2", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }, { start: 1, name: "indices", type: "number[]" }, { start: 2, name: "elementShape", type: "shape" }, { start: 3, name: "numElements", type: "number" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListGather", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "indices", type: "number[]" }, { start: 2, name: "elementShape", type: "shape" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListGetItem", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "index", type: "number" }, { start: 2, name: "elementShape", type: "shape" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListSetItem", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "index", type: "number" }, { start: 2, name: "tensor", type: "tensor" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListReserve", category: "control", inputs: [{ start: 0, name: "elementShape", type: "shape" }, { start: 1, name: "numElements", type: "number" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListFromTensor", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }, { start: 1, name: "elementShape", type: "shape" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListStack", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "elementShape", type: "shape" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }, { tfName: "num_elements", name: "numElements", type: "dtype" }] }, { tfOpName: "TensorListSplit", category: "control", inputs: [{ start: 0, name: "tensor", type: "tensor" }, { start: 1, name: "elementShape", type: "shape" }, { start: 2, name: "lengths", type: "number[]" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListConcat", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }], attrs: [{ tfName: "element_shape", name: "elementShape", type: "shape" }, { tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListPopBack", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "elementShape", type: "shape" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }, { tfOpName: "TensorListPushBack", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "tensor", type: "tensor" }], attrs: [{ tfName: "element_dtype", name: "elementDType", type: "dtype" }] }];
var $v = {};
qe($v, { json: () => GX });
var GX = [{ tfOpName: "AvgPool", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", notSupported: true }, { tfName: "ksize", name: "kernelSize", type: "number[]" }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "MaxPool", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", notSupported: true }, { tfName: "ksize", name: "kernelSize", type: "number[]" }, { tfName: "explicit_paddings", name: "explicitPaddings", type: "number[]", defaultValue: [], notSupported: true }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "MaxPoolWithArgmax", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "ksize", name: "kernelSize", type: "number[]" }, { tfName: "include_batch_in_index", name: "includeBatchInIndex", type: "bool" }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "AvgPool3D", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", notSupported: true }, { tfName: "ksize", name: "kernelSize", type: "number[]" }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "MaxPool3D", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", notSupported: true }, { tfName: "ksize", name: "kernelSize", type: "number[]" }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Conv1D", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }], attrs: [{ tfName: "stride", name: "stride", type: "number" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", defaultValue: "NWC" }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }, { tfName: "dilation", name: "dilation", type: "number", defaultValue: 1 }] }, { tfOpName: "Conv2D", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }, { tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "useCudnnOnGpu", name: "useCudnnOnGpu", type: "bool" }, { tfName: "data_format", name: "dataFormat", type: "string", defaultValue: "NHWC" }, { tfName: "explicit_paddings", name: "explicitPaddings", type: "number[]", defaultValue: [] }, { tfName: "dilations", name: "dilations", type: "number[]" }] }, { tfOpName: "_FusedConv2D", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }, { start: 2, end: 0, name: "args", type: "tensors" }], attrs: [{ tfName: "num_args", name: "numArgs", type: "number" }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }, { tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "explicit_paddings", name: "explicitPaddings", type: "number[]", defaultValue: [] }, { tfName: "use_cudnn_on_gpu", name: "useCudnnOnGpu", type: "bool", defaultValue: true }, { tfName: "data_format", name: "dataFormat", type: "string", defaultValue: "NHWC" }, { tfName: "dilations", name: "dilations", type: "number[]", defaultValue: [1, 1, 1, 1] }, { tfName: "fused_ops", name: "fusedOps", type: "string[]", defaultValue: [] }, { tfName: "epsilon", name: "epsilon", type: "number", defaultValue: 1e-4 }, { tfName: "leakyrelu_alpha", name: "leakyreluAlpha", type: "number" }] }, { tfOpName: "Conv2DBackpropInput", category: "convolution", inputs: [{ start: 2, name: "x", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }, { start: 0, name: "outputShape", type: "number[]" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", notSupported: true }, { tfName: "explicit_paddings", name: "explicitPaddings", type: "number[]", defaultValue: [] }, { tfName: "dilations", name: "dilations", type: "number[]", notSupported: true }] }, { tfOpName: "DepthwiseConv2d", category: "convolution", inputs: [{ start: 0, name: "input", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", defaultValue: "NHWC" }, { tfName: "explicit_paddings", name: "explicitPaddings", type: "number[]", defaultValue: [] }, { tfName: "dilations", name: "dilations", type: "number[]" }] }, { tfOpName: "DepthwiseConv2dNative", category: "convolution", inputs: [{ start: 0, name: "input", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", defaultValue: "NHWC" }, { tfName: "explicit_paddings", name: "explicitPaddings", type: "number[]", defaultValue: [] }, { tfName: "dilations", name: "dilations", type: "number[]" }] }, { tfOpName: "FusedDepthwiseConv2dNative", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }, { start: 2, end: 0, name: "args", type: "tensors" }], attrs: [{ tfName: "num_args", name: "numArgs", type: "number" }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }, { tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", defaultValue: "NHWC" }, { tfName: "dilations", name: "dilations", type: "number[]", defaultValue: [1, 1, 1, 1] }, { tfName: "fused_ops", name: "fusedOps", type: "string[]", defaultValue: [] }, { tfName: "explicit_paddings", name: "explicitPaddings", type: "number[]", defaultValue: [] }] }, { tfOpName: "Conv3D", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }, { tfName: "data_format", name: "dataFormat", type: "string", defaultValue: "NHWC" }, { tfName: "dilations", name: "dilations", type: "number[]" }] }, { tfOpName: "Dilation2D", category: "convolution", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "filter", type: "tensor" }], attrs: [{ tfName: "strides", name: "strides", type: "number[]" }, { tfName: "rates", name: "dilations", type: "number[]" }, { tfName: "padding", name: "pad", type: "string" }] }];
var Rv = {};
qe(Rv, { json: () => WX });
var WX = [{ tfOpName: "Fill", category: "creation", inputs: [{ start: 0, name: "shape", type: "number[]" }, { start: 1, name: "value", type: "number" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype" }] }, { tfOpName: "LinSpace", category: "creation", inputs: [{ start: 0, name: "start", type: "number" }, { start: 1, name: "stop", type: "number" }, { start: 2, name: "num", type: "number" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "OneHot", category: "creation", inputs: [{ start: 0, name: "indices", type: "tensor" }, { start: 1, name: "depth", type: "number" }, { start: 2, name: "onValue", type: "number", defaultValue: 1 }, { start: 3, name: "offValue", type: "number", defaultValue: 0 }], attrs: [{ tfName: "axis", name: "axis", type: "number", notSupported: true }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Ones", category: "creation", inputs: [{ start: 0, name: "shape", type: "number[]" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype" }] }, { tfOpName: "OnesLike", category: "creation", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "dtype", name: "dtype", type: "dtype" }] }, { tfOpName: "RandomUniform", category: "creation", inputs: [{ start: 0, name: "shape", type: "number[]" }], attrs: [{ tfName: "minval", name: "minval", type: "number", defaultValue: 0 }, { tfName: "maxval", name: "maxval", type: "number", defaultValue: 1 }, { tfName: "dtype", name: "dtype", type: "dtype" }, { tfName: "seed", name: "seed", type: "number", defaultValue: 0 }, { tfName: "seed2", name: "seed2", type: "number", defaultValue: 0, notSupported: true }, { tfName: "T", name: "T", type: "number", notSupported: true }] }, { tfOpName: "Range", category: "creation", inputs: [{ start: 0, name: "start", type: "number" }, { start: 1, name: "stop", type: "number" }, { start: 2, name: "step", type: "number", defaultValue: 0 }], attrs: [{ tfName: "Tidx", name: "dtype", type: "dtype" }] }, { tfOpName: "TruncatedNormal", category: "creation", inputs: [{ start: 0, name: "shape", type: "number[]" }], attrs: [{ tfName: "means", name: "mean", type: "number", defaultValue: 0 }, { tfName: "stddev", name: "stdDev", type: "number", defaultValue: 1 }, { tfName: "seed", name: "seed", type: "number" }, { tfName: "seed2", name: "seed2", type: "number", defaultValue: 0, notSupported: true }, { tfName: "dtype", name: "dtype", type: "dtype" }, { tfName: "T", name: "T", type: "number", notSupported: true }] }, { tfOpName: "Zeros", category: "creation", inputs: [{ start: 0, name: "shape", type: "number[]" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype" }] }, { tfOpName: "ZerosLike", category: "creation", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype" }] }, { tfOpName: "Multinomial", category: "creation", inputs: [{ start: 0, name: "logits", type: "tensor" }, { start: 1, name: "numSamples", type: "number" }], attrs: [{ tfName: "seed", name: "seed", type: "number" }, { tfName: "seed2", name: "seed2", type: "number" }, { tfName: "T", name: "dtype", type: "dtype" }, { tfName: "output_dtype", name: "output_dtype", type: "dtype" }] }];
var Fv = {};
qe(Fv, { json: () => UX });
var UX = [{ tfOpName: "NonMaxSuppressionV2", category: "dynamic", inputs: [{ start: 0, name: "boxes", type: "tensor" }, { start: 1, name: "scores", type: "tensor" }, { start: 2, name: "maxOutputSize", type: "number" }, { start: 3, name: "iouThreshold", type: "number" }] }, { tfOpName: "NonMaxSuppressionV3", category: "dynamic", inputs: [{ start: 0, name: "boxes", type: "tensor" }, { start: 1, name: "scores", type: "tensor" }, { start: 2, name: "maxOutputSize", type: "number" }, { start: 3, name: "iouThreshold", type: "number" }, { start: 4, name: "scoreThreshold", type: "number" }] }, { tfOpName: "NonMaxSuppressionV4", category: "dynamic", inputs: [{ start: 0, name: "boxes", type: "tensor" }, { start: 1, name: "scores", type: "tensor" }, { start: 2, name: "maxOutputSize", type: "number" }, { start: 3, name: "iouThreshold", type: "number" }, { start: 4, name: "scoreThreshold", type: "number" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }, { tfName: "T_threshold", name: "threshold", type: "dtype", notSupported: true }, { tfName: "pad_to_max_output_size", name: "padToMaxOutputSize", type: "bool" }] }, { tfOpName: "NonMaxSuppressionV5", category: "dynamic", inputs: [{ start: 0, name: "boxes", type: "tensor" }, { start: 1, name: "scores", type: "tensor" }, { start: 2, name: "maxOutputSize", type: "number" }, { start: 3, name: "iouThreshold", type: "number" }, { start: 4, name: "scoreThreshold", type: "number" }, { start: 5, name: "softNmsSigma", type: "number" }] }, { tfOpName: "Where", category: "dynamic", inputs: [{ start: 0, name: "condition", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "ListDiff", category: "dynamic", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "y", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }];
var Ov = {};
qe(Ov, { json: () => jX });
var jX = [{ tfOpName: "TopKV2", category: "evaluation", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "k", type: "number" }], attrs: [{ tfName: "sorted", name: "sorted", type: "bool" }] }, { tfOpName: "Unique", category: "evaluation", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { tfOpName: "UniqueV2", category: "evaluation", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number" }] }];
var Pv = {};
qe(Pv, { json: () => HX });
var HX = [{ tfOpName: "PlaceholderWithDefault", category: "graph", inputs: [{ start: 0, name: "default", type: "tensor" }], attrs: [{ tfName: "shape", name: "shape", type: "shape" }, { tfName: "dtype", name: "dtype", type: "dtype" }] }, { tfOpName: "Placeholder", category: "graph", attrs: [{ tfName: "shape", name: "shape", type: "shape" }, { tfName: "dtype", name: "dtype", type: "dtype" }] }, { tfOpName: "Const", category: "graph" }, { tfOpName: "Identity", category: "graph", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { tfOpName: "IdentityN", category: "graph", inputs: [{ start: 0, end: 0, name: "x", type: "tensors" }] }, { tfOpName: "Snapshot", category: "graph", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { tfOpName: "Rank", category: "graph", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { tfOpName: "Size", category: "graph", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { tfOpName: "Shape", category: "graph", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { tfOpName: "ShapeN", category: "graph", inputs: [{ start: 0, end: 0, name: "x", type: "tensors" }] }, { tfOpName: "Print", category: "graph", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "data", type: "tensors" }], attrs: [{ tfName: "message", name: "message", type: "string" }, { tfName: "first_n", name: "firstN", type: "number", notSupported: true }, { tfName: "summarize", name: "summarize", type: "number", defaultValue: 3 }] }, { tfOpName: "NoOp", category: "graph", inputs: [] }, { tfOpName: "StopGradient", category: "graph", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { tfOpName: "FakeQuantWithMinMaxVars", category: "graph", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "min", name: "min", type: "number" }, { tfName: "max", name: "max", type: "number" }] }];
var Mv = {};
qe(Mv, { json: () => qX });
var qX = [{ tfOpName: "HashTable", category: "hash_table", inputs: [], attrs: [{ tfName: "shared_name", name: "sharedName", type: "string" }, { tfName: "use_node_name_sharing", name: "useNodeNameSharing", type: "bool" }, { tfName: "key_dtype", name: "keyDType", type: "dtype" }, { tfName: "value_dtype", name: "valueDType", type: "dtype" }] }, { tfOpName: "HashTableV2", category: "hash_table", inputs: [], attrs: [{ tfName: "shared_name", name: "sharedName", type: "string" }, { tfName: "use_node_name_sharing", name: "useNodeNameSharing", type: "bool" }, { tfName: "key_dtype", name: "keyDType", type: "dtype" }, { tfName: "value_dtype", name: "valueDType", type: "dtype" }] }, { tfOpName: "LookupTableImport", category: "hash_table", inputs: [{ start: 0, name: "tableHandle", type: "tensor" }, { start: 1, name: "keys", type: "tensor" }, { start: 2, name: "values", type: "tensor" }], attrs: [{ tfName: "Tin", name: "tIn", type: "dtype", notSupported: true }, { tfName: "Tout", name: "tOut", type: "dtype", notSupported: true }] }, { tfOpName: "LookupTableImportV2", category: "hash_table", inputs: [{ start: 0, name: "tableHandle", type: "tensor" }, { start: 1, name: "keys", type: "tensor" }, { start: 2, name: "values", type: "tensor" }], attrs: [{ tfName: "Tin", name: "tIn", type: "dtype", notSupported: true }, { tfName: "Tout", name: "tOut", type: "dtype", notSupported: true }] }, { tfOpName: "LookupTableFind", category: "hash_table", inputs: [{ start: 0, name: "tableHandle", type: "tensor" }, { start: 1, name: "keys", type: "tensor" }, { start: 2, name: "defaultValue", type: "tensor" }], attrs: [{ tfName: "Tin", name: "tIn", type: "dtype", notSupported: true }, { tfName: "Tout", name: "tOut", type: "dtype", notSupported: true }] }, { tfOpName: "LookupTableFindV2", category: "hash_table", inputs: [{ start: 0, name: "tableHandle", type: "tensor" }, { start: 1, name: "keys", type: "tensor" }, { start: 2, name: "defaultValue", type: "tensor" }], attrs: [{ tfName: "Tin", name: "tIn", type: "dtype", notSupported: true }, { tfName: "Tout", name: "tOut", type: "dtype", notSupported: true }] }, { tfOpName: "LookupTableSize", category: "hash_table", inputs: [{ start: 0, name: "tableHandle", type: "tensor" }] }, { tfOpName: "LookupTableSizeV2", category: "hash_table", inputs: [{ start: 0, name: "tableHandle", type: "tensor" }] }];
var Lv = {};
qe(Lv, { json: () => KX });
var KX = [{ tfOpName: "ResizeBilinear", category: "image", inputs: [{ start: 0, name: "images", type: "tensor" }, { start: 1, name: "size", type: "number[]" }], attrs: [{ tfName: "align_corners", name: "alignCorners", type: "bool" }, { tfName: "half_pixel_centers", name: "halfPixelCenters", type: "bool" }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "ResizeNearestNeighbor", category: "image", inputs: [{ start: 0, name: "images", type: "tensor" }, { start: 1, name: "size", type: "number[]" }], attrs: [{ tfName: "align_corners", name: "alignCorners", type: "bool" }, { tfName: "half_pixel_centers", name: "halfPixelCenters", type: "bool" }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "CropAndResize", category: "image", inputs: [{ start: 0, name: "image", type: "tensor" }, { start: 1, name: "boxes", type: "tensor" }, { start: 2, name: "boxInd", type: "tensor" }, { start: 3, name: "cropSize", type: "number[]" }], attrs: [{ tfName: "method", name: "method", type: "string" }, { tfName: "extrapolation_value", name: "extrapolationValue", type: "number" }] }];
var zv = {};
qe(zv, { json: () => XX });
var XX = [{ tfOpName: "Equal", category: "logical", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "NotEqual", category: "logical", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Greater", category: "logical", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "GreaterEqual", category: "logical", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Less", category: "logical", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "LessEqual", category: "logical", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "LogicalAnd", category: "logical", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "LogicalNot", category: "logical", inputs: [{ start: 0, name: "a", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "LogicalOr", category: "logical", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Select", category: "logical", inputs: [{ start: 0, name: "condition", type: "tensor" }, { start: 1, name: "a", type: "tensor" }, { start: 2, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "SelectV2", category: "logical", inputs: [{ start: 0, name: "condition", type: "tensor" }, { start: 1, name: "a", type: "tensor" }, { start: 2, name: "b", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }];
var Bv = {};
qe(Bv, { json: () => YX });
var YX = [{ tfOpName: "_FusedMatMul", category: "matrices", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }, { start: 2, end: 0, name: "args", type: "tensors" }], attrs: [{ tfName: "num_args", name: "numArgs", type: "number" }, { tfName: "fused_ops", name: "fusedOps", type: "string[]", defaultValue: [] }, { tfName: "epsilon", name: "epsilon", type: "number", defaultValue: 1e-4 }, { tfName: "transpose_a", name: "transposeA", type: "bool", defaultValue: false }, { tfName: "transpose_b", name: "transposeB", type: "bool", defaultValue: false }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "MatMul", category: "matrices", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "transpose_a", name: "transposeA", type: "bool", defaultValue: false }, { tfName: "transpose_b", name: "transposeB", type: "bool", defaultValue: false }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "BatchMatMul", category: "matrices", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "adj_x", name: "transposeA", type: "bool", defaultValue: false }, { tfName: "adj_y", name: "transposeB", type: "bool", defaultValue: false }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "BatchMatMulV2", category: "matrices", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "b", type: "tensor" }], attrs: [{ tfName: "adj_x", name: "transposeA", type: "bool", defaultValue: false }, { tfName: "adj_y", name: "transposeB", type: "bool", defaultValue: false }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Transpose", category: "matrices", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "perm", type: "number[]" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Einsum", category: "matrices", inputs: [{ start: 0, end: 0, name: "tensors", type: "tensors" }], attrs: [{ tfName: "equation", name: "equation", type: "string" }, { tfName: "N", name: "n", type: "number", defaultValue: 2 }, { tfName: "T", name: "dtype", type: "dtype" }] }];
var Vv = {};
qe(Vv, { json: () => ZX });
var ZX = [{ tfOpName: "FusedBatchNorm", category: "normalization", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "scale", type: "tensor" }, { start: 2, name: "offset", type: "tensor" }, { start: 3, name: "mean", type: "tensor" }, { start: 4, name: "variance", type: "tensor" }], attrs: [{ tfName: "epsilon", name: "epsilon", type: "number", defaultValue: 1e-3 }, { tfName: "data_format", name: "dataFormat", type: "string", notSupported: true }] }, { tfOpName: "FusedBatchNormV2", category: "normalization", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "scale", type: "tensor" }, { start: 2, name: "offset", type: "tensor" }, { start: 3, name: "mean", type: "tensor" }, { start: 4, name: "variance", type: "tensor" }], attrs: [{ tfName: "epsilon", name: "epsilon", type: "number", defaultValue: 1e-3 }, { tfName: "data_format", name: "dataFormat", type: "string", notSupported: true }] }, { tfOpName: "FusedBatchNormV3", category: "normalization", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "scale", type: "tensor" }, { start: 2, name: "offset", type: "tensor" }, { start: 3, name: "mean", type: "tensor" }, { start: 4, name: "variance", type: "tensor" }], attrs: [{ tfName: "epsilon", name: "epsilon", type: "number", defaultValue: 1e-3 }, { tfName: "data_format", name: "dataFormat", type: "string", notSupported: true }] }, { tfOpName: "LRN", category: "normalization", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "depth_radius", name: "radius", type: "number", defaultValue: 5 }, { tfName: "bias", name: "bias", type: "number", defaultValue: 1 }, { tfName: "alpha", name: "alpha", type: "number", defaultValue: 1 }, { tfName: "beta", name: "beta", type: "number", defaultValue: 0.5 }] }, { tfOpName: "Softmax", category: "normalization", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { tfOpName: "LogSoftmax", category: "normalization", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { tfOpName: "SparseToDense", category: "normalization", inputs: [{ start: 0, name: "sparseIndices", type: "tensor" }, { start: 1, name: "outputShape", type: "number[]" }, { start: 2, name: "sparseValues", type: "tensor" }, { start: 3, name: "defaultValue", type: "tensor" }], attrs: [{ tfName: "validate_indices", name: "validateIndices", type: "bool", defaultValue: true, notSupported: true }] }];
var Gv = {};
qe(Gv, { json: () => JX });
var JX = [{ tfOpName: "Bincount", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "size", type: "number" }, { start: 2, name: "weights", type: "tensor" }] }, { tfOpName: "DenseBincount", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "size", type: "number" }, { start: 2, name: "weights", type: "tensor" }], attrs: [{ tfName: "binary_output", name: "binaryOutput", type: "bool" }] }, { tfOpName: "Max", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number[]" }], attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }] }, { tfOpName: "Mean", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number[]" }], attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }] }, { tfOpName: "Min", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number[]" }], attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }] }, { tfOpName: "Sum", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number[]" }], attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }] }, { tfOpName: "All", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number[]" }], attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }] }, { tfOpName: "Any", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number[]" }], attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }] }, { tfOpName: "ArgMax", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number" }] }, { tfOpName: "ArgMin", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number" }] }, { tfOpName: "Prod", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number[]" }], attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool" }] }, { tfOpName: "Cumsum", category: "reduction", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number" }], attrs: [{ tfName: "exclusive", name: "exclusive", type: "bool" }, { tfName: "reverse", name: "reverse", type: "bool" }] }];
var Wv = {};
qe(Wv, { json: () => QX });
var QX = [{ tfOpName: "ConcatV2", category: "slice_join", inputs: [{ start: 0, end: -1, name: "tensors", type: "tensors" }, { start: -1, name: "axis", type: "number" }], attrs: [{ tfName: "N", name: "n", type: "number", defaultValue: 2 }] }, { tfOpName: "Concat", category: "slice_join", inputs: [{ start: 1, end: 0, name: "tensors", type: "tensors" }, { start: 0, name: "axis", type: "number" }], attrs: [{ tfName: "N", name: "n", type: "number", defaultValue: 2 }] }, { tfOpName: "GatherV2", category: "slice_join", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "indices", type: "tensor" }, { start: 2, name: "axis", type: "number", defaultValue: 0 }], attrs: [{ tfName: "batch_dims", name: "batchDims", type: "number", defaultValue: 0 }] }, { tfOpName: "Gather", category: "slice_join", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "indices", type: "tensor" }], attrs: [{ tfName: "validate_indices", name: "validateIndices", type: "bool", notSupported: true }] }, { tfOpName: "Reverse", category: "slice_join", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "dims", type: "bool[]" }] }, { tfOpName: "ReverseV2", category: "slice_join", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number[]" }] }, { tfOpName: "Slice", category: "slice_join", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "begin", type: "number[]" }, { start: 2, name: "size", type: "number[]" }] }, { tfOpName: "StridedSlice", category: "slice_join", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "begin", type: "number[]" }, { start: 2, name: "end", type: "number[]" }, { start: 3, name: "strides", type: "number[]" }], attrs: [{ tfName: "begin_mask", name: "beginMask", type: "number", defaultValue: 0 }, { tfName: "end_mask", name: "endMask", type: "number", defaultValue: 0 }, { tfName: "new_axis_mask", name: "newAxisMask", type: "number", defaultValue: 0 }, { tfName: "ellipsis_mask", name: "ellipsisMask", type: "number", defaultValue: 0 }, { tfName: "shrink_axis_mask", name: "shrinkAxisMask", type: "number", defaultValue: 0 }] }, { tfOpName: "Pack", category: "slice_join", inputs: [{ start: 0, end: 0, name: "tensors", type: "tensors" }], attrs: [{ tfName: "axis", name: "axis", type: "number", defaultValue: 0 }] }, { tfOpName: "Unpack", category: "slice_join", inputs: [{ start: 0, name: "tensor", type: "tensor" }], attrs: [{ tfName: "axis", name: "axis", type: "number", defaultValue: 0 }, { tfName: "num", name: "num", type: "number", defaultValue: 0, notSupported: true }] }, { tfOpName: "Tile", category: "slice_join", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "reps", type: "number[]" }] }, { tfOpName: "Split", category: "slice_join", inputs: [{ start: 0, name: "axis", type: "number", defaultValue: 0 }, { start: 1, name: "x", type: "tensor" }], attrs: [{ tfName: "num_split", name: "numOrSizeSplits", type: "number", defaultValue: 1 }] }, { tfOpName: "SplitV", category: "slice_join", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "numOrSizeSplits", type: "number[]" }, { start: 2, name: "axis", type: "number", defaultValue: 0 }] }, { tfOpName: "ScatterNd", category: "slice_join", inputs: [{ start: 0, name: "indices", type: "tensor" }, { start: 1, name: "values", type: "tensor" }, { start: 2, name: "shape", type: "number[]" }] }, { tfOpName: "GatherNd", category: "slice_join", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "indices", type: "tensor" }] }, { tfOpName: "SparseToDense", category: "slice_join", inputs: [{ start: 0, name: "sparseIndices", type: "tensor" }, { start: 1, name: "outputShape", type: "number[]" }, { start: 2, name: "sparseValues", type: "tensor" }, { start: 3, name: "defaultValue", type: "tensor" }], attrs: [{ tfName: "validate_indices", name: "validateIndices", type: "bool", defaultValue: false, notSupported: true }] }];
var Uv = {};
qe(Uv, { json: () => e7 });
var e7 = [{ tfOpName: "SparseFillEmptyRows", category: "sparse", inputs: [{ start: 0, name: "indices", type: "tensor" }, { start: 1, name: "values", type: "tensor" }, { start: 2, name: "denseShape", type: "tensor" }, { start: 3, name: "defaultValue", type: "tensor" }] }, { tfOpName: "SparseReshape", category: "sparse", inputs: [{ start: 0, name: "inputIndices", type: "tensor" }, { start: 1, name: "inputShape", type: "tensor" }, { start: 2, name: "newShape", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "SparseSegmentMean", category: "sparse", inputs: [{ start: 0, name: "data", type: "tensor" }, { start: 1, name: "indices", type: "tensor" }, { start: 2, name: "segmentIds", type: "tensor" }] }, { tfOpName: "SparseSegmentSum", category: "sparse", inputs: [{ start: 0, name: "data", type: "tensor" }, { start: 1, name: "indices", type: "tensor" }, { start: 2, name: "segmentIds", type: "tensor" }] }];
var jv = {};
qe(jv, { json: () => t7 });
var t7 = [{ tfOpName: "FFT", category: "spectral", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { tfOpName: "IFFT", category: "spectral", inputs: [{ start: 0, name: "x", type: "tensor" }] }, { tfOpName: "RFFT", category: "spectral", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "fft_length", type: "number", notSupported: true }] }, { tfOpName: "IRFFT", category: "spectral", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "fft_length", type: "number", notSupported: true }] }];
var Hv = {};
qe(Hv, { json: () => r7 });
var r7 = [{ tfOpName: "StringNGrams", category: "string", inputs: [{ start: 0, name: "data", type: "tensor" }, { start: 1, name: "dataSplits", type: "tensor" }], attrs: [{ tfName: "separator", name: "separator", type: "string" }, { tfName: "ngram_widths", name: "nGramWidths", type: "number[]" }, { tfName: "left_pad", name: "leftPad", type: "string" }, { tfName: "right_pad", name: "rightPad", type: "string" }, { tfName: "pad_width", name: "padWidth", type: "number" }, { tfName: "preserve_short_sequences", name: "preserveShortSequences", type: "bool" }], outputs: ["ngrams", "ngrams_splits"] }, { tfOpName: "StringSplit", category: "string", inputs: [{ start: 0, name: "input", type: "tensor" }, { start: 1, name: "delimiter", type: "tensor" }], attrs: [{ tfName: "skip_empty", name: "skipEmpty", type: "bool" }], outputs: ["indices", "values", "shape"] }, { tfOpName: "StringToHashBucketFast", category: "string", inputs: [{ start: 0, name: "input", type: "tensor" }], attrs: [{ tfName: "num_buckets", name: "numBuckets", type: "number" }] }];
var qv = {};
qe(qv, { json: () => n7 });
var n7 = [{ tfOpName: "Cast", category: "transformation", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "SrcT", name: "sdtype", type: "dtype", notSupported: true }, { tfName: "DstT", name: "dtype", type: "dtype" }] }, { tfOpName: "ExpandDims", category: "transformation", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number" }] }, { tfOpName: "MirrorPad", category: "transformation", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "padding", type: "number[]" }], attrs: [{ tfName: "mode", name: "mode", type: "string" }] }, { tfOpName: "Pad", category: "transformation", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "padding", type: "number[]" }], attrs: [{ tfName: "constant_value", name: "constantValue", type: "number", defaultValue: 0 }] }, { tfOpName: "PadV2", category: "transformation", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "padding", type: "number[]" }, { start: 2, name: "constantValue", type: "number", defaultValue: 0 }] }, { tfOpName: "Reshape", category: "transformation", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "shape", type: "number[]" }] }, { tfOpName: "Squeeze", category: "transformation", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "axis", tfDeprecatedName: "squeeze_dims", name: "axis", type: "number[]" }] }, { tfOpName: "SpaceToBatchND", category: "transformation", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "blockShape", type: "number[]" }, { start: 2, name: "paddings", type: "number[]" }] }, { tfOpName: "BatchToSpaceND", category: "transformation", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "blockShape", type: "number[]" }, { start: 2, name: "crops", type: "number[]" }] }, { tfOpName: "DepthToSpace", category: "transformation", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "block_size", name: "blockSize", type: "number" }, { tfName: "data_format", name: "dataFormat", type: "string" }] }, { tfOpName: "BroadcastTo", category: "transformation", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "shape", type: "number[]" }], attrs: [] }, { tfOpName: "BroadcastArgs", category: "transformation", inputs: [{ start: 0, name: "s0", type: "tensor" }, { start: 1, name: "s1", type: "tensor" }], attrs: [] }];
var Xx = class {
static get Instance() {
return this._instance || (this._instance = new this());
}
constructor() {
let e = [Ev, Av, Dv, $v, Rv, Fv, Ov, Pv, Mv, Lv, zv, Bv, Vv, Gv, Wv, Uv, jv, Hv, qv], t = [].concat(...e.map((n) => n.json));
this.opMappers = t.reduce((n, o) => (n[o.tfOpName] = o, n), {});
}
transformGraph(e, t = {}) {
let n = e.node, o = [], s = [], a = [], i = n.reduce((h, g) => (h[g.name] = this.mapNode(g), g.op.startsWith("Placeholder") ? o.push(h[g.name]) : g.op === "Const" ? s.push(h[g.name]) : (g.input == null || g.input.length === 0) && a.push(h[g.name]), h), {}), l = [], u = [], c = {}, p = {};
t != null && (c = this.mapSignatureEntries(t.inputs), p = this.mapSignatureEntries(t.outputs));
let m = Object.keys(i);
m.forEach((h) => {
let g = i[h];
g.inputNames.forEach((x, y) => {
let [w, , _] = js(x), C = i[w];
if (C.outputs != null) {
let A = C.outputs.indexOf(_);
if (A !== -1) {
let D = `${w}:${A}`;
g.inputNames[y] = D;
}
}
g.inputs.push(C), C.children.push(g);
});
}), Object.keys(p).length === 0 ? m.forEach((h) => {
let g = i[h];
g.children.length === 0 && u.push(g);
}) : Object.keys(p).forEach((h) => {
let [g] = js(h), x = i[g];
x != null && (x.signatureKey = p[h], u.push(x));
}), Object.keys(c).length > 0 ? Object.keys(c).forEach((h) => {
let [g] = js(h), x = i[g];
x && (x.signatureKey = c[h], l.push(x));
}) : l = o;
let f = {};
e.library != null && e.library.function != null && (f = e.library.function.reduce((h, g) => (h[g.signature.name] = this.mapFunction(g), h), {}));
let d = { nodes: i, inputs: l, outputs: u, weights: s, placeholders: o, signature: t, functions: f };
return a.length > 0 && (d.initNodes = a), d;
}
mapSignatureEntries(e) {
return Object.keys(e || {}).reduce((t, n) => (t[e[n].name] = n, t), {});
}
mapNode(e) {
let t = qx(e.op) || this.opMappers[e.op] || {};
e.attr == null && (e.attr = {});
let n = { name: e.name, op: e.op, category: t.category, inputNames: (e.input || []).map((o) => o.startsWith("^") ? o.substr(1) : o), inputs: [], children: [], inputParams: {}, attrParams: {}, rawAttrs: e.attr, outputs: t.outputs };
return t.inputs != null && (n.inputParams = t.inputs.reduce((o, s) => (o[s.name] = { type: s.type, inputIndexStart: s.start, inputIndexEnd: s.end }, o), {})), t.attrs != null && (n.attrParams = t.attrs.reduce((o, s) => {
let a = s.type, i;
switch (s.type) {
case "string":
i = Yx(e.attr, s.tfName, s.defaultValue), i === void 0 && !!s.tfDeprecatedName && (i = Yx(e.attr, s.tfDeprecatedName, s.defaultValue));
break;
case "string[]":
i = ny(e.attr, s.tfName, s.defaultValue), i === void 0 && !!s.tfDeprecatedName && (i = ny(e.attr, s.tfDeprecatedName, s.defaultValue));
break;
case "number":
i = Jx(e.attr, s.tfName, s.defaultValue || 0), i === void 0 && !!s.tfDeprecatedName && (i = Jx(e.attr, s.tfDeprecatedName, s.defaultValue));
break;
case "number[]":
i = ry(e.attr, s.tfName, s.defaultValue), i === void 0 && !!s.tfDeprecatedName && (i = ry(e.attr, s.tfDeprecatedName, s.defaultValue));
break;
case "bool":
i = Zx(e.attr, s.tfName, s.defaultValue), i === void 0 && !!s.tfDeprecatedName && (i = Zx(e.attr, s.tfDeprecatedName, s.defaultValue));
break;
case "bool[]":
i = sy(e.attr, s.tfName, s.defaultValue), i === void 0 && !!s.tfDeprecatedName && (i = sy(e.attr, s.tfDeprecatedName, s.defaultValue));
break;
case "shape":
i = ty(e.attr, s.tfName, s.defaultValue), i === void 0 && !!s.tfDeprecatedName && (i = ty(e.attr, s.tfDeprecatedName, s.defaultValue));
break;
case "shape[]":
i = oy(e.attr, s.tfName, s.defaultValue), i === void 0 && !!s.tfDeprecatedName && (i = oy(e.attr, s.tfDeprecatedName, s.defaultValue));
break;
case "dtype":
i = Qx(e.attr, s.tfName, s.defaultValue), i === void 0 && !!s.tfDeprecatedName && (i = Qx(e.attr, s.tfDeprecatedName, s.defaultValue));
break;
case "dtype[]":
i = ey(e.attr, s.tfName, s.defaultValue), i === void 0 && !!s.tfDeprecatedName && (i = ey(e.attr, s.tfDeprecatedName, s.defaultValue));
break;
case "func":
i = JA(e.attr, s.tfName, s.defaultValue), i === void 0 && !!s.tfDeprecatedName && (i = JA(e.attr, s.tfDeprecatedName, s.defaultValue));
break;
case "tensor":
case "tensors":
break;
default:
throw new Error(`Unsupported param type: ${s.type} for op: ${e.op}`);
}
return o[s.name] = { value: i, type: a }, o;
}, {})), n;
}
mapFunction(e) {
let t = e.nodeDef, n = [], o = [], s = {};
t != null && (s = t.reduce((p, m) => (p[m.name] = this.mapNode(m), m.op === "Const" && o.push(p[m.name]), p), {}));
let a = [], i = [];
e.signature.inputArg.forEach((p) => {
let [m] = js(p.name), f = { name: m, op: "Placeholder", inputs: [], inputNames: [], category: "graph", inputParams: {}, attrParams: { dtype: { value: Kv(p.type), type: "dtype" } }, children: [] };
f.signatureKey = p.name, a.push(f), s[m] = f;
}), Object.keys(s).forEach((p) => {
let m = s[p];
m.inputNames.forEach((f, d) => {
let [h, , g] = js(f), x = s[h];
if (x.outputs != null) {
let y = x.outputs.indexOf(g);
if (y !== -1) {
let w = `${h}:${y}`;
m.inputNames[d] = w;
}
}
m.inputs.push(x), x.children.push(m);
});
});
let u = e.ret;
e.signature.outputArg.forEach((p) => {
let [m, f] = js(u[p.name]), d = s[m];
d != null && (d.defaultOutput = f, i.push(d));
});
let c = this.mapArgsToSignature(e);
return { nodes: s, inputs: a, outputs: i, weights: o, placeholders: n, signature: c };
}
mapArgsToSignature(e) {
return { methodName: e.signature.name, inputs: e.signature.inputArg.reduce((t, n) => (t[n.name] = this.mapArgToTensorInfo(n), t), {}), outputs: e.signature.outputArg.reduce((t, n) => (t[n.name] = this.mapArgToTensorInfo(n, e.ret), t), {}) };
}
mapArgToTensorInfo(e, t) {
let n = e.name;
return t != null && (n = t[n]), { name: n, dtype: e.type };
}
};
function o7(r) {
let e = U().global;
if (typeof e.atob != "undefined")
return e.atob(r);
if (typeof Buffer != "undefined")
return new Buffer(r, "base64").toString();
throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()");
}
function ZA(r, e) {
let t = Array.isArray(r) ? String.fromCharCode.apply(null, r) : o7(r);
return e ? t : t.toLowerCase();
}
function Yx(r, e, t, n = false) {
let o = r[e];
return o != null ? ZA(o.s, n) : t;
}
function Zx(r, e, t) {
let n = r[e];
return n ? n.b : t;
}
function Jx(r, e, t) {
let n = r[e] || {}, o = n.i != null ? n.i : n.f != null ? n.f : t;
return typeof o == "number" ? o : parseInt(o, 10);
}
function Kv(r) {
switch (typeof r == "string" && (r = ko[r]), r) {
case ko.DT_FLOAT:
return "float32";
case ko.DT_INT32:
case ko.DT_INT64:
case ko.DT_INT8:
case ko.DT_UINT8:
return "int32";
case ko.DT_BOOL:
return "bool";
case ko.DT_DOUBLE:
return "float32";
case ko.DT_STRING:
return "string";
default:
return null;
}
}
function JA(r, e, t) {
let n = r[e];
return n && n.func ? n.func.name : t;
}
function Qx(r, e, t) {
let n = r[e];
return n && n.type ? Kv(n.type) : t;
}
function ey(r, e, t) {
let n = r[e];
return n && n.list && n.list.type ? n.list.type.map((o) => Kv(o)) : t;
}
function QA(r) {
if (!r.unknownRank)
return r.dim != null ? r.dim.map((e) => typeof e.size == "number" ? e.size : parseInt(e.size, 10)) : [];
}
function ty(r, e, t) {
let n = r[e];
return n && n.shape ? QA(n.shape) : t;
}
function ry(r, e, t) {
let n = r[e];
return n ? ((n.list.f && n.list.f.length ? n.list.f : n.list.i) || []).map((o) => typeof o == "number" ? o : parseInt(o, 10)) : t;
}
function ny(r, e, t, n = false) {
let o = r[e];
return o && o.list && o.list.s ? o.list.s.map((s) => ZA(s, n)) : t;
}
function oy(r, e, t) {
let n = r[e];
return n && n.list && n.list.shape ? n.list.shape.map((o) => QA(o)) : t;
}
function sy(r, e, t) {
let n = r[e];
return n && n.list && n.list.b ? n.list.b : t;
}
var Xv = class {
constructor(e, t, n) {
this.node = e, this.tensorMap = t, this.context = n, this.inputs = [], this.attrs = {}, this.inputs = e.inputNames.map((o) => this.getInput(o)), e.rawAttrs != null && (this.attrs = Object.keys(e.rawAttrs).reduce((o, s) => (o[s] = this.getAttr(s), o), {}));
}
getInput(e) {
return br(e, this.tensorMap, this.context);
}
getAttr(e, t) {
let n = this.node.rawAttrs[e];
if (n.tensor != null)
return br(e, this.tensorMap, this.context);
if (n.i != null || n.f != null)
return Jx(this.node.rawAttrs, e, t);
if (n.s != null)
return Yx(this.node.rawAttrs, e, t);
if (n.b != null)
return Zx(this.node.rawAttrs, e, t);
if (n.shape != null)
return ty(this.node.rawAttrs, e, t);
if (n.type != null)
return Qx(this.node.rawAttrs, e, t);
if (n.list != null) {
if (n.list.i != null || n.list.f != null)
return ry(this.node.rawAttrs, e, t);
if (n.list.s != null)
return ny(this.node.rawAttrs, e, t);
if (n.list.shape != null)
return oy(this.node.rawAttrs, e, t);
if (n.list.b != null)
return sy(this.node.rawAttrs, e, t);
if (n.list.type != null)
return ey(this.node.rawAttrs, e, t);
}
return t;
}
};
var eD = (r, e, t) => {
switch (r.op) {
case "BiasAdd":
case "AddV2":
case "Add":
return [Z(v("a", r, e, t), v("b", r, e, t))];
case "AddN":
return [F_(v("tensors", r, e, t))];
case "FloorMod":
case "Mod":
return [Mf(v("a", r, e, t), v("b", r, e, t))];
case "Mul":
return [O(v("a", r, e, t), v("b", r, e, t))];
case "RealDiv":
case "Div":
return [ce(v("a", r, e, t), v("b", r, e, t))];
case "DivNoNan":
return [Tf(v("a", r, e, t), v("b", r, e, t))];
case "FloorDiv":
return [bu(v("a", r, e, t), v("b", r, e, t))];
case "Sub":
return [le(v("a", r, e, t), v("b", r, e, t))];
case "Minimum":
return [Ps(v("a", r, e, t), v("b", r, e, t))];
case "Maximum":
return [sn(v("a", r, e, t), v("b", r, e, t))];
case "Pow":
return [Hr(v("a", r, e, t), v("b", r, e, t))];
case "SquaredDifference":
return [Bu(v("a", r, e, t), v("b", r, e, t))];
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var tD = (r, e, t) => {
switch (r.op) {
case "Abs":
case "ComplexAbs":
return [Ct(v("x", r, e, t))];
case "Acos":
return [df(v("x", r, e, t))];
case "Acosh":
return [hf(v("x", r, e, t))];
case "Asin":
return [xf(v("x", r, e, t))];
case "Asinh":
return [yf(v("x", r, e, t))];
case "Atan":
return [bf(v("x", r, e, t))];
case "Atan2":
return [wf(v("x", r, e, t), v("y", r, e, t))];
case "Atanh":
return [_f(v("x", r, e, t))];
case "Ceil":
return [Cf(v("x", r, e, t))];
case "Complex":
return [Pn(v("real", r, e, t), v("imag", r, e, t))];
case "Cos":
return [Da(v("x", r, e, t))];
case "Cosh":
return [Iu(v("x", r, e, t))];
case "Elu":
return [Rs(v("x", r, e, t))];
case "Erf":
return [Ef(v("x", r, e, t))];
case "Exp":
return [Kt(v("x", r, e, t))];
case "Expm1":
return [Af(v("x", r, e, t))];
case "Floor":
return [Os(v("x", r, e, t))];
case "Log":
return [xr(v("x", r, e, t))];
case "Log1p":
return [Ra(v("x", r, e, t))];
case "Imag":
return [Nu(v("x", r, e, t))];
case "Neg":
return [He(v("x", r, e, t))];
case "Reciprocal":
return [Lf(v("x", r, e, t))];
case "Real":
return [Dl(v("x", r, e, t))];
case "Relu":
return [Ir(v("x", r, e, t))];
case "Round":
return [Fu(v("x", r, e, t))];
case "Selu":
return [Pu(v("x", r, e, t))];
case "Sigmoid":
return [zr(v("x", r, e, t))];
case "Sin":
return [Mu(v("x", r, e, t))];
case "Sign":
return [Bf(v("x", r, e, t))];
case "Sinh":
return [Lu(v("x", r, e, t))];
case "Softplus":
return [co(v("x", r, e, t))];
case "Sqrt":
return [bt(v("x", r, e, t))];
case "Square":
return [Ve(v("x", r, e, t))];
case "Tanh":
return [Ds(v("x", r, e, t))];
case "Tan":
return [Uf(v("x", r, e, t))];
case "ClipByValue":
return [gr(v("x", r, e, t), v("clipValueMin", r, e, t), v("clipValueMax", r, e, t))];
case "Relu6":
return [Ru(v("x", r, e, t))];
case "Rsqrt":
return [Ou(br(r.inputNames[0], e, t))];
case "Prod":
return [Du(v("x", r, e, t), v("axes", r, e, t))];
case "LeakyRelu":
return [$a(v("x", r, e, t), v("alpha", r, e, t))];
case "Prelu":
return [Ma(v("x", r, e, t), v("alpha", r, e, t))];
case "IsNan":
return [Df(br(r.inputNames[0], e, t))];
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
function zn(r, e, t = "") {
if (!(typeof r == "number" || typeof e == "number")) {
b.assert(r.length === e.length, () => t + ` Shapes ${r} and ${e} must match`);
for (let n = 0; n < r.length; n++) {
let o = r[n], s = e[n];
b.assert(o < 0 || s < 0 || o === s, () => t + ` Shapes ${r} and ${e} must match`);
}
}
}
function rD(r) {
return !(typeof r == "number" || r.some((e) => e < 0));
}
function gm(r, e, t) {
let n = iy(r, t), o = !rD(n);
if (o && e.length === 0)
throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${n}`);
if (o && e.forEach((s) => {
n = iy(s.shape, n);
}), !rD(n))
throw new Error(`Non-fully-defined elementShape: ${n}`);
return n;
}
function iy(r, e) {
if (typeof r == "number")
return e;
if (typeof e == "number")
return r;
if (r.length !== e.length)
throw new Error(`Incompatible ranks during merge: ${r} vs. ${e}`);
let t = [];
for (let n = 0; n < r.length; ++n) {
let o = r[n], s = e[n];
if (o >= 0 && s >= 0 && o !== s)
throw new Error(`Incompatible shape during merge: ${r} vs. ${e}`);
t[n] = o >= 0 ? o : s;
}
return t;
}
var Yv = class {
constructor(e, t, n, o, s, a, i) {
this.name = e, this.dtype = t, this.maxSize = n, this.elementShape = o, this.identicalElementShapes = s, this.dynamicSize = a, this.clearAfterRead = i, this.tensors = [], this.closed_ = false, this.idTensor = pe(0), Ft(this.idTensor);
}
get id() {
return this.idTensor.id;
}
get closed() {
return this.closed_;
}
clearAndClose(e) {
this.tensors.forEach((t) => {
(e == null || !e.has(t.tensor.id)) && t.tensor.dispose();
}), this.tensors = [], this.closed_ = true, this.idTensor.dispose();
}
size() {
return this.tensors.length;
}
read(e) {
if (this.closed_)
throw new Error(`TensorArray ${this.name} has already been closed.`);
if (e < 0 || e >= this.size())
throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);
let t = this.tensors[e];
if (t.cleared)
throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);
return this.clearAfterRead && (t.cleared = true), t.read = true, t.tensor;
}
readMany(e) {
return e.map((t) => this.read(t));
}
write(e, t) {
if (this.closed_)
throw new Error(`TensorArray ${this.name} has already been closed.`);
if (e < 0 || !this.dynamicSize && e >= this.maxSize)
throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);
let n = this.tensors[e] || {};
if (t.dtype !== this.dtype)
throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);
if (this.size() === 0 && (this.elementShape == null || this.elementShape.length === 0) && (this.elementShape = t.shape), zn(this.elementShape, t.shape, `TensorArray ${this.name}: Could not write to TensorArray index ${e}.`), n.read)
throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);
if (n.written)
throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);
n.tensor = t, Ft(t), n.written = true, this.tensors[e] = n;
}
writeMany(e, t) {
if (e.length !== t.length)
throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);
e.forEach((n, o) => this.write(n, t[o]));
}
gather(e, t) {
if (!!t && t !== this.dtype)
throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);
if (e)
e = e.slice(0, this.size());
else {
e = [];
for (let o = 0; o < this.size(); o++)
e.push(o);
}
if (e.length === 0)
return Dr([], [0].concat(this.elementShape));
let n = this.readMany(e);
return zn(this.elementShape, n[0].shape, "TensorArray shape mismatch: "), Xt(n, 0);
}
concat(e) {
if (!!e && e !== this.dtype)
throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);
if (this.size() === 0)
return Dr([], [0].concat(this.elementShape));
let t = [];
for (let o = 0; o < this.size(); o++)
t.push(o);
let n = this.readMany(t);
return zn(this.elementShape, n[0].shape, `TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`), tt(n, 0);
}
scatter(e, t) {
if (t.dtype !== this.dtype)
throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);
if (e.length !== t.shape[0])
throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);
let n = Math.max(...e);
if (!this.dynamicSize && n >= this.maxSize)
throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);
this.writeMany(e, yr(t, 0));
}
split(e, t) {
if (t.dtype !== this.dtype)
throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);
let n = 0, o = e.map((l) => (n += l, n));
if (n !== t.shape[0])
throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${n}, and tensor's shape is: ${t.shape}`);
if (!this.dynamicSize && e.length !== this.maxSize)
throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);
let s = n === 0 ? 0 : t.size / n, a = [];
V(() => {
t = F(t, [1, n, s]);
for (let l = 0; l < e.length; ++l) {
let u = l === 0 ? 0 : o[l - 1], c = [0, u, 0], p = [1, e[l], s];
a[l] = F(Oe(t, c, p), this.elementShape);
}
return a;
});
let i = [];
for (let l = 0; l < e.length; l++)
i[l] = l;
this.writeMany(i, a);
}
};
var uc = class {
constructor(e, t, n, o = -1) {
this.tensors = e, this.elementShape = t, this.elementDtype = n, e != null && e.forEach((s) => {
if (n !== s.dtype)
throw new Error(`Invalid data types; op elements ${n}, but list elements ${s.dtype}`);
zn(t, s.shape, "TensorList shape mismatch: "), Ft(s);
}), this.idTensor = pe(0), this.maxNumElements = o, Ft(this.idTensor);
}
get id() {
return this.idTensor.id;
}
copy() {
return new uc([...this.tensors], this.elementShape, this.elementDtype);
}
clearAndClose(e) {
this.tensors.forEach((t) => {
(e == null || !e.has(t.id)) && t.dispose();
}), this.tensors.length = 0, this.idTensor.dispose();
}
size() {
return this.tensors.length;
}
stack(e, t, n = -1) {
if (t !== this.elementDtype)
throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);
if (n !== -1 && this.tensors.length !== n)
throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);
zn(e, this.elementShape, "TensorList shape mismatch: ");
let o = gm(this.elementShape, this.tensors, e);
return V(() => {
let s = this.tensors.map((a) => F(a, o));
return Xt(s, 0);
});
}
popBack(e, t) {
if (t !== this.elementDtype)
throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);
if (this.size() === 0)
throw new Error("Trying to pop from an empty list.");
let n = gm(this.elementShape, this.tensors, e), o = this.tensors.pop();
return zn(o.shape, e, "TensorList shape mismatch: "), F(o, n);
}
pushBack(e) {
if (e.dtype !== this.elementDtype)
throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);
if (zn(e.shape, this.elementShape, "TensorList shape mismatch: "), this.maxNumElements === this.size())
throw new Error("Trying to push element into a full list.");
Ft(e), this.tensors.push(e);
}
resize(e) {
if (e < 0)
throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);
if (this.maxNumElements !== -1 && e > this.maxNumElements)
throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);
this.tensors.length = e;
}
getItem(e, t, n) {
if (n !== this.elementDtype)
throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);
if (e < 0 || e > this.tensors.length)
throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);
if (this.tensors[e] == null)
throw new Error(`element at index ${e} is null.`);
zn(this.tensors[e].shape, t, "TensorList shape mismatch: ");
let o = gm(this.elementShape, this.tensors, t);
return F(this.tensors[e], o);
}
setItem(e, t) {
if (t.dtype !== this.elementDtype)
throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);
if (e < 0 || this.maxNumElements !== -1 && e >= this.maxNumElements)
throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);
zn(this.elementShape, t.shape, "TensorList shape mismatch: "), Ft(t), this.tensors[e] = t;
}
gather(e, t, n) {
if (t !== this.elementDtype)
throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);
zn(this.elementShape, n, "TensorList shape mismatch: "), e = e.slice(0, this.size());
let o = gm(this.elementShape, this.tensors, n);
return e.length === 0 ? Dr([], [0].concat(o)) : V(() => {
let s = e.map((a) => F(this.tensors[a], o));
return Xt(s, 0);
});
}
concat(e, t) {
if (!!e && e !== this.elementDtype)
throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);
zn(this.elementShape, t, "TensorList shape mismatch: ");
let n = gm(this.elementShape, this.tensors, t);
return this.size() === 0 ? Dr([], [0].concat(n)) : V(() => {
let o = this.tensors.map((s) => F(s, n));
return tt(o, 0);
});
}
};
function nD(r, e, t) {
let n = r.dtype;
if (r.shape.length < 1)
throw new Error(`Tensor must be at least a vector, but saw shape: ${r.shape}`);
if (r.dtype !== t)
throw new Error(`Invalid data types; op elements ${r.dtype}, but list elements ${t}`);
let o = r.shape.slice(1);
zn(o, e, "TensorList shape mismatch: ");
let s = yr(r);
return new uc(s, e, n);
}
function oD(r, e, t) {
return new uc([], r, e, t);
}
function sD(r, e, t, n) {
if (e.length !== r.shape[0])
throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${r.shape[0]}`);
let o = Math.max(...e);
if (n != null && n !== -1 && o >= n)
throw new Error(`Max index must be < array size (${o} vs. ${n})`);
let s = new uc([], t, r.dtype, n), a = yr(r, 0);
return e.forEach((i, l) => {
s.setItem(i, a[l]);
}), s;
}
function iD(r, e, t) {
let n = 0, o = e.map((c) => (n += c, n));
if (n !== r.shape[0])
throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${n}, and tensor's shape is: ${r.shape}`);
let s = r.shape.slice(1), a = iy(s, t), i = n === 0 ? 0 : r.size / n, l = V(() => {
let c = [];
r = F(r, [1, n, i]);
for (let p = 0; p < e.length; ++p) {
let m = p === 0 ? 0 : o[p - 1], f = [0, m, 0], d = [1, e[p], i];
c[p] = F(Oe(r, f, d), a);
}
return r.dispose(), c;
}), u = new uc([], t, r.dtype, e.length);
for (let c = 0; c < l.length; c++)
u.setItem(c, l[c]);
return u;
}
var aD = async (r, e, t) => {
switch (r.op) {
case "If":
case "StatelessIf": {
let n = v("thenBranch", r, e, t), o = v("elseBranch", r, e, t), s = v("cond", r, e, t), a = v("args", r, e, t);
return (await s.data())[0] ? t.functionMap[n].executeFunctionAsync(a, t.tensorArrayMap, t.tensorListMap) : t.functionMap[o].executeFunctionAsync(a, t.tensorArrayMap, t.tensorListMap);
}
case "While":
case "StatelessWhile": {
let n = v("body", r, e, t), o = v("cond", r, e, t), s = v("args", r, e, t), a = await t.functionMap[o].executeFunctionAsync(s, t.tensorArrayMap, t.tensorListMap), i = s.map((c) => c.id), l = await a[0].data();
a.forEach((c) => {
!c.kept && i.indexOf(c.id) === -1 && c.dispose();
});
let u = s;
for (; l[0]; ) {
let c = u;
u = await t.functionMap[n].executeFunctionAsync(u, t.tensorArrayMap, t.tensorListMap);
let p = u.map((f) => f.id);
c.forEach((f) => {
!f.kept && i.indexOf(f.id) === -1 && p.indexOf(f.id) === -1 && f.dispose();
});
let m = await t.functionMap[o].executeFunctionAsync(u, t.tensorArrayMap, t.tensorListMap);
l = await m[0].data(), m.forEach((f) => {
!f.kept && i.indexOf(f.id) === -1 && p.indexOf(f.id) === -1 && f.dispose();
});
}
return u;
}
case "LoopCond": {
let n = v("pred", r, e, t);
return [Hs(n)];
}
case "Switch": {
let n = v("pred", r, e, t), o = v("data", r, e, t);
return o.kept || (o = Hs(o)), (await n.data())[0] ? [void 0, o] : [o, void 0];
}
case "Merge": {
let n = r.inputNames.find((o) => br(o, e, t) !== void 0);
if (n) {
let o = br(n, e, t);
return [Hs(o)];
}
return;
}
case "Enter": {
let n = v("frameName", r, e, t), o = v("tensor", r, e, t);
return t.enterFrame(n), [Hs(o)];
}
case "Exit": {
let n = v("tensor", r, e, t);
return t.exitFrame(), [Hs(n)];
}
case "NextIteration": {
let n = v("tensor", r, e, t);
return t.nextIteration(), [Hs(n)];
}
case "TensorArrayV3": {
let n = v("size", r, e, t), o = v("dtype", r, e, t), s = v("elementShape", r, e, t), a = v("dynamicSize", r, e, t), i = v("clearAfterRead", r, e, t), l = v("identicalElementShapes", r, e, t), u = v("name", r, e, t), c = new Yv(u, o, n, s, l, a, i);
return t.addTensorArray(c), [c.idTensor, pe(1)];
}
case "TensorArrayWriteV3": {
let n = v("tensorArrayId", r, e, t), o = v("index", r, e, t), s = v("tensor", r, e, t), a = t.getTensorArray(n.id);
return a.write(o, s), [a.idTensor];
}
case "TensorArrayReadV3": {
let n = v("tensorArrayId", r, e, t), o = v("index", r, e, t);
return [t.getTensorArray(n.id).read(o)];
}
case "TensorArrayGatherV3": {
let n = v("tensorArrayId", r, e, t), o = v("indices", r, e, t), s = v("dtype", r, e, t);
return [t.getTensorArray(n.id).gather(o, s)];
}
case "TensorArrayScatterV3": {
let n = v("tensorArrayId", r, e, t), o = v("indices", r, e, t), s = v("tensor", r, e, t), a = t.getTensorArray(n.id);
return a.scatter(o, s), [a.idTensor];
}
case "TensorArrayConcatV3": {
let n = v("tensorArrayId", r, e, t), o = t.getTensorArray(n.id), s = v("dtype", r, e, t);
return [o.concat(s)];
}
case "TensorArraySplitV3": {
let n = v("tensorArrayId", r, e, t), o = v("tensor", r, e, t), s = v("lengths", r, e, t), a = t.getTensorArray(n.id);
return a.split(s, o), [a.idTensor];
}
case "TensorArraySizeV3": {
let n = v("tensorArrayId", r, e, t), o = t.getTensorArray(n.id);
return [pe(o.size(), "int32")];
}
case "TensorArrayCloseV3": {
let n = v("tensorArrayId", r, e, t), o = t.getTensorArray(n.id);
return o.clearAndClose(), [o.idTensor];
}
case "TensorListSetItem": {
let n = v("tensorListId", r, e, t), o = v("index", r, e, t), s = v("tensor", r, e, t), a = t.getTensorList(n.id);
return a.setItem(o, s), [a.idTensor];
}
case "TensorListGetItem": {
let n = v("tensorListId", r, e, t), o = v("index", r, e, t), s = v("elementShape", r, e, t), a = v("elementDType", r, e, t);
return [t.getTensorList(n.id).getItem(o, s, a)];
}
case "TensorListScatterV2":
case "TensorListScatter": {
let n = v("indices", r, e, t), o = v("tensor", r, e, t), s = v("elementShape", r, e, t), a = v("numElements", r, e, t), i = sD(o, n, s, a);
return t.addTensorList(i), [i.idTensor];
}
case "TensorListReserve":
case "EmptyTensorList": {
let n = v("elementShape", r, e, t), o = v("elementDType", r, e, t), s;
r.op === "TensorListReserve" ? s = "numElements" : s = "maxNumElements";
let a = v(s, r, e, t), i = oD(n, o, a);
return t.addTensorList(i), [i.idTensor];
}
case "TensorListGather": {
let n = v("tensorListId", r, e, t), o = v("indices", r, e, t), s = v("elementShape", r, e, t), a = v("elementDType", r, e, t);
return [t.getTensorList(n.id).gather(o, a, s)];
}
case "TensorListStack": {
let n = v("tensorListId", r, e, t), o = v("elementShape", r, e, t), s = v("elementDType", r, e, t), a = v("numElements", r, e, t);
return [t.getTensorList(n.id).stack(o, s, a)];
}
case "TensorListFromTensor": {
let n = v("tensor", r, e, t), o = v("elementShape", r, e, t), s = v("elementDType", r, e, t), a = nD(n, o, s);
return t.addTensorList(a), [a.idTensor];
}
case "TensorListConcat": {
let n = v("tensorListId", r, e, t), o = t.getTensorList(n.id), s = v("dtype", r, e, t), a = v("elementShape", r, e, t);
return [o.concat(s, a)];
}
case "TensorListPushBack": {
let n = v("tensorListId", r, e, t), o = v("tensor", r, e, t), s = t.getTensorList(n.id);
return s.pushBack(o), [s.idTensor];
}
case "TensorListPopBack": {
let n = v("tensorListId", r, e, t), o = v("elementShape", r, e, t), s = v("elementDType", r, e, t);
return [t.getTensorList(n.id).popBack(o, s)];
}
case "TensorListSplit": {
let n = v("tensor", r, e, t), o = v("elementShape", r, e, t), s = v("lengths", r, e, t), a = iD(n, s, o);
return t.addTensorList(a), [a.idTensor];
}
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
function lD(r, e, t) {
let [n, o] = v("fusedOps", r, e, t), s = n === "biasadd", a = !s, i = o === "prelu", l = n === "fusedbatchnorm", u = v("numArgs", r, e, t);
if (s) {
if (i && u !== 2)
throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");
if (!i && s && u !== 1)
throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.");
}
if (l)
throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");
let c = v("strides", r, e, t), p = yh(r, e, t), m = v("dataFormat", r, e, t).toUpperCase(), f = v("dilations", r, e, t), [d, h] = v("args", r, e, t);
a && (h = d, d = void 0);
let g = v("leakyreluAlpha", r, e, t);
return { stride: c, pad: p, dataFormat: m, dilations: f, biasArg: d, preluArg: h, activationFunc: o, leakyreluAlpha: g };
}
var uD = (r, e, t) => {
switch (r.op) {
case "Conv1D": {
let n = v("stride", r, e, t), o = v("pad", r, e, t), s = v("dataFormat", r, e, t).toUpperCase(), a = v("dilation", r, e, t);
return [vu(v("x", r, e, t), v("filter", r, e, t), n, o, s, a)];
}
case "Conv2D": {
let n = v("strides", r, e, t), o = yh(r, e, t), s = v("dataFormat", r, e, t).toUpperCase(), a = v("dilations", r, e, t);
return [nn(v("x", r, e, t), v("filter", r, e, t), [n[1], n[2]], o, s, [a[1], a[2]])];
}
case "_FusedConv2D": {
let { stride: n, pad: o, dataFormat: s, dilations: a, biasArg: i, preluArg: l, activationFunc: u, leakyreluAlpha: c } = lD(r, e, t);
return [fo.conv2d({ x: v("x", r, e, t), filter: v("filter", r, e, t), strides: [n[1], n[2]], pad: o, dataFormat: s, dilations: [a[1], a[2]], bias: i, activation: u, preluActivationWeights: l, leakyreluAlpha: c })];
}
case "FusedDepthwiseConv2dNative": {
let { stride: n, pad: o, dataFormat: s, dilations: a, biasArg: i, preluArg: l, activationFunc: u, leakyreluAlpha: c } = lD(r, e, t);
return [fo.depthwiseConv2d({ x: v("x", r, e, t), filter: v("filter", r, e, t), strides: [n[1], n[2]], pad: o, dataFormat: s, dilations: [a[1], a[2]], bias: i, activation: u, preluActivationWeights: l, leakyreluAlpha: c })];
}
case "Conv2DBackpropInput":
case "Conv2dTranspose": {
let n = v("outputShape", r, e, t), o = v("strides", r, e, t), s = yh(r, e, t);
return [Cu(v("x", r, e, t), v("filter", r, e, t), n, [o[1], o[2]], s)];
}
case "DepthwiseConv2dNative":
case "DepthwiseConv2d": {
let n = v("strides", r, e, t), o = yh(r, e, t), s = v("dilations", r, e, t), a = v("dataFormat", r, e, t).toUpperCase();
return [$s(v("input", r, e, t), v("filter", r, e, t), [n[1], n[2]], o, a, [s[1], s[2]])];
}
case "Conv3D": {
let n = v("strides", r, e, t), o = v("pad", r, e, t), s = v("dataFormat", r, e, t).toUpperCase(), a = v("dilations", r, e, t);
return [If(v("x", r, e, t), v("filter", r, e, t), [n[1], n[2], n[3]], o, s, [a[1], a[2], a[3]])];
}
case "AvgPool": {
let n = v("strides", r, e, t), o = v("pad", r, e, t), s = v("kernelSize", r, e, t);
return [Ta(v("x", r, e, t), [s[1], s[2]], [n[1], n[2]], o)];
}
case "MaxPool": {
let n = v("strides", r, e, t), o = v("pad", r, e, t), s = v("kernelSize", r, e, t);
return [Oa(v("x", r, e, t), [s[1], s[2]], [n[1], n[2]], o)];
}
case "MaxPoolWithArgmax": {
let n = v("strides", r, e, t), o = v("pad", r, e, t), s = v("kernelSize", r, e, t), a = v("includeBatchInIndex", r, e, t), { result: i, indexes: l } = ok(v("x", r, e, t), [s[1], s[2]], [n[1], n[2]], o, a);
return [i, l];
}
case "AvgPool3D": {
let n = v("strides", r, e, t), o = v("pad", r, e, t), s = v("kernelSize", r, e, t);
return [kf(v("x", r, e, t), [s[1], s[2], s[3]], [n[1], n[2], n[3]], o)];
}
case "MaxPool3D": {
let n = v("strides", r, e, t), o = v("pad", r, e, t), s = v("kernelSize", r, e, t);
return [Of(v("x", r, e, t), [s[1], s[2], s[3]], [n[1], n[2], n[3]], o)];
}
case "Dilation2D": {
let n = v("strides", r, e, t), o = v("pad", r, e, t), s = v("dilations", r, e, t), a = n[1], i = n[2], l = s[1], u = s[2];
return [Nf(v("x", r, e, t), v("filter", r, e, t), [a, i], o, [l, u], "NHWC")];
}
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var cD = (r, e, t) => {
switch (r.op) {
case "Fill": {
let n = v("shape", r, e, t), o = v("dtype", r, e, t), s = v("value", r, e, t);
return [Fs(n, s, o)];
}
case "LinSpace": {
let n = v("start", r, e, t), o = v("stop", r, e, t), s = v("num", r, e, t);
return [J_(n, o, s)];
}
case "Multinomial": {
let n = v("logits", r, e, t), o = v("numSamples", r, e, t), s = v("seed", r, e, t);
return [sk(n, o, s)];
}
case "OneHot": {
let n = v("indices", r, e, t), o = v("depth", r, e, t), s = v("onValue", r, e, t), a = v("offValue", r, e, t);
return [Ts(n, o, s, a)];
}
case "Ones":
return [or(v("shape", r, e, t), v("dtype", r, e, t))];
case "OnesLike":
return [fr(v("x", r, e, t))];
case "RandomUniform":
return [Ms(v("shape", r, e, t), v("minval", r, e, t), v("maxval", r, e, t), v("dtype", r, e, t))];
case "Range": {
let n = v("start", r, e, t), o = v("stop", r, e, t), s = v("step", r, e, t);
return [La(n, o, s, v("dtype", r, e, t))];
}
case "TruncatedNormal": {
let n = v("shape", r, e, t), o = v("mean", r, e, t), s = v("stdDev", r, e, t), a = v("seed", r, e, t);
return [Vu(n, o, s, v("dtype", r, e, t), a)];
}
case "Zeros":
return [yt(v("shape", r, e, t), v("dtype", r, e, t))];
case "ZerosLike":
return [Se(v("x", r, e, t))];
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
function Zv(r, e, t) {
let n = v("boxes", r, e, t), o = v("scores", r, e, t), s = v("maxOutputSize", r, e, t), a = v("iouThreshold", r, e, t), i = v("scoreThreshold", r, e, t), l = v("softNmsSigma", r, e, t);
return { boxes: n, scores: o, maxOutputSize: s, iouThreshold: a, scoreThreshold: i, softNmsSigma: l };
}
var pD = async (r, e, t) => {
switch (r.op) {
case "NonMaxSuppressionV5": {
let { boxes: n, scores: o, maxOutputSize: s, iouThreshold: a, scoreThreshold: i, softNmsSigma: l } = Zv(r, e, t), u = await Cn.nonMaxSuppressionWithScoreAsync(n, o, s, a, i, l);
return [u.selectedIndices, u.selectedScores];
}
case "NonMaxSuppressionV4": {
let { boxes: n, scores: o, maxOutputSize: s, iouThreshold: a, scoreThreshold: i } = Zv(r, e, t), l = v("padToMaxOutputSize", r, e, t), u = await Cn.nonMaxSuppressionPaddedAsync(n, o, s, a, i, l);
return [u.selectedIndices, u.validOutputs];
}
case "NonMaxSuppressionV3":
case "NonMaxSuppressionV2": {
let { boxes: n, scores: o, maxOutputSize: s, iouThreshold: a, scoreThreshold: i } = Zv(r, e, t);
return [await Cn.nonMaxSuppressionAsync(n, o, s, a, i)];
}
case "Where": {
let n = Y(v("condition", r, e, t), "bool"), o = [await qf(n)];
return n.dispose(), o;
}
case "ListDiff":
return xk(v("x", r, e, t), v("y", r, e, t));
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var mD = (r, e, t) => {
switch (r.op) {
case "TopKV2": {
let n = v("x", r, e, t), o = v("k", r, e, t), s = v("sorted", r, e, t), a = jf(n, o, s);
return [a.values, a.indices];
}
case "Unique": {
let n = v("x", r, e, t), o = Gp(n);
return [o.values, o.indices];
}
case "UniqueV2": {
let n = v("x", r, e, t), o = v("axis", r, e, t), s = Gp(n, o);
return [s.values, s.indices];
}
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var fD = (r, e, t) => {
switch (r.op) {
case "Const":
return e[r.name];
case "PlaceholderWithDefault":
let n = v("default", r, e, t);
return [br(r.name, e, t) || n];
case "Placeholder":
return [br(r.name, e, t)];
case "Identity":
case "StopGradient":
case "FakeQuantWithMinMaxVars": {
let u = v("x", r, e, t);
return [Hs(u)];
}
case "IdentityN":
return v("x", r, e, t).map((u) => Hs(u));
case "Snapshot":
let o = v("x", r, e, t);
return [Hs(o)];
case "Shape":
return [$t(v("x", r, e, t).shape, "int32")];
case "ShapeN":
return v("x", r, e, t).map((u) => $t(u.shape));
case "Size":
return [pe(v("x", r, e, t).size, "int32")];
case "Rank":
return [pe(v("x", r, e, t).rank, "int32")];
case "NoOp":
return [pe(1)];
case "Print":
let s = v("x", r, e, t), a = v("data", r, e, t), i = v("message", r, e, t), l = v("summarize", r, e, t);
console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."), console.log(i);
for (let u = 0; u < a.length; u++)
console.log(Array.prototype.slice.call(a[u].dataSync()).slice(0, l));
return [s];
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var Jv = class {
constructor(e, t) {
this.keyDType = e, this.valueDType = t, this.handle = pe(0), this.tensorMap = new Map(), Ft(this.handle);
}
get id() {
return this.handle.id;
}
clearAndClose() {
this.tensorMap.forEach((e) => e.dispose()), this.tensorMap.clear(), this.handle.dispose();
}
size() {
return this.tensorMap.size;
}
tensorSize() {
return pe(this.size(), "int32");
}
async import(e, t) {
this.checkKeyAndValueTensor(e, t);
let n = await e.data();
return this.tensorMap.forEach((o) => o.dispose()), this.tensorMap.clear(), V(() => {
let o = yr(t), s = n.length, a = o.length;
b.assert(s === a, () => `The number of elements doesn't match, keys has ${s} elements, the values has ${a} elements.`);
for (let i = 0; i < s; i++) {
let l = n[i], u = o[i];
Ft(u), this.tensorMap.set(l, u);
}
return this.handle;
});
}
async find(e, t) {
this.checkKeyAndValueTensor(e, t);
let n = await e.data();
return V(() => {
let o = [];
for (let s = 0; s < n.length; s++) {
let a = n[s], i = this.findWithDefault(a, t);
o.push(i);
}
return Xt(o);
});
}
findWithDefault(e, t) {
let n = this.tensorMap.get(e);
return n != null ? n : t;
}
checkKeyAndValueTensor(e, t) {
if (e.dtype !== this.keyDType)
throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);
if (t.dtype !== this.valueDType)
throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`);
}
};
var dD = async (r, e, t, n) => {
switch (r.op) {
case "HashTable":
case "HashTableV2": {
let o = v("keyDType", r, e, t), s = v("valueDType", r, e, t), a = new Jv(o, s);
return n.addHashTable(r.name, a), [a.handle];
}
case "LookupTableImport":
case "LookupTableImportV2": {
let o = v("tableHandle", r, e, t, n), s = v("keys", r, e, t), a = v("values", r, e, t);
return [await n.getHashTableById(o.id).import(s, a)];
}
case "LookupTableFind":
case "LookupTableFindV2": {
let o = v("tableHandle", r, e, t, n), s = v("keys", r, e, t), a = v("defaultValue", r, e, t);
return [await n.getHashTableById(o.id).find(s, a)];
}
case "LookupTableSize":
case "LookupTableSizeV2": {
let o = v("tableHandle", r, e, t, n);
return [n.getHashTableById(o.id).tensorSize()];
}
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var hD = (r, e, t) => {
switch (r.op) {
case "ResizeBilinear": {
let n = v("images", r, e, t), o = v("size", r, e, t), s = v("alignCorners", r, e, t), a = v("halfPixelCenters", r, e, t);
return [Cn.resizeBilinear(n, [o[0], o[1]], s, a)];
}
case "ResizeNearestNeighbor": {
let n = v("images", r, e, t), o = v("size", r, e, t), s = v("alignCorners", r, e, t), a = v("halfPixelCenters", r, e, t);
return [Cn.resizeNearestNeighbor(n, [o[0], o[1]], s, a)];
}
case "CropAndResize": {
let n = v("image", r, e, t), o = v("boxes", r, e, t), s = v("boxInd", r, e, t), a = v("cropSize", r, e, t), i = v("method", r, e, t), l = v("extrapolationValue", r, e, t);
return [Cn.cropAndResize(n, o, s, a, i, l)];
}
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var gD = (r, e, t) => {
switch (r.op) {
case "Equal":
return [kr(v("a", r, e, t), v("b", r, e, t))];
case "NotEqual":
return [mo(v("a", r, e, t), v("b", r, e, t))];
case "Greater":
return [zt(v("a", r, e, t), v("b", r, e, t))];
case "GreaterEqual":
return [kn(v("a", r, e, t), v("b", r, e, t))];
case "Less":
return [Tu(v("a", r, e, t), v("b", r, e, t))];
case "LessEqual":
return [vn(v("a", r, e, t), v("b", r, e, t))];
case "LogicalAnd":
return [Cr(v("a", r, e, t), v("b", r, e, t))];
case "LogicalNot":
return [Fa(v("a", r, e, t))];
case "LogicalOr":
return [Au(v("a", r, e, t), v("b", r, e, t))];
case "Select":
case "SelectV2":
return [St(v("condition", r, e, t), v("a", r, e, t), v("b", r, e, t))];
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var xD = (r, e, t) => {
switch (r.op) {
case "BatchMatMul":
case "BatchMatMulV2":
case "MatMul":
return [ze(v("a", r, e, t), v("b", r, e, t), v("transposeA", r, e, t), v("transposeB", r, e, t))];
case "Einsum":
return [X_(v("equation", r, e, t), ...v("tensors", r, e, t))];
case "Transpose":
return [Be(v("x", r, e, t), v("perm", r, e, t))];
case "_FusedMatMul":
let [n, o] = v("fusedOps", r, e, t), s = n === "biasadd", a = o === "prelu", i = v("numArgs", r, e, t), l = v("leakyreluAlpha", r, e, t);
if (s) {
if (a && i !== 2)
throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");
if (!a && i !== 1)
throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.");
}
let [u, c] = v("args", r, e, t);
return [fo.matMul({ a: v("a", r, e, t), b: v("b", r, e, t), transposeA: v("transposeA", r, e, t), transposeB: v("transposeB", r, e, t), bias: u, activation: o, preluActivationWeights: c, leakyreluAlpha: l })];
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var yD = (r, e, t) => {
switch (r.op) {
case "FusedBatchNorm":
case "FusedBatchNormV2":
return [lo(v("x", r, e, t), v("mean", r, e, t), v("variance", r, e, t), v("offset", r, e, t), v("scale", r, e, t), v("epsilon", r, e, t))];
case "FusedBatchNormV3":
return [lo(v("x", r, e, t), v("mean", r, e, t), v("variance", r, e, t), v("offset", r, e, t), v("scale", r, e, t), v("epsilon", r, e, t))];
case "LRN":
return [$f(v("x", r, e, t), v("radius", r, e, t), v("bias", r, e, t), v("alpha", r, e, t), v("beta", r, e, t))];
case "Softmax":
return [za(v("x", r, e, t))];
case "LogSoftmax":
return [Eu(v("x", r, e, t))];
case "SparseToDense":
return [ox(v("sparseIndices", r, e, t), v("outputShape", r, e, t), v("sparseValues", r, e, t), v("defaultValue", r, e, t))];
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var bD = (r, e, t) => {
switch (r.op) {
case "Max": {
let a = v("axis", r, e, t), i = v("keepDims", r, e, t);
return [Rr(v("x", r, e, t), a, i)];
}
case "Mean": {
let a = v("axis", r, e, t), i = v("keepDims", r, e, t);
return [xt(v("x", r, e, t), a, i)];
}
case "Min": {
let a = v("axis", r, e, t), i = v("keepDims", r, e, t);
return [Al(v("x", r, e, t), a, i)];
}
case "Sum": {
let a = v("axis", r, e, t), i = v("keepDims", r, e, t);
return [me(v("x", r, e, t), a, i)];
}
case "All": {
let a = v("axis", r, e, t), i = v("keepDims", r, e, t);
return [wu(v("x", r, e, t), a, i)];
}
case "Any": {
let a = v("axis", r, e, t), i = v("keepDims", r, e, t);
return [El(v("x", r, e, t), a, i)];
}
case "ArgMax": {
let a = v("axis", r, e, t);
return [As(v("x", r, e, t), a)];
}
case "ArgMin": {
let a = v("axis", r, e, t);
return [gf(v("x", r, e, t), a)];
}
case "Prod": {
let a = v("axis", r, e, t), i = v("keepDims", r, e, t);
return [Du(v("x", r, e, t), a, i)];
}
case "Cumsum": {
let a = v("axis", r, e, t), i = v("exclusive", r, e, t), l = v("reverse", r, e, t);
return [Su(v("x", r, e, t), a, i, l)];
}
case "Bincount":
let n = v("x", r, e, t), o = v("weights", r, e, t), s = v("size", r, e, t);
return [vf(n, o, s)];
case "DenseBincount": {
let a = v("x", r, e, t), i = v("weights", r, e, t), l = v("size", r, e, t), u = v("binaryOutput", r, e, t);
return [q_(a, i, l, u)];
}
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var wD = (r, e, t) => {
switch (r.op) {
case "ConcatV2":
case "Concat": {
let n = v("n", r, e, t), o = v("axis", r, e, t), s = v("tensors", r, e, t);
return s = s.slice(0, n), [tt(s, o)];
}
case "Gather": {
let n = v("x", r, e, t), o = v("indices", r, e, t);
return [uo(n, Y(o, "int32"), 0)];
}
case "GatherV2": {
let n = v("axis", r, e, t), o = v("batchDims", r, e, t), s = v("x", r, e, t), a = v("indices", r, e, t);
return [uo(s, Y(a, "int32"), n, o)];
}
case "Reverse": {
let n = v("dims", r, e, t), o = [];
for (let a = 0; a < n.length; a++)
n[a] && o.push(a);
let s = v("x", r, e, t);
return [er(s, o)];
}
case "ReverseV2": {
let n = v("axis", r, e, t), o = v("x", r, e, t);
return [er(o, n)];
}
case "Slice": {
let n = v("begin", r, e, t), o = v("size", r, e, t);
return [Oe(v("x", r, e, t), n, o)];
}
case "StridedSlice": {
let n = v("begin", r, e, t), o = v("end", r, e, t), s = v("strides", r, e, t), a = v("beginMask", r, e, t), i = v("endMask", r, e, t), l = v("ellipsisMask", r, e, t), u = v("newAxisMask", r, e, t), c = v("shrinkAxisMask", r, e, t), p = v("x", r, e, t);
return [Wf(p, n, o, s, a, i, l, u, c)];
}
case "Pack":
return V(() => {
let n = v("axis", r, e, t), o = v("tensors", r, e, t), s = o[0].shape, a = Br(o[0]).shape, i = o.map((l) => {
let u = b.arraysEqual(l.shape, s);
if (!u && !b.arraysEqual(Br(l).shape, a))
throw new Error("the input tensors shape does not match");
return u ? l : F(l, s);
});
return [Xt(i, n)];
});
case "Unpack": {
let n = v("axis", r, e, t), o = v("tensor", r, e, t);
return yr(o, n);
}
case "Tile": {
let n = v("reps", r, e, t);
return [vr(v("x", r, e, t), n)];
}
case "Split":
case "SplitV": {
let n = v("axis", r, e, t), o = v("numOrSizeSplits", r, e, t), s = v("x", r, e, t);
return sr(s, o, n);
}
case "ScatterNd": {
let n = v("indices", r, e, t), o = v("values", r, e, t), s = v("shape", r, e, t);
return [Y1(n, o, s)];
}
case "GatherNd": {
let n = v("x", r, e, t), o = v("indices", r, e, t);
return [J1(n, o)];
}
case "SparseToDense": {
let n = v("sparseIndices", r, e, t), o = v("outputShape", r, e, t), s = v("sparseValues", r, e, t), a = v("defaultValue", r, e, t);
return [ox(n, s, o, s.dtype === a.dtype ? a : Y(a, s.dtype))];
}
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var _D = (r, e, t) => {
switch (r.op) {
case "SparseFillEmptyRows": {
let { outputIndices: n, outputValues: o, emptyRowIndicator: s, reverseIndexMap: a } = Kf.sparseFillEmptyRows(v("indices", r, e, t), v("values", r, e, t), v("denseShape", r, e, t), v("defaultValue", r, e, t));
return [n, o, s, a];
}
case "SparseReshape": {
let { outputIndices: n, outputShape: o } = Kf.sparseReshape(v("inputIndices", r, e, t), v("inputShape", r, e, t), v("newShape", r, e, t));
return [n, o];
}
case "SparseSegmentMean":
return [Kf.sparseSegmentMean(v("data", r, e, t), v("indices", r, e, t), v("segmentIds", r, e, t))];
case "SparseSegmentSum":
return [Kf.sparseSegmentSum(v("data", r, e, t), v("indices", r, e, t), v("segmentIds", r, e, t))];
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var kD = (r, e, t) => {
switch (r.op) {
case "FFT":
return [Ba(v("x", r, e, t))];
case "IFFT":
return [_i(v("x", r, e, t))];
case "RFFT":
return [Va(v("x", r, e, t))];
case "IRFFT":
return [zu(v("x", r, e, t))];
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var vD = (r, e, t) => {
switch (r.op) {
case "StringNGrams": {
let { nGrams: n, nGramsSplits: o } = hx.stringNGrams(v("data", r, e, t), v("dataSplits", r, e, t), v("separator", r, e, t), v("nGramWidths", r, e, t), v("leftPad", r, e, t), v("rightPad", r, e, t), v("padWidth", r, e, t), v("preserveShortSequences", r, e, t));
return [n, o];
}
case "StringSplit": {
let { indices: n, values: o, shape: s } = hx.stringSplit(v("input", r, e, t), v("delimiter", r, e, t), v("skipEmpty", r, e, t));
return [n, o, s];
}
case "StringToHashBucketFast":
return [hx.stringToHashBucketFast(v("input", r, e, t), v("numBuckets", r, e, t))];
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
var CD = (r, e, t) => {
switch (r.op) {
case "Cast":
return [Y(v("x", r, e, t), v("dtype", r, e, t))];
case "ExpandDims": {
let n = v("axis", r, e, t);
return [mr(v("x", r, e, t), n)];
}
case "Squeeze": {
let n = v("axis", r, e, t);
return [Br(v("x", r, e, t), n)];
}
case "Reshape":
return [F(v("x", r, e, t), v("shape", r, e, t))];
case "MirrorPad":
return [Pf(v("x", r, e, t), v("padding", r, e, t), v("mode", r, e, t))];
case "PadV2":
case "Pad":
return [jr(v("x", r, e, t), v("padding", r, e, t), v("constantValue", r, e, t))];
case "SpaceToBatchND": {
let n = v("blockShape", r, e, t), o = v("paddings", r, e, t);
return [Pa(v("x", r, e, t), n, o)];
}
case "BatchToSpaceND": {
let n = v("blockShape", r, e, t), o = v("crops", r, e, t);
return [Ea(v("x", r, e, t), n, o)];
}
case "DepthToSpace": {
let n = v("blockSize", r, e, t), o = v("dataFormat", r, e, t).toUpperCase();
return [Sf(v("x", r, e, t), n, o)];
}
case "BroadcastTo":
return [Aa(v("x", r, e, t), v("shape", r, e, t))];
case "BroadcastArgs":
return [V_(v("s0", r, e, t), v("s1", r, e, t))];
default:
throw TypeError(`Node type ${r.op} is not implemented`);
}
};
function Qv(r, e, t, n) {
let o = ((s, a, i) => {
switch (s.category) {
case "arithmetic":
return V(() => eD(s, a, i));
case "basic_math":
return V(() => tD(s, a, i));
case "control":
return aD(s, a, i);
case "convolution":
return V(() => uD(s, a, i));
case "creation":
return V(() => cD(s, a, i));
case "dynamic":
return pD(s, a, i);
case "evaluation":
return V(() => mD(s, a, i));
case "image":
return V(() => hD(s, a, i));
case "graph":
return V(() => fD(s, a, i));
case "logical":
return V(() => gD(s, a, i));
case "matrices":
return V(() => xD(s, a, i));
case "normalization":
return V(() => yD(s, a, i));
case "reduction":
return V(() => bD(s, a, i));
case "slice_join":
return V(() => wD(s, a, i));
case "sparse":
return V(() => _D(s, a, i));
case "spectral":
return V(() => kD(s, a, i));
case "string":
return V(() => vD(s, a, i));
case "transformation":
return V(() => CD(s, a, i));
case "hash_table":
return dD(s, a, i, n);
case "custom":
let l = qx(s.op);
if (l && l.customExecutor)
return l.customExecutor(new Xv(s, a, i));
throw TypeError(`Custom op ${s.op} is not registered.`);
default:
throw TypeError(`Unknown op '${s.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`);
}
})(r, e, t);
return b.isPromise(o) ? o.then((s) => [].concat(s)) : [].concat(o);
}
var ay = class {
constructor(e = {}, t = {}, n = {}, o = {}) {
this.weightMap = e, this.tensorArrayMap = t, this.tensorListMap = n, this.functionMap = o, this.rootContext = { id: 0, frameName: "", iterationId: 0 }, this.contexts = [this.rootContext], this.lastId = 0, this.generateCurrentContextIds();
}
newFrame(e, t) {
return { id: e, frameName: t, iterationId: 0 };
}
set currentContext(e) {
this.contexts !== e && (this.contexts = e, this.generateCurrentContextIds());
}
get currentContext() {
return this.contexts;
}
get currentContextId() {
return this._currentContextIds[0];
}
get currentContextIds() {
return this._currentContextIds;
}
generateCurrentContextIds() {
let e = [];
for (let t = 0; t < this.contexts.length - 1; t++) {
let n = this.contexts.slice(0, this.contexts.length - t);
e.push(this.contextIdforContexts(n));
}
e.push(""), this._currentContextIds = e;
}
contextIdforContexts(e) {
return e ? e.map((t) => t.id === 0 && t.iterationId === 0 ? "" : `${t.frameName}-${t.iterationId}`).join("/") : "";
}
enterFrame(e) {
this.contexts && (this.lastId++, this.contexts = this.contexts.slice(), this.contexts.push(this.newFrame(this.lastId, e)), this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)));
}
exitFrame() {
if (this.contexts && this.contexts.length > 1)
this.contexts = this.contexts.slice(), this.contexts.splice(-1), this.currentContextIds.shift();
else
throw new Error("Cannot exit frame, the context is empty");
}
nextIteration() {
if (this.contexts && this.contexts.length > 0) {
this.contexts = this.contexts.slice(), this.lastId++;
let e = Object.assign({}, this.contexts[this.contexts.length - 1]);
e.iterationId += 1, e.id = this.lastId, this.contexts.splice(-1, 1, e), this._currentContextIds.splice(0, 1, this.contextIdforContexts(this.contexts));
} else
throw new Error("Cannot increase frame iteration, the context is empty");
}
getWeight(e) {
return this.weightMap[e];
}
addTensorArray(e) {
this.tensorArrayMap[e.id] = e;
}
getTensorArray(e) {
return this.tensorArrayMap[e];
}
addTensorList(e) {
this.tensorListMap[e.id] = e;
}
getTensorList(e) {
return this.tensorListMap[e];
}
dispose(e) {
for (let t in this.tensorArrayMap)
this.tensorArrayMap[t].clearAndClose(e);
for (let t in this.tensorListMap)
this.tensorListMap[t].clearAndClose(e);
}
};
function e0(r, e, t, n) {
let o = new Set(), s = [], a = null, i = null, l = new Set(), u = Object.keys(r).map((m) => fn(m)[0]), c = [];
n != null && (c = n.map((m) => fn(m.name)[0]));
let p = [...e];
for (; p.length > 0; ) {
let m = p.pop();
if ((t0(m) || l7(m) || u7(m)) && a == null && (a = m, i = a.children.map((f) => f.name).filter((f) => o.has(f))), o.add(m.name), t[m.name] == null && u.indexOf(m.name) === -1 && c.indexOf(m.name) === -1) {
if (m.inputs.length === 0) {
s.push(m.name);
continue;
}
m.inputs.forEach((f) => {
l.has(f.name) || (l.add(f.name), p.push(f));
});
}
}
return { inputs: r, outputs: e, usedNodes: o, missingInputs: s, dynamicNode: a, syncInputs: i };
}
function ID(r, e, t) {
let { usedNodes: n, inputs: o } = t, s = [], a = Object.keys(o).map((c) => fn(c)[0]).map((c) => r.nodes[c]), i = r.initNodes;
a.forEach((c) => {
n.has(c.name) && s.push(c);
}), r.weights.forEach((c) => {
n.has(c.name) && s.push(c);
}), i != null && i.forEach((c) => {
n.has(c.name) && s.push(c);
});
let l = new Set(), u = [];
for (; s.length > 0; ) {
let c = s.pop();
l.add(c.name), e[c.name] || u.push(c), c.children.forEach((p) => {
!l.has(p.name) && n.has(p.name) && p.inputs.every((m) => l.has(m.name)) && s.push(p);
});
}
return u;
}
var s7 = ["Switch", "Merge", "Enter", "Exit", "NextIteration", "StatelessIf", "StatelessWhile", "if", "While"];
var i7 = ["NonMaxSuppressionV2", "NonMaxSuppressionV3", "NonMaxSuppressionV5", "Where"];
var a7 = ["HashTable", "HashTableV2", "LookupTableImport", "LookupTableImportV2", "LookupTableFind", "LookupTableFindV2", "LookupTableSize", "LookupTableSizeV2"];
function t0(r) {
return s7.indexOf(r.op) >= 0;
}
function l7(r) {
return i7.indexOf(r.op) >= 0;
}
function u7(r) {
return a7.indexOf(r.op) >= 0;
}
var xm = class {
constructor(e, t) {
this.graph = e, this.parent = t, this.compiledMap = new Map(), this._weightMap = {}, this.SEPERATOR = ",", this._functions = {}, this._functionExecutorMap = {}, this._outputs = e.outputs, this._inputs = e.inputs, this._initNodes = e.initNodes, this._signature = e.signature, this._functions = e.functions, e.functions != null && Object.keys(e.functions).forEach((n) => {
this._functionExecutorMap[n] = new xm(e.functions[n], this);
});
}
get weightIds() {
return this.parent ? this.parent.weightIds : this._weightIds;
}
get functionExecutorMap() {
return this.parent ? this.parent.functionExecutorMap : this._functionExecutorMap;
}
get weightMap() {
return this.parent ? this.parent.weightMap : this._weightMap;
}
set weightMap(e) {
let t = Object.keys(e).map((n) => e[n].map((o) => o.id));
this._weightIds = [].concat(...t), this._weightMap = e;
}
set resourceManager(e) {
this._resourceManager = e;
}
get inputs() {
return this._inputs.map((e) => ({ name: e.name, shape: e.attrParams.shape ? e.attrParams.shape.value : void 0, dtype: e.attrParams.dtype ? e.attrParams.dtype.value : void 0 }));
}
get outputs() {
return this._outputs.map((e) => ({ name: e.name, shape: e.attrParams.shape ? e.attrParams.shape.value : void 0, dtype: e.attrParams.dtype ? e.attrParams.dtype.value : void 0 }));
}
get inputNodes() {
return this._inputs.map((e) => e.signatureKey || e.name);
}
get outputNodes() {
return this._outputs.map((e) => {
let t = e.signatureKey || e.name;
return e.defaultOutput ? `${t}:${e.defaultOutput}` : t;
});
}
get functions() {
return Object.keys(this._functions).reduce((e, t) => (e[t] = this._functions[t].signature, e), {});
}
getCompilationKey(e, t) {
let n = e.map((s) => s.name).sort(), o = t.map((s) => s.name).sort();
return n.join(this.SEPERATOR) + "--" + o.join(this.SEPERATOR);
}
compile(e, t) {
let n = e0(e, t, this.weightMap, this._initNodes), { missingInputs: o, dynamicNode: s, syncInputs: a } = n;
if (s != null)
throw new Error(`This execution contains the node '${s.name}', which has the dynamic op '${s.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);
if (o.length > 0) {
let i = t.map((u) => u.name), l = Object.keys(e);
throw new Error(`Cannot compute the outputs [${i}] from the provided inputs [${l}]. Missing the following inputs: [${o}]`);
}
return ID(this.graph, this.weightMap, n);
}
execute(e, t) {
e = this.mapInputs(e);
let n = Object.keys(e).sort();
this.checkInputs(e), this.checkInputShapeAndType(e), t = this.mapOutputs(t), this.checkOutputs(t);
let o = n.map((p) => this.graph.nodes[fn(p)[0]]), s = t.map((p) => fn(p)[0]), a = s.map((p) => this.graph.nodes[p]);
a.length === 0 && (a = this._outputs);
let i = this.getCompilationKey(o, a), l = this.compiledMap.get(i);
l == null && (l = this.compile(e, a), this.compiledMap.set(i, l));
let u = {}, c = {};
return V(() => {
let p = new ay(this.weightMap, u, c, this.functionExecutorMap), m = Object.assign({}, this.weightMap);
Object.keys(e).forEach((h) => {
let [g, x] = fn(h), y = [];
y[x] = e[h], m[g] = y;
});
let f = this.getFrozenTensorIds(m), d = {};
for (let h = 0; h < l.length; h++) {
let g = l[h];
if (!m[g.name]) {
let x = Qv(g, m, p, this._resourceManager);
if (b.isPromise(x))
throw new Error(`The execution of the op '${g.op}' returned a promise. Please use model.executeAsync() instead.`);
m[g.name] = x, this.checkTensorForDisposal(g.name, g, m, p, f, s, d);
}
}
return this.parent == null && p.dispose(f), t.map((h) => br(h, m, p));
});
}
getFrozenTensorIds(e) {
let t = [].concat.apply([], Object.keys(e).map((n) => e[n]).map((n) => n.map((o) => o.id)));
return new Set(t);
}
checkTensorForDisposal(e, t, n, o, s, a, i) {
t.category === "control" || a.indexOf(e) !== -1 || (n[e].forEach((l) => {
l != null && (i[l.id] = (i[l.id] || 0) + t.children.length);
}), t.inputs.forEach((l) => {
if (l.category !== "control") {
let u = YA(l.name, n, o);
u != null && u.forEach((c) => {
if (c && !c.kept && !s.has(c.id)) {
let p = i[c.id];
p === 1 ? (c.dispose(), delete i[c.id]) : p != null && i[c.id]--;
}
});
}
}));
}
async executeAsync(e, t) {
return this._executeAsync(e, t);
}
async _executeAsync(e, t, n = false, o = {}, s = {}) {
n || (e = this.mapInputs(e), this.checkInputs(e), this.checkInputShapeAndType(e), t = this.mapOutputs(t), this.checkOutputs(t));
let a = new ay(this.weightMap, o, s, this.functionExecutorMap), i = await this.executeWithControlFlow(e, a, t, n), l = t.map((m) => br(m, i, a)), u = l.map((m) => m.id), c = Object.keys(e).map((m) => e[m].id), p = new Set([...u, ...c, ...this.weightIds]);
return Object.keys(i).forEach((m) => {
i[m].forEach((d) => {
d && !d.kept && !d.isDisposed && !p.has(d.id) && d.dispose();
});
}), this.parent == null && a.dispose(p), l;
}
async executeFunctionAsync(e, t, n) {
let o = e.reduce((s, a, i) => (s[this.inputs[i].name] = a, s), {});
return this._executeAsync(o, this.outputNodes, true, t, n);
}
async executeWithControlFlow(e, t, n, o) {
let s = Object.keys(e), a = s.map((w) => this.graph.nodes[fn(w)[0]]), i = n.map((w) => fn(w)[0]), l = i.map((w) => this.graph.nodes[w]);
l.length === 0 && (l = this._outputs);
let { usedNodes: u, missingInputs: c, dynamicNode: p, syncInputs: m } = e0(e, l, this.weightMap, this._initNodes), f = [...a, ...this.graph.weights, ...this._initNodes || []].map((w) => ({ node: w, contexts: t.currentContext })), d = Object.assign({}, this.weightMap);
Object.keys(e).forEach((w) => {
let [_, C] = fn(w), A = [];
A[C] = e[w], d[_] = A;
});
let h = {}, g = this.getFrozenTensorIds(d), x = {};
for (; f.length > 0; ) {
let w = this.processStack(a, f, t, d, x, g, i, h, u);
await Promise.all(w);
}
p == null && !o && console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");
let y = l.filter((w) => !t0(w) && !br(w.name, d, t)).map((w) => w.name);
if (y.length > 0) {
let w = "";
throw p != null && (w = `Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${m}]`), new Error(`Cannot compute the outputs [${y}] from the provided inputs [${s}]. Consider providing the following inputs: [${c}]. ${w}`);
}
return d;
}
processStack(e, t, n, o, s, a, i, l, u) {
let c = [];
for (; t.length > 0; ) {
let p = t.pop();
n.currentContext = p.contexts;
let m = "";
if (p.node.op === "Enter" && v("isConstant", p.node, o, n) && ([m] = js(p.node.name, n)), o[p.node.name] == null) {
let f = Qv(p.node, o, n, this._resourceManager);
m || ([m] = js(p.node.name, n));
let d = n.currentContext;
b.isPromise(f) ? c.push(f.then((h) => (o[m] = h, n.currentContext = d, this.checkTensorForDisposal(m, p.node, o, n, a, i, l), this.processChildNodes(p.node, t, n, o, s, u), h))) : (o[m] = f, this.checkTensorForDisposal(m, p.node, o, n, a, i, l), this.processChildNodes(p.node, t, n, o, s, u));
} else
this.processChildNodes(p.node, t, n, o, s, u);
}
return c;
}
processChildNodes(e, t, n, o, s, a) {
e.children.forEach((i) => {
let [l] = js(i.name, n);
s[l] || !a.has(i.name) || (i.op === "Merge" ? i.inputNames.some((u) => !!br(u, o, n)) && (s[l] = true, t.push({ contexts: n.currentContext, node: i })) : i.inputNames.every((u) => !!br(u, o, n)) && (s[l] = true, t.push({ contexts: n.currentContext, node: i })));
});
}
dispose() {
Object.keys(this.weightMap).forEach((e) => this.weightMap[e].forEach((t) => t.dispose()));
}
checkInputShapeAndType(e) {
Object.keys(e).forEach((t) => {
let n = e[t], [o] = fn(t), s = this.graph.nodes[o];
if (s.attrParams.shape && s.attrParams.shape.value) {
let a = s.attrParams.shape.value, i = a.length === n.shape.length && n.shape.every((l, u) => a[u] === -1 || a[u] === l);
b.assert(i, () => `The shape of dict['${s.name}'] provided in model.execute(dict) must be [${a}], but was [${n.shape}]`);
}
s.attrParams.dtype && s.attrParams.dtype.value && b.assert(n.dtype === s.attrParams.dtype.value, () => `The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${n.dtype}`);
});
}
mapInputs(e) {
let t = {};
for (let n in e)
if (this._signature != null && this._signature.inputs != null && this._signature.inputs[n] != null) {
let o = this._signature.inputs[n];
t[o.name] = e[n];
} else
t[n] = e[n];
return t;
}
checkInputs(e) {
let t = Object.keys(e).filter((n) => {
let [o] = fn(n);
return this.graph.nodes[o] == null;
});
if (t.length > 0)
throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`);
}
mapOutputs(e) {
return e.map((t) => this._signature != null && this._signature.outputs != null && this._signature.outputs[t] != null ? this._signature.outputs[t].name : t, {});
}
checkOutputs(e) {
e.forEach((t) => {
let [n] = fn(t);
if (!this.graph.nodes[n])
throw new Error(`The output '${t}' is not found in the graph`);
});
}
};
var r0 = class {
constructor(e = {}, t = {}) {
this.hashTableNameToHandle = e, this.hashTableMap = t;
}
addHashTable(e, t) {
this.hashTableNameToHandle[e] = t.handle, this.hashTableMap[t.id] = t;
}
getHashTableHandleByName(e) {
return this.hashTableNameToHandle[e];
}
getHashTableById(e) {
return this.hashTableMap[e];
}
dispose() {
for (let e in this.hashTableMap)
this.hashTableMap[e].clearAndClose(), delete this.hashTableMap[e];
for (let e in this.hashTableNameToHandle)
this.hashTableNameToHandle[e].dispose(), delete this.hashTableNameToHandle[e];
}
};
var c7 = "?tfjs-format=file";
var p7 = "model.json";
var ly = class {
constructor(e, t = {}) {
this.modelUrl = e, this.loadOptions = t, this.version = "n/a", t == null && (this.loadOptions = {}), this.resourceManager = new r0();
}
get modelVersion() {
return this.version;
}
get inputNodes() {
return this.executor.inputNodes;
}
get outputNodes() {
return this.executor.outputNodes;
}
get inputs() {
return this.executor.inputs;
}
get outputs() {
return this.executor.outputs;
}
get weights() {
return this.executor.weightMap;
}
get metadata() {
return this.artifacts.userDefinedMetadata;
}
get modelSignature() {
return this.signature;
}
findIOHandler() {
let e = this.modelUrl;
if (e.load != null)
this.handler = e;
else if (this.loadOptions.requestInit != null)
this.handler = Lr.browserHTTPRequest(e, this.loadOptions);
else {
let t = Lr.getLoadHandlers(e, this.loadOptions);
if (t.length === 0)
t.push(Lr.browserHTTPRequest(e, this.loadOptions));
else if (t.length > 1)
throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);
this.handler = t[0];
}
}
async load() {
if (this.findIOHandler(), this.handler.load == null)
throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");
let e = await this.handler.load();
return this.loadSync(e);
}
loadSync(e) {
this.artifacts = e;
let t = this.artifacts.modelTopology, n;
this.artifacts.userDefinedMetadata != null && this.artifacts.userDefinedMetadata.signature != null ? n = this.artifacts.userDefinedMetadata.signature : n = this.artifacts.signature, this.signature = n, this.version = `${t.versions.producer}.${t.versions.minConsumer}`;
let o = Lr.decodeWeights(this.artifacts.weightData, this.artifacts.weightSpecs);
if (this.executor = new xm(Xx.Instance.transformGraph(t, this.signature)), this.executor.weightMap = this.convertTensorMapToTensorsMap(o), this.executor.resourceManager = this.resourceManager, e.modelInitializer != null && e.modelInitializer.node != null) {
let s = Xx.Instance.transformGraph(e.modelInitializer);
this.initializer = new xm(s), this.initializer.weightMap = this.executor.weightMap, this.initializer.resourceManager = this.resourceManager, this.initializer.executeAsync({}, []);
}
return true;
}
async save(e, t) {
if (typeof e == "string") {
let n = Lr.getSaveHandlers(e);
if (n.length === 0)
throw new Error(`Cannot find any save handlers for URL '${e}'`);
if (n.length > 1)
throw new Error(`Found more than one (${n.length}) save handlers for URL '${e}'`);
e = n[0];
}
if (e.save == null)
throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");
return e.save(this.artifacts);
}
predict(e, t) {
return this.execute(e, this.outputNodes);
}
normalizeInputs(e) {
if (!(e instanceof Le) && !Array.isArray(e))
return e;
if (e = Array.isArray(e) ? e : [e], e.length !== this.inputNodes.length)
throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);
return this.inputNodes.reduce((t, n, o) => (t[n] = e[o], t), {});
}
normalizeOutputs(e) {
return e = e || this.outputNodes, Array.isArray(e) ? e : [e];
}
execute(e, t) {
e = this.normalizeInputs(e), t = this.normalizeOutputs(t);
let n = this.executor.execute(e, t);
return n.length > 1 ? n : n[0];
}
async executeAsync(e, t) {
e = this.normalizeInputs(e), t = this.normalizeOutputs(t);
let n = await this.executor.executeAsync(e, t);
return n.length > 1 ? n : n[0];
}
convertTensorMapToTensorsMap(e) {
return Object.keys(e).reduce((t, n) => (t[n] = [e[n]], t), {});
}
dispose() {
this.executor.dispose(), this.initializer && this.initializer.dispose(), this.resourceManager.dispose();
}
};
async function m7(r, e = {}) {
if (r == null)
throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");
e == null && (e = {}), e.fromTFHub && r.load == null && (r.endsWith("/") || (r = r + "/"), r = `${r}${p7}${c7}`);
let t = new ly(r, e);
return await t.load(), t;
}
var SD = "3.10.0";
var v$ = {};
qe(v$, { CSVDataset: () => vh, Dataset: () => Ti, FileDataSource: () => Th, TextLineDataset: () => _h, URLDataSource: () => Eh, array: () => u$, csv: () => y$, func: () => b$, generator: () => w$, microphone: () => k$, version_data: () => y0, webcam: () => _$, zip: () => c$ });
var l$ = ou(u0());
var qD = ou(u0());
function GD(r, e) {
return cy(r, e);
}
function cy(r, e, t = new Map(), n = new Set()) {
if (r == null)
return null;
if (typeof Blob == "function" && r instanceof Blob)
return r.slice();
if (n.has(r))
throw new Error("Circular references are not supported.");
if (t.has(r))
return t.get(r);
let o = e(r);
if (o.recurse && o.value !== null)
throw new Error("A deep map function may not return both a value and recurse=true.");
if (o.recurse)
if (Ul(r)) {
let s = Array.isArray(r) ? [] : {};
n.add(r);
for (let a in r) {
let i = r[a], l = cy(i, e, t, n);
s[a] = l;
}
return n.delete(r), r.__proto__ && (s.__proto__ = r.__proto__), s;
} else
throw new Error(`Can't recurse into non-iterable type: ${r}`);
else
return t.set(r, o.value), o.value;
}
function WD(r, e = p0) {
return UD(r, e);
}
function UD(r, e, t = new Set()) {
let n = r[0];
if (t.has(n))
throw new Error("Circular references are not supported.");
let o = e(r);
if (o.recurse && o.value !== null)
throw new Error("A deep zip function may not return both a value and recurse=true.");
if (o.recurse)
if (Ul(n)) {
let s = Array.isArray(n) ? [] : {};
t.add(n);
for (let a in n) {
let i = r.map((u) => u[a]), l = UD(i, e, t);
s[a] = l;
}
return t.delete(n), s;
} else
throw new Error(`Can't recurse into non-iterable type: ${n}`);
else
return o.value;
}
function p0(r) {
return r === null ? null : Ul(r[0]) ? { value: null, recurse: true } : { value: r, recurse: false };
}
async function py(r, e) {
let t = new Map();
cy(r, e, t);
for (let o of Array.from(t.keys())) {
let s = t.get(o);
if (b.isPromise(s)) {
let a = await s;
t.set(o, a);
}
}
return cy(r, e, t);
}
function Ul(r) {
let e = false;
if (U().get("IS_BROWSER"))
e = r instanceof TextDecoder;
else {
let { StringDecoder: t } = c0();
e = r instanceof t;
}
return r != null && !ArrayBuffer.isView(r) && (Array.isArray(r) || typeof r == "object" && !(r instanceof Le) && !(r instanceof Promise) && !e);
}
function jD(r) {
return r == null || b7(r) || Array.isArray(r) || typeof r == "object" && r instanceof Le || b.isTypedArray(r);
}
function b7(r) {
return r === null || typeof r != "object" && typeof r != "function";
}
function HD(r) {
return GD(r, w7);
}
function w7(r) {
return r instanceof Le ? { value: r.clone(), recurse: false } : Ul(r) ? { value: null, recurse: true } : { value: r, recurse: false };
}
var bh = class {
constructor(e) {
if (this.capacity = e, this.begin = 0, this.end = 0, e == null)
throw new RangeError("Can't create a ring buffer of unknown capacity.");
if (e < 1)
throw new RangeError("Can't create ring buffer of capacity < 1.");
this.data = new Array(e), this.doubledCapacity = 2 * e;
}
wrap(e) {
for (; e < 0; )
e += this.doubledCapacity;
return e % this.doubledCapacity;
}
get(e) {
if (e < 0)
throw new RangeError("Can't get item at a negative index.");
return this.data[e % this.capacity];
}
set(e, t) {
if (e < 0)
throw new RangeError("Can't set item at a negative index.");
this.data[e % this.capacity] = t;
}
length() {
let e = this.end - this.begin;
return e < 0 && (e = this.doubledCapacity + e), e;
}
isFull() {
return this.length() === this.capacity;
}
isEmpty() {
return this.length() === 0;
}
push(e) {
if (this.isFull())
throw new RangeError("Ring buffer is full.");
this.set(this.end, e), this.end = this.wrap(this.end + 1);
}
pushAll(e) {
for (let t of e)
this.push(t);
}
pop() {
if (this.isEmpty())
throw new RangeError("Ring buffer is empty.");
this.end = this.wrap(this.end - 1);
let e = this.get(this.end);
return this.set(this.end, void 0), e;
}
unshift(e) {
if (this.isFull())
throw new RangeError("Ring buffer is full.");
this.begin = this.wrap(this.begin - 1), this.set(this.begin, e);
}
shift() {
if (this.isEmpty())
throw new RangeError("Ring buffer is empty.");
let e = this.get(this.begin);
return this.set(this.begin, void 0), this.begin = this.wrap(this.begin + 1), e;
}
shuffleExcise(e) {
if (this.isEmpty())
throw new RangeError("Ring buffer is empty.");
let t = this.wrap(this.begin + e), n = this.get(t);
return this.set(t, this.pop()), n;
}
};
var ym = class extends bh {
constructor() {
super(ym.INITIAL_CAPACITY);
}
isFull() {
return false;
}
push(e) {
super.isFull() && this.expand(), super.push(e);
}
unshift(e) {
super.isFull() && this.expand(), super.unshift(e);
}
expand() {
let e = this.capacity * 2, t = new Array(e), n = this.length();
for (let o = 0; o < n; o++)
t[o] = this.get(this.wrap(this.begin + o));
this.data = t, this.capacity = e, this.doubledCapacity = 2 * this.capacity, this.begin = 0, this.end = n;
}
};
ym.INITIAL_CAPACITY = 32;
function m0(r) {
return new YD(r);
}
function wh(r) {
return new ZD(r);
}
function KD(r, e) {
return new d0(r, e);
}
function XD(r, e = Xa.FAIL) {
return new i$(r, e);
}
var tr = class {
async toArray() {
let e = [], t = await this.next();
for (; !t.done; )
e.push(t.value), t = await this.next();
return e;
}
async toArrayForTest() {
let e = this.prefetch(100), t = [], n = await e.next();
for (; !n.done; )
t.push(n.value), n = await e.next();
return t;
}
async resolveFully() {
let e = await this.next();
for (; !e.done; )
e = await this.next();
}
async resolveWhile(e) {
let t = await this.next(), n = e(t.value);
for (; !t.done && n; )
t = await this.next(), n = e(t.value);
}
handleErrors(e) {
return new o$(this, e);
}
filter(e) {
return new r$(this, e);
}
map(e) {
return new n$(this, e);
}
mapAsync(e) {
return new f0(this, e);
}
serialMapAsync(e) {
return new f0(this, e).serial();
}
flatmap(e) {
return new s$(this, e);
}
async forEachAsync(e) {
return this.map(e).resolveFully();
}
async serialForEach(e) {
return this.serialMapAsync(e).resolveWhile((t) => t === true);
}
rowMajorBatch(e, t = true) {
return new t$(this, e, t);
}
columnMajorBatch(e, t = true, n = p0) {
return this.rowMajorBatch(e, t).map((s) => WD(s, n));
}
concatenate(e, t) {
return new d0(m0([this, e]), t);
}
take(e) {
return e < 0 || e == null ? this : new e$(this, e);
}
skip(e) {
return e < 0 || e == null ? this : new QD(this, e);
}
prefetch(e) {
return new h0(this, e);
}
shuffle(e, t) {
return new a$(this, e, t);
}
serial() {
return new JD(this);
}
};
var YD = class extends tr {
constructor(e) {
super();
this.items = e, this.trav = 0;
}
summary() {
return `Array of ${this.items.length} items`;
}
async next() {
if (this.trav >= this.items.length)
return { value: null, done: true };
let e = this.items[this.trav];
return this.trav++, { value: HD(e), done: false };
}
};
var ZD = class extends tr {
constructor(e) {
super();
this.nextFn = e;
}
summary() {
return "Function call";
}
async next() {
try {
return this.nextFn();
} catch (e) {
throw e.message = `Error thrown while iterating through a dataset: ${e.message}`, e;
}
}
};
var JD = class extends tr {
constructor(e) {
super();
this.upstream = e, this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> Serial`;
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
async serialNext() {
return this.upstream.next();
}
};
var QD = class extends tr {
constructor(e, t) {
super();
this.upstream = e, this.maxCount = t, this.count = 0, this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> Skip`;
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
async serialNext() {
for (; this.count++ < this.maxCount; ) {
let e = await this.upstream.next();
if (e.done)
return e;
De(e.value);
}
return this.upstream.next();
}
};
var e$ = class extends tr {
constructor(e, t) {
super();
this.upstream = e, this.maxCount = t, this.count = 0;
}
summary() {
return `${this.upstream.summary()} -> Take`;
}
async next() {
return this.count++ >= this.maxCount ? { value: null, done: true } : this.upstream.next();
}
};
var t$ = class extends tr {
constructor(e, t, n = true) {
super();
this.upstream = e, this.batchSize = t, this.enableSmallLastBatch = n, this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> RowMajorBatch`;
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
async serialNext() {
let e = [];
for (; e.length < this.batchSize; ) {
let t = await this.upstream.next();
if (t.done)
return this.enableSmallLastBatch && e.length > 0 ? { value: e, done: false } : { value: null, done: true };
e.push(t.value);
}
return { value: e, done: false };
}
};
var r$ = class extends tr {
constructor(e, t) {
super();
this.upstream = e, this.predicate = t, this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> Filter`;
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
async serialNext() {
for (; ; ) {
let e = await this.upstream.next();
if (e.done || this.predicate(e.value))
return e;
De(e.value);
}
}
};
var n$ = class extends tr {
constructor(e, t) {
super();
this.upstream = e, this.transform = t;
}
summary() {
return `${this.upstream.summary()} -> Map`;
}
async next() {
let e = await this.upstream.next();
if (e.done)
return { value: null, done: true };
let t = ao.getTensorsInContainer(e.value), n = this.transform(e.value), o = ao.getTensorsInContainer(n);
for (let s of t)
ao.isTensorInList(s, o) || s.dispose();
return { value: n, done: false };
}
};
var o$ = class extends tr {
constructor(e, t) {
super();
this.upstream = e, this.handler = t, this.count = 0, this.lastRead = Promise.resolve({ value: null, done: false });
}
summary() {
return `${this.upstream.summary()} -> handleErrors`;
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
async serialNext() {
for (; ; )
try {
return await this.upstream.next();
} catch (e) {
if (!this.handler(e))
return { value: null, done: true };
}
}
};
var f0 = class extends tr {
constructor(e, t) {
super();
this.upstream = e, this.transform = t;
}
summary() {
return `${this.upstream.summary()} -> AsyncMap`;
}
async next() {
let e = await this.upstream.next();
if (e.done)
return { value: null, done: true };
let t = ao.getTensorsInContainer(e.value), n = await this.transform(e.value), o = ao.getTensorsInContainer(n);
for (let s of t)
ao.isTensorInList(s, o) || s.dispose();
return { value: n, done: false };
}
};
var bm = class extends tr {
constructor() {
super();
this.outputQueue = new ym(), this.lastRead = Promise.resolve({ value: null, done: false });
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
async serialNext() {
for (; this.outputQueue.length() === 0; )
if (!await this.pump())
return { value: null, done: true };
return { value: this.outputQueue.shift(), done: false };
}
};
var s$ = class extends bm {
constructor(e, t) {
super();
this.upstream = e, this.transform = t;
}
summary() {
return `${this.upstream.summary()} -> Flatmap`;
}
async pump() {
let e = await this.upstream.next();
if (e.done)
return false;
let t = ao.getTensorsInContainer(e.value), n = this.transform(e.value), o = ao.getTensorsInContainer(n);
this.outputQueue.pushAll(n);
for (let s of t)
ao.isTensorInList(s, o) || s.dispose();
return true;
}
};
var d0 = class extends tr {
constructor(e, t) {
super();
this.baseErrorHandler = t, this.lastRead = null, this.iterator = null, this.moreIterators = e;
}
summary() {
return "TODO: fill in upstream of chained summaries -> Chained";
}
async next() {
return this.lastRead = this.readFromChain(this.lastRead), this.lastRead;
}
async readFromChain(e) {
if (await e, this.iterator == null) {
let n = await this.moreIterators.next();
if (n.done)
return { value: null, done: true };
this.iterator = n.value, this.baseErrorHandler != null && (this.iterator = this.iterator.handleErrors(this.baseErrorHandler));
}
let t = await this.iterator.next();
return t.done ? (this.iterator = null, this.readFromChain(e)) : t;
}
};
var Xa;
(function(r) {
r[r.FAIL = 0] = "FAIL", r[r.SHORTEST = 1] = "SHORTEST", r[r.LONGEST = 2] = "LONGEST";
})(Xa || (Xa = {}));
var i$ = class extends tr {
constructor(e, t = Xa.FAIL) {
super();
this.iterators = e, this.mismatchMode = t, this.count = 0, this.currentPromise = null;
}
summary() {
return "{TODO: fill in upstream of zip summaries} -> Zip";
}
async nextState(e) {
await e;
let t = 0, n = 0;
function o(a) {
return a instanceof tr ? { value: a.next().then((l) => (t++, l.done && n++, l.value)), recurse: false } : { value: null, recurse: true };
}
let s = await py(this.iterators, o);
if (t === n)
return { value: null, done: true };
if (n > 0)
switch (this.mismatchMode) {
case Xa.FAIL:
throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);
case Xa.SHORTEST:
return { value: null, done: true };
case Xa.LONGEST:
default:
}
return this.count++, { value: s, done: false };
}
async next() {
return this.currentPromise = this.nextState(this.currentPromise), this.currentPromise;
}
};
var h0 = class extends tr {
constructor(e, t) {
super();
this.upstream = e, this.bufferSize = t, this.buffer = new bh(t);
}
summary() {
return `${this.upstream.summary()} -> Prefetch`;
}
refill() {
for (; !this.buffer.isFull(); ) {
let e = this.upstream.next();
this.buffer.push(e);
}
}
next() {
return this.refill(), this.buffer.shift();
}
};
var a$ = class extends h0 {
constructor(e, t, n) {
super(e, t);
this.upstream = e, this.windowSize = t, this.upstreamExhausted = false, this.random = qD.alea(n || b.now().toString()), this.lastRead = Promise.resolve({ value: null, done: false });
}
async next() {
return this.lastRead = this.lastRead.then(() => this.serialNext()), this.lastRead;
}
randomInt(e) {
return Math.floor(this.random() * e);
}
chooseIndex() {
return this.randomInt(this.buffer.length());
}
async serialNext() {
for (this.upstreamExhausted || this.refill(); !this.buffer.isEmpty(); ) {
let e = this.chooseIndex(), t = await this.buffer.shuffleExcise(e);
if (t.done)
this.upstreamExhausted = true;
else
return this.refill(), t;
}
return { value: null, done: true };
}
};
var Ti = class {
constructor() {
this.size = null;
}
batch(e, t = true) {
let n = this;
b.assert(e > 0, () => `batchSize needs to be positive, but it is
${e}`);
let o;
return this.size === 1 / 0 || this.size == null ? o = this.size : t ? o = Math.ceil(this.size / e) : o = Math.floor(this.size / e), Tn(async () => (await n.iterator()).columnMajorBatch(e, t, _7), o);
}
concatenate(e) {
let t = this, n;
return this.size === 1 / 0 || e.size === 1 / 0 ? n = 1 / 0 : this.size != null && e.size != null ? n = this.size + e.size : n = null, Tn(async () => (await t.iterator()).concatenate(await e.iterator()), n);
}
filter(e) {
let t = this, n;
return this.size === 1 / 0 ? n = 1 / 0 : n = null, Tn(async () => (await t.iterator()).filter((o) => V(() => e(o))), n);
}
async forEachAsync(e) {
return (await this.iterator()).forEachAsync(e);
}
map(e) {
let t = this;
return Tn(async () => (await t.iterator()).map((n) => V(() => e(n))), this.size);
}
mapAsync(e) {
let t = this;
return Tn(async () => (await t.iterator()).mapAsync(e), this.size);
}
prefetch(e) {
if (e == null)
throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");
let t = this;
return Tn(async () => (await t.iterator()).prefetch(e), this.size);
}
repeat(e) {
let t = this, n;
return this.size != null && e > 0 ? n = this.size * e : e === 0 ? n = 0 : this.size != null && (e === void 0 || e < 0) ? n = 1 / 0 : n = null, Tn(async () => {
let o = wh(async () => ({ value: await t.iterator(), done: false }));
return KD(o.take(e));
}, n);
}
skip(e) {
let t = this, n;
return this.size != null && e >= 0 && this.size >= e ? n = this.size - e : this.size != null && (this.size < e || e === void 0 || e < 0) ? n = 0 : n = null, Tn(async () => (await t.iterator()).skip(e), n);
}
shuffle(e, t, n = true) {
if (e == null || e < 0)
throw this.size == null ? new RangeError("`Dataset.shuffle()` requires bufferSize to be specified.") : new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);
let o = this, s = l$.alea(t || b.now().toString());
return Tn(async () => {
let a = s.int32();
return n && (a += s.int32()), (await o.iterator()).shuffle(e, a.toString());
}, this.size);
}
take(e) {
let t = this, n;
return this.size != null && this.size > e ? n = e : this.size != null && this.size <= e ? n = this.size : n = null, Tn(async () => (await t.iterator()).take(e), n);
}
async toArray() {
if (this.size === 1 / 0)
throw new Error("Can not convert infinite data stream to array.");
return (await this.iterator()).toArray();
}
async toArrayForTest() {
if (this.size === 1 / 0)
throw new Error("Can not convert infinite data stream to array.");
return (await this.iterator()).toArrayForTest();
}
};
Ti.MAX_BUFFER_SIZE = 1e4;
function Tn(r, e = null) {
return new class extends Ti {
constructor() {
super(...arguments);
this.size = e;
}
async iterator() {
return r();
}
}();
}
function u$(r) {
return Tn(async () => m0(r), r.length);
}
function c$(r) {
if (!Ul(r))
throw new Error("The argument to zip() must be an object or array.");
let e;
if (Array.isArray(r))
for (let t = 0; t < r.length; t++)
e = e == null ? r[t].size : Math.min(e, r[t].size);
else if (r instanceof Object)
for (let t in r)
e = e == null ? r[t].size : Math.min(e, r[t].size);
return Tn(async () => {
let t = await py(r, (n) => {
if (n instanceof Ti)
return { value: n.iterator(), recurse: false };
if (Ul(n))
return { value: null, recurse: true };
throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.");
});
return XD(t, Xa.SHORTEST);
}, e);
}
function _7(r) {
if (r === null)
return null;
let e = r[0];
return jD(e) ? { value: k7(r), recurse: false } : { value: null, recurse: true };
}
function k7(r) {
if (r.length === 0)
throw new Error("Can't make a batch of zero elements.");
return r[0] instanceof Le ? Xt(r) : Dr(r);
}
var _h = class extends Ti {
constructor(e) {
super();
this.input = e;
}
async iterator() {
return (await this.input.iterator()).decodeUTF8().split(`
`).map((o) => (o.endsWith("\r") && (o = o.slice(0, -1)), o));
}
};
var my = '"';
var kh = Symbol("out");
var p$ = Symbol("field");
var fy = Symbol("quote");
var g0 = Symbol("quoteafterquote");
var m$ = Symbol("quoteinquote");
var vh = class extends Ti {
constructor(e, t) {
super();
this.input = e, this.hasHeader = true, this.fullColumnNames = null, this.columnNamesValidated = false, this.columnConfigs = null, this.configuredColumnsOnly = false, this.delimiter = ",", this.delimWhitespace = false, this.base = new _h(e), t || (t = {}), this.hasHeader = t.hasHeader !== false, this.fullColumnNames = t.columnNames, this.columnConfigs = t.columnConfigs, this.configuredColumnsOnly = t.configuredColumnsOnly, t.delimWhitespace ? (b.assert(t.delimiter == null, () => "Delimiter should not be provided when delimWhitespace is true."), this.delimWhitespace = true, this.delimiter = " ") : this.delimiter = t.delimiter ? t.delimiter : ",";
}
async columnNames() {
return this.columnNamesValidated || await this.setColumnNames(), this.configuredColumnsOnly ? Object.keys(this.columnConfigs) : this.fullColumnNames;
}
async setColumnNames() {
let e = await this.maybeReadHeaderLine();
if (!this.fullColumnNames && !e)
throw new Error("Column names must be provided if there is no header line.");
this.fullColumnNames && e && b.assert(e.length === this.fullColumnNames.length, () => "The length of provided columnNames (" + this.fullColumnNames.length.toString() + ") does not match the length of the header line read from file (" + e.length.toString() + ")."), this.fullColumnNames || (this.fullColumnNames = e);
let t = this.fullColumnNames.reduce((o, s) => (o[s] = o[s] + 1 || 1, o), {}), n = Object.keys(t).filter((o) => t[o] > 1);
if (b.assert(n.length === 0, () => "Duplicate column names found: " + n.toString()), this.columnConfigs) {
for (let o of Object.keys(this.columnConfigs))
if (this.fullColumnNames.indexOf(o) === -1)
throw new Error('The key "' + o + '" provided in columnConfigs does not match any of the column names (' + this.fullColumnNames.toString() + ").");
}
this.columnNamesValidated = true;
}
async maybeReadHeaderLine() {
if (this.hasHeader) {
let t = await (await this.base.iterator()).next();
if (t.done)
throw new Error("No data was found for CSV parsing.");
let n = t.value;
return this.parseRow(n, false);
} else
return null;
}
async iterator() {
this.columnNamesValidated || await this.setColumnNames();
let e = await this.base.iterator();
return this.hasHeader && (e = e.skip(1)), e.map((t) => this.makeDataElement(t));
}
makeDataElement(e) {
let t = this.parseRow(e), n = {}, o = {};
for (let s = 0; s < this.fullColumnNames.length; s++) {
let a = this.fullColumnNames[s], i = this.columnConfigs ? this.columnConfigs[a] : null;
if (!(this.configuredColumnsOnly && !i)) {
let l = t[s], u = null;
if (l === "")
if (i && i.default !== void 0)
u = i.default;
else {
if (i && (i.required || i.isLabel))
throw new Error(`Required column ${a} is empty in this line: ${e}`);
u = void 0;
}
else {
let c = Number(l);
if (isNaN(c))
i && i.dtype === "bool" ? u = this.getBoolean(l) : u = l;
else if (!i || !i.dtype)
u = c;
else
switch (i.dtype) {
case "float32":
u = c;
break;
case "int32":
u = Math.floor(c);
break;
case "bool":
u = this.getBoolean(l);
break;
default:
u = c;
}
}
i && i.isLabel ? o[a] = u : n[a] = u;
}
}
return Object.keys(o).length === 0 ? n : { xs: n, ys: o };
}
getBoolean(e) {
return e === "1" || e.toLowerCase() === "true" ? 1 : 0;
}
parseRow(e, t = true) {
let n = [], o = 0, s = e.length, a = kh;
for (let i = 0; i < s; i++)
switch (a) {
case kh:
switch (e.charAt(i)) {
case my:
o = i + 1, a = fy;
break;
case this.delimiter:
if (o = i + 1, this.delimiter === " " && this.delimWhitespace)
break;
n.push(""), a = kh;
break;
default:
a = p$, o = i;
break;
}
break;
case p$:
switch (e.charAt(i)) {
case this.delimiter:
n.push(e.substring(o, i)), a = kh, o = i + 1;
break;
default:
}
break;
case fy:
switch (e.charAt(i)) {
case my:
a = g0;
break;
default:
}
break;
case g0:
switch (e.charAt(i)) {
case this.delimiter:
n.push(e.substring(o, i - 1)), a = kh, o = i + 1;
break;
case my:
a = fy;
break;
default:
a = m$;
break;
}
break;
case m$:
switch (e.charAt(i)) {
case my:
a = fy;
break;
default:
}
break;
default:
}
if (a === g0 ? n.push(e.substring(o, s - 1)) : n.push(e.substring(o)), t && n.length !== this.fullColumnNames.length)
throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);
return n;
}
};
var Ch = class extends tr {
constructor(e) {
super();
this.microphoneConfig = e, this.isClosed = false, this.fftSize = e.fftSize || 1024;
let t = Math.log2(this.fftSize);
if (this.fftSize < 0 || t < 4 || t > 14 || !Number.isInteger(t))
throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);
if (this.numFrames = e.numFramesPerSpectrogram || 43, this.sampleRateHz = e.sampleRateHz, this.columnTruncateLength = e.columnTruncateLength || this.fftSize, this.audioTrackConstraints = e.audioTrackConstraints, this.smoothingTimeConstant = e.smoothingTimeConstant || 0, this.includeSpectrogram = e.includeSpectrogram !== false, this.includeWaveform = e.includeWaveform === true, !this.includeSpectrogram && !this.includeWaveform)
throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.");
}
summary() {
return "microphone";
}
static async create(e = {}) {
if (U().get("IS_NODE"))
throw new Error("microphone API is only supported in browser environment.");
let t = new Ch(e);
return await t.start(), t;
}
async start() {
try {
this.stream = await navigator.mediaDevices.getUserMedia({ audio: this.audioTrackConstraints == null ? true : this.audioTrackConstraints, video: false });
} catch (n) {
throw new Error(`Error thrown while initializing video stream: ${n.message}`);
}
if (!this.stream)
throw new Error("Could not obtain audio from microphone.");
let e = window.AudioContext || window.webkitAudioContext;
if (this.audioContext = new e(), !this.sampleRateHz)
this.sampleRateHz = this.audioContext.sampleRate;
else if (this.audioContext.sampleRate !== this.sampleRateHz)
throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);
let t = this.audioContext.createMediaStreamSource(this.stream);
this.analyser = this.audioContext.createAnalyser(), this.analyser.fftSize = this.fftSize * 2, this.analyser.smoothingTimeConstant = this.smoothingTimeConstant, t.connect(this.analyser), this.freqData = new Float32Array(this.fftSize), this.timeData = new Float32Array(this.fftSize);
}
async next() {
if (this.isClosed)
return { value: null, done: true };
let e, t, n = await this.getAudioData();
if (this.includeSpectrogram) {
let o = this.flattenQueue(n.freqDataQueue);
e = this.getTensorFromAudioDataArray(o, [this.numFrames, this.columnTruncateLength, 1]);
}
if (this.includeWaveform) {
let o = this.flattenQueue(n.timeDataQueue);
t = this.getTensorFromAudioDataArray(o, [this.numFrames * this.fftSize, 1]);
}
return { value: { spectrogram: e, waveform: t }, done: false };
}
async capture() {
return (await this.next()).value;
}
async getAudioData() {
let e = [], t = [], n = 0;
return new Promise((o) => {
let s = setInterval(() => {
this.includeSpectrogram && (this.analyser.getFloatFrequencyData(this.freqData), this.freqData[0] === -1 / 0 && o({ freqDataQueue: e, timeDataQueue: t }), e.push(this.freqData.slice(0, this.columnTruncateLength))), this.includeWaveform && (this.analyser.getFloatTimeDomainData(this.timeData), t.push(this.timeData.slice())), ++n === this.numFrames && (clearInterval(s), o({ freqDataQueue: e, timeDataQueue: t }));
}, this.fftSize / this.sampleRateHz * 1e3);
});
}
stop() {
this.isClosed || (this.isClosed = true, this.analyser.disconnect(), this.audioContext.close(), this.stream != null && this.stream.getTracks().length > 0 && this.stream.getTracks()[0].stop());
}
toArray() {
throw new Error("Can not convert infinite audio stream to array.");
}
getSampleRate() {
return this.sampleRateHz;
}
flattenQueue(e) {
let t = e[0].length, n = new Float32Array(e.length * t);
return e.forEach((o, s) => n.set(o, s * t)), n;
}
getTensorFromAudioDataArray(e, t) {
let n = new Float32Array(b.sizeFromShape(t));
return n.set(e, n.length - e.length), Dr(n, t);
}
};
var Ih = class extends tr {
constructor(e, t) {
super();
if (this.webcamVideoElement = e, this.webcamConfig = t, this.isClosed = true, this.resize = false, this.needToResize())
if (this.resize = true, this.cropSize = [this.webcamConfig.resizeHeight, this.webcamConfig.resizeWidth], this.cropBoxInd = $t([0], "int32"), this.webcamConfig.centerCrop) {
let n = this.webcamConfig.resizeWidth * 1 / this.webcamVideoElement.width, o = this.webcamConfig.resizeHeight * 1 / this.webcamVideoElement.height, s = (1 - n) / 2, a = (1 - o) / 2, i = s + n, l = o + a;
this.cropBox = ki([a, s, l, i], [1, 4]);
} else
this.cropBox = ki([0, 0, 1, 1], [1, 4]);
}
summary() {
return "webcam";
}
static async create(e, t = {}) {
if (U().get("IS_NODE"))
throw new Error("tf.data.webcam is only supported in browser environment.");
if (!e) {
if (e = document.createElement("video"), !t.resizeWidth || !t.resizeHeight)
throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");
e.width = t.resizeWidth, e.height = t.resizeHeight;
}
let n = new Ih(e, t);
return await n.start(), n;
}
async start() {
this.webcamConfig.facingMode && b.assert(this.webcamConfig.facingMode === "user" || this.webcamConfig.facingMode === "environment", () => `Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);
try {
this.stream = await navigator.mediaDevices.getUserMedia({ video: { deviceId: this.webcamConfig.deviceId, facingMode: this.webcamConfig.facingMode ? this.webcamConfig.facingMode : "user", width: this.webcamVideoElement.width, height: this.webcamVideoElement.height } });
} catch (e) {
throw e.message = `Error thrown while initializing video stream: ${e.message}`, e;
}
if (!this.stream)
throw new Error("Could not obtain video from webcam.");
try {
this.webcamVideoElement.srcObject = this.stream;
} catch (e) {
console.log(e), this.webcamVideoElement.src = window.URL.createObjectURL(this.stream);
}
return this.webcamVideoElement.play(), this.isClosed = false, new Promise((e) => {
this.webcamVideoElement.onloadedmetadata = () => {
e();
};
});
}
async next() {
if (this.isClosed)
return { value: null, done: true };
let e;
try {
e = Gg.fromPixels(this.webcamVideoElement);
} catch (t) {
throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`);
}
if (this.resize)
try {
return { value: this.cropAndResizeFrame(e), done: false };
} catch (t) {
throw new Error(`Error thrown cropping the video: ${t.message}`);
} finally {
e.dispose();
}
else
return { value: e, done: false };
}
needToResize() {
return !!(this.webcamConfig.resizeWidth && this.webcamConfig.resizeHeight && (this.webcamVideoElement.width !== this.webcamConfig.resizeWidth || this.webcamVideoElement.height !== this.webcamConfig.resizeHeight));
}
cropAndResizeFrame(e) {
return V(() => {
let t = mr(Y(e, "float32"), 0), n;
n = Cn.cropAndResize(t, this.cropBox, this.cropBoxInd, this.cropSize, "bilinear");
let o = n.shape;
return F(n, o.slice(1));
});
}
async capture() {
return (await this.next()).value;
}
stop() {
this.stream.getTracks().forEach((t) => t.stop());
try {
this.webcamVideoElement.srcObject = null;
} catch (t) {
console.log(t), this.webcamVideoElement.src = null;
}
this.isClosed = true;
}
toArray() {
throw new Error("Can not convert infinite video stream to array.");
}
};
var Sh = class {
};
var dy = class extends tr {
split(e) {
return new f$(this, e);
}
};
var f$ = class extends dy {
constructor(e, t) {
super();
this.upstream = e, this.impl = new d$(e, t);
}
summary() {
return this.impl.summary();
}
async next() {
return this.impl.next();
}
};
var d$ = class extends bm {
constructor(e, t) {
super();
this.upstream = e, this.separator = t, this.carryover = "";
}
summary() {
return `${this.upstream.summary()} -> Split('${this.separator}')`;
}
async pump() {
let e = await this.upstream.next();
if (e.done)
return this.carryover === "" ? false : (this.outputQueue.push(this.carryover), this.carryover = "", true);
let t = e.value.split(this.separator);
t[0] = this.carryover + t[0];
for (let n of t.slice(0, -1))
this.outputQueue.push(n);
return this.carryover = t[t.length - 1], true;
}
};
var x0 = class extends tr {
decodeUTF8() {
return new h$(this);
}
};
var h$ = class extends dy {
constructor(e) {
super();
this.upstream = e, this.impl = new g$(e);
}
summary() {
return this.impl.summary();
}
async next() {
return this.impl.next();
}
};
var g$ = class extends bm {
constructor(e) {
super();
if (this.upstream = e, U().get("IS_BROWSER"))
this.decoder = new TextDecoder("utf-8");
else {
let { StringDecoder: t } = c0();
this.decoder = new t("utf8");
}
}
summary() {
return `${this.upstream.summary()} -> Utf8`;
}
async pump() {
let e = await this.upstream.next(), t;
if (e.done)
return false;
t = e.value;
let n;
return U().get("IS_BROWSER") ? n = this.decoder.decode(t, { stream: true }) : n = this.decoder.write(Buffer.from(t.buffer)), this.outputQueue.push(n), true;
}
};
var Nh = class extends x0 {
constructor(e, t = {}) {
super();
this.file = e, this.options = t, b.assert(e instanceof Uint8Array || (U().get("IS_BROWSER") ? e instanceof File || e instanceof Blob : false), () => "FileChunkIterator only supports File, Blob and Uint8Array right now."), this.offset = t.offset || 0, this.chunkSize = t.chunkSize || 1024 * 1024;
}
summary() {
return `FileChunks ${this.file}`;
}
async next() {
return this.offset >= (this.file instanceof Uint8Array ? this.file.byteLength : this.file.size) ? { value: null, done: true } : { value: await new Promise((t, n) => {
let o = this.offset + this.chunkSize;
if (this.file instanceof Uint8Array)
t(new Uint8Array(this.file.slice(this.offset, o)));
else {
let s = new FileReader();
s.onload = (i) => {
let l = s.result;
if (l instanceof ArrayBuffer && (l = new Uint8Array(l)), !(l instanceof Uint8Array))
return n(new TypeError("FileReader returned unknown type."));
t(l);
}, s.onabort = (i) => n(new Error("Aborted")), s.onerror = (i) => n(new Error(i.type));
let a = this.file.slice(this.offset, o);
s.readAsArrayBuffer(a);
}
this.offset = o;
}), done: false };
}
};
async function x$(r, e = {}, t) {
let n, o;
typeof r == "string" ? n = r : (n = r.url, o = v7(r));
let s = await (t || b.fetch)(n, o);
if (s.ok) {
let a = new Uint8Array(await s.arrayBuffer());
return new Nh(a, e);
} else
throw new Error(s.statusText);
}
var v7 = (r) => ({ method: r.method, headers: r.headers, body: r.body, mode: r.mode, credentials: r.credentials, cache: r.cache, redirect: r.redirect, referrer: r.referrer, integrity: r.integrity });
function hy(r) {
return typeof r == "string" && r.substr(0, 7) === "file://";
}
var Th = class extends Sh {
constructor(e, t = {}) {
super();
this.input = e, this.options = t;
}
async iterator() {
if (hy(this.input) && U().get("IS_NODE")) {
let e = Lc("fs");
this.input = e.readFileSync(this.input.substr(7));
}
return new Nh(this.input, this.options);
}
};
var Eh = class extends Sh {
constructor(e, t = {}) {
super();
this.url = e, this.fileOptions = t;
}
async iterator() {
return hy(this.url) ? new Th(this.url, this.fileOptions).iterator() : x$(this.url, this.fileOptions);
}
};
function y$(r, e = {}) {
return new vh(new Eh(r), e);
}
function b$(r) {
let e = wh(r);
return Tn(async () => e);
}
function w$(r) {
return Tn(async () => {
let e = await r();
return wh(() => e.next());
});
}
async function _$(r, e) {
return Ih.create(r, e);
}
async function k$(r) {
return Ch.create(r);
}
var y0 = "3.10.0";
function te(r, e) {
Array.isArray(r) || (r = [r]), r.forEach((t) => {
t != null && b.assert(t.dtype !== "complex64", () => `${e} does not support complex64 tensors in the CPU backend.`);
});
}
var C7 = Gr.whereImpl;
var pc = class extends Js {
constructor() {
super();
this.blockSize = 48, this.firstUse = true, this.data = new pl(this, Es());
}
nextDataId() {
return pc.nextDataId++;
}
write(e, t, n) {
this.firstUse && (this.firstUse = false, U().get("IS_NODE") && I.warn(`
============================
Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
============================`));
let o = { id: this.nextDataId() };
return this.data.set(o, { values: e, dtype: n, refCount: 1 }), o;
}
makeTensorInfo(e, t, n) {
let o;
if (t === "string" && n != null && n.length > 0 && b.isString(n[0])) {
let s = n.map((a) => b.encodeString(a));
o = this.write(s, e, t);
} else
o = this.write(n, e, t);
return { dataId: o, shape: e, dtype: t };
}
refCount(e) {
return this.data.has(e) ? this.data.get(e).refCount : 0;
}
incRef(e) {
let t = this.data.get(e);
t.refCount++;
}
decRef(e) {
if (this.data.has(e)) {
let t = this.data.get(e);
t.refCount--;
}
}
move(e, t, n, o, s) {
this.data.set(e, { values: t, dtype: o, refCount: s });
}
numDataIds() {
return this.data.numDataIds();
}
async read(e) {
return this.readSync(e);
}
readSync(e) {
let { dtype: t, complexTensorInfos: n } = this.data.get(e);
if (t === "complex64") {
let o = this.readSync(n.real.dataId), s = this.readSync(n.imag.dataId);
return I.mergeRealAndImagArrays(o, s);
}
return this.data.get(e).values;
}
bufferSync(e) {
let t = this.readSync(e.dataId), n = t;
if (e.dtype === "string")
try {
n = t.map((o) => b.decodeString(o));
} catch (o) {
throw new Error("Failed to decode encoded string bytes into utf-8");
}
return Ie(e.shape, e.dtype, n);
}
makeOutput(e, t, n) {
let o = this.write(e, t, n);
return Es().makeTensorFromDataId(o, t, n, this);
}
disposeData(e, t = false) {
if (this.data.has(e)) {
if (this.data.get(e).refCount--, !t && this.data.get(e).refCount > 0)
return false;
let { complexTensorInfos: n } = this.data.get(e);
n != null && (this.disposeData(n.real.dataId, true), this.disposeData(n.imag.dataId, true)), this.data.delete(e);
}
return true;
}
disposeIntermediateTensorInfo(e) {
this.disposeData(e.dataId);
}
async time(e) {
let t = b.now();
return e(), { kernelMs: b.now() - t };
}
memory() {
return { unreliable: true, reasons: ["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."] };
}
where(e) {
te([e], "where");
let t = this.readSync(e.dataId);
return C7(e.shape, t);
}
dispose() {
}
floatPrecision() {
return 32;
}
epsilon() {
return super.epsilon();
}
};
pc.nextDataId = 0;
var Ay = {};
qe(Ay, { addImpl: () => w0, bincountImpl: () => km, bincountReduceImpl: () => gy, ceilImpl: () => _0, concatImpl: () => mc, equalImpl: () => k0, expImpl: () => C0, expm1Impl: () => S0, floorImpl: () => N0, gatherNdImpl: () => xy, gatherV2Impl: () => yy, greaterEqualImpl: () => E0, greaterImpl: () => T0, lessEqualImpl: () => D0, lessImpl: () => A0, linSpaceImpl: () => by, logImpl: () => $0, maxImpl: () => wy, maximumImpl: () => R0, minimumImpl: () => F0, multiplyImpl: () => Ah, negImpl: () => O0, notEqualImpl: () => P0, prodImpl: () => M0, rangeImpl: () => dc, rsqrtImpl: () => L0, sigmoidImpl: () => K$, simpleAbsImpl: () => b0, sliceImpl: () => hc, sparseFillEmptyRowsImpl: () => _y, sparseReshapeImpl: () => ky, sparseSegmentReductionImpl: () => Cm, sqrtImpl: () => Z$, squaredDifferenceImpl: () => B0, stridedSliceImpl: () => vy, stringNGramsImpl: () => Cy, stringSplitImpl: () => Iy, stringToHashBucketFastImpl: () => Sy, subImpl: () => V0, tileImpl: () => Ny, topKImpl: () => Ty, transposeImpl: () => vm, uniqueImpl: () => Ey });
function b0(r) {
let e = new Float32Array(r.length);
for (let t = 0; t < r.length; ++t)
e[t] = Math.abs(r[t]);
return e;
}
var I7 = (r) => {
let { x: e } = r.inputs, t = r.backend;
te(e, "abs");
let n = new Float32Array(b.sizeFromShape(e.shape)), o = t.data.get(e.dataId).values;
return n = b0(o), t.makeOutput(n, e.shape, e.dtype);
};
var C$ = { kernelName: ti, backendName: "cpu", kernelFunc: I7 };
function Ze(r) {
return (e, t, n, o, s) => {
let a = I.assertAndGetBroadcastShape(e, t), i = a.length, l = b.computeStrides(a), u = b.sizeFromShape(a), c = b.getTypedArrayFromDType(s, u), p = e.length, m = t.length, f = b.computeStrides(e), d = b.computeStrides(t), h = I.getBroadcastDims(e, a), g = I.getBroadcastDims(t, a);
if (h.length + g.length === 0)
for (let x = 0; x < c.length; ++x)
c[x] = r(n[x % n.length], o[x % o.length]);
else
for (let x = 0; x < c.length; ++x) {
let y = b.indexToLoc(x, i, l), w = y.slice(-p);
h.forEach((D) => w[D] = 0);
let _ = b.locToIndex(w, p, f), C = y.slice(-m);
g.forEach((D) => C[D] = 0);
let A = b.locToIndex(C, m, d);
c[x] = r(n[_], o[A]);
}
return [c, a];
};
}
function wr(r) {
let { inputs: e, backend: t } = r, { real: n, imag: o } = e, s = t.data.get(n.dataId).values, a = t.data.get(o.dataId).values, i = t.makeTensorInfo(n.shape, "complex64"), l = t.data.get(i.dataId);
return l.complexTensorInfos = { real: t.makeTensorInfo(n.shape, "float32", s), imag: t.makeTensorInfo(o.shape, "float32", a) }, i;
}
var I$ = { kernelName: qc, backendName: "cpu", kernelFunc: wr };
function wm(r, e, t = "float32") {
if (t === "complex64") {
let o = wm(r, e, "float32"), s = wm(r, e, "float32");
return wr({ inputs: { real: o, imag: s }, backend: r });
}
let n = b.makeZerosTypedArray(b.sizeFromShape(e), t);
return r.makeTensorInfo(e, t, n);
}
function Wr(r) {
let { inputs: e, backend: t } = r, { x: n } = e;
return t.incRef(n.dataId), { dataId: n.dataId, shape: n.shape, dtype: n.dtype };
}
var S$ = { kernelName: ro, backendName: "cpu", kernelFunc: Wr };
function vo(r) {
let { inputs: e, backend: t } = r, { input: n } = e, o = t.data.get(n.dataId).complexTensorInfos.real, s = t.data.get(o.dataId).values;
return t.makeTensorInfo(o.shape, o.dtype, s);
}
var N$ = { kernelName: mp, backendName: "cpu", kernelFunc: vo };
function Co(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { dtype: s } = n;
if (s === "complex64") {
if (o.dtype === "complex64")
return Wr({ inputs: { x: o }, backend: t });
let a = wm(t, o.shape, o.dtype), i = Co({ inputs: { x: o }, backend: t, attrs: { dtype: "float32" } }), l = wr({ inputs: { real: i, imag: a }, backend: t });
return t.disposeIntermediateTensorInfo(a), t.disposeIntermediateTensorInfo(i), l;
}
if (o.dtype === "complex64") {
let a = vo({ inputs: { input: o }, backend: t }), i = Co({ inputs: { x: a }, backend: t, attrs: { dtype: s } });
return t.disposeIntermediateTensorInfo(a), i;
}
if (!b.hasEncodingLoss(o.dtype, s)) {
let a = Wr({ inputs: { x: o }, backend: t });
return { dataId: a.dataId, shape: a.shape, dtype: s };
}
if (s === "int32") {
let a = t.data.get(o.dataId).values, i = Int32Array.from(a);
return t.makeTensorInfo(o.shape, "int32", i);
}
if (s === "bool") {
let a = t.data.get(o.dataId).values, i = b.toTypedArray([0], o.dtype), [l, u] = Ze((c, p) => c !== p ? 1 : 0)(o.shape, [], a, i, "bool");
return t.makeTensorInfo(u, "bool", l);
}
throw new Error(`Error in Cast: failed to cast ${o.dtype} to ${s}`);
}
var T$ = { kernelName: eo, backendName: "cpu", kernelFunc: Co };
function rt(r, e, t, n) {
return t == null ? ({ inputs: o, backend: s }) => {
let { a, b: i } = o, l = s;
te([a, i], r);
let u = l.data.get(a.dataId).values, c = l.data.get(i.dataId).values, p = a.dtype === "string" ? I.fromUint8ToStringArray(u) : u, m = a.dtype === "string" ? I.fromUint8ToStringArray(c) : c, f = n || a.dtype, [d, h] = e(a.shape, i.shape, p, m, f);
return l.makeTensorInfo(h, f, d);
} : ({ inputs: o, backend: s }) => {
let { a, b: i } = o, l = s;
if (a.dtype === "complex64" || i.dtype === "complex64") {
let u = Co({ inputs: { x: a }, backend: l, attrs: { dtype: "complex64" } }), c = l.data.get(u.dataId), p = c.complexTensorInfos.real, m = c.complexTensorInfos.imag, f = l.data.get(p.dataId).values, d = l.data.get(m.dataId).values, h = Co({ inputs: { x: i }, backend: l, attrs: { dtype: "complex64" } }), g = l.data.get(h.dataId), x = g.complexTensorInfos.real, y = g.complexTensorInfos.imag, w = l.data.get(x.dataId).values, _ = l.data.get(y.dataId).values, [C, A, D] = t(a.shape, i.shape, f, d, w, _), R = l.makeTensorInfo(D, "float32", C), P = l.makeTensorInfo(D, "float32", A), L = wr({ inputs: { real: R, imag: P }, backend: l });
return l.disposeIntermediateTensorInfo(u), l.disposeIntermediateTensorInfo(h), l.disposeIntermediateTensorInfo(R), l.disposeIntermediateTensorInfo(P), L;
} else {
let u = l.data.get(a.dataId).values, c = l.data.get(i.dataId).values, p = n || a.dtype, [m, f] = e(a.shape, i.shape, u, c, p);
return l.makeTensorInfo(f, p, m);
}
};
}
function _m(r) {
return (e, t, n, o, s, a) => {
let i = I.assertAndGetBroadcastShape(e, t), l = b.sizeFromShape(i), u = i.length, c = b.computeStrides(i), p = b.getTypedArrayFromDType("float32", l), m = b.getTypedArrayFromDType("float32", l), f = I.getBroadcastDims(e, i), d = I.getBroadcastDims(t, i), h = I.mergeRealAndImagArrays(n, o), g = I.mergeRealAndImagArrays(s, a), x = e.length, y = b.computeStrides(e), w = t.length, _ = b.computeStrides(t);
if (f.length + d.length === 0)
for (let C = 0; C < p.length; C++) {
let A = C % h.length, D = C % g.length, R = r(h[A * 2], h[A * 2 + 1], g[D * 2], g[D * 2 + 1]);
p[C] = R.real, m[C] = R.imag;
}
else
for (let C = 0; C < p.length; C++) {
let A = b.indexToLoc(C, u, c), D = A.slice(-x);
f.forEach((W) => D[W] = 0);
let R = b.locToIndex(D, x, y), P = A.slice(-w);
d.forEach((W) => P[W] = 0);
let L = b.locToIndex(P, w, _), G = r(h[R * 2], h[R * 2 + 1], g[L * 2], g[L * 2 + 1]);
p[C] = G.real, m[C] = G.imag;
}
return [p, m, i];
};
}
var w0 = Ze((r, e) => r + e);
var S7 = _m((r, e, t, n) => ({ real: r + t, imag: e + n }));
var Ya = rt(jn, w0, S7);
var E$ = { kernelName: jn, backendName: "cpu", kernelFunc: Ya };
function km(r, e, t, n, o) {
let s = b.sizeFromShape(n), a = b.makeZerosTypedArray(o, t);
for (let i = 0; i < r.length; i++) {
let l = r[i];
if (l < 0)
throw new Error("Input x must be non-negative!");
l >= o || (s > 0 ? a[l] += e[i] : a[l] += 1);
}
return a;
}
function gy(r, e, t, n = false) {
let o = r.shape[0], s = r.shape[1], a = Ie([o, t], e.dtype);
for (let i = 0; i < o; i++)
for (let l = 0; l < s; l++) {
let u = r.get(i, l);
if (u < 0)
throw new Error("Input x must be non-negative!");
u >= t || (n ? a.set(1, i, u) : e.size > 0 ? a.set(a.get(i, u) + e.get(i, l), i, u) : a.set(a.get(i, u) + 1, i, u));
}
return a;
}
function dn(r) {
return (e, t, n) => {
let o = b.getTypedArrayFromDType(t, e.length);
for (let s = 0; s < e.length; ++s)
o[s] = r(e[s], n);
return o;
};
}
function $e(r, e, t) {
return ({ inputs: n, attrs: o, backend: s }) => {
let { x: a } = n;
if (te(a, r), a.dtype === "string" || t === "string")
throw new Error("unaryKernelFunc does not support string input/output");
let i = s, l = i.data.get(a.dataId).values, u = b.sizeFromShape(a.shape), c = t || a.dtype, p = b.getArrayFromDType(c, u);
for (let m = 0; m < u; ++m)
p[m] = e(l[m], o);
return i.makeTensorInfo(a.shape, c, p);
};
}
function Io(r, e, t) {
return ({ inputs: n, attrs: o, backend: s }) => {
let { x: a } = n;
if (te(a, r), a.dtype === "string" || t === "string")
throw new Error("unaryKernelFunc does not support string input/output");
let i = s, l = i.data.get(a.dataId).values, u = t || a.dtype, c = e(l, u, o);
return i.makeTensorInfo(a.shape, u, c);
};
}
var _0 = dn((r) => Math.ceil(r));
var N7 = Io(Po, _0);
var A$ = { kernelName: Po, backendName: "cpu", kernelFunc: N7 };
function mc(r, e, t, n) {
let o = b.getArrayFromDType(t, b.sizeFromShape(e));
if (n && t !== "string") {
let s = 0;
r.forEach((a) => {
let i = b.sizeFromShape(a.shape);
o.set(a.vals, s), s += i;
});
} else {
let s = 0;
r.forEach((a) => {
let i = t === "string" ? I.fromUint8ToStringArray(a.vals) : a.vals, l = 0;
for (let u = 0; u < a.shape[0]; ++u) {
let c = u * e[1] + s;
for (let p = 0; p < a.shape[1]; ++p)
o[c + p] = i[l++];
}
s += a.shape[1];
});
}
return o;
}
var k0 = Ze((r, e) => r === e ? 1 : 0);
var v0 = rt(Xi, k0, null, "bool");
var D$ = { kernelName: Xi, backendName: "cpu", kernelFunc: v0 };
var C0 = dn((r) => Math.exp(r));
var I0 = Io(jo, C0, "float32");
var $$ = { kernelName: jo, backendName: "cpu", kernelFunc: I0 };
var S0 = dn((r) => Math.expm1(r));
var T7 = Io(Yi, S0);
var R$ = { kernelName: Yi, backendName: "cpu", kernelFunc: T7 };
var N0 = dn((r) => Math.floor(r));
var E7 = Io(Ho, N0);
var F$ = { kernelName: Ho, backendName: "cpu", kernelFunc: E7 };
function xy(r, e, t, n, o, s, a, i, l) {
let u = Ie([n, s], t);
for (let c = 0; c < n; c++) {
let p = [], m = 0;
for (let f = 0; f < o; f++) {
let d = r[c * o + f];
m += d * a[f], p.push(d);
}
if (m < 0 || m >= l / s)
throw new Error(`Invalid indices: ${p} does not index into ${i}`);
for (let f = 0; f < s; f++)
u.values[c * s + f] = e.get(...e.indexToLoc(m * s + f));
}
return u;
}
function yy(r, e, t) {
let n = Ie(t, r.dtype);
for (let o = 0; o < n.size; ++o) {
let a = n.indexToLoc(o).slice(), i = a[0], l = a[2], u = e.locToIndex([i, l]);
a[2] = e.values[u];
let c = r.locToIndex(a);
n.values[o] = r.values[c];
}
return n;
}
var T0 = Ze((r, e) => r > e ? 1 : 0);
var A7 = rt(Qi, T0, null, "bool");
var O$ = { kernelName: Qi, backendName: "cpu", kernelFunc: A7 };
var E0 = Ze((r, e) => r >= e ? 1 : 0);
var D7 = rt(Xo, E0, null, "bool");
var P$ = { kernelName: Xo, backendName: "cpu", kernelFunc: D7 };
var A0 = Ze((r, e) => r < e ? 1 : 0);
var $7 = rt(na, A0, null, "bool");
var M$ = { kernelName: na, backendName: "cpu", kernelFunc: $7 };
var D0 = Ze((r, e) => r <= e ? 1 : 0);
var R7 = rt(oa, D0, null, "bool");
var L$ = { kernelName: oa, backendName: "cpu", kernelFunc: R7 };
function by(r, e, t) {
let n = (e - r) / (t - 1), o = b.makeZerosTypedArray(t, "float32");
o[0] = r;
for (let s = 1; s < o.length; s++)
o[s] = o[s - 1] + n;
return o;
}
var $0 = dn((r) => Math.log(r));
var F7 = Io(Zo, $0);
var z$ = { kernelName: Zo, backendName: "cpu", kernelFunc: F7 };
function wy(r, e, t, n) {
let o = b.getTypedArrayFromDType(n, b.sizeFromShape(t));
for (let s = 0; s < o.length; ++s) {
let a = s * e, i = r[a];
for (let l = 0; l < e; ++l) {
let u = r[a + l];
(Number.isNaN(u) || u > i) && (i = u);
}
o[s] = i;
}
return o;
}
var R0 = Ze((r, e) => Math.max(r, e));
var O7 = rt(Qo, R0);
var B$ = { kernelName: Qo, backendName: "cpu", kernelFunc: O7 };
var F0 = Ze((r, e) => Math.min(r, e));
var P7 = rt(ns, F0);
var V$ = { kernelName: ns, backendName: "cpu", kernelFunc: P7 };
var Ah = Ze((r, e) => r * e);
var M7 = _m((r, e, t, n) => ({ real: r * t - e * n, imag: r * n + e * t }));
var fc = rt(ss, Ah, M7);
var G$ = { kernelName: ss, backendName: "cpu", kernelFunc: fc };
function O0(r, e, t) {
let n = b.createScalarValue(-1, t);
return Ah([], e, n, r, t);
}
function L7(r) {
let { inputs: e, backend: t } = r, { x: n } = e;
te(n, "neg");
let o = t.data.get(n.dataId).values, [s, a] = O0(o, n.shape, n.dtype);
return t.makeTensorInfo(a, n.dtype, s);
}
var W$ = { kernelName: ii, backendName: "cpu", kernelFunc: L7 };
var P0 = Ze((r, e) => r !== e ? 1 : 0);
var z7 = rt(la, P0, null, "bool");
var U$ = { kernelName: la, backendName: "cpu", kernelFunc: z7 };
function vm(r, e, t, n, o) {
let s = e.length, a = b.sizeFromShape(e), i = b.computeStrides(e), l = b.computeStrides(o), u = b.getTypedArrayFromDType(t, b.sizeFromShape(o));
for (let c = 0; c < a; ++c) {
let p = b.indexToLoc(c, s, i), m = new Array(p.length);
for (let d = 0; d < m.length; d++)
m[d] = p[n[d]];
let f = b.locToIndex(m, s, l);
u[f] = r[c];
}
return u;
}
function rr(r) {
let { inputs: e, attrs: t, backend: n } = r, { x: o } = e, { perm: s } = t;
te(o, "transpose");
let a = o.shape.length, i = new Array(a);
for (let p = 0; p < i.length; p++)
i[p] = o.shape[s[p]];
let l = n.data.get(o.dataId).values, u = vm(l, o.shape, o.dtype, s, i);
return { dataId: n.write(u, i, o.dtype), shape: i, dtype: o.dtype };
}
var j$ = { kernelName: Is, backendName: "cpu", kernelFunc: rr };
function M0(r, e, t, n) {
let [o, s] = I.computeOutAndReduceShapes(r, n), a = hr(e, "int32"), i = b.makeZerosTypedArray(b.sizeFromShape(o), a), l = b.sizeFromShape(s);
for (let u = 0; u < i.length; ++u) {
let c = u * l, p = 1;
for (let m = 0; m < l; ++m)
p *= t[c + m];
i[u] = p;
}
return { outVals: i, outShape: o, outDtype: a };
}
function B7(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, keepDims: a } = n;
te(o, "prod");
let i = o.shape.length, l = b.parseAxisParam(s, o.shape), u = I.getAxesPermutation(l, i), c = l, p = o, m = [];
u != null && (p = rr({ inputs: { x: o }, backend: t, attrs: { perm: u } }), m.push(p), c = I.getInnerMostAxes(c.length, i));
let f = t.data.get(p.dataId).values, { outVals: d, outShape: h, outDtype: g } = M0(p.shape, p.dtype, f, c), x = h;
return a && (x = I.expandShapeToKeepDim(h, l)), m.forEach((y) => t.disposeIntermediateTensorInfo(y)), t.makeTensorInfo(x, g, d);
}
var H$ = { kernelName: ma, backendName: "cpu", kernelFunc: B7 };
function dc(r, e, t, n) {
let o = r === e, s = r < e && t < 0, a = e < r && t > 1;
if (o || s || a)
return b.makeZerosTypedArray(0, n);
let i = Math.abs(Math.ceil((e - r) / t)), l = b.makeZerosTypedArray(i, n);
e < r && t === 1 && (t = -1), l[0] = r;
for (let u = 1; u < l.length; u++)
l[u] = l[u - 1] + t;
return l;
}
var L0 = dn((r) => 1 / Math.sqrt(r));
var V7 = Io(hs, L0);
var q$ = { kernelName: hs, backendName: "cpu", kernelFunc: V7 };
var K$ = dn((r) => 1 / (1 + Math.exp(-r)));
var z0 = $e(xs, (r) => 1 / (1 + Math.exp(-r)));
var X$ = { kernelName: xs, backendName: "cpu", kernelFunc: z0 };
function hc(r, e, t, n, o) {
let s = pr.isSliceContinous(n, e, t), a = b.sizeFromShape(t), i = b.computeStrides(n);
if (s) {
let p = pr.computeFlatOffset(e, i);
return o === "string" ? r.slice(p, p + a) : r.subarray(p, p + a);
}
let l = o === "string" ? I.fromUint8ToStringArray(r) : r, u = Ie(n, o, l), c = Ie(t, o);
for (let p = 0; p < c.size; ++p) {
let m = c.indexToLoc(p), f = m.map((d, h) => d + e[h]);
c.set(u.get(...f), ...m);
}
return o === "string" ? I.fromStringArrayToUint8(c.values) : c.values;
}
function So(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { begin: s, size: a } = n;
te(o, "slice");
let [i, l] = pr.parseSliceParams(o, s, a);
pr.assertParamsValid(o, i, l);
let u = t.data.get(o.dataId).values, c = hc(u, i, l, o.shape, o.dtype);
return t.makeTensorInfo(l, o.dtype, c);
}
var Y$ = { kernelName: pi, backendName: "cpu", kernelFunc: So };
function _y(r, e, t, n, o, s, a) {
let i = e[0], l = s[0], u = new Array(l), c = new Array(i), p = e[1];
if (l === 0) {
if (i !== 0)
throw new Error(`Received SparseTensor with denseShape[0] = 0 but
indices.shape[0] = ${i}`);
let g = b.getArrayFromDType(t, 0), x = b.getArrayFromDType(o, 0);
return [g, [0, p], x, u, c];
}
let m = true, f = 0, d = new Array(l).fill(0);
for (let g = 0; g < i; ++g) {
let x = r[g * p];
if (x < 0)
throw new Error(`indices(${g}, 0) is invalid: ${x} < 0`);
if (x >= l)
throw new Error(`indices(${g}, 0) is invalid: ${x} >= ${l}`);
++d[x], m = m && x >= f, f = x;
}
let h = true;
for (let g = 0; g < l; ++g) {
let x = d[g] === 0;
u[g] = x, h = h && !x, d[g] = Math.max(d[g], 1), g > 0 && (d[g] += d[g - 1]);
}
if (h && m) {
let g = r, x = n;
for (let y = 0; y < i; ++y)
c[y] = y;
return [g, [i, p], x, u, c];
} else {
let g = d[l - 1], x = b.getArrayFromDType(t, g * p), y = b.getArrayFromDType(o, g), w = new Array(l).fill(0);
for (let _ = 0; _ < i; ++_) {
let C = r[_ * p], A = w[C], D = (C === 0 ? 0 : d[C - 1]) + A;
w[C]++;
for (let R = 0; R < p; ++R)
x[D * p + R] = r[_ * p + R];
y[D] = n[_], c[_] = D;
}
for (let _ = 0; _ < l; ++_)
if (w[_] === 0) {
let A = _ === 0 ? 0 : d[_ - 1];
x[A * p + 0] = _;
for (let D = 1; D < p; ++D)
x[A * p + D] = 0;
y[A] = a;
}
return [x, [g, p], y, u, c];
}
}
function ky(r, e, t, n, o) {
let s = b.sizeFromShape(n), a = e[0], i = o.length, l = [], u = 1, c = -1;
for (let g = 0; g < i; ++g) {
let x = o[g];
if (x === -1) {
if (c !== -1)
throw new Error(`only one output dimension may be -1, not both ${c} and ${g}`);
c = g, l.push(1);
} else {
if (x < 0)
throw new Error(`size ${g} must be non-negative, not ${x}`);
u *= x, l.push(x);
}
}
if (c !== -1) {
if (u <= 0)
throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");
let g = Math.trunc(s / u);
if (u * g !== s)
throw new Error(`Input to reshape is a SparseTensor with ${s}
dense values, but the requested shape requires a multiple of ${u}. inputShape=${n} outputShape= ${l}`);
l[c] = g;
}
let p = b.sizeFromShape(l);
if (p !== s)
throw new Error(`Input to reshape is a tensor with ${s} dense values, but the requested shape has ${p}. inputShape=${n} outputShape=${l}`);
let m = n.length, f = [];
if (m > 0) {
f[m - 1] = 1;
for (let g = m - 2; g >= 0; --g)
f[g] = f[g + 1] * n[g + 1];
}
let d = [];
if (i > 0) {
d[i - 1] = 1;
for (let g = i - 2; g >= 0; --g)
d[g] = d[g + 1] * l[g + 1];
}
let h = b.getArrayFromDType(t, a * i);
for (let g = 0; g < a; ++g) {
let x = 0;
for (let y = 0; y < m; ++y)
x += r[g * m + y] * f[y];
for (let y = 0; y < i; ++y)
h[g * i + y] = Math.trunc(x / d[y]), x %= d[y];
}
return [h, [a, i], l];
}
function Cm(r, e, t, n, o, s = false, a = 0) {
let i = n.length;
if (i !== o.length)
throw new Error("segmentIds and indices should have same size.");
let l = [e[0], r.length / e[0]], u = l[1], p = i > 0 ? o[i - 1] + 1 : 0;
if (p < 0)
throw new Error("segment ids must be >= 0");
let m = e.slice();
m[0] = p;
let f = m.reduce((w, _) => w * _, 1), d = b.getArrayFromDType(t, f);
if (i === 0)
return p > 0 && d.fill(a), [d, m];
if (p <= 0)
throw new Error("segment ids must be >= 0");
let h = 0, g = 1, x = 0, y = o[h];
for (; ; ) {
let w = 0;
if (g < i) {
if (w = o[g], y === w) {
++g;
continue;
}
if (y >= w)
throw new Error("segment ids are not increasing");
}
if (y < 0 || y >= p)
throw new Error(`Segment id ${y} out of range [0, ${p}), possibly because segmentIds input is not sorted.`);
y > x && d.fill(a, x * u, y * u);
for (let _ = h; _ < g; ++_) {
let C = n[_];
if (C < 0 || C >= l[0])
throw new Error(`Bad: indices[${_}] == ${n[_]} out of range [0, ${l[0]})`);
for (let A = 0; A < u; A++)
d[y * u + A] += r[C * u + A];
}
if (s)
for (let _ = 0; _ < u; _++)
d[y * u + _] /= g - h;
if (h = g, ++g, x = y + 1, y = w, g > i)
break;
}
return x < p && d.fill(a, x * u, p * u), [d, m];
}
var Z$ = dn((r) => Math.sqrt(r));
var G7 = $e(ys, (r) => Math.sqrt(r));
var J$ = { kernelName: ys, backendName: "cpu", kernelFunc: G7 };
var B0 = Ze((r, e) => {
let t = r - e;
return t * t;
});
var W7 = rt(_s, B0);
var Q$ = { kernelName: _s, backendName: "cpu", kernelFunc: W7 };
function vy(r, e, t, n) {
let o = Ie(r, e.dtype);
for (let s = 0; s < o.size; s++) {
let a = o.indexToLoc(s), i = new Array(a.length);
for (let l = 0; l < i.length; l++)
i[l] = a[l] * t[l] + n[l];
o.set(e.get(...i), ...a);
}
return o;
}
var eR = class {
constructor(e, t, n, o, s, a) {
this.separator = b.encodeString(e), this.nGramWidths = t, this.leftPad = b.encodeString(n), this.rightPad = b.encodeString(o), this.padWidth = s, this.preserveShort = a;
}
getPadWidth(e) {
return Math.min(this.padWidth < 0 ? e - 1 : this.padWidth, e - 1);
}
getNumNGrams(e, t) {
let n = this.getPadWidth(t);
return Math.max(0, e + 2 * n - t + 1);
}
createNGrams(e, t, n, o, s, a) {
for (let i = 0; i < s; ++i) {
let l = this.getPadWidth(a), u = Math.max(0, l - i), c = Math.max(0, l - (s - (i + 1))), p = a - (u + c), m = t + (u > 0 ? 0 : i - l), f = 0;
f += u * this.leftPad.length;
for (let y = 0; y < p; ++y)
f += e[m + y].length;
f += c * this.rightPad.length, f += (u + c + p - 1) * this.separator.length, n[o + i] = new Uint8Array(f);
let h = n[o + i], g = 0, x = (y) => y.forEach((w) => h[g++] = w);
for (let y = 0; y < u; ++y)
x(this.leftPad), x(this.separator);
for (let y = 0; y < p - 1; ++y)
x(e[m + y]), x(this.separator);
if (p > 0) {
x(e[m + p - 1]);
for (let y = 0; y < c; ++y)
x(this.separator), x(this.rightPad);
} else {
for (let y = 0; y < c - 1; ++y)
x(this.rightPad), x(this.separator);
x(this.rightPad);
}
}
}
compute(e, t) {
let n = e.length, o = t.length;
if (o > 0) {
let l = t[0];
if (l !== 0)
throw new Error(`First split value must be 0, got ${l}`);
for (let u = 1; u < o; ++u) {
let c = t[u] >= l;
if (c = c && t[u] <= n, !c)
throw new Error(`Invalid split value ${t[u]}, must be in [${l}, ${n}]`);
l = t[u];
}
if (l !== n)
throw new Error(`Last split value must be data size. Expected ${n}, got ${l}`);
}
let s = o - 1, a = b.getArrayFromDType("int32", o);
if (n === 0 || o === 0) {
let l = new Array(n);
for (let u = 0; u <= s; ++u)
a[u] = 0;
return [l, a];
}
a[0] = 0;
for (let l = 1; l <= s; ++l) {
let u = t[l] - t[l - 1], c = 0;
this.nGramWidths.forEach((p) => {
c += this.getNumNGrams(u, p);
}), this.preserveShort && u > 0 && c === 0 && (c = 1), a[l] = a[l - 1] + c;
}
let i = new Array(a[s]);
for (let l = 0; l < s; ++l) {
let u = t[l], c = a[l];
if (this.nGramWidths.forEach((p) => {
let m = t[l + 1] - t[l], f = this.getNumNGrams(m, p);
this.createNGrams(e, u, i, c, f, p), c += f;
}), this.preserveShort && c === a[l]) {
let p = t[l + 1] - t[l];
if (p === 0)
continue;
let m = p + 2 * this.padWidth, f = 1;
this.createNGrams(e, u, i, c, f, m);
}
}
return [i, a];
}
};
function Cy(r, e, t, n, o, s, a, i) {
return new eR(t, n, o, s, a, i).compute(r, e);
}
function U7(r, e, t, n) {
if (!r.length)
return;
if (e.length === 0) {
for (let s = 0; s < r.length; ++s)
n.push(r.subarray(s, s + 1));
return;
}
if (e.length === 1) {
let s = e[0], a = r.indexOf(s);
for (; a !== -1; ) {
let i = r.subarray(0, a);
(!t || i.length !== 0) && n.push(i), r = r.subarray(a + 1), a = r.indexOf(s);
}
(!t || r.length !== 0) && n.push(r);
return;
}
let o = 0;
for (let s = 0; s < r.length + 1; s++)
if (s === r.length || e.indexOf(r[s]) !== -1) {
let a = r.subarray(o, s);
(!t || a.length !== 0) && n.push(a), o = s + 1;
}
}
function Iy(r, e, t) {
let n = r.length, o = [], s = 0, a = 0, i = new Array(n);
for (let m = 0; m < n; ++m) {
let f = o.length;
U7(r[m], e, t, o);
let d = o.length - f;
i[m] = d, s += d, a = Math.max(a, d);
}
let l = b.getArrayFromDType("int32", s * 2), u = new Array(s), c = [n, a], p = 0;
for (let m = 0; m < n; ++m)
for (let f = 0; f < i[m]; ++f)
l[p * 2] = m, l[p * 2 + 1] = f, u[p] = o[p], ++p;
return [l, u, c];
}
function Sy(r, e) {
let t = b.getArrayFromDType("int32", r.length);
for (let n = 0; n < r.length; ++n)
t[n] = b.fingerPrint64(r[n]).modulo(e).getLowBitsUnsigned();
return t;
}
var V0 = Ze((r, e) => r - e);
var j7 = _m((r, e, t, n) => ({ real: r - t, imag: e - n }));
var Dh = rt(ks, V0, j7);
var tR = { kernelName: ks, backendName: "cpu", kernelFunc: Dh };
function Ny(r, e) {
let t = new Array(r.rank);
for (let o = 0; o < t.length; o++)
t[o] = r.shape[o] * e[o];
let n = Ie(t, r.dtype);
for (let o = 0; o < n.values.length; ++o) {
let s = n.indexToLoc(o), a = new Array(r.rank);
for (let l = 0; l < a.length; l++)
a[l] = s[l] % r.shape[l];
let i = r.locToIndex(a);
n.values[o] = r.values[i];
}
return n;
}
var $h = (r, e) => {
let t = e.value - r.value;
return t === 0 ? r.index - e.index : t;
};
function rR(r, e, t = 0, n = r.length - 1) {
for (; n > t; ) {
if (n - t > 600) {
let i = n - t + 1, l = e - t + 1, u = Math.log(i), c = 0.5 * Math.exp(2 * u / 3), p = 0.5 * Math.sqrt(u * c * (i - c) / i) * Math.sign(l - i / 2), m = Math.max(t, Math.floor(e - l * c / i + p)), f = Math.min(n, Math.floor(e + (i - l) * c / i + p));
rR(r, e, m, f);
}
let o = r[e], s = t, a = n;
for (b.swap(r, t, e), $h(r[n], o) > 0 && b.swap(r, t, n); s < a; ) {
for (b.swap(r, s, a), s++, a--; $h(r[s], o) < 0; )
s = s + 1;
for (; $h(r[a], o) > 0; )
a = a - 1;
}
$h(r[t], o) === 0 ? b.swap(r, t, a) : (a = a + 1, b.swap(r, a, n)), a <= e && (t = a + 1), e <= a && (n = a - 1);
}
}
function Ty(r, e, t, n, o) {
let s = e[e.length - 1], [a, i] = [r.length / s, s], l = b.getTypedArrayFromDType(t, a * n), u = b.getTypedArrayFromDType("int32", a * n);
for (let p = 0; p < a; p++) {
let m = p * i, f = r.subarray(m, m + i), d = new Array(f.length);
f.forEach((y, w) => d[w] = { value: y, index: w }), n < d.length && (rR(d, n), d = d.slice(0, n)), o && d.sort($h);
let h = p * n, g = l.subarray(h, h + n), x = u.subarray(h, h + n);
for (let y = 0; y < n; y++)
g[y] = d[y].value, x[y] = d[y].index;
}
let c = e.slice();
return c[c.length - 1] = n, [Ie(c, t, l), Ie(c, "int32", u)];
}
function Ey(r, e, t, n) {
let o = b.parseAxisParam(e, t)[0], s = [1, t[0], 1];
for (let d = 0; d < o; d++)
s[0] *= t[d];
s[1] = t[o];
for (let d = o + 1; d < t.length; d++)
s[2] *= t[d];
let a = {}, i = new Int32Array(t[o]), l = new mt(s, n, r), u = [], c = s[0] === 1 && s[2] === 1;
for (let d = 0; d < t[o]; d++) {
let h;
if (c)
h = r[d].toString();
else {
let g = [];
for (let x = 0; x < s[0]; x++)
for (let y = 0; y < s[2]; y++)
g.push(l.get(x, d, y));
h = g.join(",");
}
if (a[h] !== void 0)
i[d] = a[h];
else {
let g = Object.keys(a).length;
a[h] = g, i[d] = g, u.push(d);
}
}
let p = s.slice();
p[1] = Object.keys(a).length;
let m = new mt(p, n);
u.forEach((d, h) => {
for (let g = 0; g < s[0]; g++)
for (let x = 0; x < s[2]; x++)
m.set(l.get(g, d, x), g, h, x);
});
let f = t.slice();
return f[o] = p[1], { outputValues: m.values, outputShape: f, indices: i };
}
Op("cpu", () => new pc(), 1);
var G0 = $e(Uo, (r) => r >= 0 ? r : Math.exp(r) - 1);
var nR = { kernelName: Uo, backendName: "cpu", kernelFunc: G0 };
function W0(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { alpha: s } = n;
te([o], "leakyRelu");
let a = b.sizeFromShape(o.shape), i = t.data.get(o.dataId).values, l = b.getTypedArrayFromDType("float32", a);
for (let u = 0; u < i.length; u++)
l[u] = i[u] < 0 ? s * i[u] : i[u];
return t.makeTensorInfo(o.shape, "float32", l);
}
var oR = { kernelName: Yo, backendName: "cpu", kernelFunc: W0 };
var q7 = Ze((r, e) => r < 0 ? e * r : r);
function U0(r) {
let { inputs: e, backend: t } = r, { x: n, alpha: o } = e;
te([n, o], "prelu");
let s = t.data.get(n.dataId).values, a = t.data.get(o.dataId).values, [i, l] = q7(n.shape, o.shape, s, a, "float32");
return t.makeTensorInfo(l, "float32", i);
}
var sR = { kernelName: us, backendName: "cpu", kernelFunc: U0 };
var j0 = $e(cs, (r) => Math.max(0, r));
var iR = { kernelName: cs, backendName: "cpu", kernelFunc: j0 };
var H0 = $e(ms, (r) => Math.min(Math.max(0, r), 6));
var aR = { kernelName: ms, backendName: "cpu", kernelFunc: H0 };
function Im(r, e, t, n, o) {
if (t === "linear")
return Wr({ inputs: { x: e }, backend: r });
if (t === "relu")
return j0({ inputs: { x: e }, backend: r });
if (t === "elu")
return G0({ inputs: { x: e }, backend: r });
if (t === "relu6")
return H0({ inputs: { x: e }, backend: r });
if (t === "prelu")
return U0({ inputs: { x: e, alpha: n }, backend: r });
if (t === "leakyrelu")
return W0({ inputs: { x: e }, backend: r, attrs: { alpha: o } });
if (t === "sigmoid")
return z0({ inputs: { x: e }, backend: r });
throw new Error(`Activation ${t} has not been implemented for the CPU backend.`);
}
function Je(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { shape: s } = n, a = b.sizeFromShape(o.shape), i = b.inferFromImplicitShape(s, a), l = b.sizeFromShape(i);
b.assert(a === l, () => `The new shape (${i}) has ${l} elements and the old shape (${o.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`), t.incRef(o.dataId);
let u = t.data.get(o.dataId);
if (u.complexTensorInfos != null) {
let c = u.complexTensorInfos.real, p = u.complexTensorInfos.imag;
c.shape = i, p.shape = i;
}
return { dataId: o.dataId, shape: i, dtype: o.dtype };
}
var lR = { kernelName: ui, backendName: "cpu", kernelFunc: Je };
function q0(r) {
let { inputs: e, backend: t, attrs: n } = r, { a: o, b: s } = e, { transposeA: a, transposeB: i } = n;
te([o, s], "matMul");
let l = o.shape.length, u = s.shape.length, c = a ? o.shape[l - 2] : o.shape[l - 1], p = i ? s.shape[u - 1] : s.shape[u - 2], m = a ? o.shape[l - 1] : o.shape[l - 2], f = i ? s.shape[u - 2] : s.shape[u - 1], d = o.shape.slice(0, -2), h = s.shape.slice(0, -2), g = b.sizeFromShape(d), x = b.sizeFromShape(h), y = g === x || g === 1 || x === 1;
b.assert(l >= 2 && u >= 2 && y, () => `Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${d}) and (${h}).`);
let _ = (g > x ? o.shape.slice(0, -2) : s.shape.slice(0, -2)).concat([m, f]);
b.assert(c === p, () => `Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${o.shape} and ${s.shape} and transposeA=${a} and transposeB=${i} must match.`);
let C = a ? [g, c, m] : [g, m, c], A = i ? [x, f, p] : [x, p, f], D = Je({ inputs: { x: o }, backend: t, attrs: { shape: C } }), R = Je({ inputs: { x: s }, backend: t, attrs: { shape: A } }), P = a ? D.shape[1] : D.shape[2], L = a ? D.shape[2] : D.shape[1], G = i ? R.shape[1] : R.shape[2], W = Math.max(g, x), j = t.data.get(D.dataId).values, H = t.data.get(R.dataId).values, q = b.computeStrides(D.shape), X = b.computeStrides(R.shape), [re, J, oe] = a ? [q[0], 1, q[1]] : [q[0], q[1], 1], [se, ne, fe] = i ? [1, X[1], X[0]] : [X[1], 1, X[0]], ae = L * G, ge = Ie([W, L, G], D.dtype), de = ge.values, ye = t.blockSize;
for (let _e = 0; _e < W; _e++)
for (let Re = 0; Re < L; Re += ye)
for (let Ee = 0; Ee < G; Ee += ye)
for (let Fe = 0; Fe < P; Fe += ye) {
let Ye = Math.min(Re + ye, L), ut = Math.min(Ee + ye, G), At = Math.min(Fe + ye, P);
for (let Dt = Re; Dt < Ye; Dt++)
for (let ft = Ee; ft < ut; ft++) {
let Ke = 0;
for (let ht = Fe; ht < At; ht++) {
let Mt = Math.min(_e, g - 1) * re, Dn = Math.min(_e, x - 1) * fe, lr = j[Mt + Dt * J + ht * oe], gn = H[ht * se + ft * ne + Dn];
Ke += lr * gn;
}
de[_e * ae + (Dt * G + ft)] += Ke;
}
}
return t.disposeIntermediateTensorInfo(D), t.disposeIntermediateTensorInfo(R), t.makeTensorInfo(_, ge.dtype, ge.values);
}
var uR = { kernelName: Oo, backendName: "cpu", kernelFunc: q0 };
function K7(r) {
let { inputs: e, backend: t, attrs: n } = r, { a: o, b: s, bias: a, preluActivationWeights: i } = e, { transposeA: l, transposeB: u, activation: c, leakyreluAlpha: p } = n, m, f, d, h = [];
m = q0({ inputs: { a: o, b: s }, attrs: { transposeA: l, transposeB: u }, backend: t }), a && (f = Ya({ inputs: { a: m, b: a }, backend: t }), h.push(m), m = f), c && (d = Im(t, m, c, i, p), h.push(m), m = d);
for (let x of h)
t.disposeIntermediateTensorInfo(x);
return m;
}
var cR = { kernelName: gi, backendName: "cpu", kernelFunc: K7 };
var X7 = $e(Mi, (r) => Math.acos(r));
var pR = { kernelName: Mi, backendName: "cpu", kernelFunc: X7 };
var Y7 = $e(Li, (r) => Math.acosh(r));
var mR = { kernelName: Li, backendName: "cpu", kernelFunc: Y7 };
function Z7(r) {
let { inputs: e, backend: t } = r, n = e;
te(e, "addN");
let o = n.map((i) => t.data.get(i.dataId).values), s = Ie(n[0].shape, n[0].dtype), a = s.values;
for (let i = 0; i < n.length; i++) {
let l = o[i];
for (let u = 0; u < a.length; u++)
a[u] += l[u];
}
return t.makeTensorInfo(s.shape, s.dtype, s.values);
}
var fR = { kernelName: $o, backendName: "cpu", kernelFunc: Z7 };
function J7(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, keepDims: a } = n;
te(o, "all");
let i = b.parseAxisParam(s, o.shape), l = i, u = I.getAxesPermutation(l, o.shape.length), c = o;
u != null && (c = rr({ inputs: { x: o }, backend: t, attrs: { perm: u } }), l = I.getInnerMostAxes(l.length, o.shape.length)), I.assertAxesAreInnerMostDims("all", l, c.shape.length);
let [p, m] = I.computeOutAndReduceShapes(c.shape, l), f = b.sizeFromShape(m), d = b.makeZerosTypedArray(b.sizeFromShape(p), c.dtype), h = t.data.get(c.dataId).values;
for (let x = 0; x < d.length; ++x) {
let y = x * f, w = h[y];
for (let _ = 0; _ < f; ++_) {
let C = h[y + _];
w = w && C;
}
d[x] = w;
}
u != null && t.disposeIntermediateTensorInfo(c);
let g = t.makeTensorInfo(p, c.dtype, d);
if (a) {
let x = I.expandShapeToKeepDim(p, i), y = Je({ inputs: { x: g }, backend: t, attrs: { shape: x } });
return t.disposeIntermediateTensorInfo(g), y;
}
return g;
}
var dR = { kernelName: zi, backendName: "cpu", kernelFunc: J7 };
function Q7(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, keepDims: a } = n;
te(o, "any");
let i = b.parseAxisParam(s, o.shape), l = i, u = I.getAxesPermutation(l, o.shape.length), c = o;
u != null && (c = rr({ inputs: { x: o }, backend: t, attrs: { perm: u } }), l = I.getInnerMostAxes(l.length, o.shape.length)), I.assertAxesAreInnerMostDims("any", l, c.shape.length);
let [p, m] = I.computeOutAndReduceShapes(c.shape, l), f = b.sizeFromShape(m), d = b.makeZerosTypedArray(b.sizeFromShape(p), c.dtype), h = t.data.get(c.dataId).values;
for (let x = 0; x < d.length; ++x) {
let y = x * f, w = h[y];
for (let _ = 0; _ < f; ++_) {
let C = h[y + _];
w = w || C;
}
d[x] = w;
}
u != null && t.disposeIntermediateTensorInfo(c);
let g = t.makeTensorInfo(p, c.dtype, d);
if (a) {
let x = I.expandShapeToKeepDim(p, i), y = Je({ inputs: { x: g }, backend: t, attrs: { shape: x } });
return t.disposeIntermediateTensorInfo(g), y;
}
return g;
}
var hR = { kernelName: Bi, backendName: "cpu", kernelFunc: Q7 };
function eY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s } = n;
te(o, "argMax");
let a = b.parseAxisParam(s, o.shape), i = I.getAxesPermutation(a, o.shape.length), l = o, u = [];
i != null && (l = rr({ inputs: { x: o }, backend: t, attrs: { perm: i } }), u.push(l), a = I.getInnerMostAxes(a.length, l.shape.length)), a = [a[0]], I.assertAxesAreInnerMostDims("argMax", a, l.shape.length);
let [c, p] = I.computeOutAndReduceShapes(l.shape, a), m = b.sizeFromShape(c), f = b.makeZerosTypedArray(m, "int32"), d = b.sizeFromShape(p), h = t.data.get(l.dataId).values;
for (let g = 0; g < f.length; ++g) {
let x = g * d, y = h[x], w = 0;
for (let _ = 0; _ < d; ++_) {
let C = h[x + _];
C > y && (y = C, w = _);
}
f[g] = w;
}
return u.forEach((g) => t.disposeIntermediateTensorInfo(g)), t.makeTensorInfo(c, "int32", f);
}
var gR = { kernelName: Ro, backendName: "cpu", kernelFunc: eY };
function tY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s } = n;
te(o, "argMin");
let a = b.parseAxisParam(s, o.shape), i = I.getAxesPermutation(a, o.shape.length), l = o, u = [];
i != null && (l = rr({ inputs: { x: o }, backend: t, attrs: { perm: i } }), u.push(l), a = I.getInnerMostAxes(a.length, l.shape.length)), a = [a[0]], I.assertAxesAreInnerMostDims("argMin", a, l.shape.length);
let [c, p] = I.computeOutAndReduceShapes(l.shape, a), m = b.sizeFromShape(c), f = b.makeZerosTypedArray(m, "int32"), d = b.sizeFromShape(p), h = t.data.get(l.dataId).values;
for (let g = 0; g < f.length; ++g) {
let x = g * d, y = h[x], w = 0;
for (let _ = 0; _ < d; ++_) {
let C = h[x + _];
C < y && (y = C, w = _);
}
f[g] = w;
}
return u.forEach((g) => t.disposeIntermediateTensorInfo(g)), t.makeTensorInfo(c, "int32", f);
}
var xR = { kernelName: ml, backendName: "cpu", kernelFunc: tY };
var rY = $e(Vi, (r) => Math.asin(r));
var yR = { kernelName: Vi, backendName: "cpu", kernelFunc: rY };
var nY = $e(Gi, (r) => Math.asinh(r));
var bR = { kernelName: Gi, backendName: "cpu", kernelFunc: nY };
var oY = $e(Wi, (r) => Math.atan(r));
var wR = { kernelName: Wi, backendName: "cpu", kernelFunc: oY };
var sY = Ze((r, e) => Math.atan2(r, e));
var iY = rt(ji, sY);
var _R = { kernelName: ji, backendName: "cpu", kernelFunc: iY };
var aY = $e(Ui, (r) => Math.atanh(r));
var kR = { kernelName: Ui, backendName: "cpu", kernelFunc: aY };
function Sm(r, e, t, n, o, s) {
let a = o.strideHeight, i = o.strideWidth, l = o.dilationHeight, u = o.dilationWidth, c = o.effectiveFilterHeight, p = o.effectiveFilterWidth, m = o.padInfo.top, f = o.padInfo.left, d = s === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, h = Ie(o.outShape, t), g = h.values, x = o.outShape[1] * o.outShape[2] * o.outShape[3], y = o.outShape[2] * o.outShape[3], w = o.outShape[3];
for (let _ = 0; _ < o.batchSize; ++_) {
let C = _ * x, A = _ * n[0];
for (let D = 0; D < o.inChannels; ++D)
for (let R = 0; R < o.outHeight; ++R) {
let P = R * a - m, L = Math.max(0, P), G = Math.min(o.inHeight, c + P), W = C + R * y;
for (let j = 0; j < o.outWidth; ++j) {
let H = j * i - f, q = Math.max(0, H), X = Math.min(o.inWidth, p + H), re = d, J = 0, oe = 0;
for (let ne = L; ne < G; ne += l) {
let fe = A + ne * n[1];
for (let ae = q; ae < X; ae += u) {
let ge = fe + ae * n[2], de = r[ge + D];
s === "max" && de > re ? re = de : s === "avg" && (J += de, oe++);
}
if (isNaN(re))
break;
}
let se = W + j * w + D;
g[se] = s === "avg" ? J / oe : re;
}
}
}
return h;
}
function Dy(r, e, t, n, o = false, s = false) {
let a = Ie(n.outShape, "int32"), i = n.strideHeight, l = n.strideWidth, u = n.dilationHeight, c = n.dilationWidth, p = n.effectiveFilterHeight, m = n.effectiveFilterWidth, f = n.padInfo.top, d = n.padInfo.left, h = Ie(e, t, r);
for (let g = 0; g < n.batchSize; ++g)
for (let x = 0; x < n.inChannels; ++x)
for (let y = 0; y < n.outHeight; ++y) {
let w = y * i - f, _ = w;
for (; _ < 0; )
_ += u;
let C = Math.min(n.inHeight, p + w);
for (let A = 0; A < n.outWidth; ++A) {
let D = A * l - d, R = D;
for (; R < 0; )
R += c;
let P = Math.min(n.inWidth, m + D), L = Number.NEGATIVE_INFINITY, G = -1;
for (let W = _; W < C; W += u) {
let j = W - w;
for (let H = R; H < P; H += c) {
let q = H - D, X = h.get(g, W, H, x);
X > L && (L = X, o ? G = s ? ((g * n.inHeight + W) * n.inWidth + H) * n.inChannels + x : (W * n.inWidth + H) * n.inChannels + x : G = j * m + q);
}
}
a.set(G, g, y, A, x);
}
}
return a;
}
function $y(r, e, t, n, o, s) {
let a = o.strideDepth, i = o.strideHeight, l = o.strideWidth, u = o.dilationDepth, c = o.dilationHeight, p = o.dilationWidth, m = o.effectiveFilterDepth, f = o.effectiveFilterHeight, d = o.effectiveFilterWidth, h = o.padInfo.front, g = o.padInfo.top, x = o.padInfo.left, y = s === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, w = Ie(o.outShape, t), _ = w.values, C = o.outShape[1] * o.outShape[2] * o.outShape[3] * o.outShape[4], A = o.outShape[2] * o.outShape[3] * o.outShape[4], D = o.outShape[3] * o.outShape[4], R = o.outShape[4];
for (let P = 0; P < o.batchSize; ++P) {
let L = P * C, G = P * n[0];
for (let W = 0; W < o.inChannels; ++W)
for (let j = 0; j < o.outDepth; ++j) {
let H = j * a - h, q = H;
for (; q < 0; )
q += u;
let X = Math.min(o.inDepth, m + H), re = L + j * A;
for (let J = 0; J < o.outHeight; ++J) {
let oe = J * i - g, se = oe;
for (; se < 0; )
se += c;
let ne = Math.min(o.inHeight, f + oe), fe = re + J * D;
for (let ae = 0; ae < o.outWidth; ++ae) {
let ge = ae * l - x, de = ge;
for (; de < 0; )
de += p;
let ye = Math.min(o.inWidth, d + ge), _e = fe + ae * R, Re = y, Ee = 0, Fe = 0;
for (let ut = q; ut < X; ut += u) {
let At = G + ut * n[1];
for (let Dt = se; Dt < ne; Dt += c) {
let ft = At + Dt * n[2];
for (let Ke = de; Ke < ye; Ke += p) {
let ht = ft + Ke * n[3], Mt = r[ht + W];
if (s === "max" && Mt > Re ? Re = Mt : s === "avg" && (Ee += Mt, Fe++), isNaN(Re))
break;
}
if (isNaN(Re))
break;
}
if (isNaN(Re))
break;
}
let Ye = _e + W;
_[Ye] = s === "avg" ? Ee / Fe : Re;
}
}
}
}
return w;
}
function vR(r, e) {
let t = Ie(e.outShape, "int32"), n = e.strideDepth, o = e.strideHeight, s = e.strideWidth, a = e.dilationDepth, i = e.dilationHeight, l = e.dilationWidth, u = e.effectiveFilterDepth, c = e.effectiveFilterHeight, p = e.effectiveFilterWidth, m = e.padInfo.front, f = e.padInfo.top, d = e.padInfo.left;
for (let h = 0; h < e.batchSize; ++h)
for (let g = 0; g < e.inChannels; ++g)
for (let x = 0; x < e.outDepth; ++x) {
let y = x * n - m, w = y;
for (; w < 0; )
w += a;
let _ = Math.min(e.inDepth, u + y);
for (let C = 0; C < e.outHeight; ++C) {
let A = C * o - f, D = A;
for (; D < 0; )
D += i;
let R = Math.min(e.inHeight, c + A);
for (let P = 0; P < e.outWidth; ++P) {
let L = P * s - d, G = L;
for (; G < 0; )
G += l;
let W = Math.min(e.inWidth, p + L), j = Number.NEGATIVE_INFINITY, H = -1;
for (let q = w; q < _; q += a) {
let X = q - y;
for (let re = D; re < R; re += i) {
let J = re - A;
for (let oe = G; oe < W; oe += l) {
let se = oe - L, ne = r.get(h, q, re, oe, g);
ne >= j && (j = ne, H = X * c * p + J * c + se);
}
}
}
t.set(H, h, x, C, P, g);
}
}
}
return t;
}
function lY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e;
te(o, "avgPool");
let { filterSize: s, strides: a, pad: i, dimRoundingMode: l } = n, u = 1;
b.assert(I.eitherStridesOrDilationsAreOne(a, u), () => `Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);
let c = I.computePool2DInfo(o.shape, s, a, u, i, l), p;
if (c.filterWidth === 1 && c.filterHeight === 1 && b.arraysEqual(c.inShape, c.outShape))
p = Wr({ inputs: { x: o }, backend: t });
else {
let m = t.data.get(o.dataId).values, f = b.computeStrides(o.shape), d = Sm(m, o.shape, o.dtype, f, c, "avg");
p = t.makeTensorInfo(c.outShape, o.dtype, d.values);
}
return p;
}
var CR = { kernelName: Fo, backendName: "cpu", kernelFunc: lY };
function uY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { filterSize: s, strides: a, pad: i, dimRoundingMode: l, dataFormat: u } = n;
te(o, "avgPool3d");
let c = I.computePool3DInfo(o.shape, s, a, 1, i, l, u), p = t.data.get(o.dataId).values, m = $y(p, o.shape, o.dtype, b.computeStrides(o.shape), c, "avg");
return t.makeTensorInfo(m.shape, "float32", m.values);
}
var IR = { kernelName: fl, backendName: "cpu", kernelFunc: uY };
function cY(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, input: s } = e, { filterSize: a, strides: i, pad: l, dimRoundingMode: u } = n;
te([o, s], "avgPool3DGrad");
let c = I.computePool3DInfo(s.shape, a, i, 1, l, u), p = c.strideDepth, m = c.strideHeight, f = c.strideWidth, d = c.filterDepth, h = c.filterHeight, g = c.filterWidth, x = c.dilationDepth, y = c.dilationHeight, w = c.dilationWidth, _ = c.effectiveFilterDepth, C = c.effectiveFilterHeight, A = c.effectiveFilterWidth, D = _ - 1 - c.padInfo.front, R = A - 1 - c.padInfo.left, P = C - 1 - c.padInfo.top, L = Ie(s.shape, "float32"), G = 1 / (d * h * g), W = t.bufferSync(o);
for (let j = 0; j < c.batchSize; ++j)
for (let H = 0; H < c.inChannels; ++H)
for (let q = 0; q < c.inDepth; ++q)
for (let X = 0; X < c.inHeight; ++X)
for (let re = 0; re < c.inWidth; ++re) {
let J = q - D, oe = X - P, se = re - R, ne = 0;
for (let fe = 0; fe < _; fe += x) {
let ae = (J + fe) / p;
if (!(ae < 0 || ae >= c.outDepth || Math.floor(ae) !== ae))
for (let ge = 0; ge < C; ge += y) {
let de = (oe + ge) / m;
if (!(de < 0 || de >= c.outHeight || Math.floor(de) !== de))
for (let ye = 0; ye < A; ye += w) {
let _e = (se + ye) / f;
if (_e < 0 || _e >= c.outWidth || Math.floor(_e) !== _e)
continue;
ne += W.get(j, ae, de, _e, H);
}
}
}
L.set(ne * G, j, q, X, re, H);
}
return t.makeTensorInfo(L.shape, L.dtype, L.values);
}
var SR = { kernelName: Uc, backendName: "cpu", kernelFunc: cY };
function pY(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, input: s } = e, a = s;
te([o, s], "avgPoolGrad");
let { filterSize: i, strides: l, pad: u } = n, c = I.computePool2DInfo(a.shape, i, l, 1, u), p = c.strideHeight, m = c.strideWidth, f = c.filterHeight, d = c.filterWidth, h = c.dilationHeight, g = c.dilationWidth, x = c.effectiveFilterHeight, y = c.effectiveFilterWidth, w = y - 1 - c.padInfo.left, _ = x - 1 - c.padInfo.top, C = Ie(a.shape, "float32"), A = 1 / (f * d), D = t.data.get(o.dataId).values, R = Ie(o.shape, "float32", D);
for (let P = 0; P < c.batchSize; ++P)
for (let L = 0; L < c.inChannels; ++L)
for (let G = 0; G < c.inHeight; ++G)
for (let W = 0; W < c.inWidth; ++W) {
let j = G - _, H = W - w, q = 0;
for (let X = 0; X < x; X += h) {
let re = (j + X) / p;
if (!(re < 0 || re >= c.outHeight || Math.floor(re) !== re))
for (let J = 0; J < y; J += g) {
let oe = (H + J) / m;
if (oe < 0 || oe >= c.outWidth || Math.floor(oe) !== oe)
continue;
q += R.get(P, re, oe, L);
}
}
C.set(q * A, P, G, W, L);
}
return t.makeTensorInfo(C.shape, C.dtype, C.values);
}
var NR = { kernelName: Wc, backendName: "cpu", kernelFunc: pY };
function mY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, scale: s, offset: a, mean: i, variance: l } = e;
b.assert(i.shape.length === l.shape.length, () => "Batch normalization gradient requires mean and variance to have equal ranks."), b.assert(a == null || i.shape.length === a.shape.length, () => "Batch normalization gradient requires mean and offset to have equal ranks."), b.assert(s == null || i.shape.length === s.shape.length, () => "Batch normalization gradient requires mean and scale to have equal ranks."), te([o, i, l, s, a], "batchNorm");
let { varianceEpsilon: u } = n;
u == null && (u = 1e-3);
let c = t.data.get(o.dataId).values, p = t.data.get(i.dataId).values, m = t.data.get(l.dataId).values, f = s ? t.data.get(s.dataId).values : new Float32Array([1]), d = a ? t.data.get(a.dataId).values : new Float32Array([0]), h = new Float32Array(c.length), g = d.length, x = f.length, y = m.length, w = p.length, _ = 0, C = 0, A = 0, D = 0;
for (let R = 0; R < c.length; ++R)
h[R] = d[_++] + (c[R] - p[C++]) * f[A++] / Math.sqrt(m[D++] + u), _ >= g && (_ = 0), C >= w && (C = 0), A >= x && (A = 0), D >= y && (D = 0);
return t.makeTensorInfo(o.shape, o.dtype, h);
}
var TR = { kernelName: Ko, backendName: "cpu", kernelFunc: mY };
function fY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { blockShape: s, crops: a } = n;
te([o], "batchToSpaceND");
let i = s.reduce((x, y) => x * y), l = I.getReshaped(o.shape, s, i), u = I.getPermuted(l.length, s.length), c = I.getReshapedPermuted(o.shape, s, i), p = I.getSliceBeginCoords(a, s.length), m = I.getSliceSize(c, a, s.length), f = Je({ inputs: { x: o }, backend: t, attrs: { shape: l } }), d = rr({ inputs: { x: f }, backend: t, attrs: { perm: u } }), h = Je({ inputs: { x: d }, backend: t, attrs: { shape: c } }), g = So({ inputs: { x: h }, backend: t, attrs: { begin: p, size: m } });
return t.disposeIntermediateTensorInfo(f), t.disposeIntermediateTensorInfo(d), t.disposeIntermediateTensorInfo(h), g;
}
var ER = { kernelName: ri, backendName: "cpu", kernelFunc: fY };
function dY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, weights: s } = e, { size: a } = n, i = t.data.get(o.dataId).values, l = t.data.get(s.dataId).values, u = km(i, l, s.dtype, s.shape, a);
return t.makeTensorInfo([a], s.dtype, u);
}
var AR = { kernelName: jc, backendName: "cpu", kernelFunc: dY };
function hY(r) {
let { inputs: e, backend: t } = r, { s0: n, s1: o } = e, s = t.data.get(n.dataId).values, a = t.data.get(o.dataId).values, i = I.assertAndGetBroadcastShape(Array.from(s), Array.from(a));
return t.makeTensorInfo([i.length], "int32", Int32Array.from(i));
}
var DR = { kernelName: Hc, backendName: "cpu", kernelFunc: hY };
var gY = $e(to, (r, e) => {
let t = e;
return r > t.clipValueMax ? t.clipValueMax : r < t.clipValueMin ? t.clipValueMin : r;
});
var $R = { kernelName: to, backendName: "cpu", kernelFunc: gY };
var xY = (r) => {
let { x: e } = r.inputs, t = r.backend, n = new Float32Array(b.sizeFromShape(e.shape)), o = t.data.get(e.dataId), s = o.complexTensorInfos.real, a = o.complexTensorInfos.imag, i = t.data.get(s.dataId).values, l = t.data.get(a.dataId).values;
for (let u = 0; u < i.length; u++) {
let c = i[u], p = l[u];
n[u] = Math.hypot(c, p);
}
return t.makeOutput(n, e.shape, "float32");
};
var RR = { kernelName: dl, backendName: "cpu", kernelFunc: xY };
function Ei(r) {
let { inputs: e, backend: t } = r, { input: n } = e, o = t.data.get(n.dataId).complexTensorInfos.imag, s = t.data.get(o.dataId).values;
return t.makeTensorInfo(o.shape, o.dtype, s);
}
var FR = { kernelName: sp, backendName: "cpu", kernelFunc: Ei };
function jl(r) {
let { inputs: e, backend: t, attrs: n } = r, { axis: o } = n, s = b.parseAxisParam(o, e[0].shape)[0], a = I.computeOutShape(e.map((h) => h.shape), s);
if (b.sizeFromShape(a) === 0)
return t.makeTensorInfo(a, e[0].dtype, []);
let i = e.filter((h) => b.sizeFromShape(h.shape) > 0);
if (i.length === 1)
return Wr({ inputs: { x: i[0] }, backend: t });
let l = i.map((h) => h.shape);
if (I.assertParamsConsistent(l, s), i[0].dtype === "complex64") {
let h = i.map((_) => vo({ inputs: { input: _ }, backend: t })), g = i.map((_) => Ei({ inputs: { input: _ }, backend: t })), x = jl({ inputs: h, backend: t, attrs: { axis: s } }), y = jl({ inputs: g, backend: t, attrs: { axis: s } }), w = wr({ inputs: { real: x, imag: y }, backend: t });
return h.forEach((_) => t.disposeIntermediateTensorInfo(_)), g.forEach((_) => t.disposeIntermediateTensorInfo(_)), t.disposeIntermediateTensorInfo(x), t.disposeIntermediateTensorInfo(y), w;
}
let u = i.map((h) => {
let g = b.sizeFromShape(h.shape.slice(s));
return Je({ inputs: { x: h }, backend: t, attrs: { shape: [-1, g] } });
}), c = u.map((h) => ({ vals: t.data.get(h.dataId).values, shape: h.shape }));
a = I.computeOutShape(u.map((h) => h.shape), 1);
let p = u[0].shape[0] === 1, m = mc(c, a, e[0].dtype, p), f = I.computeOutShape(i.map((h) => h.shape), s), d = t.makeTensorInfo(f, e[0].dtype, m);
return u.forEach((h) => t.disposeIntermediateTensorInfo(h)), d;
}
var OR = { kernelName: ni, backendName: "cpu", kernelFunc: jl };
function K0(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, filter: s } = e, { strides: a, pad: i, dataFormat: l, dilations: u, dimRoundingMode: c } = n;
te([o, s], "conv2d");
let p = I.convertConv2DDataFormat(l), m = I.computeConv2DInfo(o.shape, s.shape, a, u, i, c, false, p), f = m.filterHeight, d = m.filterWidth, h = m.dilationHeight, g = m.dilationWidth, x = m.padInfo.left, y = m.padInfo.top, w = m.dataFormat === "channelsLast", _ = new mt(m.outShape, o.dtype), C = b.computeStrides(o.shape), A = b.computeStrides(s.shape), D = C[0], R = w ? C[1] : C[2], P = w ? C[2] : 1, L = w ? 1 : C[1], G = _.strides[0], W = w ? _.strides[1] : _.strides[2], j = w ? _.strides[2] : 1, H = w ? 1 : _.strides[1], q = t.data.get(o.dataId).values, X = t.data.get(s.dataId).values, re = _.values;
for (let J = 0; J < m.batchSize; ++J) {
let oe = J * D, se = J * G;
for (let ne = 0; ne < m.outHeight; ++ne) {
let fe = se + ne * W, ae = ne * m.strideHeight - y;
for (let ge = 0; ge < f; ++ge) {
let de = ae + ge * h;
if (de < 0 || de >= m.inHeight)
continue;
let ye = ge * A[0], _e = oe + de * R;
for (let Re = 0; Re < m.outWidth; ++Re) {
let Ee = fe + Re * j, Fe = Re * m.strideWidth - x;
for (let Ye = 0; Ye < d; ++Ye) {
let ut = Fe + Ye * g;
if (ut < 0 || ut >= m.inWidth)
continue;
let At = ye + Ye * A[1], Dt = _e + ut * P, ft = At;
for (let Ke = 0; Ke < m.inChannels; ++Ke) {
let ht = q[Dt + Ke * L];
for (let Mt = 0; Mt < m.outChannels; ++Mt)
re[Ee + Mt * H] += ht * X[ft + Mt];
ft += m.outChannels;
}
}
}
}
}
}
return t.makeTensorInfo(_.shape, _.dtype, re);
}
var PR = { kernelName: Mo, backendName: "cpu", kernelFunc: K0 };
function yY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, dy: s } = e, { strides: a, pad: i, dataFormat: l, dimRoundingMode: u, filterShape: c } = n;
te([o, s], "conv2dBackpropFilter");
let p = I.convertConv2DDataFormat(l), m = I.computeConv2DInfo(o.shape, c, a, 1, i, u, false, p), { strideHeight: f, strideWidth: d, filterHeight: h, filterWidth: g } = m, x = m.dataFormat === "channelsLast", y = new mt(m.filterShape, "float32"), w = m.padInfo.left, _ = m.padInfo.top, C = t.data.get(o.dataId).values, A = t.data.get(s.dataId).values, D = new mt(o.shape, o.dtype, C), R = new mt(s.shape, s.dtype, A);
for (let P = 0; P < h; ++P) {
let L = Math.max(0, Math.ceil((_ - P) / f)), G = Math.min(m.outHeight, (m.inHeight + _ - P) / f);
for (let W = 0; W < g; ++W) {
let j = Math.max(0, Math.ceil((w - W) / d)), H = Math.min(m.outWidth, (m.inWidth + w - W) / d);
for (let q = 0; q < m.inChannels; ++q)
for (let X = 0; X < m.outChannels; ++X) {
let re = 0;
for (let J = 0; J < m.batchSize; ++J)
for (let oe = L; oe < G; ++oe) {
let se = P + oe * f - _;
for (let ne = j; ne < H; ++ne) {
let fe = W + ne * d - w;
x ? re += D.get(J, se, fe, q) * R.get(J, oe, ne, X) : re += D.get(J, q, se, fe) * R.get(J, X, oe, ne);
}
}
y.set(re, P, W, q, X);
}
}
}
return t.makeTensorInfo(y.shape, y.dtype, y.values);
}
var MR = { kernelName: Kc, backendName: "cpu", kernelFunc: yY };
function bY(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, filter: s } = e, { inputShape: a, strides: i, pad: l, dataFormat: u, dimRoundingMode: c } = n;
te([o, s], "conv2dBackpropInput");
let p = b.computeStrides(s.shape), m = b.computeStrides(o.shape), f = I.convertConv2DDataFormat(u), d = I.computeConv2DInfo(a, s.shape, i, 1, l, c, false, f), h = new mt(d.inShape, "float32"), g = h.values, x = t.data.get(o.dataId).values, y = t.data.get(s.dataId).values, [w, _, C] = p, { batchSize: A, filterHeight: D, filterWidth: R, inChannels: P, inHeight: L, inWidth: G, outChannels: W, outHeight: j, outWidth: H, strideHeight: q, strideWidth: X } = d;
f = d.dataFormat;
let re = D - 1 - d.padInfo.top, J = R - 1 - d.padInfo.left, oe = f === "channelsLast", se = h.strides[0], ne = oe ? h.strides[1] : h.strides[2], fe = oe ? h.strides[2] : 1, ae = oe ? 1 : h.strides[1], ge = m[0], de = oe ? m[1] : m[2], ye = oe ? m[2] : 1, _e = oe ? 1 : m[1];
for (let Re = 0; Re < A; ++Re)
for (let Ee = 0; Ee < P; ++Ee)
for (let Fe = 0; Fe < L; ++Fe) {
let Ye = Fe - re, ut = Math.max(0, Math.ceil(Ye / q)), At = Math.min(j, (D + Ye) / q);
for (let Dt = 0; Dt < G; ++Dt) {
let ft = Dt - J, Ke = Math.max(0, Math.ceil(ft / X)), ht = Math.min(H, (R + ft) / X), Mt = 0;
for (let lr = ut; lr < At; ++lr) {
let gn = lr * q - Ye;
for (let Or = Ke; Or < ht; ++Or) {
let To = Or * X - ft, Zr = ge * Re + de * lr + ye * Or, Tr = w * (D - 1 - gn) + _ * (R - 1 - To) + C * Ee;
for (let Gn = 0; Gn < W; ++Gn) {
let ur = x[Zr + _e * Gn], xn = y[Tr + Gn];
Mt += ur * xn;
}
}
}
let Dn = se * Re + ne * Fe + fe * Dt + ae * Ee;
g[Dn] = Mt;
}
}
return t.makeTensorInfo(h.shape, h.dtype, h.values);
}
var LR = { kernelName: Lo, backendName: "cpu", kernelFunc: bY };
function wY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, filter: s } = e, { strides: a, pad: i, dilations: l } = n;
te([o, s], "conv3d");
let u = I.computeConv3DInfo(o.shape, s.shape, a, l, i), { filterDepth: c, filterHeight: p, filterWidth: m, dilationDepth: f, dilationHeight: d, dilationWidth: h, padInfo: g } = u, x = g.front, y = g.left, w = g.top, _ = new mt(u.outShape, o.dtype), C = t.data.get(o.dataId).values, A = t.data.get(s.dataId).values, D = _.values, R = b.computeStrides(o.shape), P = b.computeStrides(s.shape);
for (let L = 0; L < u.batchSize; ++L) {
let G = L * R[0], W = L * _.strides[0];
for (let j = 0; j < u.outDepth; ++j) {
let H = W + j * _.strides[1], q = j * u.strideDepth - x;
for (let X = 0; X < c; ++X) {
let re = q + X * f;
if (re < 0 || re >= u.inDepth)
continue;
let J = X * P[0], oe = G + re * R[1];
for (let se = 0; se < u.outHeight; ++se) {
let ne = H + se * _.strides[2], fe = se * u.strideHeight - w;
for (let ae = 0; ae < p; ++ae) {
let ge = fe + ae * d;
if (ge < 0 || ge >= u.inHeight)
continue;
let de = J + ae * P[1], ye = oe + ge * R[2];
for (let _e = 0; _e < u.outWidth; ++_e) {
let Re = ne + _e * u.outChannels, Ee = _e * u.strideWidth - y;
for (let Fe = 0; Fe < m; ++Fe) {
let Ye = Ee + Fe * h;
if (Ye < 0 || Ye >= u.inWidth)
continue;
let ut = de + Fe * P[2], At = ye + Ye * u.inChannels, Dt = ut;
for (let ft = 0; ft < u.inChannels; ++ft) {
let Ke = C[At + ft];
for (let ht = 0; ht < u.outChannels; ++ht)
D[Re + ht] += Ke * A[Dt + ht];
Dt += u.outChannels;
}
}
}
}
}
}
}
}
return t.makeTensorInfo(_.shape, _.dtype, _.values);
}
var zR = { kernelName: hl, backendName: "cpu", kernelFunc: wY };
function _Y(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, dy: s } = e, { strides: a, pad: i, filterShape: l } = n;
te([o, s], "conv3dBackpropFilterV2");
let u = b.computeStrides(o.shape), c = b.computeStrides(s.shape), p = I.computeConv3DInfo(o.shape, l, a, 1, i), m = p.strideDepth, f = p.strideHeight, d = p.strideWidth, h = p.filterDepth, g = p.filterHeight, x = p.filterWidth, y = new mt(p.filterShape, "float32"), w = y.values, [_, C, A, D] = y.strides, R = t.data.get(s.dataId).values, [P, L, G, W] = c, j = t.data.get(o.dataId).values, [H, q, X, re] = u, J = p.padInfo.front, oe = p.padInfo.left, se = p.padInfo.top;
for (let ne = 0; ne < h; ++ne) {
let fe = Math.max(0, Math.ceil((J - ne) / m)), ae = Math.min(p.outDepth, (p.inDepth + J - ne) / m), ge = ne * _;
for (let de = 0; de < g; ++de) {
let ye = Math.max(0, Math.ceil((se - de) / f)), _e = Math.min(p.outHeight, (p.inHeight + se - de) / f), Re = de * C + ge;
for (let Ee = 0; Ee < x; ++Ee) {
let Fe = Math.max(0, Math.ceil((oe - Ee) / d)), Ye = Math.min(p.outWidth, (p.inWidth + oe - Ee) / d), ut = Ee * A + Re;
for (let At = 0; At < p.inChannels; ++At) {
let Dt = At * D + ut;
for (let ft = 0; ft < p.outChannels; ++ft) {
let Ke = 0;
for (let ht = 0; ht < p.batchSize; ++ht) {
let Mt = ht * H, Dn = ht * P;
for (let lr = fe; lr < ae; ++lr) {
let Or = (ne + lr * m - J) * q + Mt, To = lr * L + Dn;
for (let Zr = ye; Zr < _e; ++Zr) {
let Gn = (de + Zr * f - se) * X + Or, ur = Zr * G + To;
for (let xn = Fe; xn < Ye; ++xn) {
let Jl = (Ee + xn * d - oe) * re + Gn, Ql = xn * W + ur;
Ke += j[Jl + At] * R[Ql + ft];
}
}
}
}
w[Dt + ft] = Ke;
}
}
}
}
}
return t.makeTensorInfo(y.shape, y.dtype, y.values);
}
var BR = { kernelName: Xc, backendName: "cpu", kernelFunc: _Y };
function kY(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, filter: s } = e, { pad: a, strides: i, inputShape: l } = n;
te([o], "conv3dBackpropInputV2");
let u = b.computeStrides(o.shape), c = b.computeStrides(s.shape), p = I.computeConv3DInfo(l, s.shape, i, 1, a), m = new mt(p.inShape, "float32"), f = m.values, [d, h, g, x] = m.strides, y = t.data.get(o.dataId).values, [w, _, C, A] = u, D = t.data.get(s.dataId).values, [R, P, L, G] = c, { batchSize: W, filterDepth: j, filterHeight: H, filterWidth: q, inChannels: X, inDepth: re, inHeight: J, inWidth: oe, outChannels: se, outDepth: ne, outHeight: fe, outWidth: ae, strideDepth: ge, strideHeight: de, strideWidth: ye } = p, _e = j - 1 - p.padInfo.front, Re = H - 1 - p.padInfo.top, Ee = q - 1 - p.padInfo.left;
for (let Fe = 0; Fe < W; ++Fe)
for (let Ye = 0; Ye < X; ++Ye)
for (let ut = 0; ut < re; ++ut) {
let At = ut - _e, Dt = Math.max(0, Math.ceil(At / ge)), ft = Math.min(ne, (j + At) / ge);
for (let Ke = 0; Ke < J; ++Ke) {
let ht = Ke - Re, Mt = Math.max(0, Math.ceil(ht / de)), Dn = Math.min(fe, (H + ht) / de);
for (let lr = 0; lr < oe; ++lr) {
let gn = lr - Ee, Or = Math.max(0, Math.ceil(gn / ye)), To = Math.min(ae, (q + gn) / ye), Zr = 0;
for (let Tr = Dt; Tr < ft; ++Tr) {
let Gn = Tr * ge - At;
for (let ur = Mt; ur < Dn; ++ur) {
let xn = ur * de - ht;
for (let $n = Or; $n < To; ++$n) {
let Jl = $n * ye - gn, Ql = w * Fe + _ * Tr + C * ur + A * $n, Eo = R * (j - 1 - Gn) + P * (H - 1 - xn) + L * (q - 1 - Jl) + G * Ye;
for (let Ri = 0; Ri < se; ++Ri) {
let zm = y[Ql + Ri], Ec = D[Eo + Ri];
Zr += zm * Ec;
}
}
}
}
f[d * Fe + h * ut + g * Ke + x * lr + Ye] = Zr;
}
}
}
return t.makeTensorInfo(m.shape, m.dtype, m.values);
}
var VR = { kernelName: Yc, backendName: "cpu", kernelFunc: kY };
var vY = $e(zo, (r) => Math.cos(r));
var GR = { kernelName: zo, backendName: "cpu", kernelFunc: vY };
var CY = $e(Bo, (r) => Math.cosh(r));
var WR = { kernelName: Bo, backendName: "cpu", kernelFunc: CY };
function IY(r) {
let { inputs: e, backend: t, attrs: n } = r, { image: o, boxes: s, boxInd: a } = e, { cropSize: i, method: l, extrapolationValue: u } = n, [c, p, m, f] = o.shape, d = s.shape[0], [h, g] = i, x = Ie([d, h, g, f], "float32"), y = t.data.get(s.dataId).values, w = t.data.get(a.dataId).values, _ = t.data.get(o.dataId).values, C = b.computeStrides(o.shape), A = b.computeStrides(x.shape);
for (let D = 0; D < d; D++) {
let R = D * 4, P = y[R], L = y[R + 1], G = y[R + 2], W = y[R + 3], j = w[D];
if (j >= c)
continue;
let H = h > 1 ? (G - P) * (p - 1) / (h - 1) : 0, q = g > 1 ? (W - L) * (m - 1) / (g - 1) : 0;
for (let X = 0; X < h; X++) {
let re = h > 1 ? P * (p - 1) + X * H : 0.5 * (P + G) * (p - 1);
if (re < 0 || re > p - 1) {
for (let J = 0; J < g; J++)
for (let oe = 0; oe < f; oe++) {
let se = oe + J * A[2] + X * A[1] + D * A[0];
x.values[se] = u;
}
continue;
}
if (l === "bilinear") {
let J = Math.floor(re), oe = Math.ceil(re), se = re - J;
for (let ne = 0; ne < g; ne++) {
let fe = g > 1 ? L * (m - 1) + ne * q : 0.5 * (L + W) * (m - 1);
if (fe < 0 || fe > m - 1) {
for (let ye = 0; ye < f; ye++) {
let _e = ye + ne * A[2] + X * A[1] + D * A[0];
x.values[_e] = u;
}
continue;
}
let ae = Math.floor(fe), ge = Math.ceil(fe), de = fe - ae;
for (let ye = 0; ye < f; ye++) {
let _e = ye + ae * C[2] + J * C[1] + j * C[0], Re = _[_e];
_e = ye + ge * C[2] + J * C[1] + j * C[0];
let Ee = _[_e];
_e = ye + ae * C[2] + oe * C[1] + j * C[0];
let Fe = _[_e];
_e = ye + ge * C[2] + oe * C[1] + j * C[0];
let Ye = _[_e], ut = Re + (Ee - Re) * de, At = Fe + (Ye - Fe) * de;
_e = ye + ne * A[2] + X * A[1] + D * A[0], x.values[_e] = ut + (At - ut) * se;
}
}
} else
for (let J = 0; J < g; ++J) {
let oe = g > 1 ? L * (m - 1) + J * q : 0.5 * (L + W) * (m - 1);
if (oe < 0 || oe > m - 1) {
for (let fe = 0; fe < f; fe++) {
let ae = fe + J * A[2] + X * A[1] + D * A[0];
x.values[ae] = u;
}
continue;
}
let se = Math.round(oe), ne = Math.round(re);
for (let fe = 0; fe < f; fe++) {
let ae = fe + se * C[2] + ne * C[1] + j * C[0], ge = fe + J * A[2] + X * A[1] + D * A[0];
x.values[ge] = _[ae];
}
}
}
}
return t.makeTensorInfo(x.shape, x.dtype, x.values);
}
var UR = { kernelName: Hi, backendName: "cpu", kernelFunc: IY };
function SY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, exclusive: a, reverse: i } = n;
te(o, "cumsum");
let l = I.getAxesPermutation([s], o.shape.length), u = o;
l != null && (u = rr({ inputs: { x: o }, backend: t, attrs: { perm: l } }));
let c = I.getInnerMostAxes(1, o.shape.length)[0];
if (c !== u.shape.length - 1)
throw new Error(`backend.cumsum in CPU expects an inner-most axis=${u.shape.length - 1} but got axis=${c}`);
let p = hr(u.dtype, "int32"), m = b.makeZerosTypedArray(b.sizeFromShape(u.shape), p), f = t.data.get(u.dataId).values, d = u.shape[u.shape.length - 1], h = i ? (x, y) => x + d - y - 1 : (x, y) => x + y;
for (let x = 0; x < f.length; x += d)
for (let y = 0; y < d; y++) {
let w = h(x, y);
if (y === 0)
m[w] = a ? 0 : f[w];
else {
let _ = h(x, y - 1);
m[w] = a ? f[_] + m[_] : f[w] + m[_];
}
}
let g = t.makeTensorInfo(u.shape, p, m);
if (l != null) {
let x = I.getUndoAxesPermutation(l), y = rr({ inputs: { x: g }, backend: t, attrs: { perm: x } });
return t.disposeIntermediateTensorInfo(g), t.disposeIntermediateTensorInfo(u), y;
}
return g;
}
var jR = { kernelName: Vo, backendName: "cpu", kernelFunc: SY };
function NY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, weights: s } = e, { size: a, binaryOutput: i } = n;
if (o.shape.length === 1) {
let l = t.data.get(o.dataId).values, u = t.data.get(s.dataId).values, c = km(l, u, s.dtype, s.shape, a);
return t.makeTensorInfo([a], s.dtype, c);
} else if (o.shape.length === 2) {
let l = t.bufferSync(o), u = t.bufferSync(s), c = gy(l, u, a, i);
return t.makeTensorInfo(c.shape, s.dtype, c.values);
}
throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`);
}
var HR = { kernelName: Zc, backendName: "cpu", kernelFunc: NY };
function TY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { blockSize: s, dataFormat: a } = n;
b.assert(a === "NHWC", () => `Only NHWC dataFormat supported on CPU for depthToSpace. Got ${a}`);
let i = o.shape[0], l = o.shape[1], u = o.shape[2], c = o.shape[3], p = l * s, m = u * s, f = c / (s * s), d = t.data.get(o.dataId).values, h = new Float32Array(i * p * m * f), g = 0;
for (let x = 0; x < i; ++x)
for (let y = 0; y < p; ++y) {
let w = Math.floor(y / s), _ = y % s;
for (let C = 0; C < m; ++C) {
let A = Math.floor(C / s), D = C % s, R = (_ * s + D) * f;
for (let P = 0; P < f; ++P) {
let G = P + R + c * (A + u * (w + l * x));
h[g++] = d[G];
}
}
}
return t.makeTensorInfo([i, p, m, f], o.dtype, h);
}
var qR = { kernelName: qi, backendName: "cpu", kernelFunc: TY };
function X0(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, filter: s } = e, { strides: a, pad: i, dilations: l, dimRoundingMode: u } = n;
te([o, s], "depthwiseConv2DNative");
let c = b.computeStrides(o.shape), p = b.computeStrides(s.shape), m = l;
m == null && (m = [1, 1]), b.assert(I.eitherStridesOrDilationsAreOne(a, m), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${m}'`);
let f = I.computeConv2DInfo(o.shape, s.shape, a, m, i, u, true), { filterHeight: d, filterWidth: h, dilationHeight: g, dilationWidth: x, padInfo: y } = f, w = y.left, _ = y.top, C = f.outChannels / f.inChannels, A = new mt(f.outShape, o.dtype), D = t.data.get(o.dataId).values, R = t.data.get(s.dataId).values, P = A.values;
for (let L = 0; L < f.batchSize; ++L) {
let G = L * c[0], W = L * A.strides[0];
for (let j = 0; j < f.outHeight; ++j) {
let H = W + j * A.strides[1], q = j * f.strideHeight - _;
for (let X = 0; X < d; ++X) {
let re = q + X * g;
if (re < 0 || re >= f.inHeight)
continue;
let J = X * p[0], oe = G + re * c[1];
for (let se = 0; se < f.outWidth; ++se) {
let ne = H + se * A.strides[2], fe = se * f.strideWidth - w;
for (let ae = 0; ae < h; ++ae) {
let ge = fe + ae * x;
if (ge < 0 || ge >= f.inWidth)
continue;
let de = J + ae * p[1], ye = oe + ge * f.inChannels, _e = ne, Re = de;
for (let Ee = 0; Ee < f.inChannels; ++Ee) {
let Fe = D[ye + Ee];
for (let Ye = 0; Ye < C; ++Ye)
P[_e + Ye] += Fe * R[Re + Ye];
_e += C, Re += C;
}
}
}
}
}
}
return t.makeTensorInfo(A.shape, A.dtype, A.values);
}
var KR = { kernelName: Go, backendName: "cpu", kernelFunc: X0 };
function EY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, dy: s } = e, { strides: a, dilations: i, pad: l, dimRoundingMode: u, filterShape: c } = n;
te([o, s], "depthwiseConv2dNativeBackpropFilter");
let p = I.computeConv2DInfo(o.shape, c, a, i, l, u, true), { strideHeight: m, strideWidth: f, filterHeight: d, filterWidth: h } = p, g = new mt(p.filterShape, "float32"), x = p.padInfo.left, y = p.padInfo.top, w = p.outChannels / p.inChannels, _ = t.data.get(o.dataId).values, C = new mt(o.shape, o.dtype, _), A = t.data.get(s.dataId).values, D = new mt(s.shape, s.dtype, A);
for (let R = 0; R < d; ++R) {
let P = Math.max(0, Math.ceil((y - R) / m)), L = Math.min(p.outHeight, (p.inHeight + y - R) / m);
for (let G = 0; G < h; ++G) {
let W = Math.max(0, Math.ceil((x - G) / f)), j = Math.min(p.outWidth, (p.inWidth + x - G) / f);
for (let H = 0; H < p.outChannels; ++H) {
let q = Math.trunc(H / w), X = H % w, re = 0;
for (let J = 0; J < p.batchSize; ++J)
for (let oe = P; oe < L; ++oe) {
let se = R + oe * m - y;
for (let ne = W; ne < j; ++ne) {
let fe = G + ne * f - x;
re += C.get(J, se, fe, q) * D.get(J, oe, ne, H);
}
}
g.set(re, R, G, q, X);
}
}
}
return t.makeTensorInfo(g.shape, g.dtype, g.values);
}
var XR = { kernelName: Jc, backendName: "cpu", kernelFunc: EY };
function AY(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, filter: s } = e, { strides: a, dilations: i, pad: l, dimRoundingMode: u, inputShape: c } = n;
te([o, s], "depthwiseConv2DNativeBackpropInput");
let p = b.computeStrides(o.shape), m = b.computeStrides(s.shape), f = I.computeConv2DInfo(c, s.shape, a, i, l, u, true), d = new mt(f.inShape, "float32"), h = d.values, [g, x, y] = d.strides, w = t.data.get(o.dataId).values, [_, C, A] = p, D = t.data.get(s.dataId).values, [R, P, L] = m, { batchSize: G, filterHeight: W, filterWidth: j, inChannels: H, inHeight: q, inWidth: X, outChannels: re, outHeight: J, outWidth: oe, strideHeight: se, strideWidth: ne } = f, fe = W - 1 - f.padInfo.top, ae = j - 1 - f.padInfo.left, ge = re / H;
for (let de = 0; de < G; ++de)
for (let ye = 0; ye < H; ++ye)
for (let _e = 0; _e < q; ++_e) {
let Re = _e - fe, Ee = Math.max(0, Math.ceil(Re / se)), Fe = Math.min(J, (W + Re) / se);
for (let Ye = 0; Ye < X; ++Ye) {
let ut = Ye - ae, At = Math.max(0, Math.ceil(ut / ne)), Dt = Math.min(oe, (j + ut) / ne), ft = 0;
for (let Ke = Ee; Ke < Fe; ++Ke) {
let ht = Ke * se - Re;
for (let Mt = At; Mt < Dt; ++Mt) {
let Dn = Mt * ne - ut, lr = _ * de + C * Ke + A * Mt, gn = R * (W - 1 - ht) + P * (j - 1 - Dn) + L * ye;
for (let Or = 0; Or < ge; ++Or) {
let To = ye * ge + Or, Zr = w[lr + To], Tr = D[gn + Or];
ft += Zr * Tr;
}
}
}
h[g * de + x * _e + y * Ye + ye] = ft;
}
}
return t.makeTensorInfo(d.shape, d.dtype, d.values);
}
var YR = { kernelName: Qc, backendName: "cpu", kernelFunc: AY };
function DY(r) {
let { inputs: e, backend: t } = r, { x: n } = e, o = b.sizeFromShape(n.shape), s = t.data.get(n.dataId).values, a = Ie([o, o], n.dtype), i = a.values;
for (let u = 0; u < s.length; u++)
i[u * o + u] = s[u];
let l = [...n.shape, ...n.shape];
return t.makeTensorInfo(l, a.dtype, a.values);
}
var ZR = { kernelName: ep, backendName: "cpu", kernelFunc: DY };
var JR = { kernelName: gl, backendName: "cpu", kernelFunc: ({ inputs: r, backend: e, attrs: t }) => {
let { x: n, filter: o } = r, { strides: s, pad: a, dilations: i } = t, l = e, u = l.data.get(n.dataId).values, c = n.shape.length, p = l.data.get(o.dataId).values, m = o.shape.length, { batchSize: f, inHeight: d, inWidth: h, inChannels: g, outHeight: x, outWidth: y, padInfo: w, strideHeight: _, strideWidth: C, filterHeight: A, filterWidth: D, dilationHeight: R, dilationWidth: P, outShape: L } = I.computeDilation2DInfo(n.shape, o.shape, s, a, "NHWC", i), G = b.sizeFromShape(L), W = L.length, j = b.getArrayFromDType(n.dtype, G);
for (let q = 0; q < f; ++q)
for (let X = 0; X < x; ++X) {
let re = X * _ - w.top;
for (let J = 0; J < y; ++J) {
let oe = J * C - w.left;
for (let se = 0; se < g; ++se) {
let ne = Number.MIN_SAFE_INTEGER;
for (let ae = 0; ae < A; ++ae) {
let ge = re + ae * R;
if (ge >= 0 && ge < d)
for (let de = 0; de < D; ++de) {
let ye = oe + de * P;
if (ye >= 0 && ye < h) {
let _e = b.locToIndex([q, ge, ye, se], c, b.computeStrides(n.shape)), Re = b.locToIndex([ae, de, se], m, b.computeStrides(o.shape)), Ee = u[_e] + p[Re];
Ee > ne && (ne = Ee);
}
}
}
let fe = b.locToIndex([q, X, J, se], W, b.computeStrides(L));
j[fe] = ne;
}
}
}
return { dataId: l.write(b.toTypedArray(j, n.dtype), L, n.dtype), shape: L, dtype: n.dtype };
} };
var QR = { kernelName: rf, backendName: "cpu", kernelFunc: ({ inputs: r, backend: e, attrs: t }) => {
let { x: n, filter: o, dy: s } = r, { strides: a, pad: i, dilations: l } = t, u = e, c = b.toNestedArray(n.shape, u.data.get(n.dataId).values), p = b.toNestedArray(o.shape, u.data.get(o.dataId).values), { batchSize: m, inHeight: f, inWidth: d, inChannels: h, outHeight: g, outWidth: x, padInfo: y, strideHeight: w, strideWidth: _, filterHeight: C, filterWidth: A, dilationHeight: D, dilationWidth: R, outShape: P } = I.computeDilation2DInfo(n.shape, o.shape, a, i, "NHWC", l);
b.assert(s.rank === P.length, () => `Error in ${rf}, dy must have the same rank as output ${P.length}, but got ${s.rank}`);
let L = b.toNestedArray(P, u.data.get(s.dataId).values), G = b.makeZerosNestedTypedArray(o.shape, o.dtype);
for (let j = 0; j < m; ++j)
for (let H = 0; H < g; ++H) {
let q = H * w - y.top;
for (let X = 0; X < x; ++X) {
let re = X * _ - y.left;
for (let J = 0; J < h; ++J) {
let oe = Number.MIN_SAFE_INTEGER, se = 0, ne = 0;
for (let fe = 0; fe < C; ++fe) {
let ae = q + fe * D;
if (ae >= 0 && ae < f)
for (let ge = 0; ge < A; ++ge) {
let de = re + ge * R;
if (de >= 0 && de < d) {
let ye = c[j][ae][de][J] + p[fe][ge][J];
ye > oe && (oe = ye, se = fe, ne = ge);
}
}
}
G[se][ne][J] += L[j][H][X][J];
}
}
}
return { dataId: u.write(b.toTypedArray(G, n.dtype), o.shape, o.dtype), shape: o.shape, dtype: o.dtype };
} };
var eF = { kernelName: tf, backendName: "cpu", kernelFunc: ({ inputs: r, backend: e, attrs: t }) => {
let { x: n, filter: o, dy: s } = r, { strides: a, pad: i, dilations: l } = t, u = e, c = b.toNestedArray(n.shape, u.data.get(n.dataId).values), p = b.toNestedArray(o.shape, u.data.get(o.dataId).values), { batchSize: m, inHeight: f, inWidth: d, inChannels: h, outHeight: g, outWidth: x, padInfo: y, strideHeight: w, strideWidth: _, filterHeight: C, filterWidth: A, dilationHeight: D, dilationWidth: R, outShape: P } = I.computeDilation2DInfo(n.shape, o.shape, a, i, "NHWC", l);
b.assert(s.rank === P.length, () => `Error in ${tf}, dy must have the same rank as output ${P.length}, but got ${s.rank}`);
let L = b.toNestedArray(P, u.data.get(s.dataId).values), G = b.makeZerosNestedTypedArray(n.shape, n.dtype);
for (let j = 0; j < m; ++j)
for (let H = 0; H < g; ++H) {
let q = H * w - y.top;
for (let X = 0; X < x; ++X) {
let re = X * _ - y.left;
for (let J = 0; J < h; ++J) {
let oe = Number.MIN_SAFE_INTEGER, se = q < 0 ? 0 : q, ne = re < 0 ? 0 : re;
for (let fe = 0; fe < C; ++fe) {
let ae = q + fe * D;
if (ae >= 0 && ae < f)
for (let ge = 0; ge < A; ++ge) {
let de = re + ge * R;
if (de >= 0 && de < d) {
let ye = c[j][ae][de][J] + p[fe][ge][J];
ye > oe && (oe = ye, se = ae, ne = de);
}
}
}
G[j][se][ne][J] += L[j][H][X][J];
}
}
}
return { dataId: u.write(b.toTypedArray(G, n.dtype), n.shape, n.dtype), shape: n.shape, dtype: n.dtype };
} };
function Za(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, keepDims: a } = n;
te(o, "sum");
let i;
o.dtype === "bool" ? i = Co({ inputs: { x: o }, backend: t, attrs: { dtype: "int32" } }) : i = Wr({ inputs: { x: o }, backend: t });
let l = i.shape.length, u = b.parseAxisParam(s, i.shape), c = I.getAxesPermutation(u, l), p = u, m = i;
c != null && (m = rr({ inputs: { x: i }, backend: t, attrs: { perm: c } }), p = I.getInnerMostAxes(p.length, l)), I.assertAxesAreInnerMostDims("sum", p, m.shape.length);
let [f, d] = I.computeOutAndReduceShapes(m.shape, p), h = I.upcastType(m.dtype, "int32"), g = wm(t, f, h), x = b.sizeFromShape(d), y = t.data.get(g.dataId).values, w = t.data.get(m.dataId).values;
for (let _ = 0; _ < y.length; ++_) {
let C = _ * x, A = 0;
for (let D = 0; D < x; ++D)
A += w[C + D];
y[_] = A;
}
if (a) {
let _ = I.expandShapeToKeepDim(g.shape, u), C = g;
g = Je({ inputs: { x: g }, backend: t, attrs: { shape: _ } }), t.disposeIntermediateTensorInfo(C);
}
return t.disposeIntermediateTensorInfo(i), c != null && t.disposeIntermediateTensorInfo(m), g;
}
var tF = { kernelName: bs, backendName: "cpu", kernelFunc: Za };
function $Y(r) {
let { inputs: e, backend: t, attrs: n } = r, { equation: o } = n, s = e, { allDims: a, summedDims: i, idDims: l } = I.decodeEinsumEquation(o, s.length);
I.checkEinsumDimSizes(a.length, l, s);
let { path: u, steps: c } = I.getEinsumComputePath(i, l), p = c.length, m = null, f = a.length, d = [];
for (let h = 0; h < p; ++h) {
for (let g of c[h]) {
let { permutationIndices: x, expandDims: y } = I.getEinsumPermutation(f, l[g]), w;
I.isIdentityPermutation(x) ? w = s[g] : (w = rr({ inputs: { x: s[g] }, backend: t, attrs: { perm: x } }), d.push(w));
let _ = w.shape.slice();
for (let C = 0; C < y.length; ++C)
_.splice(y[C], 0, 1);
b.arraysEqual(w.shape, _) || (w = Je({ inputs: { x: w }, backend: t, attrs: { shape: _ } }), d.push(w)), m === null ? m = w : (m = fc({ inputs: { a: w, b: m }, backend: t }), d.push(m));
}
h < p - 1 && (u[h] >= 0 && (m = Za({ inputs: { x: m }, backend: t, attrs: { axis: u[h] - (a.length - f), keepDims: false } }), d.push(m)), f--);
}
for (let h of d)
h !== m && t.disposeIntermediateTensorInfo(h);
return m;
}
var rF = { kernelName: tp, backendName: "cpu", kernelFunc: $Y };
function RY(r) {
let { inputs: e, backend: t } = r, { dy: n, y: o } = e;
te([n, o], "eluGrad");
let s = new Float32Array(b.sizeFromShape(o.shape)), a = t.data.get(o.dataId).values, i = t.data.get(n.dataId).values;
for (let l = 0; l < a.length; ++l) {
let u = a[l];
u >= 1 ? s[l] = i[l] : s[l] = i[l] * (u + 1);
}
return t.makeTensorInfo(o.shape, "float32", s);
}
var nF = { kernelName: rp, backendName: "cpu", kernelFunc: RY };
var FY = I.ERF_P;
var OY = I.ERF_A1;
var PY = I.ERF_A2;
var MY = I.ERF_A3;
var LY = I.ERF_A4;
var zY = I.ERF_A5;
var BY = $e(Ki, (r) => {
let e = Math.sign(r), t = Math.abs(r), n = 1 / (1 + FY * t);
return e * (1 - ((((zY * n + LY) * n + MY) * n + PY) * n + OY) * n * Math.exp(-t * t));
});
var oF = { kernelName: Ki, backendName: "cpu", kernelFunc: BY };
function Nm(r) {
let { inputs: e, backend: t, attrs: n } = r, { input: o } = e, { dim: s } = n, a = o.shape.length, i = o.shape.slice(), l = s;
return s < 0 && (b.assert(-(a + 1) <= s, () => `Axis must be in the interval [${-(a + 1)}, ${a}]`), l = a + s + 1), i.splice(l, 0, 1), Je({ inputs: { x: o }, backend: t, attrs: { shape: i } });
}
var sF = { kernelName: oi, backendName: "cpu", kernelFunc: Nm };
var VY = Ze((r, e) => r / e);
var Rh = rt(Wo, VY);
var Fh = { kernelName: Wo, backendName: "cpu", kernelFunc: Rh };
function Ry(r, e, t) {
let n = r.shape, o = n[0], s = n[1], a = t.data.get(r.dataId), i = a.complexTensorInfos.real, l = a.complexTensorInfos.imag, u = [o, s], c = b.sizeFromShape(u), p = b.getTypedArrayFromDType("float32", c), m = b.getTypedArrayFromDType("float32", c);
for (let g = 0; g < o; g++) {
let x = So({ inputs: { x: i }, backend: t, attrs: { begin: [g, 0], size: [1, s] } }), y = So({ inputs: { x: l }, backend: t, attrs: { begin: [g, 0], size: [1, s] } }), w = wr({ inputs: { real: x, imag: y }, backend: t }), { real: _, imag: C } = GY(w, e, t), A = I.mergeRealAndImagArrays(_, C);
for (let D = 0; D < s; D++) {
let R = I.getComplexWithIndex(A, D);
p[g * s + D] = R.real, m[g * s + D] = R.imag;
}
t.disposeIntermediateTensorInfo(x), t.disposeIntermediateTensorInfo(y), t.disposeIntermediateTensorInfo(w);
}
let f = t.makeTensorInfo(u, "float32", p), d = t.makeTensorInfo(u, "float32", m), h = wr({ inputs: { real: f, imag: d }, backend: t });
return t.disposeIntermediateTensorInfo(f), t.disposeIntermediateTensorInfo(d), h;
}
function GY(r, e, t) {
let n = b.sizeFromShape(r.shape), o = t.data.get(r.dataId), s = t.data.get(o.complexTensorInfos.real.dataId).values, a = t.data.get(o.complexTensorInfos.imag.dataId).values;
if (WY(n)) {
let i = Y0(s, a, n, e, t), l = [r.shape[0], r.shape[1]];
if (e) {
let u = t.makeTensorInfo(l, "float32", i.real), c = t.makeTensorInfo(l, "float32", i.imag), p = t.makeTensorInfo([], "float32", b.createScalarValue(n, "float32")), m = Wr({ inputs: { x: p }, backend: t }), f = Fh.kernelFunc({ inputs: { a: u, b: p }, backend: t }), d = Fh.kernelFunc({ inputs: { a: c, b: m }, backend: t }), h = t.data.get(f.dataId).values, g = t.data.get(d.dataId).values;
return t.disposeIntermediateTensorInfo(u), t.disposeIntermediateTensorInfo(c), t.disposeIntermediateTensorInfo(p), t.disposeIntermediateTensorInfo(m), t.disposeIntermediateTensorInfo(f), t.disposeIntermediateTensorInfo(d), { real: h, imag: g };
}
return i;
} else {
let i = I.mergeRealAndImagArrays(s, a), l = UY(i, n, e);
return I.splitRealAndImagArrays(l);
}
}
function WY(r) {
return (r & r - 1) == 0;
}
function Y0(r, e, t, n, o) {
if (t === 1)
return { real: r, imag: e };
let s = I.mergeRealAndImagArrays(r, e), a = t / 2, i = I.complexWithEvenIndex(s), l = i.real, u = i.imag, c = [l.length], p = o.makeTensorInfo(c, "float32", l), m = o.makeTensorInfo(c, "float32", u), f = wr({ inputs: { real: p, imag: m }, backend: o }), d = I.complexWithOddIndex(s), h = d.real, g = d.imag, x = [h.length], y = o.makeTensorInfo(x, "float32", h), w = o.makeTensorInfo(x, "float32", g), _ = wr({ inputs: { real: y, imag: w }, backend: o }), C = Y0(l, u, a, n, o), A = C.real, D = C.imag, R = [A.length], P = o.makeTensorInfo(R, "float32", A), L = o.makeTensorInfo(R, "float32", D), G = wr({ inputs: { real: P, imag: L }, backend: o }), W = Y0(h, g, a, n, o), j = W.real, H = W.imag, q = [j.length], X = o.makeTensorInfo(q, "float32", j), re = o.makeTensorInfo(q, "float32", H), J = wr({ inputs: { real: X, imag: re }, backend: o }), oe = I.exponents(t, n), se = [oe.real.length], ne = o.makeTensorInfo(se, "float32", oe.real), fe = o.makeTensorInfo(se, "float32", oe.imag), ae = wr({ inputs: { real: ne, imag: fe }, backend: o }), ge = fc({ inputs: { a: ae, b: J }, backend: o }), de = Ya({ inputs: { a: G, b: ge }, backend: o }), ye = Dh({ inputs: { a: G, b: ge }, backend: o }), _e = vo({ inputs: { input: de }, backend: o }), Re = vo({ inputs: { input: ye }, backend: o }), Ee = Ei({ inputs: { input: de }, backend: o }), Fe = Ei({ inputs: { input: ye }, backend: o }), Ye = jl({ inputs: [_e, Re], backend: o, attrs: { axis: 0 } }), ut = jl({ inputs: [Ee, Fe], backend: o, attrs: { axis: 0 } }), At = o.data.get(Ye.dataId).values, Dt = o.data.get(ut.dataId).values;
return o.disposeIntermediateTensorInfo(p), o.disposeIntermediateTensorInfo(m), o.disposeIntermediateTensorInfo(f), o.disposeIntermediateTensorInfo(y), o.disposeIntermediateTensorInfo(w), o.disposeIntermediateTensorInfo(_), o.disposeIntermediateTensorInfo(P), o.disposeIntermediateTensorInfo(L), o.disposeIntermediateTensorInfo(G), o.disposeIntermediateTensorInfo(X), o.disposeIntermediateTensorInfo(re), o.disposeIntermediateTensorInfo(J), o.disposeIntermediateTensorInfo(ne), o.disposeIntermediateTensorInfo(fe), o.disposeIntermediateTensorInfo(ae), o.disposeIntermediateTensorInfo(ge), o.disposeIntermediateTensorInfo(de), o.disposeIntermediateTensorInfo(ye), o.disposeIntermediateTensorInfo(_e), o.disposeIntermediateTensorInfo(Ee), o.disposeIntermediateTensorInfo(Re), o.disposeIntermediateTensorInfo(Fe), o.disposeIntermediateTensorInfo(Ye), o.disposeIntermediateTensorInfo(ut), { real: At, imag: Dt };
}
function UY(r, e, t) {
let n = new Float32Array(e * 2);
for (let o = 0; o < e; o++) {
let s = 0, a = 0;
for (let i = 0; i < e; i++) {
let l = I.exponent(o * i, e, t), u = I.getComplexWithIndex(r, i);
s += u.real * l.real - u.imag * l.imag, a += u.real * l.imag + u.imag * l.real;
}
t && (s /= e, a /= e), I.assignToTypedArray(n, s, a, o);
}
return n;
}
function jY(r) {
let { inputs: e, backend: t } = r, { input: n } = e, o = b.sizeFromShape(n.shape), s = n.shape[n.shape.length - 1], a = o / s, i = Je({ inputs: { x: n }, backend: t, attrs: { shape: [a, s] } }), l = Ry(i, false, t), u = Je({ inputs: { x: l }, backend: t, attrs: { shape: n.shape } });
return t.disposeIntermediateTensorInfo(i), t.disposeIntermediateTensorInfo(l), u;
}
var iF = { kernelName: np, backendName: "cpu", kernelFunc: jY };
function Oh(r) {
let { backend: e, attrs: t } = r, { shape: n, value: o, dtype: s } = t, a = s || b.inferDtype(o), i = b.getArrayFromDType(a, b.sizeFromShape(n));
return HY(i, o, a), e.makeTensorInfo(n, a, i);
}
var aF = { kernelName: xl, backendName: "cpu", kernelFunc: Oh };
function HY(r, e, t) {
r.fill(e);
}
var lF = { kernelName: Zi, backendName: "cpu", kernelFunc: ({ inputs: r, attrs: e, backend: t }) => {
let { image: n } = r, o = t, s = b.getTypedArrayFromDType(n.dtype, b.sizeFromShape(n.shape)), [a, i, l, u] = n.shape, c = o.data.get(n.dataId).values;
for (let m = 0; m < a; m++) {
let f = m * l * i * u;
for (let d = 0; d < i; d++) {
let h = d * (l * u);
for (let g = 0; g < l; g++) {
let x = g * u;
for (let y = 0; y < u; y++) {
let w = Math.round(l - g - 1), _ = f + h + x + y, C = c[_];
if (w >= 0 && w < l) {
let A = w * u, D = f + h + A + y;
C = c[D];
}
s[_] = C;
}
}
}
}
return { dataId: o.write(s, n.shape, n.dtype), shape: n.shape, dtype: n.dtype };
} };
var qY = Ze((r, e) => Math.floor(r / e));
var KY = rt(qo, qY, null, "int32");
var uF = { kernelName: qo, backendName: "cpu", kernelFunc: KY };
function XY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, filter: s, bias: a, preluActivationWeights: i } = e, { strides: l, pad: u, dataFormat: c, dilations: p, dimRoundingMode: m, activation: f, leakyreluAlpha: d } = n, h = K0({ inputs: { x: o, filter: s }, backend: t, attrs: { strides: l, pad: u, dataFormat: c, dilations: p, dimRoundingMode: m } });
if (a) {
let g = h;
h = Ya({ inputs: { a: h, b: a }, backend: t }), t.disposeIntermediateTensorInfo(g);
}
if (f) {
let g = h;
h = Im(t, h, f, i, d), t.disposeIntermediateTensorInfo(g);
}
return h;
}
var cF = { kernelName: xi, backendName: "cpu", kernelFunc: XY };
function YY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, filter: s, bias: a, preluActivationWeights: i } = e, { strides: l, pad: u, dataFormat: c, dilations: p, dimRoundingMode: m, activation: f, leakyreluAlpha: d } = n, h = X0({ inputs: { x: o, filter: s }, backend: t, attrs: { strides: l, pad: u, dataFormat: c, dilations: p, dimRoundingMode: m } });
if (a) {
let g = h;
h = Ya({ inputs: { a: h, b: a }, backend: t }), t.disposeIntermediateTensorInfo(g);
}
if (f) {
let g = h;
h = Im(t, h, f, i, d), t.disposeIntermediateTensorInfo(g);
}
return h;
}
var pF = { kernelName: yi, backendName: "cpu", kernelFunc: YY };
function ZY(r) {
let { inputs: e, backend: t } = r, { params: n, indices: o } = e, s = b.sizeFromShape(n.shape), a = o.shape, i = a[a.length - 1], [l, u, c, p] = I.prepareAndValidate(n, o);
if (u === 0)
return t.makeTensorInfo(l, n.dtype, []);
let m = t.data.get(o.dataId).values, f = t.bufferSync(n), d = xy(m, f, n.dtype, u, i, c, p, n.shape, s);
return t.makeTensorInfo(l, n.dtype, d.values);
}
var mF = { kernelName: Ji, backendName: "cpu", kernelFunc: ZY };
function JY(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, indices: s } = e, { axis: a, batchDims: i } = n;
te([o, s], "gatherV2");
let l = b.parseAxisParam(a, o.shape)[0], u = t.data.get(s.dataId).values, c = o.shape[l];
for (let _ = 0; _ < u.length; ++_) {
let C = u[_];
b.assert(C <= c - 1 && C >= 0, () => `GatherV2: the index value ${C} is not in [0, ${c - 1}]`);
}
let p = i;
i == null && (p = 0);
let m = b.sizeFromShape(s.shape), f = I.segment_util.collectGatherOpShapeInfo(o, s, l, p), d = Je({ inputs: { x: o }, backend: t, attrs: { shape: [f.batchSize, f.outerSize, f.dimSize, f.sliceSize] } }), h = Je({ inputs: { x: s }, backend: t, attrs: { shape: [f.batchSize, m / f.batchSize] } }), g = [f.batchSize, f.outerSize, m / f.batchSize, f.sliceSize], x = t.bufferSync(h), y = t.bufferSync(d), w = yy(y, x, g);
return t.disposeIntermediateTensorInfo(d), t.disposeIntermediateTensorInfo(h), t.makeTensorInfo(f.outputShape, w.dtype, w.values);
}
var fF = { kernelName: si, backendName: "cpu", kernelFunc: JY };
function QY(r) {
let { inputs: e, backend: t } = r, { input: n } = e, o = b.sizeFromShape(n.shape), s = n.shape[n.shape.length - 1], a = o / s, i = Je({ inputs: { x: n }, backend: t, attrs: { shape: [a, s] } }), l = Ry(i, true, t), u = Je({ inputs: { x: l }, backend: t, attrs: { shape: n.shape } });
return t.disposeIntermediateTensorInfo(i), t.disposeIntermediateTensorInfo(l), u;
}
var dF = { kernelName: op, backendName: "cpu", kernelFunc: QY };
var e9 = $e(ea, (r) => Number.isFinite(r) ? 1 : 0, "bool");
var hF = { kernelName: ea, backendName: "cpu", kernelFunc: e9 };
var t9 = $e(ta, (r) => Math.abs(r) === 1 / 0 ? 1 : 0, "bool");
var gF = { kernelName: ta, backendName: "cpu", kernelFunc: t9 };
var r9 = $e(ra, (r) => Number.isNaN(r) ? 1 : 0, "bool");
var xF = { kernelName: ra, backendName: "cpu", kernelFunc: r9 };
function n9(r) {
let { backend: e, attrs: t } = r, { start: n, stop: o, num: s } = t, a = by(n, o, s);
return e.makeTensorInfo([a.length], "float32", a);
}
var yF = { kernelName: ip, backendName: "cpu", kernelFunc: n9 };
var o9 = $e(sa, (r) => Math.log1p(r));
var bF = { kernelName: sa, backendName: "cpu", kernelFunc: o9 };
var s9 = Ze((r, e) => r && e);
var i9 = rt(ia, s9, null, "bool");
var wF = { kernelName: ia, backendName: "cpu", kernelFunc: i9 };
var a9 = $e(au, (r) => r ? 0 : 1, "bool");
var _F = { kernelName: au, backendName: "cpu", kernelFunc: a9 };
var l9 = Ze((r, e) => r || e);
var u9 = rt(lu, l9, null, "bool");
var kF = { kernelName: lu, backendName: "cpu", kernelFunc: u9 };
function c9(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { depthRadius: s, bias: a, alpha: i, beta: l } = n;
te(o, "LRN");
let u = o.shape[3], c = u - 1, p = t.data.get(o.dataId).values, m = b.sizeFromShape(o.shape), f = new Float32Array(m);
function d(h) {
let g = h % u, x = h - g + Math.max(0, g - s), y = h - g + Math.min(g + s, c), w = 0;
for (; x <= y; x++) {
let _ = p[x];
w += _ * _;
}
return w;
}
for (let h = 0; h < m; h++) {
let g = d(h), x = p[h] * Math.pow(a + i * g, -l);
f[h] = x;
}
return t.makeTensorInfo(o.shape, o.dtype, f);
}
var vF = { kernelName: yl, backendName: "cpu", kernelFunc: c9 };
function p9(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, y: s, dy: a } = e, { depthRadius: i, bias: l, alpha: u, beta: c } = n;
te(a, "LRNGrad");
let p = b.sizeFromShape(a.shape), m = a.shape[3], f = t.data.get(a.dataId).values, d = t.data.get(o.dataId).values, h = t.data.get(s.dataId).values, g = new Float32Array(p), x = p;
for (let y = 0; y < x; y++) {
let w = y % m, _ = y - w + Math.max(0, w - i), C = y - w + Math.min(m, w + i + 1), A = 0;
for (let D = _; D < C; D++)
A += Math.pow(d[D], 2);
A = u * A + l;
for (let D = _; D < C; D++) {
let R = -2 * u * c * d[D] * h[y] / A;
y === D && (R += Math.pow(A, -c)), R *= f[y], g[D] += R;
}
}
return t.makeTensorInfo(a.shape, o.dtype, g);
}
var CF = { kernelName: ap, backendName: "cpu", kernelFunc: p9 };
function Z0(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { reductionIndices: s, keepDims: a } = n, i = t, l = o.shape, u = l.length, c = b.parseAxisParam(s, l), p = c, m = I.getAxesPermutation(p, u), f = i.data.get(o.dataId).values;
if (m != null) {
let _ = new Array(u);
for (let C = 0; C < _.length; C++)
_[C] = l[m[C]];
f = vm(f, l, o.dtype, m, _), p = I.getInnerMostAxes(p.length, u), l = _;
}
te(o, "max"), I.assertAxesAreInnerMostDims("max", p, u);
let [d, h] = I.computeOutAndReduceShapes(l, p), g = b.sizeFromShape(h), x = wy(f, g, d, o.dtype), y = i.write(x, d, o.dtype), w = d;
return a && (w = I.expandShapeToKeepDim(d, c)), { dataId: y, shape: w, dtype: o.dtype };
}
var IF = { kernelName: Jo, backendName: "cpu", kernelFunc: Z0 };
function m9(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e;
te(o, "maxPool");
let { filterSize: s, strides: a, pad: i, dimRoundingMode: l } = n, u = 1;
b.assert(I.eitherStridesOrDilationsAreOne(a, u), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);
let c = I.computePool2DInfo(o.shape, s, a, u, i, l), p;
if (c.filterWidth === 1 && c.filterHeight === 1 && b.arraysEqual(c.inShape, c.outShape))
p = Wr({ inputs: { x: o }, backend: t });
else {
let m = t.data.get(o.dataId).values, f = b.computeStrides(o.shape), d = Sm(m, o.shape, o.dtype, f, c, "max");
p = t.makeTensorInfo(c.outShape, o.dtype, d.values);
}
return p;
}
var SF = { kernelName: es, backendName: "cpu", kernelFunc: m9 };
function f9(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { filterSize: s, strides: a, pad: i, dimRoundingMode: l, dataFormat: u } = n;
te(o, "maxPool3d");
let c = I.computePool3DInfo(o.shape, s, a, 1, i, l, u), p = t.data.get(o.dataId).values, m = $y(p, o.shape, o.dtype, b.computeStrides(o.shape), c, "max");
return t.makeTensorInfo(m.shape, "float32", m.values);
}
var NF = { kernelName: bl, backendName: "cpu", kernelFunc: f9 };
function d9(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, input: s } = e, { filterSize: a, strides: i, pad: l, dimRoundingMode: u } = n;
te([o, s], "maxPool3DGrad");
let c = I.computePool3DInfo(s.shape, a, i, 1, l, u), p = t.bufferSync(s), m = vR(p, c), f = c.strideDepth, d = c.strideHeight, h = c.strideWidth, g = c.dilationDepth, x = c.dilationHeight, y = c.dilationWidth, w = c.effectiveFilterDepth, _ = c.effectiveFilterHeight, C = c.effectiveFilterWidth, A = w - 1 - c.padInfo.front, D = C - 1 - c.padInfo.left, R = _ - 1 - c.padInfo.top, P = Ie(s.shape, "float32"), L = t.bufferSync(o);
for (let G = 0; G < c.batchSize; ++G)
for (let W = 0; W < c.inChannels; ++W)
for (let j = 0; j < c.inDepth; ++j)
for (let H = 0; H < c.inHeight; ++H)
for (let q = 0; q < c.inWidth; ++q) {
let X = j - A, re = H - R, J = q - D, oe = 0;
for (let se = 0; se < w; se += g) {
let ne = (X + se) / f;
if (!(ne < 0 || ne >= c.outDepth || Math.floor(ne) !== ne))
for (let fe = 0; fe < _; fe += x) {
let ae = (re + fe) / d;
if (!(ae < 0 || ae >= c.outHeight || Math.floor(ae) !== ae))
for (let ge = 0; ge < C; ge += y) {
let de = (J + ge) / h;
if (de < 0 || de >= c.outWidth || Math.floor(de) !== de)
continue;
let ye = w * _ * C - 1 - m.get(G, ne, ae, de, W), _e = se * _ * C + fe * C + ge, Re = ye === _e ? 1 : 0;
if (Re === 0)
continue;
oe += L.get(G, ne, ae, de, W) * Re;
}
}
}
P.set(oe, G, j, H, q, W);
}
return t.makeTensorInfo(P.shape, P.dtype, P.values);
}
var TF = { kernelName: up, backendName: "cpu", kernelFunc: d9 };
function h9(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, input: s, output: a } = e, i = s;
te([s, a], "maxPoolGrad");
let { filterSize: l, strides: u, pad: c, dimRoundingMode: p } = n, m = I.computePool2DInfo(i.shape, l, u, 1, c, p), f = t.data.get(i.dataId).values, d = Ie(m.outShape, i.dtype, Dy(f, i.shape, i.dtype, m).values), h = m.strideHeight, g = m.strideWidth, x = m.dilationHeight, y = m.dilationWidth, w = m.effectiveFilterHeight, _ = m.effectiveFilterWidth, C = _ - 1 - m.padInfo.left, A = w - 1 - m.padInfo.top, D = Ie(i.shape, "float32"), R = t.data.get(o.dataId).values, P = Ie(o.shape, "float32", R);
for (let L = 0; L < m.batchSize; ++L)
for (let G = 0; G < m.inChannels; ++G)
for (let W = 0; W < m.inHeight; ++W)
for (let j = 0; j < m.inWidth; ++j) {
let H = W - A, q = j - C, X = 0;
for (let re = 0; re < w; re += x) {
let J = (H + re) / h;
if (!(J < 0 || J >= m.outHeight || Math.floor(J) !== J))
for (let oe = 0; oe < _; oe += y) {
let se = (q + oe) / g;
if (se < 0 || se >= m.outWidth || Math.floor(se) !== se)
continue;
let ne = w * _ - 1 - d.get(L, J, se, G), fe = re * _ + oe, ae = ne === fe ? 1 : 0;
if (ae === 0)
continue;
X += P.get(L, J, se, G) * ae;
}
}
D.set(X, L, W, j, G);
}
return t.makeTensorInfo(D.shape, D.dtype, D.values);
}
var EF = { kernelName: lp, backendName: "cpu", kernelFunc: h9 };
function AF(r, e, t, n, o) {
let s = b.computeStrides(e), a = Sm(r, e, t, s, o, "max"), i = Dy(r, e, t, o, true, n);
return [a.values, i.values];
}
var DF = { kernelName: cp, backendName: "cpu", kernelFunc: ({ inputs: r, attrs: e, backend: t }) => {
let { x: n } = r, { filterSize: o, strides: s, pad: a, includeBatchInIndex: i } = e, l = t;
te(n, "MaxPoolWithArgmax");
let u = l.data.get(n.dataId).values, c = I.computePool2DInfo(n.shape, o, s, [1, 1], a), [p, m] = AF(u, n.shape, n.dtype, i, c), f = l.write(p, c.outShape, n.dtype), d = l.write(m, c.outShape, n.dtype);
return [{ dataId: f, shape: c.outShape, dtype: n.dtype }, { dataId: d, shape: c.outShape, dtype: "int32" }];
} };
function g9(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, keepDims: a } = n, i = b.parseAxisParam(s, o.shape), u = I.computeOutAndReduceShapes(o.shape, i)[1], c = b.sizeFromShape(u), p = [], m = t.makeTensorInfo([], "float32", new Float32Array([c]));
p.push(m);
let f = Co({ inputs: { x: o }, backend: t, attrs: { dtype: "float32" } });
p.push(f);
let d = Rh({ inputs: { a: f, b: m }, backend: t });
p.push(d);
let h = Za({ inputs: { x: d }, backend: t, attrs: { axis: s, keepDims: a } });
return p.forEach((g) => t.disposeIntermediateTensorInfo(g)), h;
}
var $F = { kernelName: ts, backendName: "cpu", kernelFunc: g9 };
function x9(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, keepDims: a } = n;
te(o, "min");
let i = b.parseAxisParam(s, o.shape), l = i, u = I.getAxesPermutation(l, o.shape.length), c = o;
u != null && (c = rr({ inputs: { x: o }, backend: t, attrs: { perm: u } }), l = I.getInnerMostAxes(l.length, o.shape.length)), I.assertAxesAreInnerMostDims("min", l, c.shape.length);
let [p, m] = I.computeOutAndReduceShapes(c.shape, l), f = b.sizeFromShape(m), d = b.makeZerosTypedArray(b.sizeFromShape(p), c.dtype), h = t.data.get(c.dataId).values;
for (let x = 0; x < d.length; ++x) {
let y = x * f, w = h[y];
for (let _ = 0; _ < f; ++_) {
let C = h[y + _];
(Number.isNaN(C) || C < w) && (w = C);
}
d[x] = w;
}
u != null && t.disposeIntermediateTensorInfo(c);
let g = t.makeTensorInfo(p, c.dtype, d);
if (a) {
let x = I.expandShapeToKeepDim(p, i), y = Je({ inputs: { x: g }, backend: t, attrs: { shape: x } });
return t.disposeIntermediateTensorInfo(g), y;
}
return g;
}
var RF = { kernelName: rs, backendName: "cpu", kernelFunc: x9 };
function y9(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { paddings: s, mode: a } = n;
te(o, "mirrorPad");
let i = s.map((w, _) => w[0] + o.shape[_] + w[1]), l = s.map((w) => w[0]), u = s.map((w, _) => w[0] + o.shape[_]), c = a === "reflect" ? 0 : 1, p = t.data.get(o.dataId).values, m = o.shape.length, f = b.computeStrides(o.shape), d = b.sizeFromShape(i), h = i.length, g = b.computeStrides(i), x = b.getTypedArrayFromDType(o.dtype, d);
for (let w = 0; w < d; w++) {
let _ = b.indexToLoc(w, h, g);
for (let A = 0; A < h; A++)
_[A] < l[A] ? _[A] = l[A] * 2 - _[A] - c : _[A] >= u[A] && (_[A] = (u[A] - 1) * 2 - _[A] + c);
_ = _.map((A, D) => A - l[D]);
let C = b.locToIndex(_, m, f);
x[w] = p[C];
}
return { dataId: t.write(x, i, o.dtype), shape: i, dtype: o.dtype };
}
var FF = { kernelName: os, backendName: "cpu", kernelFunc: y9 };
var b9 = Ze((r, e) => {
let t = r % e;
return r < 0 && e < 0 || r >= 0 && e >= 0 ? t : (t + e) % e;
});
var w9 = rt(aa, b9);
var OF = { kernelName: aa, backendName: "cpu", kernelFunc: w9 };
var MF = ou(dk());
function J0(r) {
let { inputs: e, backend: t, attrs: n } = r, { logits: o } = e, { dim: s } = n, a = o.shape.length, i = s;
if (i === -1 && (i = a - 1), i !== a - 1)
throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${a} and dim was ${i}`);
let l = b.parseAxisParam([i], o.shape), u = Z0({ inputs: { x: o }, backend: t, attrs: { reductionIndices: l, keepDims: false } }), c = I.expandShapeToKeepDim(u.shape, l), p = Je({ inputs: { x: u }, backend: t, attrs: { shape: c } }), m = Dh({ inputs: { a: o, b: p }, backend: t }), f = I0({ inputs: { x: m }, backend: t }), d = Za({ inputs: { x: f }, backend: t, attrs: { axis: l, keepDims: false } }), h = Je({ inputs: { x: d }, backend: t, attrs: { shape: c } }), g = Rh({ inputs: { a: f, b: h }, backend: t });
return t.disposeIntermediateTensorInfo(u), t.disposeIntermediateTensorInfo(p), t.disposeIntermediateTensorInfo(m), t.disposeIntermediateTensorInfo(f), t.disposeIntermediateTensorInfo(d), t.disposeIntermediateTensorInfo(h), g;
}
var PF = { kernelName: ws, backendName: "cpu", kernelFunc: J0 };
function _9(r) {
let { inputs: e, backend: t, attrs: n } = r, { logits: o } = e, { numSamples: s, seed: a, normalized: i } = n;
te(o, "multinomial");
let l = i ? o : J0({ inputs: { logits: o }, backend: t, attrs: { dim: -1 } }), u = l.shape[0], c = l.shape[1], p = t.data.get(l.dataId).values, m = [u, s], f = b.makeZerosTypedArray(b.sizeFromShape(m), "int32");
for (let d = 0; d < u; ++d) {
let h = d * c, g = new Float32Array(c - 1);
g[0] = p[h];
for (let w = 1; w < g.length; ++w)
g[w] = g[w - 1] + p[h + w];
let x = MF.alea(a.toString()), y = d * s;
for (let w = 0; w < s; ++w) {
let _ = x();
f[y + w] = g.length;
for (let C = 0; C < g.length; C++)
if (_ < g[C]) {
f[y + w] = C;
break;
}
}
}
return i || t.disposeIntermediateTensorInfo(l), t.makeTensorInfo(m, "int32", f);
}
var LF = { kernelName: pp, backendName: "cpu", kernelFunc: _9 };
var k9 = Gr.nonMaxSuppressionV3Impl;
function v9(r) {
let { inputs: e, backend: t, attrs: n } = r, { boxes: o, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: l } = n;
te(o, "NonMaxSuppression");
let u = t.data.get(o.dataId).values, c = t.data.get(s.dataId).values, { selectedIndices: p } = k9(u, c, a, i, l);
return t.makeTensorInfo([p.length], "int32", new Int32Array(p));
}
var zF = { kernelName: ua, backendName: "cpu", kernelFunc: v9 };
var C9 = Gr.nonMaxSuppressionV4Impl;
function I9(r) {
let { inputs: e, backend: t, attrs: n } = r, { boxes: o, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: l, padToMaxOutputSize: u } = n;
te(o, "NonMaxSuppressionPadded");
let c = t.data.get(o.dataId).values, p = t.data.get(s.dataId).values, { selectedIndices: m, validOutputs: f } = C9(c, p, a, i, l, u);
return [t.makeTensorInfo([m.length], "int32", new Int32Array(m)), t.makeTensorInfo([], "int32", new Int32Array([f]))];
}
var BF = { kernelName: ca, backendName: "cpu", kernelFunc: I9 };
var S9 = Gr.nonMaxSuppressionV5Impl;
function N9(r) {
let { inputs: e, backend: t, attrs: n } = r, { boxes: o, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: l, softNmsSigma: u } = n;
te(o, "NonMaxSuppressionWithScore");
let c = t.data.get(o.dataId).values, p = t.data.get(s.dataId).values, m = a, f = i, d = l, h = u, { selectedIndices: g, selectedScores: x } = S9(c, p, m, f, d, h);
return [t.makeTensorInfo([g.length], "int32", new Int32Array(g)), t.makeTensorInfo([x.length], "float32", new Float32Array(x))];
}
var VF = { kernelName: pa, backendName: "cpu", kernelFunc: N9 };
function T9(r) {
let { inputs: e, backend: t, attrs: n } = r, { indices: o } = e, { depth: s, onValue: a, offValue: i } = n;
te(o, "oneHot");
let l = b.sizeFromShape(o.shape), u = new Float32Array(l * s);
u.fill(i);
let c = t.data.get(o.dataId).values;
for (let p = 0; p < l; ++p)
c[p] >= 0 && c[p] < s && (u[p * s + c[p]] = a);
return t.makeTensorInfo([...o.shape, s], "int32", u);
}
var GF = { kernelName: is, backendName: "cpu", kernelFunc: T9 };
function Ph(r) {
let { inputs: e, backend: t } = r, { x: n } = e;
if (n.dtype === "string")
throw new Error("zerosLike is not supported for string tensors");
if (n.dtype === "complex64") {
let o = vo({ inputs: { input: n }, backend: t }), s = Ph({ inputs: { x: o }, backend: t }), a = Ei({ inputs: { input: n }, backend: t }), i = Ph({ inputs: { x: a }, backend: t }), l = wr({ inputs: { real: s, imag: i }, backend: t });
return t.disposeIntermediateTensorInfo(o), t.disposeIntermediateTensorInfo(s), t.disposeIntermediateTensorInfo(a), t.disposeIntermediateTensorInfo(i), l;
} else
return Oh({ backend: t, attrs: { shape: n.shape, value: 0, dtype: n.dtype } });
}
var WF = { kernelName: hi, backendName: "cpu", kernelFunc: Ph };
function UF(r) {
let { inputs: e, backend: t } = r, { x: n } = e;
if (n.dtype === "string")
throw new Error("onesLike is not supported for string tensors");
if (n.dtype === "complex64") {
let o = vo({ inputs: { input: n }, backend: t }), s = UF({ inputs: { x: o }, backend: t }), a = Ei({ inputs: { input: n }, backend: t }), i = Ph({ inputs: { x: a }, backend: t }), l = wr({ inputs: { real: s, imag: i }, backend: t });
return t.disposeIntermediateTensorInfo(o), t.disposeIntermediateTensorInfo(s), t.disposeIntermediateTensorInfo(a), t.disposeIntermediateTensorInfo(i), l;
} else
return Oh({ backend: t, attrs: { shape: n.shape, value: 1, dtype: n.dtype } });
}
var jF = { kernelName: ai, backendName: "cpu", kernelFunc: UF };
function Q0(r) {
let { inputs: e, backend: t, attrs: n } = r, { axis: o } = n;
if (e.length === 1)
return Nm({ inputs: { input: e[0] }, backend: t, attrs: { dim: o } });
let s = e[0].shape, a = e[0].dtype;
e.forEach((c) => {
b.assertShapesMatch(s, c.shape, "All tensors passed to stack must have matching shapes"), b.assert(a === c.dtype, () => "All tensors passed to stack must have matching dtypes");
});
let i = [], l = e.map((c) => {
let p = Nm({ inputs: { input: c }, backend: t, attrs: { dim: o } });
return i.push(p), p;
}), u = jl({ inputs: l, backend: t, attrs: { axis: o } });
return i.forEach((c) => t.disposeIntermediateTensorInfo(c)), u;
}
var HF = { kernelName: li, backendName: "cpu", kernelFunc: Q0 };
function E9(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { paddings: s, constantValue: a } = n;
te(o, "pad");
let i = s.map((y, w) => y[0] + o.shape[w] + y[1]), l = s.map((y) => y[0]), u = t.data.get(o.dataId).values, c = b.sizeFromShape(o.shape), p = o.shape.length, m = b.computeStrides(o.shape), f = b.sizeFromShape(i), d = i.length, h = b.computeStrides(i), g = b.getTypedArrayFromDType(o.dtype, f);
a !== 0 && g.fill(a);
for (let y = 0; y < c; y++) {
let _ = b.indexToLoc(y, p, m).map((A, D) => A + l[D]), C = b.locToIndex(_, d, h);
g[C] = u[y];
}
return { dataId: t.write(g, i, o.dtype), shape: i, dtype: o.dtype };
}
var Fy = { kernelName: as, backendName: "cpu", kernelFunc: E9 };
var A9 = Ze((r, e) => Math.pow(r, e));
var D9 = rt(ls, A9);
var qF = { kernelName: ls, backendName: "cpu", kernelFunc: D9 };
function $9(r) {
let { backend: e, attrs: t } = r, { start: n, stop: o, dtype: s, step: a } = t, i = dc(n, o, a, s);
return e.makeTensorInfo([i.length], s, i);
}
var KF = { kernelName: wl, backendName: "cpu", kernelFunc: $9 };
var R9 = $e(fa, (r) => 1 / r);
var XF = { kernelName: fa, backendName: "cpu", kernelFunc: R9 };
function F9(r) {
let { inputs: e, backend: t, attrs: n } = r, { images: o } = e, { alignCorners: s, halfPixelCenters: a, size: i } = n;
te(o, "resizeBilinear");
let l = b.computeStrides(o.shape), [u, c] = i, [p, m, f, d] = o.shape, h = t.data.get(o.dataId).values, g = new Float32Array(b.sizeFromShape([p, u, c, d])), x = [s && u > 1 ? m - 1 : m, s && c > 1 ? f - 1 : f], y = [s && u > 1 ? u - 1 : u, s && c > 1 ? c - 1 : c], w = 0, _ = x[0] / y[0], C = x[1] / y[1];
for (let A = 0; A < p; A++)
for (let D = 0; D < u; D++) {
let R;
a ? R = _ * (D + 0.5) - 0.5 : R = _ * D;
let P = Math.max(0, Math.floor(R)), L = R - P, G = Math.min(m - 1, Math.ceil(R)), W = A * l[0] + P * l[1], j = A * l[0] + G * l[1];
for (let H = 0; H < c; H++) {
let q;
a ? q = C * (H + 0.5) - 0.5 : q = C * H;
let X = Math.max(0, Math.floor(q)), re = q - X, J = Math.min(f - 1, Math.ceil(q)), oe = W + X * l[2], se = j + X * l[2], ne = W + J * l[2], fe = j + J * l[2];
for (let ae = 0; ae < d; ae++) {
let ge = h[oe + ae], de = h[se + ae], ye = h[ne + ae], _e = h[fe + ae], Re = ge + (ye - ge) * re, Ee = de + (_e - de) * re, Fe = Re + (Ee - Re) * L;
g[w++] = Fe;
}
}
}
return t.makeTensorInfo([p, u, c, d], "float32", g);
}
var YF = { kernelName: ps, backendName: "cpu", kernelFunc: F9 };
function O9(r) {
let { inputs: e, backend: t, attrs: n } = r, { images: o, dy: s } = e, { alignCorners: a } = n;
te([s, o], "resizeBilinearGrad");
let i = b.computeStrides(o.shape), [l, u, c, p] = o.shape, [, m, f] = s.shape, d = new Float32Array(l * u * c * p), h = [a && m > 1 ? u - 1 : u, a && f > 1 ? c - 1 : c], g = [a && m > 1 ? m - 1 : m, a && f > 1 ? f - 1 : f], x = h[0] / g[0], y = h[1] / g[1], w = t.data.get(s.dataId).values, _ = 0;
for (let C = 0; C < l; C++) {
let A = C * i[0];
for (let D = 0; D < m; D++) {
let R = D * x, P = Math.floor(R), L = Math.min(Math.ceil(R), u - 1), G = A + P * i[1], W = A + L * i[1], j = R - P, H = 1 - j;
for (let q = 0; q < f; q++) {
let X = q * y, re = Math.floor(X), J = Math.min(Math.ceil(X), c - 1), oe = X - re, se = 1 - oe, ne = G + re * i[2], fe = G + J * i[2], ae = W + re * i[2], ge = W + J * i[2], de = H * se, ye = H * oe, _e = j * se, Re = j * oe;
for (let Ee = 0; Ee < p; Ee++) {
let Fe = w[_++];
d[ne + Ee] += Fe * de, d[fe + Ee] += Fe * ye, d[ae + Ee] += Fe * _e, d[ge + Ee] += Fe * Re;
}
}
}
}
return t.makeTensorInfo([l, c, u, p], "float32", d);
}
var ZF = { kernelName: dp, backendName: "cpu", kernelFunc: O9 };
function P9(r) {
let { inputs: e, backend: t, attrs: n } = r, { images: o } = e, { alignCorners: s, halfPixelCenters: a, size: i } = n;
te(o, "resizeNearestNeighbor");
let l = b.computeStrides(o.shape), [u, c] = i, [p, m, f, d] = o.shape, h = t.data.get(o.dataId).values, g = new Float32Array(p * u * c * d), x = [s && u > 1 ? m - 1 : m, s && c > 1 ? f - 1 : f], y = [s && u > 1 ? u - 1 : u, s && c > 1 ? c - 1 : c], w = x[0] / y[0], _ = x[1] / y[1], C = 0;
for (let A = 0; A < p; A++) {
let D = A * l[0];
for (let R = 0; R < u; R++) {
let P = a ? w * (R + 0.5) : w * R, L = Math.min(m - 1, s ? Math.round(P) : Math.floor(P));
a && (L = Math.max(0, L));
let G = D + L * l[1];
for (let W = 0; W < c; W++) {
let j = a ? _ * (W + 0.5) : _ * W, H = Math.min(f - 1, s ? Math.round(j) : Math.floor(j));
a && (H = Math.max(0, H));
let q = G + H * l[2];
for (let X = 0; X < d; X++) {
let re = h[q + X];
g[C++] = re;
}
}
}
}
return t.makeTensorInfo([p, u, c, d], o.dtype, g);
}
var JF = { kernelName: _l, backendName: "cpu", kernelFunc: P9 };
function M9(r) {
let { inputs: e, backend: t, attrs: n } = r, { images: o, dy: s } = e, { alignCorners: a } = n;
te([s, o], "resizeNearestNeighborGrad");
let i = b.computeStrides(o.shape), l = b.computeStrides(s.shape), [u, c, p, m] = o.shape, [, f, d] = s.shape, h = new Float32Array(u * c * p * m), g = t.data.get(s.dataId).values, x = [a && f > 1 ? c - 1 : c, a && d > 1 ? p - 1 : p], y = [a && f > 1 ? f - 1 : f, a && d > 1 ? d - 1 : d], w = x[0] / y[0], _ = x[1] / y[1], C = 1 / w, A = 1 / _, D = Math.ceil(C) * 2 + 2, R = Math.ceil(A) * 2 + 2;
for (let P = 0; P < u; P++) {
let L = P * i[0];
for (let G = 0; G < c; G++) {
let W = L + G * i[1], j = Math.floor(G * C), H = Math.floor(j - D / 2);
for (let q = 0; q < p; q++) {
let X = W + q * i[2], re = Math.floor(q * A), J = Math.floor(re - R / 2);
for (let oe = 0; oe < m; oe++) {
let se = 0;
for (let ne = 0; ne < D; ne++) {
let fe = ne + H;
if (fe < 0 || fe >= f)
continue;
let ae = L + fe * l[1], ge = fe * w, de = Math.min(c - 1, a ? Math.round(ge) : Math.floor(ge));
if (G === de)
for (let ye = 0; ye < R; ye++) {
let _e = ye + J;
if (_e < 0 || _e >= d)
continue;
let Re = ae + _e * l[2], Ee = _e * _, Fe = Math.min(p - 1, a ? Math.round(Ee) : Math.floor(Ee));
q === Fe && (se += g[Re + oe]);
}
}
h[X + oe] = se;
}
}
}
}
return t.makeTensorInfo(o.shape, o.dtype, h);
}
var QF = { kernelName: fp, backendName: "cpu", kernelFunc: M9 };
function L9(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { dims: s } = n;
te(o, "reverse");
let a = o.shape.length, i = b.parseAxisParam(s, o.shape);
if (a === 0)
return Wr({ inputs: { x: o }, backend: t });
let l = new mt(o.shape, o.dtype), u = t.bufferSync(o);
for (let c = 0; c < l.size; c++) {
let p = l.indexToLoc(c), m = p.slice();
i.forEach((f) => m[f] = o.shape[f] - 1 - m[f]), l.set(u.get(...m), ...p);
}
return t.makeTensorInfo(l.shape, l.dtype, l.values);
}
var eO = { kernelName: fs, backendName: "cpu", kernelFunc: L9 };
var tO = { kernelName: ka, backendName: "cpu", kernelFunc: ({ inputs: r, attrs: e, backend: t }) => {
let { image: n } = r, { radians: o, fillValue: s, center: a } = e, i = t, l = b.getTypedArrayFromDType(n.dtype, b.sizeFromShape(n.shape)), [u, c, p, m] = n.shape, [f, d] = I.getImageCenter(a, c, p), h = 255, g = Math.sin(o), x = Math.cos(o), y = i.data.get(n.dataId).values;
for (let _ = 0; _ < u; _++) {
let C = _ * p * c * m;
for (let A = 0; A < c; A++) {
let D = A * (p * m);
for (let R = 0; R < p; R++) {
let P = R * m;
for (let L = 0; L < m; L++) {
let G = [u, A, R, L], W = G[2], j = G[1], H = (W - f) * x - (j - d) * g, q = (W - f) * g + (j - d) * x;
H = Math.round(H + f), q = Math.round(q + d);
let X = s;
if (typeof s != "number" && (L === 3 ? X = h : X = s[L]), H >= 0 && H < p && q >= 0 && q < c) {
let J = q * (p * m), oe = H * m, se = C + J + oe + L;
X = y[se];
}
let re = C + D + P + L;
l[re] = X;
}
}
}
}
return { dataId: i.write(l, n.shape, n.dtype), shape: n.shape, dtype: n.dtype };
} };
var z9 = $e(ds, (r) => {
let e = Math.floor(r);
return r - e < 0.5 ? Math.floor(r) : r - e > 0.5 ? Math.ceil(r) : e % 2 == 0 ? e : e + 1;
});
var rO = { kernelName: ds, backendName: "cpu", kernelFunc: z9 };
function Oy(r, e, t, n, o, s, a, i, l, u) {
let c = [n / o, o], p = r.values, m = e.values;
if (n === 0)
return Ie(t, e.dtype);
let f = Ie(c, e.dtype);
f.values.fill(l);
for (let d = 0; d < s; d++) {
let h = [], g = 0;
for (let x = 0; x < a; x++) {
let y = p[d * a + x];
h.push(y), g += y * i[x];
}
if (g < 0 || g >= n / o)
throw new Error(`Invalid indices: ${h} does not index into ${t}`);
for (let x = 0; x < o; x++)
u ? f.values[g * o + x] += m[d * o + x] : f.values[g * o + x] = e.rank === 0 ? m[0] : m[d * o + x];
}
return f;
}
function B9(r) {
let { inputs: e, backend: t, attrs: n } = r, { indices: o, updates: s } = e, { shape: a } = n, { sliceRank: i, numUpdates: l, sliceSize: u, strides: c, outputSize: p } = I.calculateShapes(s, o, a), m = true, f = t.bufferSync(o), d = t.bufferSync(s), h = Oy(f, d, a, p, u, l, i, c, 0, m);
return t.makeTensorInfo(a, h.dtype, h.values);
}
var nO = { kernelName: da, backendName: "cpu", kernelFunc: B9 };
function V9(r) {
let { inputs: e, backend: t } = r, { condition: n, t: o, e: s } = e;
te([n, o, s], "select");
let a = n.shape.length, i = t.data.get(n.dataId).values, l = t.data.get(o.dataId).values, u = t.data.get(s.dataId).values, c = hr(o.dtype, s.dtype), p = b.makeZerosTypedArray(b.sizeFromShape(o.shape), c), m = 0, f = a === 0 || a > 1 || o.shape.length === 1 ? 1 : b.sizeFromShape(o.shape.slice(1));
for (let d = 0; d < i.length; d++)
for (let h = 0; h < f; h++)
i[d] === 1 ? p[m++] = l[d] : p[m++] = u[d];
return t.makeTensorInfo(o.shape, c, p);
}
var oO = { kernelName: ci, backendName: "cpu", kernelFunc: V9 };
var G9 = I.SELU_SCALEALPHA;
var W9 = I.SELU_SCALE;
var U9 = $e(ha, (r) => r >= 0 ? W9 * r : G9 * (Math.exp(r) - 1));
var sO = { kernelName: ha, backendName: "cpu", kernelFunc: U9 };
var j9 = $e(xa, (r) => r < 0 ? -1 : r > 0 ? 1 : 0);
var iO = { kernelName: xa, backendName: "cpu", kernelFunc: j9 };
var H9 = $e(gs, (r) => Math.sin(r));
var aO = { kernelName: gs, backendName: "cpu", kernelFunc: H9 };
var q9 = $e(ga, (r) => Math.sinh(r));
var lO = { kernelName: ga, backendName: "cpu", kernelFunc: q9 };
var K9 = 11920928955078125e-23;
var uO = Math.log(K9) + 2;
var X9 = $e(ya, (r) => {
let e = r > -uO, t = r < uO, n = Math.exp(r), o;
return t ? o = n : e ? o = r : o = Math.log(1 + n), o;
});
var cO = { kernelName: ya, backendName: "cpu", kernelFunc: X9 };
function Y9(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { blockShape: s, paddings: a } = n;
te([o], "spaceToBatchND");
let i = b.sizeFromShape(s), l = [[0, 0]];
l.push(...a);
for (let A = 1 + s.length; A < o.shape.length; ++A)
l.push([0, 0]);
let u = Fy.kernelFunc({ inputs: { x: o }, backend: t, attrs: { paddings: l, constantValue: 0 } }), c = I.getReshaped(u.shape, s, i, false), p = I.getPermuted(c.length, s.length, false), m = I.getReshapedPermuted(u.shape, s, i, false), h = Je({ inputs: { x: u }, backend: t, attrs: { shape: c } }), y = rr({ inputs: { x: h }, backend: t, attrs: { perm: p } }), C = Je({ inputs: { x: y }, backend: t, attrs: { shape: m } });
return t.disposeIntermediateTensorInfo(u), t.disposeIntermediateTensorInfo(h), t.disposeIntermediateTensorInfo(y), C;
}
var pO = { kernelName: mi, backendName: "cpu", kernelFunc: Y9 };
function Z9(r) {
let { inputs: e, backend: t } = r, { indices: n, values: o, denseShape: s, defaultValue: a } = e;
if (s.shape.length !== 1)
throw new Error(`Dense shape must be a vector, saw:
${s.shape}`);
if (n.shape.length !== 2)
throw new Error(`Indices must be a matrix, saw:
${n.shape}`);
if (o.shape.length !== 1)
throw new Error(`Values must be a vector, saw:
${o.shape}`);
if (a.shape.length !== 0)
throw new Error(`Default value must be a scalar, saw:
${a.shape}`);
let i = t.data.get(n.dataId).values, l = t.data.get(o.dataId).values, u = t.data.get(s.dataId).values, c = t.data.get(a.dataId).values[0], [p, m, f, d, h] = _y(i, n.shape, n.dtype, l, o.dtype, u, c);
return [t.makeTensorInfo(m, n.dtype, p), t.makeTensorInfo([m[0]], o.dtype, f), t.makeTensorInfo([d.length], "bool", new Uint8Array(d.map((g) => Number(g)))), t.makeTensorInfo([h.length], n.dtype, new Int32Array(h))];
}
var mO = { kernelName: hp, backendName: "cpu", kernelFunc: Z9 };
function J9(r) {
let { inputs: e, backend: t } = r, { inputIndices: n, inputShape: o, newShape: s } = e;
if (n.shape.length !== 2)
throw new Error(`Input indices should be a matrix but received shape
${n.shape}`);
if (o.shape.length !== 1)
throw new Error(`Input shape should be a vector but received shape
${o.shape}`);
if (s.shape.length !== 1)
throw new Error(`Target shape should be a vector but received shape ${s.shape}`);
let a = Array.from(t.data.get(o.dataId).values), i = t.data.get(n.dataId).values, l = Array.from(t.data.get(s.dataId).values), [u, c, p] = ky(i, n.shape, n.dtype, a, l);
return [t.makeTensorInfo(c, n.dtype, u), t.makeTensorInfo([p.length], s.dtype, new Int32Array(p))];
}
var fO = { kernelName: gp, backendName: "cpu", kernelFunc: J9 };
function Q9(r) {
let { inputs: e, backend: t } = r, { data: n, indices: o, segmentIds: s } = e;
if (n.shape.length < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (o.shape.length !== 1)
throw new Error(`Indices should be a vector but received shape
${o.shape}`);
if (s.shape.length !== 1)
throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);
let a = t.data.get(n.dataId).values, i = t.data.get(o.dataId).values, l = t.data.get(s.dataId).values, [u, c] = Cm(a, n.shape, n.dtype, i, l, true);
return t.makeTensorInfo(c, n.dtype, u);
}
var dO = { kernelName: xp, backendName: "cpu", kernelFunc: Q9 };
function eZ(r) {
let { inputs: e, backend: t } = r, { data: n, indices: o, segmentIds: s } = e;
if (n.shape.length < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (o.shape.length !== 1)
throw new Error(`Indices should be a vector but received shape
${o.shape}`);
if (s.shape.length !== 1)
throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);
let a = t.data.get(n.dataId).values, i = t.data.get(o.dataId).values, l = t.data.get(s.dataId).values, [u, c] = Cm(a, n.shape, n.dtype, i, l);
return t.makeTensorInfo(c, n.dtype, u);
}
var hO = { kernelName: yp, backendName: "cpu", kernelFunc: eZ };
function tZ(r) {
let { inputs: e, backend: t, attrs: n } = r, { sparseIndices: o, sparseValues: s, defaultValue: a } = e, { outputShape: i } = n, { sliceRank: l, numUpdates: u, sliceSize: c, strides: p, outputSize: m } = I.calculateShapes(s, o, i), f = false, d = t.bufferSync(o), h = t.bufferSync(s), g = t.data.get(a.dataId).values[0], x = Oy(d, h, i, m, c, u, l, p, g, f);
return t.makeTensorInfo(i, x.dtype, x.values);
}
var gO = { kernelName: bp, backendName: "cpu", kernelFunc: tZ };
function rZ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { numOrSizeSplits: s, axis: a } = n, i = b.parseAxisParam(a, o.shape)[0], l = I.prepareSplitSize(o, s, i), u = new Array(o.shape.length).fill(0), c = o.shape.slice();
return l.map((p) => {
let m = [...c];
m[i] = p;
let f = So({ inputs: { x: o }, backend: t, attrs: { begin: u, size: m } });
return u[i] += p, f;
});
}
var xO = { kernelName: fi, backendName: "cpu", kernelFunc: rZ };
var yO = { kernelName: kl, backendName: "cpu", kernelFunc: ({ inputs: r, backend: e }) => {
let { x: t } = r, n = e;
te(t, "square");
let o = n.data.get(t.dataId).values, s = new Float32Array(o.length);
for (let i = 0; i < o.length; ++i) {
let l = o[i];
s[i] = l * l;
}
return { dataId: n.write(s, t.shape, t.dtype), shape: t.shape, dtype: t.dtype };
} };
var nZ = $e(no, (r, e) => {
let t = e;
return isNaN(r) ? NaN : r > 0 ? 1 : t.alpha;
});
var bO = { kernelName: no, backendName: "cpu", kernelFunc: nZ };
function oZ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { begin: s, end: a, strides: i, beginMask: l, endMask: u, ellipsisMask: c, newAxisMask: p, shrinkAxisMask: m } = n;
te(o, "stridedSlice");
let { nonStrided: f, $begin: d, $strides: h, size: g, newShape: x, outShape: y } = pr.sliceInfo(o.shape, s, a, i, l, u, c, p, m), w = Je({ inputs: { x: o }, backend: t, attrs: { shape: x } }), _;
if (f) {
let A = So({ inputs: { x: w }, backend: t, attrs: { begin: d, size: g } });
_ = Je({ inputs: { x: A }, backend: t, attrs: { shape: y } }), t.disposeIntermediateTensorInfo(A);
} else if (y.some((A) => A === 0))
_ = t.makeTensorInfo(y, o.dtype, []);
else {
let A = t.bufferSync(w), D = vy(y, A, h, d);
_ = t.makeTensorInfo(D.shape, D.dtype, D.values);
}
let C = Je({ inputs: { x: _ }, backend: t, attrs: { shape: y } });
return t.disposeIntermediateTensorInfo(w), t.disposeIntermediateTensorInfo(_), C;
}
var wO = { kernelName: ba, backendName: "cpu", kernelFunc: oZ };
function sZ(r) {
let { inputs: e, backend: t, attrs: n } = r, { separator: o, nGramWidths: s, leftPad: a, rightPad: i, padWidth: l, preserveShortSequences: u } = n, { data: c, dataSplits: p } = e, m = t.data.get(c.dataId).values, f = t.data.get(p.dataId).values, [d, h] = Cy(m, f, o, s, a, i, l, u);
return [t.makeTensorInfo([d.length], "string", d), t.makeTensorInfo(p.shape, "int32", h)];
}
var _O = { kernelName: wp, backendName: "cpu", kernelFunc: sZ };
function iZ(r) {
let { inputs: e, backend: t, attrs: n } = r, { skipEmpty: o } = n, { input: s, delimiter: a } = e;
if (s.dtype !== "string")
throw new Error("Input must be of datatype string");
if (s.shape.length !== 1)
throw new Error(`Input must be a vector, got shape: ${s.shape}`);
if (a.shape.length !== 0)
throw new Error(`Delimiter must be a scalar, got shape: ${a.shape}`);
let i = t.data.get(s.dataId).values, l = t.data.get(a.dataId).values[0], [u, c, p] = Iy(i, l, o), m = c.length;
return [t.makeTensorInfo([m, 2], "int32", u), t.makeTensorInfo([m], "string", c), t.makeTensorInfo([2], "int32", new Int32Array(p))];
}
var kO = { kernelName: _p, backendName: "cpu", kernelFunc: iZ };
function aZ(r) {
let { inputs: e, backend: t, attrs: n } = r, { numBuckets: o } = n, { input: s } = e;
if (s.dtype !== "string")
throw new Error("Input must be of datatype string");
if (o <= 0)
throw new Error("Number of buckets must be at least 1");
let a = t.data.get(s.dataId).values, i = Sy(a, o);
return t.makeTensorInfo(s.shape, "int32", i);
}
var vO = { kernelName: kp, backendName: "cpu", kernelFunc: aZ };
var lZ = $e(vs, (r) => Math.tan(r));
var CO = { kernelName: vs, backendName: "cpu", kernelFunc: lZ };
var uZ = $e(Cs, (r) => Math.tanh(r));
var IO = { kernelName: Cs, backendName: "cpu", kernelFunc: uZ };
function cZ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { reps: s } = n;
te(o, "tile");
let a = Ny(t.bufferSync(o), s);
return t.makeTensorInfo(a.shape, a.dtype, a.values);
}
var SO = { kernelName: Hn, backendName: "cpu", kernelFunc: cZ };
function pZ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { k: s, sorted: a } = n;
te(o, "topk");
let i = t.data.get(o.dataId).values, [l, u] = Ty(i, o.shape, o.dtype, s, a);
return [t.makeTensorInfo(l.shape, l.dtype, l.values), t.makeTensorInfo(u.shape, u.dtype, u.values)];
}
var NO = { kernelName: wa, backendName: "cpu", kernelFunc: pZ };
function mZ(r) {
let { inputs: e, attrs: t, backend: n } = r, { image: o, transforms: s } = e, { interpolation: a, fillMode: i, fillValue: l, outputShape: u } = t, [c, p, m, f] = o.shape, [d, h] = u != null ? u : [p, m], g = [c, d, h, f], x = b.computeStrides(o.shape), y = x[0], w = x[1], _ = x[2], C = b.getTypedArrayFromDType(o.dtype, b.sizeFromShape(g));
C.fill(l);
let A = n.data.get(o.dataId).values, D = n.data.get(s.dataId).values;
for (let P = 0; P < c; ++P) {
let L = s.shape[0] === 1 ? D : D.subarray(P * 8, P * 8 + 8);
for (let G = 0; G < d; ++G)
for (let W = 0; W < h; ++W)
for (let j = 0; j < f; ++j) {
let H, q = L[6] * W + L[7] * G + 1;
if (q === 0)
continue;
let X = (L[0] * W + L[1] * G + L[2]) / q, re = (L[3] * W + L[4] * G + L[5]) / q, J = EO(X, m, i), oe = EO(re, p, i);
switch (a) {
case "nearest":
H = xZ(A, p, m, y, w, _, P, oe, J, j, l);
break;
case "bilinear":
H = yZ(A, p, m, y, w, _, P, oe, J, j, l);
break;
default:
throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${a}`);
}
let se = P * y + G * w + W * _ + j;
C[se] = H;
}
return n.makeTensorInfo(g, o.dtype, C);
}
return { dataId: n.write(C, g, o.dtype), shape: o.shape, dtype: o.dtype };
}
var TO = { kernelName: _a, backendName: "cpu", kernelFunc: mZ };
function EO(r, e, t) {
switch (t) {
case "reflect":
return fZ(r, e);
case "wrap":
return dZ(r, e);
case "nearest":
return gZ(r, e);
case "constant":
default:
return hZ(r, e);
}
}
function fZ(r, e) {
let t = r;
if (t < 0)
if (e <= 1)
t = 0;
else {
let n = 2 * e;
t < n && (t = n * Math.trunc(-t / n) + t), t = t < -e ? t + n : -t - 1;
}
else if (t > e - 1)
if (e <= 1)
t = 0;
else {
let n = 2 * e;
t -= n * Math.trunc(t / n), t >= e && (t = n - t - 1);
}
return b.clamp(0, t, e - 1);
}
function dZ(r, e) {
let t = r;
if (t < 0)
if (e <= 1)
t = 0;
else {
let n = e - 1;
t += e * (Math.trunc(-t / n) + 1);
}
else if (t > e - 1)
if (e <= 1)
t = 0;
else {
let n = e - 1;
t -= e * Math.trunc(t / n);
}
return b.clamp(0, t, e - 1);
}
function hZ(r, e) {
return r;
}
function gZ(r, e) {
return b.clamp(0, r, e - 1);
}
function Mh(r, e, t, n, o, s, a, i, l, u, c) {
let p = a * n + i * o + l * s + u;
return 0 <= i && i < e && 0 <= l && l < t ? r[p] : c;
}
function xZ(r, e, t, n, o, s, a, i, l, u, c) {
let p = Math.round(i), m = Math.round(l);
return Mh(r, e, t, n, o, s, a, p, m, u, c);
}
function yZ(r, e, t, n, o, s, a, i, l, u, c) {
let p = Math.floor(i), m = Math.floor(l), f = p + 1, d = m + 1, h = (d - l) * Mh(r, e, t, n, o, s, a, p, m, u, c) + (l - m) * Mh(r, e, t, n, o, s, a, p, d, u, c), g = (d - l) * Mh(r, e, t, n, o, s, a, f, m, u, c) + (l - m) * Mh(r, e, t, n, o, s, a, f, d, u, c);
return (f - i) * h + (i - p) * g;
}
function bZ(r) {
let { inputs: e, attrs: t, backend: n } = r, { axis: o } = t, { x: s } = e;
te(s, "unique");
let a = n.data.get(s.dataId).values, { outputValues: i, outputShape: l, indices: u } = Ey(a, o, s.shape, s.dtype);
return [n.makeTensorInfo(l, s.dtype, i), n.makeTensorInfo([u.length], "int32", u)];
}
var AO = { kernelName: vp, backendName: "cpu", kernelFunc: bZ };
function wZ(r) {
let { inputs: e, backend: t, attrs: n } = r, { value: o } = e, { axis: s } = n;
s < 0 && (s += o.shape.length);
let a = o.shape.length, i = o.shape[s], l = new Array(a - 1), u = 0;
for (let f = 0; f < a; f++)
f !== s && (l[u++] = o.shape[f]);
let c = new Array(a).fill(0), p = o.shape.slice();
p[s] = 1;
let m = new Array(i);
for (let f = 0; f < m.length; f++) {
c[s] = f;
let d = So({ inputs: { x: o }, backend: t, attrs: { begin: c, size: p } });
m[f] = Je({ inputs: { x: d }, backend: t, attrs: { shape: l } }), t.disposeIntermediateTensorInfo(d);
}
return m;
}
var DO = { kernelName: di, backendName: "cpu", kernelFunc: wZ };
function _Z(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, segmentIds: s } = e, { numSegments: a } = n;
te(o, "unsortedSegmentSum");
let i = o.shape.length, l = s.shape.length, u = [], c = [], p = i - l, m = s;
for (let d = 0; d < p; ++d) {
let h = Nm({ inputs: { input: m }, backend: t, attrs: { dim: d + 1 } });
m = h, c.push(h);
}
for (let d = 0; d < a; ++d) {
let h = b.createScalarValue(d, "int32"), g = t.makeTensorInfo([], "int32", h), x = v0({ inputs: { a: g, b: m }, backend: t }), y = Co({ inputs: { x }, backend: t, attrs: { dtype: "float32" } }), w = fc({ inputs: { a: y, b: o }, backend: t }), _ = Za({ inputs: { x: w }, backend: t, attrs: { axis: 0, keepDims: false } });
u.push(_), c.push(g), c.push(x), c.push(y), c.push(w), c.push(_);
}
let f = Q0({ inputs: u, backend: t, attrs: { axis: 0 } });
return c.forEach((d) => t.disposeIntermediateTensorInfo(d)), f;
}
var $O = { kernelName: vl, backendName: "cpu", kernelFunc: _Z };
var kZ = [cR, C$, pR, mR, E$, fR, dR, hR, gR, xR, yR, bR, wR, _R, kR, CR, IR, SR, NR, uR, TR, ER, AR, DR, T$, A$, $R, I$, RR, OR, MR, LR, PR, BR, VR, zR, GR, WR, UR, jR, HR, qR, KR, XR, YR, ZR, JR, eF, QR, Fh, rF, nR, nF, D$, oF, $$, sF, R$, iF, aF, lF, F$, uF, cF, pF, mF, fF, O$, P$, S$, dF, FR, hF, gF, xF, oR, M$, L$, yF, z$, bF, wF, _F, kF, vF, CF, B$, SF, NF, TF, EF, DF, IF, $F, RF, V$, FF, OF, LF, G$, W$, zF, BF, VF, U$, GF, jF, HF, Fy, qF, sR, H$, KF, N$, XF, iR, aR, lR, YF, ZF, JF, QF, eO, tO, rO, q$, nO, oO, sO, X$, iO, aO, lO, Y$, PF, cO, pO, mO, fO, dO, hO, gO, xO, J$, yO, Q$, bO, wO, _O, kO, vO, tR, tF, CO, IO, SO, NO, j$, TO, AO, DO, $O, WF];
for (let r of kZ)
uu(r);
var zO = {};
qe(zO, { assertNotComplex: () => qs, bindCanvasToFramebuffer: () => $Z, bindColorTextureToFramebuffer: () => Vh, bindTextureToProgramUniformSampler: () => dC, bindTextureUnit: () => PO, bindVertexBufferToProgramAttribute: () => Py, callAndCheck: () => ke, canBeRepresented: () => rC, createFragmentShader: () => oC, createFramebuffer: () => pC, createProgram: () => sC, createStaticIndexBuffer: () => lC, createStaticVertexBuffer: () => aC, createTexture: () => uC, createVertexShader: () => nC, getBatchDim: () => Qa, getExtensionOrThrow: () => Tm, getFramebufferErrorMessage: () => MO, getMaxTexturesInShader: () => xC, getNumChannels: () => AZ, getProgramUniformLocation: () => fC, getProgramUniformLocationOrThrow: () => mC, getRowsCols: () => el, getShapeAs3D: () => Gh, getTextureShapeFromLogicalShape: () => hC, getWebGLDisjointQueryTimerVersion: () => yC, getWebGLErrorMessage: () => OO, getWebGLMaxTextureSize: () => gC, hasExtension: () => Bn, isCapableOfRenderingToFloatTexture: () => bC, isDownloadFloatTextureEnabled: () => wC, isReshapeFree: () => ql, isWebGLFenceEnabled: () => kC, isWebGLVersionEnabled: () => Vy, linkProgram: () => iC, resetMaxTextureSize: () => RZ, resetMaxTexturesInShader: () => FZ, unbindColorTextureFromFramebuffer: () => My, unbindTextureUnit: () => DZ, validateFramebuffer: () => Em, validateProgram: () => Bh, validateTextureSize: () => cC });
var gc = {};
var eC = { alpha: false, antialias: false, premultipliedAlpha: false, preserveDrawingBuffer: false, depth: false, stencil: false, failIfMajorPerformanceCaveat: true };
function tC(r, e) {
gc[r] = e;
}
function Zn(r) {
if (!(r in gc)) {
let t = CZ(r);
if (t !== null)
gc[r] = t;
else
return console.log("Could not get context for WebGL version", r), null;
}
let e = gc[r];
return e.isContextLost() ? (delete gc[r], Zn(r)) : (e.disable(e.DEPTH_TEST), e.disable(e.STENCIL_TEST), e.disable(e.BLEND), e.disable(e.DITHER), e.disable(e.POLYGON_OFFSET_FILL), e.disable(e.SAMPLE_COVERAGE), e.enable(e.SCISSOR_TEST), e.enable(e.CULL_FACE), e.cullFace(e.BACK), gc[r]);
}
function vZ(r) {
if (typeof OffscreenCanvas != "undefined" && r === 2)
return new OffscreenCanvas(300, 150);
if (typeof document != "undefined")
return document.createElement("canvas");
throw new Error("Cannot create a canvas in this context");
}
function CZ(r) {
if (r !== 1 && r !== 2)
throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");
let e = vZ(r);
return e.addEventListener("webglcontextlost", (t) => {
t.preventDefault(), delete gc[r];
}, false), r === 1 ? e.getContext("webgl", eC) || e.getContext("experimental-webgl", eC) : e.getContext("webgl2", eC);
}
var Hl;
(function(r) {
r[r.DENSE = 0] = "DENSE", r[r.SHARED_BATCH = 1] = "SHARED_BATCH";
})(Hl || (Hl = {}));
var Ur;
(function(r) {
r[r.RENDER = 0] = "RENDER", r[r.UPLOAD = 1] = "UPLOAD", r[r.PIXELS = 2] = "PIXELS", r[r.DOWNLOAD = 3] = "DOWNLOAD";
})(Ur || (Ur = {}));
var Fr;
(function(r) {
r[r.UNPACKED_FLOAT16 = 0] = "UNPACKED_FLOAT16", r[r.UNPACKED_FLOAT32 = 1] = "UNPACKED_FLOAT32", r[r.PACKED_4X1_UNSIGNED_BYTE = 2] = "PACKED_4X1_UNSIGNED_BYTE", r[r.PACKED_2X2_FLOAT32 = 3] = "PACKED_2X2_FLOAT32", r[r.PACKED_2X2_FLOAT16 = 4] = "PACKED_2X2_FLOAT16";
})(Fr || (Fr = {}));
function xc(r, e) {
return [e, r];
}
function RO(r, e) {
return r * e;
}
function Lh(r) {
let e = b.sizeFromShape(r), t = Math.ceil(e / 4);
return b.sizeToSquarishShape(t);
}
function Ai(r, e) {
return [Math.max(1, Math.ceil(e / 2)), Math.max(1, Math.ceil(r / 2))];
}
function FO(r, e) {
let [t, n] = Ai(r, e);
return t * n * 4;
}
function zh(r, e) {
let t = r, n, o, s, a, i, l, u, c, p, m;
return U().getNumber("WEBGL_VERSION") === 2 ? (n = t.R32F, o = t.R16F, s = t.RGBA16F, a = t.RGBA32F, i = t.RED, u = 4, c = 1, p = t.HALF_FLOAT, m = t.FLOAT) : (n = r.RGBA, o = r.RGBA, s = r.RGBA, a = t.RGBA, i = r.RGBA, u = 4, c = 4, p = e != null ? e.HALF_FLOAT_OES : null, m = r.FLOAT), l = r.RGBA, { internalFormatFloat: n, internalFormatHalfFloat: o, internalFormatPackedHalfFloat: s, internalFormatPackedFloat: a, textureFormatFloat: i, downloadTextureFormat: l, downloadUnpackNumChannels: u, defaultNumChannels: c, textureTypeHalfFloat: p, textureTypeFloat: m };
}
function ke(r, e) {
let t = e();
return U().getBool("DEBUG") && IZ(r), t;
}
function IZ(r) {
let e = r.getError();
if (e !== r.NO_ERROR)
throw new Error("WebGL Error: " + OO(r, e));
}
var SZ = 596e-10;
var NZ = 65504;
function rC(r) {
return !!(U().getBool("WEBGL_RENDER_FLOAT32_ENABLED") || r === 0 || SZ < Math.abs(r) && Math.abs(r) < NZ);
}
function OO(r, e) {
switch (e) {
case r.NO_ERROR:
return "NO_ERROR";
case r.INVALID_ENUM:
return "INVALID_ENUM";
case r.INVALID_VALUE:
return "INVALID_VALUE";
case r.INVALID_OPERATION:
return "INVALID_OPERATION";
case r.INVALID_FRAMEBUFFER_OPERATION:
return "INVALID_FRAMEBUFFER_OPERATION";
case r.OUT_OF_MEMORY:
return "OUT_OF_MEMORY";
case r.CONTEXT_LOST_WEBGL:
return "CONTEXT_LOST_WEBGL";
default:
return `Unknown error code ${e}`;
}
}
function Tm(r, e) {
return Ja(r, () => r.getExtension(e), 'Extension "' + e + '" not supported on this browser.');
}
function nC(r, e) {
let t = Ja(r, () => r.createShader(r.VERTEX_SHADER), "Unable to create vertex WebGLShader.");
if (ke(r, () => r.shaderSource(t, e)), ke(r, () => r.compileShader(t)), r.getShaderParameter(t, r.COMPILE_STATUS) === false)
throw console.log(r.getShaderInfoLog(t)), new Error("Failed to compile vertex shader.");
return t;
}
function oC(r, e) {
let t = Ja(r, () => r.createShader(r.FRAGMENT_SHADER), "Unable to create fragment WebGLShader.");
if (ke(r, () => r.shaderSource(t, e)), ke(r, () => r.compileShader(t)), r.getShaderParameter(t, r.COMPILE_STATUS) === false)
throw EZ(e, r.getShaderInfoLog(t)), new Error("Failed to compile fragment shader.");
return t;
}
var TZ = /ERROR: [0-9]+:([0-9]+):/g;
function EZ(r, e) {
let t = TZ.exec(e);
if (t == null) {
console.log(`Couldn't parse line number in error: ${e}`), console.log(r);
return;
}
let n = +t[1], o = r.split(`
`), s = o.length.toString().length + 2, a = o.map((p, m) => b.rightPad((m + 1).toString(), s) + p), i = 0;
for (let p = 0; p < a.length; p++)
i = Math.max(a[p].length, i);
let l = a.slice(0, n - 1), u = a.slice(n - 1, n), c = a.slice(n);
console.log(l.join(`
`)), console.log(e.split(`
`)[0]), console.log(`%c ${b.rightPad(u[0], i)}`, "border:1px solid red; background-color:#e3d2d2; color:#a61717"), console.log(c.join(`
`));
}
function sC(r) {
return Ja(r, () => r.createProgram(), "Unable to create WebGLProgram.");
}
function iC(r, e) {
if (ke(r, () => r.linkProgram(e)), r.getProgramParameter(e, r.LINK_STATUS) === false)
throw console.log(r.getProgramInfoLog(e)), new Error("Failed to link vertex and fragment shaders.");
}
function Bh(r, e) {
if (ke(r, () => r.validateProgram(e)), r.getProgramParameter(e, r.VALIDATE_STATUS) === false)
throw console.log(r.getProgramInfoLog(e)), new Error("Shader program validation failed.");
}
function aC(r, e) {
let t = Ja(r, () => r.createBuffer(), "Unable to create WebGLBuffer");
return ke(r, () => r.bindBuffer(r.ARRAY_BUFFER, t)), ke(r, () => r.bufferData(r.ARRAY_BUFFER, e, r.STATIC_DRAW)), t;
}
function lC(r, e) {
let t = Ja(r, () => r.createBuffer(), "Unable to create WebGLBuffer");
return ke(r, () => r.bindBuffer(r.ELEMENT_ARRAY_BUFFER, t)), ke(r, () => r.bufferData(r.ELEMENT_ARRAY_BUFFER, e, r.STATIC_DRAW)), t;
}
function AZ() {
return U().getNumber("WEBGL_VERSION") === 2 ? 1 : 4;
}
function uC(r) {
return Ja(r, () => r.createTexture(), "Unable to create WebGLTexture.");
}
function cC(r, e) {
let t = U().getNumber("WEBGL_MAX_TEXTURE_SIZE");
if (r <= 0 || e <= 0) {
let n = `[${r}x${e}]`;
throw new Error("Requested texture size " + n + " is invalid.");
}
if (r > t || e > t) {
let n = `[${r}x${e}]`, o = `[${t}x${t}]`;
throw new Error("Requested texture size " + n + " greater than WebGL maximum on this browser / GPU " + o + ".");
}
}
function pC(r) {
return Ja(r, () => r.createFramebuffer(), "Unable to create WebGLFramebuffer.");
}
function Py(r, e, t, n, o, s, a) {
let i = r.getAttribLocation(e, t);
return i === -1 ? false : (ke(r, () => r.bindBuffer(r.ARRAY_BUFFER, n)), ke(r, () => r.vertexAttribPointer(i, o, r.FLOAT, false, s, a)), ke(r, () => r.enableVertexAttribArray(i)), true);
}
function PO(r, e, t) {
LO(r, t), ke(r, () => r.activeTexture(r.TEXTURE0 + t)), ke(r, () => r.bindTexture(r.TEXTURE_2D, e));
}
function DZ(r, e) {
LO(r, e), ke(r, () => r.activeTexture(r.TEXTURE0 + e)), ke(r, () => r.bindTexture(r.TEXTURE_2D, null));
}
function mC(r, e, t) {
return Ja(r, () => r.getUniformLocation(e, t), 'uniform "' + t + '" not present in program.');
}
function fC(r, e, t) {
return r.getUniformLocation(e, t);
}
function dC(r, e, t, n) {
ke(r, () => PO(r, e, n)), ke(r, () => r.uniform1i(t, n));
}
function $Z(r) {
ke(r, () => r.bindFramebuffer(r.FRAMEBUFFER, null)), ke(r, () => r.viewport(0, 0, r.canvas.width, r.canvas.height)), ke(r, () => r.scissor(0, 0, r.canvas.width, r.canvas.height));
}
function Vh(r, e, t) {
ke(r, () => r.bindFramebuffer(r.FRAMEBUFFER, t)), ke(r, () => r.framebufferTexture2D(r.FRAMEBUFFER, r.COLOR_ATTACHMENT0, r.TEXTURE_2D, e, 0));
}
function My(r, e) {
ke(r, () => r.bindFramebuffer(r.FRAMEBUFFER, e)), ke(r, () => r.framebufferTexture2D(r.FRAMEBUFFER, r.COLOR_ATTACHMENT0, r.TEXTURE_2D, null, 0));
}
function Em(r) {
let e = r.checkFramebufferStatus(r.FRAMEBUFFER);
if (e !== r.FRAMEBUFFER_COMPLETE)
throw new Error("Error binding framebuffer: " + MO(r, e));
}
function MO(r, e) {
switch (e) {
case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
return "FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
return "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
return "FRAMEBUFFER_INCOMPLETE_DIMENSIONS";
case r.FRAMEBUFFER_UNSUPPORTED:
return "FRAMEBUFFER_UNSUPPORTED";
default:
return `unknown error ${e}`;
}
}
function Ja(r, e, t) {
let n = ke(r, () => e());
if (n == null)
throw new Error(t);
return n;
}
function LO(r, e) {
let t = r.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1, n = e + r.TEXTURE0;
if (n < r.TEXTURE0 || n > t) {
let o = `[gl.TEXTURE0, gl.TEXTURE${t}]`;
throw new Error(`textureUnit must be in ${o}.`);
}
}
function Qa(r, e = 2) {
return b.sizeFromShape(r.slice(0, r.length - e));
}
function el(r) {
if (r.length === 0)
throw Error("Cannot get rows and columns of an empty shape array.");
return [r.length > 1 ? r[r.length - 2] : 1, r[r.length - 1]];
}
function Gh(r) {
let e = [1, 1, 1];
return r.length === 0 || r.length === 1 && r[0] === 1 || (e = [Qa(r), ...el(r)]), e;
}
function hC(r, e = false) {
let t = U().getNumber("WEBGL_MAX_TEXTURE_SIZE");
e && (t = t * 2, r = r.map((o, s) => s >= r.length - 2 ? b.nearestLargerEven(r[s]) : r[s]), r.length === 1 && (r = [2, r[0]])), r.length !== 2 && (r = b.squeezeShape(r).newShape);
let n = b.sizeFromShape(r);
if (r.length <= 1 && n <= t)
return [1, n];
if (r.length === 2 && r[0] <= t && r[1] <= t)
return r;
if (r.length === 3 && r[0] * r[1] <= t && r[2] <= t)
return [r[0] * r[1], r[2]];
if (r.length === 3 && r[0] <= t && r[1] * r[2] <= t)
return [r[0], r[1] * r[2]];
if (r.length === 4 && r[0] * r[1] * r[2] <= t && r[3] <= t)
return [r[0] * r[1] * r[2], r[3]];
if (r.length === 4 && r[0] <= t && r[1] * r[2] * r[3] <= t)
return [r[0], r[1] * r[2] * r[3]];
if (e) {
let o = Qa(r), s = 2, a = 2;
return r.length && ([s, a] = el(r)), n = o * (s / 2) * (a / 2), b.sizeToSquarishShape(n).map((i) => i * 2);
}
return b.sizeToSquarishShape(n);
}
function Ly(r) {
return r % 2 == 0;
}
function ql(r, e) {
if (r = r.slice(-2), e = e.slice(-2), b.arraysEqual(r, e) || !r.length || !e.length || r[0] === 0 || r[1] === 0 || e[0] === 0 || e[1] === 0)
return true;
if (r.length !== e.length) {
let t = r.slice(-1)[0], n = e.slice(-1)[0];
if (t === n || Ly(t) && Ly(n) && (r[0] === 1 || e[0] === 1))
return true;
}
return r[1] === e[1] && Ly(r[0]) && Ly(e[0]);
}
var zy;
var By;
function gC(r) {
if (zy == null) {
let e = Zn(r);
zy = e.getParameter(e.MAX_TEXTURE_SIZE);
}
return zy;
}
function RZ() {
zy = null;
}
function FZ() {
By = null;
}
function xC(r) {
if (By == null) {
let e = Zn(r);
By = e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS);
}
return Math.min(16, By);
}
function yC(r) {
if (r === 0)
return 0;
let e, t = Zn(r);
return Bn(t, "EXT_disjoint_timer_query_webgl2") && r === 2 ? e = 2 : Bn(t, "EXT_disjoint_timer_query") ? e = 1 : e = 0, e;
}
function Bn(r, e) {
return r.getExtension(e) != null;
}
function Vy(r) {
try {
if (Zn(r) != null)
return true;
} catch (e) {
return console.log("Error when getting WebGL context: ", e), false;
}
return false;
}
function bC(r) {
if (r === 0)
return false;
let e = Zn(r);
if (r === 1) {
if (!Bn(e, "OES_texture_float"))
return false;
} else if (!Bn(e, "EXT_color_buffer_float"))
return false;
return _C(e);
}
function wC(r) {
if (r === 0)
return false;
let e = Zn(r);
if (r === 1) {
if (!Bn(e, "OES_texture_float") || !Bn(e, "WEBGL_color_buffer_float"))
return false;
} else {
if (Bn(e, "EXT_color_buffer_float"))
return _C(e);
let n = "EXT_color_buffer_half_float";
if (Bn(e, n)) {
let o = e.getExtension(n);
return OZ(e, o);
}
return false;
}
return _C(e);
}
function _C(r) {
let e = zh(r), t = r.createTexture();
r.bindTexture(r.TEXTURE_2D, t);
let n = 1, o = 1;
r.texImage2D(r.TEXTURE_2D, 0, e.internalFormatFloat, n, o, 0, e.textureFormatFloat, e.textureTypeFloat, null);
let s = r.createFramebuffer();
r.bindFramebuffer(r.FRAMEBUFFER, s), r.framebufferTexture2D(r.FRAMEBUFFER, r.COLOR_ATTACHMENT0, r.TEXTURE_2D, t, 0);
let a = r.checkFramebufferStatus(r.FRAMEBUFFER) === r.FRAMEBUFFER_COMPLETE;
return r.bindTexture(r.TEXTURE_2D, null), r.bindFramebuffer(r.FRAMEBUFFER, null), r.deleteTexture(t), r.deleteFramebuffer(s), a;
}
function OZ(r, e) {
let t = zh(r, e), n = r.createTexture();
r.bindTexture(r.TEXTURE_2D, n);
let o = 1, s = 1;
r.texImage2D(r.TEXTURE_2D, 0, t.internalFormatHalfFloat, o, s, 0, t.textureFormatFloat, t.textureTypeHalfFloat, null);
let a = r.createFramebuffer();
r.bindFramebuffer(r.FRAMEBUFFER, a), r.framebufferTexture2D(r.FRAMEBUFFER, r.COLOR_ATTACHMENT0, r.TEXTURE_2D, n, 0);
let i = r.checkFramebufferStatus(r.FRAMEBUFFER) === r.FRAMEBUFFER_COMPLETE;
return r.bindTexture(r.TEXTURE_2D, null), r.bindFramebuffer(r.FRAMEBUFFER, null), r.deleteTexture(n), r.deleteFramebuffer(a), i;
}
function kC(r) {
return r !== 2 ? false : Zn(r).fenceSync != null;
}
function qs(r, e) {
Array.isArray(r) || (r = [r]), r.forEach((t) => {
t != null && b.assert(t.dtype !== "complex64", () => `${e} does not support complex64 tensors in the WebGL backend.`);
});
}
var Pe = U();
Pe.registerFlag("HAS_WEBGL", () => Pe.getNumber("WEBGL_VERSION") > 0);
Pe.registerFlag("WEBGL_VERSION", () => Vy(2) ? 2 : Vy(1) ? 1 : 0);
Pe.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS", () => false);
Pe.registerFlag("WEBGL_BUFFER_SUPPORTED", () => Pe.get("WEBGL_VERSION") === 2);
Pe.registerFlag("WEBGL_CPU_FORWARD", () => true);
Pe.registerFlag("WEBGL_FORCE_F16_TEXTURES", () => false);
Pe.registerFlag("WEBGL_PACK", () => Pe.getBool("HAS_WEBGL"));
Pe.registerFlag("WEBGL_PACK_NORMALIZATION", () => Pe.getBool("WEBGL_PACK"));
Pe.registerFlag("WEBGL_PACK_CLIP", () => Pe.getBool("WEBGL_PACK"));
Pe.registerFlag("WEBGL_PACK_DEPTHWISECONV", () => Pe.getBool("WEBGL_PACK"));
Pe.registerFlag("WEBGL_PACK_BINARY_OPERATIONS", () => Pe.getBool("WEBGL_PACK"));
Pe.registerFlag("WEBGL_PACK_UNARY_OPERATIONS", () => Pe.getBool("WEBGL_PACK"));
Pe.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS", () => Pe.getBool("WEBGL_PACK"));
Pe.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS", () => Pe.getBool("WEBGL_PACK"));
Pe.registerFlag("WEBGL_PACK_REDUCE", () => Pe.getBool("WEBGL_PACK"));
Pe.registerFlag("WEBGL_LAZILY_UNPACK", () => Pe.getBool("WEBGL_PACK"));
Pe.registerFlag("WEBGL_CONV_IM2COL", () => Pe.getBool("WEBGL_PACK"));
Pe.registerFlag("WEBGL_MAX_TEXTURE_SIZE", () => gC(Pe.getNumber("WEBGL_VERSION")));
Pe.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER", () => xC(Pe.getNumber("WEBGL_VERSION")));
Pe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION", () => {
let r = Pe.getNumber("WEBGL_VERSION");
return r === 0 ? 0 : yC(r);
});
Pe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE", () => Pe.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") > 0 && !xu.isMobile());
Pe.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE", () => bC(Pe.getNumber("WEBGL_VERSION")));
Pe.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED", () => Pe.getBool("WEBGL_FORCE_F16_TEXTURES") ? false : Pe.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));
Pe.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED", () => wC(Pe.getNumber("WEBGL_VERSION")));
Pe.registerFlag("WEBGL_FENCE_API_ENABLED", () => kC(Pe.getNumber("WEBGL_VERSION")));
Pe.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM", () => Pe.getBool("WEBGL_RENDER_FLOAT32_ENABLED") ? 4 : 0);
Pe.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD", () => -1, (r) => {
if (r < 0 && r !== -1)
throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${r}.`);
});
Pe.registerFlag("WEBGL_FLUSH_THRESHOLD", () => xu.isMobile() ? 1 : -1, (r) => {
if (r < 0 && r !== -1)
throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${r}.`);
});
Pe.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD", () => 128);
Pe.registerFlag("WEBGL_USE_SHAPES_UNIFORMS", () => false);
Pe.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD", () => 1e5);
Pe.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD", () => 128);
function Gt() {
let r, e, t, n, o, s, a, i, l, u;
return U().getNumber("WEBGL_VERSION") === 2 ? (r = "#version 300 es", e = "in", t = "out", n = "in", o = "texture", s = "outputColor", a = "out vec4 outputColor;", i = `
bool isnan_custom(float val) {
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
}
#define isnan(value) isnan_custom(value)
`, l = "", u = `
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`) : (r = "", e = "attribute", t = "varying", n = "varying", o = "texture2D", s = "gl_FragColor", a = "", i = `
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
}
`, l = `
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`, u = `
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`), { version: r, attribute: e, varyingVs: t, varyingFs: n, texture2D: o, output: s, defineOutput: a, defineSpecialNaN: i, defineSpecialInf: l, defineRound: u };
}
function Ks(r, e, t = "index") {
let n = b.computeStrides(e);
return n.map((o, s) => {
let a = `int ${r[s]} = ${t} / ${o}`, i = s === n.length - 1 ? `int ${r[s + 1]} = ${t} - ${r[s]} * ${o}` : `index -= ${r[s]} * ${o}`;
return `${a}; ${i};`;
}).join("");
}
function yc(r, e, t = "index") {
let n = b.computeStrides(e);
return n.map((o, s) => {
let a = `int ${r[s]} = ${t} / outShapeStrides[${s}]`, i = s === n.length - 1 ? `int ${r[s + 1]} = ${t} - ${r[s]} * outShapeStrides[${s}]` : `index -= ${r[s]} * outShapeStrides[${s}]`;
return `${a}; ${i};`;
}).join("");
}
function PZ(r, e) {
let t = r.length, n = r.map((s) => `${e}[${s}]`), o = new Array(t - 1);
o[t - 2] = n[t - 1];
for (let s = t - 3; s >= 0; --s)
o[s] = `(${o[s + 1]} * ${n[s + 1]})`;
return o;
}
function BO(r, e, t = "index") {
let n = r.map((s, a) => a), o = PZ(n, e);
return o.map((s, a) => {
let i = `int ${r[a]} = ${t} / ${o[a]}`, l = a === o.length - 1 ? `int ${r[a + 1]} = ${t} - ${r[a]} * ${o[a]}` : `index -= ${r[a]} * ${o[a]}`;
return `${i}; ${l};`;
}).join("");
}
function Am(r) {
let e = b.computeStrides(r).map((t) => t.toString());
return `
int getFlatIndex(ivec3 coords) {
return coords.x * ${e[0]} + coords.y * ${e[1]} + coords.z;
}
`;
}
function Dm() {
return `
int getFlatIndex(ivec3 coords) {
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
}
`;
}
var Gy = `
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
lowp vec4 encode_float(highp float v) {
if (isnan(v)) {
return vec4(255, 255, 255, 255);
}
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
}
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
`;
var { getBroadcastDims: VO } = I;
function GO(r, e, t) {
let n = [];
if (r.forEach((f) => {
let d = b.sizeFromShape(f.shapeInfo.logicalShape);
if (f.shapeInfo.isUniform ? n.push(`uniform float ${f.name}${d > 1 ? `[${d}]` : ""};`) : (n.push(`uniform sampler2D ${f.name};`), n.push(`uniform int offset${f.name};`)), t.enableShapeUniforms) {
let { uniformShape: h } = Wy(t.packedInputs, f.shapeInfo.logicalShape, f.shapeInfo.texShape);
switch (h.length) {
case 1:
n.push(`uniform int ${f.name}Shape;`);
break;
case 2:
n.push(`uniform ivec2 ${f.name}Shape;`);
break;
case 3:
n.push(`uniform ivec3 ${f.name}Shape;`);
break;
case 4:
n.push(`uniform ivec4 ${f.name}Shape;`);
break;
default:
break;
}
n.push(`uniform ivec2 ${f.name}TexShape;`);
}
}), t.enableShapeUniforms) {
switch (e.logicalShape.length) {
case 1:
n.push("uniform int outShape;");
break;
case 2:
n.push("uniform ivec2 outShape;"), n.push("uniform int outShapeStrides;");
break;
case 3:
n.push("uniform ivec3 outShape;"), n.push("uniform ivec2 outShapeStrides;");
break;
case 4:
n.push("uniform ivec4 outShape;"), n.push("uniform ivec3 outShapeStrides;");
break;
default:
break;
}
n.push("uniform ivec2 outTexShape;");
}
t.customUniforms && t.customUniforms.forEach((f) => {
n.push(`uniform ${f.type} ${f.name}${f.arrayIndex ? `[${f.arrayIndex}]` : ""};`);
});
let o = n.join(`
`), s = r.map((f) => MZ(f, e, t.packedInputs, t.enableShapeUniforms)).join(`
`), a = e.texShape, i = Gt(), l = BZ(i), u, c, p = WZ(i);
return e.isPacked ? (u = LZ(e.logicalShape, a, t.enableShapeUniforms), c = GZ(i)) : (u = zZ(e.logicalShape, a, t.enableShapeUniforms), c = VZ(i)), t.packedInputs && (p += qZ), [p, l, c, o, u, s, t.userCode].join(`
`);
}
function $m(r, e = false) {
let t = r.shapeInfo.logicalShape;
switch (t.length) {
case 0:
return sJ(r, e);
case 1:
return aJ(r, e);
case 2:
return uJ(r, e);
case 3:
return pJ(r, e);
case 4:
return fJ(r, e);
case 5:
return dJ(r);
case 6:
return hJ(r);
default:
throw new Error(`${t.length}-D input sampling is not yet supported`);
}
}
function WO(r, e) {
switch (r.shapeInfo.logicalShape.length) {
case 0:
return oJ(r);
case 1:
return iJ(r, e);
case 2:
return lJ(r, e);
case 3:
return cJ(r, e);
default:
return mJ(r, e);
}
}
function MZ(r, e, t = false, n) {
let o = "";
t ? o += WO(r, n) : o += $m(r, n);
let s = r.shapeInfo.logicalShape, a = e.logicalShape;
return s.length <= a.length && (t ? o += gJ(r, e) : o += xJ(r, e)), o;
}
function LZ(r, e, t) {
switch (r.length) {
case 0:
return UO();
case 1:
return KZ(r, e, t);
case 2:
return rJ(r, e, t);
case 3:
return YZ(r, e, t);
default:
return JZ(r, e, t);
}
}
function zZ(r, e, t) {
switch (r.length) {
case 0:
return UO();
case 1:
return XZ(r, e, t);
case 2:
return nJ(r, e, t);
case 3:
return ZZ(r, e, t);
case 4:
return QZ(r, e, t);
case 5:
return eJ(r, e);
case 6:
return tJ(r, e);
default:
throw new Error(`${r.length}-D output sampling is not yet supported`);
}
}
function BZ(r) {
return `
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${r.texture2D}(textureSampler, uv).r;
}
`;
}
function VZ(r) {
return `
void setOutput(float val) {
${r.output} = vec4(val, 0, 0, 0);
}
`;
}
function GZ(r) {
return `
void setOutput(vec4 val) {
${r.output} = val;
}
`;
}
function WZ(r) {
return `${r.version}
precision highp float;
precision highp int;
precision highp sampler2D;
${r.varyingFs} vec2 resultUV;
${r.defineOutput}
const vec2 halfCR = vec2(0.5, 0.5);
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
uniform float NAN;
${r.defineSpecialNaN}
${r.defineSpecialInf}
${r.defineRound}
int imod(int x, int y) {
return x - y * (x / y);
}
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
}
return res;
}
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
}
${UZ}
${jZ}
${HZ}
`;
}
var UZ = `
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`;
var jZ = `
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
int texNumC, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`;
var HZ = `
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`;
var qZ = `
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
`;
function UO() {
return `
int getOutputCoords() {
return 0;
}
`;
}
function KZ(r, e, t) {
let n = [Math.ceil(e[0] / 2), Math.ceil(e[1] / 2)];
return n[0] === 1 ? t ? `
int getOutputCoords() {
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
}
` : `
int getOutputCoords() {
return 2 * int(resultUV.x * ${n[1]}.0);
}
` : n[1] === 1 ? t ? `
int getOutputCoords() {
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
}
` : `
int getOutputCoords() {
return 2 * int(resultUV.y * ${n[0]}.0);
}
` : t ? `
int getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
}
` : `
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
return 2 * (resTexRC.x * ${n[1]} + resTexRC.y);
}
`;
}
function XZ(r, e, t) {
return e[0] === 1 ? t ? `
int getOutputCoords() {
return int(resultUV.x * float(outTexShape[1]));
}
` : `
int getOutputCoords() {
return int(resultUV.x * ${e[1]}.0);
}
` : e[1] === 1 ? t ? `
int getOutputCoords() {
return int(resultUV.y * float(outTexShape[0]));
}
` : `
int getOutputCoords() {
return int(resultUV.y * ${e[0]}.0);
}
` : t ? `
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
return resTexRC.x * outTexShape[1] + resTexRC.y;
}
` : `
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
return resTexRC.x * ${e[1]} + resTexRC.y;
}
`;
}
function YZ(r, e, t) {
if (t)
return `
ivec3 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec3(b, r, c);
}
`;
let n = [Math.ceil(e[0] / 2), Math.ceil(e[1] / 2)], o = Math.ceil(r[2] / 2), s = o * Math.ceil(r[1] / 2);
return `
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int b = index / ${s};
index -= b * ${s};
int r = 2 * (index / ${o});
int c = imod(index, ${o}) * 2;
return ivec3(b, r, c);
}
`;
}
function ZZ(r, e, t) {
if (t)
return `
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${yc(["r", "c", "d"], r)}
return ivec3(r, c, d);
}
`;
let n = Ks(["r", "c", "d"], r);
return `
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
${n}
return ivec3(r, c, d);
}
`;
}
function JZ(r, e, t) {
if (t)
return `
ivec4 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
int texelsInBatchN = texelsInBatch * outShape[1];
int b2 = index / texelsInBatchN;
index -= b2 * texelsInBatchN;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec4(b2, b, r, c);
}
`;
let n = [Math.ceil(e[0] / 2), Math.ceil(e[1] / 2)], o = Math.ceil(r[r.length - 1] / 2), s = o * Math.ceil(r[r.length - 2] / 2), a = s, i = "", l = "b, r, c";
for (let u = 2; u < r.length - 1; u++)
a *= r[r.length - u - 1], i = `
int b${u} = index / ${a};
index -= b${u} * ${a};
` + i, l = `b${u}, ` + l;
return `
ivec${r.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
${i}
int b = index / ${s};
index -= b * ${s};
int r = 2 * (index / ${o});
int c = imod(index, ${o}) * 2;
return ivec${r.length}(${l});
}
`;
}
function QZ(r, e, t) {
if (t)
return `
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${yc(["r", "c", "d", "d2"], r)}
return ivec4(r, c, d, d2);
}
`;
let n = Ks(["r", "c", "d", "d2"], r);
return `
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
${n}
return ivec4(r, c, d, d2);
}
`;
}
function eJ(r, e) {
let t = Ks(["r", "c", "d", "d2", "d3"], r);
return `
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${e[0]},
${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
${t}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
`;
}
function tJ(r, e) {
let t = Ks(["r", "c", "d", "d2", "d3", "d4"], r);
return `
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
${t}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`;
}
function rJ(r, e, t) {
let n = [Math.ceil(e[0] / 2), Math.ceil(e[1] / 2)];
if (b.arraysEqual(r, e))
return t ? `
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
}
` : `
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]}));
}
`;
let o = Math.ceil(r[1] / 2);
return t ? `
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec2(r, c);
}
` : `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int r = 2 * (index / ${o});
int c = imod(index, ${o}) * 2;
return ivec2(r, c);
}
`;
}
function nJ(r, e, t) {
return b.arraysEqual(r, e) ? t ? `
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
}
` : `
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${e[0]}, ${e[1]}));
}
` : r[1] === 1 ? t ? `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(index, 0);
}
` : `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
return ivec2(index, 0);
}
` : r[0] === 1 ? t ? `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(0, index);
}
` : `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
return ivec2(0, index);
}
` : t ? `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
int r = index / outShape[1];
int c = index - r * outShape[1];
return ivec2(r, c);
}
` : `
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${e[0]}, ${e[1]}));
int index = resTexRC.x * ${e[1]} + resTexRC.y;
int r = index / ${r[1]};
int c = index - r * ${r[1]};
return ivec2(r, c);
}
`;
}
function bc(r) {
return `offset${r}`;
}
function oJ(r) {
let e = r.name, t = "get" + e.charAt(0).toUpperCase() + e.slice(1), n = Gt();
return `
vec4 ${t}() {
return ${n.texture2D}(${e}, halfCR);
}
`;
}
function sJ(r, e) {
let t = r.name, n = "get" + t.charAt(0).toUpperCase() + t.slice(1);
if (r.shapeInfo.isUniform)
return `float ${n}() {return ${t};}`;
let [o, s] = r.shapeInfo.texShape;
if (o === 1 && s === 1)
return `
float ${n}() {
return sampleTexture(${t}, halfCR);
}
`;
let a = bc(t);
if (e)
return `
float ${n}() {
vec2 uv = uvFromFlat(${t}TexShape[0], ${t}TexShape[1], ${a});
return sampleTexture(${t}, uv);
}
`;
let [i, l] = r.shapeInfo.texShape;
return `
float ${n}() {
vec2 uv = uvFromFlat(${i}, ${l}, ${a});
return sampleTexture(${t}, uv);
}
`;
}
function iJ(r, e) {
let t = r.name, n = "get" + t.charAt(0).toUpperCase() + t.slice(1), o = r.shapeInfo.texShape, s = Gt();
if (e)
return `
vec4 ${n}(int index) {
ivec2 packedTexShape = ivec2(ceil(float(${t}TexShape[0]) / 2.0), ceil(float(${t}TexShape[1]) / 2.0));
vec2 uv = packedUVfrom1D(
packedTexShape[0], packedTexShape[1], index);
return ${s.texture2D}(${t}, uv);
}
`;
let a = [Math.ceil(o[0] / 2), Math.ceil(o[1] / 2)];
return `
vec4 ${n}(int index) {
vec2 uv = packedUVfrom1D(
${a[0]}, ${a[1]}, index);
return ${s.texture2D}(${t}, uv);
}
`;
}
function aJ(r, e) {
let t = r.name, n = "get" + t.charAt(0).toUpperCase() + t.slice(1);
if (r.shapeInfo.isUniform)
return `
float ${n}(int index) {
${Rm(r)}
}
`;
let o = r.shapeInfo.texShape, s = o[0], a = o[1];
if (a === 1 && s === 1)
return `
float ${n}(int index) {
return sampleTexture(${t}, halfCR);
}
`;
let i = bc(t);
return a === 1 ? e ? `
float ${n}(int index) {
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / float(${t}TexShape[0]));
return sampleTexture(${t}, uv);
}
` : `
float ${n}(int index) {
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${s}.0);
return sampleTexture(${t}, uv);
}
` : s === 1 ? e ? `
float ${n}(int index) {
vec2 uv = vec2((float(index + ${i}) + 0.5) / float(${t}TexShape[1]), 0.5);
return sampleTexture(${t}, uv);
}
` : `
float ${n}(int index) {
vec2 uv = vec2((float(index + ${i}) + 0.5) / ${a}.0, 0.5);
return sampleTexture(${t}, uv);
}
` : e ? `
float ${n}(int index) {
vec2 uv = uvFromFlat(${t}TexShape[0], ${t}TexShape[1], index + ${i});
return sampleTexture(${t}, uv);
}
` : `
float ${n}(int index) {
vec2 uv = uvFromFlat(${s}, ${a}, index + ${i});
return sampleTexture(${t}, uv);
}
`;
}
function lJ(r, e) {
let t = r.shapeInfo.logicalShape, n = r.name, o = "get" + n.charAt(0).toUpperCase() + n.slice(1), s = r.shapeInfo.texShape, a = s[0], i = s[1], l = Gt();
if (s != null && b.arraysEqual(t, s))
return e ? `
vec4 ${o}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
return ${l.texture2D}(${n}, uv);
}
` : `
vec4 ${o}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${a}.0);
return ${l.texture2D}(${n}, uv);
}
`;
if (e)
return `
vec4 ${o}(int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${n}Shape[1]) / 2.0));
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
return ${l.texture2D}(${n}, uv);
}
`;
let u = [Math.ceil(s[0] / 2), Math.ceil(s[1] / 2)], c = Math.ceil(t[1] / 2);
return `
vec4 ${o}(int row, int col) {
vec2 uv = packedUVfrom2D(${c}, ${u[0]}, ${u[1]}, row, col);
return ${l.texture2D}(${n}, uv);
}
`;
}
function uJ(r, e) {
let t = r.shapeInfo.logicalShape, n = r.name, o = "get" + n.charAt(0).toUpperCase() + n.slice(1), s = r.shapeInfo.texShape;
if (s != null && b.arraysEqual(t, s)) {
if (e)
return `
float ${o}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
`;
let m = s[0], f = s[1];
return `
float ${o}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${f}.0, ${m}.0);
return sampleTexture(${n}, uv);
}
`;
}
let { newShape: a, keptDims: i } = b.squeezeShape(t), l = a;
if (l.length < t.length) {
let m = Fm(r, l), f = ["row", "col"];
return `
${$m(m, e)}
float ${o}(int row, int col) {
return ${o}(${Om(f, i)});
}
`;
}
if (r.shapeInfo.isUniform)
return `
float ${o}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
${Rm(r)}
}
`;
let u = s[0], c = s[1], p = bc(n);
return c === 1 ? e ? `
float ${o}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${n}Shape[1], 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / float(${n}TexShape[0]));
return sampleTexture(${n}, uv);
}
` : `
float ${o}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);
return sampleTexture(${n}, uv);
}
` : u === 1 ? e ? `
float ${o}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${n}Shape[1], 1, 1));
vec2 uv = vec2((index + 0.5) / float(${n}TexShape[1]), 0.5);
return sampleTexture(${n}, uv);
}
` : `
float ${o}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);
return sampleTexture(${n}, uv);
}
` : e ? `
float ${o}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${n}Shape[1] + col + ${p};
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
return sampleTexture(${n}, uv);
}
` : `
float ${o}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${t[1]} + col + ${p};
vec2 uv = uvFromFlat(${u}, ${c}, index);
return sampleTexture(${n}, uv);
}
`;
}
function cJ(r, e) {
let t = r.shapeInfo.logicalShape, n = r.name, o = "get" + n.charAt(0).toUpperCase() + n.slice(1), s = r.shapeInfo.texShape, a = [Math.ceil(s[0] / 2), Math.ceil(s[1] / 2)];
if (t[0] === 1) {
let m = t.slice(1), f = [1, 2], d = Fm(r, m), h = ["b", "row", "col"];
return `
${WO(d, e)}
vec4 ${o}(int b, int row, int col) {
return ${o}(${Om(h, f)});
}
`;
}
let i = Gt();
if (e)
return `
vec4 ${o}(int b, int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${n}Shape[2]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[1]) / 2.0));
vec2 uv = packedUVfrom3D(
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
return ${i.texture2D}(${n}, uv);
}
`;
let l = a[0], u = a[1], c = Math.ceil(t[2] / 2), p = c * Math.ceil(t[1] / 2);
return `
vec4 ${o}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${l}, ${u}, ${p}, ${c}, b, row, col);
return ${i.texture2D}(${n}, uv);
}
`;
}
function pJ(r, e) {
let t = r.shapeInfo.logicalShape, n = r.name, o = "get" + n.charAt(0).toUpperCase() + n.slice(1), s = t[1] * t[2], a = t[2], { newShape: i, keptDims: l } = b.squeezeShape(t), u = i;
if (u.length < t.length) {
let h = Fm(r, u), g = ["row", "col", "depth"];
return `
${$m(h, e)}
float ${o}(int row, int col, int depth) {
return ${o}(${Om(g, l)});
}
`;
}
if (r.shapeInfo.isUniform)
return `
float ${o}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${s}, ${a}, 1)));
${Rm(r)}
}
`;
let c = r.shapeInfo.texShape, p = c[0], m = c[1], f = r.shapeInfo.flatOffset;
if (m === s && f == null)
return e ? `
float ${o}(int row, int col, int depth) {
int stride1 = ${n}Shape[2];
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(stride1, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
` : `
float ${o}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${a}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${m}.0, ${p}.0);
return sampleTexture(${n}, uv);
}
`;
if (m === a && f == null)
return e ? `
float ${o}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${n}Shape[1], 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
` : `
float ${o}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${t[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${m}.0, ${p}.0);
return sampleTexture(${n}, uv);
}
`;
let d = bc(n);
return e ? `
float ${o}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int stride0 = ${n}Shape[1] * ${n}Shape[2];
int stride1 = ${n}Shape[2];
int index = row * ${s} + col * ${a} + depth + ${d};
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
return sampleTexture(${n}, uv);
}
` : `
float ${o}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${s} + col * ${a} + depth + ${d};
vec2 uv = uvFromFlat(${p}, ${m}, index);
return sampleTexture(${n}, uv);
}
`;
}
function mJ(r, e) {
let t = r.name, n = "get" + t.charAt(0).toUpperCase() + t.slice(1), o = Gt();
if (e)
return `
vec4 ${n}(int b2, int b, int row, int col) {
int valuesPerRow = int(ceil(float(${t}Shape[3]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${t}Shape[2]) / 2.0));
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
texelsInBatch *= ${t}Shape[1];
index = b2 * texelsInBatch + index;
ivec2 packedTexShape = ivec2(ceil(float(${t}TexShape[0]) / 2.0), ceil(float(${t}TexShape[1]) / 2.0));
int texR = index / packedTexShape[1];
int texC = index - texR * packedTexShape[1];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${o.texture2D}(${t}, uv);
}
`;
let s = r.shapeInfo.logicalShape, a = s.length, i = r.shapeInfo.texShape, l = [Math.ceil(i[0] / 2), Math.ceil(i[1] / 2)], u = l[0], c = l[1], p = Math.ceil(s[a - 1] / 2), m = p * Math.ceil(s[a - 2] / 2), f = "int b, int row, int col", d = `b * ${m} + (row / 2) * ${p} + (col / 2)`;
for (let h = 2; h < a - 1; h++)
f = `int b${h}, ` + f, m *= s[a - h - 1], d = `b${h} * ${m} + ` + d;
return `
vec4 ${n}(${f}) {
int index = ${d};
int texR = index / ${c};
int texC = index - texR * ${c};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${u});
return ${o.texture2D}(${t}, uv);
}
`;
}
function fJ(r, e) {
let t = r.shapeInfo.logicalShape, n = r.name, o = "get" + n.charAt(0).toUpperCase() + n.slice(1), s = t[3], a = t[2] * s, i = t[1] * a, { newShape: l, keptDims: u } = b.squeezeShape(t);
if (l.length < t.length) {
let y = Fm(r, l), w = ["row", "col", "depth", "depth2"];
return `
${$m(y, e)}
float ${o}(int row, int col, int depth, int depth2) {
return ${o}(${Om(w, u)});
}
`;
}
if (r.shapeInfo.isUniform)
return `
float ${o}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${i}, ${a}, ${s}, 1)));
${Rm(r)}
}
`;
let c = r.shapeInfo.flatOffset, p = r.shapeInfo.texShape, m = p[0], f = p[1], d = `int stride2 = ${n}Shape[3];`, h = `int stride1 = ${n}Shape[2] * stride2;`, g = `int stride0 = ${n}Shape[1] * stride1;`;
if (f === i && c == null)
return e ? `
float ${o}(int row, int col, int depth, int depth2) {
${d}
${h}
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(stride1, stride2, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
` : `
float ${o}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${a}, ${s}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${m}.0);
return sampleTexture(${n}, uv);
}
`;
if (f === s && c == null)
return e ? `
float ${o}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${n}Shape[1] * ${n}Shape[2], ${n}Shape[2], 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
` : `
float ${o}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${t[1] * t[2]}, ${t[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${m}.0);
return sampleTexture(${n}, uv);
}
`;
let x = bc(n);
return e ? `
float ${o}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
${d}
${h}
${g}
int index = row * stride0 + col * stride1 +
depth * stride2 + depth2;
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${x});
return sampleTexture(${n}, uv);
}
` : `
float ${o}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${a} +
depth * ${s} + depth2;
vec2 uv = uvFromFlat(${m}, ${f}, index + ${x});
return sampleTexture(${n}, uv);
}
`;
}
function dJ(r) {
let e = r.shapeInfo.logicalShape, t = r.name, n = "get" + t.charAt(0).toUpperCase() + t.slice(1), o = e[4], s = e[3] * o, a = e[2] * s, i = e[1] * a, { newShape: l, keptDims: u } = b.squeezeShape(e);
if (l.length < e.length) {
let h = Fm(r, l), g = ["row", "col", "depth", "depth2", "depth3"];
return `
${$m(h)}
float ${n}(int row, int col, int depth, int depth2, int depth3) {
return ${n}(${Om(g, u)});
}
`;
}
if (r.shapeInfo.isUniform)
return `
float ${n}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${i}, ${a}, ${s}, ${o})) +
depth3;
${Rm(r)}
}
`;
let c = r.shapeInfo.flatOffset, p = r.shapeInfo.texShape, m = p[0], f = p[1];
if (f === i && c == null)
return `
float ${n}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${a}, ${s}, ${o}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${m}.0);
return sampleTexture(${t}, uv);
}
`;
if (f === o && c == null)
return `
float ${n}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${e[1] * e[2] * e[3]},
${e[2] * e[3]}, ${e[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${m}.0);
return sampleTexture(${t}, uv);
}
`;
let d = bc(t);
return `
float ${n}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${a} + depth * ${s} +
depth2 * ${o} + depth3 + ${d};
vec2 uv = uvFromFlat(${m}, ${f}, index);
return sampleTexture(${t}, uv);
}
`;
}
function hJ(r) {
let e = r.shapeInfo.logicalShape, t = r.name, n = "get" + t.charAt(0).toUpperCase() + t.slice(1), { newShape: o, keptDims: s } = b.squeezeShape(e);
if (o.length < e.length) {
let g = Fm(r, o), x = ["row", "col", "depth", "depth2", "depth3", "depth4"];
return `
${$m(g)}
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${n}(${Om(x, s)});
}
`;
}
let a = e[5], i = e[4] * a, l = e[3] * i, u = e[2] * l, c = e[1] * u;
if (r.shapeInfo.isUniform)
return `
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${c}, ${u}, ${l}, ${i})) +
dot(
vec2(depth3, depth4),
vec2(${a}, 1)));
${Rm(r)}
}
`;
let p = r.shapeInfo.flatOffset, m = r.shapeInfo.texShape, f = m[0], d = m[1];
if (d === c && p == null)
return `
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${u}, ${l}, ${i}, ${a})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${d}.0, ${f}.0);
return sampleTexture(${t}, uv);
}
`;
if (d === a && p == null)
return `
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${e[1] * e[2] * e[3] * e[4]},
${e[2] * e[3] * e[4]},
${e[3] * e[4]},
${e[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${d}.0, ${f}.0);
return sampleTexture(${t}, uv);
}
`;
let h = bc(t);
return `
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${c} + col * ${u} + depth * ${l} +
depth2 * ${i} + depth3 * ${a} + depth4 + ${h};
vec2 uv = uvFromFlat(${f}, ${d}, index);
return sampleTexture(${t}, uv);
}
`;
}
function Rm(r) {
let e = r.name, t = b.sizeFromShape(r.shapeInfo.logicalShape);
return t < 2 ? `return ${e};` : `
for (int i = 0; i < ${t}; i++) {
if (i == index) {
return ${e}[i];
}
}
`;
}
function gJ(r, e) {
let t = r.name, n = t.charAt(0).toUpperCase() + t.slice(1), o = "get" + n + "AtOutCoords", s = r.shapeInfo.logicalShape.length, a = e.logicalShape.length, i = VO(r.shapeInfo.logicalShape, e.logicalShape), l = Ue(a), u = a - s, c, p = ["x", "y", "z", "w", "u", "v"];
s === 0 ? c = "" : a < 2 && i.length >= 1 ? c = "coords = 0;" : c = i.map((y) => `coords.${p[y + u]} = 0;`).join(`
`);
let m = "";
a < 2 && s > 0 ? m = "coords" : m = r.shapeInfo.logicalShape.map((y, w) => `coords.${p[w + u]}`).join(", ");
let f = "return outputValue;", h = b.sizeFromShape(r.shapeInfo.logicalShape) === 1, x = b.sizeFromShape(e.logicalShape) === 1;
if (s === 1 && !h && !x)
f = `
return vec4(outputValue.xy, outputValue.xy);
`;
else if (h && !x)
a === 1 ? f = `
return vec4(outputValue.x, outputValue.x, 0., 0.);
` : f = `
return vec4(outputValue.x);
`;
else if (i.length) {
let y = s - 2, w = s - 1;
i.indexOf(y) > -1 && i.indexOf(w) > -1 ? f = "return vec4(outputValue.x);" : i.indexOf(y) > -1 ? f = "return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);" : i.indexOf(w) > -1 && (f = "return vec4(outputValue.xx, outputValue.zz);");
}
return `
vec4 ${o}() {
${l} coords = getOutputCoords();
${c}
vec4 outputValue = get${n}(${m});
${f}
}
`;
}
function xJ(r, e) {
let t = r.name, n = t.charAt(0).toUpperCase() + t.slice(1), o = "get" + n + "AtOutCoords", s = e.texShape, a = r.shapeInfo.texShape, i = r.shapeInfo.logicalShape.length, l = e.logicalShape.length;
if (!r.shapeInfo.isUniform && i === l && r.shapeInfo.flatOffset == null && b.arraysEqual(a, s))
return `
float ${o}() {
return sampleTexture(${t}, resultUV);
}
`;
let u = Ue(l), c = VO(r.shapeInfo.logicalShape, e.logicalShape), p = l - i, m, f = ["x", "y", "z", "w", "u", "v"];
i === 0 ? m = "" : l < 2 && c.length >= 1 ? m = "coords = 0;" : m = c.map((h) => `coords.${f[h + p]} = 0;`).join(`
`);
let d = "";
return l < 2 && i > 0 ? d = "coords" : d = r.shapeInfo.logicalShape.map((h, g) => `coords.${f[g + p]}`).join(", "), `
float ${o}() {
${u} coords = getOutputCoords();
${m}
return get${n}(${d});
}
`;
}
function Ue(r) {
if (r <= 1)
return "int";
if (r === 2)
return "ivec2";
if (r === 3)
return "ivec3";
if (r === 4)
return "ivec4";
if (r === 5)
return "ivec5";
if (r === 6)
return "ivec6";
throw Error(`GPU for rank ${r} is not yet supported`);
}
function Wy(r, e, t) {
let { newShape: n, keptDims: o } = b.squeezeShape(e), s = e.length, a = r && s === 3 && e[0] === 1, i = a ? e.slice(1) : n, l = !r && s > 1 && !b.arraysEqual(e, t) && n.length < s || a;
return { useSqueezeShape: l, uniformShape: l ? i : e, keptDims: o };
}
function Fm(r, e) {
let t = JSON.parse(JSON.stringify(r));
return t.shapeInfo.logicalShape = e, t;
}
function Om(r, e) {
return e.map((t) => r[t]).join(", ");
}
function jO(r, e, t, n) {
let o = t.map((w, _) => {
let C = { logicalShape: w.shape, texShape: w.isUniform ? null : w.texData.texShape, isUniform: w.isUniform, isPacked: w.isUniform ? false : w.texData.isPacked, flatOffset: null };
return w.texData != null && w.texData.slice != null && w.texData.slice.flatOffset > 0 && (C.flatOffset = w.texData.slice.flatOffset), { name: e.variableNames[_], shapeInfo: C };
}), s = o.map((w) => w.shapeInfo), a = { logicalShape: n.shape, texShape: n.texData.texShape, isUniform: false, isPacked: n.texData.isPacked, flatOffset: null }, i = GO(o, a, e), l = r.createProgram(i), u = null, c = r.getUniformLocation(l, "NAN", false);
U().getNumber("WEBGL_VERSION") === 1 && (u = r.getUniformLocation(l, "INFINITY", false));
let p = false, m = {}, f = {}, d = {};
for (let w = 0; w < e.variableNames.length; w++) {
let _ = e.variableNames[w];
m[_] = r.getUniformLocation(l, _, p), m[`offset${_}`] = r.getUniformLocation(l, `offset${_}`, p), e.enableShapeUniforms && (f[`${_}Shape`] = r.getUniformLocation(l, `${_}Shape`, p), d[`${_}TexShape`] = r.getUniformLocation(l, `${_}TexShape`, p));
}
let h, g, x;
e.enableShapeUniforms && (h = r.getUniformLocation(l, "outShape", p), x = r.getUniformLocation(l, "outShapeStrides", p), g = r.getUniformLocation(l, "outTexShape", p));
let y = [];
return e.customUniforms && e.customUniforms.forEach((w, _) => {
y[_] = r.getUniformLocation(l, w.name, p);
}), { program: e, source: i, webGLProgram: l, uniformLocations: m, customUniformLocations: y, inShapeInfos: s, outShapeInfo: a, infLoc: u, nanLoc: c, inShapesLocations: f, inTexShapesLocations: d, outShapeLocation: h, outShapeStridesLocation: x, outTexShapeLocation: g };
}
function HO(r, e) {
if (r.length !== e.length)
throw Error(`Binary was compiled with ${r.length} inputs, but was executed with ${e.length} inputs`);
r.forEach((t, n) => {
let o = t.logicalShape, s = e[n], a = s.shape;
if (!b.arraysEqual(o, a))
throw Error(`Binary was compiled with different shapes than the current args. Shapes ${o} and ${a} must match`);
if (t.isUniform && s.isUniform)
return;
let i = t.texShape, l = s.isUniform ? null : s.texData.texShape;
if (!b.arraysEqual(i, l))
throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${l} must match`);
});
}
function qO(r, e, t, n, o) {
e.program.enableShapeUniforms || (HO(e.inShapeInfos, t), HO([e.outShapeInfo], [n]));
let s = n.texData.texture, a = n.texData.texShape;
n.texData.isPacked ? r.setOutputPackedMatrixTexture(s, a[0], a[1]) : r.setOutputMatrixTexture(s, a[0], a[1]), r.setProgram(e.webGLProgram), U().getNumber("WEBGL_VERSION") === 1 && e.infLoc !== null && r.gl.uniform1f(e.infLoc, 1 / 0), e.nanLoc !== null && r.gl.uniform1f(e.nanLoc, NaN), t.forEach((l, u) => {
let c = e.program.variableNames[u], p = e.uniformLocations[c], m = e.uniformLocations[`offset${c}`], f = e.inShapesLocations[`${c}Shape`], d = e.inTexShapesLocations[`${c}TexShape`];
if (f) {
let { uniformShape: h } = Wy(e.program.packedInputs, l.shape, l.texData.texShape);
switch (h.length) {
case 1:
r.gl.uniform1iv(f, new Int32Array(h));
break;
case 2:
r.gl.uniform2iv(f, new Int32Array(h));
break;
case 3:
r.gl.uniform3iv(f, new Int32Array(h));
break;
case 4:
r.gl.uniform4iv(f, new Int32Array(h));
break;
default:
break;
}
}
if (d && r.gl.uniform2i(d, l.texData.texShape[0], l.texData.texShape[1]), p != null) {
if (l.isUniform) {
if (b.sizeFromShape(l.shape) < 2)
r.gl.uniform1f(p, l.uniformValues[0]);
else {
let h = l.uniformValues;
h instanceof Float32Array || (h = new Float32Array(h)), r.gl.uniform1fv(p, h);
}
return;
}
l.texData.slice != null && m != null && r.gl.uniform1i(m, l.texData.slice.flatOffset), r.setInputMatrixTexture(l.texData.texture, p, u);
}
});
let i = e.outShapeLocation;
if (i)
switch (n.shape.length) {
case 1:
r.gl.uniform1iv(i, new Int32Array(n.shape));
break;
case 2:
r.gl.uniform2iv(i, new Int32Array(n.shape));
break;
case 3:
r.gl.uniform3iv(i, new Int32Array(n.shape));
break;
case 4:
r.gl.uniform4iv(i, new Int32Array(n.shape));
break;
default:
break;
}
if (e.outShapeStridesLocation) {
let l = b.computeStrides(n.shape);
switch (n.shape.length) {
case 2:
r.gl.uniform1iv(e.outShapeStridesLocation, new Int32Array(l));
break;
case 3:
r.gl.uniform2iv(e.outShapeStridesLocation, new Int32Array(l));
break;
case 4:
r.gl.uniform3iv(e.outShapeStridesLocation, new Int32Array(l));
break;
default:
break;
}
}
e.outTexShapeLocation && r.gl.uniform2i(e.outTexShapeLocation, n.texData.texShape[0], n.texData.texShape[1]), e.program.customUniforms && o && e.program.customUniforms.forEach((l, u) => {
let c = e.customUniformLocations[u], p = o[u];
if (l.type === "float")
r.gl.uniform1fv(c, p);
else if (l.type === "vec2")
r.gl.uniform2fv(c, p);
else if (l.type === "vec3")
r.gl.uniform3fv(c, p);
else if (l.type === "vec4")
r.gl.uniform4fv(c, p);
else if (l.type === "int")
r.gl.uniform1iv(c, p);
else if (l.type === "ivec2")
r.gl.uniform2iv(c, p);
else if (l.type === "ivec3")
r.gl.uniform3iv(c, p);
else if (l.type === "ivec4")
r.gl.uniform4iv(c, p);
else
throw Error(`uniform type ${l.type} is not supported yet.`);
}), r.executeProgram();
}
function KO(r, e, t) {
let n = "";
e.concat(t).forEach((a) => {
let i = a.texData != null && a.texData.slice != null && a.texData.slice.flatOffset > 0;
if (r.enableShapeUniforms && !a.isUniform) {
let l = a.texData.texShape, { useSqueezeShape: u, uniformShape: c, keptDims: p } = Wy(r.packedInputs, a.shape, l), m = "", f = "", d = "";
if (c.length === 1 && r.packedInputs) {
let C = [Math.ceil(l[0] / 2), Math.ceil(l[1] / 2)];
m = `${C[0] > 1}_${C[1] > 1}`;
} else if (c.length === 2 && !r.packedInputs)
f = `${c[0] > 1}_${c[1] > 1}`;
else if (c.length > 2 && !r.packedInputs) {
let C = b.computeStrides(c);
d = `${C[0] === l[1]}_${C[C.length - 1] === l[1]}`;
}
let h = a.shape.length, g = c.length === 2 && b.arraysEqual(a.shape, l), x = b.sizeFromShape(a.shape) === 1, y = I.getBroadcastDims(a.shape, t.shape), w = !r.packedInputs && h === t.shape.length && b.arraysEqual(l, t.texData.texShape), _ = r.packedInputs || c.length > 2 ? "" : `${l[0] > 1}_${l[1] > 1}`;
n += `${h}_${w}_${u ? p : ""}_${c.length}_${x}_${y}_${g}_${m}_${f}_${d}_${_}_${i}`;
} else {
let l = a.isUniform ? "uniform" : a.texData.texShape;
n += `${a.shape}_${l}_${i}`;
}
});
let o = r.userCode, s = r.constructor.name;
return s += "_" + n + "_" + o + `${U().getNumber("WEBGL_VERSION")}`, s;
}
function jt(r) {
return U().getBool("WEBGL_USE_SHAPES_UNIFORMS") && r <= 4;
}
var vC = class {
constructor(e) {
this.variableNames = ["A"], this.packedInputs = false, this.packedOutput = true, this.outPackingScheme = Hl.DENSE, this.customUniforms = [{ name: "texShape", type: "ivec2" }];
let t = Gt();
this.outputShape = e, this.enableShapeUniforms = jt(this.outputShape.length), this.userCode = `
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms ? yc(["r", "c", "d"], e) : Ks(["r", "c", "d"], e)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
}
${t.output} = result;
}
`;
}
};
var CC = class {
constructor(e) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.outPackingScheme = Hl.DENSE, this.customUniforms = [{ name: "texShape", type: "ivec2" }];
let t = Gt();
this.outputShape = e, this.enableShapeUniforms = jt(this.outputShape.length), this.userCode = `
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms ? yc(["r", "c", "d"], e) : Ks(["r", "c", "d"], e)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
}
${t.output} = result;
}
`;
}
};
var IC = class {
constructor(e) {
this.variableNames = ["A"], this.outTexUsage = Ur.DOWNLOAD;
let t = Gt();
this.outputShape = e, this.userCode = `
${Gy}
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
`;
}
};
var SC = class {
constructor(e) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = false, this.outTexUsage = Ur.DOWNLOAD;
let t = Gt();
this.outputShape = e, this.userCode = `
${Gy}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
`;
}
};
var NC = class {
constructor(e, t = false) {
this.variableNames = ["A"], this.customUniforms = [{ name: "texShape", type: "ivec2" }];
let n = Gt();
this.outputShape = e, this.enableShapeUniforms = jt(this.outputShape.length);
let o = "result";
t && (o = "floor(result * 255. + 0.5)"), this.userCode = `
${this.enableShapeUniforms ? Dm() : Am(e)}
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / texShape[1];
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
vec4 values = ${n.texture2D}(A, uv);
float result;
if(offset == 0) {
result = values[0];
} else if(offset == 1) {
result = values[1];
} else if(offset == 2) {
result = values[2];
} else {
result = values[3];
}
${n.output} = vec4(${o}, 0., 0., 0.);
}
`;
}
};
var TC = class {
constructor(e, t = false) {
this.variableNames = ["A"], this.packedInputs = false, this.packedOutput = true, this.customUniforms = [{ name: "texShape", type: "ivec2" }];
let n = Gt();
this.outputShape = e, this.enableShapeUniforms = jt(this.outputShape.length);
let o = "", s = "result";
t && (s = "floor(result * 255. + 0.5)");
for (let a = 0; a <= 1; a++)
for (let i = 0; i <= 1; i++) {
let l = a * 2 + i;
o += `
localCoords = coords;
if(localCoords[2] + ${i} < ${this.enableShapeUniforms ? "outShape[2]" : `${e[2]}`}) {
localCoords[2] += ${i};
if (localCoords[1] + ${a} < ${this.enableShapeUniforms ? "outShape[1]" : `${e[1]}`}) {
localCoords[1] += ${a};
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / texShape[1];
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
values = ${n.texture2D}(A, uv);
if (offset == 0) {
result[${l}] = values[0];
} else if (offset == 1) {
result[${l}] = values[1];
} else if (offset == 2) {
result[${l}] = values[2];
} else {
result[${l}] = values[3];
}
}
}
`;
}
this.userCode = `
${this.enableShapeUniforms ? Dm() : Am(e)}
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${o}
${n.output} = ${s};
}
`;
}
};
var XO = {};
qe(XO, { bindVertexProgramAttributeStreams: () => MC, createBufferFromOutputTexture: () => BC, createFloat16MatrixTexture: () => RC, createFloat16PackedMatrixTexture: () => PC, createFloat32MatrixTexture: () => $C, createIndexBuffer: () => DC, createPackedMatrixTexture: () => OC, createUnsignedBytesMatrixTexture: () => FC, createVertexBuffer: () => AC, createVertexShader: () => EC, downloadByteEncodedFloatMatrixFromOutputTexture: () => GC, downloadFloat32MatrixFromBuffer: () => VC, downloadMatrixFromPackedOutputTexture: () => UC, downloadPackedMatrixFromBuffer: () => WC, getInternalFormatForFloat16MatrixTexture: () => jy, getInternalFormatForFloat16PackedMatrixTexture: () => Ky, getInternalFormatForFloat32MatrixTexture: () => Uy, getInternalFormatForPackedMatrixTexture: () => qy, getInternalFormatForUnsignedBytesMatrixTexture: () => Hy, uploadDenseMatrixToTexture: () => LC, uploadPixelDataToTexture: () => zC });
function EC(r) {
let e = Gt(), t = `${e.version}
precision highp float;
${e.attribute} vec3 clipSpacePos;
${e.attribute} vec2 uv;
${e.varyingVs} vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
}`;
return nC(r, t);
}
function AC(r) {
let e = new Float32Array([-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]);
return aC(r, e);
}
function DC(r) {
let e = new Uint16Array([0, 1, 2, 2, 1, 3]);
return lC(r, e);
}
function Wh(r, e, t, n, o, s) {
cC(e, t);
let a = uC(r), i = r.TEXTURE_2D;
return ke(r, () => r.bindTexture(i, a)), ke(r, () => r.texParameteri(i, r.TEXTURE_WRAP_S, r.CLAMP_TO_EDGE)), ke(r, () => r.texParameteri(i, r.TEXTURE_WRAP_T, r.CLAMP_TO_EDGE)), ke(r, () => r.texParameteri(i, r.TEXTURE_MIN_FILTER, r.NEAREST)), ke(r, () => r.texParameteri(i, r.TEXTURE_MAG_FILTER, r.NEAREST)), ke(r, () => r.texImage2D(i, 0, n, e, t, 0, o, s, null)), ke(r, () => r.bindTexture(r.TEXTURE_2D, null)), a;
}
function Uy(r) {
return r.internalFormatFloat;
}
function $C(r, e, t, n) {
let [o, s] = xc(e, t);
return Wh(r, o, s, Uy(n), n.textureFormatFloat, r.FLOAT);
}
function jy(r) {
return r.internalFormatHalfFloat;
}
function RC(r, e, t, n) {
let [o, s] = xc(e, t);
return Wh(r, o, s, jy(n), n.textureFormatFloat, n.textureTypeHalfFloat);
}
function Hy(r) {
return r.downloadTextureFormat;
}
function FC(r, e, t, n) {
let [o, s] = xc(e, t);
return Wh(r, o, s, Hy(n), r.RGBA, r.UNSIGNED_BYTE);
}
function qy(r) {
return r.internalFormatPackedFloat;
}
function OC(r, e, t, n) {
let [o, s] = Ai(e, t);
return Wh(r, o, s, qy(n), r.RGBA, r.FLOAT);
}
function Ky(r) {
return r.internalFormatPackedHalfFloat;
}
function PC(r, e, t, n) {
let [o, s] = Ai(e, t);
return Wh(r, o, s, Ky(n), r.RGBA, n.textureTypeHalfFloat);
}
function MC(r, e, t) {
let n = 0, o = 3 * 4, s = 3 * 4 + 2 * 4;
return ke(r, () => r.bindBuffer(r.ARRAY_BUFFER, t)), Py(r, e, "clipSpacePos", t, 3, s, n) && Py(r, e, "uv", t, 2, s, o);
}
function LC(r, e, t, n, o, s) {
ke(r, () => r.bindTexture(r.TEXTURE_2D, e));
let a, i, l;
o instanceof Uint8Array ? (a = new Uint8Array(t * n * 4), i = r.UNSIGNED_BYTE, l = r.RGBA) : (a = new Float32Array(t * n * 4), i = r.FLOAT, l = s.internalFormatPackedFloat), a.set(o), ke(r, () => r.texImage2D(r.TEXTURE_2D, 0, l, t, n, 0, r.RGBA, i, a)), ke(r, () => r.bindTexture(r.TEXTURE_2D, null));
}
function zC(r, e, t) {
ke(r, () => r.bindTexture(r.TEXTURE_2D, e)), t.data instanceof Uint8Array ? ke(r, () => r.texImage2D(r.TEXTURE_2D, 0, r.RGBA, t.width, t.height, 0, r.RGBA, r.UNSIGNED_BYTE, t.data)) : ke(r, () => r.texImage2D(r.TEXTURE_2D, 0, r.RGBA, r.RGBA, r.UNSIGNED_BYTE, t)), ke(r, () => r.bindTexture(r.TEXTURE_2D, null));
}
function BC(r, e, t, n) {
let o = r.createBuffer();
ke(r, () => r.bindBuffer(r.PIXEL_PACK_BUFFER, o));
let i = 4 * 4 * e * t;
return ke(r, () => r.bufferData(r.PIXEL_PACK_BUFFER, i, r.STREAM_READ)), ke(r, () => r.readPixels(0, 0, t, e, r.RGBA, r.FLOAT, 0)), ke(r, () => r.bindBuffer(r.PIXEL_PACK_BUFFER, null)), o;
}
function VC(r, e, t) {
let n = r, o = new Float32Array(t);
return n.bindBuffer(n.PIXEL_PACK_BUFFER, e), n.getBufferSubData(n.PIXEL_PACK_BUFFER, 0, o), n.bindBuffer(n.PIXEL_PACK_BUFFER, null), o;
}
function GC(r, e, t, n) {
let [o, s] = xc(e, t), a = 4, i = new Uint8Array(RO(e * t, a));
return ke(r, () => r.readPixels(0, 0, o, s, n.downloadTextureFormat, r.UNSIGNED_BYTE, i)), new Float32Array(i.buffer);
}
function WC(r, e, t, n, o, s, a, i) {
let l = r, u = new Float32Array(FO(s, a));
return l.bindBuffer(l.PIXEL_PACK_BUFFER, e), l.getBufferSubData(l.PIXEL_PACK_BUFFER, 0, u), l.bindBuffer(l.PIXEL_PACK_BUFFER, null), u;
}
function UC(r, e, t) {
let n = new Float32Array(e * t * 4);
return ke(r, () => r.readPixels(0, 0, t, e, r.RGBA, r.FLOAT, n)), n;
}
var Xy = class {
constructor(e) {
this.outputTexture = null, this.program = null, this.disposed = false, this.vertexAttrsAreBound = false, this.itemsToPoll = [];
let t = U().getNumber("WEBGL_VERSION");
e != null ? (this.gl = e, tC(t, e)) : this.gl = Zn(t);
let n = "WEBGL_color_buffer_float", o = "EXT_color_buffer_half_float";
if (U().getNumber("WEBGL_VERSION") === 1) {
let s = "OES_texture_float", a = "OES_texture_half_float";
if (this.textureFloatExtension = Tm(this.gl, s), Bn(this.gl, a))
this.textureHalfFloatExtension = Tm(this.gl, a);
else if (U().get("WEBGL_FORCE_F16_TEXTURES"))
throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");
if (this.colorBufferFloatExtension = this.gl.getExtension(n), Bn(this.gl, o))
this.colorBufferHalfFloatExtension = Tm(this.gl, o);
else if (U().get("WEBGL_FORCE_F16_TEXTURES"))
throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");
} else if (n = "EXT_color_buffer_float", Bn(this.gl, n))
this.colorBufferFloatExtension = this.gl.getExtension(n);
else if (Bn(this.gl, o))
this.colorBufferHalfFloatExtension = this.gl.getExtension(o);
else
throw new Error("GL context does not support color renderable floats");
this.vertexBuffer = AC(this.gl), this.indexBuffer = DC(this.gl), this.framebuffer = pC(this.gl), this.textureConfig = zh(this.gl, this.textureHalfFloatExtension);
}
get debug() {
return U().getBool("DEBUG");
}
dispose() {
if (this.disposed)
return;
this.program != null && console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."), this.outputTexture != null && console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");
let e = this.gl;
ke(e, () => e.finish()), ke(e, () => e.bindFramebuffer(e.FRAMEBUFFER, null)), ke(e, () => e.deleteFramebuffer(this.framebuffer)), ke(e, () => e.bindBuffer(e.ARRAY_BUFFER, null)), ke(e, () => e.bindBuffer(e.ELEMENT_ARRAY_BUFFER, null)), ke(e, () => e.deleteBuffer(this.indexBuffer)), this.disposed = true;
}
createFloat32MatrixTexture(e, t) {
return this.throwIfDisposed(), $C(this.gl, e, t, this.textureConfig);
}
createFloat16MatrixTexture(e, t) {
return this.throwIfDisposed(), RC(this.gl, e, t, this.textureConfig);
}
createUnsignedBytesMatrixTexture(e, t) {
return this.throwIfDisposed(), FC(this.gl, e, t, this.textureConfig);
}
uploadPixelDataToTexture(e, t) {
this.throwIfDisposed(), zC(this.gl, e, t);
}
uploadDenseMatrixToTexture(e, t, n, o) {
this.throwIfDisposed(), LC(this.gl, e, t, n, o, this.textureConfig);
}
createFloat16PackedMatrixTexture(e, t) {
return this.throwIfDisposed(), PC(this.gl, e, t, this.textureConfig);
}
createPackedMatrixTexture(e, t) {
return this.throwIfDisposed(), OC(this.gl, e, t, this.textureConfig);
}
deleteMatrixTexture(e) {
this.throwIfDisposed(), this.outputTexture === e && (My(this.gl, this.framebuffer), this.outputTexture = null), ke(this.gl, () => this.gl.deleteTexture(e));
}
downloadByteEncodedFloatMatrixFromOutputTexture(e, t, n) {
return this.downloadMatrixDriver(e, () => GC(this.gl, t, n, this.textureConfig));
}
downloadPackedMatrixFromBuffer(e, t, n, o, s, a) {
return WC(this.gl, e, t, n, o, s, a, this.textureConfig);
}
downloadFloat32MatrixFromBuffer(e, t) {
return VC(this.gl, e, t);
}
createBufferFromTexture(e, t, n) {
this.bindTextureToFrameBuffer(e);
let o = BC(this.gl, t, n, this.textureConfig);
return this.unbindTextureToFrameBuffer(), o;
}
createAndWaitForFence() {
let e = this.createFence(this.gl);
return this.pollFence(e);
}
createFence(e) {
let t, n;
if (U().getBool("WEBGL_FENCE_API_ENABLED")) {
let o = e, s = o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE, 0);
e.flush(), n = () => {
let a = o.clientWaitSync(s, 0, 0);
return a === o.ALREADY_SIGNALED || a === o.CONDITION_SATISFIED;
}, t = s;
} else
U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") > 0 ? (t = this.beginQuery(), this.endQuery(), n = () => this.isQueryAvailable(t, U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))) : n = () => true;
return { query: t, isFencePassed: n };
}
downloadMatrixFromPackedTexture(e, t, n) {
return this.downloadMatrixDriver(e, () => UC(this.gl, t, n));
}
createProgram(e) {
this.throwIfDisposed();
let t = this.gl, n = oC(t, e);
this.vertexShader == null && (this.vertexShader = EC(t));
let o = sC(t);
return ke(t, () => t.attachShader(o, this.vertexShader)), ke(t, () => t.attachShader(o, n)), iC(t, o), this.debug && Bh(t, o), this.vertexAttrsAreBound || (this.setProgram(o), this.vertexAttrsAreBound = MC(t, this.program, this.vertexBuffer)), o;
}
deleteProgram(e) {
this.throwIfDisposed(), e === this.program && (this.program = null), e != null && ke(this.gl, () => this.gl.deleteProgram(e));
}
setProgram(e) {
this.throwIfDisposed(), this.program = e, this.program != null && this.debug && Bh(this.gl, this.program), ke(this.gl, () => this.gl.useProgram(e));
}
getUniformLocation(e, t, n = true) {
return this.throwIfDisposed(), n ? mC(this.gl, e, t) : fC(this.gl, e, t);
}
getAttributeLocation(e, t) {
return this.throwIfDisposed(), ke(this.gl, () => this.gl.getAttribLocation(e, t));
}
getUniformLocationNoThrow(e, t) {
return this.throwIfDisposed(), this.gl.getUniformLocation(e, t);
}
setInputMatrixTexture(e, t, n) {
this.throwIfDisposed(), this.throwIfNoProgram(), dC(this.gl, e, t, n);
}
setOutputMatrixTexture(e, t, n) {
this.setOutputMatrixTextureDriver(e, n, t);
}
setOutputPackedMatrixTexture(e, t, n) {
this.throwIfDisposed();
let [o, s] = Ai(t, n);
this.setOutputMatrixTextureDriver(e, o, s);
}
setOutputMatrixWriteRegion(e, t, n, o) {
this.setOutputMatrixWriteRegionDriver(n, e, o, t);
}
setOutputPackedMatrixWriteRegion(e, t, n, o) {
throw new Error("setOutputPackedMatrixWriteRegion not implemented.");
}
debugValidate() {
this.program != null && Bh(this.gl, this.program), Em(this.gl);
}
executeProgram() {
this.throwIfDisposed(), this.throwIfNoProgram();
let e = this.gl;
this.debug && this.debugValidate(), ke(e, () => e.drawElements(e.TRIANGLES, 6, e.UNSIGNED_SHORT, 0));
}
blockUntilAllProgramsCompleted() {
this.throwIfDisposed(), ke(this.gl, () => this.gl.finish());
}
getQueryTimerExtension() {
return this.disjointQueryTimerExtension == null && (this.disjointQueryTimerExtension = Tm(this.gl, U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2 ? "EXT_disjoint_timer_query_webgl2" : "EXT_disjoint_timer_query")), this.disjointQueryTimerExtension;
}
getQueryTimerExtensionWebGL2() {
return this.getQueryTimerExtension();
}
getQueryTimerExtensionWebGL1() {
return this.getQueryTimerExtension();
}
beginQuery() {
if (U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2) {
let n = this.gl, o = this.getQueryTimerExtensionWebGL2(), s = n.createQuery();
return n.beginQuery(o.TIME_ELAPSED_EXT, s), s;
}
let e = this.getQueryTimerExtensionWebGL1(), t = e.createQueryEXT();
return e.beginQueryEXT(e.TIME_ELAPSED_EXT, t), t;
}
endQuery() {
if (U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2) {
let t = this.gl, n = this.getQueryTimerExtensionWebGL2();
t.endQuery(n.TIME_ELAPSED_EXT);
return;
}
let e = this.getQueryTimerExtensionWebGL1();
e.endQueryEXT(e.TIME_ELAPSED_EXT);
}
async waitForQueryAndGetTime(e) {
return await b.repeatedTry(() => this.disposed || this.isQueryAvailable(e, U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))), this.getQueryTime(e, U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"));
}
getQueryTime(e, t) {
if (t === 0)
return null;
if (t === 2) {
let n = this.gl;
return n.getQueryParameter(e, n.QUERY_RESULT) / 1e6;
} else {
let n = this.getQueryTimerExtensionWebGL1();
return n.getQueryObjectEXT(e, n.QUERY_RESULT_EXT) / 1e6;
}
}
isQueryAvailable(e, t) {
if (t === 0)
return true;
if (t === 2) {
let n = this.gl, o = this.getQueryTimerExtensionWebGL2(), s = n.getQueryParameter(e, n.QUERY_RESULT_AVAILABLE);
return this.disjoint == null && (this.disjoint = this.gl.getParameter(o.GPU_DISJOINT_EXT)), s && !this.disjoint;
} else {
let n = this.getQueryTimerExtensionWebGL1(), o = n.getQueryObjectEXT(e, n.QUERY_RESULT_AVAILABLE_EXT);
return this.disjoint == null && (this.disjoint = this.gl.getParameter(n.GPU_DISJOINT_EXT)), o && !this.disjoint;
}
}
pollFence(e) {
return new Promise((t) => {
this.addItemToPoll(() => e.isFencePassed(), () => t());
});
}
pollItems() {
let e = yJ(this.itemsToPoll.map((t) => t.isDoneFn));
for (let t = 0; t <= e; ++t) {
let { resolveFn: n } = this.itemsToPoll[t];
n();
}
this.itemsToPoll = this.itemsToPoll.slice(e + 1);
}
addItemToPoll(e, t) {
this.itemsToPoll.push({ isDoneFn: e, resolveFn: t }), !(this.itemsToPoll.length > 1) && b.repeatedTry(() => (this.pollItems(), this.itemsToPoll.length === 0));
}
bindTextureToFrameBuffer(e) {
this.throwIfDisposed(), Vh(this.gl, e, this.framebuffer), this.debug && Em(this.gl);
}
unbindTextureToFrameBuffer() {
this.outputTexture != null ? (Vh(this.gl, this.outputTexture, this.framebuffer), this.debug && Em(this.gl)) : My(this.gl, this.framebuffer);
}
downloadMatrixDriver(e, t) {
this.bindTextureToFrameBuffer(e);
let n = t();
return this.unbindTextureToFrameBuffer(), n;
}
setOutputMatrixTextureDriver(e, t, n) {
this.throwIfDisposed();
let o = this.gl;
Vh(o, e, this.framebuffer), this.debug && Em(o), this.outputTexture = e, ke(o, () => o.viewport(0, 0, t, n)), ke(o, () => o.scissor(0, 0, t, n));
}
setOutputMatrixWriteRegionDriver(e, t, n, o) {
this.throwIfDisposed(), ke(this.gl, () => this.gl.scissor(e, t, n, o));
}
throwIfDisposed() {
if (this.disposed)
throw new Error("Attempted to use disposed GPGPUContext.");
}
throwIfNoProgram() {
if (this.program == null)
throw new Error("No GPU program is currently set.");
}
};
function yJ(r) {
let e = 0;
for (; e < r.length && r[e](); ++e)
;
return e - 1;
}
var { addImpl: YO, bincountImpl: Yy, bincountReduceImpl: ZO, ceilImpl: JO, concatImpl: QO, equalImpl: eP, expImpl: tP, expm1Impl: rP, floorImpl: nP, gatherNdImpl: oP, gatherV2Impl: sP, greaterImpl: iP, greaterEqualImpl: aP, lessImpl: lP, lessEqualImpl: uP, linSpaceImpl: cP, logImpl: pP, maxImpl: mP, maximumImpl: fP, minimumImpl: dP, multiplyImpl: hP, negImpl: gP, notEqualImpl: xP, prodImpl: yP, rangeImpl: bP, rsqrtImpl: wP, sigmoidImpl: _P, simpleAbsImpl: Zy, sliceImpl: kP, sparseFillEmptyRowsImpl: vP, sparseReshapeImpl: CP, sparseSegmentReductionImpl: Jy, sqrtImpl: IP, stridedSliceImpl: SP, stringNGramsImpl: NP, stringSplitImpl: TP, stringToHashBucketFastImpl: EP, subImpl: AP, tileImpl: DP, topKImpl: $P, transposeImpl: wc, uniqueImpl: RP } = Ay;
function jC(r, e) {
return ["x", "y", "z", "w", "u", "v"].slice(0, e).map((t) => `${r}.${t}`);
}
function Jt(r, e) {
return e === 1 ? [r] : jC(r, e);
}
function FP(r, e) {
if (r === 1)
return "rc";
let t = "";
for (let n = 0; n < r; n++)
t += e[n], n < r - 1 && (t += ",");
return t;
}
var HC = class {
constructor(e) {
this.variableNames = ["A"], this.packedInputs = false, this.packedOutput = true, this.outputShape = e;
let t = e.length;
if (t === 0)
this.userCode = `
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;
else {
let n = Jt("rc", t), o = Ue(t), s = wJ(t, e, n), a = _J(t, e[e.length - 1], e[e.length - 2], n), i = kJ(e, n);
this.userCode = `
void main() {
${o} rc = getOutputCoords();
if(${s}) {
setOutput(vec4(0));
} else {
${a}
setOutput(vec4(${i}));
}
}
`;
}
}
};
function bJ(r, e) {
let t = [];
for (let n = 0; n <= 1; n++)
for (let o = 0; o <= 1; o++) {
let s = `${n === 0 ? "r" : "rp1"}, ${o === 0 ? "c" : "cp1"}`;
for (let a = 2; a < r; a++)
s = `${e[e.length - 1 - a]},` + s;
t.push(s);
}
return t;
}
function wJ(r, e, t) {
if (r === 1)
return `rc > ${e[0]}`;
let n = "";
for (let o = r - 2; o < r; o++)
n += `${t[o]} >= ${e[o]}`, o < r - 1 && (n += "||");
return n;
}
function _J(r, e, t, n) {
if (r === 1)
return "";
let o = n.slice(-2);
return `
int r = ${o[0]};
int c = ${o[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${e};
bool rEdge = rp1 >= ${t};
`;
}
function kJ(r, e) {
let t = r.length, n = bJ(t, e);
return t === 1 ? `getA(rc),
rc + 1 >= ${r[0]} ? 0. : getA(rc + 1),
0, 0` : `getA(${n[0]}),
cEdge ? 0. : getA(${n[1]}),
rEdge ? 0. : getA(${n[2]}),
rEdge || cEdge ? 0. : getA(${n[3]})`;
}
var Uh = class {
constructor(e, t) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "inputShape", type: "ivec3" }], this.outputShape = e, this.enableShapeUniforms = jt(this.outputShape.length);
let n = "";
for (let o = 0; o < 4; o++) {
let s = "thisRC = rc;";
o % 2 == 1 && (s += "thisRC.z += 1;"), o > 1 && (s += "thisRC.y += 1;"), n += `
${s}
${o > 0 ? "if(thisRC.y < rows && thisRC.z < cols){" : ""}
int flatIndex = getFlatIndex(thisRC);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
result[${o}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${o > 0 ? "}" : ""}
`;
}
this.userCode = `
${vJ(t, this.enableShapeUniforms)}
${this.enableShapeUniforms ? Dm() : Am(e)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${this.enableShapeUniforms ? "outShape[1]" : e[1]};
int cols = ${this.enableShapeUniforms ? "outShape[2]" : e[2]};
${n}
setOutput(result);
}
`;
}
};
function vJ(r, e) {
return `
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${e ? BO(["r", "c", "d"], "inputShape") : Ks(["r", "c", "d"], r)}
return ivec3(r, c, d);
}
`;
}
var qC = class {
constructor(e) {
this.gpgpu = e, this.numUsedTextures = 0, this.numFreeTextures = 0, this._numBytesAllocated = 0, this._numBytesFree = 0, this.freeTextures = {}, this.logEnabled = false, this.usedTextures = {};
}
acquireTexture(e, t, n) {
let o = PP(t, n), s = MP(e, o, n);
s in this.freeTextures || (this.freeTextures[s] = []), s in this.usedTextures || (this.usedTextures[s] = []);
let a = OP(e, o, this.gpgpu.gl, this.gpgpu.textureConfig, n);
if (this.freeTextures[s].length > 0) {
this.numFreeTextures--, this.numUsedTextures++, this._numBytesFree -= a, this.log();
let l = this.freeTextures[s].shift();
return this.usedTextures[s].push(l), l;
}
let i;
return o === Fr.PACKED_2X2_FLOAT32 ? i = this.gpgpu.createPackedMatrixTexture(e[0], e[1]) : o === Fr.PACKED_2X2_FLOAT16 ? i = this.gpgpu.createFloat16PackedMatrixTexture(e[0], e[1]) : o === Fr.UNPACKED_FLOAT32 ? i = this.gpgpu.createFloat32MatrixTexture(e[0], e[1]) : o === Fr.UNPACKED_FLOAT16 ? i = this.gpgpu.createFloat16MatrixTexture(e[0], e[1]) : o === Fr.PACKED_4X1_UNSIGNED_BYTE && (i = this.gpgpu.createUnsignedBytesMatrixTexture(e[0], e[1])), this.usedTextures[s].push(i), this.numUsedTextures++, this._numBytesAllocated += a, this.log(), i;
}
releaseTexture(e, t, n, o) {
if (this.freeTextures == null)
return;
let s = PP(n, o), a = MP(t, s, o);
a in this.freeTextures || (this.freeTextures[a] = []);
let i = OP(t, s, this.gpgpu.gl, this.gpgpu.textureConfig, o), l = U().get("WEBGL_DELETE_TEXTURE_THRESHOLD");
l !== -1 && this._numBytesAllocated > l ? (this.gpgpu.deleteMatrixTexture(e), this._numBytesAllocated -= i) : (this.freeTextures[a].push(e), this.numFreeTextures++, this._numBytesFree += i), this.numUsedTextures--;
let u = this.usedTextures[a], c = u.indexOf(e);
if (c < 0)
throw new Error("Cannot release a texture that was never provided by this texture manager");
u.splice(c, 1), this.log();
}
log() {
if (!this.logEnabled)
return;
let e = this.numFreeTextures + this.numUsedTextures;
console.log("Free/Used", `${this.numFreeTextures} / ${this.numUsedTextures}`, `(${e})`);
let t = this._numBytesFree / this._numBytesAllocated;
console.log(`Bytes allocated: ${this._numBytesAllocated}`), console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100 * t)}%)`);
}
get numBytesAllocated() {
return this._numBytesAllocated;
}
get numBytesFree() {
return this._numBytesFree;
}
getNumUsedTextures() {
return this.numUsedTextures;
}
getNumFreeTextures() {
return this.numFreeTextures;
}
dispose() {
if (this.freeTextures != null) {
for (let e in this.freeTextures)
this.freeTextures[e].forEach((t) => {
this.gpgpu.deleteMatrixTexture(t);
});
for (let e in this.usedTextures)
this.usedTextures[e].forEach((t) => {
this.gpgpu.deleteMatrixTexture(t);
});
this.freeTextures = null, this.usedTextures = null, this.numUsedTextures = 0, this.numFreeTextures = 0, this._numBytesAllocated = 0, this._numBytesFree = 0;
}
}
};
function CJ(r, e) {
let t = r;
if (e === t.R32F)
return 4;
if (e === t.R16F)
return 2;
if (e === t.RGBA32F)
return 16;
if (e === r.RGBA)
return 16;
if (e === t.RGBA16F)
return 8;
throw new Error(`Unknown internal format ${e}`);
}
function OP(r, e, t, n, o) {
let s = IJ(e, n), a;
if (o) {
let [l, u] = Ai(r[0], r[1]);
a = l * u;
} else {
let [l, u] = xc(r[0], r[1]);
a = l * u;
}
let i = CJ(t, s);
return a * i;
}
function IJ(r, e) {
switch (r) {
case Fr.PACKED_2X2_FLOAT32:
return qy(e);
case Fr.PACKED_2X2_FLOAT16:
return Ky(e);
case Fr.UNPACKED_FLOAT32:
return Uy(e);
case Fr.UNPACKED_FLOAT16:
return jy(e);
case Fr.PACKED_4X1_UNSIGNED_BYTE:
return Hy(e);
default:
throw new Error(`Unknown physical texture type ${r}`);
}
}
function SJ(r) {
return U().getBool("WEBGL_RENDER_FLOAT32_ENABLED") ? r ? Fr.PACKED_2X2_FLOAT32 : Fr.UNPACKED_FLOAT32 : r ? Fr.PACKED_2X2_FLOAT16 : Fr.UNPACKED_FLOAT16;
}
function PP(r, e) {
if (r === Ur.UPLOAD)
return Fr.PACKED_2X2_FLOAT32;
if (r === Ur.RENDER || r == null)
return SJ(e);
if (r === Ur.DOWNLOAD || r === Ur.PIXELS)
return Fr.PACKED_4X1_UNSIGNED_BYTE;
throw new Error(`Unknown logical texture type ${r}`);
}
function MP(r, e, t) {
return `${r[0]}_${r[1]}_${e}_${t}`;
}
var En = class {
constructor(e, t) {
this.variableNames = ["A"], this.outputShape = e, this.enableShapeUniforms = jt(this.outputShape.length), this.userCode = `
float unaryOperation(float x) {
${t}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`;
}
};
var Nr = "if (isnan(x)) return x;";
var LP = "return x;";
var KC = "return abs(x);";
var zP = "return (x >= 0.0) ? x : (exp(x) - 1.0);";
var BP = Nr + `
return (x < 0.0) ? 0.0 : x;
`;
var VP = Nr + `
return (x < 0.0) ? 0.0 : min(6.0, x);
`;
var jh = "return x;";
var GP = "return 1.0 / (1.0 + exp(-1.0 * x));";
var WP = "return x;";
var UP = `
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
`;
var jP = `
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;
var HP = `
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;
var qP = "return 1.0 / (1.0 + exp(-1.0 * x));";
var Xs = class {
constructor(e, t) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.outputShape = e, this.enableShapeUniforms = jt(this.outputShape.length), this.userCode = `
vec4 unaryOperation(vec4 x) {
${t}
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
`;
}
};
var XC = class {
constructor(e) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = false, this.outputShape = e;
let t = e.length, n = Jt("rc", t), o = Ue(t), s = FP(t, n), a = n.slice(-2), i = t <= 1 ? "rc" : `vec2(${a.join(",")})`;
this.userCode = `
void main() {
${o} rc = getOutputCoords();
vec4 packedInput = getA(${s});
setOutput(getChannel(packedInput, ${i}));
}
`;
}
};
var NJ = Gr.whereImpl;
var TJ = 1e-7;
var EJ = 1e-4;
var Qy = {};
function AJ(r) {
return r in Qy || (Qy[r] = {}), Qy[r];
}
var DJ = U().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");
var $J = 600;
function RJ() {
return U().global.screen == null ? 1024 : U().global.screen.height * U().global.screen.width * window.devicePixelRatio * $J / 1024 / 1024;
}
var _c = class extends Js {
constructor(e) {
super();
if (this.pendingRead = new WeakMap(), this.pendingDisposal = new WeakSet(), this.dataRefCount = new WeakMap(), this.numBytesInGPU = 0, this.uploadWaitMs = 0, this.downloadWaitMs = 0, this.lastGlFlushTime = 0, this.warnedAboutMemory = false, this.pendingDeletes = 0, this.disposed = false, !U().getBool("HAS_WEBGL"))
throw new Error("WebGL is not supported on this device");
if (e == null) {
let t = Zn(U().getNumber("WEBGL_VERSION"));
this.binaryCache = AJ(U().getNumber("WEBGL_VERSION")), this.gpgpu = new Xy(t), this.canvas = t.canvas, this.gpgpuCreatedLocally = true;
} else
this.gpgpu = e, this.binaryCache = {}, this.gpgpuCreatedLocally = false, this.canvas = e.gl.canvas;
this.textureManager = new qC(this.gpgpu), this.numMBBeforeWarning = RJ(), this.texData = new pl(this, Es());
}
nextDataId() {
return _c.nextDataId++;
}
numDataIds() {
return this.texData.numDataIds() - this.pendingDeletes;
}
write(e, t, n) {
if ((U().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS") || U().getBool("DEBUG")) && this.checkNumericalProblems(e), n === "complex64" && e != null)
throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
let o = { id: this.nextDataId() };
return this.texData.set(o, { shape: t, dtype: n, values: e, usage: Ur.UPLOAD, refCount: 1 }), o;
}
refCount(e) {
return this.texData.has(e) ? this.texData.get(e).refCount : 0;
}
incRef(e) {
let t = this.texData.get(e);
t.refCount++;
}
decRef(e) {
if (this.texData.has(e)) {
let t = this.texData.get(e);
t.refCount--;
}
}
move(e, t, n, o, s) {
if (U().getBool("DEBUG") && this.checkNumericalProblems(t), o === "complex64")
throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
this.texData.set(e, { shape: n, dtype: o, values: t, usage: Ur.UPLOAD, refCount: s });
}
disposeIntermediateTensorInfo(e) {
this.disposeData(e.dataId);
}
readSync(e) {
let t = this.texData.get(e), { values: n, dtype: o, complexTensorInfos: s, slice: a, shape: i, isPacked: l } = t;
if (a != null) {
let m;
l ? m = new Xs(i, jh) : m = new En(i, jh);
let f = this.runWebGLProgram(m, [{ dataId: e, shape: i, dtype: o }], o), d = this.readSync(f.dataId);
return this.disposeIntermediateTensorInfo(f), d;
}
if (n != null)
return this.convertAndCacheOnCPU(e);
if (o === "string")
return n;
let u = this.activeTimers != null, c;
u && (c = b.now());
let p;
if (o === "complex64") {
let m = this.readSync(s.real.dataId), f = this.readSync(s.imag.dataId);
p = I.mergeRealAndImagArrays(m, f);
} else
p = this.getValuesFromTexture(e);
return u && (this.downloadWaitMs += b.now() - c), this.convertAndCacheOnCPU(e, p);
}
async read(e) {
if (this.pendingRead.has(e)) {
let d = this.pendingRead.get(e);
return new Promise((h) => d.push(h));
}
let t = this.texData.get(e), { values: n, shape: o, slice: s, dtype: a, complexTensorInfos: i, isPacked: l } = t;
if (s != null) {
let d;
l ? d = new Xs(o, jh) : d = new En(o, jh);
let h = this.runWebGLProgram(d, [{ dataId: e, shape: o, dtype: a }], a), g = this.read(h.dataId);
return this.disposeIntermediateTensorInfo(h), g;
}
if (n != null)
return this.convertAndCacheOnCPU(e);
if (!U().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED") && U().getNumber("WEBGL_VERSION") === 2)
throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");
let u = null, c;
if (a !== "complex64" && U().get("WEBGL_BUFFER_SUPPORTED")) {
c = this.decode(e);
let d = this.texData.get(c.dataId);
u = this.gpgpu.createBufferFromTexture(d.texture, ...Lh(o));
}
this.pendingRead.set(e, []), a !== "complex64" && await this.gpgpu.createAndWaitForFence();
let p;
if (a === "complex64") {
let d = await Promise.all([this.read(i.real.dataId), this.read(i.imag.dataId)]), h = d[0], g = d[1];
p = I.mergeRealAndImagArrays(h, g);
} else if (u == null)
p = this.getValuesFromTexture(e);
else {
let d = b.sizeFromShape(o);
p = this.gpgpu.downloadFloat32MatrixFromBuffer(u, d);
}
if (c != null && this.disposeIntermediateTensorInfo(c), u != null) {
let d = this.gpgpu.gl;
ke(d, () => d.deleteBuffer(u));
}
let m = this.convertAndCacheOnCPU(e, p), f = this.pendingRead.get(e);
return this.pendingRead.delete(e), f.forEach((d) => d(m)), this.pendingDisposal.has(e) && (this.pendingDisposal.delete(e), this.disposeData(e) && Es().removeDataId(e, this), this.pendingDeletes--), m;
}
bufferSync(e) {
let t = this.readSync(e.dataId), n = t;
if (e.dtype === "string")
try {
n = t.map((o) => b.decodeString(o));
} catch (o) {
throw new Error("Failed to decode encoded string bytes into utf-8");
}
return Ie(e.shape, e.dtype, n);
}
checkNumericalProblems(e) {
if (e != null)
for (let t = 0; t < e.length; t++) {
let n = e[t];
if (!rC(n))
throw U().getBool("WEBGL_RENDER_FLOAT32_CAPABLE") ? Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`) : Error(`The value ${n} cannot be represented on this device.`);
}
}
getValuesFromTexture(e) {
let { shape: t, dtype: n, isPacked: o } = this.texData.get(e), s = b.sizeFromShape(t);
if (U().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")) {
let m = this.decode(e), f = this.texData.get(m.dataId), d = this.gpgpu.downloadMatrixFromPackedTexture(f.texture, ...Lh(t)).subarray(0, s);
return this.disposeIntermediateTensorInfo(m), d;
}
let a = U().getBool("WEBGL_PACK") && o === true, i = a ? Gh(t) : t, l = a ? new SC(i) : new IC(i), u = this.runWebGLProgram(l, [{ shape: i, dtype: n, dataId: e }], "float32"), c = this.texData.get(u.dataId), p = this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(c.texture, c.texShape[0], c.texShape[1]).subarray(0, s);
return this.disposeIntermediateTensorInfo(u), p;
}
timerAvailable() {
return U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0;
}
async time(e) {
let t = this.activeTimers, n = [], o = false;
this.programTimersStack == null ? (this.programTimersStack = n, o = true) : this.activeTimers.push(n), this.activeTimers = n, e();
let s = b.flatten(this.activeTimers.map((l) => l.query)).filter((l) => l != null), a = b.flatten(this.activeTimers.map((l) => l.name)).filter((l) => l != null);
this.activeTimers = t, o && (this.programTimersStack = null);
let i = { uploadWaitMs: this.uploadWaitMs, downloadWaitMs: this.downloadWaitMs, kernelMs: null, wallMs: null };
if (U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0) {
let l = await Promise.all(s);
i.kernelMs = b.sum(l), i.getExtraProfileInfo = () => l.map((u, c) => ({ name: a[c], ms: u })).map((u) => `${u.name}: ${u.ms}`).join(", ");
} else
i.kernelMs = { error: "WebGL query timers are not supported in this environment." };
return this.uploadWaitMs = 0, this.downloadWaitMs = 0, i;
}
memory() {
return { unreliable: false, numBytesInGPU: this.numBytesInGPU, numBytesInGPUAllocated: this.textureManager.numBytesAllocated, numBytesInGPUFree: this.textureManager.numBytesFree };
}
startTimer() {
return U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0 ? this.gpgpu.beginQuery() : { startMs: b.now(), endMs: null };
}
endTimer(e) {
return U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0 ? (this.gpgpu.endQuery(), e) : (e.endMs = b.now(), e);
}
async getQueryTime(e) {
if (U().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0)
return this.gpgpu.waitForQueryAndGetTime(e);
let t = e;
return t.endMs - t.startMs;
}
disposeData(e, t = false) {
if (this.pendingDisposal.has(e))
return false;
if (!this.texData.has(e))
return true;
if (t ? this.texData.get(e).refCount = 0 : this.texData.get(e).refCount--, !t && this.texData.get(e).refCount > 0)
return false;
if (this.pendingRead.has(e))
return this.pendingDisposal.add(e), this.pendingDeletes++, false;
this.releaseGPUData(e);
let { complexTensorInfos: n } = this.texData.get(e);
return n != null && (this.disposeData(n.real.dataId, t), this.disposeData(n.imag.dataId, t)), this.texData.delete(e), true;
}
releaseGPUData(e) {
let { texture: t, dtype: n, texShape: o, usage: s, isPacked: a, slice: i } = this.texData.get(e), l = i && i.origDataId || e, u = this.dataRefCount.get(l);
u > 1 ? this.dataRefCount.set(l, u - 1) : (this.dataRefCount.delete(l), t != null && (this.numBytesInGPU -= this.computeBytes(o, n), this.textureManager.releaseTexture(t, o, s, a)));
let c = this.texData.get(e);
c.texture = null, c.texShape = null, c.isPacked = false, c.slice = null;
}
getTexture(e) {
return this.uploadToGPU(e), this.texData.get(e).texture;
}
getDataInfo(e) {
return this.texData.get(e);
}
shouldExecuteOnCPU(e, t = DJ) {
return U().getBool("WEBGL_CPU_FORWARD") && e.every((n) => this.texData.get(n.dataId).texture == null && b.sizeFromShape(n.shape) < t);
}
getGPGPUContext() {
return this.gpgpu;
}
where(e) {
I.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");
let t = e.dataSync();
return NJ(e.shape, t);
}
packedUnaryOp(e, t, n) {
let o = new Xs(e.shape, t), s = this.compileAndRun(o, [e], n);
return Es().makeTensorFromDataId(s.dataId, s.shape, s.dtype);
}
abs(e) {
if (this.shouldExecuteOnCPU([e]) && e.dtype !== "complex64") {
let o = Zy(this.texData.get(e.dataId).values);
return this.makeOutput(e.shape, e.dtype, o);
}
if (U().getBool("WEBGL_PACK_UNARY_OPERATIONS"))
return this.packedUnaryOp(e, KC, e.dtype);
let t = new En(e.shape, KC), n = this.compileAndRun(t, [e]);
return Es().makeTensorFromDataId(n.dataId, n.shape, n.dtype);
}
makeTensorInfo(e, t, n) {
let o;
if (t === "string" && n != null && n.length > 0 && b.isString(n[0])) {
let s = n.map((a) => b.encodeString(a));
o = this.write(s, e, t);
} else
o = this.write(n, e, t);
return this.texData.get(o).usage = null, { dataId: o, shape: e, dtype: t };
}
makeOutput(e, t, n) {
let { dataId: o } = this.makeTensorInfo(e, t, n);
return Es().makeTensorFromDataId(o, e, t, this);
}
unpackTensor(e) {
let t = new XC(e.shape);
return this.runWebGLProgram(t, [e], e.dtype);
}
packTensor(e) {
let t = new HC(e.shape), n = true;
return this.runWebGLProgram(t, [e], e.dtype, null, n);
}
packedReshape(e, t) {
let n = [Qa(e.shape), ...el(e.shape)], o = { dtype: e.dtype, shape: n, dataId: e.dataId }, s = [Qa(t), ...el(t)], a = new Uh(s, n), i = true, l = [n], u = this.runWebGLProgram(a, [o], e.dtype, l, i);
return { dataId: u.dataId, shape: t, dtype: u.dtype };
}
decode(e) {
let t = this.texData.get(e), { isPacked: n, shape: o, dtype: s } = t, a = Gh(o), i, l = Lh(a);
n ? i = new CC(a) : i = new vC(a);
let u = true, c = [l], p = this.runWebGLProgram(i, [{ shape: a, dtype: s, dataId: e }], s, c, u);
return { dtype: s, shape: o, dataId: p.dataId };
}
runWebGLProgram(e, t, n, o, s = false) {
let a = this.makeTensorInfo(e.outputShape, n), i = this.texData.get(a.dataId);
if (e.packedOutput && (i.isPacked = true), e.outPackingScheme === Hl.DENSE) {
let g = Lh(e.outputShape);
i.texShape = g.map((x) => x * 2);
}
if (e.outTexUsage != null && (i.usage = e.outTexUsage), b.sizeFromShape(a.shape) === 0)
return i.values = b.getTypedArrayFromDType(a.dtype, 0), a;
let l = [], u = t.map((g) => {
if (g.dtype === "complex64")
throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");
let x = this.texData.get(g.dataId);
if (x.texture == null) {
if (!e.packedInputs && b.sizeFromShape(g.shape) <= U().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))
return { shape: g.shape, texData: null, isUniform: true, uniformValues: x.values };
e.packedInputs && (x.isPacked = true, x.shape = g.shape);
} else if (!!x.isPacked != !!e.packedInputs)
g = x.isPacked ? this.unpackTensor(g) : this.packTensor(g), l.push(g), x = this.texData.get(g.dataId);
else if (x.isPacked && !ql(x.shape, g.shape)) {
let y = g, w = g.shape;
g.shape = x.shape, g = this.packedReshape(g, w), l.push(g), x = this.texData.get(g.dataId), y.shape = w;
}
return this.uploadToGPU(g.dataId), { shape: g.shape, texData: x, isUniform: false };
});
this.uploadToGPU(a.dataId);
let c = { shape: a.shape, texData: i, isUniform: false }, p = KO(e, u, c), m = this.getAndSaveBinary(p, () => jO(this.gpgpu, e, u, c)), f = this.activeTimers != null, d;
f && (d = this.startTimer()), qO(this.gpgpu, m, u, c, o), l.forEach((g) => this.disposeIntermediateTensorInfo(g)), f && (d = this.endTimer(d), this.activeTimers.push({ name: e.constructor.name, query: this.getQueryTime(d) }));
let h = U().get("WEBGL_FLUSH_THRESHOLD");
if (h > 0) {
let g = b.now();
g - this.lastGlFlushTime > h && (this.gpgpu.gl.flush(), this.lastGlFlushTime = g);
}
if (!U().getBool("WEBGL_LAZILY_UNPACK") && i.isPacked && s === false) {
let g = this.unpackTensor(a);
return this.disposeIntermediateTensorInfo(a), g;
}
return a;
}
compileAndRun(e, t, n, o, s = false) {
return n = n || t[0].dtype, this.runWebGLProgram(e, t, n, o, s);
}
getAndSaveBinary(e, t) {
return e in this.binaryCache || (this.binaryCache[e] = t()), this.binaryCache[e];
}
getTextureManager() {
return this.textureManager;
}
dispose() {
this.disposed || (U().getBool("IS_TEST") || Object.keys(this.binaryCache).forEach((t) => {
this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram), delete this.binaryCache[t];
}), this.textureManager.dispose(), this.canvas != null && typeof HTMLCanvasElement != "undefined" && this.canvas instanceof HTMLCanvasElement ? this.canvas.remove() : this.canvas = null, this.gpgpuCreatedLocally && (this.gpgpu.program = null, this.gpgpu.dispose()), this.disposed = true);
}
floatPrecision() {
return this.floatPrecisionValue == null && (this.floatPrecisionValue = V(() => {
if (!U().get("WEBGL_RENDER_FLOAT32_ENABLED")) {
let e = U().getBool("DEBUG");
U().set("DEBUG", false);
let t = this.abs(pe(1e-8)).dataSync()[0];
if (U().set("DEBUG", e), t > 0)
return 32;
}
return 16;
})), this.floatPrecisionValue;
}
epsilon() {
return this.floatPrecision() === 32 ? TJ : EJ;
}
uploadToGPU(e) {
let t = this.texData.get(e), { shape: n, dtype: o, values: s, texture: a, usage: i, isPacked: l } = t;
if (a != null)
return;
let u = this.activeTimers != null, c;
u && (c = b.now());
let p = t.texShape;
if (p == null && (p = hC(n, l), t.texShape = p), s != null) {
let m = Gh(n), f, d = p[1], h = p[0], g = s instanceof Uint8Array || s instanceof Uint8ClampedArray;
l ? ([d, h] = Ai(p[0], p[1]), f = new TC(m, g)) : f = new NC(m, g);
let x = this.makeTensorInfo([h, d], o);
g ? this.texData.get(x.dataId).usage = Ur.PIXELS : this.texData.get(x.dataId).usage = Ur.UPLOAD, this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(x.dataId), d, h, s);
let y = [[h, d]], w = true, _ = this.runWebGLProgram(f, [x], o, y, w), C = this.texData.get(_.dataId);
t.texture = C.texture, t.texShape = C.texShape, t.isPacked = C.isPacked, t.usage = C.usage, this.disposeIntermediateTensorInfo(x), this.texData.delete(_.dataId), t.values = null, u && (this.uploadWaitMs += b.now() - c);
} else {
let m = this.acquireTexture(p, i, o, l);
t.texture = m;
}
}
convertAndCacheOnCPU(e, t) {
let n = this.texData.get(e), { dtype: o } = n;
return this.releaseGPUData(e), t != null && (n.values = FJ(t, o)), n.values;
}
acquireTexture(e, t, n, o) {
if (this.numBytesInGPU += this.computeBytes(e, n), !this.warnedAboutMemory && this.numBytesInGPU > this.numMBBeforeWarning * 1024 * 1024) {
let s = (this.numBytesInGPU / 1024 / 1024).toFixed(2);
this.warnedAboutMemory = true, console.warn(`High memory usage in GPU: ${s} MB, most likely due to a memory leak`);
}
return this.textureManager.acquireTexture(e, t, o);
}
computeBytes(e, t) {
return e[0] * e[1] * b.bytesPerElement(t);
}
};
_c.nextDataId = 0;
function FJ(r, e) {
if (e === "float32" || e === "complex64")
return r;
if (e === "int32" || e === "bool") {
let t = e === "int32" ? new Int32Array(r.length) : new Uint8Array(r.length);
for (let n = 0; n < t.length; ++n)
t[n] = Math.round(r[n]);
return t;
} else
throw new Error(`Unknown dtype ${e}`);
}
var KP = "3.10.0";
function XP() {
U().set("WEBGL_FORCE_F16_TEXTURES", true);
}
xu.isBrowser() && Op("webgl", () => new _c(), 2);
var LTt = { forceHalfFloat: XP };
var eb = `
if (isnan(a)) return a;
if (isnan(b)) return b;
`;
var No = class {
constructor(e, t, n) {
this.variableNames = ["A", "B"], this.outputShape = I.assertAndGetBroadcastShape(t, n), this.enableShapeUniforms = jt(this.outputShape.length), this.userCode = `
float binaryOperation(float a, float b) {
${e}
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`;
}
};
var Kl = `
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
`;
var Ys = class {
constructor(e, t, n, o = false) {
this.variableNames = ["A", "B"], this.supportsBroadcasting = true, this.packedInputs = true, this.packedOutput = true, this.outputShape = I.assertAndGetBroadcastShape(t, n);
let s = this.outputShape.length;
this.enableShapeUniforms = jt(s);
let a = "";
if (o)
if (s === 0 || b.sizeFromShape(this.outputShape) === 1)
a = `
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;
else if (a = `
${Ue(s)} coords = getOutputCoords();
`, s === 1)
this.enableShapeUniforms ? a += `
result.y = (coords + 1) >= outShape ? 0. : result.y;
result.z = 0.;
result.w = 0.;
` : a += `
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;
else {
let l = Jt("coords", s);
this.enableShapeUniforms ? a += `
bool nextRowOutOfBounds =
(${l[s - 2]} + 1) >= outShape[${s} - 2];
bool nextColOutOfBounds =
(${l[s - 1]} + 1) >= outShape[${s} - 1];
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
` : a += `
bool nextRowOutOfBounds =
(${l[s - 2]} + 1) >= ${this.outputShape[s - 2]};
bool nextColOutOfBounds =
(${l[s - 1]} + 1) >= ${this.outputShape[s - 1]};
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`;
}
this.userCode = `
vec4 binaryOperation(vec4 a, vec4 b) {
${e}
}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
${a}
setOutput(result);
}
`;
}
};
function Qt(r) {
let { inputs: e, backend: t } = r, { x: n } = e;
return t.incRef(n.dataId), { dataId: n.dataId, shape: n.shape, dtype: n.dtype };
}
var YP = { kernelName: ro, backendName: "webgl", kernelFunc: Qt };
function An(r) {
let { inputs: e, backend: t } = r, { real: n, imag: o } = e, s = t.makeTensorInfo(n.shape, "complex64"), a = t.texData.get(s.dataId), i = Qt({ inputs: { x: n }, backend: t }), l = Qt({ inputs: { x: o }, backend: t });
return a.complexTensorInfos = { real: i, imag: l }, s;
}
var ZP = { kernelName: qc, backendName: "webgl", kernelFunc: An };
var YC = "return (a < 0.) ? b * a : a;";
var ZC = `
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;
function OJ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { alpha: s } = n, a = t.makeTensorInfo([], "float32", b.createScalarValue(s, "float32")), i = U().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new Ys(ZC, o.shape, a.shape) : new No(YC, o.shape, a.shape), l = t.runWebGLProgram(i, [o, a], "float32");
return t.disposeIntermediateTensorInfo(a), l;
}
var JP = { kernelName: Yo, backendName: "webgl", kernelFunc: OJ };
var JC = "return (a < 0.) ? b * a : a;";
var QC = `
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;
function PJ(r) {
let { inputs: e, backend: t } = r, { x: n, alpha: o } = e, s = U().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new Ys(QC, n.shape, o.shape) : new No(JC, n.shape, o.shape);
return t.runWebGLProgram(s, [n, o], "float32");
}
var QP = { kernelName: us, backendName: "webgl", kernelFunc: PJ };
var tb = "if (isnan(x)) return x;";
var eM = `
if (isnan(a)) return a;
if (isnan(b)) return b;
`;
var tM = `
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
`;
function ve({ opSnippet: r, packedOpSnippet: e, cpuKernelImpl: t, dtype: n }) {
return ({ inputs: o, backend: s }) => {
let { x: a } = o, i = s, l = n || a.dtype;
if (i.shouldExecuteOnCPU([a]) && t != null) {
let p = i.texData.get(a.dataId), m = t(p.values, l);
return i.makeTensorInfo(a.shape, l, m);
}
let u = U().getBool("WEBGL_PACK_UNARY_OPERATIONS") && e != null, c;
return u ? c = new Xs(a.shape, e) : c = new En(a.shape, r), i.runWebGLProgram(c, [a], l);
};
}
function at({ opSnippet: r, packedOpSnippet: e, checkOutOfBounds: t = false, supportsComplex: n = false, cpuKernelImpl: o, dtype: s }) {
return ({ inputs: a, backend: i }) => {
let { a: l, b: u } = a, c = i;
if (n && l.dtype === "complex64") {
let d = c.texData.get(l.dataId), h = c.texData.get(u.dataId), [g, x] = [[d.complexTensorInfos.real, h.complexTensorInfos.real], [d.complexTensorInfos.imag, h.complexTensorInfos.imag]].map((w) => {
let [_, C] = w, A = { dataId: _.dataId, dtype: _.dtype, shape: l.shape }, D = { dataId: C.dataId, dtype: C.dtype, shape: u.shape }, R = new No(r, l.shape, u.shape);
return c.runWebGLProgram(R, [A, D], hr(_.dtype, C.dtype));
}), y = An({ inputs: { real: g, imag: x }, backend: c });
return c.disposeIntermediateTensorInfo(g), c.disposeIntermediateTensorInfo(x), y;
}
let p = s || hr(l.dtype, u.dtype);
if ((l.dtype === "string" || u.dtype === "string" || c.shouldExecuteOnCPU([l, u])) && o != null) {
let d = c.texData.get(l.dataId).values, h = c.texData.get(u.dataId).values, g = l.dtype === "string" ? I.fromUint8ToStringArray(d) : d, x = l.dtype === "string" ? I.fromUint8ToStringArray(h) : h, [y, w] = o(l.shape, u.shape, g, x, p), _ = c.makeTensorInfo(w, p), C = c.texData.get(_.dataId);
return C.values = y, _;
}
let m = U().getBool("WEBGL_PACK_BINARY_OPERATIONS") && e != null, f;
return m ? f = new Ys(e, l.shape, u.shape, t) : f = new No(r, l.shape, u.shape), c.runWebGLProgram(f, [l, u], p);
};
}
function Xl(r, e = false) {
if (r === "linear")
return e ? WP : LP;
if (r === "relu")
return e ? jP : BP;
if (r === "elu")
return e ? UP : zP;
if (r === "relu6")
return e ? HP : VP;
if (r === "prelu")
return e ? QC : JC;
if (r === "leakyrelu")
return e ? ZC : YC;
if (r === "sigmoid")
return e ? qP : GP;
throw new Error(`Activation ${r} has not been implemented for the WebGL backend.`);
}
var Hh = class {
constructor(e, t, n, o = false, s = false, a = false, i = null, l = false, u = false) {
this.variableNames = ["matrixA", "matrixB"], this.packedInputs = true, this.packedOutput = true, this.outputShape = n, this.enableShapeUniforms = jt(this.outputShape.length);
let c = o ? e[1] : e[2], p = Math.ceil(c / 2), m = o ? "i * 2, rc.y" : "rc.y, i * 2", f = s ? "rc.z, i * 2" : "i * 2, rc.z", d = o ? ["a.xxyy", "a.zzww"] : ["a.xxzz", "a.yyww"], h = s ? ["b.xzxz", "b.ywyw"] : ["b.xyxy", "b.zwzw"], g = "", x = "";
i && (l ? g = `vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${i}
}` : u ? g = `vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${i}
}` : g = `vec4 activation(vec4 x) {
${i}
}`, x = "result = activation(result);");
let y = a ? "result += getBiasAtOutCoords();" : "";
a && this.variableNames.push("bias"), l && this.variableNames.push("preluActivationWeights"), u && this.variableNames.push("leakyreluAlpha");
let w = "rc.x", _ = "rc.x";
e[0] < t[0] ? w = `int(min(float(rc.x), ${e[0] - 1}.))` : t[0] < e[0] && (_ = `int(min(float(rc.x), ${t[0] - 1}.))`), this.userCode = `
${g}
// Don't use uniform for sharedDimensionPacked for performance.
const float sharedDimension = ${p}.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${p}; i++) {
int batchA = ${w};
int batchB = ${_};
vec4 a = getMatrixA(batchA, ${m});
vec4 b = getMatrixB(batchB, ${f});
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${d[0]} * ${h[0]});
result += (${d[1]} * ${h[1]});
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${y}
${x}
setOutput(result);
}
`;
}
};
var eI = { REAL: "return areal * breal - aimag * bimag;", IMAG: "return areal * bimag + aimag * breal;" };
var rb = class {
constructor(e, t, n) {
this.variableNames = ["AReal", "AImag", "BReal", "BImag"], this.outputShape = I.assertAndGetBroadcastShape(t, n), this.userCode = `
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`;
}
};
var rM = "return a * b;";
function qh(r) {
let { inputs: e, backend: t } = r, { a: n, b: o } = e, s = I.upcastType(n.dtype, o.dtype);
if (n.dtype === "complex64") {
let i = t.texData.get(n.dataId), l = t.texData.get(o.dataId), u = new rb(eI.REAL, n.shape, o.shape), c = new rb(eI.IMAG, n.shape, o.shape), p = [{ dataId: i.complexTensorInfos.real.dataId, dtype: i.complexTensorInfos.real.dtype, shape: n.shape }, { dataId: i.complexTensorInfos.imag.dataId, dtype: i.complexTensorInfos.imag.dtype, shape: n.shape }, { dataId: l.complexTensorInfos.real.dataId, dtype: l.complexTensorInfos.real.dtype, shape: o.shape }, { dataId: l.complexTensorInfos.imag.dataId, dtype: l.complexTensorInfos.imag.dtype, shape: o.shape }], m = t.runWebGLProgram(u, p, "float32"), f = t.runWebGLProgram(c, p, "float32"), d = An({ inputs: { real: m, imag: f }, backend: t });
return t.disposeIntermediateTensorInfo(m), t.disposeIntermediateTensorInfo(f), d;
}
if (t.shouldExecuteOnCPU([n, o])) {
let i = t.texData.get(n.dataId), l = t.texData.get(o.dataId), [u, c] = hP(n.shape, o.shape, i.values, l.values, s), p = t.makeTensorInfo(c, s), m = t.texData.get(p.dataId);
return m.values = u, p;
}
let a;
return U().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? a = new Ys(rM, n.shape, o.shape) : a = new No(rM, n.shape, o.shape), t.runWebGLProgram(a, [n, o], s);
}
var nM = { kernelName: ss, backendName: "webgl", kernelFunc: qh };
function oM(r, e, t) {
let n = [Qa(r.shape), ...el(r.shape)], o = { dtype: r.dtype, shape: n, dataId: r.dataId }, s = [Qa(e), ...el(e)], a = new Uh(s, n), i = true, l = [n], u = t.runWebGLProgram(a, [o], r.dtype, l, i);
return { dataId: u.dataId, shape: e, dtype: u.dtype };
}
function ue(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { shape: s } = n, a = t, i = b.sizeFromShape(o.shape), l = b.inferFromImplicitShape(s, i), u = b.sizeFromShape(l);
b.assert(i === u, () => `The new shape (${l}) has ${u} elements and the old shape (${o.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);
let c = a.texData.get(o.dataId);
return c.isPacked && !ql(o.shape, l) && !(c.texture !== null && ql(c.shape, l)) ? oM(o, l, a) : (a.incRef(o.dataId), { dataId: o.dataId, shape: l, dtype: o.dtype });
}
var sM = { kernelName: ui, backendName: "webgl", kernelFunc: ue };
var nb = class {
constructor(e, t) {
this.variableNames = ["x"];
let { windowSize: n, batchSize: o, inSize: s, outSize: a } = e;
this.outputShape = [o, a];
let i = Math.floor(n / 4) * 4, l = n % 4, u = "sumValue += dot(values, ones);";
if (t != null) {
let p = 1 / t;
u = `sumValue += dot(values * ${b.isInt(p) ? p.toPrecision(2) : p}, ones);`;
}
let c = "";
s % n > 0 && (c = `
if (inIdx < 0 || inIdx >= ${s}) {
return 0.0;
}
`), this.userCode = `
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${c}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
float sumValue = 0.0;
for (int i = 0; i < ${i}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${u}
}
int inIdx = inOffset + ${i};
if (${l === 1}) {
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
${u}
} else if (${l === 2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1), 0.0, 0.0);
${u}
} else if (${l === 3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
${u}
}
setOutput(sumValue);
}
`;
}
};
var tI = class {
constructor(e, t) {
this.variableNames = ["x"];
let { windowSize: n, batchSize: o, inSize: s, outSize: a } = e;
this.outputShape = [o, a];
let i = "0.0", l = "";
t === "prod" ? i = "1.0" : t === "min" ? (i = "1.0 / 1e-20", l = "min") : t === "max" && (i = "-1.0 / 1e-20", l = "max");
let u = `${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;
t === "sum" ? u = "sumValue" : t === "prod" ? u = "prodValue" : t === "all" ? u = "allValue" : t === "any" && (u = "anyValue");
let c = Math.floor(n / 4) * 4, p = n % 4, m = `
if (${t === "sum"}) {
sumValue += dot(values, ones);
} else if (${t === "prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${l}(values, minMaxValue);
if (${t === "min"} || ${t === "max"}) {
minMaxValue = ${l}(values, minMaxValue);
bvec4 isNaN = isnan(values);
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
minMaxValue = vec4(NAN);
}
}
}
`, f = "vec4";
t === "all" ? (i = "1.0", m = `
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`, f = "bvec4") : t === "any" && (i = "0.0", m = `
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`, f = "bvec4");
let d = "";
s % n > 0 && (d = `
if (inIdx < 0 || inIdx >= ${s}) {
return initializationValue;
}
`), this.userCode = `
const float initializationValue = ${i};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${d}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
vec4 minMaxValue = vec4(${i});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
for (int i = 0; i < ${c}; i += 4) {
int inIdx = inOffset + i;
${f} values = ${f}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${m}
}
int inIdx = inOffset + ${c};
if (${p === 1}) {
${f} values = ${f}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${m}
} else if (${p === 2}) {
${f} values = ${f}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${m}
} else if (${p === 3}) {
${f} values = ${f}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${m}
}
setOutput(${u});
}
`;
}
};
function MJ(r) {
let e = [];
for (; e.length === 0 || e[e.length - 1].outSize !== 1; ) {
let t = e.length ? e[e.length - 1].outSize : r[1], n = I.computeOptimalWindowSize(t);
e.push({ inSize: t, windowSize: n, outSize: Math.ceil(t / n) });
}
return e;
}
function Vn(r, e, t, n) {
let o = MJ(r.shape), s = r;
for (let a = 0; a < o.length; a++) {
let { inSize: i, windowSize: l, outSize: u } = o[a], c, p;
t === "mean" ? c = a === 0 ? new nb({ windowSize: l, inSize: i, batchSize: r.shape[0], outSize: u }, i) : new nb({ windowSize: l, inSize: i, batchSize: r.shape[0], outSize: u }) : c = new tI({ windowSize: l, inSize: i, batchSize: r.shape[0], outSize: u }, t), p = s, s = n.runWebGLProgram(c, [s], e), p.dataId !== r.dataId && n.disposeIntermediateTensorInfo(p);
}
return s;
}
var rI = class {
constructor(e, t) {
this.variableNames = ["A"];
let n = new Array(e.length);
for (let a = 0; a < n.length; a++)
n[a] = e[t[a]];
this.outputShape = n, this.rank = n.length;
let o = Ue(this.rank), s = LJ(t);
this.userCode = `
void main() {
${o} resRC = getOutputCoords();
setOutput(getA(${s}));
}
`;
}
};
function LJ(r) {
let e = r.length;
if (e > 6)
throw Error(`Transpose for rank ${e} is not yet supported`);
let t = ["resRC.x", "resRC.y", "resRC.z", "resRC.w", "resRC.u", "resRC.v"], n = new Array(e);
for (let o = 0; o < r.length; o++)
n[r[o]] = t[o];
return n.join();
}
var nI = class {
constructor(e, t) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true;
let n = new Array(e.length);
for (let c = 0; c < n.length; c++)
n[c] = e[t[c]];
if (this.outputShape = n, this.rank = n.length, this.rank > 6)
throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);
let o = Ue(this.rank), s = jC("rc", this.rank), a = new Array(this.rank);
for (let c = 0; c < t.length; c++)
a[t[c]] = s[c];
let i = `vec2(${a.slice(-2).join()})`, l = `++${s[this.rank - 1]} < ${n[this.rank - 1]}`, u = `getChannel(getA(${a.join()}), ${i})`;
this.userCode = `
void main() {
${o} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${u};
if(${l}) {
result[1] = ${u};
}
--${s[this.rank - 1]};
if(++${s[this.rank - 2]} < ${n[this.rank - 2]}) {
result[2] = ${u};
if(${l}) {
result[3] = ${u};
}
}
setOutput(result);
}
`;
}
};
function Yl(r, e, t) {
let n = U().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new nI(r.shape, e) : new rI(r.shape, e);
return t.runWebGLProgram(n, [r], r.dtype);
}
function iM(r, e, t, n) {
let o = e, s = r.shape.length, a = b.parseAxisParam(o, r.shape), i = a, l = I.getAxesPermutation(i, s), u = l != null, c = r;
u && (c = Yl(r, l, n), i = I.getInnerMostAxes(i.length, s)), I.assertAxesAreInnerMostDims("sum", i, s);
let [p, m] = I.computeOutAndReduceShapes(c.shape, i), f = p;
t && (f = I.expandShapeToKeepDim(p, a));
let d = b.sizeFromShape(m), g = b.sizeFromShape(r.shape) / d, x = ue({ inputs: { x: c }, attrs: { shape: [g, d] }, backend: n }), y = hu(r.dtype), w = Vn(x, y, "sum", n), _ = ue({ inputs: { x: w }, attrs: { shape: f }, backend: n });
return n.disposeIntermediateTensorInfo(x), n.disposeIntermediateTensorInfo(w), u && n.disposeIntermediateTensorInfo(c), _;
}
function kc(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, keepDims: a } = n;
return iM(o, s, a, t);
}
var aM = { kernelName: bs, backendName: "webgl", kernelFunc: kc };
function Pt(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { perm: s } = n, a = t, i = o.shape.length, l = new Array(i);
for (let c = 0; c < l.length; c++)
l[c] = o.shape[s[c]];
let u;
if (a.shouldExecuteOnCPU([o])) {
let p = a.texData.get(o.dataId).values, m = wc(p, o.shape, o.dtype, s, l);
u = a.makeTensorInfo(l, o.dtype);
let f = a.texData.get(u.dataId);
f.values = m;
} else
u = Yl(o, s, a);
return u;
}
var lM = { kernelName: Is, backendName: "webgl", kernelFunc: Pt };
var oI = 1e3;
function vc({ a: r, b: e, transposeA: t, transposeB: n, backend: o, bias: s = null, preluActivationWeights: a = null, leakyreluAlpha: i = 0, activation: l = null }) {
let u = r.shape.length, c = e.shape.length, p = t ? r.shape[u - 2] : r.shape[u - 1], m = n ? e.shape[c - 1] : e.shape[c - 2], f = t ? r.shape[u - 1] : r.shape[u - 2], d = n ? e.shape[c - 2] : e.shape[c - 1], h = r.shape.slice(0, -2), g = e.shape.slice(0, -2), x = b.sizeFromShape(h), y = b.sizeFromShape(g), w = x === y || x === 1 || y === 1;
b.assert(u >= 2 && c >= 2 && w, () => `Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${h}) and (${g}).`);
let C = (x > y ? r.shape.slice(0, -2) : e.shape.slice(0, -2)).concat([f, d]);
b.assert(p === m, () => `Error in matMul: inner shapes (${p}) and (${m}) of Tensors with shapes ${r.shape} and ${e.shape} and transposeA=${t} and transposeB=${n} must match.`);
let A = t ? [x, p, f] : [x, f, p], D = n ? [y, d, m] : [y, m, d], R = ue({ inputs: { x: r }, backend: o, attrs: { shape: A } }), P = ue({ inputs: { x: e }, backend: o, attrs: { shape: D } }), L = [R, P], G = Math.max(x, y), W = t ? R.shape[1] : R.shape[2], j = s != null, H = a != null, q = l === "leakyrelu", X = l != null ? Xl(l, true) : null, re = j || H || q || X != null, J;
if ((f === 1 || d === 1) && W > oI && re === false) {
let se = R, ne = P;
t && (se = Pt({ inputs: { x: R }, backend: o, attrs: { perm: [0, 2, 1] } }), L.push(se)), n && (ne = Pt({ inputs: { x: P }, backend: o, attrs: { perm: [0, 2, 1] } }), L.push(ne));
let fe = d !== 1, ae = d === 1, ge = se;
fe && (ge = ue({ inputs: { x: se }, backend: o, attrs: { shape: [G, W, 1] } }), L.push(ge));
let de = d === 1 ? 2 : 1, ye = ne;
ae && (ye = ue({ inputs: { x: ne }, backend: o, attrs: { shape: [G, 1, W] } }), L.push(ye));
let _e = qh({ inputs: { a: ge, b: ye }, backend: o });
J = kc({ inputs: { x: _e }, backend: o, attrs: { axis: de, keepDims: true } }), L.push(_e);
} else {
let se = hr(r.dtype, e.dtype), ne = new Hh(A, D, [G, f, d], t, n, j, X, H, q), fe = [R, P];
if (s != null && fe.push(s), H && fe.push(a), q) {
let ae = o.makeTensorInfo([], "float32", b.createScalarValue(i, "float32"));
fe.push(ae), L.push(ae);
}
J = o.runWebGLProgram(ne, fe, se);
}
let oe = ue({ inputs: { x: J }, backend: o, attrs: { shape: C } });
L.push(J);
for (let se of L)
o.disposeIntermediateTensorInfo(se);
return oe;
}
function zJ(r) {
let { inputs: e, backend: t, attrs: n } = r, { a: o, b: s, bias: a, preluActivationWeights: i } = e, { transposeA: l, transposeB: u, activation: c, leakyreluAlpha: p } = n;
return vc({ a: o, b: s, transposeA: l, transposeB: u, backend: t, bias: a, preluActivationWeights: i, leakyreluAlpha: p, activation: c });
}
var uM = { kernelName: gi, backendName: "webgl", kernelFunc: zJ };
var cM = "return abs(x);";
function BJ(r) {
let { inputs: e, backend: t } = r, { x: n } = e;
if (t.shouldExecuteOnCPU([n]) && n.dtype !== "complex64") {
let s = t.texData.get(n.dataId), a = Zy(s.values);
return t.makeTensorInfo(n.shape, n.dtype, a);
}
let o;
return U().getBool("WEBGL_PACK_UNARY_OPERATIONS") ? o = new Xs(n.shape, cM) : o = new En(n.shape, cM), t.runWebGLProgram(o, [n], n.dtype);
}
var pM = { kernelName: ti, backendName: "webgl", kernelFunc: BJ };
var VJ = Nr + `
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`;
var GJ = ve({ opSnippet: VJ });
var mM = { kernelName: Mi, backendName: "webgl", kernelFunc: GJ };
var WJ = Nr + `
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`;
var UJ = ve({ opSnippet: WJ });
var fM = { kernelName: Li, backendName: "webgl", kernelFunc: UJ };
var dM = "return a + b;";
var jJ = at({ opSnippet: dM, packedOpSnippet: dM, supportsComplex: true, cpuKernelImpl: YO });
var hM = { kernelName: jn, backendName: "webgl", kernelFunc: jJ };
var sI = class {
constructor(e, t) {
this.outputShape = [], this.outputShape = e, this.variableNames = t.map((s, a) => `T${a}`);
let n = [];
this.variableNames.forEach((s) => {
n.push(`float v${s} = get${s}AtOutCoords();`);
});
let o = this.variableNames.map((s) => `v${s}`).join(" + ");
this.userCode = `
void main() {
${n.join(`
`)}
float result = ${o};
setOutput(result);
}
`;
}
};
var iI = class {
constructor(e, t) {
this.outputShape = [], this.packedInputs = true, this.packedOutput = true, this.outputShape = e, this.variableNames = t.map((s, a) => `T${a}`);
let n = [];
this.variableNames.forEach((s) => {
n.push(`vec4 v${s} = get${s}AtOutCoords();`);
});
let o = this.variableNames.map((s) => `v${s}`).join(" + ");
this.userCode = `
void main() {
${n.join(`
`)}
vec4 result = ${o};
setOutput(result);
}
`;
}
};
function ob(r) {
let { inputs: e, backend: t } = r, n = e;
if (n.length === 1)
return Qt({ inputs: { x: n[0] }, backend: t });
if (n.length > U().get("WEBGL_MAX_TEXTURES_IN_SHADER")) {
let l = Math.floor(n.length / 2), u = ob({ inputs: n.slice(0, l), backend: t }), c = ob({ inputs: n.slice(l), backend: t });
return ob({ inputs: [u, c], backend: t });
}
let o = n.map((l) => l.dtype).reduce((l, u) => hr(l, u)), s = n.map((l) => l.shape), i = U().getBool("WEBGL_PACK") ? new iI(n[0].shape, s) : new sI(n[0].shape, s);
return t.runWebGLProgram(i, n, o);
}
var gM = { kernelName: $o, backendName: "webgl", kernelFunc: ob };
function HJ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, keepDims: a } = n, i = o.shape.length, l = b.parseAxisParam(s, o.shape), u = l, c = I.getAxesPermutation(u, i), p = o;
c != null && (p = Pt({ inputs: { x: o }, backend: t, attrs: { perm: c } }), u = I.getInnerMostAxes(u.length, i)), I.assertAxesAreInnerMostDims("all", u, i);
let [m, f] = I.computeOutAndReduceShapes(p.shape, u), d = b.sizeFromShape(f), h = ue({ inputs: { x: p }, backend: t, attrs: { shape: [-1, d] } }), g = Vn(h, h.dtype, "all", t), x;
if (a) {
let y = I.expandShapeToKeepDim(m, l);
x = ue({ inputs: { x: g }, backend: t, attrs: { shape: y } });
} else
x = ue({ inputs: { x: g }, backend: t, attrs: { shape: m } });
return t.disposeIntermediateTensorInfo(h), t.disposeIntermediateTensorInfo(g), c != null && t.disposeIntermediateTensorInfo(p), x;
}
var xM = { kernelName: zi, backendName: "webgl", kernelFunc: HJ };
function qJ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, keepDims: a } = n, i = o.shape.length, l = b.parseAxisParam(s, o.shape), u = l, c = I.getAxesPermutation(u, i), p = o;
c != null && (p = Pt({ inputs: { x: o }, backend: t, attrs: { perm: c } }), u = I.getInnerMostAxes(u.length, i)), I.assertAxesAreInnerMostDims("any", u, i);
let [m, f] = I.computeOutAndReduceShapes(p.shape, u), d = b.sizeFromShape(f), h = ue({ inputs: { x: p }, backend: t, attrs: { shape: [-1, d] } }), g = Vn(h, h.dtype, "any", t), x;
if (a) {
let y = I.expandShapeToKeepDim(m, l);
x = ue({ inputs: { x: g }, backend: t, attrs: { shape: y } });
} else
x = ue({ inputs: { x: g }, backend: t, attrs: { shape: m } });
return t.disposeIntermediateTensorInfo(h), t.disposeIntermediateTensorInfo(g), c != null && t.disposeIntermediateTensorInfo(p), x;
}
var yM = { kernelName: Bi, backendName: "webgl", kernelFunc: qJ };
var aI = class {
constructor(e, t, n) {
this.variableNames = ["A"];
let { windowSize: o, batchSize: s, outSize: a } = e;
n || this.variableNames.push("bestIndicesA"), this.outputShape = [s, a];
let i = t === "max" ? ">" : "<", l = n ? "inOffset + i;" : "round(getBestIndicesA(batch, inOffset + i));";
this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${o};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${o}; i++) {
int inIdx = ${l};
float candidate = getA(batch, inIdx);
if (candidate ${i} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`;
}
};
var lI = class {
constructor(e, t, n, o) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, b.assert(e.length > 2, () => `Packed arg${n.charAt(0).toUpperCase() + n.slice(1)} supports only inputs with rank above 2.`);
let s = e[e.length - 1], a = Math.ceil(s / t);
this.outputShape = e.slice(0, -1), a > 1 && this.outputShape.push(a), o || this.variableNames.push("bestIndicesA");
let i = this.outputShape, l = i.length, u = Ue(l), c = Jt("coords", l), p, m;
if (a === 1) {
m = l + 1;
let R = Ue(m);
p = `
${R} sourceLocR = ${R}(${c.join()}, 0);
++${c[l - 1]};
${R} sourceLocG = ${R}(${c.join()}, 0);
++${c[l - 2]};
${R} sourceLocA = ${R}(${c.join()}, 0);
--${c[l - 1]};
${R} sourceLocB = ${R}(${c.join()}, 0);
--${c[l - 2]};`;
} else
m = l, p = `
${u} sourceLocR = coords;
++${c[l - 1]};
${u} sourceLocG = coords;
++${c[l - 2]};
${u} sourceLocA = coords;
--${c[l - 1]};
${u} sourceLocB = coords;
--${c[l - 2]};`;
let f = ["x", "y", "z", "w", "u", "v"].slice(0, m), d = "." + f[m - 1], h = f.map((R) => "int " + R), g = Jt("sourceLocR", m - 1).concat("inIdx.r"), x = Jt("sourceLocG", m - 1).concat("inIdx.g"), y = Jt("sourceLocB", m - 1).concat("inIdx.b"), w = Jt("sourceLocA", m - 1).concat("inIdx.a"), _ = n === "max" ? "greaterThan" : "lessThan", C = o ? "" : `
inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),
getBestIndicesAChannel(${x.join()}),
getBestIndicesAChannel(${y.join()}),
getBestIndicesAChannel(${w.join()})));`, A = `vec4(
getAChannel(${g.join()}),
hasNextCol ? getAChannel(${x.join()}) : 0.,
hasNextRow ? getAChannel(${y.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${w.join()}) : 0.)`, D = o ? "" : `
float getBestIndicesAChannel(${h.join()}) {
return getChannel(getBestIndicesA(${f.join()}),
vec2(${f.slice(-2).join()}));
}`;
this.userCode = `
float getAChannel(${h.join()}) {
return getChannel(getA(${f.join()}),
vec2(${f.slice(-2).join()}));
}
${D}
void main() {
${u} coords = getOutputCoords();
bool hasNextCol = ${c[l - 1]} < ${i[l - 1] - 1};
bool hasNextRow = ${c[l - 2]} < ${i[l - 2] - 1};
${p}
ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},
sourceLocB${d}, sourceLocA${d}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${A};
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${C}
vec4 candidate = ${A};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${_}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
`;
}
};
function bM(r, e, t, n = null) {
let o = e.shape[0], s = e.shape[1];
n != null && (o = n.shape[0], s = n.shape[1]);
let a = I.computeOptimalWindowSize(s), i = { windowSize: a, inSize: s, batchSize: o, outSize: Math.ceil(s / a) }, l = new aI(i, t, n == null), u = [e];
n != null && u.push(n);
let c = r.runWebGLProgram(l, u, "int32");
if (c.shape[1] === 1)
return c;
let p = bM(r, e, t, c);
return r.disposeIntermediateTensorInfo(c), p;
}
function wM(r, e, t, n = null) {
let o = n != null ? n.shape : e.shape, s = o[o.length - 1], a = I.computeOptimalWindowSize(s), i = new lI(o, a, t, n == null), l = n == null ? [e] : [e, n], u = r.runWebGLProgram(i, l, "int32");
if (u.shape.length === e.shape.length) {
let c = wM(r, e, t, u);
return r.disposeIntermediateTensorInfo(u), c;
}
return u;
}
function sb(r, e, t, n) {
let o = [t];
if (I.assertAxesAreInnerMostDims("arg" + n.charAt(0).toUpperCase() + n.slice(1), o, e.shape.length), !U().getBool("WEBGL_PACK_REDUCE") || e.shape.length <= 2) {
let s = [], a = r.texData.get(e.dataId), i = a !== null && a.isPacked, l = e;
i && (l = r.unpackTensor(e), s.push(l));
let [u, c] = I.computeOutAndReduceShapes(l.shape, o), p = b.sizeFromShape(c), m = ue({ inputs: { x: l }, backend: r, attrs: { shape: [-1, p] } });
s.push(m);
let f = bM(r, m, n);
s.push(f);
let d = ue({ inputs: { x: f }, backend: r, attrs: { shape: u } });
return s.forEach((h) => r.disposeIntermediateTensorInfo(h)), d;
}
return wM(r, e, n);
}
function KJ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s } = n, a = b.parseAxisParam(s, o.shape), i = I.getAxesPermutation(a, o.shape.length), l = o, u = [];
i != null && (l = Pt({ inputs: { x: o }, backend: t, attrs: { perm: i } }), u.push(l), a = I.getInnerMostAxes(a.length, l.shape.length)), I.assertAxesAreInnerMostDims("argMax", [a[0]], l.shape.length);
let c = sb(t, l, a[0], "max");
return u.forEach((p) => t.disposeIntermediateTensorInfo(p)), c;
}
var _M = { kernelName: Ro, backendName: "webgl", kernelFunc: KJ };
function XJ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s } = n, a = b.parseAxisParam(s, o.shape), i = I.getAxesPermutation(a, o.shape.length), l = o, u = [];
i != null && (l = Pt({ inputs: { x: o }, backend: t, attrs: { perm: i } }), u.push(l), a = I.getInnerMostAxes(a.length, l.shape.length)), I.assertAxesAreInnerMostDims("argMin", [a[0]], l.shape.length);
let c = sb(t, l, a[0], "min");
return u.forEach((p) => t.disposeIntermediateTensorInfo(p)), c;
}
var kM = { kernelName: ml, backendName: "webgl", kernelFunc: XJ };
var YJ = Nr + `
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`;
var ZJ = ve({ opSnippet: YJ });
var vM = { kernelName: Vi, backendName: "webgl", kernelFunc: ZJ };
var JJ = Nr + "return log(x + sqrt(x * x + 1.0));";
var QJ = ve({ opSnippet: JJ });
var CM = { kernelName: Gi, backendName: "webgl", kernelFunc: QJ };
var eQ = Nr + `
return atan(x);
`;
var tQ = ve({ opSnippet: eQ });
var IM = { kernelName: Wi, backendName: "webgl", kernelFunc: tQ };
var rQ = eM + `
return atan(a, b);
`;
var nQ = `
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
` + tM + `
return result;
`;
var oQ = at({ opSnippet: rQ, packedOpSnippet: nQ });
var SM = { kernelName: ji, backendName: "webgl", kernelFunc: oQ };
var sQ = Nr + `
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`;
var iQ = ve({ opSnippet: sQ });
var NM = { kernelName: Ui, backendName: "webgl", kernelFunc: iQ };
var Di = class {
constructor(e, t, n, o = false, s = false) {
if (this.variableNames = ["x"], t === "avg" && n)
throw new Error("Cannot compute positions for average pool.");
let a = e.filterWidth, i = e.strideHeight, l = e.strideWidth, u = e.dilationHeight, c = e.dilationWidth, p = e.effectiveFilterHeight, m = e.effectiveFilterWidth, f = e.padInfo.top, d = e.padInfo.left;
this.outputShape = e.outShape;
let h = t === "avg", g = `((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`, x = `(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`, y = "0.0";
if (h || (y = "-1.0 / 1e-20"), n) {
let R = ">=";
this.userCode = `
const ivec2 strides = ivec2(${i}, ${l});
const ivec2 pads = ivec2(${f}, ${d});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
for (int wR = 0; wR < ${p};
wR += ${u}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${m};
wC += ${c}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xR, xC, d);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${R} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${o ? s ? g : x : `wR * ${m} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;
return;
}
let w = "max", _ = `${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;
t === "avg" && (_ = "avgValue / count");
let C = Math.floor(a / 4) * 4, A = a % 4, D = `
if (${h}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${w}(values, minMaxValue);
}
`;
this.userCode = `
const ivec2 strides = ivec2(${i}, ${l});
const ivec2 pads = ivec2(${f}, ${d});
const float initializationValue = ${y};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xR, xC, d);
}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4(${y});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${p};
wR += ${u}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${C}; wC += 4) {
int xC = xCCorner + wC * ${c};
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
getValue(batch, xR, xC + 2 * ${c}, d),
getValue(batch, xR, xC + 3 * ${c}, d)
);
${D}
}
int xC = xCCorner + ${C};
if (${A === 1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${D}
} else if (${A === 2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
initializationValue,
initializationValue
);
${D}
} else if (${A === 3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
getValue(batch, xR, xC + 2 * ${c}, d),
initializationValue
);
${D}
}
}
setOutput(${_});
}
`;
}
};
var Cc = class {
constructor(e, t, n, o = false, s = false) {
if (this.variableNames = ["x"], t === "avg" && n)
throw new Error("Cannot compute positions for average pool.");
let a = e.filterWidth, i = e.strideDepth, l = e.strideHeight, u = e.strideWidth, c = e.dilationDepth, p = e.dilationHeight, m = e.dilationWidth, f = e.effectiveFilterDepth, d = e.effectiveFilterHeight, h = e.effectiveFilterWidth, g = e.padInfo.front, x = e.padInfo.top, y = e.padInfo.left;
this.outputShape = e.outShape;
let w = t === "avg", _ = "0.0";
if (w || (_ = "-1.0 / 1e-20"), n) {
let L = ">=";
this.userCode = `
const ivec3 strides =
ivec3(${i}, ${l}, ${u});
const ivec3 pads = ivec3(${g}, ${x}, ${y});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
for (int wD = 0; wD < ${f};
wD += ${c}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${d};
wR += ${p}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${h};
wC += ${m}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${L} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${o ? s ? `(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch` : `((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch` : `wD * ${d} * ${h} +
wR * ${h} + wC`};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;
return;
}
let C = "max", A = `${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;
t === "avg" && (A = "avgValue / count");
let D = Math.floor(a / 4) * 4, R = a % 4, P = `
if (${w}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${C}(values, minMaxValue);
}
`;
this.userCode = `
const ivec3 strides =
ivec3(${i}, ${l}, ${u});
const ivec3 pads = ivec3(${g}, ${x}, ${y});
const float initializationValue = ${_};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4(${_});
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < ${f};
wD += ${c}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${d};
wR += ${p}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${D}; wC += 4) {
int xC = xCCorner + wC * ${m};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${m}, ch),
getValue(batch, xD, xR, xC + 2 * ${m}, ch),
getValue(batch, xD, xR, xC + 3 * ${m}, ch)
);
${P}
}
int xC = xCCorner + ${D};
if (${R === 1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${P}
} else if (${R === 2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${m}, ch),
initializationValue,
initializationValue
);
${P}
} else if (${R === 3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${m}, ch),
getValue(batch, xD, xR, xC + 2 * ${m}, ch),
initializationValue
);
${P}
}
}
setOutput(${A});
}
}
`;
}
};
function aQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e;
qs(o, "avgPool");
let { filterSize: s, strides: a, pad: i, dimRoundingMode: l } = n, u = 1;
b.assert(I.eitherStridesOrDilationsAreOne(a, u), () => `Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);
let c = I.computePool2DInfo(o.shape, s, a, u, i, l);
if (c.filterWidth === 1 && c.filterHeight === 1 && b.arraysEqual(c.inShape, c.outShape))
return Qt({ inputs: { x: o }, backend: t });
let p = new Di(c, "avg", false);
return t.runWebGLProgram(p, [o], "float32");
}
var TM = { kernelName: Fo, backendName: "webgl", kernelFunc: aQ };
function lQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { filterSize: s, strides: a, pad: i, dimRoundingMode: l, dataFormat: u } = n, c = [1, 1, 1], p = I.computePool3DInfo(o.shape, s, a, c, i, l, u), m = new Cc(p, "avg", false);
return t.runWebGLProgram(m, [o], "float32");
}
var EM = { kernelName: fl, backendName: "webgl", kernelFunc: lQ };
var uI = class {
constructor(e) {
this.variableNames = ["dy"], this.outputShape = e.inShape;
let t = e.filterHeight, n = e.filterWidth, o = e.strideHeight, s = e.strideWidth, a = e.dilationHeight, i = e.dilationWidth, l = e.effectiveFilterHeight, u = e.effectiveFilterWidth, c = l - 1 - e.padInfo.top, p = u - 1 - e.padInfo.left, m = 1 / (t * n);
this.userCode = `
const ivec2 pads = ivec2(${c}, ${p});
const float avgMultiplier = float(${m});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${l};
wR += ${a}) {
float dyR = float(dyRCorner + wR) / ${o}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${u};
wC+= ${i}) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
}
}
setOutput(dotProd);
}
`;
}
};
var cI = class {
constructor(e) {
this.variableNames = ["dy"], this.outputShape = e.inShape;
let t = e.filterDepth, n = e.filterHeight, o = e.filterWidth, s = e.strideDepth, a = e.strideHeight, i = e.strideWidth, l = e.dilationDepth, u = e.dilationHeight, c = e.dilationWidth, p = e.effectiveFilterDepth, m = e.effectiveFilterHeight, f = e.effectiveFilterWidth, d = p - 1 - e.padInfo.front, h = m - 1 - e.padInfo.top, g = f - 1 - e.padInfo.left, x = 1 / (t * n * o);
this.userCode = `
const ivec3 pads = ivec3(${d}, ${h}, ${g});
const float avgMultiplier = float(${x});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${p};
wD += ${l}) {
float dyD = float(dyDCorner + wD) / ${s}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${m};
wR += ${u}) {
float dyR = float(dyRCorner + wR) / ${a}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${f};
wC += ${c}) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
}
`;
}
};
function uQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, input: s } = e, a = s, { filterSize: i, strides: l, pad: u, dimRoundingMode: c } = n, p = [1, 1, 1], m = I.computePool3DInfo(a.shape, i, l, p, u, c), f = new cI(m);
return t.runWebGLProgram(f, [o], a.dtype);
}
var AM = { kernelName: Uc, backendName: "webgl", kernelFunc: uQ };
function cQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, input: s } = e, a = s;
qs([o, s], "avgPoolGrad");
let { filterSize: i, strides: l, pad: u } = n, c = I.computePool2DInfo(a.shape, i, l, 1, u), p = new uI(c);
return t.runWebGLProgram(p, [o], a.dtype);
}
var DM = { kernelName: Wc, backendName: "webgl", kernelFunc: cQ };
function pQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { a: o, b: s } = e, { transposeA: a, transposeB: i } = n;
return vc({ a: o, b: s, transposeA: a, transposeB: i, backend: t });
}
var $M = { kernelName: Oo, backendName: "webgl", kernelFunc: pQ };
var pI = class {
constructor(e, t, n, o, s, a) {
this.outputShape = [], this.variableNames = ["x", "mean", "variance"], I.assertAndGetBroadcastShape(e, t), I.assertAndGetBroadcastShape(e, n);
let i = "0.0";
o != null && (I.assertAndGetBroadcastShape(e, o), this.variableNames.push("offset"), i = "getOffsetAtOutCoords()");
let l = "1.0";
s != null && (I.assertAndGetBroadcastShape(e, s), this.variableNames.push("scale"), l = "getScaleAtOutCoords()"), this.outputShape = e, this.userCode = `
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${i};
float scale = ${l};
float inv = scale * inversesqrt(variance + float(${a}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
`;
}
};
var mI = class {
constructor(e, t, n, o, s, a) {
this.packedInputs = true, this.packedOutput = true, this.variableNames = ["x", "mean", "variance"], I.assertAndGetBroadcastShape(e, t), I.assertAndGetBroadcastShape(e, n);
let i = "vec4(0.0)";
o != null && (I.assertAndGetBroadcastShape(e, o), this.variableNames.push("offset"), i = "getOffsetAtOutCoords()");
let l = "vec4(1.0)";
s != null && (I.assertAndGetBroadcastShape(e, s), this.variableNames.push("scale"), l = "getScaleAtOutCoords()"), this.outputShape = e, this.userCode = `
void main() {
vec4 offset = ${i};
vec4 scale = ${l};
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(${a}));
setOutput((x - mean) * inv + offset);
}
`;
}
};
var mQ = ({ inputs: r, backend: e, attrs: t }) => {
let { x: n, mean: o, variance: s, offset: a, scale: i } = r;
b.assert(o.shape.length === s.shape.length, () => "Batch normalization gradient requires mean and variance to have equal ranks."), b.assert(a == null || o.shape.length === a.shape.length, () => "Batch normalization gradient requires mean and offset to have equal ranks."), b.assert(i == null || o.shape.length === i.shape.length, () => "Batch normalization gradient requires mean and scale to have equal ranks.");
let { varianceEpsilon: l } = t;
l == null && (l = 1e-3);
let u = [n, o, s], c = null;
a != null && (c = a.shape, u.push(a));
let p = null;
i != null && (p = i.shape, u.push(i));
let m = U().getBool("WEBGL_PACK_NORMALIZATION") ? new mI(n.shape, o.shape, s.shape, c, p, l) : new pI(n.shape, o.shape, s.shape, c, p, l);
return e.runWebGLProgram(m, u, u[0].dtype);
};
var RM = { kernelName: Ko, backendName: "webgl", kernelFunc: mQ };
var fI = class {
constructor(e) {
this.variableNames = ["source"], this.outputShape = e, this.rank = e.length;
let t = Ue(this.rank);
this.customUniforms = [{ name: "start", arrayIndex: this.rank, type: "int" }];
let n = fQ(this.rank), o, s = e.map((a, i) => `sourceLoc.${dI[i]} = start[${i}] + coords.${dI[i]};`);
o = `
${t} sourceLoc;
${t} coords = getOutputCoords();
${s.join(`
`)}
`, this.userCode = `
void main() {
${o}
setOutput(getSource(${n}));
}
`;
}
};
var dI = ["x", "y", "z", "w", "u", "v"];
function fQ(r) {
if (r === 1)
return "sourceLoc";
if (r <= 6)
return dI.slice(0, r).map((e) => "sourceLoc." + e).join(",");
throw Error(`Slicing for rank ${r} is not yet supported`);
}
var hI = class {
constructor(e) {
this.variableNames = ["source"], this.packedInputs = true, this.packedOutput = true, this.outputShape = e, this.rank = e.length, this.customUniforms = [{ name: "start", arrayIndex: this.rank, type: "int" }];
let t = Ue(this.rank), n = Jt("coords", this.rank), o = Jt("sourceLoc", this.rank), s = this.rank === 1 ? "sourceLoc" : `vec2(${o.slice(-2).join()})`, a = `getChannel(getSource(${o.join()}), ${s})`, i = `
result.x = ${a};
if (++${n[this.rank - 1]} < ${e[this.rank - 1]}) {
++${o[this.rank - 1]};
result.y = ${a};
--${o[this.rank - 1]};
}
`, l = this.rank === 1 ? "" : `
--${n[this.rank - 1]};
if (++${n[this.rank - 2]} < ${e[this.rank - 2]}) {
++${o[this.rank - 2]};
result.z = ${a};
if (++${n[this.rank - 1]} < ${e[this.rank - 1]}) {
++${o[this.rank - 1]};
result.w = ${a};
}
}
`, u = this.rank <= 4 ? `sourceLoc = coords +
${t}(${e.map((c, p) => `start[${p}]`).join()});` : e.map((c, p) => `${o[p]} = ${n[p]} + start[${p}];`).join(`
`);
this.userCode = `
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
${u}
vec4 result = vec4(0.);
${i}
${l}
setOutput(result);
}
`;
}
};
function dQ(r, e, t, n) {
let o = n.texData.get(r.dataId), s = n.makeTensorInfo(t, r.dtype), a = n.texData.get(s.dataId);
Object.assign(a, o), a.refCount = 1, a.shape = t, a.dtype = r.dtype;
let i = pr.computeFlatOffset(e, b.computeStrides(r.shape));
o.slice && (i += o.slice.flatOffset), a.slice = { flatOffset: i, origDataId: o.slice && o.slice.origDataId || r.dataId };
let l = n.dataRefCount.get(a.slice.origDataId) || 1;
return n.dataRefCount.set(a.slice.origDataId, l + 1), s;
}
function Zs(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { begin: s, size: a } = n, [i, l] = pr.parseSliceParams(o, s, a);
if (pr.assertParamsValid(o, i, l), b.sizeFromShape(l) === 0)
return t.makeTensorInfo(l, o.dtype, []);
if (t.shouldExecuteOnCPU([o]) || o.dtype === "string") {
let p = t.texData.get(o.dataId), m = kP(p.values, i, l, o.shape, o.dtype);
return t.makeTensorInfo(l, o.dtype, m);
}
let { isPacked: u } = t.texData.get(o.dataId), c = pr.isSliceContinous(o.shape, i, l);
if (u || !c) {
let p = U().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new hI(l) : new fI(l), m = [i];
return t.runWebGLProgram(p, [o], o.dtype, m);
}
return t.uploadToGPU(o.dataId), dQ(o, i, l, t);
}
var FM = { kernelName: pi, backendName: "webgl", kernelFunc: Zs };
var hQ = (r) => {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { blockShape: s, crops: a } = n;
b.assert(o.shape.length <= 4, () => "batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");
let i = s.reduce((y, w) => y * w), l = I.getReshaped(o.shape, s, i), u = I.getPermuted(l.length, s.length), c = I.getReshapedPermuted(o.shape, s, i), p = I.getSliceBeginCoords(a, s.length), m = I.getSliceSize(c, a, s.length), f = [], d = ue({ inputs: { x: o }, backend: t, attrs: { shape: l } }), h = Pt({ inputs: { x: d }, backend: t, attrs: { perm: u } }), g = ue({ inputs: { x: h }, backend: t, attrs: { shape: c } }), x = Zs({ inputs: { x: g }, backend: t, attrs: { begin: p, size: m } });
return f.push(d), f.push(h), f.push(g), f.forEach((y) => t.disposeIntermediateTensorInfo(y)), x;
};
var OM = { kernelName: ri, backendName: "webgl", kernelFunc: hQ };
function gQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, weights: s } = e, { size: a } = n, i = t.readSync(o.dataId), l = t.readSync(s.dataId), u = Yy(i, l, s.dtype, s.shape, a);
return t.makeTensorInfo([a], s.dtype, u);
}
var PM = { kernelName: jc, backendName: "webgl", kernelFunc: gQ };
function xQ(r) {
let { inputs: e, backend: t } = r, { s0: n, s1: o } = e, s = t.readSync(n.dataId), a = t.readSync(o.dataId), i = I.assertAndGetBroadcastShape(Array.from(s), Array.from(a));
return t.makeTensorInfo([i.length], "int32", Int32Array.from(i));
}
var MM = { kernelName: Hc, backendName: "webgl", kernelFunc: xQ };
var yQ = "return float(a != b);";
var gI = at({ opSnippet: yQ, cpuKernelImpl: xP, dtype: "bool" });
var LM = { kernelName: la, backendName: "webgl", kernelFunc: gI };
function tl(r) {
let { inputs: e, backend: t } = r, { input: n } = e, o = t.texData.get(n.dataId);
return Qt({ inputs: { x: o.complexTensorInfos.real }, backend: t });
}
var zM = { kernelName: mp, backendName: "webgl", kernelFunc: tl };
var bQ = "return float(int(x));";
function BM(r, e) {
let t = new En(r.shape, bQ), n = e.runWebGLProgram(t, [r], "int32");
return { dataId: n.dataId, shape: n.shape, dtype: n.dtype };
}
function xI(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { dtype: s } = n;
if (s === "complex64") {
if (o.dtype === "complex64")
return Qt({ inputs: { x: o }, backend: t });
let a = yt(o.shape), i = xI({ inputs: { x: o }, backend: t, attrs: { dtype: "float32" } }), l = An({ inputs: { real: i, imag: a }, backend: t });
return a.dispose(), t.disposeIntermediateTensorInfo(i), l;
}
if (o.dtype === "complex64") {
let a = tl({ inputs: { input: o }, backend: t }), i = xI({ inputs: { x: a }, backend: t, attrs: { dtype: s } });
return t.disposeIntermediateTensorInfo(a), i;
}
if (!b.hasEncodingLoss(o.dtype, s)) {
let a = Qt({ inputs: { x: o }, backend: t });
return { dataId: a.dataId, shape: a.shape, dtype: s };
}
if (s === "int32")
return BM(o, t);
if (s === "bool") {
let a = t.makeTensorInfo([], "bool", b.getTypedArrayFromDType("bool", 1)), l = gI({ inputs: { a: o, b: a }, backend: t });
return t.disposeIntermediateTensorInfo(a), l;
}
throw new Error(`Error in Cast: failed to cast ${o.dtype} to ${s}`);
}
var VM = { kernelName: eo, backendName: "webgl", kernelFunc: xI };
var GM = "return ceil(x);";
var wQ = ve({ opSnippet: GM, packedOpSnippet: GM, cpuKernelImpl: JO });
var WM = { kernelName: Po, backendName: "webgl", kernelFunc: wQ };
var yI = class {
constructor(e) {
this.variableNames = ["A"], this.customUniforms = [{ name: "minVal", type: "float" }, { name: "maxVal", type: "float" }], this.outputShape = e, this.userCode = `
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
`;
}
};
var bI = class {
constructor(e) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "minVal", type: "float" }, { name: "maxVal", type: "float" }], this.outputShape = e, this.userCode = `
void main() {
vec4 value = getAAtOutCoords();
if (any(isnan(value))) {
setOutput(value);
return;
}
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
`;
}
};
function _Q(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { clipValueMin: s, clipValueMax: a } = n, i;
U().getBool("WEBGL_PACK_CLIP") ? i = new bI(o.shape) : i = new yI(o.shape);
let l = [[s], [a]];
return t.runWebGLProgram(i, [o], o.dtype, l);
}
var UM = { kernelName: to, backendName: "webgl", kernelFunc: _Q };
var wI = class {
constructor(e) {
this.variableNames = ["real", "imag"], this.outputShape = e, this.userCode = `
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
}
`;
}
};
function jM(r, e) {
return { dataId: e.dataId, dtype: e.dtype, shape: r.shape };
}
function kQ(r) {
let { inputs: e, backend: t } = r, { x: n } = e, o = t.texData.get(n.dataId), s = new wI(n.shape), a = [jM(n, o.complexTensorInfos.real), jM(n, o.complexTensorInfos.imag)];
return t.runWebGLProgram(s, a, a[0].dtype);
}
var HM = { kernelName: dl, backendName: "webgl", kernelFunc: kQ };
var _I = class {
constructor(e) {
this.outputShape = [], this.outputShape = I.computeOutShape(e, 1), this.variableNames = e.map((a, i) => `T${i}`);
let t = new Array(e.length - 1);
t[0] = e[0][1];
for (let a = 1; a < t.length; a++)
t[a] = t[a - 1] + e[a][1];
let n = [`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];
for (let a = 1; a < t.length; a++) {
let i = t[a - 1];
n.push(`else if (yC < ${t[a]}) setOutput(getT${a}(yR, yC-${i}));`);
}
let o = t.length, s = t[t.length - 1];
n.push(`else setOutput(getT${o}(yR, yC-${s}));`), this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${n.join(`
`)}
}
`;
}
};
var kI = class {
constructor(e, t) {
this.packedInputs = true, this.packedOutput = true, this.outputShape = [], this.outputShape = I.computeOutShape(e, t);
let n = this.outputShape, o = n.length, s = Ue(o), a = Jt("coords", o), i = ["x", "y", "z", "w", "u", "v"].slice(0, o);
this.variableNames = e.map((h, g) => `T${g}`);
let l = new Array(e.length - 1);
l[0] = e[0][t];
for (let h = 1; h < l.length; h++)
l[h] = l[h - 1] + e[h][t];
let u = i[t], c = i.slice(-2), p = i.join(), m = `if (${u} < ${l[0]}) {
return getChannel(
getT0(${p}), vec2(${c.join()}));
}`;
for (let h = 1; h < l.length; h++) {
let g = l[h - 1];
m += `
if (${u} < ${l[h]} && ${u} >= ${l[h - 1]}) {
return getChannel(
getT${h}(${ib(i, u, g)}),
vec2(${ib(c, u, g)}));
}`;
}
let f = l.length, d = l[l.length - 1];
m += `
return getChannel(
getT${f}(${ib(i, u, d)}),
vec2(${ib(c, u, d)}));`, this.userCode = `
float getValue(${i.map((h) => "int " + h)}) {
${m}
}
void main() {
${s} coords = getOutputCoords();
vec4 result = vec4(getValue(${a}), 0., 0., 0.);
${a[o - 1]} = ${a[o - 1]} + 1;
if (${a[o - 1]} < ${n[o - 1]}) {
result.g = getValue(${a});
}
${a[o - 2]} = ${a[o - 2]} + 1;
if (${a[o - 2]} < ${n[o - 2]}) {
result.a = getValue(${a});
}
${a[o - 1]} = ${a[o - 1]} - 1;
if (${a[o - 2]} < ${n[o - 2]} &&
${a[o - 1]} < ${n[o - 1]}) {
result.b = getValue(${a});
}
setOutput(result);
}
`;
}
};
function ib(r, e, t) {
let n = r.indexOf(e);
return r.map((s, a) => a === n ? `${s} - ${t}` : s).join();
}
function Ic(r) {
let { inputs: e, backend: t } = r, { input: n } = e, o = t.texData.get(n.dataId);
return Qt({ inputs: { x: o.complexTensorInfos.imag }, backend: t });
}
var qM = { kernelName: sp, backendName: "webgl", kernelFunc: Ic };
function Sc(r, e, t) {
let n = r[0].dtype;
if (n === "complex64") {
let c = r.map((h) => tl({ inputs: { input: h }, backend: t })), p = r.map((h) => Ic({ inputs: { input: h }, backend: t })), m = Sc(c, e, t), f = Sc(p, e, t), d = An({ inputs: { real: m, imag: f }, backend: t });
return c.forEach((h) => t.disposeIntermediateTensorInfo(h)), p.forEach((h) => t.disposeIntermediateTensorInfo(h)), t.disposeIntermediateTensorInfo(m), t.disposeIntermediateTensorInfo(f), d;
}
let o = t.shouldExecuteOnCPU(r);
if (n === "string" && (o = true), o) {
let c = r.map((x) => {
let y = b.sizeFromShape(x.shape.slice(e));
return ue({ inputs: { x }, backend: t, attrs: { shape: [-1, y] } });
}), p = c.map((x) => ({ vals: t.readSync(x.dataId), shape: x.shape })), m = I.computeOutShape(c.map((x) => x.shape), 1), f = c[0].shape[0] === 1, d = QO(p, m, n, f), h = I.computeOutShape(r.map((x) => x.shape), e), g = t.makeTensorInfo(h, n, d);
return c.forEach((x) => t.disposeIntermediateTensorInfo(x)), g;
}
if (r.length > U().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")) {
let c = Math.floor(r.length / 2), p = Sc(r.slice(0, c), e, t), m = Sc(r.slice(c), e, t), f = Sc([p, m], e, t);
return t.disposeIntermediateTensorInfo(p), t.disposeIntermediateTensorInfo(m), f;
}
if (U().getBool("WEBGL_PACK_ARRAY_OPERATIONS") && r[0].shape.length > 1) {
let c = new kI(r.map((p) => p.shape), e);
return t.runWebGLProgram(c, r, n);
}
let { tensors2D: s, outShape: a } = vQ(r, e, t), i = new _I(s.map((c) => c.shape)), l = t.runWebGLProgram(i, s, n);
s.forEach((c) => t.disposeIntermediateTensorInfo(c));
let u = ue({ inputs: { x: l }, attrs: { shape: a }, backend: t });
return t.disposeIntermediateTensorInfo(l), u;
}
function vQ(r, e, t) {
let n = I.computeOutShape(r.map((s) => s.shape), e);
return { tensors2D: r.map((s) => ue({ inputs: { x: s }, attrs: { shape: [-1, b.sizeFromShape(s.shape.slice(e))] }, backend: t })), outShape: n };
}
function vI(r) {
let { inputs: e, backend: t, attrs: n } = r, { axis: o } = n, s = b.parseAxisParam(o, e[0].shape)[0], a = I.computeOutShape(e.map((u) => u.shape), s);
if (b.sizeFromShape(a) === 0)
return t.makeTensorInfo(a, e[0].dtype, []);
let i = e.filter((u) => b.sizeFromShape(u.shape) > 0);
if (i.length === 1)
return Qt({ inputs: { x: i[0] }, backend: t });
let l = i.map((u) => u.shape);
return I.assertParamsConsistent(l, s), Sc(i, s, t);
}
var KM = { kernelName: ni, backendName: "webgl", kernelFunc: vI };
var Kh = class {
constructor(e, t = false, n = null, o = false, s = false) {
this.variableNames = ["x", "W"], this.outputShape = e.outShape;
let a = e.padInfo.top, i = e.padInfo.left, l = e.strideHeight, u = e.strideWidth, c = e.dilationHeight, p = e.dilationWidth, m = e.filterHeight, f = e.filterWidth, d = Math.floor(e.inChannels / 4) * 4, h = e.inChannels % 4, g = e.dataFormat === "channelsLast", x = g ? 1 : 2, y = g ? 2 : 3, w = g ? 3 : 1, _ = "", C = "";
n && (o ? _ = `float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}` : s ? _ = `float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${n}
}` : _ = `
float activation(float x) {
${n}
}
`, C = "result = activation(result);");
let A = t ? "result += getBiasAtOutCoords();" : "";
t && this.variableNames.push("bias"), o && this.variableNames.push("preluActivationWeights"), s && this.variableNames.push("leakyreluAlpha"), this.userCode = `
${_}
const ivec2 strides = ivec2(${l}, ${u});
const ivec2 pads = ivec2(${a}, ${i});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${w}];
ivec2 xRCCorner =
ivec2(coords[${x}], coords[${y}]) * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${m}; wR++) {
int xR = xRCorner + wR * ${c};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${f}; wC++) {
int xC = xCCorner + wC * ${p};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${d}; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
if (${g}) {
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
if (${h === 1}) {
if (${g}) {
dotProd +=
getX(batch, xR, xC, ${d}) *
getW(wR, wC, ${d}, d2);
} else {
dotProd +=
getX(batch, ${d}, xR, xC) *
getW(wR, wC, ${d}, d2);
}
} else if (${h === 2}) {
vec2 wValues = vec2(
getW(wR, wC, ${d}, d2),
getW(wR, wC, ${d} + 1, d2)
);
if (${g}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${d}),
getX(batch, xR, xC, ${d} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${d}, xR, xC),
getX(batch, ${d} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (${h === 3}) {
vec3 wValues = vec3(
getW(wR, wC, ${d}, d2),
getW(wR, wC, ${d} + 1, d2),
getW(wR, wC, ${d} + 2, d2)
);
if (${g}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${d}),
getX(batch, xR, xC, ${d} + 1),
getX(batch, xR, xC, ${d} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${d}, xR, xC),
getX(batch, ${d} + 1, xR, xC),
getX(batch, ${d} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
${A}
${C}
setOutput(result);
}
`;
}
};
var CI = class {
constructor(e) {
this.variableNames = ["x", "W"], this.outputShape = e.outShape;
let t = e.padInfo.front, n = e.padInfo.top, o = e.padInfo.left, s = e.strideDepth, a = e.strideHeight, i = e.strideWidth, l = e.dilationDepth, u = e.dilationHeight, c = e.dilationWidth, p = e.filterDepth, m = e.filterHeight, f = e.filterWidth, d = Math.floor(e.inChannels / 4) * 4, h = e.inChannels % 4;
this.userCode = `
const ivec3 strides = ivec3(${s}, ${a}, ${i});
const ivec3 pads = ivec3(${t}, ${n}, ${o});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
for (int wF = 0; wF < ${p}; wF++) {
int xF = xFCorner + wF * ${l};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${m}; wR++) {
int xR = xRCorner + wR * ${u};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${f}; wC++) {
int xC = xCCorner + wC * ${c};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${d}; d1 += 4) {
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
dotProd += dot(xValues, wValues);
}
if (${h === 1}) {
dotProd +=
getX(batch, xF, xR, xC, ${d}) *
getW(wF, wR, wC, ${d}, d2);
} else if (${h === 2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${d}),
getX(batch, xF, xR, xC, ${d} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${d}, d2),
getW(wF, wR, wC, ${d} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${h === 3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${d}),
getX(batch, xF, xR, xC, ${d} + 1),
getX(batch, xF, xR, xC, ${d} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${d}, d2),
getW(wF, wR, wC, ${d} + 1, d2),
getW(wF, wR, wC, ${d} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
`;
}
};
var II = class {
constructor(e, t) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "inputShape", type: "ivec3" }, { name: "pad", type: "ivec2" }, { name: "stride", type: "ivec2" }, { name: "dilation", type: "ivec2" }, { name: "inChannels", type: "int" }, { name: "itemsPerBlockRow", type: "int" }, { name: "outWidth", type: "int" }], this.outputShape = e, this.enableShapeUniforms = jt(this.outputShape.length);
let { dataFormat: n } = t, o = Gt(), s = n === "channelsLast", a = s ? 0 : 1, i = s ? 1 : 2, l = this.enableShapeUniforms ? "if(blockIndex < outShape[1] && pos < outShape[0]) {" : `if(blockIndex < ${e[1]} && pos < ${e[0]}) {`, u = "";
for (let c = 0; c <= 1; c++)
for (let p = 0; p <= 1; p++)
u += `
blockIndex = rc.y + ${p};
pos = rc.x + ${c};
${l}
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
if(d0 < inputShape[${a}] && d0 >= 0) {
// Use custom imod instead mod. On Intel GPU, mod may generate
// unexpected value.
// https://github.com/tensorflow/tfjs/issues/5447
offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
inChannels);
if(d1 < inputShape[${i}] && d1 >= 0) {
ch = imod(pos, inChannels);
if (${s}) {
innerDims = vec2(d1, ch);
result[${c * 2 + p}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${c * 2 + p}] = getChannel(
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;
this.userCode = `
void main() {
ivec2 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
${u}
${o.output} = result;
}
`;
}
};
function ab({ x: r, filter: e, convInfo: t, backend: n, bias: o = null, preluActivationWeights: s = null, leakyreluAlpha: a = 0, activation: i = null }) {
let l = r.shape, u = n.texData.get(r.dataId), c = t.inChannels, p = l[0] * l[1] * l[2], m = t.outChannels, f = t.dataFormat === "channelsLast", d = false, h = false, g, x = [];
if (!((p === 1 || m === 1) && c > oI) && u.isPacked && f && u.texture != null && l[2] % 2 != 0 && b.arraysEqual(u.shape.slice(-3), l.slice(-3))) {
let _ = l[0] * l[1] * (l[2] + 1), C = { dataId: r.dataId, shape: [1, _, t.inChannels], dtype: r.dtype }, A = u.shape;
u.shape = u.shape.slice(), u.shape[u.shape.length - 2]++, b.assert(ql(u.shape, C.shape), () => `packed reshape ${u.shape} to ${C.shape} isn't free`);
let D = ue({ inputs: { x: e }, backend: n, attrs: { shape: [1, t.inChannels, t.outChannels] } });
x.push(D);
let R = vc({ a: C, b: D, backend: n, transposeA: d, transposeB: h, bias: o, activation: i, preluActivationWeights: s, leakyreluAlpha: a }), P = n.texData.get(R.dataId);
b.assert(P.isPacked, () => "batchMatMul result is expected to be packed"), u.shape = A, P.shape = t.outShape, g = Qt({ inputs: { x: R }, backend: n }), g.shape = t.outShape, x.push(R);
} else {
let _ = f ? l[0] * l[1] * l[2] : l[0] * l[2] * l[3], C = ue({ inputs: { x: r }, backend: n, attrs: { shape: [1, _, t.inChannels] } }), A = ue({ inputs: { x: e }, backend: n, attrs: { shape: [1, t.inChannels, t.outChannels] } }), D = vc({ a: C, b: A, transposeA: d, transposeB: h, backend: n, bias: o, activation: i, preluActivationWeights: s, leakyreluAlpha: a });
g = ue({ inputs: { x: D }, backend: n, attrs: { shape: t.outShape } }), x.push(C), x.push(A), x.push(D);
}
for (let _ of x)
n.disposeIntermediateTensorInfo(_);
return g;
}
function lb({ x: r, filter: e, convInfo: t, backend: n, bias: o = null, preluActivationWeights: s = null, leakyreluAlpha: a = 0, activation: i = null }) {
let { filterWidth: l, filterHeight: u, inChannels: c, outWidth: p, outHeight: m, dataFormat: f } = t, d = f === "channelsLast", h = l * u * c, g = m * p, x = [h, g], y = true, w = false, _ = [], C = ue({ inputs: { x: r }, backend: n, attrs: { shape: r.shape.slice(1) } }), A = ue({ inputs: { x: e }, backend: n, attrs: { shape: [1, h, b.sizeFromShape(e.shape) / h] } });
_.push(C), _.push(A);
let D = new II(x, t), R = [C.shape, [t.padInfo.top, t.padInfo.left], [t.strideHeight, t.strideWidth], [t.dilationHeight, t.dilationWidth], [t.inChannels], [t.filterWidth * t.inChannels], [t.outWidth]], P = n.runWebGLProgram(D, [C], "float32", R), L = ue({ inputs: { x: P }, backend: n, attrs: { shape: [1, x[0], x[1]] } });
_.push(P), _.push(L);
let G = o != null, W = s != null, j = i === "leakyrelu", H = i ? Xl(i, true) : null, q = new Hh(L.shape, A.shape, [1, g, t.outChannels], y, w, G, H, W, j), X = [L, A];
if (o && X.push(o), W && X.push(s), j) {
let se = n.makeTensorInfo([], "float32", b.createScalarValue(a, "float32"));
X.push(se), _.push(se);
}
let re = n.runWebGLProgram(q, X, "float32"), J = d ? [1, m, p, t.outChannels] : [1, t.outChannels, m, p], oe = ue({ inputs: { x: re }, backend: n, attrs: { shape: J } });
_.push(re);
for (let se of _)
n.disposeIntermediateTensorInfo(se);
return oe;
}
function CQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, filter: s } = e, { strides: a, pad: i, dataFormat: l, dilations: u, dimRoundingMode: c } = n, p = I.convertConv2DDataFormat(l), m = I.computeConv2DInfo(o.shape, s.shape, a, u, i, c, false, p), f;
if (m.filterHeight === 1 && m.filterWidth === 1 && m.dilationHeight === 1 && m.dilationWidth === 1 && m.strideHeight === 1 && m.strideWidth === 1 && (m.padInfo.type === "SAME" || m.padInfo.type === "VALID"))
f = ab({ x: o, filter: s, convInfo: m, backend: t });
else if (U().getBool("WEBGL_CONV_IM2COL") && o.shape[0] === 1)
f = lb({ x: o, filter: s, convInfo: m, backend: t });
else {
let h = new Kh(m);
f = t.runWebGLProgram(h, [o, s], "float32");
}
let d = ue({ inputs: { x: f }, backend: t, attrs: { shape: m.outShape } });
return t.disposeIntermediateTensorInfo(f), d;
}
var XM = { kernelName: Mo, backendName: "webgl", kernelFunc: CQ };
var SI = class {
constructor(e) {
this.variableNames = ["x", "dy"], this.outputShape = e.filterShape;
let t = e.strideHeight, n = e.strideWidth, o = e.padInfo.top, s = e.padInfo.left, a = e.dataFormat === "channelsLast";
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${o};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${s};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
if (${a}) {
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`;
}
};
var NI = class {
constructor(e) {
this.variableNames = ["dy", "W"], this.outputShape = e.inShape;
let t = e.filterHeight, n = e.filterWidth, o = e.strideHeight, s = e.strideWidth, a = e.dataFormat === "channelsLast", i = t - 1 - e.padInfo.top, l = n - 1 - e.padInfo.left, u = a ? 1 : 2, c = a ? 2 : 3, p = a ? 3 : 1;
this.userCode = `
const ivec2 pads = ivec2(${i}, ${l});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${p}];
ivec2 dyCorner = ivec2(coords[${u}], coords[${c}]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${o}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
if (${a}) {
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`;
}
};
var TI = class {
constructor(e) {
this.variableNames = ["x", "dy"], this.outputShape = e.filterShape;
let t = e.strideDepth, n = e.strideHeight, o = e.strideWidth, s = e.padInfo.front, a = e.padInfo.top, i = e.padInfo.left;
this.userCode = `
void main() {
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yF = 0; yF < ${e.outDepth}; yF++) {
int xF = wF + yF * ${t} - ${s};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${n} - ${a};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${o} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`;
}
};
var EI = class {
constructor(e) {
this.variableNames = ["dy", "W"], this.outputShape = e.inShape;
let t = e.filterDepth, n = e.filterHeight, o = e.filterWidth, s = e.strideDepth, a = e.strideHeight, i = e.strideWidth, l = t - 1 - e.padInfo.front, u = n - 1 - e.padInfo.top, c = o - 1 - e.padInfo.left;
this.userCode = `
const ivec3 pads = ivec3(${l}, ${u}, ${c});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < ${t}; wF++) {
float dyF = float(dyFCorner + wF) / ${s}.0;
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
int wFPerm = ${t} - 1 - wF;
for (int wR = 0; wR < ${n}; wR++) {
float dyR = float(dyRCorner + wR) / ${a}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${n} - 1 - wR;
for (int wC = 0; wC < ${o}; wC++) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${o} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`;
}
};
function IQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, dy: s } = e, { strides: a, pad: i, dataFormat: l, dimRoundingMode: u, filterShape: c } = n, p = I.convertConv2DDataFormat(l), m = I.computeConv2DInfo(o.shape, c, a, 1, i, u, false, p), f = new SI(m);
return t.runWebGLProgram(f, [o, s], "float32");
}
var YM = { kernelName: Kc, backendName: "webgl", kernelFunc: IQ };
function SQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, filter: s } = e, { inputShape: a, strides: i, pad: l, dataFormat: u, dimRoundingMode: c } = n, p = I.convertConv2DDataFormat(u), m = I.computeConv2DInfo(a, s.shape, i, 1, l, c, false, p), f = new NI(m);
return t.runWebGLProgram(f, [o, s], "float32");
}
var ZM = { kernelName: Lo, backendName: "webgl", kernelFunc: SQ };
function NQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, filter: s } = e, { strides: a, pad: i, dilations: l } = n, u = I.computeConv3DInfo(o.shape, s.shape, a, l, i), c = new CI(u);
return t.runWebGLProgram(c, [o, s], "float32");
}
var JM = { kernelName: hl, backendName: "webgl", kernelFunc: NQ };
function TQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, dy: s } = e, { strides: a, pad: i, filterShape: l } = n, u = I.computeConv3DInfo(o.shape, l, a, 1, i), c = new TI(u);
return t.runWebGLProgram(c, [o, s], "float32");
}
var QM = { kernelName: Xc, backendName: "webgl", kernelFunc: TQ };
function EQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, filter: s } = e, { pad: a, strides: i, inputShape: l } = n, u = I.computeConv3DInfo(l, s.shape, i, 1, a), c = new EI(u);
return t.runWebGLProgram(c, [o, s], "float32");
}
var eL = { kernelName: Yc, backendName: "webgl", kernelFunc: EQ };
var AQ = tb + `
return cos(x);
`;
var DQ = ve({ opSnippet: AQ });
var tL = { kernelName: zo, backendName: "webgl", kernelFunc: DQ };
var $Q = `
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`;
var RQ = ve({ opSnippet: $Q });
var rL = { kernelName: Bo, backendName: "webgl", kernelFunc: RQ };
var AI = class {
constructor(e, t, n, o, s) {
this.variableNames = ["Image", "Boxes", "BoxInd"], this.outputShape = [];
let [a, i, l, u] = e, [c] = t, [p, m] = n;
this.outputShape = [c, p, m, u];
let f = o === "bilinear" ? 1 : 0, [d, h] = [`${i - 1}.0`, `${l - 1}.0`], [g, x, y] = p > 1 ? [`${(i - 1) / (p - 1)}`, "(y2-y1) * height_ratio", `y1*${d} + float(y)*(height_scale)`] : ["0.0", "0.0", `0.5 * (y1+y2) * ${d}`], [w, _, C] = m > 1 ? [`${(l - 1) / (m - 1)}`, "(x2-x1) * width_ratio", `x1*${h} + float(x)*(width_scale)`] : ["0.0", "0.0", `0.5 * (x1+x2) * ${h}`];
this.userCode = `
const float height_ratio = float(${g});
const float width_ratio = float(${w});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${a}) {
return;
}
float height_scale = ${x};
float width_scale = ${_};
float in_y = ${y};
if( in_y < 0.0 || in_y > ${d} ) {
setOutput(float(${s}));
return;
}
float in_x = ${C};
if( in_x < 0.0 || in_x > ${h} ) {
setOutput(float(${s}));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${f} == 1) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
}
`;
}
};
var FQ = (r) => {
let { inputs: e, backend: t, attrs: n } = r, { image: o, boxes: s, boxInd: a } = e, { cropSize: i, method: l, extrapolationValue: u } = n, c = new AI(o.shape, s.shape, i, l, u);
return t.runWebGLProgram(c, [o, s, a], "float32");
};
var nL = { kernelName: Hi, backendName: "webgl", kernelFunc: FQ };
var ub = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.customUniforms = [{ name: "index", type: "float" }], this.outputShape = e;
let o = e.length, s = t ? "0.0" : `getX(${oL(o, "coords")})`, a = e[e.length - 1], i = "", l = "";
t ? (i = n ? `end != ${a - 1}` : "end != 0", l = n ? "end + 1" : "end - 1") : (i = n ? `end + pow2 < ${a}` : "end >= pow2", l = n ? "end + pow2" : "end - pow2"), this.userCode = `
void main() {
${Ue(o)} coords = getOutputCoords();
int end = ${sL(o, "coords")};
float val = ${s};
int pow2 = int(pow(2.0, index));
if (${i}) {
int idx = ${l};
${sL(o, "coords")} = idx;
val += getX(${oL(o, "coords")});
}
setOutput(val);
}
`;
}
};
function oL(r, e) {
if (r === 1)
return `${e}`;
if (r === 2)
return `${e}.x, ${e}.y`;
if (r === 3)
return `${e}.x, ${e}.y, ${e}.z`;
if (r === 4)
return `${e}.x, ${e}.y, ${e}.z, ${e}.w`;
throw Error(`Cumulative sum for rank ${r} is not yet supported`);
}
function sL(r, e) {
if (r === 1)
return `${e}`;
if (r === 2)
return `${e}.y`;
if (r === 3)
return `${e}.z`;
if (r === 4)
return `${e}.w`;
throw Error(`Cumulative sum for rank ${r} is not yet supported`);
}
function OQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, exclusive: a, reverse: i } = n, l = o.shape.length, u = I.getAxesPermutation([s], l), c = o;
u != null && (c = Pt({ inputs: { x: o }, backend: t, attrs: { perm: u } }));
let p = I.getInnerMostAxes(1, l)[0];
if (p !== l - 1)
throw new Error(`WebGL cumsum shader expects an inner-most axis=${o.shape.length - 1} but got axis=${s}`);
let m = c.shape[p], f = Qt({ inputs: { x: c }, backend: t });
for (let d = 0; d <= Math.ceil(Math.log2(m)) - 1; d++) {
let h = new ub(c.shape, false, i), g = [[d]], x = f;
f = t.runWebGLProgram(h, [f], f.dtype, g), t.disposeIntermediateTensorInfo(x);
}
if (a) {
let d = new ub(c.shape, a, i), h = f;
f = t.runWebGLProgram(d, [f], f.dtype), t.disposeIntermediateTensorInfo(h);
}
if (u != null) {
let d = I.getUndoAxesPermutation(u), h = Pt({ inputs: { x: f }, backend: t, attrs: { perm: d } });
return t.disposeIntermediateTensorInfo(f), t.disposeIntermediateTensorInfo(c), h;
}
return f;
}
var iL = { kernelName: Vo, backendName: "webgl", kernelFunc: OQ };
function PQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, weights: s } = e, { size: a, binaryOutput: i } = n;
if (o.shape.length === 1) {
let l = t.readSync(o.dataId), u = t.readSync(s.dataId), c = Yy(l, u, s.dtype, s.shape, a);
return t.makeTensorInfo([a], s.dtype, c);
} else if (o.shape.length === 2) {
let l = t.bufferSync(o), u = t.bufferSync(s), c = ZO(l, u, a, i);
return t.makeTensorInfo(c.shape, s.dtype, c.values);
}
throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`);
}
var aL = { kernelName: Zc, backendName: "webgl", kernelFunc: PQ };
var DI = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.outputShape = [], this.outputShape = e, this.blockSize = t, this.dataFormat = n, this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
int in_h = h / ${t};
int offset_h = imod(h, ${t});
int in_w = w / ${t};
int offset_w = imod(w, ${t});
int offset_d = (offset_h * ${t} + offset_w) *
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
}
`;
}
getHeightCoordString() {
return this.dataFormat === "NHWC" ? "coords[1]" : "coords[2]";
}
getWidthCoordString() {
return this.dataFormat === "NHWC" ? "coords[2]" : "coords[3]";
}
getDepthCoordString() {
return this.dataFormat === "NHWC" ? "coords[3]" : "coords[1]";
}
getOutputDepthSize() {
return this.dataFormat === "NHWC" ? this.outputShape[3] : this.outputShape[1];
}
getInputSamplingString() {
return this.dataFormat === "NHWC" ? "getX(b, in_h, in_w, in_d)" : "getX(b, in_d, in_h, in_w)";
}
};
function MQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { blockSize: s, dataFormat: a } = n, i = o.shape[0], l = a === "NHWC" ? o.shape[1] : o.shape[2], u = a === "NHWC" ? o.shape[2] : o.shape[3], c = a === "NHWC" ? o.shape[3] : o.shape[1], p = l * s, m = u * s, f = c / (s * s), d = a === "NHWC" ? [i, p, m, f] : [i, f, p, m], h = new DI(d, s, a);
return t.runWebGLProgram(h, [o], o.dtype);
}
var lL = { kernelName: qi, backendName: "webgl", kernelFunc: MQ };
var Xh = class {
constructor(e, t = false, n = null, o = false, s = false) {
this.variableNames = ["x", "W"], this.customUniforms = [{ name: "pads", type: "ivec2" }, { name: "strides", type: "ivec2" }, { name: "dilations", type: "ivec2" }, { name: "inDims", type: "ivec2" }], this.outputShape = e.outShape, this.enableShapeUniforms = jt(this.outputShape.length);
let a = e.filterHeight, i = e.filterWidth, l = e.outChannels / e.inChannels, u = "", c = "";
n && (o ? u = `float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}` : s ? u = `float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${n}
}` : u = `
float activation(float x) {
${n}
}
`, c = "result = activation(result);");
let p = t ? "result += getBiasAtOutCoords();" : "";
t && this.variableNames.push("bias"), o && this.variableNames.push("preluActivationWeights"), s && this.variableNames.push("leakyreluAlpha"), this.userCode = `
${u}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${l};
int q = d2 - d1 * ${l};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < ${a}; wR++) {
int xR = xRCorner + wR * dilations[0];
if (xR < 0 || xR >= inDims[0]) {
continue;
}
for (int wC = 0; wC < ${i}; wC++) {
int xC = xCCorner + wC * dilations[1];
if (xC < 0 || xC >= inDims[1]) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
${p}
${c}
setOutput(result);
}
`;
}
};
var Yh = class {
constructor(e, t = false, n = null, o = false, s = false) {
this.variableNames = ["x", "W"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "pads", type: "ivec2" }, { name: "strides", type: "ivec2" }, { name: "dilations", type: "ivec2" }, { name: "inDims", type: "ivec2" }], this.outputShape = e.outShape, this.enableShapeUniforms = jt(this.outputShape.length);
let a = e.outChannels / e.inChannels, i = e.padInfo.left, l = e.strideWidth, u = e.dilationWidth, c = e.filterHeight, p = e.filterWidth, m = p, f = `
int xR; int xC; int xCOffset;
vec4 wTexel; vec4 previous; vec4 final;`;
for (let x = 0; x < p; x++)
f += `
vec4 xTexelC${x * 2};
int xTexelC${x * 2}Ready;
vec4 xTexelC${x * 2 + 1};
int xTexelC${x * 2 + 1}Ready;
vec4 xC${x};`;
f += `
for (int r = 0; r < ${c}; r++) {
`;
for (let x = 0; x < p; x++)
f += `
xTexelC${x * 2} = vec4(0.0);
xTexelC${x * 2}Ready = 0;
xTexelC${x * 2 + 1} = vec4(0.0);
xTexelC${x * 2 + 1}Ready = 0;
xC${x} = vec4(0.0);`;
f += `
xR = xRCorner + r * dilations[0];
if (xR >=0 && xR < inDims[0]) {
`;
for (let x = 0; x < (m + 1) / 2; x++) {
let y = x * 2;
if (f += `
xC = xCCorner + ${y * u};
`, l === 1) {
if (y < p && (i % 2 == 1 ? (f += `
xCOffset = xC + 1;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
}
xTexelC${y}Ready = 1;
}
`, u === 1 && y > 0 ? f += `
xC${y} = vec4(xTexelC${y - 2}.zw, xTexelC${y}.xy);
` : f += `
xCOffset = xC + 1 - 2;
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
previous.zw = vec2(0.0);
}
xC${y} = vec4(previous.zw, xTexelC${y}.xy);
} else {
xC${y} = vec4(0.0, 0.0, xTexelC${y}.xy);
}
`) : f += `
if (xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
}
xTexelC${y}Ready = 1;
}
xC${y} = xTexelC${y};
`, y + 1 < p)) {
let w = i % 2 == 0 ? b.nearestLargerEven(u) : u;
u % 2 == 0 && i % 2 == 1 || u % 2 != 0 && i % 2 != 1 ? (f += `
xCOffset = xC + imod(pads[1], 2) + ${w};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y + 1}Ready == 0) {
xTexelC${y + 1} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y + 1}.zw = vec2(0.0);
}
xTexelC${y + 1}Ready = 1;
}
`, u > 1 && (f += `
xCOffset -= 2;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xCOffset, d1);
xTexelC${y}Ready = 1;
}
`), f += `
xC${y + 1} = vec4(xTexelC${y}.zw, xTexelC${y + 1}.xy);
`) : w === 1 ? f += `
xC${y + 1} = xTexelC${y};
` : f += `
xCOffset = xC + ${w};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y + 1}Ready == 0) {
xTexelC${y + 1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y + 1}.zw = vec2(0.0);
}
xTexelC${y + 1}Ready = 1;
}
xC${y + 1} = xTexelC${y + 1};
`;
}
} else
y < p && (i % 2 == 1 ? (f += `
xCOffset = xC + 1 - strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
}
xTexelC${y}Ready = 1;
}
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${y + 1}Ready == 0) {
xTexelC${y + 1} = getX(batch, xR, xC + 1, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xC + 2 >= inDims[1]) {
xTexelC${y + 1}.zw = vec2(0.0);
}
xTexelC${y + 1}Ready = 1;
}
xC${y} = vec4(xTexelC${y}.zw, xTexelC${y + 1}.zw);
`, y + 1 < p && (f += `
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
xC${y + 1} = vec4(xTexelC${y + 1}.xy, final.xy);
`)) : (f += `
if(xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
}
xTexelC${y}Ready = 1;
}
xCOffset = xC + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y + 1}Ready == 0) {
xTexelC${y + 1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y + 1}.zw = vec2(0.);
}
xTexelC${y + 1}Ready = 1;
}
xC${y} = vec4(
xTexelC${y}.xy, xTexelC${y + 1}.xy);
`, y + 1 < p && (f += `
xC${y + 1} = vec4(xTexelC${y}.zw, xTexelC${y + 1}.zw);
`)));
y < p && (f += `
wTexel = getW(r, ${y}, d1, q);
dotProd += xC${y} * vec4(wTexel.xz, wTexel.xz);
`, y + 1 < p && (f += `
wTexel = getW(r, ${y + 1}, d1, q);
dotProd += xC${y + 1} * vec4(wTexel.xz, wTexel.xz);
`));
}
f += `
}
`, f += `
}
`;
let d = "", h = "";
n && (o ? d = `vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${n}
}` : s ? d = `vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${n}
}` : d = `vec4 activation(vec4 x) {
${n}
}`, h = "result = activation(result);");
let g = t ? "result += getBiasAtOutCoords();" : "";
t && this.variableNames.push("bias"), o && this.variableNames.push("preluActivationWeights"), s && this.variableNames.push("leakyreluAlpha"), this.userCode = `
${d}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${a};
int q = d2 - d1 * ${a};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4(0.000000000000001);
${f}
vec4 result = dotProd - vec4(0.000000000000001);
${g}
${h}
setOutput(result);
}
`;
}
};
function LQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, filter: s } = e, { strides: a, pad: i, dilations: l, dimRoundingMode: u } = n, c = l;
c == null && (c = [1, 1]), b.assert(I.eitherStridesOrDilationsAreOne(a, c), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${c}'`);
let p = I.computeConv2DInfo(o.shape, s.shape, a, c, i, u, true), m;
U().getBool("WEBGL_PACK_DEPTHWISECONV") && p.strideWidth <= 2 && p.outChannels / p.inChannels == 1 ? m = new Yh(p) : m = new Xh(p);
let f = [[p.padInfo.top, p.padInfo.left], [p.strideHeight, p.strideWidth], [p.dilationHeight, p.dilationWidth], [p.inHeight, p.inWidth]];
return t.runWebGLProgram(m, [o, s], "float32", f);
}
var uL = { kernelName: Go, backendName: "webgl", kernelFunc: LQ };
var $I = class {
constructor(e) {
this.variableNames = ["x", "dy"], this.outputShape = e.filterShape;
let t = e.strideHeight, n = e.strideWidth, o = e.padInfo.top, s = e.padInfo.left, a = e.outChannels / e.inChannels;
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${a} + dm;
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${o};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${s};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
}
`;
}
};
var RI = class {
constructor(e) {
this.variableNames = ["dy", "W"], this.outputShape = e.inShape;
let t = e.filterHeight, n = e.filterWidth, o = e.strideHeight, s = e.strideWidth, a = t - 1 - e.padInfo.top, i = n - 1 - e.padInfo.left, l = e.outChannels / e.inChannels;
this.userCode = `
const ivec2 pads = ivec2(${a}, ${i});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${o}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${l}; dm++) {
int d2 = d1 * ${l} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`;
}
};
function zQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, dy: s } = e, { strides: a, dilations: i, pad: l, dimRoundingMode: u, filterShape: c } = n, p = I.computeConv2DInfo(o.shape, c, a, i, l, u, true), m = new $I(p);
return t.runWebGLProgram(m, [o, s], "float32");
}
var cL = { kernelName: Jc, backendName: "webgl", kernelFunc: zQ };
function BQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, filter: s } = e, { strides: a, dilations: i, pad: l, dimRoundingMode: u, inputShape: c } = n, p = I.computeConv2DInfo(c, s.shape, a, i, l, u, true), m = new RI(p);
return t.runWebGLProgram(m, [o, s], "float32");
}
var pL = { kernelName: Qc, backendName: "webgl", kernelFunc: BQ };
var FI = class {
constructor(e) {
this.variableNames = ["X"], this.outputShape = [e, e], this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
`;
}
};
function VQ(r) {
let { inputs: e, backend: t } = r, { x: n } = e, o = [...n.shape, ...n.shape], s = b.sizeFromShape(n.shape), a = ue({ inputs: { x: n }, backend: t, attrs: { shape: [s] } }), i = new FI(s), l = t.runWebGLProgram(i, [a], a.dtype), u = ue({ inputs: { x: l }, backend: t, attrs: { shape: o } });
return t.disposeIntermediateTensorInfo(a), t.disposeIntermediateTensorInfo(l), u;
}
var mL = { kernelName: ep, backendName: "webgl", kernelFunc: VQ };
var OI = class {
constructor(e) {
this.variableNames = ["x", "W"], this.outputShape = e.outShape;
let { inHeight: t, inWidth: n, padInfo: o, strideHeight: s, strideWidth: a, filterHeight: i, filterWidth: l, dilationHeight: u, dilationWidth: c } = e, { top: p, left: m } = o;
this.userCode = `
const ivec2 strides = ivec2(${s}, ${a});
const ivec2 pads = ivec2(${p}, ${m});
const float neg_infinity = -3.4e38;
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.w;
ivec2 outTopLeftCorner =
coords.yz * strides - pads;
int hBeg = outTopLeftCorner.x;
int wBeg = outTopLeftCorner.y;
float curVal = neg_infinity;
for (int h = 0; h < ${i}; h++) {
int hIn = hBeg + h * ${u};
if (hIn >= 0 && hIn < ${t}) {
for (int w = 0; w < ${l}; w++) {
int wIn = wBeg + w * ${c};
if (wIn >= 0 && wIn < ${n}) {
float xVal = getX(batch, hIn, wIn, d1);
float wVal = getW(h, w, d1);
float val = xVal + wVal;
if (val > curVal) {
curVal = val;
}
}
}
}
}
float result = curVal;
setOutput(result);
}
`;
}
};
function GQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, filter: s } = e, { strides: a, pad: i, dilations: l } = n, u = I.computeDilation2DInfo(o.shape, s.shape, a, i, "NHWC", l), c, p = new OI(u);
c = t.runWebGLProgram(p, [o, s], "float32");
let m = ue({ inputs: { x: c }, backend: t, attrs: { shape: u.outShape } });
return t.disposeIntermediateTensorInfo(c), m;
}
var fL = { kernelName: gl, backendName: "webgl", kernelFunc: GQ };
function WQ(r) {
let { inputs: e, backend: t, attrs: n } = r, { equation: o } = n, s = e, { allDims: a, summedDims: i, idDims: l } = I.decodeEinsumEquation(o, s.length);
I.checkEinsumDimSizes(a.length, l, s);
let { path: u, steps: c } = I.getEinsumComputePath(i, l), p = c.length, m = null, f = a.length, d = [];
for (let h = 0; h < p; ++h) {
for (let g of c[h]) {
let { permutationIndices: x, expandDims: y } = I.getEinsumPermutation(f, l[g]), w;
I.isIdentityPermutation(x) ? w = s[g] : (w = Pt({ inputs: { x: s[g] }, backend: t, attrs: { perm: x } }), d.push(w));
let _ = w.shape.slice();
for (let C = 0; C < y.length; ++C)
_.splice(y[C], 0, 1);
b.arraysEqual(w.shape, _) || (w = ue({ inputs: { x: w }, backend: t, attrs: { shape: _ } }), d.push(w)), m === null ? m = w : (m = qh({ inputs: { a: w, b: m }, backend: t }), d.push(m));
}
h < p - 1 && (u[h] >= 0 && (m = kc({ inputs: { x: m }, backend: t, attrs: { axis: u[h] - (a.length - f), keepDims: false } }), d.push(m)), f--);
}
for (let h of d)
h !== m && t.disposeIntermediateTensorInfo(h);
return m;
}
var dL = { kernelName: tp, backendName: "webgl", kernelFunc: WQ };
var UQ = "return (x >= 0.0) ? x : (exp(x) - 1.0);";
var jQ = `
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
`;
var HQ = ve({ opSnippet: UQ, packedOpSnippet: jQ });
var hL = { kernelName: Uo, backendName: "webgl", kernelFunc: HQ };
var qQ = "return (b >= 1.0) ? a : a * (b + 1.0);";
var KQ = `
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`;
var XQ = (r) => {
let { inputs: e, backend: t } = r, { dy: n, y: o } = e, s = U().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new Ys(KQ, n.shape, o.shape) : new No(qQ, n.shape, o.shape);
return t.runWebGLProgram(s, [n, o], n.dtype);
};
var gL = { kernelName: rp, backendName: "webgl", kernelFunc: XQ };
var YQ = `
return vec4(equal(a, b));
`;
var ZQ = "return float(a == b);";
var JQ = at({ opSnippet: ZQ, packedOpSnippet: YQ, dtype: "bool", cpuKernelImpl: eP });
var xL = { kernelName: Xi, backendName: "webgl", kernelFunc: JQ };
var QQ = `
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${I.ERF_P};
float a1 = ${I.ERF_A1};
float a2 = ${I.ERF_A2};
float a3 = ${I.ERF_A3};
float a4 = ${I.ERF_A4};
float a5 = ${I.ERF_A5};
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
`;
var eee = ve({ opSnippet: QQ });
var yL = { kernelName: Ki, backendName: "webgl", kernelFunc: eee };
var bL = "return exp(x);";
var PI = ve({ opSnippet: bL, packedOpSnippet: bL, cpuKernelImpl: tP, dtype: "float32" });
var wL = { kernelName: jo, backendName: "webgl", kernelFunc: PI };
function cb(r) {
let { inputs: e, attrs: t, backend: n } = r, { dim: o } = t, { input: s } = e, a = s.shape.length, i = s.shape.slice(), l = o;
return o < 0 && (b.assert(-(a + 1) <= o, () => `Axis must be in the interval [${-(a + 1)}, ${a}]`), l = a + o + 1), i.splice(l, 0, 1), ue({ inputs: { x: s }, backend: n, attrs: { shape: i } });
}
var _L = { kernelName: oi, backendName: "webgl", kernelFunc: cb };
var kL = "return exp(x) - 1.0;";
var tee = ve({ opSnippet: kL, packedOpSnippet: kL, cpuKernelImpl: rP });
var vL = { kernelName: Yi, backendName: "webgl", kernelFunc: tee };
var pb = class {
constructor(e, t, n) {
this.variableNames = ["real", "imag"];
let o = t[1];
this.outputShape = t;
let s = n ? `2.0 * ${Math.PI}` : `-2.0 * ${Math.PI}`, a = n ? `${o}.0` : "1.0", i;
if (e === "real")
i = "return real * expR - imag * expI;";
else if (e === "imag")
i = "return real * expI + imag * expR;";
else
throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);
this.userCode = `
const float exponentMultiplier = ${s};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${i}
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${o});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${o}; i++) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float(i);
float expR = cos(x);
float expI = sin(x);
float real = getReal(batch, i);
float imag = getImag(batch, i);
result +=
unaryOpComplex(real, expR, imag, expI) / ${a};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`;
}
};
function mb(r, e, t) {
let n = t.texData.get(r.dataId), o = b.sizeFromShape(r.shape), s = r.shape[r.shape.length - 1], a = o / s, i = ue({ inputs: { x: r }, backend: t, attrs: { shape: [a, s] } }), l = i.shape, u = new pb("real", l, e), c = new pb("imag", l, e), p = [{ dataId: n.complexTensorInfos.real.dataId, dtype: n.complexTensorInfos.real.dtype, shape: l }, { dataId: n.complexTensorInfos.imag.dataId, dtype: n.complexTensorInfos.imag.dtype, shape: l }], m = t.runWebGLProgram(u, p, "float32"), f = t.runWebGLProgram(c, p, "float32"), d = An({ inputs: { real: m, imag: f }, backend: t });
t.disposeIntermediateTensorInfo(m), t.disposeIntermediateTensorInfo(f);
let h = ue({ inputs: { x: d }, backend: t, attrs: { shape: r.shape } });
return t.disposeIntermediateTensorInfo(i), t.disposeIntermediateTensorInfo(d), h;
}
function ree(r) {
let { inputs: e, backend: t } = r, { input: n } = e;
return mb(n, false, t);
}
var CL = { kernelName: np, backendName: "webgl", kernelFunc: ree };
var MI = class {
constructor(e, t) {
this.outputShape = [], this.customUniforms = [{ name: "value", type: "float" }], this.variableNames = ["x"], this.outputShape = e, this.userCode = `
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
`;
}
};
function rl(r) {
let { backend: e, attrs: t } = r, { shape: n, value: o } = t, { dtype: s } = t;
if (s = s || b.inferDtype(o), s === "string") {
let a = b.getArrayFromDType(s, b.sizeFromShape(n));
return a.fill(o), e.makeTensorInfo(n, s, a);
} else {
let a = new MI(n, o), i = [[o]];
return e.runWebGLProgram(a, [], s, i);
}
}
var IL = { kernelName: xl, backendName: "webgl", kernelFunc: rl };
var LI = class {
constructor(e) {
this.variableNames = ["Image"], this.outputShape = [];
let t = e[2];
this.outputShape = e, this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int coordX = ${t} - x - 1;
float outputValue;
if(coordX >= 0 && coordX < ${t}) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
`;
}
};
var SL = { kernelName: Zi, backendName: "webgl", kernelFunc: ({ inputs: r, backend: e }) => {
let { image: t } = r, n = e, o = new LI(t.shape);
return n.runWebGLProgram(o, [t], t.dtype);
} };
var NL = "return floor(x);";
var nee = ve({ opSnippet: NL, packedOpSnippet: NL, cpuKernelImpl: nP });
var TL = { kernelName: Ho, backendName: "webgl", kernelFunc: nee };
var oee = `
float s = sign(a) * sign(b);
int ia = round(a);
int ib = round(b);
if (ib != 0) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float(idiv(ia, ib, s));
} else {
return NAN;
}
`;
var see = `
ivec4 ia = round(a);
ivec4 ib = round(b);
bvec4 cond = notEqual(ib, ivec4(0));
ivec4 result = ivec4(0);
vec4 s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
result[0] = idiv(ia[0], ib[0], s[0]);
}
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
}
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
}
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
}
return vec4(result);
`;
var iee = at({ opSnippet: oee, packedOpSnippet: see, dtype: "int32" });
var EL = { kernelName: qo, backendName: "webgl", kernelFunc: iee };
var zI = class {
constructor(e) {
this.variableNames = ["A"];
let t = Gt(), [n, o] = e;
this.outputShape = e, this.userCode = `
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${o}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
setOutput(floor(value * 255.0 + 0.5));
}
`;
}
};
var BI = class {
constructor(e) {
this.variableNames = ["A"], this.packedInputs = false, this.packedOutput = true;
let t = Gt(), [n, o] = e;
this.outputShape = e, this.userCode = `
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec4 result = vec4(0.);
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${o}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
}
${t.output} = result;
}
`;
}
};
var AL = { kernelName: nf, backendName: "webgl", kernelFunc: aee };
var Pm;
function aee(r) {
let { inputs: e, backend: t, attrs: n } = r, { pixels: o } = e, { numChannels: s } = n, a = typeof HTMLVideoElement != "undefined" && o instanceof HTMLVideoElement, i = typeof HTMLImageElement != "undefined" && o instanceof HTMLImageElement, [l, u] = a ? [o.videoWidth, o.videoHeight] : [o.width, o.height], c = [u, l], p = [u, l, s];
(i || a) && (Pm == null && (Pm = document.createElement("canvas").getContext("2d")), Pm.canvas.width = l, Pm.canvas.height = u, Pm.drawImage(o, 0, 0, l, u), o = Pm.canvas);
let m = t.makeTensorInfo(c, "int32");
t.texData.get(m.dataId).usage = Ur.PIXELS, t.gpgpu.uploadPixelDataToTexture(t.getTexture(m.dataId), o);
let f = U().getBool("WEBGL_PACK") ? new BI(p) : new zI(p), d = t.runWebGLProgram(f, [m], "int32");
return t.disposeData(m.dataId), d;
}
function lee(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, filter: s, bias: a, preluActivationWeights: i } = e, { strides: l, pad: u, dataFormat: c, dilations: p, dimRoundingMode: m, activation: f, leakyreluAlpha: d } = n, h = I.convertConv2DDataFormat(c), g = I.computeConv2DInfo(o.shape, s.shape, l, p, u, m, false, h), x, y = [];
if (g.filterHeight === 1 && g.filterWidth === 1 && g.dilationHeight === 1 && g.dilationWidth === 1 && g.strideHeight === 1 && g.strideWidth === 1 && (g.padInfo.type === "SAME" || g.padInfo.type === "VALID"))
x = ab({ x: o, filter: s, convInfo: g, backend: t, bias: a, activation: f, preluActivationWeights: i, leakyreluAlpha: d });
else if (U().getBool("WEBGL_CONV_IM2COL") && o.shape[0] === 1)
x = lb({ x: o, filter: s, convInfo: g, backend: t, bias: a, activation: f, preluActivationWeights: i, leakyreluAlpha: d });
else {
let _ = a != null, C = i != null, A = f === "leakyrelu", D = f ? Xl(f, false) : null, R = new Kh(g, _, D, C, A), P = [o, s];
if (a && P.push(a), i && P.push(i), A) {
let L = t.makeTensorInfo([], "float32", b.createScalarValue(d, "float32"));
P.push(L), y.push(L);
}
x = t.runWebGLProgram(R, P, "float32");
}
let w = ue({ inputs: { x }, backend: t, attrs: { shape: g.outShape } });
return y.push(x), y.forEach((_) => t.disposeIntermediateTensorInfo(_)), w;
}
var DL = { kernelName: xi, backendName: "webgl", kernelFunc: lee };
function uee(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, filter: s, bias: a, preluActivationWeights: i } = e, { strides: l, pad: u, dilations: c, dimRoundingMode: p, activation: m, leakyreluAlpha: f } = n, d = [], h = c;
h == null && (h = [1, 1]), b.assert(I.eitherStridesOrDilationsAreOne(l, h), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${h}'`);
let g = I.computeConv2DInfo(o.shape, s.shape, l, h, u, p, true), x = U().getBool("WEBGL_PACK_DEPTHWISECONV") && g.strideWidth <= 2 && g.outChannels / g.inChannels == 1, y = m ? Xl(m, x) : null, w = [o, s], _ = a != null, C = i != null, A = m === "leakyrelu";
if (_ && w.push(a), C && w.push(i), A) {
let L = t.makeTensorInfo([], "float32", b.createScalarValue(f, "float32"));
w.push(L), d.push(L);
}
let D;
x ? D = new Yh(g, _, y, C, A) : D = new Xh(g, _, y, C, A);
let R = [[g.padInfo.top, g.padInfo.left], [g.strideHeight, g.strideWidth], [g.dilationHeight, g.dilationWidth], [g.inHeight, g.inWidth]], P = t.runWebGLProgram(D, w, "float32", R);
return d.forEach((L) => t.disposeIntermediateTensorInfo(L)), P;
}
var $L = { kernelName: yi, backendName: "webgl", kernelFunc: uee };
var VI = class {
constructor(e, t, n) {
this.sliceDim = e, this.strides = t, this.variableNames = ["x", "indices"], this.outputShape = n;
let o = Ue(t.length), s = Ue(n.length), a = this.sliceDim > 1 ? "strides[j]" : "strides";
this.userCode = `
${o} strides = ${o}(${this.strides});
void main() {
${s} coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
flattenIndex += index * ${a};
}
setOutput(getX(flattenIndex, coords[1]));
}
`;
}
};
function cee(r) {
let { inputs: e, backend: t } = r, { params: n, indices: o } = e, s = o.shape, a = s[s.length - 1], i = b.sizeFromShape(n.shape), [l, u, c, p] = I.prepareAndValidate(n, o), m = ue({ inputs: { x: o }, backend: t, attrs: { shape: [u, a] } }), f = ue({ inputs: { x: n }, backend: t, attrs: { shape: [b.sizeFromShape(n.shape) / c, c] } });
if (t.shouldExecuteOnCPU([n, o]) || n.dtype === "string") {
let x = t.readSync(o.dataId), y = t.bufferSync(n), w = oP(x, y, n.dtype, u, a, c, p, n.shape, i);
return t.makeTensorInfo(l, n.dtype, w.values);
}
let d = new VI(a, p, [u, c]), h = t.runWebGLProgram(d, [f, m], f.dtype), g = ue({ inputs: { x: h }, backend: t, attrs: { shape: l } });
return t.disposeIntermediateTensorInfo(m), t.disposeIntermediateTensorInfo(f), t.disposeIntermediateTensorInfo(h), g;
}
var RL = { kernelName: Ji, backendName: "webgl", kernelFunc: cee };
var GI = class {
constructor(e, t) {
this.variableNames = ["A", "indices"], this.outputShape = t, this.rank = t.length;
let n = Ue(this.rank), o = pee(e, 2);
this.userCode = `
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${o}));
}
`;
}
};
function pee(r, e) {
let t = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], n = [];
for (let o = 0; o < r.length; o++)
o === 2 ? n.push("int(getIndices(resRC.x, resRC.z))") : n.push(`${t[o]}`);
return n.join();
}
function WI(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, indices: s } = e, { axis: a, batchDims: i } = n, l = b.parseAxisParam(a, o.shape)[0], u = t.readSync(s.dataId), c = o.shape[l];
for (let _ = 0; _ < u.length; ++_) {
let C = u[_];
b.assert(C <= c - 1 && C >= 0, () => `GatherV2: the index value ${C} is not in [0, ${c - 1}]`);
}
let p = I.segment_util.collectGatherOpShapeInfo(o, s, l, i), m = b.sizeFromShape(s.shape), f = [], d = ue({ inputs: { x: o }, backend: t, attrs: { shape: [p.batchSize, p.outerSize, p.dimSize, p.sliceSize] } }), h = ue({ inputs: { x: s }, backend: t, attrs: { shape: [p.batchSize, m / p.batchSize] } });
f.push(d), f.push(h);
let g = [p.batchSize, p.outerSize, m / p.batchSize, p.sliceSize];
if (t.shouldExecuteOnCPU([o, s]) || o.dtype === "string") {
let _ = t.bufferSync(h), C = t.bufferSync(d), A = sP(C, _, g);
return f.forEach((D) => t.disposeIntermediateTensorInfo(D)), t.makeTensorInfo(p.outputShape, A.dtype, A.values);
}
let x = new GI(d.shape, g), y = t.runWebGLProgram(x, [d, h], d.dtype);
f.push(y);
let w = ue({ inputs: { x: y }, backend: t, attrs: { shape: p.outputShape } });
return f.forEach((_) => t.disposeIntermediateTensorInfo(_)), w;
}
var FL = { kernelName: si, backendName: "webgl", kernelFunc: WI };
var mee = "return float(a > b);";
var fee = `
return vec4(greaterThan(a, b));
`;
var dee = at({ opSnippet: mee, packedOpSnippet: fee, cpuKernelImpl: iP, dtype: "bool" });
var OL = { kernelName: Qi, backendName: "webgl", kernelFunc: dee };
var hee = "return float(a >= b);";
var gee = `
return vec4(greaterThanEqual(a, b));
`;
var xee = at({ opSnippet: hee, packedOpSnippet: gee, dtype: "bool", cpuKernelImpl: aP });
var PL = { kernelName: Xo, backendName: "webgl", kernelFunc: xee };
function yee(r) {
let { inputs: e, backend: t } = r, { input: n } = e;
return mb(n, true, t);
}
var ML = { kernelName: op, backendName: "webgl", kernelFunc: yee };
var bee = "return float(!isnan(x) && !isinf(x));";
var wee = ve({ opSnippet: bee, dtype: "bool" });
var LL = { kernelName: ea, backendName: "webgl", kernelFunc: wee };
var _ee = "return float(isinf(x));";
var kee = ve({ opSnippet: _ee, dtype: "bool" });
var zL = { kernelName: ta, backendName: "webgl", kernelFunc: kee };
var vee = "return float(isnan(x));";
var Cee = ve({ opSnippet: vee, dtype: "bool" });
var BL = { kernelName: ra, backendName: "webgl", kernelFunc: Cee };
var Iee = "return float(a < b);";
var See = `
return vec4(lessThan(a, b));
`;
var Nee = at({ opSnippet: Iee, packedOpSnippet: See, cpuKernelImpl: lP, dtype: "bool" });
var VL = { kernelName: na, backendName: "webgl", kernelFunc: Nee };
var Tee = "return float(a <= b);";
var Eee = `
return vec4(lessThanEqual(a, b));
`;
var Aee = at({ opSnippet: Tee, packedOpSnippet: Eee, cpuKernelImpl: uP, dtype: "bool" });
var GL = { kernelName: oa, backendName: "webgl", kernelFunc: Aee };
function Dee(r) {
let { backend: e, attrs: t } = r, { start: n, stop: o, num: s } = t, a = cP(n, o, s);
return e.makeTensorInfo([a.length], "float32", a);
}
var WL = { kernelName: ip, backendName: "webgl", kernelFunc: Dee };
var $ee = `if (x < 0.0) return NAN;
return log(x);`;
var Ree = `
vec4 result = log(x);
vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
result.r = isNaN.r == 1.0 ? NAN : result.r;
result.g = isNaN.g == 1.0 ? NAN : result.g;
result.b = isNaN.b == 1.0 ? NAN : result.b;
result.a = isNaN.a == 1.0 ? NAN : result.a;
return result;
`;
var Fee = ve({ opSnippet: $ee, packedOpSnippet: Ree, cpuKernelImpl: pP });
var UL = { kernelName: Zo, backendName: "webgl", kernelFunc: Fee };
var Oee = "return log(1.0 + x);";
var Pee = ve({ opSnippet: Oee });
var jL = { kernelName: sa, backendName: "webgl", kernelFunc: Pee };
var Mee = "return float(a >= 1.0 && b >= 1.0);";
var Lee = `
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`;
var zee = at({ opSnippet: Mee, packedOpSnippet: Lee, dtype: "bool" });
var HL = { kernelName: ia, backendName: "webgl", kernelFunc: zee };
var Bee = "return float(!(x >= 1.0));";
var Vee = ve({ opSnippet: Bee });
var qL = { kernelName: au, backendName: "webgl", kernelFunc: Vee };
var Gee = "return float(a >= 1.0 || b >= 1.0);";
var Wee = `
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`;
var Uee = at({ opSnippet: Gee, packedOpSnippet: Wee, dtype: "bool" });
var KL = { kernelName: lu, backendName: "webgl", kernelFunc: Uee };
var UI = class {
constructor(e, t, n, o, s) {
this.variableNames = ["x"], this.outputShape = [];
let a = t, i = e[3] - 1;
this.outputShape = e;
let l, u = `float(${n}) + float(${o}) * sum`;
s === 0.5 ? l = `inversesqrt(${u})` : s === 1 ? l = `1.0/(${u})` : l = `exp(log(${u}) * float(-${s}));`, this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -${a}; j <= ${a}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${i}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${l};
setOutput(val);
}
`;
}
};
var jI = class {
constructor(e, t, n, o, s) {
this.variableNames = ["x"], this.outputShape = [], this.packedInputs = true, this.packedOutput = true;
let a = t, i = e[3] - 1;
this.outputShape = e;
let l, u = `float(${n}) + float(${o}) * sum`;
s === 0.5 ? l = `inversesqrt(${u})` : s === 1 ? l = `1.0/(${u})` : l = `exp(log(${u}) * float(-${s}));`, this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
int firstChannel = d - ${a};
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
}
}
ivec2 depth = ivec2(d, d + 1);
for (int j = - ${a}; j <= ${a}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i}));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
}
cache.xy = z.yw;
sum += z * z;
}
}
vec4 result = xAtOutputCoords * ${l};
setOutput(result);
}
`;
}
};
var jee = (r) => {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { depthRadius: s, bias: a, alpha: i, beta: l } = n, u = U().getBool("WEBGL_PACK_NORMALIZATION") ? new jI(o.shape, s, a, i, l) : new UI(o.shape, s, a, i, l);
return t.runWebGLProgram(u, [o], o.dtype);
};
var XL = { kernelName: yl, backendName: "webgl", kernelFunc: jee };
var HI = class {
constructor(e, t, n, o, s) {
this.variableNames = ["inputImage", "outputImage", "dy"], this.outputShape = [], this.outputShape = e, this.depth = e[3], this.depthRadius = t, this.bias = n, this.alpha = o, this.beta = s, this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
int depthBegin = int(max(0.0, float(d - ${t})));
int depthEnd = int(min(float(${this.depth}),
float(d + ${t} + 1)));
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = ${this.depth};
float norm = 0.0;
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
}
else {
break;
}
}
norm = float(${o}) * norm + float(${n});
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(${o})
* float(${s})
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${s});
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
`;
}
};
var Hee = (r) => {
let { inputs: e, backend: t, attrs: n } = r, { x: o, y: s, dy: a } = e, { depthRadius: i, bias: l, alpha: u, beta: c } = n, p = new HI(o.shape, i, l, u, c);
return t.runWebGLProgram(p, [o, s, a], o.dtype);
};
var YL = { kernelName: ap, backendName: "webgl", kernelFunc: Hee };
function ZL(r, e, t, n) {
let o = b.sizeFromShape(e), a = b.sizeFromShape(r.shape) / o, i = ue({ inputs: { x: r }, attrs: { shape: [a, o] }, backend: n }), l = Vn(i, r.dtype, "max", n), u = ue({ inputs: { x: l }, attrs: { shape: t }, backend: n });
return n.disposeIntermediateTensorInfo(i), n.disposeIntermediateTensorInfo(l), u;
}
function qI(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { reductionIndices: s, keepDims: a } = n, i = o.shape.length, l = b.parseAxisParam(s, o.shape), u = l, c = I.getAxesPermutation(u, i), p = c != null, m = t.shouldExecuteOnCPU([o]), f = o;
if (p) {
if (m) {
let w = t.texData.get(f.dataId).values, _ = new Array(i);
for (let D = 0; D < _.length; D++)
_[D] = o.shape[c[D]];
let C = wc(w, o.shape, o.dtype, c, _);
f = t.makeTensorInfo(_, o.dtype);
let A = t.texData.get(f.dataId);
A.values = C;
} else
f = Yl(o, c, t);
u = I.getInnerMostAxes(u.length, i);
}
I.assertAxesAreInnerMostDims("max", u, i);
let [d, h] = I.computeOutAndReduceShapes(f.shape, u), g = d;
a && (g = I.expandShapeToKeepDim(d, l));
let x;
if (m) {
let w = t.texData.get(f.dataId).values, _ = mP(w, b.sizeFromShape(h), g, o.dtype);
x = t.makeTensorInfo(g, o.dtype);
let C = t.texData.get(x.dataId);
C.values = _;
} else
x = ZL(f, h, g, t);
return p && t.disposeIntermediateTensorInfo(f), x;
}
var JL = { kernelName: Jo, backendName: "webgl", kernelFunc: qI };
var qee = eb + `
return max(a, b);
`;
var Kee = `
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
` + Kl + `
return result;
`;
var Xee = at({ opSnippet: qee, packedOpSnippet: Kee, cpuKernelImpl: fP });
var QL = { kernelName: Qo, backendName: "webgl", kernelFunc: Xee };
function Yee(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e;
qs(o, "maxPool");
let { filterSize: s, strides: a, pad: i, dimRoundingMode: l } = n, u = 1;
b.assert(I.eitherStridesOrDilationsAreOne(a, u), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);
let c = I.computePool2DInfo(o.shape, s, a, u, i, l);
if (c.filterWidth === 1 && c.filterHeight === 1 && b.arraysEqual(c.inShape, c.outShape))
return Qt({ inputs: { x: o }, backend: t });
let p = new Di(c, "max", false);
return t.runWebGLProgram(p, [o], o.dtype);
}
var ez = { kernelName: es, backendName: "webgl", kernelFunc: Yee };
function Zee(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { filterSize: s, strides: a, pad: i, dataFormat: l, dimRoundingMode: u } = n, c = [1, 1, 1], p = I.computePool3DInfo(o.shape, s, a, c, i, u, l), m = new Cc(p, "max", false);
return t.runWebGLProgram(m, [o], o.dtype);
}
var tz = { kernelName: bl, backendName: "webgl", kernelFunc: Zee };
var KI = class {
constructor(e) {
this.variableNames = ["dy", "maxPos"], this.outputShape = e.inShape;
let t = e.strideHeight, n = e.strideWidth, o = e.dilationHeight, s = e.effectiveFilterHeight, a = e.effectiveFilterWidth, i = s - 1 - e.padInfo.top, l = a - 1 - e.padInfo.left, u = s * a - 1;
this.userCode = `
const ivec2 pads = ivec2(${i}, ${l});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${s};
wR += ${o}) {
float dyR = float(dyRCorner + wR) / ${t}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${a}; wC++) {
float dyC = float(dyCCorner + wC) / ${n}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${u} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${a} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`;
}
};
var XI = class {
constructor(e) {
this.variableNames = ["dy", "maxPos"], this.outputShape = e.inShape;
let t = e.strideDepth, n = e.strideHeight, o = e.strideWidth, s = e.dilationDepth, a = e.dilationHeight, i = e.dilationWidth, l = e.effectiveFilterDepth, u = e.effectiveFilterHeight, c = e.effectiveFilterWidth, p = l - 1 - e.padInfo.front, m = u - 1 - e.padInfo.top, f = c - 1 - e.padInfo.left, d = l * u * c - 1;
this.userCode = `
const ivec3 pads = ivec3(${p}, ${m}, ${f});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${l};
wD += ${s}) {
float dyD = float(dyDCorner + wD) / ${t}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${u};
wR += ${a}) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${c};
wC += ${i}) {
float dyC = float(dyCCorner + wC) / ${o}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${d} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${u} * ${c} +
wR * ${c} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`;
}
};
function Jee(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, input: s } = e, a = s, { filterSize: i, strides: l, pad: u, dimRoundingMode: c } = n, p = [1, 1, 1], m = I.computePool3DInfo(a.shape, i, l, p, u, c), f = new Cc(m, "max", true), d = t.runWebGLProgram(f, [a], a.dtype), h = new XI(m), g = t.runWebGLProgram(h, [o, d], a.dtype);
return t.disposeIntermediateTensorInfo(d), g;
}
var rz = { kernelName: up, backendName: "webgl", kernelFunc: Jee };
function Qee(r) {
let { inputs: e, backend: t, attrs: n } = r, { dy: o, input: s, output: a } = e, i = s;
qs([s, a], "maxPoolGrad");
let { filterSize: l, strides: u, pad: c, dimRoundingMode: p } = n, m = I.computePool2DInfo(i.shape, l, u, 1, c, p), f = true, d = new Di(m, "max", f), h = t.runWebGLProgram(d, [i], i.dtype), g = new KI(m), x = t.runWebGLProgram(g, [o, h], i.dtype);
return t.disposeIntermediateTensorInfo(h), x;
}
var nz = { kernelName: lp, backendName: "webgl", kernelFunc: Qee };
function oz(r, e, t, n) {
let o = new Di(t, "max", false), s = n.runWebGLProgram(o, [r], "float32");
o = new Di(t, "max", true, true, e);
let a = n.runWebGLProgram(o, [r], "float32");
return [s, a];
}
var sz = { kernelName: cp, backendName: "webgl", kernelFunc: ({ inputs: r, attrs: e, backend: t }) => {
let { x: n } = r, { filterSize: o, strides: s, pad: a, includeBatchInIndex: i } = e, l = t;
b.assert(n.shape.length === 4, () => `Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);
let u = [1, 1];
b.assert(I.eitherStridesOrDilationsAreOne(s, u), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);
let c = I.computePool2DInfo(n.shape, o, s, u, a), [p, m] = oz(n, i, c, l);
return [p, m];
} };
function iz(r, e, t, n) {
let o = b.sizeFromShape(e), a = b.sizeFromShape(r.shape) / o, i = ue({ inputs: { x: r }, attrs: { shape: [a, o] }, backend: n }), l = Vn(i, "float32", "mean", n), u = ue({ inputs: { x: l }, attrs: { shape: t }, backend: n });
return n.disposeIntermediateTensorInfo(i), n.disposeIntermediateTensorInfo(l), u;
}
var az = { kernelName: ts, backendName: "webgl", kernelFunc: ({ inputs: r, attrs: e, backend: t }) => {
let { x: n } = r, { keepDims: o, axis: s } = e, a = t, i = n.shape.length, l = b.parseAxisParam(s, n.shape), u = l, c = I.getAxesPermutation(u, i), p = c != null, m = a.shouldExecuteOnCPU([n]), f = [], d = n;
if (p) {
if (m) {
let _ = a.texData.get(d.dataId).values, C = new Array(i);
for (let R = 0; R < C.length; R++)
C[R] = n.shape[c[R]];
let A = wc(_, n.shape, n.dtype, c, C);
d = a.makeTensorInfo(C, n.dtype);
let D = a.texData.get(d.dataId);
D.values = A;
} else
d = Yl(n, c, a);
f.push(d), u = I.getInnerMostAxes(u.length, i);
}
I.assertAxesAreInnerMostDims("sum", u, i);
let [h, g] = I.computeOutAndReduceShapes(d.shape, u), x = h;
o && (x = I.expandShapeToKeepDim(h, l));
let y = iz(d, g, x, a);
for (let w of f)
a.disposeIntermediateTensorInfo(w);
return y;
} };
function ete(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, keepDims: a } = n, i = o.shape.length, l = b.parseAxisParam(s, o.shape), u = l, c = I.getAxesPermutation(u, i), p = o;
c != null && (p = Pt({ inputs: { x: o }, backend: t, attrs: { perm: c } }), u = I.getInnerMostAxes(u.length, o.shape.length)), I.assertAxesAreInnerMostDims("min", u, i);
let [m, f] = I.computeOutAndReduceShapes(p.shape, u), d = b.sizeFromShape(f), h = ue({ inputs: { x: p }, backend: t, attrs: { shape: [-1, d] } }), g = Vn(h, h.dtype, "min", t), x;
if (a) {
let y = I.expandShapeToKeepDim(m, l);
x = ue({ inputs: { x: g }, backend: t, attrs: { shape: y } });
} else
x = ue({ inputs: { x: g }, backend: t, attrs: { shape: m } });
return t.disposeIntermediateTensorInfo(h), t.disposeIntermediateTensorInfo(g), c != null && t.disposeIntermediateTensorInfo(p), x;
}
var lz = { kernelName: rs, backendName: "webgl", kernelFunc: ete };
var tte = eb + `
return min(a, b);
`;
var rte = `
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
` + Kl + `
return result;
`;
var nte = at({ opSnippet: tte, packedOpSnippet: rte, cpuKernelImpl: dP });
var uz = { kernelName: ns, backendName: "webgl", kernelFunc: nte };
var YI = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.outputShape = t.map((c, p) => c[0] + e[p] + c[1]);
let o = e.length, s = Ue(o), a = t.map((c) => c[0]).join(","), i = t.map((c, p) => c[0] + e[p]).join(","), l = ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, o), u = n === "reflect" ? 0 : 1;
if (o === 1) {
this.userCode = `
int start = ${a};
int end = ${i};
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - ${u};
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + ${u};
}
setOutput(getX(outC - start));
}
`;
return;
}
this.userCode = `
${s} start = ${s}(${a});
${s} end = ${s}(${i});
void main() {
${s} outC = getOutputCoords();
for (int i = 0; i < ${o}; i++) {
if (outC[i] < start[i]) {
outC[i] = start[i] * 2 - outC[i] - ${u};
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + ${u};
}
}
${s} coords = outC - start;
setOutput(getX(${l}));
}
`;
}
};
var ZI = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.packedInputs = true, this.packedOutput = true, this.outputShape = t.map((d, h) => d[0] + e[h] + d[1]);
let o = e.length, s = Ue(o), a = t.map((d) => d[0]).join(","), i = t.map((d, h) => d[0] + e[h]).join(","), l = Jt("rc", o), u = Jt("source", o), c = `${l[o - 1]} < ${this.outputShape[o - 1]}`, p = o === 1 ? "source" : `vec2(${u.slice(-2).join()})`, m = n === "reflect" ? 0 : 1, f = "";
if (o === 1) {
let d = `
${s} source = rc;
if (source < start) {
source = start * 2 - source - ${m};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${m};
}
source -= start;
`;
f = `
${s} rc = outputLoc;
${d}
result[0] = getChannel(getX(${u.join()}), ${p});
${l[o - 1]} += 1;
if(${c}) {
${d}
result[1] = getChannel(getX(${u.join()}), ${p});
}
`;
} else {
let d = `
${s} source = rc;
${s} lt = ${s}(lessThan(source, start));
${s} gte = ${s}(greaterThanEqual(source, end));
${s} orig = 1 - (lt + gte);
source = orig * source +
lt * (start * 2 - source - ${m}) +
gte * ((end - 1) * 2 - source + ${m});
source -= start;
`;
f = `
${s} rc = outputLoc;
${d}
result[0] = getChannel(getX(${u.join()}), ${p});
${l[o - 1]} += 1;
if(${c}) {
${d}
result[1] = getChannel(getX(${u.join()}), ${p});
}
rc = outputLoc;
${l[o - 2]} += 1;
if(${l[o - 2]} < ${this.outputShape[o - 2]}) {
${d}
result[2] = getChannel(getX(${u.join()}), ${p});
${l[o - 1]} += 1;
if(${c}) {
${d}
result[3] = getChannel(getX(${u.join()}), ${p});
}
}
`;
}
this.userCode = `
const ${s} start = ${s}(${a});
const ${s} end = ${s}(${i});
void main() {
${s} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${f}
setOutput(result);
}
`;
}
};
var ote = ({ inputs: r, backend: e, attrs: t }) => {
let { x: n } = r, { paddings: o, mode: s } = t, a = U().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new ZI(n.shape, o, s) : new YI(n.shape, o, s);
return e.runWebGLProgram(a, [n], n.dtype);
};
var cz = { kernelName: os, backendName: "webgl", kernelFunc: ote };
var ste = `if (b == 0.0) return NAN;
return mod(a, b);`;
var ite = `
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
` + Kl + `
return result;
`;
var ate = at({ opSnippet: ste, packedOpSnippet: ite });
var pz = { kernelName: aa, backendName: "webgl", kernelFunc: ate };
var JI = class {
constructor(e, t, n) {
this.variableNames = ["probs"], this.customUniforms = [{ name: "seed", type: "float" }], this.outputShape = [e, n], this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
float r = random(seed);
float cdf = 0.0;
for (int i = 0; i < ${t - 1}; i++) {
cdf += getProbs(batch, i);
if (r < cdf) {
setOutput(float(i));
return;
}
}
// If no other event happened, last event happened.
setOutput(float(${t - 1}));
}
`;
}
};
var lte = `
if (a == b) {
return 1.0;
};
return a / b;`;
var ute = `
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b;
if(a.x == b.x) {
result.x = 1.;
}
if(a.y == b.y) {
result.y = 1.;
}
if(a.z == b.z) {
result.z = 1.;
}
if(a.w == b.w) {
result.w = 1.;
}
return result;
`;
var QI = at({ opSnippet: lte, packedOpSnippet: ute, checkOutOfBounds: true });
var mz = { kernelName: Wo, backendName: "webgl", kernelFunc: QI };
var fz = "return a - b;";
var eS = at({ opSnippet: fz, packedOpSnippet: fz, supportsComplex: true, cpuKernelImpl: AP });
var dz = { kernelName: ks, backendName: "webgl", kernelFunc: eS };
function tS(r) {
let { inputs: e, backend: t, attrs: n } = r, { logits: o } = e, { dim: s } = n, a = b.parseAxisParam([s], o.shape), i = qI({ inputs: { x: o }, backend: t, attrs: { reductionIndices: a, keepDims: false } }), l = I.expandShapeToKeepDim(i.shape, a), u = ue({ inputs: { x: i }, backend: t, attrs: { shape: l } }), c = eS({ inputs: { a: o, b: u }, backend: t }), p = PI({ inputs: { x: c }, backend: t }), m = kc({ inputs: { x: p }, backend: t, attrs: { axis: a, keepDims: false } }), f = ue({ inputs: { x: m }, backend: t, attrs: { shape: l } }), d = QI({ inputs: { a: p, b: f }, backend: t });
return t.disposeIntermediateTensorInfo(i), t.disposeIntermediateTensorInfo(u), t.disposeIntermediateTensorInfo(c), t.disposeIntermediateTensorInfo(p), t.disposeIntermediateTensorInfo(m), t.disposeIntermediateTensorInfo(f), d;
}
var hz = { kernelName: ws, backendName: "webgl", kernelFunc: tS };
function cte(r) {
let { inputs: e, backend: t, attrs: n } = r, { logits: o } = e, { numSamples: s, seed: a, normalized: i } = n, l = i ? o : tS({ inputs: { logits: o }, backend: t, attrs: { dim: o.shape.length - 1 } }), u = l.shape[0], c = l.shape[1], p = new JI(u, c, s), m = [[a]], f = t.runWebGLProgram(p, [l], "int32", m);
return i || t.disposeIntermediateTensorInfo(l), f;
}
var gz = { kernelName: pp, backendName: "webgl", kernelFunc: cte };
var xz = "return -x;";
function pte(r) {
let { inputs: e, backend: t } = r, { x: n } = e;
if (t.shouldExecuteOnCPU([n])) {
let s = t.texData.get(n.dataId), [a, i] = gP(s.values, n.shape, n.dtype);
return t.makeTensorInfo(i, n.dtype, a);
}
let o;
return U().getBool("WEBGL_PACK_UNARY_OPERATIONS") ? o = new Xs(n.shape, xz) : o = new En(n.shape, xz), t.runWebGLProgram(o, [n], n.dtype);
}
var yz = { kernelName: ii, backendName: "webgl", kernelFunc: pte };
var mte = Gr.nonMaxSuppressionV3Impl;
function fte(r) {
I.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
let { inputs: e, backend: t, attrs: n } = r, { boxes: o, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: l } = n, u = t.readSync(o.dataId), c = t.readSync(s.dataId), { selectedIndices: p } = mte(u, c, a, i, l);
return t.makeTensorInfo([p.length], "int32", new Int32Array(p));
}
var bz = { kernelName: ua, backendName: "webgl", kernelFunc: fte };
var dte = Gr.nonMaxSuppressionV4Impl;
function hte(r) {
I.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
let { inputs: e, backend: t, attrs: n } = r, { boxes: o, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: l, padToMaxOutputSize: u } = n, c = t.readSync(o.dataId), p = t.readSync(s.dataId), { selectedIndices: m, validOutputs: f } = dte(c, p, a, i, l, u);
return [t.makeTensorInfo([m.length], "int32", new Int32Array(m)), t.makeTensorInfo([], "int32", new Int32Array([f]))];
}
var wz = { kernelName: ca, backendName: "webgl", kernelFunc: hte };
var gte = Gr.nonMaxSuppressionV5Impl;
function xte(r) {
I.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
let { inputs: e, backend: t, attrs: n } = r, { boxes: o, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: l, softNmsSigma: u } = n, c = t.readSync(o.dataId), p = t.readSync(s.dataId), m = a, f = i, d = l, h = u, { selectedIndices: g, selectedScores: x } = gte(c, p, m, f, d, h);
return [t.makeTensorInfo([g.length], "int32", new Int32Array(g)), t.makeTensorInfo([x.length], "float32", new Float32Array(x))];
}
var _z = { kernelName: pa, backendName: "webgl", kernelFunc: xte };
var rS = class {
constructor(e, t, n, o) {
this.variableNames = ["indices"], this.outputShape = [e, t], this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${o}), float(${n}),
float(index == coords.y)));
}
`;
}
};
var yte = (r) => {
let { inputs: e, backend: t, attrs: n } = r, { indices: o } = e, { depth: s, onValue: a, offValue: i } = n, l = b.sizeFromShape(o.shape), u = new rS(l, s, a, i), c = ue({ inputs: { x: o }, backend: t, attrs: { shape: [l] } }), p = t.runWebGLProgram(u, [c], o.dtype);
t.disposeIntermediateTensorInfo(c);
let m = [...o.shape, s], f = ue({ inputs: { x: p }, backend: t, attrs: { shape: m } });
return t.disposeIntermediateTensorInfo(p), f;
};
var kz = { kernelName: is, backendName: "webgl", kernelFunc: yte };
function Zh(r) {
let { inputs: e, backend: t } = r, { x: n } = e;
if (n.dtype === "complex64") {
let o = tl({ inputs: { input: n }, backend: t }), s = Zh({ inputs: { x: o }, backend: t }), a = Ic({ inputs: { input: n }, backend: t }), i = Zh({ inputs: { x: a }, backend: t }), l = An({ inputs: { real: s, imag: i }, backend: t });
return t.disposeIntermediateTensorInfo(o), t.disposeIntermediateTensorInfo(s), t.disposeIntermediateTensorInfo(a), t.disposeIntermediateTensorInfo(i), l;
} else
return rl({ attrs: { shape: n.shape, dtype: n.dtype, value: n.dtype === "string" ? "" : 0 }, backend: t });
}
var vz = { kernelName: hi, backendName: "webgl", kernelFunc: Zh };
function Cz(r) {
let { inputs: e, backend: t } = r, { x: n } = e;
if (n.dtype === "string")
throw new Error("onesLike is not supported under string dtype");
if (n.dtype === "complex64") {
let o = tl({ inputs: { input: n }, backend: t }), s = Cz({ inputs: { x: o }, backend: t }), a = Ic({ inputs: { input: n }, backend: t }), i = Zh({ inputs: { x: a }, backend: t }), l = An({ inputs: { real: s, imag: i }, backend: t });
return t.disposeIntermediateTensorInfo(o), t.disposeIntermediateTensorInfo(s), t.disposeIntermediateTensorInfo(a), t.disposeIntermediateTensorInfo(i), l;
} else
return rl({ attrs: { shape: n.shape, dtype: n.dtype, value: 1 }, backend: t });
}
var Iz = { kernelName: ai, backendName: "webgl", kernelFunc: Cz };
function bte(r) {
let { inputs: e, backend: t, attrs: n } = r, { axis: o } = n;
if (e.length === 1)
return cb({ inputs: { input: e[0] }, backend: t, attrs: { dim: o } });
let s = e[0].shape, a = e[0].dtype;
e.forEach((c) => {
b.assertShapesMatch(s, c.shape, "All tensors passed to stack must have matching shapes"), b.assert(a === c.dtype, () => "All tensors passed to stack must have matching dtypes");
});
let i = [], l = e.map((c) => {
let p = cb({ inputs: { input: c }, backend: t, attrs: { dim: o } });
return i.push(p), p;
}), u = vI({ inputs: l, backend: t, attrs: { axis: o } });
return i.forEach((c) => t.disposeIntermediateTensorInfo(c)), u;
}
var Sz = { kernelName: li, backendName: "webgl", kernelFunc: bte };
var nS = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.customUniforms = [{ name: "value", type: "float" }], this.outputShape = t.map((u, c) => u[0] + e[c] + u[1]);
let o = e.length, s = Ue(o), a = t.map((u) => u[0]).join(","), i = t.map((u, c) => u[0] + e[c]).join(","), l = ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, o);
if (o === 1) {
this.userCode = `
int start = ${a};
int end = ${i};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(value);
} else {
setOutput(getX(outC - start));
}
}
`;
return;
}
this.userCode = `
${s} start = ${s}(${a});
${s} end = ${s}(${i});
void main() {
${s} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(value);
} else {
${s} coords = outC - start;
setOutput(getX(${l}));
}
}
`;
}
};
var oS = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "value", type: "float" }], this.outputShape = t.map((h, g) => h[0] + e[g] + h[1]);
let o = e.length, s = Ue(o), a = t.map((h) => h[0]).join(","), i = t.map((h, g) => h[0] + e[g]).join(","), l = Jt("rc", o), u = Jt("source", o), c = `${l[o - 1]} < ${this.outputShape[o - 1]}`, p = o === 1 ? "source" : `vec2(${u.slice(-2).join()})`, m = [`${s} rc = outputLoc;`, `${l[o - 1]} += 1;
if(${c}) {
`, o === 1 ? "" : `}
rc = outputLoc;
${l[o - 2]} += 1;
if(${l[o - 2]} < ${this.outputShape[o - 2]}) {`, o === 1 ? "" : ` ${l[o - 1]} += 1;
if(${c}) {`], f = o === 1 ? "rc < start || rc >= end" : "any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))", d = "";
for (let h = 0, g = o === 1 ? 2 : 4; h < g; h++)
d += `
${m[h]}
if (${f}) {
result[${h}] = float(value);
} else {
${s} source = rc - start;
result[${h}] = getChannel(getX(${u.join()}), ${p});
}
`;
d += o === 1 ? "} " : "}}", this.userCode = `
const ${s} start = ${s}(${a});
const ${s} end = ${s}(${i});
void main() {
${s} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${d}
setOutput(result);
}
`;
}
};
var sS = (r) => {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { paddings: s, constantValue: a } = n;
if (b.sizeFromShape(o.shape) === 0) {
let u = s.map((c, p) => c[0] + o.shape[p] + c[1]);
return rl({ backend: t, attrs: { shape: u, value: a, dtype: o.dtype } });
}
let i = U().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new oS(o.shape, s, a) : new nS(o.shape, s, a), l = [[a]];
return t.runWebGLProgram(i, [o], o.dtype, l);
};
var Nz = { kernelName: as, backendName: "webgl", kernelFunc: sS };
var wte = `
if(a < 0.0 && floor(b) < b){
return NAN;
}
if (b == 0.0) {
return 1.0;
}
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
`;
var _te = `
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
vec4 result = multiplier * pow(abs(a), b);
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal(b, vec4(0.0));
result.r = isExpZero.r ? 1.0 : result.r;
result.g = isExpZero.g ? 1.0 : result.g;
result.b = isExpZero.b ? 1.0 : result.b;
result.a = isExpZero.a ? 1.0 : result.a;
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
` + Kl + `
return result;
`;
var kte = at({ opSnippet: wte, packedOpSnippet: _te });
var Tz = { kernelName: ls, backendName: "webgl", kernelFunc: kte };
function vte(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, keepDims: a } = n, i = o.shape.length, l = [], u = b.parseAxisParam(s, o.shape), c = u, p = I.getAxesPermutation(c, i), m = o;
p != null && (m = Pt({ inputs: { x: o }, backend: t, attrs: { perm: p } }), c = I.getInnerMostAxes(c.length, i), l.push(m)), I.assertAxesAreInnerMostDims("prod", c, i);
let f;
if (t.shouldExecuteOnCPU([m])) {
let d = t.texData.get(m.dataId).values, { outVals: h, outShape: g, outDtype: x } = yP(m.shape, m.dtype, d, c);
f = t.makeTensorInfo(g, x, h);
} else {
let [d, h] = I.computeOutAndReduceShapes(m.shape, c), g = b.sizeFromShape(h), x = ue({ inputs: { x: m }, backend: t, attrs: { shape: [-1, g] } }), y = hu(o.dtype), w = Vn(x, y, "prod", t);
f = ue({ inputs: { x: w }, backend: t, attrs: { shape: d } }), l.push(x), l.push(w);
}
if (a) {
l.push(f);
let d = I.expandShapeToKeepDim(f.shape, u);
f = ue({ inputs: { x: f }, backend: t, attrs: { shape: d } });
}
return l.forEach((d) => t.disposeIntermediateTensorInfo(d)), f;
}
var Ez = { kernelName: ma, backendName: "webgl", kernelFunc: vte };
var iS = (r) => {
let { backend: e, attrs: t } = r, { start: n, stop: o, step: s, dtype: a } = t, i = bP(n, o, s, a);
return e.makeTensorInfo([i.length], a, i);
};
var Az = { kernelName: wl, backendName: "webgl", kernelFunc: iS };
var Cte = "return 1.0 / x;";
var Ite = ve({ opSnippet: Cte });
var Dz = { kernelName: fa, backendName: "webgl", kernelFunc: Ite };
var Ste = Nr + `
return (x < 0.0) ? 0.0 : x;
`;
var Nte = `
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;
var Tte = ve({ opSnippet: Ste, packedOpSnippet: Nte });
var $z = { kernelName: cs, backendName: "webgl", kernelFunc: Tte };
var Ete = Nr + `
return (x < 0.0) ? 0.0 : min(6.0, x);
`;
var Ate = `
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`;
var Dte = ve({ opSnippet: Ete, packedOpSnippet: Ate });
var Rz = { kernelName: ms, backendName: "webgl", kernelFunc: Dte };
var aS = class {
constructor(e, t, n, o, s) {
this.variableNames = ["A"], this.outputShape = [];
let [a, i, l, u] = e;
this.outputShape = [a, t, n, u];
let c = [o && t > 1 ? i - 1 : i, o && n > 1 ? l - 1 : l], p = [o && t > 1 ? t - 1 : t, o && n > 1 ? n - 1 : n], m;
s ? m = "(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)" : m = "vec2(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
const vec2 effectiveInputOverOutputRatioRC = vec2(
${c[0] / p[0]},
${c[1] / p[1]});
const vec2 inputShapeRC = vec2(${i}.0, ${l}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = ${m};
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
}
`;
}
};
var lS = class {
constructor(e, t, n, o, s) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.outputShape = [];
let [a, i, l, u] = e;
this.outputShape = [a, t, n, u];
let c = [o && t > 1 ? i - 1 : i, o && n > 1 ? l - 1 : l], p = [o && t > 1 ? t - 1 : t, o && n > 1 ? n - 1 : n], m;
s ? m = "(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)" : m = "vec3(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
const vec3 effectiveInputOverOutputRatioRC = vec3(
${c[0] / p[0]},
${c[1] / p[1]},
${c[1] / p[1]});
const vec3 inputShapeRC = vec3(${i}.0, ${l}.0,
${l}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = ${m};
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${u - 1};
bool hasNextRow = coords.z < ${n - 1};
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
setOutput(newValue);
}
`;
}
};
function $te(r) {
let { inputs: e, backend: t, attrs: n } = r, { images: o } = e, { alignCorners: s, halfPixelCenters: a, size: i } = n, [l, u] = i, c = U().getBool("WEBGL_PACK_IMAGE_OPERATIONS") ? new lS(o.shape, l, u, s, a) : new aS(o.shape, l, u, s, a);
return t.runWebGLProgram(c, [o], "float32");
}
var Fz = { kernelName: ps, backendName: "webgl", kernelFunc: $te };
var uS = class {
constructor(e, t, n) {
this.variableNames = ["dy"], this.outputShape = [], this.outputShape = t;
let [, o, s] = t, [, a, i] = e, l = [n && a > 1 ? o - 1 : o, n && i > 1 ? s - 1 : s], u = [n && a > 1 ? a - 1 : a, n && i > 1 ? i - 1 : i], c = l[0] / u[0], p = l[1] / u[1], m = 1 / c, f = 1 / p, d = Math.ceil(m) * 2 + 2, h = Math.ceil(f) * 2 + 2;
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${c});
const float widthScale = float(${p});
const float invHeightScale = float(${m});
const float invWidthScale = float(${f});
const int winHeight = int(${d});
const int winWidth = int(${h});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${a}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${i}) {
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${o - 1}.0));
float dxRLerp = dxR - float(topDxRIndex);
float inverseDxRLerp = 1.0 - dxRLerp;
float dxC = float(dyC) * widthScale;
int leftDxCIndex = int(floor(dxC));
int rightDxCIndex = int(min(ceil(dxC), ${s - 1}.0));
float dxCLerp = dxC - float(leftDxCIndex);
float inverseDxCLerp = 1.0 - dxCLerp;
if (r == topDxRIndex && c == leftDxCIndex) {
// topLeft
accumulator +=
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
}
if (r == topDxRIndex && c == rightDxCIndex) {
// topRight
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
}
if (r == bottomDxRIndex && c == leftDxCIndex) {
// bottomLeft
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
}
if (r == bottomDxRIndex && c == rightDxCIndex) {
// bottomRight
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
}
}
}
// End loop over dy
setOutput(accumulator);
}
`;
}
};
function Rte(r) {
let { inputs: e, backend: t, attrs: n } = r, { images: o, dy: s } = e, { alignCorners: a } = n, i = new uS(s.shape, o.shape, a);
return t.runWebGLProgram(i, [s], s.dtype);
}
var Oz = { kernelName: dp, backendName: "webgl", kernelFunc: Rte };
var cS = class {
constructor(e, t, n, o, s) {
this.variableNames = ["A"], this.outputShape = [];
let [a, i, l, u] = e;
this.outputShape = [a, t, n, u];
let c = [o && t > 1 ? i - 1 : i, o && n > 1 ? l - 1 : l], p = [o && t > 1 ? t - 1 : t, o && n > 1 ? n - 1 : n], m = o ? "0.5" : "0.0", f;
s ? f = "max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))" : f = "vec2(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
const vec2 effectiveInputOverOutputRatioRC = vec2(
${c[0] / p[0]},
${c[1] / p[1]});
const vec2 inputShapeRC = vec2(${i}.0, ${l}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = ${f};
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${m})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
`;
}
};
var pS = class {
constructor(e, t, n, o, s) {
this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.outputShape = [];
let [a, i, l, u] = e;
this.outputShape = [a, t, n, u];
let c = [o && t > 1 ? i - 1 : i, o && n > 1 ? l - 1 : l], p = [o && t > 1 ? t - 1 : t, o && n > 1 ? n - 1 : n], m = o ? "0.5" : "0.0", f;
s ? f = "max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))" : f = "vec3(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
const vec3 effectiveInputOverOutputRatioRC = vec3(
${c[0] / p[0]},
${c[1] / p[1]},
${c[1] / p[1]});
const vec3 inputShapeRC = vec3(${i}.0, ${l}.0,
${l}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = ${f};
// Compute the coordinators of nearest neighbor point.
ivec3 sourceNearestRC = ivec3(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${m})));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${u - 1};
bool hasNextRow = coords.z < ${n - 1};
vec4 newValue = vec4(
getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
setOutput(newValue);
}
`;
}
};
function Fte(r) {
let { inputs: e, backend: t, attrs: n } = r, { images: o } = e, { alignCorners: s, halfPixelCenters: a, size: i } = n, [l, u] = i, c = U().getBool("WEBGL_PACK_IMAGE_OPERATIONS") ? new pS(o.shape, l, u, s, a) : new cS(o.shape, l, u, s, a);
return t.runWebGLProgram(c, [o], o.dtype);
}
var Pz = { kernelName: _l, backendName: "webgl", kernelFunc: Fte };
var mS = class {
constructor(e, t, n) {
this.variableNames = ["dy"], this.outputShape = [], this.outputShape = t;
let [, o, s] = t, [, a, i] = e, l = [n && a > 1 ? o - 1 : o, n && i > 1 ? s - 1 : s], u = [n && a > 1 ? a - 1 : a, n && i > 1 ? i - 1 : i], c = l[0] / u[0], p = l[1] / u[1], m = 1 / c, f = 1 / p, d = Math.ceil(m) * 2 + 2, h = Math.ceil(f) * 2 + 2;
this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${c});
const float widthScale = float(${p});
const float invHeightScale = float(${m});
const float invWidthScale = float(${f});
const int winHeight = int(${d});
const int winWidth = int(${h});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${a}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${i}) {
continue;
}
float sourceFracRow =
float(${l[0]}) *
(float(dyR) / float(${u[0]}));
float sourceFracCol =
float(${l[1]}) *
(float(dyC) / float(${u[1]}));
int sourceNearestRow = int(min(
float(int(${o}) - 1),
${n} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${s}) - 1),
${n} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`;
}
};
function Ote(r) {
let { inputs: e, backend: t, attrs: n } = r, { images: o, dy: s } = e, { alignCorners: a } = n, i = new mS(s.shape, o.shape, a);
return t.runWebGLProgram(i, [s], s.dtype);
}
var Mz = { kernelName: fp, backendName: "webgl", kernelFunc: Ote };
var fS = class {
constructor(e, t) {
this.variableNames = ["x"];
let n = e.length;
if (n > 4)
throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);
if (this.outputShape = e, n === 1) {
this.userCode = `
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
`;
return;
}
let o = (i) => t.indexOf(i) !== -1 && e[i] !== 1 ? `${e[i]} - coords[${i}] - 1` : `coords[${i}]`, s = e.map((i, l) => o(l)).join(","), a = Ue(n);
this.userCode = `
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${s}));
}
`;
}
};
var dS = class {
constructor(e, t) {
this.variableNames = ["x"], this.packedInputs = true, this.packedOutput = true;
let n = e.length;
if (n > 4)
throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);
this.outputShape = e;
let o = Jt("rc", n), s = `${o[n - 1]} + 1 < ${this.outputShape[n - 1]}`, a = `${o[n - 2]} + 1 < ${this.outputShape[n - 2]}`, i = Ue(n);
n === 1 ? this.userCode = `
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${e[0]} - rc - 1),
${e[0]} - rc - 1);
if(${s}){
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
${e[0]} - (rc + 1) - 1);
}
setOutput(result);
}
` : this.userCode = `
void main() {
${i} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${l(o.slice())};
if(${s}){
result.g = ${u(o.slice())};
}
if(${a}) {
result.b = ${c(o.slice())};
if(${s}) {
result.a = ${p(o.slice())};
}
}
setOutput(result);
}
`;
function l(d) {
return m(d);
}
function u(d) {
return d[n - 1] = "(" + d[n - 1] + " + 1)", m(d);
}
function c(d) {
return d[n - 2] = "(" + d[n - 2] + " + 1)", m(d);
}
function p(d) {
return d[n - 1] = "(" + d[n - 1] + " + 1)", d[n - 2] = "(" + d[n - 2] + " + 1)", m(d);
}
function m(d) {
let h = e.map((y, w) => f(w, d)), g = h.join(","), x = h.slice(-2).join(",");
return `getChannel(getX(${g}), vec2(${x}))`;
}
function f(d, h) {
return t.indexOf(d) !== -1 && e[d] !== 1 ? `${e[d]} - ${h[d]} - 1` : `${h[d]}`;
}
}
};
function Pte(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { dims: s } = n, a = o.shape.length, i = b.parseAxisParam(s, o.shape);
if (a === 0)
return Qt({ inputs: { x: o }, backend: t });
let l = U().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new dS(o.shape, i) : new fS(o.shape, i);
return t.runWebGLProgram(l, [o], o.dtype);
}
var Lz = { kernelName: fs, backendName: "webgl", kernelFunc: Pte };
var hS = class {
constructor(e, t) {
this.variableNames = ["Image"], this.outputShape = [], this.customUniforms = [{ name: "params", type: "vec4" }];
let n = e[1], o = e[2];
this.outputShape = e;
let s = "";
typeof t == "number" ? s = `float outputValue = ${t.toFixed(2)};` : s = `
vec3 fill = vec3(${t.join(",")});
float outputValue = fill[coords[3]];`, this.userCode = `
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
float coordXFloat = (float(x) - params[0]) * params[3] -
(float(y) - params[1]) * params[2];
float coordYFloat = (float(x) - params[0]) * params[2] +
(float(y) - params[1]) * params[3];
int coordX = int(round(coordXFloat + params[0]));
int coordY = int(round(coordYFloat + params[1]));
${s}
if(coordX >= 0 && coordX < ${o} && coordY >= 0 && coordY < ${n}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`;
}
};
var zz = { kernelName: ka, backendName: "webgl", kernelFunc: ({ inputs: r, attrs: e, backend: t }) => {
let { image: n } = r, { radians: o, fillValue: s, center: a } = e, i = t, l = new hS(n.shape, s), [u, c] = I.getImageCenter(a, n.shape[1], n.shape[2]), p = [[u, c, Math.sin(o), Math.cos(o)]];
return i.runWebGLProgram(l, [n], n.dtype, p);
} };
var Mte = `
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor(x);
if ((x - base) < 0.5) {
return floor(x);
} else if ((x - base) > 0.5) {
return ceil(x);
} else {
if (mod(base, 2.0) == 0.0) {
return base;
} else {
return base + 1.0;
}
}
`;
var Lte = ve({ opSnippet: Mte });
var Bz = { kernelName: ds, backendName: "webgl", kernelFunc: Lte };
var zte = "return inversesqrt(x);";
var Bte = ve({ opSnippet: zte, cpuKernelImpl: wP });
var Vz = { kernelName: hs, backendName: "webgl", kernelFunc: Bte };
var Jh = class {
constructor(e, t, n, o, s, a, i = true) {
this.variableNames = ["updates", "indices", "defaultValue"], this.outputShape = a;
let l = Ue(s.length), u = Ue(a.length), c = "";
n === 1 ? c = "i" : n === 2 && (c = "i, j");
let p = `getIndices(${c})`, m = "";
o === 1 ? m = "i" : o === 2 && (m = "i, coords[1]");
let f = `getUpdates(${m})`, d = t > 1 ? "strides[j]" : "strides";
this.userCode = `
${l} strides = ${l}(${s});
void main() {
${u} coords = getOutputCoords();
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${e}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${t}; j++) {
int index = round(${p});
flattenedIndex += index * ${d};
}
if (flattenedIndex == coords[0]) {
sum += ${f};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
`;
}
};
function Vte(r) {
let { inputs: e, backend: t, attrs: n } = r, { indices: o, updates: s } = e, { shape: a } = n, { sliceRank: i, numUpdates: l, sliceSize: u, strides: c, outputSize: p } = I.calculateShapes(s, o, a), m = [p / u, u];
if (p === 0)
return t.makeTensorInfo(a, o.dtype);
let f = ue({ inputs: { x: o }, backend: t, attrs: { shape: [l, i] } }), d = ue({ inputs: { x: s }, backend: t, attrs: { shape: [l, u] } }), h = t.makeTensorInfo([], "float32", new Float32Array([0])), g = new Jh(l, i, f.shape.length, d.shape.length, c, m), x = t.runWebGLProgram(g, [d, f, h], d.dtype), y = ue({ inputs: { x }, backend: t, attrs: { shape: a } });
return t.disposeIntermediateTensorInfo(f), t.disposeIntermediateTensorInfo(d), t.disposeIntermediateTensorInfo(x), t.disposeIntermediateTensorInfo(h), y;
}
var Gz = { kernelName: da, backendName: "webgl", kernelFunc: Vte };
var gS = class {
constructor(e, t, n) {
this.variableNames = ["c", "a", "b"], this.outputShape = t;
let o, s;
if (n > 4)
throw Error(`Where for rank ${n} is not yet supported`);
if (n === 1)
s = "resRC", o = "resRC";
else {
let i = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], l = [], u = [];
for (let c = 0; c < t.length; c++)
u.push(`${i[c]}`), c < e && l.push(`${i[c]}`);
o = l.join(), s = u.join();
}
let a = Ue(n);
this.userCode = `
void main() {
${a} resRC = getOutputCoords();
float cVal = getC(${o});
if (cVal >= 1.0) {
setOutput(getA(${s}));
} else {
setOutput(getB(${s}));
}
}
`;
}
};
function Gte(r) {
let { inputs: e, backend: t } = r, { condition: n, t: o, e: s } = e, a = new gS(n.shape.length, o.shape, o.shape.length);
return t.runWebGLProgram(a, [n, o, s], hr(o.dtype, s.dtype));
}
var Wz = { kernelName: ci, backendName: "webgl", kernelFunc: Gte };
var Wte = `
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${I.SELU_SCALEALPHA};
float scale = ${I.SELU_SCALE};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`;
var Ute = ve({ opSnippet: Wte });
var Uz = { kernelName: ha, backendName: "webgl", kernelFunc: Ute };
var jz = "return 1.0 / (1.0 + exp(-1.0 * x));";
var jte = ve({ opSnippet: jz, packedOpSnippet: jz, cpuKernelImpl: _P });
var Hz = { kernelName: xs, backendName: "webgl", kernelFunc: jte };
var Hte = `
if (isnan(x)) { return 0.0; }
return sign(x);
`;
var qte = ve({ opSnippet: Hte });
var qz = { kernelName: xa, backendName: "webgl", kernelFunc: qte };
var Kte = tb + `
return sin(x);
`;
var Xte = ve({ opSnippet: Kte });
var Kz = { kernelName: gs, backendName: "webgl", kernelFunc: Xte };
var Yte = `
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`;
var Zte = ve({ opSnippet: Yte });
var Xz = { kernelName: ga, backendName: "webgl", kernelFunc: Zte };
var Jte = `
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
if (too_large){
result = x;
}
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
}
return result;
`;
var Qte = ve({ opSnippet: Jte });
var Yz = { kernelName: ya, backendName: "webgl", kernelFunc: Qte };
var ere = (r) => {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { blockShape: s, paddings: a } = n;
b.assert(o.shape.length <= 4, () => "spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");
let i = s.reduce((x, y) => x * y), l = [[0, 0]];
l.push(...a);
for (let x = 1 + s.length; x < o.shape.length; ++x)
l.push([0, 0]);
let u = [], c = sS({ inputs: { x: o }, backend: t, attrs: { paddings: l, constantValue: 0 } }), p = I.getReshaped(c.shape, s, i, false), m = I.getPermuted(p.length, s.length, false), f = I.getReshapedPermuted(c.shape, s, i, false), d = ue({ inputs: { x: c }, backend: t, attrs: { shape: p } }), h = Pt({ inputs: { x: d }, backend: t, attrs: { perm: m } }), g = ue({ inputs: { x: h }, backend: t, attrs: { shape: f } });
return u.push(c), u.push(d), u.push(h), u.forEach((x) => t.disposeIntermediateTensorInfo(x)), g;
};
var Zz = { kernelName: mi, backendName: "webgl", kernelFunc: ere };
function tre(r) {
let { inputs: e, backend: t } = r, { indices: n, values: o, denseShape: s, defaultValue: a } = e;
if (s.shape.length !== 1)
throw new Error(`Dense shape must be a vector, saw:
${s.shape}`);
if (n.shape.length !== 2)
throw new Error(`Indices must be a matrix, saw:
${n.shape}`);
if (o.shape.length !== 1)
throw new Error(`Values must be a vector, saw:
${o.shape}`);
if (a.shape.length !== 0)
throw new Error(`Default value must be a scalar, saw:
${a.shape}`);
let i = t.readSync(n.dataId), l = t.readSync(o.dataId), u = t.readSync(s.dataId), c = t.readSync(a.dataId)[0], [p, m, f, d, h] = vP(i, n.shape, n.dtype, l, o.dtype, u, c);
return [t.makeTensorInfo(m, n.dtype, p), t.makeTensorInfo([m[0]], o.dtype, f), t.makeTensorInfo([d.length], "bool", new Uint8Array(d.map((g) => Number(g)))), t.makeTensorInfo([h.length], n.dtype, new Int32Array(h))];
}
var Jz = { kernelName: hp, backendName: "webgl", kernelFunc: tre };
function rre(r) {
let { inputs: e, backend: t } = r, { inputIndices: n, inputShape: o, newShape: s } = e;
if (n.shape.length !== 2)
throw new Error(`Input indices should be a matrix but received shape ${n.shape}`);
if (o.shape.length !== 1)
throw new Error(`Input shape should be a vector but received shape ${o.shape}`);
if (s.shape.length !== 1)
throw new Error(`Target shape should be a vector but received shape ${s.shape}`);
let a = Array.from(t.readSync(o.dataId)), i = t.readSync(n.dataId), l = Array.from(t.readSync(s.dataId)), [u, c, p] = CP(i, n.shape, n.dtype, a, l);
return [t.makeTensorInfo(c, n.dtype, u), t.makeTensorInfo([p.length], s.dtype, new Int32Array(p))];
}
var Qz = { kernelName: gp, backendName: "webgl", kernelFunc: rre };
function nre(r) {
let { inputs: e, backend: t } = r, { data: n, indices: o, segmentIds: s } = e;
if (n.shape.length < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (o.shape.length !== 1)
throw new Error(`Indices should be a vector but received shape
${o.shape}`);
if (s.shape.length !== 1)
throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);
let a = t.readSync(n.dataId), i = t.readSync(o.dataId), l = t.readSync(s.dataId), [u, c] = Jy(a, n.shape, n.dtype, i, l, true);
return t.makeTensorInfo(c, n.dtype, u);
}
var e3 = { kernelName: xp, backendName: "webgl", kernelFunc: nre };
function ore(r) {
let { inputs: e, backend: t } = r, { data: n, indices: o, segmentIds: s } = e;
if (n.shape.length < 1)
throw new Error("Data should be at least 1 dimensional but received scalar");
if (o.shape.length !== 1)
throw new Error(`Indices should be a vector but received shape
${o.shape}`);
if (s.shape.length !== 1)
throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);
let a = t.readSync(n.dataId), i = t.readSync(o.dataId), l = t.readSync(s.dataId), [u, c] = Jy(a, n.shape, n.dtype, i, l);
return t.makeTensorInfo(c, n.dtype, u);
}
var t3 = { kernelName: yp, backendName: "webgl", kernelFunc: ore };
function sre(r) {
let { inputs: e, backend: t, attrs: n } = r, { sparseIndices: o, sparseValues: s, defaultValue: a } = e, { outputShape: i } = n, { sliceRank: l, numUpdates: u, strides: c, outputSize: p } = I.calculateShapes(s, o, i), m = false, f = new Jh(u, l, o.shape.length, s.shape.length, c, [p, 1], m), d = t.runWebGLProgram(f, [s, o, a], s.dtype), h = ue({ inputs: { x: d }, backend: t, attrs: { shape: i } });
return t.disposeIntermediateTensorInfo(d), h;
}
var r3 = { kernelName: bp, backendName: "webgl", kernelFunc: sre };
function ire(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { numOrSizeSplits: s, axis: a } = n, i = b.parseAxisParam(a, o.shape)[0], l = I.prepareSplitSize(o, s, i), u = o.shape.length, c = new Array(u).fill(0), p = o.shape.slice();
return l.map((m) => {
let f = [...p];
f[i] = m;
let d = Zs({ inputs: { x: o }, backend: t, attrs: { begin: c, size: f } });
return c[i] += m, d;
});
}
var n3 = { kernelName: fi, backendName: "webgl", kernelFunc: ire };
var o3 = "return sqrt(x);";
var are = ve({ opSnippet: o3, packedOpSnippet: o3, cpuKernelImpl: IP });
var s3 = { kernelName: ys, backendName: "webgl", kernelFunc: are };
var lre = "return x * x;";
var ure = ve({ opSnippet: lre });
var i3 = { kernelName: kl, backendName: "webgl", kernelFunc: ure };
var a3 = "return (a - b) * (a - b);";
var cre = at({ opSnippet: a3, packedOpSnippet: a3 });
var l3 = { kernelName: _s, backendName: "webgl", kernelFunc: cre };
function pre({ inputs: r, attrs: e, backend: t }) {
let { x: n } = r, o = Nr + `
return x > 0.0 ? 1.0 : float(${e.alpha});
`, s = new En(n.shape, o);
return t.runWebGLProgram(s, [n], n.dtype);
}
var u3 = { kernelName: no, backendName: "webgl", kernelFunc: pre };
var xS = class {
constructor(e, t, n) {
this.variableNames = ["x"], this.outputShape = n;
let o = n.length, s = Ue(n.length), a = Ue(n.length), i = "";
if (o === 1)
i = "coords * strides + begin";
else {
let l = 0;
i = n.map((u, c) => (l++, n.length === 1 ? `coords * strides[${c}] + begin[${c}]` : `coords[${l - 1}] * strides[${c}] + begin[${c}]`)).join(",");
}
this.userCode = `
${s} begin = ${s}(${e});
${s} strides = ${s}(${t});
void main() {
${a} coords = getOutputCoords();
setOutput(getX(${i}));
}
`;
}
};
function mre(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { begin: s, end: a, strides: i, beginMask: l, endMask: u, ellipsisMask: c, newAxisMask: p, shrinkAxisMask: m } = n, { nonStrided: f, $begin: d, $strides: h, size: g, newShape: x, outShape: y } = pr.sliceInfo(o.shape, s, a, i, l, u, c, p, m), w = ue({ inputs: { x: o }, backend: t, attrs: { shape: x } }), _;
if (f) {
let A = Zs({ inputs: { x: w }, backend: t, attrs: { begin: d, size: g } });
_ = ue({ inputs: { x: A }, backend: t, attrs: { shape: y } }), t.disposeIntermediateTensorInfo(A);
} else if (y.some((A) => A === 0))
_ = t.makeTensorInfo(y, o.dtype, []);
else if (t.shouldExecuteOnCPU([w])) {
let R = t.texData.get(w.dataId).values, P = Ie(w.shape, w.dtype, R), L = SP(y, P, h, d);
_ = t.makeTensorInfo(y, w.dtype, L.values);
} else {
let D = new xS(d, h, y);
_ = t.runWebGLProgram(D, [w], w.dtype);
}
let C = ue({ inputs: { x: _ }, backend: t, attrs: { shape: y } });
return t.disposeIntermediateTensorInfo(w), t.disposeIntermediateTensorInfo(_), C;
}
var c3 = { kernelName: ba, backendName: "webgl", kernelFunc: mre };
function fre(r) {
let { inputs: e, backend: t, attrs: n } = r, { separator: o, nGramWidths: s, leftPad: a, rightPad: i, padWidth: l, preserveShortSequences: u } = n, { data: c, dataSplits: p } = e, m = t.readSync(c.dataId), f = t.readSync(p.dataId), [d, h] = NP(m, f, o, s, a, i, l, u);
return [t.makeTensorInfo([d.length], "string", d), t.makeTensorInfo(p.shape, "int32", h)];
}
var p3 = { kernelName: wp, backendName: "webgl", kernelFunc: fre };
function dre(r) {
let { inputs: e, backend: t, attrs: n } = r, { skipEmpty: o } = n, { input: s, delimiter: a } = e;
if (s.dtype !== "string")
throw new Error("Input must be of datatype string");
if (s.shape.length !== 1)
throw new Error(`Input must be a vector, got shape: ${s.shape}`);
if (a.shape.length !== 0)
throw new Error(`Delimiter must be a scalar, got shape: ${a.shape}`);
let i = t.readSync(s.dataId), l = t.readSync(a.dataId)[0], [u, c, p] = TP(i, l, o), m = c.length;
return [t.makeTensorInfo([m, 2], "int32", u), t.makeTensorInfo([m], "string", c), t.makeTensorInfo([2], "int32", new Int32Array(p))];
}
var m3 = { kernelName: _p, backendName: "webgl", kernelFunc: dre };
function hre(r) {
let { inputs: e, backend: t, attrs: n } = r, { numBuckets: o } = n, { input: s } = e;
if (s.dtype !== "string")
throw new Error("Input must be of datatype string");
if (o <= 0)
throw new Error("Number of buckets must be at least 1");
let a = t.readSync(s.dataId), i = EP(a, o);
return t.makeTensorInfo(s.shape, "int32", i);
}
var f3 = { kernelName: kp, backendName: "webgl", kernelFunc: hre };
var gre = "return tan(x);";
var xre = ve({ opSnippet: gre });
var d3 = { kernelName: vs, backendName: "webgl", kernelFunc: xre };
var yre = `
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`;
var bre = ve({ opSnippet: yre });
var h3 = { kernelName: Cs, backendName: "webgl", kernelFunc: bre };
var yS = class {
constructor(e, t) {
this.variableNames = ["A"];
let n = new Array(e.length);
for (let a = 0; a < n.length; a++)
n[a] = e[a] * t[a];
this.outputShape = n, this.rank = n.length;
let o = Ue(this.rank), s = wre(e);
this.userCode = `
void main() {
${o} resRC = getOutputCoords();
setOutput(getA(${s}));
}
`;
}
};
function wre(r) {
let e = r.length;
if (e > 5)
throw Error(`Tile for rank ${e} is not yet supported`);
if (e === 1)
return `imod(resRC, ${r[0]})`;
let t = ["resRC.x", "resRC.y", "resRC.z", "resRC.w", "resRC.u"], n = [];
for (let o = 0; o < r.length; o++)
n.push(`imod(${t[o]}, ${r[o]})`);
return n.join();
}
function bS(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { reps: s } = n;
if (o.dtype === "string" || o.shape.length > 5) {
let l = t.readSync(o.dataId), u = o.dtype === "string" ? l.map((m) => b.decodeString(m)) : l, c = Ie(o.shape, o.dtype, u), p = DP(c, s);
return t.makeTensorInfo(p.shape, p.dtype, p.values);
}
let a = new yS(o.shape, s);
return t.runWebGLProgram(a, [o], o.dtype);
}
var g3 = { kernelName: Hn, backendName: "webgl", kernelFunc: bS };
var wS = class {
constructor(e) {
this.variableNames = ["x", "indices"], this.customUniforms = [{ name: "n", type: "int" }, { name: "firstPass", type: "int" }, { name: "negativeInf", type: "float" }, { name: "dir", type: "int" }, { name: "inc", type: "int" }], this.outputShape = e, this.userCode = `
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
// We compare elements pair-wise within a group of size 2 * inc.
// The comparing rule for each group alternates between ascending
// and descending. Within each group, we compare each pair at
// positions i and i+inc. To decide whether an element at position i
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
// inc, it is in the first half of the group, we denote it as x0,
// otherwise we denote it as x1.
// For example, as shown in the Bitonic top K paper referenced above,
// Figure5(a) shows that element[1] is in the
// second half of the group when group size is 2, but it is in the
// first half of the group when group size is 4.
bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
int i = isFirstInPair ? elemIdx : elemIdx - inc;
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));
float x0 = i0 < n ? getX(batch, i0) : negativeInf;
float x1 = i1 < n ? getX(batch, i1) : negativeInf;
// Denotes which direction indices are in (ascending or descending).
bool reverse = imod(elemIdx, 2 * dir) >= dir;
bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
if (reverse == isGreater) { // Elements in opposite order of direction
int iTemp = i0;
i0 = i1;
i1 = iTemp;
}
if (isFirstInPair) {
setOutput(float(i0));
} else {
setOutput(float(i1));
}
}
`;
}
};
var _S = class {
constructor(e) {
this.variableNames = ["x", "indices"], this.customUniforms = [{ name: "n", type: "int" }, { name: "firstPass", type: "int" }, { name: "k", type: "int" }], this.outputShape = e, this.userCode = `
void main() {
// Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
// The output size is half of the previous size.
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),
// we only need to output the indices at positions |, the indices at
// positions _ can be thrown away, see Figure5(b) After Phase 2
// (Merge phase) in the Bitonic Top K paper referenced above.
// For example, the paper shows we only need to output the orange bars.
// The output sequence should look like this | | | | | | | |.
// Because the sequence is halved, to map the output index back
// to the previous sequence to find the corresponding value,
// we need to double the index. When we double the index,
// we basically interpolate a position, so 2i looks like
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
// of each 2k positions by - elemIdx % k. E.g. for output at
// index 4,5,6,7, we want to get the corresponding element at
// original index 8,9,10,11, for output at index 8,9,10,11,
// we want to get the corresponding element at original index
// 16,17,18,19, so on and so forth.
int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));
float x0 = getX(batch, i0);
float x1 = i1 < n ? getX(batch, i1) : x0;
setOutput(x0 >= x1 ? float(i0) : float(i1));
}
`;
}
};
function Nc(r, e) {
e !== null && r.disposeIntermediateTensorInfo(e);
}
function x3(r) {
let e = 1;
for (; e < r; )
e *= 2;
return e;
}
function _re(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { k: s, sorted: a } = n, i = U().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"), l = U().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"), u = o.shape, c = u[u.length - 1];
if (t.shouldExecuteOnCPU([o]) || c < i || s > l) {
let L = t.readSync(o.dataId), [G, W] = $P(L, u, o.dtype, s, a);
return [t.makeTensorInfo(G.shape, G.dtype, G.values), t.makeTensorInfo(W.shape, W.dtype, W.values)];
}
if (s === 0)
return u[u.length - 1] = 0, [t.makeTensorInfo(u, o.dtype, []), t.makeTensorInfo(u, "int32", [])];
if (c === 1)
return [o, rl({ attrs: { shape: u, dtype: "int32", value: 0 }, backend: t })];
let p = t.texData.get(o.dataId), m = p !== null && p.isPacked, f = m ? t.unpackTensor(o) : o, h = b.sizeFromShape(u) / c, g = ue({ inputs: { x: f }, attrs: { shape: [h, c] }, backend: t });
m && Nc(t, f);
let x = x3(s), y = x3(c), w = null, _ = () => w === null ? [g, g] : [g, w], C = (L, G, W) => {
let j = _(), H = new wS(W), X = [[c], [w === null ? 1 : 0], [Number.NEGATIVE_INFINITY], [L], [G]], re = w;
w = t.runWebGLProgram(H, j, "int32", X), Nc(t, re);
};
for (let L = 1; L < x; L *= 2) {
let G = L * 2;
for (let W = L; W >= 1; W /= 2)
C(G, W, [h, y]);
}
for (let L = y; L > x; L /= 2) {
let G = _(), W = new _S([h, L / 2]), H = [[c], [w === null ? 1 : 0], [x]], q = w;
w = t.runWebGLProgram(W, G, "int32", H), Nc(t, q);
let X = x / 2, re = X * 2;
for (let J = X; J >= 1; J /= 2)
C(re, J, w.shape);
}
let A = w;
w = Zs({ inputs: { x: w }, backend: t, attrs: { begin: 0, size: [h, s] } }), Nc(t, A);
let D = WI({ inputs: { x: g, indices: w }, backend: t, attrs: { axis: 1, batchDims: 1 } });
Nc(t, g);
let R = u.slice(0, -1);
R.push(s), A = w, w = ue({ inputs: { x: w }, attrs: { shape: R }, backend: t }), Nc(t, A);
let P = D;
return D = ue({ inputs: { x: D }, attrs: { shape: R }, backend: t }), Nc(t, P), [D, w];
}
var y3 = { kernelName: wa, backendName: "webgl", kernelFunc: _re };
var kS = class {
constructor(e, t, n, o, s, a) {
this.variableNames = ["Image", "Transforms"], this.outputShape = a;
let i = n === "nearest" ? 1 : 2, l;
switch (o) {
case "constant":
l = 1;
break;
case "reflect":
l = 2;
break;
case "wrap":
l = 3;
break;
case "nearest":
l = 4;
break;
default:
l = 1;
break;
}
this.userCode = `
float mapCoord(float outCoord, float len) {
float inCoord = outCoord;
if(${l} == 2) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz2 = 2.0 * len;
if (inCoord < sz2) {
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
inCoord;
}
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz2 = 2.0 * len;
inCoord -= sz2 * float(int(float(inCoord / sz2)));
if (inCoord >= len) {
inCoord = sz2 - inCoord - 1.0;
}
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (${l} == 3) {
if (inCoord < 0.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz = len - 1.0;
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
}
} else if (inCoord > len - 1.0) {
if (len <= 1.0) {
inCoord = 0.0;
} else {
float sz = len - 1.0;
inCoord -= len * float(int(float(inCoord / sz)));
}
}
return clamp(inCoord, 0.0, len - 1.0);
} else if (${l} == 4) {
return clamp(outCoord, 0.0, len - 1.0);
} else {
return outCoord;
}
}
float readWithFillValue(int batch, int coordY, int coordX,
int channel) {
float outputValue;
if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
outputValue = getImage(batch, coordY, coordX, channel);
} else {
outputValue = float(${s});
}
return outputValue;
}
void main() {
ivec4 coords = getOutputCoords();
float outputValue;
int batch = coords[0];
int x = coords[2];
int y = coords[1];
int channel = coords[3];
float xf = float(x);
float yf = float(y);
float a1 = getTransforms(batch, 0);
float a2 = getTransforms(batch, 1);
float a3 = getTransforms(batch, 2);
float b1 = getTransforms(batch, 3);
float b2 = getTransforms(batch, 4);
float b3 = getTransforms(batch, 5);
float c1 = getTransforms(batch, 6);
float c2 = getTransforms(batch, 7);
float projection = c1 * xf + c2 * yf + 1.0;
if (projection == 0.0) {
outputValue = float(${s});
} else {
float inX = (a1 * xf + a2 * yf + a3) / projection;
float inY = (b1 * xf + b2 * yf + b3) / projection;
float mapX = mapCoord(inX, float(${t}));
float mapY = mapCoord(inY, float(${e}));
if (${i} == 1) {
int coordY = int(round(mapY));
int coordX = int(round(mapX));
outputValue = readWithFillValue(batch, coordY, coordX,
channel);
} else {
float yFloor = floor(mapY);
float xFloor = floor(mapX);
float yCeil = yFloor + 1.0;
float xCeil = xFloor + 1.0;
float valueYFloor = (xCeil - mapX) *
readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, int(yFloor), int(xCeil), channel);
float valueYCeil = (xCeil - mapX) *
readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
(mapX - xFloor) *
readWithFillValue(batch, int(yCeil), int(xCeil), channel);
outputValue = (yCeil - mapY) * valueYFloor +
(mapY - yFloor) * valueYCeil;
}
}
setOutput(outputValue);
}
`;
}
};
function kre(r) {
let { inputs: e, backend: t, attrs: n } = r, { image: o, transforms: s } = e, { interpolation: a, fillMode: i, fillValue: l, outputShape: u } = n, [c, p, m, f] = o.shape, [d, h] = u != null ? u : [p, m], g = [c, d, h, f], x = new kS(p, m, a, i, l, g);
return t.runWebGLProgram(x, [o, s], "float32");
}
var b3 = { kernelName: _a, backendName: "webgl", kernelFunc: kre };
function vre(r) {
let { inputs: e, attrs: t, backend: n } = r, { axis: o } = t, { x: s } = e;
qs(s, "unique"), console.warn("WARNING: ", "UI might be locked temporarily as data is being downloaded");
let a = n.readSync(s.dataId), { outputValues: i, outputShape: l, indices: u } = RP(a, o, s.shape, s.dtype);
return [n.makeTensorInfo(l, s.dtype, i), n.makeTensorInfo([u.length], "int32", u)];
}
var w3 = { kernelName: vp, backendName: "webgl", kernelFunc: vre };
function Cre(r) {
let { inputs: e, backend: t, attrs: n } = r, { value: o } = e, { axis: s } = n;
s < 0 && (s += o.shape.length);
let a = o, i = a.shape.length, l = o.shape[s], u = new Array(i - 1), c = 0;
for (let h = 0; h < i; h++)
h !== s && (u[c++] = a.shape[h]);
let p = [], m = new Array(i).fill(0), f = a.shape.slice();
f[s] = 1;
let d = new Array(l);
for (let h = 0; h < d.length; h++) {
m[s] = h;
let g = Zs({ inputs: { x: a }, backend: t, attrs: { begin: m, size: f } }), x = ue({ inputs: { x: g }, backend: t, attrs: { shape: u } });
d[h] = x, p.push(g);
}
return p.forEach((h) => t.disposeIntermediateTensorInfo(h)), d;
}
var _3 = { kernelName: di, backendName: "webgl", kernelFunc: Cre };
var vS = class {
constructor(e, t) {
this.variableNames = ["x", "segmentIds"];
let n = e.windowSize, o = e.batchSize, s = e.inSize, a = e.numSegments, i = a * Math.ceil(s / n);
this.outputShape = [o, i];
let l = "0.0", u = "sumValue", c = Math.floor(n / 4) * 4, p = n % 4, m = `
sumValue += dot(values, segFilter);
`, f = "";
s % n > 0 && (f = `
if (inIdx < 0 || inIdx >= ${s}) {
return initializationValue;
}
`);
let d = "";
s % n > 0 && (d = `
if (inIdx < 0 || inIdx >= ${s}) {
return -1.0;
}
`), this.userCode = `
const float initializationValue = ${l};
float getValue(int batch, int inIdx) {
${f}
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
${d}
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${a})) * float(${n}));
int currentSeg = int(mod(float(outIdx), float(${a})));
float sumValue = 0.0;
for (int i = 0; i < ${c}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
${m}
}
int inIdx = inOffset + ${c};
if (${p === 1}) {
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
${m}
} else if (${p === 2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
${m}
} else if (${p === 3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
${m}
}
setOutput(${u});
}
`;
}
};
function Ire(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o, segmentIds: s } = e, { numSegments: a } = n, i = o.shape.length, l = [], u = 0, c = I.getAxesPermutation([u], i), p = o;
c != null && (p = Pt({ inputs: { x: o }, backend: t, attrs: { perm: c } }), l.push(p), u = I.getInnerMostAxes(1, i)[0]);
let m = I.segment_util.computeOutShape(p.shape, u, a), f = b.sizeFromShape([p.shape[u]]), d = ue({ inputs: { x: p }, backend: t, attrs: { shape: [-1, f] } });
l.push(d);
let h = hu(o.dtype), g = (_, C, A, D, R) => {
let P = _.shape[0], L = _.shape[1], G = I.segment_util.segOpComputeOptimalWindowSize(L, R), W = { windowSize: G, inSize: L, batchSize: P, numSegments: R }, j = new vS(W, C), H = t.compileAndRun(j, [_, A], D);
if (l.push(H), H.shape[1] === R)
return H;
let q = iS({ backend: t, attrs: { start: 0, stop: R, step: 1, dtype: "float32" } }), X = bS({ inputs: { x: q }, backend: t, attrs: { reps: [L / G] } });
return l.push(q), l.push(X), g(H, C, X, D, R);
}, x = g(d, "unsortedSegmentSum", s, h, a), y = ue({ inputs: { x }, backend: t, attrs: { shape: m } }), w = y;
if (c != null) {
l.push(y);
let _ = I.getUndoAxesPermutation(c);
w = Pt({ inputs: { x: w }, backend: t, attrs: { perm: _ } });
}
return l.forEach((_) => t.disposeIntermediateTensorInfo(_)), w;
}
var k3 = { kernelName: vl, backendName: "webgl", kernelFunc: Ire };
var Sre = [XL, YL, uM, pM, mM, fM, hM, gM, xM, yM, _M, kM, vM, CM, SM, IM, NM, EM, TM, AM, DM, $M, RM, OM, PM, MM, VM, WM, UM, HM, ZP, KM, YM, ZM, XM, QM, eL, JM, tL, rL, nL, iL, aL, lL, cL, pL, uL, mL, fL, dL, hL, gL, xL, yL, wL, _L, vL, CL, IL, SL, TL, EL, AL, DL, $L, RL, FL, OL, PL, YP, ML, qM, LL, zL, BL, JP, VL, GL, WL, jL, UL, HL, qL, KL, JL, tz, ez, rz, nz, sz, QL, az, lz, uz, cz, pz, gz, nM, yz, bz, wz, _z, LM, kz, Iz, Sz, Nz, Tz, QP, Ez, Az, zM, mz, Dz, Rz, $z, sM, Fz, Oz, Pz, Mz, Lz, zz, Bz, Vz, Gz, Wz, Uz, Hz, qz, Kz, Xz, FM, hz, Yz, Zz, Jz, Qz, e3, t3, r3, n3, s3, i3, l3, u3, c3, p3, m3, f3, dz, aM, d3, h3, g3, y3, b3, lM, w3, _3, k3, vz];
for (let r of Sre)
uu(r);
var et;
(function(r) {
r[r.float32 = 0] = "float32", r[r.int32 = 1] = "int32", r[r.bool = 2] = "bool", r[r.string = 3] = "string", r[r.complex64 = 4] = "complex64";
})(et || (et = {}));
var Zl;
(function(r) {
r[r.linear = 0] = "linear", r[r.relu = 1] = "relu", r[r.relu6 = 2] = "relu6", r[r.prelu = 3] = "prelu", r[r.leakyrelu = 4] = "leakyrelu", r[r.sigmoid = 5] = "sigmoid", r[r.elu = 6] = "elu";
})(Zl || (Zl = {}));
var v3;
function Nre(r) {
v3 = r.wasm.cwrap(gi, null, ["number", "array", "number", "number", "array", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Tre(r) {
let { inputs: e, backend: t, attrs: n } = r, { a: o, b: s, bias: a, preluActivationWeights: i } = e;
if (o.dtype !== "float32" || s.dtype !== "float32")
throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");
let { transposeA: l, transposeB: u, activation: c, leakyreluAlpha: p } = n, m = t.dataIdMap.get(o.dataId).id, f = t.dataIdMap.get(s.dataId).id, d = 0;
if (a != null) {
let R = t.dataIdMap.get(a.dataId);
if (R.shape.length !== 1)
throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${R.shape.length}.`);
d = R.id;
}
let h = i == null ? 0 : t.dataIdMap.get(i.dataId).id, g = Zl[c];
if (g == null)
throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);
let x = l ? o.shape[2] : o.shape[1], y = u ? s.shape[1] : s.shape[2], w = o.shape[0], _ = t.makeOutput([w, x, y], o.dtype), C = t.dataIdMap.get(_.dataId).id, A = new Uint8Array(new Int32Array(o.shape).buffer), D = new Uint8Array(new Int32Array(s.shape).buffer);
return v3(m, A, o.shape.length, f, D, s.shape.length, l, u, g, d, h, p || 0, C), _;
}
var C3 = { kernelName: gi, backendName: "wasm", setupFunc: Nre, kernelFunc: Tre };
function lt(r, e) {
let t;
function n(s) {
t = s.wasm.cwrap(r, null, ["number", "number", "number"]);
}
function o(s) {
let { backend: a, inputs: { x: i } } = s, l = a.dataIdMap.get(i.dataId).id, u = a.makeOutput(i.shape, e || i.dtype), c = a.dataIdMap.get(u.dataId).id;
return b.sizeFromShape(u.shape) === 0 || t(l, et[i.dtype], c), u;
}
return { kernelName: r, backendName: "wasm", setupFunc: n, kernelFunc: o };
}
var I3 = lt(ti);
function kt(r, e, t) {
let n;
function o(a) {
n = a.wasm.cwrap(r, null, ["number", "array", "number", "number", "array", "number", "number", "number"]);
}
function s(a) {
let { backend: i, inputs: l } = a, { a: u, b: c } = l, p = i.dataIdMap.get(u.dataId).id, m = i.dataIdMap.get(c.dataId).id, f = t != null ? t : u.dtype, d = I.assertAndGetBroadcastShape(u.shape, c.shape), h = i.makeOutput(d, f);
if (b.sizeFromShape(d) === 0)
return h;
let g = new Uint8Array(new Int32Array(u.shape).buffer), x = new Uint8Array(new Int32Array(c.shape).buffer), y = i.dataIdMap.get(h.dataId).id, w = () => n(p, g, u.shape.length, m, x, c.shape.length, et[u.dtype], y);
if (e && u.dtype === "float32")
return w(), h;
let _ = I.getBroadcastDims(u.shape, d), C = I.getBroadcastDims(c.shape, d), A = _.every((R, P) => R === P), D = C.every((R, P) => R === P);
if (A && D)
return w(), h;
throw new Error(`Broadcasting along outer dims is not yet supported for ${u.dtype} ${r}.`);
}
return { kernelName: r, backendName: "wasm", setupFunc: o, kernelFunc: s };
}
var Ere = true;
var S3 = kt(jn, Ere);
var N3;
function Are(r) {
N3 = r.wasm.cwrap($o, null, ["array", "number", "number", "number"]);
}
function Dre(r) {
let { inputs: e, backend: t } = r, n = t.makeOutput(e[0].shape, e[0].dtype);
if (b.sizeFromShape(n.shape) === 0)
return n;
let o = e.map((i) => t.dataIdMap.get(i.dataId).id), s = new Uint8Array(new Int32Array(o).buffer), a = t.dataIdMap.get(n.dataId).id;
return N3(s, o.length, et[n.dtype], a), n;
}
var T3 = { kernelName: $o, backendName: "wasm", setupFunc: Are, kernelFunc: Dre };
function Tc(r) {
let { inputs: { x: e }, backend: t } = r, n = t.makeOutput(e.shape, e.dtype), o = t.typedArrayFromHeap(e);
return t.typedArrayFromHeap(n).set(o), n;
}
var E3 = { kernelName: ro, backendName: "wasm", kernelFunc: Tc };
var A3;
function $re(r) {
A3 = r.wasm.cwrap(Is, null, ["number", "array", "number", "number", "number", "array", "number"]);
}
function $i(r) {
let { inputs: e, backend: t, attrs: n } = r, [o, s] = Fre(e.x.shape, n.perm), a = true;
for (let d = 0; d < s.length; d++)
s[d] !== d && (a = false);
let i = Rre(e.x.shape, n.perm), l = { dataId: e.x.dataId, shape: o, dtype: e.x.dtype };
if (a) {
let d = Tc({ inputs: e, backend: t });
return d.shape = i, d;
}
let u = t.makeOutput(i, l.dtype), c = t.dataIdMap.get(l.dataId).id, p = t.dataIdMap.get(u.dataId).id, m = new Uint8Array(new Int32Array(s).buffer), f = new Uint8Array(new Int32Array(l.shape).buffer);
return A3(c, f, l.shape.length, et[l.dtype], p, m, s.length), u;
}
function Rre(r, e) {
let t = new Array(r.length);
for (let n = 0; n < t.length; n++)
t[n] = r[e[n]];
return t;
}
function Fre(r, e) {
let t = [], n = [];
for (let o = 0; o < r.length; ++o)
r[o] !== 1 && t.push(r[o]), r[e[o]] !== 1 && n.push(e[o]);
for (let o = 0; o < n.length; ++o) {
let s = -1;
for (let a = 0; a < n.length; ++a)
n[a] >= o && (s === -1 || n[s] > n[a]) && (s = a);
n[s] = o;
}
return [t, n];
}
var D3 = { kernelName: Is, backendName: "wasm", kernelFunc: $i, setupFunc: $re };
function hn(r, e, t) {
let n = r.shape, o = r.shape.length, s = b.parseAxisParam(e, n), a = s, i = I.getAxesPermutation(a, o), l = null, u = false;
if (i != null) {
let c = new Array(o);
for (let f = 0; f < c.length; f++)
c[f] = n[i[f]];
a = I.getInnerMostAxes(a.length, o), l = $i({ inputs: { x: r }, attrs: { perm: i }, backend: t });
let p = t.dataIdMap.get(r.dataId).id;
t.dataIdMap.get(l.dataId).id !== p && (u = true);
}
return { transposed: l, originalAxes: s, axes: a, inputWasTransposed: u };
}
var $3;
function Ore(r) {
$3 = r.wasm.cwrap(zi, null, ["number, number, number"]);
}
function Pre(r) {
let { backend: e, inputs: t, attrs: n } = r, { axis: o, keepDims: s } = n, { x: a } = t, l = e.dataIdMap.get(a.dataId).id, u = a, { transposed: c, axes: p, originalAxes: m, inputWasTransposed: f } = hn(a, o, e);
if (f) {
let w = e.dataIdMap.get(c.dataId).id;
u = c, l = w;
}
let d = u.shape.length;
I.assertAxesAreInnerMostDims("all", p, d);
let [h, g] = I.computeOutAndReduceShapes(u.shape, p), x = b.sizeFromShape(g), y = e.makeOutput(h, a.dtype);
if (b.sizeFromShape(u.shape) !== 0) {
let w = e.dataIdMap.get(y.dataId).id;
$3(l, x, w);
}
if (f && e.disposeData(c.dataId), s) {
let w = I.expandShapeToKeepDim(y.shape, m);
y.shape = w;
}
return y;
}
var R3 = { kernelName: zi, backendName: "wasm", setupFunc: Ore, kernelFunc: Pre };
var F3;
function Mre(r) {
F3 = r.wasm.cwrap(Bi, null, ["number, number, number"]);
}
function Lre(r) {
let { backend: e, inputs: t, attrs: n } = r, { axis: o, keepDims: s } = n, { x: a } = t, l = e.dataIdMap.get(a.dataId).id, u = a, { transposed: c, axes: p, originalAxes: m, inputWasTransposed: f } = hn(a, o, e);
if (f) {
let w = e.dataIdMap.get(c.dataId).id;
u = c, l = w;
}
let d = u.shape.length;
I.assertAxesAreInnerMostDims("any", p, d);
let [h, g] = I.computeOutAndReduceShapes(u.shape, p), x = b.sizeFromShape(g), y = e.makeOutput(h, a.dtype);
if (b.sizeFromShape(u.shape) !== 0) {
let w = e.dataIdMap.get(y.dataId).id;
F3(l, x, w);
}
if (f && e.disposeData(c.dataId), s) {
let w = I.expandShapeToKeepDim(y.shape, m);
y.shape = w;
}
return y;
}
var O3 = { kernelName: Bi, backendName: "wasm", setupFunc: Mre, kernelFunc: Lre };
var P3;
function zre(r) {
P3 = r.wasm.cwrap(Ro, null, ["number", "number", "number", "number", "number"]);
}
function Bre(r) {
let { backend: e, inputs: t, attrs: n } = r, { axis: o } = n, { x: s } = t, a = e.dataIdMap.get(s.dataId).id, i = a, l = s, { transposed: u, axes: c, inputWasTransposed: p } = hn(s, o, e);
if (p) {
let x = e.dataIdMap.get(u.dataId).id;
x !== a && (l = u, i = x);
}
let m = l.shape.slice(0, -1), f = e.makeOutput(m, "int32"), d = e.dataIdMap.get(f.dataId).id, h = b.sizeFromShape(f.shape), g = l.shape[c[0]];
return P3(i, et[l.dtype], h, g, d), p && e.disposeData(u.dataId), f;
}
var M3 = { kernelName: Ro, backendName: "wasm", kernelFunc: Bre, setupFunc: zre };
var L3;
function Vre(r) {
L3 = r.wasm.cwrap(Fo, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Gre(r) {
let { inputs: e, attrs: t, backend: n } = r, o = e.x, s = n.dataIdMap.get(o.dataId).id, { filterSize: a, strides: i, pad: l, dimRoundingMode: u } = t, c = I.computePool2DInfo(o.shape, a, i, 1, l, u), p = c.filterHeight, m = c.filterWidth, f = c.padInfo.top, d = c.padInfo.right, h = c.padInfo.bottom, g = c.padInfo.left, x = c.strideHeight, y = c.strideWidth, w = c.inChannels;
if (c.dataFormat !== "channelsLast")
throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);
if (c.dilationWidth !== 1 || c.dilationHeight !== 1)
throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${c.dilationHeight}, ${c.dilationWidth}].`);
let _ = n.makeOutput(c.outShape, "float32"), C = n.dataIdMap.get(_.dataId).id;
return L3(s, o.shape[0], o.shape[1], o.shape[2], p, m, f, d, h, g, x, y, w, C), _;
}
var z3 = { kernelName: Fo, backendName: "wasm", setupFunc: Vre, kernelFunc: Gre };
function ar(r) {
let { inputs: e, attrs: t } = r, { x: n } = e, { shape: o } = t, s = b.sizeFromShape(n.shape), a = b.inferFromImplicitShape(o, s);
return b.assert(s === b.sizeFromShape(a), () => `new shape: ${a}, old shape: ${n.shape}. New shape and old shape must have the same number of elements.`), r.backend.incRef(n.dataId), { dataId: n.dataId, shape: a, dtype: n.dtype };
}
var B3 = { kernelName: ui, backendName: "wasm", kernelFunc: ar };
var V3;
function Wre(r) {
V3 = r.wasm.cwrap(Oo, null, ["number", "array", "number", "number", "array", "number", "number", "number", "number"]);
}
function Ure(r) {
let { inputs: e, backend: t, attrs: n } = r, { a: o, b: s } = e, { transposeA: a, transposeB: i } = n;
if (o.dtype !== "float32" || s.dtype !== "float32")
throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");
let l = o.shape.length, u = s.shape.length, c = a ? o.shape[l - 2] : o.shape[l - 1], p = i ? s.shape[u - 1] : s.shape[u - 2], m = a ? o.shape[l - 1] : o.shape[l - 2], f = i ? s.shape[u - 2] : s.shape[u - 1], d = o.shape.slice(0, -2), h = s.shape.slice(0, -2), g = b.sizeFromShape(d), x = b.sizeFromShape(h), y = g === x || g === 1 || x === 1;
b.assert(l >= 2 && u >= 2 && y, () => `Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${d}) and (${h}).`);
let _ = (g > x ? o.shape.slice(0, -2) : s.shape.slice(0, -2)).concat([m, f]);
b.assert(c === p, () => `Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${o.shape} and ${s.shape} and transposeA=${a} and transposeB=${i} must match.`);
let C = a ? [g, c, m] : [g, m, c], A = i ? [x, f, p] : [x, p, f], D = ar({ inputs: { x: o }, backend: t, attrs: { shape: C } }), R = ar({ inputs: { x: s }, backend: t, attrs: { shape: A } }), P = t.dataIdMap.get(D.dataId).id, L = t.dataIdMap.get(R.dataId).id, G = a ? D.shape[2] : D.shape[1], W = i ? R.shape[1] : R.shape[2], j = Math.max(g, x), H = t.makeOutput([j, G, W], D.dtype), q = t.dataIdMap.get(H.dataId).id, X = new Uint8Array(new Int32Array(D.shape).buffer), re = new Uint8Array(new Int32Array(R.shape).buffer);
return V3(P, X, D.shape.length, L, re, R.shape.length, a, i, q), t.disposeData(D.dataId), t.disposeData(R.dataId), H.shape = _, H;
}
var G3 = { kernelName: Oo, backendName: "wasm", setupFunc: Wre, kernelFunc: Ure };
function nl(r) {
let { inputs: { x: e }, attrs: { begin: t, size: n }, backend: o } = r, [s, a] = pr.parseSliceParams(e, t, n), i = pr.isSliceContinous(e.shape, s, a), l = o.readSync(e.dataId), u = o.makeOutput(a, e.dtype), c = b.computeStrides(e.shape), p = o.dataIdMap.get(u.dataId);
if (i) {
let d = pr.computeFlatOffset(s, c);
return e.dtype === "string" ? p.stringBytes = l.slice(d, d + b.sizeFromShape(a)) : o.typedArrayFromHeap(u).set(l.subarray(d, d + b.sizeFromShape(a))), u;
}
if (e.dtype === "string") {
let d = hc(l, s, a, e.shape, e.dtype);
return p.stringBytes = d, u;
}
let m = o.typedArrayFromHeap(u), f = e.shape.length;
if (f === 2)
jre(l, c[0], m, s, a);
else if (f === 3)
Hre(l, c[0], c[1], m, s, a);
else if (f === 4)
qre(l, c[0], c[1], c[2], m, s, a);
else {
let d = hc(l, s, a, e.shape, e.dtype);
m.set(d);
}
return u;
}
function jre(r, e, t, n, o) {
let s = 0, a = n[0], i = n[1], l = a + o[0];
for (let u = a; u < l; u++) {
let c = u * e + i;
t.set(r.subarray(c, c + o[1]), s), s += o[1];
}
}
function Hre(r, e, t, n, o, s) {
let a = 0, i = o[0], l = o[1], u = o[2], c = i + s[0], p = l + s[1];
for (let m = i; m < c; m++)
for (let f = l; f < p; f++) {
let d = m * e + f * t + u;
n.set(r.subarray(d, d + s[2]), a), a += s[2];
}
}
function qre(r, e, t, n, o, s, a) {
let i = 0, l = s[0], u = s[1], c = s[2], p = l + a[0], m = u + a[1], f = c + a[2], d = s[3];
for (let h = l; h < p; h++)
for (let g = u; g < m; g++)
for (let x = c; x < f; x++) {
let y = h * e + g * t + x * n + d;
o.set(r.subarray(y, y + a[3]), i), i += a[3];
}
}
var W3 = { kernelName: pi, backendName: "wasm", kernelFunc: nl };
function Kre(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { blockShape: s, crops: a } = n, i = s.reduce((x, y) => x * y), l = I.getReshaped(o.shape, s, i), u = I.getPermuted(l.length, s.length), c = I.getReshapedPermuted(o.shape, s, i), p = I.getSliceBeginCoords(a, s.length), m = I.getSliceSize(c, a, s.length), f = ar({ inputs: { x: o }, backend: t, attrs: { shape: l } }), d = $i({ inputs: { x: f }, backend: t, attrs: { perm: u } }), h = ar({ inputs: { x: d }, backend: t, attrs: { shape: c } }), g = nl({ inputs: { x: h }, backend: t, attrs: { begin: p, size: m } });
return t.disposeData(f.dataId), t.disposeData(d.dataId), t.disposeData(f.dataId), g;
}
var U3 = { kernelName: ri, backendName: "wasm", kernelFunc: Kre };
function ol(r) {
let { inputs: { x: e }, attrs: { dtype: t }, backend: n } = r, o = n.makeOutput(e.shape, t), s = n.typedArrayFromHeap(e);
return n.typedArrayFromHeap(o).set(s), o;
}
var j3 = { kernelName: eo, backendName: "wasm", kernelFunc: ol };
var H3 = lt(Po);
var q3;
function Xre(r) {
q3 = r.wasm.cwrap(to, null, ["number", "number", "number", "number"]);
}
function Yre(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { clipValueMin: s, clipValueMax: a } = n, i = t.dataIdMap.get(o.dataId).id, l = t.makeOutput(o.shape, o.dtype), u = t.dataIdMap.get(l.dataId).id;
return q3(i, s, a, u), l;
}
var K3 = { kernelName: to, backendName: "wasm", setupFunc: Xre, kernelFunc: Yre };
function CS(r) {
let { inputs: e, backend: t } = r, n = b.parseAxisParam(r.attrs.axis, e[0].shape)[0], o = I.computeOutShape(e.map((f) => f.shape), n), s = e.filter((f) => b.sizeFromShape(f.shape) > 0);
if (s.length === 1)
return Tc({ inputs: { x: s[0] }, backend: t });
let a = t.makeOutput(o, e[0].dtype);
if (b.sizeFromShape(o) === 0)
return a;
let i = s.map((f) => f.shape);
if (I.assertParamsConsistent(i, n), s[0].dtype === "string") {
let f = s.map((w) => {
let _ = b.sizeFromShape(w.shape.slice(n));
return ar({ inputs: { x: w }, backend: t, attrs: { shape: [-1, _] } });
}), d = f.map((w) => ({ vals: t.readSync(w.dataId), shape: w.shape }));
o = I.computeOutShape(f.map((w) => w.shape), 1);
let h = f[0].shape[0] === 1, g = mc(d, o, e[0].dtype, h), x = I.computeOutShape(s.map((w) => w.shape), n);
a.shape = x;
let y = t.dataIdMap.get(a.dataId);
return y.stringBytes = I.fromStringArrayToUint8(g), f.forEach((w) => t.disposeData(w.dataId)), a;
}
let l = b.sizeFromShape(s[0].shape.slice(0, n)), u = 0, c = s.map((f) => {
let d = b.sizeFromShape(f.shape.slice(n));
return u += d, d;
}), p = s.map((f) => t.typedArrayFromHeap(f)), m = t.typedArrayFromHeap(a);
for (let f = 0; f < l; f++) {
let d = f * u;
for (let h = 0; h < p.length; h++) {
let g = c[h], x = f * g, y = p[h].subarray(x, x + g);
m.set(y, d), d += g;
}
}
return a;
}
var X3 = { kernelName: ni, backendName: "wasm", kernelFunc: CS };
var Y3;
function Zre(r) {
Y3 = r.wasm.cwrap(Mo, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Jre(r) {
let { inputs: e, attrs: t, backend: n } = r, { x: o, filter: s } = e, a = n.dataIdMap.get(o.dataId).id, i = n.dataIdMap.get(s.dataId).id, { strides: l, dilations: u, pad: c, dimRoundingMode: p, dataFormat: m } = t, f = I.convertConv2DDataFormat(m), d = I.computeConv2DInfo(o.shape, s.shape, l, u, c, p, false, f), h = d.filterHeight, g = d.filterWidth, x = d.padInfo.top, y = d.padInfo.right, w = d.padInfo.bottom, _ = d.padInfo.left, C = d.dilationHeight, A = d.dilationWidth, D = d.strideHeight, R = d.strideWidth, P = d.inChannels, L = d.outChannels, G = d.padInfo.type === "SAME" ? 1 : 0;
if (d.dataFormat !== "channelsLast")
throw new Error(`wasm backend Conv2D does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);
let W = n.makeOutput(d.outShape, "float32"), j = n.dataIdMap.get(W.dataId).id;
return Y3(a, o.shape[0], o.shape[1], o.shape[2], i, h, g, x, y, w, _, G, C, A, D, R, P, L, j), W;
}
var Z3 = { kernelName: Mo, backendName: "wasm", setupFunc: Zre, kernelFunc: Jre };
var J3;
function Qre(r) {
J3 = r.wasm.cwrap(Lo, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function ene(r) {
let { backend: e, inputs: t, attrs: n } = r, { dy: o, filter: s } = t, { strides: a, pad: i, dataFormat: l, dimRoundingMode: u, inputShape: c } = n, p = 1, m = I.convertConv2DDataFormat(l), f = I.computeConv2DInfo(c, s.shape, a, p, i, u, false, m), { batchSize: d, filterHeight: h, filterWidth: g, inChannels: x, inHeight: y, inWidth: w, outChannels: _, outHeight: C, outWidth: A, strideHeight: D, strideWidth: R } = f, P = h - 1 - f.padInfo.top, L = g - 1 - f.padInfo.left, G = f.dataFormat === "channelsLast", W = b.computeStrides(f.inShape), j = b.computeStrides(o.shape), [H, q, X] = b.computeStrides(s.shape), re = W[0], J = G ? W[1] : W[2], oe = G ? W[2] : 1, se = G ? 1 : W[1], ne = j[0], fe = G ? j[1] : j[2], ae = G ? j[2] : 1, ge = G ? 1 : j[1], de = e.makeOutput(f.inShape, "float32"), ye = e.dataIdMap.get(de.dataId).id, _e = e.dataIdMap.get(o.dataId).id, Re = e.dataIdMap.get(s.dataId).id;
return J3(_e, Re, d, h, g, y, w, x, C, A, _, D, R, P, L, H, q, X, re, J, oe, se, ne, fe, ae, ge, ye), de;
}
var Q3 = { kernelName: Lo, backendName: "wasm", setupFunc: Qre, kernelFunc: ene };
var eB = lt(zo);
var tB = lt(Bo);
var IS;
(function(r) {
r[r.bilinear = 0] = "bilinear", r[r.nearest = 1] = "nearest";
})(IS || (IS = {}));
var rB;
function tne(r) {
rB = r.wasm.cwrap(Hi, null, ["number", "number", "number", "number", "array", "number", "number", "number", "number", "number"]);
}
function rne(r) {
let { backend: e, inputs: t, attrs: n } = r, { method: o, extrapolationValue: s, cropSize: a } = n, { image: i, boxes: l, boxInd: u } = t, c = l.shape[0], [p, m] = a, f = [c, p, m, i.shape[3]], d = e.dataIdMap.get(i.dataId), h;
i.dtype !== "float32" && (h = ol({ backend: e, inputs: { x: i }, attrs: { dtype: "float32" } }), d = e.dataIdMap.get(h.dataId));
let g = d.id, x = e.dataIdMap.get(l.dataId).id, y = e.dataIdMap.get(u.dataId).id, w = e.makeOutput(f, "float32"), _ = e.dataIdMap.get(w.dataId).id, C = new Uint8Array(new Int32Array(i.shape).buffer);
return rB(g, x, y, c, C, p, m, IS[o], s, _), h != null && e.disposeData(h.dataId), w;
}
var nB = { kernelName: Hi, backendName: "wasm", setupFunc: tne, kernelFunc: rne };
var oB;
function nne(r) {
oB = r.wasm.cwrap(Vo, null, ["number", "number", "number", "number", "number", "number"]);
}
function one(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { axis: s, exclusive: a, reverse: i } = n, l = o.shape.length;
b.assert(o.dtype === "float32" || o.dtype === "int32", () => `cumsum does not support ${o.dtype} tensors in the WASM backend`);
let u = I.getAxesPermutation([s], l), c = o;
u !== null && (c = $i({ inputs: { x: o }, attrs: { perm: u }, backend: t }));
let p = I.getInnerMostAxes(1, l)[0];
I.assertAxesAreInnerMostDims("cumsum", [p], l);
let m = t.makeOutput(c.shape, c.dtype), f = c.shape[p], d = t.dataIdMap.get(c.dataId).id, h = t.dataIdMap.get(m.dataId).id;
oB(d, a ? 1 : 0, i ? 1 : 0, f, h, et[o.dtype]);
let g = m;
if (u !== null) {
let x = I.getUndoAxesPermutation(u);
g = $i({ inputs: { x: m }, attrs: { perm: x }, backend: t }), t.disposeData(c.dataId), t.disposeData(m.dataId);
}
return g;
}
var sB = { kernelName: Vo, backendName: "wasm", setupFunc: nne, kernelFunc: one };
var iB;
function sne(r) {
iB = r.wasm.cwrap(qi, null, ["number", "number", "number", "array", "number", "array", "array", "number", "number"]);
}
function ine(r) {
let { backend: e, inputs: t, attrs: n } = r, { x: o } = t, { blockSize: s, dataFormat: a } = n, i = o.shape[0], l = a === "NHWC" ? o.shape[1] : o.shape[2], u = a === "NHWC" ? o.shape[2] : o.shape[3], c = a === "NHWC" ? o.shape[3] : o.shape[1], p = l * s, m = u * s, f = c / (s * s), d = a === "NHWC" ? [i, p, m, f] : [i, f, p, m], h = e.makeOutput(d, "float32"), x = e.dataIdMap.get(o.dataId).id, y = new Uint8Array(new Int32Array(b.computeStrides(o.shape)).buffer), w = new Uint8Array(new Int32Array(d).buffer), _ = new Uint8Array(new Int32Array(b.computeStrides(d)).buffer), C = e.dataIdMap.get(h.dataId).id;
return iB(x, s, a === "NHWC" ? 1 : 0, y, o.shape.length - 1, w, _, d.length, C), h;
}
var aB = { kernelName: qi, backendName: "wasm", setupFunc: sne, kernelFunc: ine };
var lB;
function ane(r) {
lB = r.wasm.cwrap(Go, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function lne(r) {
let { inputs: e, attrs: t, backend: n } = r, { x: o, filter: s } = e, a = n.dataIdMap.get(o.dataId).id, i = n.dataIdMap.get(s.dataId).id, { strides: l, dilations: u, pad: c, dimRoundingMode: p } = t, m = u == null ? [1, 1] : u, f = I.computeConv2DInfo(o.shape, s.shape, l, m, c, p, true), d = f.filterHeight, h = f.filterWidth, g = f.padInfo.top, x = f.padInfo.right, y = f.padInfo.bottom, w = f.padInfo.left, _ = f.dilationHeight, C = f.dilationWidth, A = f.strideHeight, D = f.strideWidth, R = f.inChannels, P = f.outChannels, L = f.padInfo.type === "SAME" ? 1 : 0;
if (f.dataFormat !== "channelsLast")
throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);
let G = n.makeOutput(f.outShape, "float32"), W = n.dataIdMap.get(G.dataId).id;
return lB(a, o.shape[0], o.shape[1], o.shape[2], i, d, h, g, x, y, w, L, _, C, A, D, R, P, W), G;
}
var uB = { kernelName: Go, backendName: "wasm", setupFunc: ane, kernelFunc: lne };
var cB = lt(Uo);
var une = false;
var pB = kt(Xi, une, "bool");
var mB = lt(jo, "float32");
function fb(r) {
let { inputs: e, attrs: t, backend: n } = r, { input: o } = e, { dim: s } = t, a = o.shape.length, i = o.shape.slice(), l = s;
return s < 0 && (b.assert(-(a + 1) <= s, () => `Axis must be in the interval [${-(a + 1)}, ${a}]`), l = a + s + 1), i.splice(l, 0, 1), ar({ inputs: { x: o }, backend: n, attrs: { shape: i } });
}
var fB = { kernelName: oi, backendName: "wasm", kernelFunc: fb };
function SS(r) {
let { attrs: { shape: e, value: t, dtype: n }, backend: o } = r, s = o.makeOutput(e, n);
return o.typedArrayFromHeap(s).fill(t), s;
}
var dB = { kernelName: xl, backendName: "wasm", kernelFunc: SS };
var hB;
function cne(r) {
hB = r.wasm.cwrap(Zi, null, ["number", "number", "number", "number", "number", "number"]);
}
function pne(r) {
let { inputs: e, backend: t } = r, { image: n } = e, o = t.makeOutput(n.shape, n.dtype), s = t.dataIdMap.get(n.dataId).id, a = t.dataIdMap.get(o.dataId).id, [i, l, u, c] = n.shape;
return hB(s, i, l, u, c, a), o;
}
var gB = { kernelName: Zi, backendName: "wasm", kernelFunc: pne, setupFunc: cne };
var xB = lt(Ho);
var mne = false;
var yB = kt(qo, mne);
var bB;
function fne(r) {
bB = r.wasm.cwrap(Ko, null, ["number", "number", "number", "number", "number", "number", "number"]);
}
function dne(r) {
let { backend: e, inputs: t, attrs: n } = r, { varianceEpsilon: o } = n, { x: s, mean: a, variance: i, offset: l, scale: u } = t, c = e.dataIdMap.get(s.dataId).id, p = e.dataIdMap.get(a.dataId).id, m = e.dataIdMap.get(i.dataId).id, f = l != null ? e.dataIdMap.get(l.dataId).id : 0, d = u != null ? e.dataIdMap.get(u.dataId).id : 0, h = e.makeOutput(s.shape, s.dtype);
if (b.sizeFromShape(s.shape) === 0)
return h;
let g = e.dataIdMap.get(h.dataId).id;
return bB(c, p, m, f, d, o, g), h;
}
var wB = { kernelName: Ko, backendName: "wasm", setupFunc: fne, kernelFunc: dne };
var _B;
function hne(r) {
_B = r.wasm.cwrap(xi, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function gne(r) {
let { inputs: e, attrs: t, backend: n } = r, { x: o, filter: s, bias: a, preluActivationWeights: i } = e, { strides: l, pad: u, dilations: c, dataFormat: p, dimRoundingMode: m, activation: f, leakyreluAlpha: d } = t, h = I.computeConv2DInfo(o.shape, s.shape, l, c, u, m), g = Zl[f];
if (g == null)
throw new Error(`${f} activation not yet supported for FusedConv2D in the wasm backend.`);
let x = n.dataIdMap.get(o.dataId).id, y = n.dataIdMap.get(s.dataId).id, w = h.outChannels, _ = 0;
if (a != null) {
let ae = n.dataIdMap.get(a.dataId);
if (ae.shape.length !== 1)
throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${ae.shape.length}.`);
if (ae.shape[0] !== w)
throw new Error(`FusedConv2D bias shape (${ae.shape}) does not match the number of output channels (${w})`);
_ = ae.id;
}
let C = h.filterHeight, A = h.filterWidth, D = h.padInfo.top, R = h.padInfo.right, P = h.padInfo.bottom, L = h.padInfo.left, G = h.dilationHeight, W = h.dilationWidth, j = h.strideHeight, H = h.strideWidth, q = h.inChannels, X = h.padInfo.type === "SAME" ? 1 : 0, re = h.batchSize, J = h.inHeight, oe = h.inWidth;
if (p !== "NHWC")
throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);
let se = n.makeOutput(h.outShape, "float32"), ne = n.dataIdMap.get(se.dataId).id, fe = i == null ? 0 : n.dataIdMap.get(i.dataId).id;
return _B(x, re, J, oe, y, C, A, _, D, R, P, L, X, G, W, j, H, q, w, g, fe, d || 0, ne), se;
}
var kB = { kernelName: xi, backendName: "wasm", setupFunc: hne, kernelFunc: gne };
var vB;
function xne(r) {
vB = r.wasm.cwrap(yi, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function yne(r) {
let { inputs: e, attrs: t, backend: n } = r, { x: o, filter: s, bias: a, preluActivationWeights: i } = e, { strides: l, pad: u, dilations: c, dataFormat: p, dimRoundingMode: m, activation: f, leakyreluAlpha: d } = t, h = I.computeConv2DInfo(o.shape, s.shape, l, c, u, m, true), g = Zl[f];
if (g == null)
throw new Error(`${f} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);
let x = n.dataIdMap.get(o.dataId).id, y = n.dataIdMap.get(s.dataId).id, w = h.outChannels, _ = 0;
if (a != null) {
let ae = n.dataIdMap.get(a.dataId);
if (ae.shape.length !== 1)
throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${ae.shape.length}.`);
if (ae.shape[0] !== w)
throw new Error(`FusedDepthwiseConv2D bias shape (${ae.shape}) does not match the number of output channels (${w})`);
_ = ae.id;
}
let C = h.filterHeight, A = h.filterWidth, D = h.padInfo.top, R = h.padInfo.right, P = h.padInfo.bottom, L = h.padInfo.left, G = h.dilationHeight, W = h.dilationWidth, j = h.strideHeight, H = h.strideWidth, q = h.inChannels, X = h.padInfo.type === "SAME" ? 1 : 0, re = h.batchSize, J = h.inHeight, oe = h.inWidth;
if (p !== "NHWC")
throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);
let se = n.makeOutput(h.outShape, "float32"), ne = n.dataIdMap.get(se.dataId).id, fe = i == null ? 0 : n.dataIdMap.get(i.dataId).id;
return vB(x, re, J, oe, y, C, A, _, D, R, P, L, X, G, W, j, H, q, w, g, fe, d || 0, ne), se;
}
var CB = { kernelName: yi, backendName: "wasm", setupFunc: xne, kernelFunc: yne };
var IB;
function bne(r) {
IB = r.wasm.cwrap(Ji, null, ["number", "number", "number", "number", "number", "number", "array", "number"]);
}
function wne(r) {
let { backend: e, inputs: t } = r, { params: n, indices: o } = t, [s, a, i, l] = Wg.prepareAndValidate(n, o), u = e.makeOutput(s, n.dtype);
if (a === 0)
return u;
let c = o.shape, p = c[c.length - 1], f = e.dataIdMap.get(n.dataId).id, h = e.dataIdMap.get(o.dataId).id, g = new Uint8Array(new Int32Array(l).buffer), x = e.dataIdMap.get(u.dataId).id;
return IB(f, et[n.dtype], h, a, p, i, g, x), u;
}
var SB = { kernelName: Ji, backendName: "wasm", setupFunc: bne, kernelFunc: wne };
var NB;
function _ne(r) {
NB = r.wasm.cwrap("Gather", null, ["number", "number", "array", "number", "number", "number", "array", "number"]);
}
function kne(r) {
let { backend: e, inputs: t, attrs: n } = r, { x: o, indices: s } = t, { axis: a, batchDims: i } = n, l = b.parseAxisParam(a, o.shape)[0], u = e.readSync(s.dataId), c = o.shape[l];
for (let P = 0; P < u.length; ++P) {
let L = u[P];
b.assert(L <= c - 1 && L >= 0, () => `GatherV2: the index value ${L} is not in [0, ${c - 1}]`);
}
let p = I.segment_util.collectGatherOpShapeInfo(o, s, l, i), m = ar({ inputs: { x: o }, attrs: { shape: [p.batchSize, p.outerSize, p.dimSize, p.sliceSize] }, backend: e }), f = b.sizeFromShape(s.shape), d = ar({ inputs: { x: s }, attrs: { shape: [p.batchSize, f / p.batchSize] }, backend: e }), h = [p.batchSize, p.outerSize, f / p.batchSize, p.sliceSize], g = e.makeOutput(h, o.dtype);
if (b.sizeFromShape(o.shape) === 0)
return g;
let x = m.shape.length - 1, w = e.dataIdMap.get(m.dataId).id, C = e.dataIdMap.get(d.dataId).id, A = e.dataIdMap.get(g.dataId).id, D = new Uint8Array(new Int32Array(b.computeStrides(m.shape)).buffer), R = new Uint8Array(new Int32Array(b.computeStrides(h)).buffer);
return NB(w, et[o.dtype], D, x, C, p.batchSize, R, A), e.disposeData(m.dataId), e.disposeData(d.dataId), g.shape = p.outputShape, g;
}
var TB = { kernelName: si, backendName: "wasm", setupFunc: _ne, kernelFunc: kne };
var vne = false;
var EB = kt(Qi, vne, "bool");
var Cne = false;
var AB = kt(Xo, Cne, "bool");
var DB;
function Ine(r) {
DB = r.wasm.cwrap(Yo, null, ["number", "number", "number", "number"]);
}
function Sne(r) {
let { inputs: { x: e }, attrs: { alpha: t }, backend: n } = r, o = n.dataIdMap.get(e.dataId).id, s = n.makeOutput(e.shape, "float32");
if (b.sizeFromShape(e.shape) !== 0) {
let a = n.dataIdMap.get(s.dataId).id;
DB(o, et[e.dtype], t, a);
}
return s;
}
var $B = { kernelName: Yo, backendName: "wasm", setupFunc: Ine, kernelFunc: Sne };
var Nne = false;
var RB = kt(na, Nne, "bool");
var Tne = false;
var FB = kt(oa, Tne, "bool");
var OB = lt(Zo);
var Ene = false;
var PB = kt(ia, Ene, "bool");
var MB;
function Ane(r) {
MB = r.wasm.cwrap(Jo, null, ["number", "number", "number", "number"]);
}
function Dne(r) {
let { backend: e, inputs: t, attrs: n } = r, { reductionIndices: o, keepDims: s } = n, { x: a } = t, l = e.dataIdMap.get(a.dataId).id, u = a, { transposed: c, axes: p, originalAxes: m, inputWasTransposed: f } = hn(a, o, e);
if (f) {
let w = e.dataIdMap.get(c.dataId).id;
u = c, l = w;
}
let d = u.shape.length;
I.assertAxesAreInnerMostDims("max", p, d);
let [h, g] = I.computeOutAndReduceShapes(u.shape, p), x = b.sizeFromShape(g), y = e.makeOutput(h, a.dtype);
if (b.sizeFromShape(u.shape) !== 0) {
let w = e.dataIdMap.get(y.dataId).id;
MB(l, et[a.dtype], x, w);
}
if (f && e.disposeData(c.dataId), s) {
let w = I.expandShapeToKeepDim(y.shape, m);
y.shape = w;
}
return y;
}
var LB = { kernelName: Jo, backendName: "wasm", setupFunc: Ane, kernelFunc: Dne };
var $ne = false;
var zB = kt(Qo, $ne);
var BB;
function Rne(r) {
BB = r.wasm.cwrap(es, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Fne(r) {
let { inputs: e, attrs: t, backend: n } = r, o = e.x, s = n.dataIdMap.get(o.dataId).id;
b.assert(o.dtype === "float32", () => `Error in MaxPool: only float32 input is supported. Got ${o.dtype}.`);
let { filterSize: a, strides: i, pad: l, dimRoundingMode: u } = t, c = I.computePool2DInfo(o.shape, a, i, 1, l, u), p = c.filterHeight, m = c.filterWidth, f = c.padInfo.top, d = c.padInfo.right, h = c.padInfo.bottom, g = c.padInfo.left, x = c.dilationHeight, y = c.dilationWidth, w = c.strideHeight, _ = c.strideWidth, C = c.inChannels, A = c.outChannels;
if (c.dataFormat !== "channelsLast")
throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);
let D = n.makeOutput(c.outShape, "float32"), R = n.dataIdMap.get(D.dataId).id;
return BB(s, o.shape[0], o.shape[1], o.shape[2], p, m, f, d, h, g, x, y, w, _, C, A, R), D;
}
var VB = { kernelName: es, backendName: "wasm", setupFunc: Rne, kernelFunc: Fne };
var GB;
function One(r) {
GB = r.wasm.cwrap(ts, null, ["number, number, number"]);
}
function Pne(r) {
let { backend: e, inputs: t, attrs: n } = r, { axis: o, keepDims: s } = n, { x: a } = t, i = e.dataIdMap.get(a.dataId).id, l = i, u = a, { transposed: c, axes: p, originalAxes: m, inputWasTransposed: f } = hn(a, o, e), d = p;
if (f) {
let _ = e.dataIdMap.get(c.dataId).id;
_ !== i && (u = c, l = _, d = I.getInnerMostAxes(d.length, u.shape.length));
}
I.assertAxesAreInnerMostDims("mean", d, u.shape.length);
let [h, g] = I.computeOutAndReduceShapes(u.shape, d), x = b.sizeFromShape(g), y = u;
u.dtype !== "float32" && (y = ol({ backend: e, inputs: { x: u }, attrs: { dtype: "float32" } }), l = e.dataIdMap.get(y.dataId).id);
let w = e.makeOutput(h, "float32");
if (b.sizeFromShape(u.shape) !== 0) {
let _ = e.dataIdMap.get(w.dataId).id;
GB(l, x, _);
}
if (f && e.disposeData(c.dataId), s) {
let _ = I.expandShapeToKeepDim(w.shape, m);
w.shape = _;
}
return u.dtype !== "float32" && e.disposeData(y.dataId), w;
}
var WB = { kernelName: ts, backendName: "wasm", setupFunc: One, kernelFunc: Pne };
var UB;
function Mne(r) {
UB = r.wasm.cwrap(rs, null, ["number", "number", "number", "number"]);
}
function Lne(r) {
let { backend: e, inputs: t, attrs: n } = r, { axis: o, keepDims: s } = n, { x: a } = t, i = e.dataIdMap.get(a.dataId).id, l = i, u = a, { transposed: c, axes: p, originalAxes: m, inputWasTransposed: f } = hn(a, o, e);
if (f) {
let w = e.dataIdMap.get(c.dataId).id;
w !== i && (u = c, l = w);
}
let d = u.shape.length;
I.assertAxesAreInnerMostDims("min", p, d);
let [h, g] = I.computeOutAndReduceShapes(u.shape, p), x = b.sizeFromShape(g), y = e.makeOutput(h, u.dtype);
if (b.sizeFromShape(u.shape) !== 0) {
let w = e.dataIdMap.get(y.dataId).id;
UB(l, et[a.dtype], x, w);
}
if (f && e.disposeData(c.dataId), s) {
let w = I.expandShapeToKeepDim(y.shape, m);
y.shape = w;
}
return y;
}
var jB = { kernelName: rs, backendName: "wasm", setupFunc: Mne, kernelFunc: Lne };
var zne = false;
var HB = kt(ns, zne);
var NS;
(function(r) {
r[r.reflect = 0] = "reflect", r[r.symmetric = 1] = "symmetric";
})(NS || (NS = {}));
var qB;
function Bne(r) {
qB = r.wasm.cwrap(os, null, ["number", "array", "number", "number", "array", "array", "number", "number"]);
}
function Vne(r) {
let { inputs: { x: e }, backend: t, attrs: { paddings: n, mode: o } } = r, s = n.map((d, h) => d[0] + e.shape[h] + d[1]), a = t.dataIdMap.get(e.dataId).id, i = t.makeOutput(s, e.dtype), l = t.dataIdMap.get(i.dataId).id, u = new Uint8Array(new Int32Array(e.shape).buffer), c = n.map((d) => d[0]), p = n.map((d) => d[1]), m = new Uint8Array(new Int32Array(c).buffer), f = new Uint8Array(new Int32Array(p).buffer);
return qB(a, u, e.shape.length, et[e.dtype], m, f, NS[o], l), i;
}
var KB = { kernelName: os, backendName: "wasm", kernelFunc: Vne, setupFunc: Bne };
var Gne = true;
var XB = kt(ss, Gne);
var YB = lt(ii);
function Mm(r, e) {
let t = new Int32Array(r.wasm.HEAPU8.buffer, e, 4), n = t[0], o = t[1], s = t[2], a = t[3];
return r.wasm._free(e), { pSelectedIndices: n, selectedSize: o, pSelectedScores: s, pValidOutputs: a };
}
var ZB;
function Wne(r) {
ZB = r.wasm.cwrap(ua, "number", ["number", "number", "number", "number", "number"]);
}
function Une(r) {
let { backend: e, inputs: t, attrs: n } = r, { iouThreshold: o, maxOutputSize: s, scoreThreshold: a } = n, { boxes: i, scores: l } = t, u = e.dataIdMap.get(i.dataId).id, c = e.dataIdMap.get(l.dataId).id, p = ZB(u, c, s, o, a), { pSelectedIndices: m, selectedSize: f, pSelectedScores: d, pValidOutputs: h } = Mm(e, p);
return e.wasm._free(d), e.wasm._free(h), e.makeOutput([f], "int32", m);
}
var JB = { kernelName: ua, backendName: "wasm", setupFunc: Wne, kernelFunc: Une };
var QB;
function jne(r) {
QB = r.wasm.cwrap(ca, "number", ["number", "number", "number", "number", "number", "bool"]);
}
function Hne(r) {
let { backend: e, inputs: t, attrs: n } = r, { iouThreshold: o, maxOutputSize: s, scoreThreshold: a, padToMaxOutputSize: i } = n, { boxes: l, scores: u } = t, c = e.dataIdMap.get(l.dataId).id, p = e.dataIdMap.get(u.dataId).id, m = QB(c, p, s, o, a, i), { pSelectedIndices: f, selectedSize: d, pSelectedScores: h, pValidOutputs: g } = Mm(e, m);
e.wasm._free(h);
let x = e.makeOutput([d], "int32", f), y = e.makeOutput([], "int32", g);
return [x, y];
}
var eV = { kernelName: ca, backendName: "wasm", setupFunc: jne, kernelFunc: Hne };
var tV;
function qne(r) {
tV = r.wasm.cwrap(pa, "number", ["number", "number", "number", "number", "number", "number"]);
}
function Kne(r) {
let { backend: e, inputs: t, attrs: n } = r, { iouThreshold: o, maxOutputSize: s, scoreThreshold: a, softNmsSigma: i } = n, { boxes: l, scores: u } = t, c = e.dataIdMap.get(l.dataId).id, p = e.dataIdMap.get(u.dataId).id, m = tV(c, p, s, o, a, i), { pSelectedIndices: f, selectedSize: d, pSelectedScores: h, pValidOutputs: g } = Mm(e, m);
e.wasm._free(g);
let x = e.makeOutput([d], "int32", f), y = e.makeOutput([d], "float32", h);
return [x, y];
}
var rV = { kernelName: pa, backendName: "wasm", setupFunc: qne, kernelFunc: Kne };
var Xne = false;
var nV = kt(la, Xne, "bool");
var oV;
function Yne(r) {
oV = r.wasm.cwrap(is, null, ["number", "number", "number", "number", "number"]);
}
function Zne(r) {
let { inputs: e, backend: t, attrs: n } = r, { indices: o } = e, { depth: s, onValue: a, offValue: i } = n, l = t.makeOutput([...o.shape, s], "int32"), u = t.dataIdMap.get(l.dataId).id, p = t.dataIdMap.get(o.dataId).id;
return oV(p, s, a, i, u), l;
}
var sV = { kernelName: is, backendName: "wasm", setupFunc: Yne, kernelFunc: Zne };
function Jne(r) {
let { inputs: { x: e }, backend: t } = r, n = t.makeOutput(e.shape, e.dtype);
return t.typedArrayFromHeap(n).fill(1), n;
}
var iV = { kernelName: ai, backendName: "wasm", kernelFunc: Jne };
function Qne(r) {
let { inputs: e, backend: t, attrs: n } = r, { axis: o } = n;
if (e.length === 1)
return fb({ inputs: { input: e[0] }, backend: t, attrs: { dim: o } });
let s = e[0].shape, a = e[0].dtype;
e.forEach((c) => {
b.assertShapesMatch(s, c.shape, "All tensors passed to stack must have matching shapes"), b.assert(a === c.dtype, () => "All tensors passed to stack must have matching dtypes");
});
let i = [], l = e.map((c) => {
let p = fb({ inputs: { input: c }, backend: t, attrs: { dim: o } });
return i.push(p), p;
}), u = CS({ inputs: l, backend: t, attrs: { axis: o } });
return i.forEach((c) => t.disposeData(c.dataId)), u;
}
var aV = { kernelName: li, backendName: "wasm", kernelFunc: Qne };
var lV;
function eoe(r) {
lV = r.wasm.cwrap(as, null, ["number", "array", "number", "number", "array", "array", "number", "number"]);
}
function toe(r) {
let { inputs: { x: e }, backend: t, attrs: { paddings: n, constantValue: o } } = r, s = n.map((h, g) => h[0] + e.shape[g] + h[1]);
if (b.sizeFromShape(e.shape) === 0)
return SS({ backend: t, attrs: { shape: s, value: o, dtype: e.dtype } });
let a = t.dataIdMap.get(e.dataId).id, i = t.makeOutput(s, e.dtype), u = t.dataIdMap.get(i.dataId).id, c = new Uint8Array(new Int32Array(e.shape).buffer), p = n.map((h) => h[0]), m = n.map((h) => h[1]), f = new Uint8Array(new Int32Array(p).buffer), d = new Uint8Array(new Int32Array(m).buffer);
return lV(a, c, e.shape.length, et[e.dtype], f, d, o, u), i;
}
var db = { kernelName: as, backendName: "wasm", kernelFunc: toe, setupFunc: eoe };
var roe = false;
var uV = kt(ls, roe);
var cV;
function noe(r) {
cV = r.wasm.cwrap(us, null, ["number", "number", "number"]);
}
function ooe(r) {
let { inputs: e, backend: t } = r, { x: n, alpha: o } = e, s = t.dataIdMap.get(n.dataId).id, a = t.dataIdMap.get(o.dataId).id, i = s, l = n, u = l;
l.dtype !== "float32" && (u = ol({ backend: t, inputs: { x: n }, attrs: { dtype: "float32" } }), i = t.dataIdMap.get(u.dataId).id);
let c = t.makeOutput(n.shape, "float32"), p = t.dataIdMap.get(c.dataId).id;
return cV(i, a, p), l.dtype !== "float32" && t.disposeData(u.dataId), c;
}
var pV = { kernelName: us, backendName: "wasm", setupFunc: noe, kernelFunc: ooe };
var mV;
function soe(r) {
mV = r.wasm.cwrap(ma, null, ["number", "number", "number", "number"]);
}
function ioe(r) {
let { backend: e, inputs: t, attrs: n } = r, { axis: o, keepDims: s } = n, { x: a } = t, i = e.dataIdMap.get(a.dataId).id, l = i, u = a, { transposed: c, axes: p, originalAxes: m, inputWasTransposed: f } = hn(a, o, e), d = p;
if (f) {
let w = e.dataIdMap.get(c.dataId).id;
w !== i && (u = c, l = w, d = I.getInnerMostAxes(d.length, u.shape.length));
}
I.assertAxesAreInnerMostDims("prod", d, u.shape.length);
let [h, g] = I.computeOutAndReduceShapes(u.shape, d), x = b.sizeFromShape(g), y = e.makeOutput(h, u.dtype);
if (b.sizeFromShape(u.shape) !== 0) {
let w = e.dataIdMap.get(y.dataId).id;
mV(l, x, et[y.dtype], w);
}
if (f && e.disposeData(c.dataId), s) {
let w = I.expandShapeToKeepDim(y.shape, m);
y.shape = w;
}
return y;
}
var fV = { kernelName: ma, backendName: "wasm", setupFunc: soe, kernelFunc: ioe };
var aoe = (r) => {
let { backend: e, attrs: t } = r, { start: n, stop: o, step: s, dtype: a } = t, i = dc(n, o, s, a), l = e.makeOutput([i.length], a);
return e.typedArrayFromHeap(l).set(i), l;
};
var dV = { kernelName: wl, backendName: "wasm", kernelFunc: aoe };
var loe = true;
var hV = kt(Wo, loe);
var gV = lt(cs);
var xV = lt(ms);
var yV;
function uoe(r) {
yV = r.wasm.cwrap(ps, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function coe(r) {
let { backend: e, inputs: t, attrs: n } = r, { images: o } = t, { alignCorners: s, halfPixelCenters: a, size: i } = n, [l, u] = i, [c, p, m, f] = o.shape, d = [c, l, u, f], h = e.dataIdMap.get(o.dataId), g;
h.dtype !== "float32" && (g = ol({ backend: e, inputs: { x: o }, attrs: { dtype: "float32" } }), h = e.dataIdMap.get(g.dataId));
let x = h.id, y = e.makeOutput(d, "float32");
if (b.sizeFromShape(o.shape) === 0)
return y;
let w = e.dataIdMap.get(y.dataId).id;
return yV(x, c, p, m, f, l, u, s ? 1 : 0, a ? 1 : 0, w), g != null && e.disposeData(g.dataId), y;
}
var bV = { kernelName: ps, backendName: "wasm", setupFunc: uoe, kernelFunc: coe };
var wV;
function poe(r) {
wV = r.wasm.cwrap(fs, null, ["number", "array", "number", "array", "number", "number"]);
}
function moe(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { dims: s } = n, a = b.parseAxisParam(s, o.shape);
if (o.shape.length === 0)
return Tc({ inputs: { x: o }, backend: t });
let i = t.makeOutput(o.shape, o.dtype), l = t.dataIdMap.get(o.dataId).id, u = t.dataIdMap.get(i.dataId).id, c = new Uint8Array(new Int32Array(a).buffer), p = new Uint8Array(new Int32Array(o.shape).buffer);
wV(l, c, a.length, p, o.shape.length, u);
let m = ar({ inputs: { x: i }, attrs: { shape: o.shape }, backend: t });
return t.disposeData(i.dataId), m;
}
var _V = { kernelName: fs, backendName: "wasm", kernelFunc: moe, setupFunc: poe };
var kV;
function foe(r) {
kV = r.wasm.cwrap(ka, null, ["number", "number", "number", "number", "number", "number", "number", "number", "array", "number", "number"]);
}
function doe(r) {
let { inputs: e, backend: t, attrs: n } = r, { image: o } = e, { radians: s, fillValue: a, center: i } = n, l = t.makeOutput(o.shape, o.dtype), u = t.dataIdMap.get(o.dataId).id, c = t.dataIdMap.get(l.dataId).id, [p, m, f, d] = o.shape, [h, g] = I.getImageCenter(i, m, f), x = a === 0, y = 255, w = typeof a == "number" ? [a, a, a, x ? 0 : y] : [...a, y], _ = new Uint8Array(new Int32Array(w).buffer);
return kV(u, p, m, f, d, s, h, g, _, w.length, c), l;
}
var vV = { kernelName: ka, backendName: "wasm", kernelFunc: doe, setupFunc: foe };
var CV = lt(ds);
var IV = lt(hs);
var SV;
function hoe(r) {
SV = r.wasm.cwrap(da, null, ["number", "number", "number", "number", "number", "number", "array", "number", "number"]);
}
function goe(r) {
let { backend: e, inputs: t, attrs: n } = r, { indices: o, updates: s } = t, { shape: a } = n, i = e.makeOutput(a, s.dtype);
if (b.sizeFromShape(a) === 0)
return i;
let { sliceRank: l, numUpdates: u, sliceSize: c, strides: p, outputSize: m } = jg.calculateShapes(s, o, a), d = e.dataIdMap.get(o.dataId).id, g = e.dataIdMap.get(s.dataId).id, x = new Uint8Array(new Int32Array(p).buffer), y = e.dataIdMap.get(i.dataId).id;
return SV(d, g, et[s.dtype], l, u, c, x, m, y), i;
}
var NV = { kernelName: da, backendName: "wasm", setupFunc: hoe, kernelFunc: goe };
var TV;
function xoe(r) {
TV = r.wasm.cwrap("SelectV2", null, ["number", "number", "number", "number", "number"]);
}
function yoe(r) {
let { inputs: e, backend: t } = r, { condition: n, t: o, e: s } = e, a = t.dataIdMap.get(n.dataId).id, i = t.dataIdMap.get(o.dataId).id, l = t.dataIdMap.get(s.dataId).id, u = t.makeOutput(o.shape, o.dtype), c = t.dataIdMap.get(u.dataId).id, p = n.shape.length, m = o.shape.length, f = p === 0 || p > 1 || m === 1 ? 1 : b.sizeFromShape(o.shape.slice(1));
return TV(a, i, l, f, c), u;
}
var EV = { kernelName: ci, backendName: "wasm", kernelFunc: yoe, setupFunc: xoe };
var AV;
function boe(r) {
AV = r.wasm.cwrap(xs, null, ["number", "number"]);
}
function woe(r) {
let { backend: e, inputs: { x: t } } = r, n = e.dataIdMap.get(t.dataId).id, o = e.makeOutput(t.shape, t.dtype), s = e.dataIdMap.get(o.dataId).id;
return b.sizeFromShape(o.shape) === 0 || AV(n, s), o;
}
var DV = { kernelName: "Sigmoid", backendName: "wasm", setupFunc: boe, kernelFunc: woe };
var $V = lt(gs);
var RV;
function _oe(r) {
RV = r.wasm.cwrap(ws, null, ["number", "number", "number", "number"]);
}
function koe(r) {
let { backend: e, inputs: { logits: t }, attrs: { dim: n } } = r, o = e.dataIdMap.get(t.dataId).id, s = e.makeOutput(t.shape, t.dtype), a = e.dataIdMap.get(s.dataId).id, i = t.shape[n], l = b.sizeFromShape(t.shape) / i;
return b.sizeFromShape(s.shape) === 0 || RV(o, a, i, l), s;
}
var FV = { kernelName: ws, backendName: "wasm", setupFunc: _oe, kernelFunc: koe };
function voe(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, { blockShape: s, paddings: a } = n, i = b.sizeFromShape(s), l = [[0, 0]];
l.push(...a);
for (let A = 1 + s.length; A < o.shape.length; ++A)
l.push([0, 0]);
let u = db.kernelFunc({ inputs: { x: o }, backend: t, attrs: { paddings: l, constantValue: 0 } }), c = I.getReshaped(u.shape, s, i, false), p = I.getPermuted(c.length, s.length, false), m = I.getReshapedPermuted(u.shape, s, i, false), h = ar({ inputs: { x: u }, backend: t, attrs: { shape: c } }), y = $i({ inputs: { x: h }, backend: t, attrs: { perm: p } }), C = ar({ inputs: { x: y }, backend: t, attrs: { shape: m } });
return t.disposeData(u.dataId), t.disposeData(h.dataId), t.disposeData(y.dataId), C;
}
var OV = { kernelName: mi, backendName: "wasm", kernelFunc: voe };
function Coe(r) {
let { inputs: e, attrs: t, backend: n } = r, { x: o } = e, { numOrSizeSplits: s, axis: a } = t, i = b.parseAxisParam(a, o.shape)[0], l = I.prepareSplitSize(o, s, i), u = new Array(o.shape.length).fill(0), c = o.shape.slice();
return l.map((p) => {
let m = [...c];
m[i] = p;
let f = nl({ inputs: { x: o }, attrs: { begin: u, size: m }, backend: n });
return u[i] += p, f;
});
}
var PV = { kernelName: fi, backendName: "wasm", kernelFunc: Coe };
var MV = lt(ys);
var LV = lt(kl);
var Ioe = true;
var zV = kt(_s, Ioe);
var BV;
function Soe(r) {
BV = r.wasm.cwrap(no, null, ["number", "number", "number", "number"]);
}
function Noe(r) {
let { backend: e, inputs: t, attrs: n } = r, { alpha: o } = n, { x: s } = t, a = e.dataIdMap.get(s.dataId).id, i = e.makeOutput(s.shape, s.dtype), l = e.dataIdMap.get(i.dataId).id;
return BV(a, o, et[s.dtype], l), i;
}
var VV = { kernelName: no, backendName: "wasm", setupFunc: Soe, kernelFunc: Noe };
var GV;
function Toe(r) {
GV = r.wasm.cwrap(ba, null, ["number", "array", "number", "array", "array", "array", "array", "array", "number", "number"]);
}
function Eoe(r) {
let { backend: e, inputs: t, attrs: n } = r, { x: o } = t, { begin: s, end: a, strides: i } = n;
i == null && (i = new Array(s.length));
let { beginMask: l, endMask: u, ellipsisMask: c, newAxisMask: p, shrinkAxisMask: m } = n, f = I.slice_util.maskToAxes(c);
if (f.length > 1)
throw new Error("Multiple ellipses in slice is not allowed.");
if (c !== 0 && p !== 0)
throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");
if (c !== 0 && m !== 0)
throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");
let d = o.shape.length - s.length, h = I.slice_util.maskToAxes(p), g = o.shape.slice();
h.forEach((G) => {
s[G] = 0, a[G] = 1, g.splice(G, 0, 1);
});
let x = ar({ inputs: { x: o }, attrs: { shape: g }, backend: e }), { begin: y, end: w, strides: _ } = I.slice_util.getNormalizedAxes(x.shape, f, d, s, a, i, l, u, c);
s = y, a = w, i = _;
let C = I.slice_util.maskToAxes(m);
C.forEach((G) => {
a[G] = s[G] + 1, i[G] = 1;
});
let A = I.slice_util.computeOutShape(s, a, i), D = A.filter((G, W) => C.indexOf(W) === -1);
if (i.every((G) => G === 1)) {
let G = nl({ inputs: { x }, attrs: { begin: s, size: A }, backend: e });
e.disposeData(x.dataId);
let W = ar({ inputs: { x: G }, attrs: { shape: D }, backend: e });
return e.disposeData(G.dataId), W;
}
let P = e.makeOutput(D, "float32");
if (!D.some((G) => G === 0)) {
let G = e.dataIdMap.get(x.dataId).id, W = new Uint8Array(new Int32Array(b.computeStrides(x.shape)).buffer), j = new Uint8Array(new Int32Array(s).buffer), H = new Uint8Array(new Int32Array(a).buffer), q = new Uint8Array(new Int32Array(i).buffer), X = new Uint8Array(new Int32Array(D).buffer), re = new Uint8Array(new Int32Array(b.computeStrides(D)).buffer), J = e.dataIdMap.get(P.dataId).id;
GV(G, W, x.shape.length, j, H, q, X, re, D.length, J);
}
e.disposeData(x.dataId);
let L = ar({ inputs: { x: P }, attrs: { shape: D }, backend: e });
return e.disposeData(P.dataId), L;
}
var WV = { kernelName: ba, backendName: "wasm", setupFunc: Toe, kernelFunc: Eoe };
var Aoe = true;
var UV = kt(ks, Aoe);
var jV;
function Doe(r) {
jV = r.wasm.cwrap(bs, null, ["number", "number", "number", "number"]);
}
function $oe(r) {
let { backend: e, inputs: t, attrs: n } = r, { axis: o, keepDims: s } = n, { x: a } = t, i = e.dataIdMap.get(a.dataId).id, l = i, u = a, { transposed: c, axes: p, originalAxes: m, inputWasTransposed: f } = hn(a, o, e), d = p;
if (f) {
let w = e.dataIdMap.get(c.dataId).id;
w !== i && (u = c, l = w, d = I.getInnerMostAxes(d.length, u.shape.length));
}
I.assertAxesAreInnerMostDims("sum", d, u.shape.length);
let [h, g] = I.computeOutAndReduceShapes(u.shape, d), x = b.sizeFromShape(g), y = e.makeOutput(h, u.dtype);
if (b.sizeFromShape(u.shape) !== 0) {
let w = e.dataIdMap.get(y.dataId).id;
jV(l, x, et[y.dtype], w);
}
if (f && e.disposeData(c.dataId), s) {
let w = I.expandShapeToKeepDim(y.shape, m);
y.shape = w;
}
return y;
}
var HV = { kernelName: bs, backendName: "wasm", setupFunc: Doe, kernelFunc: $oe };
var qV = lt(vs);
var KV = lt(Cs);
var XV;
function Roe(r) {
XV = r.wasm.cwrap(Hn, null, ["number", "array", "number", "array", "number", "number"]);
}
function Foe(r) {
let { inputs: e, backend: t, attrs: n } = r, { x: o } = e, s = t.dataIdMap.get(o.dataId).id, { reps: a } = n, i = new Array(o.shape.length);
for (let m = 0; m < i.length; m++)
i[m] = o.shape[m] * a[m];
let l = new Uint8Array(new Int32Array(o.shape).buffer), u = new Uint8Array(new Int32Array(i).buffer), c = t.makeOutput(i, o.dtype), p = t.dataIdMap.get(c.dataId).id;
return XV(s, l, o.shape.length, u, i.length, et[c.dtype], p), c;
}
var YV = { kernelName: Hn, backendName: "wasm", setupFunc: Roe, kernelFunc: Foe };
var ZV;
function Ooe(r) {
ZV = r.wasm.cwrap(wa, null, ["number", "array", "number", "number", "number", "bool", "number", "number"]);
}
var Poe = ({ inputs: r, backend: e, attrs: t }) => {
let { x: n } = r, { k: o, sorted: s } = t, a = e.dataIdMap.get(n.dataId).id, i = new Uint8Array(new Int32Array(n.shape).buffer), l = n.shape.slice();
l[l.length - 1] = o;
let u = e.makeOutput(l, n.dtype), c = e.dataIdMap.get(u.dataId).id, p = e.makeOutput(l, "int32"), m = e.dataIdMap.get(p.dataId).id;
return ZV(a, i, n.shape.length, et[n.dtype], o, s, c, m), [u, p];
};
var JV = { kernelName: wa, backendName: "wasm", setupFunc: Ooe, kernelFunc: Poe };
var QV;
function Moe(r) {
QV = r.wasm.cwrap(_a, null, ["number", "number", "bool", "number", "number", "number", "number", "number", "number", "array", "number", "number", "number", "number", "number"]);
}
function Loe(r) {
let { backend: e, inputs: t, attrs: n } = r, { image: o, transforms: s } = t, { interpolation: a, fillMode: i, fillValue: l, outputShape: u } = n, [c, p, m, f] = o.shape, [d, h] = u != null ? u : [p, m], g = [c, d, h, f], x = new Uint8Array(new Int32Array(b.computeStrides(o.shape)).buffer), y = e.makeOutput(g, o.dtype), w = e.dataIdMap.get(y.dataId).id, C = e.dataIdMap.get(o.dataId).id, D = e.dataIdMap.get(s.dataId).id, R = a === "nearest" ? 1 : 2, P;
switch (i) {
case "constant":
P = 1;
break;
case "reflect":
P = 2;
break;
case "wrap":
P = 3;
break;
case "nearest":
P = 4;
break;
default:
P = 1;
break;
}
return QV(C, D, s.shape[0] > 1, c, d, h, f, m, p, x, o.shape.length - 1, R, P, l, w), y;
}
var eG = { kernelName: _a, backendName: "wasm", setupFunc: Moe, kernelFunc: Loe };
function zoe(r) {
let { inputs: e, backend: t, attrs: n } = r, { value: o } = e, { axis: s } = n;
s < 0 && (s += o.shape.length);
let a = o.shape[s], i = o.shape.length, l = new Array(i - 1), u = 0;
for (let f = 0; f < i; f++)
f !== s && (l[u++] = o.shape[f]);
let c = new Array(a), p = new Array(i).fill(0), m = o.shape.slice();
m[s] = 1;
for (let f = 0; f < c.length; f++)
p[s] = f, c[f] = nl({ inputs: { x: o }, attrs: { begin: p, size: m }, backend: t });
return c.map(({ dataId: f, dtype: d }) => ({ dataId: f, dtype: d, shape: l }));
}
var tG = { kernelName: di, backendName: "wasm", kernelFunc: zoe };
function Boe(r) {
let { inputs: { x: e }, backend: t } = r, n = t.makeOutput(e.shape, e.dtype);
return t.typedArrayFromHeap(n).fill(0), n;
}
var rG = { kernelName: hi, backendName: "wasm", kernelFunc: Boe };
var Voe = [I3, S3, T3, R3, O3, M3, z3, G3, U3, j3, H3, K3, X3, Z3, Q3, eB, tB, nB, sB, aB, uB, cB, pB, mB, fB, dB, gB, xB, yB, C3, wB, kB, CB, SB, TB, EB, AB, E3, $B, RB, FB, OB, PB, LB, zB, VB, WB, jB, HB, KB, XB, YB, JB, eV, rV, nV, sV, iV, aV, db, uV, pV, fV, dV, hV, gV, xV, B3, bV, _V, vV, IV, CV, NV, EV, DV, $V, W3, FV, OV, PV, MV, LV, zV, VV, WV, UV, HV, qV, KV, YV, JV, eG, D3, tG, rG];
for (let r of Voe)
uu(r);
var TS = U();
TS.registerFlag("WASM_HAS_SIMD_SUPPORT", async () => WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 9, 1, 7, 0, 65, 0, 253, 15, 26, 11])));
TS.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT", async () => {
if (TS.get("IS_NODE"))
return false;
try {
return new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)), WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11]));
} catch (r) {
return false;
}
});
var RS = ou(sG());
var iG = 'var Module={};function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;this.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);Module["wasmModule"]=null;receiveInstance(instance);return instance.exports};function moduleLoaded(){}this.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["_emscripten_tls_init"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].setThreadStatus(Module["_pthread_self"](),1);try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(!Module["getNoExitRuntime"]())Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["getNoExitRuntime"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};if(typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string"){self={location:{href:__filename}};var onmessage=this.onmessage;var nodeWorkerThreads=require("worker_threads");global.Worker=nodeWorkerThreads.Worker;var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var nodeFS=require("fs");var nodeRead=function(filename){return nodeFS.readFileSync(filename,"utf8")};function globalEval(x){global.require=require;global.Module=Module;eval.call(null,x)}importScripts=function(f){globalEval(nodeRead(f))};postMessage=function(msg){parentPort.postMessage(msg)};if(typeof performance==="undefined"){performance={now:function(){return Date.now()}}}}';
var lG = ou(aG());
var xb = class extends Js {
constructor(e) {
super();
this.wasm = e, this.dataIdNextNumber = 1, this.wasm.tfjs.initWithThreadsCount(pG), OS = this.wasm.tfjs.getThreadsCount(), this.dataIdMap = new pl(this, Es());
}
write(e, t, n) {
let o = { id: this.dataIdNextNumber++ };
return this.move(o, e, t, n, 1), o;
}
numDataIds() {
return this.dataIdMap.numDataIds();
}
async time(e) {
let t = b.now();
return e(), { kernelMs: b.now() - t };
}
move(e, t, n, o, s) {
let a = this.dataIdNextNumber++;
if (o === "string") {
let c = t;
this.dataIdMap.set(e, { id: a, stringBytes: c, shape: n, dtype: o, memoryOffset: null, refCount: s });
return;
}
let i = b.sizeFromShape(n), l = i * b.bytesPerElement(o), u = this.wasm._malloc(l);
this.dataIdMap.set(e, { id: a, memoryOffset: u, shape: n, dtype: o, refCount: s }), this.wasm.tfjs.registerTensor(a, i, u), t != null && this.wasm.HEAPU8.set(new Uint8Array(t.buffer, t.byteOffset, l), u);
}
async read(e) {
return this.readSync(e);
}
readSync(e) {
let { memoryOffset: t, dtype: n, shape: o, stringBytes: s } = this.dataIdMap.get(e);
if (n === "string")
return s;
let a = this.wasm.HEAPU8.slice(t, t + b.sizeFromShape(o) * b.bytesPerElement(n));
return Woe(a.buffer, n);
}
disposeData(e, t = false) {
if (this.dataIdMap.has(e)) {
let n = this.dataIdMap.get(e);
if (n.refCount--, !t && n.refCount > 0)
return false;
this.wasm._free(n.memoryOffset), this.wasm.tfjs.disposeData(n.id), this.dataIdMap.delete(e);
}
return true;
}
refCount(e) {
return this.dataIdMap.has(e) ? this.dataIdMap.get(e).refCount : 0;
}
incRef(e) {
let t = this.dataIdMap.get(e);
t != null && t.refCount++;
}
floatPrecision() {
return 32;
}
getMemoryOffset(e) {
return this.dataIdMap.get(e).memoryOffset;
}
dispose() {
this.wasm.tfjs.dispose(), "PThread" in this.wasm && this.wasm.PThread.terminateAllThreads(), this.wasm = null;
}
memory() {
return { unreliable: false };
}
makeOutput(e, t, n) {
let o;
if (n == null)
o = this.write(null, e, t);
else {
let s = this.dataIdNextNumber++;
o = { id: s }, this.dataIdMap.set(o, { id: s, memoryOffset: n, shape: e, dtype: t, refCount: 1 });
let a = b.sizeFromShape(e);
this.wasm.tfjs.registerTensor(s, a, n);
}
return { dataId: o, shape: e, dtype: t };
}
typedArrayFromHeap({ shape: e, dtype: t, dataId: n }) {
let o = this.wasm.HEAPU8.buffer, { memoryOffset: s } = this.dataIdMap.get(n), a = b.sizeFromShape(e);
switch (t) {
case "float32":
return new Float32Array(o, s, a);
case "int32":
return new Int32Array(o, s, a);
case "bool":
return new Uint8Array(o, s, a);
default:
throw new Error(`Unknown dtype ${t}`);
}
}
};
function Goe(r) {
return (e, t) => (b.fetch(r, { credentials: "same-origin" }).then((n) => {
n.ok || e.env.a(`failed to load wasm binary file at '${r}'`), n.arrayBuffer().then((o) => {
WebAssembly.instantiate(o, e).then((s) => {
t(s.instance, s.module);
});
});
}), {});
}
function uG(r, e, t) {
if (yb != null)
return yb;
let n = "tfjs-backend-wasm.wasm";
return r && e ? n = "tfjs-backend-wasm-threaded-simd.wasm" : r && (n = "tfjs-backend-wasm-simd.wasm"), eg != null && eg[n] != null ? eg[n] : t + n;
}
async function cG() {
let [r, e] = await Promise.all([U().getAsync("WASM_HAS_SIMD_SUPPORT"), U().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);
return new Promise((t, n) => {
let o = {};
o.locateFile = (i, l) => {
if (i.endsWith(".worker.js")) {
let u = iG, c = new Blob([u], { type: "application/javascript" });
return URL.createObjectURL(c);
}
return i.endsWith(".wasm") ? uG(r, e, Qh != null ? Qh : l) : l + i;
}, FS && (o.instantiateWasm = Goe(uG(r, e, Qh != null ? Qh : "")));
let s = false;
o.onAbort = () => {
if (s || tg)
return;
tg = true, n({ message: "Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers" });
};
let a;
e && r && yb == null ? (o.mainScriptUrlOrBlob = new Blob(["var WasmBackendModuleThreadedSimd = " + RS.default.toString()], { type: "text/javascript" }), a = (0, RS.default)(o)) : a = (0, lG.default)(o), a.then((i) => {
s = true, tg = false;
let l = null;
i.tfjs = { init: i.cwrap("init", null, []), initWithThreadsCount: i.cwrap("init_with_threads_count", null, ["number"]), getThreadsCount: i.cwrap("get_threads_count", "number", []), registerTensor: i.cwrap("register_tensor", null, ["number", "number", "number"]), disposeData: i.cwrap("dispose_data", l, ["number"]), dispose: i.cwrap("dispose", l, []) }, t({ wasm: i });
});
});
}
function Woe(r, e) {
switch (e) {
case "float32":
return new Float32Array(r);
case "int32":
return new Int32Array(r);
case "bool":
return new Uint8Array(r);
default:
throw new Error(`Unknown dtype ${e}`);
}
}
var Uoe = ["tfjs-backend-wasm.wasm", "tfjs-backend-wasm-simd.wasm", "tfjs-backend-wasm-threaded-simd.wasm"];
var yb = null;
var Qh = null;
var eg = {};
var tg = false;
var FS = false;
function joe(r, e = false) {
if (R_("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."), tg)
throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");
yb = r, FS = e;
}
function Hoe(r, e = false) {
if (tg)
throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");
if (typeof r == "string")
Qh = r;
else {
eg = r;
let t = Uoe.filter((n) => eg[n] == null);
if (t.length > 0)
throw new Error(`There were no entries found for the following binaries: ${t.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`);
}
FS = e;
}
var pG = -1;
var OS = -1;
function qoe(r) {
pG = r;
}
function Koe() {
if (OS === -1)
throw new Error("WASM backend not initialized.");
return OS;
}
var Xoe = "3.10.0";
var Yoe = 2;
Op("wasm", async () => {
let { wasm: r } = await cG();
return new xb(r);
}, Yoe);
var Zoe = "3.10.0";
var Joe = "3.10.0";
var Qoe = "3.10.0";
var ese = "3.10.0";
var tse = "3.10.0";
var rse = "3.10.0";
var nse = "3.10.0";
var ose = "3.10.0";
var sse = { tfjs: Zoe, "tfjs-core": Joe, "tfjs-data": Qoe, "tfjs-layers": ese, "tfjs-converter": tse, "tfjs-backend-cpu": rse, "tfjs-backend-webgl": nse, "tfjs-backend-wasm": ose };
// src/image/imagefxshaders.ts
var vertexIdentity = `
precision highp float;
attribute vec2 pos;
attribute vec2 uv;
varying vec2 vUv;
uniform float flipY;
void main(void) {
vUv = uv;
gl_Position = vec4(pos.x, pos.y*flipY, 0.0, 1.);
}
`;
var colorMatrixWithAlpha = `
precision highp float;
varying vec2 vUv;
uniform sampler2D texture;
uniform float m[20];
void main(void) {
vec4 c = texture2D(texture, vUv);
gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[3] * c.a + m[4];
gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[8] * c.a + m[9];
gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[13] * c.a + m[14];
gl_FragColor.a = m[15] * c.r + m[16] * c.g + m[17] * c.b + m[18] * c.a + m[19];
}
`;
var colorMatrixWithoutAlpha = `
precision highp float;
varying vec2 vUv;
uniform sampler2D texture;
uniform float m[20];
void main(void) {
vec4 c = texture2D(texture, vUv);
gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[4];
gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[9];
gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[14];
gl_FragColor.a = c.a;
}
`;
var pixelate = `
precision highp float;
varying vec2 vUv;
uniform vec2 size;
uniform sampler2D texture;
vec2 pixelate(vec2 coord, vec2 size) {
return floor( coord / size ) * size;
}
void main(void) {
gl_FragColor = vec4(0.0);
vec2 coord = pixelate(vUv, size);
gl_FragColor += texture2D(texture, coord);
}
`;
var blur = `
precision highp float;
varying vec2 vUv;
uniform sampler2D texture;
uniform vec2 px;
void main(void) {
gl_FragColor = vec4(0.0);
gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;
gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;
gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;
gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;
gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;
gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;
gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;
gl_FragColor += texture2D(texture, vUv )*0.159576912161;
gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;
gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;
gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;
gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;
gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;
gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;
gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;
}
`;
var convolution = `
precision highp float;
varying vec2 vUv;
uniform sampler2D texture;
uniform vec2 px;
uniform float m[9];
void main(void) {
vec4 c11 = texture2D(texture, vUv - px); // top left
vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y)); // top center
vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y)); // top right
vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) ); // mid left
vec4 c22 = texture2D(texture, vUv); // mid center
vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) ); // mid right
vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) ); // bottom left
vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) ); // bottom center
vec4 c33 = texture2D(texture, vUv + px ); // bottom right
gl_FragColor =
c11 * m[0] + c12 * m[1] + c22 * m[2] +
c21 * m[3] + c22 * m[4] + c23 * m[5] +
c31 * m[6] + c32 * m[7] + c33 * m[8];
gl_FragColor.a = c22.a;
}
`;
// src/image/imagefx.ts
var collect = (source, prefix, collection) => {
const r = new RegExp("\\b" + prefix + " \\w+ (\\w+)", "ig");
source.replace(r, (match4, name) => {
collection[name] = 0;
return match4;
});
};
var GLProgram = class {
constructor(gl2, vertexSource, fragmentSource) {
__publicField(this, "uniform", {});
__publicField(this, "attribute", {});
__publicField(this, "gl");
__publicField(this, "id");
__publicField(this, "compile", (source, type) => {
const shader = this.gl.createShader(type);
this.gl.shaderSource(shader, source);
this.gl.compileShader(shader);
if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS))
throw new Error(`filter: gl compile failed: ${this.gl.getShaderInfoLog(shader)}`);
return shader;
});
this.gl = gl2;
const vertexShader = this.compile(vertexSource, this.gl.VERTEX_SHADER);
const fragmentShader = this.compile(fragmentSource, this.gl.FRAGMENT_SHADER);
this.id = this.gl.createProgram();
this.gl.attachShader(this.id, vertexShader);
this.gl.attachShader(this.id, fragmentShader);
this.gl.linkProgram(this.id);
if (!this.gl.getProgramParameter(this.id, this.gl.LINK_STATUS))
throw new Error(`filter: gl link failed: ${this.gl.getProgramInfoLog(this.id)}`);
this.gl.useProgram(this.id);
collect(vertexSource, "attribute", this.attribute);
for (const a in this.attribute)
this.attribute[a] = this.gl.getAttribLocation(this.id, a);
collect(vertexSource, "uniform", this.uniform);
collect(fragmentSource, "uniform", this.uniform);
for (const u in this.uniform)
this.uniform[u] = this.gl.getUniformLocation(this.id, u);
}
};
function GLImageFilter() {
let drawCount = 0;
let sourceTexture = null;
let lastInChain = false;
let currentFramebufferIndex = -1;
let tempFramebuffers = [null, null];
let filterChain = [];
let vertexBuffer = null;
let currentProgram = null;
const fxcanvas = canvas(100, 100);
const shaderProgramCache = {};
const DRAW = { INTERMEDIATE: 1 };
const gl2 = fxcanvas.getContext("webgl");
if (!gl2)
throw new Error("filter: cannot get webgl context");
function resize(width, height) {
if (width === fxcanvas.width && height === fxcanvas.height)
return;
fxcanvas.width = width;
fxcanvas.height = height;
if (!vertexBuffer) {
const vertices = new Float32Array([-1, -1, 0, 1, 1, -1, 1, 1, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 1, 1, 1, 1, 1, 0]);
vertexBuffer = gl2.createBuffer();
gl2.bindBuffer(gl2.ARRAY_BUFFER, vertexBuffer);
gl2.bufferData(gl2.ARRAY_BUFFER, vertices, gl2.STATIC_DRAW);
gl2.pixelStorei(gl2.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
}
gl2.viewport(0, 0, fxcanvas.width, fxcanvas.height);
tempFramebuffers = [null, null];
}
function createFramebufferTexture(width, height) {
const fbo = gl2.createFramebuffer();
gl2.bindFramebuffer(gl2.FRAMEBUFFER, fbo);
const renderbuffer = gl2.createRenderbuffer();
gl2.bindRenderbuffer(gl2.RENDERBUFFER, renderbuffer);
const texture = gl2.createTexture();
gl2.bindTexture(gl2.TEXTURE_2D, texture);
gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, width, height, 0, gl2.RGBA, gl2.UNSIGNED_BYTE, null);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MAG_FILTER, gl2.LINEAR);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MIN_FILTER, gl2.LINEAR);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_S, gl2.CLAMP_TO_EDGE);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_T, gl2.CLAMP_TO_EDGE);
gl2.framebufferTexture2D(gl2.FRAMEBUFFER, gl2.COLOR_ATTACHMENT0, gl2.TEXTURE_2D, texture, 0);
gl2.bindTexture(gl2.TEXTURE_2D, null);
gl2.bindFramebuffer(gl2.FRAMEBUFFER, null);
return { fbo, texture };
}
function getTempFramebuffer(index) {
tempFramebuffers[index] = tempFramebuffers[index] || createFramebufferTexture(fxcanvas.width, fxcanvas.height);
return tempFramebuffers[index];
}
function draw2(flags = 0) {
var _a2, _b;
if (!currentProgram)
return;
let source = null;
let target = null;
let flipY = false;
if (drawCount === 0)
source = sourceTexture;
else
source = ((_a2 = getTempFramebuffer(currentFramebufferIndex)) == null ? void 0 : _a2.texture) || null;
drawCount++;
if (lastInChain && !(flags & DRAW.INTERMEDIATE)) {
target = null;
flipY = drawCount % 2 === 0;
} else {
currentFramebufferIndex = (currentFramebufferIndex + 1) % 2;
target = ((_b = getTempFramebuffer(currentFramebufferIndex)) == null ? void 0 : _b.fbo) || null;
}
gl2.bindTexture(gl2.TEXTURE_2D, source);
gl2.bindFramebuffer(gl2.FRAMEBUFFER, target);
gl2.uniform1f(currentProgram.uniform["flipY"], flipY ? -1 : 1);
gl2.drawArrays(gl2.TRIANGLES, 0, 6);
}
function compileShader(fragmentSource) {
if (shaderProgramCache[fragmentSource]) {
currentProgram = shaderProgramCache[fragmentSource];
gl2.useProgram((currentProgram == null ? void 0 : currentProgram.id) || null);
return currentProgram;
}
currentProgram = new GLProgram(gl2, vertexIdentity, fragmentSource);
const floatSize = Float32Array.BYTES_PER_ELEMENT;
const vertSize = 4 * floatSize;
gl2.enableVertexAttribArray(currentProgram.attribute["pos"]);
gl2.vertexAttribPointer(currentProgram.attribute["pos"], 2, gl2.FLOAT, false, vertSize, 0 * floatSize);
gl2.enableVertexAttribArray(currentProgram.attribute["uv"]);
gl2.vertexAttribPointer(currentProgram.attribute["uv"], 2, gl2.FLOAT, false, vertSize, 2 * floatSize);
shaderProgramCache[fragmentSource] = currentProgram;
return currentProgram;
}
const filter = {
colorMatrix: (matrix) => {
const m = new Float32Array(matrix);
m[4] /= 255;
m[9] /= 255;
m[14] /= 255;
m[19] /= 255;
const shader = m[18] === 1 && m[3] === 0 && m[8] === 0 && m[13] === 0 && m[15] === 0 && m[16] === 0 && m[17] === 0 && m[19] === 0 ? colorMatrixWithoutAlpha : colorMatrixWithAlpha;
const program = compileShader(shader);
gl2.uniform1fv(program == null ? void 0 : program.uniform["m"], m);
draw2();
},
brightness: (brightness) => {
const b10 = (brightness || 0) + 1;
filter.colorMatrix([
b10,
0,
0,
0,
0,
0,
b10,
0,
0,
0,
0,
0,
b10,
0,
0,
0,
0,
0,
1,
0
]);
},
saturation: (amount) => {
const x = (amount || 0) * 2 / 3 + 1;
const y = (x - 1) * -0.5;
filter.colorMatrix([
x,
y,
y,
0,
0,
y,
x,
y,
0,
0,
y,
y,
x,
0,
0,
0,
0,
0,
1,
0
]);
},
desaturate: () => {
filter.saturation(-1);
},
contrast: (amount) => {
const v10 = (amount || 0) + 1;
const o = -128 * (v10 - 1);
filter.colorMatrix([
v10,
0,
0,
0,
o,
0,
v10,
0,
0,
o,
0,
0,
v10,
0,
o,
0,
0,
0,
1,
0
]);
},
negative: () => {
filter.contrast(-2);
},
hue: (rotation) => {
rotation = (rotation || 0) / 180 * Math.PI;
const cos = Math.cos(rotation);
const sin = Math.sin(rotation);
const lumR = 0.213;
const lumG = 0.715;
const lumB = 0.072;
filter.colorMatrix([
lumR + cos * (1 - lumR) + sin * -lumR,
lumG + cos * -lumG + sin * -lumG,
lumB + cos * -lumB + sin * (1 - lumB),
0,
0,
lumR + cos * -lumR + sin * 0.143,
lumG + cos * (1 - lumG) + sin * 0.14,
lumB + cos * -lumB + sin * -0.283,
0,
0,
lumR + cos * -lumR + sin * -(1 - lumR),
lumG + cos * -lumG + sin * lumG,
lumB + cos * (1 - lumB) + sin * lumB,
0,
0,
0,
0,
0,
1,
0
]);
},
desaturateLuminance: () => {
filter.colorMatrix([
0.2764723,
0.929708,
0.0938197,
0,
-37.1,
0.2764723,
0.929708,
0.0938197,
0,
-37.1,
0.2764723,
0.929708,
0.0938197,
0,
-37.1,
0,
0,
0,
1,
0
]);
},
sepia: () => {
filter.colorMatrix([
0.393,
0.7689999,
0.18899999,
0,
0,
0.349,
0.6859999,
0.16799999,
0,
0,
0.272,
0.5339999,
0.13099999,
0,
0,
0,
0,
0,
1,
0
]);
},
brownie: () => {
filter.colorMatrix([
0.5997023498159715,
0.34553243048391263,
-0.2708298674538042,
0,
47.43192855600873,
-0.037703249837783157,
0.8609577587992641,
0.15059552388459913,
0,
-36.96841498319127,
0.24113635128153335,
-0.07441037908422492,
0.44972182064877153,
0,
-7.562075277591283,
0,
0,
0,
1,
0
]);
},
vintagePinhole: () => {
filter.colorMatrix([
0.6279345635605994,
0.3202183420819367,
-0.03965408211312453,
0,
9.651285835294123,
0.02578397704808868,
0.6441188644374771,
0.03259127616149294,
0,
7.462829176470591,
0.0466055556782719,
-0.0851232987247891,
0.5241648018700465,
0,
5.159190588235296,
0,
0,
0,
1,
0
]);
},
kodachrome: () => {
filter.colorMatrix([
1.1285582396593525,
-0.3967382283601348,
-0.03992559172921793,
0,
63.72958762196502,
-0.16404339962244616,
1.0835251566291304,
-0.05498805115633132,
0,
24.732407896706203,
-0.16786010706155763,
-0.5603416277695248,
1.6014850761964943,
0,
35.62982807460946,
0,
0,
0,
1,
0
]);
},
technicolor: () => {
filter.colorMatrix([
1.9125277891456083,
-0.8545344976951645,
-0.09155508482755585,
0,
11.793603434377337,
-0.3087833385928097,
1.7658908555458428,
-0.10601743074722245,
0,
-70.35205161461398,
-0.231103377548616,
-0.7501899197440212,
1.847597816108189,
0,
30.950940869491138,
0,
0,
0,
1,
0
]);
},
polaroid: () => {
filter.colorMatrix([
1.438,
-0.062,
-0.062,
0,
0,
-0.122,
1.378,
-0.122,
0,
0,
-0.016,
-0.016,
1.483,
0,
0,
0,
0,
0,
1,
0
]);
},
shiftToBGR: () => {
filter.colorMatrix([
0,
0,
1,
0,
0,
0,
1,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
1,
0
]);
},
convolution: (matrix) => {
const m = new Float32Array(matrix);
const pixelSizeX = 1 / fxcanvas.width;
const pixelSizeY = 1 / fxcanvas.height;
const program = compileShader(convolution);
gl2.uniform1fv(program == null ? void 0 : program.uniform["m"], m);
gl2.uniform2f(program == null ? void 0 : program.uniform["px"], pixelSizeX, pixelSizeY);
draw2();
},
detectEdges: () => {
filter.convolution.call(this, [
0,
1,
0,
1,
-4,
1,
0,
1,
0
]);
},
sobelX: () => {
filter.convolution.call(this, [
-1,
0,
1,
-2,
0,
2,
-1,
0,
1
]);
},
sobelY: () => {
filter.convolution.call(this, [
-1,
-2,
-1,
0,
0,
0,
1,
2,
1
]);
},
sharpen: (amount) => {
const a = amount || 1;
filter.convolution.call(this, [
0,
-1 * a,
0,
-1 * a,
1 + 4 * a,
-1 * a,
0,
-1 * a,
0
]);
},
emboss: (size2) => {
const s = size2 || 1;
filter.convolution.call(this, [
-2 * s,
-1 * s,
0,
-1 * s,
1,
1 * s,
0,
1 * s,
2 * s
]);
},
blur: (size2) => {
const blurSizeX = size2 / 7 / fxcanvas.width;
const blurSizeY = size2 / 7 / fxcanvas.height;
const program = compileShader(blur);
gl2.uniform2f(program == null ? void 0 : program.uniform["px"], 0, blurSizeY);
draw2(DRAW.INTERMEDIATE);
gl2.uniform2f(program == null ? void 0 : program.uniform["px"], blurSizeX, 0);
draw2();
},
pixelate: (size2) => {
const blurSizeX = size2 / fxcanvas.width;
const blurSizeY = size2 / fxcanvas.height;
const program = compileShader(pixelate);
gl2.uniform2f(program == null ? void 0 : program.uniform["size"], blurSizeX, blurSizeY);
draw2();
}
};
this.add = function(name) {
const args = Array.prototype.slice.call(arguments, 1);
const func = filter[name];
filterChain.push({ func, args });
};
this.reset = function() {
filterChain = [];
};
this.get = function() {
return filterChain;
};
this.apply = function(image6) {
resize(image6.width, image6.height);
drawCount = 0;
if (!sourceTexture)
sourceTexture = gl2.createTexture();
gl2.bindTexture(gl2.TEXTURE_2D, sourceTexture);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_S, gl2.CLAMP_TO_EDGE);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_T, gl2.CLAMP_TO_EDGE);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MIN_FILTER, gl2.NEAREST);
gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MAG_FILTER, gl2.NEAREST);
gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, gl2.RGBA, gl2.UNSIGNED_BYTE, image6);
for (let i = 0; i < filterChain.length; i++) {
lastInChain = i === filterChain.length - 1;
const f = filterChain[i];
f.func.apply(this, f.args || []);
}
return fxcanvas;
};
this.draw = function(image6) {
this.add("brightness", 0);
return this.apply(image6);
};
}
// src/image/image.ts
var maxSize = 2048;
var inCanvas = null;
var outCanvas = null;
var tmpCanvas = null;
var fx2;
function canvas(width, height) {
let c;
if (env.browser) {
if (env.offscreen) {
c = new OffscreenCanvas(width, height);
} else {
if (typeof document === "undefined")
throw new Error("attempted to run in web worker but offscreenCanvas is not supported");
c = document.createElement("canvas");
c.width = width;
c.height = height;
}
} else {
if (typeof env.Canvas !== "undefined")
c = new env.Canvas(width, height);
else if (typeof globalThis.Canvas !== "undefined")
c = new globalThis.Canvas(width, height);
}
return c;
}
function copy(input, output) {
const outputCanvas = output || canvas(input.width, input.height);
const ctx = outputCanvas.getContext("2d");
ctx.drawImage(input, 0, 0);
return outputCanvas;
}
function process2(input, config3, getTensor = true) {
if (!input) {
if (config3.debug)
log("input is missing");
return { tensor: null, canvas: null };
}
if (!(input instanceof Le) && !(typeof Image !== "undefined" && input instanceof Image) && !(typeof env.Canvas !== "undefined" && input instanceof env.Canvas) && !(typeof globalThis.Canvas !== "undefined" && input instanceof globalThis.Canvas) && !(typeof ImageData !== "undefined" && input instanceof ImageData) && !(typeof ImageBitmap !== "undefined" && input instanceof ImageBitmap) && !(typeof HTMLImageElement !== "undefined" && input instanceof HTMLImageElement) && !(typeof HTMLMediaElement !== "undefined" && input instanceof HTMLMediaElement) && !(typeof HTMLVideoElement !== "undefined" && input instanceof HTMLVideoElement) && !(typeof HTMLCanvasElement !== "undefined" && input instanceof HTMLCanvasElement) && !(typeof OffscreenCanvas !== "undefined" && input instanceof OffscreenCanvas)) {
throw new Error("input type is not recognized");
}
if (input instanceof Le) {
if (input["isDisposedInternal"]) {
throw new Error("input tensor is disposed");
} else if (!input.shape || input.shape.length !== 4 || input.shape[0] !== 1 || input.shape[3] !== 3) {
throw new Error(`input tensor shape must be [1, height, width, 3] and instead was ${input["shape"]}`);
} else {
return { tensor: wn(input), canvas: config3.filter.return ? outCanvas : null };
}
} else {
if (typeof input["readyState"] !== "undefined" && input["readyState"] <= 2) {
if (config3.debug)
log("input stream is not ready");
return { tensor: null, canvas: inCanvas };
}
const originalWidth = input["naturalWidth"] || input["videoWidth"] || input["width"] || input["shape"] && input["shape"][1] > 0;
const originalHeight = input["naturalHeight"] || input["videoHeight"] || input["height"] || input["shape"] && input["shape"][2] > 0;
if (!originalWidth || !originalHeight) {
if (config3.debug)
log("cannot determine input dimensions");
return { tensor: null, canvas: inCanvas };
}
let targetWidth = originalWidth;
let targetHeight = originalHeight;
if (targetWidth > maxSize) {
targetWidth = maxSize;
targetHeight = Math.trunc(targetWidth * originalHeight / originalWidth);
}
if (targetHeight > maxSize) {
targetHeight = maxSize;
targetWidth = Math.trunc(targetHeight * originalWidth / originalHeight);
}
if ((config3.filter.width || 0) > 0)
targetWidth = config3.filter.width;
else if ((config3.filter.height || 0) > 0)
targetWidth = originalWidth * ((config3.filter.height || 0) / originalHeight);
if ((config3.filter.height || 0) > 0)
targetHeight = config3.filter.height;
else if ((config3.filter.width || 0) > 0)
targetHeight = originalHeight * ((config3.filter.width || 0) / originalWidth);
if (!targetWidth || !targetHeight)
throw new Error("input cannot determine dimension");
if (!inCanvas || (inCanvas == null ? void 0 : inCanvas.width) !== targetWidth || (inCanvas == null ? void 0 : inCanvas.height) !== targetHeight)
inCanvas = canvas(targetWidth, targetHeight);
const inCtx = inCanvas.getContext("2d");
if (typeof ImageData !== "undefined" && input instanceof ImageData) {
inCtx.putImageData(input, 0, 0);
} else {
if (config3.filter.flip && typeof inCtx.translate !== "undefined") {
inCtx.translate(originalWidth, 0);
inCtx.scale(-1, 1);
inCtx.drawImage(input, 0, 0, originalWidth, originalHeight, 0, 0, inCanvas == null ? void 0 : inCanvas.width, inCanvas == null ? void 0 : inCanvas.height);
inCtx.setTransform(1, 0, 0, 1, 0, 0);
} else {
inCtx.drawImage(input, 0, 0, originalWidth, originalHeight, 0, 0, inCanvas == null ? void 0 : inCanvas.width, inCanvas == null ? void 0 : inCanvas.height);
}
}
if (!outCanvas || inCanvas.width !== outCanvas.width || (inCanvas == null ? void 0 : inCanvas.height) !== (outCanvas == null ? void 0 : outCanvas.height))
outCanvas = canvas(inCanvas.width, inCanvas.height);
if (config3.filter.enabled && env.webgl.supported) {
if (!fx2)
fx2 = env.browser ? new GLImageFilter() : null;
env.filter = !!fx2;
if (!fx2)
return { tensor: null, canvas: inCanvas };
fx2.reset();
if (config3.filter.brightness !== 0)
fx2.add("brightness", config3.filter.brightness);
if (config3.filter.contrast !== 0)
fx2.add("contrast", config3.filter.contrast);
if (config3.filter.sharpness !== 0)
fx2.add("sharpen", config3.filter.sharpness);
if (config3.filter.blur !== 0)
fx2.add("blur", config3.filter.blur);
if (config3.filter.saturation !== 0)
fx2.add("saturation", config3.filter.saturation);
if (config3.filter.hue !== 0)
fx2.add("hue", config3.filter.hue);
if (config3.filter.negative)
fx2.add("negative");
if (config3.filter.sepia)
fx2.add("sepia");
if (config3.filter.vintage)
fx2.add("brownie");
if (config3.filter.sepia)
fx2.add("sepia");
if (config3.filter.kodachrome)
fx2.add("kodachrome");
if (config3.filter.technicolor)
fx2.add("technicolor");
if (config3.filter.polaroid)
fx2.add("polaroid");
if (config3.filter.pixelate !== 0)
fx2.add("pixelate", config3.filter.pixelate);
if (fx2.get() > 0)
outCanvas = fx2.apply(inCanvas);
else
outCanvas = fx2.draw(inCanvas);
} else {
copy(inCanvas, outCanvas);
if (fx2)
fx2 = null;
env.filter = !!fx2;
}
if (!getTensor)
return { tensor: null, canvas: outCanvas };
if (!outCanvas)
throw new Error("cannot create output canvas");
let pixels;
let depth = 3;
if (typeof ImageData !== "undefined" && input instanceof ImageData || input["data"] && input["width"] && input["height"]) {
if (env.browser && Gg) {
pixels = Gg ? Gg.fromPixels(input) : null;
} else {
depth = input["data"].length / input["height"] / input["width"];
const arr = new Uint8Array(input["data"]["buffer"]);
pixels = Dr(arr, [input["height"], input["width"], depth], "int32");
}
} else {
if (!tmpCanvas || outCanvas.width !== tmpCanvas.width || (outCanvas == null ? void 0 : outCanvas.height) !== (tmpCanvas == null ? void 0 : tmpCanvas.height))
tmpCanvas = canvas(outCanvas.width, outCanvas.height);
if (Gg && env.browser) {
if (config3.backend === "webgl" || config3.backend === "humangl" || config3.backend === "webgpu") {
pixels = Gg.fromPixels(outCanvas);
} else {
tmpCanvas = copy(outCanvas);
pixels = Gg.fromPixels(tmpCanvas);
}
} else {
const tempCanvas = copy(outCanvas);
const tempCtx = tempCanvas.getContext("2d");
const tempData = tempCtx.getImageData(0, 0, targetWidth, targetHeight);
depth = tempData.data.length / targetWidth / targetHeight;
const arr = new Uint8Array(tempData.data.buffer);
pixels = Dr(arr, [targetWidth, targetHeight, depth]);
}
}
if (depth === 4) {
const rgb2 = Gf(pixels, [0, 0, 0], [-1, -1, 3]);
De(pixels);
pixels = rgb2;
}
if (!pixels)
throw new Error("cannot create tensor from input");
const casted = Y(pixels, "float32");
const tensor = mr(casted, 0);
De([pixels, casted]);
return { tensor, canvas: config3.filter.return ? outCanvas : null };
}
}
var lastInputSum = 0;
var lastCacheDiff = 1;
var benchmarked = 0;
var checksum = async (input) => {
const resizeFact = 48;
const reduced = Cn.resizeBilinear(input, [Math.trunc((input.shape[1] || 1) / resizeFact), Math.trunc((input.shape[2] || 1) / resizeFact)]);
const tfSum = async () => {
const sumT = me(reduced);
const sum0 = await sumT.data();
De(sumT);
return sum0[0];
};
const jsSum = async () => {
const reducedData = await reduced.data();
let sum0 = 0;
for (let i = 0; i < reducedData.length / 3; i++)
sum0 += reducedData[3 * i + 2];
return sum0;
};
if (benchmarked === 0) {
const t02 = now();
await jsSum();
const t12 = now();
await tfSum();
const t22 = now();
benchmarked = t12 - t02 < t22 - t12 ? 1 : 2;
}
const res = benchmarked === 1 ? await jsSum() : await tfSum();
De(reduced);
return res;
};
async function skip(config3, input) {
if (config3.cacheSensitivity === 0)
return false;
const sum = await checksum(input);
const diff = 100 * (Math.max(sum, lastInputSum) / Math.min(sum, lastInputSum) - 1);
lastInputSum = sum;
let skipFrame = diff < Math.max(config3.cacheSensitivity, lastCacheDiff);
lastCacheDiff = diff > 10 * config3.cacheSensitivity ? 0 : diff;
skipFrame = skipFrame && lastCacheDiff > 0;
return skipFrame;
}
// src/util/env.ts
var Env = class {
constructor() {
__publicField(this, "browser");
__publicField(this, "node");
__publicField(this, "worker");
__publicField(this, "platform", "");
__publicField(this, "agent", "");
__publicField(this, "backends", []);
__publicField(this, "initial");
__publicField(this, "filter");
__publicField(this, "tfjs");
__publicField(this, "offscreen");
__publicField(this, "wasm", {
supported: void 0,
backend: void 0,
simd: void 0,
multithread: void 0
});
__publicField(this, "webgl", {
supported: void 0,
backend: void 0,
version: void 0,
renderer: void 0
});
__publicField(this, "webgpu", {
supported: void 0,
backend: void 0,
adapter: void 0
});
__publicField(this, "cpu", {
model: void 0,
flags: []
});
__publicField(this, "kernels", []);
__publicField(this, "Canvas");
__publicField(this, "Image");
__publicField(this, "ImageData");
this.browser = typeof navigator !== "undefined";
this.node = typeof process !== "undefined";
this.tfjs = { version: E1 };
this.offscreen = typeof OffscreenCanvas !== "undefined";
this.initial = true;
this.worker = this.browser && this.offscreen ? typeof WorkerGlobalScope !== "undefined" : void 0;
if (typeof navigator !== "undefined") {
const raw = navigator.userAgent.match(/\(([^()]+)\)/g);
if (raw && raw[0]) {
const platformMatch = raw[0].match(/\(([^()]+)\)/g);
this.platform = platformMatch && platformMatch[0] ? platformMatch[0].replace(/\(|\)/g, "") : "";
this.agent = navigator.userAgent.replace(raw[0], "");
if (this.platform[1])
this.agent = this.agent.replace(raw[1], "");
this.agent = this.agent.replace(/ /g, " ");
}
} else if (typeof process !== "undefined") {
this.platform = `${process.platform} ${process.arch}`;
this.agent = `NodeJS ${process.version}`;
}
}
async updateBackend() {
var _a2;
this.backends = Object.keys(Es().registryFactory);
this.wasm.supported = typeof WebAssembly !== "undefined";
this.wasm.backend = this.backends.includes("wasm");
if (this.wasm.supported && this.wasm.backend && cue() === "wasm") {
this.wasm.simd = await U().getAsync("WASM_HAS_SIMD_SUPPORT");
this.wasm.multithread = await U().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");
}
const c = canvas(100, 100);
const ctx = c ? c.getContext("webgl2") : void 0;
this.webgl.supported = typeof ctx !== "undefined";
this.webgl.backend = this.backends.includes("webgl");
if (this.webgl.supported && this.webgl.backend && (cue() === "webgl" || cue() === "humangl")) {
const gl2 = A1().gpgpu !== "undefined" ? await A1().getGPGPUContext().gl : null;
if (gl2) {
this.webgl.version = gl2.getParameter(gl2.VERSION);
this.webgl.renderer = gl2.getParameter(gl2.RENDERER);
}
}
this.webgpu.supported = this.browser && typeof navigator["gpu"] !== "undefined";
this.webgpu.backend = this.backends.includes("webgpu");
if (this.webgpu.supported)
this.webgpu.adapter = (_a2 = await navigator["gpu"].requestAdapter()) == null ? void 0 : _a2.name;
this.kernels = Ag(cue()).map((kernel) => kernel.kernelName.toLowerCase());
}
async updateCPU() {
var _a2;
const cpu = { model: "", flags: [] };
if (this.node && ((_a2 = this.platform) == null ? void 0 : _a2.startsWith("linux"))) {
const fs2 = __require("fs");
try {
const data = fs2.readFileSync("/proc/cpuinfo").toString();
for (const line of data.split("\n")) {
if (line.startsWith("model name")) {
cpu.model = line.match(/:(.*)/g)[0].replace(":", "").trim();
}
if (line.startsWith("flags")) {
cpu.flags = line.match(/:(.*)/g)[0].replace(":", "").trim().split(" ").sort();
}
}
} catch (e) {
}
}
if (!this["cpu"])
Object.defineProperty(this, "cpu", { value: cpu });
else
this["cpu"] = cpu;
}
};
var env = new Env();
// package.json
var version = "2.4.0";
// src/gear/gear-agegenderrace.ts
var model;
var skipped = Number.MAX_SAFE_INTEGER;
async function load(config3) {
if (env.initial)
model = null;
if (!model) {
model = await m7(join(config3.modelBasePath, config3.face.agegenderrace.modelPath));
if (!model || !model["modelUrl"])
log("load model failed:", config3.face.agegenderrace.modelPath);
else if (config3.debug)
log("load model:", model["modelUrl"]);
} else if (config3.debug)
log("cached model:", model["modelUrl"]);
return model;
}
// src/face/antispoof.ts
var model2;
var cached = [];
var skipped2 = Number.MAX_SAFE_INTEGER;
var lastCount = 0;
var last = 0;
async function load2(config3) {
var _a2, _b;
if (env.initial)
model2 = null;
if (!model2) {
model2 = await m7(join(config3.modelBasePath, ((_a2 = config3.face.antispoof) == null ? void 0 : _a2.modelPath) || ""));
if (!model2 || !model2["modelUrl"])
log("load model failed:", (_b = config3.face.antispoof) == null ? void 0 : _b.modelPath);
else if (config3.debug)
log("load model:", model2["modelUrl"]);
} else if (config3.debug)
log("cached model:", model2["modelUrl"]);
return model2;
}
async function predict(image6, config3, idx, count2) {
var _a2, _b;
if (!model2)
return null;
if (skipped2 < (((_a2 = config3.face.antispoof) == null ? void 0 : _a2.skipFrames) || 0) && (((_b = config3.face.antispoof) == null ? void 0 : _b.skipTime) || 0) <= now() - last && config3.skipFrame && lastCount === count2 && cached[idx]) {
skipped2++;
return cached[idx];
}
skipped2 = 0;
return new Promise(async (resolve) => {
const resize = Cn.resizeBilinear(image6, [(model2 == null ? void 0 : model2.inputs[0].shape) ? model2.inputs[0].shape[2] : 0, (model2 == null ? void 0 : model2.inputs[0].shape) ? model2.inputs[0].shape[1] : 0], false);
const res = model2 == null ? void 0 : model2.predict(resize);
const num = (await res.data())[0];
cached[idx] = Math.round(100 * num) / 100;
lastCount = count2;
last = now();
De([resize, res]);
resolve(cached[idx]);
});
}
// src/face/facemeshcoords.ts
var meshAnnotations = {
silhouette: [
10,
338,
297,
332,
284,
251,
389,
356,
454,
323,
361,
288,
397,
365,
379,
378,
400,
377,
152,
148,
176,
149,
150,
136,
172,
58,
132,
93,
234,
127,
162,
21,
54,
103,
67,
109
],
lipsUpperOuter: [61, 185, 40, 39, 37, 0, 267, 269, 270, 409, 291],
lipsLowerOuter: [146, 91, 181, 84, 17, 314, 405, 321, 375, 291],
lipsUpperInner: [78, 191, 80, 81, 82, 13, 312, 311, 310, 415, 308],
lipsLowerInner: [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308],
rightEyeUpper0: [246, 161, 160, 159, 158, 157, 173],
rightEyeLower0: [33, 7, 163, 144, 145, 153, 154, 155, 133],
rightEyeUpper1: [247, 30, 29, 27, 28, 56, 190],
rightEyeLower1: [130, 25, 110, 24, 23, 22, 26, 112, 243],
rightEyeUpper2: [113, 225, 224, 223, 222, 221, 189],
rightEyeLower2: [226, 31, 228, 229, 230, 231, 232, 233, 244],
rightEyeLower3: [143, 111, 117, 118, 119, 120, 121, 128, 245],
rightEyebrowUpper: [156, 70, 63, 105, 66, 107, 55, 193],
rightEyebrowLower: [35, 124, 46, 53, 52, 65],
rightEyeIris: [473, 474, 475, 476, 477],
leftEyeUpper0: [466, 388, 387, 386, 385, 384, 398],
leftEyeLower0: [263, 249, 390, 373, 374, 380, 381, 382, 362],
leftEyeUpper1: [467, 260, 259, 257, 258, 286, 414],
leftEyeLower1: [359, 255, 339, 254, 253, 252, 256, 341, 463],
leftEyeUpper2: [342, 445, 444, 443, 442, 441, 413],
leftEyeLower2: [446, 261, 448, 449, 450, 451, 452, 453, 464],
leftEyeLower3: [372, 340, 346, 347, 348, 349, 350, 357, 465],
leftEyebrowUpper: [383, 300, 293, 334, 296, 336, 285, 417],
leftEyebrowLower: [265, 353, 276, 283, 282, 295],
leftEyeIris: [468, 469, 470, 471, 472],
midwayBetweenEyes: [168],
noseTip: [1],
noseBottom: [2],
noseRightCorner: [98],
noseLeftCorner: [327],
rightCheek: [205],
leftCheek: [425]
};
var meshLandmarks = {
count: 468,
mouth: 13,
symmetryLine: [13, meshAnnotations["midwayBetweenEyes"][0]]
};
var blazeFaceLandmarks = {
leftEye: 0,
rightEye: 1,
nose: 2,
mouth: 3,
leftEar: 4,
rightEar: 5,
symmetryLine: [3, 2]
};
var MESH_TO_IRIS_INDICES_MAP = [
{ key: "EyeUpper0", indices: [9, 10, 11, 12, 13, 14, 15] },
{ key: "EyeUpper1", indices: [25, 26, 27, 28, 29, 30, 31] },
{ key: "EyeUpper2", indices: [41, 42, 43, 44, 45, 46, 47] },
{ key: "EyeLower0", indices: [0, 1, 2, 3, 4, 5, 6, 7, 8] },
{ key: "EyeLower1", indices: [16, 17, 18, 19, 20, 21, 22, 23, 24] },
{ key: "EyeLower2", indices: [32, 33, 34, 35, 36, 37, 38, 39, 40] },
{ key: "EyeLower3", indices: [54, 55, 56, 57, 58, 59, 60, 61, 62] }
];
var UV468 = [
[0.499976992607117, 0.652534008026123],
[0.500025987625122, 0.547487020492554],
[0.499974012374878, 0.602371990680695],
[0.482113003730774, 0.471979022026062],
[0.500150978565216, 0.527155995368958],
[0.499909996986389, 0.498252987861633],
[0.499523013830185, 0.40106201171875],
[0.289712011814117, 0.380764007568359],
[0.499954998493195, 0.312398016452789],
[0.499987006187439, 0.269918978214264],
[0.500023007392883, 0.107050001621246],
[0.500023007392883, 0.666234016418457],
[0.5000159740448, 0.679224014282227],
[0.500023007392883, 0.692348003387451],
[0.499976992607117, 0.695277988910675],
[0.499976992607117, 0.70593398809433],
[0.499976992607117, 0.719385027885437],
[0.499976992607117, 0.737019002437592],
[0.499967992305756, 0.781370997428894],
[0.499816000461578, 0.562981009483337],
[0.473773002624512, 0.573909997940063],
[0.104906998574734, 0.254140973091125],
[0.365929991006851, 0.409575998783112],
[0.338757991790771, 0.41302502155304],
[0.311120003461838, 0.409460008144379],
[0.274657994508743, 0.389131009578705],
[0.393361985683441, 0.403706014156342],
[0.345234006643295, 0.344011008739471],
[0.370094001293182, 0.346076011657715],
[0.319321990013123, 0.347265005111694],
[0.297903001308441, 0.353591024875641],
[0.24779200553894, 0.410809993743896],
[0.396889001131058, 0.842755019664764],
[0.280097991228104, 0.375599980354309],
[0.106310002505779, 0.399955987930298],
[0.2099249958992, 0.391353011131287],
[0.355807989835739, 0.534406006336212],
[0.471751004457474, 0.65040397644043],
[0.474155008792877, 0.680191993713379],
[0.439785003662109, 0.657229006290436],
[0.414617002010345, 0.66654098033905],
[0.450374007225037, 0.680860996246338],
[0.428770989179611, 0.682690978050232],
[0.374971002340317, 0.727805018424988],
[0.486716985702515, 0.547628998756409],
[0.485300987958908, 0.527395009994507],
[0.257764995098114, 0.314490020275116],
[0.401223003864288, 0.455172002315521],
[0.429818987846375, 0.548614978790283],
[0.421351999044418, 0.533740997314453],
[0.276895999908447, 0.532056987285614],
[0.483370006084442, 0.499586999416351],
[0.33721199631691, 0.282882988452911],
[0.296391993761063, 0.293242990970612],
[0.169294998049736, 0.193813979625702],
[0.447580009698868, 0.302609980106354],
[0.392390012741089, 0.353887975215912],
[0.354490011930466, 0.696784019470215],
[0.067304998636246, 0.730105042457581],
[0.442739009857178, 0.572826027870178],
[0.457098007202148, 0.584792017936707],
[0.381974011659622, 0.694710969924927],
[0.392388999462128, 0.694203019142151],
[0.277076005935669, 0.271932005882263],
[0.422551989555359, 0.563233017921448],
[0.385919004678726, 0.281364023685455],
[0.383103013038635, 0.255840003490448],
[0.331431001424789, 0.119714021682739],
[0.229923993349075, 0.232002973556519],
[0.364500999450684, 0.189113974571228],
[0.229622006416321, 0.299540996551514],
[0.173287004232407, 0.278747975826263],
[0.472878992557526, 0.666198015213013],
[0.446828007698059, 0.668527007102966],
[0.422762006521225, 0.673889994621277],
[0.445307999849319, 0.580065965652466],
[0.388103008270264, 0.693961024284363],
[0.403039008378983, 0.706539988517761],
[0.403629004955292, 0.693953037261963],
[0.460041999816895, 0.557139039039612],
[0.431158006191254, 0.692366003990173],
[0.452181994915009, 0.692366003990173],
[0.475387006998062, 0.692366003990173],
[0.465828001499176, 0.779190003871918],
[0.472328990697861, 0.736225962638855],
[0.473087012767792, 0.717857003211975],
[0.473122000694275, 0.704625964164734],
[0.473033010959625, 0.695277988910675],
[0.427942007780075, 0.695277988910675],
[0.426479011774063, 0.703539967536926],
[0.423162013292313, 0.711845993995667],
[0.4183090031147, 0.720062971115112],
[0.390094995498657, 0.639572978019714],
[0.013953999616206, 0.560034036636353],
[0.499913990497589, 0.58014702796936],
[0.413199990987778, 0.69539999961853],
[0.409626007080078, 0.701822996139526],
[0.468080013990402, 0.601534962654114],
[0.422728985548019, 0.585985004901886],
[0.463079988956451, 0.593783974647522],
[0.37211999297142, 0.47341400384903],
[0.334562003612518, 0.496073007583618],
[0.411671012639999, 0.546965003013611],
[0.242175996303558, 0.14767599105835],
[0.290776997804642, 0.201445996761322],
[0.327338010072708, 0.256527006626129],
[0.399509996175766, 0.748921036720276],
[0.441727995872498, 0.261676013469696],
[0.429764986038208, 0.187834024429321],
[0.412198007106781, 0.108901023864746],
[0.288955003023148, 0.398952007293701],
[0.218936994671822, 0.435410976409912],
[0.41278201341629, 0.398970007896423],
[0.257135003805161, 0.355440020561218],
[0.427684992551804, 0.437960982322693],
[0.448339998722076, 0.536936044692993],
[0.178560003638268, 0.45755398273468],
[0.247308000922203, 0.457193970680237],
[0.286267012357712, 0.467674970626831],
[0.332827985286713, 0.460712015628815],
[0.368755996227264, 0.447206974029541],
[0.398963987827301, 0.432654976844788],
[0.476410001516342, 0.405806005001068],
[0.189241006970406, 0.523923993110657],
[0.228962004184723, 0.348950982093811],
[0.490725994110107, 0.562400996685028],
[0.404670000076294, 0.485132992267609],
[0.019469000399113, 0.401564002037048],
[0.426243007183075, 0.420431017875671],
[0.396993011236191, 0.548797011375427],
[0.266469985246658, 0.376977026462555],
[0.439121007919312, 0.51895797252655],
[0.032313998788595, 0.644356966018677],
[0.419054001569748, 0.387154996395111],
[0.462783008813858, 0.505746960639954],
[0.238978996872902, 0.779744982719421],
[0.198220998048782, 0.831938028335571],
[0.107550002634525, 0.540755033493042],
[0.183610007166862, 0.740257024765015],
[0.134409993886948, 0.333683013916016],
[0.385764002799988, 0.883153975009918],
[0.490967005491257, 0.579378008842468],
[0.382384985685349, 0.508572995662689],
[0.174399003386497, 0.397670984268188],
[0.318785011768341, 0.39623498916626],
[0.343364000320435, 0.400596976280212],
[0.396100014448166, 0.710216999053955],
[0.187885001301765, 0.588537991046906],
[0.430987000465393, 0.944064974784851],
[0.318993002176285, 0.898285031318665],
[0.266247987747192, 0.869701027870178],
[0.500023007392883, 0.190576016902924],
[0.499976992607117, 0.954452991485596],
[0.366169989109039, 0.398822009563446],
[0.393207013607025, 0.39553701877594],
[0.410373002290726, 0.391080021858215],
[0.194993004202843, 0.342101991176605],
[0.388664990663528, 0.362284004688263],
[0.365961998701096, 0.355970978736877],
[0.343364000320435, 0.355356991291046],
[0.318785011768341, 0.35834002494812],
[0.301414996385574, 0.363156020641327],
[0.058132998645306, 0.319076001644135],
[0.301414996385574, 0.387449026107788],
[0.499987989664078, 0.618434011936188],
[0.415838003158569, 0.624195992946625],
[0.445681989192963, 0.566076993942261],
[0.465844005346298, 0.620640993118286],
[0.49992299079895, 0.351523995399475],
[0.288718998432159, 0.819945991039276],
[0.335278987884521, 0.852819979190826],
[0.440512001514435, 0.902418971061707],
[0.128294005990028, 0.791940987110138],
[0.408771991729736, 0.373893976211548],
[0.455606997013092, 0.451801002025604],
[0.499877005815506, 0.908990025520325],
[0.375436991453171, 0.924192011356354],
[0.11421000212431, 0.615022003650665],
[0.448662012815475, 0.695277988910675],
[0.4480200111866, 0.704632043838501],
[0.447111994028091, 0.715808033943176],
[0.444831997156143, 0.730794012546539],
[0.430011987686157, 0.766808986663818],
[0.406787008047104, 0.685672998428345],
[0.400738000869751, 0.681069016456604],
[0.392399996519089, 0.677703022956848],
[0.367855995893478, 0.663918972015381],
[0.247923001646996, 0.601333022117615],
[0.452769994735718, 0.420849978923798],
[0.43639200925827, 0.359887003898621],
[0.416164010763168, 0.368713974952698],
[0.413385987281799, 0.692366003990173],
[0.228018000721931, 0.683571994304657],
[0.468268007040024, 0.352671027183533],
[0.411361992359161, 0.804327011108398],
[0.499989002943039, 0.469825029373169],
[0.479153990745544, 0.442654013633728],
[0.499974012374878, 0.439637005329132],
[0.432112008333206, 0.493588984012604],
[0.499886006116867, 0.866917014122009],
[0.49991300702095, 0.821729004383087],
[0.456548988819122, 0.819200992584229],
[0.344549000263214, 0.745438992977142],
[0.37890899181366, 0.574010014533997],
[0.374292999505997, 0.780184984207153],
[0.319687992334366, 0.570737957954407],
[0.357154995203018, 0.604269981384277],
[0.295284003019333, 0.621580958366394],
[0.447750002145767, 0.862477004528046],
[0.410986006259918, 0.508723020553589],
[0.31395098567009, 0.775308012962341],
[0.354128003120422, 0.812552988529205],
[0.324548006057739, 0.703992962837219],
[0.189096003770828, 0.646299958229065],
[0.279776990413666, 0.71465802192688],
[0.1338230073452, 0.682700991630554],
[0.336768001317978, 0.644733011722565],
[0.429883986711502, 0.466521978378296],
[0.455527991056442, 0.548622965812683],
[0.437114000320435, 0.558896005153656],
[0.467287987470627, 0.529924988746643],
[0.414712011814117, 0.335219979286194],
[0.37704598903656, 0.322777986526489],
[0.344107985496521, 0.320150971412659],
[0.312875986099243, 0.32233202457428],
[0.283526003360748, 0.333190023899078],
[0.241245999932289, 0.382785975933075],
[0.102986000478268, 0.468762993812561],
[0.267612010240555, 0.424560010433197],
[0.297879010438919, 0.433175981044769],
[0.333433985710144, 0.433878004550934],
[0.366427004337311, 0.426115989685059],
[0.396012008190155, 0.416696012020111],
[0.420121014118195, 0.41022801399231],
[0.007561000064015, 0.480777025222778],
[0.432949006557465, 0.569517970085144],
[0.458638995885849, 0.479089021682739],
[0.473466008901596, 0.545744001865387],
[0.476087987422943, 0.563830018043518],
[0.468472003936768, 0.555056989192963],
[0.433990985155106, 0.582361996173859],
[0.483518004417419, 0.562983989715576],
[0.482482999563217, 0.57784903049469],
[0.42645001411438, 0.389798998832703],
[0.438998997211456, 0.39649498462677],
[0.450067013502121, 0.400434017181396],
[0.289712011814117, 0.368252992630005],
[0.276670008897781, 0.363372981548309],
[0.517862021923065, 0.471948027610779],
[0.710287988185883, 0.380764007568359],
[0.526226997375488, 0.573909997940063],
[0.895093023777008, 0.254140973091125],
[0.634069979190826, 0.409575998783112],
[0.661242008209229, 0.41302502155304],
[0.688880026340485, 0.409460008144379],
[0.725341975688934, 0.389131009578705],
[0.606630027294159, 0.40370500087738],
[0.654766023159027, 0.344011008739471],
[0.629905998706818, 0.346076011657715],
[0.680678009986877, 0.347265005111694],
[0.702096998691559, 0.353591024875641],
[0.75221198797226, 0.410804986953735],
[0.602918028831482, 0.842862963676453],
[0.719901978969574, 0.375599980354309],
[0.893692970275879, 0.399959981441498],
[0.790081977844238, 0.391354024410248],
[0.643998026847839, 0.534487962722778],
[0.528249025344849, 0.65040397644043],
[0.525849997997284, 0.680191040039062],
[0.560214996337891, 0.657229006290436],
[0.585384011268616, 0.66654098033905],
[0.549625992774963, 0.680860996246338],
[0.57122802734375, 0.682691991329193],
[0.624852001667023, 0.72809898853302],
[0.513050019741058, 0.547281980514526],
[0.51509702205658, 0.527251958847046],
[0.742246985435486, 0.314507007598877],
[0.598631024360657, 0.454979002475739],
[0.570338010787964, 0.548575043678284],
[0.578631997108459, 0.533622980117798],
[0.723087012767792, 0.532054007053375],
[0.516445994377136, 0.499638974666595],
[0.662801027297974, 0.282917976379395],
[0.70362401008606, 0.293271005153656],
[0.830704987049103, 0.193813979625702],
[0.552385985851288, 0.302568018436432],
[0.607609987258911, 0.353887975215912],
[0.645429015159607, 0.696707010269165],
[0.932694971561432, 0.730105042457581],
[0.557260990142822, 0.572826027870178],
[0.542901992797852, 0.584792017936707],
[0.6180260181427, 0.694710969924927],
[0.607590973377228, 0.694203019142151],
[0.722943007946014, 0.271963000297546],
[0.577413976192474, 0.563166975975037],
[0.614082992076874, 0.281386971473694],
[0.616907000541687, 0.255886018276215],
[0.668509006500244, 0.119913995265961],
[0.770092010498047, 0.232020974159241],
[0.635536015033722, 0.189248979091644],
[0.77039098739624, 0.299556016921997],
[0.826722025871277, 0.278755009174347],
[0.527121007442474, 0.666198015213013],
[0.553171992301941, 0.668527007102966],
[0.577238023281097, 0.673889994621277],
[0.554691970348358, 0.580065965652466],
[0.611896991729736, 0.693961024284363],
[0.59696102142334, 0.706539988517761],
[0.596370995044708, 0.693953037261963],
[0.539958000183105, 0.557139039039612],
[0.568841993808746, 0.692366003990173],
[0.547818005084991, 0.692366003990173],
[0.52461302280426, 0.692366003990173],
[0.534089982509613, 0.779141008853912],
[0.527670979499817, 0.736225962638855],
[0.526912987232208, 0.717857003211975],
[0.526877999305725, 0.704625964164734],
[0.526966989040375, 0.695277988910675],
[0.572058022022247, 0.695277988910675],
[0.573521018028259, 0.703539967536926],
[0.57683801651001, 0.711845993995667],
[0.581691026687622, 0.720062971115112],
[0.609944999217987, 0.639909982681274],
[0.986046016216278, 0.560034036636353],
[0.5867999792099, 0.69539999961853],
[0.590372025966644, 0.701822996139526],
[0.531915009021759, 0.601536989212036],
[0.577268004417419, 0.585934996604919],
[0.536915004253387, 0.593786001205444],
[0.627542972564697, 0.473352015018463],
[0.665585994720459, 0.495950996875763],
[0.588353991508484, 0.546862006187439],
[0.757824003696442, 0.14767599105835],
[0.709249973297119, 0.201507985591888],
[0.672684013843536, 0.256581008434296],
[0.600408971309662, 0.74900496006012],
[0.55826598405838, 0.261672019958496],
[0.570303976535797, 0.187870979309082],
[0.588165998458862, 0.109044015407562],
[0.711045026779175, 0.398952007293701],
[0.781069993972778, 0.435405015945435],
[0.587247014045715, 0.398931980133057],
[0.742869973182678, 0.355445981025696],
[0.572156012058258, 0.437651991844177],
[0.55186802148819, 0.536570012569427],
[0.821442008018494, 0.457556009292603],
[0.752701997756958, 0.457181990146637],
[0.71375697851181, 0.467626988887787],
[0.66711300611496, 0.460672974586487],
[0.631101012229919, 0.447153985500336],
[0.6008620262146, 0.432473003864288],
[0.523481011390686, 0.405627012252808],
[0.810747981071472, 0.523926019668579],
[0.771045982837677, 0.348959028720856],
[0.509127020835876, 0.562718033790588],
[0.595292985439301, 0.485023975372314],
[0.980530977249146, 0.401564002037048],
[0.573499977588654, 0.420000016689301],
[0.602994978427887, 0.548687994480133],
[0.733529984951019, 0.376977026462555],
[0.560611009597778, 0.519016981124878],
[0.967685997486115, 0.644356966018677],
[0.580985009670258, 0.387160003185272],
[0.537728011608124, 0.505385041236877],
[0.760966002941132, 0.779752969741821],
[0.801778972148895, 0.831938028335571],
[0.892440974712372, 0.54076099395752],
[0.816350996494293, 0.740260004997253],
[0.865594983100891, 0.333687007427216],
[0.614073991775513, 0.883246004581451],
[0.508952975273132, 0.579437971115112],
[0.617941975593567, 0.508316040039062],
[0.825608015060425, 0.397674977779388],
[0.681214988231659, 0.39623498916626],
[0.656635999679565, 0.400596976280212],
[0.603900015354156, 0.710216999053955],
[0.81208598613739, 0.588539004325867],
[0.56801301240921, 0.944564998149872],
[0.681007981300354, 0.898285031318665],
[0.733752012252808, 0.869701027870178],
[0.633830010890961, 0.398822009563446],
[0.606792986392975, 0.39553701877594],
[0.589659988880157, 0.391062021255493],
[0.805015981197357, 0.342108011245728],
[0.611334979534149, 0.362284004688263],
[0.634037971496582, 0.355970978736877],
[0.656635999679565, 0.355356991291046],
[0.681214988231659, 0.35834002494812],
[0.698584973812103, 0.363156020641327],
[0.941866993904114, 0.319076001644135],
[0.698584973812103, 0.387449026107788],
[0.584177017211914, 0.624107003211975],
[0.554318010807037, 0.566076993942261],
[0.534153997898102, 0.62064003944397],
[0.711217999458313, 0.819975018501282],
[0.664629995822906, 0.852871000766754],
[0.559099972248077, 0.902631998062134],
[0.871706008911133, 0.791940987110138],
[0.591234028339386, 0.373893976211548],
[0.544341027736664, 0.451583981513977],
[0.624562978744507, 0.924192011356354],
[0.88577002286911, 0.615028977394104],
[0.551338016986847, 0.695277988910675],
[0.551980018615723, 0.704632043838501],
[0.552887976169586, 0.715808033943176],
[0.555167973041534, 0.730794012546539],
[0.569944024085999, 0.767035007476807],
[0.593203008174896, 0.685675978660583],
[0.599261999130249, 0.681069016456604],
[0.607599973678589, 0.677703022956848],
[0.631937980651855, 0.663500010967255],
[0.752032995223999, 0.601315021514893],
[0.547226011753082, 0.420395016670227],
[0.563543975353241, 0.359827995300293],
[0.583841025829315, 0.368713974952698],
[0.586614012718201, 0.692366003990173],
[0.771915018558502, 0.683578014373779],
[0.531597018241882, 0.352482974529266],
[0.588370978832245, 0.804440975189209],
[0.52079701423645, 0.442565023899078],
[0.567984998226166, 0.493479013442993],
[0.543282985687256, 0.819254994392395],
[0.655317008495331, 0.745514988899231],
[0.621008992195129, 0.574018001556396],
[0.625559985637665, 0.78031200170517],
[0.680198013782501, 0.570719003677368],
[0.64276397228241, 0.604337990283966],
[0.704662978649139, 0.621529996395111],
[0.552012026309967, 0.862591981887817],
[0.589071989059448, 0.508637011051178],
[0.685944974422455, 0.775357007980347],
[0.645735025405884, 0.812640011310577],
[0.675342977046967, 0.703978002071381],
[0.810858011245728, 0.646304965019226],
[0.72012197971344, 0.714666962623596],
[0.866151988506317, 0.682704985141754],
[0.663187026977539, 0.644596993923187],
[0.570082008838654, 0.466325998306274],
[0.544561982154846, 0.548375964164734],
[0.562758982181549, 0.558784961700439],
[0.531987011432648, 0.530140042304993],
[0.585271000862122, 0.335177004337311],
[0.622952997684479, 0.32277899980545],
[0.655896008014679, 0.320163011550903],
[0.687132000923157, 0.322345972061157],
[0.716481983661652, 0.333200991153717],
[0.758756995201111, 0.382786989212036],
[0.897013008594513, 0.468769013881683],
[0.732392013072968, 0.424547016620636],
[0.70211398601532, 0.433162987232208],
[0.66652500629425, 0.433866024017334],
[0.633504986763, 0.426087975502014],
[0.603875994682312, 0.416586995124817],
[0.579657971858978, 0.409945011138916],
[0.992439985275269, 0.480777025222778],
[0.567192018032074, 0.569419980049133],
[0.54136598110199, 0.478899002075195],
[0.526564002037048, 0.546118021011353],
[0.523913025856018, 0.563830018043518],
[0.531529009342194, 0.555056989192963],
[0.566035985946655, 0.582329034805298],
[0.51631098985672, 0.563053965568542],
[0.5174720287323, 0.577877044677734],
[0.573594987392426, 0.389806985855103],
[0.560697972774506, 0.395331978797913],
[0.549755990505219, 0.399751007556915],
[0.710287988185883, 0.368252992630005],
[0.723330020904541, 0.363372981548309]
];
var TRI468 = [
127,
34,
139,
11,
0,
37,
232,
231,
120,
72,
37,
39,
128,
121,
47,
232,
121,
128,
104,
69,
67,
175,
171,
148,
157,
154,
155,
118,
50,
101,
73,
39,
40,
9,
151,
108,
48,
115,
131,
194,
204,
211,
74,
40,
185,
80,
42,
183,
40,
92,
186,
230,
229,
118,
202,
212,
214,
83,
18,
17,
76,
61,
146,
160,
29,
30,
56,
157,
173,
106,
204,
194,
135,
214,
192,
203,
165,
98,
21,
71,
68,
51,
45,
4,
144,
24,
23,
77,
146,
91,
205,
50,
187,
201,
200,
18,
91,
106,
182,
90,
91,
181,
85,
84,
17,
206,
203,
36,
148,
171,
140,
92,
40,
39,
193,
189,
244,
159,
158,
28,
247,
246,
161,
236,
3,
196,
54,
68,
104,
193,
168,
8,
117,
228,
31,
189,
193,
55,
98,
97,
99,
126,
47,
100,
166,
79,
218,
155,
154,
26,
209,
49,
131,
135,
136,
150,
47,
126,
217,
223,
52,
53,
45,
51,
134,
211,
170,
140,
67,
69,
108,
43,
106,
91,
230,
119,
120,
226,
130,
247,
63,
53,
52,
238,
20,
242,
46,
70,
156,
78,
62,
96,
46,
53,
63,
143,
34,
227,
173,
155,
133,
123,
117,
111,
44,
125,
19,
236,
134,
51,
216,
206,
205,
154,
153,
22,
39,
37,
167,
200,
201,
208,
36,
142,
100,
57,
212,
202,
20,
60,
99,
28,
158,
157,
35,
226,
113,
160,
159,
27,
204,
202,
210,
113,
225,
46,
43,
202,
204,
62,
76,
77,
137,
123,
116,
41,
38,
72,
203,
129,
142,
64,
98,
240,
49,
102,
64,
41,
73,
74,
212,
216,
207,
42,
74,
184,
169,
170,
211,
170,
149,
176,
105,
66,
69,
122,
6,
168,
123,
147,
187,
96,
77,
90,
65,
55,
107,
89,
90,
180,
101,
100,
120,
63,
105,
104,
93,
137,
227,
15,
86,
85,
129,
102,
49,
14,
87,
86,
55,
8,
9,
100,
47,
121,
145,
23,
22,
88,
89,
179,
6,
122,
196,
88,
95,
96,
138,
172,
136,
215,
58,
172,
115,
48,
219,
42,
80,
81,
195,
3,
51,
43,
146,
61,
171,
175,
199,
81,
82,
38,
53,
46,
225,
144,
163,
110,
246,
33,
7,
52,
65,
66,
229,
228,
117,
34,
127,
234,
107,
108,
69,
109,
108,
151,
48,
64,
235,
62,
78,
191,
129,
209,
126,
111,
35,
143,
163,
161,
246,
117,
123,
50,
222,
65,
52,
19,
125,
141,
221,
55,
65,
3,
195,
197,
25,
7,
33,
220,
237,
44,
70,
71,
139,
122,
193,
245,
247,
130,
33,
71,
21,
162,
153,
158,
159,
170,
169,
150,
188,
174,
196,
216,
186,
92,
144,
160,
161,
2,
97,
167,
141,
125,
241,
164,
167,
37,
72,
38,
12,
145,
159,
160,
38,
82,
13,
63,
68,
71,
226,
35,
111,
158,
153,
154,
101,
50,
205,
206,
92,
165,
209,
198,
217,
165,
167,
97,
220,
115,
218,
133,
112,
243,
239,
238,
241,
214,
135,
169,
190,
173,
133,
171,
208,
32,
125,
44,
237,
86,
87,
178,
85,
86,
179,
84,
85,
180,
83,
84,
181,
201,
83,
182,
137,
93,
132,
76,
62,
183,
61,
76,
184,
57,
61,
185,
212,
57,
186,
214,
207,
187,
34,
143,
156,
79,
239,
237,
123,
137,
177,
44,
1,
4,
201,
194,
32,
64,
102,
129,
213,
215,
138,
59,
166,
219,
242,
99,
97,
2,
94,
141,
75,
59,
235,
24,
110,
228,
25,
130,
226,
23,
24,
229,
22,
23,
230,
26,
22,
231,
112,
26,
232,
189,
190,
243,
221,
56,
190,
28,
56,
221,
27,
28,
222,
29,
27,
223,
30,
29,
224,
247,
30,
225,
238,
79,
20,
166,
59,
75,
60,
75,
240,
147,
177,
215,
20,
79,
166,
187,
147,
213,
112,
233,
244,
233,
128,
245,
128,
114,
188,
114,
217,
174,
131,
115,
220,
217,
198,
236,
198,
131,
134,
177,
132,
58,
143,
35,
124,
110,
163,
7,
228,
110,
25,
356,
389,
368,
11,
302,
267,
452,
350,
349,
302,
303,
269,
357,
343,
277,
452,
453,
357,
333,
332,
297,
175,
152,
377,
384,
398,
382,
347,
348,
330,
303,
304,
270,
9,
336,
337,
278,
279,
360,
418,
262,
431,
304,
408,
409,
310,
415,
407,
270,
409,
410,
450,
348,
347,
422,
430,
434,
313,
314,
17,
306,
307,
375,
387,
388,
260,
286,
414,
398,
335,
406,
418,
364,
367,
416,
423,
358,
327,
251,
284,
298,
281,
5,
4,
373,
374,
253,
307,
320,
321,
425,
427,
411,
421,
313,
18,
321,
405,
406,
320,
404,
405,
315,
16,
17,
426,
425,
266,
377,
400,
369,
322,
391,
269,
417,
465,
464,
386,
257,
258,
466,
260,
388,
456,
399,
419,
284,
332,
333,
417,
285,
8,
346,
340,
261,
413,
441,
285,
327,
460,
328,
355,
371,
329,
392,
439,
438,
382,
341,
256,
429,
420,
360,
364,
394,
379,
277,
343,
437,
443,
444,
283,
275,
440,
363,
431,
262,
369,
297,
338,
337,
273,
375,
321,
450,
451,
349,
446,
342,
467,
293,
334,
282,
458,
461,
462,
276,
353,
383,
308,
324,
325,
276,
300,
293,
372,
345,
447,
382,
398,
362,
352,
345,
340,
274,
1,
19,
456,
248,
281,
436,
427,
425,
381,
256,
252,
269,
391,
393,
200,
199,
428,
266,
330,
329,
287,
273,
422,
250,
462,
328,
258,
286,
384,
265,
353,
342,
387,
259,
257,
424,
431,
430,
342,
353,
276,
273,
335,
424,
292,
325,
307,
366,
447,
345,
271,
303,
302,
423,
266,
371,
294,
455,
460,
279,
278,
294,
271,
272,
304,
432,
434,
427,
272,
407,
408,
394,
430,
431,
395,
369,
400,
334,
333,
299,
351,
417,
168,
352,
280,
411,
325,
319,
320,
295,
296,
336,
319,
403,
404,
330,
348,
349,
293,
298,
333,
323,
454,
447,
15,
16,
315,
358,
429,
279,
14,
15,
316,
285,
336,
9,
329,
349,
350,
374,
380,
252,
318,
402,
403,
6,
197,
419,
318,
319,
325,
367,
364,
365,
435,
367,
397,
344,
438,
439,
272,
271,
311,
195,
5,
281,
273,
287,
291,
396,
428,
199,
311,
271,
268,
283,
444,
445,
373,
254,
339,
263,
466,
249,
282,
334,
296,
449,
347,
346,
264,
447,
454,
336,
296,
299,
338,
10,
151,
278,
439,
455,
292,
407,
415,
358,
371,
355,
340,
345,
372,
390,
249,
466,
346,
347,
280,
442,
443,
282,
19,
94,
370,
441,
442,
295,
248,
419,
197,
263,
255,
359,
440,
275,
274,
300,
383,
368,
351,
412,
465,
263,
467,
466,
301,
368,
389,
380,
374,
386,
395,
378,
379,
412,
351,
419,
436,
426,
322,
373,
390,
388,
2,
164,
393,
370,
462,
461,
164,
0,
267,
302,
11,
12,
374,
373,
387,
268,
12,
13,
293,
300,
301,
446,
261,
340,
385,
384,
381,
330,
266,
425,
426,
423,
391,
429,
355,
437,
391,
327,
326,
440,
457,
438,
341,
382,
362,
459,
457,
461,
434,
430,
394,
414,
463,
362,
396,
369,
262,
354,
461,
457,
316,
403,
402,
315,
404,
403,
314,
405,
404,
313,
406,
405,
421,
418,
406,
366,
401,
361,
306,
408,
407,
291,
409,
408,
287,
410,
409,
432,
436,
410,
434,
416,
411,
264,
368,
383,
309,
438,
457,
352,
376,
401,
274,
275,
4,
421,
428,
262,
294,
327,
358,
433,
416,
367,
289,
455,
439,
462,
370,
326,
2,
326,
370,
305,
460,
455,
254,
449,
448,
255,
261,
446,
253,
450,
449,
252,
451,
450,
256,
452,
451,
341,
453,
452,
413,
464,
463,
441,
413,
414,
258,
442,
441,
257,
443,
442,
259,
444,
443,
260,
445,
444,
467,
342,
445,
459,
458,
250,
289,
392,
290,
290,
328,
460,
376,
433,
435,
250,
290,
392,
411,
416,
433,
341,
463,
464,
453,
464,
465,
357,
465,
412,
343,
412,
399,
360,
363,
440,
437,
399,
456,
420,
456,
363,
401,
435,
288,
372,
383,
353,
339,
255,
249,
448,
261,
255,
133,
243,
190,
133,
155,
112,
33,
246,
247,
33,
130,
25,
398,
384,
286,
362,
398,
414,
362,
463,
341,
263,
359,
467,
263,
249,
255,
466,
467,
260,
75,
60,
166,
238,
239,
79,
162,
127,
139,
72,
11,
37,
121,
232,
120,
73,
72,
39,
114,
128,
47,
233,
232,
128,
103,
104,
67,
152,
175,
148,
173,
157,
155,
119,
118,
101,
74,
73,
40,
107,
9,
108,
49,
48,
131,
32,
194,
211,
184,
74,
185,
191,
80,
183,
185,
40,
186,
119,
230,
118,
210,
202,
214,
84,
83,
17,
77,
76,
146,
161,
160,
30,
190,
56,
173,
182,
106,
194,
138,
135,
192,
129,
203,
98,
54,
21,
68,
5,
51,
4,
145,
144,
23,
90,
77,
91,
207,
205,
187,
83,
201,
18,
181,
91,
182,
180,
90,
181,
16,
85,
17,
205,
206,
36,
176,
148,
140,
165,
92,
39,
245,
193,
244,
27,
159,
28,
30,
247,
161,
174,
236,
196,
103,
54,
104,
55,
193,
8,
111,
117,
31,
221,
189,
55,
240,
98,
99,
142,
126,
100,
219,
166,
218,
112,
155,
26,
198,
209,
131,
169,
135,
150,
114,
47,
217,
224,
223,
53,
220,
45,
134,
32,
211,
140,
109,
67,
108,
146,
43,
91,
231,
230,
120,
113,
226,
247,
105,
63,
52,
241,
238,
242,
124,
46,
156,
95,
78,
96,
70,
46,
63,
116,
143,
227,
116,
123,
111,
1,
44,
19,
3,
236,
51,
207,
216,
205,
26,
154,
22,
165,
39,
167,
199,
200,
208,
101,
36,
100,
43,
57,
202,
242,
20,
99,
56,
28,
157,
124,
35,
113,
29,
160,
27,
211,
204,
210,
124,
113,
46,
106,
43,
204,
96,
62,
77,
227,
137,
116,
73,
41,
72,
36,
203,
142,
235,
64,
240,
48,
49,
64,
42,
41,
74,
214,
212,
207,
183,
42,
184,
210,
169,
211,
140,
170,
176,
104,
105,
69,
193,
122,
168,
50,
123,
187,
89,
96,
90,
66,
65,
107,
179,
89,
180,
119,
101,
120,
68,
63,
104,
234,
93,
227,
16,
15,
85,
209,
129,
49,
15,
14,
86,
107,
55,
9,
120,
100,
121,
153,
145,
22,
178,
88,
179,
197,
6,
196,
89,
88,
96,
135,
138,
136,
138,
215,
172,
218,
115,
219,
41,
42,
81,
5,
195,
51,
57,
43,
61,
208,
171,
199,
41,
81,
38,
224,
53,
225,
24,
144,
110,
105,
52,
66,
118,
229,
117,
227,
34,
234,
66,
107,
69,
10,
109,
151,
219,
48,
235,
183,
62,
191,
142,
129,
126,
116,
111,
143,
7,
163,
246,
118,
117,
50,
223,
222,
52,
94,
19,
141,
222,
221,
65,
196,
3,
197,
45,
220,
44,
156,
70,
139,
188,
122,
245,
139,
71,
162,
145,
153,
159,
149,
170,
150,
122,
188,
196,
206,
216,
92,
163,
144,
161,
164,
2,
167,
242,
141,
241,
0,
164,
37,
11,
72,
12,
144,
145,
160,
12,
38,
13,
70,
63,
71,
31,
226,
111,
157,
158,
154,
36,
101,
205,
203,
206,
165,
126,
209,
217,
98,
165,
97,
237,
220,
218,
237,
239,
241,
210,
214,
169,
140,
171,
32,
241,
125,
237,
179,
86,
178,
180,
85,
179,
181,
84,
180,
182,
83,
181,
194,
201,
182,
177,
137,
132,
184,
76,
183,
185,
61,
184,
186,
57,
185,
216,
212,
186,
192,
214,
187,
139,
34,
156,
218,
79,
237,
147,
123,
177,
45,
44,
4,
208,
201,
32,
98,
64,
129,
192,
213,
138,
235,
59,
219,
141,
242,
97,
97,
2,
141,
240,
75,
235,
229,
24,
228,
31,
25,
226,
230,
23,
229,
231,
22,
230,
232,
26,
231,
233,
112,
232,
244,
189,
243,
189,
221,
190,
222,
28,
221,
223,
27,
222,
224,
29,
223,
225,
30,
224,
113,
247,
225,
99,
60,
240,
213,
147,
215,
60,
20,
166,
192,
187,
213,
243,
112,
244,
244,
233,
245,
245,
128,
188,
188,
114,
174,
134,
131,
220,
174,
217,
236,
236,
198,
134,
215,
177,
58,
156,
143,
124,
25,
110,
7,
31,
228,
25,
264,
356,
368,
0,
11,
267,
451,
452,
349,
267,
302,
269,
350,
357,
277,
350,
452,
357,
299,
333,
297,
396,
175,
377,
381,
384,
382,
280,
347,
330,
269,
303,
270,
151,
9,
337,
344,
278,
360,
424,
418,
431,
270,
304,
409,
272,
310,
407,
322,
270,
410,
449,
450,
347,
432,
422,
434,
18,
313,
17,
291,
306,
375,
259,
387,
260,
424,
335,
418,
434,
364,
416,
391,
423,
327,
301,
251,
298,
275,
281,
4,
254,
373,
253,
375,
307,
321,
280,
425,
411,
200,
421,
18,
335,
321,
406,
321,
320,
405,
314,
315,
17,
423,
426,
266,
396,
377,
369,
270,
322,
269,
413,
417,
464,
385,
386,
258,
248,
456,
419,
298,
284,
333,
168,
417,
8,
448,
346,
261,
417,
413,
285,
326,
327,
328,
277,
355,
329,
309,
392,
438,
381,
382,
256,
279,
429,
360,
365,
364,
379,
355,
277,
437,
282,
443,
283,
281,
275,
363,
395,
431,
369,
299,
297,
337,
335,
273,
321,
348,
450,
349,
359,
446,
467,
283,
293,
282,
250,
458,
462,
300,
276,
383,
292,
308,
325,
283,
276,
293,
264,
372,
447,
346,
352,
340,
354,
274,
19,
363,
456,
281,
426,
436,
425,
380,
381,
252,
267,
269,
393,
421,
200,
428,
371,
266,
329,
432,
287,
422,
290,
250,
328,
385,
258,
384,
446,
265,
342,
386,
387,
257,
422,
424,
430,
445,
342,
276,
422,
273,
424,
306,
292,
307,
352,
366,
345,
268,
271,
302,
358,
423,
371,
327,
294,
460,
331,
279,
294,
303,
271,
304,
436,
432,
427,
304,
272,
408,
395,
394,
431,
378,
395,
400,
296,
334,
299,
6,
351,
168,
376,
352,
411,
307,
325,
320,
285,
295,
336,
320,
319,
404,
329,
330,
349,
334,
293,
333,
366,
323,
447,
316,
15,
315,
331,
358,
279,
317,
14,
316,
8,
285,
9,
277,
329,
350,
253,
374,
252,
319,
318,
403,
351,
6,
419,
324,
318,
325,
397,
367,
365,
288,
435,
397,
278,
344,
439,
310,
272,
311,
248,
195,
281,
375,
273,
291,
175,
396,
199,
312,
311,
268,
276,
283,
445,
390,
373,
339,
295,
282,
296,
448,
449,
346,
356,
264,
454,
337,
336,
299,
337,
338,
151,
294,
278,
455,
308,
292,
415,
429,
358,
355,
265,
340,
372,
388,
390,
466,
352,
346,
280,
295,
442,
282,
354,
19,
370,
285,
441,
295,
195,
248,
197,
457,
440,
274,
301,
300,
368,
417,
351,
465,
251,
301,
389,
385,
380,
386,
394,
395,
379,
399,
412,
419,
410,
436,
322,
387,
373,
388,
326,
2,
393,
354,
370,
461,
393,
164,
267,
268,
302,
12,
386,
374,
387,
312,
268,
13,
298,
293,
301,
265,
446,
340,
380,
385,
381,
280,
330,
425,
322,
426,
391,
420,
429,
437,
393,
391,
326,
344,
440,
438,
458,
459,
461,
364,
434,
394,
428,
396,
262,
274,
354,
457,
317,
316,
402,
316,
315,
403,
315,
314,
404,
314,
313,
405,
313,
421,
406,
323,
366,
361,
292,
306,
407,
306,
291,
408,
291,
287,
409,
287,
432,
410,
427,
434,
411,
372,
264,
383,
459,
309,
457,
366,
352,
401,
1,
274,
4,
418,
421,
262,
331,
294,
358,
435,
433,
367,
392,
289,
439,
328,
462,
326,
94,
2,
370,
289,
305,
455,
339,
254,
448,
359,
255,
446,
254,
253,
449,
253,
252,
450,
252,
256,
451,
256,
341,
452,
414,
413,
463,
286,
441,
414,
286,
258,
441,
258,
257,
442,
257,
259,
443,
259,
260,
444,
260,
467,
445,
309,
459,
250,
305,
289,
290,
305,
290,
460,
401,
376,
435,
309,
250,
392,
376,
411,
433,
453,
341,
464,
357,
453,
465,
343,
357,
412,
437,
343,
399,
344,
360,
440,
420,
437,
456,
360,
420,
363,
361,
401,
288,
265,
372,
353,
390,
339,
249,
339,
448,
255
];
var VTX68 = [
127,
234,
132,
58,
172,
150,
149,
148,
152,
377,
378,
379,
397,
288,
361,
454,
356,
70,
63,
105,
66,
107,
336,
296,
334,
293,
300,
168,
6,
195,
4,
98,
97,
2,
326,
327,
33,
160,
158,
133,
153,
144,
362,
385,
387,
263,
373,
380,
57,
40,
37,
0,
267,
270,
287,
321,
314,
17,
84,
91,
78,
81,
13,
311,
308,
402,
14,
178
];
var VTX33 = [33, 133, 362, 263, 1, 62, 308, 159, 145, 386, 374, 6, 102, 331, 2, 13, 14, 70, 105, 107, 336, 334, 300, 54, 10, 284, 50, 280, 234, 454, 58, 288, 152];
var VTX7 = [33, 133, 362, 263, 1, 78, 308];
var UV68 = VTX68.map((x) => UV468[x]);
var UV33 = VTX33.map((x) => UV468[x]);
var UV7 = VTX7.map((x) => UV468[x]);
// src/face/facemeshutil.ts
var createBox = (startEndTensor) => ({ startPoint: Oe(startEndTensor, [0, 0], [-1, 2]), endPoint: Oe(startEndTensor, [0, 2], [-1, 2]) });
var getBoxSize = (box4) => [Math.abs(box4.endPoint[0] - box4.startPoint[0]), Math.abs(box4.endPoint[1] - box4.startPoint[1])];
var getBoxCenter = (box4) => [box4.startPoint[0] + (box4.endPoint[0] - box4.startPoint[0]) / 2, box4.startPoint[1] + (box4.endPoint[1] - box4.startPoint[1]) / 2];
var getClampedBox = (box4, input) => box4 ? [
Math.trunc(Math.max(0, box4.startPoint[0])),
Math.trunc(Math.max(0, box4.startPoint[1])),
Math.trunc(Math.min(input.shape[2] || 0, box4.endPoint[0]) - Math.max(0, box4.startPoint[0])),
Math.trunc(Math.min(input.shape[1] || 0, box4.endPoint[1]) - Math.max(0, box4.startPoint[1]))
] : [0, 0, 0, 0];
var getRawBox = (box4, input) => box4 ? [
box4.startPoint[0] / (input.shape[2] || 0),
box4.startPoint[1] / (input.shape[1] || 0),
(box4.endPoint[0] - box4.startPoint[0]) / (input.shape[2] || 0),
(box4.endPoint[1] - box4.startPoint[1]) / (input.shape[1] || 0)
] : [0, 0, 0, 0];
var scaleBoxCoordinates = (box4, factor) => {
const startPoint = [box4.startPoint[0] * factor[0], box4.startPoint[1] * factor[1]];
const endPoint = [box4.endPoint[0] * factor[0], box4.endPoint[1] * factor[1]];
return { startPoint, endPoint };
};
var cutBoxFromImageAndResize = (box4, image6, cropSize) => {
const h = image6.shape[1];
const w = image6.shape[2];
return Cn.cropAndResize(image6, [[box4.startPoint[1] / h, box4.startPoint[0] / w, box4.endPoint[1] / h, box4.endPoint[0] / w]], [0], cropSize);
};
var enlargeBox = (box4, factor = 1.5) => {
const center = getBoxCenter(box4);
const size2 = getBoxSize(box4);
const halfSize = [factor * size2[0] / 2, factor * size2[1] / 2];
return { startPoint: [center[0] - halfSize[0], center[1] - halfSize[1]], endPoint: [center[0] + halfSize[0], center[1] + halfSize[1]], landmarks: box4.landmarks };
};
var squarifyBox = (box4) => {
const centers = getBoxCenter(box4);
const size2 = getBoxSize(box4);
const halfSize = Math.max(...size2) / 2;
return { startPoint: [Math.round(centers[0] - halfSize), Math.round(centers[1] - halfSize)], endPoint: [Math.round(centers[0] + halfSize), Math.round(centers[1] + halfSize)], landmarks: box4.landmarks };
};
var calculateLandmarksBoundingBox = (landmarks) => {
const xs2 = landmarks.map((d) => d[0]);
const ys2 = landmarks.map((d) => d[1]);
return { startPoint: [Math.min(...xs2), Math.min(...ys2)], endPoint: [Math.max(...xs2), Math.max(...ys2)], landmarks };
};
var IDENTITY_MATRIX = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
var normalizeRadians = (angle) => angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));
var computeRotation = (point1, point2) => normalizeRadians(Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]));
var buildTranslationMatrix = (x, y) => [[1, 0, x], [0, 1, y], [0, 0, 1]];
var dot = (v12, v22) => {
let product = 0;
for (let i = 0; i < v12.length; i++)
product += v12[i] * v22[i];
return product;
};
var getColumnFrom2DArr = (arr, columnIndex) => {
const column = [];
for (let i = 0; i < arr.length; i++)
column.push(arr[i][columnIndex]);
return column;
};
var multiplyTransformMatrices = (mat1, mat2) => {
const product = [];
const size2 = mat1.length;
for (let row = 0; row < size2; row++) {
product.push([]);
for (let col = 0; col < size2; col++)
product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));
}
return product;
};
var buildRotationMatrix = (rotation, center) => {
const cosA = Math.cos(rotation);
const sinA = Math.sin(rotation);
const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];
const translationMatrix = buildTranslationMatrix(center[0], center[1]);
const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);
const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);
return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);
};
var invertTransformMatrix = (matrix) => {
const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];
const translationComponent = [matrix[0][2], matrix[1][2]];
const invertedTranslation = [-dot(rotationComponent[0], translationComponent), -dot(rotationComponent[1], translationComponent)];
return [rotationComponent[0].concat(invertedTranslation[0]), rotationComponent[1].concat(invertedTranslation[1]), [0, 0, 1]];
};
var rotatePoint = (homogeneousCoordinate, rotationMatrix) => [dot(homogeneousCoordinate, rotationMatrix[0]), dot(homogeneousCoordinate, rotationMatrix[1])];
function generateAnchors(inputSize8) {
const spec = { strides: [inputSize8 / 16, inputSize8 / 8], anchors: [2, 6] };
const anchors4 = [];
for (let i = 0; i < spec.strides.length; i++) {
const stride = spec.strides[i];
const gridRows = Math.floor((inputSize8 + stride - 1) / stride);
const gridCols = Math.floor((inputSize8 + stride - 1) / stride);
const anchorsNum = spec.anchors[i];
for (let gridY = 0; gridY < gridRows; gridY++) {
const anchorY = stride * (gridY + 0.5);
for (let gridX = 0; gridX < gridCols; gridX++) {
const anchorX = stride * (gridX + 0.5);
for (let n = 0; n < anchorsNum; n++)
anchors4.push([anchorX, anchorY]);
}
}
}
return anchors4;
}
function transformRawCoords(rawCoords, box4, angle, rotationMatrix, inputSize8) {
const boxSize = getBoxSize({ startPoint: box4.startPoint, endPoint: box4.endPoint });
const coordsScaled = rawCoords.map((coord) => [
boxSize[0] / inputSize8 * (coord[0] - inputSize8 / 2),
boxSize[1] / inputSize8 * (coord[1] - inputSize8 / 2),
coord[2] || 0
]);
const coordsRotationMatrix = angle !== 0 ? buildRotationMatrix(angle, [0, 0]) : IDENTITY_MATRIX;
const coordsRotated = angle !== 0 ? coordsScaled.map((coord) => [...rotatePoint(coord, coordsRotationMatrix), coord[2]]) : coordsScaled;
const inverseRotationMatrix = angle !== 0 ? invertTransformMatrix(rotationMatrix) : IDENTITY_MATRIX;
const boxCenter = [...getBoxCenter({ startPoint: box4.startPoint, endPoint: box4.endPoint }), 1];
return coordsRotated.map((coord) => [
Math.round(coord[0] + dot(boxCenter, inverseRotationMatrix[0])),
Math.round(coord[1] + dot(boxCenter, inverseRotationMatrix[1])),
Math.round(coord[2] || 0)
]);
}
function correctFaceRotation(box4, input, inputSize8) {
const symmetryLine = box4.landmarks.length >= meshLandmarks.count ? meshLandmarks.symmetryLine : blazeFaceLandmarks.symmetryLine;
const angle = computeRotation(box4.landmarks[symmetryLine[0]], box4.landmarks[symmetryLine[1]]);
const faceCenter = getBoxCenter({ startPoint: box4.startPoint, endPoint: box4.endPoint });
const faceCenterNormalized = [faceCenter[0] / input.shape[2], faceCenter[1] / input.shape[1]];
const rotated = Cn.rotateWithOffset(input, angle, 0, faceCenterNormalized);
const rotationMatrix = buildRotationMatrix(-angle, faceCenter);
const cut = cutBoxFromImageAndResize({ startPoint: box4.startPoint, endPoint: box4.endPoint }, rotated, [inputSize8, inputSize8]);
const face5 = ce(cut, 255);
De(cut);
De(rotated);
return [angle, rotationMatrix, face5];
}
// src/face/blazeface.ts
var keypointsCount = 6;
var model3;
var anchorsData = [];
var anchors = null;
var inputSize = 0;
var size = () => inputSize;
async function load3(config3) {
var _a2, _b;
if (env.initial)
model3 = null;
if (!model3) {
model3 = await m7(join(config3.modelBasePath, ((_a2 = config3.face.detector) == null ? void 0 : _a2.modelPath) || ""));
if (!model3 || !model3["modelUrl"])
log("load model failed:", (_b = config3.face.detector) == null ? void 0 : _b.modelPath);
else if (config3.debug)
log("load model:", model3["modelUrl"]);
} else if (config3.debug)
log("cached model:", model3["modelUrl"]);
inputSize = model3.inputs[0].shape ? model3.inputs[0].shape[2] : 0;
if (inputSize === -1)
inputSize = 64;
anchorsData = generateAnchors(inputSize);
anchors = ki(anchorsData);
return model3;
}
function decodeBounds(boxOutputs) {
const boxStarts = Oe(boxOutputs, [0, 1], [-1, 2]);
const centers = Z(boxStarts, anchors);
const boxSizes = Oe(boxOutputs, [0, 3], [-1, 2]);
const boxSizesNormalized = ce(boxSizes, inputSize);
const centersNormalized = ce(centers, inputSize);
const halfBoxSize = ce(boxSizesNormalized, 2);
const starts = le(centersNormalized, halfBoxSize);
const ends = Z(centersNormalized, halfBoxSize);
const startNormalized = O(starts, inputSize);
const endNormalized = O(ends, inputSize);
const concatAxis = 1;
return W_([startNormalized, endNormalized], concatAxis);
}
async function getBoxes(inputImage, config3) {
var _a2, _b, _c2, _d2;
if (!inputImage || inputImage["isDisposedInternal"] || inputImage.shape.length !== 4 || inputImage.shape[1] < 1 || inputImage.shape[2] < 1)
return { boxes: [] };
const [batch, boxes, scores] = V(() => {
const resizedImage = Cn.resizeBilinear(inputImage, [inputSize, inputSize]);
const normalizedImage = le(ce(resizedImage, 127.5), 0.5);
const res = model3 == null ? void 0 : model3.execute(normalizedImage);
let batchOut;
if (Array.isArray(res)) {
const sorted = res.sort((a, b10) => a.size - b10.size);
const concat384 = tt([sorted[0], sorted[2]], 2);
const concat512 = tt([sorted[1], sorted[3]], 2);
const concat = tt([concat512, concat384], 1);
batchOut = Br(concat, 0);
} else {
batchOut = Br(res);
}
const boxesOut = decodeBounds(batchOut);
const logits = Oe(batchOut, [0, 0], [-1, 1]);
const scoresOut = Br(zr(logits));
return [batchOut, boxesOut, scoresOut];
});
const nmsTensor = await Cn.nonMaxSuppressionAsync(boxes, scores, ((_a2 = config3.face.detector) == null ? void 0 : _a2.maxDetected) || 0, ((_b = config3.face.detector) == null ? void 0 : _b.iouThreshold) || 0, ((_c2 = config3.face.detector) == null ? void 0 : _c2.minConfidence) || 0);
const nms = await nmsTensor.array();
De(nmsTensor);
const annotatedBoxes = [];
const scoresData = await scores.data();
for (let i = 0; i < nms.length; i++) {
const confidence = scoresData[nms[i]];
if (confidence > (((_d2 = config3.face.detector) == null ? void 0 : _d2.minConfidence) || 0)) {
const boundingBox = Oe(boxes, [nms[i], 0], [1, -1]);
const landmarks = V(() => F(Br(Oe(batch, [nms[i], keypointsCount - 1], [1, -1])), [keypointsCount, -1]));
annotatedBoxes.push({ box: createBox(boundingBox), landmarks, anchor: anchorsData[nms[i]], confidence });
De(boundingBox);
}
}
De(batch);
De(boxes);
De(scores);
return {
boxes: annotatedBoxes,
scaleFactor: [inputImage.shape[2] / inputSize, inputImage.shape[1] / inputSize]
};
}
// src/body/blazeposecoords.ts
var blazeposecoords_exports = {};
__export(blazeposecoords_exports, {
connected: () => connected,
kpt: () => kpt
});
var kpt = [
"nose",
"leftEyeInside",
"leftEye",
"leftEyeOutside",
"rightEyeInside",
"rightEye",
"rightEyeOutside",
"leftEar",
"rightEar",
"leftMouth",
"rightMouth",
"leftShoulder",
"rightShoulder",
"leftElbow",
"rightElbow",
"leftWrist",
"rightWrist",
"leftPalm",
"rightPalm",
"leftIndex",
"rightIndex",
"leftPinky",
"rightPinky",
"leftHip",
"rightHip",
"leftKnee",
"rightKnee",
"leftAnkle",
"rightAnkle",
"leftHeel",
"rightHeel",
"leftFoot",
"rightFoot",
"bodyCenter",
"bodyTop",
"leftThumb",
"leftHand",
"rightThumb",
"rightHand"
];
var connected = {
leftLeg: ["leftHip", "leftKnee", "leftAnkle", "leftHeel", "leftFoot"],
rightLeg: ["rightHip", "rightKnee", "rightAnkle", "rightHeel", "rightFoot"],
torso: ["leftShoulder", "rightShoulder", "rightHip", "leftHip", "leftShoulder"],
leftArm: ["leftShoulder", "leftElbow", "leftWrist", "leftPalm"],
rightArm: ["rightShoulder", "rightElbow", "rightWrist", "rightPalm"],
leftHand: [],
rightHand: [],
head: []
};
// src/body/blazepose.ts
var env2 = { initial: true };
var models = [null, null];
var inputSize2 = [[0, 0], [0, 0]];
var skipped3 = Number.MAX_SAFE_INTEGER;
var outputNodes;
var cache = null;
var padding = [[0, 0], [0, 0], [0, 0], [0, 0]];
var last2 = 0;
async function loadDetect(config3) {
var _a2, _b, _c2;
if (env2.initial)
models[0] = null;
if (!models[0] && ((_a2 = config3.body.detector) == null ? void 0 : _a2.modelPath) || "") {
models[0] = await m7(join(config3.modelBasePath, ((_b = config3.body.detector) == null ? void 0 : _b.modelPath) || ""));
const inputs = Object.values(models[0].modelSignature["inputs"]);
inputSize2[0][0] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[1].size) : 0;
inputSize2[0][1] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
if (!models[0] || !models[0]["modelUrl"])
log("load model failed:", (_c2 = config3.body.detector) == null ? void 0 : _c2.modelPath);
else if (config3.debug)
log("load model:", models[0]["modelUrl"]);
} else if (config3.debug && models[0])
log("cached model:", models[0]["modelUrl"]);
return models[0];
}
async function loadPose(config3) {
var _a2;
if (env2.initial)
models[1] = null;
if (!models[1]) {
models[1] = await m7(join(config3.modelBasePath, config3.body.modelPath || ""));
const inputs = Object.values(models[1].modelSignature["inputs"]);
inputSize2[1][0] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[1].size) : 0;
inputSize2[1][1] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
if ((_a2 = config3.body.modelPath) == null ? void 0 : _a2.includes("lite"))
outputNodes = ["ld_3d", "output_segmentation", "output_heatmap", "world_3d", "output_poseflag"];
else
outputNodes = ["Identity", "Identity_2", "Identity_3", "Identity_4", "Identity_1"];
if (!models[1] || !models[1]["modelUrl"])
log("load model failed:", config3.body.modelPath);
else if (config3.debug)
log("load model:", models[1]["modelUrl"]);
} else if (config3.debug)
log("cached model:", models[1]["modelUrl"]);
return models[1];
}
function calculateBoxes(keypoints, outputSize2) {
const x = keypoints.map((a) => a.position[0]);
const y = keypoints.map((a) => a.position[1]);
const keypointsBox = [Math.min(...x), Math.min(...y), Math.max(...x) - Math.min(...x), Math.max(...y) - Math.min(...y)];
const keypointsBoxRaw = [keypointsBox[0] / outputSize2[0], keypointsBox[1] / outputSize2[1], keypointsBox[2] / outputSize2[0], keypointsBox[3] / outputSize2[1]];
return { keypointsBox, keypointsBoxRaw };
}
async function prepareImage(input) {
const t = {};
if (!input.shape || !input.shape[1] || !input.shape[2])
return input;
padding = [
[0, 0],
[input.shape[2] > input.shape[1] ? Math.trunc((input.shape[2] - input.shape[1]) / 2) : 0, input.shape[2] > input.shape[1] ? Math.trunc((input.shape[2] - input.shape[1]) / 2) : 0],
[input.shape[1] > input.shape[2] ? Math.trunc((input.shape[1] - input.shape[2]) / 2) : 0, input.shape[1] > input.shape[2] ? Math.trunc((input.shape[1] - input.shape[2]) / 2) : 0],
[0, 0]
];
t.pad = jr(input, padding);
t.resize = Cn.resizeBilinear(t.pad, [inputSize2[1][0], inputSize2[1][1]]);
const final = ce(t.resize, 255);
Object.keys(t).forEach((tensor) => De(t[tensor]));
return final;
}
function rescaleKeypoints(keypoints, outputSize2) {
for (const kpt4 of keypoints) {
kpt4.position = [
kpt4.position[0] * (outputSize2[0] + padding[2][0] + padding[2][1]) / outputSize2[0] - padding[2][0],
kpt4.position[1] * (outputSize2[1] + padding[1][0] + padding[1][1]) / outputSize2[1] - padding[1][0],
kpt4.position[2]
];
kpt4.positionRaw = [
kpt4.position[0] / outputSize2[0],
kpt4.position[1] / outputSize2[1],
kpt4.position[2]
];
}
return keypoints;
}
var sigmoid = (x) => 1 - 1 / (1 + Math.exp(x));
async function detectParts(input, config3, outputSize2) {
var _a2;
const t = {};
t.input = await prepareImage(input);
[t.ld, t.segmentation, t.heatmap, t.world, t.poseflag] = await ((_a2 = models[1]) == null ? void 0 : _a2.execute(t.input, outputNodes));
const poseScoreRaw = (await t.poseflag.data())[0];
const poseScore = Math.max(0, (poseScoreRaw - 0.8) / (1 - 0.8));
const points = await t.ld.data();
const keypointsRelative = [];
const depth = 5;
for (let i = 0; i < points.length / depth; i++) {
const score = sigmoid(points[depth * i + 3]);
const presence = sigmoid(points[depth * i + 4]);
const adjScore = Math.trunc(100 * score * presence * poseScore) / 100;
const positionRaw = [points[depth * i + 0] / inputSize2[1][0], points[depth * i + 1] / inputSize2[1][1], points[depth * i + 2] + 0];
const position = [Math.trunc(outputSize2[0] * positionRaw[0]), Math.trunc(outputSize2[1] * positionRaw[1]), positionRaw[2]];
keypointsRelative.push({ part: kpt[i], positionRaw, position, score: adjScore });
}
if (poseScore < (config3.body.minConfidence || 0))
return null;
const keypoints = rescaleKeypoints(keypointsRelative, outputSize2);
const boxes = calculateBoxes(keypoints, [outputSize2[0], outputSize2[1]]);
Object.keys(t).forEach((tensor) => De(t[tensor]));
const annotations2 = {};
for (const [name, indexes] of Object.entries(connected)) {
const pt = [];
for (let i = 0; i < indexes.length - 1; i++) {
const pt0 = keypoints.find((kpt4) => kpt4.part === indexes[i]);
const pt1 = keypoints.find((kpt4) => kpt4.part === indexes[i + 1]);
if (pt0 && pt1 && pt0.score > (config3.body.minConfidence || 0) && pt1.score > (config3.body.minConfidence || 0))
pt.push([pt0.position, pt1.position]);
}
annotations2[name] = pt;
}
const body4 = { id: 0, score: Math.trunc(100 * poseScore) / 100, box: boxes.keypointsBox, boxRaw: boxes.keypointsBoxRaw, keypoints, annotations: annotations2 };
return body4;
}
async function predict2(input, config3) {
const outputSize2 = [input.shape[2] || 0, input.shape[1] || 0];
if (skipped3 < (config3.body.skipFrames || 0) && (config3.body.skipTime || 0) <= now() - last2 && config3.skipFrame && cache !== null) {
skipped3++;
} else {
cache = await detectParts(input, config3, outputSize2);
last2 = now();
skipped3 = 0;
}
if (cache)
return [cache];
return [];
}
// src/object/labels.ts
var labels = [
{ class: 1, label: "person" },
{ class: 2, label: "bicycle" },
{ class: 3, label: "car" },
{ class: 4, label: "motorcycle" },
{ class: 5, label: "airplane" },
{ class: 6, label: "bus" },
{ class: 7, label: "train" },
{ class: 8, label: "truck" },
{ class: 9, label: "boat" },
{ class: 10, label: "traffic light" },
{ class: 11, label: "fire hydrant" },
{ class: 12, label: "stop sign" },
{ class: 13, label: "parking meter" },
{ class: 14, label: "bench" },
{ class: 15, label: "bird" },
{ class: 16, label: "cat" },
{ class: 17, label: "dog" },
{ class: 18, label: "horse" },
{ class: 19, label: "sheep" },
{ class: 20, label: "cow" },
{ class: 21, label: "elephant" },
{ class: 22, label: "bear" },
{ class: 23, label: "zebra" },
{ class: 24, label: "giraffe" },
{ class: 25, label: "backpack" },
{ class: 26, label: "umbrella" },
{ class: 27, label: "handbag" },
{ class: 28, label: "tie" },
{ class: 29, label: "suitcase" },
{ class: 30, label: "frisbee" },
{ class: 31, label: "skis" },
{ class: 32, label: "snowboard" },
{ class: 33, label: "sports ball" },
{ class: 34, label: "kite" },
{ class: 35, label: "baseball bat" },
{ class: 36, label: "baseball glove" },
{ class: 37, label: "skateboard" },
{ class: 38, label: "surfboard" },
{ class: 39, label: "tennis racket" },
{ class: 40, label: "bottle" },
{ class: 41, label: "wine glass" },
{ class: 42, label: "cup" },
{ class: 43, label: "fork" },
{ class: 44, label: "knife" },
{ class: 45, label: "spoon" },
{ class: 46, label: "bowl" },
{ class: 47, label: "banana" },
{ class: 48, label: "apple" },
{ class: 49, label: "sandwich" },
{ class: 50, label: "orange" },
{ class: 51, label: "broccoli" },
{ class: 52, label: "carrot" },
{ class: 53, label: "hot dog" },
{ class: 54, label: "pizza" },
{ class: 55, label: "donut" },
{ class: 56, label: "cake" },
{ class: 57, label: "chair" },
{ class: 58, label: "couch" },
{ class: 59, label: "potted plant" },
{ class: 60, label: "bed" },
{ class: 61, label: "dining table" },
{ class: 62, label: "toilet" },
{ class: 63, label: "tv" },
{ class: 64, label: "laptop" },
{ class: 65, label: "mouse" },
{ class: 66, label: "remote" },
{ class: 67, label: "keyboard" },
{ class: 68, label: "cell phone" },
{ class: 69, label: "microwave" },
{ class: 70, label: "oven" },
{ class: 71, label: "toaster" },
{ class: 72, label: "sink" },
{ class: 73, label: "refrigerator" },
{ class: 74, label: "book" },
{ class: 75, label: "clock" },
{ class: 76, label: "vase" },
{ class: 77, label: "scissors" },
{ class: 78, label: "teddy bear" },
{ class: 79, label: "hair drier" },
{ class: 80, label: "toothbrush" }
];
// src/object/centernet.ts
var model4;
var inputSize3 = 0;
var last3 = [];
var lastTime = 0;
var skipped4 = Number.MAX_SAFE_INTEGER;
async function load4(config3) {
if (env.initial)
model4 = null;
if (!model4) {
fakeOps(["floormod"], config3);
model4 = await m7(join(config3.modelBasePath, config3.object.modelPath || ""));
const inputs = Object.values(model4.modelSignature["inputs"]);
inputSize3 = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
if (!model4 || !model4["modelUrl"])
log("load model failed:", config3.object.modelPath);
else if (config3.debug)
log("load model:", model4["modelUrl"]);
} else if (config3.debug)
log("cached model:", model4["modelUrl"]);
return model4;
}
async function process3(res, outputShape, config3) {
if (!res)
return [];
const results = [];
const detections = await res.array();
const squeezeT = Br(res);
De(res);
const arr = sr(squeezeT, 6, 1);
De(squeezeT);
const stackT = Xt([arr[1], arr[0], arr[3], arr[2]], 1);
const boxesT = Br(stackT);
De(stackT);
const scoresT = Br(arr[4]);
const classesT = Br(arr[5]);
arr.forEach((t) => De(t));
const nmsT = await Cn.nonMaxSuppressionAsync(boxesT, scoresT, config3.object.maxDetected, config3.object.iouThreshold, config3.object.minConfidence);
De(boxesT);
De(scoresT);
De(classesT);
const nms = await nmsT.data();
De(nmsT);
let i = 0;
for (const id2 of nms) {
const score = Math.trunc(100 * detections[0][id2][4]) / 100;
const classVal = detections[0][id2][5];
const label = labels[classVal].label;
const [x, y] = [
detections[0][id2][0] / inputSize3,
detections[0][id2][1] / inputSize3
];
const boxRaw = [
x,
y,
detections[0][id2][2] / inputSize3 - x,
detections[0][id2][3] / inputSize3 - y
];
const box4 = [
Math.trunc(boxRaw[0] * outputShape[0]),
Math.trunc(boxRaw[1] * outputShape[1]),
Math.trunc(boxRaw[2] * outputShape[0]),
Math.trunc(boxRaw[3] * outputShape[1])
];
results.push({ id: i++, score, class: classVal, label, box: box4, boxRaw });
}
return results;
}
async function predict3(input, config3) {
if (skipped4 < (config3.object.skipFrames || 0) && (config3.object.skipTime || 0) <= now() - lastTime && config3.skipFrame && last3.length > 0) {
skipped4++;
return last3;
}
skipped4 = 0;
if (!env.kernels.includes("mod") || !env.kernels.includes("sparsetodense"))
return last3;
return new Promise(async (resolve) => {
const outputSize2 = [input.shape[2], input.shape[1]];
const resize = Cn.resizeBilinear(input, [inputSize3, inputSize3]);
const objectT = config3.object.enabled ? model4 == null ? void 0 : model4.execute(resize, ["tower_0/detections"]) : null;
lastTime = now();
De(resize);
const obj = await process3(objectT, outputSize2, config3);
last3 = obj;
resolve(obj);
});
}
// src/body/efficientposecoords.ts
var efficientposecoords_exports = {};
__export(efficientposecoords_exports, {
connected: () => connected2,
kpt: () => kpt2
});
var kpt2 = [
"head",
"neck",
"rightShoulder",
"rightElbow",
"rightWrist",
"chest",
"leftShoulder",
"leftElbow",
"leftWrist",
"bodyCenter",
"rightHip",
"rightKnee",
"rightAnkle",
"leftHip",
"leftKnee",
"leftAnkle"
];
var connected2 = {
leftLeg: ["leftHip", "leftKnee", "leftAnkle"],
rightLeg: ["rightHip", "rightKnee", "rightAnkle"],
torso: ["leftShoulder", "rightShoulder", "rightHip", "leftHip", "leftShoulder"],
leftArm: ["leftShoulder", "leftElbow", "leftWrist"],
rightArm: ["rightShoulder", "rightElbow", "rightWrist"],
head: []
};
// src/body/efficientpose.ts
var model5;
var last4 = 0;
var cache2 = { id: 0, keypoints: [], box: [0, 0, 0, 0], boxRaw: [0, 0, 0, 0], score: 0, annotations: {} };
var skipped5 = Number.MAX_SAFE_INTEGER;
async function load5(config3) {
if (env.initial)
model5 = null;
if (!model5) {
model5 = await m7(join(config3.modelBasePath, config3.body.modelPath || ""));
if (!model5 || !model5["modelUrl"])
log("load model failed:", config3.body.modelPath);
else if (config3.debug)
log("load model:", model5["modelUrl"]);
} else if (config3.debug)
log("cached model:", model5["modelUrl"]);
return model5;
}
function max2d(inputs, minScore) {
const [width, height] = inputs.shape;
return V(() => {
const mod = (a, b10) => le(a, O(ce(a, pe(b10, "int32")), pe(b10, "int32")));
const reshaped = F(inputs, [height * width]);
const newScore = Rr(reshaped, 0).dataSync()[0];
if (newScore > minScore) {
const coordinates = As(reshaped, 0);
const x = mod(coordinates, width).dataSync()[0];
const y = ce(coordinates, pe(width, "int32")).dataSync()[0];
return [x, y, newScore];
}
return [0, 0, newScore];
});
}
async function predict4(image6, config3) {
var _a2;
if (skipped5 < (((_a2 = config3.body) == null ? void 0 : _a2.skipFrames) || 0) && config3.skipFrame && Object.keys(cache2.keypoints).length > 0 && (config3.body.skipTime || 0) <= now() - last4) {
skipped5++;
return [cache2];
}
skipped5 = 0;
return new Promise(async (resolve) => {
var _a3;
const tensor = V(() => {
if (!(model5 == null ? void 0 : model5.inputs[0].shape))
return null;
const resize = Cn.resizeBilinear(image6, [model5.inputs[0].shape[2], model5.inputs[0].shape[1]], false);
const enhance2 = O(resize, 2);
const norm = enhance2.sub(1);
return norm;
});
let resT;
if (config3.body.enabled)
resT = await (model5 == null ? void 0 : model5.predict(tensor));
last4 = now();
De(tensor);
if (resT) {
cache2.keypoints.length = 0;
const squeeze = resT.squeeze();
De(resT);
const stack = squeeze.unstack(2);
De(squeeze);
for (let id2 = 0; id2 < stack.length; id2++) {
const [x7, y7, partScore] = max2d(stack[id2], config3.body.minConfidence);
if (partScore > (((_a3 = config3.body) == null ? void 0 : _a3.minConfidence) || 0)) {
cache2.keypoints.push({
score: Math.round(100 * partScore) / 100,
part: kpt2[id2],
positionRaw: [
x7 / model5.inputs[0].shape[2],
y7 / model5.inputs[0].shape[1]
],
position: [
Math.round(image6.shape[2] * x7 / model5.inputs[0].shape[2]),
Math.round(image6.shape[1] * y7 / model5.inputs[0].shape[1])
]
});
}
}
stack.forEach((s) => De(s));
}
cache2.score = cache2.keypoints.reduce((prev, curr) => curr.score > prev ? curr.score : prev, 0);
const x = cache2.keypoints.map((a) => a.position[0]);
const y = cache2.keypoints.map((a) => a.position[1]);
cache2.box = [
Math.min(...x),
Math.min(...y),
Math.max(...x) - Math.min(...x),
Math.max(...y) - Math.min(...y)
];
const xRaw = cache2.keypoints.map((a) => a.positionRaw[0]);
const yRaw = cache2.keypoints.map((a) => a.positionRaw[1]);
cache2.boxRaw = [
Math.min(...xRaw),
Math.min(...yRaw),
Math.max(...xRaw) - Math.min(...xRaw),
Math.max(...yRaw) - Math.min(...yRaw)
];
for (const [name, indexes] of Object.entries(connected2)) {
const pt = [];
for (let i = 0; i < indexes.length - 1; i++) {
const pt0 = cache2.keypoints.find((kpt4) => kpt4.part === indexes[i]);
const pt1 = cache2.keypoints.find((kpt4) => kpt4.part === indexes[i + 1]);
if (pt0 && pt1 && pt0.score > (config3.body.minConfidence || 0) && pt1.score > (config3.body.minConfidence || 0))
pt.push([pt0.position, pt1.position]);
}
cache2.annotations[name] = pt;
}
resolve([cache2]);
});
}
// src/gear/emotion.ts
var annotations = ["angry", "disgust", "fear", "happy", "sad", "surprise", "neutral"];
var model6;
var last5 = [];
var lastCount2 = 0;
var lastTime2 = 0;
var skipped6 = Number.MAX_SAFE_INTEGER;
var rgb = [0.2989, 0.587, 0.114];
async function load6(config3) {
var _a2, _b;
if (env.initial)
model6 = null;
if (!model6) {
model6 = await m7(join(config3.modelBasePath, ((_a2 = config3.face.emotion) == null ? void 0 : _a2.modelPath) || ""));
if (!model6 || !model6["modelUrl"])
log("load model failed:", (_b = config3.face.emotion) == null ? void 0 : _b.modelPath);
else if (config3.debug)
log("load model:", model6["modelUrl"]);
} else if (config3.debug)
log("cached model:", model6["modelUrl"]);
return model6;
}
async function predict5(image6, config3, idx, count2) {
var _a2, _b;
if (!model6)
return null;
if (skipped6 < (((_a2 = config3.face.emotion) == null ? void 0 : _a2.skipFrames) || 0) && (((_b = config3.face.emotion) == null ? void 0 : _b.skipTime) || 0) <= now() - lastTime2 && config3.skipFrame && lastCount2 === count2 && last5[idx] && last5[idx].length > 0) {
skipped6++;
return last5[idx];
}
skipped6 = 0;
return new Promise(async (resolve) => {
var _a3, _b2;
const obj = [];
if ((_a3 = config3.face.emotion) == null ? void 0 : _a3.enabled) {
const resize = Cn.resizeBilinear(image6, [(model6 == null ? void 0 : model6.inputs[0].shape) ? model6.inputs[0].shape[2] : 0, (model6 == null ? void 0 : model6.inputs[0].shape) ? model6.inputs[0].shape[1] : 0], false);
const [red, green, blue] = sr(resize, 3, 3);
De(resize);
const redNorm = O(red, rgb[0]);
const greenNorm = O(green, rgb[1]);
const blueNorm = O(blue, rgb[2]);
De(red);
De(green);
De(blue);
const grayscale = F_([redNorm, greenNorm, blueNorm]);
De(redNorm);
De(greenNorm);
De(blueNorm);
const normalize = V(() => O(le(grayscale, 0.5), 2));
De(grayscale);
const emotionT = await (model6 == null ? void 0 : model6.predict(normalize));
lastTime2 = now();
const data = await emotionT.data();
De(emotionT);
for (let i = 0; i < data.length; i++) {
if (data[i] > (((_b2 = config3.face.emotion) == null ? void 0 : _b2.minConfidence) || 0))
obj.push({ score: Math.min(0.99, Math.trunc(100 * data[i]) / 100), emotion: annotations[i] });
}
obj.sort((a, b10) => b10.score - a.score);
De(normalize);
}
last5[idx] = obj;
lastCount2 = count2;
resolve(obj);
});
}
// src/face/iris.ts
var model7;
var inputSize4 = 0;
var irisEnlarge = 2.3;
var leftOutline = meshAnnotations["leftEyeLower0"];
var rightOutline = meshAnnotations["rightEyeLower0"];
var eyeLandmarks = {
leftBounds: [leftOutline[0], leftOutline[leftOutline.length - 1]],
rightBounds: [rightOutline[0], rightOutline[rightOutline.length - 1]]
};
var irisLandmarks = {
upperCenter: 3,
lowerCenter: 4,
index: 71,
numCoordinates: 76
};
async function load7(config3) {
var _a2, _b;
if (env.initial)
model7 = null;
if (!model7) {
model7 = await m7(join(config3.modelBasePath, ((_a2 = config3.face.iris) == null ? void 0 : _a2.modelPath) || ""));
if (!model7 || !model7["modelUrl"])
log("load model failed:", (_b = config3.face.iris) == null ? void 0 : _b.modelPath);
else if (config3.debug)
log("load model:", model7["modelUrl"]);
} else if (config3.debug)
log("cached model:", model7["modelUrl"]);
inputSize4 = model7.inputs[0].shape ? model7.inputs[0].shape[2] : 0;
if (inputSize4 === -1)
inputSize4 = 64;
return model7;
}
function replaceRawCoordinates(rawCoords, newCoords, prefix, keys) {
for (let i = 0; i < MESH_TO_IRIS_INDICES_MAP.length; i++) {
const { key, indices } = MESH_TO_IRIS_INDICES_MAP[i];
const originalIndices = meshAnnotations[`${prefix}${key}`];
if (!keys || keys.includes(key)) {
for (let j = 0; j < indices.length; j++) {
const index = indices[j];
rawCoords[originalIndices[j]] = [
newCoords[index][0],
newCoords[index][1],
(newCoords[index][2] + rawCoords[originalIndices[j]][2]) / 2
];
}
}
}
}
var getLeftToRightEyeDepthDifference = (rawCoords) => {
const leftEyeZ = rawCoords[eyeLandmarks.leftBounds[0]][2];
const rightEyeZ = rawCoords[eyeLandmarks.rightBounds[0]][2];
return leftEyeZ - rightEyeZ;
};
var getEyeBox = (rawCoords, face5, eyeInnerCornerIndex, eyeOuterCornerIndex, flip = false, meshSize) => {
const box4 = squarifyBox(enlargeBox(calculateLandmarksBoundingBox([rawCoords[eyeInnerCornerIndex], rawCoords[eyeOuterCornerIndex]]), irisEnlarge));
const boxSize = getBoxSize(box4);
let crop2 = Cn.cropAndResize(face5, [[
box4.startPoint[1] / meshSize,
box4.startPoint[0] / meshSize,
box4.endPoint[1] / meshSize,
box4.endPoint[0] / meshSize
]], [0], [inputSize4, inputSize4]);
if (flip && env.kernels.includes("flipleftright")) {
const flipped = Cn.flipLeftRight(crop2);
De(crop2);
crop2 = flipped;
}
return { box: box4, boxSize, crop: crop2 };
};
var getEyeCoords = (eyeData, eyeBox, eyeBoxSize, flip = false) => {
const eyeRawCoords = [];
for (let i = 0; i < irisLandmarks.numCoordinates; i++) {
const x = eyeData[i * 3];
const y = eyeData[i * 3 + 1];
const z10 = eyeData[i * 3 + 2];
eyeRawCoords.push([
(flip ? 1 - x / inputSize4 : x / inputSize4) * eyeBoxSize[0] + eyeBox.startPoint[0],
y / inputSize4 * eyeBoxSize[1] + eyeBox.startPoint[1],
z10
]);
}
return { rawCoords: eyeRawCoords, iris: eyeRawCoords.slice(irisLandmarks.index) };
};
var getAdjustedIrisCoords = (rawCoords, irisCoords, direction) => {
const upperCenterZ = rawCoords[meshAnnotations[`${direction}EyeUpper0`][irisLandmarks.upperCenter]][2];
const lowerCenterZ = rawCoords[meshAnnotations[`${direction}EyeLower0`][irisLandmarks.lowerCenter]][2];
const averageZ = (upperCenterZ + lowerCenterZ) / 2;
return irisCoords.map((coord, i) => {
let z10 = averageZ;
if (i === 2) {
z10 = upperCenterZ;
} else if (i === 4) {
z10 = lowerCenterZ;
}
return [coord[0], coord[1], z10];
});
};
async function augmentIris(rawCoords, face5, config3, meshSize) {
if (!model7) {
if (config3.debug)
log("face mesh iris detection requested, but model is not loaded");
return rawCoords;
}
const { box: leftEyeBox, boxSize: leftEyeBoxSize, crop: leftEyeCrop } = getEyeBox(rawCoords, face5, eyeLandmarks.leftBounds[0], eyeLandmarks.leftBounds[1], true, meshSize);
const { box: rightEyeBox, boxSize: rightEyeBoxSize, crop: rightEyeCrop } = getEyeBox(rawCoords, face5, eyeLandmarks.rightBounds[0], eyeLandmarks.rightBounds[1], true, meshSize);
const combined = tt([leftEyeCrop, rightEyeCrop]);
De(leftEyeCrop);
De(rightEyeCrop);
const eyePredictions = model7.predict(combined);
De(combined);
const eyePredictionsData = await eyePredictions.data();
De(eyePredictions);
const leftEyeData = eyePredictionsData.slice(0, irisLandmarks.numCoordinates * 3);
const { rawCoords: leftEyeRawCoords, iris: leftIrisRawCoords } = getEyeCoords(leftEyeData, leftEyeBox, leftEyeBoxSize, true);
const rightEyeData = eyePredictionsData.slice(irisLandmarks.numCoordinates * 3);
const { rawCoords: rightEyeRawCoords, iris: rightIrisRawCoords } = getEyeCoords(rightEyeData, rightEyeBox, rightEyeBoxSize);
const leftToRightEyeDepthDifference = getLeftToRightEyeDepthDifference(rawCoords);
if (Math.abs(leftToRightEyeDepthDifference) < 30) {
replaceRawCoordinates(rawCoords, leftEyeRawCoords, "left", null);
replaceRawCoordinates(rawCoords, rightEyeRawCoords, "right", null);
} else if (leftToRightEyeDepthDifference < 1) {
replaceRawCoordinates(rawCoords, leftEyeRawCoords, "left", ["EyeUpper0", "EyeLower0"]);
} else {
replaceRawCoordinates(rawCoords, rightEyeRawCoords, "right", ["EyeUpper0", "EyeLower0"]);
}
const adjustedLeftIrisCoords = getAdjustedIrisCoords(rawCoords, leftIrisRawCoords, "left");
const adjustedRightIrisCoords = getAdjustedIrisCoords(rawCoords, rightIrisRawCoords, "right");
const newCoords = rawCoords.concat(adjustedLeftIrisCoords).concat(adjustedRightIrisCoords);
return newCoords;
}
// src/face/facemesh.ts
var boxCache = [];
var model8 = null;
var inputSize5 = 0;
var skipped7 = Number.MAX_SAFE_INTEGER;
var lastTime3 = 0;
var detectedFaces = 0;
async function predict6(input, config3) {
var _a2, _b, _c2, _d2, _e, _f2, _g, _h2, _i2, _j2, _k2, _l2, _m2;
if (!config3.skipFrame || (detectedFaces !== ((_a2 = config3.face.detector) == null ? void 0 : _a2.maxDetected) || !((_b = config3.face.mesh) == null ? void 0 : _b.enabled)) && (skipped7 > (((_c2 = config3.face.detector) == null ? void 0 : _c2.skipFrames) || 0) && (((_d2 = config3.face.description) == null ? void 0 : _d2.skipTime) || 0) <= now() - lastTime3)) {
const newBoxes2 = await getBoxes(input, config3);
lastTime3 = now();
boxCache = [];
for (const possible of newBoxes2.boxes) {
const startPoint = await possible.box.startPoint.data();
const endPoint = await possible.box.endPoint.data();
const landmarks = await possible.landmarks.array();
boxCache.push({ startPoint, endPoint, landmarks, confidence: possible.confidence });
}
newBoxes2.boxes.forEach((prediction) => De([prediction.box.startPoint, prediction.box.endPoint, prediction.landmarks]));
for (let i = 0; i < boxCache.length; i++) {
const scaledBox = scaleBoxCoordinates({ startPoint: boxCache[i].startPoint, endPoint: boxCache[i].endPoint }, newBoxes2.scaleFactor);
const enlargedBox = enlargeBox(scaledBox);
const squarifiedBox = squarifyBox(enlargedBox);
boxCache[i] = { ...squarifiedBox, confidence: boxCache[i].confidence, landmarks: boxCache[i].landmarks };
}
skipped7 = 0;
} else {
skipped7++;
}
const faces = [];
const newBoxes = [];
let id2 = 0;
for (let box4 of boxCache) {
let angle = 0;
let rotationMatrix;
const face5 = {
id: id2++,
mesh: [],
meshRaw: [],
box: [0, 0, 0, 0],
boxRaw: [0, 0, 0, 0],
score: 0,
boxScore: 0,
faceScore: 0,
annotations: {}
};
if (((_e = config3.face.detector) == null ? void 0 : _e.rotation) && ((_f2 = config3.face.mesh) == null ? void 0 : _f2.enabled) && env.kernels.includes("rotatewithoffset")) {
[angle, rotationMatrix, face5.tensor] = correctFaceRotation(box4, input, inputSize5);
} else {
rotationMatrix = IDENTITY_MATRIX;
const cut = cutBoxFromImageAndResize({ startPoint: box4.startPoint, endPoint: box4.endPoint }, input, ((_g = config3.face.mesh) == null ? void 0 : _g.enabled) ? [inputSize5, inputSize5] : [size(), size()]);
face5.tensor = ce(cut, 255);
De(cut);
}
face5.boxScore = Math.round(100 * box4.confidence) / 100;
if (!((_h2 = config3.face.mesh) == null ? void 0 : _h2.enabled)) {
face5.box = getClampedBox(box4, input);
face5.boxRaw = getRawBox(box4, input);
face5.score = Math.round(100 * box4.confidence || 0) / 100;
face5.mesh = box4.landmarks.map((pt) => [
(box4.startPoint[0] + box4.endPoint[0]) / 2 + (box4.endPoint[0] + box4.startPoint[0]) * pt[0] / size(),
(box4.startPoint[1] + box4.endPoint[1]) / 2 + (box4.endPoint[1] + box4.startPoint[1]) * pt[1] / size()
]);
face5.meshRaw = face5.mesh.map((pt) => [pt[0] / (input.shape[2] || 0), pt[1] / (input.shape[1] || 0), (pt[2] || 0) / inputSize5]);
for (const key of Object.keys(blazeFaceLandmarks))
face5.annotations[key] = [face5.mesh[blazeFaceLandmarks[key]]];
} else if (!model8) {
if (config3.debug)
log("face mesh detection requested, but model is not loaded");
} else {
const [contours, confidence, contourCoords] = model8.execute(face5.tensor);
De(contours);
const faceConfidence = (await confidence.data())[0];
De(confidence);
const coordsReshaped = F(contourCoords, [-1, 3]);
let rawCoords = await coordsReshaped.array();
De(contourCoords);
De(coordsReshaped);
if (faceConfidence < (((_i2 = config3.face.detector) == null ? void 0 : _i2.minConfidence) || 1)) {
box4.confidence = faceConfidence;
} else {
if ((_j2 = config3.face.iris) == null ? void 0 : _j2.enabled)
rawCoords = await augmentIris(rawCoords, face5.tensor, config3, inputSize5);
face5.mesh = transformRawCoords(rawCoords, box4, angle, rotationMatrix, inputSize5);
face5.meshRaw = face5.mesh.map((pt) => [pt[0] / (input.shape[2] || 0), pt[1] / (input.shape[1] || 0), (pt[2] || 0) / inputSize5]);
box4 = { ...enlargeBox(calculateLandmarksBoundingBox(face5.mesh), 1.5), confidence: box4.confidence };
for (const key of Object.keys(meshAnnotations))
face5.annotations[key] = meshAnnotations[key].map((index) => face5.mesh[index]);
if (((_k2 = config3.face.detector) == null ? void 0 : _k2.rotation) && config3.face.mesh.enabled && ((_l2 = config3.face.description) == null ? void 0 : _l2.enabled) && env.kernels.includes("rotatewithoffset")) {
De(face5.tensor);
[angle, rotationMatrix, face5.tensor] = correctFaceRotation(box4, input, inputSize5);
}
face5.box = getClampedBox(box4, input);
face5.boxRaw = getRawBox(box4, input);
face5.score = Math.round(100 * faceConfidence || 100 * box4.confidence || 0) / 100;
face5.faceScore = Math.round(100 * faceConfidence) / 100;
box4 = { ...squarifyBox(box4), confidence: box4.confidence, faceConfidence };
}
}
faces.push(face5);
newBoxes.push(box4);
}
if ((_m2 = config3.face.mesh) == null ? void 0 : _m2.enabled)
boxCache = newBoxes.filter((a) => {
var _a3;
return a.confidence > (((_a3 = config3.face.detector) == null ? void 0 : _a3.minConfidence) || 0);
});
detectedFaces = faces.length;
return faces;
}
async function load8(config3) {
var _a2, _b;
if (env.initial)
model8 = null;
if (!model8) {
model8 = await m7(join(config3.modelBasePath, ((_a2 = config3.face.mesh) == null ? void 0 : _a2.modelPath) || ""));
if (!model8 || !model8["modelUrl"])
log("load model failed:", (_b = config3.face.mesh) == null ? void 0 : _b.modelPath);
else if (config3.debug)
log("load model:", model8["modelUrl"]);
} else if (config3.debug)
log("cached model:", model8["modelUrl"]);
inputSize5 = model8.inputs[0].shape ? model8.inputs[0].shape[2] : 0;
if (inputSize5 === -1)
inputSize5 = 64;
return model8;
}
var triangulation = TRI468;
var uvmap = UV468;
// src/face/faceres.ts
var model9;
var last6 = [];
var lastTime4 = 0;
var lastCount3 = 0;
var skipped8 = Number.MAX_SAFE_INTEGER;
async function load9(config3) {
var _a2, _b;
const modelUrl = join(config3.modelBasePath, ((_a2 = config3.face.description) == null ? void 0 : _a2.modelPath) || "");
if (env.initial)
model9 = null;
if (!model9) {
model9 = await m7(modelUrl);
if (!model9)
log("load model failed:", ((_b = config3.face.description) == null ? void 0 : _b.modelPath) || "");
else if (config3.debug)
log("load model:", modelUrl);
} else if (config3.debug)
log("cached model:", modelUrl);
return model9;
}
function enhance(input) {
const image6 = V(() => {
const tensor = input.image || input.tensor || input;
if (!(tensor instanceof Le))
return null;
const box4 = [[0.05, 0.15, 0.85, 0.85]];
if (!(model9 == null ? void 0 : model9.inputs[0].shape))
return null;
const crop2 = tensor.shape.length === 3 ? Cn.cropAndResize(mr(tensor, 0), box4, [0], [model9.inputs[0].shape[2], model9.inputs[0].shape[1]]) : Cn.cropAndResize(tensor, box4, [0], [model9.inputs[0].shape[2], model9.inputs[0].shape[1]]);
const norm = O(crop2, 255);
return norm;
});
return image6;
}
async function predict7(image6, config3, idx, count2) {
var _a2, _b, _c2, _d2;
if (!model9)
return null;
if (skipped8 < (((_a2 = config3.face.description) == null ? void 0 : _a2.skipFrames) || 0) && (((_b = config3.face.description) == null ? void 0 : _b.skipTime) || 0) <= now() - lastTime4 && config3.skipFrame && lastCount3 === count2 && ((_c2 = last6[idx]) == null ? void 0 : _c2.age) && ((_d2 = last6[idx]) == null ? void 0 : _d2.age) > 0) {
skipped8++;
return last6[idx];
}
skipped8 = 0;
return new Promise(async (resolve) => {
var _a3, _b2;
const obj = {
age: 0,
gender: "unknown",
genderScore: 0,
descriptor: []
};
if ((_a3 = config3.face.description) == null ? void 0 : _a3.enabled) {
const enhanced = enhance(image6);
const resT = await (model9 == null ? void 0 : model9.predict(enhanced));
lastTime4 = now();
De(enhanced);
const genderT = await resT.find((t) => t.shape[1] === 1);
const gender = await genderT.data();
const confidence = Math.trunc(200 * Math.abs(gender[0] - 0.5)) / 100;
if (confidence > (((_b2 = config3.face.description) == null ? void 0 : _b2.minConfidence) || 0)) {
obj.gender = gender[0] <= 0.5 ? "female" : "male";
obj.genderScore = Math.min(0.99, confidence);
}
const argmax = As(resT.find((t) => t.shape[1] === 100), 1);
const age = (await argmax.data())[0];
De(argmax);
const ageT = resT.find((t) => t.shape[1] === 100);
const all2 = await ageT.data();
obj.age = Math.round(all2[age - 1] > all2[age + 1] ? 10 * age - 100 * all2[age - 1] : 10 * age + 100 * all2[age + 1]) / 10;
const desc = resT.find((t) => t.shape[1] === 1024);
const descriptor = desc ? await desc.data() : [];
obj.descriptor = Array.from(descriptor);
resT.forEach((t) => De(t));
}
last6[idx] = obj;
lastCount3 = count2;
resolve(obj);
});
}
// src/hand/handposeutil.ts
function getBoxSize2(box4) {
return [
Math.abs(box4.endPoint[0] - box4.startPoint[0]),
Math.abs(box4.endPoint[1] - box4.startPoint[1])
];
}
function getBoxCenter2(box4) {
return [
box4.startPoint[0] + (box4.endPoint[0] - box4.startPoint[0]) / 2,
box4.startPoint[1] + (box4.endPoint[1] - box4.startPoint[1]) / 2
];
}
function cutBoxFromImageAndResize2(box4, image6, cropSize) {
const h = image6.shape[1];
const w = image6.shape[2];
const boxes = [[
box4.startPoint[1] / h,
box4.startPoint[0] / w,
box4.endPoint[1] / h,
box4.endPoint[0] / w
]];
return Cn.cropAndResize(image6, boxes, [0], cropSize);
}
function scaleBoxCoordinates2(box4, factor) {
const startPoint = [box4.startPoint[0] * factor[0], box4.startPoint[1] * factor[1]];
const endPoint = [box4.endPoint[0] * factor[0], box4.endPoint[1] * factor[1]];
const palmLandmarks = box4.palmLandmarks.map((coord) => {
const scaledCoord = [coord[0] * factor[0], coord[1] * factor[1]];
return scaledCoord;
});
return { startPoint, endPoint, palmLandmarks, confidence: box4.confidence };
}
function enlargeBox2(box4, factor = 1.5) {
const center = getBoxCenter2(box4);
const size2 = getBoxSize2(box4);
const newHalfSize = [factor * size2[0] / 2, factor * size2[1] / 2];
const startPoint = [center[0] - newHalfSize[0], center[1] - newHalfSize[1]];
const endPoint = [center[0] + newHalfSize[0], center[1] + newHalfSize[1]];
return { startPoint, endPoint, palmLandmarks: box4.palmLandmarks };
}
function squarifyBox2(box4) {
const centers = getBoxCenter2(box4);
const size2 = getBoxSize2(box4);
const maxEdge = Math.max(...size2);
const halfSize = maxEdge / 2;
const startPoint = [centers[0] - halfSize, centers[1] - halfSize];
const endPoint = [centers[0] + halfSize, centers[1] + halfSize];
return { startPoint, endPoint, palmLandmarks: box4.palmLandmarks };
}
function normalizeRadians2(angle) {
return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));
}
function computeRotation2(point1, point2) {
const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);
return normalizeRadians2(radians);
}
var buildTranslationMatrix2 = (x, y) => [[1, 0, x], [0, 1, y], [0, 0, 1]];
function dot2(v12, v22) {
let product = 0;
for (let i = 0; i < v12.length; i++) {
product += v12[i] * v22[i];
}
return product;
}
function getColumnFrom2DArr2(arr, columnIndex) {
const column = [];
for (let i = 0; i < arr.length; i++) {
column.push(arr[i][columnIndex]);
}
return column;
}
function multiplyTransformMatrices2(mat1, mat2) {
const product = [];
const size2 = mat1.length;
for (let row = 0; row < size2; row++) {
product.push([]);
for (let col = 0; col < size2; col++) {
product[row].push(dot2(mat1[row], getColumnFrom2DArr2(mat2, col)));
}
}
return product;
}
function buildRotationMatrix2(rotation, center) {
const cosA = Math.cos(rotation);
const sinA = Math.sin(rotation);
const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];
const translationMatrix = buildTranslationMatrix2(center[0], center[1]);
const translationTimesRotation = multiplyTransformMatrices2(translationMatrix, rotationMatrix);
const negativeTranslationMatrix = buildTranslationMatrix2(-center[0], -center[1]);
return multiplyTransformMatrices2(translationTimesRotation, negativeTranslationMatrix);
}
function invertTransformMatrix2(matrix) {
const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];
const translationComponent = [matrix[0][2], matrix[1][2]];
const invertedTranslation = [
-dot2(rotationComponent[0], translationComponent),
-dot2(rotationComponent[1], translationComponent)
];
return [
rotationComponent[0].concat(invertedTranslation[0]),
rotationComponent[1].concat(invertedTranslation[1]),
[0, 0, 1]
];
}
function rotatePoint2(homogeneousCoordinate, rotationMatrix) {
return [
dot2(homogeneousCoordinate, rotationMatrix[0]),
dot2(homogeneousCoordinate, rotationMatrix[1])
];
}
// src/hand/handposeanchors.ts
var anchors2 = [
{ x: 0.015625, y: 0.015625 },
{ x: 0.015625, y: 0.015625 },
{ x: 0.046875, y: 0.015625 },
{ x: 0.046875, y: 0.015625 },
{ x: 0.078125, y: 0.015625 },
{ x: 0.078125, y: 0.015625 },
{ x: 0.109375, y: 0.015625 },
{ x: 0.109375, y: 0.015625 },
{ x: 0.140625, y: 0.015625 },
{ x: 0.140625, y: 0.015625 },
{ x: 0.171875, y: 0.015625 },
{ x: 0.171875, y: 0.015625 },
{ x: 0.203125, y: 0.015625 },
{ x: 0.203125, y: 0.015625 },
{ x: 0.234375, y: 0.015625 },
{ x: 0.234375, y: 0.015625 },
{ x: 0.265625, y: 0.015625 },
{ x: 0.265625, y: 0.015625 },
{ x: 0.296875, y: 0.015625 },
{ x: 0.296875, y: 0.015625 },
{ x: 0.328125, y: 0.015625 },
{ x: 0.328125, y: 0.015625 },
{ x: 0.359375, y: 0.015625 },
{ x: 0.359375, y: 0.015625 },
{ x: 0.390625, y: 0.015625 },
{ x: 0.390625, y: 0.015625 },
{ x: 0.421875, y: 0.015625 },
{ x: 0.421875, y: 0.015625 },
{ x: 0.453125, y: 0.015625 },
{ x: 0.453125, y: 0.015625 },
{ x: 0.484375, y: 0.015625 },
{ x: 0.484375, y: 0.015625 },
{ x: 0.515625, y: 0.015625 },
{ x: 0.515625, y: 0.015625 },
{ x: 0.546875, y: 0.015625 },
{ x: 0.546875, y: 0.015625 },
{ x: 0.578125, y: 0.015625 },
{ x: 0.578125, y: 0.015625 },
{ x: 0.609375, y: 0.015625 },
{ x: 0.609375, y: 0.015625 },
{ x: 0.640625, y: 0.015625 },
{ x: 0.640625, y: 0.015625 },
{ x: 0.671875, y: 0.015625 },
{ x: 0.671875, y: 0.015625 },
{ x: 0.703125, y: 0.015625 },
{ x: 0.703125, y: 0.015625 },
{ x: 0.734375, y: 0.015625 },
{ x: 0.734375, y: 0.015625 },
{ x: 0.765625, y: 0.015625 },
{ x: 0.765625, y: 0.015625 },
{ x: 0.796875, y: 0.015625 },
{ x: 0.796875, y: 0.015625 },
{ x: 0.828125, y: 0.015625 },
{ x: 0.828125, y: 0.015625 },
{ x: 0.859375, y: 0.015625 },
{ x: 0.859375, y: 0.015625 },
{ x: 0.890625, y: 0.015625 },
{ x: 0.890625, y: 0.015625 },
{ x: 0.921875, y: 0.015625 },
{ x: 0.921875, y: 0.015625 },
{ x: 0.953125, y: 0.015625 },
{ x: 0.953125, y: 0.015625 },
{ x: 0.984375, y: 0.015625 },
{ x: 0.984375, y: 0.015625 },
{ x: 0.015625, y: 0.046875 },
{ x: 0.015625, y: 0.046875 },
{ x: 0.046875, y: 0.046875 },
{ x: 0.046875, y: 0.046875 },
{ x: 0.078125, y: 0.046875 },
{ x: 0.078125, y: 0.046875 },
{ x: 0.109375, y: 0.046875 },
{ x: 0.109375, y: 0.046875 },
{ x: 0.140625, y: 0.046875 },
{ x: 0.140625, y: 0.046875 },
{ x: 0.171875, y: 0.046875 },
{ x: 0.171875, y: 0.046875 },
{ x: 0.203125, y: 0.046875 },
{ x: 0.203125, y: 0.046875 },
{ x: 0.234375, y: 0.046875 },
{ x: 0.234375, y: 0.046875 },
{ x: 0.265625, y: 0.046875 },
{ x: 0.265625, y: 0.046875 },
{ x: 0.296875, y: 0.046875 },
{ x: 0.296875, y: 0.046875 },
{ x: 0.328125, y: 0.046875 },
{ x: 0.328125, y: 0.046875 },
{ x: 0.359375, y: 0.046875 },
{ x: 0.359375, y: 0.046875 },
{ x: 0.390625, y: 0.046875 },
{ x: 0.390625, y: 0.046875 },
{ x: 0.421875, y: 0.046875 },
{ x: 0.421875, y: 0.046875 },
{ x: 0.453125, y: 0.046875 },
{ x: 0.453125, y: 0.046875 },
{ x: 0.484375, y: 0.046875 },
{ x: 0.484375, y: 0.046875 },
{ x: 0.515625, y: 0.046875 },
{ x: 0.515625, y: 0.046875 },
{ x: 0.546875, y: 0.046875 },
{ x: 0.546875, y: 0.046875 },
{ x: 0.578125, y: 0.046875 },
{ x: 0.578125, y: 0.046875 },
{ x: 0.609375, y: 0.046875 },
{ x: 0.609375, y: 0.046875 },
{ x: 0.640625, y: 0.046875 },
{ x: 0.640625, y: 0.046875 },
{ x: 0.671875, y: 0.046875 },
{ x: 0.671875, y: 0.046875 },
{ x: 0.703125, y: 0.046875 },
{ x: 0.703125, y: 0.046875 },
{ x: 0.734375, y: 0.046875 },
{ x: 0.734375, y: 0.046875 },
{ x: 0.765625, y: 0.046875 },
{ x: 0.765625, y: 0.046875 },
{ x: 0.796875, y: 0.046875 },
{ x: 0.796875, y: 0.046875 },
{ x: 0.828125, y: 0.046875 },
{ x: 0.828125, y: 0.046875 },
{ x: 0.859375, y: 0.046875 },
{ x: 0.859375, y: 0.046875 },
{ x: 0.890625, y: 0.046875 },
{ x: 0.890625, y: 0.046875 },
{ x: 0.921875, y: 0.046875 },
{ x: 0.921875, y: 0.046875 },
{ x: 0.953125, y: 0.046875 },
{ x: 0.953125, y: 0.046875 },
{ x: 0.984375, y: 0.046875 },
{ x: 0.984375, y: 0.046875 },
{ x: 0.015625, y: 0.078125 },
{ x: 0.015625, y: 0.078125 },
{ x: 0.046875, y: 0.078125 },
{ x: 0.046875, y: 0.078125 },
{ x: 0.078125, y: 0.078125 },
{ x: 0.078125, y: 0.078125 },
{ x: 0.109375, y: 0.078125 },
{ x: 0.109375, y: 0.078125 },
{ x: 0.140625, y: 0.078125 },
{ x: 0.140625, y: 0.078125 },
{ x: 0.171875, y: 0.078125 },
{ x: 0.171875, y: 0.078125 },
{ x: 0.203125, y: 0.078125 },
{ x: 0.203125, y: 0.078125 },
{ x: 0.234375, y: 0.078125 },
{ x: 0.234375, y: 0.078125 },
{ x: 0.265625, y: 0.078125 },
{ x: 0.265625, y: 0.078125 },
{ x: 0.296875, y: 0.078125 },
{ x: 0.296875, y: 0.078125 },
{ x: 0.328125, y: 0.078125 },
{ x: 0.328125, y: 0.078125 },
{ x: 0.359375, y: 0.078125 },
{ x: 0.359375, y: 0.078125 },
{ x: 0.390625, y: 0.078125 },
{ x: 0.390625, y: 0.078125 },
{ x: 0.421875, y: 0.078125 },
{ x: 0.421875, y: 0.078125 },
{ x: 0.453125, y: 0.078125 },
{ x: 0.453125, y: 0.078125 },
{ x: 0.484375, y: 0.078125 },
{ x: 0.484375, y: 0.078125 },
{ x: 0.515625, y: 0.078125 },
{ x: 0.515625, y: 0.078125 },
{ x: 0.546875, y: 0.078125 },
{ x: 0.546875, y: 0.078125 },
{ x: 0.578125, y: 0.078125 },
{ x: 0.578125, y: 0.078125 },
{ x: 0.609375, y: 0.078125 },
{ x: 0.609375, y: 0.078125 },
{ x: 0.640625, y: 0.078125 },
{ x: 0.640625, y: 0.078125 },
{ x: 0.671875, y: 0.078125 },
{ x: 0.671875, y: 0.078125 },
{ x: 0.703125, y: 0.078125 },
{ x: 0.703125, y: 0.078125 },
{ x: 0.734375, y: 0.078125 },
{ x: 0.734375, y: 0.078125 },
{ x: 0.765625, y: 0.078125 },
{ x: 0.765625, y: 0.078125 },
{ x: 0.796875, y: 0.078125 },
{ x: 0.796875, y: 0.078125 },
{ x: 0.828125, y: 0.078125 },
{ x: 0.828125, y: 0.078125 },
{ x: 0.859375, y: 0.078125 },
{ x: 0.859375, y: 0.078125 },
{ x: 0.890625, y: 0.078125 },
{ x: 0.890625, y: 0.078125 },
{ x: 0.921875, y: 0.078125 },
{ x: 0.921875, y: 0.078125 },
{ x: 0.953125, y: 0.078125 },
{ x: 0.953125, y: 0.078125 },
{ x: 0.984375, y: 0.078125 },
{ x: 0.984375, y: 0.078125 },
{ x: 0.015625, y: 0.109375 },
{ x: 0.015625, y: 0.109375 },
{ x: 0.046875, y: 0.109375 },
{ x: 0.046875, y: 0.109375 },
{ x: 0.078125, y: 0.109375 },
{ x: 0.078125, y: 0.109375 },
{ x: 0.109375, y: 0.109375 },
{ x: 0.109375, y: 0.109375 },
{ x: 0.140625, y: 0.109375 },
{ x: 0.140625, y: 0.109375 },
{ x: 0.171875, y: 0.109375 },
{ x: 0.171875, y: 0.109375 },
{ x: 0.203125, y: 0.109375 },
{ x: 0.203125, y: 0.109375 },
{ x: 0.234375, y: 0.109375 },
{ x: 0.234375, y: 0.109375 },
{ x: 0.265625, y: 0.109375 },
{ x: 0.265625, y: 0.109375 },
{ x: 0.296875, y: 0.109375 },
{ x: 0.296875, y: 0.109375 },
{ x: 0.328125, y: 0.109375 },
{ x: 0.328125, y: 0.109375 },
{ x: 0.359375, y: 0.109375 },
{ x: 0.359375, y: 0.109375 },
{ x: 0.390625, y: 0.109375 },
{ x: 0.390625, y: 0.109375 },
{ x: 0.421875, y: 0.109375 },
{ x: 0.421875, y: 0.109375 },
{ x: 0.453125, y: 0.109375 },
{ x: 0.453125, y: 0.109375 },
{ x: 0.484375, y: 0.109375 },
{ x: 0.484375, y: 0.109375 },
{ x: 0.515625, y: 0.109375 },
{ x: 0.515625, y: 0.109375 },
{ x: 0.546875, y: 0.109375 },
{ x: 0.546875, y: 0.109375 },
{ x: 0.578125, y: 0.109375 },
{ x: 0.578125, y: 0.109375 },
{ x: 0.609375, y: 0.109375 },
{ x: 0.609375, y: 0.109375 },
{ x: 0.640625, y: 0.109375 },
{ x: 0.640625, y: 0.109375 },
{ x: 0.671875, y: 0.109375 },
{ x: 0.671875, y: 0.109375 },
{ x: 0.703125, y: 0.109375 },
{ x: 0.703125, y: 0.109375 },
{ x: 0.734375, y: 0.109375 },
{ x: 0.734375, y: 0.109375 },
{ x: 0.765625, y: 0.109375 },
{ x: 0.765625, y: 0.109375 },
{ x: 0.796875, y: 0.109375 },
{ x: 0.796875, y: 0.109375 },
{ x: 0.828125, y: 0.109375 },
{ x: 0.828125, y: 0.109375 },
{ x: 0.859375, y: 0.109375 },
{ x: 0.859375, y: 0.109375 },
{ x: 0.890625, y: 0.109375 },
{ x: 0.890625, y: 0.109375 },
{ x: 0.921875, y: 0.109375 },
{ x: 0.921875, y: 0.109375 },
{ x: 0.953125, y: 0.109375 },
{ x: 0.953125, y: 0.109375 },
{ x: 0.984375, y: 0.109375 },
{ x: 0.984375, y: 0.109375 },
{ x: 0.015625, y: 0.140625 },
{ x: 0.015625, y: 0.140625 },
{ x: 0.046875, y: 0.140625 },
{ x: 0.046875, y: 0.140625 },
{ x: 0.078125, y: 0.140625 },
{ x: 0.078125, y: 0.140625 },
{ x: 0.109375, y: 0.140625 },
{ x: 0.109375, y: 0.140625 },
{ x: 0.140625, y: 0.140625 },
{ x: 0.140625, y: 0.140625 },
{ x: 0.171875, y: 0.140625 },
{ x: 0.171875, y: 0.140625 },
{ x: 0.203125, y: 0.140625 },
{ x: 0.203125, y: 0.140625 },
{ x: 0.234375, y: 0.140625 },
{ x: 0.234375, y: 0.140625 },
{ x: 0.265625, y: 0.140625 },
{ x: 0.265625, y: 0.140625 },
{ x: 0.296875, y: 0.140625 },
{ x: 0.296875, y: 0.140625 },
{ x: 0.328125, y: 0.140625 },
{ x: 0.328125, y: 0.140625 },
{ x: 0.359375, y: 0.140625 },
{ x: 0.359375, y: 0.140625 },
{ x: 0.390625, y: 0.140625 },
{ x: 0.390625, y: 0.140625 },
{ x: 0.421875, y: 0.140625 },
{ x: 0.421875, y: 0.140625 },
{ x: 0.453125, y: 0.140625 },
{ x: 0.453125, y: 0.140625 },
{ x: 0.484375, y: 0.140625 },
{ x: 0.484375, y: 0.140625 },
{ x: 0.515625, y: 0.140625 },
{ x: 0.515625, y: 0.140625 },
{ x: 0.546875, y: 0.140625 },
{ x: 0.546875, y: 0.140625 },
{ x: 0.578125, y: 0.140625 },
{ x: 0.578125, y: 0.140625 },
{ x: 0.609375, y: 0.140625 },
{ x: 0.609375, y: 0.140625 },
{ x: 0.640625, y: 0.140625 },
{ x: 0.640625, y: 0.140625 },
{ x: 0.671875, y: 0.140625 },
{ x: 0.671875, y: 0.140625 },
{ x: 0.703125, y: 0.140625 },
{ x: 0.703125, y: 0.140625 },
{ x: 0.734375, y: 0.140625 },
{ x: 0.734375, y: 0.140625 },
{ x: 0.765625, y: 0.140625 },
{ x: 0.765625, y: 0.140625 },
{ x: 0.796875, y: 0.140625 },
{ x: 0.796875, y: 0.140625 },
{ x: 0.828125, y: 0.140625 },
{ x: 0.828125, y: 0.140625 },
{ x: 0.859375, y: 0.140625 },
{ x: 0.859375, y: 0.140625 },
{ x: 0.890625, y: 0.140625 },
{ x: 0.890625, y: 0.140625 },
{ x: 0.921875, y: 0.140625 },
{ x: 0.921875, y: 0.140625 },
{ x: 0.953125, y: 0.140625 },
{ x: 0.953125, y: 0.140625 },
{ x: 0.984375, y: 0.140625 },
{ x: 0.984375, y: 0.140625 },
{ x: 0.015625, y: 0.171875 },
{ x: 0.015625, y: 0.171875 },
{ x: 0.046875, y: 0.171875 },
{ x: 0.046875, y: 0.171875 },
{ x: 0.078125, y: 0.171875 },
{ x: 0.078125, y: 0.171875 },
{ x: 0.109375, y: 0.171875 },
{ x: 0.109375, y: 0.171875 },
{ x: 0.140625, y: 0.171875 },
{ x: 0.140625, y: 0.171875 },
{ x: 0.171875, y: 0.171875 },
{ x: 0.171875, y: 0.171875 },
{ x: 0.203125, y: 0.171875 },
{ x: 0.203125, y: 0.171875 },
{ x: 0.234375, y: 0.171875 },
{ x: 0.234375, y: 0.171875 },
{ x: 0.265625, y: 0.171875 },
{ x: 0.265625, y: 0.171875 },
{ x: 0.296875, y: 0.171875 },
{ x: 0.296875, y: 0.171875 },
{ x: 0.328125, y: 0.171875 },
{ x: 0.328125, y: 0.171875 },
{ x: 0.359375, y: 0.171875 },
{ x: 0.359375, y: 0.171875 },
{ x: 0.390625, y: 0.171875 },
{ x: 0.390625, y: 0.171875 },
{ x: 0.421875, y: 0.171875 },
{ x: 0.421875, y: 0.171875 },
{ x: 0.453125, y: 0.171875 },
{ x: 0.453125, y: 0.171875 },
{ x: 0.484375, y: 0.171875 },
{ x: 0.484375, y: 0.171875 },
{ x: 0.515625, y: 0.171875 },
{ x: 0.515625, y: 0.171875 },
{ x: 0.546875, y: 0.171875 },
{ x: 0.546875, y: 0.171875 },
{ x: 0.578125, y: 0.171875 },
{ x: 0.578125, y: 0.171875 },
{ x: 0.609375, y: 0.171875 },
{ x: 0.609375, y: 0.171875 },
{ x: 0.640625, y: 0.171875 },
{ x: 0.640625, y: 0.171875 },
{ x: 0.671875, y: 0.171875 },
{ x: 0.671875, y: 0.171875 },
{ x: 0.703125, y: 0.171875 },
{ x: 0.703125, y: 0.171875 },
{ x: 0.734375, y: 0.171875 },
{ x: 0.734375, y: 0.171875 },
{ x: 0.765625, y: 0.171875 },
{ x: 0.765625, y: 0.171875 },
{ x: 0.796875, y: 0.171875 },
{ x: 0.796875, y: 0.171875 },
{ x: 0.828125, y: 0.171875 },
{ x: 0.828125, y: 0.171875 },
{ x: 0.859375, y: 0.171875 },
{ x: 0.859375, y: 0.171875 },
{ x: 0.890625, y: 0.171875 },
{ x: 0.890625, y: 0.171875 },
{ x: 0.921875, y: 0.171875 },
{ x: 0.921875, y: 0.171875 },
{ x: 0.953125, y: 0.171875 },
{ x: 0.953125, y: 0.171875 },
{ x: 0.984375, y: 0.171875 },
{ x: 0.984375, y: 0.171875 },
{ x: 0.015625, y: 0.203125 },
{ x: 0.015625, y: 0.203125 },
{ x: 0.046875, y: 0.203125 },
{ x: 0.046875, y: 0.203125 },
{ x: 0.078125, y: 0.203125 },
{ x: 0.078125, y: 0.203125 },
{ x: 0.109375, y: 0.203125 },
{ x: 0.109375, y: 0.203125 },
{ x: 0.140625, y: 0.203125 },
{ x: 0.140625, y: 0.203125 },
{ x: 0.171875, y: 0.203125 },
{ x: 0.171875, y: 0.203125 },
{ x: 0.203125, y: 0.203125 },
{ x: 0.203125, y: 0.203125 },
{ x: 0.234375, y: 0.203125 },
{ x: 0.234375, y: 0.203125 },
{ x: 0.265625, y: 0.203125 },
{ x: 0.265625, y: 0.203125 },
{ x: 0.296875, y: 0.203125 },
{ x: 0.296875, y: 0.203125 },
{ x: 0.328125, y: 0.203125 },
{ x: 0.328125, y: 0.203125 },
{ x: 0.359375, y: 0.203125 },
{ x: 0.359375, y: 0.203125 },
{ x: 0.390625, y: 0.203125 },
{ x: 0.390625, y: 0.203125 },
{ x: 0.421875, y: 0.203125 },
{ x: 0.421875, y: 0.203125 },
{ x: 0.453125, y: 0.203125 },
{ x: 0.453125, y: 0.203125 },
{ x: 0.484375, y: 0.203125 },
{ x: 0.484375, y: 0.203125 },
{ x: 0.515625, y: 0.203125 },
{ x: 0.515625, y: 0.203125 },
{ x: 0.546875, y: 0.203125 },
{ x: 0.546875, y: 0.203125 },
{ x: 0.578125, y: 0.203125 },
{ x: 0.578125, y: 0.203125 },
{ x: 0.609375, y: 0.203125 },
{ x: 0.609375, y: 0.203125 },
{ x: 0.640625, y: 0.203125 },
{ x: 0.640625, y: 0.203125 },
{ x: 0.671875, y: 0.203125 },
{ x: 0.671875, y: 0.203125 },
{ x: 0.703125, y: 0.203125 },
{ x: 0.703125, y: 0.203125 },
{ x: 0.734375, y: 0.203125 },
{ x: 0.734375, y: 0.203125 },
{ x: 0.765625, y: 0.203125 },
{ x: 0.765625, y: 0.203125 },
{ x: 0.796875, y: 0.203125 },
{ x: 0.796875, y: 0.203125 },
{ x: 0.828125, y: 0.203125 },
{ x: 0.828125, y: 0.203125 },
{ x: 0.859375, y: 0.203125 },
{ x: 0.859375, y: 0.203125 },
{ x: 0.890625, y: 0.203125 },
{ x: 0.890625, y: 0.203125 },
{ x: 0.921875, y: 0.203125 },
{ x: 0.921875, y: 0.203125 },
{ x: 0.953125, y: 0.203125 },
{ x: 0.953125, y: 0.203125 },
{ x: 0.984375, y: 0.203125 },
{ x: 0.984375, y: 0.203125 },
{ x: 0.015625, y: 0.234375 },
{ x: 0.015625, y: 0.234375 },
{ x: 0.046875, y: 0.234375 },
{ x: 0.046875, y: 0.234375 },
{ x: 0.078125, y: 0.234375 },
{ x: 0.078125, y: 0.234375 },
{ x: 0.109375, y: 0.234375 },
{ x: 0.109375, y: 0.234375 },
{ x: 0.140625, y: 0.234375 },
{ x: 0.140625, y: 0.234375 },
{ x: 0.171875, y: 0.234375 },
{ x: 0.171875, y: 0.234375 },
{ x: 0.203125, y: 0.234375 },
{ x: 0.203125, y: 0.234375 },
{ x: 0.234375, y: 0.234375 },
{ x: 0.234375, y: 0.234375 },
{ x: 0.265625, y: 0.234375 },
{ x: 0.265625, y: 0.234375 },
{ x: 0.296875, y: 0.234375 },
{ x: 0.296875, y: 0.234375 },
{ x: 0.328125, y: 0.234375 },
{ x: 0.328125, y: 0.234375 },
{ x: 0.359375, y: 0.234375 },
{ x: 0.359375, y: 0.234375 },
{ x: 0.390625, y: 0.234375 },
{ x: 0.390625, y: 0.234375 },
{ x: 0.421875, y: 0.234375 },
{ x: 0.421875, y: 0.234375 },
{ x: 0.453125, y: 0.234375 },
{ x: 0.453125, y: 0.234375 },
{ x: 0.484375, y: 0.234375 },
{ x: 0.484375, y: 0.234375 },
{ x: 0.515625, y: 0.234375 },
{ x: 0.515625, y: 0.234375 },
{ x: 0.546875, y: 0.234375 },
{ x: 0.546875, y: 0.234375 },
{ x: 0.578125, y: 0.234375 },
{ x: 0.578125, y: 0.234375 },
{ x: 0.609375, y: 0.234375 },
{ x: 0.609375, y: 0.234375 },
{ x: 0.640625, y: 0.234375 },
{ x: 0.640625, y: 0.234375 },
{ x: 0.671875, y: 0.234375 },
{ x: 0.671875, y: 0.234375 },
{ x: 0.703125, y: 0.234375 },
{ x: 0.703125, y: 0.234375 },
{ x: 0.734375, y: 0.234375 },
{ x: 0.734375, y: 0.234375 },
{ x: 0.765625, y: 0.234375 },
{ x: 0.765625, y: 0.234375 },
{ x: 0.796875, y: 0.234375 },
{ x: 0.796875, y: 0.234375 },
{ x: 0.828125, y: 0.234375 },
{ x: 0.828125, y: 0.234375 },
{ x: 0.859375, y: 0.234375 },
{ x: 0.859375, y: 0.234375 },
{ x: 0.890625, y: 0.234375 },
{ x: 0.890625, y: 0.234375 },
{ x: 0.921875, y: 0.234375 },
{ x: 0.921875, y: 0.234375 },
{ x: 0.953125, y: 0.234375 },
{ x: 0.953125, y: 0.234375 },
{ x: 0.984375, y: 0.234375 },
{ x: 0.984375, y: 0.234375 },
{ x: 0.015625, y: 0.265625 },
{ x: 0.015625, y: 0.265625 },
{ x: 0.046875, y: 0.265625 },
{ x: 0.046875, y: 0.265625 },
{ x: 0.078125, y: 0.265625 },
{ x: 0.078125, y: 0.265625 },
{ x: 0.109375, y: 0.265625 },
{ x: 0.109375, y: 0.265625 },
{ x: 0.140625, y: 0.265625 },
{ x: 0.140625, y: 0.265625 },
{ x: 0.171875, y: 0.265625 },
{ x: 0.171875, y: 0.265625 },
{ x: 0.203125, y: 0.265625 },
{ x: 0.203125, y: 0.265625 },
{ x: 0.234375, y: 0.265625 },
{ x: 0.234375, y: 0.265625 },
{ x: 0.265625, y: 0.265625 },
{ x: 0.265625, y: 0.265625 },
{ x: 0.296875, y: 0.265625 },
{ x: 0.296875, y: 0.265625 },
{ x: 0.328125, y: 0.265625 },
{ x: 0.328125, y: 0.265625 },
{ x: 0.359375, y: 0.265625 },
{ x: 0.359375, y: 0.265625 },
{ x: 0.390625, y: 0.265625 },
{ x: 0.390625, y: 0.265625 },
{ x: 0.421875, y: 0.265625 },
{ x: 0.421875, y: 0.265625 },
{ x: 0.453125, y: 0.265625 },
{ x: 0.453125, y: 0.265625 },
{ x: 0.484375, y: 0.265625 },
{ x: 0.484375, y: 0.265625 },
{ x: 0.515625, y: 0.265625 },
{ x: 0.515625, y: 0.265625 },
{ x: 0.546875, y: 0.265625 },
{ x: 0.546875, y: 0.265625 },
{ x: 0.578125, y: 0.265625 },
{ x: 0.578125, y: 0.265625 },
{ x: 0.609375, y: 0.265625 },
{ x: 0.609375, y: 0.265625 },
{ x: 0.640625, y: 0.265625 },
{ x: 0.640625, y: 0.265625 },
{ x: 0.671875, y: 0.265625 },
{ x: 0.671875, y: 0.265625 },
{ x: 0.703125, y: 0.265625 },
{ x: 0.703125, y: 0.265625 },
{ x: 0.734375, y: 0.265625 },
{ x: 0.734375, y: 0.265625 },
{ x: 0.765625, y: 0.265625 },
{ x: 0.765625, y: 0.265625 },
{ x: 0.796875, y: 0.265625 },
{ x: 0.796875, y: 0.265625 },
{ x: 0.828125, y: 0.265625 },
{ x: 0.828125, y: 0.265625 },
{ x: 0.859375, y: 0.265625 },
{ x: 0.859375, y: 0.265625 },
{ x: 0.890625, y: 0.265625 },
{ x: 0.890625, y: 0.265625 },
{ x: 0.921875, y: 0.265625 },
{ x: 0.921875, y: 0.265625 },
{ x: 0.953125, y: 0.265625 },
{ x: 0.953125, y: 0.265625 },
{ x: 0.984375, y: 0.265625 },
{ x: 0.984375, y: 0.265625 },
{ x: 0.015625, y: 0.296875 },
{ x: 0.015625, y: 0.296875 },
{ x: 0.046875, y: 0.296875 },
{ x: 0.046875, y: 0.296875 },
{ x: 0.078125, y: 0.296875 },
{ x: 0.078125, y: 0.296875 },
{ x: 0.109375, y: 0.296875 },
{ x: 0.109375, y: 0.296875 },
{ x: 0.140625, y: 0.296875 },
{ x: 0.140625, y: 0.296875 },
{ x: 0.171875, y: 0.296875 },
{ x: 0.171875, y: 0.296875 },
{ x: 0.203125, y: 0.296875 },
{ x: 0.203125, y: 0.296875 },
{ x: 0.234375, y: 0.296875 },
{ x: 0.234375, y: 0.296875 },
{ x: 0.265625, y: 0.296875 },
{ x: 0.265625, y: 0.296875 },
{ x: 0.296875, y: 0.296875 },
{ x: 0.296875, y: 0.296875 },
{ x: 0.328125, y: 0.296875 },
{ x: 0.328125, y: 0.296875 },
{ x: 0.359375, y: 0.296875 },
{ x: 0.359375, y: 0.296875 },
{ x: 0.390625, y: 0.296875 },
{ x: 0.390625, y: 0.296875 },
{ x: 0.421875, y: 0.296875 },
{ x: 0.421875, y: 0.296875 },
{ x: 0.453125, y: 0.296875 },
{ x: 0.453125, y: 0.296875 },
{ x: 0.484375, y: 0.296875 },
{ x: 0.484375, y: 0.296875 },
{ x: 0.515625, y: 0.296875 },
{ x: 0.515625, y: 0.296875 },
{ x: 0.546875, y: 0.296875 },
{ x: 0.546875, y: 0.296875 },
{ x: 0.578125, y: 0.296875 },
{ x: 0.578125, y: 0.296875 },
{ x: 0.609375, y: 0.296875 },
{ x: 0.609375, y: 0.296875 },
{ x: 0.640625, y: 0.296875 },
{ x: 0.640625, y: 0.296875 },
{ x: 0.671875, y: 0.296875 },
{ x: 0.671875, y: 0.296875 },
{ x: 0.703125, y: 0.296875 },
{ x: 0.703125, y: 0.296875 },
{ x: 0.734375, y: 0.296875 },
{ x: 0.734375, y: 0.296875 },
{ x: 0.765625, y: 0.296875 },
{ x: 0.765625, y: 0.296875 },
{ x: 0.796875, y: 0.296875 },
{ x: 0.796875, y: 0.296875 },
{ x: 0.828125, y: 0.296875 },
{ x: 0.828125, y: 0.296875 },
{ x: 0.859375, y: 0.296875 },
{ x: 0.859375, y: 0.296875 },
{ x: 0.890625, y: 0.296875 },
{ x: 0.890625, y: 0.296875 },
{ x: 0.921875, y: 0.296875 },
{ x: 0.921875, y: 0.296875 },
{ x: 0.953125, y: 0.296875 },
{ x: 0.953125, y: 0.296875 },
{ x: 0.984375, y: 0.296875 },
{ x: 0.984375, y: 0.296875 },
{ x: 0.015625, y: 0.328125 },
{ x: 0.015625, y: 0.328125 },
{ x: 0.046875, y: 0.328125 },
{ x: 0.046875, y: 0.328125 },
{ x: 0.078125, y: 0.328125 },
{ x: 0.078125, y: 0.328125 },
{ x: 0.109375, y: 0.328125 },
{ x: 0.109375, y: 0.328125 },
{ x: 0.140625, y: 0.328125 },
{ x: 0.140625, y: 0.328125 },
{ x: 0.171875, y: 0.328125 },
{ x: 0.171875, y: 0.328125 },
{ x: 0.203125, y: 0.328125 },
{ x: 0.203125, y: 0.328125 },
{ x: 0.234375, y: 0.328125 },
{ x: 0.234375, y: 0.328125 },
{ x: 0.265625, y: 0.328125 },
{ x: 0.265625, y: 0.328125 },
{ x: 0.296875, y: 0.328125 },
{ x: 0.296875, y: 0.328125 },
{ x: 0.328125, y: 0.328125 },
{ x: 0.328125, y: 0.328125 },
{ x: 0.359375, y: 0.328125 },
{ x: 0.359375, y: 0.328125 },
{ x: 0.390625, y: 0.328125 },
{ x: 0.390625, y: 0.328125 },
{ x: 0.421875, y: 0.328125 },
{ x: 0.421875, y: 0.328125 },
{ x: 0.453125, y: 0.328125 },
{ x: 0.453125, y: 0.328125 },
{ x: 0.484375, y: 0.328125 },
{ x: 0.484375, y: 0.328125 },
{ x: 0.515625, y: 0.328125 },
{ x: 0.515625, y: 0.328125 },
{ x: 0.546875, y: 0.328125 },
{ x: 0.546875, y: 0.328125 },
{ x: 0.578125, y: 0.328125 },
{ x: 0.578125, y: 0.328125 },
{ x: 0.609375, y: 0.328125 },
{ x: 0.609375, y: 0.328125 },
{ x: 0.640625, y: 0.328125 },
{ x: 0.640625, y: 0.328125 },
{ x: 0.671875, y: 0.328125 },
{ x: 0.671875, y: 0.328125 },
{ x: 0.703125, y: 0.328125 },
{ x: 0.703125, y: 0.328125 },
{ x: 0.734375, y: 0.328125 },
{ x: 0.734375, y: 0.328125 },
{ x: 0.765625, y: 0.328125 },
{ x: 0.765625, y: 0.328125 },
{ x: 0.796875, y: 0.328125 },
{ x: 0.796875, y: 0.328125 },
{ x: 0.828125, y: 0.328125 },
{ x: 0.828125, y: 0.328125 },
{ x: 0.859375, y: 0.328125 },
{ x: 0.859375, y: 0.328125 },
{ x: 0.890625, y: 0.328125 },
{ x: 0.890625, y: 0.328125 },
{ x: 0.921875, y: 0.328125 },
{ x: 0.921875, y: 0.328125 },
{ x: 0.953125, y: 0.328125 },
{ x: 0.953125, y: 0.328125 },
{ x: 0.984375, y: 0.328125 },
{ x: 0.984375, y: 0.328125 },
{ x: 0.015625, y: 0.359375 },
{ x: 0.015625, y: 0.359375 },
{ x: 0.046875, y: 0.359375 },
{ x: 0.046875, y: 0.359375 },
{ x: 0.078125, y: 0.359375 },
{ x: 0.078125, y: 0.359375 },
{ x: 0.109375, y: 0.359375 },
{ x: 0.109375, y: 0.359375 },
{ x: 0.140625, y: 0.359375 },
{ x: 0.140625, y: 0.359375 },
{ x: 0.171875, y: 0.359375 },
{ x: 0.171875, y: 0.359375 },
{ x: 0.203125, y: 0.359375 },
{ x: 0.203125, y: 0.359375 },
{ x: 0.234375, y: 0.359375 },
{ x: 0.234375, y: 0.359375 },
{ x: 0.265625, y: 0.359375 },
{ x: 0.265625, y: 0.359375 },
{ x: 0.296875, y: 0.359375 },
{ x: 0.296875, y: 0.359375 },
{ x: 0.328125, y: 0.359375 },
{ x: 0.328125, y: 0.359375 },
{ x: 0.359375, y: 0.359375 },
{ x: 0.359375, y: 0.359375 },
{ x: 0.390625, y: 0.359375 },
{ x: 0.390625, y: 0.359375 },
{ x: 0.421875, y: 0.359375 },
{ x: 0.421875, y: 0.359375 },
{ x: 0.453125, y: 0.359375 },
{ x: 0.453125, y: 0.359375 },
{ x: 0.484375, y: 0.359375 },
{ x: 0.484375, y: 0.359375 },
{ x: 0.515625, y: 0.359375 },
{ x: 0.515625, y: 0.359375 },
{ x: 0.546875, y: 0.359375 },
{ x: 0.546875, y: 0.359375 },
{ x: 0.578125, y: 0.359375 },
{ x: 0.578125, y: 0.359375 },
{ x: 0.609375, y: 0.359375 },
{ x: 0.609375, y: 0.359375 },
{ x: 0.640625, y: 0.359375 },
{ x: 0.640625, y: 0.359375 },
{ x: 0.671875, y: 0.359375 },
{ x: 0.671875, y: 0.359375 },
{ x: 0.703125, y: 0.359375 },
{ x: 0.703125, y: 0.359375 },
{ x: 0.734375, y: 0.359375 },
{ x: 0.734375, y: 0.359375 },
{ x: 0.765625, y: 0.359375 },
{ x: 0.765625, y: 0.359375 },
{ x: 0.796875, y: 0.359375 },
{ x: 0.796875, y: 0.359375 },
{ x: 0.828125, y: 0.359375 },
{ x: 0.828125, y: 0.359375 },
{ x: 0.859375, y: 0.359375 },
{ x: 0.859375, y: 0.359375 },
{ x: 0.890625, y: 0.359375 },
{ x: 0.890625, y: 0.359375 },
{ x: 0.921875, y: 0.359375 },
{ x: 0.921875, y: 0.359375 },
{ x: 0.953125, y: 0.359375 },
{ x: 0.953125, y: 0.359375 },
{ x: 0.984375, y: 0.359375 },
{ x: 0.984375, y: 0.359375 },
{ x: 0.015625, y: 0.390625 },
{ x: 0.015625, y: 0.390625 },
{ x: 0.046875, y: 0.390625 },
{ x: 0.046875, y: 0.390625 },
{ x: 0.078125, y: 0.390625 },
{ x: 0.078125, y: 0.390625 },
{ x: 0.109375, y: 0.390625 },
{ x: 0.109375, y: 0.390625 },
{ x: 0.140625, y: 0.390625 },
{ x: 0.140625, y: 0.390625 },
{ x: 0.171875, y: 0.390625 },
{ x: 0.171875, y: 0.390625 },
{ x: 0.203125, y: 0.390625 },
{ x: 0.203125, y: 0.390625 },
{ x: 0.234375, y: 0.390625 },
{ x: 0.234375, y: 0.390625 },
{ x: 0.265625, y: 0.390625 },
{ x: 0.265625, y: 0.390625 },
{ x: 0.296875, y: 0.390625 },
{ x: 0.296875, y: 0.390625 },
{ x: 0.328125, y: 0.390625 },
{ x: 0.328125, y: 0.390625 },
{ x: 0.359375, y: 0.390625 },
{ x: 0.359375, y: 0.390625 },
{ x: 0.390625, y: 0.390625 },
{ x: 0.390625, y: 0.390625 },
{ x: 0.421875, y: 0.390625 },
{ x: 0.421875, y: 0.390625 },
{ x: 0.453125, y: 0.390625 },
{ x: 0.453125, y: 0.390625 },
{ x: 0.484375, y: 0.390625 },
{ x: 0.484375, y: 0.390625 },
{ x: 0.515625, y: 0.390625 },
{ x: 0.515625, y: 0.390625 },
{ x: 0.546875, y: 0.390625 },
{ x: 0.546875, y: 0.390625 },
{ x: 0.578125, y: 0.390625 },
{ x: 0.578125, y: 0.390625 },
{ x: 0.609375, y: 0.390625 },
{ x: 0.609375, y: 0.390625 },
{ x: 0.640625, y: 0.390625 },
{ x: 0.640625, y: 0.390625 },
{ x: 0.671875, y: 0.390625 },
{ x: 0.671875, y: 0.390625 },
{ x: 0.703125, y: 0.390625 },
{ x: 0.703125, y: 0.390625 },
{ x: 0.734375, y: 0.390625 },
{ x: 0.734375, y: 0.390625 },
{ x: 0.765625, y: 0.390625 },
{ x: 0.765625, y: 0.390625 },
{ x: 0.796875, y: 0.390625 },
{ x: 0.796875, y: 0.390625 },
{ x: 0.828125, y: 0.390625 },
{ x: 0.828125, y: 0.390625 },
{ x: 0.859375, y: 0.390625 },
{ x: 0.859375, y: 0.390625 },
{ x: 0.890625, y: 0.390625 },
{ x: 0.890625, y: 0.390625 },
{ x: 0.921875, y: 0.390625 },
{ x: 0.921875, y: 0.390625 },
{ x: 0.953125, y: 0.390625 },
{ x: 0.953125, y: 0.390625 },
{ x: 0.984375, y: 0.390625 },
{ x: 0.984375, y: 0.390625 },
{ x: 0.015625, y: 0.421875 },
{ x: 0.015625, y: 0.421875 },
{ x: 0.046875, y: 0.421875 },
{ x: 0.046875, y: 0.421875 },
{ x: 0.078125, y: 0.421875 },
{ x: 0.078125, y: 0.421875 },
{ x: 0.109375, y: 0.421875 },
{ x: 0.109375, y: 0.421875 },
{ x: 0.140625, y: 0.421875 },
{ x: 0.140625, y: 0.421875 },
{ x: 0.171875, y: 0.421875 },
{ x: 0.171875, y: 0.421875 },
{ x: 0.203125, y: 0.421875 },
{ x: 0.203125, y: 0.421875 },
{ x: 0.234375, y: 0.421875 },
{ x: 0.234375, y: 0.421875 },
{ x: 0.265625, y: 0.421875 },
{ x: 0.265625, y: 0.421875 },
{ x: 0.296875, y: 0.421875 },
{ x: 0.296875, y: 0.421875 },
{ x: 0.328125, y: 0.421875 },
{ x: 0.328125, y: 0.421875 },
{ x: 0.359375, y: 0.421875 },
{ x: 0.359375, y: 0.421875 },
{ x: 0.390625, y: 0.421875 },
{ x: 0.390625, y: 0.421875 },
{ x: 0.421875, y: 0.421875 },
{ x: 0.421875, y: 0.421875 },
{ x: 0.453125, y: 0.421875 },
{ x: 0.453125, y: 0.421875 },
{ x: 0.484375, y: 0.421875 },
{ x: 0.484375, y: 0.421875 },
{ x: 0.515625, y: 0.421875 },
{ x: 0.515625, y: 0.421875 },
{ x: 0.546875, y: 0.421875 },
{ x: 0.546875, y: 0.421875 },
{ x: 0.578125, y: 0.421875 },
{ x: 0.578125, y: 0.421875 },
{ x: 0.609375, y: 0.421875 },
{ x: 0.609375, y: 0.421875 },
{ x: 0.640625, y: 0.421875 },
{ x: 0.640625, y: 0.421875 },
{ x: 0.671875, y: 0.421875 },
{ x: 0.671875, y: 0.421875 },
{ x: 0.703125, y: 0.421875 },
{ x: 0.703125, y: 0.421875 },
{ x: 0.734375, y: 0.421875 },
{ x: 0.734375, y: 0.421875 },
{ x: 0.765625, y: 0.421875 },
{ x: 0.765625, y: 0.421875 },
{ x: 0.796875, y: 0.421875 },
{ x: 0.796875, y: 0.421875 },
{ x: 0.828125, y: 0.421875 },
{ x: 0.828125, y: 0.421875 },
{ x: 0.859375, y: 0.421875 },
{ x: 0.859375, y: 0.421875 },
{ x: 0.890625, y: 0.421875 },
{ x: 0.890625, y: 0.421875 },
{ x: 0.921875, y: 0.421875 },
{ x: 0.921875, y: 0.421875 },
{ x: 0.953125, y: 0.421875 },
{ x: 0.953125, y: 0.421875 },
{ x: 0.984375, y: 0.421875 },
{ x: 0.984375, y: 0.421875 },
{ x: 0.015625, y: 0.453125 },
{ x: 0.015625, y: 0.453125 },
{ x: 0.046875, y: 0.453125 },
{ x: 0.046875, y: 0.453125 },
{ x: 0.078125, y: 0.453125 },
{ x: 0.078125, y: 0.453125 },
{ x: 0.109375, y: 0.453125 },
{ x: 0.109375, y: 0.453125 },
{ x: 0.140625, y: 0.453125 },
{ x: 0.140625, y: 0.453125 },
{ x: 0.171875, y: 0.453125 },
{ x: 0.171875, y: 0.453125 },
{ x: 0.203125, y: 0.453125 },
{ x: 0.203125, y: 0.453125 },
{ x: 0.234375, y: 0.453125 },
{ x: 0.234375, y: 0.453125 },
{ x: 0.265625, y: 0.453125 },
{ x: 0.265625, y: 0.453125 },
{ x: 0.296875, y: 0.453125 },
{ x: 0.296875, y: 0.453125 },
{ x: 0.328125, y: 0.453125 },
{ x: 0.328125, y: 0.453125 },
{ x: 0.359375, y: 0.453125 },
{ x: 0.359375, y: 0.453125 },
{ x: 0.390625, y: 0.453125 },
{ x: 0.390625, y: 0.453125 },
{ x: 0.421875, y: 0.453125 },
{ x: 0.421875, y: 0.453125 },
{ x: 0.453125, y: 0.453125 },
{ x: 0.453125, y: 0.453125 },
{ x: 0.484375, y: 0.453125 },
{ x: 0.484375, y: 0.453125 },
{ x: 0.515625, y: 0.453125 },
{ x: 0.515625, y: 0.453125 },
{ x: 0.546875, y: 0.453125 },
{ x: 0.546875, y: 0.453125 },
{ x: 0.578125, y: 0.453125 },
{ x: 0.578125, y: 0.453125 },
{ x: 0.609375, y: 0.453125 },
{ x: 0.609375, y: 0.453125 },
{ x: 0.640625, y: 0.453125 },
{ x: 0.640625, y: 0.453125 },
{ x: 0.671875, y: 0.453125 },
{ x: 0.671875, y: 0.453125 },
{ x: 0.703125, y: 0.453125 },
{ x: 0.703125, y: 0.453125 },
{ x: 0.734375, y: 0.453125 },
{ x: 0.734375, y: 0.453125 },
{ x: 0.765625, y: 0.453125 },
{ x: 0.765625, y: 0.453125 },
{ x: 0.796875, y: 0.453125 },
{ x: 0.796875, y: 0.453125 },
{ x: 0.828125, y: 0.453125 },
{ x: 0.828125, y: 0.453125 },
{ x: 0.859375, y: 0.453125 },
{ x: 0.859375, y: 0.453125 },
{ x: 0.890625, y: 0.453125 },
{ x: 0.890625, y: 0.453125 },
{ x: 0.921875, y: 0.453125 },
{ x: 0.921875, y: 0.453125 },
{ x: 0.953125, y: 0.453125 },
{ x: 0.953125, y: 0.453125 },
{ x: 0.984375, y: 0.453125 },
{ x: 0.984375, y: 0.453125 },
{ x: 0.015625, y: 0.484375 },
{ x: 0.015625, y: 0.484375 },
{ x: 0.046875, y: 0.484375 },
{ x: 0.046875, y: 0.484375 },
{ x: 0.078125, y: 0.484375 },
{ x: 0.078125, y: 0.484375 },
{ x: 0.109375, y: 0.484375 },
{ x: 0.109375, y: 0.484375 },
{ x: 0.140625, y: 0.484375 },
{ x: 0.140625, y: 0.484375 },
{ x: 0.171875, y: 0.484375 },
{ x: 0.171875, y: 0.484375 },
{ x: 0.203125, y: 0.484375 },
{ x: 0.203125, y: 0.484375 },
{ x: 0.234375, y: 0.484375 },
{ x: 0.234375, y: 0.484375 },
{ x: 0.265625, y: 0.484375 },
{ x: 0.265625, y: 0.484375 },
{ x: 0.296875, y: 0.484375 },
{ x: 0.296875, y: 0.484375 },
{ x: 0.328125, y: 0.484375 },
{ x: 0.328125, y: 0.484375 },
{ x: 0.359375, y: 0.484375 },
{ x: 0.359375, y: 0.484375 },
{ x: 0.390625, y: 0.484375 },
{ x: 0.390625, y: 0.484375 },
{ x: 0.421875, y: 0.484375 },
{ x: 0.421875, y: 0.484375 },
{ x: 0.453125, y: 0.484375 },
{ x: 0.453125, y: 0.484375 },
{ x: 0.484375, y: 0.484375 },
{ x: 0.484375, y: 0.484375 },
{ x: 0.515625, y: 0.484375 },
{ x: 0.515625, y: 0.484375 },
{ x: 0.546875, y: 0.484375 },
{ x: 0.546875, y: 0.484375 },
{ x: 0.578125, y: 0.484375 },
{ x: 0.578125, y: 0.484375 },
{ x: 0.609375, y: 0.484375 },
{ x: 0.609375, y: 0.484375 },
{ x: 0.640625, y: 0.484375 },
{ x: 0.640625, y: 0.484375 },
{ x: 0.671875, y: 0.484375 },
{ x: 0.671875, y: 0.484375 },
{ x: 0.703125, y: 0.484375 },
{ x: 0.703125, y: 0.484375 },
{ x: 0.734375, y: 0.484375 },
{ x: 0.734375, y: 0.484375 },
{ x: 0.765625, y: 0.484375 },
{ x: 0.765625, y: 0.484375 },
{ x: 0.796875, y: 0.484375 },
{ x: 0.796875, y: 0.484375 },
{ x: 0.828125, y: 0.484375 },
{ x: 0.828125, y: 0.484375 },
{ x: 0.859375, y: 0.484375 },
{ x: 0.859375, y: 0.484375 },
{ x: 0.890625, y: 0.484375 },
{ x: 0.890625, y: 0.484375 },
{ x: 0.921875, y: 0.484375 },
{ x: 0.921875, y: 0.484375 },
{ x: 0.953125, y: 0.484375 },
{ x: 0.953125, y: 0.484375 },
{ x: 0.984375, y: 0.484375 },
{ x: 0.984375, y: 0.484375 },
{ x: 0.015625, y: 0.515625 },
{ x: 0.015625, y: 0.515625 },
{ x: 0.046875, y: 0.515625 },
{ x: 0.046875, y: 0.515625 },
{ x: 0.078125, y: 0.515625 },
{ x: 0.078125, y: 0.515625 },
{ x: 0.109375, y: 0.515625 },
{ x: 0.109375, y: 0.515625 },
{ x: 0.140625, y: 0.515625 },
{ x: 0.140625, y: 0.515625 },
{ x: 0.171875, y: 0.515625 },
{ x: 0.171875, y: 0.515625 },
{ x: 0.203125, y: 0.515625 },
{ x: 0.203125, y: 0.515625 },
{ x: 0.234375, y: 0.515625 },
{ x: 0.234375, y: 0.515625 },
{ x: 0.265625, y: 0.515625 },
{ x: 0.265625, y: 0.515625 },
{ x: 0.296875, y: 0.515625 },
{ x: 0.296875, y: 0.515625 },
{ x: 0.328125, y: 0.515625 },
{ x: 0.328125, y: 0.515625 },
{ x: 0.359375, y: 0.515625 },
{ x: 0.359375, y: 0.515625 },
{ x: 0.390625, y: 0.515625 },
{ x: 0.390625, y: 0.515625 },
{ x: 0.421875, y: 0.515625 },
{ x: 0.421875, y: 0.515625 },
{ x: 0.453125, y: 0.515625 },
{ x: 0.453125, y: 0.515625 },
{ x: 0.484375, y: 0.515625 },
{ x: 0.484375, y: 0.515625 },
{ x: 0.515625, y: 0.515625 },
{ x: 0.515625, y: 0.515625 },
{ x: 0.546875, y: 0.515625 },
{ x: 0.546875, y: 0.515625 },
{ x: 0.578125, y: 0.515625 },
{ x: 0.578125, y: 0.515625 },
{ x: 0.609375, y: 0.515625 },
{ x: 0.609375, y: 0.515625 },
{ x: 0.640625, y: 0.515625 },
{ x: 0.640625, y: 0.515625 },
{ x: 0.671875, y: 0.515625 },
{ x: 0.671875, y: 0.515625 },
{ x: 0.703125, y: 0.515625 },
{ x: 0.703125, y: 0.515625 },
{ x: 0.734375, y: 0.515625 },
{ x: 0.734375, y: 0.515625 },
{ x: 0.765625, y: 0.515625 },
{ x: 0.765625, y: 0.515625 },
{ x: 0.796875, y: 0.515625 },
{ x: 0.796875, y: 0.515625 },
{ x: 0.828125, y: 0.515625 },
{ x: 0.828125, y: 0.515625 },
{ x: 0.859375, y: 0.515625 },
{ x: 0.859375, y: 0.515625 },
{ x: 0.890625, y: 0.515625 },
{ x: 0.890625, y: 0.515625 },
{ x: 0.921875, y: 0.515625 },
{ x: 0.921875, y: 0.515625 },
{ x: 0.953125, y: 0.515625 },
{ x: 0.953125, y: 0.515625 },
{ x: 0.984375, y: 0.515625 },
{ x: 0.984375, y: 0.515625 },
{ x: 0.015625, y: 0.546875 },
{ x: 0.015625, y: 0.546875 },
{ x: 0.046875, y: 0.546875 },
{ x: 0.046875, y: 0.546875 },
{ x: 0.078125, y: 0.546875 },
{ x: 0.078125, y: 0.546875 },
{ x: 0.109375, y: 0.546875 },
{ x: 0.109375, y: 0.546875 },
{ x: 0.140625, y: 0.546875 },
{ x: 0.140625, y: 0.546875 },
{ x: 0.171875, y: 0.546875 },
{ x: 0.171875, y: 0.546875 },
{ x: 0.203125, y: 0.546875 },
{ x: 0.203125, y: 0.546875 },
{ x: 0.234375, y: 0.546875 },
{ x: 0.234375, y: 0.546875 },
{ x: 0.265625, y: 0.546875 },
{ x: 0.265625, y: 0.546875 },
{ x: 0.296875, y: 0.546875 },
{ x: 0.296875, y: 0.546875 },
{ x: 0.328125, y: 0.546875 },
{ x: 0.328125, y: 0.546875 },
{ x: 0.359375, y: 0.546875 },
{ x: 0.359375, y: 0.546875 },
{ x: 0.390625, y: 0.546875 },
{ x: 0.390625, y: 0.546875 },
{ x: 0.421875, y: 0.546875 },
{ x: 0.421875, y: 0.546875 },
{ x: 0.453125, y: 0.546875 },
{ x: 0.453125, y: 0.546875 },
{ x: 0.484375, y: 0.546875 },
{ x: 0.484375, y: 0.546875 },
{ x: 0.515625, y: 0.546875 },
{ x: 0.515625, y: 0.546875 },
{ x: 0.546875, y: 0.546875 },
{ x: 0.546875, y: 0.546875 },
{ x: 0.578125, y: 0.546875 },
{ x: 0.578125, y: 0.546875 },
{ x: 0.609375, y: 0.546875 },
{ x: 0.609375, y: 0.546875 },
{ x: 0.640625, y: 0.546875 },
{ x: 0.640625, y: 0.546875 },
{ x: 0.671875, y: 0.546875 },
{ x: 0.671875, y: 0.546875 },
{ x: 0.703125, y: 0.546875 },
{ x: 0.703125, y: 0.546875 },
{ x: 0.734375, y: 0.546875 },
{ x: 0.734375, y: 0.546875 },
{ x: 0.765625, y: 0.546875 },
{ x: 0.765625, y: 0.546875 },
{ x: 0.796875, y: 0.546875 },
{ x: 0.796875, y: 0.546875 },
{ x: 0.828125, y: 0.546875 },
{ x: 0.828125, y: 0.546875 },
{ x: 0.859375, y: 0.546875 },
{ x: 0.859375, y: 0.546875 },
{ x: 0.890625, y: 0.546875 },
{ x: 0.890625, y: 0.546875 },
{ x: 0.921875, y: 0.546875 },
{ x: 0.921875, y: 0.546875 },
{ x: 0.953125, y: 0.546875 },
{ x: 0.953125, y: 0.546875 },
{ x: 0.984375, y: 0.546875 },
{ x: 0.984375, y: 0.546875 },
{ x: 0.015625, y: 0.578125 },
{ x: 0.015625, y: 0.578125 },
{ x: 0.046875, y: 0.578125 },
{ x: 0.046875, y: 0.578125 },
{ x: 0.078125, y: 0.578125 },
{ x: 0.078125, y: 0.578125 },
{ x: 0.109375, y: 0.578125 },
{ x: 0.109375, y: 0.578125 },
{ x: 0.140625, y: 0.578125 },
{ x: 0.140625, y: 0.578125 },
{ x: 0.171875, y: 0.578125 },
{ x: 0.171875, y: 0.578125 },
{ x: 0.203125, y: 0.578125 },
{ x: 0.203125, y: 0.578125 },
{ x: 0.234375, y: 0.578125 },
{ x: 0.234375, y: 0.578125 },
{ x: 0.265625, y: 0.578125 },
{ x: 0.265625, y: 0.578125 },
{ x: 0.296875, y: 0.578125 },
{ x: 0.296875, y: 0.578125 },
{ x: 0.328125, y: 0.578125 },
{ x: 0.328125, y: 0.578125 },
{ x: 0.359375, y: 0.578125 },
{ x: 0.359375, y: 0.578125 },
{ x: 0.390625, y: 0.578125 },
{ x: 0.390625, y: 0.578125 },
{ x: 0.421875, y: 0.578125 },
{ x: 0.421875, y: 0.578125 },
{ x: 0.453125, y: 0.578125 },
{ x: 0.453125, y: 0.578125 },
{ x: 0.484375, y: 0.578125 },
{ x: 0.484375, y: 0.578125 },
{ x: 0.515625, y: 0.578125 },
{ x: 0.515625, y: 0.578125 },
{ x: 0.546875, y: 0.578125 },
{ x: 0.546875, y: 0.578125 },
{ x: 0.578125, y: 0.578125 },
{ x: 0.578125, y: 0.578125 },
{ x: 0.609375, y: 0.578125 },
{ x: 0.609375, y: 0.578125 },
{ x: 0.640625, y: 0.578125 },
{ x: 0.640625, y: 0.578125 },
{ x: 0.671875, y: 0.578125 },
{ x: 0.671875, y: 0.578125 },
{ x: 0.703125, y: 0.578125 },
{ x: 0.703125, y: 0.578125 },
{ x: 0.734375, y: 0.578125 },
{ x: 0.734375, y: 0.578125 },
{ x: 0.765625, y: 0.578125 },
{ x: 0.765625, y: 0.578125 },
{ x: 0.796875, y: 0.578125 },
{ x: 0.796875, y: 0.578125 },
{ x: 0.828125, y: 0.578125 },
{ x: 0.828125, y: 0.578125 },
{ x: 0.859375, y: 0.578125 },
{ x: 0.859375, y: 0.578125 },
{ x: 0.890625, y: 0.578125 },
{ x: 0.890625, y: 0.578125 },
{ x: 0.921875, y: 0.578125 },
{ x: 0.921875, y: 0.578125 },
{ x: 0.953125, y: 0.578125 },
{ x: 0.953125, y: 0.578125 },
{ x: 0.984375, y: 0.578125 },
{ x: 0.984375, y: 0.578125 },
{ x: 0.015625, y: 0.609375 },
{ x: 0.015625, y: 0.609375 },
{ x: 0.046875, y: 0.609375 },
{ x: 0.046875, y: 0.609375 },
{ x: 0.078125, y: 0.609375 },
{ x: 0.078125, y: 0.609375 },
{ x: 0.109375, y: 0.609375 },
{ x: 0.109375, y: 0.609375 },
{ x: 0.140625, y: 0.609375 },
{ x: 0.140625, y: 0.609375 },
{ x: 0.171875, y: 0.609375 },
{ x: 0.171875, y: 0.609375 },
{ x: 0.203125, y: 0.609375 },
{ x: 0.203125, y: 0.609375 },
{ x: 0.234375, y: 0.609375 },
{ x: 0.234375, y: 0.609375 },
{ x: 0.265625, y: 0.609375 },
{ x: 0.265625, y: 0.609375 },
{ x: 0.296875, y: 0.609375 },
{ x: 0.296875, y: 0.609375 },
{ x: 0.328125, y: 0.609375 },
{ x: 0.328125, y: 0.609375 },
{ x: 0.359375, y: 0.609375 },
{ x: 0.359375, y: 0.609375 },
{ x: 0.390625, y: 0.609375 },
{ x: 0.390625, y: 0.609375 },
{ x: 0.421875, y: 0.609375 },
{ x: 0.421875, y: 0.609375 },
{ x: 0.453125, y: 0.609375 },
{ x: 0.453125, y: 0.609375 },
{ x: 0.484375, y: 0.609375 },
{ x: 0.484375, y: 0.609375 },
{ x: 0.515625, y: 0.609375 },
{ x: 0.515625, y: 0.609375 },
{ x: 0.546875, y: 0.609375 },
{ x: 0.546875, y: 0.609375 },
{ x: 0.578125, y: 0.609375 },
{ x: 0.578125, y: 0.609375 },
{ x: 0.609375, y: 0.609375 },
{ x: 0.609375, y: 0.609375 },
{ x: 0.640625, y: 0.609375 },
{ x: 0.640625, y: 0.609375 },
{ x: 0.671875, y: 0.609375 },
{ x: 0.671875, y: 0.609375 },
{ x: 0.703125, y: 0.609375 },
{ x: 0.703125, y: 0.609375 },
{ x: 0.734375, y: 0.609375 },
{ x: 0.734375, y: 0.609375 },
{ x: 0.765625, y: 0.609375 },
{ x: 0.765625, y: 0.609375 },
{ x: 0.796875, y: 0.609375 },
{ x: 0.796875, y: 0.609375 },
{ x: 0.828125, y: 0.609375 },
{ x: 0.828125, y: 0.609375 },
{ x: 0.859375, y: 0.609375 },
{ x: 0.859375, y: 0.609375 },
{ x: 0.890625, y: 0.609375 },
{ x: 0.890625, y: 0.609375 },
{ x: 0.921875, y: 0.609375 },
{ x: 0.921875, y: 0.609375 },
{ x: 0.953125, y: 0.609375 },
{ x: 0.953125, y: 0.609375 },
{ x: 0.984375, y: 0.609375 },
{ x: 0.984375, y: 0.609375 },
{ x: 0.015625, y: 0.640625 },
{ x: 0.015625, y: 0.640625 },
{ x: 0.046875, y: 0.640625 },
{ x: 0.046875, y: 0.640625 },
{ x: 0.078125, y: 0.640625 },
{ x: 0.078125, y: 0.640625 },
{ x: 0.109375, y: 0.640625 },
{ x: 0.109375, y: 0.640625 },
{ x: 0.140625, y: 0.640625 },
{ x: 0.140625, y: 0.640625 },
{ x: 0.171875, y: 0.640625 },
{ x: 0.171875, y: 0.640625 },
{ x: 0.203125, y: 0.640625 },
{ x: 0.203125, y: 0.640625 },
{ x: 0.234375, y: 0.640625 },
{ x: 0.234375, y: 0.640625 },
{ x: 0.265625, y: 0.640625 },
{ x: 0.265625, y: 0.640625 },
{ x: 0.296875, y: 0.640625 },
{ x: 0.296875, y: 0.640625 },
{ x: 0.328125, y: 0.640625 },
{ x: 0.328125, y: 0.640625 },
{ x: 0.359375, y: 0.640625 },
{ x: 0.359375, y: 0.640625 },
{ x: 0.390625, y: 0.640625 },
{ x: 0.390625, y: 0.640625 },
{ x: 0.421875, y: 0.640625 },
{ x: 0.421875, y: 0.640625 },
{ x: 0.453125, y: 0.640625 },
{ x: 0.453125, y: 0.640625 },
{ x: 0.484375, y: 0.640625 },
{ x: 0.484375, y: 0.640625 },
{ x: 0.515625, y: 0.640625 },
{ x: 0.515625, y: 0.640625 },
{ x: 0.546875, y: 0.640625 },
{ x: 0.546875, y: 0.640625 },
{ x: 0.578125, y: 0.640625 },
{ x: 0.578125, y: 0.640625 },
{ x: 0.609375, y: 0.640625 },
{ x: 0.609375, y: 0.640625 },
{ x: 0.640625, y: 0.640625 },
{ x: 0.640625, y: 0.640625 },
{ x: 0.671875, y: 0.640625 },
{ x: 0.671875, y: 0.640625 },
{ x: 0.703125, y: 0.640625 },
{ x: 0.703125, y: 0.640625 },
{ x: 0.734375, y: 0.640625 },
{ x: 0.734375, y: 0.640625 },
{ x: 0.765625, y: 0.640625 },
{ x: 0.765625, y: 0.640625 },
{ x: 0.796875, y: 0.640625 },
{ x: 0.796875, y: 0.640625 },
{ x: 0.828125, y: 0.640625 },
{ x: 0.828125, y: 0.640625 },
{ x: 0.859375, y: 0.640625 },
{ x: 0.859375, y: 0.640625 },
{ x: 0.890625, y: 0.640625 },
{ x: 0.890625, y: 0.640625 },
{ x: 0.921875, y: 0.640625 },
{ x: 0.921875, y: 0.640625 },
{ x: 0.953125, y: 0.640625 },
{ x: 0.953125, y: 0.640625 },
{ x: 0.984375, y: 0.640625 },
{ x: 0.984375, y: 0.640625 },
{ x: 0.015625, y: 0.671875 },
{ x: 0.015625, y: 0.671875 },
{ x: 0.046875, y: 0.671875 },
{ x: 0.046875, y: 0.671875 },
{ x: 0.078125, y: 0.671875 },
{ x: 0.078125, y: 0.671875 },
{ x: 0.109375, y: 0.671875 },
{ x: 0.109375, y: 0.671875 },
{ x: 0.140625, y: 0.671875 },
{ x: 0.140625, y: 0.671875 },
{ x: 0.171875, y: 0.671875 },
{ x: 0.171875, y: 0.671875 },
{ x: 0.203125, y: 0.671875 },
{ x: 0.203125, y: 0.671875 },
{ x: 0.234375, y: 0.671875 },
{ x: 0.234375, y: 0.671875 },
{ x: 0.265625, y: 0.671875 },
{ x: 0.265625, y: 0.671875 },
{ x: 0.296875, y: 0.671875 },
{ x: 0.296875, y: 0.671875 },
{ x: 0.328125, y: 0.671875 },
{ x: 0.328125, y: 0.671875 },
{ x: 0.359375, y: 0.671875 },
{ x: 0.359375, y: 0.671875 },
{ x: 0.390625, y: 0.671875 },
{ x: 0.390625, y: 0.671875 },
{ x: 0.421875, y: 0.671875 },
{ x: 0.421875, y: 0.671875 },
{ x: 0.453125, y: 0.671875 },
{ x: 0.453125, y: 0.671875 },
{ x: 0.484375, y: 0.671875 },
{ x: 0.484375, y: 0.671875 },
{ x: 0.515625, y: 0.671875 },
{ x: 0.515625, y: 0.671875 },
{ x: 0.546875, y: 0.671875 },
{ x: 0.546875, y: 0.671875 },
{ x: 0.578125, y: 0.671875 },
{ x: 0.578125, y: 0.671875 },
{ x: 0.609375, y: 0.671875 },
{ x: 0.609375, y: 0.671875 },
{ x: 0.640625, y: 0.671875 },
{ x: 0.640625, y: 0.671875 },
{ x: 0.671875, y: 0.671875 },
{ x: 0.671875, y: 0.671875 },
{ x: 0.703125, y: 0.671875 },
{ x: 0.703125, y: 0.671875 },
{ x: 0.734375, y: 0.671875 },
{ x: 0.734375, y: 0.671875 },
{ x: 0.765625, y: 0.671875 },
{ x: 0.765625, y: 0.671875 },
{ x: 0.796875, y: 0.671875 },
{ x: 0.796875, y: 0.671875 },
{ x: 0.828125, y: 0.671875 },
{ x: 0.828125, y: 0.671875 },
{ x: 0.859375, y: 0.671875 },
{ x: 0.859375, y: 0.671875 },
{ x: 0.890625, y: 0.671875 },
{ x: 0.890625, y: 0.671875 },
{ x: 0.921875, y: 0.671875 },
{ x: 0.921875, y: 0.671875 },
{ x: 0.953125, y: 0.671875 },
{ x: 0.953125, y: 0.671875 },
{ x: 0.984375, y: 0.671875 },
{ x: 0.984375, y: 0.671875 },
{ x: 0.015625, y: 0.703125 },
{ x: 0.015625, y: 0.703125 },
{ x: 0.046875, y: 0.703125 },
{ x: 0.046875, y: 0.703125 },
{ x: 0.078125, y: 0.703125 },
{ x: 0.078125, y: 0.703125 },
{ x: 0.109375, y: 0.703125 },
{ x: 0.109375, y: 0.703125 },
{ x: 0.140625, y: 0.703125 },
{ x: 0.140625, y: 0.703125 },
{ x: 0.171875, y: 0.703125 },
{ x: 0.171875, y: 0.703125 },
{ x: 0.203125, y: 0.703125 },
{ x: 0.203125, y: 0.703125 },
{ x: 0.234375, y: 0.703125 },
{ x: 0.234375, y: 0.703125 },
{ x: 0.265625, y: 0.703125 },
{ x: 0.265625, y: 0.703125 },
{ x: 0.296875, y: 0.703125 },
{ x: 0.296875, y: 0.703125 },
{ x: 0.328125, y: 0.703125 },
{ x: 0.328125, y: 0.703125 },
{ x: 0.359375, y: 0.703125 },
{ x: 0.359375, y: 0.703125 },
{ x: 0.390625, y: 0.703125 },
{ x: 0.390625, y: 0.703125 },
{ x: 0.421875, y: 0.703125 },
{ x: 0.421875, y: 0.703125 },
{ x: 0.453125, y: 0.703125 },
{ x: 0.453125, y: 0.703125 },
{ x: 0.484375, y: 0.703125 },
{ x: 0.484375, y: 0.703125 },
{ x: 0.515625, y: 0.703125 },
{ x: 0.515625, y: 0.703125 },
{ x: 0.546875, y: 0.703125 },
{ x: 0.546875, y: 0.703125 },
{ x: 0.578125, y: 0.703125 },
{ x: 0.578125, y: 0.703125 },
{ x: 0.609375, y: 0.703125 },
{ x: 0.609375, y: 0.703125 },
{ x: 0.640625, y: 0.703125 },
{ x: 0.640625, y: 0.703125 },
{ x: 0.671875, y: 0.703125 },
{ x: 0.671875, y: 0.703125 },
{ x: 0.703125, y: 0.703125 },
{ x: 0.703125, y: 0.703125 },
{ x: 0.734375, y: 0.703125 },
{ x: 0.734375, y: 0.703125 },
{ x: 0.765625, y: 0.703125 },
{ x: 0.765625, y: 0.703125 },
{ x: 0.796875, y: 0.703125 },
{ x: 0.796875, y: 0.703125 },
{ x: 0.828125, y: 0.703125 },
{ x: 0.828125, y: 0.703125 },
{ x: 0.859375, y: 0.703125 },
{ x: 0.859375, y: 0.703125 },
{ x: 0.890625, y: 0.703125 },
{ x: 0.890625, y: 0.703125 },
{ x: 0.921875, y: 0.703125 },
{ x: 0.921875, y: 0.703125 },
{ x: 0.953125, y: 0.703125 },
{ x: 0.953125, y: 0.703125 },
{ x: 0.984375, y: 0.703125 },
{ x: 0.984375, y: 0.703125 },
{ x: 0.015625, y: 0.734375 },
{ x: 0.015625, y: 0.734375 },
{ x: 0.046875, y: 0.734375 },
{ x: 0.046875, y: 0.734375 },
{ x: 0.078125, y: 0.734375 },
{ x: 0.078125, y: 0.734375 },
{ x: 0.109375, y: 0.734375 },
{ x: 0.109375, y: 0.734375 },
{ x: 0.140625, y: 0.734375 },
{ x: 0.140625, y: 0.734375 },
{ x: 0.171875, y: 0.734375 },
{ x: 0.171875, y: 0.734375 },
{ x: 0.203125, y: 0.734375 },
{ x: 0.203125, y: 0.734375 },
{ x: 0.234375, y: 0.734375 },
{ x: 0.234375, y: 0.734375 },
{ x: 0.265625, y: 0.734375 },
{ x: 0.265625, y: 0.734375 },
{ x: 0.296875, y: 0.734375 },
{ x: 0.296875, y: 0.734375 },
{ x: 0.328125, y: 0.734375 },
{ x: 0.328125, y: 0.734375 },
{ x: 0.359375, y: 0.734375 },
{ x: 0.359375, y: 0.734375 },
{ x: 0.390625, y: 0.734375 },
{ x: 0.390625, y: 0.734375 },
{ x: 0.421875, y: 0.734375 },
{ x: 0.421875, y: 0.734375 },
{ x: 0.453125, y: 0.734375 },
{ x: 0.453125, y: 0.734375 },
{ x: 0.484375, y: 0.734375 },
{ x: 0.484375, y: 0.734375 },
{ x: 0.515625, y: 0.734375 },
{ x: 0.515625, y: 0.734375 },
{ x: 0.546875, y: 0.734375 },
{ x: 0.546875, y: 0.734375 },
{ x: 0.578125, y: 0.734375 },
{ x: 0.578125, y: 0.734375 },
{ x: 0.609375, y: 0.734375 },
{ x: 0.609375, y: 0.734375 },
{ x: 0.640625, y: 0.734375 },
{ x: 0.640625, y: 0.734375 },
{ x: 0.671875, y: 0.734375 },
{ x: 0.671875, y: 0.734375 },
{ x: 0.703125, y: 0.734375 },
{ x: 0.703125, y: 0.734375 },
{ x: 0.734375, y: 0.734375 },
{ x: 0.734375, y: 0.734375 },
{ x: 0.765625, y: 0.734375 },
{ x: 0.765625, y: 0.734375 },
{ x: 0.796875, y: 0.734375 },
{ x: 0.796875, y: 0.734375 },
{ x: 0.828125, y: 0.734375 },
{ x: 0.828125, y: 0.734375 },
{ x: 0.859375, y: 0.734375 },
{ x: 0.859375, y: 0.734375 },
{ x: 0.890625, y: 0.734375 },
{ x: 0.890625, y: 0.734375 },
{ x: 0.921875, y: 0.734375 },
{ x: 0.921875, y: 0.734375 },
{ x: 0.953125, y: 0.734375 },
{ x: 0.953125, y: 0.734375 },
{ x: 0.984375, y: 0.734375 },
{ x: 0.984375, y: 0.734375 },
{ x: 0.015625, y: 0.765625 },
{ x: 0.015625, y: 0.765625 },
{ x: 0.046875, y: 0.765625 },
{ x: 0.046875, y: 0.765625 },
{ x: 0.078125, y: 0.765625 },
{ x: 0.078125, y: 0.765625 },
{ x: 0.109375, y: 0.765625 },
{ x: 0.109375, y: 0.765625 },
{ x: 0.140625, y: 0.765625 },
{ x: 0.140625, y: 0.765625 },
{ x: 0.171875, y: 0.765625 },
{ x: 0.171875, y: 0.765625 },
{ x: 0.203125, y: 0.765625 },
{ x: 0.203125, y: 0.765625 },
{ x: 0.234375, y: 0.765625 },
{ x: 0.234375, y: 0.765625 },
{ x: 0.265625, y: 0.765625 },
{ x: 0.265625, y: 0.765625 },
{ x: 0.296875, y: 0.765625 },
{ x: 0.296875, y: 0.765625 },
{ x: 0.328125, y: 0.765625 },
{ x: 0.328125, y: 0.765625 },
{ x: 0.359375, y: 0.765625 },
{ x: 0.359375, y: 0.765625 },
{ x: 0.390625, y: 0.765625 },
{ x: 0.390625, y: 0.765625 },
{ x: 0.421875, y: 0.765625 },
{ x: 0.421875, y: 0.765625 },
{ x: 0.453125, y: 0.765625 },
{ x: 0.453125, y: 0.765625 },
{ x: 0.484375, y: 0.765625 },
{ x: 0.484375, y: 0.765625 },
{ x: 0.515625, y: 0.765625 },
{ x: 0.515625, y: 0.765625 },
{ x: 0.546875, y: 0.765625 },
{ x: 0.546875, y: 0.765625 },
{ x: 0.578125, y: 0.765625 },
{ x: 0.578125, y: 0.765625 },
{ x: 0.609375, y: 0.765625 },
{ x: 0.609375, y: 0.765625 },
{ x: 0.640625, y: 0.765625 },
{ x: 0.640625, y: 0.765625 },
{ x: 0.671875, y: 0.765625 },
{ x: 0.671875, y: 0.765625 },
{ x: 0.703125, y: 0.765625 },
{ x: 0.703125, y: 0.765625 },
{ x: 0.734375, y: 0.765625 },
{ x: 0.734375, y: 0.765625 },
{ x: 0.765625, y: 0.765625 },
{ x: 0.765625, y: 0.765625 },
{ x: 0.796875, y: 0.765625 },
{ x: 0.796875, y: 0.765625 },
{ x: 0.828125, y: 0.765625 },
{ x: 0.828125, y: 0.765625 },
{ x: 0.859375, y: 0.765625 },
{ x: 0.859375, y: 0.765625 },
{ x: 0.890625, y: 0.765625 },
{ x: 0.890625, y: 0.765625 },
{ x: 0.921875, y: 0.765625 },
{ x: 0.921875, y: 0.765625 },
{ x: 0.953125, y: 0.765625 },
{ x: 0.953125, y: 0.765625 },
{ x: 0.984375, y: 0.765625 },
{ x: 0.984375, y: 0.765625 },
{ x: 0.015625, y: 0.796875 },
{ x: 0.015625, y: 0.796875 },
{ x: 0.046875, y: 0.796875 },
{ x: 0.046875, y: 0.796875 },
{ x: 0.078125, y: 0.796875 },
{ x: 0.078125, y: 0.796875 },
{ x: 0.109375, y: 0.796875 },
{ x: 0.109375, y: 0.796875 },
{ x: 0.140625, y: 0.796875 },
{ x: 0.140625, y: 0.796875 },
{ x: 0.171875, y: 0.796875 },
{ x: 0.171875, y: 0.796875 },
{ x: 0.203125, y: 0.796875 },
{ x: 0.203125, y: 0.796875 },
{ x: 0.234375, y: 0.796875 },
{ x: 0.234375, y: 0.796875 },
{ x: 0.265625, y: 0.796875 },
{ x: 0.265625, y: 0.796875 },
{ x: 0.296875, y: 0.796875 },
{ x: 0.296875, y: 0.796875 },
{ x: 0.328125, y: 0.796875 },
{ x: 0.328125, y: 0.796875 },
{ x: 0.359375, y: 0.796875 },
{ x: 0.359375, y: 0.796875 },
{ x: 0.390625, y: 0.796875 },
{ x: 0.390625, y: 0.796875 },
{ x: 0.421875, y: 0.796875 },
{ x: 0.421875, y: 0.796875 },
{ x: 0.453125, y: 0.796875 },
{ x: 0.453125, y: 0.796875 },
{ x: 0.484375, y: 0.796875 },
{ x: 0.484375, y: 0.796875 },
{ x: 0.515625, y: 0.796875 },
{ x: 0.515625, y: 0.796875 },
{ x: 0.546875, y: 0.796875 },
{ x: 0.546875, y: 0.796875 },
{ x: 0.578125, y: 0.796875 },
{ x: 0.578125, y: 0.796875 },
{ x: 0.609375, y: 0.796875 },
{ x: 0.609375, y: 0.796875 },
{ x: 0.640625, y: 0.796875 },
{ x: 0.640625, y: 0.796875 },
{ x: 0.671875, y: 0.796875 },
{ x: 0.671875, y: 0.796875 },
{ x: 0.703125, y: 0.796875 },
{ x: 0.703125, y: 0.796875 },
{ x: 0.734375, y: 0.796875 },
{ x: 0.734375, y: 0.796875 },
{ x: 0.765625, y: 0.796875 },
{ x: 0.765625, y: 0.796875 },
{ x: 0.796875, y: 0.796875 },
{ x: 0.796875, y: 0.796875 },
{ x: 0.828125, y: 0.796875 },
{ x: 0.828125, y: 0.796875 },
{ x: 0.859375, y: 0.796875 },
{ x: 0.859375, y: 0.796875 },
{ x: 0.890625, y: 0.796875 },
{ x: 0.890625, y: 0.796875 },
{ x: 0.921875, y: 0.796875 },
{ x: 0.921875, y: 0.796875 },
{ x: 0.953125, y: 0.796875 },
{ x: 0.953125, y: 0.796875 },
{ x: 0.984375, y: 0.796875 },
{ x: 0.984375, y: 0.796875 },
{ x: 0.015625, y: 0.828125 },
{ x: 0.015625, y: 0.828125 },
{ x: 0.046875, y: 0.828125 },
{ x: 0.046875, y: 0.828125 },
{ x: 0.078125, y: 0.828125 },
{ x: 0.078125, y: 0.828125 },
{ x: 0.109375, y: 0.828125 },
{ x: 0.109375, y: 0.828125 },
{ x: 0.140625, y: 0.828125 },
{ x: 0.140625, y: 0.828125 },
{ x: 0.171875, y: 0.828125 },
{ x: 0.171875, y: 0.828125 },
{ x: 0.203125, y: 0.828125 },
{ x: 0.203125, y: 0.828125 },
{ x: 0.234375, y: 0.828125 },
{ x: 0.234375, y: 0.828125 },
{ x: 0.265625, y: 0.828125 },
{ x: 0.265625, y: 0.828125 },
{ x: 0.296875, y: 0.828125 },
{ x: 0.296875, y: 0.828125 },
{ x: 0.328125, y: 0.828125 },
{ x: 0.328125, y: 0.828125 },
{ x: 0.359375, y: 0.828125 },
{ x: 0.359375, y: 0.828125 },
{ x: 0.390625, y: 0.828125 },
{ x: 0.390625, y: 0.828125 },
{ x: 0.421875, y: 0.828125 },
{ x: 0.421875, y: 0.828125 },
{ x: 0.453125, y: 0.828125 },
{ x: 0.453125, y: 0.828125 },
{ x: 0.484375, y: 0.828125 },
{ x: 0.484375, y: 0.828125 },
{ x: 0.515625, y: 0.828125 },
{ x: 0.515625, y: 0.828125 },
{ x: 0.546875, y: 0.828125 },
{ x: 0.546875, y: 0.828125 },
{ x: 0.578125, y: 0.828125 },
{ x: 0.578125, y: 0.828125 },
{ x: 0.609375, y: 0.828125 },
{ x: 0.609375, y: 0.828125 },
{ x: 0.640625, y: 0.828125 },
{ x: 0.640625, y: 0.828125 },
{ x: 0.671875, y: 0.828125 },
{ x: 0.671875, y: 0.828125 },
{ x: 0.703125, y: 0.828125 },
{ x: 0.703125, y: 0.828125 },
{ x: 0.734375, y: 0.828125 },
{ x: 0.734375, y: 0.828125 },
{ x: 0.765625, y: 0.828125 },
{ x: 0.765625, y: 0.828125 },
{ x: 0.796875, y: 0.828125 },
{ x: 0.796875, y: 0.828125 },
{ x: 0.828125, y: 0.828125 },
{ x: 0.828125, y: 0.828125 },
{ x: 0.859375, y: 0.828125 },
{ x: 0.859375, y: 0.828125 },
{ x: 0.890625, y: 0.828125 },
{ x: 0.890625, y: 0.828125 },
{ x: 0.921875, y: 0.828125 },
{ x: 0.921875, y: 0.828125 },
{ x: 0.953125, y: 0.828125 },
{ x: 0.953125, y: 0.828125 },
{ x: 0.984375, y: 0.828125 },
{ x: 0.984375, y: 0.828125 },
{ x: 0.015625, y: 0.859375 },
{ x: 0.015625, y: 0.859375 },
{ x: 0.046875, y: 0.859375 },
{ x: 0.046875, y: 0.859375 },
{ x: 0.078125, y: 0.859375 },
{ x: 0.078125, y: 0.859375 },
{ x: 0.109375, y: 0.859375 },
{ x: 0.109375, y: 0.859375 },
{ x: 0.140625, y: 0.859375 },
{ x: 0.140625, y: 0.859375 },
{ x: 0.171875, y: 0.859375 },
{ x: 0.171875, y: 0.859375 },
{ x: 0.203125, y: 0.859375 },
{ x: 0.203125, y: 0.859375 },
{ x: 0.234375, y: 0.859375 },
{ x: 0.234375, y: 0.859375 },
{ x: 0.265625, y: 0.859375 },
{ x: 0.265625, y: 0.859375 },
{ x: 0.296875, y: 0.859375 },
{ x: 0.296875, y: 0.859375 },
{ x: 0.328125, y: 0.859375 },
{ x: 0.328125, y: 0.859375 },
{ x: 0.359375, y: 0.859375 },
{ x: 0.359375, y: 0.859375 },
{ x: 0.390625, y: 0.859375 },
{ x: 0.390625, y: 0.859375 },
{ x: 0.421875, y: 0.859375 },
{ x: 0.421875, y: 0.859375 },
{ x: 0.453125, y: 0.859375 },
{ x: 0.453125, y: 0.859375 },
{ x: 0.484375, y: 0.859375 },
{ x: 0.484375, y: 0.859375 },
{ x: 0.515625, y: 0.859375 },
{ x: 0.515625, y: 0.859375 },
{ x: 0.546875, y: 0.859375 },
{ x: 0.546875, y: 0.859375 },
{ x: 0.578125, y: 0.859375 },
{ x: 0.578125, y: 0.859375 },
{ x: 0.609375, y: 0.859375 },
{ x: 0.609375, y: 0.859375 },
{ x: 0.640625, y: 0.859375 },
{ x: 0.640625, y: 0.859375 },
{ x: 0.671875, y: 0.859375 },
{ x: 0.671875, y: 0.859375 },
{ x: 0.703125, y: 0.859375 },
{ x: 0.703125, y: 0.859375 },
{ x: 0.734375, y: 0.859375 },
{ x: 0.734375, y: 0.859375 },
{ x: 0.765625, y: 0.859375 },
{ x: 0.765625, y: 0.859375 },
{ x: 0.796875, y: 0.859375 },
{ x: 0.796875, y: 0.859375 },
{ x: 0.828125, y: 0.859375 },
{ x: 0.828125, y: 0.859375 },
{ x: 0.859375, y: 0.859375 },
{ x: 0.859375, y: 0.859375 },
{ x: 0.890625, y: 0.859375 },
{ x: 0.890625, y: 0.859375 },
{ x: 0.921875, y: 0.859375 },
{ x: 0.921875, y: 0.859375 },
{ x: 0.953125, y: 0.859375 },
{ x: 0.953125, y: 0.859375 },
{ x: 0.984375, y: 0.859375 },
{ x: 0.984375, y: 0.859375 },
{ x: 0.015625, y: 0.890625 },
{ x: 0.015625, y: 0.890625 },
{ x: 0.046875, y: 0.890625 },
{ x: 0.046875, y: 0.890625 },
{ x: 0.078125, y: 0.890625 },
{ x: 0.078125, y: 0.890625 },
{ x: 0.109375, y: 0.890625 },
{ x: 0.109375, y: 0.890625 },
{ x: 0.140625, y: 0.890625 },
{ x: 0.140625, y: 0.890625 },
{ x: 0.171875, y: 0.890625 },
{ x: 0.171875, y: 0.890625 },
{ x: 0.203125, y: 0.890625 },
{ x: 0.203125, y: 0.890625 },
{ x: 0.234375, y: 0.890625 },
{ x: 0.234375, y: 0.890625 },
{ x: 0.265625, y: 0.890625 },
{ x: 0.265625, y: 0.890625 },
{ x: 0.296875, y: 0.890625 },
{ x: 0.296875, y: 0.890625 },
{ x: 0.328125, y: 0.890625 },
{ x: 0.328125, y: 0.890625 },
{ x: 0.359375, y: 0.890625 },
{ x: 0.359375, y: 0.890625 },
{ x: 0.390625, y: 0.890625 },
{ x: 0.390625, y: 0.890625 },
{ x: 0.421875, y: 0.890625 },
{ x: 0.421875, y: 0.890625 },
{ x: 0.453125, y: 0.890625 },
{ x: 0.453125, y: 0.890625 },
{ x: 0.484375, y: 0.890625 },
{ x: 0.484375, y: 0.890625 },
{ x: 0.515625, y: 0.890625 },
{ x: 0.515625, y: 0.890625 },
{ x: 0.546875, y: 0.890625 },
{ x: 0.546875, y: 0.890625 },
{ x: 0.578125, y: 0.890625 },
{ x: 0.578125, y: 0.890625 },
{ x: 0.609375, y: 0.890625 },
{ x: 0.609375, y: 0.890625 },
{ x: 0.640625, y: 0.890625 },
{ x: 0.640625, y: 0.890625 },
{ x: 0.671875, y: 0.890625 },
{ x: 0.671875, y: 0.890625 },
{ x: 0.703125, y: 0.890625 },
{ x: 0.703125, y: 0.890625 },
{ x: 0.734375, y: 0.890625 },
{ x: 0.734375, y: 0.890625 },
{ x: 0.765625, y: 0.890625 },
{ x: 0.765625, y: 0.890625 },
{ x: 0.796875, y: 0.890625 },
{ x: 0.796875, y: 0.890625 },
{ x: 0.828125, y: 0.890625 },
{ x: 0.828125, y: 0.890625 },
{ x: 0.859375, y: 0.890625 },
{ x: 0.859375, y: 0.890625 },
{ x: 0.890625, y: 0.890625 },
{ x: 0.890625, y: 0.890625 },
{ x: 0.921875, y: 0.890625 },
{ x: 0.921875, y: 0.890625 },
{ x: 0.953125, y: 0.890625 },
{ x: 0.953125, y: 0.890625 },
{ x: 0.984375, y: 0.890625 },
{ x: 0.984375, y: 0.890625 },
{ x: 0.015625, y: 0.921875 },
{ x: 0.015625, y: 0.921875 },
{ x: 0.046875, y: 0.921875 },
{ x: 0.046875, y: 0.921875 },
{ x: 0.078125, y: 0.921875 },
{ x: 0.078125, y: 0.921875 },
{ x: 0.109375, y: 0.921875 },
{ x: 0.109375, y: 0.921875 },
{ x: 0.140625, y: 0.921875 },
{ x: 0.140625, y: 0.921875 },
{ x: 0.171875, y: 0.921875 },
{ x: 0.171875, y: 0.921875 },
{ x: 0.203125, y: 0.921875 },
{ x: 0.203125, y: 0.921875 },
{ x: 0.234375, y: 0.921875 },
{ x: 0.234375, y: 0.921875 },
{ x: 0.265625, y: 0.921875 },
{ x: 0.265625, y: 0.921875 },
{ x: 0.296875, y: 0.921875 },
{ x: 0.296875, y: 0.921875 },
{ x: 0.328125, y: 0.921875 },
{ x: 0.328125, y: 0.921875 },
{ x: 0.359375, y: 0.921875 },
{ x: 0.359375, y: 0.921875 },
{ x: 0.390625, y: 0.921875 },
{ x: 0.390625, y: 0.921875 },
{ x: 0.421875, y: 0.921875 },
{ x: 0.421875, y: 0.921875 },
{ x: 0.453125, y: 0.921875 },
{ x: 0.453125, y: 0.921875 },
{ x: 0.484375, y: 0.921875 },
{ x: 0.484375, y: 0.921875 },
{ x: 0.515625, y: 0.921875 },
{ x: 0.515625, y: 0.921875 },
{ x: 0.546875, y: 0.921875 },
{ x: 0.546875, y: 0.921875 },
{ x: 0.578125, y: 0.921875 },
{ x: 0.578125, y: 0.921875 },
{ x: 0.609375, y: 0.921875 },
{ x: 0.609375, y: 0.921875 },
{ x: 0.640625, y: 0.921875 },
{ x: 0.640625, y: 0.921875 },
{ x: 0.671875, y: 0.921875 },
{ x: 0.671875, y: 0.921875 },
{ x: 0.703125, y: 0.921875 },
{ x: 0.703125, y: 0.921875 },
{ x: 0.734375, y: 0.921875 },
{ x: 0.734375, y: 0.921875 },
{ x: 0.765625, y: 0.921875 },
{ x: 0.765625, y: 0.921875 },
{ x: 0.796875, y: 0.921875 },
{ x: 0.796875, y: 0.921875 },
{ x: 0.828125, y: 0.921875 },
{ x: 0.828125, y: 0.921875 },
{ x: 0.859375, y: 0.921875 },
{ x: 0.859375, y: 0.921875 },
{ x: 0.890625, y: 0.921875 },
{ x: 0.890625, y: 0.921875 },
{ x: 0.921875, y: 0.921875 },
{ x: 0.921875, y: 0.921875 },
{ x: 0.953125, y: 0.921875 },
{ x: 0.953125, y: 0.921875 },
{ x: 0.984375, y: 0.921875 },
{ x: 0.984375, y: 0.921875 },
{ x: 0.015625, y: 0.953125 },
{ x: 0.015625, y: 0.953125 },
{ x: 0.046875, y: 0.953125 },
{ x: 0.046875, y: 0.953125 },
{ x: 0.078125, y: 0.953125 },
{ x: 0.078125, y: 0.953125 },
{ x: 0.109375, y: 0.953125 },
{ x: 0.109375, y: 0.953125 },
{ x: 0.140625, y: 0.953125 },
{ x: 0.140625, y: 0.953125 },
{ x: 0.171875, y: 0.953125 },
{ x: 0.171875, y: 0.953125 },
{ x: 0.203125, y: 0.953125 },
{ x: 0.203125, y: 0.953125 },
{ x: 0.234375, y: 0.953125 },
{ x: 0.234375, y: 0.953125 },
{ x: 0.265625, y: 0.953125 },
{ x: 0.265625, y: 0.953125 },
{ x: 0.296875, y: 0.953125 },
{ x: 0.296875, y: 0.953125 },
{ x: 0.328125, y: 0.953125 },
{ x: 0.328125, y: 0.953125 },
{ x: 0.359375, y: 0.953125 },
{ x: 0.359375, y: 0.953125 },
{ x: 0.390625, y: 0.953125 },
{ x: 0.390625, y: 0.953125 },
{ x: 0.421875, y: 0.953125 },
{ x: 0.421875, y: 0.953125 },
{ x: 0.453125, y: 0.953125 },
{ x: 0.453125, y: 0.953125 },
{ x: 0.484375, y: 0.953125 },
{ x: 0.484375, y: 0.953125 },
{ x: 0.515625, y: 0.953125 },
{ x: 0.515625, y: 0.953125 },
{ x: 0.546875, y: 0.953125 },
{ x: 0.546875, y: 0.953125 },
{ x: 0.578125, y: 0.953125 },
{ x: 0.578125, y: 0.953125 },
{ x: 0.609375, y: 0.953125 },
{ x: 0.609375, y: 0.953125 },
{ x: 0.640625, y: 0.953125 },
{ x: 0.640625, y: 0.953125 },
{ x: 0.671875, y: 0.953125 },
{ x: 0.671875, y: 0.953125 },
{ x: 0.703125, y: 0.953125 },
{ x: 0.703125, y: 0.953125 },
{ x: 0.734375, y: 0.953125 },
{ x: 0.734375, y: 0.953125 },
{ x: 0.765625, y: 0.953125 },
{ x: 0.765625, y: 0.953125 },
{ x: 0.796875, y: 0.953125 },
{ x: 0.796875, y: 0.953125 },
{ x: 0.828125, y: 0.953125 },
{ x: 0.828125, y: 0.953125 },
{ x: 0.859375, y: 0.953125 },
{ x: 0.859375, y: 0.953125 },
{ x: 0.890625, y: 0.953125 },
{ x: 0.890625, y: 0.953125 },
{ x: 0.921875, y: 0.953125 },
{ x: 0.921875, y: 0.953125 },
{ x: 0.953125, y: 0.953125 },
{ x: 0.953125, y: 0.953125 },
{ x: 0.984375, y: 0.953125 },
{ x: 0.984375, y: 0.953125 },
{ x: 0.015625, y: 0.984375 },
{ x: 0.015625, y: 0.984375 },
{ x: 0.046875, y: 0.984375 },
{ x: 0.046875, y: 0.984375 },
{ x: 0.078125, y: 0.984375 },
{ x: 0.078125, y: 0.984375 },
{ x: 0.109375, y: 0.984375 },
{ x: 0.109375, y: 0.984375 },
{ x: 0.140625, y: 0.984375 },
{ x: 0.140625, y: 0.984375 },
{ x: 0.171875, y: 0.984375 },
{ x: 0.171875, y: 0.984375 },
{ x: 0.203125, y: 0.984375 },
{ x: 0.203125, y: 0.984375 },
{ x: 0.234375, y: 0.984375 },
{ x: 0.234375, y: 0.984375 },
{ x: 0.265625, y: 0.984375 },
{ x: 0.265625, y: 0.984375 },
{ x: 0.296875, y: 0.984375 },
{ x: 0.296875, y: 0.984375 },
{ x: 0.328125, y: 0.984375 },
{ x: 0.328125, y: 0.984375 },
{ x: 0.359375, y: 0.984375 },
{ x: 0.359375, y: 0.984375 },
{ x: 0.390625, y: 0.984375 },
{ x: 0.390625, y: 0.984375 },
{ x: 0.421875, y: 0.984375 },
{ x: 0.421875, y: 0.984375 },
{ x: 0.453125, y: 0.984375 },
{ x: 0.453125, y: 0.984375 },
{ x: 0.484375, y: 0.984375 },
{ x: 0.484375, y: 0.984375 },
{ x: 0.515625, y: 0.984375 },
{ x: 0.515625, y: 0.984375 },
{ x: 0.546875, y: 0.984375 },
{ x: 0.546875, y: 0.984375 },
{ x: 0.578125, y: 0.984375 },
{ x: 0.578125, y: 0.984375 },
{ x: 0.609375, y: 0.984375 },
{ x: 0.609375, y: 0.984375 },
{ x: 0.640625, y: 0.984375 },
{ x: 0.640625, y: 0.984375 },
{ x: 0.671875, y: 0.984375 },
{ x: 0.671875, y: 0.984375 },
{ x: 0.703125, y: 0.984375 },
{ x: 0.703125, y: 0.984375 },
{ x: 0.734375, y: 0.984375 },
{ x: 0.734375, y: 0.984375 },
{ x: 0.765625, y: 0.984375 },
{ x: 0.765625, y: 0.984375 },
{ x: 0.796875, y: 0.984375 },
{ x: 0.796875, y: 0.984375 },
{ x: 0.828125, y: 0.984375 },
{ x: 0.828125, y: 0.984375 },
{ x: 0.859375, y: 0.984375 },
{ x: 0.859375, y: 0.984375 },
{ x: 0.890625, y: 0.984375 },
{ x: 0.890625, y: 0.984375 },
{ x: 0.921875, y: 0.984375 },
{ x: 0.921875, y: 0.984375 },
{ x: 0.953125, y: 0.984375 },
{ x: 0.953125, y: 0.984375 },
{ x: 0.984375, y: 0.984375 },
{ x: 0.984375, y: 0.984375 },
{ x: 0.03125, y: 0.03125 },
{ x: 0.03125, y: 0.03125 },
{ x: 0.09375, y: 0.03125 },
{ x: 0.09375, y: 0.03125 },
{ x: 0.15625, y: 0.03125 },
{ x: 0.15625, y: 0.03125 },
{ x: 0.21875, y: 0.03125 },
{ x: 0.21875, y: 0.03125 },
{ x: 0.28125, y: 0.03125 },
{ x: 0.28125, y: 0.03125 },
{ x: 0.34375, y: 0.03125 },
{ x: 0.34375, y: 0.03125 },
{ x: 0.40625, y: 0.03125 },
{ x: 0.40625, y: 0.03125 },
{ x: 0.46875, y: 0.03125 },
{ x: 0.46875, y: 0.03125 },
{ x: 0.53125, y: 0.03125 },
{ x: 0.53125, y: 0.03125 },
{ x: 0.59375, y: 0.03125 },
{ x: 0.59375, y: 0.03125 },
{ x: 0.65625, y: 0.03125 },
{ x: 0.65625, y: 0.03125 },
{ x: 0.71875, y: 0.03125 },
{ x: 0.71875, y: 0.03125 },
{ x: 0.78125, y: 0.03125 },
{ x: 0.78125, y: 0.03125 },
{ x: 0.84375, y: 0.03125 },
{ x: 0.84375, y: 0.03125 },
{ x: 0.90625, y: 0.03125 },
{ x: 0.90625, y: 0.03125 },
{ x: 0.96875, y: 0.03125 },
{ x: 0.96875, y: 0.03125 },
{ x: 0.03125, y: 0.09375 },
{ x: 0.03125, y: 0.09375 },
{ x: 0.09375, y: 0.09375 },
{ x: 0.09375, y: 0.09375 },
{ x: 0.15625, y: 0.09375 },
{ x: 0.15625, y: 0.09375 },
{ x: 0.21875, y: 0.09375 },
{ x: 0.21875, y: 0.09375 },
{ x: 0.28125, y: 0.09375 },
{ x: 0.28125, y: 0.09375 },
{ x: 0.34375, y: 0.09375 },
{ x: 0.34375, y: 0.09375 },
{ x: 0.40625, y: 0.09375 },
{ x: 0.40625, y: 0.09375 },
{ x: 0.46875, y: 0.09375 },
{ x: 0.46875, y: 0.09375 },
{ x: 0.53125, y: 0.09375 },
{ x: 0.53125, y: 0.09375 },
{ x: 0.59375, y: 0.09375 },
{ x: 0.59375, y: 0.09375 },
{ x: 0.65625, y: 0.09375 },
{ x: 0.65625, y: 0.09375 },
{ x: 0.71875, y: 0.09375 },
{ x: 0.71875, y: 0.09375 },
{ x: 0.78125, y: 0.09375 },
{ x: 0.78125, y: 0.09375 },
{ x: 0.84375, y: 0.09375 },
{ x: 0.84375, y: 0.09375 },
{ x: 0.90625, y: 0.09375 },
{ x: 0.90625, y: 0.09375 },
{ x: 0.96875, y: 0.09375 },
{ x: 0.96875, y: 0.09375 },
{ x: 0.03125, y: 0.15625 },
{ x: 0.03125, y: 0.15625 },
{ x: 0.09375, y: 0.15625 },
{ x: 0.09375, y: 0.15625 },
{ x: 0.15625, y: 0.15625 },
{ x: 0.15625, y: 0.15625 },
{ x: 0.21875, y: 0.15625 },
{ x: 0.21875, y: 0.15625 },
{ x: 0.28125, y: 0.15625 },
{ x: 0.28125, y: 0.15625 },
{ x: 0.34375, y: 0.15625 },
{ x: 0.34375, y: 0.15625 },
{ x: 0.40625, y: 0.15625 },
{ x: 0.40625, y: 0.15625 },
{ x: 0.46875, y: 0.15625 },
{ x: 0.46875, y: 0.15625 },
{ x: 0.53125, y: 0.15625 },
{ x: 0.53125, y: 0.15625 },
{ x: 0.59375, y: 0.15625 },
{ x: 0.59375, y: 0.15625 },
{ x: 0.65625, y: 0.15625 },
{ x: 0.65625, y: 0.15625 },
{ x: 0.71875, y: 0.15625 },
{ x: 0.71875, y: 0.15625 },
{ x: 0.78125, y: 0.15625 },
{ x: 0.78125, y: 0.15625 },
{ x: 0.84375, y: 0.15625 },
{ x: 0.84375, y: 0.15625 },
{ x: 0.90625, y: 0.15625 },
{ x: 0.90625, y: 0.15625 },
{ x: 0.96875, y: 0.15625 },
{ x: 0.96875, y: 0.15625 },
{ x: 0.03125, y: 0.21875 },
{ x: 0.03125, y: 0.21875 },
{ x: 0.09375, y: 0.21875 },
{ x: 0.09375, y: 0.21875 },
{ x: 0.15625, y: 0.21875 },
{ x: 0.15625, y: 0.21875 },
{ x: 0.21875, y: 0.21875 },
{ x: 0.21875, y: 0.21875 },
{ x: 0.28125, y: 0.21875 },
{ x: 0.28125, y: 0.21875 },
{ x: 0.34375, y: 0.21875 },
{ x: 0.34375, y: 0.21875 },
{ x: 0.40625, y: 0.21875 },
{ x: 0.40625, y: 0.21875 },
{ x: 0.46875, y: 0.21875 },
{ x: 0.46875, y: 0.21875 },
{ x: 0.53125, y: 0.21875 },
{ x: 0.53125, y: 0.21875 },
{ x: 0.59375, y: 0.21875 },
{ x: 0.59375, y: 0.21875 },
{ x: 0.65625, y: 0.21875 },
{ x: 0.65625, y: 0.21875 },
{ x: 0.71875, y: 0.21875 },
{ x: 0.71875, y: 0.21875 },
{ x: 0.78125, y: 0.21875 },
{ x: 0.78125, y: 0.21875 },
{ x: 0.84375, y: 0.21875 },
{ x: 0.84375, y: 0.21875 },
{ x: 0.90625, y: 0.21875 },
{ x: 0.90625, y: 0.21875 },
{ x: 0.96875, y: 0.21875 },
{ x: 0.96875, y: 0.21875 },
{ x: 0.03125, y: 0.28125 },
{ x: 0.03125, y: 0.28125 },
{ x: 0.09375, y: 0.28125 },
{ x: 0.09375, y: 0.28125 },
{ x: 0.15625, y: 0.28125 },
{ x: 0.15625, y: 0.28125 },
{ x: 0.21875, y: 0.28125 },
{ x: 0.21875, y: 0.28125 },
{ x: 0.28125, y: 0.28125 },
{ x: 0.28125, y: 0.28125 },
{ x: 0.34375, y: 0.28125 },
{ x: 0.34375, y: 0.28125 },
{ x: 0.40625, y: 0.28125 },
{ x: 0.40625, y: 0.28125 },
{ x: 0.46875, y: 0.28125 },
{ x: 0.46875, y: 0.28125 },
{ x: 0.53125, y: 0.28125 },
{ x: 0.53125, y: 0.28125 },
{ x: 0.59375, y: 0.28125 },
{ x: 0.59375, y: 0.28125 },
{ x: 0.65625, y: 0.28125 },
{ x: 0.65625, y: 0.28125 },
{ x: 0.71875, y: 0.28125 },
{ x: 0.71875, y: 0.28125 },
{ x: 0.78125, y: 0.28125 },
{ x: 0.78125, y: 0.28125 },
{ x: 0.84375, y: 0.28125 },
{ x: 0.84375, y: 0.28125 },
{ x: 0.90625, y: 0.28125 },
{ x: 0.90625, y: 0.28125 },
{ x: 0.96875, y: 0.28125 },
{ x: 0.96875, y: 0.28125 },
{ x: 0.03125, y: 0.34375 },
{ x: 0.03125, y: 0.34375 },
{ x: 0.09375, y: 0.34375 },
{ x: 0.09375, y: 0.34375 },
{ x: 0.15625, y: 0.34375 },
{ x: 0.15625, y: 0.34375 },
{ x: 0.21875, y: 0.34375 },
{ x: 0.21875, y: 0.34375 },
{ x: 0.28125, y: 0.34375 },
{ x: 0.28125, y: 0.34375 },
{ x: 0.34375, y: 0.34375 },
{ x: 0.34375, y: 0.34375 },
{ x: 0.40625, y: 0.34375 },
{ x: 0.40625, y: 0.34375 },
{ x: 0.46875, y: 0.34375 },
{ x: 0.46875, y: 0.34375 },
{ x: 0.53125, y: 0.34375 },
{ x: 0.53125, y: 0.34375 },
{ x: 0.59375, y: 0.34375 },
{ x: 0.59375, y: 0.34375 },
{ x: 0.65625, y: 0.34375 },
{ x: 0.65625, y: 0.34375 },
{ x: 0.71875, y: 0.34375 },
{ x: 0.71875, y: 0.34375 },
{ x: 0.78125, y: 0.34375 },
{ x: 0.78125, y: 0.34375 },
{ x: 0.84375, y: 0.34375 },
{ x: 0.84375, y: 0.34375 },
{ x: 0.90625, y: 0.34375 },
{ x: 0.90625, y: 0.34375 },
{ x: 0.96875, y: 0.34375 },
{ x: 0.96875, y: 0.34375 },
{ x: 0.03125, y: 0.40625 },
{ x: 0.03125, y: 0.40625 },
{ x: 0.09375, y: 0.40625 },
{ x: 0.09375, y: 0.40625 },
{ x: 0.15625, y: 0.40625 },
{ x: 0.15625, y: 0.40625 },
{ x: 0.21875, y: 0.40625 },
{ x: 0.21875, y: 0.40625 },
{ x: 0.28125, y: 0.40625 },
{ x: 0.28125, y: 0.40625 },
{ x: 0.34375, y: 0.40625 },
{ x: 0.34375, y: 0.40625 },
{ x: 0.40625, y: 0.40625 },
{ x: 0.40625, y: 0.40625 },
{ x: 0.46875, y: 0.40625 },
{ x: 0.46875, y: 0.40625 },
{ x: 0.53125, y: 0.40625 },
{ x: 0.53125, y: 0.40625 },
{ x: 0.59375, y: 0.40625 },
{ x: 0.59375, y: 0.40625 },
{ x: 0.65625, y: 0.40625 },
{ x: 0.65625, y: 0.40625 },
{ x: 0.71875, y: 0.40625 },
{ x: 0.71875, y: 0.40625 },
{ x: 0.78125, y: 0.40625 },
{ x: 0.78125, y: 0.40625 },
{ x: 0.84375, y: 0.40625 },
{ x: 0.84375, y: 0.40625 },
{ x: 0.90625, y: 0.40625 },
{ x: 0.90625, y: 0.40625 },
{ x: 0.96875, y: 0.40625 },
{ x: 0.96875, y: 0.40625 },
{ x: 0.03125, y: 0.46875 },
{ x: 0.03125, y: 0.46875 },
{ x: 0.09375, y: 0.46875 },
{ x: 0.09375, y: 0.46875 },
{ x: 0.15625, y: 0.46875 },
{ x: 0.15625, y: 0.46875 },
{ x: 0.21875, y: 0.46875 },
{ x: 0.21875, y: 0.46875 },
{ x: 0.28125, y: 0.46875 },
{ x: 0.28125, y: 0.46875 },
{ x: 0.34375, y: 0.46875 },
{ x: 0.34375, y: 0.46875 },
{ x: 0.40625, y: 0.46875 },
{ x: 0.40625, y: 0.46875 },
{ x: 0.46875, y: 0.46875 },
{ x: 0.46875, y: 0.46875 },
{ x: 0.53125, y: 0.46875 },
{ x: 0.53125, y: 0.46875 },
{ x: 0.59375, y: 0.46875 },
{ x: 0.59375, y: 0.46875 },
{ x: 0.65625, y: 0.46875 },
{ x: 0.65625, y: 0.46875 },
{ x: 0.71875, y: 0.46875 },
{ x: 0.71875, y: 0.46875 },
{ x: 0.78125, y: 0.46875 },
{ x: 0.78125, y: 0.46875 },
{ x: 0.84375, y: 0.46875 },
{ x: 0.84375, y: 0.46875 },
{ x: 0.90625, y: 0.46875 },
{ x: 0.90625, y: 0.46875 },
{ x: 0.96875, y: 0.46875 },
{ x: 0.96875, y: 0.46875 },
{ x: 0.03125, y: 0.53125 },
{ x: 0.03125, y: 0.53125 },
{ x: 0.09375, y: 0.53125 },
{ x: 0.09375, y: 0.53125 },
{ x: 0.15625, y: 0.53125 },
{ x: 0.15625, y: 0.53125 },
{ x: 0.21875, y: 0.53125 },
{ x: 0.21875, y: 0.53125 },
{ x: 0.28125, y: 0.53125 },
{ x: 0.28125, y: 0.53125 },
{ x: 0.34375, y: 0.53125 },
{ x: 0.34375, y: 0.53125 },
{ x: 0.40625, y: 0.53125 },
{ x: 0.40625, y: 0.53125 },
{ x: 0.46875, y: 0.53125 },
{ x: 0.46875, y: 0.53125 },
{ x: 0.53125, y: 0.53125 },
{ x: 0.53125, y: 0.53125 },
{ x: 0.59375, y: 0.53125 },
{ x: 0.59375, y: 0.53125 },
{ x: 0.65625, y: 0.53125 },
{ x: 0.65625, y: 0.53125 },
{ x: 0.71875, y: 0.53125 },
{ x: 0.71875, y: 0.53125 },
{ x: 0.78125, y: 0.53125 },
{ x: 0.78125, y: 0.53125 },
{ x: 0.84375, y: 0.53125 },
{ x: 0.84375, y: 0.53125 },
{ x: 0.90625, y: 0.53125 },
{ x: 0.90625, y: 0.53125 },
{ x: 0.96875, y: 0.53125 },
{ x: 0.96875, y: 0.53125 },
{ x: 0.03125, y: 0.59375 },
{ x: 0.03125, y: 0.59375 },
{ x: 0.09375, y: 0.59375 },
{ x: 0.09375, y: 0.59375 },
{ x: 0.15625, y: 0.59375 },
{ x: 0.15625, y: 0.59375 },
{ x: 0.21875, y: 0.59375 },
{ x: 0.21875, y: 0.59375 },
{ x: 0.28125, y: 0.59375 },
{ x: 0.28125, y: 0.59375 },
{ x: 0.34375, y: 0.59375 },
{ x: 0.34375, y: 0.59375 },
{ x: 0.40625, y: 0.59375 },
{ x: 0.40625, y: 0.59375 },
{ x: 0.46875, y: 0.59375 },
{ x: 0.46875, y: 0.59375 },
{ x: 0.53125, y: 0.59375 },
{ x: 0.53125, y: 0.59375 },
{ x: 0.59375, y: 0.59375 },
{ x: 0.59375, y: 0.59375 },
{ x: 0.65625, y: 0.59375 },
{ x: 0.65625, y: 0.59375 },
{ x: 0.71875, y: 0.59375 },
{ x: 0.71875, y: 0.59375 },
{ x: 0.78125, y: 0.59375 },
{ x: 0.78125, y: 0.59375 },
{ x: 0.84375, y: 0.59375 },
{ x: 0.84375, y: 0.59375 },
{ x: 0.90625, y: 0.59375 },
{ x: 0.90625, y: 0.59375 },
{ x: 0.96875, y: 0.59375 },
{ x: 0.96875, y: 0.59375 },
{ x: 0.03125, y: 0.65625 },
{ x: 0.03125, y: 0.65625 },
{ x: 0.09375, y: 0.65625 },
{ x: 0.09375, y: 0.65625 },
{ x: 0.15625, y: 0.65625 },
{ x: 0.15625, y: 0.65625 },
{ x: 0.21875, y: 0.65625 },
{ x: 0.21875, y: 0.65625 },
{ x: 0.28125, y: 0.65625 },
{ x: 0.28125, y: 0.65625 },
{ x: 0.34375, y: 0.65625 },
{ x: 0.34375, y: 0.65625 },
{ x: 0.40625, y: 0.65625 },
{ x: 0.40625, y: 0.65625 },
{ x: 0.46875, y: 0.65625 },
{ x: 0.46875, y: 0.65625 },
{ x: 0.53125, y: 0.65625 },
{ x: 0.53125, y: 0.65625 },
{ x: 0.59375, y: 0.65625 },
{ x: 0.59375, y: 0.65625 },
{ x: 0.65625, y: 0.65625 },
{ x: 0.65625, y: 0.65625 },
{ x: 0.71875, y: 0.65625 },
{ x: 0.71875, y: 0.65625 },
{ x: 0.78125, y: 0.65625 },
{ x: 0.78125, y: 0.65625 },
{ x: 0.84375, y: 0.65625 },
{ x: 0.84375, y: 0.65625 },
{ x: 0.90625, y: 0.65625 },
{ x: 0.90625, y: 0.65625 },
{ x: 0.96875, y: 0.65625 },
{ x: 0.96875, y: 0.65625 },
{ x: 0.03125, y: 0.71875 },
{ x: 0.03125, y: 0.71875 },
{ x: 0.09375, y: 0.71875 },
{ x: 0.09375, y: 0.71875 },
{ x: 0.15625, y: 0.71875 },
{ x: 0.15625, y: 0.71875 },
{ x: 0.21875, y: 0.71875 },
{ x: 0.21875, y: 0.71875 },
{ x: 0.28125, y: 0.71875 },
{ x: 0.28125, y: 0.71875 },
{ x: 0.34375, y: 0.71875 },
{ x: 0.34375, y: 0.71875 },
{ x: 0.40625, y: 0.71875 },
{ x: 0.40625, y: 0.71875 },
{ x: 0.46875, y: 0.71875 },
{ x: 0.46875, y: 0.71875 },
{ x: 0.53125, y: 0.71875 },
{ x: 0.53125, y: 0.71875 },
{ x: 0.59375, y: 0.71875 },
{ x: 0.59375, y: 0.71875 },
{ x: 0.65625, y: 0.71875 },
{ x: 0.65625, y: 0.71875 },
{ x: 0.71875, y: 0.71875 },
{ x: 0.71875, y: 0.71875 },
{ x: 0.78125, y: 0.71875 },
{ x: 0.78125, y: 0.71875 },
{ x: 0.84375, y: 0.71875 },
{ x: 0.84375, y: 0.71875 },
{ x: 0.90625, y: 0.71875 },
{ x: 0.90625, y: 0.71875 },
{ x: 0.96875, y: 0.71875 },
{ x: 0.96875, y: 0.71875 },
{ x: 0.03125, y: 0.78125 },
{ x: 0.03125, y: 0.78125 },
{ x: 0.09375, y: 0.78125 },
{ x: 0.09375, y: 0.78125 },
{ x: 0.15625, y: 0.78125 },
{ x: 0.15625, y: 0.78125 },
{ x: 0.21875, y: 0.78125 },
{ x: 0.21875, y: 0.78125 },
{ x: 0.28125, y: 0.78125 },
{ x: 0.28125, y: 0.78125 },
{ x: 0.34375, y: 0.78125 },
{ x: 0.34375, y: 0.78125 },
{ x: 0.40625, y: 0.78125 },
{ x: 0.40625, y: 0.78125 },
{ x: 0.46875, y: 0.78125 },
{ x: 0.46875, y: 0.78125 },
{ x: 0.53125, y: 0.78125 },
{ x: 0.53125, y: 0.78125 },
{ x: 0.59375, y: 0.78125 },
{ x: 0.59375, y: 0.78125 },
{ x: 0.65625, y: 0.78125 },
{ x: 0.65625, y: 0.78125 },
{ x: 0.71875, y: 0.78125 },
{ x: 0.71875, y: 0.78125 },
{ x: 0.78125, y: 0.78125 },
{ x: 0.78125, y: 0.78125 },
{ x: 0.84375, y: 0.78125 },
{ x: 0.84375, y: 0.78125 },
{ x: 0.90625, y: 0.78125 },
{ x: 0.90625, y: 0.78125 },
{ x: 0.96875, y: 0.78125 },
{ x: 0.96875, y: 0.78125 },
{ x: 0.03125, y: 0.84375 },
{ x: 0.03125, y: 0.84375 },
{ x: 0.09375, y: 0.84375 },
{ x: 0.09375, y: 0.84375 },
{ x: 0.15625, y: 0.84375 },
{ x: 0.15625, y: 0.84375 },
{ x: 0.21875, y: 0.84375 },
{ x: 0.21875, y: 0.84375 },
{ x: 0.28125, y: 0.84375 },
{ x: 0.28125, y: 0.84375 },
{ x: 0.34375, y: 0.84375 },
{ x: 0.34375, y: 0.84375 },
{ x: 0.40625, y: 0.84375 },
{ x: 0.40625, y: 0.84375 },
{ x: 0.46875, y: 0.84375 },
{ x: 0.46875, y: 0.84375 },
{ x: 0.53125, y: 0.84375 },
{ x: 0.53125, y: 0.84375 },
{ x: 0.59375, y: 0.84375 },
{ x: 0.59375, y: 0.84375 },
{ x: 0.65625, y: 0.84375 },
{ x: 0.65625, y: 0.84375 },
{ x: 0.71875, y: 0.84375 },
{ x: 0.71875, y: 0.84375 },
{ x: 0.78125, y: 0.84375 },
{ x: 0.78125, y: 0.84375 },
{ x: 0.84375, y: 0.84375 },
{ x: 0.84375, y: 0.84375 },
{ x: 0.90625, y: 0.84375 },
{ x: 0.90625, y: 0.84375 },
{ x: 0.96875, y: 0.84375 },
{ x: 0.96875, y: 0.84375 },
{ x: 0.03125, y: 0.90625 },
{ x: 0.03125, y: 0.90625 },
{ x: 0.09375, y: 0.90625 },
{ x: 0.09375, y: 0.90625 },
{ x: 0.15625, y: 0.90625 },
{ x: 0.15625, y: 0.90625 },
{ x: 0.21875, y: 0.90625 },
{ x: 0.21875, y: 0.90625 },
{ x: 0.28125, y: 0.90625 },
{ x: 0.28125, y: 0.90625 },
{ x: 0.34375, y: 0.90625 },
{ x: 0.34375, y: 0.90625 },
{ x: 0.40625, y: 0.90625 },
{ x: 0.40625, y: 0.90625 },
{ x: 0.46875, y: 0.90625 },
{ x: 0.46875, y: 0.90625 },
{ x: 0.53125, y: 0.90625 },
{ x: 0.53125, y: 0.90625 },
{ x: 0.59375, y: 0.90625 },
{ x: 0.59375, y: 0.90625 },
{ x: 0.65625, y: 0.90625 },
{ x: 0.65625, y: 0.90625 },
{ x: 0.71875, y: 0.90625 },
{ x: 0.71875, y: 0.90625 },
{ x: 0.78125, y: 0.90625 },
{ x: 0.78125, y: 0.90625 },
{ x: 0.84375, y: 0.90625 },
{ x: 0.84375, y: 0.90625 },
{ x: 0.90625, y: 0.90625 },
{ x: 0.90625, y: 0.90625 },
{ x: 0.96875, y: 0.90625 },
{ x: 0.96875, y: 0.90625 },
{ x: 0.03125, y: 0.96875 },
{ x: 0.03125, y: 0.96875 },
{ x: 0.09375, y: 0.96875 },
{ x: 0.09375, y: 0.96875 },
{ x: 0.15625, y: 0.96875 },
{ x: 0.15625, y: 0.96875 },
{ x: 0.21875, y: 0.96875 },
{ x: 0.21875, y: 0.96875 },
{ x: 0.28125, y: 0.96875 },
{ x: 0.28125, y: 0.96875 },
{ x: 0.34375, y: 0.96875 },
{ x: 0.34375, y: 0.96875 },
{ x: 0.40625, y: 0.96875 },
{ x: 0.40625, y: 0.96875 },
{ x: 0.46875, y: 0.96875 },
{ x: 0.46875, y: 0.96875 },
{ x: 0.53125, y: 0.96875 },
{ x: 0.53125, y: 0.96875 },
{ x: 0.59375, y: 0.96875 },
{ x: 0.59375, y: 0.96875 },
{ x: 0.65625, y: 0.96875 },
{ x: 0.65625, y: 0.96875 },
{ x: 0.71875, y: 0.96875 },
{ x: 0.71875, y: 0.96875 },
{ x: 0.78125, y: 0.96875 },
{ x: 0.78125, y: 0.96875 },
{ x: 0.84375, y: 0.96875 },
{ x: 0.84375, y: 0.96875 },
{ x: 0.90625, y: 0.96875 },
{ x: 0.90625, y: 0.96875 },
{ x: 0.96875, y: 0.96875 },
{ x: 0.96875, y: 0.96875 },
{ x: 0.0625, y: 0.0625 },
{ x: 0.0625, y: 0.0625 },
{ x: 0.0625, y: 0.0625 },
{ x: 0.0625, y: 0.0625 },
{ x: 0.0625, y: 0.0625 },
{ x: 0.0625, y: 0.0625 },
{ x: 0.1875, y: 0.0625 },
{ x: 0.1875, y: 0.0625 },
{ x: 0.1875, y: 0.0625 },
{ x: 0.1875, y: 0.0625 },
{ x: 0.1875, y: 0.0625 },
{ x: 0.1875, y: 0.0625 },
{ x: 0.3125, y: 0.0625 },
{ x: 0.3125, y: 0.0625 },
{ x: 0.3125, y: 0.0625 },
{ x: 0.3125, y: 0.0625 },
{ x: 0.3125, y: 0.0625 },
{ x: 0.3125, y: 0.0625 },
{ x: 0.4375, y: 0.0625 },
{ x: 0.4375, y: 0.0625 },
{ x: 0.4375, y: 0.0625 },
{ x: 0.4375, y: 0.0625 },
{ x: 0.4375, y: 0.0625 },
{ x: 0.4375, y: 0.0625 },
{ x: 0.5625, y: 0.0625 },
{ x: 0.5625, y: 0.0625 },
{ x: 0.5625, y: 0.0625 },
{ x: 0.5625, y: 0.0625 },
{ x: 0.5625, y: 0.0625 },
{ x: 0.5625, y: 0.0625 },
{ x: 0.6875, y: 0.0625 },
{ x: 0.6875, y: 0.0625 },
{ x: 0.6875, y: 0.0625 },
{ x: 0.6875, y: 0.0625 },
{ x: 0.6875, y: 0.0625 },
{ x: 0.6875, y: 0.0625 },
{ x: 0.8125, y: 0.0625 },
{ x: 0.8125, y: 0.0625 },
{ x: 0.8125, y: 0.0625 },
{ x: 0.8125, y: 0.0625 },
{ x: 0.8125, y: 0.0625 },
{ x: 0.8125, y: 0.0625 },
{ x: 0.9375, y: 0.0625 },
{ x: 0.9375, y: 0.0625 },
{ x: 0.9375, y: 0.0625 },
{ x: 0.9375, y: 0.0625 },
{ x: 0.9375, y: 0.0625 },
{ x: 0.9375, y: 0.0625 },
{ x: 0.0625, y: 0.1875 },
{ x: 0.0625, y: 0.1875 },
{ x: 0.0625, y: 0.1875 },
{ x: 0.0625, y: 0.1875 },
{ x: 0.0625, y: 0.1875 },
{ x: 0.0625, y: 0.1875 },
{ x: 0.1875, y: 0.1875 },
{ x: 0.1875, y: 0.1875 },
{ x: 0.1875, y: 0.1875 },
{ x: 0.1875, y: 0.1875 },
{ x: 0.1875, y: 0.1875 },
{ x: 0.1875, y: 0.1875 },
{ x: 0.3125, y: 0.1875 },
{ x: 0.3125, y: 0.1875 },
{ x: 0.3125, y: 0.1875 },
{ x: 0.3125, y: 0.1875 },
{ x: 0.3125, y: 0.1875 },
{ x: 0.3125, y: 0.1875 },
{ x: 0.4375, y: 0.1875 },
{ x: 0.4375, y: 0.1875 },
{ x: 0.4375, y: 0.1875 },
{ x: 0.4375, y: 0.1875 },
{ x: 0.4375, y: 0.1875 },
{ x: 0.4375, y: 0.1875 },
{ x: 0.5625, y: 0.1875 },
{ x: 0.5625, y: 0.1875 },
{ x: 0.5625, y: 0.1875 },
{ x: 0.5625, y: 0.1875 },
{ x: 0.5625, y: 0.1875 },
{ x: 0.5625, y: 0.1875 },
{ x: 0.6875, y: 0.1875 },
{ x: 0.6875, y: 0.1875 },
{ x: 0.6875, y: 0.1875 },
{ x: 0.6875, y: 0.1875 },
{ x: 0.6875, y: 0.1875 },
{ x: 0.6875, y: 0.1875 },
{ x: 0.8125, y: 0.1875 },
{ x: 0.8125, y: 0.1875 },
{ x: 0.8125, y: 0.1875 },
{ x: 0.8125, y: 0.1875 },
{ x: 0.8125, y: 0.1875 },
{ x: 0.8125, y: 0.1875 },
{ x: 0.9375, y: 0.1875 },
{ x: 0.9375, y: 0.1875 },
{ x: 0.9375, y: 0.1875 },
{ x: 0.9375, y: 0.1875 },
{ x: 0.9375, y: 0.1875 },
{ x: 0.9375, y: 0.1875 },
{ x: 0.0625, y: 0.3125 },
{ x: 0.0625, y: 0.3125 },
{ x: 0.0625, y: 0.3125 },
{ x: 0.0625, y: 0.3125 },
{ x: 0.0625, y: 0.3125 },
{ x: 0.0625, y: 0.3125 },
{ x: 0.1875, y: 0.3125 },
{ x: 0.1875, y: 0.3125 },
{ x: 0.1875, y: 0.3125 },
{ x: 0.1875, y: 0.3125 },
{ x: 0.1875, y: 0.3125 },
{ x: 0.1875, y: 0.3125 },
{ x: 0.3125, y: 0.3125 },
{ x: 0.3125, y: 0.3125 },
{ x: 0.3125, y: 0.3125 },
{ x: 0.3125, y: 0.3125 },
{ x: 0.3125, y: 0.3125 },
{ x: 0.3125, y: 0.3125 },
{ x: 0.4375, y: 0.3125 },
{ x: 0.4375, y: 0.3125 },
{ x: 0.4375, y: 0.3125 },
{ x: 0.4375, y: 0.3125 },
{ x: 0.4375, y: 0.3125 },
{ x: 0.4375, y: 0.3125 },
{ x: 0.5625, y: 0.3125 },
{ x: 0.5625, y: 0.3125 },
{ x: 0.5625, y: 0.3125 },
{ x: 0.5625, y: 0.3125 },
{ x: 0.5625, y: 0.3125 },
{ x: 0.5625, y: 0.3125 },
{ x: 0.6875, y: 0.3125 },
{ x: 0.6875, y: 0.3125 },
{ x: 0.6875, y: 0.3125 },
{ x: 0.6875, y: 0.3125 },
{ x: 0.6875, y: 0.3125 },
{ x: 0.6875, y: 0.3125 },
{ x: 0.8125, y: 0.3125 },
{ x: 0.8125, y: 0.3125 },
{ x: 0.8125, y: 0.3125 },
{ x: 0.8125, y: 0.3125 },
{ x: 0.8125, y: 0.3125 },
{ x: 0.8125, y: 0.3125 },
{ x: 0.9375, y: 0.3125 },
{ x: 0.9375, y: 0.3125 },
{ x: 0.9375, y: 0.3125 },
{ x: 0.9375, y: 0.3125 },
{ x: 0.9375, y: 0.3125 },
{ x: 0.9375, y: 0.3125 },
{ x: 0.0625, y: 0.4375 },
{ x: 0.0625, y: 0.4375 },
{ x: 0.0625, y: 0.4375 },
{ x: 0.0625, y: 0.4375 },
{ x: 0.0625, y: 0.4375 },
{ x: 0.0625, y: 0.4375 },
{ x: 0.1875, y: 0.4375 },
{ x: 0.1875, y: 0.4375 },
{ x: 0.1875, y: 0.4375 },
{ x: 0.1875, y: 0.4375 },
{ x: 0.1875, y: 0.4375 },
{ x: 0.1875, y: 0.4375 },
{ x: 0.3125, y: 0.4375 },
{ x: 0.3125, y: 0.4375 },
{ x: 0.3125, y: 0.4375 },
{ x: 0.3125, y: 0.4375 },
{ x: 0.3125, y: 0.4375 },
{ x: 0.3125, y: 0.4375 },
{ x: 0.4375, y: 0.4375 },
{ x: 0.4375, y: 0.4375 },
{ x: 0.4375, y: 0.4375 },
{ x: 0.4375, y: 0.4375 },
{ x: 0.4375, y: 0.4375 },
{ x: 0.4375, y: 0.4375 },
{ x: 0.5625, y: 0.4375 },
{ x: 0.5625, y: 0.4375 },
{ x: 0.5625, y: 0.4375 },
{ x: 0.5625, y: 0.4375 },
{ x: 0.5625, y: 0.4375 },
{ x: 0.5625, y: 0.4375 },
{ x: 0.6875, y: 0.4375 },
{ x: 0.6875, y: 0.4375 },
{ x: 0.6875, y: 0.4375 },
{ x: 0.6875, y: 0.4375 },
{ x: 0.6875, y: 0.4375 },
{ x: 0.6875, y: 0.4375 },
{ x: 0.8125, y: 0.4375 },
{ x: 0.8125, y: 0.4375 },
{ x: 0.8125, y: 0.4375 },
{ x: 0.8125, y: 0.4375 },
{ x: 0.8125, y: 0.4375 },
{ x: 0.8125, y: 0.4375 },
{ x: 0.9375, y: 0.4375 },
{ x: 0.9375, y: 0.4375 },
{ x: 0.9375, y: 0.4375 },
{ x: 0.9375, y: 0.4375 },
{ x: 0.9375, y: 0.4375 },
{ x: 0.9375, y: 0.4375 },
{ x: 0.0625, y: 0.5625 },
{ x: 0.0625, y: 0.5625 },
{ x: 0.0625, y: 0.5625 },
{ x: 0.0625, y: 0.5625 },
{ x: 0.0625, y: 0.5625 },
{ x: 0.0625, y: 0.5625 },
{ x: 0.1875, y: 0.5625 },
{ x: 0.1875, y: 0.5625 },
{ x: 0.1875, y: 0.5625 },
{ x: 0.1875, y: 0.5625 },
{ x: 0.1875, y: 0.5625 },
{ x: 0.1875, y: 0.5625 },
{ x: 0.3125, y: 0.5625 },
{ x: 0.3125, y: 0.5625 },
{ x: 0.3125, y: 0.5625 },
{ x: 0.3125, y: 0.5625 },
{ x: 0.3125, y: 0.5625 },
{ x: 0.3125, y: 0.5625 },
{ x: 0.4375, y: 0.5625 },
{ x: 0.4375, y: 0.5625 },
{ x: 0.4375, y: 0.5625 },
{ x: 0.4375, y: 0.5625 },
{ x: 0.4375, y: 0.5625 },
{ x: 0.4375, y: 0.5625 },
{ x: 0.5625, y: 0.5625 },
{ x: 0.5625, y: 0.5625 },
{ x: 0.5625, y: 0.5625 },
{ x: 0.5625, y: 0.5625 },
{ x: 0.5625, y: 0.5625 },
{ x: 0.5625, y: 0.5625 },
{ x: 0.6875, y: 0.5625 },
{ x: 0.6875, y: 0.5625 },
{ x: 0.6875, y: 0.5625 },
{ x: 0.6875, y: 0.5625 },
{ x: 0.6875, y: 0.5625 },
{ x: 0.6875, y: 0.5625 },
{ x: 0.8125, y: 0.5625 },
{ x: 0.8125, y: 0.5625 },
{ x: 0.8125, y: 0.5625 },
{ x: 0.8125, y: 0.5625 },
{ x: 0.8125, y: 0.5625 },
{ x: 0.8125, y: 0.5625 },
{ x: 0.9375, y: 0.5625 },
{ x: 0.9375, y: 0.5625 },
{ x: 0.9375, y: 0.5625 },
{ x: 0.9375, y: 0.5625 },
{ x: 0.9375, y: 0.5625 },
{ x: 0.9375, y: 0.5625 },
{ x: 0.0625, y: 0.6875 },
{ x: 0.0625, y: 0.6875 },
{ x: 0.0625, y: 0.6875 },
{ x: 0.0625, y: 0.6875 },
{ x: 0.0625, y: 0.6875 },
{ x: 0.0625, y: 0.6875 },
{ x: 0.1875, y: 0.6875 },
{ x: 0.1875, y: 0.6875 },
{ x: 0.1875, y: 0.6875 },
{ x: 0.1875, y: 0.6875 },
{ x: 0.1875, y: 0.6875 },
{ x: 0.1875, y: 0.6875 },
{ x: 0.3125, y: 0.6875 },
{ x: 0.3125, y: 0.6875 },
{ x: 0.3125, y: 0.6875 },
{ x: 0.3125, y: 0.6875 },
{ x: 0.3125, y: 0.6875 },
{ x: 0.3125, y: 0.6875 },
{ x: 0.4375, y: 0.6875 },
{ x: 0.4375, y: 0.6875 },
{ x: 0.4375, y: 0.6875 },
{ x: 0.4375, y: 0.6875 },
{ x: 0.4375, y: 0.6875 },
{ x: 0.4375, y: 0.6875 },
{ x: 0.5625, y: 0.6875 },
{ x: 0.5625, y: 0.6875 },
{ x: 0.5625, y: 0.6875 },
{ x: 0.5625, y: 0.6875 },
{ x: 0.5625, y: 0.6875 },
{ x: 0.5625, y: 0.6875 },
{ x: 0.6875, y: 0.6875 },
{ x: 0.6875, y: 0.6875 },
{ x: 0.6875, y: 0.6875 },
{ x: 0.6875, y: 0.6875 },
{ x: 0.6875, y: 0.6875 },
{ x: 0.6875, y: 0.6875 },
{ x: 0.8125, y: 0.6875 },
{ x: 0.8125, y: 0.6875 },
{ x: 0.8125, y: 0.6875 },
{ x: 0.8125, y: 0.6875 },
{ x: 0.8125, y: 0.6875 },
{ x: 0.8125, y: 0.6875 },
{ x: 0.9375, y: 0.6875 },
{ x: 0.9375, y: 0.6875 },
{ x: 0.9375, y: 0.6875 },
{ x: 0.9375, y: 0.6875 },
{ x: 0.9375, y: 0.6875 },
{ x: 0.9375, y: 0.6875 },
{ x: 0.0625, y: 0.8125 },
{ x: 0.0625, y: 0.8125 },
{ x: 0.0625, y: 0.8125 },
{ x: 0.0625, y: 0.8125 },
{ x: 0.0625, y: 0.8125 },
{ x: 0.0625, y: 0.8125 },
{ x: 0.1875, y: 0.8125 },
{ x: 0.1875, y: 0.8125 },
{ x: 0.1875, y: 0.8125 },
{ x: 0.1875, y: 0.8125 },
{ x: 0.1875, y: 0.8125 },
{ x: 0.1875, y: 0.8125 },
{ x: 0.3125, y: 0.8125 },
{ x: 0.3125, y: 0.8125 },
{ x: 0.3125, y: 0.8125 },
{ x: 0.3125, y: 0.8125 },
{ x: 0.3125, y: 0.8125 },
{ x: 0.3125, y: 0.8125 },
{ x: 0.4375, y: 0.8125 },
{ x: 0.4375, y: 0.8125 },
{ x: 0.4375, y: 0.8125 },
{ x: 0.4375, y: 0.8125 },
{ x: 0.4375, y: 0.8125 },
{ x: 0.4375, y: 0.8125 },
{ x: 0.5625, y: 0.8125 },
{ x: 0.5625, y: 0.8125 },
{ x: 0.5625, y: 0.8125 },
{ x: 0.5625, y: 0.8125 },
{ x: 0.5625, y: 0.8125 },
{ x: 0.5625, y: 0.8125 },
{ x: 0.6875, y: 0.8125 },
{ x: 0.6875, y: 0.8125 },
{ x: 0.6875, y: 0.8125 },
{ x: 0.6875, y: 0.8125 },
{ x: 0.6875, y: 0.8125 },
{ x: 0.6875, y: 0.8125 },
{ x: 0.8125, y: 0.8125 },
{ x: 0.8125, y: 0.8125 },
{ x: 0.8125, y: 0.8125 },
{ x: 0.8125, y: 0.8125 },
{ x: 0.8125, y: 0.8125 },
{ x: 0.8125, y: 0.8125 },
{ x: 0.9375, y: 0.8125 },
{ x: 0.9375, y: 0.8125 },
{ x: 0.9375, y: 0.8125 },
{ x: 0.9375, y: 0.8125 },
{ x: 0.9375, y: 0.8125 },
{ x: 0.9375, y: 0.8125 },
{ x: 0.0625, y: 0.9375 },
{ x: 0.0625, y: 0.9375 },
{ x: 0.0625, y: 0.9375 },
{ x: 0.0625, y: 0.9375 },
{ x: 0.0625, y: 0.9375 },
{ x: 0.0625, y: 0.9375 },
{ x: 0.1875, y: 0.9375 },
{ x: 0.1875, y: 0.9375 },
{ x: 0.1875, y: 0.9375 },
{ x: 0.1875, y: 0.9375 },
{ x: 0.1875, y: 0.9375 },
{ x: 0.1875, y: 0.9375 },
{ x: 0.3125, y: 0.9375 },
{ x: 0.3125, y: 0.9375 },
{ x: 0.3125, y: 0.9375 },
{ x: 0.3125, y: 0.9375 },
{ x: 0.3125, y: 0.9375 },
{ x: 0.3125, y: 0.9375 },
{ x: 0.4375, y: 0.9375 },
{ x: 0.4375, y: 0.9375 },
{ x: 0.4375, y: 0.9375 },
{ x: 0.4375, y: 0.9375 },
{ x: 0.4375, y: 0.9375 },
{ x: 0.4375, y: 0.9375 },
{ x: 0.5625, y: 0.9375 },
{ x: 0.5625, y: 0.9375 },
{ x: 0.5625, y: 0.9375 },
{ x: 0.5625, y: 0.9375 },
{ x: 0.5625, y: 0.9375 },
{ x: 0.5625, y: 0.9375 },
{ x: 0.6875, y: 0.9375 },
{ x: 0.6875, y: 0.9375 },
{ x: 0.6875, y: 0.9375 },
{ x: 0.6875, y: 0.9375 },
{ x: 0.6875, y: 0.9375 },
{ x: 0.6875, y: 0.9375 },
{ x: 0.8125, y: 0.9375 },
{ x: 0.8125, y: 0.9375 },
{ x: 0.8125, y: 0.9375 },
{ x: 0.8125, y: 0.9375 },
{ x: 0.8125, y: 0.9375 },
{ x: 0.8125, y: 0.9375 },
{ x: 0.9375, y: 0.9375 },
{ x: 0.9375, y: 0.9375 },
{ x: 0.9375, y: 0.9375 },
{ x: 0.9375, y: 0.9375 },
{ x: 0.9375, y: 0.9375 },
{ x: 0.9375, y: 0.9375 }
];
// src/hand/handposedetector.ts
var HandDetector = class {
constructor(model14) {
__publicField(this, "model");
__publicField(this, "anchors");
__publicField(this, "anchorsTensor");
__publicField(this, "inputSize");
__publicField(this, "inputSizeTensor");
__publicField(this, "doubleInputSizeTensor");
this.model = model14;
this.anchors = anchors2.map((anchor) => [anchor.x, anchor.y]);
this.anchorsTensor = ki(this.anchors);
this.inputSize = this.model && this.model.inputs && this.model.inputs[0].shape ? this.model.inputs[0].shape[2] : 0;
this.inputSizeTensor = $t([this.inputSize, this.inputSize]);
this.doubleInputSizeTensor = $t([this.inputSize * 2, this.inputSize * 2]);
}
normalizeBoxes(boxes) {
return V(() => {
const boxOffsets = Oe(boxes, [0, 0], [-1, 2]);
const boxSizes = Oe(boxes, [0, 2], [-1, 2]);
const boxCenterPoints = Z(ce(boxOffsets, this.inputSizeTensor), this.anchorsTensor);
const halfBoxSizes = ce(boxSizes, this.doubleInputSizeTensor);
const startPoints = O(le(boxCenterPoints, halfBoxSizes), this.inputSizeTensor);
const endPoints = O(Z(boxCenterPoints, halfBoxSizes), this.inputSizeTensor);
return W_([startPoints, endPoints], 1);
});
}
normalizeLandmarks(rawPalmLandmarks, index) {
return V(() => {
const landmarks = Z(ce(F(rawPalmLandmarks, [-1, 7, 2]), this.inputSizeTensor), this.anchors[index]);
return O(landmarks, this.inputSizeTensor);
});
}
async getBoxes(input, config3) {
const t = {};
t.batched = this.model.predict(input);
t.predictions = Br(t.batched);
t.scores = V(() => Br(zr(Oe(t.predictions, [0, 0], [-1, 1]))));
const scores = await t.scores.data();
t.boxes = Oe(t.predictions, [0, 1], [-1, 4]);
t.norm = this.normalizeBoxes(t.boxes);
t.nms = await Cn.nonMaxSuppressionAsync(t.norm, t.scores, 3 * config3.hand.maxDetected, config3.hand.iouThreshold, config3.hand.minConfidence);
const nms = await t.nms.array();
const hands = [];
for (const index of nms) {
const palmBox = Oe(t.norm, [index, 0], [1, -1]);
const palmLandmarks = V(() => F(this.normalizeLandmarks(Oe(t.predictions, [index, 5], [1, 14]), index), [-1, 2]));
hands.push({ box: palmBox, palmLandmarks, confidence: scores[index] });
}
for (const tensor of Object.keys(t))
De(t[tensor]);
return hands;
}
async estimateHandBounds(input, config3) {
const inputHeight = input.shape[1];
const inputWidth = input.shape[2];
const image6 = V(() => le(ce(Cn.resizeBilinear(input, [this.inputSize, this.inputSize]), 127.5), 1));
const predictions = await this.getBoxes(image6, config3);
De(image6);
const hands = [];
if (!predictions || predictions.length === 0)
return hands;
for (const prediction of predictions) {
const boxes = await prediction.box.data();
const startPoint = boxes.slice(0, 2);
const endPoint = boxes.slice(2, 4);
const palmLandmarks = await prediction.palmLandmarks.array();
De(prediction.box);
De(prediction.palmLandmarks);
hands.push(scaleBoxCoordinates2({ startPoint, endPoint, palmLandmarks, confidence: prediction.confidence }, [inputWidth / this.inputSize, inputHeight / this.inputSize]));
}
return hands;
}
};
// src/hand/handposepipeline.ts
var palmBoxEnlargeFactor = 5;
var handBoxEnlargeFactor = 1.65;
var palmLandmarkIds = [0, 5, 9, 13, 17, 1, 2];
var palmLandmarksPalmBase = 0;
var palmLandmarksMiddleFingerBase = 2;
var lastTime5 = 0;
var HandPipeline = class {
constructor(handDetector, handPoseModel2) {
__publicField(this, "handDetector");
__publicField(this, "handPoseModel");
__publicField(this, "inputSize");
__publicField(this, "storedBoxes");
__publicField(this, "skipped");
__publicField(this, "detectedHands");
this.handDetector = handDetector;
this.handPoseModel = handPoseModel2;
this.inputSize = this.handPoseModel && this.handPoseModel.inputs[0].shape ? this.handPoseModel.inputs[0].shape[2] : 0;
this.storedBoxes = [];
this.skipped = 0;
this.detectedHands = 0;
}
calculateLandmarksBoundingBox(landmarks) {
const xs2 = landmarks.map((d) => d[0]);
const ys2 = landmarks.map((d) => d[1]);
const startPoint = [Math.min(...xs2), Math.min(...ys2)];
const endPoint = [Math.max(...xs2), Math.max(...ys2)];
return { startPoint, endPoint };
}
getBoxForPalmLandmarks(palmLandmarks, rotationMatrix) {
const rotatedPalmLandmarks = palmLandmarks.map((coord) => rotatePoint2([...coord, 1], rotationMatrix));
const boxAroundPalm = this.calculateLandmarksBoundingBox(rotatedPalmLandmarks);
return enlargeBox2(squarifyBox2(boxAroundPalm), palmBoxEnlargeFactor);
}
getBoxForHandLandmarks(landmarks) {
const boundingBox = this.calculateLandmarksBoundingBox(landmarks);
const boxAroundHand = enlargeBox2(squarifyBox2(boundingBox), handBoxEnlargeFactor);
boxAroundHand.palmLandmarks = [];
for (let i = 0; i < palmLandmarkIds.length; i++) {
boxAroundHand.palmLandmarks.push(landmarks[palmLandmarkIds[i]].slice(0, 2));
}
return boxAroundHand;
}
transformRawCoords(rawCoords, box22, angle, rotationMatrix) {
const boxSize = getBoxSize2(box22);
const scaleFactor = [boxSize[0] / this.inputSize, boxSize[1] / this.inputSize, (boxSize[0] + boxSize[1]) / this.inputSize / 2];
const coordsScaled = rawCoords.map((coord) => [
scaleFactor[0] * (coord[0] - this.inputSize / 2),
scaleFactor[1] * (coord[1] - this.inputSize / 2),
scaleFactor[2] * coord[2]
]);
const coordsRotationMatrix = buildRotationMatrix2(angle, [0, 0]);
const coordsRotated = coordsScaled.map((coord) => {
const rotated = rotatePoint2(coord, coordsRotationMatrix);
return [...rotated, coord[2]];
});
const inverseRotationMatrix = invertTransformMatrix2(rotationMatrix);
const boxCenter = [...getBoxCenter2(box22), 1];
const originalBoxCenter = [
dot2(boxCenter, inverseRotationMatrix[0]),
dot2(boxCenter, inverseRotationMatrix[1])
];
return coordsRotated.map((coord) => [
Math.trunc(coord[0] + originalBoxCenter[0]),
Math.trunc(coord[1] + originalBoxCenter[1]),
Math.trunc(coord[2])
]);
}
async estimateHands(image6, config3) {
let useFreshBox = false;
let boxes;
if (this.skipped === 0 || this.skipped > config3.hand.skipFrames && (config3.hand.skipTime || 0) <= now() - lastTime5 || !config3.hand.landmarks || !config3.skipFrame) {
boxes = await this.handDetector.estimateHandBounds(image6, config3);
this.skipped = 0;
}
if (config3.skipFrame)
this.skipped++;
if (boxes && boxes.length > 0 && (boxes.length !== this.detectedHands && this.detectedHands !== config3.hand.maxDetected || !config3.hand.landmarks)) {
this.detectedHands = 0;
this.storedBoxes = [...boxes];
if (this.storedBoxes.length > 0)
useFreshBox = true;
}
const hands = [];
for (let i = 0; i < this.storedBoxes.length; i++) {
const currentBox = this.storedBoxes[i];
if (!currentBox)
continue;
if (config3.hand.landmarks) {
const angle = config3.hand.rotation ? computeRotation2(currentBox.palmLandmarks[palmLandmarksPalmBase], currentBox.palmLandmarks[palmLandmarksMiddleFingerBase]) : 0;
const palmCenter = getBoxCenter2(currentBox);
const palmCenterNormalized = [palmCenter[0] / image6.shape[2], palmCenter[1] / image6.shape[1]];
const rotatedImage = config3.hand.rotation && env.kernels.includes("rotatewithoffset") ? Cn.rotateWithOffset(image6, angle, 0, palmCenterNormalized) : image6.clone();
const rotationMatrix = buildRotationMatrix2(-angle, palmCenter);
const newBox = useFreshBox ? this.getBoxForPalmLandmarks(currentBox.palmLandmarks, rotationMatrix) : currentBox;
const croppedInput = cutBoxFromImageAndResize2(newBox, rotatedImage, [this.inputSize, this.inputSize]);
const handImage = ce(croppedInput, 255);
De(croppedInput);
De(rotatedImage);
const [confidenceT, keypoints] = await this.handPoseModel.predict(handImage);
lastTime5 = now();
De(handImage);
const confidence = (await confidenceT.data())[0];
De(confidenceT);
if (confidence >= config3.hand.minConfidence / 4) {
const keypointsReshaped = F(keypoints, [-1, 3]);
const rawCoords = await keypointsReshaped.array();
De(keypoints);
De(keypointsReshaped);
const coords8 = this.transformRawCoords(rawCoords, newBox, angle, rotationMatrix);
const nextBoundingBox = this.getBoxForHandLandmarks(coords8);
this.storedBoxes[i] = { ...nextBoundingBox, confidence };
const result = {
landmarks: coords8,
confidence,
boxConfidence: currentBox.confidence,
fingerConfidence: confidence,
box: { topLeft: nextBoundingBox.startPoint, bottomRight: nextBoundingBox.endPoint }
};
hands.push(result);
} else {
this.storedBoxes[i] = null;
}
De(keypoints);
} else {
const enlarged = enlargeBox2(squarifyBox2(currentBox), handBoxEnlargeFactor);
const result = {
confidence: currentBox.confidence,
boxConfidence: currentBox.confidence,
fingerConfidence: 0,
box: { topLeft: enlarged.startPoint, bottomRight: enlarged.endPoint },
landmarks: []
};
hands.push(result);
}
}
this.storedBoxes = this.storedBoxes.filter((a) => a !== null);
this.detectedHands = hands.length;
if (hands.length > config3.hand.maxDetected)
hands.length = config3.hand.maxDetected;
return hands;
}
};
// src/hand/fingerdef.ts
var Finger = {
thumb: 0,
index: 1,
middle: 2,
ring: 3,
pinky: 4,
all: [0, 1, 2, 3, 4],
nameMapping: { 0: "thumb", 1: "index", 2: "middle", 3: "ring", 4: "pinky" },
pointsMapping: {
0: [[0, 1], [1, 2], [2, 3], [3, 4]],
1: [[0, 5], [5, 6], [6, 7], [7, 8]],
2: [[0, 9], [9, 10], [10, 11], [11, 12]],
3: [[0, 13], [13, 14], [14, 15], [15, 16]],
4: [[0, 17], [17, 18], [18, 19], [19, 20]]
},
getName: (value) => Finger.nameMapping[value],
getPoints: (value) => Finger.pointsMapping[value]
};
var FingerCurl = {
none: 0,
half: 1,
full: 2,
nameMapping: { 0: "none", 1: "half", 2: "full" },
getName: (value) => FingerCurl.nameMapping[value]
};
var FingerDirection = {
verticalUp: 0,
verticalDown: 1,
horizontalLeft: 2,
horizontalRight: 3,
diagonalUpRight: 4,
diagonalUpLeft: 5,
diagonalDownRight: 6,
diagonalDownLeft: 7,
nameMapping: { 0: "verticalUp", 1: "verticalDown", 2: "horizontalLeft", 3: "horizontalRight", 4: "diagonalUpRight", 5: "diagonalUpLeft", 6: "diagonalDownRight", 7: "diagonalDownLeft" },
getName: (value) => FingerDirection.nameMapping[value]
};
var FingerGesture = class {
constructor(name) {
__publicField(this, "name");
__publicField(this, "curls");
__publicField(this, "directions");
__publicField(this, "weights");
__publicField(this, "weightsRelative");
this.name = name;
this.curls = {};
this.directions = {};
this.weights = [1, 1, 1, 1, 1];
this.weightsRelative = [1, 1, 1, 1, 1];
}
addCurl(finger, curl, confidence) {
if (typeof this.curls[finger] === "undefined")
this.curls[finger] = [];
this.curls[finger].push([curl, confidence]);
}
addDirection(finger, position, confidence) {
if (!this.directions[finger])
this.directions[finger] = [];
this.directions[finger].push([position, confidence]);
}
setWeight(finger, weight) {
this.weights[finger] = weight;
const total = this.weights.reduce((a, b10) => a + b10, 0);
this.weightsRelative = this.weights.map((el2) => el2 * 5 / total);
}
matchAgainst(detectedCurls, detectedDirections) {
let confidence = 0;
for (const fingerIdx in detectedCurls) {
const detectedCurl = detectedCurls[fingerIdx];
const expectedCurls = this.curls[fingerIdx];
if (typeof expectedCurls === "undefined") {
confidence += this.weightsRelative[fingerIdx];
continue;
}
for (const [expectedCurl, score] of expectedCurls) {
if (detectedCurl === expectedCurl) {
confidence += score * this.weightsRelative[fingerIdx];
break;
}
}
}
for (const fingerIdx in detectedDirections) {
const detectedDirection = detectedDirections[fingerIdx];
const expectedDirections = this.directions[fingerIdx];
if (typeof expectedDirections === "undefined") {
confidence += this.weightsRelative[fingerIdx];
continue;
}
for (const [expectedDirection, score] of expectedDirections) {
if (detectedDirection === expectedDirection) {
confidence += score * this.weightsRelative[fingerIdx];
break;
}
}
}
return confidence / 10;
}
};
// src/hand/fingergesture.ts
var ThumbsUp = new FingerGesture("thumbs up");
ThumbsUp.addCurl(Finger.thumb, FingerCurl.none, 1);
ThumbsUp.addDirection(Finger.thumb, FingerDirection.verticalUp, 1);
ThumbsUp.addDirection(Finger.thumb, FingerDirection.diagonalUpLeft, 0.25);
ThumbsUp.addDirection(Finger.thumb, FingerDirection.diagonalUpRight, 0.25);
for (const finger of [Finger.index, Finger.middle, Finger.ring, Finger.pinky]) {
ThumbsUp.addCurl(finger, FingerCurl.full, 1);
ThumbsUp.addDirection(finger, FingerDirection.horizontalLeft, 1);
ThumbsUp.addDirection(finger, FingerDirection.horizontalRight, 1);
}
var Victory = new FingerGesture("victory");
Victory.addCurl(Finger.thumb, FingerCurl.half, 0.5);
Victory.addCurl(Finger.thumb, FingerCurl.none, 0.5);
Victory.addDirection(Finger.thumb, FingerDirection.verticalUp, 1);
Victory.addDirection(Finger.thumb, FingerDirection.diagonalUpLeft, 1);
Victory.addCurl(Finger.index, FingerCurl.none, 1);
Victory.addDirection(Finger.index, FingerDirection.verticalUp, 0.75);
Victory.addDirection(Finger.index, FingerDirection.diagonalUpLeft, 1);
Victory.addCurl(Finger.middle, FingerCurl.none, 1);
Victory.addDirection(Finger.middle, FingerDirection.verticalUp, 1);
Victory.addDirection(Finger.middle, FingerDirection.diagonalUpLeft, 0.75);
Victory.addCurl(Finger.ring, FingerCurl.full, 1);
Victory.addDirection(Finger.ring, FingerDirection.verticalUp, 0.2);
Victory.addDirection(Finger.ring, FingerDirection.diagonalUpLeft, 1);
Victory.addDirection(Finger.ring, FingerDirection.horizontalLeft, 0.2);
Victory.addCurl(Finger.pinky, FingerCurl.full, 1);
Victory.addDirection(Finger.pinky, FingerDirection.verticalUp, 0.2);
Victory.addDirection(Finger.pinky, FingerDirection.diagonalUpLeft, 1);
Victory.addDirection(Finger.pinky, FingerDirection.horizontalLeft, 0.2);
Victory.setWeight(Finger.index, 2);
Victory.setWeight(Finger.middle, 2);
var fingergesture_default = [ThumbsUp, Victory];
// src/hand/fingerpose.ts
var minConfidence = 0.7;
var options = {
HALF_CURL_START_LIMIT: 60,
NO_CURL_START_LIMIT: 130,
DISTANCE_VOTE_POWER: 1.1,
SINGLE_ANGLE_VOTE_POWER: 0.9,
TOTAL_ANGLE_VOTE_POWER: 1.6
};
function calculateSlope(point1x, point1y, point2x, point2y) {
const value = (point1y - point2y) / (point1x - point2x);
let slope = Math.atan(value) * 180 / Math.PI;
if (slope <= 0)
slope = -slope;
else if (slope > 0)
slope = 180 - slope;
return slope;
}
function getSlopes(point1, point2) {
if (!point1 || !point2)
return [0, 0];
const slopeXY = calculateSlope(point1[0], point1[1], point2[0], point2[1]);
if (point1.length === 2)
return slopeXY;
const slopeYZ = calculateSlope(point1[1], point1[2], point2[1], point2[2]);
return [slopeXY, slopeYZ];
}
function angleOrientationAt(angle, weightageAt = 1) {
let isVertical = 0;
let isDiagonal = 0;
let isHorizontal = 0;
if (angle >= 75 && angle <= 105)
isVertical = 1 * weightageAt;
else if (angle >= 25 && angle <= 155)
isDiagonal = 1 * weightageAt;
else
isHorizontal = 1 * weightageAt;
return [isVertical, isDiagonal, isHorizontal];
}
function estimateFingerCurl(startPoint, midPoint, endPoint) {
const start_mid_x_dist = startPoint[0] - midPoint[0];
const start_end_x_dist = startPoint[0] - endPoint[0];
const mid_end_x_dist = midPoint[0] - endPoint[0];
const start_mid_y_dist = startPoint[1] - midPoint[1];
const start_end_y_dist = startPoint[1] - endPoint[1];
const mid_end_y_dist = midPoint[1] - endPoint[1];
const start_mid_z_dist = startPoint[2] - midPoint[2];
const start_end_z_dist = startPoint[2] - endPoint[2];
const mid_end_z_dist = midPoint[2] - endPoint[2];
const start_mid_dist = Math.sqrt(start_mid_x_dist * start_mid_x_dist + start_mid_y_dist * start_mid_y_dist + start_mid_z_dist * start_mid_z_dist);
const start_end_dist = Math.sqrt(start_end_x_dist * start_end_x_dist + start_end_y_dist * start_end_y_dist + start_end_z_dist * start_end_z_dist);
const mid_end_dist = Math.sqrt(mid_end_x_dist * mid_end_x_dist + mid_end_y_dist * mid_end_y_dist + mid_end_z_dist * mid_end_z_dist);
let cos_in = (mid_end_dist * mid_end_dist + start_mid_dist * start_mid_dist - start_end_dist * start_end_dist) / (2 * mid_end_dist * start_mid_dist);
if (cos_in > 1)
cos_in = 1;
else if (cos_in < -1)
cos_in = -1;
let angleOfCurve = Math.acos(cos_in);
angleOfCurve = 57.2958 * angleOfCurve % 180;
let fingerCurl;
if (angleOfCurve > options.NO_CURL_START_LIMIT)
fingerCurl = FingerCurl.none;
else if (angleOfCurve > options.HALF_CURL_START_LIMIT)
fingerCurl = FingerCurl.half;
else
fingerCurl = FingerCurl.full;
return fingerCurl;
}
function estimateHorizontalDirection(start_end_x_dist, start_mid_x_dist, mid_end_x_dist, max_dist_x) {
let estimatedDirection;
if (max_dist_x === Math.abs(start_end_x_dist)) {
if (start_end_x_dist > 0)
estimatedDirection = FingerDirection.horizontalLeft;
else
estimatedDirection = FingerDirection.horizontalRight;
} else if (max_dist_x === Math.abs(start_mid_x_dist)) {
if (start_mid_x_dist > 0)
estimatedDirection = FingerDirection.horizontalLeft;
else
estimatedDirection = FingerDirection.horizontalRight;
} else {
if (mid_end_x_dist > 0)
estimatedDirection = FingerDirection.horizontalLeft;
else
estimatedDirection = FingerDirection.horizontalRight;
}
return estimatedDirection;
}
function estimateVerticalDirection(start_end_y_dist, start_mid_y_dist, mid_end_y_dist, max_dist_y) {
let estimatedDirection;
if (max_dist_y === Math.abs(start_end_y_dist)) {
if (start_end_y_dist < 0)
estimatedDirection = FingerDirection.verticalDown;
else
estimatedDirection = FingerDirection.verticalUp;
} else if (max_dist_y === Math.abs(start_mid_y_dist)) {
if (start_mid_y_dist < 0)
estimatedDirection = FingerDirection.verticalDown;
else
estimatedDirection = FingerDirection.verticalUp;
} else {
if (mid_end_y_dist < 0)
estimatedDirection = FingerDirection.verticalDown;
else
estimatedDirection = FingerDirection.verticalUp;
}
return estimatedDirection;
}
function estimateDiagonalDirection(start_end_y_dist, start_mid_y_dist, mid_end_y_dist, max_dist_y, start_end_x_dist, start_mid_x_dist, mid_end_x_dist, max_dist_x) {
let estimatedDirection;
const reqd_vertical_direction = estimateVerticalDirection(start_end_y_dist, start_mid_y_dist, mid_end_y_dist, max_dist_y);
const reqd_horizontal_direction = estimateHorizontalDirection(start_end_x_dist, start_mid_x_dist, mid_end_x_dist, max_dist_x);
if (reqd_vertical_direction === FingerDirection.verticalUp) {
if (reqd_horizontal_direction === FingerDirection.horizontalLeft)
estimatedDirection = FingerDirection.diagonalUpLeft;
else
estimatedDirection = FingerDirection.diagonalUpRight;
} else {
if (reqd_horizontal_direction === FingerDirection.horizontalLeft)
estimatedDirection = FingerDirection.diagonalDownLeft;
else
estimatedDirection = FingerDirection.diagonalDownRight;
}
return estimatedDirection;
}
function calculateFingerDirection(startPoint, midPoint, endPoint, fingerSlopes) {
const start_mid_x_dist = startPoint[0] - midPoint[0];
const start_end_x_dist = startPoint[0] - endPoint[0];
const mid_end_x_dist = midPoint[0] - endPoint[0];
const start_mid_y_dist = startPoint[1] - midPoint[1];
const start_end_y_dist = startPoint[1] - endPoint[1];
const mid_end_y_dist = midPoint[1] - endPoint[1];
const max_dist_x = Math.max(Math.abs(start_mid_x_dist), Math.abs(start_end_x_dist), Math.abs(mid_end_x_dist));
const max_dist_y = Math.max(Math.abs(start_mid_y_dist), Math.abs(start_end_y_dist), Math.abs(mid_end_y_dist));
let voteVertical = 0;
let voteDiagonal = 0;
let voteHorizontal = 0;
const start_end_x_y_dist_ratio = max_dist_y / (max_dist_x + 1e-5);
if (start_end_x_y_dist_ratio > 1.5)
voteVertical += options.DISTANCE_VOTE_POWER;
else if (start_end_x_y_dist_ratio > 0.66)
voteDiagonal += options.DISTANCE_VOTE_POWER;
else
voteHorizontal += options.DISTANCE_VOTE_POWER;
const start_mid_dist = Math.sqrt(start_mid_x_dist * start_mid_x_dist + start_mid_y_dist * start_mid_y_dist);
const start_end_dist = Math.sqrt(start_end_x_dist * start_end_x_dist + start_end_y_dist * start_end_y_dist);
const mid_end_dist = Math.sqrt(mid_end_x_dist * mid_end_x_dist + mid_end_y_dist * mid_end_y_dist);
const max_dist = Math.max(start_mid_dist, start_end_dist, mid_end_dist);
let calc_start_point_x = startPoint[0];
let calc_start_point_y = startPoint[1];
let calc_end_point_x = endPoint[0];
let calc_end_point_y = endPoint[1];
if (max_dist === start_mid_dist) {
calc_end_point_x = endPoint[0];
calc_end_point_y = endPoint[1];
} else if (max_dist === mid_end_dist) {
calc_start_point_x = midPoint[0];
calc_start_point_y = midPoint[1];
}
const calcStartPoint = [calc_start_point_x, calc_start_point_y];
const calcEndPoint = [calc_end_point_x, calc_end_point_y];
const totalAngle = getSlopes(calcStartPoint, calcEndPoint);
const votes = angleOrientationAt(totalAngle, options.TOTAL_ANGLE_VOTE_POWER);
voteVertical += votes[0];
voteDiagonal += votes[1];
voteHorizontal += votes[2];
for (const fingerSlope of fingerSlopes) {
const fingerVotes = angleOrientationAt(fingerSlope, options.SINGLE_ANGLE_VOTE_POWER);
voteVertical += fingerVotes[0];
voteDiagonal += fingerVotes[1];
voteHorizontal += fingerVotes[2];
}
let estimatedDirection;
if (voteVertical === Math.max(voteVertical, voteDiagonal, voteHorizontal)) {
estimatedDirection = estimateVerticalDirection(start_end_y_dist, start_mid_y_dist, mid_end_y_dist, max_dist_y);
} else if (voteHorizontal === Math.max(voteDiagonal, voteHorizontal)) {
estimatedDirection = estimateHorizontalDirection(start_end_x_dist, start_mid_x_dist, mid_end_x_dist, max_dist_x);
} else {
estimatedDirection = estimateDiagonalDirection(start_end_y_dist, start_mid_y_dist, mid_end_y_dist, max_dist_y, start_end_x_dist, start_mid_x_dist, mid_end_x_dist, max_dist_x);
}
return estimatedDirection;
}
function estimate(landmarks) {
const slopesXY = [];
const slopesYZ = [];
const fingerCurls = [];
const fingerDirections = [];
if (!landmarks)
return { curls: fingerCurls, directions: fingerDirections };
for (const finger of Finger.all) {
const points = Finger.getPoints(finger);
const slopeAtXY = [];
const slopeAtYZ = [];
for (const point2 of points) {
const point1 = landmarks[point2[0]];
const point22 = landmarks[point2[1]];
const slopes = getSlopes(point1, point22);
const slopeXY = slopes[0];
const slopeYZ = slopes[1];
slopeAtXY.push(slopeXY);
slopeAtYZ.push(slopeYZ);
}
slopesXY.push(slopeAtXY);
slopesYZ.push(slopeAtYZ);
}
for (const finger of Finger.all) {
const pointIndexAt = finger === Finger.thumb ? 1 : 0;
const fingerPointsAt = Finger.getPoints(finger);
const startPoint = landmarks[fingerPointsAt[pointIndexAt][0]];
const midPoint = landmarks[fingerPointsAt[pointIndexAt + 1][1]];
const endPoint = landmarks[fingerPointsAt[3][1]];
const fingerCurled = estimateFingerCurl(startPoint, midPoint, endPoint);
const fingerPosition = calculateFingerDirection(startPoint, midPoint, endPoint, slopesXY[finger].slice(pointIndexAt));
fingerCurls[finger] = fingerCurled;
fingerDirections[finger] = fingerPosition;
}
return { curls: fingerCurls, directions: fingerDirections };
}
function analyze(keypoints) {
if (!keypoints || keypoints.length === 0)
return null;
const estimatorRes = estimate(keypoints);
const landmarks = {};
for (const fingerIdx of Finger.all) {
landmarks[Finger.getName(fingerIdx)] = {
curl: FingerCurl.getName(estimatorRes.curls[fingerIdx]),
direction: FingerDirection.getName(estimatorRes.directions[fingerIdx])
};
}
return landmarks;
}
function match(keypoints) {
const poses = [];
if (!keypoints || keypoints.length === 0)
return poses;
const estimatorRes = estimate(keypoints);
for (const gesture3 of fingergesture_default) {
const confidence = gesture3.matchAgainst(estimatorRes.curls, estimatorRes.directions);
if (confidence >= minConfidence)
poses.push({ name: gesture3.name, confidence });
}
return poses;
}
// src/hand/handpose.ts
var meshAnnotations2 = {
thumb: [1, 2, 3, 4],
index: [5, 6, 7, 8],
middle: [9, 10, 11, 12],
ring: [13, 14, 15, 16],
pinky: [17, 18, 19, 20],
palm: [0]
};
var handDetectorModel;
var handPoseModel;
var handPipeline;
async function predict8(input, config3) {
const predictions = await handPipeline.estimateHands(input, config3);
if (!predictions)
return [];
const hands = [];
for (let i = 0; i < predictions.length; i++) {
const annotations2 = {};
if (predictions[i].landmarks) {
for (const key of Object.keys(meshAnnotations2)) {
annotations2[key] = meshAnnotations2[key].map((index) => predictions[i].landmarks[index]);
}
}
const keypoints = predictions[i].landmarks;
let box4 = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, 0, 0];
let boxRaw = [0, 0, 0, 0];
if (keypoints && keypoints.length > 0) {
for (const pt of keypoints) {
if (pt[0] < box4[0])
box4[0] = pt[0];
if (pt[1] < box4[1])
box4[1] = pt[1];
if (pt[0] > box4[2])
box4[2] = pt[0];
if (pt[1] > box4[3])
box4[3] = pt[1];
}
box4[2] -= box4[0];
box4[3] -= box4[1];
boxRaw = [box4[0] / (input.shape[2] || 0), box4[1] / (input.shape[1] || 0), box4[2] / (input.shape[2] || 0), box4[3] / (input.shape[1] || 0)];
} else {
box4 = predictions[i].box ? [
Math.trunc(Math.max(0, predictions[i].box.topLeft[0])),
Math.trunc(Math.max(0, predictions[i].box.topLeft[1])),
Math.trunc(Math.min(input.shape[2] || 0, predictions[i].box.bottomRight[0]) - Math.max(0, predictions[i].box.topLeft[0])),
Math.trunc(Math.min(input.shape[1] || 0, predictions[i].box.bottomRight[1]) - Math.max(0, predictions[i].box.topLeft[1]))
] : [0, 0, 0, 0];
boxRaw = [
predictions[i].box.topLeft[0] / (input.shape[2] || 0),
predictions[i].box.topLeft[1] / (input.shape[1] || 0),
(predictions[i].box.bottomRight[0] - predictions[i].box.topLeft[0]) / (input.shape[2] || 0),
(predictions[i].box.bottomRight[1] - predictions[i].box.topLeft[1]) / (input.shape[1] || 0)
];
}
const landmarks = analyze(keypoints);
hands.push({
id: i,
score: Math.round(100 * predictions[i].confidence) / 100,
boxScore: Math.round(100 * predictions[i].boxConfidence) / 100,
fingerScore: Math.round(100 * predictions[i].fingerConfidence) / 100,
label: "hand",
box: box4,
boxRaw,
keypoints,
annotations: annotations2,
landmarks
});
}
return hands;
}
async function load10(config3) {
var _a2, _b, _c2, _d2, _e, _f2;
if (env.initial) {
handDetectorModel = null;
handPoseModel = null;
}
if (!handDetectorModel || !handPoseModel) {
[handDetectorModel, handPoseModel] = await Promise.all([
config3.hand.enabled ? m7(join(config3.modelBasePath, ((_a2 = config3.hand.detector) == null ? void 0 : _a2.modelPath) || ""), { fromTFHub: (((_b = config3.hand.detector) == null ? void 0 : _b.modelPath) || "").includes("tfhub.dev") }) : null,
config3.hand.landmarks ? m7(join(config3.modelBasePath, ((_c2 = config3.hand.skeleton) == null ? void 0 : _c2.modelPath) || ""), { fromTFHub: (((_d2 = config3.hand.skeleton) == null ? void 0 : _d2.modelPath) || "").includes("tfhub.dev") }) : null
]);
if (config3.hand.enabled) {
if (!handDetectorModel || !handDetectorModel["modelUrl"])
log("load model failed:", ((_e = config3.hand.detector) == null ? void 0 : _e.modelPath) || "");
else if (config3.debug)
log("load model:", handDetectorModel["modelUrl"]);
if (!handPoseModel || !handPoseModel["modelUrl"])
log("load model failed:", ((_f2 = config3.hand.skeleton) == null ? void 0 : _f2.modelPath) || "");
else if (config3.debug)
log("load model:", handPoseModel["modelUrl"]);
}
} else {
if (config3.debug)
log("cached model:", handDetectorModel["modelUrl"]);
if (config3.debug)
log("cached model:", handPoseModel["modelUrl"]);
}
const handDetector = new HandDetector(handDetectorModel);
handPipeline = new HandPipeline(handDetector, handPoseModel);
return [handDetectorModel, handPoseModel];
}
// src/util/box.ts
function calc(keypoints, outputSize2 = [1, 1]) {
const coords8 = [keypoints.map((pt) => pt[0]), keypoints.map((pt) => pt[1])];
const min = [Math.min(...coords8[0]), Math.min(...coords8[1])];
const max = [Math.max(...coords8[0]), Math.max(...coords8[1])];
const box4 = [min[0], min[1], max[0] - min[0], max[1] - min[1]];
const boxRaw = [box4[0] / outputSize2[0], box4[1] / outputSize2[1], box4[2] / outputSize2[0], box4[3] / outputSize2[1]];
return { box: box4, boxRaw };
}
function square(keypoints, outputSize2 = [1, 1]) {
const coords8 = [keypoints.map((pt) => pt[0]), keypoints.map((pt) => pt[1])];
const min = [Math.min(...coords8[0]), Math.min(...coords8[1])];
const max = [Math.max(...coords8[0]), Math.max(...coords8[1])];
const center = [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2];
const dist = Math.max(center[0] - min[0], center[1] - min[1], -center[0] + max[0], -center[1] + max[1]);
const box4 = [Math.trunc(center[0] - dist), Math.trunc(center[1] - dist), Math.trunc(2 * dist), Math.trunc(2 * dist)];
const boxRaw = [box4[0] / outputSize2[0], box4[1] / outputSize2[1], box4[2] / outputSize2[0], box4[3] / outputSize2[1]];
return { box: box4, boxRaw };
}
function scale(box4, scaleFact) {
const dist = [box4[2] * scaleFact, box4[3] * scaleFact];
const newBox = [
box4[0] - (dist[0] - box4[2]) / 2,
box4[1] - (dist[1] - box4[3]) / 2,
dist[0],
dist[1]
];
return newBox;
}
function crop(box4) {
const yxBox = [Math.max(0, box4[1]), Math.max(0, box4[0]), Math.min(1, box4[3] + box4[1]), Math.min(1, box4[2] + box4[0])];
return yxBox;
}
// src/hand/handtrack.ts
var models2 = [null, null];
var modelOutputNodes = ["StatefulPartitionedCall/Postprocessor/Slice", "StatefulPartitionedCall/Postprocessor/ExpandDims_1"];
var inputSize6 = [[0, 0], [0, 0]];
var classes = ["hand", "fist", "pinch", "point", "face", "tip", "pinchtip"];
var faceIndex = 4;
var boxExpandFact = 1.6;
var maxDetectorResolution = 512;
var detectorExpandFact = 1.4;
var skipped9 = 0;
var lastTime6 = 0;
var outputSize = [0, 0];
var cache3 = {
boxes: [],
hands: []
};
var fingerMap = {
thumb: [1, 2, 3, 4],
index: [5, 6, 7, 8],
middle: [9, 10, 11, 12],
ring: [13, 14, 15, 16],
pinky: [17, 18, 19, 20],
palm: [0]
};
async function loadDetect2(config3) {
var _a2, _b;
if (env.initial)
models2[0] = null;
if (!models2[0]) {
fakeOps(["tensorlistreserve", "enter", "tensorlistfromtensor", "merge", "loopcond", "switch", "exit", "tensorliststack", "nextiteration", "tensorlistsetitem", "tensorlistgetitem", "reciprocal", "shape", "split", "where"], config3);
models2[0] = await m7(join(config3.modelBasePath, ((_a2 = config3.hand.detector) == null ? void 0 : _a2.modelPath) || ""));
const inputs = Object.values(models2[0].modelSignature["inputs"]);
inputSize6[0][0] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[1].size) : 0;
inputSize6[0][1] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
if (!models2[0] || !models2[0]["modelUrl"])
log("load model failed:", (_b = config3.hand.detector) == null ? void 0 : _b.modelPath);
else if (config3.debug)
log("load model:", models2[0]["modelUrl"]);
} else if (config3.debug)
log("cached model:", models2[0]["modelUrl"]);
return models2[0];
}
async function loadSkeleton(config3) {
var _a2, _b;
if (env.initial)
models2[1] = null;
if (!models2[1]) {
models2[1] = await m7(join(config3.modelBasePath, ((_a2 = config3.hand.skeleton) == null ? void 0 : _a2.modelPath) || ""));
const inputs = Object.values(models2[1].modelSignature["inputs"]);
inputSize6[1][0] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[1].size) : 0;
inputSize6[1][1] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
if (!models2[1] || !models2[1]["modelUrl"])
log("load model failed:", (_b = config3.hand.skeleton) == null ? void 0 : _b.modelPath);
else if (config3.debug)
log("load model:", models2[1]["modelUrl"]);
} else if (config3.debug)
log("cached model:", models2[1]["modelUrl"]);
return models2[1];
}
async function detectHands(input, config3) {
const hands = [];
if (!input || !models2[0])
return hands;
const t = {};
const ratio = (input.shape[2] || 1) / (input.shape[1] || 1);
const height = Math.min(Math.round((input.shape[1] || 0) / 8) * 8, maxDetectorResolution);
const width = Math.round(height * ratio / 8) * 8;
t.resize = Cn.resizeBilinear(input, [height, width]);
t.cast = Y(t.resize, "int32");
[t.rawScores, t.rawBoxes] = await models2[0].executeAsync(t.cast, modelOutputNodes);
t.boxes = Br(t.rawBoxes, [0, 2]);
t.scores = Br(t.rawScores, [0]);
const classScores = yr(t.scores, 1);
De(classScores[faceIndex]);
classScores.splice(faceIndex, 1);
t.filtered = Xt(classScores, 1);
De(classScores);
t.max = Rr(t.filtered, 1);
t.argmax = As(t.filtered, 1);
let id2 = 0;
t.nms = await Cn.nonMaxSuppressionAsync(t.boxes, t.max, config3.hand.maxDetected, config3.hand.iouThreshold, config3.hand.minConfidence);
const nms = await t.nms.data();
const scores = await t.max.data();
const classNum = await t.argmax.data();
for (const nmsIndex of Array.from(nms)) {
const boxSlice = Oe(t.boxes, nmsIndex, 1);
const boxYX = await boxSlice.data();
De(boxSlice);
const boxData = [boxYX[1], boxYX[0], boxYX[3] - boxYX[1], boxYX[2] - boxYX[0]];
const boxRaw = scale(boxData, detectorExpandFact);
const boxCrop = crop(boxRaw);
const boxFull = [Math.trunc(boxData[0] * outputSize[0]), Math.trunc(boxData[1] * outputSize[1]), Math.trunc(boxData[2] * outputSize[0]), Math.trunc(boxData[3] * outputSize[1])];
const score = scores[nmsIndex];
const label = classes[classNum[nmsIndex]];
const hand3 = { id: id2++, score, box: boxFull, boxRaw, boxCrop, label };
hands.push(hand3);
}
Object.keys(t).forEach((tensor) => De(t[tensor]));
hands.sort((a, b10) => b10.score - a.score);
if (hands.length > (config3.hand.maxDetected || 1))
hands.length = config3.hand.maxDetected || 1;
return hands;
}
async function detectFingers(input, h, config3) {
const hand3 = {
id: h.id,
score: Math.round(100 * h.score) / 100,
boxScore: Math.round(100 * h.score) / 100,
fingerScore: 0,
box: h.box,
boxRaw: h.boxRaw,
label: h.label,
keypoints: [],
landmarks: {},
annotations: {}
};
if (input && models2[1] && config3.hand.landmarks && h.score > (config3.hand.minConfidence || 0)) {
const t = {};
t.crop = Cn.cropAndResize(input, [h.boxCrop], [0], [inputSize6[1][0], inputSize6[1][1]], "bilinear");
t.cast = Y(t.crop, "float32");
t.div = ce(t.cast, 255);
[t.score, t.keypoints] = models2[1].execute(t.div);
const rawScore = (await t.score.data())[0];
const score = (100 - Math.trunc(100 / (1 + Math.exp(rawScore)))) / 100;
if (score >= (config3.hand.minConfidence || 0)) {
hand3.fingerScore = score;
t.reshaped = F(t.keypoints, [-1, 3]);
const coordsData = await t.reshaped.array();
const coordsRaw = coordsData.map((kpt4) => [kpt4[0] / inputSize6[1][1], kpt4[1] / inputSize6[1][0], kpt4[2] || 0]);
const coordsNorm = coordsRaw.map((kpt4) => [kpt4[0] * h.boxRaw[2], kpt4[1] * h.boxRaw[3], kpt4[2] || 0]);
hand3.keypoints = coordsNorm.map((kpt4) => [
outputSize[0] * (kpt4[0] + h.boxRaw[0]),
outputSize[1] * (kpt4[1] + h.boxRaw[1]),
kpt4[2] || 0
]);
hand3.landmarks = analyze(hand3.keypoints);
for (const key of Object.keys(fingerMap)) {
hand3.annotations[key] = fingerMap[key].map((index) => hand3.landmarks && hand3.keypoints[index] ? hand3.keypoints[index] : null);
}
}
Object.keys(t).forEach((tensor) => De(t[tensor]));
}
return hand3;
}
async function predict9(input, config3) {
var _a2, _b;
if (!models2[0] || !models2[1] || !((_a2 = models2[0]) == null ? void 0 : _a2.inputs[0].shape) || !((_b = models2[1]) == null ? void 0 : _b.inputs[0].shape))
return [];
outputSize = [input.shape[2] || 0, input.shape[1] || 0];
skipped9++;
if (config3.skipFrame && skipped9 <= (config3.hand.skipFrames || 0) && (config3.hand.skipTime || 0) <= now() - lastTime6) {
return cache3.hands;
}
return new Promise(async (resolve) => {
if (config3.skipFrame && cache3.hands.length === config3.hand.maxDetected) {
cache3.hands = await Promise.all(cache3.boxes.map((handBox) => detectFingers(input, handBox, config3)));
} else if (config3.skipFrame && skipped9 < 3 * (config3.hand.skipFrames || 0) && (config3.hand.skipTime || 0) <= 3 * (now() - lastTime6) && cache3.hands.length > 0) {
cache3.hands = await Promise.all(cache3.boxes.map((handBox) => detectFingers(input, handBox, config3)));
} else {
cache3.boxes = await detectHands(input, config3);
lastTime6 = now();
cache3.hands = await Promise.all(cache3.boxes.map((handBox) => detectFingers(input, handBox, config3)));
skipped9 = 0;
}
const oldCache = [...cache3.boxes];
cache3.boxes.length = 0;
if (config3.cacheSensitivity > 0) {
for (let i = 0; i < cache3.hands.length; i++) {
const boxKpt = square(cache3.hands[i].keypoints, outputSize);
if (boxKpt.box[2] / (input.shape[2] || 1) > 0.05 && boxKpt.box[3] / (input.shape[1] || 1) > 0.05 && cache3.hands[i].fingerScore && cache3.hands[i].fingerScore > (config3.hand.minConfidence || 0)) {
const boxScale = scale(boxKpt.box, boxExpandFact);
const boxScaleRaw = scale(boxKpt.boxRaw, boxExpandFact);
const boxCrop = crop(boxScaleRaw);
cache3.boxes.push({ ...oldCache[i], box: boxScale, boxRaw: boxScaleRaw, boxCrop });
}
}
}
for (let i = 0; i < cache3.hands.length; i++) {
const bbox = calc(cache3.hands[i].keypoints, outputSize);
cache3.hands[i].box = bbox.box;
cache3.hands[i].boxRaw = bbox.boxRaw;
}
resolve(cache3.hands);
});
}
// src/body/movenetcoords.ts
var movenetcoords_exports = {};
__export(movenetcoords_exports, {
connected: () => connected3,
horizontal: () => horizontal,
kpt: () => kpt3,
relative: () => relative,
vertical: () => vertical
});
var kpt3 = [
"nose",
"leftEye",
"rightEye",
"leftEar",
"rightEar",
"leftShoulder",
"rightShoulder",
"leftElbow",
"rightElbow",
"leftWrist",
"rightWrist",
"leftHip",
"rightHip",
"leftKnee",
"rightKnee",
"leftAnkle",
"rightAnkle"
];
var horizontal = [
["leftEye", "rightEye"],
["leftEar", "rightEar"],
["leftShoulder", "rightShoulder"],
["leftElbow", "rightElbow"],
["leftWrist", "rightWrist"],
["leftHip", "rightHip"],
["leftKnee", "rightKnee"],
["leftAnkle", "rightAnkle"]
];
var vertical = [
["leftKnee", "leftShoulder"],
["rightKnee", "rightShoulder"],
["leftAnkle", "leftKnee"],
["rightAnkle", "rightKnee"]
];
var relative = [
[["leftHip", "rightHip"], ["leftShoulder", "rightShoulder"]],
[["leftElbow", "rightElbow"], ["leftShoulder", "rightShoulder"]]
];
var connected3 = {
leftLeg: ["leftHip", "leftKnee", "leftAnkle"],
rightLeg: ["rightHip", "rightKnee", "rightAnkle"],
torso: ["leftShoulder", "rightShoulder", "rightHip", "leftHip", "leftShoulder"],
leftArm: ["leftShoulder", "leftElbow", "leftWrist"],
rightArm: ["rightShoulder", "rightElbow", "rightWrist"],
head: []
};
// src/body/movenetfix.ts
var maxJitter = 5e-3;
var cache4 = {
keypoints: [],
padding: [[0, 0], [0, 0], [0, 0], [0, 0]]
};
function bodyParts(body4) {
for (const pair of horizontal) {
const left = body4.keypoints.findIndex((kp2) => kp2.part === pair[0]);
const right = body4.keypoints.findIndex((kp2) => kp2.part === pair[1]);
if (body4.keypoints[left] && body4.keypoints[right]) {
if (body4.keypoints[left].position[0] < body4.keypoints[right].position[0]) {
const tmp = body4.keypoints[left];
body4.keypoints[left] = body4.keypoints[right];
body4.keypoints[right] = tmp;
}
}
}
for (const pair of vertical) {
const lower = body4.keypoints.findIndex((kp2) => kp2 && kp2.part === pair[0]);
const higher = body4.keypoints.findIndex((kp2) => kp2 && kp2.part === pair[1]);
if (body4.keypoints[lower] && body4.keypoints[higher]) {
if (body4.keypoints[lower].position[1] < body4.keypoints[higher].position[1]) {
body4.keypoints.splice(lower, 1);
}
}
}
for (const [pair, compare] of relative) {
const left = body4.keypoints.findIndex((kp2) => kp2 && kp2.part === pair[0]);
const right = body4.keypoints.findIndex((kp2) => kp2 && kp2.part === pair[1]);
const leftTo = body4.keypoints.findIndex((kp2) => kp2 && kp2.part === compare[0]);
const rightTo = body4.keypoints.findIndex((kp2) => kp2 && kp2.part === compare[1]);
if (!body4.keypoints[leftTo] || !body4.keypoints[rightTo])
continue;
const distanceLeft = body4.keypoints[left] ? [
Math.abs(body4.keypoints[leftTo].position[0] - body4.keypoints[left].position[0]),
Math.abs(body4.keypoints[rightTo].position[0] - body4.keypoints[left].position[0])
] : [0, 0];
const distanceRight = body4.keypoints[right] ? [
Math.abs(body4.keypoints[rightTo].position[0] - body4.keypoints[right].position[0]),
Math.abs(body4.keypoints[leftTo].position[0] - body4.keypoints[right].position[0])
] : [0, 0];
if (distanceLeft[0] > distanceLeft[1] || distanceRight[0] > distanceRight[1]) {
const tmp = body4.keypoints[left];
body4.keypoints[left] = body4.keypoints[right];
body4.keypoints[right] = tmp;
}
}
}
function jitter(keypoints) {
for (let i = 0; i < keypoints.length; i++) {
if (keypoints[i] && cache4.keypoints[i]) {
const diff = [Math.abs(keypoints[i].positionRaw[0] - cache4.keypoints[i].positionRaw[0]), Math.abs(keypoints[i].positionRaw[1] - cache4.keypoints[i].positionRaw[1])];
if (diff[0] < maxJitter && diff[1] < maxJitter) {
keypoints[i] = cache4.keypoints[i];
} else {
cache4.keypoints[i] = keypoints[i];
}
} else {
cache4.keypoints[i] = keypoints[i];
}
}
return keypoints;
}
function padInput(input, inputSize8) {
const t = {};
if (!input.shape || !input.shape[1] || !input.shape[2])
return input;
cache4.padding = [
[0, 0],
[input.shape[2] > input.shape[1] ? Math.trunc((input.shape[2] - input.shape[1]) / 2) : 0, input.shape[2] > input.shape[1] ? Math.trunc((input.shape[2] - input.shape[1]) / 2) : 0],
[input.shape[1] > input.shape[2] ? Math.trunc((input.shape[1] - input.shape[2]) / 2) : 0, input.shape[1] > input.shape[2] ? Math.trunc((input.shape[1] - input.shape[2]) / 2) : 0],
[0, 0]
];
t.pad = jr(input, cache4.padding);
t.resize = Cn.resizeBilinear(t.pad, [inputSize8, inputSize8]);
const final = Y(t.resize, "int32");
Object.keys(t).forEach((tensor) => De(t[tensor]));
return final;
}
function rescaleBody(body4, outputSize2) {
body4.keypoints = body4.keypoints.filter((kpt4) => kpt4 && kpt4.position);
for (const kpt4 of body4.keypoints) {
kpt4.position = [
kpt4.position[0] * (outputSize2[0] + cache4.padding[2][0] + cache4.padding[2][1]) / outputSize2[0] - cache4.padding[2][0],
kpt4.position[1] * (outputSize2[1] + cache4.padding[1][0] + cache4.padding[1][1]) / outputSize2[1] - cache4.padding[1][0]
];
kpt4.positionRaw = [
kpt4.position[0] / outputSize2[0],
kpt4.position[1] / outputSize2[1]
];
}
const rescaledBoxes = calc(body4.keypoints.map((pt) => pt.position), outputSize2);
body4.box = rescaledBoxes.box;
body4.boxRaw = rescaledBoxes.boxRaw;
return body4;
}
// src/body/movenet.ts
var model10;
var inputSize7 = 0;
var skipped10 = Number.MAX_SAFE_INTEGER;
var cache5 = {
boxes: [],
bodies: [],
last: 0
};
async function load11(config3) {
if (env.initial)
model10 = null;
if (!model10) {
fakeOps(["size"], config3);
model10 = await m7(join(config3.modelBasePath, config3.body.modelPath || ""));
if (!model10 || !model10["modelUrl"])
log("load model failed:", config3.body.modelPath);
else if (config3.debug)
log("load model:", model10["modelUrl"]);
} else if (config3.debug)
log("cached model:", model10["modelUrl"]);
inputSize7 = model10.inputs[0].shape ? model10.inputs[0].shape[2] : 0;
if (inputSize7 === -1)
inputSize7 = 256;
return model10;
}
async function parseSinglePose(res, config3, image6, inputBox) {
const kpt4 = res[0][0];
const keypoints = [];
let score = 0;
for (let id2 = 0; id2 < kpt4.length; id2++) {
score = kpt4[id2][2];
if (score > config3.body.minConfidence) {
const positionRaw = [
(inputBox[3] - inputBox[1]) * kpt4[id2][1] + inputBox[1],
(inputBox[2] - inputBox[0]) * kpt4[id2][0] + inputBox[0]
];
keypoints.push({
score: Math.round(100 * score) / 100,
part: kpt3[id2],
positionRaw,
position: [
Math.round((image6.shape[2] || 0) * positionRaw[0]),
Math.round((image6.shape[1] || 0) * positionRaw[1])
]
});
}
}
score = keypoints.reduce((prev, curr) => curr.score > prev ? curr.score : prev, 0);
const bodies = [];
const newBox = calc(keypoints.map((pt) => pt.position), [image6.shape[2], image6.shape[1]]);
const annotations2 = {};
for (const [name, indexes] of Object.entries(connected3)) {
const pt = [];
for (let i = 0; i < indexes.length - 1; i++) {
const pt0 = keypoints.find((kp2) => kp2.part === indexes[i]);
const pt1 = keypoints.find((kp2) => kp2.part === indexes[i + 1]);
if (pt0 && pt1 && pt0.score > (config3.body.minConfidence || 0) && pt1.score > (config3.body.minConfidence || 0))
pt.push([pt0.position, pt1.position]);
}
annotations2[name] = pt;
}
const body4 = { id: 0, score, box: newBox.box, boxRaw: newBox.boxRaw, keypoints, annotations: annotations2 };
bodyParts(body4);
bodies.push(body4);
return bodies;
}
async function parseMultiPose(res, config3, image6, inputBox) {
const bodies = [];
for (let id2 = 0; id2 < res[0].length; id2++) {
const kpt4 = res[0][id2];
const totalScore = Math.round(100 * kpt4[51 + 4]) / 100;
if (totalScore > config3.body.minConfidence) {
const keypoints = [];
for (let i = 0; i < 17; i++) {
const score = kpt4[3 * i + 2];
if (score > config3.body.minConfidence) {
const positionRaw = [
(inputBox[3] - inputBox[1]) * kpt4[3 * i + 1] + inputBox[1],
(inputBox[2] - inputBox[0]) * kpt4[3 * i + 0] + inputBox[0]
];
keypoints.push({
part: kpt3[i],
score: Math.round(100 * score) / 100,
positionRaw,
position: [Math.round((image6.shape[2] || 0) * positionRaw[0]), Math.round((image6.shape[1] || 0) * positionRaw[1])]
});
}
}
const newBox = calc(keypoints.map((pt) => pt.position), [image6.shape[2], image6.shape[1]]);
const annotations2 = {};
for (const [name, indexes] of Object.entries(connected3)) {
const pt = [];
for (let i = 0; i < indexes.length - 1; i++) {
const pt0 = keypoints.find((kp2) => kp2.part === indexes[i]);
const pt1 = keypoints.find((kp2) => kp2.part === indexes[i + 1]);
if (pt0 && pt1 && pt0.score > (config3.body.minConfidence || 0) && pt1.score > (config3.body.minConfidence || 0))
pt.push([pt0.position, pt1.position]);
}
annotations2[name] = pt;
}
const body4 = { id: id2, score: totalScore, box: newBox.box, boxRaw: newBox.boxRaw, keypoints: [...keypoints], annotations: annotations2 };
bodyParts(body4);
bodies.push(body4);
}
}
bodies.sort((a, b10) => b10.score - a.score);
if (bodies.length > config3.body.maxDetected)
bodies.length = config3.body.maxDetected;
return bodies;
}
async function predict10(input, config3) {
if (!model10 || !(model10 == null ? void 0 : model10.inputs[0].shape))
return [];
if (!config3.skipFrame)
cache5.boxes.length = 0;
skipped10++;
if (config3.skipFrame && (skipped10 <= (config3.body.skipFrames || 0) && (config3.body.skipTime || 0) <= now() - cache5.last)) {
return cache5.bodies;
}
return new Promise(async (resolve) => {
const t = {};
skipped10 = 0;
t.input = padInput(input, inputSize7);
t.res = await (model10 == null ? void 0 : model10.predict(t.input));
cache5.last = now();
const res = await t.res.array();
cache5.bodies = t.res.shape[2] === 17 ? await parseSinglePose(res, config3, input, [0, 0, 1, 1]) : await parseMultiPose(res, config3, input, [0, 0, 1, 1]);
for (const body4 of cache5.bodies) {
rescaleBody(body4, [input.shape[2] || 1, input.shape[1] || 1]);
jitter(body4.keypoints);
}
Object.keys(t).forEach((tensor) => De(t[tensor]));
resolve(cache5.bodies);
});
}
// src/object/nanodet.ts
var model11;
var last7 = [];
var lastTime7 = 0;
var skipped11 = Number.MAX_SAFE_INTEGER;
var scaleBox = 2.5;
async function load12(config3) {
if (!model11 || env.initial) {
model11 = await m7(join(config3.modelBasePath, config3.object.modelPath || ""));
const inputs = Object.values(model11.modelSignature["inputs"]);
model11.inputSize = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : null;
if (!model11.inputSize)
throw new Error(`cannot determine model inputSize: ${config3.object.modelPath}`);
if (!model11 || !model11.modelUrl)
log("load model failed:", config3.object.modelPath);
else if (config3.debug)
log("load model:", model11.modelUrl);
} else if (config3.debug)
log("cached model:", model11.modelUrl);
return model11;
}
async function process4(res, inputSize8, outputShape, config3) {
let id2 = 0;
let results = [];
for (const strideSize of [1, 2, 4]) {
V(async () => {
var _a2, _b;
const baseSize = strideSize * 13;
const scoresT = (_a2 = res.find((a) => a.shape[1] === baseSize ** 2 && a.shape[2] === labels.length)) == null ? void 0 : _a2.squeeze();
const featuresT = (_b = res.find((a) => a.shape[1] === baseSize ** 2 && a.shape[2] < labels.length)) == null ? void 0 : _b.squeeze();
const boxesMax = featuresT.reshape([-1, 4, featuresT.shape[1] / 4]);
const boxIdx = await boxesMax.argMax(2).array();
const scores = await scoresT.array();
for (let i = 0; i < scoresT.shape[0]; i++) {
for (let j = 0; j < scoresT.shape[1]; j++) {
const score = scores[i][j];
if (score > config3.object.minConfidence && j !== 61) {
const cx2 = (0.5 + Math.trunc(i % baseSize)) / baseSize;
const cy2 = (0.5 + Math.trunc(i / baseSize)) / baseSize;
const boxOffset = boxIdx[i].map((a) => a * (baseSize / strideSize / inputSize8));
const [x, y] = [
cx2 - scaleBox / strideSize * boxOffset[0],
cy2 - scaleBox / strideSize * boxOffset[1]
];
const [w, h] = [
cx2 + scaleBox / strideSize * boxOffset[2] - x,
cy2 + scaleBox / strideSize * boxOffset[3] - y
];
let boxRaw = [x, y, w, h];
boxRaw = boxRaw.map((a) => Math.max(0, Math.min(a, 1)));
const box4 = [
boxRaw[0] * outputShape[0],
boxRaw[1] * outputShape[1],
boxRaw[2] * outputShape[0],
boxRaw[3] * outputShape[1]
];
const result = {
id: id2++,
score: Math.round(100 * score) / 100,
class: j + 1,
label: labels[j].label,
box: box4.map((a) => Math.trunc(a)),
boxRaw
};
results.push(result);
}
}
}
});
}
res.forEach((t) => De(t));
const nmsBoxes = results.map((a) => [a.boxRaw[1], a.boxRaw[0], a.boxRaw[3], a.boxRaw[2]]);
const nmsScores = results.map((a) => a.score);
let nmsIdx = [];
if (nmsBoxes && nmsBoxes.length > 0) {
const nms = await Cn.nonMaxSuppressionAsync(nmsBoxes, nmsScores, config3.object.maxDetected, config3.object.iouThreshold, config3.object.minConfidence);
nmsIdx = await nms.data();
De(nms);
}
results = results.filter((_val, idx) => nmsIdx.includes(idx)).sort((a, b10) => b10.score - a.score);
return results;
}
async function predict11(image6, config3) {
if (skipped11 < (config3.object.skipFrames || 0) && (config3.object.skipTime || 0) <= now() - lastTime7 && config3.skipFrame && last7.length > 0) {
skipped11++;
return last7;
}
skipped11 = 0;
if (!env.kernels.includes("mod") || !env.kernels.includes("sparsetodense"))
return last7;
return new Promise(async (resolve) => {
const outputSize2 = [image6.shape[2], image6.shape[1]];
const resize = Cn.resizeBilinear(image6, [model11.inputSize, model11.inputSize], false);
const norm = ce(resize, 255);
const transpose = norm.transpose([0, 3, 1, 2]);
De(norm);
De(resize);
let objectT;
if (config3.object.enabled)
objectT = await model11.predict(transpose);
lastTime7 = now();
De(transpose);
const obj = await process4(objectT, model11.inputSize, outputSize2, config3);
last7 = obj;
resolve(obj);
});
}
// src/body/posenetutils.ts
var partNames = [
"nose",
"leftEye",
"rightEye",
"leftEar",
"rightEar",
"leftShoulder",
"rightShoulder",
"leftElbow",
"rightElbow",
"leftWrist",
"rightWrist",
"leftHip",
"rightHip",
"leftKnee",
"rightKnee",
"leftAnkle",
"rightAnkle"
];
var count = partNames.length;
var partIds = partNames.reduce((result, jointName, i) => {
result[jointName] = i;
return result;
}, {});
var connectedPartNames = [
["leftHip", "leftShoulder"],
["leftElbow", "leftShoulder"],
["leftElbow", "leftWrist"],
["leftHip", "leftKnee"],
["leftKnee", "leftAnkle"],
["rightHip", "rightShoulder"],
["rightElbow", "rightShoulder"],
["rightElbow", "rightWrist"],
["rightHip", "rightKnee"],
["rightKnee", "rightAnkle"],
["leftShoulder", "rightShoulder"],
["leftHip", "rightHip"]
];
var connectedPartIndices = connectedPartNames.map(([jointNameA, jointNameB]) => [partIds[jointNameA], partIds[jointNameB]]);
var poseChain = [
["nose", "leftEye"],
["leftEye", "leftEar"],
["nose", "rightEye"],
["rightEye", "rightEar"],
["nose", "leftShoulder"],
["leftShoulder", "leftElbow"],
["leftElbow", "leftWrist"],
["leftShoulder", "leftHip"],
["leftHip", "leftKnee"],
["leftKnee", "leftAnkle"],
["nose", "rightShoulder"],
["rightShoulder", "rightElbow"],
["rightElbow", "rightWrist"],
["rightShoulder", "rightHip"],
["rightHip", "rightKnee"],
["rightKnee", "rightAnkle"]
];
function getBoundingBox(keypoints) {
const coord = keypoints.reduce(({ maxX, maxY, minX, minY }, { position: { x, y } }) => ({
maxX: Math.max(maxX, x),
maxY: Math.max(maxY, y),
minX: Math.min(minX, x),
minY: Math.min(minY, y)
}), {
maxX: Number.NEGATIVE_INFINITY,
maxY: Number.NEGATIVE_INFINITY,
minX: Number.POSITIVE_INFINITY,
minY: Number.POSITIVE_INFINITY
});
return [coord.minX, coord.minY, coord.maxX - coord.minX, coord.maxY - coord.minY];
}
function scalePoses(poses, [height, width], [inputResolutionHeight, inputResolutionWidth]) {
const scaleY = height / inputResolutionHeight;
const scaleX = width / inputResolutionWidth;
const scalePose = (pose, i) => ({
id: i,
score: pose.score,
boxRaw: [pose.box[0] / inputResolutionWidth, pose.box[1] / inputResolutionHeight, pose.box[2] / inputResolutionWidth, pose.box[3] / inputResolutionHeight],
box: [Math.trunc(pose.box[0] * scaleX), Math.trunc(pose.box[1] * scaleY), Math.trunc(pose.box[2] * scaleX), Math.trunc(pose.box[3] * scaleY)],
keypoints: pose.keypoints.map(({ score, part, position }) => ({
score,
part,
position: [Math.trunc(position.x * scaleX), Math.trunc(position.y * scaleY)],
positionRaw: [position.x / inputResolutionHeight, position.y / inputResolutionHeight]
}))
});
const scaledPoses = poses.map((pose, i) => scalePose(pose, i));
return scaledPoses;
}
var MaxHeap = class {
constructor(maxSize2, getElementValue) {
__publicField(this, "priorityQueue");
__publicField(this, "numberOfElements");
__publicField(this, "getElementValue");
this.priorityQueue = new Array(maxSize2);
this.numberOfElements = -1;
this.getElementValue = getElementValue;
}
enqueue(x) {
this.priorityQueue[++this.numberOfElements] = x;
this.swim(this.numberOfElements);
}
dequeue() {
const max = this.priorityQueue[0];
this.exchange(0, this.numberOfElements--);
this.sink(0);
this.priorityQueue[this.numberOfElements + 1] = null;
return max;
}
empty() {
return this.numberOfElements === -1;
}
size() {
return this.numberOfElements + 1;
}
all() {
return this.priorityQueue.slice(0, this.numberOfElements + 1);
}
max() {
return this.priorityQueue[0];
}
swim(k10) {
while (k10 > 0 && this.less(Math.floor(k10 / 2), k10)) {
this.exchange(k10, Math.floor(k10 / 2));
k10 = Math.floor(k10 / 2);
}
}
sink(k10) {
while (2 * k10 <= this.numberOfElements) {
let j = 2 * k10;
if (j < this.numberOfElements && this.less(j, j + 1))
j++;
if (!this.less(k10, j))
break;
this.exchange(k10, j);
k10 = j;
}
}
getValueAt(i) {
return this.getElementValue(this.priorityQueue[i]);
}
less(i, j) {
return this.getValueAt(i) < this.getValueAt(j);
}
exchange(i, j) {
const t = this.priorityQueue[i];
this.priorityQueue[i] = this.priorityQueue[j];
this.priorityQueue[j] = t;
}
};
function getOffsetPoint(y, x, keypoint, offsets) {
return {
y: offsets.get(y, x, keypoint),
x: offsets.get(y, x, keypoint + count)
};
}
function getImageCoords(part, outputStride2, offsets) {
const { heatmapY, heatmapX, id: keypoint } = part;
const { y, x } = getOffsetPoint(heatmapY, heatmapX, keypoint, offsets);
return {
x: part.heatmapX * outputStride2 + x,
y: part.heatmapY * outputStride2 + y
};
}
function clamp(a, min, max) {
if (a < min)
return min;
if (a > max)
return max;
return a;
}
function squaredDistance(y12, x12, y22, x22) {
const dy2 = y22 - y12;
const dx2 = x22 - x12;
return dy2 * dy2 + dx2 * dx2;
}
function addVectors(a, b10) {
return { x: a.x + b10.x, y: a.y + b10.y };
}
// src/body/posenet.ts
var model12;
var poseNetOutputs = ["MobilenetV1/offset_2/BiasAdd", "MobilenetV1/heatmap_2/BiasAdd", "MobilenetV1/displacement_fwd_2/BiasAdd", "MobilenetV1/displacement_bwd_2/BiasAdd"];
var localMaximumRadius = 1;
var outputStride = 16;
var squaredNmsRadius = 50 ** 2;
function traverse(edgeId, sourceKeypoint, targetId, scores, offsets, displacements, offsetRefineStep = 2) {
const getDisplacement = (point2) => ({
y: displacements.get(point2.y, point2.x, edgeId),
x: displacements.get(point2.y, point2.x, displacements.shape[2] / 2 + edgeId)
});
const getStridedIndexNearPoint = (point2, height2, width2) => ({
y: clamp(Math.round(point2.y / outputStride), 0, height2 - 1),
x: clamp(Math.round(point2.x / outputStride), 0, width2 - 1)
});
const [height, width] = scores.shape;
const sourceKeypointIndices = getStridedIndexNearPoint(sourceKeypoint.position, height, width);
const displacement = getDisplacement(sourceKeypointIndices);
const displacedPoint = addVectors(sourceKeypoint.position, displacement);
let targetKeypoint = displacedPoint;
for (let i = 0; i < offsetRefineStep; i++) {
const targetKeypointIndices = getStridedIndexNearPoint(targetKeypoint, height, width);
const offsetPoint = getOffsetPoint(targetKeypointIndices.y, targetKeypointIndices.x, targetId, offsets);
targetKeypoint = addVectors({ x: targetKeypointIndices.x * outputStride, y: targetKeypointIndices.y * outputStride }, { x: offsetPoint.x, y: offsetPoint.y });
}
const targetKeyPointIndices = getStridedIndexNearPoint(targetKeypoint, height, width);
const score = scores.get(targetKeyPointIndices.y, targetKeyPointIndices.x, targetId);
return { position: targetKeypoint, part: partNames[targetId], score };
}
function decodePose(root, scores, offsets, displacementsFwd, displacementsBwd) {
const tuples = poseChain.map(([parentJoinName, childJoinName]) => [partIds[parentJoinName], partIds[childJoinName]]);
const edgesFwd = tuples.map(([, childJointId]) => childJointId);
const edgesBwd = tuples.map(([parentJointId]) => parentJointId);
const numParts = scores.shape[2];
const numEdges = edgesFwd.length;
const keypoints = new Array(numParts);
const rootPoint = getImageCoords(root.part, outputStride, offsets);
keypoints[root.part.id] = {
score: root.score,
part: partNames[root.part.id],
position: rootPoint
};
for (let edge = numEdges - 1; edge >= 0; --edge) {
const sourceId = edgesFwd[edge];
const targetId = edgesBwd[edge];
if (keypoints[sourceId] && !keypoints[targetId]) {
keypoints[targetId] = traverse(edge, keypoints[sourceId], targetId, scores, offsets, displacementsBwd);
}
}
for (let edge = 0; edge < numEdges; ++edge) {
const sourceId = edgesBwd[edge];
const targetId = edgesFwd[edge];
if (keypoints[sourceId] && !keypoints[targetId]) {
keypoints[targetId] = traverse(edge, keypoints[sourceId], targetId, scores, offsets, displacementsFwd);
}
}
return keypoints;
}
function scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, scores) {
const [height, width] = scores.shape;
let localMaximum = true;
const yStart = Math.max(heatmapY - localMaximumRadius, 0);
const yEnd = Math.min(heatmapY + localMaximumRadius + 1, height);
for (let yCurrent = yStart; yCurrent < yEnd; ++yCurrent) {
const xStart = Math.max(heatmapX - localMaximumRadius, 0);
const xEnd = Math.min(heatmapX + localMaximumRadius + 1, width);
for (let xCurrent = xStart; xCurrent < xEnd; ++xCurrent) {
if (scores.get(yCurrent, xCurrent, keypointId) > score) {
localMaximum = false;
break;
}
}
if (!localMaximum)
break;
}
return localMaximum;
}
function buildPartWithScoreQueue(minConfidence2, scores) {
const [height, width, numKeypoints] = scores.shape;
const queue = new MaxHeap(height * width * numKeypoints, ({ score }) => score);
for (let heatmapY = 0; heatmapY < height; ++heatmapY) {
for (let heatmapX = 0; heatmapX < width; ++heatmapX) {
for (let keypointId = 0; keypointId < numKeypoints; ++keypointId) {
const score = scores.get(heatmapY, heatmapX, keypointId);
if (score < minConfidence2)
continue;
if (scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, scores))
queue.enqueue({ score, part: { heatmapY, heatmapX, id: keypointId } });
}
}
}
return queue;
}
function withinRadius(poses, { x, y }, keypointId) {
return poses.some(({ keypoints }) => {
var _a2;
const correspondingKeypoint = (_a2 = keypoints[keypointId]) == null ? void 0 : _a2.position;
if (!correspondingKeypoint)
return false;
return squaredDistance(y, x, correspondingKeypoint.y, correspondingKeypoint.x) <= squaredNmsRadius;
});
}
function getInstanceScore(existingPoses, keypoints) {
const notOverlappedKeypointScores = keypoints.reduce((result, { position, score }, keypointId) => {
if (!withinRadius(existingPoses, position, keypointId))
result += score;
return result;
}, 0);
return notOverlappedKeypointScores / keypoints.length;
}
function decode(offsets, scores, displacementsFwd, displacementsBwd, maxDetected, minConfidence2) {
const poses = [];
const queue = buildPartWithScoreQueue(minConfidence2, scores);
while (poses.length < maxDetected && !queue.empty()) {
const root = queue.dequeue();
const rootImageCoords = getImageCoords(root.part, outputStride, offsets);
if (withinRadius(poses, rootImageCoords, root.part.id))
continue;
let keypoints = decodePose(root, scores, offsets, displacementsFwd, displacementsBwd);
keypoints = keypoints.filter((a) => a.score > minConfidence2);
const score = getInstanceScore(poses, keypoints);
const box4 = getBoundingBox(keypoints);
if (score > minConfidence2)
poses.push({ keypoints, box: box4, score: Math.round(100 * score) / 100 });
}
return poses;
}
async function predict12(input, config3) {
const res = V(() => {
if (!model12.inputs[0].shape)
return [];
const resized = Cn.resizeBilinear(input, [model12.inputs[0].shape[2], model12.inputs[0].shape[1]]);
const normalized = le(ce(Y(resized, "float32"), 127.5), 1);
const results = model12.execute(normalized, poseNetOutputs);
const results3d = results.map((y) => Br(y, [0]));
results3d[1] = results3d[1].sigmoid();
return results3d;
});
const buffers = await Promise.all(res.map((tensor) => tensor.buffer()));
for (const t of res)
De(t);
const decoded = await decode(buffers[0], buffers[1], buffers[2], buffers[3], config3.body.maxDetected, config3.body.minConfidence);
if (!model12.inputs[0].shape)
return [];
const scaled = scalePoses(decoded, [input.shape[1], input.shape[2]], [model12.inputs[0].shape[2], model12.inputs[0].shape[1]]);
return scaled;
}
async function load13(config3) {
if (!model12 || env.initial) {
model12 = await m7(join(config3.modelBasePath, config3.body.modelPath || ""));
if (!model12 || !model12["modelUrl"])
log("load model failed:", config3.body.modelPath);
else if (config3.debug)
log("load model:", model12["modelUrl"]);
} else if (config3.debug)
log("cached model:", model12["modelUrl"]);
return model12;
}
// src/segmentation/segmentation.ts
var model13;
var busy = false;
async function load14(config3) {
if (!model13 || env.initial) {
model13 = await m7(join(config3.modelBasePath, config3.segmentation.modelPath || ""));
if (!model13 || !model13["modelUrl"])
log("load model failed:", config3.segmentation.modelPath);
else if (config3.debug)
log("load model:", model13["modelUrl"]);
} else if (config3.debug)
log("cached model:", model13["modelUrl"]);
return model13;
}
async function process5(input, background, config3) {
var _a2, _b;
if (busy)
return { data: [], canvas: null, alpha: null };
busy = true;
if (!model13)
await load14(config3);
const inputImage = process2(input, config3);
const width = ((_a2 = inputImage.canvas) == null ? void 0 : _a2.width) || 0;
const height = ((_b = inputImage.canvas) == null ? void 0 : _b.height) || 0;
if (!inputImage.tensor)
return { data: [], canvas: null, alpha: null };
const t = {};
t.resize = Cn.resizeBilinear(inputImage.tensor, [model13.inputs[0].shape ? model13.inputs[0].shape[1] : 0, model13.inputs[0].shape ? model13.inputs[0].shape[2] : 0], false);
De(inputImage.tensor);
t.norm = ce(t.resize, 255);
t.res = model13.predict(t.norm);
t.squeeze = Br(t.res, 0);
if (t.squeeze.shape[2] === 2) {
t.softmax = za(t.squeeze);
[t.bg, t.fg] = yr(t.softmax, 2);
t.expand = mr(t.fg, 2);
t.pad = mr(t.expand, 0);
t.crop = Cn.cropAndResize(t.pad, [[0, 0, 0.5, 0.5]], [0], [width, height]);
t.data = Br(t.crop, 0);
} else {
t.data = Cn.resizeBilinear(t.squeeze, [height, width]);
}
const data = Array.from(await t.data.data());
if (env.node && !env.Canvas && typeof ImageData === "undefined") {
if (config3.debug)
log("canvas support missing");
Object.keys(t).forEach((tensor) => De(t[tensor]));
return { data, canvas: null, alpha: null };
}
const alphaCanvas = canvas(width, height);
await Gg.toPixels(t.data, alphaCanvas);
const alphaCtx = alphaCanvas.getContext("2d");
if (config3.segmentation.blur && config3.segmentation.blur > 0)
alphaCtx.filter = `blur(${config3.segmentation.blur}px)`;
const alphaData = alphaCtx.getImageData(0, 0, width, height);
const compositeCanvas = canvas(width, height);
const compositeCtx = compositeCanvas.getContext("2d");
if (inputImage.canvas)
compositeCtx.drawImage(inputImage.canvas, 0, 0);
compositeCtx.globalCompositeOperation = "darken";
if (config3.segmentation.blur && config3.segmentation.blur > 0)
compositeCtx.filter = `blur(${config3.segmentation.blur}px)`;
compositeCtx.drawImage(alphaCanvas, 0, 0);
compositeCtx.globalCompositeOperation = "source-over";
compositeCtx.filter = "none";
const compositeData = compositeCtx.getImageData(0, 0, width, height);
for (let i = 0; i < width * height; i++)
compositeData.data[4 * i + 3] = alphaData.data[4 * i + 0];
compositeCtx.putImageData(compositeData, 0, 0);
let mergedCanvas = null;
if (background && compositeCanvas) {
mergedCanvas = canvas(width, height);
const bgImage = process2(background, config3);
De(bgImage.tensor);
const ctxMerge = mergedCanvas.getContext("2d");
ctxMerge.drawImage(bgImage.canvas, 0, 0, mergedCanvas.width, mergedCanvas.height);
ctxMerge.drawImage(compositeCanvas, 0, 0);
}
Object.keys(t).forEach((tensor) => De(t[tensor]));
busy = false;
return { data, canvas: mergedCanvas || compositeCanvas, alpha: alphaCanvas };
}
// src/models.ts
var Models = class {
constructor() {
__publicField(this, "age", null);
__publicField(this, "agegenderrace", null);
__publicField(this, "blazeposedetect", null);
__publicField(this, "blazepose", null);
__publicField(this, "centernet", null);
__publicField(this, "efficientpose", null);
__publicField(this, "embedding", null);
__publicField(this, "emotion", null);
__publicField(this, "facedetect", null);
__publicField(this, "faceiris", null);
__publicField(this, "facemesh", null);
__publicField(this, "faceres", null);
__publicField(this, "gender", null);
__publicField(this, "handpose", null);
__publicField(this, "handskeleton", null);
__publicField(this, "handtrack", null);
__publicField(this, "movenet", null);
__publicField(this, "nanodet", null);
__publicField(this, "posenet", null);
__publicField(this, "segmentation", null);
__publicField(this, "antispoof", null);
}
};
function reset(instance) {
for (const model14 of Object.keys(instance.models))
instance.models[model14] = null;
}
async function load15(instance) {
var _a2, _b, _c2, _d2, _e, _f2, _g, _h2, _i2, _j2, _k2, _l2, _m2, _n2, _o2, _p2, _q2, _r, _s2, _t2, _u2, _v2, _w, _x2, _y2, _z2, _A2, _B2, _C2, _D2, _E2;
if (env.initial)
reset(instance);
if (instance.config.hand.enabled) {
if (!instance.models.handpose && ((_b = (_a2 = instance.config.hand.detector) == null ? void 0 : _a2.modelPath) == null ? void 0 : _b.includes("handdetect")))
[instance.models.handpose, instance.models.handskeleton] = await load10(instance.config);
if (!instance.models.handskeleton && instance.config.hand.landmarks && ((_d2 = (_c2 = instance.config.hand.detector) == null ? void 0 : _c2.modelPath) == null ? void 0 : _d2.includes("handdetect")))
[instance.models.handpose, instance.models.handskeleton] = await load10(instance.config);
}
if (instance.config.face.enabled && !instance.models.facedetect)
instance.models.facedetect = load3(instance.config);
if (instance.config.face.enabled && ((_e = instance.config.face.mesh) == null ? void 0 : _e.enabled) && !instance.models.facemesh)
instance.models.facemesh = load8(instance.config);
if (instance.config.face.enabled && ((_f2 = instance.config.face.iris) == null ? void 0 : _f2.enabled) && !instance.models.faceiris)
instance.models.faceiris = load7(instance.config);
if (instance.config.face.enabled && ((_g = instance.config.face.antispoof) == null ? void 0 : _g.enabled) && !instance.models.antispoof)
instance.models.antispoof = load2(instance.config);
if (instance.config.hand.enabled && !instance.models.handtrack && ((_i2 = (_h2 = instance.config.hand.detector) == null ? void 0 : _h2.modelPath) == null ? void 0 : _i2.includes("handtrack")))
instance.models.handtrack = loadDetect2(instance.config);
if (instance.config.hand.enabled && instance.config.hand.landmarks && !instance.models.handskeleton && ((_k2 = (_j2 = instance.config.hand.detector) == null ? void 0 : _j2.modelPath) == null ? void 0 : _k2.includes("handtrack")))
instance.models.handskeleton = loadSkeleton(instance.config);
if (instance.config.body.enabled && !instance.models.posenet && ((_m2 = (_l2 = instance.config.body) == null ? void 0 : _l2.modelPath) == null ? void 0 : _m2.includes("posenet")))
instance.models.posenet = load13(instance.config);
if (instance.config.body.enabled && !instance.models.efficientpose && ((_o2 = (_n2 = instance.config.body) == null ? void 0 : _n2.modelPath) == null ? void 0 : _o2.includes("efficientpose")))
instance.models.efficientpose = load5(instance.config);
if (instance.config.body.enabled && !instance.models.blazepose && ((_q2 = (_p2 = instance.config.body) == null ? void 0 : _p2.modelPath) == null ? void 0 : _q2.includes("blazepose")))
instance.models.blazepose = loadPose(instance.config);
if (instance.config.body.enabled && !instance.models.blazeposedetect && ((_r = instance.config.body.detector) == null ? void 0 : _r.modelPath) && ((_t2 = (_s2 = instance.config.body) == null ? void 0 : _s2.modelPath) == null ? void 0 : _t2.includes("blazepose")))
instance.models.blazeposedetect = loadDetect(instance.config);
if (instance.config.body.enabled && !instance.models.efficientpose && ((_v2 = (_u2 = instance.config.body) == null ? void 0 : _u2.modelPath) == null ? void 0 : _v2.includes("efficientpose")))
instance.models.efficientpose = load5(instance.config);
if (instance.config.body.enabled && !instance.models.movenet && ((_x2 = (_w = instance.config.body) == null ? void 0 : _w.modelPath) == null ? void 0 : _x2.includes("movenet")))
instance.models.movenet = load11(instance.config);
if (instance.config.object.enabled && !instance.models.nanodet && ((_z2 = (_y2 = instance.config.object) == null ? void 0 : _y2.modelPath) == null ? void 0 : _z2.includes("nanodet")))
instance.models.nanodet = load12(instance.config);
if (instance.config.object.enabled && !instance.models.centernet && ((_B2 = (_A2 = instance.config.object) == null ? void 0 : _A2.modelPath) == null ? void 0 : _B2.includes("centernet")))
instance.models.centernet = load4(instance.config);
if (instance.config.face.enabled && ((_C2 = instance.config.face.emotion) == null ? void 0 : _C2.enabled) && !instance.models.emotion)
instance.models.emotion = load6(instance.config);
if (instance.config.face.enabled && ((_D2 = instance.config.face.description) == null ? void 0 : _D2.enabled) && !instance.models.faceres)
instance.models.faceres = load9(instance.config);
if (instance.config.segmentation.enabled && !instance.models.segmentation)
instance.models.segmentation = load14(instance.config);
if (instance.config.face.enabled && ((_E2 = instance.config.face["agegenderrace"]) == null ? void 0 : _E2.enabled) && !instance.models.agegenderrace)
instance.models.agegenderrace = load(instance.config);
for await (const model14 of Object.keys(instance.models)) {
if (instance.models[model14] && typeof instance.models[model14] !== "undefined")
instance.models[model14] = await instance.models[model14];
}
}
async function validate2(instance) {
const simpleOps = ["const", "placeholder", "noop", "pad", "squeeze", "add", "sub", "mul", "div"];
for (const defined of Object.keys(instance.models)) {
if (instance.models[defined]) {
let models5 = [];
if (Array.isArray(instance.models[defined])) {
models5 = instance.models[defined].filter((model14) => model14 !== null).map((model14) => model14 && model14.executor ? model14 : model14.model);
} else {
models5 = [instance.models[defined]];
}
for (const model14 of models5) {
if (!model14) {
if (instance.config.debug)
log("model marked as loaded but not defined:", defined);
continue;
}
const ops = [];
const executor = model14 == null ? void 0 : model14.executor;
if (executor && executor.graph.nodes) {
for (const kernel of Object.values(executor.graph.nodes)) {
const op2 = kernel.op.toLowerCase();
if (!ops.includes(op2))
ops.push(op2);
}
} else {
if (!executor && instance.config.debug)
log("model signature not determined:", defined);
}
const missing = [];
for (const op2 of ops) {
if (!simpleOps.includes(op2) && !instance.env.kernels.includes(op2) && !instance.env.kernels.includes(op2.replace("_", "")) && !instance.env.kernels.includes(op2.replace("native", "")) && !instance.env.kernels.includes(op2.replace("v2", ""))) {
missing.push(op2);
}
}
if (missing.length > 0 && instance.config.debug)
log("model validation:", defined, missing);
}
}
}
}
// src/tfjs/humangl.ts
var config2 = {
name: "humangl",
priority: 999,
canvas: null,
gl: null,
extensions: [],
webGLattr: {
alpha: false,
antialias: false,
premultipliedAlpha: false,
preserveDrawingBuffer: false,
depth: false,
stencil: false,
failIfMajorPerformanceCaveat: false,
desynchronized: true
}
};
function extensions() {
const gl2 = config2.gl;
if (!gl2)
return;
config2.extensions = gl2.getSupportedExtensions();
}
async function register(instance) {
var _a2;
if (instance.config.backend !== "humangl")
return;
if (config2.name in Es().registry && (!config2.gl || !config2.gl.getParameter(config2.gl.VERSION))) {
log("error: humangl backend invalid context");
reset(instance);
}
if (!mue(config2.name)) {
try {
config2.canvas = await canvas(100, 100);
} catch (err) {
log("error: cannot create canvas:", err);
return;
}
try {
config2.gl = (_a2 = config2.canvas) == null ? void 0 : _a2.getContext("webgl2", config2.webGLattr);
if (config2.canvas) {
config2.canvas.addEventListener("webglcontextlost", async (e) => {
log("error: humangl:", e.type);
log("possible browser memory leak using webgl or conflict with multiple backend registrations");
instance.emit("error");
throw new Error("browser webgl error");
});
config2.canvas.addEventListener("webglcontextrestored", (e) => {
log("error: humangl context restored:", e);
});
config2.canvas.addEventListener("webglcontextcreationerror", (e) => {
log("error: humangl context create:", e);
});
}
} catch (err) {
log("error: cannot get WebGL context:", err);
return;
}
try {
tC(2, config2.gl);
} catch (err) {
log("error: cannot set WebGL context:", err);
return;
}
try {
const ctx = new Xy(config2.gl);
Op(config2.name, () => new _c(ctx), config2.priority);
} catch (err) {
log("error: cannot register WebGL backend:", err);
return;
}
try {
const kernels = Ag("webgl");
kernels.forEach((kernelConfig) => {
const newKernelConfig = { ...kernelConfig, backendName: config2.name };
uu(newKernelConfig);
});
} catch (err) {
log("error: cannot update WebGL backend registration:", err);
return;
}
const current = A1().getGPGPUContext ? A1().getGPGPUContext().gl : null;
if (current) {
log(`humangl webgl version:${current.getParameter(current.VERSION)} renderer:${current.getParameter(current.RENDERER)}`);
} else {
log("error: no current gl context:", current, config2.gl);
return;
}
try {
Xw.set("WEBGL_VERSION", 2);
} catch (err) {
log("error: cannot set WebGL backend flags:", err);
return;
}
extensions();
log("backend registered:", config2.name);
}
}
// src/tfjs/backend.ts
async function check(instance, force = false) {
instance.state = "backend";
if (force || env.initial || instance.config.backend && instance.config.backend.length > 0 && cue() !== instance.config.backend) {
const timeStamp = now();
if (instance.config.backend && instance.config.backend.length > 0) {
if (typeof window === "undefined" && typeof WorkerGlobalScope !== "undefined" && instance.config.debug) {
if (instance.config.debug)
log("running inside web worker");
}
if (env.browser && instance.config.backend === "tensorflow") {
if (instance.config.debug)
log("override: backend set to tensorflow while running in browser");
instance.config.backend = "humangl";
}
if (env.node && (instance.config.backend === "webgl" || instance.config.backend === "humangl")) {
if (instance.config.debug)
log(`override: backend set to ${instance.config.backend} while running in nodejs`);
instance.config.backend = "tensorflow";
}
if (env.browser && instance.config.backend === "webgpu") {
if (typeof navigator === "undefined" || typeof navigator["gpu"] === "undefined") {
log("override: backend set to webgpu but browser does not support webgpu");
instance.config.backend = "humangl";
} else {
const adapter = await navigator["gpu"].requestAdapter();
if (instance.config.debug)
log("enumerated webgpu adapter:", adapter);
}
}
if (instance.config.backend === "humangl")
await register(instance);
const available = Object.keys(Es().registryFactory);
if (instance.config.debug)
log("available backends:", available);
if (!available.includes(instance.config.backend)) {
log(`error: backend ${instance.config.backend} not found in registry`);
instance.config.backend = env.node ? "tensorflow" : "webgl";
if (instance.config.debug)
log(`override: setting backend ${instance.config.backend}`);
}
if (instance.config.debug)
log("setting backend:", instance.config.backend);
if (instance.config.backend === "wasm") {
if (instance.config.debug)
log("wasm path:", instance.config.wasmPath);
if (typeof (tfjs_esm_exports == null ? void 0 : tfjs_esm_exports.setWasmPaths) !== "undefined")
await Hoe(instance.config.wasmPath);
else
throw new Error("wasm backend is not loaded");
const simd = await U().getAsync("WASM_HAS_SIMD_SUPPORT");
const mt2 = await U().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");
if (instance.config.debug)
log(`wasm execution: ${simd ? "SIMD" : "no SIMD"} ${mt2 ? "multithreaded" : "singlethreaded"}`);
if (instance.config.debug && !simd)
log("warning: wasm simd support is not enabled");
}
try {
await q4(instance.config.backend);
await uue();
} catch (err) {
log("error: cannot set backend:", instance.config.backend, err);
return false;
}
}
if (cue() === "humangl") {
Xw.set("CHECK_COMPUTATION_FOR_ERRORS", false);
Xw.set("WEBGL_CPU_FORWARD", true);
Xw.set("WEBGL_USE_SHAPES_UNIFORMS", true);
Xw.set("CPU_HANDOFF_SIZE_THRESHOLD", 256);
if (typeof instance.config["deallocate"] !== "undefined" && instance.config["deallocate"]) {
log("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:", true);
Xw.set("WEBGL_DELETE_TEXTURE_THRESHOLD", 0);
}
if (A1().getGPGPUContext) {
const gl2 = await A1().getGPGPUContext().gl;
if (instance.config.debug)
log(`gl version:${gl2.getParameter(gl2.VERSION)} renderer:${gl2.getParameter(gl2.RENDERER)}`);
}
}
if (cue() === "webgpu") {
}
nue();
await uue();
instance.performance.backend = Math.trunc(now() - timeStamp);
instance.config.backend = cue();
env.updateBackend();
}
return true;
}
function fakeOps(kernelNames, config3) {
for (const kernelName of kernelNames) {
const kernelConfig = {
kernelName,
backendName: config3.backend,
kernelFunc: () => {
if (config3.debug)
log("kernelFunc", kernelName, config3.backend);
}
};
uu(kernelConfig);
}
env.kernels = Ag(cue()).map((kernel) => kernel.kernelName.toLowerCase());
}
// src/util/draw.ts
var options2 = {
color: "rgba(173, 216, 230, 0.6)",
labelColor: "rgba(173, 216, 230, 1)",
shadowColor: "black",
font: 'small-caps 14px "Segoe UI"',
lineHeight: 18,
lineWidth: 4,
pointSize: 2,
roundRect: 8,
drawPoints: false,
drawLabels: true,
drawBoxes: true,
drawGestures: true,
drawPolygons: true,
drawGaze: true,
fillPolygons: false,
useDepth: true,
useCurves: false,
bufferedOutput: true
};
var getCanvasContext = (input) => {
if (input && input.getContext)
return input.getContext("2d");
throw new Error("invalid canvas");
};
var rad2deg = (theta) => Math.round(theta * 180 / Math.PI);
function point(ctx, x, y, z10 = 0, localOptions) {
ctx.fillStyle = localOptions.useDepth && z10 ? `rgba(${127.5 + 2 * z10}, ${127.5 - 2 * z10}, 255, 0.3)` : localOptions.color;
ctx.beginPath();
ctx.arc(x, y, localOptions.pointSize, 0, 2 * Math.PI);
ctx.fill();
}
function rect(ctx, x, y, width, height, localOptions) {
ctx.beginPath();
if (localOptions.useCurves) {
const cx2 = (x + x + width) / 2;
const cy2 = (y + y + height) / 2;
ctx.ellipse(cx2, cy2, width / 2, height / 2, 0, 0, 2 * Math.PI);
} else {
ctx.lineWidth = localOptions.lineWidth;
ctx.moveTo(x + localOptions.roundRect, y);
ctx.lineTo(x + width - localOptions.roundRect, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + localOptions.roundRect);
ctx.lineTo(x + width, y + height - localOptions.roundRect);
ctx.quadraticCurveTo(x + width, y + height, x + width - localOptions.roundRect, y + height);
ctx.lineTo(x + localOptions.roundRect, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - localOptions.roundRect);
ctx.lineTo(x, y + localOptions.roundRect);
ctx.quadraticCurveTo(x, y, x + localOptions.roundRect, y);
ctx.closePath();
}
ctx.stroke();
}
function lines(ctx, points = [], localOptions) {
if (points === void 0 || points.length === 0)
return;
ctx.beginPath();
ctx.moveTo(points[0][0], points[0][1]);
for (const pt of points) {
const z10 = pt[2] || 0;
ctx.strokeStyle = localOptions.useDepth && z10 ? `rgba(${127.5 + 2 * z10}, ${127.5 - 2 * z10}, 255, 0.3)` : localOptions.color;
ctx.fillStyle = localOptions.useDepth && z10 ? `rgba(${127.5 + 2 * z10}, ${127.5 - 2 * z10}, 255, 0.3)` : localOptions.color;
ctx.lineTo(pt[0], Math.round(pt[1]));
}
ctx.stroke();
if (localOptions.fillPolygons) {
ctx.closePath();
ctx.fill();
}
}
function curves(ctx, points = [], localOptions) {
if (points === void 0 || points.length === 0)
return;
if (!localOptions.useCurves || points.length <= 2) {
lines(ctx, points, localOptions);
return;
}
ctx.moveTo(points[0][0], points[0][1]);
for (let i = 0; i < points.length - 2; i++) {
const xc2 = (points[i][0] + points[i + 1][0]) / 2;
const yc2 = (points[i][1] + points[i + 1][1]) / 2;
ctx.quadraticCurveTo(points[i][0], points[i][1], xc2, yc2);
}
ctx.quadraticCurveTo(points[points.length - 2][0], points[points.length - 2][1], points[points.length - 1][0], points[points.length - 1][1]);
ctx.stroke();
if (localOptions.fillPolygons) {
ctx.closePath();
ctx.fill();
}
}
function arrow(ctx, from, to2, radius = 5) {
let angle;
let x;
let y;
ctx.beginPath();
ctx.moveTo(from[0], from[1]);
ctx.lineTo(to2[0], to2[1]);
angle = Math.atan2(to2[1] - from[1], to2[0] - from[0]);
x = radius * Math.cos(angle) + to2[0];
y = radius * Math.sin(angle) + to2[1];
ctx.moveTo(x, y);
angle += 1 / 3 * (2 * Math.PI);
x = radius * Math.cos(angle) + to2[0];
y = radius * Math.sin(angle) + to2[1];
ctx.lineTo(x, y);
angle += 1 / 3 * (2 * Math.PI);
x = radius * Math.cos(angle) + to2[0];
y = radius * Math.sin(angle) + to2[1];
ctx.lineTo(x, y);
ctx.closePath();
ctx.stroke();
ctx.fill();
}
async function gesture(inCanvas2, result, drawOptions) {
const localOptions = mergeDeep(options2, drawOptions);
if (!result || !inCanvas2)
return;
if (localOptions.drawGestures) {
const ctx = getCanvasContext(inCanvas2);
ctx.font = localOptions.font;
ctx.fillStyle = localOptions.color;
let i = 1;
for (let j = 0; j < result.length; j++) {
let where = [];
let what = [];
[where, what] = Object.entries(result[j]);
if (what.length > 1 && what[1].length > 0) {
const who = where[1] > 0 ? `#${where[1]}` : "";
const label = `${where[0]} ${who}: ${what[1]}`;
if (localOptions.shadowColor && localOptions.shadowColor !== "") {
ctx.fillStyle = localOptions.shadowColor;
ctx.fillText(label, 8, 2 + i * localOptions.lineHeight);
}
ctx.fillStyle = localOptions.labelColor;
ctx.fillText(label, 6, 0 + i * localOptions.lineHeight);
i += 1;
}
}
}
}
async function face(inCanvas2, result, drawOptions) {
var _a2, _b, _c2, _d2, _e;
const localOptions = mergeDeep(options2, drawOptions);
if (!result || !inCanvas2)
return;
const ctx = getCanvasContext(inCanvas2);
for (const f of result) {
ctx.font = localOptions.font;
ctx.strokeStyle = localOptions.color;
ctx.fillStyle = localOptions.color;
if (localOptions.drawBoxes)
rect(ctx, f.box[0], f.box[1], f.box[2], f.box[3], localOptions);
if (localOptions.drawLabels) {
const labels2 = [];
labels2.push(`face: ${Math.trunc(100 * f.score)}%`);
if (f.genderScore)
labels2.push(`${f.gender || ""} ${Math.trunc(100 * f.genderScore)}%`);
if (f.age)
labels2.push(`age: ${f.age || ""}`);
if (f.iris)
labels2.push(`distance: ${f.iris}`);
if (f.real)
labels2.push(`real: ${Math.trunc(100 * f.real)}%`);
if (f.emotion && f.emotion.length > 0) {
const emotion3 = f.emotion.map((a) => `${Math.trunc(100 * a.score)}% ${a.emotion}`);
if (emotion3.length > 3)
emotion3.length = 3;
labels2.push(emotion3.join(" "));
}
if (f.rotation && f.rotation.angle && f.rotation.gaze) {
if (f.rotation.angle.roll)
labels2.push(`roll: ${rad2deg(f.rotation.angle.roll)}\xB0 yaw:${rad2deg(f.rotation.angle.yaw)}\xB0 pitch:${rad2deg(f.rotation.angle.pitch)}\xB0`);
if (f.rotation.gaze.bearing)
labels2.push(`gaze: ${rad2deg(f.rotation.gaze.bearing)}\xB0`);
}
if (labels2.length === 0)
labels2.push("face");
ctx.fillStyle = localOptions.color;
for (let i = labels2.length - 1; i >= 0; i--) {
const x = Math.max(f.box[0], 0);
const y = i * localOptions.lineHeight + f.box[1];
if (localOptions.shadowColor && localOptions.shadowColor !== "") {
ctx.fillStyle = localOptions.shadowColor;
ctx.fillText(labels2[i], x + 5, y + 16);
}
ctx.fillStyle = localOptions.labelColor;
ctx.fillText(labels2[i], x + 4, y + 15);
}
}
ctx.lineWidth = 1;
if (f.mesh && f.mesh.length > 0) {
if (localOptions.drawPoints) {
for (const pt of f.mesh)
point(ctx, pt[0], pt[1], pt[2], localOptions);
}
if (localOptions.drawPolygons) {
ctx.lineWidth = 1;
if (f.mesh.length > 450) {
for (let i = 0; i < TRI468.length / 3; i++) {
const points = [
TRI468[i * 3 + 0],
TRI468[i * 3 + 1],
TRI468[i * 3 + 2]
].map((index) => f.mesh[index]);
lines(ctx, points, localOptions);
}
}
if (f.annotations && f.annotations["leftEyeIris"] && f.annotations["leftEyeIris"][0]) {
ctx.strokeStyle = localOptions.useDepth ? "rgba(255, 200, 255, 0.3)" : localOptions.color;
ctx.beginPath();
const sizeX = Math.abs(f.annotations["leftEyeIris"][3][0] - f.annotations["leftEyeIris"][1][0]) / 2;
const sizeY = Math.abs(f.annotations["leftEyeIris"][4][1] - f.annotations["leftEyeIris"][2][1]) / 2;
ctx.ellipse(f.annotations["leftEyeIris"][0][0], f.annotations["leftEyeIris"][0][1], sizeX, sizeY, 0, 0, 2 * Math.PI);
ctx.stroke();
if (localOptions.fillPolygons) {
ctx.fillStyle = localOptions.useDepth ? "rgba(255, 255, 200, 0.3)" : localOptions.color;
ctx.fill();
}
}
if (f.annotations && f.annotations["rightEyeIris"] && f.annotations["rightEyeIris"][0]) {
ctx.strokeStyle = localOptions.useDepth ? "rgba(255, 200, 255, 0.3)" : localOptions.color;
ctx.beginPath();
const sizeX = Math.abs(f.annotations["rightEyeIris"][3][0] - f.annotations["rightEyeIris"][1][0]) / 2;
const sizeY = Math.abs(f.annotations["rightEyeIris"][4][1] - f.annotations["rightEyeIris"][2][1]) / 2;
ctx.ellipse(f.annotations["rightEyeIris"][0][0], f.annotations["rightEyeIris"][0][1], sizeX, sizeY, 0, 0, 2 * Math.PI);
ctx.stroke();
if (localOptions.fillPolygons) {
ctx.fillStyle = localOptions.useDepth ? "rgba(255, 255, 200, 0.3)" : localOptions.color;
ctx.fill();
}
}
if (localOptions.drawGaze && ((_a2 = f.rotation) == null ? void 0 : _a2.angle)) {
ctx.strokeStyle = "pink";
const valX = f.box[0] + f.box[2] / 2 - f.box[3] * rad2deg(f.rotation.angle.yaw) / 90;
const valY = f.box[1] + f.box[3] / 2 + f.box[2] * rad2deg(f.rotation.angle.pitch) / 90;
const pathV = new Path2D(`
M ${f.box[0] + f.box[2] / 2} ${f.box[1]}
C
${valX} ${f.box[1]},
${valX} ${f.box[1] + f.box[3]},
${f.box[0] + f.box[2] / 2} ${f.box[1] + f.box[3]}
`);
const pathH = new Path2D(`
M ${f.box[0]} ${f.box[1] + f.box[3] / 2}
C
${f.box[0]} ${valY},
${f.box[0] + f.box[2]} ${valY},
${f.box[0] + f.box[2]} ${f.box[1] + f.box[3] / 2}
`);
ctx.stroke(pathH);
ctx.stroke(pathV);
}
if (localOptions.drawGaze && ((_c2 = (_b = f.rotation) == null ? void 0 : _b.gaze) == null ? void 0 : _c2.strength) && ((_e = (_d2 = f.rotation) == null ? void 0 : _d2.gaze) == null ? void 0 : _e.bearing) && f.annotations["leftEyeIris"] && f.annotations["rightEyeIris"] && f.annotations["leftEyeIris"][0] && f.annotations["rightEyeIris"][0]) {
ctx.strokeStyle = "pink";
ctx.fillStyle = "pink";
const leftGaze = [
f.annotations["leftEyeIris"][0][0] + Math.sin(f.rotation.gaze.bearing) * f.rotation.gaze.strength * f.box[3],
f.annotations["leftEyeIris"][0][1] + Math.cos(f.rotation.gaze.bearing) * f.rotation.gaze.strength * f.box[2]
];
arrow(ctx, [f.annotations["leftEyeIris"][0][0], f.annotations["leftEyeIris"][0][1]], [leftGaze[0], leftGaze[1]], 4);
const rightGaze = [
f.annotations["rightEyeIris"][0][0] + Math.sin(f.rotation.gaze.bearing) * f.rotation.gaze.strength * f.box[3],
f.annotations["rightEyeIris"][0][1] + Math.cos(f.rotation.gaze.bearing) * f.rotation.gaze.strength * f.box[2]
];
arrow(ctx, [f.annotations["rightEyeIris"][0][0], f.annotations["rightEyeIris"][0][1]], [rightGaze[0], rightGaze[1]], 4);
}
}
}
}
}
async function body(inCanvas2, result, drawOptions) {
var _a2;
const localOptions = mergeDeep(options2, drawOptions);
if (!result || !inCanvas2)
return;
const ctx = getCanvasContext(inCanvas2);
ctx.lineJoin = "round";
for (let i = 0; i < result.length; i++) {
ctx.strokeStyle = localOptions.color;
ctx.fillStyle = localOptions.color;
ctx.lineWidth = localOptions.lineWidth;
ctx.font = localOptions.font;
if (localOptions.drawBoxes && result[i].box && ((_a2 = result[i].box) == null ? void 0 : _a2.length) === 4) {
rect(ctx, result[i].box[0], result[i].box[1], result[i].box[2], result[i].box[3], localOptions);
if (localOptions.drawLabels) {
if (localOptions.shadowColor && localOptions.shadowColor !== "") {
ctx.fillStyle = localOptions.shadowColor;
ctx.fillText(`body ${100 * result[i].score}%`, result[i].box[0] + 3, 1 + result[i].box[1] + localOptions.lineHeight, result[i].box[2]);
}
ctx.fillStyle = localOptions.labelColor;
ctx.fillText(`body ${100 * result[i].score}%`, result[i].box[0] + 2, 0 + result[i].box[1] + localOptions.lineHeight, result[i].box[2]);
}
}
if (localOptions.drawPoints && result[i].keypoints) {
for (let pt = 0; pt < result[i].keypoints.length; pt++) {
ctx.fillStyle = localOptions.useDepth && result[i].keypoints[pt].position[2] ? `rgba(${127.5 + 2 * (result[i].keypoints[pt].position[2] || 0)}, ${127.5 - 2 * (result[i].keypoints[pt].position[2] || 0)}, 255, 0.5)` : localOptions.color;
point(ctx, result[i].keypoints[pt].position[0], result[i].keypoints[pt].position[1], 0, localOptions);
}
}
if (localOptions.drawLabels && result[i].keypoints) {
ctx.font = localOptions.font;
for (const pt of result[i].keypoints) {
ctx.fillStyle = localOptions.useDepth && pt.position[2] ? `rgba(${127.5 + 2 * pt.position[2]}, ${127.5 - 2 * pt.position[2]}, 255, 0.5)` : localOptions.color;
ctx.fillText(`${pt.part} ${Math.trunc(100 * pt.score)}%`, pt.position[0] + 4, pt.position[1] + 4);
}
}
if (localOptions.drawPolygons && result[i].keypoints && result[i].annotations) {
for (const part of Object.values(result[i].annotations)) {
for (const connected4 of part)
curves(ctx, connected4, localOptions);
}
}
}
}
async function hand(inCanvas2, result, drawOptions) {
const localOptions = mergeDeep(options2, drawOptions);
if (!result || !inCanvas2)
return;
const ctx = getCanvasContext(inCanvas2);
ctx.lineJoin = "round";
ctx.font = localOptions.font;
for (const h of result) {
if (localOptions.drawBoxes) {
ctx.strokeStyle = localOptions.color;
ctx.fillStyle = localOptions.color;
rect(ctx, h.box[0], h.box[1], h.box[2], h.box[3], localOptions);
if (localOptions.drawLabels) {
if (localOptions.shadowColor && localOptions.shadowColor !== "") {
ctx.fillStyle = localOptions.shadowColor;
ctx.fillText(`hand:${Math.trunc(100 * h.score)}%`, h.box[0] + 3, 1 + h.box[1] + localOptions.lineHeight, h.box[2]);
}
ctx.fillStyle = localOptions.labelColor;
ctx.fillText(`hand:${Math.trunc(100 * h.score)}%`, h.box[0] + 2, 0 + h.box[1] + localOptions.lineHeight, h.box[2]);
}
ctx.stroke();
}
if (localOptions.drawPoints) {
if (h.keypoints && h.keypoints.length > 0) {
for (const pt of h.keypoints) {
ctx.fillStyle = localOptions.useDepth ? `rgba(${127.5 + 2 * (pt[2] || 0)}, ${127.5 - 2 * (pt[2] || 0)}, 255, 0.5)` : localOptions.color;
point(ctx, pt[0], pt[1], 0, localOptions);
}
}
}
if (localOptions.drawLabels && h.annotations) {
const addHandLabel = (part, title) => {
if (!part || part.length === 0 || !part[0])
return;
ctx.fillStyle = localOptions.useDepth ? `rgba(${127.5 + 2 * part[part.length - 1][2]}, ${127.5 - 2 * part[part.length - 1][2]}, 255, 0.5)` : localOptions.color;
ctx.fillText(title, part[part.length - 1][0] + 4, part[part.length - 1][1] + 4);
};
ctx.font = localOptions.font;
addHandLabel(h.annotations["index"], "index");
addHandLabel(h.annotations["middle"], "middle");
addHandLabel(h.annotations["ring"], "ring");
addHandLabel(h.annotations["pinky"], "pinky");
addHandLabel(h.annotations["thumb"], "thumb");
addHandLabel(h.annotations["palm"], "palm");
}
if (localOptions.drawPolygons && h.annotations) {
const addHandLine = (part) => {
if (!part || part.length === 0 || !part[0])
return;
for (let i = 0; i < part.length; i++) {
ctx.beginPath();
ctx.strokeStyle = localOptions.useDepth ? `rgba(${127.5 + 2 * part[i][2]}, ${127.5 - 2 * part[i][2]}, 255, 0.5)` : localOptions.color;
ctx.moveTo(part[i > 0 ? i - 1 : 0][0], part[i > 0 ? i - 1 : 0][1]);
ctx.lineTo(part[i][0], part[i][1]);
ctx.stroke();
}
};
ctx.lineWidth = localOptions.lineWidth;
addHandLine(h.annotations["index"]);
addHandLine(h.annotations["middle"]);
addHandLine(h.annotations["ring"]);
addHandLine(h.annotations["pinky"]);
addHandLine(h.annotations["thumb"]);
}
}
}
async function object(inCanvas2, result, drawOptions) {
const localOptions = mergeDeep(options2, drawOptions);
if (!result || !inCanvas2)
return;
const ctx = getCanvasContext(inCanvas2);
ctx.lineJoin = "round";
ctx.font = localOptions.font;
for (const h of result) {
if (localOptions.drawBoxes) {
ctx.strokeStyle = localOptions.color;
ctx.fillStyle = localOptions.color;
rect(ctx, h.box[0], h.box[1], h.box[2], h.box[3], localOptions);
if (localOptions.drawLabels) {
const label = `${h.label} ${Math.round(100 * h.score)}%`;
if (localOptions.shadowColor && localOptions.shadowColor !== "") {
ctx.fillStyle = localOptions.shadowColor;
ctx.fillText(label, h.box[0] + 3, 1 + h.box[1] + localOptions.lineHeight, h.box[2]);
}
ctx.fillStyle = localOptions.labelColor;
ctx.fillText(label, h.box[0] + 2, 0 + h.box[1] + localOptions.lineHeight, h.box[2]);
}
ctx.stroke();
}
}
}
async function person(inCanvas2, result, drawOptions) {
const localOptions = mergeDeep(options2, drawOptions);
if (!result || !inCanvas2)
return;
const ctx = getCanvasContext(inCanvas2);
ctx.lineJoin = "round";
ctx.font = localOptions.font;
for (let i = 0; i < result.length; i++) {
if (localOptions.drawBoxes) {
ctx.strokeStyle = localOptions.color;
ctx.fillStyle = localOptions.color;
rect(ctx, result[i].box[0], result[i].box[1], result[i].box[2], result[i].box[3], localOptions);
if (localOptions.drawLabels) {
const label = `person #${i}`;
if (localOptions.shadowColor && localOptions.shadowColor !== "") {
ctx.fillStyle = localOptions.shadowColor;
ctx.fillText(label, result[i].box[0] + 3, 1 + result[i].box[1] + localOptions.lineHeight, result[i].box[2]);
}
ctx.fillStyle = localOptions.labelColor;
ctx.fillText(label, result[i].box[0] + 2, 0 + result[i].box[1] + localOptions.lineHeight, result[i].box[2]);
}
ctx.stroke();
}
}
}
async function canvas2(input, output) {
if (!input || !output)
return;
const ctx = getCanvasContext(output);
ctx.drawImage(input, 0, 0);
}
async function all(inCanvas2, result, drawOptions) {
if (!result || !result.performance || !result || !inCanvas2)
return null;
const timestamp = now();
const localOptions = mergeDeep(options2, drawOptions);
const promise = Promise.all([
face(inCanvas2, result.face, localOptions),
body(inCanvas2, result.body, localOptions),
hand(inCanvas2, result.hand, localOptions),
object(inCanvas2, result.object, localOptions),
gesture(inCanvas2, result.gesture, localOptions)
]);
result.performance.draw = Math.trunc(now() - timestamp);
return promise;
}
// src/face/angles.ts
var calculateGaze = (face5) => {
const radians = (pt1, pt2) => Math.atan2(pt1[1] - pt2[1], pt1[0] - pt2[0]);
if (!face5.annotations["rightEyeIris"] || !face5.annotations["leftEyeIris"])
return { bearing: 0, strength: 0 };
const offsetIris = [0, -0.1];
const eyeRatio = 1;
const left = face5.mesh[33][2] > face5.mesh[263][2];
const irisCenter = left ? face5.mesh[473] : face5.mesh[468];
const eyeCenter = left ? [(face5.mesh[133][0] + face5.mesh[33][0]) / 2, (face5.mesh[133][1] + face5.mesh[33][1]) / 2] : [(face5.mesh[263][0] + face5.mesh[362][0]) / 2, (face5.mesh[263][1] + face5.mesh[362][1]) / 2];
const eyeSize = left ? [face5.mesh[133][0] - face5.mesh[33][0], face5.mesh[23][1] - face5.mesh[27][1]] : [face5.mesh[263][0] - face5.mesh[362][0], face5.mesh[253][1] - face5.mesh[257][1]];
const eyeDiff = [
(eyeCenter[0] - irisCenter[0]) / eyeSize[0] - offsetIris[0],
eyeRatio * (irisCenter[1] - eyeCenter[1]) / eyeSize[1] - offsetIris[1]
];
let strength = Math.sqrt(eyeDiff[0] ** 2 + eyeDiff[1] ** 2);
strength = Math.min(strength, face5.boxRaw[2] / 2, face5.boxRaw[3] / 2);
const bearing = (radians([0, 0], eyeDiff) + Math.PI / 2) % Math.PI;
return { bearing, strength };
};
var calculateFaceAngle = (face5, imageSize) => {
const normalize = (v10) => {
const length = Math.sqrt(v10[0] * v10[0] + v10[1] * v10[1] + v10[2] * v10[2]);
v10[0] /= length;
v10[1] /= length;
v10[2] /= length;
return v10;
};
const subVectors = (a, b10) => {
const x = a[0] - b10[0];
const y = a[1] - b10[1];
const z10 = a[2] - b10[2];
return [x, y, z10];
};
const crossVectors = (a, b10) => {
const x = a[1] * b10[2] - a[2] * b10[1];
const y = a[2] * b10[0] - a[0] * b10[2];
const z10 = a[0] * b10[1] - a[1] * b10[0];
return [x, y, z10];
};
const rotationMatrixToEulerAngle = (r) => {
const [r00, r01, r02, r10, r11, r12, r20, r21, r22] = r;
let thetaX;
let thetaY;
let thetaZ;
if (r10 < 1) {
if (r10 > -1) {
thetaZ = Math.asin(r10);
thetaY = Math.atan2(-r20, r00);
thetaX = Math.atan2(-r12, r11);
} else {
thetaZ = -Math.PI / 2;
thetaY = -Math.atan2(r21, r22);
thetaX = 0;
}
} else {
thetaZ = Math.PI / 2;
thetaY = Math.atan2(r21, r22);
thetaX = 0;
}
if (isNaN(thetaX))
thetaX = 0;
if (isNaN(thetaY))
thetaY = 0;
if (isNaN(thetaZ))
thetaZ = 0;
return { pitch: 2 * -thetaX, yaw: 2 * -thetaY, roll: 2 * -thetaZ };
};
const meshToEulerAngle = (mesh2) => {
const radians = (a12, a22, b12, b22) => Math.atan2(b22 - a22, b12 - a12);
const angle2 = {
pitch: radians(mesh2[10][1], mesh2[10][2], mesh2[152][1], mesh2[152][2]),
yaw: radians(mesh2[33][0], mesh2[33][2], mesh2[263][0], mesh2[263][2]),
roll: radians(mesh2[33][0], mesh2[33][1], mesh2[263][0], mesh2[263][1])
};
return angle2;
};
const mesh = face5.meshRaw;
if (!mesh || mesh.length < 300)
return { angle: { pitch: 0, yaw: 0, roll: 0 }, matrix: [1, 0, 0, 0, 1, 0, 0, 0, 1], gaze: { bearing: 0, strength: 0 } };
const size2 = Math.max(face5.boxRaw[2] * imageSize[0], face5.boxRaw[3] * imageSize[1]) / 1.5;
const pts = [mesh[10], mesh[152], mesh[234], mesh[454]].map((pt) => [
pt[0] * imageSize[0] / size2,
pt[1] * imageSize[1] / size2,
pt[2]
]);
const y_axis = normalize(subVectors(pts[1], pts[0]));
let x_axis = normalize(subVectors(pts[3], pts[2]));
const z_axis = normalize(crossVectors(x_axis, y_axis));
x_axis = crossVectors(y_axis, z_axis);
const matrix = [
x_axis[0],
x_axis[1],
x_axis[2],
y_axis[0],
y_axis[1],
y_axis[2],
z_axis[0],
z_axis[1],
z_axis[2]
];
const angle = rotationMatrixToEulerAngle(matrix);
const gaze = mesh.length === 478 ? calculateGaze(face5) : { bearing: 0, strength: 0 };
return { angle, matrix, gaze };
};
// src/face/face.ts
var detectFace = async (parent, input) => {
var _a2, _b, _c2, _d2;
let timeStamp;
let ageRes;
let gearRes;
let genderRes;
let emotionRes;
let embeddingRes;
let antispoofRes;
let descRes;
const faceRes = [];
parent.state = "run:face";
timeStamp = now();
const faces = await predict6(input, parent.config);
parent.performance.face = Math.trunc(now() - timeStamp);
if (!input.shape || input.shape.length !== 4)
return [];
if (!faces)
return [];
for (let i = 0; i < faces.length; i++) {
parent.analyze("Get Face");
if (!faces[i].tensor || faces[i].tensor["isDisposedInternal"]) {
log("Face object is disposed:", faces[i].tensor);
continue;
}
const rotation = calculateFaceAngle(faces[i], [input.shape[2], input.shape[1]]);
parent.analyze("Start Emotion:");
if (parent.config.async) {
emotionRes = parent.config.face.emotion.enabled ? predict5(faces[i].tensor || Dr([]), parent.config, i, faces.length) : null;
} else {
parent.state = "run:emotion";
timeStamp = now();
emotionRes = parent.config.face.emotion.enabled ? await predict5(faces[i].tensor || Dr([]), parent.config, i, faces.length) : null;
parent.performance.emotion = Math.trunc(now() - timeStamp);
}
parent.analyze("End Emotion:");
parent.analyze("Start AntiSpoof:");
if (parent.config.async) {
antispoofRes = parent.config.face.antispoof.enabled ? predict(faces[i].tensor || Dr([]), parent.config, i, faces.length) : null;
} else {
parent.state = "run:antispoof";
timeStamp = now();
antispoofRes = parent.config.face.antispoof.enabled ? await predict(faces[i].tensor || Dr([]), parent.config, i, faces.length) : null;
parent.performance.antispoof = Math.trunc(now() - timeStamp);
}
parent.analyze("End AntiSpoof:");
parent.analyze("Start Description:");
if (parent.config.async) {
descRes = parent.config.face.description.enabled ? predict7(faces[i].tensor || Dr([]), parent.config, i, faces.length) : null;
} else {
parent.state = "run:description";
timeStamp = now();
descRes = parent.config.face.description.enabled ? await predict7(faces[i].tensor || Dr([]), parent.config, i, faces.length) : null;
parent.performance.embedding = Math.trunc(now() - timeStamp);
}
parent.analyze("End Description:");
if (parent.config.async) {
[ageRes, genderRes, emotionRes, embeddingRes, descRes, gearRes, antispoofRes] = await Promise.all([ageRes, genderRes, emotionRes, embeddingRes, descRes, gearRes, antispoofRes]);
}
parent.analyze("Finish Face:");
if (!parent.config.face.iris.enabled && ((_b = (_a2 = faces[i]) == null ? void 0 : _a2.annotations) == null ? void 0 : _b.leftEyeIris) && ((_d2 = (_c2 = faces[i]) == null ? void 0 : _c2.annotations) == null ? void 0 : _d2.rightEyeIris)) {
delete faces[i].annotations.leftEyeIris;
delete faces[i].annotations.rightEyeIris;
}
const irisSize = faces[i].annotations && faces[i].annotations.leftEyeIris && faces[i].annotations.leftEyeIris[0] && faces[i].annotations.rightEyeIris && faces[i].annotations.rightEyeIris[0] && faces[i].annotations.leftEyeIris.length > 0 && faces[i].annotations.rightEyeIris.length > 0 && faces[i].annotations.leftEyeIris[0] !== null && faces[i].annotations.rightEyeIris[0] !== null ? Math.max(Math.abs(faces[i].annotations.leftEyeIris[3][0] - faces[i].annotations.leftEyeIris[1][0]), Math.abs(faces[i].annotations.rightEyeIris[4][1] - faces[i].annotations.rightEyeIris[2][1])) / input.shape[2] : 0;
const tensor = parent.config.face.detector.return ? Br(faces[i].tensor) : null;
De(faces[i].tensor);
if (faces[i].tensor)
delete faces[i].tensor;
faceRes.push({
...faces[i],
id: i,
age: descRes == null ? void 0 : descRes.age,
gender: descRes == null ? void 0 : descRes.gender,
genderScore: descRes == null ? void 0 : descRes.genderScore,
embedding: descRes == null ? void 0 : descRes.descriptor,
emotion: emotionRes,
real: antispoofRes,
iris: irisSize !== 0 ? Math.trunc(500 / irisSize / 11.7) / 100 : 0,
rotation,
tensor
});
parent.analyze("End Face");
}
parent.analyze("End FaceMesh:");
if (parent.config.async) {
if (parent.performance.face)
delete parent.performance.face;
if (parent.performance.age)
delete parent.performance.age;
if (parent.performance.gender)
delete parent.performance.gender;
if (parent.performance.emotion)
delete parent.performance.emotion;
}
return faceRes;
};
// src/gesture/gesture.ts
var body2 = (res) => {
if (!res)
return [];
const gestures = [];
for (let i = 0; i < res.length; i++) {
const leftWrist = res[i].keypoints.find((a) => a.part === "leftWrist");
const rightWrist = res[i].keypoints.find((a) => a.part === "rightWrist");
const nose = res[i].keypoints.find((a) => a.part === "nose");
if (nose && leftWrist && rightWrist && leftWrist.position[1] < nose.position[1] && rightWrist.position[1] < nose.position[1])
gestures.push({ body: i, gesture: "i give up" });
else if (nose && leftWrist && leftWrist.position[1] < nose.position[1])
gestures.push({ body: i, gesture: "raise left hand" });
else if (nose && rightWrist && rightWrist.position[1] < nose.position[1])
gestures.push({ body: i, gesture: "raise right hand" });
const leftShoulder = res[i].keypoints.find((a) => a.part === "leftShoulder");
const rightShoulder = res[i].keypoints.find((a) => a.part === "rightShoulder");
if (leftShoulder && rightShoulder)
gestures.push({ body: i, gesture: `leaning ${leftShoulder.position[1] > rightShoulder.position[1] ? "left" : "right"}` });
}
return gestures;
};
var face2 = (res) => {
if (!res)
return [];
const gestures = [];
for (let i = 0; i < res.length; i++) {
if (res[i].mesh && res[i].mesh.length > 450) {
const eyeFacing = res[i].mesh[33][2] - res[i].mesh[263][2];
if (Math.abs(eyeFacing) < 10)
gestures.push({ face: i, gesture: "facing center" });
else
gestures.push({ face: i, gesture: `facing ${eyeFacing < 0 ? "left" : "right"}` });
const openLeft = Math.abs(res[i].mesh[374][1] - res[i].mesh[386][1]) / Math.abs(res[i].mesh[443][1] - res[i].mesh[450][1]);
if (openLeft < 0.2)
gestures.push({ face: i, gesture: "blink left eye" });
const openRight = Math.abs(res[i].mesh[145][1] - res[i].mesh[159][1]) / Math.abs(res[i].mesh[223][1] - res[i].mesh[230][1]);
if (openRight < 0.2)
gestures.push({ face: i, gesture: "blink right eye" });
const mouthOpen = Math.min(100, 500 * Math.abs(res[i].mesh[13][1] - res[i].mesh[14][1]) / Math.abs(res[i].mesh[10][1] - res[i].mesh[152][1]));
if (mouthOpen > 10)
gestures.push({ face: i, gesture: `mouth ${Math.trunc(mouthOpen)}% open` });
const chinDepth = res[i].mesh[152][2];
if (Math.abs(chinDepth) > 10)
gestures.push({ face: i, gesture: `head ${chinDepth < 0 ? "up" : "down"}` });
}
}
return gestures;
};
var iris3 = (res) => {
if (!res)
return [];
const gestures = [];
for (let i = 0; i < res.length; i++) {
if (!res[i].annotations || !res[i].annotations.leftEyeIris || !res[i].annotations.leftEyeIris[0] || !res[i].annotations.rightEyeIris || !res[i].annotations.rightEyeIris[0])
continue;
const sizeXLeft = res[i].annotations.leftEyeIris[3][0] - res[i].annotations.leftEyeIris[1][0];
const sizeYLeft = res[i].annotations.leftEyeIris[4][1] - res[i].annotations.leftEyeIris[2][1];
const areaLeft = Math.abs(sizeXLeft * sizeYLeft);
const sizeXRight = res[i].annotations.rightEyeIris[3][0] - res[i].annotations.rightEyeIris[1][0];
const sizeYRight = res[i].annotations.rightEyeIris[4][1] - res[i].annotations.rightEyeIris[2][1];
const areaRight = Math.abs(sizeXRight * sizeYRight);
let center = false;
const difference = Math.abs(areaLeft - areaRight) / Math.max(areaLeft, areaRight);
if (difference < 0.25) {
center = true;
gestures.push({ iris: i, gesture: "facing center" });
}
const rightIrisCenterX = Math.abs(res[i].mesh[33][0] - res[i].annotations.rightEyeIris[0][0]) / res[i].box[2];
const leftIrisCenterX = Math.abs(res[i].mesh[263][0] - res[i].annotations.leftEyeIris[0][0]) / res[i].box[2];
if (leftIrisCenterX > 0.06 || rightIrisCenterX > 0.06)
center = false;
if (leftIrisCenterX > 0.06)
gestures.push({ iris: i, gesture: "looking right" });
if (rightIrisCenterX > 0.06)
gestures.push({ iris: i, gesture: "looking left" });
const rightIrisCenterY = Math.abs(res[i].mesh[145][1] - res[i].annotations.rightEyeIris[0][1]) / res[i].box[3];
const leftIrisCenterY = Math.abs(res[i].mesh[374][1] - res[i].annotations.leftEyeIris[0][1]) / res[i].box[3];
if (leftIrisCenterY < 0.01 || rightIrisCenterY < 0.01 || leftIrisCenterY > 0.022 || rightIrisCenterY > 0.022)
center = false;
if (leftIrisCenterY < 0.01 || rightIrisCenterY < 0.01)
gestures.push({ iris: i, gesture: "looking down" });
if (leftIrisCenterY > 0.022 || rightIrisCenterY > 0.022)
gestures.push({ iris: i, gesture: "looking up" });
if (center)
gestures.push({ iris: i, gesture: "looking center" });
}
return gestures;
};
var hand2 = (res) => {
if (!res)
return [];
const gestures = [];
for (let i = 0; i < res.length; i++) {
const fingers = [];
if (res[i]["annotations"]) {
for (const [finger, pos] of Object.entries(res[i]["annotations"])) {
if (finger !== "palmBase" && Array.isArray(pos) && pos[0])
fingers.push({ name: finger.toLowerCase(), position: pos[0] });
}
}
if (fingers && fingers.length > 0) {
const closest = fingers.reduce((best, a) => best.position[2] < a.position[2] ? best : a);
gestures.push({ hand: i, gesture: `${closest.name} forward` });
const highest = fingers.reduce((best, a) => best.position[1] < a.position[1] ? best : a);
gestures.push({ hand: i, gesture: `${highest.name} up` });
}
if (res[i]["keypoints"]) {
const poses = match(res[i]["keypoints"]);
for (const pose of poses)
gestures.push({ hand: i, gesture: pose.name });
}
}
return gestures;
};
// src/util/interpolate.ts
var bufferedResult = { face: [], body: [], hand: [], gesture: [], object: [], persons: [], performance: {}, timestamp: 0 };
function calc2(newResult, config3) {
var _a2, _b, _c2, _d2, _e, _f2, _g, _h2, _i2, _j2, _k2, _l2, _m2, _n2, _o2, _p2, _q2, _r, _s2, _t2, _u2, _v2, _w, _x2, _y2, _z2, _A2;
const t02 = now();
if (!newResult)
return { face: [], body: [], hand: [], gesture: [], object: [], persons: [], performance: {}, timestamp: 0 };
const elapsed = Date.now() - newResult.timestamp;
const bufferedFactor = elapsed < 1e3 ? 8 - Math.log(elapsed + 1) : 1;
bufferedResult.canvas = newResult.canvas;
if (!bufferedResult.body || newResult.body.length !== bufferedResult.body.length) {
bufferedResult.body = JSON.parse(JSON.stringify(newResult.body));
} else {
for (let i = 0; i < newResult.body.length; i++) {
const box4 = newResult.body[i].box.map((b10, j) => ((bufferedFactor - 1) * bufferedResult.body[i].box[j] + b10) / bufferedFactor);
const boxRaw = newResult.body[i].boxRaw.map((b10, j) => ((bufferedFactor - 1) * bufferedResult.body[i].boxRaw[j] + b10) / bufferedFactor);
const keypoints = newResult.body[i].keypoints.map((keypoint, j) => ({
score: keypoint.score,
part: keypoint.part,
position: [
bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * bufferedResult.body[i].keypoints[j].position[0] + keypoint.position[0]) / bufferedFactor : keypoint.position[0],
bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * bufferedResult.body[i].keypoints[j].position[1] + keypoint.position[1]) / bufferedFactor : keypoint.position[1]
],
positionRaw: [
bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * bufferedResult.body[i].keypoints[j].positionRaw[0] + keypoint.positionRaw[0]) / bufferedFactor : keypoint.position[0],
bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * bufferedResult.body[i].keypoints[j].positionRaw[1] + keypoint.positionRaw[1]) / bufferedFactor : keypoint.position[1]
]
}));
const annotations2 = {};
let coords8 = { connected: {} };
if ((_b = (_a2 = config3.body) == null ? void 0 : _a2.modelPath) == null ? void 0 : _b.includes("efficientpose"))
coords8 = efficientposecoords_exports;
else if ((_d2 = (_c2 = config3.body) == null ? void 0 : _c2.modelPath) == null ? void 0 : _d2.includes("blazepose"))
coords8 = blazeposecoords_exports;
else if ((_f2 = (_e = config3.body) == null ? void 0 : _e.modelPath) == null ? void 0 : _f2.includes("movenet"))
coords8 = movenetcoords_exports;
for (const [name, indexes] of Object.entries(coords8.connected)) {
const pt = [];
for (let j = 0; j < indexes.length - 1; j++) {
const pt0 = keypoints.find((kp2) => kp2.part === indexes[j]);
const pt1 = keypoints.find((kp2) => kp2.part === indexes[j + 1]);
if (pt0 && pt1 && pt0.score > (config3.body.minConfidence || 0) && pt1.score > (config3.body.minConfidence || 0))
pt.push([pt0.position, pt1.position]);
}
annotations2[name] = pt;
}
bufferedResult.body[i] = { ...newResult.body[i], box: box4, boxRaw, keypoints, annotations: annotations2 };
}
}
if (!bufferedResult.hand || newResult.hand.length !== bufferedResult.hand.length) {
bufferedResult.hand = JSON.parse(JSON.stringify(newResult.hand));
} else {
for (let i = 0; i < newResult.hand.length; i++) {
const box4 = newResult.hand[i].box.map((b10, j) => ((bufferedFactor - 1) * bufferedResult.hand[i].box[j] + b10) / bufferedFactor);
const boxRaw = newResult.hand[i].boxRaw.map((b10, j) => ((bufferedFactor - 1) * bufferedResult.hand[i].boxRaw[j] + b10) / bufferedFactor);
if (bufferedResult.hand[i].keypoints.length !== newResult.hand[i].keypoints.length)
bufferedResult.hand[i].keypoints = newResult.hand[i].keypoints;
const keypoints = newResult.hand[i].keypoints && newResult.hand[i].keypoints.length > 0 ? newResult.hand[i].keypoints.map((landmark, j) => landmark.map((coord, k10) => ((bufferedFactor - 1) * (bufferedResult.hand[i].keypoints[j][k10] || 1) + (coord || 0)) / bufferedFactor)) : [];
let annotations2 = {};
if (Object.keys(bufferedResult.hand[i].annotations).length !== Object.keys(newResult.hand[i].annotations).length) {
bufferedResult.hand[i].annotations = newResult.hand[i].annotations;
annotations2 = bufferedResult.hand[i].annotations;
} else if (newResult.hand[i].annotations) {
for (const key of Object.keys(newResult.hand[i].annotations)) {
annotations2[key] = newResult.hand[i].annotations[key] && newResult.hand[i].annotations[key][0] ? newResult.hand[i].annotations[key].map((val, j) => val.map((coord, k10) => ((bufferedFactor - 1) * bufferedResult.hand[i].annotations[key][j][k10] + coord) / bufferedFactor)) : null;
}
}
bufferedResult.hand[i] = { ...newResult.hand[i], box: box4, boxRaw, keypoints, annotations: annotations2 };
}
}
if (!bufferedResult.face || newResult.face.length !== bufferedResult.face.length) {
bufferedResult.face = JSON.parse(JSON.stringify(newResult.face));
} else {
for (let i = 0; i < newResult.face.length; i++) {
const box4 = newResult.face[i].box.map((b10, j) => ((bufferedFactor - 1) * bufferedResult.face[i].box[j] + b10) / bufferedFactor);
const boxRaw = newResult.face[i].boxRaw.map((b10, j) => ((bufferedFactor - 1) * bufferedResult.face[i].boxRaw[j] + b10) / bufferedFactor);
const rotation = { matrix: [0, 0, 0, 0, 0, 0, 0, 0, 0], angle: { roll: 0, yaw: 0, pitch: 0 }, gaze: { bearing: 0, strength: 0 } };
rotation.matrix = (_g = newResult.face[i].rotation) == null ? void 0 : _g.matrix;
rotation.angle = {
roll: ((bufferedFactor - 1) * (((_i2 = (_h2 = bufferedResult.face[i].rotation) == null ? void 0 : _h2.angle) == null ? void 0 : _i2.roll) || 0) + (((_k2 = (_j2 = newResult.face[i].rotation) == null ? void 0 : _j2.angle) == null ? void 0 : _k2.roll) || 0)) / bufferedFactor,
yaw: ((bufferedFactor - 1) * (((_m2 = (_l2 = bufferedResult.face[i].rotation) == null ? void 0 : _l2.angle) == null ? void 0 : _m2.yaw) || 0) + (((_o2 = (_n2 = newResult.face[i].rotation) == null ? void 0 : _n2.angle) == null ? void 0 : _o2.yaw) || 0)) / bufferedFactor,
pitch: ((bufferedFactor - 1) * (((_q2 = (_p2 = bufferedResult.face[i].rotation) == null ? void 0 : _p2.angle) == null ? void 0 : _q2.pitch) || 0) + (((_s2 = (_r = newResult.face[i].rotation) == null ? void 0 : _r.angle) == null ? void 0 : _s2.pitch) || 0)) / bufferedFactor
};
rotation.gaze = {
bearing: ((bufferedFactor - 1) * (((_u2 = (_t2 = bufferedResult.face[i].rotation) == null ? void 0 : _t2.gaze) == null ? void 0 : _u2.bearing) || 0) + (((_w = (_v2 = newResult.face[i].rotation) == null ? void 0 : _v2.gaze) == null ? void 0 : _w.bearing) || 0)) / bufferedFactor,
strength: ((bufferedFactor - 1) * (((_y2 = (_x2 = bufferedResult.face[i].rotation) == null ? void 0 : _x2.gaze) == null ? void 0 : _y2.strength) || 0) + (((_A2 = (_z2 = newResult.face[i].rotation) == null ? void 0 : _z2.gaze) == null ? void 0 : _A2.strength) || 0)) / bufferedFactor
};
bufferedResult.face[i] = { ...newResult.face[i], rotation, box: box4, boxRaw };
}
}
if (!bufferedResult.object || newResult.object.length !== bufferedResult.object.length) {
bufferedResult.object = JSON.parse(JSON.stringify(newResult.object));
} else {
for (let i = 0; i < newResult.object.length; i++) {
const box4 = newResult.object[i].box.map((b10, j) => ((bufferedFactor - 1) * bufferedResult.object[i].box[j] + b10) / bufferedFactor);
const boxRaw = newResult.object[i].boxRaw.map((b10, j) => ((bufferedFactor - 1) * bufferedResult.object[i].boxRaw[j] + b10) / bufferedFactor);
bufferedResult.object[i] = { ...newResult.object[i], box: box4, boxRaw };
}
}
if (newResult.persons) {
const newPersons = newResult.persons;
if (!bufferedResult.persons || newPersons.length !== bufferedResult.persons.length) {
bufferedResult.persons = JSON.parse(JSON.stringify(newPersons));
} else {
for (let i = 0; i < newPersons.length; i++) {
bufferedResult.persons[i].box = newPersons[i].box.map((box4, j) => ((bufferedFactor - 1) * bufferedResult.persons[i].box[j] + box4) / bufferedFactor);
}
}
}
if (newResult.gesture)
bufferedResult.gesture = newResult.gesture;
const t12 = now();
if (newResult.performance)
bufferedResult.performance = { ...newResult.performance, interpolate: Math.round(t12 - t02) };
return bufferedResult;
}
// src/face/match.ts
function distance(descriptor1, descriptor2, options3 = { order: 2 }) {
let sum = 0;
for (let i = 0; i < descriptor1.length; i++) {
const diff = options3.order === 2 ? descriptor1[i] - descriptor2[i] : Math.abs(descriptor1[i] - descriptor2[i]);
sum += options3.order === 2 ? diff * diff : diff ** options3.order;
}
return sum;
}
function similarity(descriptor1, descriptor2, options3 = { order: 2 }) {
const dist = distance(descriptor1, descriptor2, options3);
const invert = options3.order === 2 ? Math.sqrt(dist) : dist ** (1 / options3.order);
return Math.max(0, 100 - invert) / 100;
}
function match2(descriptor, descriptors, options3 = { order: 2, threshold: 0 }) {
if (!Array.isArray(descriptor) || !Array.isArray(descriptors) || descriptor.length < 64 || descriptors.length === 0 || descriptor.length !== descriptors[0].length) {
return { index: -1, distance: Number.POSITIVE_INFINITY, similarity: 0 };
}
let best = Number.MAX_SAFE_INTEGER;
let index = -1;
for (let i = 0; i < descriptors.length; i++) {
const res = distance(descriptor, descriptors[i], { order: options3.order });
if (res < best) {
best = res;
index = i;
}
if (best < options3.threshold)
break;
}
best = options3.order === 2 ? Math.sqrt(best) : best ** (1 / options3.order);
return { index, distance: best, similarity: Math.max(0, 100 - best) / 100 };
}
// src/util/persons.ts
function join2(faces, bodies, hands, gestures, shape) {
var _a2, _b, _c2, _d2, _e, _f2, _g, _h2, _i2, _j2, _k2, _l2, _m2, _n2, _o2, _p2;
let id2 = 0;
const persons2 = [];
for (const face5 of faces) {
const person2 = { id: id2++, face: face5, body: null, hands: { left: null, right: null }, gestures: [], box: [0, 0, 0, 0] };
for (const body4 of bodies) {
if (face5.box[0] > body4.box[0] && face5.box[0] < body4.box[0] + body4.box[2] && face5.box[1] + face5.box[3] > body4.box[1] && face5.box[1] + face5.box[3] < body4.box[1] + body4.box[3]) {
person2.body = body4;
}
}
if (person2.body) {
for (const hand3 of hands) {
if (hand3.box[0] + hand3.box[2] > person2.body.box[0] && hand3.box[0] + hand3.box[2] < person2.body.box[0] + person2.body.box[2] && hand3.box[1] + hand3.box[3] > person2.body.box[1] && hand3.box[1] + hand3.box[3] < person2.body.box[1] + person2.body.box[3]) {
if (person2.hands)
person2.hands.left = hand3;
}
if (hand3.box[0] < person2.body.box[0] + person2.body.box[2] && hand3.box[0] > person2.body.box[0] && hand3.box[1] + hand3.box[3] > person2.body.box[1] && hand3.box[1] + hand3.box[3] < person2.body.box[1] + person2.body.box[3]) {
if (person2.hands)
person2.hands.right = hand3;
}
}
}
for (const gesture3 of gestures) {
if (gesture3["face"] !== void 0 && gesture3["face"] === face5.id)
(_a2 = person2.gestures) == null ? void 0 : _a2.push(gesture3);
else if (gesture3["iris"] !== void 0 && gesture3["iris"] === face5.id)
(_b = person2.gestures) == null ? void 0 : _b.push(gesture3);
else if (gesture3["body"] !== void 0 && gesture3["body"] === ((_c2 = person2.body) == null ? void 0 : _c2.id))
(_d2 = person2.gestures) == null ? void 0 : _d2.push(gesture3);
else if (gesture3["hand"] !== void 0 && gesture3["hand"] === ((_f2 = (_e = person2.hands) == null ? void 0 : _e.left) == null ? void 0 : _f2.id))
(_g = person2.gestures) == null ? void 0 : _g.push(gesture3);
else if (gesture3["hand"] !== void 0 && gesture3["hand"] === ((_i2 = (_h2 = person2.hands) == null ? void 0 : _h2.right) == null ? void 0 : _i2.id))
(_j2 = person2.gestures) == null ? void 0 : _j2.push(gesture3);
}
const x = [];
const y = [];
const extractXY = (box4) => {
if (box4 && box4.length === 4) {
x.push(box4[0], box4[0] + box4[2]);
y.push(box4[1], box4[1] + box4[3]);
}
};
extractXY((_k2 = person2.face) == null ? void 0 : _k2.box);
extractXY((_l2 = person2.body) == null ? void 0 : _l2.box);
extractXY((_n2 = (_m2 = person2.hands) == null ? void 0 : _m2.left) == null ? void 0 : _n2.box);
extractXY((_p2 = (_o2 = person2.hands) == null ? void 0 : _o2.right) == null ? void 0 : _p2.box);
const minX = Math.min(...x);
const minY = Math.min(...y);
person2.box = [minX, minY, Math.max(...x) - minX, Math.max(...y) - minY];
if (shape && shape[1] && shape[2])
person2.boxRaw = [person2.box[0] / shape[2], person2.box[1] / shape[1], person2.box[2] / shape[2], person2.box[3] / shape[1]];
persons2.push(person2);
}
return persons2;
}
// src/sample.ts
var face3 = `
/9j/4AAQSkZJRgABAQEAYABgAAD/4QBoRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUA
AAABAAAARgEoAAMAAAABAAIAAAExAAIAAAARAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQu
bmV0IDQuMi4xMwAA/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxob
IxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgo
KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgBAAEAAwEhAAIRAQMRAf/E
AB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAE
EQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZH
SElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1
tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEB
AQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXET
IjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFla
Y2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG
x8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A+qaKACigApGOKAML
Xp8xlF5A7V4X8RtYs7PzfNImnx8sa8Kp9z3q2tEgp6angWs62ZZ5CTGoJ6DArGNz5p+UrID6EUrF
PUlW1EuN0XNW7PQ2L5j3JnoKXN0KijqNP0eYoqXBdgPuuo+ZPeupisWn2Jd4+0r924XgsQOCff3/
AJ1FzRKxDqGii6m3siiQ8F1XGfXI6YNWLfRbiRQMkcZI9fpTDluT2/h6Qy8gDPbtmtG38JeY480Z
5zSLUTZg8M28YwYxjAArXtdPt402qgHbpSaLWhma3o0Uqk7Nx9DWLaaVblgPs6qRyds2M/gRSQp9
zZOni2iWS2hlQ+kjYz9OMGrdjq89vIPPVhj+8M/lQyDq9P1WOYBlMZz1AOD+VdDaTiReOKulK0jO
tHmi0WDTlr0TyxRVhT8tJjIX+9SUxHXUV553BRQAVBcPhSBTSuxPY86+IGti0s5I7dsORy9fM3i6
8e8mfDO5P90ZrWWiJicNPpZZtxV/xrW0jQt4DOv6Vk2dEEdTY6BHuB25rpbPSo0QARjP0qTRI17W
wA/hFaMWmoQMgflQXYsDS142rU9tpqqenfNA7GgtihxkdKuRW6qMY/GkDZY8sY4Ap4hXbyB+VArk
EtuH4wPyrk/EGkOm+a3jw3suRQLc5i38SX9hJ9nnY+XnBUdPyNdFY6pa3KkkAE9l6f8AfJ/pSJT6
GhDmI+Zb4ZRycdv6ium0nUhKFydrelTsNnS2829RnrVgV6NKXNG55lWPLIM81Op+WrZkRMfmNNzT
A7GivPO4KKAEY4XNYWt3vkwPg4OK0giJdjw/xrqhm87Zs8tc7pX5A+leSajf6aHYJ50kn4AZpTep
rBWRm2Vobm4BXfyehPFdnpmnBFUY5rI2SN63tlToK0YI+KZpFF+3QdavwoKTLtoW0Toaswpk5pCb
LCxipAhoIuP2dKevHXoaYDylRyxhlwRQI4nxVoCXWZI1GfpXGtbSWjYPGP73+NIGupt6TqMsLruZ
ih4xnP5V09mQ+JLd8gn0xSYJnVaVdkook69K34zuUGunDS3Rx4qOzHVIp4rrOMY3NJQI7GivPO8K
KAILt9kZrz3xlebYiu8KCCWb0XvW0NFch6ysfO3jLVjfXLIn+pQkKorl7WxNxIPl71g2dUUdpo+l
pBGvHPet23iC8ihFosrxirkHQUFo0IF4FXI1O726CpKLacCrMJoJLYHAPpTwucHpSRJJ5e4AZI9x
UqpxzVpCuOC8cUpQUMRnXttuB4rjNdsYyeVwfXpmpGmcvcQyafMCFJjPY10eg34BUg4DcZP8jUO4
HaRq3lLNF+IHet7R7jz7c56rwa2wz9+xhiVeFy/T1PFegeaNPWigDsc0ZrzzvDNIaAM7VpNqdegr
xL4l6kywyRhseZ19lrdfAZL4jxYg3Fw20d63tJsdrDI5rm3Z3R0R0Mce1eKnQYAplIkWrMJ45oZS
NO3PHbNXIyfpSGWowSOasxLUiZdjFSqtNEMkUemKlAGKsRJjAppFAiORMjmsTVrNZEO4cfSoZSOD
1eJ7WXBUzQZ+7nkfSo7e2Ei+ZaMzxntjBX2NSU1Y6/wxqojiEFzkA8KTXYaUoWRyv3W5rSjpNHPX
+BmpSg8V6J5gUUAdhRXnneFFAGHrTfu5PpXzj8S70/aZtxzztXFbv4DKHxHI+H4GZiz9zxXXW8G3
GBXMjvLRXAx0oPGPSmMVeOnWrMTYpFI0bcg1fh54xmgovRcD3qxETSIZcRvzp+/BpEkqsBUqsM9K
q4Em4Gkxk0yRGXrVW6i8yFhkg+tJjRxGsWrxllkUMh9eK5uMz6bcebbnfG33kPcVkay2OntPKuo0
nhXI67c8qa7Lw3c+adjcEDGK1paSRhVV4s6A0or0jyRRQ1AHX0V553hRQBz+vNtt5z3xXzX8Qbdm
uic5YnOMdK3l8JnTXvlbwpYl+WySOgrp5YfLOOB9O1c62O7qQkc+9RsKChFPWp4DluOlSykaNruH
ArUgHShFNF2NT1qxGO3NBmyxGcE1N2560CFzjrUysO9JAPDDjFOVuKoQuSRTWouBkazbCa3cd8cV
wF7IISQccHBzUSWpV9C3o1x5b5GAjdQD1rs9DjC3kckbEhqKfxIzn8LOupRXqnkPccBSkUAzraK8
87wooA5rxMSI3HqK8B8bQl9Q8sffY5b/AAraXwkUviNrw9pH2W1ViMMRTdRjw4HpWNtDti9TPc4P
FQs2M5qdyyMHLcfjV63HTAoBGtap0wK0YxigpsuRDtVhVYd6GQydVwwIqdRnqKCR23I5pCMUW6gD
YNKuetAEise9KTxQBWuFyhrznxNZkXjFeN3I+tTIZg2OqmzmxNF0PO3vXp/g2+hukVl4zyPanTXv
JmVR+60dpThXpnlPceopWFAbnV0V553hSGgRynjC5FujOey14Ssp1HxNmTnc+a3kvcIpv37HoEYQ
QmMdVHSsnVbYJF5jVk0dsNzlruVIsl2wKxbjWrVHILjg1CRbZJb+ILHPzyhfStODWLQgFJFYd+el
UJM27HUIXxhga1Y5lLVLKLkMnoauxnPPrSEx7ShF+Y/n2qrc6xBbhizDAqkK1zJuvG9nbg8ZA681
ly/Ei052RO3uKAsZlx8QGd8xxvt9Aa1NH8dK7AXMcip64zigdkdrZX8F7EJLdwwNXMkrz1qRMRly
CK4TxmpidWI49felPYSOMmi80NIoOV6qRzXYeA5SskYPfirpfEjGr8LPWVHyD6U4CvQPL3ZItOYc
UDOoNFeed4Uhpks4H4iE/Z5MeleMeGULeLgjds10S+BGdL+Jc9OSBU2Huc5Nc74yvUtrcDBrJnZF
63PJdXvLy/lKWw46bvQVz82jXhkLO5Y+9ZlsYthcRnbIjY9R3q3awTRkEM3WmJI6C0ea3dGRsr1x
XY6TqW9FLHnjrUs0izpLK5DDjofSta3ckH09KRUkZuuTvFGdvPauE1Y3U6Mqbssf/rUxHPTaJPK2
ZmJPbBqzY6DCZh5xJC9s9aBJHU6dpemJjfEmfetJtI0+VPkUr/unFOxdiextHs33W07YHQHk11mk
Xb3KbZ1xIvcd6LEyWho4Nct41sTPYb16ipexCPPZN+wYGCvH1rrPAEJmvkPoc1VL4kZVvgZ6yFwK
cBXoHkkqinFaVyzo80GuE7WJRQSziPiGdthK5HQV4x4J/wBI8WPIewNdEvgRNL42emO/yj1UHNef
eNpRczbC+I17DvWT2OqJxc0sMK4TCisy41q0hfEkqj8aixdwTXNOlwvmqD9anS9tXH7uVG+hosO4
/wC0oOhrR0+6G4YNIEzsNEuCxAPNdjZruA4xxUmjINSjURksOlcbqFykbnjFA1sYGoassaknCqO5
rl7rxhGm7yBnBxuJq0rkSlYpw+NLlsfd5P8AerVsvHEqSBHwPVgcgVpyMyVXU3rXxcHYETAk+hru
/DWti6ZSTyOKzZqndHaxvvUGq2rQ+dYyqR24qWI8dvbr7LqDxyDAzXpvw6FvIxePGSM06Xxoyr/A
zviKFHNegeX1J41zUhXioGbuaSuM6wpCaBHG/EcA6HN/exxXjXw2jL67cv8A3Qa6H8CFR+NnoWpO
I4XI44rxLxrqjQzSEsQM1gdSPM9U1uR1YbmWIdXHf2rmpIb67YS28UrRlsLI3c/jW0VZGUpO5pW1
jfLNOjahawzwReYI5cjzMkDavHJ5/SrVv9uhtPtVxCPLBwzxnlT9KGghLU3tKvvPjHzbl7EGuisJ
GRxWLOg7nRXJEbDjmvSNK+aFSfSoZr0KutRkphc4NcRrdkVjL9aVio7Hk3iqS8ubhrWzUlsZY9kG
cZNc5D4aee5MclzJIFTzHAO0MfatqSOWu7bFS1srDUZEis0vIZoUxPvfcC+4/dx2xjr712XiTwXb
WmlQ6hol3cRhoFd4rlg3zY5wR0GelavQwjq7GD4etdVvSnk2wAB+9v8A8mvcfA2kXiRo0/UdcDis
ZnTTulqeoWqbUAJqWUb42X1FZlnjfjSwlGrr5S/eNdD4RkvLAAQ4yRyaUZcruVKl7TQ9I0G+mnzH
ckFwM8VuIK7ac3KF2eXiKapz5UWYxipNtMyNejNch0jSar3cjR27uoyQCRVRWom9DxTx54gu5fMi
lbKdMVjfCZPNlv5v9rFbVHpYqjGzbOn8SzFI9o715L4u0r7arYzk+lYdTqSujy7U/C0u4vHk+WwO
xuh9q3J9dgvbdVukMV1EwbDDgn04rZMwlHoZ+orZ6hfQ3RWVnQYCgZAq+8U0ln5NtBsV2yxYcfgK
JtW0CnB31LlroVwJ1nQLGDjeP7w+lb0dsFxjrWB0tHS6NuWPJ6A16ToUm63T3Gallr4S7cxiTjrX
PaxaF7dlVeSMUhxZ5jd+H7qCa4eF3DSE5x3zXN3Wk6jbyeaiFWUY6ZyPStYS5SalPmVipFbX0E4c
W0alvmPHJrag0rVvEE6LdljGpG2NRtQD+tW5XMI0uU9M8NeFo9PiQhecDIIrtrOMIoG3H4VlJm9t
C6CB06VPGM1IHLeItGS6uw+ORT7e3jsbQvj7gzUNam0JaWE+HN7NqOqX80n3FO1RXo8YzXdS+BHk
4z+KyzGPapcU2YIv7qQtiuaxvcaWqG4O6FwfSrS1JbPnrxoxkv7qIfejcitj4V2f2exumI+8+aKn
xHTT+G5d8Txlm4rjLxMsQwzWT3OiK0Mm6sEkVsAcjFc1d+FEmlGwEDPQVopaEuOpr6f4ZWNAu3tW
vHpAj5ZQcUFIWaDjGMVUMQ3cVDBmvbhY7QAV2nh+T/R1yeKhlrY31+b61FcQK6nIoJMi401WblRi
qr6PCw5UYq9y+YgOgWzNkRrx3xWjp+nx2v3FQcelAbmko9anQ4GBUNisPHWr1qMrQhS2K11HvmYV
hamcxSRZ5xRIqluS/DKAQQXZxyXrvo2FdlL4EeZjH+/ZbjNSZpswLNBrE1Gt7VE4ODVIlnh/j61F
j4lmeTGyUbq6LwdEqWbeX0YbhSqfEddP4Bddj4JIrhL5d8h7VjI6oLQqKNzelWre3yc4/ClFjaL6
wqBxxUUxwCKu5BmXRA6c+9ZjP83FSBoQuPs4BrsNBlUW659KmRrDY6G1lyQtW3Hy0lqQ1qVJnAbm
oy3b9KYJCqRj3o4zRctIlhjLHmpSuOBRbQOpLGpPFaES7UqkZzKN1KsEc87/AHUUmvPLTVGv72aQ
k7WJwKmRrQ3ud74Ltilgz4++2a6iNDXdS0gjyMU71my7GpqTbxSbMki3SViajTTHqkSeR/GeyZmg
nQHkEE1S+F+oPPavBL96I4/Cia1udVF+4dVrkW+Fq8+v4tjMDWUkdVJ6WM0cNV+F+MVmjUcZgqnP
1qpNNnkcVRLiZtxIS1UzzIF7mghlxUZpVQdq6nTVdAoAOKzkbQWhvwM6gMM1twOJYx3NOJE11Kt1
H1/pVVlwBkk+9NocXoOQ45FPj+fkUJFF2NSB700v/hTEty5ZpkjvVyUgcCq6GM9zC14/8Se6GcZQ
1574Xs5WkI2HBPHFQ1dm1KSSZ7Rotn9l0+KPHIHNacae1dy0Vjxaj5ptlhVp+2s2CJ9ppCKzuWNx
zSFc1SYrHNeNdIGpaYw25ZeRXmvheyk0jVpEdcLJ0q3ZxNKTa0O3vQHg/DNcHrsJDmsmjspnNzNt
fFIJ24GazOhC+azDmgZIOOKBsp3J2qSaZodubq58yQ4QAnmhGT3NO18pb7BORmu205LfYpyKVkWp
Oxr5gKYWoIZWgfGfloFq1qTPLubnGO1RPtxg4P0oBAkY/hBz6VNDDkZ6AU0W2WSdqkdKr9ZOaGSj
VtcLHmnOcgmmYvcz7mBLy3MbdD1q9ouiRK6bUAVeelOC1InPlidSsWMDFOCEdq3uefykqrinYqGy
rFvApMVka2DAowKAsMkRXQqwyDXn/iWyitNQ3qPl6itIvRoF8RXinW4tQ6HI6GuW8SIVBPalc6qe
5x9x97r3qruwTjrWZ0ksZ9TUmcDNAmZ9/wAoao63rR0+w22MLPtAzt6mghmfofiB76LdJBJBIp5D
d/oa7bSdWLIPnpDi9TM8TeKdas51XTbIyxd3J/pXS+E/EFxqNoFu7do5OmD60maHWrnZyDRkn/69
MlEyOR0xntVoNx+FUgYjPxg4FLCuWDZyKQr2RoRnP0qO+nEFpJITgAUzLqZnhu6+0rknOTXpOmwJ
Fbrt5yMmnHYyr6Oxb2ijaKLnPYMClwKQWK3n0hn+lachHOJ9pNNN0apQFzsY10a4v4hXQh0xpieQ
MA1XLZNjhK80cT8OdV+3Wl3A7ZZJCw+hrR1qLcjZ/CsbnfHRnFXseHJArOYYbrUs1uPhYbuatqFP
ByfSkMq3UIINYkto+87Tx6GkSxfsDbflGD7CtTw/pk4nzITtPIFMFudsukh4Rxz71paTpKwP5jcn
0qTRy0NORMDgVCqewoJTJgAoxjntTiTu7fWmFxAcnn1q3EPl+X8KZMi4gKqB1Peob/Tv7Us5bfeU
yOoq4R5nYxqT5I8xieH9J1DTbvyJELRg8ODwa9Ms5mSFV9BWiptbnNVrKdmif7Q1KLg96XIZc5Is
pNL5pqeUrmMtZs0jzV08phchaY00zH1p2ZNxjS1g+LdJOt6U9ssmxjyGp2urDjLlaZzng/wUPDqz
TSTmWeTrjpVjVk3Rvjr2rnqQ5dDvo1XUd2cTqSNk9OKxXGCeKxZ1DAxHTr2q5C/y8GokUhsz54qu
uCxzSQjQ0+FZblR2ro4bZYiMVQ0dBb7Qi5x0qzuG5QOh71LYErDufpSeWrHnimIXbjkUjLkH1Hem
gGxryc+tXI19KYmWegq9YLiLJ7mtqS945cS7QsWehqxA9dEjz4krPSxyZqbFFhGxUm6smjRM55Lk
HvSvNxXTY57kLT+9MNwKdhXGm5FIbkU7Bca1wMEVhaiuQcVhXWiZ14R6tHGanGBI2OtYkqEHjgVy
s9ErEeo6UBsHipKEZs5qpPdRxcbhx70NCSuybTNWihc5brW9Fq6vjMnFSdEIdDRi8RRKygZbHFbu
m6nb3RA3gMegNJhOm0jbXGOoxTuCc1Rz3FyoGKawz9KaAVcZqeMgCmIkB4FaUTbYwB6V00Fuzixb
0SFMuDU8Mlbs4UPeXHeiOXkUrDuXYnyKk3cVk0ap6HMxxketSMhrcwRC0dMMZFMQ3yzSeVQAeUaz
9Vj8uPd271nVV4m+GdpnHX67pCeKyLtBtNcR6xlk9RVeWTb3qRnO6trgttyIfm71z7ai8j7/AJmN
DNqUVa5Yi1AnjynHuBV+11YJhWWXcP8AZNSzqgmaEerSsf3NtIQP4mGKtRavdRgMIpVI9KjU0a7n
R6T43uYQI7qN2Tpkqciu503VVuQGAYZHQjFVc4alPlZrpKGAznpTwxOc9+lWjIlUACnM4XApiLNk
nmvnsK0NvpXZRVonmYqV52GsmanhXitTmFkSiJTSAvwrxUxXIrJ7miOfjf1pzNWxkRlqYWpgJupu
6gQbuahvIxPA6eo4pNXVioS5WmefakGhndH4INZs5DJXA10PaTurmLO21uKpSZqGMoXGnRzBiyjd
9Kx5rcQS428fSkjanLoaOliHGZFB56VswW+mtPufcBsGOAfmxz+tFkd8HpoaUx09FAtFY8DO71qb
Sms/Nb7RbecG6AEjFLS5c78t+p0djpVs9wsyQiJAdyr1rW+zqjErzSe559Sbk9S3C+MA1bjbgE1S
MSXzMVG0vNUI2tPKrAuCMnrVzNd0PhR49W/O2xrHmp4TxVMzQshpIzzQBehqesnuaI5VGzT2bitz
FEbNTC1ADS1JupgG6l3UAc14s04yR/aYRll+8BXCtLncDXFWjys9TCz5oW7GddH5qqNzWDOgQnC8
VSuo1kHzAGkPYopEY2+RWxV23Vzj5G/Kg3jWaNazhZuqNXS6TaKhB2c0jR1nJWOlhOxRxU4YkCgx
Y0OQatQyDbyaaFYe8uF4NY3iC9ltbVGj43NTIL3h7WzMihjzXVQXYYDdW9Cf2WcOJpfaRZ3g9KsQ
mupnCLIabGeaAL0LcVY3cVmzRHIxtUhetzEjZqjLUAIWpN1ArhupwagAfDKQ3Q1594v0c2bm6tx+
5Y8j+6ayrR5onThp8s7dzkZjuqAAmuBnqC7c0iwgtzSA0rWzjfGRW3ZadDu4AoNYo2rfS4v7orSh
05UA2r0pDbsTm29KRottBNyJ0wpJ9KhD7f6U0ikNWffIFBz60zVUW52ow4UcUN6EPcx44WsbgOmd
ua7TT5Bd24KHnFKnLlZFSN4koluLdueRWvp14swweG9DXoxldHlTjYtzGoo25qzEvwtUxas2jRPQ
5CNqkLVsYoYzUzdQA3dSFqBBmnqaBhuqhriCXTpVIzxUz+Fl03aSPI9QTypW2/dz0qKNw3SvOPZR
Mqin8VLKRcs3O4Cuk0w/MDjt1NBtHY6O2IIHY1pxgFaETIRwMkjtVSUEk4570MlFW5bap6dKzWm8
1tqH8aY+hp2FvGoGayNevVt7/ap4xzUvYjqTLtvLPcvJxSaVcyWsxTnFZlnT2t15xHmCtOBYwQy4
B9q7cPO+jPPxFO2qLEj5HWo42+aus4HpoX4W4FTF+KlotbHII9SFuK0MUNZqiLUDE3UbqBBupwag
Bc1DefPbyD/ZND2KjujyPWlKzuPesRZjHJXms9lMuw3StjnmphKDSLTJ7OfE3JrpbO4GQc9qlnRA
3LO82k5NbFvdADkjBoCSHyXIIIzgVQvdRigT7wzjgUzO1jHknlvG7qnp61etYFQDIpCZoqVijzXn
3iC8EmsOuaCGb/heR/s0ijkVv6fbxy3QMg5xmsnuX0Ldzut3+UYTPWk+2GJSe+M1pFtamcldalmx
1eO4XaThhWnC+TXqR2PHqL3maUJ4qRjxSEjj42qXdxVmaGs1MJoATfSbqBAG5p6mgAzTJTmNvpQU
tzzHXY83D/U1zF5FhjgV5r3Pa6FMsV5HWnLe7RhqBRdmTwagN2d2K2rPU1C5LAnPrUs6Iysbdrq6
f3gK0BrUKj/WClY05iM6xLOcQAj3NT29uznfKSzHuadzNu7NSBFjHNSm5VO9IRnajqoWMhTzXFtA
bvUfMduSeg702Qz0rS7FbTToQFwzjJqaGTFyfK5PQViyzUuFmuIdgGABya5u/vTaN5cnUHFUmLoZ
zyskwlgJweSK6zQdUEwVJeGr0aUrxPLxEfe0OrhPAqVjxWhznGRtUwatDK4jNxURbmkAm6jNABup
6tQAFqhupNtu59qUnZFwV5JHnWsHdIx96w5lz15rzT2uhRmt85xWbcxMnUGmZlB0bdxmrNvFIcfM
350mWjbs7YkDJY/jW5ZWW4jikWkdNp9mqYJFaJdEHHakUULu/VB1rLn1Ld/FgetMGYd/qWSQmSa0
/AemS32pfa7piLeLkg9z6UmQtz0W7uQ2cZx0A9BVzR7cAea6j2rPqX0L99KRat5A6Dk1wOoKZ52a
YfMORTYRLujiGWEq6/NWza2yKQVHNdOHerRy4laJo6TTnbbtb8KuM3Fdh5z3OJjbmpt3FaMxAtUZ
agBN1GaQBzTwaAAms3VbjERUGsa07RsdeFpuUuY4jUjljWTKK4j02RE4IpJYFk6imQkVl0xWarsO
mAEcUi0bNnZBR0rWtoguMCkUi21wI161mXuocEKaYXMS4u+pY/hVCSWSY4HT0pEmlouiSahdpEBl
mOceleiwWcNjClvHgJH97Hc1EmVFFi3Czy7mwIl/WtJbjP7uLgd/apQ2VNVvtsBhiPzdK5S4nAuR
nqOCaTGi9pcytPlU+XpmumtWII44rah8ZjiNIXRuWeNvvViQ/LXpJWPJbu7nCRvVkNxVsxBmqJmo
EPiXca0YLMuOlJsuKuPlsSi5IrNuG8s4HWs5VEkbwoOTKsk+FJY4rC1K53k1xTk5O7PSpwVNWRzt
4cms+WpKICtSLTETQj5q0YeBSGiys23pUguGxQMq3E59ayrm4x3yaAKiRtO2WPHcmhruKFxFajzZ
ScA44qRHoXhuMaLpxaUg6hcDLMf4F9KlhuDeXGASIl+8azZslYma68y48m1+7nFW5rtbRNhb5z1p
iMKbUg0zuW4A4rPgb7VdKXOMmpA7HRbMS7nUYiUda0lkQOBngVrS+JGdbWLRt2bAx5BqeQ/LXpnj
PQ4GJ+ashuK0MhWaoWcA0AaOmASMK7jRNPWYBmHyiuepO2x10qfcv6vYxCzYqoGK4HVYVTJrmb5l
c6oaM5TUJ8EgGsG4kLNUHT0M64OaqMMikSRsuKbnFMRLG3zVehOaGNE445NNlnVFpDMu6uie9Vo1
8z5mOAOST2pDK91cNN+5tsrH3PrW54a06KxT7fdrlh/q1Pc+tJ6IUdZGvHPLezMcnBOWbsPap5r3
ylFtbdT1xUWNWzU0/Zbwlgfmx8zGsHWtRHmMqE59aAMyNifvHPc1f0gtPdqkY5JosJHeNci2tktY
euPnNY+oXWZEVJNrZ9aun8SIq/CzodHuriIokhDIR1ronbKZr0o6o8ipoz//2Q==`;
var body3 = `
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAsICAoIBwsKCQoNDAsNERwSEQ8PESIZGhQcKSQrKigk
JyctMkA3LTA9MCcnOEw5PUNFSElIKzZPVU5GVEBHSEX/2wBDAQwNDREPESESEiFFLicuRUVFRUVF
RUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUX/wAARCASwBLADASIA
AhEBAxEB/8QAGwABAAIDAQEAAAAAAAAAAAAAAAEDAgQFBgf/xABDEAEAAgECBAMECQIDBgUFAQAA
AQIDBBEFEiExE0FRBiJhcRQjMkJSgZGhsWLBJDNyFSVTY3OSNEPR4fAHFjWCokT/xAAYAQEAAwEA
AAAAAAAAAAAAAAAAAQIDBP/EACARAQEBAQADAQEBAQEBAAAAAAABAhEDITFBEjJRIhP/2gAMAwEA
AhEDEQA/APqYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAKNTq8OkxzfNkisQC8eb1XtRNbzXT4q7eU2nu0MntRq/D8StMccvW29ZmdvgjsTyvZjxOLj
+s8WLxn8TFPXs6Oj9oct7c14rkxz22nrB2I49KOdTjelmszfmpMeUxv/AA28OqwZ4icWWtt/SUi4
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmdo3nsPNe0Pt
Fh09Z0+DNWL7+9O/7A3eJcZppsV5raI27esvH6jX5ddM25p79Ilo59VbUZOe2Tm/PeGvfPfT2iKR
PLv1+DO678XmW/a97U6TtOyzTbTF538/T9WjTNecm9a7126tqk3rSYxY5ta1plRZqZNXGjyZcPXl
mZmsx+qjBrsuO16xM7eXRt04JrdTltk5OWJnfaWf0a2lty5MdZnfzSn+WOHiOutFpjHa9e8bQ2fp
+alYy462pk7zXbuxjPesbRS0f6ZZV1ET1tErzXFLHo+A+1ddZf6NrI8PJHa1vN6iJi0bxMTHwfOa
zhzd61v1846utwniM6DUdb3nBaNrVmd9vjC/ZVePYirBqMWppz4rxaPgtEAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAItaK1m09ojcHnvarjM8P0vh49+a/eY8ng9D
h1fGM1rxjtGPfvbzdbjuTJxHX48cTPNltM/KsS9Dw7S49Jp6UpHaGe2vjz1y9J7LYK13vHWe7bj2
ex1tvM80ekuxW3RnW3Vm6P5jRx8H0+OYmMcb+bapo8GKPdpC6bQwtdHU8JpWkdJ/JweL6e23iU67
d4dubSqyVi9Zi0bwIs68XGp36TtEq7ZJmZmevzdbifCKWtbJinkt6eTgZPFw32t+sRurbWVzxs1y
Rv6T8V1NZNPtfq0seTm+Kevr+SZuxXjvaPiV8N4viycto9HseG6+uu08W6Rkj7UPmFck1tE1nlmP
Ld3eA8V8HVVi1pjq6Ma/pnqce/ERMTETHaUrKgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAADW19+TQ5p/p2bLS4v04Zmt5VjeQeJ4bjnLqsupv+Ka1+ERLv4reTmcNxcuC
vy3l0qdI2hlr66sT02ot0ZV7qqrInruzrVZLGSZ37JjqgYTG0K5lbaFVhDT1Ub456RPweY4hixWi
eSdpjvD1eWejz3FNHWYtkpvFo9EIseb3tS3SerOms22rfpPqZKzvvHSYUz70TExG6Gdbs2rljeJ/
Mx5L0vEzPaelnOi98c9J2bFNTFpit47+a+PVUvx9T9nOIfT+GV5p3yY/ds67wvsXqpxau+G09Lx+
r3TqrEAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADV4ljnLw3U0jvO
O0fs2lWqyUw6XLkyfYrWZkHldBEV09eveG3Fq1mI3jd4vPrOIaid8G9MP3Y38k6fNrt/rMk9Ou8s
tfXXn49rGWInuy8SO/k5Gl1E3rG/fzbOe94wTy99mbRvTrMOOvNfJWsesywniukrG/jU6fF43WYN
TmtEeJtEQ06aSmK2+bNtEd+qfSO17unF9Hmvy1y13XWyVmN4tExLxVK8PmNq5NrT58zawam+m/yc
0Xj8NpRYSvQZ7xEOdqI3rPozxayNRXe0ct/ON03jmrKB5nV4q1yTO20Obmv4c+cx8HoeI6WZpNoj
q83niYmYscU0r8aJ6T1n49zeJ+Meqm1drb9J+Kd5p136StGVem9l9TbHxLDFp7W7+sS+q1nesT6w
+PcAzVjiGHftzQ+v4f8AJpv6On8jH9ZgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAABp8VrW/C9TW0ztOO3b5Nxp8VmI4bn37TWYB8f1HFtTfUfR9FWJmsdZ9I7MtJxDX5s
d8ta1y0xzteaR2277rcuhycP12SceLxMeWNpjttHwlu8I0mfQ1y+D7k5YmJmY36T36Ka43z/AF1t
cI1ds+qxVj7/AEej19PCw9HJ4NoK4OIU5Y35YmZdzVTGebVZabx5jJS+Tmns81rNLm1Wrzc9rVw4
Yibbem72mXTTS0w0M3BvEta1bWrM95ie5EanY87wXgNOL6XPfxraXLhra/W28bR/dzYzarBqJxRe
bzE7Rt5vWU9n8mPHOGmS0Ypnea1naJb+k9ncNLR7u2y/WcxXO4TOoyUrN6zD0FaW5Y3hu49FiwUi
KxCvLMR0hlW0jn6ukWw3iXjOJzbDlneOj3GaN6zDzfFOH+LE7SRGo83XNSZ2lbG2/WfdlvaT2cy6
rNFInlrv1mfJ37cK4PwTTxOoidRm2+/2/KFuyMp47XB4LivXiunrH2b2iH2qn2K/J8x4fGDNxTSZ
9Nh8OviRvTyfT6xtWI+DeXs9MNZubypASqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAOZx6/LoOWPvWiHTcf2hiZ0e8fc2mf1E5+vP/AEeuSd7RC2uKtI6QjHfeINTfwtPf
Jvty9WPfbt/lucP03gxfJf7d/wBoReYpm97zaNeLb4Ims9Nt94auDjem1Wo5PFi1onylS+1o7l8V
bxvtupjDMdNkYtXS1+Stt+m63xImEJ4xjHER2ZxMUjeUTO3VRmydBbjLJqPi08mbeVOXJPq1sl5Q
Vbkz9+rRy35rxHqzmZlVEe/Ez5LRlW5iyfR6zffaIjq1OSNZps2a21rZInafSPJhxGMl9LStLRWM
lorM/A4dkrWbYfLZC2W/7K6eubX6b4RzT+W76K8b7G6X62cu3Sten59nsm3j+OXz3/0ANGIAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0OIYfpOHPijvNNo+fdvtXJO18k/
/OwPFYbz2ls3jx8VqW6xMdWPEdP9D4lkx/dt79flLLHbkxTPwY6nt2512ORTRzE2x4/dpE7cvkme
E4IrW3hRMxO8THRtU1FKWtvtvK2upx22rzRCtXkqzh2jtF7ZbT122b01ndnpuWuP3Z3+Ky20qDVv
fauzVy3mejZzNK8dVjqi87KLRLYtXruqvXzkQp7Qoid88R6rcl+WGlW0/Sa22mfhCZOq2x082ix6
jkm822pO8VrPdr4dNObVeDo8XW3uzMbzK+mvxT7szE27cvnu9j7PcNjSaXx8mOIzZevbrEeic5tN
+SZnpt8J4fHD9HXHO3PPW0x/DeBtJxx29vaAJQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAKNRim9Z5e89Nl4DzXtVh5babURHrSf7f3ec1+qnDorWrvvt5Pccb0n0zhmWk
Rvevv1+cPE2rGTFNZU26PFfxwa5dVkjelI2772nZnX6bbrEUq3o0d678u8wmuDL2ittvVjXdneeK
cGv4jpJ6U56+kS7+j118+GLXpakzHaWlp9NNY3tv+bbiYiNoQy1y30uyZJlrWmZnuym6q1iIJnop
yW2Te8bdWnnypQqzZOadokiIpSZntWN5lrxki19vNRxrUeBwnNNd+fJEY6/OejXLn3Xe/wDp9wyn
E8uo4lqqxblv7lJ26T6vpD5X7G8QycKzeBMbzMRM1/FH/wA/h9QwZ6ajDXLitvWzRgsAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAeL45w+dDrZvWv1OWd4+E+j2jX
12jx67TWw5Y6T2nzifU+rZ1y9eHwzDYxxEy18+DJodXfT5o96vafWPVbjyxDn1OOzHudbM0rt2UW
iI69mVtRXZq5tREb9VUoy2iIlRbJ0UX1VZ6btTLrI7V6yk62M2oisT1c7JmtkttVMUyZp6x0beDS
RWOvdKijDimvWd3G9pNRMfRcNfvZOb9Hpb0itJeP47k/3hgjaZnbaP1XxWW3T0movbNS0W645nbf
0nrMPpXs3xamoxdJiLbe/X1n8Uf3fKsOTw4jbaXo+EarJhtGTHMxeJ6xH7Sti9Zaj6x3HM4NxXFx
DS1mtoi8dJrv2l011QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AGjxLhODieOIye7kr9m8d4eM4to9RwjPXFa0ZIvG9bR0fQXmPbDFvTTZPOJmEWS/V8bs9R43NxLL
G8eFbePg1bajU5/s0l1ceKLx1hbjwRE9mOpx0y2uRTSZsm3PMw2aaKtIjo6kYo9EXpET0hVLXxYK
xC6MZvyx1lFs0RHfaPiCnU12pLyHGNDbUajBekWma2npWN3p8+opa20e9LSyZLxExTlpM+vdOdcZ
a9tPS8MyUvFrzWlI6727u1pYxYrbVmb7x+TQx6au3Nqcl7/0rcmW9axGnwZJj1novmxnZXV0fFp4
ZxLBPgTGK8xzXr5fOH0bFlpmxVyY7Rato3iYfNuG2x56Wrqa8s2jz+7Lu8O12bS6jkwzN6THNNI6
tvrN68Y4rxlx1vHa0bskAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAA4XtTTm0OKfTJ/aXdcL2pyRGjwU362yb7fkJz9eTxxyZJjyltRXzUZK7TFtl9Lbwy06YzrHwa+
fJFd/wCVt8m0bQ0eS2qzcm+1K/an+zNZFL5M1pjFXeI72ky48eGnPkvNp27+TPU6nHpMfLXaIjpE
erk5dRMxOfN1mPeisfshW1ne1a1577Y6x5R3U0zze31FOWI6ze0byU098kRlzbxM9qrMlPDpyRMR
Md5Vt/Ihp5898mWZm1pjftE91uCt7fCI7dWeHDEW3t723l6rslqxWZnasR+SYhFbzhnfxJ2jyeq9
lcGXWZcmW0zWKxHLaI7794eJx5fpfEKabT8t8l5isddo3l9S4VjrwrRUwzSJt3tav3pdOL6Y6dXD
j8HFWm+/KsU4NRXPvtWazHquWVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAa+fXYNP9u8b+kdZBsDkZOO135cWOZn4y5Wu4xqctbe9y19Kp4njt6vi+PDm8DFMWybbzPlV
5PiGtz67UxbNbeKTtWIjaIXYpnwuaftT5tXJT3vmi1pMsrU5qIrG1V1a+5DCa7b9GFbRr5J6Wnbt
Cu+Wmk0m8956z8ZWZNorbfzcbX5rZslazPux3hUt41NTntktObJ13+zX1bek01r4/HzVm0bxPXy/
+bNfDgjVa2uOY92kdfg6ufJOKvLXtttVVSqbcta2vM7zXtHpLQy5ZtMd+vWd+7Zy3mdJHXra3f0c
vUarw7zFY5rT2hH1Lavnrgx81p3U49Pk4nE5L35MO/StfNRXR5tXnrS8W67WvfyiPSPi7uLHFK1p
jrtSsbR5Lc4RzsXBaYreP4l45esRD2HD9fnw6evvWvO3Tfr0aGk0U55ra0TFInv6uzgrXFXlx0i0
77RPlC83Yj+JW7oddqr6vHzTTw9/f6dod+L1t9m0T8pcbFSmPHER3892W0zPuz+jSbVvidkcqmfP
Sel7bekrI4n4dZnPWIrHeYnZee2Wpy8dEaml4npNZblw5qzb8M9JbYgAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAABEzFYmZnaI7yCXL1XGa0jJXT0571nbee27DiXEprp8nhbxG20W8
5cbD0ikfnKO+urTPvjoZdXqctdsmTaPSvRpWmsdZ6yztfaGplvv3lWW1tyRlz1x0vkn7Vo5atTNe
Y0+1o79V2KsZsvX7Ne5mwxnyTNvsx2iGneM/rCdRSuOsTasTt5kRFtpjqmOH4t4nk7estiMNa97R
Hwhna0iuKTEdmGWa4672nZtRele1N59Zlq6vLOSsYorEc07qcW65euzRvtXvPZy52naZ7ujr6fXV
rWdukREK8+njHgmZmPc67bq6ivVWhxxgxZLztNrT1mZ/SP4VZs0zaOvfp84WUtNsXLvtv3699+rU
z7+Jtt5qURqMnPpctaR1rMSw4ZoK57eNk6xHaJRh97Ltt7lo5Z+L1HAPZvVauZ2nFTSzMTzeJEz8
to6xPfvsZntPZ9rXxabmxzefdrv0j1dXh/BcmstW1qxTHHasR3+b0GPhGl+kWmd64dNEVjf73T7X
y8vy+Ddx6O3iRakxTH5RXrMw1/lX+3Itw2MFIraN48qRHdZi0cUjmmPen9noox1iO0fNzdXEYrTt
stcmd9aX0bJ+HePmiKTitO8TMLZ1cVjrMfqpz6ys4pjfrPRWZ9rXXptUit6zO+23VyaRHEc05L1/
w9J9ys/en1ljqdVbwYw452tlnl3jyjzbmmiMeKtYjpEbLeTXPUU8ee/+qjJpsV5rbkrFqzE1tEbT
DpYNbW21Mnu29fKWna0KbqTdjXXjld0cvQ63ltGHNPSfs2n+HUbS9c2s2UASqAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAOVxPWe99HpP8ArmP4b+r1EabT3yT3iOkesvMVtN7za07zad5l
XV5GmM9vVfEstvDx0jtaVVMlq+UJ18b5cMRvPeSuK87bUt+i2Z3PtG7zXpjkzXt6R+TXyTMzvM7t
ydHqZ+zhv1+Cv/ZuqvPTHMfOYaTMil1a1K2vHSLTELq2v+KWzThGo84rH5rq8JzedqR+ZeI7WnOS
34pYTafWXR/2Pln/AMyrKOCWnvmiPyR6O1y9585lhWJvl557Q6eo4T4dYiMvW3b3UanhldHpJtGX
e09unmjsT7eb1l4trI2t0hsZfrdNO0bzy+nzU20/+NmkzO9esz+TZxWis9dttvPv+Tn21jjaW8zn
26bTG3mp1M/Wzv3t0jyWXiKZJmsTERaZhXXDbNl8WaztWenxZLstPp5pau8frDtVrNMM5cfTfpMf
3aunxxbes9d/R09Dp8ebJi09ptFr3jtt2WyrW9wy1Jx132mK+Xq9PotT0iIU19ntLtExa3T47T+q
6nBaYvsZstZ+cT/LeMnUi0TXffo1s2m8Ws2/OIMWk5Jib5L328rS2t94Sh5TV4ppklpW6PT6rh+P
NbebTHyas8E081mZy5P2W6OFhjxNTE/hr/LoRO0Kvo9dPqctKzMxEx1la5t3tdnjnMs4noievcrO
yZjeFF1OSnNV0OG62cn1GWffj7Mz5w05joovzY7xes7TE7w0xrjPeex6Ua+j1UarBFu1o6Wj0lsN
3JfQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACrU5o0+nvlt92P3BxuM6nxNRGCs+7Tv8
2hToxm1r3m9utrTvMsonqyt7XTmcja0u3O6FMfi5t/u0/lzdJM81p9O3zdvHTwsUR5+bfPqOfX1h
dqV+3O7bs1+T31oqmI3TEM4rvCdkDGIIhlFd2daboS0NXG2bD6bufxXU1vlmu/u4us/N0+L1tTSx
kr9qk7w89j1FNZMV3jxLzvaJ8mer+LSOZqK2xZotbvljfr/89U453rXt9lse081xZtNjx7TGKu0t
DHlrevSevaN5Y6+tJ8c7VRNMt63n3ub+6/R54rERMztDYy4a5omclYmfxKcenrjtHLvtPrCnVmdb
eFe3JXmjy6eS/DrMuLVYsta9Mdt++6qLxO+0dEc8UmInr18iUfReHcXrqccb9Z27Q61Lb13eJ9nc
1Z35rTvE9avY4bTkpG8xEfB05vYxqybc07R281naGMREdoT5JQqy9mply7Q3bV3iXG1eXw7TWSka
c258t7+tpT5/BjT7MfHqndz12Z+M4lMMKyziUJJiN1WSu9fku23RaOgKNJqbaTU1t9yelo+D0cTE
xEx1iXmM1Nt3W4PqvFweDaffx9vjDbGvxz+TP66QDRiAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAOJxzU73rp6z296zsZMkYsdr2naKxvLyObNOfNfJbvad1dXkaeOdpvsc2yuZVzfbfqybutwu
s5s8R92J3dvJb3tnO4HSMegtmt3nfZvYp8SZl0z45NfSK7onH1bNcfRFqnUKJr0Y7dVtq7prjEsK
0XVpEM6028mW20IHK41aPo3J6zs4ODhdcvPnvExFevNXpMOrxi/PlrTee7PLX6Pwa09uaNlKtHg9
dM3z5d7ReOu02nu0JzZMfblrv5R5uvrcdImZ26T1mYhxs1Os7RH93PZ7axuafNfLitvbaYU3yZYt
PXs9NwHhui1HBa5LVicsb81onrEuVqNNSuS8Y67dZ6xPZa59Il9uX41vEitImZme3q2Kxbxora0T
Md/ROSa4Ztkj7c9OafL5LuGYubmyX3iu/TfbdSfVnpvZLT/XZK233+Mbbva1xRXyiPk8pwbH4N6T
adq5a71n0tD1WDL4tPe6Xr0tDpz8YVnJHWEXYxbqlBedoef4tW0XraO09HdyztSZcbUz43C+ee9b
SVMaeOfqq7+jGckQ1Yz7+7v2RN/WXPXZPjci2+2yyJaVMuy+uSJlA2d+pNoVRbeDcSxyTE+TDDlt
pdRXLTynrHrDOyiyZeVFnY9TjvXJjres71tG8MnJ4Nqt4tp7T1jrV1nRL1x2cvABKAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAHJ49qfD09cNZ97JPX5PPw2uI6j6Vrsl/ux7tfk1mWr7dOM8iLdm
vfebREefRsWldw7SxqNbWbR7lPesrn3Vteo7dYjDpMGCvfbeXQ0uLlxRLRxROfUc34p6fCHYrXlr
EejqrjY8uzCYW7MZjdVKqK9VlaxCYrsnYExBMRMJRPZA8/xPHtmpP9W2xx76vhWOInvt/C7ike7N
vwzE9kcapGfhlevTaFbFo8RqJ5vy8/RoW09ek0msxHfp3dzNoLzp4zUmZpMbT8HJyYJi20X2n0lh
ZY1li/RaidBF4w2mK3jrHaFGp1lN+tptPp5IjBkid5mIp16TKu0abBPv33vPlM7z+iPdFNcWXU5I
tkrNce/b1W5db1nTaf3ax9q0fxDW1ebNk2phty1mOu09VOm8W19orEz23j1TwfSeERFuEYMddptW
d43dvBn21eKJ75KbW+cf/JcTgMxXTb3nbljz+TpcPmc2uyZO1KRtVtGVdi0bx07qJnllsRO6rNTe
N4XVamsy8mnvPwc3R2jPwe8TPbdlxXNOPSZfhWWpwO85OFzv57qrODkzeHntSe8Sn6Rv0a3EZ218
8nXekfr1a0ZLVnqx19dWb6demXybOO7lYMvNMdW9S/VVLo0us7tPHdtUtEwJiZU3jq2Jhham8CVG
PNODNTJXvWd3qcWSubFXJWd4tG8PK3pPd1OB6veLaa89Y61/u2xfxh5c/rsgNHOAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAANLimq+i6O0xPv392rdeZ4rq/pOqnlnelOkIt5F8Z7Wj27I2I6sb25YY
V1ImY3dbQ08LRc23vZp2j5OJG+XJWle9p2h6HHtbJXFT7OOIpX+7TxT31j5rycdTh+Dpz+XaG/sw
w18PHWseULN2trBE9UcrJKBhFU7JAQi0dEomegNDUYovM7x3jb5tO1ZvpbaTLtzRExWfWPJ08kbT
Ex5NXWYYyV5omYtHWJieyeDzuizfRs19Jn6TM7Ru1uMcJxZqTkw+5f4ebqa7SV1MR4tdrx2vEfy1
axqsNOTLjnLXytVXi3Xj8+nmsxTLM16d5npPyUzpekTtSK+U7vS6vQ/SYmK1vWPS1HOn2dvvvvE/
tDO5XlcO+LbfHSd/W3o6/BdDOXPTnj3Kz38rS6Wm4FNrRyRzTH3p6RH/AKvR8L4dXSzE3jmtHn5I
mbfqLV+m4dbLSsZInHjr3iI6zLpYaxS01rHuxHRHiT9mv6s67Vj1aqL6326MrWiYa+/Q54BxPaGe
XRZpj8MquB4+Xg8zPnB7SX30to379GxpK1xcHiKz5IS8xr8PLPixH2bftLTy05o6dHYyVjLhy0t1
izjZa3pMVv3iO/qz1G2L+NbSajbNyW7xLsY8kTDz+fJXFqKZN4iZnafi6WHL0iYlStI7OO+7axW2
crFl7dW9jvE9ULN+J3ZbdFGOy+AYWpEqN7afNXLj+1Wd23KrJVMvCzseh0+auow1yU7WhY4fCdV4
OadPefcvPuz6S7jol649Tl4AJVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAV581NPhtkvO0R+4NPi2
r8DB4dJ9+/7Q83Po2NTqLanNbLfvPaPSFDHV66sZ5ET0hRknyW2lTtMyouz0c8usx2n7s7vScKwx
zc1vu/y85p+maJh6Th+SOWeveXR4/wDLm8v+nX5mUWa9bbrInolmu5jdTNkxYFk2Isr3TuCzeGMz
+THdEyDDJO9Ja823rt2XWnya946pGvktDXta0ztWu/ybvLE9dkcoOf4GbJPWK1j49VmLh9JtE33v
Mevb9G7WsW8l1ccREISophiJ2jpDYpijbaOjOuOJ8ujOdqxsgVcsUjaETYvbaFFrgu5lVsm0yUtu
ryg43H5m+GIj1XcJzePoL4pnrWGtxmfchr8JvfHS1622if3QljzTTLes+qrNjrkiYtCzPMxnm095
YZJ6boS5teB49Tqscza97VtvWvlv8V/FOF34RrIxTM2xXjelp/eHoeA6XnzReY3ivX/0dfivDcfE
9HbDbaLx1pb0lOs+jO7K8Lis3cN+0NKcd9PmthzV5clJ2mF9J9GHHVL108dm1SznYr/Ft0tuhLb8
mNohFbMhLWy0mJ3rPXvDvcO1karBG8/WV6Wj+7kWrvDDBlvpdRGSnbzj1hpjX4z8mOx6UYYstc2O
uSk71tG7Ns5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACZ2jeXneJ62dVl5KT9VTt8Z9W9xbWclPo+O
fft9qfSHEU1pv48ftYST23ZTDC/p0YtlVuvVjMbM5+LCZjYGWGdrTPxiHY4ffaf3cjTxz1v6xMS6
Olty2iXVj/Dk8n+ndrkhnGRo1v8AFdW3RCrZ5uiYsqrboncSu508yjmZRYQt50TfowYTbYGVrKrT
uTZjvukQnYhMIGVY2ZxPVWyrHVCWzXpVXkt3TE7Va+W4K7X3jv1auTNy3jdba0RZpamfroQN7Hk3
6wr1GTaN2OOJiu6Mu98NvgDi8Wy74d/yZ8PiPAiO2zU4nb6qIn1bugjfFE/ASp1ke9u15mbbRDZ1
Mb823kx0Ontn1OOkedoJCvT8I03gaKsz9q/WW+isRWsVjtHRKyrhe0XCfpWL6Vgr9fjjrEfeh5fF
feH0V5Dj3DPoOo+k4a/U5J6xH3ZZ7z3228evytOk7NvFbo0cdols47bSybt7HbddHVqUs2aW3Qnq
xVeu8LILR3SlZw3V/R8nhXn6u0/pLuPMXjeHT4Zruf6jLPvR9mZ8/g1xrvpz+TH7HUAaMAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAABRq9VXSYJyW79qx6yvmdo3l5viGs+maqYrO+OnSvx+KLeLZz2te1rZL2v
ed7WneZYWnZl5K72YV1xEyxmeqJljzIEWlVkszvbZp5soN3h2SJz3pP3odCnuWmPRxuERfJrZmtZ
mtY96fR28kbX3dXj/wAuTyf6bmK+9YX1s0cNtm3Sd4LFY2K23W1s16StiUJW7bp22RW3RluBuruz
mWEgrmCGWyNkoExKE1QlPmsqRDKeyBjaejWy2W3ttDUyz1QKslvehVqKTNosyyTvELabXptIJpaP
B39Ia2mz+JGpr51jdZefDx2hzuHZObNq58poJaGtjxJ2+LoaKP8ADRPo5+T3skx5OhpOmC0fBNQ0
5yTbn+bt8A0u9raiY6RHLVwY62mI6zMvaaHBGn0mPHt1iN5+aYVsACBXqMFNTgviyxvW0bSsAeE1
mkvw7V2w5Ote9besJx2er4rw2nEdNNekZa9aW9JeQjnxZLYskTW9Z2mJY7zz26fHrrdpbZsY7NGt
mxjvso1b9NmUwpx33XRO4K7VUTE1nmrvEx1bVo2VWiJE/XY4frY1WPlt0y17x6/FuPM0m+HJGTHO
1qu9pNVXVYt46Xj7VfRtnXXL5MfzexsALsgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHM4jxOMFJphmJv529Dq
ZLfjDjPEIx450+K3v2+1MeUOHSOWFc3nJkmZnf4yujpVlqunOeFpV2nctLCZUXRM7MJtsWlRkv3Q
ky5NmpWt9RnrixVm17TtEQnJabXisRMzPSIew9n+CRoccajURvqLx5/chfOest642OGcIpoOG2w7
ROW9d72+LQvXevyejcPUU5M+SvpLeOataraw2a0dLbLqTtK1G3Es4lVWWUSoldFtmcXUbpidgXzK
GEW3TuCUSncnsDFMMLSms9EC6J6FpVzbZE5ALy0809ZbFr9GtfrEoFMzuuwz0Ueey3HbaBLDXe7i
tMOfwWnP9I+NZbuttvhs1uBRtXPb4SDm3iIvf57N7Dbl0VrS5+XrltEd+Z1Jx7cNms9N4TURRw3T
+PrcO3WszEvZOD7P6aYiMlvu16S7y1QAIAABxOPcLnUY/pWCv1tI96I+9DtgmXl68Biy7/NtUu3+
O8HnFa2s0tfd75KR5fFyMWTdhrPHVnX9R0cd21S3Rzsdm1iuqs256wrmGcT0RYSx5d047X02SMmO
esd49YRE9WcdSXhZ2O1p89NRji9J+cei1xMc3wXi+KZj1j1dTTaqmor06WjvWW+ddcu8XK8BZmAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAMMmWmKu952UZ9XFZmuP3revlDTtzWnmvO8q3XGmfHb9ZanV3yxtWeWn7y4es
vPNtDqZJ6Ts5mppvdl/XXRMyfGvSNlu/RVvtOzLfoipLT1VTKbSpvfogRkvtDVyZOhkyvQcA4Dzz
XV6yvTvTHMfvK+c9U3rkW+zvA/D21urr789cdZ8vi9KDb45rejl8Rry6iJ/FV1HP4vXbBTJEfYt1
+UpiHM295bXsqrO9l8QkZ0lZEqqLeyBZHZLGvZkhIndADKJ3TMoqWQMZ6pjsxll2jsCLSrmU2lFY
36gieyu0LJk3jbsga0wdqzK20QpyztQGprL/AFMrOE05NLkt6qdVWZxNrSe5o9vWBLiUjnzXn0vL
q555dHt8HOwV928/1z/LpzXxbYccRvzTB+jucOwxh0dI22mY3ltIrHLWIjyjZKyoAAAAACJiJjaY
3iXleM8InR5J1GniZw2n3oj7s/8Ao9Wi9a3rNbRE1mNpifNFnVs65XhcWTdt47bnFuF24dm8TFEz
p7T0/pn0a+HJux1OOrOux08d1ndqY7tillVkzExLOk7yd4YxGwluViJhE45raL0na0dtlWO0+bZr
1TKi+2zptZGTamT3b/tLacvJjiY3XaTWdYxZZ6/dtPm1zrv1z78fPcbwC7EAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABhkyV
xUm152iAZWtFazNp2iGhm1Vss8uP3aevnKrNntqLdelI7VRHRnrX/HRjx/tZREVjZXeybW6KbWZt
pCZ6S08tN7Nmbb7zCrJtyoS5145bSx5mWafelr3tsKmS/o08uXyhlly7RPV2+AcBnPNdZrK+53pS
fP4ytnPVda4y4BwHxOXV6uvu96Unz+MvVxG0bQRG0bR2G0nHLb2gCUDX12LxtFmpHeazt82wT1gH
mMN4tWs+rcr2aEV8DU5sM/cvO3yb+O0csLUTSdrLphRE8tlkZI7Atr2ZMazDJVKTYSCawi7Ksq7z
1QERvLK3ZGPrKbyCrbdnMcsbeaa18/RhvvM7oGEwTG0JmYYTIML22a2e28xELM19oURPNO4lOem+
n3ZY5+prVnMc2GYU4/L4A0a15cNf6rz/AC6fC6+NxCPOuOu/5tHJTbHj+F5/l1+BYumXJMd9o3/d
MRXYASgAAAAAAABhlxUz4rY8lYtS0bTEvH8R4ffhmo6bzhtPu29Pg9mq1Gnx6rDbFmrzVsizq2df
zXkMWTeIbNL7tbXaHLwzUctvexWn3bmPL8WFnHVL326VZ91MfFVjvvVlz79kLrcf2m7j7bNHH3bl
J2SirLQoy4t1++7G0dBC/RanxI8PJPv18/WG241+alovSdrV6w6mDNGfFF4/OPSW2b1zeTPL1aAs
zAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAVZ9RXBTe3WZ7R6iZOpzZq4ac1p+UermZMl89+a/byj0Ra9815ted59PQ32hlrXXRjH
DpCLX6ML5NlNsm/ZRqstfdXzbsZt06sLZNvNB1Za8RDWyZdo7q8udq5Mu/mIMt4md2lmy7JzZuWJ
dHgfBL8RvGo1MTXTxPSPx/8AstJ1XWpIs4BwSdbeNVqq/URPu0n73/s9hEREbRG0QUpWlYrWIisR
tER5JbSccur2gCUAAAAPM8Sry8Uyz67fwuxbzVPGsE49XGbvF42V4M0TEL33ERnktsxpk3sumK2j
admFdPFZ33VS2Mdui2J3UU6LYlFSsN2O5NkCyJ6K7T1TEsbAsxdpReerKkTFGMxvYEz0rsqtbbpC
b2VT1QEzuwtbaGUxspuJU3neWdKoiu8rq12gCI92YatLcublnzbEz1aOptyZqTuDHLfxN6R0+t5X
qdJhjBp6UiPLeXl9NSMnEKxHa1+bb8nrlvxUAAAAAAAAAAABTqtNj1eC2LLXeto/R43VabJw/VTh
ydY+7b1h7ho8V4dXiGlmvbJXrS3xRZ1fGv5rzeHN02bEW3cys3xZJx5ImtqztMS3MeTeGFjqlb2O
8btql3NpbZtYsnSBLeiWfdTjtutid+ghherHS5p0+f3vsX6T8Fkw181d4lMvEWdnHaGnw/UeNh5L
T7+PpPxbjdyWcvAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAo1Oprgr63ntAmTqdRqK4K9etp7Q5d7Wy2m953lNrWyWm953mVd77R0
Za1104xxlN9lV8qnJl2a9s3xUXX2ybsJyRDWtl3YWydEC+2VRkzeW6q+T4tbJm+KRdfK1cmWZnlr
vNp7RC/R6HU8SycmCk7ed57Q9ZwvgOn4fEXtHi5/O9o7fJaZ6z1uRyOEezVstq6jiEbV71xevzer
rWtKxWsRFY6REeSRrJxz22gCUAAAAAANbX6aNVpL0npMRvWfSXlKamsRMVvXm+EvZXjmpaPWHzfL
oNRjzXicfWJ8phfPxFejx72x7xMzK+sXiNoiXlq+Pi6fWV/VfTNqfLJl/WTg9Pji8R70LqvMV1Gq
j/zcv6yz+lanzzZP1lWpelTET6S81Gp1P/Gyf90s412rjtnyfqql6asREdWM9+jz9eJ6yP8Az7uh
odZqMt458tpB1JvEViI3/RhzRt13/R1MNaziiZiJn5K9ZNceKZiIiQcu/WekT+iYrWI3lzdTrs+8
8uW0fJzcur1Np/zsn6g79phVaIeetqNR/wAXJ/3SwnUaj/i5P+6UD0ldonum161h5mNRqP8Ai5P1
lNtRqJjacuT9Qd22WN5aGeZyZd/KHJy59RHbLf8AVq31Gp/4uT9ZEvS8Lr/vSs2npzRtL1z53wK+
oza/HW2XJNd99pmX0Rb8VAAAAAAAAAAAAAAcHj/C5yV+l4I9+v24jzj1cLFk8nu5jeNpeW41wmdL
knU6ev1Vp96sfdn/ANFdTrXG+eq1q5F2LLtbZoY8m8d11bbSydErsYsm+zZrO/zcnBm226uhiyRK
EtrvCrJDOJTeu8A1MWX6Lqq5N/dnpb5O5ExMbx2cPNTeJb/DM/iYPDtPvY+nzhri/jDy5/W6AuwA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAa2p1UYo5adbz+xbxMlvqJ1OqjDHLXree0ejmzNrWm953tPmTPWbWneZ7yoy5YhjrXXTjH8s75N
mtkyxt0VZM2/m175N1V03yTKubMLXVXybeYLLX2VXy7eam+b0bOg4VquJW+rry4/O9uyZOq3UjVm
9r25axMzPaIdvhns1kzbZddM0p5Y47z8/R2+HcF03Doi1a8+Xzvbv+TotJnjDXkt+K8ODHp8cY8N
IpSO0RCwF2YAAAAAAAAACvUZYw6fJkntWN3k8dfHz2vLucdz8mkjFE9bz1+UOZosX1UzPm0nqI/W
MYo9FlcPNklfFGeH/NshLGun+Cz6PtHZtVZWlRLS+jxPkRpIn7rdoupHTdA5s6SI+7H6Mfo+32Y2
+To3neSIiZ7A0IjPXpXLePlMotGW3272t85datKzHZjbTVnsDj+FG/2Y/RlGP4R+jo20u7H6N1Ql
o+H8I/REY957R+jpfReiK6eOYHLtj2tttH6KrY/6Y/R2c+kjeJiFVtLG24hxpw7/AHY/RRkw9O37
O99Hrt1YX0tfOBLjcGp4XF8c+u8fs9c4dcVcGemSI61nd3IneN1orQAAAAAAAAAAAAABFqxes1tE
TE9JiUgPKcX4RbRXnNgiZwWnrH4XPi28PdXpW9JraImsxtMS8pxXhF9DecuGJtgmf+1TWW2N/la1
L7N7T5e3Vy6W3hsYcvLbqzbO9jvvCzvDR0+XeO7crO6FmGSvRThy/RtVXJ92elvk2rRvDUzU7pl4
izsd2J3jeBpcNz+Lg5LT7+Pp+Xk3W7js5eAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADs0NTrN96Yp6edkW8Wzm6+LNTq4pvTHO9vOfRoWtt
1mes95YWvs1s2fZldddOczLPLn2ju0MmebT3YZc2/mpm3qqllN1drsbZIhr3yzvtHf4AsvlYYseb
V5Yx4KTe0+UQ6nDvZ3UazbJqd8OKeu33peq0eh0+hxcmnxxWPOfOfm0mP+steT/ji8N9mKY9suum
L37+HHaPm9DSlaVitKxWsdohI0Y22gAgAAAAAAAAAABXnyRhw3yT92Nwef4xm8bVzET0rPJH5d12
CvLhho3rN9RWs9Z23n5y6O21YhrVYbdGOCfrrLPJRpv863zVS6FS09SvZj3lVZZRdPSqmnSWdrIE
ebOkK4ldTsgW1WKqd1oMZhEVZyRAImOjGI6rJ7IiATNd46qL02bHkiaxaoNGY2n4ImPgtyV2n0Vo
Gvlx7x2beiyTk08RPevSVUxux00+Fn2n7N+n5rRFb4AAAAAAAAAAAAAAACLVres1tETWekxKQHlu
L8InR2nPp43wz3j8P/s5dLveWrFqzW0bxPeJeV4xwmdFec+CJnDM9Y/CrY1xv8qvTZ+WYdbDk5oh
5zHk283U0eo3jaZZ2N5XYjrCnLSJhOK+8d1kxvCqzSwZvousrb7k9LfJ3nB1OLeJdLhufx9LEWn3
6e7LXN9Ofy5/W4AuxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAETaKxMzO0Qi9646Ta07RDmZ9VbPbaOlI7Qi3i+c3TPUaqcu9adKfy0722ZXvFa9
XO1OrjrESxt66ZJmcjPUanlidmhkzTZVfLN5VWvsC2b7R3U3yqrZZtO1esz2h2+F+zWTUcuXXTNM
feKR3n5+iZLVbqRzNJo9TxHLyaekz62ntD1fDOA6fQbZL7Zc/wCKY6R8odLBgxabFGPDSKUjyiFj
SZkYa3aALKAAAAAAAAAAAAAADQ4pl2pTFH3p3n5Q33E12Tn1eSfKscsLZ+orS00eJqbW+Lfnu1tF
XaJnZsz3WpCfsyp00fWSvmPdVYOmSUDd8kR3InoQosy7JmUX7MdwZ17ro7KKT1XRPRAsrO0rYndr
79V1ZBaQiJ6JgCSIJASwrO07MpV2nqBlrv1a1o2bf2qtfLXaQUTO0sb05o3jv3ZXhjS20xEphW5h
yeJjjf7UdJWNKLziyRePsz0lux1SgAQAAAAAAAAAAAAAADG9K5KTS8Rato2mJZAPIcU4ZbQZuekT
OC3afT4NXFkmlntc2GmoxWx5K71tG0vHa/RX0GpmlutJ61t6wrY2xr8dXS5uesN+tt4ef0eaa223
2dnHk3juyreM81OaFGiy/RtZET9jJ7s/2bdutd2jqKeic3iNTsd8a2h1H0jTVtP2o6W+bZbOO+gA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABje9cdJt
adohGTLXFTmvO0fy52bJfU23t0pHaqLeL5xdK9Rnvqb+cUjtCi94xxvK3JetKuHrdZvaa1ljb10y
cnIs1Wt3naJc++TmVWvMz1YWybfMGdsm3eWek0mo4jm8PT0mfW3lDf4V7P5tdMZdRviwfvZ6/TaX
DpMMYsFIpWPTzXmf+steT8jn8L4Dp+HxF77Zc/4pjpHydYGjC3oAAAAAAAAAAAAAAAAADG9opS1p
7RG7zszN6WtPe0zLua+3Joss/wBOzhzG2OsL5+IrY09dsSyYRijbHEMvOChb7KjF0yS2LQ169Mso
S24noyrPVXWejNVKbTuw3T3REdQWU6LYlVvsyiUDPfqupPRr79VuOQX1lZEqoZxIMksd0gT2VT0l
bPZVbuCaW8i8bwr32WxbcGnkjaZa9p2ndv5qbw5+aNugLItF6TEtvTX5sMb969HMpfazc0d9stqe
vVZDdAQAAAAAAAAAAAAAAAADV1+iprtPOO/2u9bektoB4TJTJpNRbHkja1Z6uto8viVht+0HDvpG
H6Tjj6zHHvbecONw7Ltfkmeqmo6Ma69DXbbZTkr1mGWO3RneOaGbZRoM30fVzSelMnT83aef1FZ7
x3h1tBqfpGnjmn369LNc3sc3kzy9bQCzIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAa+q1dNNXr7157VhGp1Xh70x+9f9ocy283m1p5rz3mVbrjXHjt91lz
5c9+fJ1nyjyhdM8lZlOOIiqrUXikd+kMreunnI5XEdX4dZiZcG+XmtNl/F83PeeWWHDOGanieSKY
q+5H2rz2hMzWd1Iqx1yajJXHhrNrW6REeb1nCPZumn2z62Ivl7xTyr/6uhwzhGn4Zj2xxzZJ+1kn
vLoNJnjHW7TbbsAszAAAAAAAAAAAAAAAAAAAAaPFrbaSK/itEOXt0rDf4xb/ACa/GZacRvaF58Q2
IjasQnzPIhCU92tMbZGzHmotG10C6nZkwpPRmipIllEbMIZIE7solgmJBnCyk9VMM6z1BtVllEqK
z0WRILYlluriWcSDJVbusV27gwInaSWM9ECyZ3hqamnSWxFmOSOaqRx725bNnSZNs9J+OynVY+WZ
YYr7TE+nVaIr0Ais81Yn1hKAAAAAAAAAAAAAAAAAABExvG09peU4nov9n66L0j6q/WPg9Y1OJaON
ZpL0+9HWs/EWzeVz9PbmrEtnyc3h9reHy26TWdnSr2YX6657ijLXpLX0+onSamL/AHJ6W+Tbv2aW
ekTv16JzeI1Ox6KJiYiY7Slz+E6jxdN4dp3vj6fl5Og2clnKACAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACZ2jeQRMxEbzO0Q08uqtkma4ulfO3r8lefUePMxWf
cjy9WvlzVxV6T1Z61/x0Y8f7Wc7Ur1lqVy+LqOWJ2hp6rXddon5rOF1tfmz5OkT0qzb8dWbxjp1c
biuuilJ5Z6r+IcQrixzEy8zl1E6rNt1tMztFY81sztU1eRucN4ffi2p5esRM72n0h7rS6XFo8FcO
CkVpX082nwXh3+z9FWLxHi36328vg6TZyW9ABAAAAAAAAAAAAAAAAAAAAAADj8Unm1tK/hqppHvw
y1k8/EMk+m0GOPeafiFpCZYwolnXspvHvLa9mF46gmnZmwozRUiUCBKYYsoBLOFbKAX0llEqqyzi
QXRLOJVRLOOwLIljZMEgrlhKyYYTAK5nZPN0RZjugUanHzVlz6xtLq361c+9eXItPpXX0dubTU+E
bL2lw2++O1fSW6m/VYAISAAAAAAAAAAAAAAAAAp1GbwcfTreelYEydcuMcRrM/L9nnlsV6wqpi2r
tv133mfWVkRyRtEdGFva7MzkYZNoamWN4bV4mYa9qztKIujhVppxGI8r1mJegeZpknBqKZY+7L0t
LRekWrO8TG8Ns/HJ5ZypAWZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAADS12fp4VJ6z9qVuq1HgUiI+3bpDl589cOKZmevqprXPTbx477rDJlrhr1nq4+s182tMRP
RqaziXiZJrWekNG17ZbxWJ336M5LXRbI3dLTJrs07RMY6fan1dHLrowY+X7MVjt6N3R6Kul0EbWm
s7bz8Z+LnabQX43r7Y53php/mXj+Dnv0f1JO1x/8ZxbUzj02O15mfLtD13AvZqnDds+pmMmo26el
XX0Wh0/D8EYtNjilY7+s/NstpOOTW7QBKgAAAAAAAAAAAAAAAAAAAAAADG88tLW9I3BwJtz6nNf1
vK/DHVqYJ3pzT5y3MPZeojOWMQylEKpTVjZnDCwkqzYQyRRICATCITAJZQxhMAshnEq4ZQC2srKq
qrIBZCWNZZgwswmFloVyCu0dFcx1WyrtCBhv5NTPHXds2U5o3hIz4ffbPt+KHUcTSW5c9Jme0u2v
VYAKpAAAAAAAAAAAAAAAAYZctcVOa35R6tLrltN795/YvknNqrfhpPLH92V5isd9mWq6fHjk6rn0
ZxG8KK5Jm/wbVZiYZtqrmkqL023bkxvCiY3lJHNyRG81mHS4Rn5sNsNp64+3yaWaNrzOzHBl+i6q
mT7s9J+S+ay8mex6EIneN47SNXKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAImYiJme0JafEs3h6fkidrZOn5eaLeJk7eOdm1Hi2vmtPTry/CHmOJcUvmvOPF1n09Pm
6HF9ZGm01qxO3R5vSY7XwzmzTy47zzTEd7en5Mfvt2/PURWdo3tvPrPlKymbktFqTtMTvHzbOLDG
f63JXbFX7FdnoODcDprZpq9TjiMMTvSn4vj8l5fxnrk91saPSa7i2hpOfbTVt5x1m0fLydzR6PDo
dPGHBXasd585n1lsRERG0dIF5OOe6tAEqgAAAAAAAAAAAAAAAAAAAAAAADX11+TRZrf0y2Gjxe22
gtH4piP3TPpXKwxtjhuYo9xq442iIblI2pC1RET2ILd9kxCqRjZmwlCSEohIJAQAAJZISDKGUd2M
MoBnVbVVCyAWVWeSuqyOwIlXZZKue4MJV2WWYT2QKbKL9YlfdRdIo35b7/Hd3KTzUrPrDh27uxpb
c2mpPwX/ABX9XAKpAAAAAAAAAAAAAACekTIp1eTwtJmv+GkyJn1oafeazbfpMzLR4jq/o8b823zX
6XNF8ERCvTcNpxLV5LauvPhx9Irv3lhztdtv8TtaWLicXrt03jzjzb2k1nid56ty3s/w+a7Uwzjn
1raejlarhmbhl/FpbxMO/fzj5p/ixSeXOvTtRfeI280ZI26tfDm3pWe63LaZx7qtGvniJ6tPLvOK
fOa9WzbJvTbza02jl3n5SSljscK1MajSxWZ96nSW88xw/VfQ9XMT9nfa3yemid43jtLeXsce88qQ
EqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADia3UTm1l4j7OP3Y/u
7Vp2rM+kPJW1PhYcmS0+9MzKm/jbwz31weMzbV8UppazPL9q0/BF4rk1GLDSNqxPWPhCnHmnNrtT
qPKteWPm6U6OdHaZvO+SaRNvhv12Ub/q3FhtrNVj0uKOt56z6R5y9zix1w4qY6RtWsREOJ7L6OKa
S2rvX6zNM7T6Vh3mmZyOfya7eACzIAAAAAAAAAAAAAAAAAAAAAAAAAAczjVvqMVfW/8AZ03I41bf
Lp6/OVs/UVrY47NyOzUxd4bUJpEbb3Z7IiOrKIVSjZhMLJYyhKIgmGUQSDESIEbJEgQmCITEAmGU
IiGUAyhZVhDOoM4Wx2VQtqBKuyyWEgqlhKyyuyBVaGtkbNmvk7A15l1eH2300R6TMORPSXT4ZO+O
8fFefEX63gEAAAAAAAAAAAAAAAq1WPxdLlp+Kkx+y1Fvsz8gjhaDauGK8sx07y3OE3m1tT6RaP4c
vU6yMNKUx73zT0ilY3l2eF6a+m0kRl/zbzz3+Ez5M8z26fJruW6wzYq5sV8d43raNpZjRzPPaTmx
5b6bJ9rHO3zb2WJ8GWPEscY9bgzxH2t62n19GWW0eHOzHU5XbjXZ1x8WTnz2iZ7S2M1IjH2+LX0V
KTqs8zO9ot0j8nUthi1J3UaOFMTfLFo6xMbS9BwHWTqdHOO8+/hnln5eTjYMFo1WTH5VnePzXcIm
2k4zlpPSmXy/hfF5eMfJns69OA2cgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAADG/2LfJ874rW845mubliY7bPoto5qzHrDz0+yePNF41OotaJ7RWNtpV1OtfHqZ715fhu
j8adNpcVfeyzE2/vLuanhOu1nEctIxTTFa/+ZPbZ3eHcF0vDbTfFE2yzG03t32+DokynXl9+leDB
TTYKYccbUpWIhYCzEAAAAAAAAAAAAAAAAAAAAAAAAAAAAcXjE/4zDH9M/wAu04XF5/3jj/0f3Wz9
RUYmzDWxS2I7FSyjuzY1ZKpRKEygEwiWUIkGIk2QJNhKQhMIhkCYZQxhlAMoZwwZwgWQshVCyATL
CWc9ldpBhZXLOVdpQK7NfJPRdaWvknoDVvPvOnwuel4+TlXn3nS4VPvXj4QtEV0wAAAAAAAAAAAA
AAAAAVV02CmTxK4qRf8AFFeq0AAAanEsfPpZmO9Ji0NDLfkwdOsulrumiyzHlVzJrz4Ovoy26vB8
cTBa9NffLtMY77Rv8Yegx5ImkKdJoY1HC81Y+3OSbVn0mGGkmbY45u6tnrrTOu2xGO0RxCd+nNVj
qKxTV1vH2pjaGtnyzXXYdo96ZmGXEMk15b7/AGZiVerWPTYckZcNbx5wzc7hGbnxXxzPWk7x8pdF
0S9jh1OXgAlUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAcPjEf4/FP9H93ccXjMf4vDP9Mx+62fqKrx+S+GvibEFSsqyYwlVK
ZYsmIMoRKYJQIPIEiQ2ATCUQygCGUIhMAyhnDCGUIFkLIV1ZxIMpVWWSrsCuyqyyyq09ECq8tfJK
66jJ2Bp5J6upwn7dv9Lk5J951uE/av8AJaIrqAAAAAAAAAAAAAAAAAAAAAAq1Mc2myxPnWf4cmtu
XT9fR0tffk0WSe28bfq5Wbamm3326MtunwfK6PCv/AxPraZ/dz9PO97/AOqf5dHhdZrw7Dv3mOb9
XOxRFM+avpe38mvkPHf/AFWlrKba7Tzt99ZxKkfR7euyNXMTrtPHfa0z+zPiM/UR8Zj+Wbdu8HpN
M2bfzrV13M4dO2pyR61dNvj44/J/oAWZgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADj8bj63BPzdhyeNx0wz8ZWz9RWri7Nmv
VrYu0NmqaRZHZlDGGSiwxZSgCEkCBCQSCQBMJRCYgEsoYx3Z17AlMIhlCBnDOGEM4AlhZZKq4KrK
7LLKrIFN2vdfZReAaObu6/CO9vk5OePR1uEd7fJeIrqAIAAAAAAAAAAAAAAAAAAAAGtxCk5NFliI
3mI32+XVyNTyZOHTee946PQKPoeDffw4777eW/yVs60xv+ZxOnr4Okx1t05KRv8Ao41Z5q3yed5m
XY1szXRZ5jvFJ/hxItP0aOSN9q7yrtr4f2tHFM5+KT16Yq/vK/iGSbXw4vO14UcPx5MGfNbPG18m
1oj4THRsTw7VanPXVYpi3gzMcnrvCnG11JOupwuN8+a3pEQ6jT4divjxWnJExa09pbjbM5HHu90A
JUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAHM41H1GOf6nTc/jEf4Ws+lls/UX45uGekNujTwdm5RNIthKIZKLDFlsiQIShIC
EgCUJ7AmGTGO7IDzZQhMSDJMMYZQgZwzhhDOATuqssmVdgVWVWWyqtCBTeVF19lF+wNLNG7q8I+9
8nLyupwnt+S8RXUAQAAAAAAAAAAAAAAAAAAAAAAItWL1mto3iY2lyrcLyUxzix2ia2nvPeK+jrCL
OrTVnxpanhuPPemSs8l6RtE7dJj0ldpNP9GwRSZ3neZmV4cR/Vs4AJQAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANHi1d9H
M+kt5ra+vPoskfDdOfqK4mn7Q3aNHBPZu0W0RdDOGFWcKLCJZeTGQQlCQSgASBsCYZQxhlAJTAmA
TsmAgGcM4YQyjsgRLC3VnaVcgwsrt3Z2V2QK7tbJ1bN5a9waeWO7p8Knt8nNyebpcK8vkvlFdQBA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAK9RXmwZI+ErEWjesx6wQeZwejeo0cccuW8
elpblJaaRGxVnCuss4ZrMvJEgCAASISCQIBlCYYpieoM0wx8k7gzIRueYM4Z79FcSy3QEsLJmWFp
BjaVVpZWlXMoGNmvkXXlr3kGtknu6XCf7OXkl1OEdl8orqgIAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAHmskcmtzV/rls0U62OXiWX4zErcc9GmkRfWVkSqqziWayxCPIANwBIhIJSxS
CRG6dwZwlhEs4BluMdzfqgZxLLdXuy3AmVdpZTKuZBjaVVpWWV2QlhZRdfZRcGpl7urwfrzfJy8r
rcH61vPyWitdMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHA4nHLxKZ9awnH2ZcY
jbW459aq8fZpfiI2IZwrqzhmsz3Ebm4JN0AMhCQSIASndiAziWUSriWcAyRujc80DM3RCfIETLCW
UsZEsJYSslXZAwlTddPZTkBp5e7r8Gj6rJPxhx8k9Xa4PG2C8/FaK10QAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAcfjcbZMFvnDWx9m5x2PqcNvS+zSxT7sNPxH62YZQwqzhRZO6UCB
KUAJTux3SDIRuAncQAmJZRLBMSgZ7iIAZRKd2DICUSlAljLCYWMLIFVukNfI2bNbIDTyT7zu8Ijb
Sz/qcG/2nf4T/wCE/wD2WnxWt4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHL9oL
+Hw2cm28VvEuPptfgyVj6yIn0no7/FtJfW8NzYMe3PaPd39d3iMug1WktNc2C9dvPbeP1aZ9xF+v
T471tHu2iflK2HkqWmvaZj5Surqc9Ps5bx+alTHqYHm68S1Vf/NmfnC2vGNTXvyT84Ql6A3cSvHM
sfaxVn5Ssrxyv3sM/lKB1xza8bwT3pePyWV4tpZ+/MfOEjfGrXiGlt2zV/PotrqcN/s5aT/+wLRj
FontMSlAlKEgndO6IAZQljDIEgeQljLCzOVdkCu/SGrkbF56NPNeKxMzMRHxENe0+89DwuNtHHzl
5PJr8NcnLW3Pbf7r1nCZm2gpae8zMrz4i/W6AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAETETG0xukB4HVaeMHEtRi26RedvkyjBSfX9W77QYvC4xz7dMlYlrU7M929dWJLFc6aPK0q
7YLxPS0S22FlP6q38Zac0yR92s/KVc3tHfFf8tpbcsLRvB/dR/8ALLVnU0r9uL1+dZI1mnmdvGpv
6TOy6ym+Oto2tWJ+cJ/tW+KLK5KW+zes/KU7tG+h01p64qx8Y6NXNo6Y+uPJlp8rLf0rfG7MXtHa
0x8pZxqs9e2a8f8A7Oj7HaTHn0+f6RWM23LETfr6vRW4PoL99NT8ui7F4+vEdXXtnt+fVbXjGsr/
AOZE/OsPS29nuH27YrV+VpeV9pdPXhOtw49NG9Mld55+vXcTPd42I47qo7xSfyWV9oM8d8VJ/VxM
d8l46xWF9cV7en6o/qLfxp2I9ob+eCv/AHMo9op89P8A/wBORGmyT5R+qfo2X8P7n9Q/jTsx7RR5
6ef+4/8AuHftg/8A6cWcOSO9J/WEbWr3pY7Efzp2Lcfv5YK/9zWy8d1E/ZpSv5Oba1/+Hb9lc+LP
bFt87I7E/wAabWbiurvEx4nL/pjZzc2bJkn372t85ZXx55/BX85lucC0vPxnTxlnnjm32mOiZqUu
LJ2p4TwnVavNWaYbRTfre0bQ99pcH0bT0xb78vmtiIiNojaErMwAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAHnfarF7umzRHaZrLjYrdIen9ocPi8JyTt1xzF4eUw23rCm3R4r6bMy
wt6kdTaWLdjswmNoZontsCm0K5XWjopnuDC0dGpqG5bs08/daKV672MjbSaif6oh6Z5f2LtvptRX
0tEvUN3Jfo8f7cYve0eX4zV7B5z20xc/C8eSPuZIRficfXlcPaG7ino08HWIbePpLF2NuiyOyrHK
3fZFSwuovHVfaVF4QK5YWTM9UT0EKry6Ps1Tn4zjn8NZn9nOtLseydObiWW34cf918fWfk+PYANn
KAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAq1WKM+ly4p+/WYeBxTNd6zG0xO0
vobw3FcP0bi2em20Tbmj5Srr418V9sa2Z7qKyzi07MXUylhaU7yjqhLCeiq3ddaFNxFYW7NLNG8t
zya+WO6Va9J7FW66mvwidnrXiPY3Ny8RyUn71Jj9Ht3RPjk19HK9pMHj8D1ER3rHN+jqqtTjjNps
uOe16zAifXzfTz7kNyndpYazS9qT0mszDdoxrsi6m8LazMq6zDOsq1ZEyrt1WWlXaUCqyq0rbKbi
Fdp6PReyFd8uqv8ACsfy83aXrPZHHto89/xX2/SP/dpj6y8vx6EBq5gAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAB5n2q03LfDqqx39y39npmlxbS/TOG5se29tuavzgWzeV4mtui2
O3RRSY2hdVhqO2MvI36iu9lUsrSrvDHn6spnmSiq5jooyV6tq1VV69RC32byTh43h8otMx+r6I+Z
aK/g8TwX7bXh9Mid4iW+fjl8n1ICWb57xLBOm4zqse20Tbmj8+qKdnS9q8PhcTw5tumSm0/OHMxz
0Za+uzx3sX1t0Zxurr1ZxvspWiZYWZbsbT0QK7KLrZVZJFaqt5vbezNOTg9J/FaZeJns93wCvLwb
T/GJn92uGHldIBowAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADuAPA67F9H4l
qMW20VvO3yRWW97T4fC4rXJHSMtI/WGhVlue3b473K2KzMML4+62tujG9pnozXaOSOVFMnVbmq1t
trJRW5E7wwvUxTvCyY6CHOt7moxz6Wh9PxTzYaT61h8x1MbZK/OH0zTf+Fxf6I/htj45vL9WgLMn
mvbPFvocGWO9L7fq85p5maw9d7VYvE4JkmPu2if3eW0+PasdFNOnxfF1Y2hlykRsmY+LJ0MZjZXa
eq2eyi8oQTO0KLdZWzPRjWu6VaqtHR73g0bcI0sf0Q8Nkq93wqNuFaWP+XDTDDytwBowAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAef9q8HNpcGaI60vtPyl56k9Iew49j8ThGe
PwxFv0l4zH2U26fDfTYiyJljvsjf4sm6vJ1hrXjq2MkqLdZEVbgbMx0auGdmzNt6iHN1Ub5af6of
TdPG2nxx6Vj+HzaaTm1+nx/iyVj930ysbViPRrj45vL9SAuyc7j1efguqj+jd4/T33rD3HEcPj8O
1GP8WOY/Z4TTT7sKadHhbcsZnaCJ3TPZk6VdrKbTutmP0U2nqgrGOsr8deiuI2X09EqKM1dt3uuG
f/jdN/06/wAPE546S9rwud+Gaaf+XH8NMMPK2wGjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAABrcRp4nDtRWPPHP8PCYusPoWSvNjtX1iYfPuWaXtX8MzCuvjfw32siu8ptXoxi
0wy5t4YulReqmazu2skbquURWFInddM7VYRGyL291KFnCcfj8e0le/Lbmn8n0N4b2Ur4nHLWmPsY
5e5a5+OXyXugBZmiY3iY9Xz7NjnTa3Ph/BeYj5PoTxftFg8Hjk2iOmWkW/Psrr418V5WrWd2faFc
V2jdnEMXWxntupmN7NiYU27iWML6dVMVnddjgVqMsdHr+CW5uE6f4Rt+7yuSsTDv+zWXn0WTHP3L
/tK+GHl+O0A1c4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8Dn93W56/wDM
t/L3z59qp24jn+OS38lnpr4r7ZxHQ2TEstt3PXUrt27K57rr1VT0BjKnJPRbMqMs7QlV2fYvHvrd
VknyrEfu9m8f7FZI8fVU85iJewbT45NfQBKo817W4eulzxHaZrL0rje09ItwqbfhtBVs3leai8RD
KLw1sduesL606dWFdsZT1jdhNeq6K9DlhCVUU6s4jZnt1YzAhnM71dH2bycmszY/K1d/0c6OzY4R
fwuK4p8rTstn6z8k7HrwGzkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHz3
Vxvr80/8y38voTwGpj/F5/8AqT/JfjTx/WVeyY6FPspc9dZPVXaOq2WEwIUTVRmjo2rNfLHRI3vZ
DJycXtX8dZh7t879nsnhcbwz23tt+r6I2nxyb+gCVBzuPY/E4PqI9K7ui19fTxNBnp60n+Aj5/pJ
3jZu1aOnnltMNussdfXbm+l3ZM9URHREdZVXTuT1Nk7boQiOkJw28PU47/htEp5eivJPLMTCZ9Vv
x7mJ3iJ9UqNHk8XR4b+tIXuhxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD
weqjbWZ4/wCZP8vePCaz/wDIaiP+Zb+UX408f0r9lOxWOifJhXWjfyYWllPRXYQxnrCrJHRd3YZI
6A1NJecHEsN/S0T+76bE7xE+r5dk93LW3pL6ZpMni6PDf8VIn9m2fjm8s9rgFmQxvHNS0esbMiew
PnHLyai9fS0w2aNfUTtrs3+uf5bGPqy068fF227KtSsdFlKqNGMV6myyY6sbdIQI8tlOWOi6Jhhk
j3RD0vA8nicMx9etZmHRcT2Zyb6XNT8N9/2dt0T449T2AJVAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAHhdfG3E9TH9cvdPEcXjk4zqI/q3L8aeP6xr2TsxpLOekMK6mFo6qpXSrm
OqBixvHSVmzC4OfqK7S9/wAByeLwbTW9K7fo8Fqo6Paeyl+fglI/Da0NcMPK7QC7AAB8313TiOf/
AKk/y2MHWrX4jG3E9R/1Lfyv0/aFNOrHxuU7LI7MMayGTVlHWUXhNe6Z6wIUsb9d1m20q7dkDpez
N9tRqKT5xEvRvKez9+Xis1/FSYerb5+OTyf6AFlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAB43j9eXjN/jWJ/Z7J5L2mry8Upb8VIF8f6aGOey2eynHvOy7bowrrYSxZSwQJ2YXZ
92N4BoanrEvVexmTm4blr+HJ/aHltRHSXofYm/1Wrp5RaJaYY+X49WA0c4AD51xONuKan/qW/lbp
+0MOLRtxbU/9SU4J7KadWPjep2WQrr2WRPRk1TvsndXMpiRCb9FNu0rbTuqvKBscCjfi9PhWZeue
V9n434rafTHL1TfPxy+T/QAszAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHmv
avHtfTZfnV6VxPajHzcNrf8ABeJFs/XnMcr4no18c+6vr2YadkY2YM57sEDLyY37Mo7MMnYGlqO0
vQ+xNfqNVb1tEfs87qZ2rL0/sVX/AHdnt65P7Q0wx8vx6UBo5wAHz/jUbcX1PT78qtO2vaCnJxjP
8Zif2amnnspp04+OjWejKJ6MKdmcMmyJn4m5ZHzEVPMwtJv0VZLbQDqezcb8RzT6Y/7vUPM+ytZt
n1OTyiIh6Ztn45N/6AFlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABocbxeLw
nUR5xXm/Rvq8+OMuDJjntaswEeBxT0bNZ6NatZpNqz3rO0rqsdO3PxlaWEMpY+aqWXkryT0ZT2V3
7A0dVPuy9f7G124NM/iyT/Z4zWT7sw957MYfB4Fp4/FE2/WWmGHldcBowAAeM9qKcvFeb8VIly9P
0nq7ntbTbVYL+tJj93CwT76unR4/jo0nozhhTsy3Y1sWljM9Ce7HyQIm3RRlttVbaWrnt0Sh6n2U
x8vD8mSfv3/h3XN4Bi8Lg2nj8Uc36y6TeOPXugCUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAPD8RxeBxXUU26Tbmj8+quro+02Lw+I4ssdslNvzhzazvDPbq8d7GW7Dfqz2VzG
0s2qd+iu/Zn5Ksk9BVztX1mI8930zh2LwOHabH+HHWP2fNYp4+vwYvxXiP3fUqxtWIjyjZtj45/L
faQFmQADzftfj3w6fJ6WmHmsP23rvaqnNwqLfhvEvIYZ+sV038bo0noy36MK9oZQxrdMyrlnMbMZ
QKrS1M07zEestq/RRjr4utwY/wAV4j91p9V18fQdJj8LR4ccfdpEfsuREbREJbuMAAAAAAAAAAAA
BAJAAAAEAJEAJQAJQAJEAJQAJQAJEACUJAQlAJEAJQAJQJAAAEAJEAJBAAAJAABAJEJAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwvanDzaPFmjvjv8A
tLztJ3h7HjGHx+FainnFeaPnHV4vFbeIU038VbHeGF+kso7Mb9mTdhKnLK3dRm7SIrHhGPxeP6Sv
9cT/AHfSnz72Zx+J7Q45/BWZ/Z9BbZ+OXyfQBZQABzeP4/E4NqI9Ii36S8Ng/wAx9C4jTxOH6ivr
jn+Hz3B/mQi/GvjdCnWNlsdI2V07LIlg6USrt2ZzZXMoFV+zPhGLxeOaavpbm/RVltEN72Yx+Jxm
b7dKUmf7L5+s9/HtRA2cqRACRACRACRACUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAACQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQCQQCRACRACRCQBCQBCQB
ACRACRACRACRACL1i9LVntMbPATTwdRkxT3pea/u+gPE8Xx+DxrPHlaYt+qNfGvjvtXXsi0dOrKk
dEXjZg6VMtbP2bMtXUdpEV0/Y2nNxbNf8OP+727xvsXH+N1U/wBEfy9k3nxyb+gCVQAGOWvNivX1
rMPnGGOXNNfOJ2fSZ6w+dZKeHxDPX8N7R+6L8a+L63KdoZ7q6zvEMpnowdKJ6ywmWUyqvIKM0vQ+
x+D6rU55+9aKx+TzWa36vbezmDwODYenW+95/Nphj5L6dQBo5wAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAEiAAAEoA
AAAAAAAAAAAAAEAkEAkRuAkQbgkQAkQAkQAkQAl5T2nx8nEMOT8dNv0l6pwfarHvpcGWPu32/WCr
YvK4mOem6b9mGKd4Z3idmFdka0y1c892zfpMtLPaNpEV6D2Kj/Eauf6YeweQ9ieuTVz8K/3evbT4
5NfQBKoAA8FxCvJxrUx/XMvevD8Zry8fz/Haf2RfjTx/6RSOnRMyypHu9kXjowrqVSrvPRnZVl6V
kK0775MsUjvadn0nT4ow6bFijtSsVfPuFYvpPGtNTy54mfy6vorXDm8l9pEC7JIgBIgBIgBIgBIg
BIgBIhIAgBIhIAgBIgBIIBIAAhIAhIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJAAAAAAAAAAAAAAA
AAAAAAAAABAJQkAEAAAAAAAAAAjc3BIjdG4Mkbo5kcwMjdhzHMDPc3V8xzAs3N1fMjmBZubq+Y5g
Wbm6vmOYFm5ur5jmBZubq+Y5gWbm6vmOYFm5ur5jmBZubq+Y5gWbm6vmTzAz3N2HMnmBlu5ftFTx
OEZJ/DMW/d0t2rxKni8N1FPWkiZ9eS08e7Cy8dGGn6UhZaJljXZGnmc3UT3dPP2cnUT78xCIV6j2
H/8A9c/6f7vXPI+w8bU1U+vL/d63du5NfUiDcVSIAS8b7RV5eOb/AIqRL2TyXtNX/e2KfXH/AHlF
+NPH/pr4+2xcxx0hFpY11K7R16KM32ZWz3UaidqSgrc9kcPicWyZJjfw6T+727y3sXh2xarN+K0V
h6lvPjj3e0ASqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJQAAAAAkQAkQAkAAAAAAAAAAAAAAA
EgAAAAAAAAAAAAAAAAAAAAAgAAABKDcAN0bgkY8xzAyRux5kcwM9zdXNkTcFm6OZXzMeYFvMibKu
ZHMC2bo51U2RuC2bom6rc3BZzom6sBZzI52ADPnOdggFnMc6skFnMc6rc3BbznOp3RzAv50c6nml
HMC/nOf4qOY5wX85zqOc5wbHOc7X5znBsc6edr85zg2ec52vzpi4NjmY5bROG+/bllVzsNTk5dLl
n0pP8BHmMHWNmzt0aum8obm08vVjfrtnxztR0mXHzTvaZdjVRMTLkZo6yiFen9iZ2pqY/wBP93rN
3kPY+/LfPX1rE/u9XzN3HfqzdO6vmTuIZ7m7Hc3Bnu8t7TR/vHBP9E/y9Pu837SV31umn+if5Rfi
/j/01MMb1hjkrtKzBG0bMsmOZY11tOYamr6Und0LUc7XT7u3rJPqL8er9lcPhcFpbzyWm39v7O00
+FYvA4Zpsc94xxu227jv1IAgAAAAAAAAABKAAAASgASgBIgBIgBIgBIhIAAAAAAAAAAAAAAAAAAC
UACUJAAAAAAAAAAAABIAAAAAAAAAAAAAAAAAAAAg3AEbomQZbo3YzLGbAz3RNlc3YzcFs2YzdVN2
M2Bdzom6nmNwW86JurTAMuY3REJ2BB1ZRVMVBhsbSsiqeUFXLucq3lTygp5TlXcpygp5TlXcpygp
5TlXcqOUFXKjlXcrGYBXysdlswiYBVMdUTCyY6sZBWxlnMMZgGLGZZSwkDdHMiWO4MuY5mEyjcFn
N1OdVzHMC3nTzqeY5gX85zqOZPMC+Lqdbk20eb/RKOZr8QybaK/XvtH7iZ9aGlp2luzT3fg19NHS
OjbmPcYX67XH1XSZ9XIzRvMuzrK7zLkZYmYnciunb9lZ5dTk+OP+71cXeP8AZnJ/ip2nf3J/l6iL
/Fu5L9bMWZczXi6YuIbEWTzKIuyiwLt3nuO25uI4a/hx7/rLuczg8TicvFLbfdpEK6+NPH/phhjo
stLGkctUWnoxrrU3j1cnWTzZq1jzl1clo5Zcu8c+txR63iP3Tn6pv4+g4o5cVI9IiGe7CJ2iE7t3
GyN2O6dwSINwSISAlAAlACRAAlAAlACRACRCQAAAAAAAAAASgASISAAAAAAAAAAAAACQAAAAAAAA
AAAAAASAAAAAAAAAAAAAAAAIAAAQCAJljuljsCJlhMs9mOwMJYys5TkBVsjZdyHICrZPKt5E8oK4
qmKrOVOwMIqyirPY2Bjyp2ZbAI2NmSARsbMgEbI2ZAMdjZICNkbMkSCNmOzJEgx2YyzljMAwlhKy
WEwCuWErJhhMArlhLOWEgxljMpljIImWMyTKJA3N0IBO5vux3NwZbnMx3NwZczT4jf3MdPW27a3a
fJOq1XNP2KdIRfi+J2trSYfcjeF+Wm1OicVeWIiN9kai8xjY12ORqultnI1Ecsujq79XP1FovWYI
rTgeq+j8QrWZ+3Mx+r2UXeC0WG2Ti2kiN5mL807eUREvbzbaejefHJv62Iv8WUXa0WTFhVtRdlF2
rz9WUXBtc7jR9dqc2T1ttHyhvZMvJitb0jdq6XHNcNenWVN3028U99WRj6Kb02be3Tq18/SN2Lpc
3UdN9nOmZrqKX/DaJ/d0svvTLRzV3jomK6+Pd1vvWJj0ZczT0mXxNJht60hfFnQ4qu3N1cWTEgs3
Tur5k7gz3N2O5uDM3Y7m4MtxBuCQASIASIASAAAAAAACRCQAAAAAAAAEoSAAAAAAAAAAAlAAlCQA
AAAAAAAAAAASAAAAAAAAAAAAIASgAAAEJAQJQCNkbMgGOyOVnsAw5TlZ7GwMOVPKy2NgY7GzIBGx
skA2AAAAAAAAAAQkBAEghEskAxYzDPZGwK5hjMLJhjMAqmGEwumrCagomFcw2JqqtUFEsLLrV82F
o7gqljKyYYTGwMZRKUSCAQAboJnaN5Bjkneu0d5W4ccViIiOzHFWbTzNumP1Zarr8eeRMbxDW1Mx
NO67NbkhzNVnmInqzaOZrL93JyZeV0M1++7S02jvxDWxhxx033tPpC8Z6rrezWjmZyazJG2/u03h
2vFibTHoqvamiwVwY+nLGzV0+SZ1Mx8G0/45tOhzJ5lXMc3UVXRdlF1HP+iYsDPLPPy49/tz1+Te
pSIr0ho6ak5Ms5J8o2q6NImOrHV7XX488ypzTtHXo0s9t6zG7c1G1qz6ubeZiZ3UatXJG3yauSO7
cvMTEx5tPLb3prPRMVr0HB8vicNxf0+7+kt+LOJwTJyY/Bnz3tH93X36N58cWvq6LSyiyndMSlC7
mZcymLJiwLosmJVRLKLAtiU7q4lMSCzc3YxJuDMRuAlKAEgAAAlAkAAAAAABKAEgAAAAAJAAAAAA
AAAAAAAEgAAAAAAAAAAAAAkAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAhIAAACAAAASgAAAAAAEAAAA
hGzJAImGMwzQDDZjNVuyNgUTVhNGxysZqDVmiu1G5NN2M4waM0+DCaN2cbGcQNGaMZq3JxMJxA1J
qx2bU4kU09slorWNwa20z02RXHbJbl26QvtFovbHWkxEdJt5y2MOHlr2U1W3jx+1hiw8vSO63lmI
XRTaEWmtY6snRHO1VpmJ+DjavpSZl2s8b7y4HFcnh0n0gha5ebJN55KRM2mdoiPN6fh+kpwXh0Wy
RHj5Otp/s5Ps1p62y31+em9aTMYt/OfVfxTiPjZ52naI7fBrI5t66xz5+a1rW7yx0eSL6iZjtEOX
qNbSletom3lENjh2fbHzbbWt3iVozruc+5ztWubf4M4ybpQ2Oboyrva0Vjza8WdDR4OkXt3n9ldX
kaePP9VtYqctYhdvt5oivTeCZ2YOxXk6ubqMfV0b9mrljfqlFcq88k7z2U5axeItDa1OPessuC8P
ya7XRWYnwqdbT/ZMilvIu4dpslNdixXja8Y5tt85djZdbDWnGOesRtXFtuw6T27No5Kx2OrKYQlC
ExKJgBnEpiyvdlEgsizKLKollFgWxLKJVRLKJBbEp3VxLKJBnuMWQJEbpBIAAAJAAAABIAAAAAAA
lAJAAAAAAAAAAAAAASAAAAAAAAAAAAAJAAAABAJABAlAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAA
AAABAJQAAAAgAABAAI2EoBGyJhkgGPKxmqxAKpownHC+YRMdN5BrTj67R3bOn01o7p01Iv71u89o
b9a7LfBTfS1vWI2jf12VfQPSW8KX2mas+NC2iv6xMNfJpMnLtEbuuxtMRCtzF55NR5rPps1N/ctP
y6uHreE6nXZ4pak48X3rT06fB7fNeI33cbX6mI32R/MWu7XF116aDSRhxbRERs8f499bkyZeeKae
kzE2mdon81/tfxDLGOunwbzlzbx08oaHBvZHJlx48mrvaa94pu04y617576rNGLRRM0397JEd/lu
9Dw/S3x4qxffo6mm4NjwUiKY4iI9Ib1dHFY6QIaNabbrYrLfrpJtaK1rMzPZb/s+05IpP59OyLeJ
k7eNfRaOc1ue32I7fGXYpi5Y77M8OGMeOKxHSFsU3Y29deZMzirl6dlVvhLatCjJHeYQv1rXnps1
8k9/VsW6qLVmZIi1rzitlvFKRvaZ2h6TSaenC9FFY+3brM+sqeG8Prp4+kZ+lvuxPkr1mqm95nfp
DXM459676a2q1dsV7XietvNno78+CJn1cjX6mOeIm0bR33dfRU5NJjidt9t5afjG/V6JZ7I2QMNh
nyo2BhsMuVG3wAhMSbbQRAMolnE+iuGUSCyJZRKuGUSCyJZK4llEgyZMYTuCUsYSCQASISAAAlCQ
AAAAAAEoASCASAAAAAAAAAAAAlACRACQAAAAAAAAAEgCEoASCAAAAAAAAAAAAAAAAAAAAAAABAAA
AAAAAAAISAIAAAAAAQAAACASgAAAQJAQAAhIDHZhln3do7z0WS18mWsajHjmes7pg3dNi5aRMNqO
yvDHTpPRaigHZhN4hHRlaVN59JY3zRENLUavaO+yq0iNVlitJ6vNcR1MVi0zO0era1/Ea0rPvbz5
PM5MWp45qvo2GZrhmfrsnpHpHzTCseEcM/2vrr8Q1Eb4qzy44nziPN63HpYiIiI7LNHoqabBTFii
IpSNohuVxrKtWMEejPwY9G1FFmHB4mWJn7MdfnIM9JpIx15to5pbUaas/a6rqViI7MxPxqX0UT1r
O3wVzpbR2hviP5i03Y5s6a879FNtHljydhExCv8AMTPJXBnRZbz0iG5ptFjwe/l96zctMVamTJtE
yTMibu1VrdTzRMR0j0ed4lr64MVpm0RERvMz5NvX62uOJ69XhOKX1HH9bHDtFvNYnfJeOy0Z2ojX
6jjnEq6fRUmccTvN/J9H0eKcOnx45neaxEbubwHgOHg+milI3vP2resu3Wu0JQmITsmISDHZHKz2
JgFc1RMLJhGwK9iIZ7MZgEdgmAEwyiWCdwWRLKJVxKYsC2JTuriWUSDNlEsIlMAySx3SCRCQSIAS
AAACRACQAAAAAAASIASAAAAAAAAAAAAAAACRACRACQASIAAAAAAAAAAAAAAAAAAAAAAAAQCUAAAA
AAAAAAIAAAAAAAAQAAAAAACBICBICAAEJAQJQCJcLjuS2ny6fPG/LWdpd1o8T0X07SXx/e7wCdJx
Wa0jmneHQpxPDMdZmJfNtZm49weZrh0/j4o7VtSZ2+Uw0/8A7o49k92vBLc/ntFohFW9PqGXimOI
6Tu1L8T3eCx6r2t1O3JwvHjifO99v7t/Bwf2l1PXU6rS6eJ8qUm8x+so5TsekzcSjbvs4mt4rzW5
K2mbT0itesy2cHsvbvqtbmyz5xERWP2jd1tJwrTaONsOKtZ8585+cnDrzmn4Rq+IZObUROHD32n7
Vv8A0ej0uhxaXFGPFSK1j0bkY4jyZRVZVXFGUVWbGwKsk8mObekNrSW3pWf1a2aYjHbm7bNnQ1id
PW0TvuDdhJEbQABMsLW2R0ZTMQrvfbz2YWzVhpanUxEd0dWkW5c8R5uXxDX1w4pnfr5Q19XxKuOJ
2neXltVqtVxbV/RdJ715+1bypANfiOu1HENV9C0MTfNeesx2rD1PAeBYuE6aKx72W3W9/WVnBuB4
eF4dqRzZbdb5J72l160WVK02ZxCYhOwI23TsnY2BGxsnYBjsiYZsZBjMMZZSgGEolMsQDdG6NwZ7
piVe6YkFsSziVMWZRILolMSriWUSCyJTuwhMSDMRCQSI3SAlACRCQAAEoAEoASAAAAAAAAACUACR
ACQAAAAAAAAAAAAASAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAABAAAAAAAAAAAAACBKAAAAAAAQ
JQAAAhICEbJAYTWJ7wx8KvpC0BV4ceieWGewDHlNmWwCNjZICNhIDmcZredBecdpiY69FXCOLW+i
UiZidukulmxxlx2paN4mNng+K4+I8Hy2yaTfl37TXetoCPfRxfp1qi3F48ofKMvtvxak8s6LDv61
rZji9rPaLUf5PC+bfttS0q8q3p9W/wBrRMdpUZuKdN99nzvFqPbTVz7nD8OKs+do2/mW3h4D7Xaq
ZnPrtNpqz35aRaYOHY9Zk4pNt9rR+rl6zi+OnS+WN57Rv1lXp/YrNaYtruL6zNPnGO3hxP6O5w/2
f0HDuun09Yv55Le9afznqcOvO4tBreMTHu30unnva0bWt8on+70nDuE4OHYYx4Kbesz3tPrMuhGO
IjpDOKrK9YVpsyiGUQnYGOyUgI2SlAIEmwMWMs9kTAMJYzDOYRMArmGErZhhMArlHmzmGMwDE3Ts
bAbs4swj5pgFkSziVcM4BZEsolXDKAZwyhjCYBkACQhIAAAAAAAJAAAAAAAAAAAAAAAAAAAShIAA
AAAAAAJAAAAAAAAAAAAAABAJEAAAAAAAAAAAAAAAIEoBKAAAAAAAAAAAAAAABAlAAAAAAAIAAAAA
BAkBAkBAkBAlACEgMZjdjbFW8bWrEx8YWANb6Fp+bfwab+vLDKMFK9qxH5L0bAr8OPRPKz2AY7J2
SbAjYZAI2E7AIEgIEgIEgMdkSy2NgY7MdlmyNoBXsxmFuyNgVTVjNV3KjlBRNTlXTVHKCrlIqt5T
lBhEMohlFerLlBjEMohMVTEARDKCITsAk2AEgAAAkAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAD/
2Q==`;
// src/warmup.ts
async function warmupBitmap(instance) {
const b64toBlob = (base64, type = "application/octet-stream") => fetch(`data:${type};base64,${base64}`).then((res2) => res2.blob());
let blob;
let res;
switch (instance.config.warmup) {
case "face":
blob = await b64toBlob(face3);
break;
case "body":
case "full":
blob = await b64toBlob(body3);
break;
default:
blob = null;
}
if (blob) {
const bitmap = await createImageBitmap(blob);
res = await instance.detect(bitmap, instance.config);
bitmap.close();
}
return res;
}
async function warmupCanvas(instance) {
return new Promise((resolve) => {
let src;
switch (instance.config.warmup) {
case "face":
src = "data:image/jpeg;base64," + face3;
break;
case "full":
case "body":
src = "data:image/jpeg;base64," + body3;
break;
default:
src = null;
}
let img;
if (typeof Image !== "undefined")
img = new Image();
else if (env.Image)
img = new env.Image();
img.onload = async () => {
const canvas3 = canvas(img.naturalWidth, img.naturalHeight);
if (!canvas3) {
log("Warmup: Canvas not found");
resolve({});
} else {
const ctx = canvas3.getContext("2d");
if (ctx)
ctx.drawImage(img, 0, 0);
const tensor = await instance.image(canvas3);
const res = await instance.detect(tensor.tensor, instance.config);
resolve(res);
}
};
if (src)
img.src = src;
else
resolve(null);
});
}
async function warmupNode(instance) {
const atob2 = (str) => Buffer.from(str, "base64");
let img;
if (instance.config.warmup === "face")
img = atob2(face3);
if (instance.config.warmup === "body" || instance.config.warmup === "full")
img = atob2(body3);
if (!img)
return null;
let res;
if (typeof void 0 !== "undefined") {
const data = (void 0).decodeJpeg(img);
const expanded = data.expandDims(0);
instance.tf.dispose(data);
res = await instance.detect(expanded, instance.config);
instance.tf.dispose(expanded);
} else {
if (instance.config.debug)
log("Warmup tfjs-node not loaded");
}
return res;
}
async function warmup(instance, userConfig) {
const t02 = now();
instance.state = "warmup";
if (userConfig)
instance.config = mergeDeep(instance.config, userConfig);
if (!instance.config.warmup || instance.config.warmup === "none")
return { error: "null" };
let res;
return new Promise(async (resolve) => {
if (typeof createImageBitmap === "function")
res = await warmupBitmap(instance);
else if (typeof Image !== "undefined" || env.Canvas !== void 0)
res = await warmupCanvas(instance);
else
res = await warmupNode(instance);
const t12 = now();
if (instance.config.debug)
log("Warmup", instance.config.warmup, Math.round(t12 - t02), "ms");
instance.emit("warmup");
resolve(res);
});
}
// src/human.ts
var _numTensors, _analyzeMemoryLeaks, _checkSanity, _sanity;
var Human = class {
constructor(userConfig) {
__publicField(this, "version");
__publicField(this, "config");
__publicField(this, "result");
__publicField(this, "state");
__publicField(this, "process");
__publicField(this, "tf");
__publicField(this, "env");
__publicField(this, "draw");
__publicField(this, "models");
__publicField(this, "events");
__publicField(this, "faceTriangulation");
__publicField(this, "faceUVMap");
__publicField(this, "performance");
__privateAdd(this, _numTensors, void 0);
__privateAdd(this, _analyzeMemoryLeaks, void 0);
__privateAdd(this, _checkSanity, void 0);
__publicField(this, "gl");
__publicField(this, "analyze", (...msg) => {
if (!__privateGet(this, _analyzeMemoryLeaks))
return;
const currentTensors = this.tf.engine().state.numTensors;
const previousTensors = __privateGet(this, _numTensors);
__privateSet(this, _numTensors, currentTensors);
const leaked = currentTensors - previousTensors;
if (leaked !== 0)
log(...msg, leaked);
});
__privateAdd(this, _sanity, (input) => {
if (!__privateGet(this, _checkSanity))
return null;
if (!input)
return "input is not defined";
if (this.env.node && !(input instanceof Le))
return "input must be a tensor";
try {
this.tf.getBackend();
} catch (e) {
return "backend not loaded";
}
return null;
});
__publicField(this, "similarity", similarity);
__publicField(this, "distance", distance);
__publicField(this, "match", match2);
__publicField(this, "emit", (event) => {
var _a2;
if (this.events && this.events.dispatchEvent)
(_a2 = this.events) == null ? void 0 : _a2.dispatchEvent(new Event(event));
});
this.env = env;
config.wasmPath = E1.includes("-") ? "https://vladmandic.github.io/tfjs/dist/" : `https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${E1}/dist/`;
config.modelBasePath = env.browser ? "../models/" : "file://models/";
config.backend = env.browser ? "humangl" : "tensorflow";
this.version = version;
Object.defineProperty(this, "version", { value: version });
this.config = JSON.parse(JSON.stringify(config));
Object.seal(this.config);
if (userConfig)
this.config = mergeDeep(this.config, userConfig);
this.tf = tfjs_esm_exports;
this.state = "idle";
__privateSet(this, _numTensors, 0);
__privateSet(this, _analyzeMemoryLeaks, false);
__privateSet(this, _checkSanity, false);
this.performance = { backend: 0, load: 0, image: 0, frames: 0, cached: 0, changed: 0, total: 0, draw: 0 };
this.events = typeof EventTarget !== "undefined" ? new EventTarget() : void 0;
this.models = new Models();
this.draw = {
options: options2,
canvas: (input, output) => canvas2(input, output),
face: (output, result, options3) => face(output, result, options3),
body: (output, result, options3) => body(output, result, options3),
hand: (output, result, options3) => hand(output, result, options3),
gesture: (output, result, options3) => gesture(output, result, options3),
object: (output, result, options3) => object(output, result, options3),
person: (output, result, options3) => person(output, result, options3),
all: (output, result, options3) => all(output, result, options3)
};
this.result = { face: [], body: [], hand: [], gesture: [], object: [], performance: {}, timestamp: 0, persons: [] };
this.process = { tensor: null, canvas: null };
this.faceTriangulation = triangulation;
this.faceUVMap = uvmap;
this.gl = config2;
this.emit("create");
}
reset() {
const currentBackend = this.config.backend;
this.config = JSON.parse(JSON.stringify(config));
this.config.backend = currentBackend;
}
validate(userConfig) {
return validate(config, userConfig || this.config);
}
now() {
return now();
}
image(input, getTensor = true) {
return process2(input, this.config, getTensor);
}
async segmentation(input, background) {
return process5(input, background, this.config);
}
enhance(input) {
return enhance(input);
}
async init() {
await check(this, true);
await this.tf.ready();
}
async load(userConfig) {
this.state = "load";
const timeStamp = now();
const count2 = Object.values(this.models).filter((model14) => model14).length;
if (userConfig)
this.config = mergeDeep(this.config, userConfig);
if (env.initial) {
if (this.config.debug)
log(`version: ${this.version}`);
if (this.config.debug)
log(`tfjs version: ${this.tf.version_core}`);
if (!await check(this))
log("error: backend check failed");
await uue();
if (this.env.browser) {
if (this.config.debug)
log("configuration:", this.config);
if (this.config.debug)
log("tf flags:", this.tf.ENV.flags);
}
}
await load15(this);
if (env.initial && this.config.debug)
log("tf engine state:", this.tf.engine().state.numBytes, "bytes", this.tf.engine().state.numTensors, "tensors");
env.initial = false;
const loaded = Object.values(this.models).filter((model14) => model14).length;
if (loaded !== count2) {
await validate2(this);
this.emit("load");
}
const current = Math.trunc(now() - timeStamp);
if (current > (this.performance.load || 0))
this.performance.load = current;
}
next(result = this.result) {
return calc2(result, this.config);
}
async warmup(userConfig) {
return warmup(this, userConfig);
}
async detect(input, userConfig) {
this.state = "detect";
return new Promise(async (resolve) => {
var _a2, _b, _c2, _d2, _e, _f2, _g, _h2, _i2, _j2, _k2, _l2, _m2, _n2, _o2, _p2, _q2, _r, _s2, _t2, _u2, _v2;
this.state = "config";
let timeStamp;
let elapsedTime;
this.config = mergeDeep(this.config, userConfig);
this.state = "check";
const error = __privateGet(this, _sanity).call(this, input);
if (error) {
log(error, input);
resolve({ error });
}
const timeStart = now();
await check(this);
await this.load();
timeStamp = now();
this.state = "image";
const img = process2(input, this.config);
this.process = img;
this.performance.image = Math.trunc(now() - timeStamp);
this.analyze("Get Image:");
if (!img.tensor) {
if (this.config.debug)
log("could not convert input to tensor");
resolve({ error: "could not convert input to tensor" });
return;
}
this.emit("image");
timeStamp = now();
this.config.skipFrame = await skip(this.config, img.tensor);
if (!this.performance.frames)
this.performance.frames = 0;
if (!this.performance.cached)
this.performance.cached = 0;
this.performance.frames++;
if (this.config.skipFrame)
this.performance.cached++;
this.performance.changed = Math.trunc(now() - timeStamp);
this.analyze("Check Changed:");
let faceRes = [];
let bodyRes = [];
let handRes = [];
let objectRes = [];
this.state = "detect:face";
if (this.config.async) {
faceRes = this.config.face.enabled ? detectFace(this, img.tensor) : [];
if (this.performance.face)
delete this.performance.face;
} else {
timeStamp = now();
faceRes = this.config.face.enabled ? await detectFace(this, img.tensor) : [];
elapsedTime = Math.trunc(now() - timeStamp);
if (elapsedTime > 0)
this.performance.face = elapsedTime;
}
if (this.config.async && (this.config.body.maxDetected === -1 || this.config.hand.maxDetected === -1))
faceRes = await faceRes;
this.analyze("Start Body:");
this.state = "detect:body";
const bodyConfig = this.config.body.maxDetected === -1 ? mergeDeep(this.config, { body: { maxDetected: this.config.face.enabled ? 1 * faceRes.length : 1 } }) : this.config;
if (this.config.async) {
if ((_a2 = this.config.body.modelPath) == null ? void 0 : _a2.includes("posenet"))
bodyRes = this.config.body.enabled ? predict12(img.tensor, bodyConfig) : [];
else if ((_b = this.config.body.modelPath) == null ? void 0 : _b.includes("blazepose"))
bodyRes = this.config.body.enabled ? predict2(img.tensor, bodyConfig) : [];
else if ((_c2 = this.config.body.modelPath) == null ? void 0 : _c2.includes("efficientpose"))
bodyRes = this.config.body.enabled ? predict4(img.tensor, bodyConfig) : [];
else if ((_d2 = this.config.body.modelPath) == null ? void 0 : _d2.includes("movenet"))
bodyRes = this.config.body.enabled ? predict10(img.tensor, bodyConfig) : [];
if (this.performance.body)
delete this.performance.body;
} else {
timeStamp = now();
if ((_e = this.config.body.modelPath) == null ? void 0 : _e.includes("posenet"))
bodyRes = this.config.body.enabled ? await predict12(img.tensor, bodyConfig) : [];
else if ((_f2 = this.config.body.modelPath) == null ? void 0 : _f2.includes("blazepose"))
bodyRes = this.config.body.enabled ? await predict2(img.tensor, bodyConfig) : [];
else if ((_g = this.config.body.modelPath) == null ? void 0 : _g.includes("efficientpose"))
bodyRes = this.config.body.enabled ? await predict4(img.tensor, bodyConfig) : [];
else if ((_h2 = this.config.body.modelPath) == null ? void 0 : _h2.includes("movenet"))
bodyRes = this.config.body.enabled ? await predict10(img.tensor, bodyConfig) : [];
elapsedTime = Math.trunc(now() - timeStamp);
if (elapsedTime > 0)
this.performance.body = elapsedTime;
}
this.analyze("End Body:");
this.analyze("Start Hand:");
this.state = "detect:hand";
const handConfig = this.config.hand.maxDetected === -1 ? mergeDeep(this.config, { hand: { maxDetected: this.config.face.enabled ? 2 * faceRes.length : 1 } }) : this.config;
if (this.config.async) {
if ((_j2 = (_i2 = this.config.hand.detector) == null ? void 0 : _i2.modelPath) == null ? void 0 : _j2.includes("handdetect"))
handRes = this.config.hand.enabled ? predict8(img.tensor, handConfig) : [];
else if ((_l2 = (_k2 = this.config.hand.detector) == null ? void 0 : _k2.modelPath) == null ? void 0 : _l2.includes("handtrack"))
handRes = this.config.hand.enabled ? predict9(img.tensor, handConfig) : [];
if (this.performance.hand)
delete this.performance.hand;
} else {
timeStamp = now();
if ((_n2 = (_m2 = this.config.hand.detector) == null ? void 0 : _m2.modelPath) == null ? void 0 : _n2.includes("handdetect"))
handRes = this.config.hand.enabled ? await predict8(img.tensor, handConfig) : [];
else if ((_p2 = (_o2 = this.config.hand.detector) == null ? void 0 : _o2.modelPath) == null ? void 0 : _p2.includes("handtrack"))
handRes = this.config.hand.enabled ? await predict9(img.tensor, handConfig) : [];
elapsedTime = Math.trunc(now() - timeStamp);
if (elapsedTime > 0)
this.performance.hand = elapsedTime;
}
this.analyze("End Hand:");
this.analyze("Start Object:");
this.state = "detect:object";
if (this.config.async) {
if ((_q2 = this.config.object.modelPath) == null ? void 0 : _q2.includes("nanodet"))
objectRes = this.config.object.enabled ? predict11(img.tensor, this.config) : [];
else if ((_r = this.config.object.modelPath) == null ? void 0 : _r.includes("centernet"))
objectRes = this.config.object.enabled ? predict3(img.tensor, this.config) : [];
if (this.performance.object)
delete this.performance.object;
} else {
timeStamp = now();
if ((_s2 = this.config.object.modelPath) == null ? void 0 : _s2.includes("nanodet"))
objectRes = this.config.object.enabled ? await predict11(img.tensor, this.config) : [];
else if ((_t2 = this.config.object.modelPath) == null ? void 0 : _t2.includes("centernet"))
objectRes = this.config.object.enabled ? await predict3(img.tensor, this.config) : [];
elapsedTime = Math.trunc(now() - timeStamp);
if (elapsedTime > 0)
this.performance.object = elapsedTime;
}
this.analyze("End Object:");
this.state = "detect:await";
if (this.config.async)
[faceRes, bodyRes, handRes, objectRes] = await Promise.all([faceRes, bodyRes, handRes, objectRes]);
this.state = "detect:gesture";
let gestureRes = [];
if (this.config.gesture.enabled) {
timeStamp = now();
gestureRes = [...face2(faceRes), ...body2(bodyRes), ...hand2(handRes), ...iris3(faceRes)];
if (!this.config.async)
this.performance.gesture = Math.trunc(now() - timeStamp);
else if (this.performance.gesture)
delete this.performance.gesture;
}
this.performance.total = Math.trunc(now() - timeStart);
const shape = ((_v2 = (_u2 = this.process) == null ? void 0 : _u2.tensor) == null ? void 0 : _v2.shape) || [];
this.result = {
face: faceRes,
body: bodyRes,
hand: handRes,
gesture: gestureRes,
object: objectRes,
performance: this.performance,
canvas: this.process.canvas,
timestamp: Date.now(),
get persons() {
return join2(faceRes, bodyRes, handRes, gestureRes, shape);
}
};
De(img.tensor);
this.emit("detect");
this.state = "idle";
resolve(this.result);
});
}
};
_numTensors = new WeakMap();
_analyzeMemoryLeaks = new WeakMap();
_checkSanity = new WeakMap();
_sanity = new WeakMap();
export {
Env,
Human,
Models,
Human as default,
config as defaults,
env
};
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** @license See the LICENSE file. */
//# sourceMappingURL=human.esm.js.map