/*
  Human
  homepage: <https://github.com/vladmandic/human>
  author: <https://github.com/vladmandic>'
*/

var __defProp = Object.defineProperty;
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __export = (target, all2) => {
  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);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __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), value);

// dist/tfjs.esm.js
var tfjs_esm_exports = {};
__export(tfjs_esm_exports, {
  Abs: () => Xs,
  Acos: () => Vo,
  Acosh: () => Wo,
  AdadeltaOptimizer: () => Ju,
  AdagradOptimizer: () => ep,
  AdamOptimizer: () => tp,
  AdamaxOptimizer: () => rp,
  Add: () => uo,
  AddN: () => Uo,
  All: () => Go,
  Any: () => Ho,
  ArgMax: () => Ys,
  ArgMin: () => Qs,
  Asin: () => Ko,
  Asinh: () => qo,
  Atan: () => jo,
  Atan2: () => Yo,
  Atanh: () => Xo,
  AvgPool: () => Qo,
  AvgPool3D: () => Zs,
  AvgPool3DGrad: () => Ri,
  AvgPoolGrad: () => $i,
  BackendWasm: () => pm,
  BatchMatMul: () => Zo,
  BatchToSpaceND: () => Js,
  Bincount: () => Jo,
  BitwiseAnd: () => qa,
  BroadcastArgs: () => ea,
  BroadcastTo: () => qce,
  Cast: () => yo,
  Ceil: () => en,
  ClipByValue: () => bo,
  Complex: () => Di,
  ComplexAbs: () => Ai,
  Concat: () => ta,
  Conv2D: () => tn,
  Conv2DBackpropFilter: () => Fi,
  Conv2DBackpropInput: () => rn,
  Conv3D: () => on,
  Conv3DBackpropFilterV2: () => ja,
  Conv3DBackpropInputV2: () => nn,
  Cos: () => sn,
  Cosh: () => an,
  CropAndResize: () => cn,
  Cumprod: () => un,
  Cumsum: () => pn,
  DataStorage: () => Bo,
  DenseBincount: () => ra,
  DepthToSpace: () => ln,
  DepthwiseConv2dNative: () => mn,
  DepthwiseConv2dNativeBackpropFilter: () => Pi,
  DepthwiseConv2dNativeBackpropInput: () => Oi,
  Diag: () => oa,
  Dilation2D: () => dn,
  Dilation2DBackpropFilter: () => Li,
  Dilation2DBackpropInput: () => Mi,
  Draw: () => $u,
  ENV: () => nw,
  Einsum: () => Bi,
  Elu: () => hn,
  EluGrad: () => Xa,
  Environment: () => dl,
  Equal: () => xn,
  Erf: () => gn,
  Exp: () => yn,
  ExpandDims: () => na,
  Expm1: () => bn,
  FFT: () => zi,
  Fill: () => sa,
  FlipLeftRight: () => Cn,
  Floor: () => wn,
  FloorDiv: () => Sn,
  FromPixels: () => Du,
  FusedBatchNorm: () => In,
  FusedConv2D: () => Io,
  FusedDepthwiseConv2D: () => vo,
  GPGPUContext: () => bp,
  GatherNd: () => vn,
  GatherV2: () => aa,
  GraphModel: () => Bl,
  Greater: () => kn,
  GreaterEqual: () => Nn,
  IFFT: () => Vi,
  Identity: () => Co,
  Imag: () => Wi,
  IsFinite: () => Tn,
  IsInf: () => _n,
  IsNan: () => En,
  KernelBackend: () => ao,
  LRN: () => Bn,
  LRNGrad: () => Ya,
  LeakyRelu: () => $n,
  Less: () => Rn,
  LessEqual: () => Dn,
  LinSpace: () => An,
  Log: () => Fn,
  Log1p: () => Pn,
  LogSoftmax: () => jce,
  LogicalAnd: () => On,
  LogicalNot: () => Mn,
  LogicalOr: () => Ln,
  LogicalXor: () => R0,
  LowerBound: () => Xce,
  MathBackendCPU: () => xc,
  MathBackendWebGL: () => Lc,
  MatrixBandPart: () => Yce,
  Max: () => zn,
  MaxPool: () => Wn,
  MaxPool3D: () => ia,
  MaxPool3DGrad: () => Gi,
  MaxPoolGrad: () => Ui,
  MaxPoolWithArgmax: () => ua,
  Maximum: () => Vn,
  Mean: () => Un,
  Min: () => Gn,
  Minimum: () => Hn,
  MirrorPad: () => Kn,
  Mod: () => qn,
  MomentumOptimizer: () => op,
  Multinomial: () => jn,
  Multiply: () => Xn,
  Neg: () => pa,
  NonMaxSuppressionV3: () => Qn,
  NonMaxSuppressionV4: () => Qa,
  NonMaxSuppressionV5: () => Zn,
  NotEqual: () => Yn,
  OP_SCOPE_SUFFIX: () => Nw,
  OneHot: () => Jn,
  OnesLike: () => ca,
  Optimizer: () => kr,
  OptimizerConstructors: () => Fl,
  Pack: () => la,
  PadV2: () => es,
  Pool: () => Qce,
  Pow: () => ts,
  Prelu: () => rs,
  Prod: () => os,
  RMSPropOptimizer: () => np,
  RaggedGather: () => Hp,
  RaggedRange: () => Kp,
  RaggedTensorToTensor: () => qp,
  Range: () => ma,
  Rank: () => gw,
  Real: () => Hi,
  RealDiv: () => fn,
  Reciprocal: () => ns,
  Reduction: () => $t,
  Relu: () => ss,
  Relu6: () => us,
  Reshape: () => da,
  ResizeBilinear: () => is,
  ResizeBilinearGrad: () => Ja,
  ResizeNearestNeighbor: () => as,
  ResizeNearestNeighborGrad: () => Za,
  Reverse: () => ps,
  RotateWithOffset: () => Ds,
  Round: () => cs,
  Rsqrt: () => ls,
  SGDOptimizer: () => mi,
  ScatterNd: () => ms,
  SearchSorted: () => fs,
  Select: () => fa,
  Selu: () => hs,
  Sigmoid: () => bs,
  Sign: () => ys,
  Sin: () => gs,
  Sinh: () => xs,
  Slice: () => ha,
  Softmax: () => Is,
  Softplus: () => Cs,
  SpaceToBatchND: () => ga,
  SparseFillEmptyRows: () => Ki,
  SparseReshape: () => ei,
  SparseSegmentMean: () => ya,
  SparseSegmentSum: () => ba,
  SparseToDense: () => vs,
  SplitV: () => xa,
  Sqrt: () => ws,
  Square: () => qi,
  SquaredDifference: () => ks,
  StaticRegexReplace: () => Ru,
  Step: () => wo,
  StridedSlice: () => Ns,
  StringNGrams: () => Ca,
  StringSplit: () => ji,
  StringToHashBucketFast: () => Xi,
  Sub: () => Ts,
  Sum: () => Ss,
  Tan: () => _s,
  Tanh: () => Es,
  Tensor: () => mt,
  TensorBuffer: () => tt,
  TensorScatterUpdate: () => ds,
  Tile: () => po,
  TopK: () => $s,
  Transform: () => Rs,
  Transpose: () => co,
  Unique: () => Yi,
  Unpack: () => wa,
  UnsortedSegmentSum: () => Qi,
  UpperBound: () => Zce,
  Variable: () => ri,
  WebGPUBackend: () => jc,
  ZerosLike: () => Sa,
  _FusedMatMul: () => So,
  abs: () => Qt,
  acos: () => Rk,
  acosh: () => Dk,
  add: () => Ce,
  addN: () => Ak,
  all: () => Fk,
  any: () => Pk,
  argMax: () => Ok,
  argMin: () => Mk,
  asin: () => Lk,
  asinh: () => Bk,
  atan: () => zk,
  atan2: () => Vk,
  atanh: () => Wk,
  avgPool: () => dd,
  avgPool3d: () => Hk,
  backend: () => ak,
  backend_util: () => w,
  basicLSTMCell: () => Kk,
  batchNorm: () => nu,
  batchNorm2d: () => jk,
  batchNorm3d: () => Xk,
  batchNorm4d: () => Yk,
  batchToSpaceND: () => fd,
  bincount: () => hd,
  bitwiseAnd: () => Qk,
  booleanMaskAsync: () => L6,
  broadcastArgs: () => Zk,
  broadcastTo: () => su,
  broadcast_util: () => Sr,
  browser: () => cT,
  buffer: () => me,
  cast: () => Ue,
  ceil: () => Jk,
  clipByValue: () => e2,
  clone: () => Ur,
  complex: () => Er,
  concat: () => yt,
  concat1d: () => t2,
  concat2d: () => r22,
  concat3d: () => o2,
  concat4d: () => n2,
  conv1d: () => s2,
  conv2d: () => au,
  conv2dTranspose: () => a2,
  conv3d: () => i2,
  conv3dTranspose: () => p2,
  copyRegisteredKernels: () => ale,
  cos: () => c2,
  cosh: () => l2,
  cosineWindow: () => $l,
  cumprod: () => m2,
  cumsum: () => d2,
  customGrad: () => Ir,
  denseBincount: () => f2,
  deprecationWarn: () => Tw,
  depthToSpace: () => h2,
  depthwiseConv2d: () => sc,
  deregisterOp: () => V5,
  device_util: () => eu,
  diag: () => g2,
  dilation2d: () => x2,
  disableDeprecationWarnings: () => xme,
  dispose: () => Ot,
  disposeVariables: () => yme,
  div: () => je,
  divNoNan: () => b2,
  dot: () => C2,
  dropout: () => Y6,
  einsum: () => iu,
  elu: () => bd,
  enableDebugMode: () => gme,
  enableProdMode: () => hme,
  enclosingPowerOfTwo: () => Zw,
  engine: () => ur,
  ensureShape: () => w2,
  env: () => A,
  equal: () => yd,
  erf: () => S2,
  euclideanNorm: () => k2,
  exp: () => _o,
  expandDims: () => Ms,
  expm1: () => N2,
  eye: () => Cd,
  fft: () => uc,
  fill: () => $a,
  findBackend: () => kme,
  findBackendFactory: () => Nme,
  floor: () => wd,
  floorDiv: () => md,
  forceHalfFloat: () => GD,
  fused: () => Jw,
  gather: () => Sd,
  gatherND: () => j6,
  gather_util: () => af,
  getBackend: () => sk,
  getGradient: () => iw,
  getKernel: () => Xp,
  getKernelsForBackend: () => Ym,
  getThreadsCount: () => aae,
  gpgpu_util: () => mv,
  grad: () => VK,
  grads: () => WK,
  greater: () => Wu,
  greaterEqual: () => Id,
  ifft: () => ju,
  imag: () => pu,
  image: () => eX,
  inTopKAsync: () => Z6,
  io: () => di,
  irfft: () => Hd,
  isFinite: () => T2,
  isInf: () => _2,
  isNaN: () => E2,
  keep: () => $r,
  kernel_impls: () => Vt,
  leakyRelu: () => vd,
  less: () => Tl,
  lessEqual: () => ac,
  linalg: () => tX,
  linspace: () => $2,
  loadGraphModel: () => M8,
  loadGraphModelSync: () => L8,
  localResponseNormalization: () => R2,
  log: () => pi,
  log1p: () => kd,
  logSigmoid: () => D2,
  logSoftmax: () => A2,
  logSumExp: () => _d,
  logicalAnd: () => Uu,
  logicalNot: () => Ed,
  logicalOr: () => $d,
  logicalXor: () => F2,
  losses: () => rX,
  lowerBound: () => P2,
  matMul: () => Ze,
  math: () => aT,
  max: () => Ra,
  maxPool: () => Dd,
  maxPool3d: () => O2,
  maxPoolWithArgmax: () => M2,
  maximum: () => Ad,
  mean: () => Gu,
  memory: () => bme,
  meshgrid: () => L2,
  min: () => Nl,
  minimum: () => Hu,
  mirrorPad: () => B2,
  mod: () => z2,
  moments: () => V2,
  movingAverage: () => V6,
  mul: () => se,
  multiRNNCell: () => W2,
  multinomial: () => U2,
  neg: () => pr,
  nextFrame: () => cS,
  node: () => EQt,
  norm: () => Vu,
  notEqual: () => Fd,
  oneHot: () => El,
  ones: () => Da,
  onesLike: () => G2,
  op: () => N,
  outerProduct: () => H2,
  pad: () => Aa,
  pad1d: () => K2,
  pad2d: () => q2,
  pad3d: () => j2,
  pad4d: () => X2,
  pool: () => Y2,
  pow: () => ui,
  prelu: () => Od,
  print: () => ld,
  prod: () => Q2,
  profile: () => Cme,
  raggedGather: () => Z2,
  raggedRange: () => J2,
  raggedTensorToTensor: () => e1,
  rand: () => t1,
  randomGamma: () => S1,
  randomNormal: () => Wd,
  randomStandardNormal: () => I1,
  randomUniform: () => ic,
  randomUniformInt: () => v1,
  range: () => cu,
  ready: () => Ime,
  real: () => ci,
  reciprocal: () => k1,
  registerBackend: () => tu,
  registerGradient: () => ole,
  registerKernel: () => ti,
  registerOp: () => z5,
  relu: () => lu,
  relu6: () => Ud,
  removeBackend: () => vme,
  reshape: () => W,
  reverse: () => mo,
  reverse1d: () => N1,
  reverse2d: () => T1,
  reverse3d: () => _1,
  reverse4d: () => E1,
  rfft: () => pc,
  round: () => Gd,
  rsqrt: () => $1,
  scalar: () => ke,
  scatterND: () => U6,
  scatter_util: () => du,
  searchSorted: () => _l,
  selu: () => R1,
  separableConv2d: () => D1,
  serialization: () => jN,
  setBackend: () => Sme,
  setPlatform: () => Tme,
  setThreadsCount: () => sae,
  setWasmPath: () => oae,
  setWasmPaths: () => nae,
  setWebGLContext: () => NI,
  setdiff1dAsync: () => A1,
  shared: () => Ic,
  sigmoid: () => Ea,
  sign: () => F1,
  signal: () => Jj,
  sin: () => P1,
  sinh: () => O1,
  slice: () => Xe,
  slice1d: () => M1,
  slice2d: () => L1,
  slice3d: () => B1,
  slice4d: () => z1,
  slice_util: () => pt,
  softmax: () => V1,
  softplus: () => Td,
  spaceToBatchND: () => Pd,
  sparse: () => oX,
  sparseToDense: () => K6,
  spectral: () => Zj,
  split: () => li,
  sqrt: () => Rr,
  square: () => Zt,
  squaredDifference: () => Kd,
  squeeze: () => cc,
  stack: () => vr,
  step: () => qd,
  stridedSlice: () => W1,
  string: () => nX,
  sub: () => Te,
  sum: () => ot,
  sumOutType: () => oi,
  tan: () => U1,
  tanh: () => kl,
  tensor: () => ar,
  tensor1d: () => Jt,
  tensor2d: () => mu,
  tensor3d: () => jd,
  tensor4d: () => G1,
  tensor5d: () => H1,
  tensor6d: () => K1,
  tensorScatterUpdate: () => j1,
  tensor_util: () => rk,
  test_util: () => w1,
  tidy: () => De,
  tile: () => uu,
  time: () => wme,
  topk: () => X1,
  train: () => OGe,
  transpose: () => mc,
  truncatedNormal: () => Y1,
  unique: () => Q1,
  unregisterGradient: () => sle,
  unregisterKernel: () => nle,
  unsortedSegmentSum: () => Z1,
  unstack: () => fo,
  upcastType: () => dt,
  upperBound: () => J1,
  util: () => y,
  valueAndGrad: () => UK,
  valueAndGrads: () => GK,
  variable: () => eN,
  variableGrads: () => Vw,
  version: () => Vce,
  version_converter: () => z8,
  version_core: () => OX,
  version_cpu: () => yY,
  version_wasm: () => iae,
  version_webgl: () => d9,
  webgl: () => $at,
  webgl_util: () => Ec,
  webgpu_util: () => Zv,
  where: () => lo,
  whereAsync: () => Yd,
  zeros: () => Gr,
  zerosLike: () => Gt
});
var _G = Object.create;
var QC = Object.defineProperty;
var EG = Object.getOwnPropertyDescriptor;
var $G = Object.getOwnPropertyNames;
var RG = Object.getPrototypeOf;
var DG = Object.prototype.hasOwnProperty;
var Kt = (r15, e) => () => (e || r15((e = { exports: {} }).exports, e), e.exports);
var qe = (r15, e) => {
  for (var t10 in e) QC(r15, t10, { get: e[t10], enumerable: true });
};
var AG = (r15, e, t10, o) => {
  if (e && typeof e == "object" || typeof e == "function") for (let n of $G(e)) !DG.call(r15, n) && n !== t10 && QC(r15, n, { get: () => e[n], enumerable: !(o = EG(e, n)) || o.enumerable });
  return r15;
};
var zp = (r15, e, t10) => (t10 = r15 != null ? _G(RG(r15)) : {}, AG(e || !r15 || !r15.__esModule ? QC(t10, "default", { value: r15, enumerable: true }) : t10, r15));
var U0 = Kt((ple, W0) => {
  W0.exports = kt;
  var ko = null;
  try {
    ko = 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 (r15) {
  }
  function kt(r15, e, t10) {
    this.low = r15 | 0, this.high = e | 0, this.unsigned = !!t10;
  }
  kt.prototype.__isLong__;
  Object.defineProperty(kt.prototype, "__isLong__", { value: true });
  function Wr(r15) {
    return (r15 && r15.__isLong__) === true;
  }
  kt.isLong = Wr;
  var A0 = {}, F0 = {};
  function Fu(r15, e) {
    var t10, o, n;
    return e ? (r15 >>>= 0, (n = 0 <= r15 && r15 < 256) && (o = F0[r15], o) ? o : (t10 = Nt(r15, (r15 | 0) < 0 ? -1 : 0, true), n && (F0[r15] = t10), t10)) : (r15 |= 0, (n = -128 <= r15 && r15 < 128) && (o = A0[r15], o) ? o : (t10 = Nt(r15, r15 < 0 ? -1 : 0, false), n && (A0[r15] = t10), t10));
  }
  kt.fromInt = Fu;
  function No(r15, e) {
    if (isNaN(r15)) return e ? Au : To;
    if (e) {
      if (r15 < 0) return Au;
      if (r15 >= L0) return V0;
    } else {
      if (r15 <= -O0) return Vr;
      if (r15 + 1 >= O0) return z0;
    }
    return r15 < 0 ? No(-r15, e).neg() : Nt(r15 % Qp | 0, r15 / Qp | 0, e);
  }
  kt.fromNumber = No;
  function Nt(r15, e, t10) {
    return new kt(r15, e, t10);
  }
  kt.fromBits = Nt;
  var Zm = Math.pow;
  function cw(r15, e, t10) {
    if (r15.length === 0) throw Error("empty string");
    if (r15 === "NaN" || r15 === "Infinity" || r15 === "+Infinity" || r15 === "-Infinity") return To;
    if (typeof e == "number" ? (t10 = e, e = false) : e = !!e, t10 = t10 || 10, t10 < 2 || 36 < t10) throw RangeError("radix");
    var o;
    if ((o = r15.indexOf("-")) > 0) throw Error("interior hyphen");
    if (o === 0) return cw(r15.substring(1), e, t10).neg();
    for (var n = No(Zm(t10, 8)), s = To, a = 0; a < r15.length; a += 8) {
      var i = Math.min(8, r15.length - a), p = parseInt(r15.substring(a, a + i), t10);
      if (i < 8) {
        var u = No(Zm(t10, i));
        s = s.mul(u).add(No(p));
      } else s = s.mul(n), s = s.add(No(p));
    }
    return s.unsigned = e, s;
  }
  kt.fromString = cw;
  function As(r15, e) {
    return typeof r15 == "number" ? No(r15, e) : typeof r15 == "string" ? cw(r15, e) : Nt(r15.low, r15.high, typeof e == "boolean" ? e : r15.unsigned);
  }
  kt.fromValue = As;
  var P0 = 65536, r42 = 1 << 24, Qp = P0 * P0, L0 = Qp * Qp, O0 = L0 / 2, M0 = Fu(r42), To = Fu(0);
  kt.ZERO = To;
  var Au = Fu(0, true);
  kt.UZERO = Au;
  var Yp = Fu(1);
  kt.ONE = Yp;
  var B0 = Fu(1, true);
  kt.UONE = B0;
  var pw = Fu(-1);
  kt.NEG_ONE = pw;
  var z0 = Nt(-1, 2147483647, false);
  kt.MAX_VALUE = z0;
  var V0 = Nt(-1, -1, true);
  kt.MAX_UNSIGNED_VALUE = V0;
  var Vr = Nt(0, -2147483648, false);
  kt.MIN_VALUE = Vr;
  var de = kt.prototype;
  de.toInt = function() {
    return this.unsigned ? this.low >>> 0 : this.low;
  };
  de.toNumber = function() {
    return this.unsigned ? (this.high >>> 0) * Qp + (this.low >>> 0) : this.high * Qp + (this.low >>> 0);
  };
  de.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(Vr)) {
      var t10 = No(e), o = this.div(t10), n = o.mul(t10).sub(this);
      return o.toString(e) + n.toInt().toString(e);
    } else return "-" + this.neg().toString(e);
    for (var s = No(Zm(e, 6), this.unsigned), a = this, i = ""; ; ) {
      var p = a.div(s), u = a.sub(p.mul(s)).toInt() >>> 0, c = u.toString(e);
      if (a = p, a.isZero()) return c + i;
      for (; c.length < 6; ) c = "0" + c;
      i = "" + c + i;
    }
  };
  de.getHighBits = function() {
    return this.high;
  };
  de.getHighBitsUnsigned = function() {
    return this.high >>> 0;
  };
  de.getLowBits = function() {
    return this.low;
  };
  de.getLowBitsUnsigned = function() {
    return this.low >>> 0;
  };
  de.getNumBitsAbs = function() {
    if (this.isNegative()) return this.eq(Vr) ? 64 : this.neg().getNumBitsAbs();
    for (var e = this.high != 0 ? this.high : this.low, t10 = 31; t10 > 0 && (e & 1 << t10) == 0; t10--) ;
    return this.high != 0 ? t10 + 33 : t10 + 1;
  };
  de.isZero = function() {
    return this.high === 0 && this.low === 0;
  };
  de.eqz = de.isZero;
  de.isNegative = function() {
    return !this.unsigned && this.high < 0;
  };
  de.isPositive = function() {
    return this.unsigned || this.high >= 0;
  };
  de.isOdd = function() {
    return (this.low & 1) === 1;
  };
  de.isEven = function() {
    return (this.low & 1) === 0;
  };
  de.equals = function(e) {
    return Wr(e) || (e = As(e)), this.unsigned !== e.unsigned && this.high >>> 31 === 1 && e.high >>> 31 === 1 ? false : this.high === e.high && this.low === e.low;
  };
  de.eq = de.equals;
  de.notEquals = function(e) {
    return !this.eq(e);
  };
  de.neq = de.notEquals;
  de.ne = de.notEquals;
  de.lessThan = function(e) {
    return this.comp(e) < 0;
  };
  de.lt = de.lessThan;
  de.lessThanOrEqual = function(e) {
    return this.comp(e) <= 0;
  };
  de.lte = de.lessThanOrEqual;
  de.le = de.lessThanOrEqual;
  de.greaterThan = function(e) {
    return this.comp(e) > 0;
  };
  de.gt = de.greaterThan;
  de.greaterThanOrEqual = function(e) {
    return this.comp(e) >= 0;
  };
  de.gte = de.greaterThanOrEqual;
  de.ge = de.greaterThanOrEqual;
  de.compare = function(e) {
    if (Wr(e) || (e = As(e)), this.eq(e)) return 0;
    var t10 = this.isNegative(), o = e.isNegative();
    return t10 && !o ? -1 : !t10 && o ? 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;
  };
  de.comp = de.compare;
  de.negate = function() {
    return !this.unsigned && this.eq(Vr) ? Vr : this.not().add(Yp);
  };
  de.neg = de.negate;
  de.add = function(e) {
    Wr(e) || (e = As(e));
    var t10 = this.high >>> 16, o = this.high & 65535, n = this.low >>> 16, s = this.low & 65535, a = e.high >>> 16, i = e.high & 65535, p = e.low >>> 16, u = e.low & 65535, c = 0, l = 0, m = 0, d = 0;
    return d += s + u, m += d >>> 16, d &= 65535, m += n + p, l += m >>> 16, m &= 65535, l += o + i, c += l >>> 16, l &= 65535, c += t10 + a, c &= 65535, Nt(m << 16 | d, c << 16 | l, this.unsigned);
  };
  de.subtract = function(e) {
    return Wr(e) || (e = As(e)), this.add(e.neg());
  };
  de.sub = de.subtract;
  de.multiply = function(e) {
    if (this.isZero()) return To;
    if (Wr(e) || (e = As(e)), ko) {
      var t10 = ko.mul(this.low, this.high, e.low, e.high);
      return Nt(t10, ko.get_high(), this.unsigned);
    }
    if (e.isZero()) return To;
    if (this.eq(Vr)) return e.isOdd() ? Vr : To;
    if (e.eq(Vr)) return this.isOdd() ? Vr : To;
    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(M0) && e.lt(M0)) return No(this.toNumber() * e.toNumber(), this.unsigned);
    var o = this.high >>> 16, n = this.high & 65535, s = this.low >>> 16, a = this.low & 65535, i = e.high >>> 16, p = e.high & 65535, u = e.low >>> 16, c = e.low & 65535, l = 0, m = 0, d = 0, f = 0;
    return f += a * c, d += f >>> 16, f &= 65535, d += s * c, m += d >>> 16, d &= 65535, d += a * u, m += d >>> 16, d &= 65535, m += n * c, l += m >>> 16, m &= 65535, m += s * u, l += m >>> 16, m &= 65535, m += a * p, l += m >>> 16, m &= 65535, l += o * c + n * u + s * p + a * i, l &= 65535, Nt(d << 16 | f, l << 16 | m, this.unsigned);
  };
  de.mul = de.multiply;
  de.divide = function(e) {
    if (Wr(e) || (e = As(e)), e.isZero()) throw Error("division by zero");
    if (ko) {
      if (!this.unsigned && this.high === -2147483648 && e.low === -1 && e.high === -1) return this;
      var t10 = (this.unsigned ? ko.div_u : ko.div_s)(this.low, this.high, e.low, e.high);
      return Nt(t10, ko.get_high(), this.unsigned);
    }
    if (this.isZero()) return this.unsigned ? Au : To;
    var o, n, s;
    if (this.unsigned) {
      if (e.unsigned || (e = e.toUnsigned()), e.gt(this)) return Au;
      if (e.gt(this.shru(1))) return B0;
      s = Au;
    } else {
      if (this.eq(Vr)) {
        if (e.eq(Yp) || e.eq(pw)) return Vr;
        if (e.eq(Vr)) return Yp;
        var a = this.shr(1);
        return o = a.div(e).shl(1), o.eq(To) ? e.isNegative() ? Yp : pw : (n = this.sub(e.mul(o)), s = o.add(n.div(e)), s);
      } else if (e.eq(Vr)) return this.unsigned ? Au : To;
      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 = To;
    }
    for (n = this; n.gte(e); ) {
      o = Math.max(1, Math.floor(n.toNumber() / e.toNumber()));
      for (var i = Math.ceil(Math.log(o) / Math.LN2), p = i <= 48 ? 1 : Zm(2, i - 48), u = No(o), c = u.mul(e); c.isNegative() || c.gt(n); ) o -= p, u = No(o, this.unsigned), c = u.mul(e);
      u.isZero() && (u = Yp), s = s.add(u), n = n.sub(c);
    }
    return s;
  };
  de.div = de.divide;
  de.modulo = function(e) {
    if (Wr(e) || (e = As(e)), ko) {
      var t10 = (this.unsigned ? ko.rem_u : ko.rem_s)(this.low, this.high, e.low, e.high);
      return Nt(t10, ko.get_high(), this.unsigned);
    }
    return this.sub(this.div(e).mul(e));
  };
  de.mod = de.modulo;
  de.rem = de.modulo;
  de.not = function() {
    return Nt(~this.low, ~this.high, this.unsigned);
  };
  de.and = function(e) {
    return Wr(e) || (e = As(e)), Nt(this.low & e.low, this.high & e.high, this.unsigned);
  };
  de.or = function(e) {
    return Wr(e) || (e = As(e)), Nt(this.low | e.low, this.high | e.high, this.unsigned);
  };
  de.xor = function(e) {
    return Wr(e) || (e = As(e)), Nt(this.low ^ e.low, this.high ^ e.high, this.unsigned);
  };
  de.shiftLeft = function(e) {
    return Wr(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e < 32 ? Nt(this.low << e, this.high << e | this.low >>> 32 - e, this.unsigned) : Nt(0, this.low << e - 32, this.unsigned);
  };
  de.shl = de.shiftLeft;
  de.shiftRight = function(e) {
    return Wr(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e < 32 ? Nt(this.low >>> e | this.high << 32 - e, this.high >> e, this.unsigned) : Nt(this.high >> e - 32, this.high >= 0 ? 0 : -1, this.unsigned);
  };
  de.shr = de.shiftRight;
  de.shiftRightUnsigned = function(e) {
    if (Wr(e) && (e = e.toInt()), e &= 63, e === 0) return this;
    var t10 = this.high;
    if (e < 32) {
      var o = this.low;
      return Nt(o >>> e | t10 << 32 - e, t10 >>> e, this.unsigned);
    } else return e === 32 ? Nt(t10, 0, this.unsigned) : Nt(t10 >>> e - 32, 0, this.unsigned);
  };
  de.shru = de.shiftRightUnsigned;
  de.shr_u = de.shiftRightUnsigned;
  de.toSigned = function() {
    return this.unsigned ? Nt(this.low, this.high, false) : this;
  };
  de.toUnsigned = function() {
    return this.unsigned ? this : Nt(this.low, this.high, true);
  };
  de.toBytes = function(e) {
    return e ? this.toBytesLE() : this.toBytesBE();
  };
  de.toBytesLE = function() {
    var e = this.high, t10 = this.low;
    return [t10 & 255, t10 >>> 8 & 255, t10 >>> 16 & 255, t10 >>> 24, e & 255, e >>> 8 & 255, e >>> 16 & 255, e >>> 24];
  };
  de.toBytesBE = function() {
    var e = this.high, t10 = this.low;
    return [e >>> 24, e >>> 16 & 255, e >>> 8 & 255, e & 255, t10 >>> 24, t10 >>> 16 & 255, t10 >>> 8 & 255, t10 & 255];
  };
  kt.fromBytes = function(e, t10, o) {
    return o ? kt.fromBytesLE(e, t10) : kt.fromBytesBE(e, t10);
  };
  kt.fromBytesLE = function(e, t10) {
    return new kt(e[0] | e[1] << 8 | e[2] << 16 | e[3] << 24, e[4] | e[5] << 8 | e[6] << 16 | e[7] << 24, t10);
  };
  kt.fromBytesBE = function(e, t10) {
    return new kt(e[4] << 24 | e[5] << 16 | e[6] << 8 | e[7], e[0] << 24 | e[1] << 16 | e[2] << 8 | e[3], t10);
  };
});
var Ek = Kt(() => {
});
var $k = Kt(() => {
});
var o1 = Kt((r1, Ww) => {
  (function(r15, e, t10) {
    function o(i) {
      var p = this, u = a();
      p.next = function() {
        var c = 2091639 * p.s0 + p.c * 23283064365386963e-26;
        return p.s0 = p.s1, p.s1 = p.s2, p.s2 = c - (p.c = c | 0);
      }, p.c = 1, p.s0 = u(" "), p.s1 = u(" "), p.s2 = u(" "), p.s0 -= u(i), p.s0 < 0 && (p.s0 += 1), p.s1 -= u(i), p.s1 < 0 && (p.s1 += 1), p.s2 -= u(i), p.s2 < 0 && (p.s2 += 1), u = null;
    }
    function n(i, p) {
      return p.c = i.c, p.s0 = i.s0, p.s1 = i.s1, p.s2 = i.s2, p;
    }
    function s(i, p) {
      var u = new o(i), c = p && p.state, l = u.next;
      return l.int32 = function() {
        return u.next() * 4294967296 | 0;
      }, l.double = function() {
        return l() + (l() * 2097152 | 0) * 11102230246251565e-32;
      }, l.quick = l, c && (typeof c == "object" && n(c, u), l.state = function() {
        return n(u, {});
      }), l;
    }
    function a() {
      var i = 4022871197, p = function(u) {
        u = String(u);
        for (var c = 0; c < u.length; c++) {
          i += u.charCodeAt(c);
          var l = 0.02519603282416938 * i;
          i = l >>> 0, l -= i, l *= i, i = l >>> 0, l -= i, i += l * 4294967296;
        }
        return (i >>> 0) * 23283064365386963e-26;
      };
      return p;
    }
    e && e.exports ? e.exports = s : t10 && t10.amd ? t10(function() {
      return s;
    }) : this.alea = s;
  })(r1, typeof Ww == "object" && Ww, typeof define == "function" && define);
});
var s1 = Kt((n1, Uw) => {
  (function(r15, e, t10) {
    function o(a) {
      var i = this, p = "";
      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 : p += a;
      for (var u = 0; u < p.length + 64; u++) i.x ^= p.charCodeAt(u) | 0, i.next();
    }
    function n(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 p = new o(a), u = i && i.state, c = function() {
        return (p.next() >>> 0) / 4294967296;
      };
      return c.double = function() {
        do
          var l = p.next() >>> 11, m = (p.next() >>> 0) / 4294967296, d = (l + m) / (1 << 21);
        while (d === 0);
        return d;
      }, c.int32 = p.next, c.quick = c, u && (typeof u == "object" && n(u, p), c.state = function() {
        return n(p, {});
      }), c;
    }
    e && e.exports ? e.exports = s : t10 && t10.amd ? t10(function() {
      return s;
    }) : this.xor128 = s;
  })(n1, typeof Uw == "object" && Uw, typeof define == "function" && define);
});
var i1 = Kt((a1, Gw) => {
  (function(r15, e, t10) {
    function o(a) {
      var i = this, p = "";
      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 : p += a;
      for (var u = 0; u < p.length + 64; u++) i.x ^= p.charCodeAt(u) | 0, u == p.length && (i.d = i.x << 10 ^ i.x >>> 4), i.next();
    }
    function n(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 p = new o(a), u = i && i.state, c = function() {
        return (p.next() >>> 0) / 4294967296;
      };
      return c.double = function() {
        do
          var l = p.next() >>> 11, m = (p.next() >>> 0) / 4294967296, d = (l + m) / (1 << 21);
        while (d === 0);
        return d;
      }, c.int32 = p.next, c.quick = c, u && (typeof u == "object" && n(u, p), c.state = function() {
        return n(p, {});
      }), c;
    }
    e && e.exports ? e.exports = s : t10 && t10.amd ? t10(function() {
      return s;
    }) : this.xorwow = s;
  })(a1, typeof Gw == "object" && Gw, typeof define == "function" && define);
});
var p1 = Kt((u1, Hw) => {
  (function(r15, e, t10) {
    function o(a) {
      var i = this;
      i.next = function() {
        var u = i.x, c = i.i, l, m, d;
        return l = u[c], l ^= l >>> 7, m = l ^ l << 24, l = u[c + 1 & 7], m ^= l ^ l >>> 10, l = u[c + 3 & 7], m ^= l ^ l >>> 3, l = u[c + 4 & 7], m ^= l ^ l << 7, l = u[c + 7 & 7], l = l ^ l << 13, m ^= l ^ l << 9, u[c] = m, i.i = c + 1 & 7, m;
      };
      function p(u, c) {
        var l, m, d = [];
        if (c === (c | 0)) m = d[0] = c;
        else for (c = "" + c, l = 0; l < c.length; ++l) d[l & 7] = d[l & 7] << 15 ^ c.charCodeAt(l) + d[l + 1 & 7] << 13;
        for (; d.length < 8; ) d.push(0);
        for (l = 0; l < 8 && d[l] === 0; ++l) ;
        for (l == 8 ? m = d[7] = -1 : m = d[l], u.x = d, u.i = 0, l = 256; l > 0; --l) u.next();
      }
      p(i, a);
    }
    function n(a, i) {
      return i.x = a.x.slice(), i.i = a.i, i;
    }
    function s(a, i) {
      a == null && (a = +/* @__PURE__ */ new Date());
      var p = new o(a), u = i && i.state, c = function() {
        return (p.next() >>> 0) / 4294967296;
      };
      return c.double = function() {
        do
          var l = p.next() >>> 11, m = (p.next() >>> 0) / 4294967296, d = (l + m) / (1 << 21);
        while (d === 0);
        return d;
      }, c.int32 = p.next, c.quick = c, u && (u.x && n(u, p), c.state = function() {
        return n(p, {});
      }), c;
    }
    e && e.exports ? e.exports = s : t10 && t10.amd ? t10(function() {
      return s;
    }) : this.xorshift7 = s;
  })(u1, typeof Hw == "object" && Hw, typeof define == "function" && define);
});
var l1 = Kt((c1, Kw) => {
  (function(r15, e, t10) {
    function o(a) {
      var i = this;
      i.next = function() {
        var u = i.w, c = i.X, l = i.i, m, d;
        return i.w = u = u + 1640531527 | 0, d = c[l + 34 & 127], m = c[l = l + 1 & 127], d ^= d << 13, m ^= m << 17, d ^= d >>> 15, m ^= m >>> 12, d = c[l] = d ^ m, i.i = l, d + (u ^ u >>> 16) | 0;
      };
      function p(u, c) {
        var l, m, d, f, h, g = [], x = 128;
        for (c === (c | 0) ? (m = c, c = null) : (c = c + "\0", m = 0, x = Math.max(x, c.length)), d = 0, f = -32; f < x; ++f) c && (m ^= c.charCodeAt((f + 32) % c.length)), f === 0 && (h = m), m ^= m << 10, m ^= m >>> 15, m ^= m << 4, m ^= m >>> 13, f >= 0 && (h = h + 1640531527 | 0, l = g[f & 127] ^= m + h, d = l == 0 ? d + 1 : 0);
        for (d >= 128 && (g[(c && c.length || 0) & 127] = -1), d = 127, f = 512; f > 0; --f) m = g[d + 34 & 127], l = g[d = d + 1 & 127], m ^= m << 13, l ^= l << 17, m ^= m >>> 15, l ^= l >>> 12, g[d] = m ^ l;
        u.w = h, u.X = g, u.i = d;
      }
      p(i, a);
    }
    function n(a, i) {
      return i.i = a.i, i.w = a.w, i.X = a.X.slice(), i;
    }
    function s(a, i) {
      a == null && (a = +/* @__PURE__ */ new Date());
      var p = new o(a), u = i && i.state, c = function() {
        return (p.next() >>> 0) / 4294967296;
      };
      return c.double = function() {
        do
          var l = p.next() >>> 11, m = (p.next() >>> 0) / 4294967296, d = (l + m) / (1 << 21);
        while (d === 0);
        return d;
      }, c.int32 = p.next, c.quick = c, u && (u.X && n(u, p), c.state = function() {
        return n(p, {});
      }), c;
    }
    e && e.exports ? e.exports = s : t10 && t10.amd ? t10(function() {
      return s;
    }) : this.xor4096 = s;
  })(c1, typeof Kw == "object" && Kw, typeof define == "function" && define);
});
var d1 = Kt((m1, qw) => {
  (function(r15, e, t10) {
    function o(a) {
      var i = this, p = "";
      i.next = function() {
        var c = i.b, l = i.c, m = i.d, d = i.a;
        return c = c << 25 ^ c >>> 7 ^ l, l = l - m | 0, m = m << 24 ^ m >>> 8 ^ d, d = d - c | 0, i.b = c = c << 20 ^ c >>> 12 ^ l, i.c = l = l - m | 0, i.d = m << 16 ^ l >>> 16 ^ d, i.a = d - c | 0;
      }, i.a = 0, i.b = 0, i.c = -1640531527, i.d = 1367130551, a === Math.floor(a) ? (i.a = a / 4294967296 | 0, i.b = a | 0) : p += a;
      for (var u = 0; u < p.length + 20; u++) i.b ^= p.charCodeAt(u) | 0, i.next();
    }
    function n(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 p = new o(a), u = i && i.state, c = function() {
        return (p.next() >>> 0) / 4294967296;
      };
      return c.double = function() {
        do
          var l = p.next() >>> 11, m = (p.next() >>> 0) / 4294967296, d = (l + m) / (1 << 21);
        while (d === 0);
        return d;
      }, c.int32 = p.next, c.quick = c, u && (typeof u == "object" && n(u, p), c.state = function() {
        return n(p, {});
      }), c;
    }
    e && e.exports ? e.exports = s : t10 && t10.amd ? t10(function() {
      return s;
    }) : this.tychei = s;
  })(m1, typeof qw == "object" && qw, typeof define == "function" && define);
});
var f1 = Kt(() => {
});
var g1 = Kt((h1, Md) => {
  (function(r15, e, t10) {
    var o = 256, n = 6, s = 52, a = "random", i = t10.pow(o, n), p = t10.pow(2, s), u = p * 2, c = o - 1, l;
    function m(C, S, k) {
      var _ = [];
      S = S == true ? { entropy: true } : S || {};
      var $ = g(h(S.entropy ? [C, b(e)] : C == null ? x() : C, 3), _), R = new d(_), D = function() {
        for (var P = R.g(n), O = i, M = 0; P < p; ) P = (P + M) * o, O *= o, M = R.g(1);
        for (; P >= u; ) P /= 2, O /= 2, M >>>= 1;
        return (P + M) / O;
      };
      return D.int32 = function() {
        return R.g(4) | 0;
      }, D.quick = function() {
        return R.g(4) / 4294967296;
      }, D.double = D, g(b(R.S), e), (S.pass || k || function(P, O, M, L) {
        return L && (L.S && f(L, R), P.state = function() {
          return f(R, {});
        }), M ? (t10[a] = P, O) : P;
      })(D, $, "global" in S ? S.global : this == t10, S.state);
    }
    function d(C) {
      var S, k = C.length, _ = this, $ = 0, R = _.i = _.j = 0, D = _.S = [];
      for (k || (C = [k++]); $ < o; ) D[$] = $++;
      for ($ = 0; $ < o; $++) D[$] = D[R = c & R + C[$ % k] + (S = D[$])], D[R] = S;
      (_.g = function(P) {
        for (var O, M = 0, L = _.i, B = _.j, z = _.S; P--; ) O = z[L = c & L + 1], M = M * o + z[c & (z[L] = z[B = c & B + O]) + (z[B] = O)];
        return _.i = L, _.j = B, M;
      })(o);
    }
    function f(C, S) {
      return S.i = C.i, S.j = C.j, S.S = C.S.slice(), S;
    }
    function h(C, S) {
      var k = [], _ = typeof C, $;
      if (S && _ == "object") for ($ in C) try {
        k.push(h(C[$], S - 1));
      } catch (R) {
      }
      return k.length ? k : _ == "string" ? C : C + "\0";
    }
    function g(C, S) {
      for (var k = C + "", _, $ = 0; $ < k.length; ) S[c & $] = c & (_ ^= S[c & $] * 19) + k.charCodeAt($++);
      return b(S);
    }
    function x() {
      try {
        var C;
        return l && (C = l.randomBytes) ? C = C(o) : (C = new Uint8Array(o), (r15.crypto || r15.msCrypto).getRandomValues(C)), b(C);
      } catch (_) {
        var S = r15.navigator, k = S && S.plugins;
        return [+/* @__PURE__ */ new Date(), r15, k, r15.screen, b(e)];
      }
    }
    function b(C) {
      return String.fromCharCode.apply(0, C);
    }
    if (g(t10.random(), e), typeof Md == "object" && Md.exports) {
      Md.exports = m;
      try {
        l = f1();
      } catch (C) {
      }
    } else typeof define == "function" && define.amd ? define(function() {
      return m;
    }) : t10["seed" + a] = m;
  })(typeof self != "undefined" ? self : h1, [], Math);
});
var jw = Kt((s1e, x1) => {
  var Dq = o1(), Aq = s1(), Fq = i1(), Pq = p1(), Oq = l1(), Mq = d1(), Ku = g1();
  Ku.alea = Dq;
  Ku.xor128 = Aq;
  Ku.xorwow = Fq;
  Ku.xorshift7 = Pq;
  Ku.xor4096 = Oq;
  Ku.tychei = Mq;
  x1.exports = Ku;
});
var Vv = Kt(() => {
});
var Wv = Kt(() => {
});
var LB = Kt(() => {
});
var BB = Kt(() => {
});
var zB = Kt(() => {
});
var VB = Kt((Wg, Gv) => {
  var Uv = (() => {
    var r15 = typeof document != "undefined" && document.currentScript ? document.currentScript.src : void 0;
    return typeof __filename != "undefined" && (r15 = r15 || __filename), (function(e) {
      e = e || {};
      function t10() {
        return oe.buffer != He && Tt(oe.buffer), lt;
      }
      function o() {
        return oe.buffer != He && Tt(oe.buffer), it;
      }
      function n() {
        return oe.buffer != He && Tt(oe.buffer), ht;
      }
      function s() {
        return oe.buffer != He && Tt(oe.buffer), Lr;
      }
      function a() {
        return oe.buffer != He && Tt(oe.buffer), Mt;
      }
      function i() {
        return oe.buffer != He && Tt(oe.buffer), to;
      }
      function p() {
        return oe.buffer != He && Tt(oe.buffer), rr;
      }
      var u = typeof e != "undefined" ? e : {}, c, l;
      u.ready = new Promise(function(F, V) {
        c = F, l = V;
      });
      var m;
      typeof process != "undefined" && process.listeners && (m = { uncaughtException: process.listeners("uncaughtException"), unhandledRejection: process.listeners("unhandledRejection") });
      var d = Object.assign({}, u), f = [], h = "./this.program", g = (F, V) => {
        throw V;
      }, x = typeof window == "object", b = typeof importScripts == "function", C = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string", S = u.ENVIRONMENT_IS_PTHREAD || false, k = "";
      function _(F) {
        return u.locateFile ? u.locateFile(F, k) : k + F;
      }
      var $, R, D, P;
      function O(F) {
        if (F instanceof ku) return;
        j("exiting due to exception: " + F);
      }
      if (C) {
        var M = Vv(), L = Wv();
        b ? k = L.dirname(k) + "/" : k = __dirname + "/", $ = (V, ue) => (V = Fp(V) ? new URL(V) : L.normalize(V), M.readFileSync(V, ue ? void 0 : "utf8")), D = (V) => {
          var ue = $(V, true);
          return ue.buffer || (ue = new Uint8Array(ue)), ue;
        }, R = (V, ue, $e) => {
          V = Fp(V) ? new URL(V) : L.normalize(V), M.readFile(V, function(Be, Le) {
            Be ? $e(Be) : ue(Le.buffer);
          });
        }, process.argv.length > 1 && (h = process.argv[1].replace(/\\/g, "/")), f = process.argv.slice(2), process.on("uncaughtException", function(V) {
          if (!(V instanceof ku)) throw V;
        }), process.on("unhandledRejection", function(V) {
          throw V;
        }), g = (V, ue) => {
          if (Lo()) throw process.exitCode = V, ue;
          O(ue), process.exit(V);
        }, u.inspect = function() {
          return "[Emscripten Module object]";
        };
        let F;
        try {
          F = LB();
        } catch (V) {
          throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'), V;
        }
        global.Worker = F.Worker;
      } else (x || b) && (b ? k = self.location.href : typeof document != "undefined" && document.currentScript && (k = document.currentScript.src), typeof r15 != "undefined" && r15 && (k = r15), k.indexOf("blob:") !== 0 ? k = k.substr(0, k.replace(/[?#].*/, "").lastIndexOf("/") + 1) : k = "", C || ($ = (F) => {
        var V = new XMLHttpRequest();
        return V.open("GET", F, false), V.send(null), V.responseText;
      }, b && (D = (F) => {
        var V = new XMLHttpRequest();
        return V.open("GET", F, false), V.responseType = "arraybuffer", V.send(null), new Uint8Array(V.response);
      }), R = (F, V, ue) => {
        var $e = new XMLHttpRequest();
        $e.open("GET", F, true), $e.responseType = "arraybuffer", $e.onload = () => {
          if ($e.status == 200 || $e.status == 0 && $e.response) {
            V($e.response);
            return;
          }
          ue();
        }, $e.onerror = ue, $e.send(null);
      }), P = (F) => document.title = F);
      C && typeof performance == "undefined" && (global.performance = BB().performance);
      var B = console.log.bind(console), z = console.warn.bind(console);
      C && (B = (F) => M.writeSync(1, F + `
`), z = (F) => M.writeSync(2, F + `
`));
      var U = u.print || B, j = u.printErr || z;
      Object.assign(u, d), d = null, u.arguments && (f = u.arguments), u.thisProgram && (h = u.thisProgram), u.quit && (g = u.quit);
      var q = 4, Y = Atomics.load, J = Atomics.store, re = Atomics.compareExchange, ne;
      u.wasmBinary && (ne = u.wasmBinary);
      var ee = u.noExitRuntime || true;
      typeof WebAssembly != "object" && vu("no native wasm support detected");
      var oe, ie, le = false, be;
      function _e(F, V) {
        F || vu(V);
      }
      var ve = typeof TextDecoder != "undefined" ? new TextDecoder("utf8") : void 0;
      function Fe(F, V, ue) {
        V >>>= 0;
        for (var $e = V + ue, Be = V; F[Be] && !(Be >= $e); ) ++Be;
        if (Be - V > 16 && F.buffer && ve) return ve.decode(F.buffer instanceof SharedArrayBuffer ? F.slice(V, Be) : F.subarray(V, Be));
        for (var Le = ""; V < Be; ) {
          var ge = F[V++];
          if (!(ge & 128)) {
            Le += String.fromCharCode(ge);
            continue;
          }
          var Ne = F[V++] & 63;
          if ((ge & 224) == 192) {
            Le += String.fromCharCode((ge & 31) << 6 | Ne);
            continue;
          }
          var Ft = F[V++] & 63;
          if ((ge & 240) == 224 ? ge = (ge & 15) << 12 | Ne << 6 | Ft : ge = (ge & 7) << 18 | Ne << 12 | Ft << 6 | F[V++] & 63, ge < 65536) Le += String.fromCharCode(ge);
          else {
            var so = ge - 65536;
            Le += String.fromCharCode(55296 | so >> 10, 56320 | so & 1023);
          }
        }
        return Le;
      }
      function Pe(F, V) {
        return F >>>= 0, F ? Fe(o(), F, V) : "";
      }
      function st(F, V, ue, $e) {
        if (ue >>>= 0, !($e > 0)) return 0;
        for (var Be = ue, Le = ue + $e - 1, ge = 0; ge < F.length; ++ge) {
          var Ne = F.charCodeAt(ge);
          if (Ne >= 55296 && Ne <= 57343) {
            var Ft = F.charCodeAt(++ge);
            Ne = 65536 + ((Ne & 1023) << 10) | Ft & 1023;
          }
          if (Ne <= 127) {
            if (ue >= Le) break;
            V[ue++ >>> 0] = Ne;
          } else if (Ne <= 2047) {
            if (ue + 1 >= Le) break;
            V[ue++ >>> 0] = 192 | Ne >> 6, V[ue++ >>> 0] = 128 | Ne & 63;
          } else if (Ne <= 65535) {
            if (ue + 2 >= Le) break;
            V[ue++ >>> 0] = 224 | Ne >> 12, V[ue++ >>> 0] = 128 | Ne >> 6 & 63, V[ue++ >>> 0] = 128 | Ne & 63;
          } else {
            if (ue + 3 >= Le) break;
            V[ue++ >>> 0] = 240 | Ne >> 18, V[ue++ >>> 0] = 128 | Ne >> 12 & 63, V[ue++ >>> 0] = 128 | Ne >> 6 & 63, V[ue++ >>> 0] = 128 | Ne & 63;
          }
        }
        return V[ue >>> 0] = 0, ue - Be;
      }
      function ct(F, V, ue) {
        return st(F, o(), V, ue);
      }
      var He, lt, it, ht, gt, Lr, Mt, to, rr;
      S && (He = u.buffer);
      function Tt(F) {
        He = F, u.HEAP8 = lt = new Int8Array(F), u.HEAP16 = ht = new Int16Array(F), u.HEAP32 = Lr = new Int32Array(F), u.HEAPU8 = it = new Uint8Array(F), u.HEAPU16 = gt = new Uint16Array(F), u.HEAPU32 = Mt = new Uint32Array(F), u.HEAPF32 = to = new Float32Array(F), u.HEAPF64 = rr = new Float64Array(F);
      }
      var or = u.INITIAL_MEMORY || 16777216;
      if (S) oe = u.wasmMemory, He = u.buffer;
      else if (u.wasmMemory) oe = u.wasmMemory;
      else if (oe = new WebAssembly.Memory({ initial: or / 65536, maximum: 65536, shared: true }), !(oe.buffer instanceof SharedArrayBuffer)) throw j("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"), C && j("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"), Error("bad memory");
      oe && (He = oe.buffer), or = He.byteLength, Tt(He);
      var nr, ro = [], oo = [], fr = [], Va = false;
      function Lo() {
        return ee;
      }
      function Ks() {
        if (u.preRun) for (typeof u.preRun == "function" && (u.preRun = [u.preRun]); u.preRun.length; ) ol(u.preRun.shift());
        al(ro);
      }
      function Xt() {
        Va = true, !S && al(oo);
      }
      function Wa() {
        if (!S) {
          if (u.postRun) for (typeof u.postRun == "function" && (u.postRun = [u.postRun]); u.postRun.length; ) d0(u.postRun.shift());
          al(fr);
        }
      }
      function ol(F) {
        ro.unshift(F);
      }
      function nl(F) {
        oo.unshift(F);
      }
      function d0(F) {
        fr.unshift(F);
      }
      var ki = 0, Ap = null, Ua = null;
      function Cy(F) {
        ki++, u.monitorRunDependencies && u.monitorRunDependencies(ki);
      }
      function wm(F) {
        if (ki--, u.monitorRunDependencies && u.monitorRunDependencies(ki), ki == 0 && (Ap !== null && (clearInterval(Ap), Ap = null), Ua)) {
          var V = Ua;
          Ua = null, V();
        }
      }
      function vu(F) {
        u.onAbort && u.onAbort(F), F = "Aborted(" + F + ")", j(F), le = true, be = 1, F += ". Build with -sASSERTIONS for more info.";
        var V = new WebAssembly.RuntimeError(F);
        throw l(V), V;
      }
      var wy = "data:application/octet-stream;base64,";
      function Sm(F) {
        return F.startsWith(wy);
      }
      function Fp(F) {
        return F.startsWith("file://");
      }
      var hr;
      hr = "tfjs-backend-wasm-threaded-simd.wasm", Sm(hr) || (hr = _(hr));
      function Im(F) {
        try {
          if (F == hr && ne) return new Uint8Array(ne);
          if (D) return D(F);
          throw "both async and sync fetching of the wasm failed";
        } catch (V) {
          vu(V);
        }
      }
      function Sy() {
        if (!ne && (x || b)) {
          if (typeof fetch == "function" && !Fp(hr)) return fetch(hr, { credentials: "same-origin" }).then(function(F) {
            if (!F.ok) throw "failed to load wasm binary file at '" + hr + "'";
            return F.arrayBuffer();
          }).catch(function() {
            return Im(hr);
          });
          if (R) return new Promise(function(F, V) {
            R(hr, function(ue) {
              F(new Uint8Array(ue));
            }, V);
          });
        }
        return Promise.resolve().then(function() {
          return Im(hr);
        });
      }
      function Iy() {
        var F = { env: Om, wasi_snapshot_preview1: Om };
        function V(ge, Ne) {
          var Ft = ge.exports;
          if (u.asm = Ft, Dy(u.asm._emscripten_tls_init), nr = u.asm.__indirect_function_table, nl(u.asm.__wasm_call_ctors), ie = Ne, !S) {
            var so = Me.unusedWorkers.length;
            Me.unusedWorkers.forEach(function(Ha) {
              Me.loadWasmModuleToWorker(Ha, function() {
                --so || wm("wasm-instantiate");
              });
            });
          }
        }
        S || Cy("wasm-instantiate");
        function ue(ge) {
          V(ge.instance, ge.module);
        }
        function $e(ge) {
          return Sy().then(function(Ne) {
            return WebAssembly.instantiate(Ne, F);
          }).then(function(Ne) {
            return Ne;
          }).then(ge, function(Ne) {
            j("failed to asynchronously prepare wasm: " + Ne), vu(Ne);
          });
        }
        function Be() {
          return !ne && typeof WebAssembly.instantiateStreaming == "function" && !Sm(hr) && !Fp(hr) && !C && typeof fetch == "function" ? fetch(hr, { credentials: "same-origin" }).then(function(ge) {
            var Ne = WebAssembly.instantiateStreaming(ge, F);
            return Ne.then(ue, function(Ft) {
              return j("wasm streaming compile failed: " + Ft), j("falling back to ArrayBuffer instantiation"), $e(ue);
            });
          }) : $e(ue);
        }
        if (u.instantiateWasm) try {
          var Le = u.instantiateWasm(F, V);
          return Le;
        } catch (ge) {
          j("Module.instantiateWasm callback failed with error: " + ge), l(ge);
        }
        return Be().catch(l), {};
      }
      var f0, h0, vm = {};
      function ku(F) {
        this.name = "ExitStatus", this.message = "Program terminated with exit(" + F + ")", this.status = F;
      }
      function vy(F) {
        var V = Me.pthreads[F];
        delete Me.pthreads[F], V.terminate(), jC(F), Me.runningWorkers.splice(Me.runningWorkers.indexOf(V), 1), V.pthread_ptr = 0;
      }
      function ky(F) {
        var V = Me.pthreads[F];
        V.postMessage({ cmd: "cancel" });
      }
      function sl(F) {
        var V = Me.pthreads[F];
        _e(V), Me.returnWorkerToPool(V);
      }
      function Ny(F) {
        var V = Me.getNewWorker();
        if (!V) return 6;
        Me.runningWorkers.push(V), Me.pthreads[F.pthread_ptr] = V, V.pthread_ptr = F.pthread_ptr;
        var ue = { cmd: "run", start_routine: F.startRoutine, arg: F.arg, pthread_ptr: F.pthread_ptr };
        return V.runPthread = () => {
          C && V.ref(), V.postMessage(ue, F.transferList), delete V.runPthread;
        }, V.loaded && V.runPthread(), 0;
      }
      var km = { varargs: void 0, get: function() {
        km.varargs += 4;
        var F = s()[km.varargs - 4 >>> 2];
        return F;
      }, getStr: function(F) {
        var V = Pe(F);
        return V;
      } };
      function Nm(F) {
        if (S) return Ni(1, 1, F);
        be = F, Lo() || (Me.terminateAllThreads(), u.onExit && u.onExit(F), le = true), g(F, new ku(F));
      }
      function Ty(F, V) {
        if (be = F, !V && S) throw _m(F), "unwind";
        Nm(F);
      }
      var Tm = Ty;
      function _y(F) {
        if (F instanceof ku || F == "unwind") return be;
        g(1, F);
      }
      var Me = { unusedWorkers: [], runningWorkers: [], tlsInitFunctions: [], pthreads: {}, init: function() {
        S ? Me.initWorker() : Me.initMainThread();
      }, initMainThread: function() {
        for (var F = 8; F--; ) Me.allocateUnusedWorker();
      }, initWorker: function() {
        ee = false;
      }, setExitStatus: function(F) {
        be = F;
      }, terminateAllThreads: function() {
        for (var F of Object.values(Me.pthreads)) Me.returnWorkerToPool(F);
        for (var F of Me.unusedWorkers) F.terminate();
        Me.unusedWorkers = [];
      }, returnWorkerToPool: function(F) {
        var V = F.pthread_ptr;
        delete Me.pthreads[V], Me.unusedWorkers.push(F), Me.runningWorkers.splice(Me.runningWorkers.indexOf(F), 1), F.pthread_ptr = 0, C && F.unref(), jC(V);
      }, receiveObjectTransfer: function(F) {
      }, threadInitTLS: function() {
        Me.tlsInitFunctions.forEach((F) => F());
      }, loadWasmModuleToWorker: function(F, V) {
        F.onmessage = (Le) => {
          var ge = Le.data, Ne = ge.cmd;
          if (F.pthread_ptr && (Me.currentProxiedOperationCallerThread = F.pthread_ptr), ge.targetThread && ge.targetThread != Wm()) {
            var Ft = Me.pthreads[ge.targetThread];
            Ft ? Ft.postMessage(ge, ge.transferList) : j('Internal error! Worker sent a message "' + Ne + '" to target pthread ' + ge.targetThread + ", but that thread no longer exists!"), Me.currentProxiedOperationCallerThread = void 0;
            return;
          }
          Ne === "processProxyingQueue" ? il(ge.queue) : Ne === "spawnThread" ? Ny(ge) : Ne === "cleanupThread" ? sl(ge.thread) : Ne === "killThread" ? vy(ge.thread) : Ne === "cancelThread" ? ky(ge.thread) : Ne === "loaded" ? (F.loaded = true, C && F.unref(), V && V(F), F.runPthread && F.runPthread()) : Ne === "print" ? U("Thread " + ge.threadId + ": " + ge.text) : Ne === "printErr" ? j("Thread " + ge.threadId + ": " + ge.text) : Ne === "alert" ? alert("Thread " + ge.threadId + ": " + ge.text) : ge.target === "setimmediate" ? F.postMessage(ge) : Ne === "callHandler" ? u[ge.handler](...ge.args) : Ne && j("worker sent an unknown command " + Ne), Me.currentProxiedOperationCallerThread = void 0;
        }, F.onerror = (Le) => {
          var ge = "worker sent an error!";
          throw j(ge + " " + Le.filename + ":" + Le.lineno + ": " + Le.message), Le;
        }, C && (F.on("message", function(Le) {
          F.onmessage({ data: Le });
        }), F.on("error", function(Le) {
          F.onerror(Le);
        }), F.on("detachedExit", function() {
        }));
        var ue = [], $e = ["onExit", "onAbort", "print", "printErr"];
        for (var Be of $e) u.hasOwnProperty(Be) && ue.push(Be);
        F.postMessage({ cmd: "load", handlers: ue, urlOrBlob: u.mainScriptUrlOrBlob || r15, wasmMemory: oe, wasmModule: ie });
      }, allocateUnusedWorker: function() {
        var F, V = _("tfjs-backend-wasm-threaded-simd.worker.js");
        F = new Worker(V), Me.unusedWorkers.push(F);
      }, getNewWorker: function() {
        return Me.unusedWorkers.length == 0 && (Me.allocateUnusedWorker(), Me.loadWasmModuleToWorker(Me.unusedWorkers[0])), Me.unusedWorkers.pop();
      } };
      u.PThread = Me;
      function al(F) {
        for (; F.length > 0; ) F.shift()(u);
      }
      function Ey() {
        var F = Wm(), V = s()[F + 52 >>> 2], ue = s()[F + 56 >>> 2], $e = V - ue;
        w0(V, $e), Um(V);
      }
      u.establishStackSpace = Ey;
      function _m(F) {
        if (S) return Ni(2, 0, F);
        try {
          Tm(F);
        } catch (V) {
          _y(V);
        }
      }
      var Pp = [];
      function $y(F) {
        var V = Pp[F];
        return V || (F >= Pp.length && (Pp.length = F + 1), Pp[F] = V = nr.get(F)), V;
      }
      function Ry(F, V) {
        var ue = $y(F)(V);
        Lo() ? Me.setExitStatus(ue) : C0(ue);
      }
      u.invokeEntryPoint = Ry;
      function Dy(F) {
        Me.tlsInitFunctions.push(F);
      }
      function Ay(F) {
        x0(F, !b, 1, !x), Me.threadInitTLS();
      }
      function Fy(F) {
        S ? postMessage({ cmd: "cleanupThread", thread: F }) : sl(F);
      }
      function Em(F, V, ue, $e) {
        return S ? Ni(3, 1, F, V, ue, $e) : $m(F, V, ue, $e);
      }
      function $m(F, V, ue, $e) {
        if (typeof SharedArrayBuffer == "undefined") return j("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6;
        var Be = [], Le = 0;
        if (S && (Be.length === 0 || Le)) return Em(F, V, ue, $e);
        if (Le) return Le;
        var ge = { startRoutine: ue, pthread_ptr: F, arg: $e, transferList: Be };
        return S ? (ge.cmd = "spawnThread", postMessage(ge, Be), 0) : Ny(ge);
      }
      function Py() {
        return 65536;
      }
      var Oy = true;
      function My() {
        return Oy;
      }
      function il(F) {
        Atomics.store(s(), F >> 2, 1), Wm() && b0(F), Atomics.compareExchange(s(), F >> 2, 1, 0);
      }
      u.executeNotifiedProxyingQueue = il;
      function Ly(F, V, ue, $e) {
        if (F == V) setTimeout(() => il($e));
        else if (S) postMessage({ targetThread: F, cmd: "processProxyingQueue", queue: $e });
        else {
          var Be = Me.pthreads[F];
          if (!Be) return;
          Be.postMessage({ cmd: "processProxyingQueue", queue: $e });
        }
        return 1;
      }
      function By(F, V, ue) {
        return -1;
      }
      function zy() {
        vu("");
      }
      function Nu(F) {
        Nu.shown || (Nu.shown = {}), Nu.shown[F] || (Nu.shown[F] = 1, C && (F = "warning: " + F), j(F));
      }
      function Vy() {
        C || b || Nu("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread");
      }
      function Wy() {
        return Date.now();
      }
      function Rm() {
        return 4294901760;
      }
      function Uy() {
        return Rm();
      }
      var ul;
      C ? ul = () => {
        var F = process.hrtime();
        return F[0] * 1e3 + F[1] / 1e6;
      } : ul = () => performance.timeOrigin + performance.now();
      function Gy(F, V, ue) {
        o().copyWithin(F >>> 0, V >>> 0, V + ue >>> 0);
      }
      function Hy() {
        return C ? zB().cpus().length : navigator.hardwareConcurrency;
      }
      function Ky(F) {
        var V = XC(), ue = F();
        return Um(V), ue;
      }
      function Ni(F, V) {
        var ue = arguments.length - 2, $e = arguments;
        return Ky(() => {
          for (var Be = ue, Le = Gm(Be * 8), ge = Le >> 3, Ne = 0; Ne < ue; Ne++) {
            var Ft = $e[2 + Ne];
            p()[ge + Ne >>> 0] = Ft;
          }
          return y0(F, Be, Le, V);
        });
      }
      var pl = [];
      function qy(F, V, ue) {
        pl.length = V;
        for (var $e = ue >> 3, Be = 0; Be < V; Be++) pl[Be] = p()[$e + Be >>> 0];
        var Le = F < 0, ge = Le ? vm[-F - 1] : rb[F];
        return ge.apply(null, pl);
      }
      function jy(F) {
        try {
          return oe.grow(F - He.byteLength + 65535 >>> 16), Tt(oe.buffer), 1;
        } catch (V) {
        }
      }
      function Xy(F) {
        var V = o().length;
        if (F = F >>> 0, F <= V) return false;
        var ue = Rm();
        if (F > ue) return false;
        let $e = (Ft, so) => Ft + (so - Ft % so) % so;
        for (var Be = 1; Be <= 4; Be *= 2) {
          var Le = V * (1 + 0.2 / Be);
          Le = Math.min(Le, F + 100663296);
          var ge = Math.min(ue, $e(Math.max(F, Le), 65536)), Ne = jy(ge);
          if (Ne) return true;
        }
        return false;
      }
      function Yy() {
        throw "unwind";
      }
      function Dm(F) {
        return S ? Ni(4, 1, F) : 52;
      }
      function Am(F, V, ue, $e, Be) {
        return S ? Ni(5, 1, F, V, ue, $e, Be) : 70;
      }
      var Qy = [null, [], []];
      function Zy(F, V) {
        var ue = Qy[F];
        V === 0 || V === 10 ? ((F === 1 ? U : j)(Fe(ue, 0)), ue.length = 0) : ue.push(V);
      }
      function Fm(F, V, ue, $e) {
        if (S) return Ni(6, 1, F, V, ue, $e);
        for (var Be = 0, Le = 0; Le < ue; Le++) {
          var ge = a()[V >>> 2], Ne = a()[V + 4 >>> 2];
          V += 8;
          for (var Ft = 0; Ft < Ne; Ft++) Zy(F, o()[ge + Ft >>> 0]);
          Be += Ne;
        }
        return a()[$e >>> 2] = Be, 0;
      }
      function Pm(F) {
        var V = u["_" + F];
        return V;
      }
      function Jy(F, V) {
        t10().set(F, V >>> 0);
      }
      function eb(F, V, ue, $e, Be) {
        var Le = { string: (Br) => {
          var Bp = 0;
          if (Br != null && Br !== 0) {
            var v0 = (Br.length << 2) + 1;
            Bp = Gm(v0), ct(Br, Bp, v0);
          }
          return Bp;
        }, array: (Br) => {
          var Bp = Gm(Br.length);
          return Jy(Br, Bp), Bp;
        } };
        function ge(Br) {
          return V === "string" ? Pe(Br) : V === "boolean" ? !!Br : Br;
        }
        var Ne = Pm(F), Ft = [], so = 0;
        if ($e) for (var Ha = 0; Ha < $e.length; Ha++) {
          var I0 = Le[ue[Ha]];
          I0 ? (so === 0 && (so = XC()), Ft[Ha] = I0($e[Ha])) : Ft[Ha] = $e[Ha];
        }
        var YC = Ne.apply(null, Ft);
        function TG(Br) {
          return so !== 0 && Um(so), ge(Br);
        }
        return YC = TG(YC), YC;
      }
      function tb(F, V, ue, $e) {
        ue = ue || [];
        var Be = ue.every((ge) => ge === "number" || ge === "boolean"), Le = V !== "string";
        return Le && Be && !$e ? Pm(F) : function() {
          return eb(F, V, ue, arguments, $e);
        };
      }
      Me.init();
      var rb = [null, Nm, _m, Em, Dm, Am, Fm], Om = { __emscripten_init_main_thread_js: Ay, __emscripten_thread_cleanup: Fy, __pthread_create_js: $m, _emscripten_default_pthread_stack_size: Py, _emscripten_get_now_is_monotonic: My, _emscripten_notify_task_queue: Ly, _emscripten_set_offscreencanvas_size: By, abort: zy, emscripten_check_blocking_allowed: Vy, emscripten_date_now: Wy, emscripten_get_heap_max: Uy, emscripten_get_now: ul, emscripten_memcpy_big: Gy, emscripten_num_logical_cores: Hy, emscripten_receive_on_main_thread_js: qy, emscripten_resize_heap: Xy, emscripten_unwind_to_js_event_loop: Yy, exit: Tm, fd_close: Dm, fd_seek: Am, fd_write: Fm, memory: oe || u.wasmMemory }, g0 = Iy(), ob = u.___wasm_call_ctors = function() {
        return (ob = u.___wasm_call_ctors = u.asm.__wasm_call_ctors).apply(null, arguments);
      }, nb = u._init = function() {
        return (nb = u._init = u.asm.init).apply(null, arguments);
      }, sb = u._init_with_threads_count = function() {
        return (sb = u._init_with_threads_count = u.asm.init_with_threads_count).apply(null, arguments);
      }, ab = u._get_threads_count = function() {
        return (ab = u._get_threads_count = u.asm.get_threads_count).apply(null, arguments);
      }, ib = u._register_tensor = function() {
        return (ib = u._register_tensor = u.asm.register_tensor).apply(null, arguments);
      }, ub = u._dispose_data = function() {
        return (ub = u._dispose_data = u.asm.dispose_data).apply(null, arguments);
      }, pb = u._dispose = function() {
        return (pb = u._dispose = u.asm.dispose).apply(null, arguments);
      }, cb = u._Abs = function() {
        return (cb = u._Abs = u.asm.Abs).apply(null, arguments);
      }, lb = u._Acos = function() {
        return (lb = u._Acos = u.asm.Acos).apply(null, arguments);
      }, mb = u._Acosh = function() {
        return (mb = u._Acosh = u.asm.Acosh).apply(null, arguments);
      }, db = u._Add = function() {
        return (db = u._Add = u.asm.Add).apply(null, arguments);
      }, fb = u._AddN = function() {
        return (fb = u._AddN = u.asm.AddN).apply(null, arguments);
      }, hb = u._All = function() {
        return (hb = u._All = u.asm.All).apply(null, arguments);
      }, gb = u._Any = function() {
        return (gb = u._Any = u.asm.Any).apply(null, arguments);
      }, xb = u._ArgMax = function() {
        return (xb = u._ArgMax = u.asm.ArgMax).apply(null, arguments);
      }, yb = u._ArgMin = function() {
        return (yb = u._ArgMin = u.asm.ArgMin).apply(null, arguments);
      }, bb = u._Asin = function() {
        return (bb = u._Asin = u.asm.Asin).apply(null, arguments);
      }, Cb = u._Asinh = function() {
        return (Cb = u._Asinh = u.asm.Asinh).apply(null, arguments);
      }, wb = u._Atan = function() {
        return (wb = u._Atan = u.asm.Atan).apply(null, arguments);
      }, Sb = u._Atan2 = function() {
        return (Sb = u._Atan2 = u.asm.Atan2).apply(null, arguments);
      }, Ib = u._Atanh = function() {
        return (Ib = u._Atanh = u.asm.Atanh).apply(null, arguments);
      }, vb = u._AvgPool = function() {
        return (vb = u._AvgPool = u.asm.AvgPool).apply(null, arguments);
      }, kb = u._AvgPool3D = function() {
        return (kb = u._AvgPool3D = u.asm.AvgPool3D).apply(null, arguments);
      }, Nb = u._AvgPool3DGrad = function() {
        return (Nb = u._AvgPool3DGrad = u.asm.AvgPool3DGrad).apply(null, arguments);
      }, Tb = u._AvgPoolGrad = function() {
        return (Tb = u._AvgPoolGrad = u.asm.AvgPoolGrad).apply(null, arguments);
      }, _b = u._BatchMatMul = function() {
        return (_b = u._BatchMatMul = u.asm.BatchMatMul).apply(null, arguments);
      }, Eb = u._Bincount = function() {
        return (Eb = u._Bincount = u.asm.Bincount).apply(null, arguments);
      }, $b = u._BitwiseAnd = function() {
        return ($b = u._BitwiseAnd = u.asm.BitwiseAnd).apply(null, arguments);
      }, Rb = u._Ceil = function() {
        return (Rb = u._Ceil = u.asm.Ceil).apply(null, arguments);
      }, Db = u._ClipByValue = function() {
        return (Db = u._ClipByValue = u.asm.ClipByValue).apply(null, arguments);
      }, Ab = u._Conv2D = function() {
        return (Ab = u._Conv2D = u.asm.Conv2D).apply(null, arguments);
      }, Fb = u._Conv2DBackpropInput = function() {
        return (Fb = u._Conv2DBackpropInput = u.asm.Conv2DBackpropInput).apply(null, arguments);
      }, Pb = u._Conv3D = function() {
        return (Pb = u._Conv3D = u.asm.Conv3D).apply(null, arguments);
      }, Ob = u._Conv3DBackpropFilterV2 = function() {
        return (Ob = u._Conv3DBackpropFilterV2 = u.asm.Conv3DBackpropFilterV2).apply(null, arguments);
      }, Mb = u._Conv3DBackpropInputV2 = function() {
        return (Mb = u._Conv3DBackpropInputV2 = u.asm.Conv3DBackpropInputV2).apply(null, arguments);
      }, Lb = u._Cos = function() {
        return (Lb = u._Cos = u.asm.Cos).apply(null, arguments);
      }, Bb = u._Cosh = function() {
        return (Bb = u._Cosh = u.asm.Cosh).apply(null, arguments);
      }, zb = u._CropAndResize = function() {
        return (zb = u._CropAndResize = u.asm.CropAndResize).apply(null, arguments);
      }, Vb = u._Cumprod = function() {
        return (Vb = u._Cumprod = u.asm.Cumprod).apply(null, arguments);
      }, Wb = u._Cumsum = function() {
        return (Wb = u._Cumsum = u.asm.Cumsum).apply(null, arguments);
      }, Ub = u._DenseBincount = function() {
        return (Ub = u._DenseBincount = u.asm.DenseBincount).apply(null, arguments);
      }, Gb = u._DepthToSpace = function() {
        return (Gb = u._DepthToSpace = u.asm.DepthToSpace).apply(null, arguments);
      }, Hb = u._DepthwiseConv2dNative = function() {
        return (Hb = u._DepthwiseConv2dNative = u.asm.DepthwiseConv2dNative).apply(null, arguments);
      }, Kb = u._Diag = function() {
        return (Kb = u._Diag = u.asm.Diag).apply(null, arguments);
      }, qb = u._Dilation2D = function() {
        return (qb = u._Dilation2D = u.asm.Dilation2D).apply(null, arguments);
      }, jb = u._Dilation2DBackpropFilter = function() {
        return (jb = u._Dilation2DBackpropFilter = u.asm.Dilation2DBackpropFilter).apply(null, arguments);
      }, Xb = u._Dilation2DBackpropInput = function() {
        return (Xb = u._Dilation2DBackpropInput = u.asm.Dilation2DBackpropInput).apply(null, arguments);
      }, Yb = u._Elu = function() {
        return (Yb = u._Elu = u.asm.Elu).apply(null, arguments);
      }, Qb = u._EluGrad = function() {
        return (Qb = u._EluGrad = u.asm.EluGrad).apply(null, arguments);
      }, Zb = u._Equal = function() {
        return (Zb = u._Equal = u.asm.Equal).apply(null, arguments);
      }, Jb = u._Erf = function() {
        return (Jb = u._Erf = u.asm.Erf).apply(null, arguments);
      }, eC = u._Exp = function() {
        return (eC = u._Exp = u.asm.Exp).apply(null, arguments);
      }, tC = u._Expm1 = function() {
        return (tC = u._Expm1 = u.asm.Expm1).apply(null, arguments);
      }, rC = u._FlipLeftRight = function() {
        return (rC = u._FlipLeftRight = u.asm.FlipLeftRight).apply(null, arguments);
      }, oC = u._Floor = function() {
        return (oC = u._Floor = u.asm.Floor).apply(null, arguments);
      }, nC = u._FloorDiv = function() {
        return (nC = u._FloorDiv = u.asm.FloorDiv).apply(null, arguments);
      }, sC = u._FusedBatchNorm = function() {
        return (sC = u._FusedBatchNorm = u.asm.FusedBatchNorm).apply(null, arguments);
      }, aC = u._FusedConv2D = function() {
        return (aC = u._FusedConv2D = u.asm.FusedConv2D).apply(null, arguments);
      }, iC = u._FusedDepthwiseConv2D = function() {
        return (iC = u._FusedDepthwiseConv2D = u.asm.FusedDepthwiseConv2D).apply(null, arguments);
      }, uC = u._Gather = function() {
        return (uC = u._Gather = u.asm.Gather).apply(null, arguments);
      }, pC = u._GatherNd = function() {
        return (pC = u._GatherNd = u.asm.GatherNd).apply(null, arguments);
      }, cC = u._Greater = function() {
        return (cC = u._Greater = u.asm.Greater).apply(null, arguments);
      }, lC = u._GreaterEqual = function() {
        return (lC = u._GreaterEqual = u.asm.GreaterEqual).apply(null, arguments);
      }, mC = u._IsFinite = function() {
        return (mC = u._IsFinite = u.asm.IsFinite).apply(null, arguments);
      }, dC = u._IsInf = function() {
        return (dC = u._IsInf = u.asm.IsInf).apply(null, arguments);
      }, fC = u._IsNan = function() {
        return (fC = u._IsNan = u.asm.IsNan).apply(null, arguments);
      }, hC = u._LRN = function() {
        return (hC = u._LRN = u.asm.LRN).apply(null, arguments);
      }, gC = u._LRNGrad = function() {
        return (gC = u._LRNGrad = u.asm.LRNGrad).apply(null, arguments);
      }, xC = u._LeakyRelu = function() {
        return (xC = u._LeakyRelu = u.asm.LeakyRelu).apply(null, arguments);
      }, yC = u._Less = function() {
        return (yC = u._Less = u.asm.Less).apply(null, arguments);
      }, bC = u._LessEqual = function() {
        return (bC = u._LessEqual = u.asm.LessEqual).apply(null, arguments);
      }, CC = u._LinSpace = function() {
        return (CC = u._LinSpace = u.asm.LinSpace).apply(null, arguments);
      }, wC = u._Log = function() {
        return (wC = u._Log = u.asm.Log).apply(null, arguments);
      }, SC = u._Log1p = function() {
        return (SC = u._Log1p = u.asm.Log1p).apply(null, arguments);
      }, IC = u._LogicalAnd = function() {
        return (IC = u._LogicalAnd = u.asm.LogicalAnd).apply(null, arguments);
      }, vC = u._LogicalNot = function() {
        return (vC = u._LogicalNot = u.asm.LogicalNot).apply(null, arguments);
      }, kC = u._LogicalOr = function() {
        return (kC = u._LogicalOr = u.asm.LogicalOr).apply(null, arguments);
      }, NC = u._LogicalXor = function() {
        return (NC = u._LogicalXor = u.asm.LogicalXor).apply(null, arguments);
      }, TC = u._Max = function() {
        return (TC = u._Max = u.asm.Max).apply(null, arguments);
      }, _C = u._MaxPool = function() {
        return (_C = u._MaxPool = u.asm.MaxPool).apply(null, arguments);
      }, EC = u._MaxPool3D = function() {
        return (EC = u._MaxPool3D = u.asm.MaxPool3D).apply(null, arguments);
      }, $C = u._MaxPool3DGrad = function() {
        return ($C = u._MaxPool3DGrad = u.asm.MaxPool3DGrad).apply(null, arguments);
      }, RC = u._MaxPoolGrad = function() {
        return (RC = u._MaxPoolGrad = u.asm.MaxPoolGrad).apply(null, arguments);
      }, DC = u._MaxPoolWithArgmax = function() {
        return (DC = u._MaxPoolWithArgmax = u.asm.MaxPoolWithArgmax).apply(null, arguments);
      }, AC = u._Maximum = function() {
        return (AC = u._Maximum = u.asm.Maximum).apply(null, arguments);
      }, FC = u._Mean = function() {
        return (FC = u._Mean = u.asm.Mean).apply(null, arguments);
      }, PC = u._Min = function() {
        return (PC = u._Min = u.asm.Min).apply(null, arguments);
      }, OC = u._Minimum = function() {
        return (OC = u._Minimum = u.asm.Minimum).apply(null, arguments);
      }, MC = u._MirrorPad = function() {
        return (MC = u._MirrorPad = u.asm.MirrorPad).apply(null, arguments);
      }, LC = u._Mod = function() {
        return (LC = u._Mod = u.asm.Mod).apply(null, arguments);
      }, BC = u._Multinomial = function() {
        return (BC = u._Multinomial = u.asm.Multinomial).apply(null, arguments);
      }, zC = u._Multiply = function() {
        return (zC = u._Multiply = u.asm.Multiply).apply(null, arguments);
      }, VC = u._Neg = function() {
        return (VC = u._Neg = u.asm.Neg).apply(null, arguments);
      }, WC = u._NonMaxSuppressionV3 = function() {
        return (WC = u._NonMaxSuppressionV3 = u.asm.NonMaxSuppressionV3).apply(null, arguments);
      }, UC = u._NonMaxSuppressionV4 = function() {
        return (UC = u._NonMaxSuppressionV4 = u.asm.NonMaxSuppressionV4).apply(null, arguments);
      }, Mm = u._NonMaxSuppressionV5 = function() {
        return (Mm = u._NonMaxSuppressionV5 = u.asm.NonMaxSuppressionV5).apply(null, arguments);
      }, Lm = u._NotEqual = function() {
        return (Lm = u._NotEqual = u.asm.NotEqual).apply(null, arguments);
      }, cl = u._OneHot = function() {
        return (cl = u._OneHot = u.asm.OneHot).apply(null, arguments);
      }, GC = u._PadV2 = function() {
        return (GC = u._PadV2 = u.asm.PadV2).apply(null, arguments);
      }, HC = u._Pow = function() {
        return (HC = u._Pow = u.asm.Pow).apply(null, arguments);
      }, Op = u._Prelu = function() {
        return (Op = u._Prelu = u.asm.Prelu).apply(null, arguments);
      }, Bm = u._Prod = function() {
        return (Bm = u._Prod = u.asm.Prod).apply(null, arguments);
      }, Mp = u._RealDiv = function() {
        return (Mp = u._RealDiv = u.asm.RealDiv).apply(null, arguments);
      }, Lp = u._Reciprocal = function() {
        return (Lp = u._Reciprocal = u.asm.Reciprocal).apply(null, arguments);
      }, KC = u._Relu = function() {
        return (KC = u._Relu = u.asm.Relu).apply(null, arguments);
      }, K = u._Relu6 = function() {
        return (K = u._Relu6 = u.asm.Relu6).apply(null, arguments);
      }, ae = u._ResizeBilinear = function() {
        return (ae = u._ResizeBilinear = u.asm.ResizeBilinear).apply(null, arguments);
      }, Ee = u._ResizeBilinearGrad = function() {
        return (Ee = u._ResizeBilinearGrad = u.asm.ResizeBilinearGrad).apply(null, arguments);
      }, at = u._ResizeNearestNeighbor = function() {
        return (at = u._ResizeNearestNeighbor = u.asm.ResizeNearestNeighbor).apply(null, arguments);
      }, _t = u._ResizeNearestNeighborGrad = function() {
        return (_t = u._ResizeNearestNeighborGrad = u.asm.ResizeNearestNeighborGrad).apply(null, arguments);
      }, Et = u._Reverse = function() {
        return (Et = u._Reverse = u.asm.Reverse).apply(null, arguments);
      }, Qe = u._RotateWithOffset = function() {
        return (Qe = u._RotateWithOffset = u.asm.RotateWithOffset).apply(null, arguments);
      }, Ke = u._Round = function() {
        return (Ke = u._Round = u.asm.Round).apply(null, arguments);
      }, Ut = u._Rsqrt = function() {
        return (Ut = u._Rsqrt = u.asm.Rsqrt).apply(null, arguments);
      }, no = u._ScatterNd = function() {
        return (no = u._ScatterNd = u.asm.ScatterNd).apply(null, arguments);
      }, Ga = u._SearchSorted = function() {
        return (Ga = u._SearchSorted = u.asm.SearchSorted).apply(null, arguments);
      }, zm = u._SelectV2 = function() {
        return (zm = u._SelectV2 = u.asm.SelectV2).apply(null, arguments);
      }, ll = u._Selu = function() {
        return (ll = u._Selu = u.asm.Selu).apply(null, arguments);
      }, qC = u._Sigmoid = function() {
        return (qC = u._Sigmoid = u.asm.Sigmoid).apply(null, arguments);
      }, yr = u._Sign = function() {
        return (yr = u._Sign = u.asm.Sign).apply(null, arguments);
      }, Ti = u._Sin = function() {
        return (Ti = u._Sin = u.asm.Sin).apply(null, arguments);
      }, Vm = u._Sinh = function() {
        return (Vm = u._Sinh = u.asm.Sinh).apply(null, arguments);
      }, XU = u._Softmax = function() {
        return (XU = u._Softmax = u.asm.Softmax).apply(null, arguments);
      }, YU = u._Softplus = function() {
        return (YU = u._Softplus = u.asm.Softplus).apply(null, arguments);
      }, QU = u._SparseFillEmptyRows = function() {
        return (QU = u._SparseFillEmptyRows = u.asm.SparseFillEmptyRows).apply(null, arguments);
      }, ZU = u._SparseReshape = function() {
        return (ZU = u._SparseReshape = u.asm.SparseReshape).apply(null, arguments);
      }, JU = u._SparseSegmentReduction = function() {
        return (JU = u._SparseSegmentReduction = u.asm.SparseSegmentReduction).apply(null, arguments);
      }, eG = u._SparseToDense = function() {
        return (eG = u._SparseToDense = u.asm.SparseToDense).apply(null, arguments);
      }, tG = u._Sqrt = function() {
        return (tG = u._Sqrt = u.asm.Sqrt).apply(null, arguments);
      }, rG = u._Square = function() {
        return (rG = u._Square = u.asm.Square).apply(null, arguments);
      }, oG = u._SquaredDifference = function() {
        return (oG = u._SquaredDifference = u.asm.SquaredDifference).apply(null, arguments);
      }, nG = u._Step = function() {
        return (nG = u._Step = u.asm.Step).apply(null, arguments);
      }, sG = u._StridedSlice = function() {
        return (sG = u._StridedSlice = u.asm.StridedSlice).apply(null, arguments);
      }, aG = u._Sub = function() {
        return (aG = u._Sub = u.asm.Sub).apply(null, arguments);
      }, iG = u._Sum = function() {
        return (iG = u._Sum = u.asm.Sum).apply(null, arguments);
      }, uG = u._Tan = function() {
        return (uG = u._Tan = u.asm.Tan).apply(null, arguments);
      }, pG = u._Tanh = function() {
        return (pG = u._Tanh = u.asm.Tanh).apply(null, arguments);
      }, cG = u._TensorScatterUpdate = function() {
        return (cG = u._TensorScatterUpdate = u.asm.TensorScatterUpdate).apply(null, arguments);
      }, lG = u._Tile = function() {
        return (lG = u._Tile = u.asm.Tile).apply(null, arguments);
      }, mG = u._TopK = function() {
        return (mG = u._TopK = u.asm.TopK).apply(null, arguments);
      }, dG = u._Transform = function() {
        return (dG = u._Transform = u.asm.Transform).apply(null, arguments);
      }, fG = u._Transpose = function() {
        return (fG = u._Transpose = u.asm.Transpose).apply(null, arguments);
      }, hG = u.__FusedMatMul = function() {
        return (hG = u.__FusedMatMul = u.asm._FusedMatMul).apply(null, arguments);
      }, gG = u._malloc = function() {
        return (gG = u._malloc = u.asm.malloc).apply(null, arguments);
      }, xG = u._free = function() {
        return (xG = u._free = u.asm.free).apply(null, arguments);
      }, yG = u.__emscripten_tls_init = function() {
        return (yG = u.__emscripten_tls_init = u.asm._emscripten_tls_init).apply(null, arguments);
      }, Wm = u._pthread_self = function() {
        return (Wm = u._pthread_self = u.asm.pthread_self).apply(null, arguments);
      }, bG = u.___errno_location = function() {
        return (bG = u.___errno_location = u.asm.__errno_location).apply(null, arguments);
      }, x0 = u.__emscripten_thread_init = function() {
        return (x0 = u.__emscripten_thread_init = u.asm._emscripten_thread_init).apply(null, arguments);
      }, CG = u.__emscripten_thread_crashed = function() {
        return (CG = u.__emscripten_thread_crashed = u.asm._emscripten_thread_crashed).apply(null, arguments);
      }, wG = u._emscripten_main_thread_process_queued_calls = function() {
        return (wG = u._emscripten_main_thread_process_queued_calls = u.asm.emscripten_main_thread_process_queued_calls).apply(null, arguments);
      }, SG = u._emscripten_main_browser_thread_id = function() {
        return (SG = u._emscripten_main_browser_thread_id = u.asm.emscripten_main_browser_thread_id).apply(null, arguments);
      }, y0 = u._emscripten_run_in_main_runtime_thread_js = function() {
        return (y0 = u._emscripten_run_in_main_runtime_thread_js = u.asm.emscripten_run_in_main_runtime_thread_js).apply(null, arguments);
      }, IG = u._emscripten_dispatch_to_thread_ = function() {
        return (IG = u._emscripten_dispatch_to_thread_ = u.asm.emscripten_dispatch_to_thread_).apply(null, arguments);
      }, b0 = u.__emscripten_proxy_execute_task_queue = function() {
        return (b0 = u.__emscripten_proxy_execute_task_queue = u.asm._emscripten_proxy_execute_task_queue).apply(null, arguments);
      }, jC = u.__emscripten_thread_free_data = function() {
        return (jC = u.__emscripten_thread_free_data = u.asm._emscripten_thread_free_data).apply(null, arguments);
      }, C0 = u.__emscripten_thread_exit = function() {
        return (C0 = u.__emscripten_thread_exit = u.asm._emscripten_thread_exit).apply(null, arguments);
      }, w0 = u._emscripten_stack_set_limits = function() {
        return (w0 = u._emscripten_stack_set_limits = u.asm.emscripten_stack_set_limits).apply(null, arguments);
      }, XC = u.stackSave = function() {
        return (XC = u.stackSave = u.asm.stackSave).apply(null, arguments);
      }, Um = u.stackRestore = function() {
        return (Um = u.stackRestore = u.asm.stackRestore).apply(null, arguments);
      }, Gm = u.stackAlloc = function() {
        return (Gm = u.stackAlloc = u.asm.stackAlloc).apply(null, arguments);
      }, vG = u.dynCall_iijjiiii = function() {
        return (vG = u.dynCall_iijjiiii = u.asm.dynCall_iijjiiii).apply(null, arguments);
      }, kG = u.dynCall_jiji = function() {
        return (kG = u.dynCall_jiji = u.asm.dynCall_jiji).apply(null, arguments);
      };
      u.keepRuntimeAlive = Lo, u.wasmMemory = oe, u.cwrap = tb, u.ExitStatus = ku, u.PThread = Me;
      var Hm;
      Ua = function F() {
        Hm || S0(), Hm || (Ua = F);
      };
      function S0(F) {
        if (F = F || f, ki > 0) return;
        if (S) {
          c(u), Xt(), startWorker(u);
          return;
        }
        if (Ks(), ki > 0) return;
        function V() {
          Hm || (Hm = true, u.calledRun = true, !le && (Xt(), c(u), u.onRuntimeInitialized && u.onRuntimeInitialized(), Wa()));
        }
        u.setStatus ? (u.setStatus("Running..."), setTimeout(function() {
          setTimeout(function() {
            u.setStatus("");
          }, 1), V();
        }, 1)) : V();
      }
      if (u.preInit) for (typeof u.preInit == "function" && (u.preInit = [u.preInit]); u.preInit.length > 0; ) u.preInit.pop()();
      S0();
      var Km;
      m && (Km = { uncaughtException: process.listeners("uncaughtException").filter(function(F) {
        return !m.uncaughtException.indexOf(F) > -1;
      }), unhandledRejection: process.listeners("unhandledRejection").filter(function(F) {
        return !m.unhandledRejection.indexOf(F) > -1;
      }) });
      var qm;
      if (typeof WasmBackendModule != "undefined") qm = WasmBackendModule;
      else if (typeof e != "undefined") qm = e;
      else throw new Error("Could not find wasm module in post.js");
      if (Km) {
        var NG = qm._dispose;
        qm._dispose = function() {
          NG(), Km.uncaughtException.forEach(function(F) {
            process.removeListener("uncaughtException", F);
          }), Km.unhandledRejection.forEach(function(F) {
            process.removeListener("unhandledRejection", F);
          });
        };
      }
      return e.ready;
    });
  })();
  typeof Wg == "object" && typeof Gv == "object" ? Gv.exports = Uv : typeof define == "function" && define.amd ? define([], function() {
    return Uv;
  }) : typeof Wg == "object" && (Wg.WasmBackendModuleThreadedSimd = Uv);
});
var UB = Kt((e3t, WB) => {
  WB.exports.wasmWorkerContents = `"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",data=>onmessage({data:data}));var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8")+"//# sourceURL="+f)},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"
");return}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;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.startWorker=instance=>{Module=instance;postMessage({"cmd":"loaded"})};self.onmessage=e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;for(const handler of e.data.handlers){Module[handler]=function(){postMessage({cmd:"callHandler",handler:handler,args:[...arguments]})}}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)}else if(e.data.cmd==="run"){Module["__emscripten_thread_init"](e.data.pthread_ptr,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module["executeNotifiedProxyingQueue"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processProxyingQueue"){if(initializedJS){Module["executeNotifiedProxyingQueue"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else if(e.data.cmd){err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}};`;
});
var GB = Kt((Ug, Kv) => {
  var Hv = (() => {
    var r15 = typeof document != "undefined" && document.currentScript ? document.currentScript.src : void 0;
    return typeof __filename != "undefined" && (r15 = r15 || __filename), (function(e) {
      e = e || {};
      var t10 = typeof e != "undefined" ? e : {}, o, n;
      t10.ready = new Promise(function(K, ae) {
        o = K, n = ae;
      });
      var s;
      typeof process != "undefined" && process.listeners && (s = { uncaughtException: process.listeners("uncaughtException"), unhandledRejection: process.listeners("unhandledRejection") });
      var a = Object.assign({}, t10), i = [], p = "./this.program", u = (K, ae) => {
        throw ae;
      }, c = typeof window == "object", l = typeof importScripts == "function", m = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string", d = "";
      function f(K) {
        return t10.locateFile ? t10.locateFile(K, d) : d + K;
      }
      var h, g, x, b;
      function C(K) {
        if (K instanceof Ap) return;
        $("exiting due to exception: " + K);
      }
      if (m) {
        var S = Vv(), k = Wv();
        l ? d = k.dirname(d) + "/" : d = __dirname + "/", h = (K, ae) => (K = Ks(K) ? new URL(K) : k.normalize(K), S.readFileSync(K, ae ? void 0 : "utf8")), x = (K) => {
          var ae = h(K, true);
          return ae.buffer || (ae = new Uint8Array(ae)), ae;
        }, g = (K, ae, Ee) => {
          K = Ks(K) ? new URL(K) : k.normalize(K), S.readFile(K, function(at, _t) {
            at ? Ee(at) : ae(_t.buffer);
          });
        }, process.argv.length > 1 && (p = process.argv[1].replace(/\\/g, "/")), i = process.argv.slice(2), process.on("uncaughtException", function(K) {
          if (!(K instanceof Ap)) throw K;
        }), process.on("unhandledRejection", function(K) {
          throw K;
        }), u = (K, ae) => {
          if (it()) throw process.exitCode = K, ae;
          C(ae), process.exit(K);
        }, t10.inspect = function() {
          return "[Emscripten Module object]";
        };
      } else (c || l) && (l ? d = self.location.href : typeof document != "undefined" && document.currentScript && (d = document.currentScript.src), r15 && (d = r15), d.indexOf("blob:") !== 0 ? d = d.substr(0, d.replace(/[?#].*/, "").lastIndexOf("/") + 1) : d = "", h = (K) => {
        var ae = new XMLHttpRequest();
        return ae.open("GET", K, false), ae.send(null), ae.responseText;
      }, l && (x = (K) => {
        var ae = new XMLHttpRequest();
        return ae.open("GET", K, false), ae.responseType = "arraybuffer", ae.send(null), new Uint8Array(ae.response);
      }), g = (K, ae, Ee) => {
        var at = new XMLHttpRequest();
        at.open("GET", K, true), at.responseType = "arraybuffer", at.onload = () => {
          if (at.status == 200 || at.status == 0 && at.response) {
            ae(at.response);
            return;
          }
          Ee();
        }, at.onerror = Ee, at.send(null);
      }, b = (K) => document.title = K);
      var _ = t10.print || console.log.bind(console), $ = t10.printErr || console.warn.bind(console);
      Object.assign(t10, a), a = null, t10.arguments && (i = t10.arguments), t10.thisProgram && (p = t10.thisProgram), t10.quit && (u = t10.quit);
      var R = 4, D;
      t10.wasmBinary && (D = t10.wasmBinary);
      var P = t10.noExitRuntime || true;
      typeof WebAssembly != "object" && fr("no native wasm support detected");
      var O, M = false, L;
      function B(K, ae) {
        K || fr(ae);
      }
      var z = typeof TextDecoder != "undefined" ? new TextDecoder("utf8") : void 0;
      function U(K, ae, Ee) {
        ae >>>= 0;
        for (var at = ae + Ee, _t = ae; K[_t] && !(_t >= at); ) ++_t;
        if (_t - ae > 16 && K.buffer && z) return z.decode(K.subarray(ae, _t));
        for (var Et = ""; ae < _t; ) {
          var Qe = K[ae++];
          if (!(Qe & 128)) {
            Et += String.fromCharCode(Qe);
            continue;
          }
          var Ke = K[ae++] & 63;
          if ((Qe & 224) == 192) {
            Et += String.fromCharCode((Qe & 31) << 6 | Ke);
            continue;
          }
          var Ut = K[ae++] & 63;
          if ((Qe & 240) == 224 ? Qe = (Qe & 15) << 12 | Ke << 6 | Ut : Qe = (Qe & 7) << 18 | Ke << 12 | Ut << 6 | K[ae++] & 63, Qe < 65536) Et += String.fromCharCode(Qe);
          else {
            var no = Qe - 65536;
            Et += String.fromCharCode(55296 | no >> 10, 56320 | no & 1023);
          }
        }
        return Et;
      }
      function j(K, ae) {
        return K >>>= 0, K ? U(ne, K, ae) : "";
      }
      function q(K, ae, Ee, at) {
        if (Ee >>>= 0, !(at > 0)) return 0;
        for (var _t = Ee, Et = Ee + at - 1, Qe = 0; Qe < K.length; ++Qe) {
          var Ke = K.charCodeAt(Qe);
          if (Ke >= 55296 && Ke <= 57343) {
            var Ut = K.charCodeAt(++Qe);
            Ke = 65536 + ((Ke & 1023) << 10) | Ut & 1023;
          }
          if (Ke <= 127) {
            if (Ee >= Et) break;
            ae[Ee++ >>> 0] = Ke;
          } else if (Ke <= 2047) {
            if (Ee + 1 >= Et) break;
            ae[Ee++ >>> 0] = 192 | Ke >> 6, ae[Ee++ >>> 0] = 128 | Ke & 63;
          } else if (Ke <= 65535) {
            if (Ee + 2 >= Et) break;
            ae[Ee++ >>> 0] = 224 | Ke >> 12, ae[Ee++ >>> 0] = 128 | Ke >> 6 & 63, ae[Ee++ >>> 0] = 128 | Ke & 63;
          } else {
            if (Ee + 3 >= Et) break;
            ae[Ee++ >>> 0] = 240 | Ke >> 18, ae[Ee++ >>> 0] = 128 | Ke >> 12 & 63, ae[Ee++ >>> 0] = 128 | Ke >> 6 & 63, ae[Ee++ >>> 0] = 128 | Ke & 63;
          }
        }
        return ae[Ee >>> 0] = 0, Ee - _t;
      }
      function Y(K, ae, Ee) {
        return q(K, ne, ae, Ee);
      }
      var J, re, ne, ee, oe, ie, le, be, _e;
      function ve(K) {
        J = K, t10.HEAP8 = re = new Int8Array(K), t10.HEAP16 = ee = new Int16Array(K), t10.HEAP32 = ie = new Int32Array(K), t10.HEAPU8 = ne = new Uint8Array(K), t10.HEAPU16 = oe = new Uint16Array(K), t10.HEAPU32 = le = new Uint32Array(K), t10.HEAPF32 = be = new Float32Array(K), t10.HEAPF64 = _e = new Float64Array(K);
      }
      var Fe = t10.INITIAL_MEMORY || 16777216, Pe, st = [], ct = [], He = [], lt = false;
      function it() {
        return P;
      }
      function ht() {
        if (t10.preRun) for (typeof t10.preRun == "function" && (t10.preRun = [t10.preRun]); t10.preRun.length; ) Mt(t10.preRun.shift());
        Ua(st);
      }
      function gt() {
        lt = true, Ua(ct);
      }
      function Lr() {
        if (t10.postRun) for (typeof t10.postRun == "function" && (t10.postRun = [t10.postRun]); t10.postRun.length; ) rr(t10.postRun.shift());
        Ua(He);
      }
      function Mt(K) {
        st.unshift(K);
      }
      function to(K) {
        ct.unshift(K);
      }
      function rr(K) {
        He.unshift(K);
      }
      var Tt = 0, or = null, nr = null;
      function ro(K) {
        Tt++, t10.monitorRunDependencies && t10.monitorRunDependencies(Tt);
      }
      function oo(K) {
        if (Tt--, t10.monitorRunDependencies && t10.monitorRunDependencies(Tt), Tt == 0 && (or !== null && (clearInterval(or), or = null), nr)) {
          var ae = nr;
          nr = null, ae();
        }
      }
      function fr(K) {
        t10.onAbort && t10.onAbort(K), K = "Aborted(" + K + ")", $(K), M = true, L = 1, K += ". Build with -sASSERTIONS for more info.";
        var ae = new WebAssembly.RuntimeError(K);
        throw n(ae), ae;
      }
      var Va = "data:application/octet-stream;base64,";
      function Lo(K) {
        return K.startsWith(Va);
      }
      function Ks(K) {
        return K.startsWith("file://");
      }
      var Xt;
      Xt = "tfjs-backend-wasm.wasm", Lo(Xt) || (Xt = f(Xt));
      function Wa(K) {
        try {
          if (K == Xt && D) return new Uint8Array(D);
          if (x) return x(K);
          throw "both async and sync fetching of the wasm failed";
        } catch (ae) {
          fr(ae);
        }
      }
      function ol() {
        if (!D && (c || l)) {
          if (typeof fetch == "function" && !Ks(Xt)) return fetch(Xt, { credentials: "same-origin" }).then(function(K) {
            if (!K.ok) throw "failed to load wasm binary file at '" + Xt + "'";
            return K.arrayBuffer();
          }).catch(function() {
            return Wa(Xt);
          });
          if (g) return new Promise(function(K, ae) {
            g(Xt, function(Ee) {
              K(new Uint8Array(Ee));
            }, ae);
          });
        }
        return Promise.resolve().then(function() {
          return Wa(Xt);
        });
      }
      function nl() {
        var K = { env: sl, wasi_snapshot_preview1: sl };
        function ae(Qe, Ke) {
          var Ut = Qe.exports;
          t10.asm = Ut, O = t10.asm.memory, ve(O.buffer), Pe = t10.asm.__indirect_function_table, to(t10.asm.__wasm_call_ctors), oo("wasm-instantiate");
        }
        ro("wasm-instantiate");
        function Ee(Qe) {
          ae(Qe.instance);
        }
        function at(Qe) {
          return ol().then(function(Ke) {
            return WebAssembly.instantiate(Ke, K);
          }).then(function(Ke) {
            return Ke;
          }).then(Qe, function(Ke) {
            $("failed to asynchronously prepare wasm: " + Ke), fr(Ke);
          });
        }
        function _t() {
          return !D && typeof WebAssembly.instantiateStreaming == "function" && !Lo(Xt) && !Ks(Xt) && !m && typeof fetch == "function" ? fetch(Xt, { credentials: "same-origin" }).then(function(Qe) {
            var Ke = WebAssembly.instantiateStreaming(Qe, K);
            return Ke.then(Ee, function(Ut) {
              return $("wasm streaming compile failed: " + Ut), $("falling back to ArrayBuffer instantiation"), at(Ee);
            });
          }) : at(Ee);
        }
        if (t10.instantiateWasm) try {
          var Et = t10.instantiateWasm(K, ae);
          return Et;
        } catch (Qe) {
          $("Module.instantiateWasm callback failed with error: " + Qe), n(Qe);
        }
        return _t().catch(n), {};
      }
      var d0, ki;
      function Ap(K) {
        this.name = "ExitStatus", this.message = "Program terminated with exit(" + K + ")", this.status = K;
      }
      function Ua(K) {
        for (; K.length > 0; ) K.shift()(t10);
      }
      function Cy() {
        fr("");
      }
      function wm() {
        return 4294901760;
      }
      function vu() {
        return wm();
      }
      function wy(K, ae, Ee) {
        ne.copyWithin(K >>> 0, ae >>> 0, ae + Ee >>> 0);
      }
      function Sm(K) {
        try {
          return O.grow(K - J.byteLength + 65535 >>> 16), ve(O.buffer), 1;
        } catch (ae) {
        }
      }
      function Fp(K) {
        var ae = ne.length;
        K = K >>> 0;
        var Ee = wm();
        if (K > Ee) return false;
        let at = (Ut, no) => Ut + (no - Ut % no) % no;
        for (var _t = 1; _t <= 4; _t *= 2) {
          var Et = ae * (1 + 0.2 / _t);
          Et = Math.min(Et, K + 100663296);
          var Qe = Math.min(Ee, at(Math.max(K, Et), 65536)), Ke = Sm(Qe);
          if (Ke) return true;
        }
        return false;
      }
      var hr = { varargs: void 0, get: function() {
        hr.varargs += 4;
        var K = ie[hr.varargs - 4 >>> 2];
        return K;
      }, getStr: function(K) {
        var ae = j(K);
        return ae;
      } };
      function Im(K) {
        return 52;
      }
      function Sy(K, ae, Ee, at, _t) {
        return 70;
      }
      var Iy = [null, [], []];
      function f0(K, ae) {
        var Ee = Iy[K];
        ae === 0 || ae === 10 ? ((K === 1 ? _ : $)(U(Ee, 0)), Ee.length = 0) : Ee.push(ae);
      }
      function h0(K, ae, Ee, at) {
        for (var _t = 0, Et = 0; Et < Ee; Et++) {
          var Qe = le[ae >>> 2], Ke = le[ae + 4 >>> 2];
          ae += 8;
          for (var Ut = 0; Ut < Ke; Ut++) f0(K, ne[Qe + Ut >>> 0]);
          _t += Ke;
        }
        return le[at >>> 2] = _t, 0;
      }
      function vm(K) {
        var ae = t10["_" + K];
        return ae;
      }
      function ku(K, ae) {
        re.set(K, ae >>> 0);
      }
      function vy(K, ae, Ee, at, _t) {
        var Et = { string: (yr) => {
          var Ti = 0;
          if (yr != null && yr !== 0) {
            var Vm = (yr.length << 2) + 1;
            Ti = cl(Vm), Y(yr, Ti, Vm);
          }
          return Ti;
        }, array: (yr) => {
          var Ti = cl(yr.length);
          return ku(yr, Ti), Ti;
        } };
        function Qe(yr) {
          return ae === "string" ? j(yr) : ae === "boolean" ? !!yr : yr;
        }
        var Ke = vm(K), Ut = [], no = 0;
        if (at) for (var Ga = 0; Ga < at.length; Ga++) {
          var zm = Et[Ee[Ga]];
          zm ? (no === 0 && (no = Mm()), Ut[Ga] = zm(at[Ga])) : Ut[Ga] = at[Ga];
        }
        var ll = Ke.apply(null, Ut);
        function qC(yr) {
          return no !== 0 && Lm(no), Qe(yr);
        }
        return ll = qC(ll), ll;
      }
      function ky(K, ae, Ee, at) {
        Ee = Ee || [];
        var _t = Ee.every((Qe) => Qe === "number" || Qe === "boolean"), Et = ae !== "string";
        return Et && _t && !at ? vm(K) : function() {
          return vy(K, ae, Ee, arguments, at);
        };
      }
      var sl = { abort: Cy, emscripten_get_heap_max: vu, emscripten_memcpy_big: wy, emscripten_resize_heap: Fp, fd_close: Im, fd_seek: Sy, fd_write: h0 }, Ny = nl(), km = t10.___wasm_call_ctors = function() {
        return (km = t10.___wasm_call_ctors = t10.asm.__wasm_call_ctors).apply(null, arguments);
      }, Nm = t10._init = function() {
        return (Nm = t10._init = t10.asm.init).apply(null, arguments);
      }, Ty = t10._init_with_threads_count = function() {
        return (Ty = t10._init_with_threads_count = t10.asm.init_with_threads_count).apply(null, arguments);
      }, Tm = t10._get_threads_count = function() {
        return (Tm = t10._get_threads_count = t10.asm.get_threads_count).apply(null, arguments);
      }, _y = t10._register_tensor = function() {
        return (_y = t10._register_tensor = t10.asm.register_tensor).apply(null, arguments);
      }, Me = t10._dispose_data = function() {
        return (Me = t10._dispose_data = t10.asm.dispose_data).apply(null, arguments);
      }, al = t10._dispose = function() {
        return (al = t10._dispose = t10.asm.dispose).apply(null, arguments);
      }, Ey = t10._Abs = function() {
        return (Ey = t10._Abs = t10.asm.Abs).apply(null, arguments);
      }, _m = t10._Acos = function() {
        return (_m = t10._Acos = t10.asm.Acos).apply(null, arguments);
      }, Pp = t10._Acosh = function() {
        return (Pp = t10._Acosh = t10.asm.Acosh).apply(null, arguments);
      }, $y = t10._Add = function() {
        return ($y = t10._Add = t10.asm.Add).apply(null, arguments);
      }, Ry = t10._AddN = function() {
        return (Ry = t10._AddN = t10.asm.AddN).apply(null, arguments);
      }, Dy = t10._All = function() {
        return (Dy = t10._All = t10.asm.All).apply(null, arguments);
      }, Ay = t10._Any = function() {
        return (Ay = t10._Any = t10.asm.Any).apply(null, arguments);
      }, Fy = t10._ArgMax = function() {
        return (Fy = t10._ArgMax = t10.asm.ArgMax).apply(null, arguments);
      }, Em = t10._ArgMin = function() {
        return (Em = t10._ArgMin = t10.asm.ArgMin).apply(null, arguments);
      }, $m = t10._Asin = function() {
        return ($m = t10._Asin = t10.asm.Asin).apply(null, arguments);
      }, Py = t10._Asinh = function() {
        return (Py = t10._Asinh = t10.asm.Asinh).apply(null, arguments);
      }, Oy = t10._Atan = function() {
        return (Oy = t10._Atan = t10.asm.Atan).apply(null, arguments);
      }, My = t10._Atan2 = function() {
        return (My = t10._Atan2 = t10.asm.Atan2).apply(null, arguments);
      }, il = t10._Atanh = function() {
        return (il = t10._Atanh = t10.asm.Atanh).apply(null, arguments);
      }, Ly = t10._AvgPool = function() {
        return (Ly = t10._AvgPool = t10.asm.AvgPool).apply(null, arguments);
      }, By = t10._AvgPool3D = function() {
        return (By = t10._AvgPool3D = t10.asm.AvgPool3D).apply(null, arguments);
      }, zy = t10._AvgPool3DGrad = function() {
        return (zy = t10._AvgPool3DGrad = t10.asm.AvgPool3DGrad).apply(null, arguments);
      }, Nu = t10._AvgPoolGrad = function() {
        return (Nu = t10._AvgPoolGrad = t10.asm.AvgPoolGrad).apply(null, arguments);
      }, Vy = t10._BatchMatMul = function() {
        return (Vy = t10._BatchMatMul = t10.asm.BatchMatMul).apply(null, arguments);
      }, Wy = t10._Bincount = function() {
        return (Wy = t10._Bincount = t10.asm.Bincount).apply(null, arguments);
      }, Rm = t10._BitwiseAnd = function() {
        return (Rm = t10._BitwiseAnd = t10.asm.BitwiseAnd).apply(null, arguments);
      }, Uy = t10._Ceil = function() {
        return (Uy = t10._Ceil = t10.asm.Ceil).apply(null, arguments);
      }, ul = t10._ClipByValue = function() {
        return (ul = t10._ClipByValue = t10.asm.ClipByValue).apply(null, arguments);
      }, Gy = t10._Conv2D = function() {
        return (Gy = t10._Conv2D = t10.asm.Conv2D).apply(null, arguments);
      }, Hy = t10._Conv2DBackpropInput = function() {
        return (Hy = t10._Conv2DBackpropInput = t10.asm.Conv2DBackpropInput).apply(null, arguments);
      }, Ky = t10._Conv3D = function() {
        return (Ky = t10._Conv3D = t10.asm.Conv3D).apply(null, arguments);
      }, Ni = t10._Conv3DBackpropFilterV2 = function() {
        return (Ni = t10._Conv3DBackpropFilterV2 = t10.asm.Conv3DBackpropFilterV2).apply(null, arguments);
      }, pl = t10._Conv3DBackpropInputV2 = function() {
        return (pl = t10._Conv3DBackpropInputV2 = t10.asm.Conv3DBackpropInputV2).apply(null, arguments);
      }, qy = t10._Cos = function() {
        return (qy = t10._Cos = t10.asm.Cos).apply(null, arguments);
      }, jy = t10._Cosh = function() {
        return (jy = t10._Cosh = t10.asm.Cosh).apply(null, arguments);
      }, Xy = t10._CropAndResize = function() {
        return (Xy = t10._CropAndResize = t10.asm.CropAndResize).apply(null, arguments);
      }, Yy = t10._Cumprod = function() {
        return (Yy = t10._Cumprod = t10.asm.Cumprod).apply(null, arguments);
      }, Dm = t10._Cumsum = function() {
        return (Dm = t10._Cumsum = t10.asm.Cumsum).apply(null, arguments);
      }, Am = t10._DenseBincount = function() {
        return (Am = t10._DenseBincount = t10.asm.DenseBincount).apply(null, arguments);
      }, Qy = t10._DepthToSpace = function() {
        return (Qy = t10._DepthToSpace = t10.asm.DepthToSpace).apply(null, arguments);
      }, Zy = t10._DepthwiseConv2dNative = function() {
        return (Zy = t10._DepthwiseConv2dNative = t10.asm.DepthwiseConv2dNative).apply(null, arguments);
      }, Fm = t10._Diag = function() {
        return (Fm = t10._Diag = t10.asm.Diag).apply(null, arguments);
      }, Pm = t10._Dilation2D = function() {
        return (Pm = t10._Dilation2D = t10.asm.Dilation2D).apply(null, arguments);
      }, Jy = t10._Dilation2DBackpropFilter = function() {
        return (Jy = t10._Dilation2DBackpropFilter = t10.asm.Dilation2DBackpropFilter).apply(null, arguments);
      }, eb = t10._Dilation2DBackpropInput = function() {
        return (eb = t10._Dilation2DBackpropInput = t10.asm.Dilation2DBackpropInput).apply(null, arguments);
      }, tb = t10._Elu = function() {
        return (tb = t10._Elu = t10.asm.Elu).apply(null, arguments);
      }, rb = t10._EluGrad = function() {
        return (rb = t10._EluGrad = t10.asm.EluGrad).apply(null, arguments);
      }, Om = t10._Equal = function() {
        return (Om = t10._Equal = t10.asm.Equal).apply(null, arguments);
      }, g0 = t10._Erf = function() {
        return (g0 = t10._Erf = t10.asm.Erf).apply(null, arguments);
      }, ob = t10._Exp = function() {
        return (ob = t10._Exp = t10.asm.Exp).apply(null, arguments);
      }, nb = t10._Expm1 = function() {
        return (nb = t10._Expm1 = t10.asm.Expm1).apply(null, arguments);
      }, sb = t10._FlipLeftRight = function() {
        return (sb = t10._FlipLeftRight = t10.asm.FlipLeftRight).apply(null, arguments);
      }, ab = t10._Floor = function() {
        return (ab = t10._Floor = t10.asm.Floor).apply(null, arguments);
      }, ib = t10._FloorDiv = function() {
        return (ib = t10._FloorDiv = t10.asm.FloorDiv).apply(null, arguments);
      }, ub = t10._FusedBatchNorm = function() {
        return (ub = t10._FusedBatchNorm = t10.asm.FusedBatchNorm).apply(null, arguments);
      }, pb = t10._FusedConv2D = function() {
        return (pb = t10._FusedConv2D = t10.asm.FusedConv2D).apply(null, arguments);
      }, cb = t10._FusedDepthwiseConv2D = function() {
        return (cb = t10._FusedDepthwiseConv2D = t10.asm.FusedDepthwiseConv2D).apply(null, arguments);
      }, lb = t10._Gather = function() {
        return (lb = t10._Gather = t10.asm.Gather).apply(null, arguments);
      }, mb = t10._GatherNd = function() {
        return (mb = t10._GatherNd = t10.asm.GatherNd).apply(null, arguments);
      }, db = t10._Greater = function() {
        return (db = t10._Greater = t10.asm.Greater).apply(null, arguments);
      }, fb = t10._GreaterEqual = function() {
        return (fb = t10._GreaterEqual = t10.asm.GreaterEqual).apply(null, arguments);
      }, hb = t10._IsFinite = function() {
        return (hb = t10._IsFinite = t10.asm.IsFinite).apply(null, arguments);
      }, gb = t10._IsInf = function() {
        return (gb = t10._IsInf = t10.asm.IsInf).apply(null, arguments);
      }, xb = t10._IsNan = function() {
        return (xb = t10._IsNan = t10.asm.IsNan).apply(null, arguments);
      }, yb = t10._LRN = function() {
        return (yb = t10._LRN = t10.asm.LRN).apply(null, arguments);
      }, bb = t10._LRNGrad = function() {
        return (bb = t10._LRNGrad = t10.asm.LRNGrad).apply(null, arguments);
      }, Cb = t10._LeakyRelu = function() {
        return (Cb = t10._LeakyRelu = t10.asm.LeakyRelu).apply(null, arguments);
      }, wb = t10._Less = function() {
        return (wb = t10._Less = t10.asm.Less).apply(null, arguments);
      }, Sb = t10._LessEqual = function() {
        return (Sb = t10._LessEqual = t10.asm.LessEqual).apply(null, arguments);
      }, Ib = t10._LinSpace = function() {
        return (Ib = t10._LinSpace = t10.asm.LinSpace).apply(null, arguments);
      }, vb = t10._Log = function() {
        return (vb = t10._Log = t10.asm.Log).apply(null, arguments);
      }, kb = t10._Log1p = function() {
        return (kb = t10._Log1p = t10.asm.Log1p).apply(null, arguments);
      }, Nb = t10._LogicalAnd = function() {
        return (Nb = t10._LogicalAnd = t10.asm.LogicalAnd).apply(null, arguments);
      }, Tb = t10._LogicalNot = function() {
        return (Tb = t10._LogicalNot = t10.asm.LogicalNot).apply(null, arguments);
      }, _b = t10._LogicalOr = function() {
        return (_b = t10._LogicalOr = t10.asm.LogicalOr).apply(null, arguments);
      }, Eb = t10._LogicalXor = function() {
        return (Eb = t10._LogicalXor = t10.asm.LogicalXor).apply(null, arguments);
      }, $b = t10._Max = function() {
        return ($b = t10._Max = t10.asm.Max).apply(null, arguments);
      }, Rb = t10._MaxPool = function() {
        return (Rb = t10._MaxPool = t10.asm.MaxPool).apply(null, arguments);
      }, Db = t10._MaxPool3D = function() {
        return (Db = t10._MaxPool3D = t10.asm.MaxPool3D).apply(null, arguments);
      }, Ab = t10._MaxPool3DGrad = function() {
        return (Ab = t10._MaxPool3DGrad = t10.asm.MaxPool3DGrad).apply(null, arguments);
      }, Fb = t10._MaxPoolGrad = function() {
        return (Fb = t10._MaxPoolGrad = t10.asm.MaxPoolGrad).apply(null, arguments);
      }, Pb = t10._MaxPoolWithArgmax = function() {
        return (Pb = t10._MaxPoolWithArgmax = t10.asm.MaxPoolWithArgmax).apply(null, arguments);
      }, Ob = t10._Maximum = function() {
        return (Ob = t10._Maximum = t10.asm.Maximum).apply(null, arguments);
      }, Mb = t10._Mean = function() {
        return (Mb = t10._Mean = t10.asm.Mean).apply(null, arguments);
      }, Lb = t10._Min = function() {
        return (Lb = t10._Min = t10.asm.Min).apply(null, arguments);
      }, Bb = t10._Minimum = function() {
        return (Bb = t10._Minimum = t10.asm.Minimum).apply(null, arguments);
      }, zb = t10._MirrorPad = function() {
        return (zb = t10._MirrorPad = t10.asm.MirrorPad).apply(null, arguments);
      }, Vb = t10._Mod = function() {
        return (Vb = t10._Mod = t10.asm.Mod).apply(null, arguments);
      }, Wb = t10._Multinomial = function() {
        return (Wb = t10._Multinomial = t10.asm.Multinomial).apply(null, arguments);
      }, Ub = t10._Multiply = function() {
        return (Ub = t10._Multiply = t10.asm.Multiply).apply(null, arguments);
      }, Gb = t10._Neg = function() {
        return (Gb = t10._Neg = t10.asm.Neg).apply(null, arguments);
      }, Hb = t10._NonMaxSuppressionV3 = function() {
        return (Hb = t10._NonMaxSuppressionV3 = t10.asm.NonMaxSuppressionV3).apply(null, arguments);
      }, Kb = t10._NonMaxSuppressionV4 = function() {
        return (Kb = t10._NonMaxSuppressionV4 = t10.asm.NonMaxSuppressionV4).apply(null, arguments);
      }, qb = t10._NonMaxSuppressionV5 = function() {
        return (qb = t10._NonMaxSuppressionV5 = t10.asm.NonMaxSuppressionV5).apply(null, arguments);
      }, jb = t10._NotEqual = function() {
        return (jb = t10._NotEqual = t10.asm.NotEqual).apply(null, arguments);
      }, Xb = t10._OneHot = function() {
        return (Xb = t10._OneHot = t10.asm.OneHot).apply(null, arguments);
      }, Yb = t10._PadV2 = function() {
        return (Yb = t10._PadV2 = t10.asm.PadV2).apply(null, arguments);
      }, Qb = t10._Pow = function() {
        return (Qb = t10._Pow = t10.asm.Pow).apply(null, arguments);
      }, Zb = t10._Prelu = function() {
        return (Zb = t10._Prelu = t10.asm.Prelu).apply(null, arguments);
      }, Jb = t10._Prod = function() {
        return (Jb = t10._Prod = t10.asm.Prod).apply(null, arguments);
      }, eC = t10._RealDiv = function() {
        return (eC = t10._RealDiv = t10.asm.RealDiv).apply(null, arguments);
      }, tC = t10._Reciprocal = function() {
        return (tC = t10._Reciprocal = t10.asm.Reciprocal).apply(null, arguments);
      }, rC = t10._Relu = function() {
        return (rC = t10._Relu = t10.asm.Relu).apply(null, arguments);
      }, oC = t10._Relu6 = function() {
        return (oC = t10._Relu6 = t10.asm.Relu6).apply(null, arguments);
      }, nC = t10._ResizeBilinear = function() {
        return (nC = t10._ResizeBilinear = t10.asm.ResizeBilinear).apply(null, arguments);
      }, sC = t10._ResizeBilinearGrad = function() {
        return (sC = t10._ResizeBilinearGrad = t10.asm.ResizeBilinearGrad).apply(null, arguments);
      }, aC = t10._ResizeNearestNeighbor = function() {
        return (aC = t10._ResizeNearestNeighbor = t10.asm.ResizeNearestNeighbor).apply(null, arguments);
      }, iC = t10._ResizeNearestNeighborGrad = function() {
        return (iC = t10._ResizeNearestNeighborGrad = t10.asm.ResizeNearestNeighborGrad).apply(null, arguments);
      }, uC = t10._Reverse = function() {
        return (uC = t10._Reverse = t10.asm.Reverse).apply(null, arguments);
      }, pC = t10._RotateWithOffset = function() {
        return (pC = t10._RotateWithOffset = t10.asm.RotateWithOffset).apply(null, arguments);
      }, cC = t10._Round = function() {
        return (cC = t10._Round = t10.asm.Round).apply(null, arguments);
      }, lC = t10._Rsqrt = function() {
        return (lC = t10._Rsqrt = t10.asm.Rsqrt).apply(null, arguments);
      }, mC = t10._ScatterNd = function() {
        return (mC = t10._ScatterNd = t10.asm.ScatterNd).apply(null, arguments);
      }, dC = t10._SearchSorted = function() {
        return (dC = t10._SearchSorted = t10.asm.SearchSorted).apply(null, arguments);
      }, fC = t10._SelectV2 = function() {
        return (fC = t10._SelectV2 = t10.asm.SelectV2).apply(null, arguments);
      }, hC = t10._Selu = function() {
        return (hC = t10._Selu = t10.asm.Selu).apply(null, arguments);
      }, gC = t10._Sigmoid = function() {
        return (gC = t10._Sigmoid = t10.asm.Sigmoid).apply(null, arguments);
      }, xC = t10._Sign = function() {
        return (xC = t10._Sign = t10.asm.Sign).apply(null, arguments);
      }, yC = t10._Sin = function() {
        return (yC = t10._Sin = t10.asm.Sin).apply(null, arguments);
      }, bC = t10._Sinh = function() {
        return (bC = t10._Sinh = t10.asm.Sinh).apply(null, arguments);
      }, CC = t10._Softmax = function() {
        return (CC = t10._Softmax = t10.asm.Softmax).apply(null, arguments);
      }, wC = t10._Softplus = function() {
        return (wC = t10._Softplus = t10.asm.Softplus).apply(null, arguments);
      }, SC = t10._SparseFillEmptyRows = function() {
        return (SC = t10._SparseFillEmptyRows = t10.asm.SparseFillEmptyRows).apply(null, arguments);
      }, IC = t10._SparseReshape = function() {
        return (IC = t10._SparseReshape = t10.asm.SparseReshape).apply(null, arguments);
      }, vC = t10._SparseSegmentReduction = function() {
        return (vC = t10._SparseSegmentReduction = t10.asm.SparseSegmentReduction).apply(null, arguments);
      }, kC = t10._SparseToDense = function() {
        return (kC = t10._SparseToDense = t10.asm.SparseToDense).apply(null, arguments);
      }, NC = t10._Sqrt = function() {
        return (NC = t10._Sqrt = t10.asm.Sqrt).apply(null, arguments);
      }, TC = t10._Square = function() {
        return (TC = t10._Square = t10.asm.Square).apply(null, arguments);
      }, _C = t10._SquaredDifference = function() {
        return (_C = t10._SquaredDifference = t10.asm.SquaredDifference).apply(null, arguments);
      }, EC = t10._Step = function() {
        return (EC = t10._Step = t10.asm.Step).apply(null, arguments);
      }, $C = t10._StridedSlice = function() {
        return ($C = t10._StridedSlice = t10.asm.StridedSlice).apply(null, arguments);
      }, RC = t10._Sub = function() {
        return (RC = t10._Sub = t10.asm.Sub).apply(null, arguments);
      }, DC = t10._Sum = function() {
        return (DC = t10._Sum = t10.asm.Sum).apply(null, arguments);
      }, AC = t10._Tan = function() {
        return (AC = t10._Tan = t10.asm.Tan).apply(null, arguments);
      }, FC = t10._Tanh = function() {
        return (FC = t10._Tanh = t10.asm.Tanh).apply(null, arguments);
      }, PC = t10._TensorScatterUpdate = function() {
        return (PC = t10._TensorScatterUpdate = t10.asm.TensorScatterUpdate).apply(null, arguments);
      }, OC = t10._Tile = function() {
        return (OC = t10._Tile = t10.asm.Tile).apply(null, arguments);
      }, MC = t10._TopK = function() {
        return (MC = t10._TopK = t10.asm.TopK).apply(null, arguments);
      }, LC = t10._Transform = function() {
        return (LC = t10._Transform = t10.asm.Transform).apply(null, arguments);
      }, BC = t10._Transpose = function() {
        return (BC = t10._Transpose = t10.asm.Transpose).apply(null, arguments);
      }, zC = t10.__FusedMatMul = function() {
        return (zC = t10.__FusedMatMul = t10.asm._FusedMatMul).apply(null, arguments);
      }, VC = t10._malloc = function() {
        return (VC = t10._malloc = t10.asm.malloc).apply(null, arguments);
      }, WC = t10._free = function() {
        return (WC = t10._free = t10.asm.free).apply(null, arguments);
      }, UC = t10.___errno_location = function() {
        return (UC = t10.___errno_location = t10.asm.__errno_location).apply(null, arguments);
      }, Mm = t10.stackSave = function() {
        return (Mm = t10.stackSave = t10.asm.stackSave).apply(null, arguments);
      }, Lm = t10.stackRestore = function() {
        return (Lm = t10.stackRestore = t10.asm.stackRestore).apply(null, arguments);
      }, cl = t10.stackAlloc = function() {
        return (cl = t10.stackAlloc = t10.asm.stackAlloc).apply(null, arguments);
      }, GC = t10.dynCall_iijjiiii = function() {
        return (GC = t10.dynCall_iijjiiii = t10.asm.dynCall_iijjiiii).apply(null, arguments);
      }, HC = t10.dynCall_jiji = function() {
        return (HC = t10.dynCall_jiji = t10.asm.dynCall_jiji).apply(null, arguments);
      };
      t10.cwrap = ky;
      var Op;
      nr = function K() {
        Op || Bm(), Op || (nr = K);
      };
      function Bm(K) {
        if (K = K || i, Tt > 0 || (ht(), Tt > 0)) return;
        function ae() {
          Op || (Op = true, t10.calledRun = true, !M && (gt(), o(t10), t10.onRuntimeInitialized && t10.onRuntimeInitialized(), Lr()));
        }
        t10.setStatus ? (t10.setStatus("Running..."), setTimeout(function() {
          setTimeout(function() {
            t10.setStatus("");
          }, 1), ae();
        }, 1)) : ae();
      }
      if (t10.preInit) for (typeof t10.preInit == "function" && (t10.preInit = [t10.preInit]); t10.preInit.length > 0; ) t10.preInit.pop()();
      Bm();
      var Mp;
      s && (Mp = { uncaughtException: process.listeners("uncaughtException").filter(function(K) {
        return !s.uncaughtException.indexOf(K) > -1;
      }), unhandledRejection: process.listeners("unhandledRejection").filter(function(K) {
        return !s.unhandledRejection.indexOf(K) > -1;
      }) });
      var Lp;
      if (typeof e != "undefined") Lp = e;
      else if (typeof WasmBackendModuleThreadedSimd != "undefined") Lp = WasmBackendModuleThreadedSimd;
      else throw new Error("Could not find wasm module in post.js");
      if (Mp) {
        var KC = Lp._dispose;
        Lp._dispose = function() {
          KC(), Mp.uncaughtException.forEach(function(K) {
            process.removeListener("uncaughtException", K);
          }), Mp.unhandledRejection.forEach(function(K) {
            process.removeListener("unhandledRejection", K);
          });
        };
      }
      return e.ready;
    });
  })();
  typeof Ug == "object" && typeof Kv == "object" ? Kv.exports = Hv : typeof define == "function" && define.amd ? define([], function() {
    return Hv;
  }) : typeof Ug == "object" && (Ug.WasmBackendModule = Hv);
});
var Bo = class {
  constructor(e, t10) {
    this.backend = e, this.dataMover = t10, this.data = /* @__PURE__ */ new WeakMap(), this.dataIdsCount = 0;
  }
  get(e) {
    return this.data.has(e) || this.dataMover.moveData(this.backend, e), this.data.get(e);
  }
  set(e, t10) {
    this.dataIdsCount++, this.data.set(e, t10);
  }
  has(e) {
    return this.data.has(e);
  }
  delete(e) {
    return this.dataIdsCount--, this.data.delete(e);
  }
  numDataIds() {
    return this.dataIdsCount;
  }
};
var ao = class {
  refCount(e) {
    return zr("refCount");
  }
  incRef(e) {
    return zr("incRef");
  }
  timerAvailable() {
    return true;
  }
  time(e) {
    return zr("time");
  }
  read(e) {
    return zr("read");
  }
  readSync(e) {
    return zr("readSync");
  }
  readToGPU(e, t10) {
    return zr("readToGPU");
  }
  numDataIds() {
    return zr("numDataIds");
  }
  disposeData(e, t10) {
    return zr("disposeData");
  }
  write(e, t10, o) {
    return zr("write");
  }
  move(e, t10, o, n, s) {
    return zr("move");
  }
  createTensorFromGPUData(e, t10, o) {
    return zr("createTensorFromGPUData");
  }
  memory() {
    return zr("memory");
  }
  floatPrecision() {
    return zr("floatPrecision");
  }
  epsilon() {
    return this.floatPrecision() === 32 ? 1e-7 : 1e-4;
  }
  dispose() {
    return zr("dispose");
  }
};
function zr(r15) {
  throw new Error(`'${r15}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`);
}
function k0(r15) {
  let e = r15.length, t10 = 0;
  for (; e > 0; ) t10 = Math.random() * e | 0, e--, jm(r15, e, t10);
}
function FG(r15, e) {
  if (r15.length !== e.length) throw new Error(`Array sizes must match to be shuffled together First array length was ${r15.length}Second array length was ${e.length}`);
  let t10 = r15.length, o = 0;
  for (; t10 > 0; ) o = Math.random() * t10 | 0, t10--, jm(r15, t10, o), jm(e, t10, o);
}
function Vp(r15, e, t10) {
  return Math.max(r15, Math.min(e, t10));
}
function PG(r15) {
  return r15 % 2 === 0 ? r15 : r15 + 1;
}
function jm(r15, e, t10) {
  let o = r15[e];
  r15[e] = r15[t10], r15[t10] = o;
}
function OG(r15) {
  let e = 0;
  for (let t10 = 0; t10 < r15.length; t10++) e += r15[t10];
  return e;
}
function MG(r15, e) {
  let t10 = Math.random();
  return e * t10 + (1 - t10) * r15;
}
function LG(r15, e) {
  let t10 = 0;
  for (let o = 0; o < r15.length; o++) {
    let n = Number(r15[o]) - Number(e[o]);
    t10 += n * n;
  }
  return t10;
}
function E(r15, e) {
  if (!r15) throw new Error(typeof e == "string" ? e : e());
}
function xt(r15, e, t10 = "") {
  E(br(r15, e), () => t10 + ` Shapes ${r15} and ${e} must match`);
}
function io(r15) {
  E(r15 != null, () => "The input to the tensor constructor must be a non-null value.");
}
function ze(r15) {
  if (r15.length === 0) return 1;
  let e = r15[0];
  for (let t10 = 1; t10 < r15.length; t10++) e *= r15[t10];
  return e;
}
function BG(r15) {
  return r15.length === 0;
}
function ZC(r15, e) {
  if (r15 === e) return true;
  if (r15 == null || e == null || r15.length !== e.length) return false;
  for (let t10 = 0; t10 < r15.length; t10++) if (r15[t10] !== null && e[t10] !== null && r15[t10] !== e[t10]) return false;
  return true;
}
function br(r15, e) {
  if (r15 === e) return true;
  if (r15 == null || e == null || r15.length !== e.length) return false;
  for (let t10 = 0; t10 < r15.length; t10++) if (r15[t10] !== e[t10]) return false;
  return true;
}
function Ka(r15) {
  return r15 % 1 === 0;
}
function zG(r15) {
  if (Math.tanh != null) return Math.tanh(r15);
  if (r15 === 1 / 0) return 1;
  if (r15 === -1 / 0) return -1;
  {
    let e = Math.exp(2 * r15);
    return (e - 1) / (e + 1);
  }
}
function VG(r15) {
  let e = Math.ceil(Math.sqrt(r15));
  return [e, Math.ceil(r15 / e)];
}
function WG(r15) {
  let e = new Uint32Array(r15);
  for (let t10 = 0; t10 < r15; ++t10) e[t10] = t10;
  return k0(e), e;
}
function _u(r15, e) {
  return e <= r15.length ? r15 : r15 + " ".repeat(e - r15.length);
}
function UG(r15, e = (n) => 0, t10, o) {
  return new Promise((n, s) => {
    let a = 0, i = () => {
      if (r15()) {
        n();
        return;
      }
      a++;
      let p = e(a);
      if (t10 != null && a >= t10) {
        s();
        return;
      }
      o != null ? o(i, p) : setTimeout(i, p);
    };
    i();
  });
}
function GG(r15, e) {
  let t10 = 1, o = -1;
  for (let s = 0; s < r15.length; ++s) if (r15[s] >= 0) t10 *= r15[s];
  else if (r15[s] === -1) {
    if (o !== -1) throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${o} and dim ${s}`);
    o = s;
  } else if (r15[s] < 0) throw Error(`Shapes can not be < 0. Found ${r15[s]} at dim ${s}`);
  if (o === -1) {
    if (e > 0 && e !== t10) throw Error(`Size(${e}) must match the product of shape ${r15}`);
    return r15;
  }
  if (t10 === 0) throw Error(`Cannot infer the missing size in [${r15}] when there are 0 elements`);
  if (e % t10 !== 0) throw Error(`The implicit shape can't be a fractional number. Got ${e} / ${t10}`);
  let n = r15.slice();
  return n[o] = e / t10, n;
}
function _i(r15, e) {
  let t10 = e.length;
  return r15 = r15 == null ? e.map((o, n) => n) : [].concat(r15), E(r15.every((o) => o >= -t10 && o < t10), () => `All values in axis param must be in range [-${t10}, ${t10}) but got axis ${r15}`), E(r15.every((o) => Ka(o)), () => `All values in axis param must be integers but got axis ${r15}`), r15.map((o) => o < 0 ? t10 + o : o);
}
function JC(r15, e) {
  let t10 = [], o = [], n = e != null && Array.isArray(e) && e.length === 0, s = e == null || n ? null : _i(e, r15).sort(), a = 0;
  for (let i = 0; i < r15.length; ++i) {
    if (s != null) {
      if (s[a] === i && r15[i] !== 1) throw new Error(`Can't squeeze axis ${i} since its dim '${r15[i]}' is not 1`);
      (s[a] == null || s[a] > i) && r15[i] === 1 && (t10.push(r15[i]), o.push(i)), s[a] <= i && a++;
    }
    r15[i] !== 1 && (t10.push(r15[i]), o.push(i));
  }
  return { newShape: t10, keptDims: o };
}
function ew(r15, e) {
  return Xm(r15, e);
}
function Xm(r15, e) {
  let t10 = null;
  if (r15 == null || r15 === "float32") t10 = new Float32Array(e);
  else if (r15 === "int32") t10 = new Int32Array(e);
  else if (r15 === "bool") t10 = new Uint8Array(e);
  else if (r15 === "string") t10 = new Array(e);
  else throw new Error(`Unknown data type ${r15}`);
  return t10;
}
function tw(r15, e) {
  for (let t10 = 0; t10 < r15.length; t10++) {
    let o = r15[t10];
    if (isNaN(o) || !isFinite(o)) throw Error(`A tensor of type ${e} being uploaded contains ${o}.`);
  }
}
function rw(r15) {
  return r15 === "bool" || r15 === "complex64" || r15 === "float32" || r15 === "int32" || r15 === "string";
}
function HG(r15, e) {
  return !(e === "complex64" || e === "float32" && r15 !== "complex64" || e === "int32" && r15 !== "float32" && r15 !== "complex64" || e === "bool" && r15 === "bool");
}
function Wp(r15) {
  if (r15 === "float32" || r15 === "int32") return 4;
  if (r15 === "complex64") return 8;
  if (r15 === "bool") return 1;
  throw new Error(`Unknown dtype ${r15}`);
}
function ow(r15) {
  if (r15 == null) return 0;
  let e = 0;
  return r15.forEach((t10) => e += t10.length), e;
}
function zo(r15) {
  return typeof r15 == "string" || r15 instanceof String;
}
function N0(r15) {
  return typeof r15 == "boolean";
}
function T0(r15) {
  return typeof r15 == "number";
}
function Ei(r15) {
  return Array.isArray(r15) ? Ei(r15[0]) : r15 instanceof Float32Array ? "float32" : r15 instanceof Int32Array || r15 instanceof Uint8Array || r15 instanceof Uint8ClampedArray ? "int32" : T0(r15) ? "float32" : zo(r15) ? "string" : N0(r15) ? "bool" : "float32";
}
function qs(r15) {
  return !!(r15 && r15.constructor && r15.call && r15.apply);
}
function Up(r15, e) {
  for (let t10 = e; t10 < r15; ++t10) if (r15 % t10 === 0) return t10;
  return r15;
}
function js(r15) {
  let e = r15.length;
  if (e < 2) return [];
  let t10 = new Array(e - 1);
  t10[e - 2] = r15[e - 1];
  for (let o = e - 3; o >= 0; --o) t10[o] = t10[o + 1] * r15[o + 1];
  return t10;
}
function _0(r15, e, t10, o = false) {
  let n = new Array();
  if (e.length === 1) {
    let s = e[0] * (o ? 2 : 1);
    for (let a = 0; a < s; a++) n[a] = t10[r15 + a];
  } else {
    let s = e[0], a = e.slice(1), i = a.reduce((p, u) => p * u) * (o ? 2 : 1);
    for (let p = 0; p < s; p++) n[p] = _0(r15 + p * i, a, t10, o);
  }
  return n;
}
function Tu(r15, e, t10 = false) {
  if (r15.length === 0) return e[0];
  let o = r15.reduce((n, s) => n * s) * (t10 ? 2 : 1);
  if (o === 0) return [];
  if (o !== e.length) throw new Error(`[${r15}] does not match the input size ${e.length}${t10 ? " for a complex tensor" : ""}.`);
  return _0(0, r15, e, t10);
}
function KG(r15, e) {
  if (Array.isArray(r15)) return r15;
  if (e === "float32") return r15 instanceof Float32Array ? r15 : new Float32Array(r15);
  if (e === "int32") return r15 instanceof Int32Array ? r15 : new Int32Array(r15);
  if (e === "bool" || e === "string") return Uint8Array.from(new Int32Array(r15));
  throw new Error(`Unknown dtype ${e}`);
}
function ml(r15, e) {
  let t10 = Gp(r15, e);
  for (let o = 0; o < t10.length; o++) t10[o] = 1;
  return t10;
}
function Gp(r15, e) {
  if (e == null || e === "float32" || e === "complex64") return new Float32Array(r15);
  if (e === "int32") return new Int32Array(r15);
  if (e === "bool") return new Uint8Array(r15);
  throw new Error(`Unknown data type ${e}`);
}
function qG(r15, e) {
  let t10 = r15.reduce((o, n) => o * n, 1);
  if (e == null || e === "float32") return Tu(r15, new Float32Array(t10));
  if (e === "int32") return Tu(r15, new Int32Array(t10));
  if (e === "bool") return Tu(r15, new Uint8Array(t10));
  throw new Error(`Unknown data type ${e}`);
}
function Ct(r15) {
  r15.forEach((e) => {
    E(Number.isInteger(e) && e >= 0, () => `Tensor must have a shape comprised of positive integers but got shape [${r15}].`);
  });
}
function jG(r15, e, t10) {
  if (e === 0) return 0;
  if (e === 1) return r15[0];
  let o = r15[r15.length - 1];
  for (let n = 0; n < r15.length - 1; ++n) o += t10[n] * r15[n];
  return o;
}
function XG(r15, e, t10) {
  if (e === 0) return [];
  if (e === 1) return [r15];
  let o = new Array(e);
  for (let n = 0; n < o.length - 1; ++n) o[n] = Math.floor(r15 / t10[n]), r15 -= o[n] * t10[n];
  return o[o.length - 1] = r15, o;
}
function Eu(r15) {
  return r15 && r15.then && typeof r15.then == "function";
}
var E0 = "tfjsflags";
var dl = class {
  constructor(e) {
    this.global = e, this.flags = {}, this.flagRegistry = {}, this.urlFlags = {}, this.getQueryParams = QG, this.populateURLFlags();
  }
  setPlatform(e, t10) {
    this.platform != null && (A().getBool("IS_TEST") || A().getBool("PROD") || console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)), this.platformName = e, this.platform = t10;
  }
  registerFlag(e, t10, o) {
    if (this.flagRegistry[e] = { evaluationFn: t10, setHook: o }, this.urlFlags[e] != null) {
      let n = this.urlFlags[e];
      A().getBool("IS_TEST") || A().getBool("PROD") || console.warn(`Setting feature override from URL ${e}: ${n}.`), this.set(e, n);
    }
  }
  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 t10 = this.evaluateFlag(e);
    if (Eu(t10)) throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);
    return this.flags[e] = t10, this.flags[e];
  }
  getNumber(e) {
    return this.get(e);
  }
  getBool(e) {
    return this.get(e);
  }
  getString(e) {
    return this.get(e);
  }
  getFlags() {
    return this.flags;
  }
  get features() {
    return this.flags;
  }
  set(e, t10) {
    if (this.flagRegistry[e] == null) throw new Error(`Cannot set flag ${e} as it has not been registered.`);
    this.flags[e] = t10, this.flagRegistry[e].setHook != null && this.flagRegistry[e].setHook(t10);
  }
  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);
    E0 in e && e[E0].split(",").forEach((o) => {
      let [n, s] = o.split(":");
      this.urlFlags[n] = JG(n, s);
    });
  }
};
function QG(r15) {
  let e = {};
  return r15.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (t10, ...o) => (ZG(e, o[0], o[1]), o.join("="))), e;
}
function ZG(r15, e, t10) {
  r15[decodeURIComponent(e)] = decodeURIComponent(t10 || "");
}
function JG(r15, e) {
  let t10 = e.toLowerCase();
  return t10 === "true" || t10 === "false" ? t10 === "true" : `${+t10}` === t10 ? +t10 : e;
}
function A() {
  return nw;
}
var nw = null;
function $0(r15) {
  nw = r15;
}
var sw;
function aw() {
  if (sw == null) {
    let r15;
    if (typeof window != "undefined") r15 = window;
    else if (typeof global != "undefined") r15 = global;
    else if (typeof process != "undefined") r15 = process;
    else if (typeof self != "undefined") r15 = self;
    else throw new Error("Could not find a global object");
    sw = r15;
  }
  return sw;
}
function e4() {
  let r15 = aw();
  return r15._tfGlobals == null && (r15._tfGlobals = /* @__PURE__ */ new Map()), r15._tfGlobals;
}
function fl(r15, e) {
  let t10 = e4();
  if (t10.has(r15)) return t10.get(r15);
  {
    let o = e();
    return t10.set(r15, o), t10.get(r15);
  }
}
var Xs = "Abs";
var Vo = "Acos";
var Wo = "Acosh";
var uo = "Add";
var Uo = "AddN";
var Go = "All";
var Ho = "Any";
var Ys = "ArgMax";
var Qs = "ArgMin";
var Ko = "Asin";
var qo = "Asinh";
var jo = "Atan";
var Xo = "Atanh";
var Yo = "Atan2";
var Qo = "AvgPool";
var $i = "AvgPoolGrad";
var Zs = "AvgPool3D";
var Ri = "AvgPool3DGrad";
var Zo = "BatchMatMul";
var Js = "BatchToSpaceND";
var Jo = "Bincount";
var qa = "BitwiseAnd";
var qce = "BroadcastTo";
var ea = "BroadcastArgs";
var yo = "Cast";
var en = "Ceil";
var bo = "ClipByValue";
var Di = "Complex";
var Ai = "ComplexAbs";
var ta = "Concat";
var tn = "Conv2D";
var Fi = "Conv2DBackpropFilter";
var rn = "Conv2DBackpropInput";
var on = "Conv3D";
var ja = "Conv3DBackpropFilterV2";
var nn = "Conv3DBackpropInputV2";
var sn = "Cos";
var an = "Cosh";
var un = "Cumprod";
var pn = "Cumsum";
var cn = "CropAndResize";
var ra = "DenseBincount";
var ln = "DepthToSpace";
var mn = "DepthwiseConv2dNative";
var Pi = "DepthwiseConv2dNativeBackpropFilter";
var Oi = "DepthwiseConv2dNativeBackpropInput";
var oa = "Diag";
var dn = "Dilation2D";
var Mi = "Dilation2DBackpropInput";
var Li = "Dilation2DBackpropFilter";
var $u = "Draw";
var fn = "RealDiv";
var Bi = "Einsum";
var hn = "Elu";
var Xa = "EluGrad";
var gn = "Erf";
var xn = "Equal";
var yn = "Exp";
var na = "ExpandDims";
var bn = "Expm1";
var zi = "FFT";
var sa = "Fill";
var Cn = "FlipLeftRight";
var wn = "Floor";
var Sn = "FloorDiv";
var In = "FusedBatchNorm";
var aa = "GatherV2";
var vn = "GatherNd";
var kn = "Greater";
var Nn = "GreaterEqual";
var Co = "Identity";
var Vi = "IFFT";
var Wi = "Imag";
var Tn = "IsFinite";
var _n = "IsInf";
var En = "IsNan";
var $n = "LeakyRelu";
var Rn = "Less";
var Dn = "LessEqual";
var An = "LinSpace";
var Fn = "Log";
var Pn = "Log1p";
var On = "LogicalAnd";
var Mn = "LogicalNot";
var Ln = "LogicalOr";
var R0 = "LogicalXor";
var jce = "LogSoftmax";
var Xce = "LowerBound";
var Bn = "LRN";
var Ya = "LRNGrad";
var Yce = "MatrixBandPart";
var zn = "Max";
var Vn = "Maximum";
var Wn = "MaxPool";
var Ui = "MaxPoolGrad";
var ia = "MaxPool3D";
var Gi = "MaxPool3DGrad";
var ua = "MaxPoolWithArgmax";
var Un = "Mean";
var Gn = "Min";
var Hn = "Minimum";
var Kn = "MirrorPad";
var qn = "Mod";
var jn = "Multinomial";
var Xn = "Multiply";
var pa = "Neg";
var Yn = "NotEqual";
var Qn = "NonMaxSuppressionV3";
var Qa = "NonMaxSuppressionV4";
var Zn = "NonMaxSuppressionV5";
var ca = "OnesLike";
var Jn = "OneHot";
var la = "Pack";
var es = "PadV2";
var Qce = "Pool";
var ts = "Pow";
var rs = "Prelu";
var os = "Prod";
var Hp = "RaggedGather";
var Kp = "RaggedRange";
var qp = "RaggedTensorToTensor";
var ma = "Range";
var Hi = "Real";
var ns = "Reciprocal";
var ss = "Relu";
var da = "Reshape";
var as = "ResizeNearestNeighbor";
var Za = "ResizeNearestNeighborGrad";
var is = "ResizeBilinear";
var Ja = "ResizeBilinearGrad";
var us = "Relu6";
var ps = "Reverse";
var cs = "Round";
var ls = "Rsqrt";
var ms = "ScatterNd";
var ds = "TensorScatterUpdate";
var fs = "SearchSorted";
var fa = "Select";
var hs = "Selu";
var ha = "Slice";
var gs = "Sin";
var xs = "Sinh";
var ys = "Sign";
var bs = "Sigmoid";
var Cs = "Softplus";
var ws = "Sqrt";
var Ss = "Sum";
var ga = "SpaceToBatchND";
var xa = "SplitV";
var Is = "Softmax";
var Ki = "SparseFillEmptyRows";
var ei = "SparseReshape";
var ya = "SparseSegmentMean";
var ba = "SparseSegmentSum";
var vs = "SparseToDense";
var ks = "SquaredDifference";
var qi = "Square";
var Ru = "StaticRegexReplace";
var Ns = "StridedSlice";
var Ca = "StringNGrams";
var ji = "StringSplit";
var Xi = "StringToHashBucketFast";
var Ts = "Sub";
var _s = "Tan";
var Es = "Tanh";
var po = "Tile";
var $s = "TopK";
var Rs = "Transform";
var co = "Transpose";
var Yi = "Unique";
var wa = "Unpack";
var Qi = "UnsortedSegmentSum";
var Zce = "UpperBound";
var Sa = "ZerosLike";
var wo = "Step";
var Du = "FromPixels";
var Ds = "RotateWithOffset";
var So = "_FusedMatMul";
var Io = "FusedConv2D";
var vo = "FusedDepthwiseConv2D";
function Ia(...r15) {
  A().getBool("IS_TEST") || A().getBool("PROD") || console.warn(...r15);
}
function t4(...r15) {
  A().getBool("IS_TEST") || A().getBool("PROD") || console.log(...r15);
}
var jp = fl("kernelRegistry", () => /* @__PURE__ */ new Map());
var hl = fl("gradRegistry", () => /* @__PURE__ */ new Map());
function Xp(r15, e) {
  let t10 = uw(r15, e);
  return jp.get(t10);
}
function iw(r15) {
  return hl.get(r15);
}
function Ym(r15) {
  let e = jp.entries(), t10 = [];
  for (; ; ) {
    let { done: o, value: n } = e.next();
    if (o) break;
    let [s, a] = n, [i] = s.split("_");
    i === r15 && t10.push(a);
  }
  return t10;
}
function ti(r15) {
  let { kernelName: e, backendName: t10 } = r15, o = uw(e, t10);
  jp.has(o) && Ia(`The kernel '${e}' for backend '${t10}' is already registered`), jp.set(o, r15);
}
function ole(r15) {
  let { kernelName: e } = r15;
  hl.has(e) && A().getBool("DEBUG") && Ia(`Overriding the gradient for '${e}'`), hl.set(e, r15);
}
function nle(r15, e) {
  let t10 = uw(r15, e);
  if (!jp.has(t10)) throw new Error(`The kernel '${r15}' for backend '${e}' is not registered`);
  jp.delete(t10);
}
function sle(r15) {
  if (!hl.has(r15)) throw new Error(`The gradient '${r15}' for backend is not registered`);
  hl.delete(r15);
}
function ale(r15, e) {
  Ym(r15).forEach((o) => {
    let n = Object.assign({}, o, { backendName: e });
    ti(n);
  });
}
function uw(r15, e) {
  return `${e}_${r15}`;
}
var y = {};
qe(y, { arraysEqual: () => br, arraysEqualWithNull: () => ZC, assert: () => E, assertNonNegativeIntegerDimensions: () => Ct, assertNonNull: () => io, assertShapesMatch: () => xt, bytesFromStringArray: () => ow, bytesPerElement: () => Wp, checkConversionForErrors: () => tw, clamp: () => Vp, computeStrides: () => js, convertBackendValuesAndArrayBuffer: () => KG, createScalarValue: () => u4, createShuffledIndices: () => WG, decodeString: () => Jp, distSquared: () => LG, encodeString: () => Ji, fetch: () => c4, fingerPrint64: () => i4, flatten: () => Fs, getArrayFromDType: () => Xm, getTypedArrayFromDType: () => ew, hasEncodingLoss: () => HG, hexToLong: () => gl, indexToLoc: () => XG, inferDtype: () => Ei, inferFromImplicitShape: () => GG, isBoolean: () => N0, isFunction: () => qs, isInt: () => Ka, isNumber: () => T0, isPromise: () => Eu, isScalarShape: () => BG, isString: () => zo, isTypedArray: () => Pt, isValidDtype: () => rw, locToIndex: () => jG, makeOnesTypedArray: () => ml, makeZerosNestedTypedArray: () => qG, makeZerosTypedArray: () => Gp, nearestDivisor: () => Up, nearestLargerEven: () => PG, now: () => Mu, parseAxisParam: () => _i, randUniform: () => MG, repeatedTry: () => UG, rightPad: () => _u, shuffle: () => k0, shuffleCombo: () => FG, sizeFromShape: () => ze, sizeToSquarishShape: () => VG, squeezeShape: () => JC, sum: () => OG, swap: () => jm, tanh: () => zG, toNestedArray: () => Tu, toTypedArray: () => Zp });
function Qm(r15) {
  return r15 instanceof Float32Array || r15 instanceof Int32Array || r15 instanceof Uint8Array || r15 instanceof Uint8ClampedArray;
}
var mw = zp(U0());
var Ou = mw.default || mw;
function gl(r15) {
  return Ou.fromString(r15, true, 16);
}
var H0 = gl("c3a5c85c97cb3127");
var Pu = gl("b492b66fbe98f273");
var Cr = gl("9ae16a3b2f90404f");
function lw(r15) {
  return r15.xor(r15.shru(47));
}
function K0(r15, e, t10) {
  let o = r15.slice(e, e + t10);
  return Ou.fromBytes(Array.from(o), true, true);
}
function wt(r15, e) {
  return K0(r15, e, 8);
}
function G0(r15, e) {
  return K0(r15, e, 4);
}
function Yt(r15, e) {
  return e === 0 ? r15 : r15.shru(e).or(r15.shl(64 - e));
}
function Zi(r15, e, t10 = gl("9ddfea08eb382d69")) {
  let o = r15.xor(e).mul(t10);
  o = o.xor(o.shru(47));
  let n = e.xor(o).mul(t10);
  return n = n.xor(n.shru(47)), n = n.mul(t10), n;
}
function o4(r15, e, t10, o, n, s) {
  n = n.add(r15), s = Yt(s.add(n).add(o), 21);
  let a = n;
  return n = n.add(e), n = n.add(t10), s = s.add(Yt(n, 44)), [n.add(o), s.add(a)];
}
function Jm(r15, e, t10, o) {
  return o4(wt(r15, e), wt(r15, e + 8), wt(r15, e + 16), wt(r15, e + 24), t10, o);
}
function n4(r15, e = r15.length) {
  if (e >= 8) {
    let t10 = Cr.add(e * 2), o = wt(r15, 0).add(Cr), n = wt(r15, e - 8), s = Yt(n, 37).mul(t10).add(o), a = Yt(o, 25).add(n).mul(t10);
    return Zi(s, a, t10);
  }
  if (e >= 4) {
    let t10 = Cr.add(e * 2), o = G0(r15, 0);
    return Zi(o.shl(3).add(e), G0(r15, e - 4), t10);
  }
  if (e > 0) {
    let t10 = r15[0], o = r15[e >> 1], n = r15[e - 1], s = t10 + (o << 8), a = e + (n << 2);
    return lw(Cr.mul(s).xor(H0.mul(a))).mul(Cr);
  }
  return Cr;
}
function s4(r15, e = r15.length) {
  let t10 = Cr.add(e * 2), o = wt(r15, 0).mul(Pu), n = wt(r15, 8), s = wt(r15, e - 8).mul(t10), a = wt(r15, e - 16).mul(Cr);
  return Zi(Yt(o.add(n), 43).add(Yt(s, 30)).add(a), o.add(Yt(n.add(Cr), 18)).add(s), t10);
}
function a4(r15, e = r15.length) {
  let t10 = Cr.add(e * 2), o = wt(r15, 0).mul(Cr), n = wt(r15, 8), s = wt(r15, e - 8).mul(t10), a = wt(r15, e - 16).mul(Cr), i = Yt(o.add(n), 43).add(Yt(s, 30)).add(a), p = Zi(i, o.add(Yt(n.add(Cr), 18)).add(s), t10), u = wt(r15, 16).mul(t10), c = wt(r15, 24), l = i.add(wt(r15, e - 32)).mul(t10), m = p.add(wt(r15, e - 24)).mul(t10);
  return Zi(Yt(u.add(c), 43).add(Yt(l, 30)).add(m), u.add(Yt(c.add(o), 18)).add(l), t10);
}
function i4(r15, e = r15.length) {
  let t10 = Ou.fromNumber(81, true);
  if (e <= 32) return e <= 16 ? n4(r15, e) : s4(r15, e);
  if (e <= 64) return a4(r15, e);
  let o = t10, n = t10.mul(Pu).add(113), s = lw(n.mul(Cr).add(113)).mul(Cr), a = [Ou.UZERO, Ou.UZERO], i = [Ou.UZERO, Ou.UZERO];
  o = o.mul(Cr).add(wt(r15, 0));
  let p = 0, u = (e - 1 >> 6) * 64, c = u + (e - 1 & 63) - 63;
  do
    o = Yt(o.add(n).add(a[0]).add(wt(r15, p + 8)), 37).mul(Pu), n = Yt(n.add(a[1]).add(wt(r15, p + 48)), 42).mul(Pu), o = o.xor(i[1]), n = n.add(a[0]).add(wt(r15, p + 40)), s = Yt(s.add(i[0]), 33).mul(Pu), a = Jm(r15, p, a[1].mul(Pu), o.add(i[0])), i = Jm(r15, p + 32, s.add(i[1]), n.add(wt(r15, p + 16))), [s, o] = [o, s], p += 64;
  while (p !== u);
  let l = Pu.add(s.and(255).shl(1));
  return p = c, i[0] = i[0].add(e - 1 & 63), a[0] = a[0].add(i[0]), i[0] = i[0].add(a[0]), o = Yt(o.add(n).add(a[0]).add(wt(r15, p + 8)), 37).mul(l), n = Yt(n.add(a[1]).add(wt(r15, p + 48)), 42).mul(l), o = o.xor(i[1].mul(9)), n = n.add(a[0].mul(9).add(wt(r15, p + 40))), s = Yt(s.add(i[0]), 33).mul(l), a = Jm(r15, p, a[1].mul(l), o.add(i[0])), i = Jm(r15, p + 32, s.add(i[1]), n.add(wt(r15, p + 16))), [s, o] = [o, s], Zi(Zi(a[0], i[0], l).add(lw(n).mul(H0)).add(s), Zi(a[1], i[1], l).add(o), l);
}
function u4(r15, e) {
  return e === "string" ? Ji(r15) : Zp([r15], e);
}
function p4(r15, e) {
  return r15 instanceof Float32Array && e === "float32" || r15 instanceof Int32Array && e === "int32" || r15 instanceof Uint8Array && e === "bool";
}
function Zp(r15, e) {
  if (e === "string") throw new Error("Cannot convert a string[] to a TypedArray");
  if (Array.isArray(r15) && (r15 = Fs(r15)), A().getBool("DEBUG") && tw(r15, e), p4(r15, e)) return r15;
  if (e == null || e === "float32" || e === "complex64") return new Float32Array(r15);
  if (e === "int32") return new Int32Array(r15);
  if (e === "bool") {
    let t10 = new Uint8Array(r15.length);
    for (let o = 0; o < t10.length; ++o) Math.round(r15[o]) !== 0 && (t10[o] = 1);
    return t10;
  } else throw new Error(`Unknown data type ${e}`);
}
function Mu() {
  return A().platform.now();
}
function c4(r15, e) {
  return A().platform.fetch(r15, e);
}
function Ji(r15, e = "utf-8") {
  return e = e || "utf-8", A().platform.encode(r15, e);
}
function Jp(r15, e = "utf-8") {
  return e = e || "utf-8", A().platform.decode(r15, e);
}
function Pt(r15) {
  return A().platform.isTypedArray != null ? A().platform.isTypedArray(r15) : Qm(r15);
}
function Fs(r15, e = [], t10 = false) {
  if (e == null && (e = []), typeof r15 == "boolean" || typeof r15 == "number" || typeof r15 == "string" || Eu(r15) || r15 == null || Pt(r15) && t10) e.push(r15);
  else if (Array.isArray(r15) || Pt(r15)) for (let o = 0; o < r15.length; ++o) Fs(r15[o], e, t10);
  else {
    let o = -1;
    for (let n of Object.keys(r15)) /^([1-9]+[0-9]*|0)$/.test(n) && (o = Math.max(o, Number(n)));
    for (let n = 0; n <= o; n++) Fs(r15[n], e, t10);
  }
  return e;
}
var ed = class {
  constructor(e, t10) {
    this.backendTimer = e, this.logger = t10, t10 == null && (this.logger = new dw());
  }
  profileKernel(e, t10, o) {
    let n, s = () => {
      n = o();
    }, a, i = Mu();
    if (this.backendTimer.timerAvailable()) a = this.backendTimer.time(s);
    else {
      s();
      for (let u of n) u.dataSync();
      a = Promise.resolve({ kernelMs: Mu() - i });
    }
    if (A().getBool("CHECK_COMPUTATION_FOR_ERRORS")) for (let u = 0; u < n.length; u++) {
      let c = n[u];
      c.data().then((l) => {
        l4(l, c.dtype, e);
      });
    }
    return { kernelName: e, outputs: n, inputs: t10, timeMs: a.then((u) => u.kernelMs), extraInfo: a.then((u) => u.getExtraProfileInfo != null ? u.getExtraProfileInfo() : "") };
  }
  logKernelProfile(e) {
    let { kernelName: t10, outputs: o, timeMs: n, inputs: s, extraInfo: a } = e;
    o.forEach((i) => {
      Promise.all([i.data(), n, a]).then((p) => {
        this.logger.logKernelProfile(t10, i, p[0], p[1], s, p[2]);
      });
    });
  }
};
function l4(r15, e, t10) {
  if (e !== "float32") return false;
  for (let o = 0; o < r15.length; o++) {
    let n = r15[o];
    if (isNaN(n) || !isFinite(n)) return console.warn(`Found ${n} in the result of '${t10}'`), true;
  }
  return false;
}
var dw = class {
  logKernelProfile(e, t10, o, n, s, a) {
    let i = typeof n == "number" ? _u(`${n}ms`, 9) : n.error, p = _u(e, 25), u = t10.rank, c = t10.size, l = _u(t10.shape.toString(), 14), m = "";
    for (let d in s) {
      let f = s[d];
      if (f != null) {
        let h = f.shape || t10.shape, g = h.length;
        m += `${d}: ${g}D ${g > 0 ? h : ""} `;
      }
    }
    console.log(`%c${p}	%c${i}	%c${u}D ${l}	%c${c}	%c${m}	%c${a}`, "font-weight:bold", "color:red", "color:blue", "color: orange", "color: green", "color: steelblue");
  }
};
function q0(r15, e, t10) {
  let o = {}, n = {};
  for (let p = 0; p < e.length; p++) o[e[p].id] = true;
  for (let p = 0; p < r15.length; p++) {
    let u = r15[p], c = u.inputs;
    for (let l in c) {
      let m = c[l], d = false;
      for (let f = 0; f < e.length; f++) if (o[m.id]) {
        u.outputs.forEach((h) => o[h.id] = true), d = true, n[u.id] = true;
        break;
      }
      if (d) break;
    }
  }
  let s = {};
  s[t10.id] = true;
  let a = {};
  for (let p = r15.length - 1; p >= 0; p--) {
    let u = r15[p], c = u.inputs;
    for (let l = 0; l < u.outputs.length; l++) if (s[u.outputs[l].id]) {
      for (let m in c) s[c[m].id] = true, a[u.id] = true;
      break;
    }
  }
  let i = [];
  for (let p = 0; p < r15.length; p++) {
    let u = r15[p];
    if (n[u.id] && a[u.id]) {
      let c = {};
      for (let m in u.inputs) {
        let d = u.inputs[m];
        o[d.id] && (c[m] = d);
      }
      let l = Object.assign({}, u);
      l.inputs = c, l.outputs = u.outputs, i.push(l);
    }
  }
  return i;
}
function j0(r15, e, t10, o) {
  for (let n = e.length - 1; n >= 0; n--) {
    let s = e[n], a = [];
    if (s.outputs.forEach((p) => {
      let u = r15[p.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 p in s.inputs) {
      if (!(p in i)) throw new Error(`Cannot backprop through input ${p}. Available gradients found: ${Object.keys(i)}.`);
      let u = t10(() => i[p]());
      if (u.dtype !== "float32") throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${p} must have 'float32' dtype, but has '${u.dtype}'`);
      let c = s.inputs[p];
      if (!br(u.shape, c.shape)) throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${p}' has shape '${u.shape}', which does not match the shape of the input '${c.shape}'`);
      if (r15[c.id] == null) r15[c.id] = u;
      else {
        let l = r15[c.id];
        r15[c.id] = o(l, u), l.dispose();
      }
    }
  }
}
var X0 = 20;
var xl = 3;
var fw = 7;
function Y0(r15, e, t10, o) {
  let n = js(e), s = m4(r15, e, t10, n), a = e.length, i = td(r15, e, t10, n, s), p = ["Tensor"];
  return o && (p.push(`  dtype: ${t10}`), p.push(`  rank: ${a}`), p.push(`  shape: [${e}]`), p.push("  values:")), p.push(i.map((u) => "    " + u).join(`
`)), p.join(`
`);
}
function m4(r15, e, t10, o) {
  let n = ze(e), s = o[o.length - 1], a = new Array(s).fill(0), i = e.length, p = t10 === "complex64" ? bl(r15) : r15;
  if (i > 1) for (let u = 0; u < n / s; u++) {
    let c = u * s;
    for (let l = 0; l < s; l++) a[l] = Math.max(a[l], yl(p[c + l], 0, t10).length);
  }
  return a;
}
function yl(r15, e, t10) {
  let o;
  return Array.isArray(r15) ? o = `${parseFloat(r15[0].toFixed(fw))} + ${parseFloat(r15[1].toFixed(fw))}j` : zo(r15) ? o = `'${r15}'` : t10 === "bool" ? o = Q0(r15) : o = parseFloat(r15.toFixed(fw)).toString(), _u(o, e);
}
function Q0(r15) {
  return r15 === 0 ? "false" : "true";
}
function td(r15, e, t10, o, n, s = true) {
  let a = t10 === "complex64" ? 2 : 1, i = e[0], p = e.length;
  if (p === 0) {
    if (t10 === "complex64") {
      let h = bl(r15);
      return [yl(h[0], 0, t10)];
    }
    return t10 === "bool" ? [Q0(r15[0])] : [r15[0].toString()];
  }
  if (p === 1) {
    if (i > X0) {
      let g = xl * a, x = Array.from(r15.slice(0, g)), b = Array.from(r15.slice((i - xl) * a, i * a));
      return t10 === "complex64" && (x = bl(x), b = bl(b)), ["[" + x.map((C, S) => yl(C, n[S], t10)).join(", ") + ", ..., " + b.map((C, S) => yl(C, n[i - xl + S], t10)).join(", ") + "]"];
    }
    return ["[" + (t10 === "complex64" ? bl(r15) : Array.from(r15)).map((g, x) => yl(g, n[x], t10)).join(", ") + "]"];
  }
  let u = e.slice(1), c = o.slice(1), l = o[0] * a, m = [];
  if (i > X0) {
    for (let h = 0; h < xl; h++) {
      let g = h * l, x = g + l;
      m.push(...td(r15.slice(g, x), u, t10, c, n, false));
    }
    m.push("...");
    for (let h = i - xl; h < i; h++) {
      let g = h * l, x = g + l;
      m.push(...td(r15.slice(g, x), u, t10, c, n, h === i - 1));
    }
  } else for (let h = 0; h < i; h++) {
    let g = h * l, x = g + l;
    m.push(...td(r15.slice(g, x), u, t10, c, n, h === i - 1));
  }
  let d = p === 2 ? "," : "";
  m[0] = "[" + (i > 0 ? m[0] + d : "");
  for (let h = 1; h < m.length - 1; h++) m[h] = " " + m[h] + d;
  let f = `,
`;
  for (let h = 2; h < p; h++) f += `
`;
  return m[m.length - 1] = " " + m[m.length - 1] + "]" + (s ? "" : f), m;
}
function bl(r15) {
  let e = [];
  for (let t10 = 0; t10 < r15.length; t10 += 2) e.push([r15[t10], r15[t10 + 1]]);
  return e;
}
var tt = class {
  constructor(e, t10, o) {
    if (this.dtype = t10, this.shape = e.slice(), this.size = ze(e), o != null) {
      let n = o.length;
      E(n === this.size, () => `Length of values '${n}' does not match the size inferred by the shape '${this.size}'.`);
    }
    if (t10 === "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 = o || Xm(t10, this.size), this.strides = js(e);
  }
  set(e, ...t10) {
    t10.length === 0 && (t10 = [0]), E(t10.length === this.rank, () => `The number of provided coordinates (${t10.length}) must match the rank (${this.rank})`);
    let o = this.locToIndex(t10);
    this.values[o] = e;
  }
  get(...e) {
    e.length === 0 && (e = [0]);
    let t10 = 0;
    for (let n of e) {
      if (n < 0 || n >= this.shape[t10]) {
        let s = `Requested out of range element at ${e}.   Buffer shape=${this.shape}`;
        throw new Error(s);
      }
      t10++;
    }
    let o = e[e.length - 1];
    for (let n = 0; n < e.length - 1; ++n) o += this.strides[n] * e[n];
    return this.values[o];
  }
  locToIndex(e) {
    if (this.rank === 0) return 0;
    if (this.rank === 1) return e[0];
    let t10 = e[e.length - 1];
    for (let o = 0; o < e.length - 1; ++o) t10 += this.strides[o] * e[o];
    return t10;
  }
  indexToLoc(e) {
    if (this.rank === 0) return [];
    if (this.rank === 1) return [e];
    let t10 = new Array(this.shape.length);
    for (let o = 0; o < t10.length - 1; ++o) t10[o] = Math.floor(e / this.strides[o]), e -= t10[o] * this.strides[o];
    return t10[t10.length - 1] = e, t10;
  }
  get rank() {
    return this.shape.length;
  }
  toTensor() {
    return Ps().makeTensor(this.values, this.shape, this.dtype);
  }
};
var Ps = null;
var ec = null;
var d4 = null;
function Z0(r15) {
  Ps = r15;
}
function J0(r15) {
  ec = r15;
}
function ek(r15) {
  d4 = r15;
}
var mt = class {
  constructor(e, t10, o, n) {
    this.kept = false, this.isDisposedInternal = false, this.shape = e.slice(), this.dtype = t10 || "float32", this.size = ze(e), this.strides = js(e), this.dataId = o, this.id = n, this.rankType = this.rank < 5 ? this.rank.toString() : "higher";
  }
  get rank() {
    return this.shape.length;
  }
  async buffer() {
    let e = await this.data();
    return ec.buffer(this.shape, this.dtype, e);
  }
  bufferSync() {
    return ec.buffer(this.shape, this.dtype, this.dataSync());
  }
  async array() {
    let e = await this.data();
    return Tu(this.shape, e, this.dtype === "complex64");
  }
  arraySync() {
    return Tu(this.shape, this.dataSync(), this.dtype === "complex64");
  }
  async data() {
    this.throwIfDisposed();
    let e = Ps().read(this.dataId);
    if (this.dtype === "string") {
      let t10 = await e;
      try {
        return t10.map((o) => Jp(o));
      } catch (o) {
        throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");
      }
    }
    return e;
  }
  dataToGPU(e) {
    return this.throwIfDisposed(), Ps().readToGPU(this.dataId, e);
  }
  dataSync() {
    this.throwIfDisposed();
    let e = Ps().readSync(this.dataId);
    if (this.dtype === "string") try {
      return e.map((t10) => Jp(t10));
    } catch (t10) {
      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 Ps().read(this.dataId);
    return this.dtype === "string" ? e : new Uint8Array(e.buffer);
  }
  dispose() {
    this.isDisposed || (this.kerasMask && this.kerasMask.dispose(), Ps().disposeTensor(this), this.isDisposedInternal = true);
  }
  get isDisposed() {
    return this.isDisposedInternal;
  }
  throwIfDisposed() {
    if (this.isDisposed) throw new Error("Tensor is disposed.");
  }
  print(e = false) {
    return ec.print(this, e);
  }
  clone() {
    return this.throwIfDisposed(), ec.clone(this);
  }
  toString(e = false) {
    let t10 = this.dataSync();
    return Y0(t10, this.shape, this.dtype, e);
  }
  cast(e) {
    return this.throwIfDisposed(), ec.cast(this, e);
  }
  variable(e = true, t10, o) {
    return this.throwIfDisposed(), Ps().makeVariable(this, e, t10, o);
  }
};
Object.defineProperty(mt, Symbol.hasInstance, { value: (r15) => !!r15 && r15.data != null && r15.dataSync != null && r15.throwIfDisposed != null });
function hw() {
  return fl("Tensor", () => mt);
}
hw();
var ri = class extends mt {
  constructor(e, t10, o, n) {
    super(e.shape, e.dtype, e.dataId, n), this.trainable = t10, this.name = o;
  }
  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 (!br(e.shape, this.shape)) throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);
    Ps().disposeTensor(this), this.dataId = e.dataId, Ps().incRef(this, null);
  }
  dispose() {
    Ps().disposeVariable(this), this.isDisposedInternal = true;
  }
};
Object.defineProperty(ri, Symbol.hasInstance, { value: (r15) => r15 instanceof mt && r15.assign != null && r15.assign instanceof Function });
var rk = {};
qe(rk, { assertTypesMatch: () => ww, getTensorsInContainer: () => Cl, isTensorInList: () => h4, makeTypesMatch: () => Oe });
var gw;
(function(r15) {
  r15.R0 = "R0", r15.R1 = "R1", r15.R2 = "R2", r15.R3 = "R3", r15.R4 = "R4", r15.R5 = "R5", r15.R6 = "R6";
})(gw || (gw = {}));
var xw;
(function(r15) {
  r15.float32 = "float32", r15.int32 = "int32", r15.bool = "int32", r15.complex64 = "complex64";
})(xw || (xw = {}));
var yw;
(function(r15) {
  r15.float32 = "float32", r15.int32 = "int32", r15.bool = "bool", r15.complex64 = "complex64";
})(yw || (yw = {}));
var bw;
(function(r15) {
  r15.float32 = "float32", r15.int32 = "float32", r15.bool = "float32", r15.complex64 = "complex64";
})(bw || (bw = {}));
var Cw;
(function(r15) {
  r15.float32 = "complex64", r15.int32 = "complex64", r15.bool = "complex64", r15.complex64 = "complex64";
})(Cw || (Cw = {}));
var f4 = { float32: bw, int32: xw, bool: yw, complex64: Cw };
function dt(r15, e) {
  if (r15 === "string" || e === "string") {
    if (r15 === "string" && e === "string") return "string";
    throw new Error(`Can not upcast ${r15} with ${e}`);
  }
  return f4[r15][e];
}
function oi(r15) {
  return dt(r15, "int32");
}
function rd(r15) {
  return r15 != null && typeof r15 == "object" && "texture" in r15 && r15.texture instanceof WebGLTexture;
}
function od(r15) {
  return typeof GPUBuffer != "undefined" && r15 != null && typeof r15 == "object" && "buffer" in r15 && r15.buffer instanceof GPUBuffer;
}
function Oe(r15, e) {
  if (r15.dtype === e.dtype) return [r15, e];
  let t10 = dt(r15.dtype, e.dtype);
  return [r15.cast(t10), e.cast(t10)];
}
function ww(r15, e) {
  E(r15.dtype === e.dtype, () => `The dtypes of the first(${r15.dtype}) and second(${e.dtype}) input must match`);
}
function h4(r15, e) {
  return e.some((t10) => t10.id === r15.id);
}
function Cl(r15) {
  let e = [];
  return tk(r15, e, /* @__PURE__ */ new Set()), e;
}
function tk(r15, e, t10) {
  if (r15 == null) return;
  if (r15 instanceof mt) {
    e.push(r15);
    return;
  }
  if (!g4(r15)) return;
  let o = r15;
  for (let n in o) {
    let s = o[n];
    t10.has(s) || (t10.add(s), tk(s, e, t10));
  }
}
function g4(r15) {
  return Array.isArray(r15) || typeof r15 == "object";
}
function Sw(r15) {
  return r15.kernelName != null;
}
var nd = 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 = /* @__PURE__ */ 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 wl = class r {
  constructor(e) {
    this.ENV = e, this.registry = {}, this.registryFactory = {}, this.pendingBackendInitId = 0, this.state = new nd();
  }
  async ready() {
    if (this.pendingBackendInit != null) return this.pendingBackendInit.then(() => {
    });
    if (this.backendInstance != null) return;
    let e = this.getSortedBackends();
    for (let t10 = 0; t10 < e.length; t10++) {
      let o = e[t10];
      if (await this.initializeBackend(o).success) {
        await this.setBackend(o);
        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: t10 } = this.initializeBackendsAndReturnBest();
      if (t10) 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: t10 } = this.initializeBackend(e);
      if (t10) return null;
    } else return null;
    return this.registry[e];
  }
  findBackendFactory(e) {
    return e in this.registryFactory ? this.registryFactory[e].factory : null;
  }
  registerBackend(e, t10, o = 1) {
    return e in this.registryFactory ? (Ia(`${e} backend was already registered. Reusing existing backend factory.`), false) : (this.registryFactory[e] = { factory: t10, priority: o }, 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: t10, asyncInit: o } = this.initializeBackend(e);
      if (!(o ? await t10 : t10)) return false;
    }
    return this.backendInstance = this.registry[e], this.setupRegisteredKernels(), this.profiler = new ed(this.backendInstance), true;
  }
  setupRegisteredKernels() {
    Ym(this.backendName).forEach((t10) => {
      t10.setupFunc != null && t10.setupFunc(this.backendInstance);
    });
  }
  disposeRegisteredKernels(e) {
    Ym(e).forEach((o) => {
      o.disposeFunc != null && o.disposeFunc(this.registry[e]);
    });
  }
  initializeBackend(e) {
    let t10 = this.registryFactory[e];
    if (t10 == null) throw new Error(`Cannot initialize backend ${e}, no registration found.`);
    try {
      let o = t10.factory();
      if (o && !(o instanceof ao) && typeof o.then == "function") {
        let n = ++this.pendingBackendInitId, s = o.then((a) => n < this.pendingBackendInitId ? false : (this.registry[e] = a, this.pendingBackendInit = null, true)).catch((a) => (n < this.pendingBackendInitId || (this.pendingBackendInit = null, Ia(`Initialization of backend ${e} failed`), Ia(a.stack || a.message)), false));
        return this.pendingBackendInit = s, { success: s, asyncInit: true };
      } else return this.registry[e] = o, { success: true, asyncInit: false };
    } catch (o) {
      return Ia(`Initialization of backend ${e} failed`), Ia(o.stack || o.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, t10) => this.registryFactory[t10].priority - this.registryFactory[e].priority);
  }
  initializeBackendsAndReturnBest() {
    let e = this.getSortedBackends();
    for (let t10 = 0; t10 < e.length; t10++) {
      let o = e[t10], { success: n, asyncInit: s } = this.initializeBackend(o);
      if (s || n) return { name: o, asyncInit: s };
    }
    throw new Error("Could not initialize any backends, all backend initializations failed.");
  }
  moveData(e, t10) {
    let o = this.state.tensorInfo.get(t10), n = o.backend, s = this.readSync(t10), a = n.refCount(t10);
    n.disposeData(t10, true), o.backend = e, e.move(t10, s, o.shape, o.dtype, a), this.shouldCheckForMemLeaks() && this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;
  }
  tidy(e, t10) {
    let o = null;
    if (t10 == null) {
      if (typeof e != "function") throw new Error("Please provide a function to tidy()");
      t10 = 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 t10 != "function") throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");
      o = e;
    }
    let n;
    return this.scopedRun(() => this.startScope(o), () => this.endScope(n), () => (n = t10(), n instanceof Promise && console.error("Cannot return a Promise inside of tidy."), n));
  }
  scopedRun(e, t10, o) {
    e();
    try {
      let n = o();
      return t10(), n;
    } catch (n) {
      throw t10(), n;
    }
  }
  nextTensorId() {
    return r.nextTensorId++;
  }
  nextVariableId() {
    return r.nextVariableId++;
  }
  clone(e) {
    let t10 = T.runKernel(Co, { x: e }), o = { x: e }, n = (a) => ({ x: () => {
      let i = "float32", p = { x: a }, u = { dtype: i };
      return T.runKernel(yo, p, u);
    } }), s = [];
    return this.addTapeNode(this.state.activeScope.name, o, [t10], n, s, {}), t10;
  }
  runKernel(e, t10, o) {
    if (this.backendName == null && this.backend, !(Xp(e, this.backendName) != null)) throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);
    return this.runKernelFunc({ kernelName: e, inputs: t10, attrs: o });
  }
  shouldCheckForMemLeaks() {
    return this.ENV.getBool("IS_TEST");
  }
  checkKernelForMemLeak(e, t10, o) {
    let n = this.backend.numDataIds(), s = 0;
    o.forEach((p) => {
      s += p.dtype === "complex64" ? 3 : 1;
    });
    let a = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1], i = n - t10 - 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 t10, o = [], n = 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 p, u = Sw(e) ? e.kernelName : this.state.activeScope != null ? this.state.activeScope.name : "";
    if (Sw(e)) {
      let { kernelName: f, inputs: h, attrs: g } = e;
      this.backendName == null && this.backend;
      let x = Xp(f, this.backendName);
      E(x != null, () => `Cannot find registered kernel '${f}' for backend '${this.backendName}'`), i = () => {
        let b = this.backend.numDataIds();
        p = x.kernelFunc({ inputs: h, attrs: g, backend: this.backend });
        let C = Array.isArray(p) ? p : [p];
        this.shouldCheckForMemLeaks() && this.checkKernelForMemLeak(f, b, C);
        let S = C.map((k) => k.rank != null ? k : this.makeTensorFromTensorInfo(k));
        if (n) {
          let k = this.getTensorsForGradient(f, h, S);
          o = this.saveTensorsForBackwardMode(k);
        }
        return S;
      };
    } else {
      let { forwardFunc: f } = e, h = (g) => {
        n && (o = g.map((x) => this.keep(this.clone(x))));
      };
      i = () => {
        let g = this.backend.numDataIds();
        p = this.tidy(() => f(this.backend, h));
        let x = Array.isArray(p) ? p : [p];
        return this.shouldCheckForMemLeaks() && this.checkKernelForMemLeak(u, g, x), x;
      };
    }
    let { inputs: c, attrs: l } = e, m = Sw(e) ? null : e.backwardsFunc, d;
    return this.scopedRun(() => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {
      !this.ENV.getBool("DEBUG") && !this.state.profiling ? t10 = i() : (d = this.profiler.profileKernel(u, c, () => i()), this.ENV.getBool("DEBUG") && this.profiler.logKernelProfile(d), t10 = d.outputs);
    }), n && this.addTapeNode(u, c, t10, m, o, l), 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((f) => c[f] != null ? c[f].shape : null), outputShapes: t10.map((f) => f.shape), kernelTimeMs: d.timeMs, extraInfo: d.extraInfo }), Array.isArray(p) ? t10 : t10[0];
  }
  saveTensorsForBackwardMode(e) {
    return e.map((o) => this.keep(this.clone(o)));
  }
  getTensorsForGradient(e, t10, o) {
    let n = iw(e);
    if (n != null) {
      let s = n.inputsToSave || [], a = n.outputsToSave || [], i;
      n.saveAllInputs ? (E(Array.isArray(t10), () => "saveAllInputs is true, expected inputs to be an array."), i = Object.keys(t10).map((u) => t10[u])) : i = s.map((u) => t10[u]);
      let p = o.filter((u, c) => a[c]);
      return i.concat(p);
    }
    return [];
  }
  makeTensor(e, t10, o, n) {
    if (e == null) throw new Error("Values passed to engine.makeTensor() are null");
    o = o || "float32", n = n || this.backend;
    let s = e;
    o === "string" && zo(e[0]) && (s = e.map((p) => Ji(p)));
    let a = n.write(s, t10, o), i = new mt(t10, o, a, this.nextTensorId());
    if (this.trackTensor(i, n), o === "string") {
      let p = this.state.tensorInfo.get(a), u = ow(s);
      this.state.numBytes += u - p.bytes, p.bytes = u;
    }
    return i;
  }
  makeTensorFromDataId(e, t10, o, n) {
    o = o || "float32";
    let s = { dataId: e, shape: t10, dtype: o };
    return this.makeTensorFromTensorInfo(s, n);
  }
  makeTensorFromTensorInfo(e, t10) {
    let { dataId: o, shape: n, dtype: s } = e, a = new mt(n, s, o, this.nextTensorId());
    return this.trackTensor(a, t10), a;
  }
  makeVariable(e, t10 = true, o, n) {
    o = o || this.nextVariableId().toString(), n != null && n !== e.dtype && (e = e.cast(n));
    let s = new ri(e, t10, o, 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, t10) {
    this.state.numTensors++, e.dtype === "string" && this.state.numStringTensors++;
    let o = 0;
    e.dtype !== "complex64" && e.dtype !== "string" && (o = e.size * Wp(e.dtype)), this.state.numBytes += o, this.state.tensorInfo.has(e.dataId) || (this.state.numDataBuffers++, this.state.tensorInfo.set(e.dataId, { backend: t10 || this.backend, dtype: e.dtype, shape: e.shape, bytes: o })), e instanceof ri || this.track(e);
  }
  incRef(e, t10) {
    this.trackTensor(e, t10), this.backend.incRef(e.dataId);
  }
  removeDataId(e, t10) {
    this.state.tensorInfo.has(e) && this.state.tensorInfo.get(e).backend === t10 && (this.state.tensorInfo.delete(e), this.state.numDataBuffers--);
  }
  disposeTensor(e) {
    if (!this.state.tensorInfo.has(e.dataId)) return;
    let t10 = this.state.tensorInfo.get(e.dataId);
    if (this.state.numTensors--, e.dtype === "string" && (this.state.numStringTensors--, this.state.numBytes -= t10.bytes), e.dtype !== "complex64" && e.dtype !== "string") {
      let o = e.size * Wp(e.dtype);
      this.state.numBytes -= o;
    }
    t10.backend.disposeData(e.dataId) && this.removeDataId(e.dataId, t10.backend);
  }
  disposeVariables() {
    for (let e in this.state.registeredVariables) {
      let t10 = this.state.registeredVariables[e];
      this.disposeVariable(t10);
    }
  }
  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 t10 = this.state.numBytes, o = 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((n) => n.totalBytesSnapshot)), this.state.activeProfile.newBytes = this.state.numBytes - t10, this.state.activeProfile.newTensors = this.state.numTensors - o;
    for (let n of this.state.activeProfile.kernels) n.kernelTimeMs = await n.kernelTimeMs, n.extraInfo = await n.extraInfo;
    return this.state.activeProfile;
  }
  isTapeOn() {
    return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;
  }
  addTapeNode(e, t10, o, n, s, a) {
    let i = { id: this.state.nextTapeNodeId++, kernelName: e, inputs: t10, outputs: o, saved: s }, p = iw(e);
    p != null && (n = p.gradFunc), n != null && (i.gradient = (u) => (u = u.map((c, l) => {
      if (c == null) {
        let m = o[l], d = Gp(m.size, m.dtype);
        return this.makeTensor(d, m.shape, m.dtype);
      }
      return c;
    }), n(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 t10 = { track: [], name: "unnamed scope", id: this.state.nextScopeId++ };
    e && (t10.name = e), this.state.scopeStack.push(t10), this.state.activeScope = t10;
  }
  endScope(e) {
    let t10 = Cl(e), o = new Set(t10.map((s) => s.id));
    for (let s = 0; s < this.state.activeScope.track.length; s++) {
      let a = this.state.activeScope.track[s];
      !a.kept && !o.has(a.id) && a.dispose();
    }
    let n = this.state.scopeStack.pop();
    this.state.activeScope = this.state.scopeStack.length === 0 ? null : this.state.scopeStack[this.state.scopeStack.length - 1], t10.forEach((s) => {
      !s.kept && s.scopeId === n.id && this.track(s);
    });
  }
  gradients(e, t10, o, n = false) {
    if (E(t10.length > 0, () => "gradients() received an empty list of xs."), o != null && o.dtype !== "float32") throw new Error(`dy must have 'float32' dtype, but has '${o.dtype}'`);
    let s = this.scopedRun(() => this.startTape(), () => this.endTape(), () => this.tidy("forward", e));
    E(s instanceof mt, () => "The result y returned by f() must be a tensor.");
    let a = q0(this.state.activeTape, t10, s);
    if (!n && a.length === 0 && t10.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] = o == null ? x4(s.shape) : o, j0(i, a, (u) => this.tidy(u), y4);
      let p = t10.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: p };
    });
  }
  customGrad(e) {
    return E(qs(e), () => "The f passed in customGrad(f) must be a function."), (...t10) => {
      E(t10.every((i) => i instanceof mt), () => "The args passed in customGrad(f)(x1, x2,...) must all be tensors");
      let o, n = {};
      t10.forEach((i, p) => {
        n[p] = i;
      });
      let s = (i, p) => (o = e(...t10, p), E(o.value instanceof mt, () => "The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"), E(qs(o.gradFunc), () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."), o.value), a = (i, p) => {
        let u = o.gradFunc(i, p), c = Array.isArray(u) ? u : [u];
        E(c.length === t10.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 mt), () => "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 l = {};
        return c.forEach((m, d) => {
          l[d] = () => m;
        }), l;
      };
      return this.runKernelFunc({ forwardFunc: s, backwardsFunc: a, inputs: n });
    };
  }
  readSync(e) {
    return this.state.tensorInfo.get(e).backend.readSync(e);
  }
  read(e) {
    return this.state.tensorInfo.get(e).backend.read(e);
  }
  readToGPU(e, t10) {
    return this.state.tensorInfo.get(e).backend.readToGPU(e, t10);
  }
  async time(e) {
    let t10 = Mu(), o = await this.backend.time(e);
    return o.wallMs = Mu() - t10, o;
  }
  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 nd();
    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;
  }
};
wl.nextTensorId = 0;
wl.nextVariableId = 0;
function x4(r15) {
  let e = ml(ze(r15), "float32");
  return T.makeTensor(e, r15, "float32");
}
function Iw() {
  let r15 = aw();
  if (r15._tfengine == null) {
    let e = new dl(r15);
    r15._tfengine = new wl(e);
  }
  return $0(r15._tfengine.ENV), Z0(() => r15._tfengine), r15._tfengine;
}
var T = Iw();
function y4(r15, e) {
  let t10 = { a: r15, b: e };
  return T.runKernel("Add", t10);
}
var eu = {};
qe(eu, { isBrowser: () => kw, isMobile: () => w4, mockIsMobile: () => C4 });
function b4() {
  return typeof navigator != "undefined" && navigator != null;
}
var vw;
function C4(r15) {
  vw = r15;
}
function w4(r15) {
  if (vw !== void 0) return vw;
  if (r15 || b4()) {
    if (r15 || (r15 = navigator), r15.product === "ReactNative") return true;
    let e = r15.userAgent || r15.vendor || (typeof window != "undefined" ? window.opera : "");
    if (!e) {
      let t10 = r15;
      return t10.userAgentData && t10.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 kw() {
  return typeof window != "undefined" && window.document != null || typeof WorkerGlobalScope != "undefined";
}
var _r = A();
_r.registerFlag("DEBUG", () => false, (r15) => {
  r15 && 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.");
});
_r.registerFlag("IS_BROWSER", () => kw());
_r.registerFlag("IS_NODE", () => typeof process != "undefined" && typeof process.versions != "undefined" && typeof process.versions.node != "undefined");
_r.registerFlag("IS_CHROME", () => typeof navigator != "undefined" && navigator != null && navigator.userAgent != null && /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor));
_r.registerFlag("IS_SAFARI", () => typeof navigator != "undefined" && navigator != null && navigator.userAgent != null && /Safari/.test(navigator.userAgent) && /Apple/.test(navigator.vendor));
_r.registerFlag("PROD", () => false);
_r.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", () => _r.getBool("DEBUG"));
_r.registerFlag("DEPRECATION_WARNINGS_ENABLED", () => true);
_r.registerFlag("IS_TEST", () => false);
_r.registerFlag("CHECK_COMPUTATION_FOR_ERRORS", () => _r.getBool("DEBUG"));
_r.registerFlag("WRAP_TO_IMAGEBITMAP", () => false);
_r.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU", () => false);
_r.registerFlag("USE_SETTIMEOUTCUSTOM", () => false);
function sr(r15, e) {
  let t10 = r15;
  if (Pt(r15)) return e === "string" ? [] : [r15.length];
  if (rd(r15)) {
    let n = r15.channels || "RGBA";
    return [r15.height, r15.width * n.length];
  } else if (od(r15)) return [r15.buffer.size / (e == null ? 4 : Wp(e))];
  if (!Array.isArray(r15)) return [];
  let o = [];
  for (; Array.isArray(t10) || Pt(t10) && e !== "string"; ) o.push(t10.length), t10 = t10[0];
  return Array.isArray(r15) && A().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY") && nk(r15, o, []), o;
}
function nk(r15, e, t10) {
  if (t10 = t10 || [], !Array.isArray(r15) && !Pt(r15)) {
    E(e.length === 0, () => `Element arr[${t10.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`);
    return;
  }
  E(e.length > 0, () => `Element arr[${t10.join("][")}] should be a primitive, but is an array of ${r15.length} elements`), E(r15.length === e[0], () => `Element arr[${t10.join("][")}] should have ${e[0]} elements, but has ${r15.length} elements`);
  let o = e.slice(1);
  for (let n = 0; n < r15.length; ++n) nk(r15[n], o, t10.concat(n));
}
function ok(r15, e, t10, o) {
  if (r15 !== "string_or_numeric") {
    if (r15 == null) throw new Error("Expected dtype cannot be null.");
    if (r15 !== "numeric" && r15 !== e || r15 === "numeric" && e === "string") throw new Error(`Argument '${t10}' passed to '${o}' must be ${r15} tensor, but got ${e} tensor`);
  }
}
function v(r15, e, t10, o = "numeric") {
  if (r15 instanceof hw()) return ok(o, r15.dtype, e, t10), r15;
  let n = Ei(r15);
  if (n !== "string" && ["bool", "int32", "float32"].indexOf(o) >= 0 && (n = o), ok(o, n, e, t10), r15 == null || !Pt(r15) && !Array.isArray(r15) && typeof r15 != "number" && typeof r15 != "boolean" && typeof r15 != "string") {
    let p = r15 == null ? "null" : r15.constructor.name;
    throw new Error(`Argument '${e}' passed to '${t10}' must be a Tensor or TensorLike, but got '${p}'`);
  }
  let s = sr(r15, n);
  !Pt(r15) && !Array.isArray(r15) && (r15 = [r15]);
  let i = n !== "string" ? Zp(r15, n) : Fs(r15, [], true);
  return T.makeTensor(i, s, n);
}
function ni(r15, e, t10, o = "numeric") {
  if (!Array.isArray(r15)) throw new Error(`Argument ${e} passed to ${t10} must be a \`Tensor[]\` or \`TensorLike[]\``);
  return r15.map((s, a) => v(s, `${e}[${a}]`, t10, o));
}
var Nw = "__op";
function N(r15) {
  let e = Object.keys(r15);
  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 t10 = e[0], o = r15[t10];
  t10.endsWith("_") && (t10 = t10.substring(0, t10.length - 1)), t10 = t10 + Nw;
  let n = (...s) => {
    T.startScope(t10);
    try {
      let a = o(...s);
      return Eu(a) && console.error("Cannot return a Promise inside of tidy."), T.endScope(a), a;
    } catch (a) {
      throw T.endScope(null), a;
    }
  };
  return Object.defineProperty(n, "name", { value: t10, configurable: true }), n;
}
function S4(r15, e) {
  let t10 = v(r15, "real", "complex"), o = v(e, "imag", "complex");
  xt(t10.shape, o.shape, `real and imag shapes, ${t10.shape} and ${o.shape}, must match in call to tf.complex().`);
  let n = { real: t10, imag: o };
  return T.runKernel(Di, n);
}
var Er = N({ complex_: S4 });
function wr(r15, e, t10, o) {
  if (o == null) o = Ei(r15);
  else if (o === "complex64") throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");
  if (od(r15) || rd(r15)) {
    if (o !== "float32" && o !== "int32") throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${o}.`);
    return T.backend.createTensorFromGPUData(r15, e || t10, o);
  }
  if (!Pt(r15) && !Array.isArray(r15) && typeof r15 != "number" && typeof r15 != "boolean" && typeof r15 != "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) {
    Ct(e);
    let n = ze(e), s = ze(t10);
    E(n === s, () => `Based on the provided shape, [${e}], the tensor should have ${n} values but has ${s}`);
    for (let a = 0; a < t10.length; ++a) {
      let i = t10[a], p = a === t10.length - 1 ? i !== ze(e.slice(a)) : true;
      E(t10[a] === e[a] || !p, () => `Error creating a new Tensor. Inferred shape (${t10}) does not match the provided shape (${e}). `);
    }
  }
  return !Pt(r15) && !Array.isArray(r15) && (r15 = [r15]), e = e || t10, r15 = o !== "string" ? Zp(r15, o) : Fs(r15, [], true), T.makeTensor(r15, e, o);
}
function ar(r15, e, t10) {
  let o = sr(r15, t10);
  return wr(r15, e, o, t10);
}
var si = { float32: 4, float16: 2, int32: 4, uint16: 2, uint8: 1, bool: 1, complex64: 8 };
var ir = class r2 {
  static join(e) {
    return new r2(e).slice();
  }
  constructor(e) {
    if (this.shards = [], this.previousShardIndex = 0, e == null || (e instanceof Array || (e = [e]), e = e.map((o) => Pt(o) ? o.buffer : o), e.length === 0)) return;
    this.bufferUniformSize = e[0].byteLength;
    let t10 = 0;
    for (let o = 0; o < e.length; o++) {
      let n = e[o];
      o !== e.length - 1 && n.byteLength !== this.bufferUniformSize && (this.bufferUniformSize = void 0);
      let s = t10 + n.byteLength;
      this.shards.push({ buffer: n, start: t10, end: s }), t10 = s;
    }
    this.shards.length === 0 && (this.byteLength = 0), this.byteLength = this.shards[this.shards.length - 1].end;
  }
  slice(e = 0, t10 = this.byteLength) {
    if (this.shards.length === 0) return new ArrayBuffer(0);
    if (e = isNaN(Number(e)) ? 0 : e, t10 = isNaN(Number(t10)) ? 0 : t10, e = Math.max(0, e), t10 = Math.min(this.byteLength, t10), t10 <= e) return new ArrayBuffer(0);
    let o = this.findShardForByte(e);
    if (o === -1) throw new Error(`Could not find start shard for byte ${e}`);
    let n = t10 - e, s = new ArrayBuffer(n), a = new Uint8Array(s), i = 0;
    for (let p = o; p < this.shards.length; p++) {
      let u = this.shards[p], l = e + i - u.start, m = i, f = Math.min(t10, u.end) - u.start, h = new Uint8Array(u.buffer, l, f - l);
      if (a.set(h, m), i += h.length, t10 < u.end) break;
    }
    return s;
  }
  findShardForByte(e) {
    if (this.shards.length === 0 || e < 0 || e >= this.byteLength) return -1;
    if (this.bufferUniformSize != null) return this.previousShardIndex = Math.floor(e / this.bufferUniformSize), this.previousShardIndex;
    function t10(n) {
      return e < n.start ? -1 : e >= n.end ? 1 : 0;
    }
    if (t10(this.shards[this.previousShardIndex]) === 0) return this.previousShardIndex;
    let o = I4(this.shards, t10);
    return o === -1 ? -1 : (this.previousShardIndex = o, this.previousShardIndex);
  }
};
function I4(r15, e) {
  let t10 = 0, o = r15.length;
  for (; t10 <= o; ) {
    let n = Math.floor((o - t10) / 2) + t10, s = e(r15[n]);
    if (s === 0) return n;
    s < 0 ? o = n : t10 = n + 1;
  }
  return -1;
}
function hme() {
  A().set("PROD", true);
}
function gme() {
  A().set("DEBUG", true);
}
function xme() {
  A().set("DEPRECATION_WARNINGS_ENABLED", false), console.warn("TensorFlow.js deprecation warnings have been disabled.");
}
function Tw(r15) {
  A().getBool("DEPRECATION_WARNINGS_ENABLED") && console.warn(r15 + " You can disable deprecation warnings with tf.disableDeprecationWarnings().");
}
ek(Tw);
function yme() {
  T.disposeVariables();
}
function ur() {
  return T;
}
function bme() {
  return T.memory();
}
function Cme(r15) {
  return T.profile(r15);
}
function De(r15, e) {
  return T.tidy(r15, e);
}
function Ot(r15) {
  Cl(r15).forEach((t10) => t10.dispose());
}
function $r(r15) {
  return T.keep(r15);
}
function wme(r15) {
  return T.time(r15);
}
function Sme(r15) {
  return T.setBackend(r15);
}
function Ime() {
  return T.ready();
}
function sk() {
  return T.backendName;
}
function vme(r15) {
  T.removeBackend(r15);
}
function kme(r15) {
  return T.findBackend(r15);
}
function Nme(r15) {
  return T.findBackendFactory(r15);
}
function tu(r15, e, t10 = 1) {
  return T.registerBackend(r15, e, t10);
}
function ak() {
  return T.backend;
}
function Tme(r15, e) {
  A().setPlatform(r15, e);
}
var ru = 4;
async function pk(r15, e) {
  let t10 = [], o = [], n = Array.isArray(r15) ? r15.map((a) => a.name) : Object.keys(r15);
  for (let a = 0; a < n.length; ++a) {
    let i = n[a], p = Array.isArray(r15) ? r15[a].tensor : r15[i];
    if (p.dtype !== "float32" && p.dtype !== "int32" && p.dtype !== "bool" && p.dtype !== "string" && p.dtype !== "complex64") throw new Error(`Unsupported dtype in weight '${i}': ${p.dtype}`);
    let u = { name: i, shape: p.shape, dtype: p.dtype };
    if (p.dtype === "string") {
      let c = new Promise(async (l) => {
        let m = await p.bytes(), d = m.reduce((g, x) => g + x.length, 0) + ru * m.length, f = new Uint8Array(d), h = 0;
        for (let g = 0; g < m.length; g++) {
          let x = m[g], b = new Uint8Array(new Uint32Array([x.length]).buffer);
          f.set(b, h), h += ru, f.set(x, h), h += x.length;
        }
        l(f);
      });
      o.push(c);
    } else o.push(p.data());
    e != null && (u.group = e), t10.push(u);
  }
  let s = await Promise.all(o);
  return { data: N4(s), specs: t10 };
}
function sd(r15, e) {
  let t10 = new ir(r15), o = {}, n = 0;
  for (let s of e) {
    let a = v4(s, (i, p) => t10.slice(n + i, n + p));
    o[s.name] = ck(s, t10.slice(n, n + a)), n += a;
  }
  return o;
}
function v4(r15, e) {
  let t10 = ze(r15.shape), o;
  if ("quantization" in r15) {
    let n = r15.quantization;
    o = si[n.dtype];
  } else if (r15.dtype === "string") {
    let n = 0;
    for (let s = 0; s < t10; s++) n += ru + new Uint32Array(e(n, n + ru))[0];
    return n;
  } else o = si[r15.dtype];
  return t10 * o;
}
async function k4(r15, e) {
  let t10 = ze(r15.shape), o;
  if ("quantization" in r15) {
    let n = r15.quantization;
    o = si[n.dtype];
  } else if (r15.dtype === "string") {
    let n = 0;
    for (let s = 0; s < t10; s++) n += ru + new Uint32Array(await e(n, n + ru))[0];
    return n;
  } else o = si[r15.dtype];
  return t10 * o;
}
function ck(r15, e) {
  let t10 = r15.name, o = r15.dtype, n = r15.shape, s = ze(n), a, i = 0;
  if ("quantization" in r15) {
    let p = r15.quantization;
    if (p.dtype === "uint8" || p.dtype === "uint16") {
      if (!("min" in p && "scale" in p)) throw new Error(`Weight ${r15.name} with quantization ${p.dtype} doesn't have corresponding metadata min and scale.`);
    } else if (p.dtype === "float16") {
      if (o !== "float32") throw new Error(`Weight ${r15.name} is quantized with ${p.dtype} which only supports weights of type float32 not ${o}.`);
    } else throw new Error(`Weight ${r15.name} has unknown quantization dtype ${p.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);
    let u = si[p.dtype], c = p.dtype === "uint8" ? new Uint8Array(e) : new Uint16Array(e);
    if (o === "float32") if (p.dtype === "uint8" || p.dtype === "uint16") {
      a = new Float32Array(c.length);
      for (let l = 0; l < c.length; l++) {
        let m = c[l];
        a[l] = m * p.scale + p.min;
      }
    } else if (p.dtype === "float16") a = $4()(c);
    else throw new Error(`Unsupported quantization type ${p.dtype} for weight type float32.`);
    else if (o === "int32") {
      if (p.dtype !== "uint8" && p.dtype !== "uint16") throw new Error(`Unsupported quantization type ${p.dtype} for weight type int32.`);
      a = new Int32Array(c.length);
      for (let l = 0; l < c.length; l++) {
        let m = c[l];
        a[l] = Math.round(m * p.scale + p.min);
      }
    } else throw new Error(`Unsupported dtype in weight '${t10}': ${o}`);
    i += s * u;
  } else if (o === "string") {
    let p = ze(r15.shape);
    a = [];
    for (let u = 0; u < p; u++) {
      let c = new Uint32Array(e.slice(i, i + ru))[0];
      i += ru;
      let l = new Uint8Array(e.slice(i, i + c));
      a.push(l), i += c;
    }
  } else {
    let p = si[o];
    if (o === "float32") a = new Float32Array(e);
    else if (o === "int32") a = new Int32Array(e);
    else if (o === "bool") a = new Uint8Array(e);
    else if (o === "complex64") {
      a = new Float32Array(e);
      let u = new Float32Array(a.length / 2), c = new Float32Array(a.length / 2);
      for (let f = 0; f < u.length; f++) u[f] = a[f * 2], c[f] = a[f * 2 + 1];
      let l = ar(u, n, "float32"), m = ar(c, n, "float32"), d = Er(l, m);
      return l.dispose(), m.dispose(), d;
    } else throw new Error(`Unsupported dtype in weight '${t10}': ${o}`);
    i += s * p;
  }
  return ar(a, n, o);
}
async function ik(r15, e, t10) {
  let o = new Uint8Array(e);
  for (; o.byteLength < t10; ) {
    let { done: n, value: s } = await r15.read();
    if (n && s == null) {
      let i = t10 - o.byteLength;
      throw new Error(`Reader is done but ${i} bytes are still expected`);
    }
    let a = new Uint8Array(o.length + s.byteLength);
    a.set(o, 0), a.set(new Uint8Array(s), o.length), o = a;
  }
  return o.buffer;
}
async function ad(r15, e) {
  let t10 = {}, o = r15.getReader(), n = new ArrayBuffer(0);
  for (let s of e) {
    let a = await k4(s, async (u, c) => (n = await ik(o, n, c), n.slice(u, c)));
    n = await ik(o, n, a);
    let i = n.slice(0, a);
    n = n.slice(a);
    let p = ck(s, i);
    if (t10[s.name] = p, sk() === "webgpu") {
      let u = ak();
      "uploadToGPU" in u && ze(p.shape) >= A().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD") && u.uploadToGPU(p.dataId);
    }
  }
  return t10;
}
function N4(r15) {
  if (r15 === null) throw new Error(`Invalid input value: ${JSON.stringify(r15)}`);
  let e = 0, t10 = [];
  r15.forEach((s) => {
    if (e += s.byteLength, t10.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 o = new Uint8Array(e), n = 0;
  return t10.forEach((s) => {
    o.set(new Uint8Array(s.buffer), n), n += s.byteLength;
  }), o.buffer;
}
var _w = typeof Buffer != "undefined" && (typeof Blob == "undefined" || typeof atob == "undefined" || typeof btoa == "undefined");
function uk(r15) {
  return _w ? Buffer.byteLength(r15, "utf8") : new Blob([r15]).size;
}
function lk(r15) {
  if (_w) return Buffer.from(r15).toString("base64");
  let e = new Uint8Array(r15), t10 = "";
  for (let o = 0, n = e.length; o < n; o++) t10 += String.fromCharCode(e[o]);
  return btoa(t10);
}
function mk(r15) {
  if (_w) {
    let o = Buffer.from(r15, "base64");
    return o.buffer.slice(o.byteOffset, o.byteOffset + o.byteLength);
  }
  let e = atob(r15), t10 = new Uint8Array(e.length);
  for (let o = 0; o < e.length; ++o) t10.set([e.charCodeAt(o)], o);
  return t10.buffer;
}
function dk(r15) {
  return ir.join(r15);
}
function Ew(r15) {
  for (r15 = r15.trim(); r15.endsWith("/"); ) r15 = r15.slice(0, r15.length - 1);
  let t10 = r15.split("/");
  return t10[t10.length - 1];
}
function id(r15, e) {
  let t10 = { modelTopology: r15.modelTopology, format: r15.format, generatedBy: r15.generatedBy, convertedBy: r15.convertedBy, weightsManifest: e };
  return r15.signature != null && (t10.signature = r15.signature), r15.userDefinedMetadata != null && (t10.userDefinedMetadata = r15.userDefinedMetadata), r15.modelInitializer != null && (t10.modelInitializer = r15.modelInitializer), r15.initializerSignature != null && (t10.initializerSignature = r15.initializerSignature), r15.trainingConfig != null && (t10.trainingConfig = r15.trainingConfig), t10;
}
function $w(r15, e, t10) {
  let o = { modelTopology: r15.modelTopology, format: r15.format, generatedBy: r15.generatedBy, convertedBy: r15.convertedBy };
  if (r15.trainingConfig != null && (o.trainingConfig = r15.trainingConfig), r15.weightsManifest != null) {
    if (!e) throw new Error("modelJSON has weightsManifest but weightSpecs is null");
    if (!t10) throw new Error("modelJSON has weightsManifest but weightData is null");
    o.weightSpecs = e, o.weightData = t10;
  }
  return r15.signature != null && (o.signature = r15.signature), r15.userDefinedMetadata != null && (o.userDefinedMetadata = r15.userDefinedMetadata), r15.modelInitializer != null && (o.modelInitializer = r15.modelInitializer), r15.initializerSignature != null && (o.initializerSignature = r15.initializerSignature), o;
}
async function tc(r15, e) {
  let t10, o;
  return r15.weightsManifest != null && ([t10, o] = await e(r15.weightsManifest)), $w(r15, t10, o);
}
function va(r15) {
  if (r15.modelTopology instanceof ArrayBuffer) throw new Error("Expected JSON model topology, received ArrayBuffer.");
  return { dateSaved: /* @__PURE__ */ new Date(), modelTopologyType: "JSON", modelTopologyBytes: r15.modelTopology == null ? 0 : uk(JSON.stringify(r15.modelTopology)), weightSpecsBytes: r15.weightSpecs == null ? 0 : uk(JSON.stringify(r15.weightSpecs)), weightDataBytes: r15.weightData == null ? 0 : new ir(r15.weightData).byteLength };
}
function Sl(r15) {
  let e = [];
  for (let t10 of r15) e.push(...t10.weights);
  return e;
}
function T4() {
  let r15 = (t10) => {
    let o = t10 << 13, n = 0;
    for (; (o & 8388608) === 0; ) n -= 8388608, o <<= 1;
    return o &= -8388609, n += 947912704, o | n;
  }, e = new Uint32Array(2048);
  e[0] = 0;
  for (let t10 = 1; t10 < 1024; t10++) e[t10] = r15(t10);
  for (let t10 = 1024; t10 < 2048; t10++) e[t10] = 939524096 + (t10 - 1024 << 13);
  return e;
}
function _4() {
  let r15 = new Uint32Array(64);
  r15[0] = 0, r15[31] = 1199570944, r15[32] = 2147483648, r15[63] = 3347054592;
  for (let e = 1; e < 31; e++) r15[e] = e << 23;
  for (let e = 33; e < 63; e++) r15[e] = 2147483648 + (e - 32 << 23);
  return r15;
}
function E4() {
  let r15 = new Uint32Array(64);
  for (let e = 0; e < 64; e++) r15[e] = 1024;
  return r15[0] = r15[32] = 0, r15;
}
function $4() {
  let r15 = T4(), e = _4(), t10 = E4();
  return (o) => {
    let n = new ArrayBuffer(4 * o.length), s = new Uint32Array(n);
    for (let a = 0; a < o.length; a++) {
      let i = o[a], p = r15[t10[i >> 10] + (i & 1023)] + e[i >> 10];
      s[a] = p;
    }
    return new Float32Array(n);
  };
}
var qt = class r3 {
  constructor() {
    this.saveRouters = [], this.loadRouters = [];
  }
  static getInstance() {
    return r3.instance == null && (r3.instance = new r3()), r3.instance;
  }
  static registerSaveRouter(e) {
    r3.getInstance().saveRouters.push(e);
  }
  static registerLoadRouter(e) {
    r3.getInstance().loadRouters.push(e);
  }
  static getSaveHandlers(e) {
    return r3.getHandlers(e, "save");
  }
  static getLoadHandlers(e, t10) {
    return r3.getHandlers(e, "load", t10);
  }
  static getHandlers(e, t10, o) {
    let n = [];
    return (t10 === "load" ? r3.getInstance().loadRouters : r3.getInstance().saveRouters).forEach((a) => {
      let i = a(e, o);
      i !== null && n.push(i);
    }), n;
  }
};
var fk = (r15) => qt.registerSaveRouter(r15);
var hk = (r15) => qt.registerLoadRouter(r15);
var gk = (r15) => qt.getSaveHandlers(r15);
var xk = (r15, e) => qt.getLoadHandlers(r15, e);
var Rw = "tensorflowjs";
var Dw = 1;
var Lu = "models_store";
var ou = "model_info_store";
function yk() {
  if (!A().getBool("IS_BROWSER")) throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");
  let r15 = typeof window == "undefined" ? self : window, e = r15.indexedDB || r15.mozIndexedDB || r15.webkitIndexedDB || r15.msIndexedDB || r15.shimIndexedDB;
  if (e == null) throw new Error("The current browser does not appear to support IndexedDB.");
  return e;
}
function Aw(r15) {
  let e = r15.result;
  e.createObjectStore(Lu, { keyPath: "modelPath" }), e.createObjectStore(ou, { keyPath: "modelPath" });
}
var ka = class {
  constructor(e) {
    if (this.indexedDB = yk(), 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, t10) {
    return new Promise((o, n) => {
      let s = this.indexedDB.open(Rw, Dw);
      s.onupgradeneeded = () => Aw(s), s.onsuccess = () => {
        let a = s.result;
        if (t10 == null) {
          let i = a.transaction(Lu, "readonly"), u = i.objectStore(Lu).get(this.modelPath);
          u.onsuccess = () => {
            if (u.result == null) return a.close(), n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));
            o(u.result.modelArtifacts);
          }, u.onerror = (c) => (a.close(), n(u.error)), i.oncomplete = () => a.close();
        } else {
          t10.weightData = ir.join(t10.weightData);
          let i = va(t10), p = a.transaction(ou, "readwrite"), u = p.objectStore(ou), c;
          try {
            c = u.put({ modelPath: this.modelPath, modelArtifactsInfo: i });
          } catch (m) {
            return n(m);
          }
          let l;
          c.onsuccess = () => {
            l = a.transaction(Lu, "readwrite");
            let m = l.objectStore(Lu), d;
            try {
              d = m.put({ modelPath: this.modelPath, modelArtifacts: t10, modelArtifactsInfo: i });
            } catch (f) {
              return n(f);
            }
            d.onsuccess = () => o({ modelArtifactsInfo: i }), d.onerror = (f) => {
              u = p.objectStore(ou);
              let h = u.delete(this.modelPath);
              h.onsuccess = () => (a.close(), n(d.error)), h.onerror = (g) => (a.close(), n(d.error));
            };
          }, c.onerror = (m) => (a.close(), n(c.error)), p.oncomplete = () => {
            l == null ? a.close() : l.oncomplete = () => a.close();
          };
        }
      }, s.onerror = (a) => n(s.error);
    });
  }
};
ka.URL_SCHEME = "indexeddb://";
var bk = (r15) => A().getBool("IS_BROWSER") && !Array.isArray(r15) && r15.startsWith(ka.URL_SCHEME) ? R4(r15.slice(ka.URL_SCHEME.length)) : null;
qt.registerSaveRouter(bk);
qt.registerLoadRouter(bk);
function R4(r15) {
  return new ka(r15);
}
function D4(r15) {
  return r15.startsWith(ka.URL_SCHEME) ? r15.slice(ka.URL_SCHEME.length) : r15;
}
var ud = class {
  constructor() {
    this.indexedDB = yk();
  }
  async listModels() {
    return new Promise((e, t10) => {
      let o = this.indexedDB.open(Rw, Dw);
      o.onupgradeneeded = () => Aw(o), o.onsuccess = () => {
        let n = o.result, s = n.transaction(ou, "readonly"), i = s.objectStore(ou).getAll();
        i.onsuccess = () => {
          let p = {};
          for (let u of i.result) p[u.modelPath] = u.modelArtifactsInfo;
          e(p);
        }, i.onerror = (p) => (n.close(), t10(i.error)), s.oncomplete = () => n.close();
      }, o.onerror = (n) => t10(o.error);
    });
  }
  async removeModel(e) {
    return e = D4(e), new Promise((t10, o) => {
      let n = this.indexedDB.open(Rw, Dw);
      n.onupgradeneeded = () => Aw(n), n.onsuccess = () => {
        let s = n.result, a = s.transaction(ou, "readwrite"), i = a.objectStore(ou), p = i.get(e), u;
        p.onsuccess = () => {
          if (p.result == null) return s.close(), o(new Error(`Cannot find model with path '${e}' in IndexedDB.`));
          {
            let c = i.delete(e), l = () => {
              u = s.transaction(Lu, "readwrite");
              let d = u.objectStore(Lu).delete(e);
              d.onsuccess = () => t10(p.result.modelArtifactsInfo), d.onerror = (f) => o(p.error);
            };
            c.onsuccess = l, c.onerror = (m) => (l(), s.close(), o(p.error));
          }
        }, p.onerror = (c) => (s.close(), o(p.error)), a.oncomplete = () => {
          u == null ? s.close() : u.oncomplete = () => s.close();
        };
      }, n.onerror = (s) => o(n.error);
    });
  }
};
var ai = "/";
var rc = "tensorflowjs_models";
var Ck = "info";
var A4 = "model_topology";
var F4 = "weight_specs";
var P4 = "weight_data";
var O4 = "model_metadata";
function wk(r15) {
  return { info: [rc, r15, Ck].join(ai), topology: [rc, r15, A4].join(ai), weightSpecs: [rc, r15, F4].join(ai), weightData: [rc, r15, P4].join(ai), modelMetadata: [rc, r15, O4].join(ai) };
}
function Sk(r15) {
  for (let e of Object.values(r15)) window.localStorage.removeItem(e);
}
function M4(r15) {
  let e = r15.split(ai);
  if (e.length < 3) throw new Error(`Invalid key format: ${r15}`);
  return e.slice(1, e.length - 1).join(ai);
}
function L4(r15) {
  return r15.startsWith(Na.URL_SCHEME) ? r15.slice(Na.URL_SCHEME.length) : r15;
}
var Na = class {
  constructor(e) {
    if (!A().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 = wk(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 t10 = JSON.stringify(e.modelTopology), o = JSON.stringify(e.weightSpecs), n = va(e), s = ir.join(e.weightData);
      try {
        this.LS.setItem(this.keys.info, JSON.stringify(n)), this.LS.setItem(this.keys.topology, t10), this.LS.setItem(this.keys.weightSpecs, o), this.LS.setItem(this.keys.weightData, lk(s));
        let a = { 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, initializerSignature: e.initializerSignature != null ? e.initializerSignature : void 0, trainingConfig: e.trainingConfig != null ? e.trainingConfig : void 0 };
        return this.LS.setItem(this.keys.modelMetadata, JSON.stringify(a)), { modelArtifactsInfo: n };
      } catch (a) {
        throw Sk(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=${n.modelTopologyBytes}, weightSpecsBytes=${n.weightSpecsBytes}, weightDataBytes=${n.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 t10 = {}, o = JSON.parse(this.LS.getItem(this.keys.topology));
    if (o == null) throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);
    t10.modelTopology = o;
    let n = JSON.parse(this.LS.getItem(this.keys.weightSpecs));
    if (n == null) throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);
    t10.weightSpecs = n;
    let s = this.LS.getItem(this.keys.modelMetadata);
    if (s != null) {
      let i = JSON.parse(s);
      t10.format = i.format, t10.generatedBy = i.generatedBy, t10.convertedBy = i.convertedBy, i.signature != null && (t10.signature = i.signature), i.userDefinedMetadata != null && (t10.userDefinedMetadata = i.userDefinedMetadata), i.modelInitializer != null && (t10.modelInitializer = i.modelInitializer), i.initializerSignature != null && (t10.initializerSignature = i.initializerSignature), i.trainingConfig != null && (t10.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 t10.weightData = mk(a), t10;
  }
};
Na.URL_SCHEME = "localstorage://";
var Ik = (r15) => A().getBool("IS_BROWSER") && !Array.isArray(r15) && r15.startsWith(Na.URL_SCHEME) ? B4(r15.slice(Na.URL_SCHEME.length)) : null;
qt.registerSaveRouter(Ik);
qt.registerLoadRouter(Ik);
function B4(r15) {
  return new Na(r15);
}
var pd = class {
  constructor() {
    E(A().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 = {}, t10 = rc + ai, o = ai + Ck;
    for (let n = 0; n < this.LS.length; ++n) {
      let s = this.LS.key(n);
      if (s.startsWith(t10) && s.endsWith(o)) {
        let a = M4(s);
        e[a] = JSON.parse(this.LS.getItem(s));
      }
    }
    return e;
  }
  async removeModel(e) {
    e = L4(e);
    let t10 = wk(e);
    if (this.LS.getItem(t10.info) == null) throw new Error(`Cannot find model at path '${e}'`);
    let o = JSON.parse(this.LS.getItem(t10.info));
    return Sk(t10), o;
  }
};
var oc = "://";
var Os = class r4 {
  constructor() {
    this.managers = {};
  }
  static getInstance() {
    return r4.instance == null && (r4.instance = new r4()), r4.instance;
  }
  static registerManager(e, t10) {
    E(e != null, () => "scheme must not be undefined or null."), e.endsWith(oc) && (e = e.slice(0, e.indexOf(oc))), E(e.length > 0, () => "scheme must not be an empty string.");
    let o = r4.getInstance();
    E(o.managers[e] == null, () => `A model store manager is already registered for scheme '${e}'.`), o.managers[e] = t10;
  }
  static getManager(e) {
    let t10 = r4.getInstance().managers[e];
    if (t10 == null) throw new Error(`Cannot find model manager for scheme '${e}'`);
    return t10;
  }
  static getSchemes() {
    return Object.keys(r4.getInstance().managers);
  }
};
function cd(r15) {
  if (r15.indexOf(oc) === -1) throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Os.getSchemes().join(",")}`);
  return { scheme: r15.split(oc)[0], path: r15.split(oc)[1] };
}
async function vk(r15, e, t10 = false) {
  E(r15 !== e, () => `Old path and new path are the same: '${r15}'`);
  let o = qt.getLoadHandlers(r15);
  E(o.length > 0, () => `Copying failed because no load handler is found for source URL ${r15}.`), E(o.length < 2, () => `Copying failed because more than one (${o.length}) load handlers for source URL ${r15}.`);
  let n = o[0], s = qt.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 (${o.length}) save handlers for destination URL ${e}.`);
  let a = s[0], i = cd(r15).scheme, p = cd(r15).path, u = i === cd(r15).scheme, c = await n.load();
  t10 && u && await Os.getManager(i).removeModel(p);
  let l = await a.save(c);
  return t10 && !u && await Os.getManager(i).removeModel(p), l.modelArtifactsInfo;
}
async function kk() {
  let r15 = Os.getSchemes(), e = {};
  for (let t10 of r15) {
    let o = await Os.getManager(t10).listModels();
    for (let n in o) {
      let s = t10 + oc + n;
      e[s] = o[n];
    }
  }
  return e;
}
async function Nk(r15) {
  let e = cd(r15);
  return Os.getManager(e.scheme).removeModel(e.path);
}
async function Tk(r15, e) {
  return vk(r15, e, false);
}
async function _k(r15, e) {
  return vk(r15, e, true);
}
var Fw = class {
  constructor() {
    this.messageName = "setTimeoutCustom", this.functionRefs = [], this.handledMessageCount = 0, this.hasEventListener = false;
  }
  fetch(e, t10) {
    return fetch(e, t10);
  }
  now() {
    return performance.now();
  }
  encode(e, t10) {
    if (t10 !== "utf-8" && t10 !== "utf8") throw new Error(`Browser's encoder only supports utf-8, but got ${t10}`);
    return this.textEncoder == null && (this.textEncoder = new TextEncoder()), this.textEncoder.encode(e);
  }
  decode(e, t10) {
    return new TextDecoder(t10).decode(e);
  }
  setTimeoutCustom(e, t10) {
    if (typeof window == "undefined" || !A().getBool("USE_SETTIMEOUTCUSTOM")) {
      setTimeout(e, t10);
      return;
    }
    this.functionRefs.push(e), setTimeout(() => {
      window.postMessage({ name: this.messageName, index: this.functionRefs.length - 1 }, "*");
    }, t10), this.hasEventListener || (this.hasEventListener = true, window.addEventListener("message", (o) => {
      if (o.source === window && o.data.name === this.messageName) {
        o.stopPropagation();
        let n = this.functionRefs[o.data.index];
        n(), this.handledMessageCount++, this.handledMessageCount === this.functionRefs.length && (this.functionRefs = [], this.handledMessageCount = 0);
      }
    }, true));
  }
  isTypedArray(e) {
    return Qm(e);
  }
};
if (A().get("IS_BROWSER")) {
  A().setPlatform("browser", new Fw());
  try {
    Os.registerManager(Na.URL_SCHEME, new pd());
  } catch (r15) {
  }
  try {
    Os.registerManager(ka.URL_SCHEME, new ud());
  } catch (r15) {
  }
}
var z4 = { importFetch: () => Ek() };
var Pw;
var Ow = class {
  constructor() {
    this.util = $k(), this.textEncoder = new this.util.TextEncoder();
  }
  fetch(e, t10) {
    return A().global.fetch != null ? A().global.fetch(e, t10) : (Pw == null && (Pw = z4.importFetch()), Pw(e, t10));
  }
  now() {
    let e = process.hrtime();
    return e[0] * 1e3 + e[1] / 1e6;
  }
  encode(e, t10) {
    if (t10 !== "utf-8" && t10 !== "utf8") throw new Error(`Node built-in encoder only supports utf-8, but got ${t10}`);
    return this.textEncoder.encode(e);
  }
  decode(e, t10) {
    return e.length === 0 ? "" : new this.util.TextDecoder(t10).decode(e);
  }
  isTypedArray(e) {
    return this.util.types.isFloat32Array(e) || this.util.types.isInt32Array(e) || this.util.types.isUint8Array(e) || this.util.types.isUint8ClampedArray(e);
  }
};
A().get("IS_NODE") && !A().get("IS_BROWSER") && A().setPlatform("node", new Ow());
function me(r15, e = "float32", t10) {
  return e = e || "float32", Ct(r15), new tt(r15, e, t10);
}
function V4(r15, e) {
  let t10 = v(r15, "x", "cast");
  if (!rw(e)) throw new Error(`Failed to cast to unknown dtype ${e}`);
  if (e === "string" && t10.dtype !== "string" || e !== "string" && t10.dtype === "string") throw new Error("Only strings can be casted to strings");
  let o = { x: t10 }, n = { dtype: e };
  return T.runKernel(yo, o, n);
}
var Ue = N({ cast_: V4 });
function W4(r15) {
  let t10 = { x: v(r15, "x", "clone", "string_or_numeric") };
  return T.runKernel(Co, t10);
}
var Ur = N({ clone_: W4 });
function ld(r15, e = false) {
  console.log(r15.toString(e));
}
Iw();
var U4 = { buffer: me, cast: Ue, clone: Ur, print: ld };
J0(U4);
function G4(r15, e) {
  let t10 = v(r15, "a", "add"), o = v(e, "b", "add");
  [t10, o] = Oe(t10, o);
  let n = { a: t10, b: o };
  return T.runKernel("Add", n);
}
var Ce = N({ add_: G4 });
function H4(r15, e) {
  let t10 = v(r15, "a", "floorDiv"), o = v(e, "b", "floorDiv");
  [t10, o] = Oe(t10, o);
  let n = { a: t10, b: o };
  return T.runKernel(Sn, n);
}
var md = N({ floorDiv_: H4 });
function K4(r15, e) {
  let t10 = v(r15, "a", "div"), o = v(e, "b", "div");
  if ([t10, o] = Oe(t10, o), t10.dtype === "int32" && o.dtype === "int32") return md(t10, o);
  let n = { a: t10, b: o }, s = {};
  return T.runKernel(fn, n, s);
}
var je = N({ div_: K4 });
function q4(r15, e) {
  let t10 = v(r15, "a", "mul"), o = v(e, "b", "mul");
  [t10, o] = Oe(t10, o);
  let n = { a: t10, b: o };
  return T.runKernel(Xn, n);
}
var se = N({ mul_: q4 });
function j4(r15) {
  let e = v(r15, "x", "abs");
  if (e.dtype === "complex64") {
    let t10 = { x: e };
    return T.runKernel(Ai, t10);
  } else {
    let t10 = { x: e };
    return T.runKernel("Abs", t10);
  }
}
var Qt = N({ abs_: j4 });
function X4(r15) {
  let t10 = { x: v(r15, "x", "acos") };
  return T.runKernel(Vo, t10);
}
var Rk = N({ acos_: X4 });
function Y4(r15) {
  let t10 = { x: v(r15, "x", "acosh") };
  return T.runKernel(Wo, t10);
}
var Dk = N({ acosh_: Y4 });
function Q4(r15) {
  E(Array.isArray(r15), () => "The argument passed to tf.addN() must be a list of tensors"), E(r15.length >= 1, () => `Must pass at least one tensor to tf.addN(), but got ${r15.length}`);
  let e = r15.map((n, s) => v(n, `tensors${s}`, "addN")), t10 = e[0];
  e.forEach((n) => {
    if (n.dtype !== t10.dtype) throw new Error("All tensors passed to tf.addN() must have the same dtype");
  }), e.forEach((n) => {
    if (!br(n.shape, t10.shape)) throw new Error("All tensors passed to tf.addN() must have the same shape");
  });
  let o = e;
  return T.runKernel(Uo, o);
}
var Ak = N({ addN_: Q4 });
function Z4(r15, e = null, t10 = false) {
  let n = { x: v(r15, "x", "all", "bool") }, s = { axis: e, keepDims: t10 };
  return T.runKernel("All", n, s);
}
var Fk = N({ all_: Z4 });
function J4(r15, e = null, t10 = false) {
  let n = { x: v(r15, "x", "any", "bool") }, s = { axis: e, keepDims: t10 };
  return T.runKernel("Any", n, s);
}
var Pk = N({ any_: J4 });
function eH(r15, e = 0) {
  let o = { x: v(r15, "x", "argMax") }, n = { axis: e };
  return T.runKernel(Ys, o, n);
}
var Ok = N({ argMax_: eH });
function tH(r15, e = 0) {
  let o = { x: v(r15, "x", "argMin") }, n = { axis: e };
  return T.runKernel(Qs, o, n);
}
var Mk = N({ argMin_: tH });
function rH(r15) {
  let t10 = { x: v(r15, "x", "asin") };
  return T.runKernel(Ko, t10);
}
var Lk = N({ asin_: rH });
function oH(r15) {
  let t10 = { x: v(r15, "x", "asinh") };
  return T.runKernel(qo, t10);
}
var Bk = N({ asinh_: oH });
function nH(r15) {
  let t10 = { x: v(r15, "x", "atan") };
  return T.runKernel(jo, t10);
}
var zk = N({ atan_: nH });
function sH(r15, e) {
  let t10 = v(r15, "a", "atan2"), o = v(e, "b", "atan2");
  [t10, o] = Oe(t10, o);
  let n = { a: t10, b: o };
  return T.runKernel(Yo, n);
}
var Vk = N({ atan2_: sH });
function aH(r15) {
  let t10 = { x: v(r15, "x", "atanh") };
  return T.runKernel(Xo, t10);
}
var Wk = N({ atanh_: aH });
function iH(r15, e, t10, o, n = "NHWC", s) {
  let a = r15[3], i = [...e, a], p = Gk(n);
  return zu(r15, i, t10, s, o, null, null, p);
}
function Lw(r15, e, t10, o, n, s, a = "channelsLast") {
  let [i, p] = Il(e), u;
  if (a === "channelsLast") u = [i, p, r15[3], r15[3]];
  else if (a === "channelsFirst") u = [i, p, r15[1], r15[1]];
  else throw new Error(`Unknown dataFormat ${a}`);
  return zu(r15, u, t10, o, n, s, false, a);
}
function uH(r15, e, t10, o, n, s, a = "NDHWC") {
  let [i, p, u] = Mw(e), c, l;
  if (a === "NDHWC") l = "channelsLast", c = [i, p, u, r15[4], r15[4]];
  else if (a === "NCDHW") l = "channelsFirst", c = [i, p, u, r15[1], r15[1]];
  else throw new Error(`Unknown dataFormat ${a}`);
  return Uk(r15, c, t10, o, n, false, l, s);
}
function zu(r15, e, t10, o, n, s, a = false, i = "channelsLast") {
  let [p, u, c, l] = [-1, -1, -1, -1];
  if (i === "channelsLast") [p, u, c, l] = r15;
  else if (i === "channelsFirst") [p, l, u, c] = r15;
  else throw new Error(`Unknown dataFormat ${i}`);
  let [m, d, , f] = e, [h, g] = Il(t10), [x, b] = Il(o), C = nc(m, x), S = nc(d, b), { padInfo: k, outHeight: _, outWidth: $ } = lH(n, u, c, h, g, C, S, s, i), R = a ? f * l : f, D;
  return i === "channelsFirst" ? D = [p, R, _, $] : i === "channelsLast" && (D = [p, _, $, R]), { batchSize: p, dataFormat: i, inHeight: u, inWidth: c, inChannels: l, outHeight: _, outWidth: $, outChannels: R, padInfo: k, strideHeight: h, strideWidth: g, filterHeight: m, filterWidth: d, effectiveFilterHeight: C, effectiveFilterWidth: S, dilationHeight: x, dilationWidth: b, inShape: r15, outShape: D, filterShape: e };
}
function Uk(r15, e, t10, o, n, s = false, a = "channelsLast", i) {
  let [p, u, c, l, m] = [-1, -1, -1, -1, -1];
  if (a === "channelsLast") [p, u, c, l, m] = r15;
  else if (a === "channelsFirst") [p, m, u, c, l] = r15;
  else throw new Error(`Unknown dataFormat ${a}`);
  let [d, f, h, , g] = e, [x, b, C] = Mw(t10), [S, k, _] = Mw(o), $ = nc(d, S), R = nc(f, k), D = nc(h, _), { padInfo: P, outDepth: O, outHeight: M, outWidth: L } = mH(n, u, c, l, x, b, C, $, R, D, i), B = s ? g * m : g, z;
  return a === "channelsFirst" ? z = [p, B, O, M, L] : a === "channelsLast" && (z = [p, O, M, L, B]), { batchSize: p, dataFormat: a, inDepth: u, inHeight: c, inWidth: l, inChannels: m, outDepth: O, outHeight: M, outWidth: L, outChannels: B, padInfo: P, strideDepth: x, strideHeight: b, strideWidth: C, filterDepth: d, filterHeight: f, filterWidth: h, effectiveFilterDepth: $, effectiveFilterHeight: R, effectiveFilterWidth: D, dilationDepth: S, dilationHeight: k, dilationWidth: _, inShape: r15, outShape: z, filterShape: e };
}
function pH(r15, e, t10, o, n) {
  o == null && (o = Bw(r15, e, t10));
  let s = r15[0], a = r15[1], i = vl((s - e + 2 * o) / t10 + 1, n), p = vl((a - e + 2 * o) / t10 + 1, n);
  return [i, p];
}
function cH(r15, e, t10, o, n, s) {
  n == null && (n = Bw(r15, e[0], o[0]));
  let a = [0, 0, 0, t10];
  for (let i = 0; i < 3; i++) r15[i] + 2 * n >= e[i] && (a[i] = vl((r15[i] - e[i] + 2 * n) / o[i] + 1, s));
  return a;
}
function Bw(r15, e, t10, o = 1) {
  let n = nc(e, o);
  return Math.floor((r15[0] * (t10 - 1) - t10 + n) / 2);
}
function Il(r15) {
  return typeof r15 == "number" ? [r15, r15, r15] : r15.length === 2 ? [r15[0], r15[1], 1] : r15;
}
function Mw(r15) {
  return typeof r15 == "number" ? [r15, r15, r15] : r15;
}
function nc(r15, e) {
  return e <= 1 ? r15 : r15 + (r15 - 1) * (e - 1);
}
function lH(r15, e, t10, o, n, s, a, i, p) {
  let u, c, l;
  if (typeof r15 == "number") {
    u = { top: r15, bottom: r15, left: r15, right: r15, type: r15 === 0 ? "VALID" : "NUMBER" };
    let d = pH([e, t10], s, o, r15, i);
    c = d[0], l = d[1];
  } else if (r15 === "same") {
    c = Math.ceil(e / o), l = Math.ceil(t10 / n);
    let m = Math.max(0, (c - 1) * o + s - e), d = Math.max(0, (l - 1) * n + a - t10), f = Math.floor(m / 2), h = m - f, g = Math.floor(d / 2), x = d - g;
    u = { top: f, bottom: h, left: g, right: x, type: "SAME" };
  } else if (r15 === "valid") u = { top: 0, bottom: 0, left: 0, right: 0, type: "VALID" }, c = Math.ceil((e - s + 1) / o), l = Math.ceil((t10 - a + 1) / n);
  else if (typeof r15 == "object") {
    let m = p === "channelsLast" ? r15[1][0] : r15[2][0], d = p === "channelsLast" ? r15[1][1] : r15[2][1], f = p === "channelsLast" ? r15[2][0] : r15[3][0], h = p === "channelsLast" ? r15[2][1] : r15[3][1];
    u = { top: m, bottom: d, left: f, right: h, type: m === 0 && d === 0 && f === 0 && h === 0 ? "VALID" : "EXPLICIT" }, c = vl((e - s + m + d) / o + 1, i), l = vl((t10 - a + f + h) / n + 1, i);
  } else throw Error(`Unknown padding parameter: ${r15}`);
  return { padInfo: u, outHeight: c, outWidth: l };
}
function mH(r15, e, t10, o, n, s, a, i, p, u, c) {
  let l, m, d, f;
  if (r15 === "valid" && (r15 = 0), typeof r15 == "number") {
    l = { top: r15, bottom: r15, left: r15, right: r15, front: r15, back: r15, type: r15 === 0 ? "VALID" : "NUMBER" };
    let g = cH([e, t10, o, 1], [i, p, u], 1, [n, s, a], r15, c);
    m = g[0], d = g[1], f = g[2];
  } else if (r15 === "same") {
    m = Math.ceil(e / n), d = Math.ceil(t10 / s), f = Math.ceil(o / a);
    let h = (m - 1) * n + i - e, g = (d - 1) * s + p - t10, x = (f - 1) * a + u - o, b = Math.floor(h / 2), C = h - b, S = Math.floor(g / 2), k = g - S, _ = Math.floor(x / 2), $ = x - _;
    l = { top: S, bottom: k, left: _, right: $, front: b, back: C, type: "SAME" };
  } else throw Error(`Unknown padding parameter: ${r15}`);
  return { padInfo: l, outDepth: m, outHeight: d, outWidth: f };
}
function vl(r15, e) {
  if (!e) return Math.trunc(r15);
  switch (e) {
    case "round":
      return Math.round(r15);
    case "ceil":
      return Math.ceil(r15);
    case "floor":
      return Math.floor(r15);
    default:
      throw new Error(`Unknown roundingMode ${e}`);
  }
}
function Bu(r15) {
  let [e, t10, o] = Il(r15);
  return e === 1 && t10 === 1 && o === 1;
}
function gr(r15, e) {
  return Bu(r15) || Bu(e);
}
function Ta(r15) {
  return Il(r15).every((e) => e > 0);
}
function Gk(r15) {
  if (r15 === "NHWC") return "channelsLast";
  if (r15 === "NCHW") return "channelsFirst";
  throw new Error(`Unknown dataFormat ${r15}`);
}
function Lt(r15, e, t10) {
  if (t10 != null) {
    if (typeof e == "string") throw Error(`Error in ${r15}: pad must be an integer when using dimRoundingMode ${t10} but got pad ${e}.`);
    if (typeof e == "number") E(Ka(e), () => `Error in ${r15}: pad must be an integer when using dimRoundingMode ${t10} but got pad ${e}.`);
    else if (typeof e == "object") e.forEach((o) => {
      o.forEach((n) => {
        E(Ka(n), () => `Error in ${r15}: pad must be an integer when using dimRoundingMode ${t10} but got pad ${n}.`);
      });
    });
    else throw Error(`Error in ${r15}: Unknown padding parameter: ${e}`);
  }
}
function dH(r15, e) {
  let o = { x: v(r15, "x", "reshape", "string_or_numeric") }, n = { shape: e };
  return T.runKernel(da, o, n);
}
var W = N({ reshape_: dH });
function fH(r15, e, t10, o, n) {
  let s = v(r15, "x", "avgPool", "float32"), a = 1;
  E(gr(t10, a), () => `Error in avgPool: Either strides or dilations must be 1. Got strides ${t10} and dilations '${a}'`);
  let i = s, p = false;
  s.rank === 3 && (p = true, i = W(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}.`), Lt("avgPool", o, n);
  let u = { x: i }, c = { filterSize: e, strides: t10, pad: o, dimRoundingMode: n }, l = T.runKernel(Qo, u, c);
  return l = Ue(l, s.dtype), p ? W(l, [l.shape[1], l.shape[2], l.shape[3]]) : l;
}
var dd = N({ avgPool_: fH });
function hH(r15, e, t10, o, n, s = "NDHWC") {
  let a = v(r15, "x", "avgPool3d", "float32"), i = a, p = false;
  a.rank === 4 && (p = true, i = W(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}`), E(typeof t10 == "number" && t10 > 0 || Array.isArray(t10) && t10[0] > 0 && t10[1] > 0 && t10[2] > 0, () => `Error in avgPool3d: Stride must be > 0, but got '${t10}'`), Lt("avgPool3d", o, n);
  let u = { x: i }, c = { filterSize: e, strides: t10, pad: o, dimRoundingMode: n, dataFormat: s }, l = T.runKernel(Zs, u, c);
  return l = Ue(l, i.dtype), p ? W(l, [l.shape[1], l.shape[2], l.shape[3], l.shape[4]]) : l;
}
var Hk = N({ avgPool3d_: hH });
function gH(r15, e = 0) {
  E(r15.length >= 1, () => "Pass at least one tensor to concat");
  let t10 = ni(r15, "tensors", "concat", "string_or_numeric");
  if (t10[0].dtype === "complex64" && t10.forEach((s) => {
    if (s.dtype !== "complex64") throw new Error(`Cannot concatenate complex64 tensors with a tensor
          with dtype ${s.dtype}. `);
  }), t10.length === 1) return Ur(t10[0]);
  let o = t10, n = { axis: e };
  return T.runKernel(ta, o, n);
}
var yt = N({ concat_: gH });
function xH(r15, e, t10 = false, o = false) {
  let n = v(r15, "a", "matMul"), s = v(e, "b", "matMul");
  [n, s] = Oe(n, s);
  let a = { a: n, b: s }, i = { transposeA: t10, transposeB: o };
  return T.runKernel(Zo, a, i);
}
var Ze = N({ matMul_: xH });
function yH(r15) {
  let t10 = { x: v(r15, "x", "sigmoid", "float32") };
  return T.runKernel(bs, t10);
}
var Ea = N({ sigmoid_: yH });
function bH(r15, e, t10) {
  let o = v(r15, "x", "slice", "string_or_numeric");
  if (o.rank === 0) throw new Error("Slicing scalar is not possible");
  let n = { x: o }, s = { begin: e, size: t10 };
  return T.runKernel(ha, n, s);
}
var Xe = N({ slice_: bH });
function CH(r15) {
  let t10 = { x: v(r15, "x", "tanh", "float32") };
  return T.runKernel(Es, t10);
}
var kl = N({ tanh_: CH });
function wH(r15, e, t10, o, n, s) {
  let a = v(r15, "forgetBias", "basicLSTMCell"), i = v(e, "lstmKernel", "basicLSTMCell"), p = v(t10, "lstmBias", "basicLSTMCell"), u = v(o, "data", "basicLSTMCell"), c = v(n, "c", "basicLSTMCell"), l = v(s, "h", "basicLSTMCell"), m = yt([u, l], 1), d = Ze(m, i), f = Ce(d, p), h = f.shape[0], g = f.shape[1] / 4, x = [h, g], b = Xe(f, [0, 0], x), C = Xe(f, [0, g], x), S = Xe(f, [0, g * 2], x), k = Xe(f, [0, g * 3], x), _ = Ce(se(Ea(b), kl(C)), se(c, Ea(Ce(a, S)))), $ = se(kl(_), Ea(k));
  return [_, $];
}
var Kk = N({ basicLSTMCell_: wH });
function SH(r15, e, t10) {
  let o = v(r15, "x", "batchToSpaceND"), n = e.reduce((i, p) => i * p);
  E(o.rank >= 1 + e.length, () => `input rank is ${o.rank} but should be > than blockShape.length ${e.length}`), E(t10.length === e.length, () => `crops.length is ${t10.length} but should be equal to blockShape.length  ${e.length}`), E(o.shape[0] % n === 0, () => `input tensor batch is ${o.shape[0]} but is not divisible by the product of the elements of blockShape ${e.join(" * ")} === ${n}`);
  let s = { x: o }, a = { blockShape: e, crops: t10 };
  return T.runKernel(Js, s, a);
}
var fd = N({ batchToSpaceND_: SH });
function qk(r15) {
  let e;
  return r15.rank === 0 || r15.rank === 1 ? e = W(r15, [1, 1, 1, r15.size]) : r15.rank === 2 ? e = W(r15, [1, 1, r15.shape[0], r15.shape[1]]) : r15.rank === 3 ? e = W(r15, [1, r15.shape[0], r15.shape[1], r15.shape[2]]) : e = r15, e;
}
function IH(r15, e, t10, o, n, s) {
  s == null && (s = 1e-3);
  let a = v(r15, "x", "batchNorm"), i = v(e, "mean", "batchNorm"), p = v(t10, "variance", "batchNorm"), u;
  n != null && (u = v(n, "scale", "batchNorm"));
  let c;
  o != null && (c = v(o, "offset", "batchNorm")), E(i.rank === p.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: qk(a), scale: u, offset: c, mean: i, variance: p }, d = { varianceEpsilon: s }, f = T.runKernel(In, m, d);
  return W(f, a.shape);
}
var nu = N({ batchNorm_: IH });
function vH(r15, e, t10, o, n, s) {
  let a = v(r15, "x", "batchNorm"), i = v(e, "mean", "batchNorm"), p = v(t10, "variance", "batchNorm"), u;
  n != null && (u = v(n, "scale", "batchNorm"));
  let c;
  return o != null && (c = v(o, "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(p.rank === 2 || p.rank === 1, () => `Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${p.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}.`), nu(a, i, p, c, u, s);
}
var jk = N({ batchNorm2d_: vH });
function kH(r15, e, t10, o, n, s) {
  let a = v(r15, "x", "batchNorm"), i = v(e, "mean", "batchNorm"), p = v(t10, "variance", "batchNorm"), u;
  n != null && (u = v(n, "scale", "batchNorm"));
  let c;
  return o != null && (c = v(o, "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(p.rank === 3 || p.rank === 1, () => `Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${p.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}.`), nu(a, i, p, c, u, s);
}
var Xk = N({ batchNorm3d_: kH });
function NH(r15, e, t10, o, n, s) {
  let a = v(r15, "x", "batchNorm"), i = v(e, "mean", "batchNorm"), p = v(t10, "variance", "batchNorm"), u;
  n != null && (u = v(n, "scale", "batchNorm"));
  let c;
  return o != null && (c = v(o, "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(p.rank === 4 || p.rank === 1, () => `Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${p.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}.`), nu(a, i, p, c, u, s);
}
var Yk = N({ batchNorm4d_: NH });
function TH(r15, e, t10) {
  let o = v(r15, "x", "bincount"), n = v(e, "weights", "bincount");
  E(o.dtype === "int32", () => `Error in bincount: input dtype must be int32, but got ${o.dtype}`), E(t10 >= 0, () => `size must be non-negative, but got ${t10}.`), E(n.size === o.size || n.size === 0, () => `Error in bincount: weights must have the same size as input or0-length, but got input shape: ${o.shape}, weights shape: ${n.shape}.`);
  let s = { x: o, weights: n }, a = { size: t10 };
  return T.runKernel(Jo, s, a);
}
var hd = N({ bincount_: TH });
function _H(r15, e) {
  let t10 = v(r15, "x", "bitwiseAnd"), o = v(e, "y", "bitwiseAnd");
  if (!br(t10.shape, o.shape)) throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${t10.shape}, y: ${o.shape}`);
  if (t10.dtype !== "int32" || o.dtype !== "int32") throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${t10.dtype} and type of y: ${o.dtype}`);
  let n = { a: t10, b: o };
  return T.runKernel(qa, n);
}
var Qk = N({ bitwiseAnd_: _H });
function EH(r15, e) {
  let t10 = v(r15, "s0", "broadcastArgs", "int32"), o = v(e, "s1", "broadcastArgs", "int32");
  if (t10.rank !== 1) throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${t10.rank}`);
  if (o.rank !== 1) throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${o.rank}`);
  let n = { s0: t10, s1: o };
  return T.runKernel(ea, n);
}
var Zk = N({ broadcastArgs_: EH });
function $H(r15, e) {
  let t10 = v(r15, "broadcastTo", "x"), o = t10.shape;
  if (Ct(e), e.length < t10.rank) throw new Error(`broadcastTo(): shape.length=${e.length} < input.rank=${t10.rank}.`);
  if (e.length > t10.rank) {
    let u = t10.shape.slice();
    for (; u.length < e.length; ) u.unshift(1);
    t10 = W(t10, u);
  }
  let n = t10.shape, s = Array.from(e);
  for (let u = e.length - 1; u >= 0; u--) if (n[u] === e[u]) s[u] = 1;
  else if (t10.shape[u] !== 1) throw new Error(`broadcastTo(): [${o}] cannot be broadcast to [${e}].`);
  if (s.map((u, c) => u > 1 ? c : -1).filter((u) => u >= 0).length === 0) return Ur(t10);
  let i = { x: t10 }, p = { reps: s };
  return T.runKernel(po, i, p);
}
var su = N({ broadcastTo_: $H });
function RH(r15) {
  let t10 = { x: v(r15, "x", "ceil", "float32") };
  return T.runKernel(en, t10);
}
var Jk = N({ ceil_: RH });
function $a(r15, e, t10) {
  Ct(r15), t10 = t10 || Ei(e);
  let o = { shape: r15, value: e, dtype: t10 };
  return T.runKernel(sa, {}, o);
}
function DH(r15, e, t10) {
  let o = v(r15, "x", "clipByValue");
  if (E(e <= t10, () => `Error in clip: min (${e}) must be less than or equal to max (${t10}).`), e === t10) return $a(o.shape, e, o.dtype);
  let n = { x: o }, s = { clipValueMin: e, clipValueMax: t10 };
  return T.runKernel(bo, n, s);
}
var e2 = N({ clipByValue_: DH });
function AH(r15) {
  return yt(r15, 0);
}
var t2 = N({ concat1d_: AH });
function FH(r15, e) {
  return yt(r15, e);
}
var r22 = N({ concat2d_: FH });
function PH(r15, e) {
  return yt(r15, e);
}
var o2 = N({ concat3d_: PH });
function OH(r15, e) {
  return yt(r15, e);
}
var n2 = N({ concat4d_: OH });
function MH(r15, e, t10, o, n = "NHWC", s = [1, 1], a) {
  let i = v(r15, "x", "conv2d", "float32"), p = v(e, "filter", "conv2d", "float32"), u = i, c = false;
  i.rank === 3 && (c = true, u = W(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(p.rank === 4, () => `Error in conv2d: filter must be rank 4, but got rank ${p.rank}.`), Lt("conv2d", o, a);
  let l = n === "NHWC" ? u.shape[3] : u.shape[1];
  E(l === p.shape[2], () => `Error in conv2d: depth of input (${l}) must match input depth for filter ${p.shape[2]}.`), E(gr(t10, s), () => `Error in conv2D: Either strides or dilations must be 1. Got strides ${t10} and dilations '${s}'`), E(Ta(s), () => "Error in conv2D: Dilated rates should be larger than 0."), E(Ta(t10), () => "Error in conv2D: Strides should be larger than 0.");
  let m = { x: u, filter: p }, d = { strides: t10, pad: o, dataFormat: n, dilations: s, dimRoundingMode: a }, f = T.runKernel(tn, m, d);
  return c ? W(f, [f.shape[1], f.shape[2], f.shape[3]]) : f;
}
var au = N({ conv2d_: MH });
function LH(r15, e, t10, o, n = "NWC", s = 1, a) {
  let i = v(r15, "x", "conv1d"), p = v(e, "filter", "conv1d"), u = i, c = false;
  i.rank === 2 && (c = true, u = W(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(p.rank === 3, () => `Error in conv1d: filter must be rank 3, but got rank ${p.rank}.`), Lt("conv1d", o, a), E(u.shape[2] === p.shape[1], () => `Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${p.shape[1]}.`), E(gr(t10, s), () => `Error in conv1D: Either stride or dilation must be 1. Got stride ${t10} and dilation '${s}'`), E(Ta(s), () => "Error in conv1D: Dilated rates should be larger than 0."), E(Ta(t10), () => "Error in conv1D: Stride should be larger than 0."), E(n === "NWC", () => `Error in conv1d: got dataFormat of ${n} but only NWC is currently supported.`);
  let l = W(p, [1, p.shape[0], p.shape[1], p.shape[2]]), m = W(u, [u.shape[0], 1, u.shape[1], u.shape[2]]), g = au(m, l, [1, t10], o, "NHWC", [1, s], a);
  return c ? W(g, [g.shape[2], g.shape[3]]) : W(g, [g.shape[0], g.shape[2], g.shape[3]]);
}
var s2 = N({ conv1d_: LH });
function BH(r15, e, t10, o, n, s = "NHWC", a) {
  E(r15.length === e.rank, () => `Length of inShape (${r15.length}) and rank of dy (${e.rank}) must match`);
  let i = r15, p = e, u = false;
  e.rank === 3 && (u = true, p = W(e, [1, e.shape[0], e.shape[1], e.shape[2]]), i = [1, r15[0], r15[1], r15[2]]), E(i.length === 4, () => `Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`), E(p.rank === 4, () => `Error in conv2dDerInput: dy must be rank 4, but got rank ${p.rank}`), E(t10.rank === 4, () => `Error in conv2dDerInput: filter must be rank 4, but got rank ${t10.rank}`);
  let c = s === "NHWC" ? i[3] : i[1], l = s === "NHWC" ? p.shape[3] : p.shape[1];
  E(c === t10.shape[2], () => `Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${t10.shape[2]}.`), E(l === t10.shape[3], () => `Error in conv2dDerInput: depth of output (${l}) must match output depth for filter ${t10.shape[3]}.`), Lt("conv2dDerInput", n, a);
  let m = { dy: p, filter: t10 }, d = { strides: o, pad: n, dataFormat: s, dimRoundingMode: a, inputShape: i }, f = T.runKernel(rn, m, d);
  return u ? W(f, [f.shape[1], f.shape[2], f.shape[3]]) : f;
}
var gd = N({ conv2DBackpropInput_: BH });
function zH(r15, e, t10, o, n, s) {
  let a = v(r15, "x", "conv2dTranspose"), i = v(e, "filter", "conv2dTranspose");
  return gd(t10, a, i, o, n, "NHWC", s);
}
var a2 = N({ conv2dTranspose_: zH });
function VH(r15, e, t10, o, n = "NDHWC", s = [1, 1, 1]) {
  let a = v(r15, "x", "conv3d"), i = v(e, "filter", "conv3d"), p = a, u = false;
  a.rank === 4 && (u = true, p = W(a, [1, a.shape[0], a.shape[1], a.shape[2], a.shape[3]])), E(p.rank === 5, () => `Error in conv3d: input must be rank 5, but got rank ${p.rank}.`), E(i.rank === 5, () => `Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`), E(p.shape[4] === i.shape[3], () => `Error in conv3d: depth of input (${p.shape[4]}) must match input depth for filter ${i.shape[3]}.`), E(gr(t10, s), () => `Error in conv3D: Either strides or dilations must be 1. Got strides ${t10} and dilations '${s}'`), E(n === "NDHWC", () => `Error in conv3d: got dataFormat of ${n} but only NDHWC is currently supported.`), E(Ta(s), () => "Error in conv3D: Dilated rates should be larger than 0."), E(Ta(t10), () => "Error in conv3D: Strides should be larger than 0.");
  let c = { x: p, filter: i }, l = { strides: t10, pad: o, dataFormat: n, dilations: s }, m = T.runKernel(on, c, l);
  return u ? W(m, [m.shape[1], m.shape[2], m.shape[3], m.shape[4]]) : m;
}
var i2 = N({ conv3d_: VH });
function WH(r15, e, t10, o, n) {
  E(r15.length === e.rank, () => `Length of inShape (${r15.length}) and rank of dy (${e.rank}) must match`);
  let s = r15, a = e, i = false;
  e.rank === 4 && (i = true, a = W(e, [1, e.shape[0], e.shape[1], e.shape[2], e.shape[3]]), s = [1, r15[0], r15[1], r15[2], r15[3]]);
  let p = 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(t10.rank === 5, () => `Error in conv3dDerInput: filter must be rank 5, but got rank ${t10.rank}`), E(p === t10.shape[3], () => `Error in conv3dDerInput: depth of input (${p}) must match input depth for filter ${t10.shape[3]}.`), E(u === t10.shape[4], () => `Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${t10.shape[4]}.`);
  let c = { dy: a, filter: t10 }, l = { pad: n, strides: o, inputShape: s }, m = T.runKernel(nn, c, l);
  return i ? W(m, [m.shape[1], m.shape[2], m.shape[3], m.shape[4]]) : m;
}
var u2 = N({ conv3DBackpropInput_: WH });
function UH(r15, e, t10, o, n) {
  let s = v(r15, "x", "conv3dTranspose"), a = v(e, "filter", "conv3dTranspose");
  return u2(t10, s, a, o, n);
}
var p2 = N({ conv3dTranspose_: UH });
function GH(r15) {
  let t10 = { x: v(r15, "x", "cos", "float32") };
  return T.runKernel("Cos", t10);
}
var c2 = N({ cos_: GH });
function HH(r15) {
  let t10 = { x: v(r15, "x", "cosh", "float32") };
  return T.runKernel(an, t10);
}
var l2 = N({ cosh_: HH });
function KH(r15, e = 0, t10 = false, o = false) {
  let s = { x: v(r15, "x", "cumprod") }, a = { axis: e, exclusive: t10, reverse: o };
  return T.runKernel(un, s, a);
}
var m2 = N({ cumprod_: KH });
function qH(r15, e = 0, t10 = false, o = false) {
  let s = { x: v(r15, "x", "cumsum") }, a = { axis: e, exclusive: t10, reverse: o };
  return T.runKernel(pn, s, a);
}
var d2 = N({ cumsum_: qH });
function jH(r15, e, t10, o = false) {
  let n = v(r15, "x", "denseBincount"), s = v(e, "weights", "denseBincount");
  E(n.dtype === "int32", () => `Error in denseBincount: input dtype must be int32, but got ${n.dtype}`), E(n.rank <= 2, () => `Error in denseBincount: input must be at most rank 2, but got rank ${n.rank}.`), E(t10 >= 0, () => `size must be non-negative, but got ${t10}.`), E(s.size === n.size || s.size === 0, () => `Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${n.shape}, weights shape: ${s.shape}.`);
  let a = { x: n, weights: s }, i = { size: t10, binaryOutput: o };
  return T.runKernel(ra, a, i);
}
var f2 = N({ denseBincount_: jH });
function XH(r15, e, t10 = "NHWC") {
  let o = v(r15, "x", "depthToSpace", "float32"), n = t10 === "NHWC" ? o.shape[1] : o.shape[2], s = t10 === "NHWC" ? o.shape[2] : o.shape[3], a = t10 === "NHWC" ? o.shape[3] : o.shape[1];
  E(e > 1, () => `blockSize should be > 1 for depthToSpace, but was: ${e}`), E(n * e >= 0, () => `Negative dimension size caused by overflow when multiplying
    ${n} and ${e}  for depthToSpace with input shape
    ${o.shape}`), E(s * e >= 0, () => `Negative dimension size caused by overflow when multiplying
    ${s} and ${e} for depthToSpace with input shape
        ${o.shape}`), E(a % (e * e) === 0, () => `Dimension size must be evenly divisible by ${e * e} but is ${a} for depthToSpace with input shape ${o.shape}`);
  let i = { x: o }, p = { blockSize: e, dataFormat: t10 };
  return T.runKernel(ln, i, p);
}
var h2 = N({ depthToSpace_: XH });
function YH(r15, e, t10, o, n = "NHWC", s = [1, 1], a) {
  let i = v(r15, "x", "depthwiseConv2d", "float32"), p = v(e, "filter", "depthwiseConv2d", "float32"), u = i, c = false;
  i.rank === 3 && (c = true, u = W(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(p.rank === 4, () => `Error in depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`);
  let l = n === "NHWC" ? u.shape[3] : u.shape[1];
  E(l === p.shape[2], () => `Error in depthwiseConv2d: number of input channels (${l}) must match the inChannels dimension in filter ${p.shape[2]}.`), Lt("depthwiseConv2d", o, a);
  let m = { x: u, filter: p }, d = { strides: t10, pad: o, dataFormat: n, dilations: s, dimRoundingMode: a }, f = T.runKernel(mn, m, d);
  return c ? W(f, [f.shape[1], f.shape[2], f.shape[3]]) : f;
}
var sc = N({ depthwiseConv2d_: YH });
function QH(r15) {
  let t10 = { x: v(r15, "x", "diag") };
  return T.runKernel(oa, t10);
}
var g2 = N({ diag_: QH });
function ZH(r15, e, t10, o, n = [1, 1], s = "NHWC") {
  let a = v(r15, "x", "dilation2d"), i = v(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 p = a, u = false;
  a.rank === 3 && (p = W(a, [1, a.shape[0], a.shape[1], a.shape[2]]), u = true), E(p.shape[3] === i.shape[2], () => `Error in dilation2d:  input and filter must have the same depth: ${p.shape[3]} vs ${i.shape[2]}`);
  let c = { x: p, filter: i }, l = { strides: t10, pad: o, dilations: n }, m = T.runKernel(dn, c, l);
  return u ? W(m, [m.shape[1], m.shape[2], m.shape[3]]) : m;
}
var x2 = N({ dilation2d_: ZH });
var Sr = {};
qe(Sr, { assertAndGetBroadcastShape: () => rt, getBroadcastDims: () => y2, getReductionAxes: () => xd });
function y2(r15, e) {
  let t10 = r15.length, o = [];
  for (let n = 0; n < t10; n++) {
    let s = t10 - 1 - n, a = r15[s] || 1;
    (e[e.length - 1 - n] || 1) > 1 && a === 1 && o.unshift(s);
  }
  return o;
}
function xd(r15, e) {
  let t10 = [];
  for (let o = 0; o < e.length; o++) {
    let n = r15[r15.length - o - 1], s = e.length - o - 1, a = e[s];
    (n == null || n === 1 && a > 1) && t10.unshift(s);
  }
  return t10;
}
function rt(r15, e) {
  let t10 = Math.max(r15.length, e.length), o = new Array(t10);
  for (let n = 0; n < t10; n++) {
    let s = r15[r15.length - n - 1];
    s == null && (s = 1);
    let a = e[e.length - n - 1];
    if (a == null && (a = 1), s === 1) o[t10 - n - 1] = a;
    else if (a === 1) o[t10 - n - 1] = s;
    else if (s !== a) {
      let i = `Operands could not be broadcast together with shapes ${r15} and ${e}.`;
      throw Error(i);
    } else o[t10 - n - 1] = s;
  }
  return o;
}
function JH(r15, e) {
  let t10 = v(r15, "a", "equal", "string_or_numeric"), o = v(e, "b", "equal", "string_or_numeric");
  [t10, o] = Oe(t10, o), rt(t10.shape, o.shape);
  let n = { a: t10, b: o };
  return T.runKernel(xn, n);
}
var yd = N({ equal_: JH });
function eK(r15, e, t10) {
  let o = v(e, "a", "where"), n = v(t10, "b", "where"), s = v(r15, "condition", "where", "bool"), a = rt(rt(s.shape, o.shape), n.shape), i = su(s, a), p = su(o, a), u = su(n, a), c = { condition: i, t: p, e: u };
  return T.runKernel(fa, c);
}
var lo = N({ where_: eK });
function tK(r15) {
  let t10 = { x: v(r15, "x", "zerosLike") };
  return T.runKernel(Sa, t10);
}
var Gt = N({ zerosLike_: tK });
function rK(r15, e) {
  let t10 = v(r15, "a", "div"), o = v(e, "b", "div");
  [t10, o] = Oe(t10, o);
  let n = je(t10, o), s = Gt(n), a = yd(o, s);
  return lo(a, s, n);
}
var b2 = N({ divNoNan_: rK });
function oK(r15, e) {
  let t10 = v(r15, "t1", "dot"), o = v(e, "t2", "dot");
  E((t10.rank === 1 || t10.rank === 2) && (o.rank === 1 || o.rank === 2), () => `Error in dot: inputs must all be rank 1 or 2, but got ranks ${t10.rank} and ${o.rank}.`);
  let n = t10.rank === 1 ? t10.size : t10.shape[1], s = o.rank === 1 ? o.size : o.shape[0];
  if (E(n === s, () => `Error in dot: inner dimensions of inputs must match, but got ${n} and ${s}.`), t10.rank === 1 && o.rank === 1) {
    let a = W(t10, [1, -1]), i = W(o, [-1, 1]), p = Ze(a, i);
    return W(p, []);
  } else if (t10.rank === 1 && o.rank === 2) {
    let a = W(t10, [1, -1]), i = W(o, [o.shape[0], o.shape[1]]), p = Ze(a, i);
    return W(p, [p.size]);
  } else if (t10.rank === 2 && o.rank === 1) {
    let a = W(o, [-1, 1]), i = Ze(t10, a);
    return W(i, [i.size]);
  } else {
    let a = W(o, [o.shape[0], o.shape[1]]);
    return Ze(t10, a);
  }
}
var C2 = N({ dot_: oK });
function nK(r15, ...e) {
  let t10 = e.map((n, s) => v(n, `tensors${s}`, "einsum")), o = { equation: r15 };
  return T.runKernel(Bi, t10, o);
}
var iu = N({ einsum_: nK });
function sK(r15) {
  let t10 = { x: v(r15, "x", "elu", "float32") };
  return T.runKernel("Elu", t10);
}
var bd = N({ elu_: sK });
function aK(r15, e) {
  let t10 = v(r15, "x", "ensureShape", "string_or_numeric");
  if (!ZC(t10.shape, e)) throw new Error(`EnsureShape: Shape of tensor ${t10.shape} is not compatible with expected shape ${e}`);
  return r15;
}
var w2 = N({ ensureShape_: aK });
function iK(r15) {
  let e = v(r15, "x", "erf");
  E(e.dtype === "int32" || e.dtype === "float32", () => "Input dtype must be `int32` or `float32`."), e.dtype === "int32" && (e = Ue(e, "float32"));
  let t10 = { x: e };
  return T.runKernel("Erf", t10);
}
var S2 = N({ erf_: iK });
function zw(r15, e) {
  for (let t10 = 0; t10 < r15.length; ++t10) if (r15[r15.length - t10 - 1] !== e - 1 - t10) return false;
  return true;
}
function I2(r15, e, t10) {
  let o = r15.length + e.length, n = [], s = 0, a = 0;
  for (let i = 0; i < o; i++) t10.indexOf(i) === -1 ? n.push(r15[s++]) : n.push(e[a++]);
  return n;
}
function uK(r15, e) {
  let t10 = [], o = r15.length;
  for (let s = 0; s < o; s++) e.indexOf(s) === -1 && t10.push(r15[s]);
  let n = e.map((s) => r15[s]);
  return [t10, n];
}
function ii(r15, e) {
  let t10 = e.map((o) => 1);
  return I2(r15, t10, e);
}
function pK(r15, e, t10) {
  E(zw(e, t10), () => `${r15} supports only inner-most axes for now. Got axes ${e} and rank-${t10} input.`);
}
function cK(r15, e) {
  if (zw(r15, e)) return null;
  let t10 = [];
  for (let o = 0; o < e; ++o) r15.indexOf(o) === -1 && t10.push(o);
  return r15.forEach((o) => t10.push(o)), t10;
}
function lK(r15) {
  return r15.map((e, t10) => [t10, e]).sort((e, t10) => e[1] - t10[1]).map((e) => e[0]);
}
function mK(r15, e) {
  let t10 = [];
  for (let o = e - r15; o < e; ++o) t10.push(o);
  return t10;
}
function fK(r15, e = null, t10 = false) {
  let n = { x: v(r15, "x", "max") }, s = { reductionIndices: e, keepDims: t10 };
  return T.runKernel("Max", n, s);
}
var Ra = N({ max_: fK });
function hK(r15, e = null, t10 = false) {
  let n = { x: v(r15, "x", "min") }, s = { axis: e, keepDims: t10 };
  return T.runKernel("Min", n, s);
}
var Nl = N({ min_: hK });
function gK(r15, e) {
  let t10 = v(r15, "base", "pow"), o = v(e, "exp", "pow");
  [t10, o] = Oe(t10, o);
  let n = { a: t10, b: o };
  return T.runKernel("Pow", n);
}
var ui = N({ pow_: gK });
function ke(r15, e) {
  if ((Pt(r15) && e !== "string" || Array.isArray(r15)) && e !== "complex64") throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");
  if (e === "string" && Pt(r15) && !(r15 instanceof Uint8Array)) throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");
  return wr(r15, [], [], e);
}
function xK(r15) {
  let t10 = { x: v(r15, "x", "sqrt", "float32") };
  return T.runKernel(ws, t10);
}
var Rr = N({ sqrt_: xK });
function yK(r15) {
  let e = v(r15, "x", "square"), t10 = {};
  return T.runKernel("Square", { x: e }, t10);
}
var Zt = N({ square_: yK });
function bK(r15, e = null, t10 = false) {
  let o = v(r15, "x", "sum");
  o.dtype === "bool" && (o = Ue(o, "int32"));
  let n = { x: o }, s = { axis: e, keepDims: t10 };
  return T.runKernel("Sum", n, s);
}
var ot = N({ sum_: bK });
function CK(r15, e = "euclidean", t10 = null, o = false) {
  r15 = v(r15, "x", "norm");
  let n = v2(r15, e, t10), s = n.shape;
  if (o) {
    let a = _i(t10, r15.shape);
    s = ii(n.shape, a);
  }
  return W(n, s);
}
function v2(r15, e, t10 = null) {
  if (r15.rank === 0) return Qt(r15);
  if (r15.rank !== 1 && t10 === null) return v2(W(r15, [-1]), e, t10);
  if (r15.rank === 1 || typeof t10 == "number" || Array.isArray(t10) && t10.length === 1) {
    if (e === 1) return ot(Qt(r15), t10);
    if (e === 1 / 0) return Ra(Qt(r15), t10);
    if (e === -1 / 0) return Nl(Qt(r15), t10);
    if (e === "euclidean" || e === 2) return Rr(ot(ui(Qt(r15), ke(2, "int32")), t10));
    throw new Error(`Error in norm: invalid ord value: ${e}`);
  }
  if (Array.isArray(t10) && t10.length === 2) {
    if (e === 1) return Ra(ot(Qt(r15), t10[0]), t10[1] - 1);
    if (e === 1 / 0) return Ra(ot(Qt(r15), t10[1]), t10[0]);
    if (e === -1 / 0) return Nl(ot(Qt(r15), t10[1]), t10[0]);
    if (e === "fro" || e === "euclidean") return Rr(ot(Zt(r15), t10));
    throw new Error(`Error in norm: invalid ord value: ${e}`);
  }
  throw new Error(`Error in norm: invalid axis: ${t10}`);
}
var Vu = N({ norm_: CK });
function wK(r15, e = null, t10 = false) {
  return Vu(r15, "euclidean", e, t10);
}
var k2 = N({ euclideanNorm_: wK });
function SK(r15) {
  let t10 = { x: v(r15, "x", "exp") };
  return T.runKernel("Exp", t10);
}
var _o = N({ exp_: SK });
function IK(r15, e = 0) {
  let t10 = v(r15, "x", "expandDims", "string_or_numeric");
  E(e <= t10.rank, () => "Axis must be <= rank of the tensor");
  let o = { input: t10 }, n = { dim: e };
  return T.runKernel(na, o, n);
}
var Ms = N({ expandDims_: IK });
function vK(r15) {
  let t10 = { x: v(r15, "x", "expm1") };
  return T.runKernel(bn, t10);
}
var N2 = N({ expm1_: vK });
function kK(r15, e) {
  let t10 = v(r15, "x", "tile", "string_or_numeric");
  E(t10.rank === e.length, () => `Error in transpose: rank of input ${t10.rank} must match length of reps ${e}.`);
  let o = { x: t10 }, n = { reps: e };
  return T.runKernel(po, o, n);
}
var uu = N({ tile_: kK });
function NK(r15, e, t10, o = "float32") {
  e == null && (e = r15);
  let n = me([r15, e], o), s = r15 <= e ? r15 : e;
  for (let i = 0; i < s; ++i) n.set(1, i, i);
  let a = W(n.toTensor(), [r15, e]);
  if (t10 == null) return a;
  if (t10.length === 1) return uu(Ms(a, 0), [t10[0], 1, 1]);
  if (t10.length === 2) return uu(Ms(Ms(a, 0), 0), [t10[0], t10[1], 1, 1]);
  if (t10.length === 3) return uu(Ms(Ms(Ms(a, 0), 0), 0), [t10[0], t10[1], t10[2], 1, 1]);
  throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${t10.length}D.`);
}
var Cd = N({ eye_: NK });
function TK(r15) {
  let t10 = { x: v(r15, "x", "floor", "float32") };
  return T.runKernel(wn, t10);
}
var wd = N({ floor_: TK });
function _K(r15, e, t10 = 0, o = 0) {
  let n = v(r15, "x", "gather"), s = v(e, "indices", "gather", "int32"), a = { x: n, indices: s }, i = { axis: t10, batchDims: o };
  return T.runKernel(aa, a, i);
}
var Sd = N({ gather_: _K });
function EK(r15, e) {
  let t10 = v(r15, "a", "greater", "string_or_numeric"), o = v(e, "b", "greater", "string_or_numeric");
  [t10, o] = Oe(t10, o), rt(t10.shape, o.shape);
  let n = { a: t10, b: o };
  return T.runKernel(kn, n);
}
var Wu = N({ greater_: EK });
function $K(r15, e) {
  let t10 = v(r15, "a", "greaterEqual", "string_or_numeric"), o = v(e, "b", "greaterEqual", "string_or_numeric");
  [t10, o] = Oe(t10, o), rt(t10.shape, o.shape);
  let n = { a: t10, b: o };
  return T.runKernel(Nn, n);
}
var Id = N({ greaterEqual_: $K });
function RK(r15) {
  let t10 = { input: v(r15, "input", "imag") };
  return T.runKernel(Wi, t10);
}
var pu = N({ imag_: RK });
function DK(r15) {
  let t10 = { x: v(r15, "x", "isFinite") };
  return T.runKernel(Tn, t10);
}
var T2 = N({ isFinite_: DK });
function AK(r15) {
  let t10 = { x: v(r15, "x", "isInf") };
  return T.runKernel(_n, t10);
}
var _2 = N({ isInf_: AK });
function FK(r15) {
  let t10 = { x: v(r15, "x", "isNaN") };
  return T.runKernel(En, t10);
}
var E2 = N({ isNaN_: FK });
function PK(r15, e = 0.2) {
  let o = { x: v(r15, "x", "leakyRelu") }, n = { alpha: e };
  return T.runKernel($n, o, n);
}
var vd = N({ leakyRelu_: PK });
function OK(r15, e) {
  let t10 = v(r15, "a", "less", "string_or_numeric"), o = v(e, "b", "less", "string_or_numeric");
  [t10, o] = Oe(t10, o), rt(t10.shape, o.shape);
  let n = { a: t10, b: o };
  return T.runKernel(Rn, n);
}
var Tl = N({ less_: OK });
function MK(r15, e) {
  let t10 = v(r15, "a", "lessEqual", "string_or_numeric"), o = v(e, "b", "lessEqual", "string_or_numeric");
  [t10, o] = Oe(t10, o), rt(t10.shape, o.shape);
  let n = { a: t10, b: o };
  return T.runKernel(Dn, n);
}
var ac = N({ lessEqual_: MK });
function $2(r15, e, t10) {
  if (t10 <= 0) throw new Error("The number of values should be positive.");
  let o = { start: r15, stop: e, num: t10 };
  return T.runKernel(An, {}, o);
}
function LK(r15, e = 5, t10 = 1, o = 1, n = 0.5) {
  let s = v(r15, "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(Ka(e), () => `Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${e}.`);
  let a = s, i = false;
  s.rank === 3 && (i = true, a = W(s, [1, s.shape[0], s.shape[1], s.shape[2]]));
  let p = { x: a }, u = { depthRadius: e, bias: t10, alpha: o, beta: n }, c = T.runKernel("LRN", p, u);
  return i ? W(c, [c.shape[1], c.shape[2], c.shape[3]]) : c;
}
var R2 = N({ localResponseNormalization_: LK });
function BK(r15) {
  let t10 = { x: v(r15, "x", "log", "float32") };
  return T.runKernel("Log", t10);
}
var pi = N({ log_: BK });
function zK(r15) {
  let t10 = { x: v(r15, "x", "log1p") };
  return T.runKernel(Pn, t10);
}
var kd = N({ log1p_: zK });
function VK(r15) {
  return E(qs(r15), () => "The f passed in grad(f) must be a function"), (e, t10) => {
    let o = v(e, "x", "tf.grad", "string_or_numeric"), n = t10 != null ? v(t10, "dy", "tf.grad") : null;
    return T.tidy(() => {
      let { value: s, grads: a } = T.gradients(() => r15(o), [o], n);
      return n != null && xt(s.shape, n.shape, "The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"), Nd(a), a[0];
    });
  };
}
function WK(r15) {
  return E(qs(r15), () => "The f passed in grads(f) must be a function"), (e, t10) => {
    E(Array.isArray(e), () => "The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");
    let o = ni(e, "args", "tf.grads", "string_or_numeric"), n = t10 != null ? v(t10, "dy", "tf.grads") : null;
    return T.tidy(() => {
      let { value: s, grads: a } = T.gradients(() => r15(...o), o, n);
      return n != null && xt(s.shape, n.shape, "The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"), Nd(a), a;
    });
  };
}
function UK(r15) {
  return E(qs(r15), () => "The f passed in valueAndGrad(f) must be a function"), (e, t10) => {
    E(e instanceof mt, () => "The x passed in valueAndGrad(f)(x) must be a tensor"), E(t10 == null || t10 instanceof mt, () => "The dy passed in valueAndGrad(f)(x, dy) must be a tensor");
    let { grads: o, value: n } = T.gradients(() => r15(e), [e], t10);
    return Nd(o), { grad: o[0], value: n };
  };
}
function GK(r15) {
  return E(qs(r15), () => "The f passed in valueAndGrads(f) must be a function"), (e, t10) => {
    E(Array.isArray(e) && e.every((n) => n instanceof mt), () => "The args passed in valueAndGrads(f)(args) must be array of tensors"), E(t10 == null || t10 instanceof mt, () => "The dy passed in valueAndGrads(f)(args, dy) must be a tensor");
    let o = T.gradients(() => r15(...e), e, t10);
    return t10 != null && xt(o.value.shape, t10.shape, "The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"), Nd(o.grads), o;
  };
}
function Vw(r15, e) {
  E(qs(r15), () => "The f passed in variableGrads(f) must be a function"), E(e == null || Array.isArray(e) && e.every((u) => u instanceof ri), () => "The varList passed in variableGrads(f, varList) must be an array of variables");
  let t10 = e != null;
  if (!t10) {
    e = [];
    for (let u in T.registeredVariables) e.push(T.registeredVariables[u]);
  }
  let o = t10 ? e.filter((u) => !u.trainable) : null, n = 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 ${n} variables is trainable.`);
  let s = true, { value: a, grads: i } = T.gradients(r15, 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 p = {};
  return e.forEach((u, c) => {
    i[c] != null && (p[u.name] = i[c]);
  }), o != null && o.forEach((u) => p[u.name] = null), { value: a, grads: p };
}
function Ir(r15) {
  return T.customGrad(r15);
}
function Nd(r15) {
  if (r15.filter((t10) => t10 == 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 HK(r15) {
  let t10 = { x: v(r15, "x", "neg") };
  return T.runKernel("Neg", t10);
}
var pr = N({ neg_: HK });
function KK(r15) {
  let t10 = { x: v(r15, "x", "softplus") };
  return T.runKernel(Cs, t10);
}
var Td = N({ softplus_: KK });
function qK(r15) {
  let e = v(r15, "x", "logSigmoid");
  return Ir((o) => ({ value: pr(Td(pr(o))), gradFunc: (a) => se(a, Ea(pr(o))) }))(e);
}
var D2 = N({ logSigmoid_: qK });
function jK(r15, e) {
  let t10 = v(r15, "a", "sub"), o = v(e, "b", "sub");
  [t10, o] = Oe(t10, o);
  let n = { a: t10, b: o };
  return T.runKernel("Sub", n);
}
var Te = N({ sub_: jK });
function XK(r15, e = -1) {
  let t10 = v(r15, "logits", "logSoftmax");
  if (e === -1 && (e = t10.rank - 1), e !== t10.rank - 1) throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${t10.rank} and axis was ${e}`);
  return Ir((n, s) => {
    let i = Ra(n, e, true), p = Te(n, i), u = Te(Ue(p, "float32"), pi(ot(_o(p), e, true)));
    return s([u]), { value: u, gradFunc: (l, m) => {
      let [d] = m, f = true, h = _o(d);
      return Te(l, se(ot(l, e, f), h));
    } };
  })(t10);
}
var A2 = N({ logSoftmax_: XK });
function YK(r15, e = null, t10 = false) {
  let o = v(r15, "x", "logSumExp"), n = _i(e, o.shape), s = Ra(o, n, true), a = Te(o, s), i = _o(a), p = ot(i, n), u = pi(p), c = Ce(W(s, u.shape), u);
  if (t10) {
    let l = ii(c.shape, n);
    return W(c, l);
  }
  return c;
}
var _d = N({ logSumExp_: YK });
function QK(r15, e) {
  let t10 = v(r15, "a", "logicalAnd", "bool"), o = v(e, "b", "logicalAnd", "bool");
  rt(t10.shape, o.shape);
  let n = { a: t10, b: o };
  return T.runKernel(On, n);
}
var Uu = N({ logicalAnd_: QK });
function ZK(r15) {
  let t10 = { x: v(r15, "x", "logicalNot", "bool") };
  return T.runKernel(Mn, t10);
}
var Ed = N({ logicalNot_: ZK });
function JK(r15, e) {
  let t10 = v(r15, "a", "logicalOr", "bool"), o = v(e, "b", "logicalOr", "bool");
  rt(t10.shape, o.shape);
  let n = { a: t10, b: o };
  return T.runKernel(Ln, n);
}
var $d = N({ logicalOr_: JK });
function eq(r15, e) {
  let t10 = v(r15, "a", "logicalXor", "bool"), o = v(e, "b", "logicalXor", "bool");
  return rt(t10.shape, o.shape), Uu($d(r15, e), Ed(Uu(r15, e)));
}
var F2 = N({ logicalXor_: eq });
var Rd = 2147483648;
function tq(r15, e, t10 = "left") {
  let o = v(r15, "sortedSequence", "searchSorted"), n = v(e, "values", "searchSorted"), s = o.shape[o.shape.length - 1], a = n.shape[n.shape.length - 1], i = W(o, [-1, s]), p = W(n, [-1, a]);
  if (i.rank < 2) throw new Error("Sorted input argument must be at least 2-dimensional");
  if (i.shape[0] !== p.shape[0]) throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");
  if (ze(p.shape) >= Rd) throw new Error(`values tensor size must less than ${Rd}`);
  if (i.shape[1] >= Rd) throw new Error(`trailing dim_size must less than ${Rd} for int32 output type, was ${i.shape[1]}`);
  let u = { sortedSequence: i, values: p }, c = { side: t10 };
  return T.runKernel(fs, u, c);
}
var _l = N({ searchSorted_: tq });
function P2(r15, e) {
  return _l(r15, e, "left");
}
function rq(r15, e, t10, o, n) {
  let s = v(r15, "x", "maxPool"), a = 1, i = s, p = false;
  s.rank === 3 && (p = true, i = W(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(gr(t10, a), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${t10} and dilations '${a}'`), Lt("maxPool", o, n);
  let u = { x: i }, c = { filterSize: e, strides: t10, pad: o, dimRoundingMode: n }, l = T.runKernel(Wn, u, c);
  return p ? W(l, [l.shape[1], l.shape[2], l.shape[3]]) : l;
}
var Dd = N({ maxPool_: rq });
function oq(r15, e = [1, 1, 1], t10, o, n, s = "NDHWC") {
  let a = v(r15, "x", "maxPool3d"), i = a, p = false;
  a.rank === 4 && (p = true, i = W(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}`), Lt("maxPool3d", o, n);
  let u = { x: i }, c = { filterSize: e, strides: t10, pad: o, dimRoundingMode: n, dataFormat: s }, l = T.runKernel(ia, u, c);
  return p ? W(l, [l.shape[1], l.shape[2], l.shape[3], l.shape[4]]) : l;
}
var O2 = N({ maxPool3d_: oq });
function nq(r15, e, t10, o, n = false) {
  let a = { x: v(r15, "x", "maxPoolWithArgmax") }, i = { filterSize: e, strides: t10, pad: o, includeBatchInIndex: n }, p = T.runKernel(ua, a, i);
  return { result: p[0], indexes: p[1] };
}
var M2 = N({ maxPoolWithArgmax_: nq });
function sq(r15, e) {
  let t10 = v(r15, "a", "maximum"), o = v(e, "b", "maximum");
  [t10, o] = Oe(t10, o), t10.dtype === "bool" && (t10 = Ue(t10, "int32"), o = Ue(o, "int32")), rt(t10.shape, o.shape);
  let n = { a: t10, b: o };
  return T.runKernel(Vn, n);
}
var Ad = N({ maximum_: sq });
function aq(r15, e = null, t10 = false) {
  let n = { x: v(r15, "x", "mean") }, s = { axis: e, keepDims: t10 };
  return T.runKernel(Un, n, s);
}
var Gu = N({ mean_: aq });
function Gr(r15, e = "float32") {
  if (Ct(r15), e === "complex64") {
    let o = Gr(r15, "float32"), n = Gr(r15, "float32");
    return Er(o, n);
  }
  let t10 = Gp(ze(r15), e);
  return T.makeTensor(t10, r15, e);
}
function Da(r15, e = "float32") {
  if (Ct(r15), e === "complex64") {
    let o = Da(r15, "float32"), n = Gr(r15, "float32");
    return Er(o, n);
  }
  let t10 = ml(ze(r15), e);
  return T.makeTensor(t10, r15, e);
}
function L2(r15, e, { indexing: t10 = "xy" } = {}) {
  if (t10 !== "xy" && t10 !== "ij") throw new TypeError(`${t10} is not a valid third argument to meshgrid`);
  if (r15 === void 0) return [];
  let o = v(r15, "x", "meshgrid", r15 instanceof mt ? r15.dtype : "float32");
  if (e === void 0) return [o];
  let n = v(e, "y", "meshgrid", e instanceof mt ? e.dtype : "float32"), s = ze(o.shape), a = ze(n.shape);
  return t10 === "xy" ? (o = W(o, [1, -1]), n = W(n, [-1, 1]), [Ze(Da([a, 1], o.dtype), o), Ze(n, Da([1, s], n.dtype))]) : (o = W(o, [-1, 1]), n = W(n, [1, -1]), [Ze(o, Da([1, a], o.dtype)), Ze(Da([s, 1], n.dtype), n)]);
}
function iq(r15, e) {
  let t10 = v(r15, "a", "minimum"), o = v(e, "b", "minimum");
  [t10, o] = Oe(t10, o), t10.dtype === "bool" && (t10 = Ue(t10, "int32"), o = Ue(o, "int32")), rt(t10.shape, o.shape);
  let n = { a: t10, b: o };
  return T.runKernel(Hn, n);
}
var Hu = N({ minimum_: iq });
function uq(r15, e, t10) {
  E(t10 === "reflect" || t10 === "symmetric", () => `Invalid mode. Mode must be either reflect or symmetric. Got ${t10}.`);
  let o = v(r15, "x", "mirrorPad");
  if (o.rank === 0) throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");
  E(e.length === o.rank, () => `Padding doesn't match input. Must be ${o.rank}. Got ${e.length}.`);
  let n = t10 === "reflect" ? 1 : 0;
  for (let i = 0; i < o.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] <= o.shape[i] - n && e[i][1] >= 0 && e[i][1] <= o.shape[i] - n, () => `Padding in dimension ${i} cannot be greater than or equal to ${o.shape[i] - n} or less than 0 for input of shape ${o.shape}`);
  let s = { paddings: e, mode: t10 }, a = { x: o };
  return T.runKernel(Kn, a, s);
}
var B2 = N({ mirrorPad_: uq });
function pq(r15, e) {
  let t10 = v(r15, "a", "mod"), o = v(e, "b", "mod");
  [t10, o] = Oe(t10, o);
  let n = { a: t10, b: o };
  return T.runKernel("Mod", n);
}
var z2 = N({ mod_: pq });
function cq(r15, e = null, t10 = false) {
  r15 = v(r15, "x", "moments");
  let o = _i(e, r15.shape), n = Gu(r15, o, t10), s = n.shape;
  t10 || (s = ii(n.shape, o));
  let a = Zt(Te(Ue(r15, "float32"), W(n, s))), i = Gu(a, o, t10);
  return { mean: n, variance: i };
}
var V2 = N({ moments_: cq });
function lq(r15, e, t10, o) {
  let n = v(e, "data", "multiRNNCell"), s = ni(t10, "c", "multiRNNCell"), a = ni(o, "h", "multiRNNCell"), i = n, p = [];
  for (let l = 0; l < r15.length; l++) {
    let m = r15[l](i, s[l], a[l]);
    p.push(m[0]), p.push(m[1]), i = m[1];
  }
  let u = [], c = [];
  for (let l = 0; l < p.length; l += 2) u.push(p[l]), c.push(p[l + 1]);
  return [u, c];
}
var W2 = N({ multiRNNCell_: lq });
function mq(r15, e, t10, o = false) {
  let n = v(r15, "logits", "multinomial"), s = n.size, a = n.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}`);
  t10 = t10 || Math.random();
  let p = { logits: a === 1 ? W(n, [1, -1]) : n }, u = { numSamples: e, seed: t10, normalized: o }, c = T.runKernel(jn, p, u);
  return a === 1 ? W(c, [c.size]) : c;
}
var U2 = N({ multinomial_: mq });
function dq(r15, e) {
  let t10 = v(r15, "a", "notEqual", "string_or_numeric"), o = v(e, "b", "notEqual", "string_or_numeric");
  [t10, o] = Oe(t10, o), rt(t10.shape, o.shape);
  let n = { a: t10, b: o };
  return T.runKernel(Yn, n);
}
var Fd = N({ notEqual_: dq });
function fq(r15, e, t10 = 1, o = 0, n = "int32") {
  if (e < 2) throw new Error(`Error in oneHot: depth must be >=2, but it is ${e}`);
  let a = { indices: v(r15, "indices", "oneHot", "int32") }, i = { dtype: n, depth: e, onValue: t10, offValue: o };
  return T.runKernel(Jn, a, i);
}
var El = N({ oneHot_: fq });
function hq(r15) {
  let t10 = { x: v(r15, "x", "onesLike") };
  return T.runKernel(ca, t10);
}
var G2 = N({ onesLike_: hq });
function gq(r15, e) {
  let t10 = v(r15, "v1", "outerProduct"), o = v(e, "v2", "outerProduct");
  E(t10.rank === 1 && o.rank === 1, () => `Error in outerProduct: inputs must be rank 1, but got ranks ${t10.rank} and ${o.rank}.`);
  let n = W(t10, [-1, 1]), s = W(o, [1, -1]);
  return Ze(n, s);
}
var H2 = N({ outerProduct_: gq });
function xq(r15, e, t10 = 0) {
  let o = v(r15, "x", "pad");
  if (o.rank === 0) throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");
  let n = { paddings: e, constantValue: t10 }, s = { x: o };
  return T.runKernel(es, s, n);
}
var Aa = N({ pad_: xq });
function yq(r15, e, t10 = 0) {
  return E(e.length === 2, () => "Invalid number of paddings. Must be length of 2."), Aa(r15, [e], t10);
}
var K2 = N({ pad1d_: yq });
function bq(r15, e, t10 = 0) {
  return E(e.length === 2 && e[0].length === 2 && e[1].length === 2, () => "Invalid number of paddings. Must be length of 2 each."), Aa(r15, e, t10);
}
var q2 = N({ pad2d_: bq });
function Cq(r15, e, t10 = 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."), Aa(r15, e, t10);
}
var j2 = N({ pad3d_: Cq });
function wq(r15, e, t10 = 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."), Aa(r15, e, t10);
}
var X2 = N({ pad4d_: wq });
function Sq(r15, e, t10) {
  let o = v(r15, "x", "spaceToBatchND");
  E(o.rank >= 1 + e.length, () => `input rank ${o.rank} should be > than [blockShape] ${e.length}`), E(t10.length === e.length, () => `paddings.shape[0] ${t10.length} must be equal to [blockShape] ${e.length}`), E(o.shape.reduce((a, i, p) => p > 0 && p <= e.length ? a && (i + t10[p - 1][0] + t10[p - 1][1]) % e[p - 1] === 0 : a, true), () => `input spatial dimensions ${o.shape.slice(1)} with paddings ${t10.toString()} must be divisible by blockShapes ${e.toString()}`);
  let n = { x: o }, s = { blockShape: e, paddings: t10 };
  return T.runKernel(ga, n, s);
}
var Pd = N({ spaceToBatchND_: Sq });
function Iq(r15, e, t10, o, n, s, a) {
  n == null && (n = [1, 1]), s == null && (s = 1), o === 0 && (o = "valid");
  let i = v(r15, "x", "maxPool"), p = i, u = false;
  i.rank === 3 && (u = true, p = W(i, [1, i.shape[0], i.shape[1], i.shape[2]])), E(gr(s, n), () => `Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${n}'`);
  let c = Lw(p.shape, e, s, n, o), l = [c.dilationHeight, c.dilationWidth], m;
  o === "same" ? m = kq([c.filterHeight, c.filterWidth], l) : m = [[0, 0], [0, 0]];
  let d = l[0] === 1 && l[1] === 1, [f, h] = vq([c.inHeight, c.inWidth], l, m), g = d ? o : "valid", x = d ? p : Pd(p, l, f), C = (t10 === "avg" ? () => dd(x, e, s, g, a) : () => Dd(x, e, s, g, a))(), S = d ? C : fd(C, l, h);
  return u ? W(S, [S.shape[1], S.shape[2], S.shape[3]]) : S;
}
function vq(r15, e, t10) {
  let o = t10.map((c) => c[0]), n = t10.map((c) => c[1]), s = r15.concat(o, n), a = e.map((c, l) => (c - s[l] % c) % c), i = n.map((c, l) => c + a[l]), p = e.map((c, l) => [o[l], i[l]]), u = e.map((c, l) => [0, a[l]]);
  return [p, u];
}
function kq(r15, e) {
  let o = r15.map((a, i) => a + (a - 1) * (e[i] - 1)).map((a) => a - 1), n = o.map((a) => Math.floor(a / 2)), s = o.map((a, i) => a - n[i]);
  return o.map((a, i) => [n[i], s[i]]);
}
var Y2 = N({ pool_: Iq });
function Nq(r15, e) {
  let t10 = v(r15, "x", "prelu"), o = v(e, "alpha", "prelu"), n = { x: t10, alpha: o };
  return T.runKernel(rs, n);
}
var Od = N({ prelu_: Nq });
function Tq(r15, e = null, t10 = false) {
  let o = v(r15, "x", "prod");
  o.dtype === "bool" && (o = Ue(o, "int32"));
  let n = { x: o }, s = { axis: e, keepDims: t10 };
  return T.runKernel(os, n, s);
}
var Q2 = N({ prod_: Tq });
function _q(r15, e, t10, o) {
  let n = r15.map((c, l) => v(c, `tensors${l}`, "raggedGather", "int32")), s = v(e, "paramsDenseValues", "raggedGather"), a = v(t10, "indices", "raggedGather", "int32"), i = { paramsNestedSplits: n, paramsDenseValues: s, indices: a }, p = { outputRaggedRank: o }, u = T.runKernel(Hp, i, p);
  return { outputNestedSplits: u.slice(0, u.length - 1), outputDenseValues: u[u.length - 1] };
}
var Z2 = N({ raggedGather_: _q });
function Eq(r15, e, t10) {
  let o = v(r15, "starts", "raggedRange"), n = v(e, "limits", "raggedRange", o.dtype), s = v(t10, "deltas", "raggedRange", o.dtype), a = { starts: o, limits: n, deltas: s }, i = T.runKernel(Kp, a);
  return { rtNestedSplits: i[0], rtDenseValues: i[1] };
}
var J2 = N({ raggedRange_: Eq });
function $q(r15, e, t10, o, n) {
  let s = v(r15, "shape", "raggedTensorToTensor", "int32"), a = v(e, "values", "raggedTensorToTensor"), i = v(t10, "defaultValue", "raggedTensorToTensor", a.dtype), p = o.map((l, m) => v(l, `tensors${m}`, "raggedTensorToTensor", "int32")), u = { shape: s, values: a, defaultValue: i, rowPartitionTensors: p }, c = { rowPartitionTypes: n };
  return T.runKernel(qp, u, c);
}
var e1 = N({ raggedTensorToTensor_: $q });
function Rq(r15, e, t10) {
  Ct(r15);
  let o = ze(r15), n = null;
  if (t10 == null || t10 === "float32") n = new Float32Array(o);
  else if (t10 === "int32") n = new Int32Array(o);
  else if (t10 === "bool") n = new Uint8Array(o);
  else throw new Error(`Unknown data type ${t10}`);
  for (let s = 0; s < o; s++) n[s] = e();
  return T.makeTensor(n, r15, t10);
}
var t1 = N({ rand_: Rq });
var Vd = zp(jw());
var w1 = {};
qe(w1, { TEST_EPSILON_FLOAT16: () => y1, createVideoElement: () => Gq, encodeStrings: () => C1, expectArrayBuffersEqual: () => Uq, expectArraysClose: () => Bq, expectArraysEqual: () => Vq, expectNumbersClose: () => b1, expectPromiseToFail: () => zq, expectValuesInRange: () => Wq, play: () => Hq, testEpsilon: () => Ld });
var Lq = 1e-3;
var y1 = 0.1;
function Bq(r15, e, t10) {
  return t10 == null && (t10 = Ld()), Xw(r15, e, (o, n) => Yw(o, n, t10));
}
function Ld() {
  return T.backend.floatPrecision() === 32 ? Lq : y1;
}
function Xw(r15, e, t10) {
  let o = true;
  if ((Pt(r15) || Pt(e)) && (o = false), Pt(r15) && Pt(e) && (o = true), o) {
    let a = r15.constructor.name, i = e.constructor.name;
    if (a !== i) throw new Error(`Arrays are of different type. Actual: ${a}. Expected: ${i}`);
  }
  if (Array.isArray(r15) && Array.isArray(e)) {
    let a = sr(r15), i = sr(e);
    if (!br(a, i)) throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${i}]`);
  }
  let n = Pt(r15) ? r15 : Fs(r15), s = Pt(e) ? e : Fs(e);
  if (n.length !== s.length) throw new Error(`Arrays have different lengths actual: ${n.length} vs expected: ${s.length}.
Actual:   ${n}.
Expected: ${s}.`);
  for (let a = 0; a < s.length; ++a) {
    let i = n[a], p = s[a];
    if (!t10(i, p)) throw new Error(`Arrays differ: actual[${a}] = ${i}, expected[${a}] = ${p}.
Actual:   ${n}.
Expected: ${s}.`);
  }
  typeof expect != "undefined" && expect().nothing();
}
function zq(r15, e) {
  r15().then(() => e.fail(), () => e()), typeof expect != "undefined" && expect().nothing();
}
function Vq(r15, e) {
  let t10 = typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? [e] : e;
  return zo(r15) || zo(r15[0]) || zo(e) || zo(e[0]) ? Xw(r15, t10, (o, n) => o == n) : Xw(r15, e, (o, n) => Yw(o, n, 0));
}
function b1(r15, e, t10) {
  if (t10 == null && (t10 = Ld()), !Yw(r15, e, t10)) throw new Error(`Numbers differ: actual === ${r15}, expected === ${e}`);
  typeof expect != "undefined" && expect().nothing();
}
function Yw(r15, e, t10) {
  return !isFinite(r15) && !isFinite(e) ? true : !(isNaN(r15) || isNaN(e) || Math.abs(r15 - e) > t10);
}
function Wq(r15, e, t10) {
  for (let o = 0; o < r15.length; o++) if (r15[o] < e || r15[o] > t10) throw new Error(`Value out of range:${r15[o]} low: ${e}, high: ${t10}`);
}
function Uq(r15, e) {
  let t10 = new Float32Array(r15), o = new Float32Array(e);
  if (t10.length !== o.length) throw new Error(`Expected ArrayBuffer to be of length ${o.length}, but it was ${t10.length}`);
  for (let n = 0; n < o.length; n++) if (t10[n] !== o[n]) throw new Error(`Expected ArrayBuffer value at ${n} to be ${o[n]} but got ${t10[n]} instead`);
}
function C1(r15) {
  for (let e = 0; e < r15.length; e++) {
    let t10 = r15[e];
    Array.isArray(t10) ? C1(t10) : r15[e] = Ji(t10);
  }
  return r15;
}
function Gq(r15) {
  let e = document.createElement("video");
  return "playsInline" in e && (e.playsInline = true), e.muted = true, e.loop = true, e.style.position = "fixed", e.style.left = "0px", e.style.top = "0px", e.preload = "auto", e.appendChild(r15), new Promise((t10) => {
    e.addEventListener("loadeddata", (o) => t10(e)), e.load();
  });
}
async function Hq(r15) {
  await r15.play(), "requestVideoFrameCallback" in r15 && await new Promise((e) => {
    r15.requestVideoFrameCallback(e);
  });
}
var qu = class {
  constructor(e, t10, o, n, s) {
    this.mean = e, this.stdDev = t10, this.dtype = o, this.nextVal = NaN, this.truncated = n, this.truncated && (this.upper = this.mean + this.stdDev * 2, this.lower = this.mean - this.stdDev * 2);
    let a = s || Math.random();
    this.random = Vd.alea(a.toString());
  }
  nextValue() {
    if (!isNaN(this.nextVal)) {
      let n = this.nextVal;
      return this.nextVal = NaN, n;
    }
    let e, t10, o = false;
    for (; !o; ) {
      let n, s, a;
      do
        n = 2 * this.random() - 1, s = 2 * this.random() - 1, a = n * n + s * s;
      while (a >= 1 || a === 0);
      let i = Math.sqrt(-2 * Math.log(a) / a);
      e = this.mean + this.stdDev * n * i, t10 = this.mean + this.stdDev * s * i, (!this.truncated || this.isValidTruncated(e)) && (o = true);
    }
    return (!this.truncated || this.isValidTruncated(t10)) && (this.nextVal = this.convertValue(t10)), 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 Bd = class {
  constructor(e, t10, o, n) {
    this.alpha = e, this.beta = 1 / t10, this.dtype = o;
    let s = n || Math.random();
    this.randu = Vd.alea(s.toString()), this.randn = new qu(0, 1, o, 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, t10, o, n, s, a;
    for (; ; ) {
      do
        n = this.randn.nextValue(), a = 1 + this.c * n;
      while (a <= 0);
      if (a *= a * a, e = n * n, t10 = 1 - 0.331 * e * e, o = 0.5 * e + this.d * (1 - a + Math.log(a)), s = this.randu(), s < t10 || Math.log(s) < o) 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 zd = class {
  constructor(e = 0, t10 = 1, o, n) {
    if (this.canReturnFloat = () => this.dtype == null || this.dtype === "float32", this.min = e, this.range = t10 - e, this.dtype = o, n == null && (n = Math.random()), typeof n == "number" && (n = n.toString()), !this.canReturnFloat() && this.range <= 1) throw new Error(`The difference between ${e} - ${t10} <= 1 and dtype is not float`);
    this.random = Vd.alea(n);
  }
  convertValue(e) {
    return this.canReturnFloat() ? e : Math.round(e);
  }
  nextValue() {
    return this.convertValue(this.min + this.range * this.random());
  }
};
function Kq(r15, e, t10 = 1, o = "float32", n) {
  if (Ct(r15), t10 == null && (t10 = 1), o == null && (o = "float32"), o !== "float32" && o !== "int32") throw new Error(`Unsupported data type ${o}`);
  let s = new Bd(e, t10, o, n), a = me(r15, o);
  for (let i = 0; i < a.values.length; i++) a.values[i] = s.nextValue();
  return a.toTensor();
}
var S1 = N({ randomGamma_: Kq });
function qq(r15, e = 0, t10 = 1, o, n) {
  if (Ct(r15), o != null && o === "bool") throw new Error(`Unsupported data type ${o}`);
  let s = new qu(e, t10, o, false, n), a = me(r15, o);
  for (let i = 0; i < a.values.length; i++) a.values[i] = s.nextValue();
  return a.toTensor();
}
var Wd = N({ randomNormal_: qq });
function jq(r15, e, t10) {
  if (e != null && e === "bool") throw new Error(`Unsupported data type ${e}`);
  return Wd(r15, 0, 1, e, t10);
}
var I1 = N({ randomStandardNormal_: jq });
function Xq(r15, e = 0, t10 = 1, o = "float32", n) {
  Ct(r15);
  let s = me(r15, o), a = new zd(e, t10, null, n);
  for (let i = 0; i < s.values.length; i++) s.values[i] = a.nextValue();
  return s.toTensor();
}
var ic = N({ randomUniform_: Xq });
function Yq(r15, e, t10, o) {
  return ic(r15, e, t10, "int32", o);
}
var v1 = N({ randomUniformInt_: Yq });
function cu(r15, e, t10 = 1, o = "float32") {
  if (t10 === 0) throw new Error("Cannot have a step of zero");
  let n = { start: r15, stop: e, step: t10, dtype: o };
  return T.runKernel(ma, {}, n);
}
function Qq(r15) {
  let t10 = { input: v(r15, "input", "real") };
  return T.runKernel(Hi, t10);
}
var ci = N({ real_: Qq });
function Zq(r15) {
  let t10 = { x: v(r15, "x", "reciprocal") };
  return T.runKernel(ns, t10);
}
var k1 = N({ reciprocal_: Zq });
function Jq(r15) {
  let t10 = { x: v(r15, "x", "relu") };
  return T.runKernel(ss, t10);
}
var lu = N({ relu_: Jq });
function e6(r15) {
  let t10 = { x: v(r15, "x", "relu6") };
  return T.runKernel(us, t10);
}
var Ud = N({ relu6_: e6 });
function t6(r15, e) {
  let o = { x: v(r15, "x", "reverse") }, n = { dims: e };
  return T.runKernel(ps, o, n);
}
var mo = N({ reverse_: t6 });
function r6(r15) {
  let e = v(r15, "x", "reverse");
  return E(e.rank === 1, () => `Error in reverse1D: x must be rank 1 but got rank ${e.rank}.`), mo(e, 0);
}
var N1 = N({ reverse1d_: r6 });
function o6(r15, e) {
  let t10 = v(r15, "x", "reverse");
  return E(t10.rank === 2, () => `Error in reverse2D: x must be rank 2 but got rank ${t10.rank}.`), mo(t10, e);
}
var T1 = N({ reverse2d_: o6 });
function n6(r15, e) {
  let t10 = v(r15, "x", "reverse");
  return E(t10.rank === 3, () => `Error in reverse3D: x must be rank 3 but got rank ${t10.rank}.`), mo(t10, e);
}
var _1 = N({ reverse3d_: n6 });
function s6(r15, e) {
  let t10 = v(r15, "x", "reverse");
  return E(t10.rank === 4, () => `Error in reverse4D: x must be rank 4 but got rank ${t10.rank}.`), mo(t10, e);
}
var E1 = N({ reverse4d_: s6 });
function a6(r15) {
  let t10 = { x: v(r15, "x", "round") };
  return T.runKernel(cs, t10);
}
var Gd = N({ round_: a6 });
function i6(r15) {
  let t10 = { x: v(r15, "x", "rsqrt", "float32") };
  return T.runKernel(ls, t10);
}
var $1 = N({ rsqrt_: i6 });
function u6(r15) {
  let t10 = { x: v(r15, "x", "selu") };
  return T.runKernel(hs, t10);
}
var R1 = N({ selu_: u6 });
function p6(r15, e, t10, o, n, s = [1, 1], a = "NHWC") {
  let i = v(r15, "x", "separableConv2d"), p = v(e, "depthwiseFilter", "separableConv2d"), u = v(t10, "pointwiseFilter", "separableConv2d"), c = i, l = false;
  if (i.rank === 3 && (l = true, c = W(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(p.rank === 4, () => `Error in separableConv2d: depthwise filter must be rank 4, but got rank ${p.rank}.`), E(u.rank === 4, () => `Error in separableConv2d: pointwise filter must be rank 4, but got rank ${p.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 = p.shape[2], d = p.shape[3];
  E(u.shape[2] === m * d, () => `Error in separableConv2d: the third dimension of pointwise filter must be ${m * d}, but got ${u.shape[2]}.`);
  let f = sc(c, p, o, n, a, s), g = au(f, u, 1, "valid", a);
  return l ? W(g, [g.shape[1], g.shape[2], g.shape[3]]) : g;
}
var D1 = N({ separableConv2d_: p6 });
async function c6(r15, e) {
  let t10 = v(r15, "x", "setdiff1d"), o = v(e, "y", "setdiff1d");
  E(t10.dtype === o.dtype, () => `x and y should have the same dtype, but got x (${t10.dtype}) and y (${o.dtype}).`), E(t10.rank === 1, () => `x should be 1D tensor, but got x (${t10.shape}).`), E(o.rank === 1, () => `y should be 1D tensor, but got y (${o.shape}).`);
  let n = await t10.data(), s = await o.data(), a = new Set(s), i = 0;
  for (let c = 0; c < n.length; c++) a.has(n[c]) || i++;
  let p = new tt([i], t10.dtype), u = new tt([i], "int32");
  for (let c = 0, l = 0; c < n.length; c++) a.has(n[c]) || (p.values[l] = n[c], u.values[l] = c, l++);
  return [p.toTensor(), u.toTensor()];
}
var A1 = c6;
function l6(r15) {
  let t10 = { x: v(r15, "x", "sign") };
  return T.runKernel(ys, t10);
}
var F1 = N({ sign_: l6 });
function m6(r15) {
  let t10 = { x: v(r15, "x", "sin", "float32") };
  return T.runKernel("Sin", t10);
}
var P1 = N({ sin_: m6 });
function d6(r15) {
  let t10 = { x: v(r15, "x", "sinh") };
  return T.runKernel(xs, t10);
}
var O1 = N({ sinh_: d6 });
function f6(r15, e, t10) {
  let o = v(r15, "x", "slice1d");
  return E(o.rank === 1, () => `slice1d expects a rank-1 tensor, but got a rank-${o.rank} tensor`), Xe(o, [e], [t10]);
}
var M1 = N({ slice1d_: f6 });
function h6(r15, e, t10) {
  let o = v(r15, "x", "slice2d");
  return E(o.rank === 2, () => `slice2d expects a rank-2 tensor, but got a rank-${o.rank} tensor`), Xe(o, e, t10);
}
var L1 = N({ slice2d_: h6 });
function g6(r15, e, t10) {
  let o = v(r15, "x", "slice3d");
  return E(o.rank === 3, () => `slice3d expects a rank-3 tensor, but got a rank-${o.rank} tensor`), Xe(o, e, t10);
}
var B1 = N({ slice3d_: g6 });
function x6(r15, e, t10) {
  let o = v(r15, "x", "slice4d");
  return E(o.rank === 4, () => `slice4d expects a rank-4 tensor, but got a rank-${o.rank} tensor`), Xe(o, e, t10);
}
var z1 = N({ slice4d_: x6 });
function y6(r15, e = -1) {
  let t10 = v(r15, "logits", "softmax", "float32");
  if (e === -1 && (e = t10.rank - 1), e !== t10.rank - 1) throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${t10.rank} and dim was ${e}`);
  let o = { logits: t10 }, n = { dim: e };
  return T.runKernel(Is, o, n);
}
var V1 = N({ softmax_: y6 });
function b6(r15) {
  E(r15.dtype === "complex64", () => `The dtype for tf.spectral.fft() must be complex64 but got ${r15.dtype}.`);
  let e = { input: r15 };
  return T.runKernel("FFT", e);
}
var uc = N({ fft_: b6 });
function C6(r15) {
  E(r15.dtype === "complex64", () => `The dtype for tf.spectral.ifft() must be complex64 but got ${r15.dtype}.`);
  let e = { input: r15 };
  return T.runKernel(Vi, e);
}
var ju = N({ ifft_: C6 });
function w6(r15) {
  let e = r15.shape[r15.shape.length - 1], t10 = r15.size / e, o;
  if (e <= 2) {
    let n = W(r15, [t10, e]);
    o = ju(n);
  } else {
    let n = [t10, 2 * (e - 1)], s = W(ci(r15), [t10, e]), a = W(pu(r15), [t10, e]), i = mo(Xe(s, [0, 1], [t10, e - 2]), 1), p = se(mo(Xe(a, [0, 1], [t10, e - 2]), 1), ke(-1)), u = yt([s, i], 1), c = yt([a, p], 1), l = W(Er(u, c), [n[0], n[1]]);
    o = ju(l);
  }
  if (o = ci(o), r15.rank === 3 && r15.shape[0] !== 0) {
    let n = o, s = r15.shape[0];
    o = W(o, [s, o.shape[0] / s, o.shape[1]]), n.dispose();
  }
  return o;
}
var Hd = N({ irfft_: w6 });
function S6(r15, e, t10 = 0) {
  let n = { x: v(r15, "x", "split") }, s = { numOrSizeSplits: e, axis: t10 };
  return T.runKernel(xa, n, s);
}
var li = N({ split_: S6 });
function I6(r15, e) {
  E(r15.dtype === "float32", () => `The dtype for rfft() must be real value but got ${r15.dtype}`);
  let t10 = r15.shape[r15.shape.length - 1], o = r15.size / t10, n;
  if (e != null && e < t10) {
    let f = r15.shape.map((g) => 0), h = r15.shape.map((g) => g);
    h[r15.shape.length - 1] = e, n = Xe(r15, f, h), t10 = e;
  } else if (e != null && e > t10) {
    let f = r15.shape.map((h) => h);
    f[r15.shape.length - 1] = e - t10, n = yt([r15, Gr(f)], r15.shape.length - 1), t10 = e;
  } else n = r15;
  let s = Gt(n), a = W(Er(n, s), [o, t10]), i = uc(a), p = Math.floor(t10 / 2) + 1, u = ci(i), c = pu(i), l = li(u, [p, t10 - p], u.shape.length - 1), m = li(c, [p, t10 - p], c.shape.length - 1), d = n.shape.slice();
  return d[n.shape.length - 1] = p, W(Er(l[0], m[0]), d);
}
var pc = N({ rfft_: I6 });
function v6(r15, e) {
  let t10 = v(r15, "a", "squaredDifference"), o = v(e, "b", "squaredDifference");
  [t10, o] = Oe(t10, o), rt(t10.shape, o.shape);
  let n = { a: t10, b: o }, s = {};
  return T.runKernel(ks, n, s);
}
var Kd = N({ squaredDifference_: v6 });
function k6(r15, e) {
  let t10 = v(r15, "x", "squeeze", "string_or_numeric");
  return W(t10, JC(t10.shape, e).newShape);
}
var cc = N({ squeeze_: k6 });
function N6(r15, e = 0) {
  let t10 = ni(r15, "tensors", "stack", "string_or_numeric");
  E(t10.length >= 1, () => "Pass at least one tensor to tf.stack"), t10.length > 0 && E(e <= t10[0].rank, () => "Axis must be <= rank of the tensor");
  let o = t10, n = { axis: e };
  return T.runKernel(la, o, n);
}
var vr = N({ stack_: N6 });
function T6(r15, e = 0) {
  let o = { x: v(r15, "x", "step") }, n = { alpha: e };
  return T.runKernel(wo, o, n);
}
var qd = N({ step_: T6 });
function _6(r15, e, t10, o, n = 0, s = 0, a = 0, i = 0, p = 0) {
  let c = { x: v(r15, "x", "stridedSlice", "string_or_numeric") }, l = { begin: e, end: t10, strides: o, beginMask: n, endMask: s, ellipsisMask: a, newAxisMask: i, shrinkAxisMask: p };
  return T.runKernel(Ns, c, l);
}
var W1 = N({ stridedSlice_: _6 });
function E6(r15) {
  let t10 = { x: v(r15, "x", "tan", "float32") };
  return T.runKernel("Tan", t10);
}
var U1 = N({ tan_: E6 });
function Jt(r15, e) {
  io(r15);
  let t10 = sr(r15, e);
  if (t10.length !== 1) throw new Error("tensor1d() requires values to be a flat/TypedArray");
  return wr(r15, null, t10, e);
}
function mu(r15, e, t10) {
  if (io(r15), e != null && e.length !== 2) throw new Error("tensor2d() requires shape to have two numbers");
  let o = sr(r15, t10);
  if (o.length !== 2 && o.length !== 1) throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");
  if (o.length === 1 && e == null) throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");
  return wr(r15, e, o, t10);
}
function jd(r15, e, t10) {
  if (io(r15), e != null && e.length !== 3) throw new Error("tensor3d() requires shape to have three numbers");
  let o = sr(r15, t10);
  if (o.length !== 3 && o.length !== 1) throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");
  if (o.length === 1 && e == null) throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");
  return wr(r15, e, o, t10);
}
function G1(r15, e, t10) {
  if (io(r15), e != null && e.length !== 4) throw new Error("tensor4d() requires shape to have four numbers");
  let o = sr(r15, t10);
  if (o.length !== 4 && o.length !== 1) throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");
  if (o.length === 1 && e == null) throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");
  return wr(r15, e, o, t10);
}
function H1(r15, e, t10) {
  if (io(r15), e != null && e.length !== 5) throw new Error("tensor5d() requires shape to have five numbers");
  let o = sr(r15, t10);
  if (o.length !== 5 && o.length !== 1) throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");
  if (o.length === 1 && e == null) throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");
  return wr(r15, e, o, t10);
}
function K1(r15, e, t10) {
  if (io(r15), e != null && e.length !== 6) throw new Error("tensor6d() requires shape to have six numbers");
  let o = sr(r15, t10);
  if (o.length !== 6 && o.length !== 1) throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");
  if (o.length === 1 && e == null) throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");
  return e = e || o, wr(r15, e, o, t10);
}
var du = {};
qe(du, { calculateShapes: () => q1, validateInput: () => lc, validateUpdateShape: () => Qw });
function Qw(r15, e, t10) {
  let o = e.rank > 1 ? e.shape[e.rank - 1] : 1, n = e.rank > 1 ? e.rank - 1 : 1, s = `Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${t10.shape}, indices.shape: ${e.shape}, shape: ${r15}, sliceDim: ${o}, and batchDim: ${n}.`;
  if (t10.rank < n) throw new Error(s + ` update.rank < ${n}. `);
  if (r15.length < o + (t10.rank - n)) throw new Error(s + ` Output shape length < ${o + (t10.rank - n)}`);
  if (t10.rank !== n + r15.length - o) throw new Error(s + ` update.rank != ${n + r15.length - o}`);
  for (let a = 0; a < n; ++a) if (t10.shape[a] !== e.shape[a]) throw new Error(s + ` updates.shape[${a}] (${t10.shape[a]}) != indices.shape[${a}] (${e.shape[a]}).`);
  for (let a = 0; a < t10.rank - n; ++a) if (t10.shape[a + n] !== r15[a + o]) throw new Error(s + ` updates.shape[${a + n}] (${t10.shape[a + n]}) != shape[${a + n}] (${r15[a + n]})`);
}
function lc(r15, e, t10) {
  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 (r15.rank < 1) throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${r15.rank}.`);
  if (e.dtype !== "int32") throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${e.dtype}`);
  if (t10.length < 1) throw new Error(`Output rank must be greater or equal to 1, but got shape: ${t10}`);
  if (t10.length === 0) {
    if (e.size === 0) throw new Error(`Indices specified for empty output. indices shape: ${e.shape}`);
    if (r15.size === 0) throw new Error(`Updates specified for empty output. updates shape: ${r15.shape}`);
  }
  Qw(t10, e, r15);
}
function q1(r15, e, t10) {
  let o = e.shape.length, n = o > 1 ? e.shape[o - 1] : 1, s = t10.length, a = 1;
  for (let l = n; l < s; ++l) a *= t10[l];
  let i = n < 1 ? 1 : n, p = ze(e.shape) / i, u = [...js(t10.slice(0, n)), 1], c = ze(t10);
  return { sliceRank: n, numUpdates: p, sliceSize: a, strides: u, outputSize: c };
}
function $6(r15, e, t10) {
  let o = v(r15, "tensor", "tensorScatterupdate"), n = v(e, "indices", "tensorScatterupdate", "int32"), s = v(t10, "updates", "tensorScatterupdate");
  if (lc(s, n, o.shape), o.dtype !== s.dtype) throw new Error(`tensor and updates must have the same dtype, instead they are ${o.dtype} and ${s.dtype}.`);
  let a = { tensor: o, indices: n, updates: s }, i = {};
  return T.runKernel(ds, a, i);
}
var j1 = N({ tensorScatterUpdate_: $6 });
function R6(r15, e = 1, t10 = true) {
  let o = v(r15, "x", "topk");
  if (o.rank === 0) throw new Error("topk() expects the input to be of rank 1 or higher");
  let n = o.shape[o.shape.length - 1];
  if (e < 0) throw new Error(`'k' passed to topk() must be >= 0 but got ${e}`);
  if (e > n) throw new Error(`'k' passed to topk() must be <= the last dimension (${n}) but got ${e}`);
  let s = { x: o }, a = { k: e, sorted: t10 }, [i, p] = T.runKernel($s, s, a);
  return { values: i, indices: p };
}
var X1 = N({ topk_: R6 });
function D6(r15, e = 0, t10 = 1, o, n) {
  if (Ct(r15), o != null && o === "bool") throw new Error("Unsupported data type $ { dtype }");
  let s = new qu(e, t10, o, true, n), a = me(r15, o);
  for (let i = 0; i < a.values.length; i++) a.values[i] = s.nextValue();
  return a.toTensor();
}
var Y1 = N({ truncatedNormal_: D6 });
function A6(r15, e = 0) {
  let t10 = v(r15, "x", "unique", "string_or_numeric");
  E(t10.rank > 0, () => "The input tensor must be at least 1D");
  let o = { x: t10 }, n = { axis: e }, [s, a] = T.runKernel(Yi, o, n);
  return { values: s, indices: a };
}
var Q1 = N({ unique_: A6 });
function F6(r15, e, t10) {
  let o = v(r15, "x", "unsortedSegmentSum"), n = v(e, "segmentIds", "unsortedSegmentSum", "int32");
  E(Ka(t10), () => "numSegments must be of dtype int");
  let s = { x: o, segmentIds: n }, a = { numSegments: t10 };
  return T.runKernel(Qi, s, a);
}
var Z1 = N({ unsortedSegmentSum_: F6 });
function P6(r15, e = 0) {
  let t10 = v(r15, "x", "unstack", "string_or_numeric");
  E(e >= -t10.shape.length && e < t10.shape.length, () => `Axis = ${e} is not in [-${t10.shape.length}, ${t10.shape.length})`);
  let o = { value: t10 }, n = { axis: e };
  return T.runKernel(wa, o, n);
}
var fo = N({ unstack_: P6 });
function J1(r15, e) {
  return _l(r15, e, "right");
}
function eN(r15, e = true, t10, o) {
  return T.makeVariable(r15, e, t10, o);
}
function Xd(r15, e) {
  let t10 = [];
  for (let s = 0; s < e.length; s++) e[s] && t10.push(s);
  let o = me(r15, "int32"), n = me([t10.length, r15.length], "int32");
  for (let s = 0; s < t10.length; s++) {
    let a = o.indexToLoc(t10[s]), i = s * r15.length;
    n.values.set(a, i);
  }
  return n.toTensor();
}
async function O6(r15) {
  let e = v(r15, "condition", "whereAsync", "bool"), t10 = await e.data(), o = Xd(e.shape, t10);
  return r15 !== e && e.dispose(), o;
}
var Yd = O6;
async function M6(r15, e, t10) {
  let o = v(r15, "tensor", "boolMask"), n = v(e, "mask", "boolMask", "bool"), s = t10 == null ? 0 : t10, a = n.rank, i = o.shape;
  E(a > 0, () => "mask cannot be scalar"), xt(i.slice(s, s + a), n.shape, "mask's shape must match the first K dimensions of tensor's shape,");
  let p = 1;
  for (let h = s; h < s + a; h++) p *= i[h];
  let u = i.slice(0, s).concat([p], i.slice(s + a)), c = W(o, u), l = W(n, [-1]), m = await Yd(l), d = cc(m, [1]), f = Sd(c, d, s);
  return r15 !== o && o.dispose(), e !== n && n.dispose(), d.dispose(), c.dispose(), l.dispose(), m.dispose(), f;
}
var L6 = M6;
function B6(r15, e, t10) {
  let o = v(r15, "x", "transpose");
  if (e == null && (e = o.shape.map((a, i) => i).reverse()), E(o.rank === e.length, () => `Error in transpose: rank of input ${o.rank} must match length of perm ${e}.`), e.forEach((a) => {
    E(a >= 0 && a < o.rank, () => `All entries in 'perm' must be between 0 and ${o.rank - 1} but got ${e}`);
  }), o.rank <= 1) return o.clone();
  let n = { x: o }, s = { perm: e };
  return o.dtype === "complex64" ? De(() => {
    let a = ci(o), i = pu(o);
    return a = T.runKernel(co, { x: a }, s), i = T.runKernel(co, { x: i }, s), t10 && (i = pr(i)), Er(a, i);
  }) : T.runKernel(co, n, s);
}
var mc = N({ transpose_: B6 });
function z6(r15, e, t10, o, n = true) {
  let s = v(r15, "v", "movingAverage"), a = v(e, "x", "movingAverage"), i = v(t10, "decay", "movingAverage");
  ww(s, a), E(br(s.shape, a.shape), () => "Shape mismatch in v and x");
  let p = ke(1), u = Te(p, i), c = se(Te(a, s), u);
  if (n) {
    E(o != null, () => "When using zeroDebias: true, step is required.");
    let l = v(o, "step", "movingAverage");
    c = je(c, Te(p, ui(i, l)));
  }
  return Ce(s, c);
}
var V6 = N({ movingAverage_: z6 });
function W6(r15, e, t10) {
  Ct(t10);
  let o = v(r15, "indices", "scatterND", "int32"), n = v(e, "updates", "scatterND");
  lc(n, o, t10);
  let s = { indices: o, updates: n }, a = { shape: t10 };
  return T.runKernel(ms, s, a);
}
var U6 = N({ scatterND_: W6 });
function tN(r15, e, t10, o) {
  if (r15.dtype !== "int32") throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${r15.dtype}.`);
  if (r15.rank > 2) throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${r15.shape}.`);
  let n = r15.rank > 0 ? r15.shape[0] : 1, s = r15.rank > 1 ? r15.shape[1] : 1;
  if (t10.length !== s) throw new Error(`outputShape has incorrect number of elements:, ${t10.length}, should be: ${s}.`);
  let a = e.size;
  if (!(e.rank === 0 || e.rank === 1 && a === n)) throw new Error(`sparseValues has incorrect shape ${e.shape}, should be [] or [${n}]`);
  if (e.dtype !== o.dtype) throw new Error("sparseValues.dtype must match defaultValues.dtype");
}
function H6(r15, e, t10, o = 0) {
  Ct(t10);
  let n = v(r15, "sparseIndices", "sparseToDense", "int32"), s = v(e, "sparseValues", "sparseToDense", "string_or_numeric"), a = v(o, "defaultValue", "sparseToDense", s.dtype);
  tN(n, s, t10, a);
  let i = { sparseIndices: n, sparseValues: s, defaultValue: a }, p = { outputShape: t10 };
  return T.runKernel(vs, i, p);
}
var K6 = N({ sparseToDense_: H6 });
function q6(r15, e) {
  let t10 = v(e, "indices", "gatherND", "int32"), n = { params: v(r15, "x", "gatherND", "string_or_numeric"), indices: t10 };
  return T.runKernel(vn, n);
}
var j6 = N({ gatherND_: q6 });
function rN(r15, e) {
  if (e == null) return r15.shape.slice();
  if (br(r15.shape, e)) return e;
  if (r15.shape.length === e.length) {
    let t10 = [];
    for (let o = 0; o < r15.shape.length; o++) e[o] == null && r15.shape[o] != null ? t10.push(r15.shape[o]) : t10.push(e[o]);
    return t10;
  }
  return e;
}
function X6(r15, e, t10, o) {
  let n = v(r15, "x", "dropout");
  if (E(n.dtype === "float32", () => `x has to be a floating point tensor since it's going to be scaled, but got a ${n.dtype} tensor instead.`), E(e >= 0 && e < 1, () => `rate must be a float in the range [0, 1), but got ${e}.`), e === 0) return r15 instanceof mt ? n.clone() : n;
  let s = rN(n, t10), a = 1 - e, i = je(wd(Ce(ic(s, 0, 1, "float32", o), a)), a);
  return se(n, i);
}
var Y6 = N({ dropout_: X6 });
function Zw(r15) {
  return Math.floor(Math.pow(2, Math.ceil(Math.log(r15) / Math.log(2))));
}
function $l(r15, e, t10) {
  let o = 1 - r15 % 2, n = new Float32Array(r15);
  for (let s = 0; s < r15; ++s) {
    let a = 2 * Math.PI * s / (r15 + o - 1);
    n[s] = e - t10 * Math.cos(a);
  }
  return Jt(n, "float32");
}
async function Q6(r15, e, t10 = 1) {
  let o = v(r15, "predictions", "inTopK"), n = v(e, "targets", "inTopK");
  E(o.rank > 1, () => `inTopK() expects the predictions to be of rank 2 or higher, but got ${o.rank}`), E(o.rank - 1 === n.rank, () => `predictions rank should be 1 larger than targets rank, but got predictions rank ${o.rank} and targets rank ${n.rank}`), xt(o.shape.slice(0, o.shape.length - 1), n.shape, "predictions's shape should be align with the targets' shape, except the last dimension.");
  let s = o.shape[o.shape.length - 1];
  E(t10 > 0 && t10 <= s, () => `'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${t10}`);
  let a = await o.data(), i = await n.data(), [p, u] = [a.length / s, s], c = ew("bool", p);
  for (let l = 0; l < p; l++) {
    let m = l * u, d = a.subarray(m, m + u), f = [];
    for (let h = 0; h < d.length; h++) f.push({ value: d[h], index: h });
    f.sort((h, g) => g.value - h.value), c[l] = 0;
    for (let h = 0; h < t10; h++) if (f[h].index === i[l]) {
      c[l] = 1;
      break;
    }
  }
  return r15 !== o && o.dispose(), e !== n && n.dispose(), ar(c, n.shape, "bool");
}
var Z6 = Q6;
var Jw = {};
qe(Jw, { conv2d: () => nN, depthwiseConv2d: () => iN, matMul: () => uN });
function J6(r15, e, t10, o, n, s = "NHWC", a) {
  let i = r15;
  r15.rank === 3 && (i = W(r15, [1, r15.shape[0], r15.shape[1], r15.shape[2]]));
  let p = e;
  p.rank === 3 && (p = W(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(p.rank === 4, () => `Error in conv2dDerFilter: dy must be rank 4, but got shape ${p.shape}.`), E(t10.length === 4, () => `Error in conv2dDerFilter: filterShape must be length 4, but got ${t10}.`);
  let u = s === "NHWC" ? i.shape[3] : i.shape[1], c = s === "NHWC" ? p.shape[3] : p.shape[1];
  E(u === t10[2], () => `Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${t10[2]}.`), E(c === t10[3], () => `Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${t10[3]}).`), Lt("conv2dDerFilter", n, a);
  let l = { x: i, dy: p }, m = { strides: o, pad: n, dataFormat: s, dimRoundingMode: a, filterShape: t10 };
  return T.runKernel(Fi, l, m);
}
var oN = N({ conv2DBackpropFilter_: J6 });
function Xu(r15, e, t10) {
  if (t10 == null || t10 === "linear") return r15;
  if (t10 === "relu") return se(r15, qd(e));
  throw new Error(`Cannot compute gradient for fused activation ${t10}.`);
}
function Yu(r15, e) {
  let t10 = e, o = xd(r15.shape, e.shape);
  return o.length > 0 && (t10 = ot(t10, o)), W(t10, r15.shape);
}
function Qu(r15, e, t10, o) {
  if (e === "linear") return r15;
  if (e === "relu") return lu(r15);
  if (e === "elu") return bd(r15);
  if (e === "relu6") return Ud(r15);
  if (e === "prelu") return Od(r15, t10);
  if (e === "leakyrelu") return vd(r15, o);
  if (e === "sigmoid") return Ea(r15);
  throw new Error(`Unknown fused activation ${e}.`);
}
var Zu = (r15, e) => !(r15 > 0) || e === "linear";
function ej({ x: r15, filter: e, strides: t10, pad: o, dataFormat: n = "NHWC", dilations: s = [1, 1], dimRoundingMode: a, bias: i, activation: p = "linear", preluActivationWeights: u, leakyreluAlpha: c }) {
  if (p = p || "linear", Zu(T.state.gradientDepth, p) === false) {
    E(n === "NHWC", () => `Error in fused conv2d: got dataFormat of ${n} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);
    let _ = au(r15, e, t10, o, n, s, a);
    return i != null && (_ = Ce(_, i)), Qu(_, p, u, c);
  }
  let l = v(r15, "x", "conv2d", "float32"), m = v(e, "filter", "conv2d", "float32"), d = l, f = false;
  l.rank === 3 && (f = true, d = W(l, [1, l.shape[0], l.shape[1], l.shape[2]])), E(d.rank === 4, () => `Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`), E(m.rank === 4, () => `Error in fused conv2d: filter must be rank 4, but got rank ${m.rank}.`), Lt("fused conv2d", o, a);
  let h = n === "NHWC" ? d.shape[3] : d.shape[1];
  E(m.shape[2] === h, () => `Error in conv2d: depth of input (${h}) must match input depth for filter ${m.shape[2]}.`), E(gr(t10, s), () => `Error in conv2D: Either strides or dilations must be 1. Got strides ${t10} and dilations '${s}'`);
  let g = zu(d.shape, m.shape, t10, s, o, a), x;
  i != null && (x = v(i, "bias", "fused conv2d"), [x] = Oe(x, l), n === "NHWC" ? rt(g.outShape, x.shape) : (E(x.shape.length <= 1, () => `Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${x.shape.length}.`), E(x.shape.length === 0 || x.shape[0] === g.outChannels || x.shape[0] === 1, () => `Error in fused conv2d: bias shape (${x.shape}) is not compatible with the number of output channels (${g.outChannels})`)));
  let b;
  if (u != null) {
    let _ = u.shape;
    if (E(_.length <= 1 || _.length === 3, () => `Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${_.length}.`), _.length === 1) E(_[0] === 1 || _[0] === g.outChannels, () => `Error in fused conv2d: PReLU activation weights (${_}) is not compatible with the number of output channels (${g.outChannels}).`);
    else if (_.length === 3) try {
      rt(_, g.outShape);
    } catch ($) {
      let R = `Error in fused conv2d: PReLU activation weights (${_}) is not compatible with the output shape of the conv2d (${g.outShape}).`;
      throw Error(R);
    }
    b = v(u, "prelu weights", "fused conv2d");
  }
  let C = (_, $) => {
    E(n === "NHWC", () => `Error in gradient of fused conv2D: got dataFormat of ${n} but only NHWC is currently supported.`);
    let [R, D, P, O] = $, M = Xu(_, P, p);
    E(Bu(s), () => `Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);
    let L = gd(D.shape, M, R, t10, o), B = oN(D, M, R.shape, t10, o), z = [L, B];
    if (O != null) {
      let U = Yu(O, M);
      z.push(U);
    }
    return z;
  }, S = { x: d, filter: m, bias: x, preluActivationWeights: b }, k = { strides: t10, pad: o, dataFormat: n, dilations: s, dimRoundingMode: a, activation: p, leakyreluAlpha: c };
  return i == null ? Ir(($, R, D) => {
    let P = T.runKernel(Io, S, k);
    return D([R, $, P]), f && (P = W(P, [P.shape[1], P.shape[2], P.shape[3]])), { value: P, gradFunc: C };
  })(d, m) : Ir(($, R, D, P) => {
    let O = T.runKernel(Io, S, k);
    return P([R, $, O, D]), f && (O = W(O, [O.shape[1], O.shape[2], O.shape[3]])), { value: O, gradFunc: C };
  })(d, m, x);
}
var nN = N({ fusedConv2d_: ej });
function tj(r15, e, t10, o, n, s = [1, 1], a) {
  let i = r15;
  r15.rank === 3 && (i = W(r15, [1, r15.shape[0], r15.shape[1], r15.shape[2]]));
  let p = e;
  p.rank === 3 && (p = W(e, [1, e.shape[0], e.shape[1], e.shape[2]]));
  let u = { x: i, dy: p }, c = { strides: o, pad: n, dimRoundingMode: a, dilations: s, filterShape: t10 };
  return T.runKernel(Pi, u, c);
}
var sN = N({ depthwiseConv2dNativeBackpropFilter_: tj });
function rj(r15, e, t10, o, n, s = [1, 1], a) {
  let i = e, p = false;
  e.rank === 3 && (p = true, i = W(e, [1, e.shape[0], e.shape[1], e.shape[2]]));
  let u = { dy: i, filter: t10 }, c = { strides: o, pad: n, dimRoundingMode: a, dilations: s, inputShape: r15 }, l = T.runKernel(Oi, u, c);
  return p ? W(l, [l.shape[1], l.shape[2], l.shape[3]]) : l;
}
var aN = N({ depthwiseConv2dNativeBackpropInput_: rj });
function oj({ x: r15, filter: e, strides: t10, pad: o, dataFormat: n = "NHWC", dilations: s = [1, 1], dimRoundingMode: a, bias: i, activation: p = "linear", preluActivationWeights: u, leakyreluAlpha: c }) {
  if (Zu(T.state.gradientDepth, p) === false) {
    let k = sc(r15, e, t10, o, n, s, a);
    return i != null && (k = Ce(k, i)), Qu(k, p, u, c);
  }
  let l = v(r15, "x", "depthwiseConv2d", "float32"), m = v(e, "filter", "depthwiseConv2d", "float32"), d = l, f = false;
  l.rank === 3 && (f = true, d = W(l, [1, l.shape[0], l.shape[1], l.shape[2]])), E(d.rank === 4, () => `Error in fused depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`), E(m.rank === 4, () => `Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${m.rank}.`), E(d.shape[3] === m.shape[2], () => `Error in fused depthwiseConv2d: number of input channels (${d.shape[3]}) must match the inChannels dimension in filter ${m.shape[2]}.`), s == null && (s = [1, 1]), E(gr(t10, s), () => `Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${t10} and dilations '${s}'`), Lt("fused depthwiseConv2d", o, a);
  let h = zu(d.shape, m.shape, t10, s, o, a, true), g;
  i != null && (g = v(i, "bias", "fused conv2d"), [g] = Oe(g, l), rt(h.outShape, g.shape));
  let x;
  u != null && (x = v(u, "prelu weights", "fused depthwiseConv2d"));
  let b = (k, _) => {
    E(Bu(s), () => `Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);
    let [$, R, D, P] = _, O = Xu(k, D, p), M = aN(R.shape, O, $, t10, o, s, a), L = sN(R, O, $.shape, t10, o, s, a);
    if (P != null) {
      let B = Yu(g, O);
      return [M, L, B];
    }
    return [M, L];
  }, C = { x: d, filter: m, bias: g, preluActivationWeights: x }, S = { strides: t10, pad: o, dataFormat: n, dilations: s, dimRoundingMode: a, activation: p, leakyreluAlpha: c };
  return i == null ? Ir((_, $, R) => {
    let D = T.runKernel(vo, C, S);
    return R([$, _, D]), f && (D = W(D, [D.shape[1], D.shape[2], D.shape[3]])), { value: D, gradFunc: b };
  })(d, m) : Ir((_, $, R, D) => {
    let P = T.runKernel(vo, C, S);
    return D([$, _, P, R]), f && (P = W(P, [P.shape[1], P.shape[2], P.shape[3]])), { value: P, gradFunc: b };
  })(d, m, g);
}
var iN = N({ fusedDepthwiseConv2d_: oj });
function nj({ a: r15, b: e, transposeA: t10 = false, transposeB: o = false, bias: n, activation: s = "linear", preluActivationWeights: a, leakyreluAlpha: i = 0.2 }) {
  if (Zu(T.state.gradientDepth, s) === false) {
    let O = Ze(r15, e, t10, o);
    return n != null && (O = Ce(O, n)), Qu(O, s, a, i);
  }
  let p = v(r15, "a", "fused matMul"), u = v(e, "b", "fused matMul");
  [p, u] = Oe(p, u);
  let c = t10 ? p.shape[p.rank - 2] : p.shape[p.rank - 1], l = o ? u.shape[u.rank - 1] : u.shape[u.rank - 2], m = t10 ? p.shape[p.rank - 1] : p.shape[p.rank - 2], d = o ? u.shape[u.rank - 2] : u.shape[u.rank - 1], f = p.shape.slice(0, -2), h = u.shape.slice(0, -2), g = ze(f), x = ze(h);
  E(c === l, () => `Error in fused matMul: inner shapes (${c}) and (${l}) of Tensors with shapes ${p.shape} and ${u.shape} and transposeA=${t10} and transposeB=${o} must match.`);
  let C = rt(p.shape.slice(0, -2), u.shape.slice(0, -2)).concat([m, d]), S = t10 ? W(p, [g, c, m]) : W(p, [g, m, c]), k = o ? W(u, [x, d, l]) : W(u, [x, l, d]), _;
  n != null && (_ = v(n, "bias", "fused matMul"), [_] = Oe(_, p), rt(C, _.shape));
  let $;
  a != null && ($ = v(a, "prelu weights", "fused matMul"));
  let R = (O, M) => {
    let [L, B, z, U] = M, j = Xu(W(O, z.shape), z, s), q, Y;
    if (!t10 && !o ? (q = Ze(j, B, false, true), Y = Ze(L, j, true, false)) : !t10 && o ? (q = Ze(j, B, false, false), Y = Ze(j, L, true, false)) : t10 && !o ? (q = Ze(B, j, false, true), Y = Ze(L, j, false, false)) : (q = Ze(B, j, true, true), Y = Ze(j, L, true, true)), n != null) {
      let J = Yu(U, j);
      return [q, Y, J];
    } else return [q, Y];
  }, D = { a: S, b: k, bias: _, preluActivationWeights: $ }, P = { transposeA: t10, transposeB: o, activation: s, leakyreluAlpha: i };
  return n == null ? Ir((M, L, B) => {
    let z = T.runKernel(So, D, P);
    return B([M, L, z]), { value: W(z, C), gradFunc: R };
  })(S, k) : Ir((M, L, B, z) => {
    let U = T.runKernel(So, D, P);
    return z([M, L, U, B]), { value: W(U, C), gradFunc: R };
  })(S, k, _);
}
var uN = N({ fusedMatMul_: nj });
function sj(r15) {
  return $l(r15, 0.54, 0.46);
}
var pN = N({ hammingWindow_: sj });
function aj(r15) {
  return $l(r15, 0.5, 0.5);
}
var Qd = N({ hannWindow_: aj });
function ij(r15, e, t10, o = false, n = 0) {
  let s = 0, a = [];
  for (; s + e <= r15.size; ) a.push(Xe(r15, s, e)), s += t10;
  if (o) for (; s < r15.size; ) {
    let i = s + e - r15.size, p = yt([Xe(r15, s, e - i), $a([i], n)]);
    a.push(p), s += t10;
  }
  return a.length === 0 ? mu([], [0, e]) : W(yt(a), [a.length, e]);
}
var Zd = N({ frame_: ij });
function uj(r15, e, t10, o, n = Qd) {
  o == null && (o = Zw(e));
  let s = Zd(r15, e, t10), a = se(s, n(e));
  return pc(a, o);
}
var cN = N({ stft_: uj });
function pj(r15, e, t10, o, n = "bilinear", s = 0) {
  let a = v(r15, "image", "cropAndResize"), i = v(e, "boxes", "cropAndResize", "float32"), p = v(t10, "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(p.rank === 1 && p.shape[0] === u, () => `Error in cropAndResize: boxInd must be have size [${u}] but had shape ${i.shape}.`), E(o.length === 2, () => `Error in cropAndResize: cropSize must be of length 2, but got length ${o.length}.`), E(o[0] >= 1 && o[1] >= 1, () => `cropSize must be atleast [1,1], but was ${o}`), E(n === "bilinear" || n === "nearest", () => `method must be bilinear or nearest, but was ${n}`);
  let c = { image: a, boxes: i, boxInd: p }, l = { method: n, extrapolationValue: s, cropSize: o };
  return T.runKernel(cn, c, l);
}
var lN = N({ cropAndResize_: pj });
function cj(r15) {
  let e = v(r15, "image", "flipLeftRight", "float32");
  E(e.rank === 4, () => `Error in flipLeftRight: image must be rank 4,but got rank ${e.rank}.`);
  let t10 = { image: e };
  return T.runKernel(Cn, t10, {});
}
var mN = N({ flipLeftRight_: cj });
function lj(r15) {
  let e = v(r15, "image", "grayscaleToRGB"), t10 = e.rank - 1, o = e.shape[t10];
  E(e.rank >= 2, () => `Error in grayscaleToRGB: images must be at least rank 2, but got rank ${e.rank}.`), E(o === 1, () => `Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${o}.`);
  let n = new Array(e.rank);
  return n.fill(1, 0, t10), n[t10] = 3, uu(e, n);
}
var dN = N({ grayscaleToRGB_: lj });
function mj(r15) {
  let e = v(r15, "image", "RGBToGrayscale"), t10 = e.rank - 1, o = e.shape[t10];
  E(e.rank >= 2, () => `Error in RGBToGrayscale: images must be at least rank 2, but got rank ${e.rank}.`), E(o === 3, () => `Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${o}.`);
  let n = e.dtype, s = Ue(e, "float32"), a = Jt([0.2989, 0.587, 0.114]), i;
  switch (e.rank) {
    case 2:
      i = iu("ij,j->i", s, a);
      break;
    case 3:
      i = iu("ijk,k->ij", s, a);
      break;
    case 4:
      i = iu("ijkl,l->ijk", s, a);
      break;
    case 5:
      i = iu("ijklm,m->ijkl", s, a);
      break;
    case 6:
      i = iu("ijklmn,n->ijklm", s, a);
      break;
    default:
      throw new Error("Not a valid tensor rank.");
  }
  return i = Ms(i, -1), Ue(i, n);
}
var fN = N({ rgbToGrayscale_: mj });
function dj(r15, e, t10 = 0, o = 0.5) {
  let n = v(r15, "image", "rotateWithOffset", "float32");
  E(n.rank === 4, () => `Error in rotateWithOffset: image must be rank 4,but got rank ${n.rank}.`);
  let s = { image: n }, a = { radians: e, fillValue: t10, center: o };
  return T.runKernel(Ds, s, a);
}
var hN = N({ rotateWithOffset_: dj });
function Eo(r15, e, t10, o, n, s) {
  o == null && (o = 0.5), n == null && (n = Number.NEGATIVE_INFINITY), s == null && (s = 0);
  let a = r15.shape[0];
  return t10 = Math.min(t10, a), E(0 <= o && o <= 1, () => `iouThreshold must be in [0, 1], but was '${o}'`), E(r15.rank === 2, () => `boxes must be a 2D tensor, but was of rank '${r15.rank}'`), E(r15.shape[1] === 4, () => `boxes must have 4 columns, but 2nd dimension was ${r15.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: t10, iouThreshold: o, scoreThreshold: n, softNmsSigma: s };
}
function fj(r15, e, t10, o = 0.5, n = Number.NEGATIVE_INFINITY) {
  let s = v(r15, "boxes", "nonMaxSuppression", "float32"), a = v(e, "scores", "nonMaxSuppression", "float32"), i = Eo(s, a, t10, o, n);
  t10 = i.maxOutputSize, o = i.iouThreshold, n = i.scoreThreshold;
  let p = { maxOutputSize: t10, iouThreshold: o, scoreThreshold: n };
  return T.runKernel(Qn, { boxes: s, scores: a }, p);
}
var gN = N({ nonMaxSuppression_: fj });
function xN(r15, e, t10) {
  let o = hj(r15, e, t10), n = o < 0 ? -(o + 1) : o;
  r15.splice(n, 0, e);
}
function hj(r15, e, t10) {
  return xj(r15, e, t10 || gj);
}
function gj(r15, e) {
  return r15 > e ? 1 : r15 < e ? -1 : 0;
}
function xj(r15, e, t10) {
  let o = 0, n = r15.length, s = 0, a = false;
  for (; o < n; ) {
    s = o + (n - o >>> 1);
    let i = t10(e, r15[s]);
    i > 0 ? o = s + 1 : (n = s, a = !i);
  }
  return a ? o : -o - 1;
}
function Jd(r15, e, t10, o, n) {
  return eS(r15, e, t10, o, n, 0);
}
function ef(r15, e, t10, o, n, s) {
  return eS(r15, e, t10, o, n, 0, false, s, true);
}
function tf(r15, e, t10, o, n, s) {
  return eS(r15, e, t10, o, n, s, true);
}
function eS(r15, e, t10, o, n, s, a = false, i = false, p = false) {
  let u = [];
  for (let g = 0; g < e.length; g++) e[g] > n && u.push({ score: e[g], boxIndex: g, suppressBeginIndex: 0 });
  u.sort(yN);
  let c = s > 0 ? -0.5 / s : 0, l = [], m = [];
  for (; l.length < t10 && u.length > 0; ) {
    let g = u.pop(), { score: x, boxIndex: b, suppressBeginIndex: C } = g;
    if (x < n) break;
    let S = false;
    for (let k = l.length - 1; k >= C; --k) {
      let _ = yj(r15, b, l[k]);
      if (_ >= o) {
        S = true;
        break;
      }
      if (g.score = g.score * bj(o, c, _), g.score <= n) break;
    }
    g.suppressBeginIndex = l.length, S || (g.score === x ? (l.push(b), m.push(g.score)) : g.score > n && xN(u, g, yN));
  }
  let d = l.length, f = t10 - d;
  i && f > 0 && (l.push(...new Array(f).fill(0)), m.push(...new Array(f).fill(0)));
  let h = { selectedIndices: l };
  return a && (h.selectedScores = m), p && (h.validOutputs = d), h;
}
function yj(r15, e, t10) {
  let o = r15.subarray(e * 4, e * 4 + 4), n = r15.subarray(t10 * 4, t10 * 4 + 4), s = Math.min(o[0], o[2]), a = Math.min(o[1], o[3]), i = Math.max(o[0], o[2]), p = Math.max(o[1], o[3]), u = Math.min(n[0], n[2]), c = Math.min(n[1], n[3]), l = Math.max(n[0], n[2]), m = Math.max(n[1], n[3]), d = (i - s) * (p - a), f = (l - u) * (m - c);
  if (d <= 0 || f <= 0) return 0;
  let h = Math.max(s, u), g = Math.max(a, c), x = Math.min(i, l), b = Math.min(p, m), C = Math.max(x - h, 0) * Math.max(b - g, 0);
  return C / (d + f - C);
}
function bj(r15, e, t10) {
  let o = Math.exp(e * t10 * t10);
  return t10 <= r15 ? o : 0;
}
function yN(r15, e) {
  return r15.score - e.score || r15.score === e.score && e.boxIndex - r15.boxIndex;
}
async function Cj(r15, e, t10, o = 0.5, n = Number.NEGATIVE_INFINITY) {
  let s = v(r15, "boxes", "nonMaxSuppressionAsync"), a = v(e, "scores", "nonMaxSuppressionAsync"), i = Eo(s, a, t10, o, n);
  t10 = i.maxOutputSize, o = i.iouThreshold, n = i.scoreThreshold;
  let p = await Promise.all([s.data(), a.data()]), u = p[0], c = p[1], { selectedIndices: l } = Jd(u, c, t10, o, n);
  return s !== r15 && s.dispose(), a !== e && a.dispose(), Jt(l, "int32");
}
var bN = Cj;
function wj(r15, e, t10, o = 0.5, n = Number.NEGATIVE_INFINITY, s = 0) {
  let a = v(r15, "boxes", "nonMaxSuppression"), i = v(e, "scores", "nonMaxSuppression"), p = Eo(a, i, t10, o, n, s);
  t10 = p.maxOutputSize, o = p.iouThreshold, n = p.scoreThreshold, s = p.softNmsSigma;
  let u = { boxes: a, scores: i }, c = { maxOutputSize: t10, iouThreshold: o, scoreThreshold: n, softNmsSigma: s }, l = T.runKernel(Zn, u, c);
  return { selectedIndices: l[0], selectedScores: l[1] };
}
var CN = N({ nonMaxSuppressionWithScore_: wj });
async function Sj(r15, e, t10, o = 0.5, n = Number.NEGATIVE_INFINITY, s = 0) {
  let a = v(r15, "boxes", "nonMaxSuppressionAsync"), i = v(e, "scores", "nonMaxSuppressionAsync"), p = Eo(a, i, t10, o, n, s);
  t10 = p.maxOutputSize, o = p.iouThreshold, n = p.scoreThreshold, s = p.softNmsSigma;
  let u = await Promise.all([a.data(), i.data()]), c = u[0], l = u[1], { selectedIndices: m, selectedScores: d } = tf(c, l, t10, o, n, s);
  return a !== r15 && a.dispose(), i !== e && i.dispose(), { selectedIndices: Jt(m, "int32"), selectedScores: Jt(d) };
}
var wN = Sj;
function Ij(r15, e, t10, o = 0.5, n = Number.NEGATIVE_INFINITY, s = false) {
  let a = v(r15, "boxes", "nonMaxSuppression"), i = v(e, "scores", "nonMaxSuppression"), p = Eo(a, i, t10, o, n, null), u = p.maxOutputSize, c = p.iouThreshold, l = p.scoreThreshold, m = { boxes: a, scores: i }, d = { maxOutputSize: u, iouThreshold: c, scoreThreshold: l, padToMaxOutputSize: s }, f = T.runKernel(Qa, m, d);
  return { selectedIndices: f[0], validOutputs: f[1] };
}
var SN = N({ nonMaxSuppressionPadded_: Ij });
async function vj(r15, e, t10, o = 0.5, n = Number.NEGATIVE_INFINITY, s = false) {
  let a = v(r15, "boxes", "nonMaxSuppressionAsync"), i = v(e, "scores", "nonMaxSuppressionAsync"), p = Eo(a, i, t10, o, n, null), u = p.maxOutputSize, c = p.iouThreshold, l = p.scoreThreshold, [m, d] = await Promise.all([a.data(), i.data()]), { selectedIndices: f, validOutputs: h } = ef(m, d, u, c, l, s);
  return a !== r15 && a.dispose(), i !== e && i.dispose(), { selectedIndices: Jt(f, "int32"), validOutputs: ke(h, "int32") };
}
var IN = vj;
function kj(r15, e, t10 = false, o = false) {
  let n = v(r15, "images", "resizeBilinear");
  E(n.rank === 3 || n.rank === 4, () => `Error in resizeBilinear: x must be rank 3 or 4, but got rank ${n.rank}.`), E(e.length === 2, () => `Error in resizeBilinear: new shape must 2D, but got shape ${e}.`), E(o === false || t10 === false, () => "Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");
  let s = n, a = false;
  n.rank === 3 && (a = true, s = W(n, [1, n.shape[0], n.shape[1], n.shape[2]]));
  let [] = e, i = { images: s }, p = { alignCorners: t10, halfPixelCenters: o, size: e }, u = T.runKernel(is, i, p);
  return a ? W(u, [u.shape[1], u.shape[2], u.shape[3]]) : u;
}
var vN = N({ resizeBilinear_: kj });
function Nj(r15, e, t10 = false, o = false) {
  let n = v(r15, "images", "resizeNearestNeighbor");
  E(n.rank === 3 || n.rank === 4, () => `Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${n.rank}.`), E(e.length === 2, () => `Error in resizeNearestNeighbor: new shape must 2D, but got shape ${e}.`), E(n.dtype === "float32" || n.dtype === "int32", () => "`images` must have `int32` or `float32` as dtype"), E(o === false || t10 === false, () => "Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");
  let s = n, a = false;
  n.rank === 3 && (a = true, s = W(n, [1, n.shape[0], n.shape[1], n.shape[2]]));
  let [] = e, i = { images: s }, p = { alignCorners: t10, halfPixelCenters: o, size: e }, u = T.runKernel(as, i, p);
  return a ? W(u, [u.shape[1], u.shape[2], u.shape[3]]) : u;
}
var kN = N({ resizeNearestNeighbor_: Nj });
function Tj(r15, e = "binary", t10 = false, o = 0.5) {
  let n = v(r15, "image", "threshold"), s = 0.2989, a = 0.587, i = 0.114, p = n.shape[0] * n.shape[1], u = se(Jt([o]), 255), c, l, m, d;
  if (E(n.rank === 3, () => `Error in threshold: image must be rank 3,but got rank ${n.rank}.`), E(n.shape[2] === 3 || n.shape[2] === 1, () => `Error in threshold: image color channel must be equal to 3 or 1but got ${n.shape[2]}.`), E(n.dtype === "int32" || n.dtype === "float32", () => `Error in dtype: image dtype must be int32 or float32,but got dtype ${n.dtype}.`), E(e === "otsu" || e === "binary", () => `Method must be binary or otsu, but was ${e}`), n.shape[2] === 3) {
    [c, l, m] = li(n, [1, 1, 1], -1);
    let g = se(c, s), x = se(l, a), b = se(m, i);
    d = Ce(Ce(g, x), b);
  } else d = r15;
  if (e === "otsu") {
    let g = hd(Ue(Gd(d), "int32"), ar([]), 256);
    u = _j(g, p);
  }
  let f = t10 ? ac(d, u) : Wu(d, u);
  return Ue(se(f, 255), "int32");
}
function _j(r15, e) {
  let t10 = Jt([-1]), o = Jt([0]), n = Jt([0]), s, a, i, p, u, c;
  for (let l = 0; l < r15.size - 1; l++) {
    s = Xe(r15, 0, l + 1), a = Xe(r15, l + 1), u = je(ot(s), e), c = je(ot(a), e);
    let m = ot(se(s, cu(0, s.size)));
    i = je(m, ot(s));
    let d = $a(a.shape, s.size), f = Ce(cu(0, a.size), d), h = se(a, f);
    p = je(ot(h), ot(a));
    let g = Te(i, p), x = Te(i, p), b = se(u, c);
    n = se(se(b, g), x);
    let C = Wu(n, o);
    o = lo(C, n, o), t10 = lo(C, Jt([l]), t10);
  }
  return t10;
}
var NN = N({ threshold_: Tj });
function Ej(r15, e, t10 = "nearest", o = "constant", n = 0, s) {
  let a = v(r15, "image", "transform", "float32"), i = v(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 p = { image: a, transforms: i }, u = { interpolation: t10, fillMode: o, fillValue: n, outputShape: s };
  return T.runKernel(Rs, p, u);
}
var TN = N({ transform_: Ej });
function $j(r15, e, t10) {
  let o = v(r15, "a", "bandPart");
  E(o.rank >= 2, () => `bandPart(): Rank must be at least 2, got ${o.rank}.`);
  let n = o.shape, [s, a] = o.shape.slice(-2), i, p;
  typeof e == "number" ? (E(e % 1 === 0, () => `bandPart(): numLower must be an integer, got ${e}.`), E(e <= s, () => `bandPart(): numLower (${e}) must not be greater than the number of rows (${s}).`), i = v(e < 0 ? s : e, "numLower", "bandPart")) : (E(e.dtype === "int32", () => "bandPart(): numLower's dtype must be an int32."), i = lo(Tl(e, 0), s, Hu(e, s))), typeof t10 == "number" ? (E(t10 % 1 === 0, () => `bandPart(): numUpper must be an integer, got ${t10}.`), E(t10 <= a, () => `bandPart(): numUpper (${t10}) must not be greater than the number of columns (${a}).`), p = v(t10 < 0 ? a : t10, "numUpper", "bandPart")) : (E(t10.dtype === "int32", () => "bandPart(): numUpper's dtype must be an int32."), p = lo(Tl(t10, 0), a, Hu(t10, a)));
  let u = W(cu(0, s, 1, "int32"), [-1, 1]), c = cu(0, a, 1, "int32"), l = Te(u, c), m = Uu(ac(l, i), Id(l, pr(p))), d = Gr([s, a], o.dtype);
  return W(vr(fo(W(o, [-1, s, a])).map((f) => lo(m, f, d))), n);
}
var _N = N({ bandPart_: $j });
function Rj(r15) {
  let e;
  if (Array.isArray(r15)) {
    e = false, E(r15 != null && r15.length > 0, () => "Gram-Schmidt process: input must not be null, undefined, or empty");
    let n = r15[0].shape[0];
    for (let s = 1; s < r15.length; ++s) E(r15[s].shape[0] === n, () => `Gram-Schmidt: Non-unique lengths found in the input vectors: (${r15[s].shape[0]} vs. ${n})`);
  } else e = true, r15 = li(r15, r15.shape[0], 0).map((n) => cc(n, [0]));
  E(r15.length <= r15[0].shape[0], () => `Gram-Schmidt: Number of vectors (${r15.length}) exceeds number of dimensions (${r15[0].shape[0]}).`);
  let t10 = [], o = r15;
  for (let n = 0; n < r15.length; ++n) t10.push(T.tidy(() => {
    let s = o[n];
    if (n > 0) for (let a = 0; a < n; ++a) {
      let i = se(ot(se(t10[a], s)), t10[a]);
      s = Te(s, i);
    }
    return je(s, Vu(s, "euclidean"));
  }));
  return e ? vr(t10, 0) : t10;
}
var EN = N({ gramSchmidt_: Rj });
function Dj(r15, e = false) {
  if (E(r15.rank >= 2, () => `qr() requires input tensor to have a rank >= 2, but got rank ${r15.rank}`), r15.rank === 2) return $N(r15, e);
  {
    let t10 = r15.shape.slice(0, r15.shape.length - 2).reduce((p, u) => p * u), o = fo(W(r15, [t10, r15.shape[r15.shape.length - 2], r15.shape[r15.shape.length - 1]]), 0), n = [], s = [];
    o.forEach((p) => {
      let [u, c] = $N(p, e);
      n.push(u), s.push(c);
    });
    let a = W(vr(n, 0), r15.shape), i = W(vr(s, 0), r15.shape);
    return [a, i];
  }
}
function $N(r15, e = false) {
  return T.tidy(() => {
    E(r15.shape.length === 2, () => `qr2d() requires a 2D Tensor, but got a ${r15.shape.length}D Tensor.`);
    let t10 = r15.shape[0], o = r15.shape[1], n = Cd(t10), s = Ur(r15), a = mu([[1]], [1, 1]), i = Ur(a), p = t10 >= o ? o : t10;
    for (let u = 0; u < p; ++u) {
      let c = s, l = i, m = n;
      [i, s, n] = T.tidy(() => {
        let d = Xe(s, [u, u], [t10 - u, 1]), f = Vu(d), h = Xe(s, [u, u], [1, 1]), g = lo(Wu(h, 0), mu([[-1]]), mu([[1]])), x = Te(h, se(g, f)), b = je(d, x);
        b.shape[0] === 1 ? i = Ur(a) : i = yt([a, Xe(b, [1, 0], [b.shape[0] - 1, b.shape[1]])], 0);
        let C = pr(je(Ze(g, x), f)), S = Xe(s, [u, 0], [t10 - u, o]), k = se(C, i), _ = mc(i);
        if (u === 0) s = Te(S, Ze(k, Ze(_, S)));
        else {
          let D = Te(S, Ze(k, Ze(_, S)));
          s = yt([Xe(s, [0, 0], [u, o]), D], 0);
        }
        let $ = mc(k), R = Xe(n, [0, u], [t10, n.shape[1] - u]);
        if (u === 0) n = Te(R, Ze(Ze(R, i), $));
        else {
          let D = Te(R, Ze(Ze(R, i), $));
          n = yt([Xe(n, [0, 0], [t10, u]), D], 1);
        }
        return [i, s, n];
      }), Ot([c, l, m]);
    }
    return !e && t10 > o && (n = Xe(n, [0, 0], [t10, o]), s = Xe(s, [0, 0], [o, o])), [n, s];
  });
}
var RN = N({ qr_: Dj });
var $t;
(function(r15) {
  r15[r15.NONE = 0] = "NONE", r15[r15.MEAN = 1] = "MEAN", r15[r15.SUM = 2] = "SUM", r15[r15.SUM_BY_NONZERO_WEIGHTS = 3] = "SUM_BY_NONZERO_WEIGHTS";
})($t || ($t = {}));
function Aj(r15, e, t10 = $t.SUM_BY_NONZERO_WEIGHTS) {
  let o = v(r15, "losses", "computeWeightedLoss"), n = null;
  e != null && (n = v(e, "weights", "computeWeightedLoss"));
  let s = n == null ? o : se(o, n);
  if (t10 === $t.NONE) return s;
  if (t10 === $t.SUM) return ot(s);
  if (t10 === $t.MEAN) {
    if (n == null) return Gu(s);
    {
      let a = o.size / n.size, i = je(ot(s), ot(n));
      return a > 1 ? je(i, ke(a)) : i;
    }
  }
  if (t10 === $t.SUM_BY_NONZERO_WEIGHTS) {
    if (n == null) return je(ot(s), ke(o.size));
    {
      let a = se(n, Da(o.shape)), i = Ue(ot(Fd(a, ke(0))), "float32");
      return je(ot(s), i);
    }
  }
  throw Error(`Unknown reduction: ${t10}`);
}
var cr = N({ computeWeightedLoss_: Aj });
function Fj(r15, e, t10, o = $t.SUM_BY_NONZERO_WEIGHTS) {
  let n = v(r15, "labels", "absoluteDifference"), s = v(e, "predictions", "absoluteDifference"), a = null;
  t10 != null && (a = v(t10, "weights", "absoluteDifference")), xt(n.shape, s.shape, "Error in absoluteDifference: ");
  let i = Qt(Te(n, s));
  return cr(i, a, o);
}
var DN = N({ absoluteDifference_: Fj });
function Pj(r15, e, t10, o, n = $t.SUM_BY_NONZERO_WEIGHTS) {
  let s = v(r15, "labels", "cosineDistance"), a = v(e, "predictions", "cosineDistance"), i = null;
  o != null && (i = v(o, "weights", "cosineDistance")), xt(s.shape, a.shape, "Error in cosineDistance: ");
  let p = ke(1), u = Te(p, ot(se(s, a), t10, true));
  return cr(u, i, n);
}
var AN = N({ cosineDistance_: Pj });
function Oj(r15, e, t10, o = $t.SUM_BY_NONZERO_WEIGHTS) {
  let n = v(r15, "labels", "hingeLoss"), s = v(e, "predictions", "hingeLoss"), a = null;
  t10 != null && (a = v(t10, "weights", "hingeLoss")), xt(n.shape, s.shape, "Error in hingeLoss: ");
  let i = ke(1);
  n = Te(se(ke(2), n), i);
  let p = lu(Te(i, se(n, s)));
  return cr(p, a, o);
}
var FN = N({ hingeLoss_: Oj });
function Mj(r15, e, t10, o = 1, n = $t.SUM_BY_NONZERO_WEIGHTS) {
  let s = v(r15, "labels", "huberLoss"), a = v(e, "predictions", "huberLoss"), i = null;
  t10 != null && (i = v(t10, "weights", "huberLoss")), xt(s.shape, a.shape, "Error in huberLoss: ");
  let p = ke(o), u = Qt(Te(a, s)), c = Hu(u, p), l = Te(u, c), m = Ce(se(ke(0.5), Zt(c)), se(p, l));
  return cr(m, i, n);
}
var PN = N({ huberLoss_: Mj });
function Lj(r15, e, t10, o = 1e-7, n = $t.SUM_BY_NONZERO_WEIGHTS) {
  let s = v(r15, "labels", "logLoss"), a = v(e, "predictions", "logLoss"), i = null;
  t10 != null && (i = v(t10, "weights", "logLoss")), xt(s.shape, a.shape, "Error in logLoss: ");
  let p = ke(1), u = ke(o), c = pr(se(s, pi(Ce(a, u)))), l = se(Te(p, s), pi(Ce(Te(p, a), u))), m = Te(c, l);
  return cr(m, i, n);
}
var ON = N({ logLoss_: Lj });
function Bj(r15, e, t10, o = $t.SUM_BY_NONZERO_WEIGHTS) {
  let n = v(r15, "labels", "meanSquaredError"), s = v(e, "predictions", "meanSquaredError"), a = null;
  t10 != null && (a = v(t10, "weights", "meanSquaredError")), xt(n.shape, s.shape, "Error in meanSquaredError: ");
  let i = Kd(n, s);
  return cr(i, a, o);
}
var MN = N({ meanSquaredError_: Bj });
function zj(r15, e) {
  let t10 = v(r15, "labels", "sigmoidCrossEntropyWithLogits"), o = v(e, "logits", "sigmoidCrossEntropyWithLogits");
  xt(t10.shape, o.shape, "Error in sigmoidCrossEntropyWithLogits: ");
  let n = lu(o), s = se(o, t10), a = kd(_o(pr(Qt(o))));
  return Ce(Te(n, s), a);
}
function Vj(r15, e, t10, o = 0, n = $t.SUM_BY_NONZERO_WEIGHTS) {
  let s = v(r15, "multiClassLabels", "sigmoidCrossEntropy"), a = v(e, "logits", "sigmoidCrossEntropy"), i = null;
  if (t10 != null && (i = v(t10, "weights", "sigmoidCrossEntropy")), xt(s.shape, a.shape, "Error in sigmoidCrossEntropy: "), o > 0) {
    let u = ke(o), c = ke(1), l = ke(0.5);
    s = Ce(se(s, Te(c, u)), se(l, u));
  }
  let p = zj(s, a);
  return cr(p, i, n);
}
var LN = N({ sigmoidCrossEntropy_: Vj });
function Wj(r15, e, t10 = -1) {
  if (t10 === -1 && (t10 = e.rank - 1), t10 !== 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 ${t10}`);
  return Ir((n, s, a) => {
    let p = _d(s, [t10], true), u = Te(Ue(s, "float32"), p);
    a([n, u]);
    let c = pr(se(u, n));
    return { value: ot(c, [t10]), gradFunc: (d, f) => {
      let [h, g] = f, x = ii(d.shape, [t10]);
      return [se(W(d, x), Te(Ue(h, "float32"), _o(g))), se(W(d, x), Te(_o(g), Ue(h, "float32")))];
    } };
  })(r15, e);
}
function Uj(r15, e, t10, o = 0, n = $t.SUM_BY_NONZERO_WEIGHTS) {
  let s = v(r15, "onehotLabels", "softmaxCrossEntropy"), a = v(e, "logits", "softmaxCrossEntropy"), i = null;
  if (t10 != null && (i = v(t10, "weights", "softmaxCrossEntropy")), xt(s.shape, a.shape, "Error in softmaxCrossEntropy: "), o > 0) {
    let u = ke(o), c = ke(1), l = ke(s.shape[1]);
    s = Ce(se(s, Te(c, u)), je(u, l));
  }
  let p = Wj(s, a);
  return cr(p, i, n);
}
var BN = N({ softmaxCrossEntropy_: Uj });
function Gj(r15, e, t10, o) {
  let n = v(r15, "indices", "sparseFillEmptyRows", "int32"), s = v(e, "values", "sparseFillEmptyRows"), a = v(t10, "denseShape", "sparseFillEmptyRows", "int32"), i = v(o, "defaultValue", "sparseFillEmptyRows", s.dtype);
  if (n.rank !== 2) throw new Error(`Indices should be Tensor2D but received shape
        ${n.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 p = { indices: n, values: s, denseShape: a, defaultValue: i }, u = T.runKernel(Ki, p);
  return { outputIndices: u[0], outputValues: u[1], emptyRowIndicator: u[2], reverseIndexMap: u[3] };
}
var zN = N({ sparseFillEmptyRows_: Gj });
function Hj(r15, e, t10) {
  let o = v(r15, "inputIndices", "sparseReshape", "int32"), n = v(e, "inputShape", "sparseReshape", "int32"), s = v(t10, "newShape", "sparseReshape", "int32");
  if (o.rank !== 2) throw new Error(`Input indices should be Tensor2D but received shape
        ${o.shape}`);
  if (n.rank !== 1) throw new Error(`Input shape should be Tensor1D but received shape ${n.shape}`);
  if (s.rank !== 1) throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);
  let a = { inputIndices: o, inputShape: n, newShape: s }, i = T.runKernel(ei, a);
  return { outputIndices: i[0], outputShape: i[1] };
}
var VN = N({ sparseReshape_: Hj });
function Kj(r15, e, t10) {
  let o = v(r15, "data", "sparseSegmentMean"), n = v(e, "indices", "sparseSegmentMean", "int32"), s = v(t10, "segmentIds", "sparseSegmentMean", "int32");
  if (o.rank < 1) throw new Error("Data should be at least 1 dimensional but received scalar");
  if (n.rank !== 1) throw new Error(`Indices should be Tensor1D but received shape
          ${n.shape}`);
  if (s.rank !== 1) throw new Error(`Segment ids should be Tensor1D but received shape
          ${s.shape}`);
  let a = { data: o, indices: n, segmentIds: s };
  return T.runKernel(ya, a);
}
var WN = N({ sparseSegmentMean_: Kj });
function qj(r15, e, t10) {
  let o = v(r15, "data", "sparseSegmentSum"), n = v(e, "indices", "sparseSegmentSum", "int32"), s = v(t10, "segmentIds", "sparseSegmentSum", "int32");
  if (o.rank < 1) throw new Error("Data should be at least 1 dimensional but received scalar");
  if (n.rank !== 1) throw new Error(`Indices should be Tensor1D but received shape
         ${n.shape}`);
  if (s.rank !== 1) throw new Error(`Segment ids should be Tensor1D but received shape
         ${s.shape}`);
  let a = { data: o, indices: n, segmentIds: s };
  return T.runKernel(ba, a);
}
var UN = N({ sparseSegmentSum_: qj });
function jj(r15, e, t10, o, n, s, a, i) {
  let p = v(r15, "data", "stringNGrams", "string");
  if (p.dtype !== "string") throw new Error("Data must be of datatype string");
  if (p.shape.length !== 1) throw new Error(`Data must be a vector, saw: ${p.shape}`);
  let u = v(e, "dataSplits", "stringNGrams");
  if (u.dtype !== "int32") throw new Error("Data splits must be of datatype int32");
  let c = { separator: t10, nGramWidths: o, leftPad: n, rightPad: s, padWidth: a, preserveShortSequences: i }, l = { data: p, dataSplits: u }, m = T.runKernel(Ca, l, c);
  return { nGrams: m[0], nGramsSplits: m[1] };
}
var GN = N({ stringNGrams_: jj });
function Xj(r15, e, t10 = true) {
  let o = v(r15, "input", "stringSplit", "string"), n = v(e, "delimiter", "stringSplit", "string");
  if (o.rank !== 1) throw new Error(`Input should be Tensor1D but received shape ${o.shape}`);
  if (n.rank !== 0) throw new Error(`Delimiter should be a scalar but received shape ${n.shape}`);
  let s = { skipEmpty: t10 }, a = { input: o, delimiter: n }, i = T.runKernel(ji, a, s);
  return { indices: i[0], values: i[1], shape: i[2] };
}
var HN = N({ stringSplit_: Xj });
function Yj(r15, e) {
  let t10 = v(r15, "input", "stringToHashBucketFast", "string"), o = { numBuckets: e };
  if (e <= 0) throw new Error("Number of buckets must be at least 1");
  let n = { input: t10 };
  return T.runKernel(Xi, n, o);
}
var KN = N({ stringToHashBucketFast_: Yj });
function Qj(r15, e, t10, o = true) {
  let n = v(r15, "input", "staticRegexReplace", "string"), s = { pattern: e, rewrite: t10, replaceGlobal: o };
  return T.runKernel(Ru, { x: n }, s);
}
var qN = N({ staticRegexReplace_: Qj });
var Zj = { fft: uc, ifft: ju, rfft: pc, irfft: Hd };
var Jj = { hammingWindow: pN, hannWindow: Qd, frame: Zd, stft: cN };
var eX = { flipLeftRight: mN, grayscaleToRGB: dN, resizeNearestNeighbor: kN, resizeBilinear: vN, rgbToGrayscale: fN, rotateWithOffset: hN, cropAndResize: lN, nonMaxSuppression: gN, nonMaxSuppressionAsync: bN, nonMaxSuppressionWithScore: CN, nonMaxSuppressionWithScoreAsync: wN, nonMaxSuppressionPadded: SN, nonMaxSuppressionPaddedAsync: IN, threshold: NN, transform: TN };
var tX = { bandPart: _N, gramSchmidt: EN, qr: RN };
var rX = { absoluteDifference: DN, computeWeightedLoss: cr, cosineDistance: AN, hingeLoss: FN, huberLoss: PN, logLoss: ON, meanSquaredError: MN, sigmoidCrossEntropy: LN, softmaxCrossEntropy: BN };
var oX = { sparseFillEmptyRows: zN, sparseReshape: VN, sparseSegmentMean: WN, sparseSegmentSum: UN };
var nX = { stringNGrams: GN, stringSplit: HN, stringToHashBucketFast: KN, staticRegexReplace: qN };
var jN = {};
qe(jN, { Serializable: () => Rl, SerializationMap: () => rf, getRegisteredName: () => aX, registerClass: () => rS });
var sX = /* @__PURE__ */ new Map();
var tS = /* @__PURE__ */ new Map();
var Rl = class {
  getClassName() {
    return this.constructor.className;
  }
  static fromConfig(e, t10) {
    return new e(t10);
  }
};
var rf = class r5 {
  constructor() {
    this.classNameMap = {};
  }
  static getMap() {
    return r5.instance == null && (r5.instance = new r5()), r5.instance;
  }
  static register(e) {
    r5.getMap().classNameMap[e.className] = [e, e.fromConfig];
  }
};
function rS(r15, e, t10) {
  E(r15.className != null, () => "Class being registered does not have the static className property defined."), E(typeof r15.className == "string", () => "className is required to be a string, but got type " + typeof r15.className), E(r15.className.length > 0, () => "Class being registered has an empty-string as its className, which is disallowed."), typeof e == "undefined" && (e = "Custom"), typeof t10 == "undefined" && (t10 = r15.className);
  let o = t10, n = e + ">" + o;
  return rf.register(r15), sX.set(n, r15), tS.set(r15, n), r15;
}
function aX(r15) {
  return tS.has(r15) ? tS.get(r15) : r15.className;
}
var kr = class extends Rl {
  minimize(e, t10 = false, o) {
    let { value: n, grads: s } = this.computeGradients(e, o);
    if (o != null) {
      let a = o.map((i) => ({ name: i.name, tensor: s[i.name] }));
      this.applyGradients(a);
    } else this.applyGradients(s);
    return Ot(s), t10 ? n : (n.dispose(), null);
  }
  get iterations() {
    return this.iterations_ == null && (this.iterations_ = 0), this.iterations_;
  }
  incrementIterations() {
    this.iterations_ = this.iterations + 1;
  }
  computeGradients(e, t10) {
    return Vw(e, t10);
  }
  dispose() {
    this.iterations_ != null && Ot(this.iterations_);
  }
  async saveIterations() {
    return this.iterations_ == null && (this.iterations_ = 0), { name: "iter", tensor: ke(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(kr, Symbol.hasInstance, { value: (r15) => r15.minimize != null && r15.computeGradients != null && r15.applyGradients != null });
var Ju = class extends kr {
  static get className() {
    return "Adadelta";
  }
  constructor(e, t10, o = null) {
    super(), this.learningRate = e, this.rho = t10, this.epsilon = o, this.accumulatedGrads = [], this.accumulatedUpdates = [], o == null && (this.epsilon = T.backend.epsilon());
  }
  applyGradients(e) {
    (Array.isArray(e) ? e.map((o) => o.name) : Object.keys(e)).forEach((o, n) => {
      let s = T.registeredVariables[o], a = false;
      this.accumulatedGrads[n] == null && (this.accumulatedGrads[n] = { originalName: `${o}/accum_grad`, variable: De(() => Gt(s).variable(a)) }), this.accumulatedUpdates[n] == null && (this.accumulatedUpdates[n] = { originalName: `${o}/accum_var`, variable: De(() => Gt(s).variable(a)) });
      let i = Array.isArray(e) ? e[n].tensor : e[o];
      if (i == null) return;
      let p = this.accumulatedGrads[n].variable, u = this.accumulatedUpdates[n].variable;
      De(() => {
        let c = Ce(se(p, this.rho), se(Zt(i), 1 - this.rho)), l = se(je(Rr(Ce(u, this.epsilon)), Rr(Ce(p, this.epsilon))), i), m = Ce(se(u, this.rho), se(Zt(l), 1 - this.rho));
        p.assign(c), u.assign(m);
        let d = Ce(se(l, -this.learningRate), s);
        s.assign(d);
      });
    }), this.incrementIterations();
  }
  dispose() {
    this.accumulatedUpdates != null && (Ot(this.accumulatedGrads.map((e) => e.variable)), Ot(this.accumulatedUpdates.map((e) => e.variable)));
  }
  async getWeights() {
    let e = [...this.accumulatedGrads, ...this.accumulatedUpdates];
    return [await this.saveIterations()].concat(e.map((t10) => ({ name: t10.originalName, tensor: t10.variable })));
  }
  async setWeights(e) {
    e = await this.extractIterations(e);
    let t10 = e.length / 2, o = false;
    this.accumulatedGrads = e.slice(0, t10).map((n) => ({ originalName: n.name, variable: n.tensor.variable(o) })), this.accumulatedUpdates = e.slice(t10, t10 * 2).map((n) => ({ originalName: n.name, variable: n.tensor.variable(o) }));
  }
  getConfig() {
    return { learningRate: this.learningRate, rho: this.rho, epsilon: this.epsilon };
  }
  static fromConfig(e, t10) {
    return new e(t10.learningRate, t10.rho, t10.epsilon);
  }
};
var ep = class extends kr {
  static get className() {
    return "Adagrad";
  }
  constructor(e, t10 = 0.1) {
    super(), this.learningRate = e, this.initialAccumulatorValue = t10, this.accumulatedGrads = [];
  }
  applyGradients(e) {
    (Array.isArray(e) ? e.map((o) => o.name) : Object.keys(e)).forEach((o, n) => {
      let s = T.registeredVariables[o];
      this.accumulatedGrads[n] == null && (this.accumulatedGrads[n] = { originalName: `${o}/accumulator`, variable: De(() => $a(s.shape, this.initialAccumulatorValue).variable(false)) });
      let a = Array.isArray(e) ? e[n].tensor : e[o];
      if (a == null) return;
      let i = this.accumulatedGrads[n].variable;
      De(() => {
        let p = Ce(i, Zt(a));
        i.assign(p);
        let u = Ce(se(je(a, Rr(Ce(p, T.backend.epsilon()))), -this.learningRate), s);
        s.assign(u);
      });
    }), this.incrementIterations();
  }
  dispose() {
    this.accumulatedGrads != null && Ot(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 t10 = false;
    this.accumulatedGrads = e.map((o) => ({ originalName: o.name, variable: o.tensor.variable(t10) }));
  }
  getConfig() {
    return { learningRate: this.learningRate, initialAccumulatorValue: this.initialAccumulatorValue };
  }
  static fromConfig(e, t10) {
    return new e(t10.learningRate, t10.initialAccumulatorValue);
  }
};
var tp = class extends kr {
  static get className() {
    return "Adam";
  }
  constructor(e, t10, o, n = null) {
    super(), this.learningRate = e, this.beta1 = t10, this.beta2 = o, this.epsilon = n, this.accumulatedFirstMoment = [], this.accumulatedSecondMoment = [], De(() => {
      this.accBeta1 = ke(t10).variable(), this.accBeta2 = ke(o).variable();
    }), n == null && (this.epsilon = T.backend.epsilon());
  }
  applyGradients(e) {
    let t10 = Array.isArray(e) ? e.map((o) => o.name) : Object.keys(e);
    De(() => {
      let o = Te(1, this.accBeta1), n = Te(1, this.accBeta2);
      t10.forEach((s, a) => {
        let i = T.registeredVariables[s], p = false;
        this.accumulatedFirstMoment[a] == null && (this.accumulatedFirstMoment[a] = { originalName: `${s}/m`, variable: De(() => Gt(i).variable(p)) }), this.accumulatedSecondMoment[a] == null && (this.accumulatedSecondMoment[a] = { originalName: `${s}/v`, variable: De(() => Gt(i).variable(p)) });
        let u = Array.isArray(e) ? e[a].tensor : e[s];
        if (u == null) return;
        let c = this.accumulatedFirstMoment[a].variable, l = this.accumulatedSecondMoment[a].variable, m = Ce(se(c, this.beta1), se(u, 1 - this.beta1)), d = Ce(se(l, this.beta2), se(Zt(u), 1 - this.beta2)), f = je(m, o), h = je(d, n);
        c.assign(m), l.assign(d);
        let g = Ce(se(je(f, Ce(Rr(h), this.epsilon)), -this.learningRate), i);
        i.assign(g);
      }), this.accBeta1.assign(se(this.accBeta1, this.beta1)), this.accBeta2.assign(se(this.accBeta2, this.beta2));
    }), this.incrementIterations();
  }
  dispose() {
    this.accBeta1.dispose(), this.accBeta2.dispose(), this.accumulatedFirstMoment != null && Ot(this.accumulatedFirstMoment.map((e) => e.variable)), this.accumulatedSecondMoment != null && Ot(this.accumulatedSecondMoment.map((e) => e.variable));
  }
  async getWeights() {
    let e = [...this.accumulatedFirstMoment, ...this.accumulatedSecondMoment];
    return [await this.saveIterations()].concat(e.map((t10) => ({ name: t10.originalName, tensor: t10.variable })));
  }
  async setWeights(e) {
    e = await this.extractIterations(e), De(() => {
      this.accBeta1.assign(ui(this.beta1, this.iterations_ + 1)), this.accBeta2.assign(ui(this.beta2, this.iterations_ + 1));
    });
    let t10 = e.length / 2, o = false;
    this.accumulatedFirstMoment = e.slice(0, t10).map((n) => ({ originalName: n.name, variable: n.tensor.variable(o) })), this.accumulatedSecondMoment = e.slice(t10, t10 * 2).map((n) => ({ originalName: n.name, variable: n.tensor.variable(o) }));
  }
  getConfig() {
    return { learningRate: this.learningRate, beta1: this.beta1, beta2: this.beta2, epsilon: this.epsilon };
  }
  static fromConfig(e, t10) {
    return new e(t10.learningRate, t10.beta1, t10.beta2, t10.epsilon);
  }
};
var rp = class extends kr {
  static get className() {
    return "Adamax";
  }
  constructor(e, t10, o, n = null, s = 0) {
    super(), this.learningRate = e, this.beta1 = t10, this.beta2 = o, this.epsilon = n, this.decay = s, this.accumulatedFirstMoment = [], this.accumulatedWeightedInfNorm = [], De(() => {
      this.iteration = ke(0).variable(), this.accBeta1 = ke(t10).variable();
    }), n == null && (this.epsilon = T.backend.epsilon());
  }
  applyGradients(e) {
    let t10 = Array.isArray(e) ? e.map((o) => o.name) : Object.keys(e);
    De(() => {
      let o = Te(1, this.accBeta1), n = je(-this.learningRate, Ce(se(this.iteration, this.decay), 1));
      t10.forEach((s, a) => {
        let i = T.registeredVariables[s], p = false;
        this.accumulatedFirstMoment[a] == null && (this.accumulatedFirstMoment[a] = { originalName: `${s}/m`, variable: Gt(i).variable(p) }), this.accumulatedWeightedInfNorm[a] == null && (this.accumulatedWeightedInfNorm[a] = { originalName: `${s}/v`, variable: Gt(i).variable(p) });
        let u = Array.isArray(e) ? e[a].tensor : e[s];
        if (u == null) return;
        let c = this.accumulatedFirstMoment[a].variable, l = this.accumulatedWeightedInfNorm[a].variable, m = Ce(se(c, this.beta1), se(u, 1 - this.beta1)), d = se(l, this.beta2), f = Qt(u), h = Ad(d, f);
        c.assign(m), l.assign(h);
        let g = Ce(se(je(n, o), je(m, Ce(h, this.epsilon))), i);
        i.assign(g);
      }), this.iteration.assign(Ce(this.iteration, 1)), this.accBeta1.assign(se(this.accBeta1, this.beta1));
    }), this.incrementIterations();
  }
  dispose() {
    this.accBeta1.dispose(), this.iteration.dispose(), this.accumulatedFirstMoment != null && Ot(this.accumulatedFirstMoment.map((e) => e.variable)), this.accumulatedWeightedInfNorm != null && Ot(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, t10) {
    return new e(t10.learningRate, t10.beta1, t10.beta2, t10.epsilon, t10.decay);
  }
};
var mi = class extends kr {
  static get className() {
    return "SGD";
  }
  constructor(e) {
    super(), this.learningRate = e, this.setLearningRate(e);
  }
  applyGradients(e) {
    (Array.isArray(e) ? e.map((o) => o.name) : Object.keys(e)).forEach((o, n) => {
      let s = Array.isArray(e) ? e[n].tensor : e[o];
      if (s == null) return;
      let a = T.registeredVariables[o];
      De(() => {
        let i = Ce(se(this.c, s), a);
        a.assign(i);
      });
    }), this.incrementIterations();
  }
  setLearningRate(e) {
    this.learningRate = e, this.c != null && this.c.dispose(), this.c = $r(ke(-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, t10) {
    return new e(t10.learningRate);
  }
};
var op = class extends mi {
  static get className() {
    return "Momentum";
  }
  constructor(e, t10, o = false) {
    super(e), this.learningRate = e, this.momentum = t10, this.useNesterov = o, this.accumulations = [], this.m = ke(this.momentum);
  }
  applyGradients(e) {
    (Array.isArray(e) ? e.map((o) => o.name) : Object.keys(e)).forEach((o, n) => {
      let s = T.registeredVariables[o];
      this.accumulations[n] == null && (this.accumulations[n] = { originalName: `${o}/momentum`, variable: De(() => Gt(s).variable(false)) });
      let a = this.accumulations[n].variable, i = Array.isArray(e) ? e[n].tensor : e[o];
      i != null && De(() => {
        let p, u = Ce(se(this.m, a), i);
        this.useNesterov ? p = Ce(se(this.c, Ce(i, se(u, this.m))), s) : p = Ce(se(this.c, u), s), a.assign(u), s.assign(p);
      });
    }), this.incrementIterations();
  }
  dispose() {
    this.m.dispose(), this.accumulations != null && Ot(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 t10 = false;
    this.accumulations = e.map((o) => ({ originalName: o.name, variable: o.tensor.variable(t10) }));
  }
  getConfig() {
    return { learningRate: this.learningRate, momentum: this.momentum, useNesterov: this.useNesterov };
  }
  static fromConfig(e, t10) {
    return new e(t10.learningRate, t10.momentum, t10.useNesterov);
  }
};
var np = class extends kr {
  static get className() {
    return "RMSProp";
  }
  constructor(e, t10 = 0.9, o = 0, n = null, s = false) {
    if (super(), this.learningRate = e, this.decay = t10, this.momentum = o, this.epsilon = n, this.accumulatedMeanSquares = [], this.accumulatedMoments = [], this.accumulatedMeanGrads = [], this.centered = s, n == null && (this.epsilon = T.backend.epsilon()), e == null) throw new Error("learningRate for RMSPropOptimizer must be defined.");
  }
  applyGradients(e) {
    (Array.isArray(e) ? e.map((o) => o.name) : Object.keys(e)).forEach((o, n) => {
      let s = T.registeredVariables[o], a = false;
      this.accumulatedMeanSquares[n] == null && (this.accumulatedMeanSquares[n] = { originalName: `${o}/rms`, variable: De(() => Gt(s).variable(a)) }), this.accumulatedMoments[n] == null && (this.accumulatedMoments[n] = { originalName: `${o}/momentum`, variable: De(() => Gt(s).variable(a)) }), this.accumulatedMeanGrads[n] == null && this.centered && (this.accumulatedMeanGrads[n] = { originalName: `${o}/mg`, variable: De(() => Gt(s).variable(a)) });
      let i = Array.isArray(e) ? e[n].tensor : e[o];
      if (i == null) return;
      let p = this.accumulatedMeanSquares[n].variable, u = this.accumulatedMoments[n].variable;
      De(() => {
        let c = Ce(se(p, this.decay), se(Zt(i), 1 - this.decay));
        if (this.centered) {
          let l = this.accumulatedMeanGrads[n].variable, m = Ce(se(l, this.decay), se(i, 1 - this.decay)), d = je(se(i, this.learningRate), Rr(Te(c, Ce(Zt(m), this.epsilon)))), f = Ce(se(u, this.momentum), d);
          p.assign(c), l.assign(m), u.assign(f);
          let h = Te(s, f);
          s.assign(h);
        } else {
          let l = Ce(se(p, this.decay), se(Zt(i), 1 - this.decay)), m = Ce(se(u, this.momentum), je(se(i, this.learningRate), Rr(Ce(l, this.epsilon))));
          p.assign(l), u.assign(m);
          let d = Te(s, m);
          s.assign(d);
        }
      });
    }), this.incrementIterations();
  }
  dispose() {
    this.accumulatedMeanSquares != null && Ot(this.accumulatedMeanSquares.map((e) => e.variable)), this.accumulatedMeanGrads != null && this.centered && Ot(this.accumulatedMeanGrads.map((e) => e.variable)), this.accumulatedMoments != null && Ot(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((t10) => ({ name: t10.originalName, tensor: t10.variable })));
  }
  async setWeights(e) {
    e = await this.extractIterations(e);
    let t10 = this.centered ? e.length / 3 : e.length / 2, o = false;
    this.accumulatedMeanSquares = e.slice(0, t10).map((n) => ({ originalName: n.name, variable: n.tensor.variable(o) })), this.accumulatedMoments = e.slice(t10, t10 * 2).map((n) => ({ originalName: n.name, variable: n.tensor.variable(o) })), this.centered && (this.accumulatedMeanGrads = e.slice(t10 * 2, t10 * 3).map((n) => ({ originalName: n.name, variable: n.tensor.variable(o) })));
  }
  getConfig() {
    return { learningRate: this.learningRate, decay: this.decay, momentum: this.momentum, epsilon: this.epsilon, centered: this.centered };
  }
  static fromConfig(e, t10) {
    return new e(t10.learningRate, t10.decay, t10.momentum, t10.epsilon, t10.centered);
  }
};
var iX = [Ju, ep, tp, rp, op, np, mi];
function XN() {
  for (let r15 of iX) rS(r15);
}
var di = {};
qe(di, { CompositeArrayBuffer: () => ir, browserFiles: () => QN, browserHTTPRequest: () => tT, concatenateArrayBuffers: () => dk, copyModel: () => Tk, decodeWeights: () => sd, decodeWeightsStream: () => ad, encodeWeights: () => pk, fromMemory: () => rT, fromMemorySync: () => uS, getLoadHandlers: () => xk, getModelArtifactsForJSON: () => tc, getModelArtifactsForJSONSync: () => $w, getModelArtifactsInfoForJSON: () => va, getSaveHandlers: () => gk, getWeightSpecs: () => Sl, http: () => nf, isHTTPScheme: () => of, listModels: () => kk, loadWeights: () => JN, moveModel: () => _k, registerLoadRouter: () => hk, registerSaveRouter: () => fk, removeModel: () => Nk, weightsLoaderFactory: () => aS, withSaveHandler: () => oT, withSaveHandlerSync: () => nT });
var uX = "model";
var pX = ".json";
var cX = ".weights.bin";
function YN(r15) {
  return new Promise((e) => setTimeout(e)).then(r15);
}
var dc = class r7 {
  constructor(e) {
    if (!A().getBool("IS_BROWSER")) throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");
    e.startsWith(r7.URL_SCHEME) && (e = e.slice(r7.URL_SCHEME.length)), (e == null || e.length === 0) && (e = uX), this.modelJsonFileName = e + pX, this.weightDataFileName = e + cX;
  }
  async save(e) {
    if (typeof document == "undefined") throw new Error("Browser downloads are not supported in this environment since `document` is not present");
    let t10 = ir.join(e.weightData), o = window.URL.createObjectURL(new Blob([t10], { 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 }], s = id(e, n), a = window.URL.createObjectURL(new Blob([JSON.stringify(s)], { type: "application/json" })), i = this.modelJsonAnchor == null ? document.createElement("a") : this.modelJsonAnchor;
      if (i.download = this.modelJsonFileName, i.href = a, await YN(() => i.dispatchEvent(new MouseEvent("click"))), e.weightData != null) {
        let p = this.weightDataAnchor == null ? document.createElement("a") : this.weightDataAnchor;
        p.download = this.weightDataFileName, p.href = o, await YN(() => p.dispatchEvent(new MouseEvent("click")));
      }
      return { modelArtifactsInfo: va(e) };
    }
  }
};
dc.URL_SCHEME = "downloads://";
var oS = 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, t10) => {
      let o = new FileReader();
      o.onload = (n) => {
        let s = JSON.parse(n.target.result), a = s.modelTopology;
        if (a == null) {
          t10(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));
          return;
        }
        if (s.weightsManifest == null) {
          t10(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));
          return;
        }
        if (this.weightsFiles.length === 0) {
          e({ modelTopology: a });
          return;
        }
        let p = tc(s, (u) => this.loadWeights(u));
        e(p);
      }, o.onerror = (n) => t10(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`), o.readAsText(this.jsonFile);
    });
  }
  loadWeights(e) {
    let t10 = [], o = [];
    for (let a of e) t10.push(...a.weights), o.push(...a.paths);
    let n = this.checkManifestAndWeightFiles(e), s = o.map((a) => this.loadWeightsFile(a, n[a]));
    return Promise.all(s).then((a) => [t10, a]);
  }
  loadWeightsFile(e, t10) {
    return new Promise((o, n) => {
      let s = new FileReader();
      s.onload = (a) => {
        let i = a.target.result;
        o(i);
      }, s.onerror = (a) => n(`Failed to weights data from file of path '${e}'.`), s.readAsArrayBuffer(t10);
    });
  }
  checkManifestAndWeightFiles(e) {
    let t10 = [], o = this.weightsFiles.map((s) => Ew(s.name)), n = {};
    for (let s of e) s.paths.forEach((a) => {
      let i = Ew(a);
      if (t10.indexOf(i) !== -1) throw new Error(`Duplicate file basename found in weights manifest: '${i}'`);
      if (t10.push(i), o.indexOf(i) === -1) throw new Error(`Weight file with basename '${i}' is not provided.`);
      n[a] = this.weightsFiles[o.indexOf(i)];
    });
    if (t10.length !== this.weightsFiles.length) throw new Error(`Mismatch in the number of files in weights manifest (${t10.length}) and the number of weight files provided (${this.weightsFiles.length}).`);
    return n;
  }
};
var lX = (r15) => A().getBool("IS_BROWSER") && !Array.isArray(r15) && r15.startsWith(dc.URL_SCHEME) ? mX(r15.slice(dc.URL_SCHEME.length)) : null;
qt.registerSaveRouter(lX);
function mX(r15 = "model") {
  return new dc(r15);
}
function QN(r15) {
  return new oS(r15);
}
function nS(r15, e, t10, o) {
  a(r15), t10 = t10 == null ? 0 : t10, o = o == null ? 1 : o, i(t10, o);
  let n = 0, s = (p) => (p.then((u) => {
    let c = t10 + ++n / r15.length * (o - t10);
    return e(c), u;
  }), p);
  function a(p) {
    E(p != null && Array.isArray(p) && p.length > 0, () => "promises must be a none empty array");
  }
  function i(p, u) {
    E(p >= 0 && p <= 1, () => `Progress fraction must be in range [0, 1], but got startFraction ${p}`), E(u >= 0 && u <= 1, () => `Progress fraction must be in range [0, 1], but got endFraction ${u}`), E(u >= p, () => `startFraction must be no more than endFraction, but got startFraction ${p} and endFraction ${u}`);
  }
  return Promise.all(r15.map(s));
}
async function sS(r15, e) {
  e == null && (e = {});
  let t10 = e.fetchFunc == null ? A().platform.fetch : e.fetchFunc, o = r15.map((l) => t10(l, e.requestInit, { isBinary: true })), i = (e.onProgress == null ? await Promise.all(o) : await nS(o, e.onProgress, 0, 0.5)).map((l) => l.arrayBuffer());
  return e.onProgress == null ? await Promise.all(i) : await nS(i, e.onProgress, 0.5, 1);
}
function ZN(r15, e) {
  var t10;
  let o = e.fetchFunc == null ? A().platform.fetch : e.fetchFunc, n = 0, s;
  return (t10 = e.onProgress) === null || t10 === void 0 || t10.call(e, 0), new ReadableStream({ pull: async (a) => {
    for (var i; n < r15.length; ) {
      s || (s = (await o(r15[n], e.requestInit, { isBinary: true })).body.getReader());
      let { done: p, value: u } = await s.read();
      if (p) {
        n++, s = void 0, (i = e.onProgress) === null || i === void 0 || i.call(e, n / r15.length);
        continue;
      }
      a.enqueue(u);
      return;
    }
    a.close();
  } });
}
async function JN(r15, e = "", t10, o) {
  return aS((a) => sS(a, { requestInit: o }))(r15, e, t10);
}
function aS(r15) {
  return async (e, t10 = "", o) => {
    let n = e.map(() => false), s = {}, a = o != null ? o.map(() => false) : [], i = [];
    if (e.forEach((d, f) => {
      let h = 0;
      d.weights.forEach((g) => {
        let x = "quantization" in g ? g.quantization.dtype : g.dtype, b = si[x] * ze(g.shape), C = () => {
          n[f] = true, s[f] == null && (s[f] = []), s[f].push({ manifestEntry: g, groupOffset: h, sizeBytes: b });
        };
        o != null ? o.forEach((S, k) => {
          S === g.name && (C(), a[k] = true);
        }) : C(), i.push(g.name), h += b;
      });
    }), !a.every((d) => d)) {
      let d = o.filter((f, h) => !a[h]);
      throw new Error(`Could not find weights in manifest with names: ${d.join(", ")}. 
Manifest JSON has weights with names: ${i.join(", ")}.`);
    }
    let p = n.reduce((d, f, h) => (f && d.push(h), d), []), u = [];
    p.forEach((d) => {
      e[d].paths.forEach((f) => {
        let h = t10 + (t10.endsWith("/") ? "" : "/") + f;
        u.push(h);
      });
    });
    let c = await r15(u), l = {}, m = 0;
    return p.forEach((d) => {
      let f = e[d].paths.length, h = new ir(c.slice(m, m + f));
      s[d].forEach((x) => {
        let b = h.slice(x.groupOffset, x.groupOffset + x.sizeBytes), C = sd(b, [x.manifestEntry]);
        for (let S in C) l[S] = C[S];
      }), m += f;
    }), l;
  };
}
var dX = "application/octet-stream";
var fX = "application/json";
var Dl = class {
  constructor(e, t10) {
    if (this.DEFAULT_METHOD = "POST", t10 == null && (t10 = {}), this.weightPathPrefix = t10.weightPathPrefix, this.weightUrlConverter = t10.weightUrlConverter, t10.fetchFunc != null ? (E(typeof t10.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 = t10.fetchFunc) : this.fetch = A().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, t10.requestInit != null && t10.requestInit.body != null) throw new Error("requestInit is expected to have no pre-existing body, but has one.");
    this.requestInit = t10.requestInit || {}, this.loadOptions = t10;
  }
  async save(e) {
    if (e.modelTopology instanceof ArrayBuffer) throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");
    let t10 = Object.assign({ method: this.DEFAULT_METHOD }, this.requestInit);
    t10.body = new FormData();
    let o = [{ paths: ["./model.weights.bin"], weights: e.weightSpecs }], n = id(e, o);
    if (t10.body.append("model.json", new Blob([JSON.stringify(n)], { type: fX }), "model.json"), e.weightData != null) {
      let a = ir.join(e.weightData);
      t10.body.append("model.weights.bin", new Blob([a], { type: dX }), "model.weights.bin");
    }
    let s = await this.fetch(this.path, t10);
    if (s.ok) return { modelArtifactsInfo: va(e), responses: [s] };
    throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.status}.`);
  }
  async loadModelJSON() {
    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 t10;
    try {
      t10 = 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 o = t10.modelTopology, n = t10.weightsManifest;
    if (o == null && n == null) throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);
    return t10;
  }
  async load() {
    if (this.loadOptions.streamWeights) return this.loadStream();
    let e = await this.loadModelJSON();
    return tc(e, (t10) => this.loadWeights(t10));
  }
  async loadStream() {
    let e = await this.loadModelJSON(), t10 = await this.getWeightUrls(e.weightsManifest), o = Sl(e.weightsManifest), n = () => ZN(t10, this.loadOptions);
    return Object.assign(Object.assign({}, e), { weightSpecs: o, getWeightStream: n });
  }
  async getWeightUrls(e) {
    let t10 = Array.isArray(this.path) ? this.path[1] : this.path, [o, n] = hX(t10), s = this.weightPathPrefix || o, a = [], i = [];
    for (let p of e) for (let u of p.paths) this.weightUrlConverter != null ? i.push(this.weightUrlConverter(u)) : a.push(s + u + n);
    return this.weightUrlConverter && a.push(...await Promise.all(i)), a;
  }
  async loadWeights(e) {
    let t10 = await this.getWeightUrls(e), o = Sl(e), n = await sS(t10, this.loadOptions);
    return [o, n];
  }
};
Dl.URL_SCHEME_REGEX = /^https?:\/\//;
function hX(r15) {
  let e = r15.lastIndexOf("/"), t10 = r15.lastIndexOf("?"), o = r15.substring(0, e), n = t10 > e ? r15.substring(t10) : "";
  return [o + "/", n];
}
function of(r15) {
  return r15.match(Dl.URL_SCHEME_REGEX) != null;
}
var eT = (r15, e) => {
  if (typeof fetch == "undefined" && (e == null || e.fetchFunc == null)) return null;
  {
    let t10 = true;
    if (Array.isArray(r15) ? t10 = r15.every((o) => of(o)) : t10 = of(r15), t10) return nf(r15, e);
  }
  return null;
};
qt.registerSaveRouter(eT);
qt.registerLoadRouter(eT);
function nf(r15, e) {
  return new Dl(r15, e);
}
function tT(r15, e) {
  return nf(r15, e);
}
var Al = class {
  constructor(e) {
    this.modelArtifacts = e;
  }
  load() {
    return this.modelArtifacts;
  }
};
var sf = class {
  constructor(e) {
    this.saveHandler = e;
  }
  save(e) {
    return this.saveHandler(e);
  }
};
var iS = class {
  constructor(e) {
    e.load && (this.load = () => Promise.resolve(e.load())), e.save && (this.save = (t10) => Promise.resolve(e.save(t10)));
  }
};
function rT(r15, e, t10, o) {
  let n = arguments;
  return new iS(uS(...n));
}
function uS(r15, e, t10, o) {
  return arguments.length === 1 ? r15.modelTopology != null || r15.weightSpecs != null ? new Al(r15) : (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 Al({ modelTopology: r15 })) : (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 Al({ modelTopology: r15, weightSpecs: e, weightData: t10, trainingConfig: o }));
}
function oT(r15) {
  return new sf(r15);
}
function nT(r15) {
  return new sf(r15);
}
var aT = {};
qe(aT, { confusionMatrix: () => sT });
function gX(r15, e, t10) {
  let o = v(r15, "labels", "confusionMatrix"), n = v(e, "predictions", "confusionMatrix");
  E(t10 == null || t10 > 0 && Number.isInteger(t10), () => `If provided, numClasses must be a positive integer, but got ${t10}`), E(o.rank === 1, () => `Expected the rank of labels to be 1, but got ${o.rank}`), E(n.rank === 1, () => `Expected the rank of predictions to be 1, but got ${n.rank}`), E(o.shape[0] === n.shape[0], () => `Mismatch in the number of examples: ${o.shape[0]} vs. ${n.shape[0]}. Labels and predictions should have the same number of elements.`), E(t10 > 0 && Number.isInteger(t10), () => `numClasses is required to be a positive integer, but got ${t10}`);
  let s = El(Ue(o, "int32"), t10), a = El(Ue(n, "int32"), t10), i = mc(s), p = Ze(i, a);
  return Ue(p, "int32");
}
var sT = N({ confusionMatrix_: gX });
var cT = {};
qe(cT, { draw: () => vX, fromPixels: () => kX, fromPixelsAsync: () => wX, toPixels: () => IX });
var sp;
var iT = false;
function uT(r15, e = 3) {
  if (e > 4) throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");
  if (r15 == null) throw new Error("pixels passed to tf.browser.fromPixels() can not be null");
  let t10 = false, o = false, n = false, s = false, a = false, i = false;
  if (r15.data instanceof Uint8Array) t10 = true;
  else if (typeof ImageData != "undefined" && r15 instanceof ImageData) o = true;
  else if (typeof HTMLVideoElement != "undefined" && r15 instanceof HTMLVideoElement) n = true;
  else if (typeof HTMLImageElement != "undefined" && r15 instanceof HTMLImageElement) s = true;
  else if (r15.getContext != null) a = true;
  else if (typeof ImageBitmap != "undefined" && r15 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 ${r15.constructor.name}`);
  if (Xp(Du, T.backendName) != null) {
    let f = { pixels: r15 }, h = { numChannels: e };
    return T.runKernel(Du, f, h);
  }
  let [u, c] = n ? [r15.videoWidth, r15.videoHeight] : [r15.width, r15.height], l;
  if (a) l = r15.getContext("2d").getImageData(0, 0, u, c).data;
  else if (o || t10) l = r15.data;
  else if (s || n || i) {
    if (sp == null) if (typeof document == "undefined") if (typeof OffscreenCanvas != "undefined" && typeof OffscreenCanvasRenderingContext2D != "undefined") sp = new OffscreenCanvas(1, 1).getContext("2d");
    else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");
    else sp = document.createElement("canvas").getContext("2d", { willReadFrequently: true });
    sp.canvas.width = u, sp.canvas.height = c, sp.drawImage(r15, 0, 0, u, c), l = sp.getImageData(0, 0, u, c).data;
  }
  let m;
  if (e === 4) m = new Int32Array(l);
  else {
    let f = u * c;
    m = new Int32Array(f * e);
    for (let h = 0; h < f; h++) for (let g = 0; g < e; ++g) m[h * e + g] = l[h * 4 + g];
  }
  return jd(m, [c, u, e], "int32");
}
function xX(r15) {
  return r15 != null && r15.data instanceof Uint8Array;
}
function yX() {
  return typeof window != "undefined" && typeof ImageBitmap != "undefined" && window.hasOwnProperty("createImageBitmap");
}
function bX(r15) {
  return r15 != null && r15.width !== 0 && r15.height !== 0;
}
function CX(r15) {
  return yX() && !(r15 instanceof ImageBitmap) && bX(r15) && !xX(r15);
}
async function wX(r15, e = 3) {
  let t10 = null;
  if (A().getBool("WRAP_TO_IMAGEBITMAP") && CX(r15)) {
    let o;
    try {
      o = await createImageBitmap(r15, { premultiplyAlpha: "none" });
    } catch (n) {
      o = null;
    }
    o != null && o.width === r15.width && o.height === r15.height ? t10 = o : t10 = r15;
  } else t10 = r15;
  return uT(t10, e);
}
function pT(r15) {
  if (r15.rank !== 2 && r15.rank !== 3) throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${r15.rank}.`);
  let e = r15.rank === 2 ? 1 : r15.shape[2];
  if (e > 4 || e === 2) throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${e}`);
  if (r15.dtype !== "float32" && r15.dtype !== "int32") throw new Error(`Unsupported type for toPixels: ${r15.dtype}. Please use float32 or int32 tensors.`);
}
function SX(r15) {
  let e = (r15 == null ? void 0 : r15.alpha) || 1;
  if (e > 1 || e < 0) throw new Error(`Alpha value ${e} is suppoed to be in range [0 - 1].`);
}
async function IX(r15, e) {
  let t10 = v(r15, "img", "toPixels");
  if (!(r15 instanceof mt)) {
    let u = t10;
    t10 = Ue(u, "int32"), u.dispose();
  }
  pT(t10);
  let [o, n] = t10.shape.slice(0, 2), s = t10.rank === 2 ? 1 : t10.shape[2], a = await t10.data(), i = t10.dtype === "float32" ? 255 : 1, p = new Uint8ClampedArray(n * o * 4);
  for (let u = 0; u < o * n; ++u) {
    let c = [0, 0, 0, 255];
    for (let m = 0; m < s; m++) {
      let d = a[u * s + m];
      if (t10.dtype === "float32") {
        if (d < 0 || d > 1) throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${d}.`);
      } else if (t10.dtype === "int32" && (d < 0 || d > 255)) throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${d}.`);
      s === 1 ? (c[0] = d * i, c[1] = d * i, c[2] = d * i) : c[m] = d * i;
    }
    let l = u * 4;
    p[l + 0] = Math.round(c[0]), p[l + 1] = Math.round(c[1]), p[l + 2] = Math.round(c[2]), p[l + 3] = Math.round(c[3]);
  }
  if (e != null) {
    iT || Xp($u, T.backendName) != null && (console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."), iT = true), e.width = n, e.height = o;
    let u = e.getContext("2d"), c = new ImageData(p, n, o);
    u.putImageData(c, 0, 0);
  }
  return t10 !== r15 && t10.dispose(), p;
}
function vX(r15, e, t10) {
  let o = v(r15, "img", "draw");
  if (!(r15 instanceof mt)) {
    let a = o;
    o = Ue(a, "int32"), a.dispose();
  }
  pT(o), SX(t10 == null ? void 0 : t10.imageOptions);
  let n = { image: o }, s = { canvas: e, options: t10 };
  T.runKernel($u, n, s);
}
var kX = N({ fromPixels_: uT });
var af = {};
qe(af, { prepareAndValidate: () => lT });
function lT(r15, e) {
  let t10 = r15.shape.length, o = e.shape.length;
  if (t10 < 1) throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${t10}.`);
  if (o < 1) throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${o}.`);
  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[o - 1] > t10) throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${e.shape[o - 1]} vs. ${t10}`);
  if (ze(r15.shape) === 0) throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${r15.shape}.`);
  let n = e.shape, s = n[n.length - 1], a = 1;
  for (let l = 0; l < n.length - 1; ++l) a *= n[l];
  let i = r15.shape, p = n.slice();
  p.pop();
  let u = 1;
  for (let l = s; l < t10; ++l) u *= i[l], p.push(i[l]);
  let c = [...js(r15.shape).map((l) => l / u), 1].slice(0, s);
  return [p, a, u, c];
}
var pt = {};
qe(pt, { assertParamsValid: () => TX, computeFlatOffset: () => DX, computeOutShape: () => EX, getNormalizedAxes: () => $X, isSliceContinous: () => RX, maskToAxes: () => _X, parseSliceParams: () => AX, sliceInfo: () => FX, startForAxis: () => bT, startIndicesWithElidedDims: () => gT, stopForAxis: () => CT, stopIndicesWithElidedDims: () => xT, stridesForAxis: () => yT, stridesWithElidedDims: () => dT });
var pS = -2;
var NX = -1;
function TX(r15, e, t10) {
  let o = r15.shape.length;
  E(o === e.length, () => `Error in slice${o}D: Length of begin ${e} must match the rank of the array (${o}).`), E(o === t10.length, () => `Error in slice${o}D: Length of size ${t10} must match the rank of the array (${o}).`);
  for (let n = 0; n < o; ++n) E(e[n] + t10[n] <= r15.shape[n], () => `Error in slice${o}D: begin[${n}] + size[${n}] (${e[n] + t10[n]}) would overflow input.shape[${n}] (${r15.shape[n]})`);
}
function _X(r15) {
  let e = [], t10 = 0;
  for (; r15 > 0; ) r15 & 1 && e.push(t10), r15 /= 2, t10++;
  return e;
}
function EX(r15, e, t10) {
  let o = [];
  for (let n = 0; n < r15.length; n++) o[n] = Math.ceil((e[n] - r15[n]) / t10[n]);
  return o;
}
function dT(r15, e, t10, o) {
  let n = [...r15];
  for (let s = n.length; s < o.length; s++) n.push(1);
  for (let s = 0; s < t10; s++) s === 0 ? n[e] = 1 : (n.splice(e, 0, 1), n.pop());
  return n;
}
function fT(r15, e, t10) {
  return t10 <= r15 ? t10 : t10 - (e - 1);
}
function hT(r15, e) {
  let t10 = [];
  for (let o = 0; o < r15; o++) t10.push(e + o);
  return t10;
}
function $X(r15, e, t10, o, n, s, a, i, p) {
  let u = r15.length, c = new Array(u), l = new Array(u), m = new Array(u);
  if (e.length && t10 > 0) {
    let d = e[0], f = t10 + 1;
    c = gT(a, d, f, o, r15), l = xT(i, d, f, n, r15), m = dT(s, d, f, r15);
  } else for (let d = 0; d < u; d++) c[d] = bT(a, o, s, r15, d, p), l[d] = CT(i, n, s, r15, d, p), m[d] = yT(s, d, p);
  return { begin: c, end: l, strides: m };
}
function gT(r15, e, t10, o, n) {
  let s = [...n], a = hT(t10, e);
  for (let i = 0; i < s.length; i++) if (a.indexOf(i) > -1) s[i] = 0;
  else {
    let p = fT(e, t10, i), u = o[p];
    r15 & 1 << p && (u = 0), s[i] = u;
  }
  return s;
}
function xT(r15, e, t10, o, n) {
  let s = [...n], a = hT(t10, e);
  for (let i = 0; i < s.length; i++) if (a.indexOf(i) > -1) s[i] = Number.MAX_SAFE_INTEGER;
  else {
    let p = fT(e, t10, i), u = o[p];
    r15 & 1 << p && (u = Number.MAX_SAFE_INTEGER), s[i] = u;
  }
  for (let i = 0; i < s.length; i++) {
    let p = n[i];
    s[i] < 0 && (s[i] += p), s[i] = Vp(0, s[i], n[i]);
  }
  return s;
}
function yT(r15, e, t10) {
  let o = r15[e];
  return (t10 & 1 << e || o == null) && (o = 1), o;
}
function bT(r15, e, t10, o, n, s) {
  let a = e[n], i = t10[n] || 1;
  (r15 & 1 << n || s & 1 << n || a == null) && (i > 0 ? a = Number.MIN_SAFE_INTEGER : a = Number.MAX_SAFE_INTEGER);
  let p = o[n];
  return a < 0 && (a += p), a = Vp(0, a, p - 1), a;
}
function CT(r15, e, t10, o, n, s) {
  let a = e[n], i = t10[n] || 1;
  (r15 & 1 << n || s & 1 << n || a == null) && (i > 0 ? a = Number.MAX_SAFE_INTEGER : a = Number.MIN_SAFE_INTEGER);
  let p = o[n];
  return a < 0 && (a += p), i > 0 ? a = Vp(0, a, p) : a = Vp(-1, a, p - 1), a;
}
function RX(r15, e, t10) {
  let o = t10.length;
  for (let n = 0; n < t10.length; n++) if (t10[n] > 1) {
    o = n;
    break;
  }
  for (let n = o + 1; n < t10.length; n++) if (e[n] > 0 || t10[n] !== r15[n]) return false;
  return true;
}
function DX(r15, e) {
  let t10 = r15.length > 0 ? r15[r15.length - 1] : 1;
  for (let o = 0; o < r15.length - 1; o++) t10 += r15[o] * e[o];
  return t10;
}
function AX(r15, e, t10) {
  let o, n = r15.shape.length;
  typeof e == "number" ? o = [e, ...new Array(n - 1).fill(0)] : e.length < n ? o = e.concat(new Array(n - e.length).fill(0)) : o = e.slice(), o.forEach((a) => {
    E(a !== -1, () => "slice() does not support negative begin indexing.");
  });
  let s;
  return t10 == null ? s = new Array(n).fill(-1) : typeof t10 == "number" ? s = [t10, ...new Array(n - 1).fill(-1)] : t10.length < n ? s = t10.concat(new Array(n - t10.length).fill(-1)) : s = t10, 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}.`), r15.shape[i] - o[i])), [o, s];
}
function FX(r15, e, t10, o, n, s, a, i, p) {
  let u;
  if (o == null ? (u = new Array(e.length), u.fill(1)) : u = o, a != null && (a & a - 1) !== 0) throw new Error("Multiple ellipses in slice is not allowed.");
  let c = false, l = { dims: u.length, numAddAxisAfterEllipsis: 0, begin: e.slice(), end: t10.slice(), strides: u.slice(), beginMask: n, endMask: s, ellipsisMask: a, newAxisMask: i, shrinkAxisMask: p };
  for (let C = 0; C < l.dims; C++) c && (1 << C & i) !== 0 && l.numAddAxisAfterEllipsis++, 1 << C & a && (c = true);
  c || (l.ellipsisMask |= 1 << l.dims, l.dims++);
  let m = { dims: r15.length, beginMask: 0, endMask: 0, beginValid: false, endValid: false };
  PX(l, m);
  let d = true, f = true, h = true, g = [], x = [];
  for (let C = 0; C < r15.length; ++C) {
    if (m.strides[C] === 0) throw Error(`strides[${C}] must be non-zero`);
    let S = !!(m.shrinkAxisMask & 1 << C), k = r15[C];
    if (k === -1) {
      g.push(S ? 1 : -1);
      continue;
    }
    let _ = [m.beginMask & 1 << C, m.endMask & 1 << C], $ = [m.strides[C] > 0 ? 0 : -1, m.strides[C] > 0 ? k : k - 1];
    if (S && m.strides[C] <= 0) throw Error("only stride 1 allowed on non-range indexing.");
    h = h && m.strides[C] === 1;
    let R = !!(m.beginMask & 1 << C && m.endMask & 1 << C);
    if (m.beginValid && m.endValid) {
      if (S) {
        let M = m.begin[C] < 0 ? k + m.begin[C] : m.begin[C];
        if (m.begin[C] = M, m.end[C] = m.begin[C] + 1, M < 0 || M >= k) throw Error(`slice index ${m.begin[C]} of dimension ${C} out of bounds.`);
      } else m.begin[C] = mT(m.begin[C], 0, m.strides[C], k, _, $), m.end[C] = mT(m.end[C], 1, m.strides[C], k, _, $);
      let O = m.strides[C] === 1 && m.begin[C] === 0 && m.end[C] === k;
      d = d && O, f = f && (C === 0 && m.strides[C] === 1 || O);
    } else d = d && m.strides[C] === 1 && R, f = f && (C === 0 && m.strides[C] === 1 || R);
    let D, P = false;
    if (m.beginValid && m.endValid ? (D = m.end[C] - m.begin[C], P = true) : S ? (D = 1, P = true) : R && k >= 0 && (m.strides[C] < 0 ? D = -k : D = k, P = true), P) {
      let O;
      D === 0 || D < 0 != m.strides[C] < 0 ? O = 0 : O = Math.trunc(D / m.strides[C]) + (D % m.strides[C] !== 0 ? 1 : 0), g.push(O);
    } else g.push(-1);
  }
  for (let C = 0; C < m.finalShapeGatherIndices.length; ++C) {
    let S = m.finalShapeGatherIndices[C];
    S >= 0 ? x.push(g[S]) : S === pS && x.push(1);
  }
  return { finalShapeSparse: x.filter((C, S) => m.finalShapeGatherIndices[S] !== pS), finalShape: x, isIdentity: d, sliceDim0: f, isSimpleSlice: h, begin: m.begin, end: m.end, strides: m.strides };
}
function PX(r15, e) {
  e.beginMask = 0, e.endMask = 0, e.shrinkAxisMask = 0;
  let t10 = 0;
  e.beginValid = r15.begin != null, e.endValid = r15.end != null, e.begin = new Array(e.dims), e.end = new Array(e.dims), e.strides = new Array(e.dims), e.finalShapeGatherIndices = [], e.finalShapeGatherIndicesSparse = [], e.inputShapeGatherIndicesSparse = new Array(e.dims);
  for (let o = 0; o < r15.dims; o++) if (1 << o & r15.ellipsisMask) {
    let n = Math.min(e.dims - (r15.dims - o) + 1 + r15.numAddAxisAfterEllipsis, e.dims);
    for (; t10 < n; t10++) e.begin[t10] = 0, e.end[t10] = 0, e.strides[t10] = 1, e.beginMask |= 1 << t10, e.endMask |= 1 << t10, e.finalShapeGatherIndices.push(t10), e.finalShapeGatherIndicesSparse.push(-1), e.inputShapeGatherIndicesSparse[t10] = o;
  } else if (1 << o & r15.newAxisMask) e.finalShapeGatherIndices.push(pS), e.finalShapeGatherIndicesSparse.push(-1);
  else {
    if (t10 === e.begin.length) throw Error(`Index out of range using input dim ${t10}; input has only ${e.dims} dims, ${e.begin.length}.`);
    r15.begin != null && (e.begin[t10] = r15.begin[o]), r15.end != null && (e.end[t10] = r15.end[o]), e.strides[t10] = r15.strides[o], r15.beginMask & 1 << o && (e.beginMask |= 1 << t10), r15.endMask & 1 << o && (e.endMask |= 1 << t10), r15.shrinkAxisMask & 1 << o ? (e.finalShapeGatherIndices.push(NX), e.finalShapeGatherIndicesSparse.push(-1), e.shrinkAxisMask |= 1 << t10) : (e.finalShapeGatherIndices.push(t10), e.finalShapeGatherIndicesSparse.push(o)), e.inputShapeGatherIndicesSparse[t10] = o, t10++;
  }
}
function mT(r15, e, t10, o, n, s) {
  if (n[e]) return t10 > 0 ? s[e] : s[e + 1 & 1];
  {
    let a = r15 < 0 ? o + r15 : r15;
    return a < s[0] ? s[0] : a > s[1] ? s[1] : a;
  }
}
var OX = "4.22.0";
var Fl = class {
  static sgd(e) {
    return new mi(e);
  }
  static momentum(e, t10, o = false) {
    return new op(e, t10, o);
  }
  static rmsprop(e, t10 = 0.9, o = 0, n = null, s = false) {
    return new np(e, t10, o, n, s);
  }
  static adam(e = 1e-3, t10 = 0.9, o = 0.999, n = null) {
    return new tp(e, t10, o, n);
  }
  static adadelta(e = 1e-3, t10 = 0.95, o = null) {
    return new Ju(e, t10, o);
  }
  static adamax(e = 2e-3, t10 = 0.9, o = 0.999, n = null, s = 0) {
    return new rp(e, t10, o, n, s);
  }
  static adagrad(e, t10 = 0.1) {
    return new ep(e, t10);
  }
};
var OGe = Fl;
var MX = typeof requestAnimationFrame != "undefined" ? requestAnimationFrame : typeof setImmediate != "undefined" ? setImmediate : (r15) => r15();
function cS() {
  return new Promise((r15) => MX(() => r15()));
}
var w = {};
qe(w, { ERF_A1: () => e5, ERF_A2: () => t5, ERF_A3: () => r52, ERF_A4: () => o5, ERF_A5: () => n5, ERF_P: () => JX, PARALLELIZE_THRESHOLD: () => uf, RowPartitionType: () => Fa, SELU_SCALE: () => ZX, SELU_SCALEALPHA: () => QX, applyActivation: () => Qu, assertAndGetBroadcastShape: () => rt, assertAxesAreInnerMostDims: () => pK, assertParamsConsistent: () => LX, assignToTypedArray: () => c5, axesAreInnerMostDims: () => zw, calculateShapes: () => q1, checkEinsumDimSizes: () => g5, checkPadOnDimRoundingMode: () => Lt, combineLocations: () => I2, combineRaggedTensorToTensorShapes: () => zX, complexWithEvenIndex: () => i5, complexWithOddIndex: () => u5, computeConv2DInfo: () => zu, computeConv3DInfo: () => Uk, computeDefaultPad: () => Bw, computeDilation2DInfo: () => iH, computeOptimalWindowSize: () => GX, computeOutAndReduceShapes: () => uK, computeOutShape: () => BX, computePool2DInfo: () => Lw, computePool3DInfo: () => uH, convertConv2DDataFormat: () => Gk, decodeEinsumEquation: () => f5, eitherStridesOrDilationsAreOne: () => gr, expandShapeToKeepDim: () => ii, exponent: () => m5, exponents: () => l5, fromStringArrayToUint8: () => M5, fromUint8ToStringArray: () => O5, getAxesPermutation: () => cK, getBroadcastDims: () => y2, getComplexWithIndex: () => p5, getEinsumComputePath: () => x5, getEinsumPermutation: () => h5, getFusedBiasGradient: () => Yu, getFusedDyActivation: () => Xu, getImageCenter: () => HX, getInnerMostAxes: () => mK, getPermuted: () => qX, getRaggedRank: () => WX, getReductionAxes: () => xd, getReshaped: () => KX, getReshapedPermuted: () => jX, getRowPartitionTypesHelper: () => VX, getSliceBeginCoords: () => XX, getSliceSize: () => YX, getSparseFillEmptyRowsIndicesDenseShapeMismatch: () => w5, getSparseFillEmptyRowsNegativeIndexErrorMessage: () => S5, getSparseFillEmptyRowsOutOfRangeIndexErrorMessage: () => I5, getSparseReshapeEmptyTensorZeroOutputDimErrorMessage: () => N5, getSparseReshapeInputOutputMismatchErrorMessage: () => _5, getSparseReshapeInputOutputMultipleErrorMessage: () => T5, getSparseReshapeMultipleNegativeOneOutputDimErrorMessage: () => v5, getSparseReshapeNegativeOutputDimErrorMessage: () => k5, getSparseSegmentReductionIndicesOutOfRangeErrorMessage: () => D5, getSparseSegmentReductionNegativeSegmentIdsErrorMessage: () => E5, getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage: () => $5, getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage: () => R5, getUndoAxesPermutation: () => lK, isIdentityPermutation: () => y5, log: () => t4, mergeRealAndImagArrays: () => s5, prepareAndValidate: () => lT, prepareSplitSize: () => C5, segment_util: () => mS, shouldFuse: () => Zu, slice_util: () => pt, splitRealAndImagArrays: () => a5, stridesOrDilationsArePositive: () => Ta, tupleValuesAreOne: () => Bu, upcastType: () => dt, validateDefaultValueShape: () => UX, validateInput: () => lc, validateUpdateShape: () => Qw, warn: () => Ia });
function LX(r15, e) {
  let t10 = r15[0].length;
  r15.forEach((n, s) => {
    E(n.length === t10, () => `Error in concat${t10}D: rank of tensors[${s}] must be the same as the rank of the rest (${t10})`);
  }), E(e >= 0 && e < t10, () => `Error in concat${t10}D: axis must be between 0 and ${t10 - 1}.`);
  let o = r15[0];
  r15.forEach((n, s) => {
    for (let a = 0; a < t10; a++) E(a === e || n[a] === o[a], () => `Error in concat${t10}D: Shape of tensors[${s}] (${n}) does not match the shape of the rest (${o}) along the non-concatenated axis ${s}.`);
  });
}
function BX(r15, e) {
  let t10 = r15[0].slice();
  for (let o = 1; o < r15.length; o++) t10[e] += r15[o][e];
  return t10;
}
var Fa;
(function(r15) {
  r15[r15.FIRST_DIM_SIZE = 0] = "FIRST_DIM_SIZE", r15[r15.VALUE_ROWIDS = 1] = "VALUE_ROWIDS", r15[r15.ROW_LENGTHS = 2] = "ROW_LENGTHS", r15[r15.ROW_SPLITS = 3] = "ROW_SPLITS", r15[r15.ROW_LIMITS = 4] = "ROW_LIMITS", r15[r15.ROW_STARTS = 5] = "ROW_STARTS";
})(Fa || (Fa = {}));
function zX(r15, e, t10) {
  let o = new Array();
  if (t10 == null && e == null) return o;
  if (e == null) for (; o.length < r15 + t10.length; ) o.push(-1);
  else o = e.slice();
  if (t10 == null) return o;
  if (r15 + t10.length !== o.length) throw new Error(`rt input.shape and shape=${e} are incompatible: rt input.rank = ${r15 + t10.length}, but shape.rank = ${o.length}`);
  for (let n = 1; n < t10.length; ++n) {
    let s = t10[n], a = o[o.length - t10.length + n], i = o[a];
    if (s >= 0) if (i >= 0) {
      if (i !== s) throw new Error(`rt input.shape and shape=${e} are incompatible: rt input.shape[${n + r15}] = ${s} but shape[${n + r15}] = ${i}`);
    } else o[a] = s;
  }
  return o;
}
function VX(r15) {
  let e = { FIRST_DIM_SIZE: Fa.FIRST_DIM_SIZE, VALUE_ROWIDS: Fa.VALUE_ROWIDS, ROW_LENGTHS: Fa.ROW_LENGTHS, ROW_SPLITS: Fa.ROW_SPLITS, ROW_LIMITS: Fa.ROW_LIMITS, ROW_STARTS: Fa.ROW_STARTS }, t10 = [];
  for (let o of r15) if (o in e) t10.push(e[o]);
  else break;
  return t10;
}
function WX(r15) {
  return r15.length === 0 ? 0 : r15[0] === Fa.FIRST_DIM_SIZE ? r15.length - 1 : r15.length;
}
function UX(r15, e) {
  if (r15 == null || e == null) return;
  let t10 = r15.length, o = e.length;
  if (t10 >= o) throw new Error(`defaultValue.shape=${r15} and ragged tensor flatValues.shape=${e}, are incompatible: defaultValue.rank = ${t10} must be less than ragged tensor input flatValues.rank = ${o})`);
  for (let n = 0; n < Math.min(t10, o - 1); ++n) {
    let s = r15[n], a = e[n + 1];
    if (s >= 0 && a >= 0 && s !== 1 && s !== a) throw new Error(`defaultValue.shape=${r15}, and ragged tensor input flatValues.shape=${e} are incompatible: defaultValue.shape[${n - r15.length}] = ${s} but ragged tensor input.flatValues.shape[${n - r15.length}] = ${a}`);
  }
}
var uf = 30;
function GX(r15) {
  return r15 <= uf ? r15 : Up(r15, Math.floor(Math.sqrt(r15)));
}
function HX(r15, e, t10) {
  let o = t10 * (typeof r15 == "number" ? r15 : r15[0]), n = e * (typeof r15 == "number" ? r15 : r15[1]);
  return [o, n];
}
function KX(r15, e, t10, o = true) {
  let n = [];
  if (o) n = n.concat(e.slice(0)), n.push(r15[0] / t10), n = n.concat(r15.slice(1));
  else {
    n = n.concat(r15[0]);
    let s = e.length;
    for (let a = 0; a < s; ++a) n = n.concat([r15[a + 1] / e[a], e[a]]);
    n = n.concat(r15.slice(s + 1));
  }
  return n;
}
function qX(r15, e, t10 = true) {
  let o = [];
  if (t10) {
    o.push(e);
    for (let n = e + 1; n < r15; ++n) n <= 2 * e ? (o.push(n), o.push(n - (e + 1))) : o.push(n);
  } else {
    let n = [], s = [];
    for (let a = 1; a < r15; ++a) a >= e * 2 + 1 || a % 2 === 1 ? s.push(a) : n.push(a);
    o.push(...n), o.push(0), o.push(...s);
  }
  return o;
}
function jX(r15, e, t10, o = true) {
  let n = [];
  o ? n.push(r15[0] / t10) : n.push(r15[0] * t10);
  for (let s = 1; s < r15.length; ++s) s <= e.length ? o ? n.push(e[s - 1] * r15[s]) : n.push(r15[s] / e[s - 1]) : n.push(r15[s]);
  return n;
}
function XX(r15, e) {
  let t10 = [0];
  for (let o = 0; o < e; ++o) t10.push(r15[o][0]);
  return t10;
}
function YX(r15, e, t10) {
  let o = r15.slice(0, 1);
  for (let n = 0; n < t10; ++n) o.push(r15[n + 1] - e[n][0] - e[n][1]);
  return o;
}
var QX = 1.7580993408473768;
var ZX = 1.0507009873554805;
var JX = 0.3275911;
var e5 = 0.254829592;
var t5 = -0.284496736;
var r52 = 1.421413741;
var o5 = -1.453152027;
var n5 = 1.061405429;
function s5(r15, e) {
  if (r15.length !== e.length) throw new Error(`Cannot merge real and imag arrays of different lengths. real:${r15.length}, imag: ${e.length}.`);
  let t10 = new Float32Array(r15.length * 2);
  for (let o = 0; o < t10.length; o += 2) t10[o] = r15[o / 2], t10[o + 1] = e[o / 2];
  return t10;
}
function a5(r15) {
  let e = new Float32Array(r15.length / 2), t10 = new Float32Array(r15.length / 2);
  for (let o = 0; o < r15.length; o += 2) e[o / 2] = r15[o], t10[o / 2] = r15[o + 1];
  return { real: e, imag: t10 };
}
function i5(r15) {
  let e = Math.ceil(r15.length / 4), t10 = new Float32Array(e), o = new Float32Array(e);
  for (let n = 0; n < r15.length; n += 4) t10[Math.floor(n / 4)] = r15[n], o[Math.floor(n / 4)] = r15[n + 1];
  return { real: t10, imag: o };
}
function u5(r15) {
  let e = Math.floor(r15.length / 4), t10 = new Float32Array(e), o = new Float32Array(e);
  for (let n = 2; n < r15.length; n += 4) t10[Math.floor(n / 4)] = r15[n], o[Math.floor(n / 4)] = r15[n + 1];
  return { real: t10, imag: o };
}
function p5(r15, e) {
  let t10 = r15[e * 2], o = r15[e * 2 + 1];
  return { real: t10, imag: o };
}
function c5(r15, e, t10, o) {
  r15[o * 2] = e, r15[o * 2 + 1] = t10;
}
function l5(r15, e) {
  let t10 = new Float32Array(r15 / 2), o = new Float32Array(r15 / 2);
  for (let n = 0; n < Math.ceil(r15 / 2); n++) {
    let s = (e ? 2 : -2) * Math.PI * (n / r15);
    t10[n] = Math.cos(s), o[n] = Math.sin(s);
  }
  return { real: t10, imag: o };
}
function m5(r15, e, t10) {
  let o = (t10 ? 2 : -2) * Math.PI * (r15 / e), n = Math.cos(o), s = Math.sin(o);
  return { real: n, imag: s };
}
var lS = "->";
var d5 = /->/g;
var wT = ",";
var ST = "...";
function f5(r15, e) {
  r15 = r15.replace(/\s/g, "");
  let t10 = (r15.length - r15.replace(d5, "").length) / lS.length;
  if (t10 < 1) throw new Error("Equations without an arrow are not supported.");
  if (t10 > 1) throw new Error(`Equation must contain exactly one arrow ("${lS}").`);
  let [o, n] = r15.split(lS);
  E(o.indexOf(ST) === -1, () => `The ellipsis notation ("${ST}") is not supported yet.`);
  let s = o.split(wT), 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 < n.length; ++m) {
    let d = n[m];
    if (!s.some((f) => f.indexOf(d) !== -1)) throw new Error(`Output subscripts contain the label ${d} not present in the input subscripts.`);
    i.indexOf(d) === -1 && i.push(d);
  }
  for (let m = 0; m < o.length; ++m) {
    let d = o[m];
    i.indexOf(d) === -1 && d !== wT && i.push(d);
  }
  let p = 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.`);
    p[m] = [];
    for (let d = 0; d < s[m].length; ++d) p[m].push(i.indexOf(s[m][d]));
  }
  let u = i.length, c = n.length, l = [];
  for (let m = c; m < u; ++m) l.push(m);
  return { allDims: i, summedDims: l, idDims: p };
}
function h5(r15, e) {
  let t10 = new Array(r15);
  t10.fill(-1);
  for (let n = 0; n < e.length; ++n) t10[e[n]] = n;
  let o = [];
  for (let n = 0; n < r15; ++n) t10[n] === -1 && o.push(n);
  return t10 = t10.filter((n) => n !== -1), { permutationIndices: t10, expandDims: o };
}
function g5(r15, e, t10) {
  let o = new Array(r15);
  for (let n = 0; n < t10.length; ++n) {
    let s = t10[n].shape;
    for (let a = 0; a < e[n].length; ++a) o[e[n][a]] === void 0 ? o[e[n][a]] = s[a] : E(o[e[n][a]] === s[a], () => `Expected dimension ${o[e[n][a]]} at axis ${a} of input shaped ${JSON.stringify(s)}, but got dimension ${s[a]}`);
  }
}
function x5(r15, e) {
  let t10 = r15, o = [], n = 0;
  r15.length === 0 && t10.push(-1), n = r15.length + 1;
  for (let a = 0; a < n; ++a) o.push([]);
  let s = [];
  for (let a = 0; a < t10.length; ++a) {
    let i = t10[a], p = b5(e, i);
    for (let u of p) s.indexOf(u) === -1 && (o[a].push(u), s.push(u));
  }
  return { path: t10, steps: o };
}
function y5(r15) {
  return r15.every((e, t10) => e === t10);
}
function b5(r15, e) {
  let t10 = [];
  for (let o = 0; o < r15.length; ++o) (r15[o].length === 0 || r15[o].indexOf(e) !== -1 || e === -1) && t10.push(o);
  return t10;
}
function C5(r15, e, t10 = 0) {
  let o = [];
  if (typeof e == "number") E(r15.shape[t10] % e === 0, () => "Number of splits must evenly divide the axis."), o = new Array(e).fill(r15.shape[t10] / e);
  else {
    let n = e.reduce((a, i) => (i === -1 && (a += 1), a), 0);
    E(n <= 1, () => "There should be only one negative value in split array.");
    let s = e.indexOf(-1);
    if (s !== -1) {
      let a = e.reduce((i, p) => p > 0 ? i + p : i);
      e[s] = r15.shape[t10] - a;
    }
    E(r15.shape[t10] === e.reduce((a, i) => a + i), () => "The sum of sizes must match the size of the axis dimension."), o = e;
  }
  return o;
}
function w5(r15) {
  return `Received SparseTensor with denseShape[0] = 0 but
  indices.shape[0] = ${r15}`;
}
function S5(r15, e) {
  return `indices(${r15}, 0) is invalid: ${e} < 0`;
}
function I5(r15, e, t10) {
  return `indices(${r15}, 0) is invalid: ${e} >= ${t10}`;
}
function v5(r15, e) {
  return `only one output dimension may be -1, not both ${r15} and ${e}`;
}
function k5(r15, e) {
  return `size ${r15} must be non-negative, not ${e}`;
}
function N5() {
  return "reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero";
}
function T5(r15, e) {
  let t10 = ze(r15), o = ze(e);
  return `Input to reshape is a SparseTensor with ${t10}
  dense values, but the requested shape requires a multiple of ${o}. inputShape=${r15} outputShape= ${e}`;
}
function _5(r15, e) {
  let t10 = ze(r15), o = ze(e);
  return `Input to reshape is a tensor with ${t10} dense values, but the requested shape has ${o}. inputShape=${r15} outputShape=${e}`;
}
function E5() {
  return "segment ids must be >= 0";
}
function $5() {
  return "segment ids are not increasing";
}
function R5(r15, e) {
  return `Segment id ${r15} out of range [0, ${e}), possibly because segmentIds input is not sorted.`;
}
function D5(r15, e, t10) {
  return `Bad: indices[${r15}] == ${e} out of range [0, ${t10})`;
}
var mS = {};
qe(mS, { collectGatherOpShapeInfo: () => P5, computeOutShape: () => F5, segOpComputeOptimalWindowSize: () => A5 });
function A5(r15, e) {
  let t10 = false, o;
  for (r15 <= uf ? (o = r15, t10 = true) : o = Up(r15, Math.floor(Math.sqrt(r15))); !t10; ) o > e || o === r15 ? t10 = true : o = Up(r15, o + 1);
  return o;
}
function F5(r15, e, t10) {
  let o = [], n = r15.length;
  for (let s = 0; s < n; s++) s !== e ? o.push(r15[s]) : o.push(t10);
  return o;
}
function P5(r15, e, t10, o) {
  let n = e.shape.length, s = r15.shape.length;
  if (o !== 0 && (o < -n || o > n)) throw new Error(`Expect batchDims in the range of [-${n}, ${n}], but got ${o}`);
  if (o < 0 && (o += n), o > s) throw new Error(`batchDims (${o}) must be less than rank(x) (
    ${s}).`);
  if (t10 < o) throw new Error(`batchDims (${o}) must be less than or equal to axis (${t10}).`);
  for (let l = 0; l < o; ++l) if (r15.shape[l] !== e.shape[l]) throw new Error(`x.shape[${l}]: ${r15.shape[l]} should be equal to indices.shape[${l}]: ${e.shape[l]}.`);
  let a = r15.shape[t10], i = [], p = 1, u = 1, c = 1;
  for (let l = 0; l < o; ++l) i.push(r15.shape[l]), p *= r15.shape[l];
  for (let l = o; l < t10; l++) i.push(r15.shape[l]), u *= r15.shape[l];
  for (let l = o; l < n; l++) i.push(e.shape[l]);
  for (let l = t10 + 1; l < s; l++) i.push(r15.shape[l]), c *= r15.shape[l];
  return { batchSize: p, sliceSize: c, outerSize: u, dimSize: a, outputShape: i };
}
function O5(r15) {
  try {
    return r15.map((e) => Jp(e));
  } catch (e) {
    throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`);
  }
}
function M5(r15) {
  return r15.map((e) => Ji(e));
}
var Vt = {};
qe(Vt, { nonMaxSuppressionV3Impl: () => Jd, nonMaxSuppressionV4Impl: () => ef, nonMaxSuppressionV5Impl: () => tf, whereImpl: () => Xd });
XN();
var L5 = A();
L5.registerFlag("KEEP_INTERMEDIATE_TENSORS", () => false, (r15) => {
  r15 && console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.");
});
var Dr;
(function(r15) {
  r15[r15.DT_INVALID = 0] = "DT_INVALID", r15[r15.DT_FLOAT = 1] = "DT_FLOAT", r15[r15.DT_DOUBLE = 2] = "DT_DOUBLE", r15[r15.DT_INT32 = 3] = "DT_INT32", r15[r15.DT_UINT8 = 4] = "DT_UINT8", r15[r15.DT_INT16 = 5] = "DT_INT16", r15[r15.DT_INT8 = 6] = "DT_INT8", r15[r15.DT_STRING = 7] = "DT_STRING", r15[r15.DT_COMPLEX64 = 8] = "DT_COMPLEX64", r15[r15.DT_INT64 = 9] = "DT_INT64", r15[r15.DT_BOOL = 10] = "DT_BOOL", r15[r15.DT_QINT8 = 11] = "DT_QINT8", r15[r15.DT_QUINT8 = 12] = "DT_QUINT8", r15[r15.DT_QINT32 = 13] = "DT_QINT32", r15[r15.DT_BFLOAT16 = 14] = "DT_BFLOAT16", r15[r15.DT_QINT16 = 15] = "DT_QINT16", r15[r15.DT_QUINT16 = 16] = "DT_QUINT16", r15[r15.DT_UINT16 = 17] = "DT_UINT16", r15[r15.DT_COMPLEX128 = 18] = "DT_COMPLEX128", r15[r15.DT_HALF = 19] = "DT_HALF", r15[r15.DT_RESOURCE = 20] = "DT_RESOURCE", r15[r15.DT_VARIANT = 21] = "DT_VARIANT", r15[r15.DT_UINT32 = 22] = "DT_UINT32", r15[r15.DT_UINT64 = 23] = "DT_UINT64", r15[r15.DT_FLOAT_REF = 101] = "DT_FLOAT_REF", r15[r15.DT_DOUBLE_REF = 102] = "DT_DOUBLE_REF", r15[r15.DT_INT32_REF = 103] = "DT_INT32_REF", r15[r15.DT_UINT8_REF = 104] = "DT_UINT8_REF", r15[r15.DT_INT16_REF = 105] = "DT_INT16_REF", r15[r15.DT_INT8_REF = 106] = "DT_INT8_REF", r15[r15.DT_STRING_REF = 107] = "DT_STRING_REF", r15[r15.DT_COMPLEX64_REF = 108] = "DT_COMPLEX64_REF", r15[r15.DT_INT64_REF = 109] = "DT_INT64_REF", r15[r15.DT_BOOL_REF = 110] = "DT_BOOL_REF", r15[r15.DT_QINT8_REF = 111] = "DT_QINT8_REF", r15[r15.DT_QUINT8_REF = 112] = "DT_QUINT8_REF", r15[r15.DT_QINT32_REF = 113] = "DT_QINT32_REF", r15[r15.DT_BFLOAT16_REF = 114] = "DT_BFLOAT16_REF", r15[r15.DT_QINT16_REF = 115] = "DT_QINT16_REF", r15[r15.DT_QUINT16_REF = 116] = "DT_QUINT16_REF", r15[r15.DT_UINT16_REF = 117] = "DT_UINT16_REF", r15[r15.DT_COMPLEX128_REF = 118] = "DT_COMPLEX128_REF", r15[r15.DT_HALF_REF = 119] = "DT_HALF_REF", r15[r15.DT_RESOURCE_REF = 120] = "DT_RESOURCE_REF", r15[r15.DT_VARIANT_REF = 121] = "DT_VARIANT_REF", r15[r15.DT_UINT32_REF = 122] = "DT_UINT32_REF", r15[r15.DT_UINT64_REF = 123] = "DT_UINT64_REF";
})(Dr || (Dr = {}));
var IT;
(function(r15) {
  let e;
  (function(t10) {
    t10[t10.LEGACY = 0] = "LEGACY", t10[t10.V1 = 1] = "V1", t10[t10.V2 = 2] = "V2";
  })(e = r15.CheckpointFormatVersion || (r15.CheckpointFormatVersion = {}));
})(IT || (IT = {}));
var fS = {};
function z5(r15, e) {
  let t10 = { tfOpName: r15, category: "custom", inputs: [], attrs: [], customExecutor: e };
  fS[r15] = t10;
}
function pf(r15) {
  return fS[r15];
}
function V5(r15) {
  delete fS[r15];
}
function I(r15, e, t10, o, n) {
  let s = e.inputParams[r15];
  if (s && s.inputIndexStart !== void 0) {
    let i = s.inputIndexStart, p = s.inputIndexEnd === 0 ? void 0 : s.inputIndexEnd === void 0 ? i + 1 : s.inputIndexEnd, u = i < 0 ? e.inputNames.length + i : i;
    if (s.type === "tensor") return Bt(e.inputNames[u], t10, o, n);
    if (s.type === "tensors") {
      let m = e.inputs.slice(i, p);
      return e.inputNames.slice(i, p).filter((f, h) => {
        var g;
        return ((g = m[h]) === null || g === void 0 ? void 0 : g.op) !== "NoOp";
      }).map((f) => Bt(f, t10, o, n));
    }
    let c = Bt(e.inputNames[u], t10, o, n), l = c.dataSync();
    return s.type === "number" ? l[0] : y.toNestedArray(c.shape, l);
  }
  let a = e.attrParams[r15];
  return a && a.value;
}
function Bt(r15, e, t10, o) {
  let [n, s] = Nr(r15, t10);
  if (o != null) {
    let i = o.getHashTableHandleByName(n);
    if (i != null) return i;
  }
  let a = t10.currentContextIds.find((i) => !!e[cf(n, i)]);
  return a !== void 0 ? e[cf(n, a)][s] : void 0;
}
function hS(r15, e, t10) {
  return e[cf(r15, t10.currentContextId)];
}
function Ls(r15, e) {
  let [t10, o, n] = Nr(r15, e);
  return [cf(t10, e && e.currentContextId), o, n];
}
function cf(r15, e) {
  return e ? `${r15}-${e}` : r15;
}
function Nr(r15, e) {
  if (r15 === "") return ["", 0, void 0];
  let t10 = e != null && e.parseNodeNameCache != null;
  if (t10) {
    let s = e.parseNodeNameCache.get(r15);
    if (s != null) return s;
  }
  let o = r15.split(":"), n;
  if (o.length === 1) n = [r15, 0, void 0];
  else {
    let s = o[0], a = o.length === 3 ? o[1] : void 0, i = Number(o[o.length - 1]);
    n = [s, i, a];
  }
  return t10 && e.parseNodeNameCache.set(r15, n), n;
}
function Pl(r15, e, t10) {
  let o = I("pad", r15, e, t10);
  if (o === "explicit") {
    o = I("explicitPaddings", r15, e, t10);
    let n = [[0, 0], [0, 0], [0, 0], [0, 0]];
    for (let s = 0; s < 4; s++) n[s][0] = o[s * 2], n[s][1] = o[s * 2 + 1];
    return n;
  }
  return o;
}
function Bs(r15) {
  return r15.kept ? r15 : Ur(r15);
}
var gS = {};
qe(gS, { json: () => W5 });
var W5 = [{ 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 xS = {};
qe(xS, { json: () => U5 });
var U5 = [{ 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: "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 }] }, { tfOpName: "IsFinite", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "IsInf", category: "basic_math", inputs: [{ start: 0, name: "x", type: "tensor" }], attrs: [{ tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }];
var yS = {};
qe(yS, { json: () => G5 });
var G5 = [{ 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: "TensorListConcatV2", 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" }] }, { tfOpName: "TensorListLength", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }] }, { tfOpName: "TensorListResize", category: "control", inputs: [{ start: 0, name: "tensorListId", type: "tensor" }, { start: 1, name: "size", type: "number" }] }];
var bS = {};
qe(bS, { json: () => H5 });
var H5 = [{ 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", defaultValue: 0.2 }] }, { 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 CS = {};
qe(CS, { json: () => K5 });
var K5 = [{ 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" }] }, { 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: "RandomStandardNormal", category: "creation", inputs: [{ start: 0, name: "shape", type: "number[]" }], attrs: [{ tfName: "seed", name: "seed", type: "number", defaultValue: 0 }, { 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: "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: "RandomUniformInt", category: "creation", inputs: [{ start: 0, name: "shape", type: "number[]" }], attrs: [{ tfName: "minval", name: "minval", type: "number" }, { tfName: "maxval", name: "maxval", type: "number" }, { tfName: "seed", name: "seed", type: "number", defaultValue: 0 }, { tfName: "seed2", name: "seed2", type: "number", defaultValue: 0, 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 wS = {};
qe(wS, { json: () => q5 });
var q5 = [{ 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 SS = {};
qe(SS, { json: () => j5 });
var j5 = [{ tfOpName: "LowerBound", category: "evaluation", inputs: [{ start: 0, name: "sortedSequence", type: "tensor" }, { start: 1, name: "values", type: "tensor" }] }, { 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: "UpperBound", category: "evaluation", inputs: [{ start: 0, name: "sortedSequence", type: "tensor" }, { start: 1, name: "values", type: "tensor" }] }, { 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 IS = {};
qe(IS, { json: () => X5 });
var X5 = [{ 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 vS = {};
qe(vS, { json: () => Y5 });
var Y5 = [{ 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" }] }, { tfOpName: "InitializeTable", category: "hash_table", inputs: [{ start: 0, name: "tableHandle", type: "tensor" }, { start: 1, name: "keys", type: "tensor" }, { start: 2, name: "values", type: "tensor" }] }, { tfOpName: "InitializeTableV2", category: "hash_table", inputs: [{ start: 0, name: "tableHandle", type: "tensor" }, { start: 1, name: "keys", type: "tensor" }, { start: 2, name: "values", type: "tensor" }] }];
var kS = {};
qe(kS, { json: () => Q5 });
var Q5 = [{ 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" }] }, { tfOpName: "ImageProjectiveTransformV3", category: "image", inputs: [{ start: 0, name: "images", type: "tensor" }, { start: 1, name: "transforms", type: "tensor" }, { start: 2, name: "outputShape", type: "number[]" }, { start: 3, name: "fillValue", type: "number" }], attrs: [{ tfName: "interpolation", name: "interpolation", type: "string" }, { tfName: "fill_mode", name: "fillMode", type: "string" }] }];
var NS = {};
qe(NS, { json: () => Z5 });
var Z5 = [{ 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 }] }, { tfOpName: "BitwiseAnd", category: "logical", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "y", type: "tensor" }] }];
var TS = {};
qe(TS, { json: () => J5 });
var J5 = [{ 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: "leakyrelu_alpha", name: "leakyreluAlpha", type: "number", defaultValue: 0.2 }, { 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" }] }, { tfOpName: "MatrixBandPart", category: "matrices", inputs: [{ start: 0, name: "a", type: "tensor" }, { start: 1, name: "numLower", type: "tensor" }, { start: 1, name: "numUpper", type: "tensor" }] }];
var _S = {};
qe(_S, { json: () => e8 });
var e8 = [{ tfOpName: "EuclideanNorm", category: "normalization", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "axis", type: "number[]" }], attrs: [{ tfName: "keep_dims", name: "keepDims", type: "bool", defaultValue: false }] }, { 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" }] }];
var ES = {};
qe(ES, { json: () => t8 });
var t8 = [{ 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" }, { tfName: "T", name: "dtype", type: "dtype", notSupported: true }] }, { tfOpName: "Cumprod", 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" }] }, { 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 $S = {};
qe($S, { json: () => r8 });
var r8 = [{ 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 }] }, { tfOpName: "TensorScatterUpdate", category: "slice_join", inputs: [{ start: 0, name: "tensor", type: "tensor" }, { start: 1, name: "indices", type: "tensor" }, { start: 2, name: "values", type: "tensor" }] }];
var RS = {};
qe(RS, { json: () => o8 });
var o8 = [{ 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 DS = {};
qe(DS, { json: () => n8 });
var n8 = [{ 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 AS = {};
qe(AS, { json: () => s8 });
var s8 = [{ tfOpName: "StaticRegexReplace", category: "string", inputs: [{ start: 0, name: "input", type: "tensor" }], attrs: [{ tfName: "pattern", name: "pattern", type: "string" }, { tfName: "rewrite", name: "rewrite", type: "string" }, { tfName: "replace_global", name: "replaceGlobal", type: "bool" }] }, { 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 FS = {};
qe(FS, { json: () => a8 });
var a8 = [{ 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: "EnsureShape", 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 Ol = class {
  static get Instance() {
    return this._instance || (this._instance = new this());
  }
  constructor() {
    let e = [gS, xS, yS, bS, CS, wS, SS, IS, vS, kS, NS, TS, _S, ES, $S, RS, DS, AS, FS], t10 = [].concat(...e.map((o) => o.json));
    this.opMappers = t10.reduce((o, n) => (o[n.tfOpName] = n, o), {});
  }
  transformGraph(e, t10 = {}) {
    let o = e.node, n = [], s = [], a = [], i = o.reduce((h, g) => (h[g.name] = this.mapNode(g), g.op.startsWith("Placeholder") ? n.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), {}), p = [], u = [], c = {}, l = {};
    t10 != null && (c = this.mapSignatureEntries(t10.inputs), l = this.mapSignatureEntries(t10.outputs));
    let m = Object.keys(i);
    m.forEach((h) => {
      let g = i[h];
      g.inputNames.forEach((x, b) => {
        let [C, , S] = Ls(x), k = i[C];
        if (k.outputs != null) {
          let _ = k.outputs.indexOf(S);
          if (_ !== -1) {
            let $ = `${C}:${_}`;
            g.inputNames[b] = $;
          }
        }
        g.inputs.push(k), k.children.push(g);
      });
    }), Object.keys(l).length === 0 ? m.forEach((h) => {
      let g = i[h];
      g.children.length === 0 && u.push(g);
    }) : Object.keys(l).forEach((h) => {
      let [g] = Ls(h), x = i[g];
      x != null && (x.signatureKey = l[h], u.push(x));
    }), Object.keys(c).length > 0 ? Object.keys(c).forEach((h) => {
      let [g] = Ls(h), x = i[g];
      x && (x.signatureKey = c[h], p.push(x));
    }) : p = n;
    let d = {};
    e.library != null && e.library.function != null && (d = e.library.function.reduce((h, g) => (h[g.signature.name] = this.mapFunction(g), h), {}));
    let f = { nodes: i, inputs: p, outputs: u, weights: s, placeholders: n, signature: t10, functions: d };
    return a.length > 0 && (f.initNodes = a), f;
  }
  mapSignatureEntries(e) {
    return Object.keys(e || {}).reduce((t10, o) => (t10[e[o].name] = o, t10), {});
  }
  mapNode(e) {
    let t10 = pf(e.op) || this.opMappers[e.op] || {};
    e.attr == null && (e.attr = {});
    let o = { name: e.name, op: e.op, category: t10.category, inputNames: (e.input || []).map((n) => n.startsWith("^") ? n.slice(1) : n), inputs: [], children: [], inputParams: {}, attrParams: {}, rawAttrs: e.attr, outputs: t10.outputs };
    return t10.inputs != null && (o.inputParams = t10.inputs.reduce((n, s) => (n[s.name] = { type: s.type, inputIndexStart: s.start, inputIndexEnd: s.end }, n), {})), t10.attrs != null && (o.attrParams = t10.attrs.reduce((n, s) => {
      let a = s.type, i;
      switch (s.type) {
        case "string":
          i = lf(e.attr, s.tfName, s.defaultValue), i === void 0 && s.tfDeprecatedName && (i = lf(e.attr, s.tfDeprecatedName, s.defaultValue));
          break;
        case "string[]":
          i = yf(e.attr, s.tfName, s.defaultValue), i === void 0 && s.tfDeprecatedName && (i = yf(e.attr, s.tfDeprecatedName, s.defaultValue));
          break;
        case "number":
          i = df(e.attr, s.tfName, s.defaultValue || 0), i === void 0 && s.tfDeprecatedName && (i = df(e.attr, s.tfDeprecatedName, s.defaultValue));
          break;
        case "number[]":
          i = xf(e.attr, s.tfName, s.defaultValue), i === void 0 && s.tfDeprecatedName && (i = xf(e.attr, s.tfDeprecatedName, s.defaultValue));
          break;
        case "bool":
          i = mf(e.attr, s.tfName, s.defaultValue), i === void 0 && s.tfDeprecatedName && (i = mf(e.attr, s.tfDeprecatedName, s.defaultValue));
          break;
        case "bool[]":
          i = Cf(e.attr, s.tfName, s.defaultValue), i === void 0 && s.tfDeprecatedName && (i = Cf(e.attr, s.tfDeprecatedName, s.defaultValue));
          break;
        case "shape":
          i = gf(e.attr, s.tfName, s.defaultValue), i === void 0 && s.tfDeprecatedName && (i = gf(e.attr, s.tfDeprecatedName, s.defaultValue));
          break;
        case "shape[]":
          i = bf(e.attr, s.tfName, s.defaultValue), i === void 0 && s.tfDeprecatedName && (i = bf(e.attr, s.tfDeprecatedName, s.defaultValue));
          break;
        case "dtype":
          i = ff(e.attr, s.tfName, s.defaultValue), i === void 0 && s.tfDeprecatedName && (i = ff(e.attr, s.tfDeprecatedName, s.defaultValue));
          break;
        case "dtype[]":
          i = hf(e.attr, s.tfName, s.defaultValue), i === void 0 && s.tfDeprecatedName && (i = hf(e.attr, s.tfDeprecatedName, s.defaultValue));
          break;
        case "func":
          i = vT(e.attr, s.tfName, s.defaultValue), i === void 0 && s.tfDeprecatedName && (i = vT(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 n[s.name] = { value: i, type: a }, n;
    }, {})), o;
  }
  mapFunction(e) {
    let t10 = e.nodeDef, o = [], n = [], s = {};
    t10 != null && (s = t10.reduce((l, m) => (l[m.name] = this.mapNode(m), m.op === "Const" && n.push(l[m.name]), l), {}));
    let a = [], i = [];
    e.signature.inputArg.forEach((l) => {
      let [m] = Ls(l.name), d = { name: m, op: "Placeholder", inputs: [], inputNames: [], category: "graph", inputParams: {}, attrParams: { dtype: { value: PS(l.type), type: "dtype" } }, children: [] };
      d.signatureKey = l.name, a.push(d), s[m] = d;
    }), Object.keys(s).forEach((l) => {
      let m = s[l];
      m.inputNames.forEach((d, f) => {
        let [h, , g] = Ls(d), x = s[h];
        if (x.outputs != null) {
          let b = x.outputs.indexOf(g);
          if (b !== -1) {
            let C = `${h}:${b}`;
            m.inputNames[f] = C;
          }
        }
        m.inputs.push(x), x.children.push(m);
      });
    });
    let u = e.ret;
    e.signature.outputArg.forEach((l) => {
      let [m, d] = Ls(u[l.name]), f = s[m];
      f != null && (f.defaultOutput = d, i.push(f));
    });
    let c = this.mapArgsToSignature(e);
    return { nodes: s, inputs: a, outputs: i, weights: n, placeholders: o, signature: c };
  }
  mapArgsToSignature(e) {
    return { methodName: e.signature.name, inputs: e.signature.inputArg.reduce((t10, o) => (t10[o.name] = this.mapArgToTensorInfo(o), t10), {}), outputs: e.signature.outputArg.reduce((t10, o) => (t10[o.name] = this.mapArgToTensorInfo(o, e.ret), t10), {}) };
  }
  mapArgToTensorInfo(e, t10) {
    let o = e.name;
    return t10 != null && (o = t10[o]), { name: o, dtype: e.type };
  }
};
function i8(r15) {
  let e = A().global;
  if (typeof e.atob != "undefined") return e.atob(r15);
  if (typeof Buffer != "undefined") return new Buffer(r15, "base64").toString();
  throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()");
}
function kT(r15, e) {
  let t10 = Array.isArray(r15) ? String.fromCharCode.apply(null, r15) : i8(r15);
  return e ? t10 : t10.toLowerCase();
}
function lf(r15, e, t10, o = false) {
  let n = r15[e];
  return n != null ? kT(n.s, o) : t10;
}
function mf(r15, e, t10) {
  let o = r15[e];
  return o ? o.b : t10;
}
function df(r15, e, t10) {
  let o = r15[e] || {}, n = o.i != null ? o.i : o.f != null ? o.f : t10;
  return typeof n == "number" ? n : parseInt(n, 10);
}
function PS(r15) {
  switch (typeof r15 == "string" && (r15 = Dr[r15]), r15) {
    case Dr.DT_FLOAT:
    case Dr.DT_HALF:
      return "float32";
    case Dr.DT_INT32:
    case Dr.DT_INT64:
    case Dr.DT_INT8:
    case Dr.DT_UINT8:
      return "int32";
    case Dr.DT_BOOL:
      return "bool";
    case Dr.DT_DOUBLE:
      return "float32";
    case Dr.DT_STRING:
      return "string";
    case Dr.DT_COMPLEX64:
    case Dr.DT_COMPLEX128:
      return "complex64";
    default:
      return null;
  }
}
function vT(r15, e, t10) {
  let o = r15[e];
  return o && o.func ? o.func.name : t10;
}
function ff(r15, e, t10) {
  let o = r15[e];
  return o && o.type ? PS(o.type) : t10;
}
function hf(r15, e, t10) {
  let o = r15[e];
  return o && o.list && o.list.type ? o.list.type.map((n) => PS(n)) : t10;
}
function NT(r15) {
  if (!r15.unknownRank) return r15.dim != null ? r15.dim.map((e) => typeof e.size == "number" ? e.size : parseInt(e.size, 10)) : [];
}
function gf(r15, e, t10) {
  let o = r15[e];
  return o && o.shape ? NT(o.shape) : t10;
}
function xf(r15, e, t10) {
  let o = r15[e];
  return o ? ((o.list.f && o.list.f.length ? o.list.f : o.list.i) || []).map((n) => typeof n == "number" ? n : parseInt(n, 10)) : t10;
}
function yf(r15, e, t10, o = false) {
  let n = r15[e];
  return n && n.list && n.list.s ? n.list.s.map((s) => kT(s, o)) : t10;
}
function bf(r15, e, t10) {
  let o = r15[e];
  return o && o.list && o.list.shape ? o.list.shape.map((n) => NT(n)) : t10;
}
function Cf(r15, e, t10) {
  let o = r15[e];
  return o && o.list && o.list.b ? o.list.b : t10;
}
var wf = class {
  constructor(e, t10, o) {
    this.node = e, this.tensorMap = t10, this.context = o, this.inputs = [], this.attrs = {}, this.inputs = e.inputNames.map((n) => this.getInput(n)), e.rawAttrs != null && (this.attrs = Object.keys(e.rawAttrs).reduce((n, s) => (n[s] = this.getAttr(s), n), {}));
  }
  getInput(e) {
    return Bt(e, this.tensorMap, this.context);
  }
  getAttr(e, t10) {
    let o = this.node.rawAttrs[e];
    if (o.tensor != null) return Bt(e, this.tensorMap, this.context);
    if (o.i != null || o.f != null) return df(this.node.rawAttrs, e, t10);
    if (o.s != null) return lf(this.node.rawAttrs, e, t10);
    if (o.b != null) return mf(this.node.rawAttrs, e, t10);
    if (o.shape != null) return gf(this.node.rawAttrs, e, t10);
    if (o.type != null) return ff(this.node.rawAttrs, e, t10);
    if (o.list != null) {
      if (o.list.i != null || o.list.f != null) return xf(this.node.rawAttrs, e, t10);
      if (o.list.s != null) return yf(this.node.rawAttrs, e, t10);
      if (o.list.shape != null) return bf(this.node.rawAttrs, e, t10);
      if (o.list.b != null) return Cf(this.node.rawAttrs, e, t10);
      if (o.list.type != null) return hf(this.node.rawAttrs, e, t10);
    }
    return t10;
  }
};
var Je = {};
qe(Je, { OP_SCOPE_SUFFIX: () => Nw, abs: () => Qt, acos: () => Rk, acosh: () => Dk, add: () => Ce, addN: () => Ak, all: () => Fk, any: () => Pk, argMax: () => Ok, argMin: () => Mk, asin: () => Lk, asinh: () => Bk, atan: () => zk, atan2: () => Vk, atanh: () => Wk, avgPool: () => dd, avgPool3d: () => Hk, basicLSTMCell: () => Kk, batchNorm: () => nu, batchNorm2d: () => jk, batchNorm3d: () => Xk, batchNorm4d: () => Yk, batchToSpaceND: () => fd, bincount: () => hd, bitwiseAnd: () => Qk, booleanMaskAsync: () => L6, broadcastArgs: () => Zk, broadcastTo: () => su, buffer: () => me, cast: () => Ue, ceil: () => Jk, clipByValue: () => e2, clone: () => Ur, complex: () => Er, concat: () => yt, concat1d: () => t2, concat2d: () => r22, concat3d: () => o2, concat4d: () => n2, conv1d: () => s2, conv2d: () => au, conv2dTranspose: () => a2, conv3d: () => i2, conv3dTranspose: () => p2, cos: () => c2, cosh: () => l2, cosineWindow: () => $l, cumprod: () => m2, cumsum: () => d2, denseBincount: () => f2, depthToSpace: () => h2, depthwiseConv2d: () => sc, diag: () => g2, dilation2d: () => x2, div: () => je, divNoNan: () => b2, dot: () => C2, dropout: () => Y6, einsum: () => iu, elu: () => bd, enclosingPowerOfTwo: () => Zw, ensureShape: () => w2, equal: () => yd, erf: () => S2, euclideanNorm: () => k2, exp: () => _o, expandDims: () => Ms, expm1: () => N2, eye: () => Cd, fft: () => uc, fill: () => $a, floor: () => wd, floorDiv: () => md, fused: () => Jw, gather: () => Sd, gatherND: () => j6, greater: () => Wu, greaterEqual: () => Id, ifft: () => ju, imag: () => pu, image: () => eX, inTopKAsync: () => Z6, irfft: () => Hd, isFinite: () => T2, isInf: () => _2, isNaN: () => E2, leakyRelu: () => vd, less: () => Tl, lessEqual: () => ac, linalg: () => tX, linspace: () => $2, localResponseNormalization: () => R2, log: () => pi, log1p: () => kd, logSigmoid: () => D2, logSoftmax: () => A2, logSumExp: () => _d, logicalAnd: () => Uu, logicalNot: () => Ed, logicalOr: () => $d, logicalXor: () => F2, losses: () => rX, lowerBound: () => P2, matMul: () => Ze, max: () => Ra, maxPool: () => Dd, maxPool3d: () => O2, maxPoolWithArgmax: () => M2, maximum: () => Ad, mean: () => Gu, meshgrid: () => L2, min: () => Nl, minimum: () => Hu, mirrorPad: () => B2, mod: () => z2, moments: () => V2, movingAverage: () => V6, mul: () => se, multiRNNCell: () => W2, multinomial: () => U2, neg: () => pr, norm: () => Vu, notEqual: () => Fd, oneHot: () => El, ones: () => Da, onesLike: () => G2, op: () => N, outerProduct: () => H2, pad: () => Aa, pad1d: () => K2, pad2d: () => q2, pad3d: () => j2, pad4d: () => X2, pool: () => Y2, pow: () => ui, prelu: () => Od, print: () => ld, prod: () => Q2, raggedGather: () => Z2, raggedRange: () => J2, raggedTensorToTensor: () => e1, rand: () => t1, randomGamma: () => S1, randomNormal: () => Wd, randomStandardNormal: () => I1, randomUniform: () => ic, randomUniformInt: () => v1, range: () => cu, real: () => ci, reciprocal: () => k1, relu: () => lu, relu6: () => Ud, reshape: () => W, reverse: () => mo, reverse1d: () => N1, reverse2d: () => T1, reverse3d: () => _1, reverse4d: () => E1, rfft: () => pc, round: () => Gd, rsqrt: () => $1, scalar: () => ke, scatterND: () => U6, searchSorted: () => _l, selu: () => R1, separableConv2d: () => D1, setdiff1dAsync: () => A1, sigmoid: () => Ea, sign: () => F1, signal: () => Jj, sin: () => P1, sinh: () => O1, slice: () => Xe, slice1d: () => M1, slice2d: () => L1, slice3d: () => B1, slice4d: () => z1, softmax: () => V1, softplus: () => Td, spaceToBatchND: () => Pd, sparse: () => oX, sparseToDense: () => K6, spectral: () => Zj, split: () => li, sqrt: () => Rr, square: () => Zt, squaredDifference: () => Kd, squeeze: () => cc, stack: () => vr, step: () => qd, stridedSlice: () => W1, string: () => nX, sub: () => Te, sum: () => ot, tan: () => U1, tanh: () => kl, tensor: () => ar, tensor1d: () => Jt, tensor2d: () => mu, tensor3d: () => jd, tensor4d: () => G1, tensor5d: () => H1, tensor6d: () => K1, tensorScatterUpdate: () => j1, tile: () => uu, topk: () => X1, transpose: () => mc, truncatedNormal: () => Y1, unique: () => Q1, unsortedSegmentSum: () => Z1, unstack: () => fo, upperBound: () => J1, variable: () => eN, where: () => lo, whereAsync: () => Yd, zeros: () => Gr, zerosLike: () => Gt });
var TT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "BiasAdd":
    case "AddV2":
    case "Add":
      return [o.add(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "AddN":
      return [o.addN(I("tensors", r15, e, t10))];
    case "FloorMod":
    case "Mod":
      return [o.mod(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "Mul":
      return [o.mul(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "RealDiv":
    case "Div":
      return [o.div(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "DivNoNan":
      return [o.divNoNan(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "FloorDiv":
      return [o.floorDiv(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "Sub":
      return [o.sub(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "Minimum":
      return [o.minimum(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "Maximum":
      return [o.maximum(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "Pow":
      return [o.pow(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "SquaredDifference":
      return [o.squaredDifference(I("a", r15, e, t10), I("b", r15, e, t10))];
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var _T = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "Abs":
    case "ComplexAbs":
      return [o.abs(I("x", r15, e, t10))];
    case "Acos":
      return [o.acos(I("x", r15, e, t10))];
    case "Acosh":
      return [o.acosh(I("x", r15, e, t10))];
    case "Asin":
      return [o.asin(I("x", r15, e, t10))];
    case "Asinh":
      return [o.asinh(I("x", r15, e, t10))];
    case "Atan":
      return [o.atan(I("x", r15, e, t10))];
    case "Atan2":
      return [o.atan2(I("x", r15, e, t10), I("y", r15, e, t10))];
    case "Atanh":
      return [o.atanh(I("x", r15, e, t10))];
    case "Ceil":
      return [o.ceil(I("x", r15, e, t10))];
    case "Complex":
      return [o.complex(I("real", r15, e, t10), I("imag", r15, e, t10))];
    case "Cos":
      return [o.cos(I("x", r15, e, t10))];
    case "Cosh":
      return [o.cosh(I("x", r15, e, t10))];
    case "Elu":
      return [o.elu(I("x", r15, e, t10))];
    case "Erf":
      return [o.erf(I("x", r15, e, t10))];
    case "Exp":
      return [o.exp(I("x", r15, e, t10))];
    case "Expm1":
      return [o.expm1(I("x", r15, e, t10))];
    case "Floor":
      return [o.floor(I("x", r15, e, t10))];
    case "Log":
      return [o.log(I("x", r15, e, t10))];
    case "Log1p":
      return [o.log1p(I("x", r15, e, t10))];
    case "Imag":
      return [o.imag(I("x", r15, e, t10))];
    case "Neg":
      return [o.neg(I("x", r15, e, t10))];
    case "Reciprocal":
      return [o.reciprocal(I("x", r15, e, t10))];
    case "Real":
      return [o.real(I("x", r15, e, t10))];
    case "Relu":
      return [o.relu(I("x", r15, e, t10))];
    case "Round":
      return [o.round(I("x", r15, e, t10))];
    case "Selu":
      return [o.selu(I("x", r15, e, t10))];
    case "Sigmoid":
      return [o.sigmoid(I("x", r15, e, t10))];
    case "Sin":
      return [o.sin(I("x", r15, e, t10))];
    case "Sign":
      return [o.sign(I("x", r15, e, t10))];
    case "Sinh":
      return [o.sinh(I("x", r15, e, t10))];
    case "Softplus":
      return [o.softplus(I("x", r15, e, t10))];
    case "Sqrt":
      return [o.sqrt(I("x", r15, e, t10))];
    case "Square":
      return [o.square(I("x", r15, e, t10))];
    case "Tanh":
      return [o.tanh(I("x", r15, e, t10))];
    case "Tan":
      return [o.tan(I("x", r15, e, t10))];
    case "ClipByValue":
      return [o.clipByValue(I("x", r15, e, t10), I("clipValueMin", r15, e, t10), I("clipValueMax", r15, e, t10))];
    case "Relu6":
      return [o.relu6(I("x", r15, e, t10))];
    case "Rsqrt":
      return [o.rsqrt(Bt(r15.inputNames[0], e, t10))];
    case "LeakyRelu":
      return [o.leakyRelu(I("x", r15, e, t10), I("alpha", r15, e, t10))];
    case "Prelu":
      return [o.prelu(I("x", r15, e, t10), I("alpha", r15, e, t10))];
    case "IsNan":
      return [o.isNaN(Bt(r15.inputNames[0], e, t10))];
    case "IsInf":
      return [o.isInf(Bt(r15.inputNames[0], e, t10))];
    case "IsFinite":
      return [o.isFinite(Bt(r15.inputNames[0], e, t10))];
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
function Hr(r15, e, t10 = "") {
  if (!(typeof r15 == "number" || typeof e == "number")) {
    y.assert(r15.length === e.length, () => t10 + ` Shapes ${r15} and ${e} must match`);
    for (let o = 0; o < r15.length; o++) {
      let n = r15[o], s = e[o];
      y.assert(n < 0 || s < 0 || n === s, () => t10 + ` Shapes ${r15} and ${e} must match`);
    }
  }
}
function ET(r15) {
  return !(typeof r15 == "number" || r15.some((e) => e < 0));
}
function fc(r15, e, t10) {
  let o = Sf(r15, t10), n = !ET(o);
  if (n && e.length === 0) throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${o}`);
  if (n && e.forEach((s) => {
    o = Sf(s.shape, o);
  }), !ET(o)) throw new Error(`Non-fully-defined elementShape: ${o}`);
  return o;
}
function Sf(r15, e) {
  if (typeof r15 == "number") return e;
  if (typeof e == "number") return r15;
  if (r15.length !== e.length) throw new Error(`Incompatible ranks during merge: ${r15} vs. ${e}`);
  let t10 = [];
  for (let o = 0; o < r15.length; ++o) {
    let n = r15[o], s = e[o];
    if (n >= 0 && s >= 0 && n !== s) throw new Error(`Incompatible shape during merge: ${r15} vs. ${e}`);
    t10[o] = n >= 0 ? n : s;
  }
  return t10;
}
var If = class {
  constructor(e, t10, o, n, s, a, i) {
    this.name = e, this.dtype = t10, this.maxSize = o, this.elementShape = n, this.identicalElementShapes = s, this.dynamicSize = a, this.clearAfterRead = i, this.tensors = [], this.closed_ = false, this.idTensor = ke(0), $r(this.idTensor);
  }
  get id() {
    return this.idTensor.id;
  }
  get closed() {
    return this.closed_;
  }
  clearAndClose(e) {
    this.tensors.forEach((t10) => {
      (e == null || !e.has(t10.tensor.id)) && t10.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 t10 = this.tensors[e];
    if (t10.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 && (t10.cleared = true), t10.read = true, t10.tensor;
  }
  readMany(e) {
    return e.map((t10) => this.read(t10));
  }
  write(e, t10) {
    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 o = this.tensors[e] || {};
    if (t10.dtype !== this.dtype) throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},
          because the value dtype is ${t10.dtype}, but TensorArray dtype is ${this.dtype}.`);
    if (this.size() === 0 && (this.elementShape == null || this.elementShape.length === 0) && (this.elementShape = t10.shape), Hr(this.elementShape, t10.shape, `TensorArray ${this.name}: Could not write to TensorArray index ${e}.`), o.read) throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);
    if (o.written) throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);
    o.tensor = t10, $r(t10), o.written = true, this.tensors[e] = o;
  }
  writeMany(e, t10) {
    if (e.length !== t10.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: ${t10.length}.`);
    e.forEach((o, n) => this.write(o, t10[n]));
  }
  gather(e, t10) {
    if (t10 && t10 !== this.dtype) throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t10}`);
    if (e) e = e.slice(0, this.size());
    else {
      e = [];
      for (let n = 0; n < this.size(); n++) e.push(n);
    }
    if (e.length === 0) return ar([], [0].concat(this.elementShape));
    let o = this.readMany(e);
    return Hr(this.elementShape, o[0].shape, "TensorArray shape mismatch: "), vr(o, 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 ar([], [0].concat(this.elementShape));
    let t10 = [];
    for (let n = 0; n < this.size(); n++) t10.push(n);
    let o = this.readMany(t10);
    return Hr(this.elementShape, o[0].shape, `TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${o[0].shape})`), yt(o, 0);
  }
  scatter(e, t10) {
    if (t10.dtype !== this.dtype) throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t10.dtype}`);
    if (e.length !== t10.shape[0]) throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t10.shape[0]}`);
    let o = Math.max(...e);
    if (!this.dynamicSize && o >= this.maxSize) throw new Error(`Max index must be < array size (${o}  vs. ${this.maxSize})`);
    this.writeMany(e, fo(t10, 0));
  }
  split(e, t10) {
    if (t10.dtype !== this.dtype) throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t10.dtype}`);
    let o = 0, n = e.map((p) => (o += p, o));
    if (o !== t10.shape[0]) throw new Error(`Expected sum of lengths to be equal to
          tensor.shape[0], but sum of lengths is
        ${o}, and tensor's shape is: ${t10.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 = o === 0 ? 0 : t10.size / o, a = [];
    De(() => {
      t10 = W(t10, [1, o, s]);
      for (let p = 0; p < e.length; ++p) {
        let c = [0, p === 0 ? 0 : n[p - 1], 0], l = [1, e[p], s];
        a[p] = W(Xe(t10, c, l), this.elementShape);
      }
      return a;
    });
    let i = [];
    for (let p = 0; p < e.length; p++) i[p] = p;
    this.writeMany(i, a);
  }
};
var hc = class r9 {
  get id() {
    return this.idTensor.id;
  }
  constructor(e, t10, o, n = -1) {
    this.tensors = e, this.elementShape = t10, this.elementDtype = o, e != null && e.forEach((s) => {
      if (o !== s.dtype) throw new Error(`Invalid data types; op elements ${o}, but list elements ${s.dtype}`);
      Hr(t10, s.shape, "TensorList shape mismatch: "), $r(s);
    }), this.idTensor = ke(0), this.maxNumElements = n, $r(this.idTensor);
  }
  copy() {
    return new r9([...this.tensors], this.elementShape, this.elementDtype);
  }
  clearAndClose(e) {
    this.tensors.forEach((t10) => {
      (e == null || !e.has(t10.id)) && t10.dispose();
    }), this.tensors.length = 0, this.idTensor.dispose();
  }
  size() {
    return this.tensors.length;
  }
  stack(e, t10, o = -1) {
    if (t10 !== this.elementDtype) throw new Error(`Invalid data types; op elements ${t10}, but list elements ${this.elementDtype}`);
    if (o !== -1 && this.tensors.length !== o) throw new Error(`Operation expected a list with ${o} elements but got a list with ${this.tensors.length} elements.`);
    Hr(e, this.elementShape, "TensorList shape mismatch: ");
    let n = fc(this.elementShape, this.tensors, e);
    return De(() => {
      let s = this.tensors.map((a) => W(a, n));
      return vr(s, 0);
    });
  }
  popBack(e, t10) {
    if (t10 !== this.elementDtype) throw new Error(`Invalid data types; op elements ${t10}, but list elements ${this.elementDtype}`);
    if (this.size() === 0) throw new Error("Trying to pop from an empty list.");
    let o = fc(this.elementShape, this.tensors, e), n = this.tensors.pop();
    return n.kept = false, Hr(n.shape, e, "TensorList shape mismatch: "), W(n, o);
  }
  pushBack(e) {
    if (e.dtype !== this.elementDtype) throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);
    if (Hr(e.shape, this.elementShape, "TensorList shape mismatch: "), this.maxNumElements === this.size()) throw new Error("Trying to push element into a full list.");
    $r(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}.`);
    let t10 = new r9([], this.elementShape, this.elementDtype, this.maxNumElements);
    t10.tensors.length = e;
    for (let o = 0; o < Math.min(this.tensors.length, e); ++o) t10.tensors[o] = this.tensors[o];
    return t10;
  }
  getItem(e, t10, o) {
    if (o !== this.elementDtype) throw new Error(`Invalid data types; op elements ${o}, 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.`);
    Hr(this.tensors[e].shape, t10, "TensorList shape mismatch: ");
    let n = fc(this.elementShape, this.tensors, t10);
    return W(this.tensors[e], n);
  }
  setItem(e, t10) {
    if (t10.dtype !== this.elementDtype) throw new Error(`Invalid data types; op elements ${t10.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.`);
    Hr(this.elementShape, t10.shape, "TensorList shape mismatch: "), $r(t10), this.tensors[e] != null && (this.tensors[e].kept = false), this.tensors[e] = t10;
  }
  gather(e, t10, o) {
    if (t10 !== this.elementDtype) throw new Error(`Invalid data types; op elements ${t10}, but list elements ${this.elementDtype}`);
    Hr(this.elementShape, o, "TensorList shape mismatch: "), e = e.slice(0, this.size());
    let n = fc(this.elementShape, this.tensors, o);
    return e.length === 0 ? ar([], [0].concat(n)) : De(() => {
      let s = e.map((a) => W(this.tensors[a], n));
      return vr(s, 0);
    });
  }
  concat(e, t10) {
    if (e && e !== this.elementDtype) throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);
    Hr(this.elementShape, t10, "TensorList shape mismatch: ");
    let o = fc(this.elementShape, this.tensors, t10);
    return this.size() === 0 ? ar([], [0].concat(o)) : De(() => {
      let n = this.tensors.map((s) => W(s, o));
      return yt(n, 0);
    });
  }
};
function $T(r15, e, t10) {
  let o = r15.dtype;
  if (r15.shape.length < 1) throw new Error(`Tensor must be at least a vector, but saw shape: ${r15.shape}`);
  if (r15.dtype !== t10) throw new Error(`Invalid data types; op elements ${r15.dtype}, but list elements ${t10}`);
  let n = r15.shape.slice(1);
  Hr(n, e, "TensorList shape mismatch: ");
  let s = fo(r15);
  return new hc(s, e, o);
}
function RT(r15, e, t10, o) {
  return new hc([], r15, e, o);
}
function DT(r15, e, t10, o) {
  if (e.length !== r15.shape[0]) throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${r15.shape[0]}`);
  let n = Math.max(...e);
  if (o != null && o !== -1 && n >= o) throw new Error(`Max index must be < array size (${n}  vs. ${o})`);
  let s = new hc([], t10, r15.dtype, o), a = fo(r15, 0);
  return e.forEach((i, p) => {
    s.setItem(i, a[p]);
  }), s;
}
function AT(r15, e, t10) {
  let o = 0, n = e.map((c) => (o += c, o));
  if (o !== r15.shape[0]) throw new Error(`Expected sum of lengths to be equal to
          tensor.shape[0], but sum of lengths is
        ${o}, and tensor's shape is: ${r15.shape}`);
  let s = r15.shape.slice(1), a = Sf(s, t10), i = o === 0 ? 0 : r15.size / o, p = De(() => {
    let c = [];
    r15 = W(r15, [1, o, i]);
    for (let l = 0; l < e.length; ++l) {
      let d = [0, l === 0 ? 0 : n[l - 1], 0], f = [1, e[l], i];
      c[l] = W(Xe(r15, d, f), a);
    }
    return r15.dispose(), c;
  }), u = new hc([], t10, r15.dtype, e.length);
  for (let c = 0; c < p.length; c++) u.setItem(c, p[c]);
  return u;
}
var FT = async (r15, e, t10) => {
  switch (r15.op) {
    case "If":
    case "StatelessIf": {
      let o = I("thenBranch", r15, e, t10), n = I("elseBranch", r15, e, t10), s = I("cond", r15, e, t10), a = I("args", r15, e, t10);
      return (await s.data())[0] ? t10.functionMap[o].executeFunctionAsync(a, t10.tensorArrayMap, t10.tensorListMap) : t10.functionMap[n].executeFunctionAsync(a, t10.tensorArrayMap, t10.tensorListMap);
    }
    case "While":
    case "StatelessWhile": {
      let o = I("body", r15, e, t10), n = I("cond", r15, e, t10), s = I("args", r15, e, t10), a = await t10.functionMap[n].executeFunctionAsync(s, t10.tensorArrayMap, t10.tensorListMap), i = s.map((c) => c.id), p = await a[0].data();
      a.forEach((c) => {
        !c.kept && i.indexOf(c.id) === -1 && c.dispose();
      });
      let u = s;
      for (; p[0]; ) {
        let c = u;
        u = await t10.functionMap[o].executeFunctionAsync(u, t10.tensorArrayMap, t10.tensorListMap);
        let l = u.map((d) => d.id);
        c.forEach((d) => {
          !d.kept && i.indexOf(d.id) === -1 && l.indexOf(d.id) === -1 && d.dispose();
        });
        let m = await t10.functionMap[n].executeFunctionAsync(u, t10.tensorArrayMap, t10.tensorListMap);
        p = await m[0].data(), m.forEach((d) => {
          !d.kept && i.indexOf(d.id) === -1 && l.indexOf(d.id) === -1 && d.dispose();
        });
      }
      return u;
    }
    case "LoopCond": {
      let o = I("pred", r15, e, t10);
      return [Bs(o)];
    }
    case "Switch": {
      let o = I("pred", r15, e, t10), n = I("data", r15, e, t10);
      return n.kept || (n = Bs(n)), (await o.data())[0] ? [void 0, n] : [n, void 0];
    }
    case "Merge": {
      let o = r15.inputNames.find((n) => Bt(n, e, t10) !== void 0);
      if (o) {
        let n = Bt(o, e, t10);
        return [Bs(n)];
      }
      return;
    }
    case "Enter": {
      let o = I("frameName", r15, e, t10), n = I("tensor", r15, e, t10);
      return t10.enterFrame(o), [Bs(n)];
    }
    case "Exit": {
      let o = I("tensor", r15, e, t10);
      return t10.exitFrame(), [Bs(o)];
    }
    case "NextIteration": {
      let o = I("tensor", r15, e, t10);
      return t10.nextIteration(), [Bs(o)];
    }
    case "TensorArrayV3": {
      let o = I("size", r15, e, t10), n = I("dtype", r15, e, t10), s = I("elementShape", r15, e, t10), a = I("dynamicSize", r15, e, t10), i = I("clearAfterRead", r15, e, t10), p = I("identicalElementShapes", r15, e, t10), u = I("name", r15, e, t10), c = new If(u, n, o, s, p, a, i);
      return t10.addTensorArray(c), [c.idTensor, ke(1)];
    }
    case "TensorArrayWriteV3": {
      let o = I("tensorArrayId", r15, e, t10), n = I("index", r15, e, t10), s = I("tensor", r15, e, t10), a = t10.getTensorArray(o.id);
      return a.write(n, s), [a.idTensor];
    }
    case "TensorArrayReadV3": {
      let o = I("tensorArrayId", r15, e, t10), n = I("index", r15, e, t10);
      return [t10.getTensorArray(o.id).read(n)];
    }
    case "TensorArrayGatherV3": {
      let o = I("tensorArrayId", r15, e, t10), n = I("indices", r15, e, t10), s = I("dtype", r15, e, t10);
      return [t10.getTensorArray(o.id).gather(n, s)];
    }
    case "TensorArrayScatterV3": {
      let o = I("tensorArrayId", r15, e, t10), n = I("indices", r15, e, t10), s = I("tensor", r15, e, t10), a = t10.getTensorArray(o.id);
      return a.scatter(n, s), [a.idTensor];
    }
    case "TensorArrayConcatV3": {
      let o = I("tensorArrayId", r15, e, t10), n = t10.getTensorArray(o.id), s = I("dtype", r15, e, t10);
      return [n.concat(s)];
    }
    case "TensorArraySplitV3": {
      let o = I("tensorArrayId", r15, e, t10), n = I("tensor", r15, e, t10), s = I("lengths", r15, e, t10), a = t10.getTensorArray(o.id);
      return a.split(s, n), [a.idTensor];
    }
    case "TensorArraySizeV3": {
      let o = I("tensorArrayId", r15, e, t10), n = t10.getTensorArray(o.id);
      return [ke(n.size(), "int32")];
    }
    case "TensorArrayCloseV3": {
      let o = I("tensorArrayId", r15, e, t10), n = t10.getTensorArray(o.id);
      return n.clearAndClose(), [n.idTensor];
    }
    case "TensorListSetItem": {
      let o = I("tensorListId", r15, e, t10), n = I("index", r15, e, t10), s = I("tensor", r15, e, t10), a = t10.getTensorList(o.id);
      return a.setItem(n, s), [a.idTensor];
    }
    case "TensorListGetItem": {
      let o = I("tensorListId", r15, e, t10), n = I("index", r15, e, t10), s = I("elementShape", r15, e, t10), a = I("elementDType", r15, e, t10);
      return [t10.getTensorList(o.id).getItem(n, s, a)];
    }
    case "TensorListScatterV2":
    case "TensorListScatter": {
      let o = I("indices", r15, e, t10), n = I("tensor", r15, e, t10), s = I("elementShape", r15, e, t10), a = I("numElements", r15, e, t10), i = DT(n, o, s, a);
      return t10.addTensorList(i), [i.idTensor];
    }
    case "TensorListReserve":
    case "EmptyTensorList": {
      let o = I("elementShape", r15, e, t10), n = I("elementDType", r15, e, t10), s;
      r15.op === "TensorListReserve" ? s = "numElements" : s = "maxNumElements";
      let a = I(s, r15, e, t10), i = r15.op === "TensorListReserve" ? -1 : a, p = RT(o, n, a, i);
      return t10.addTensorList(p), [p.idTensor];
    }
    case "TensorListGather": {
      let o = I("tensorListId", r15, e, t10), n = I("indices", r15, e, t10), s = I("elementShape", r15, e, t10), a = I("elementDType", r15, e, t10);
      return [t10.getTensorList(o.id).gather(n, a, s)];
    }
    case "TensorListStack": {
      let o = I("tensorListId", r15, e, t10), n = I("elementShape", r15, e, t10), s = I("elementDType", r15, e, t10), a = I("numElements", r15, e, t10);
      return [t10.getTensorList(o.id).stack(n, s, a)];
    }
    case "TensorListFromTensor": {
      let o = I("tensor", r15, e, t10), n = I("elementShape", r15, e, t10), s = I("elementDType", r15, e, t10), a = $T(o, n, s);
      return t10.addTensorList(a), [a.idTensor];
    }
    case "TensorListConcat":
    case "TensorListConcatV2": {
      let o = I("tensorListId", r15, e, t10), n = t10.getTensorList(o.id), s = I("dtype", r15, e, t10), a = I("elementShape", r15, e, t10);
      return [n.concat(s, a)];
    }
    case "TensorListPushBack": {
      let o = I("tensorListId", r15, e, t10), n = I("tensor", r15, e, t10), s = t10.getTensorList(o.id);
      return s.pushBack(n), [s.idTensor];
    }
    case "TensorListPopBack": {
      let o = I("tensorListId", r15, e, t10), n = I("elementShape", r15, e, t10), s = I("elementDType", r15, e, t10);
      return [t10.getTensorList(o.id).popBack(n, s)];
    }
    case "TensorListSplit": {
      let o = I("tensor", r15, e, t10), n = I("elementShape", r15, e, t10), s = I("lengths", r15, e, t10), a = AT(o, s, n);
      return t10.addTensorList(a), [a.idTensor];
    }
    case "TensorListLength": {
      let o = I("tensorListId", r15, e, t10), n = t10.getTensorList(o.id);
      return [ke(n.size(), "int32")];
    }
    case "TensorListResize": {
      let o = I("tensorListId", r15, e, t10), n = I("size", r15, e, t10), a = t10.getTensorList(o.id).resize(n);
      return t10.addTensorList(a), [a.idTensor];
    }
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
function PT(r15, e, t10) {
  let [o, n] = I("fusedOps", r15, e, t10), s = o === "biasadd", a = !s, i = n === "prelu", p = o === "fusedbatchnorm", u = I("numArgs", r15, e, t10);
  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 (p) throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");
  let c = I("strides", r15, e, t10), l = Pl(r15, e, t10), m = I("dataFormat", r15, e, t10).toUpperCase(), d = I("dilations", r15, e, t10), [f, h] = I("args", r15, e, t10);
  a && (h = f, f = void 0);
  let g = I("leakyreluAlpha", r15, e, t10);
  return { stride: c, pad: l, dataFormat: m, dilations: d, biasArg: f, preluArg: h, activationFunc: n, leakyreluAlpha: g };
}
var OT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "Conv1D": {
      let n = I("stride", r15, e, t10), s = I("pad", r15, e, t10), a = I("dataFormat", r15, e, t10).toUpperCase(), i = I("dilation", r15, e, t10);
      return [o.conv1d(I("x", r15, e, t10), I("filter", r15, e, t10), n, s, a, i)];
    }
    case "Conv2D": {
      let n = I("strides", r15, e, t10), s = Pl(r15, e, t10), a = I("dataFormat", r15, e, t10).toUpperCase(), i = I("dilations", r15, e, t10);
      return [o.conv2d(I("x", r15, e, t10), I("filter", r15, e, t10), [n[1], n[2]], s, a, [i[1], i[2]])];
    }
    case "_FusedConv2D": {
      let { stride: n, pad: s, dataFormat: a, dilations: i, biasArg: p, preluArg: u, activationFunc: c, leakyreluAlpha: l } = PT(r15, e, t10);
      return [o.fused.conv2d({ x: I("x", r15, e, t10), filter: I("filter", r15, e, t10), strides: [n[1], n[2]], pad: s, dataFormat: a, dilations: [i[1], i[2]], bias: p, activation: c, preluActivationWeights: u, leakyreluAlpha: l })];
    }
    case "FusedDepthwiseConv2dNative": {
      let { stride: n, pad: s, dataFormat: a, dilations: i, biasArg: p, preluArg: u, activationFunc: c, leakyreluAlpha: l } = PT(r15, e, t10);
      return [o.fused.depthwiseConv2d({ x: I("x", r15, e, t10), filter: I("filter", r15, e, t10), strides: [n[1], n[2]], pad: s, dataFormat: a, dilations: [i[1], i[2]], bias: p, activation: c, preluActivationWeights: u, leakyreluAlpha: l })];
    }
    case "Conv2DBackpropInput":
    case "Conv2dTranspose": {
      let n = I("outputShape", r15, e, t10), s = I("strides", r15, e, t10), a = Pl(r15, e, t10);
      return [o.conv2dTranspose(I("x", r15, e, t10), I("filter", r15, e, t10), n, [s[1], s[2]], a)];
    }
    case "DepthwiseConv2dNative":
    case "DepthwiseConv2d": {
      let n = I("strides", r15, e, t10), s = Pl(r15, e, t10), a = I("dilations", r15, e, t10), i = I("dataFormat", r15, e, t10).toUpperCase();
      return [o.depthwiseConv2d(I("input", r15, e, t10), I("filter", r15, e, t10), [n[1], n[2]], s, i, [a[1], a[2]])];
    }
    case "Conv3D": {
      let n = I("strides", r15, e, t10), s = I("pad", r15, e, t10), a = I("dataFormat", r15, e, t10).toUpperCase(), i = I("dilations", r15, e, t10);
      return [o.conv3d(I("x", r15, e, t10), I("filter", r15, e, t10), [n[1], n[2], n[3]], s, a, [i[1], i[2], i[3]])];
    }
    case "AvgPool": {
      let n = I("strides", r15, e, t10), s = I("pad", r15, e, t10), a = I("kernelSize", r15, e, t10);
      return [o.avgPool(I("x", r15, e, t10), [a[1], a[2]], [n[1], n[2]], s)];
    }
    case "MaxPool": {
      let n = I("strides", r15, e, t10), s = I("pad", r15, e, t10), a = I("kernelSize", r15, e, t10);
      return [o.maxPool(I("x", r15, e, t10), [a[1], a[2]], [n[1], n[2]], s)];
    }
    case "MaxPoolWithArgmax": {
      let n = I("strides", r15, e, t10), s = I("pad", r15, e, t10), a = I("kernelSize", r15, e, t10), i = I("includeBatchInIndex", r15, e, t10), { result: p, indexes: u } = o.maxPoolWithArgmax(I("x", r15, e, t10), [a[1], a[2]], [n[1], n[2]], s, i);
      return [p, u];
    }
    case "AvgPool3D": {
      let n = I("strides", r15, e, t10), s = I("pad", r15, e, t10), a = I("kernelSize", r15, e, t10);
      return [o.avgPool3d(I("x", r15, e, t10), [a[1], a[2], a[3]], [n[1], n[2], n[3]], s)];
    }
    case "MaxPool3D": {
      let n = I("strides", r15, e, t10), s = I("pad", r15, e, t10), a = I("kernelSize", r15, e, t10);
      return [o.maxPool3d(I("x", r15, e, t10), [a[1], a[2], a[3]], [n[1], n[2], n[3]], s)];
    }
    case "Dilation2D": {
      let n = I("strides", r15, e, t10), s = I("pad", r15, e, t10), a = I("dilations", r15, e, t10), i = n[1], p = n[2], u = a[1], c = a[2];
      return [o.dilation2d(I("x", r15, e, t10), I("filter", r15, e, t10), [i, p], s, [u, c], "NHWC")];
    }
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var MT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "Fill": {
      let n = I("shape", r15, e, t10), s = I("dtype", r15, e, t10), a = I("value", r15, e, t10);
      return [o.fill(n, a, s)];
    }
    case "LinSpace": {
      let n = I("start", r15, e, t10), s = I("stop", r15, e, t10), a = I("num", r15, e, t10);
      return [o.linspace(n, s, a)];
    }
    case "Multinomial": {
      let n = I("logits", r15, e, t10), s = I("numSamples", r15, e, t10), a = I("seed", r15, e, t10);
      return [o.multinomial(n, s, a)];
    }
    case "OneHot": {
      let n = I("indices", r15, e, t10), s = I("depth", r15, e, t10), a = I("onValue", r15, e, t10), i = I("offValue", r15, e, t10), p = I("dtype", r15, e, t10);
      return [o.oneHot(n, s, a, i, p)];
    }
    case "Ones":
      return [o.ones(I("shape", r15, e, t10), I("dtype", r15, e, t10))];
    case "OnesLike":
      return [o.onesLike(I("x", r15, e, t10))];
    case "RandomStandardNormal":
      return [o.randomStandardNormal(I("shape", r15, e, t10), I("dtype", r15, e, t10), I("seed", r15, e, t10))];
    case "RandomUniform":
      return [o.randomUniform(I("shape", r15, e, t10), I("minval", r15, e, t10), I("maxval", r15, e, t10), I("dtype", r15, e, t10))];
    case "RandomUniformInt":
      return [o.randomUniformInt(I("shape", r15, e, t10), I("minval", r15, e, t10), I("maxval", r15, e, t10), I("seed", r15, e, t10))];
    case "Range": {
      let n = I("start", r15, e, t10), s = I("stop", r15, e, t10), a = I("step", r15, e, t10);
      return [o.range(n, s, a, I("dtype", r15, e, t10))];
    }
    case "TruncatedNormal": {
      let n = I("shape", r15, e, t10), s = I("mean", r15, e, t10), a = I("stdDev", r15, e, t10), i = I("seed", r15, e, t10);
      return [o.truncatedNormal(n, s, a, I("dtype", r15, e, t10), i)];
    }
    case "Zeros":
      return [o.zeros(I("shape", r15, e, t10), I("dtype", r15, e, t10))];
    case "ZerosLike":
      return [o.zerosLike(I("x", r15, e, t10))];
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
function OS(r15, e, t10) {
  let o = I("boxes", r15, e, t10), n = I("scores", r15, e, t10), s = I("maxOutputSize", r15, e, t10), a = I("iouThreshold", r15, e, t10), i = I("scoreThreshold", r15, e, t10), p = I("softNmsSigma", r15, e, t10);
  return { boxes: o, scores: n, maxOutputSize: s, iouThreshold: a, scoreThreshold: i, softNmsSigma: p };
}
var LT = async (r15, e, t10, o, n = Je) => {
  switch (r15.op) {
    case "NonMaxSuppressionV5": {
      let { boxes: s, scores: a, maxOutputSize: i, iouThreshold: p, scoreThreshold: u, softNmsSigma: c } = OS(r15, e, t10), l = await n.image.nonMaxSuppressionWithScoreAsync(s, a, i, p, u, c);
      return [l.selectedIndices, l.selectedScores];
    }
    case "NonMaxSuppressionV4": {
      let { boxes: s, scores: a, maxOutputSize: i, iouThreshold: p, scoreThreshold: u } = OS(r15, e, t10), c = I("padToMaxOutputSize", r15, e, t10), l = await n.image.nonMaxSuppressionPaddedAsync(s, a, i, p, u, c);
      return [l.selectedIndices, l.validOutputs];
    }
    case "NonMaxSuppressionV3":
    case "NonMaxSuppressionV2": {
      let { boxes: s, scores: a, maxOutputSize: i, iouThreshold: p, scoreThreshold: u } = OS(r15, e, t10);
      return [await n.image.nonMaxSuppressionAsync(s, a, i, p, u)];
    }
    case "Where": {
      let s = n.cast(I("condition", r15, e, t10), "bool"), a = [await n.whereAsync(s)];
      return s.dispose(), a;
    }
    case "ListDiff":
      return n.setdiff1dAsync(I("x", r15, e, t10), I("y", r15, e, t10));
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var BT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "LowerBound": {
      let n = I("sortedSequence", r15, e, t10), s = I("values", r15, e, t10);
      return [o.lowerBound(n, s)];
    }
    case "TopKV2": {
      let n = I("x", r15, e, t10), s = I("k", r15, e, t10), a = I("sorted", r15, e, t10), i = o.topk(n, s, a);
      return [i.values, i.indices];
    }
    case "UpperBound": {
      let n = I("sortedSequence", r15, e, t10), s = I("values", r15, e, t10);
      return [o.upperBound(n, s)];
    }
    case "Unique": {
      let n = I("x", r15, e, t10), s = o.unique(n);
      return [s.values, s.indices];
    }
    case "UniqueV2": {
      let n = I("x", r15, e, t10), s = I("axis", r15, e, t10), a = o.unique(n, s);
      return [a.values, a.indices];
    }
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var zT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "Const":
      return e[r15.name];
    case "PlaceholderWithDefault":
      let n = I("default", r15, e, t10);
      return [Bt(r15.name, e, t10) || n];
    case "Placeholder":
      return [Bt(r15.name, e, t10)];
    case "Identity":
    case "StopGradient":
    case "FakeQuantWithMinMaxVars": {
      let c = I("x", r15, e, t10);
      return [Bs(c)];
    }
    case "IdentityN":
      return I("x", r15, e, t10).map((c) => Bs(c));
    case "Snapshot":
      let s = I("x", r15, e, t10);
      return [Bs(s)];
    case "Shape":
      return [o.tensor1d(I("x", r15, e, t10).shape, "int32")];
    case "ShapeN":
      return I("x", r15, e, t10).map((c) => o.tensor1d(c.shape));
    case "Size":
      return [o.scalar(I("x", r15, e, t10).size, "int32")];
    case "Rank":
      return [o.scalar(I("x", r15, e, t10).rank, "int32")];
    case "NoOp":
      return [o.scalar(1)];
    case "Print":
      let a = I("x", r15, e, t10), i = I("data", r15, e, t10), p = I("message", r15, e, t10), u = I("summarize", r15, e, t10);
      console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."), console.log(p);
      for (let c = 0; c < i.length; c++) console.log(Array.prototype.slice.call(i[c].dataSync()).slice(0, u));
      return [a];
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var vf = class {
  get id() {
    return this.handle.id;
  }
  constructor(e, t10) {
    this.keyDType = e, this.valueDType = t10, this.handle = ke(0), this.tensorMap = /* @__PURE__ */ new Map(), $r(this.handle);
  }
  clearAndClose() {
    this.tensorMap.forEach((e) => e.dispose()), this.tensorMap.clear(), this.handle.dispose();
  }
  size() {
    return this.tensorMap.size;
  }
  tensorSize() {
    return ke(this.size(), "int32");
  }
  async import(e, t10) {
    this.checkKeyAndValueTensor(e, t10);
    let o = await e.data();
    return this.tensorMap.forEach((n) => n.dispose()), this.tensorMap.clear(), De(() => {
      let n = fo(t10), s = o.length, a = n.length;
      y.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 p = o[i], u = n[i];
        $r(u), this.tensorMap.set(p, u);
      }
      return this.handle;
    });
  }
  async find(e, t10) {
    this.checkKeyAndValueTensor(e, t10);
    let o = await e.data();
    return De(() => {
      let n = [];
      for (let s = 0; s < o.length; s++) {
        let a = o[s], i = this.findWithDefault(a, t10);
        n.push(i);
      }
      return vr(n);
    });
  }
  findWithDefault(e, t10) {
    let o = this.tensorMap.get(e);
    return o != null ? o : t10;
  }
  checkKeyAndValueTensor(e, t10) {
    if (e.dtype !== this.keyDType) throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);
    if (t10.dtype !== this.valueDType) throw new Error(`Expect value dtype ${this.valueDType}, but got ${t10.dtype}`);
  }
};
var VT = async (r15, e, t10, o) => {
  switch (r15.op) {
    case "HashTable":
    case "HashTableV2": {
      let n = o.getHashTableHandleByName(r15.name);
      if (n != null) return [n];
      {
        let s = I("keyDType", r15, e, t10), a = I("valueDType", r15, e, t10), i = new vf(s, a);
        return o.addHashTable(r15.name, i), [i.handle];
      }
    }
    case "InitializeTable":
    case "InitializeTableV2":
    case "LookupTableImport":
    case "LookupTableImportV2": {
      let n = I("tableHandle", r15, e, t10, o), s = I("keys", r15, e, t10), a = I("values", r15, e, t10);
      return [await o.getHashTableById(n.id).import(s, a)];
    }
    case "LookupTableFind":
    case "LookupTableFindV2": {
      let n = I("tableHandle", r15, e, t10, o), s = I("keys", r15, e, t10), a = I("defaultValue", r15, e, t10);
      return [await o.getHashTableById(n.id).find(s, a)];
    }
    case "LookupTableSize":
    case "LookupTableSizeV2": {
      let n = I("tableHandle", r15, e, t10, o);
      return [o.getHashTableById(n.id).tensorSize()];
    }
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var WT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "ResizeBilinear": {
      let n = I("images", r15, e, t10), s = I("size", r15, e, t10), a = I("alignCorners", r15, e, t10), i = I("halfPixelCenters", r15, e, t10);
      return [o.image.resizeBilinear(n, [s[0], s[1]], a, i)];
    }
    case "ResizeNearestNeighbor": {
      let n = I("images", r15, e, t10), s = I("size", r15, e, t10), a = I("alignCorners", r15, e, t10), i = I("halfPixelCenters", r15, e, t10);
      return [o.image.resizeNearestNeighbor(n, [s[0], s[1]], a, i)];
    }
    case "CropAndResize": {
      let n = I("image", r15, e, t10), s = I("boxes", r15, e, t10), a = I("boxInd", r15, e, t10), i = I("cropSize", r15, e, t10), p = I("method", r15, e, t10), u = I("extrapolationValue", r15, e, t10);
      return [o.image.cropAndResize(n, s, a, i, p, u)];
    }
    case "ImageProjectiveTransformV3": {
      let n = I("images", r15, e, t10), s = I("transforms", r15, e, t10), a = I("outputShape", r15, e, t10), i = I("fillValue", r15, e, t10), p = I("interpolation", r15, e, t10), u = I("fillMode", r15, e, t10);
      return [o.image.transform(n, s, p.toLowerCase(), u.toLowerCase(), i, a)];
    }
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var UT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "Equal":
      return [o.equal(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "NotEqual":
      return [o.notEqual(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "Greater":
      return [o.greater(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "GreaterEqual":
      return [o.greaterEqual(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "Less":
      return [o.less(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "LessEqual":
      return [o.lessEqual(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "LogicalAnd":
      return [o.logicalAnd(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "LogicalNot":
      return [o.logicalNot(I("a", r15, e, t10))];
    case "LogicalOr":
      return [o.logicalOr(I("a", r15, e, t10), I("b", r15, e, t10))];
    case "Select":
    case "SelectV2":
      return [o.where(I("condition", r15, e, t10), I("a", r15, e, t10), I("b", r15, e, t10))];
    case "BitwiseAnd":
      return [o.bitwiseAnd(I("a", r15, e, t10), I("b", r15, e, t10))];
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var GT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "BatchMatMul":
    case "BatchMatMulV2":
    case "MatMul":
      return [o.matMul(I("a", r15, e, t10), I("b", r15, e, t10), I("transposeA", r15, e, t10), I("transposeB", r15, e, t10))];
    case "Einsum":
      return [o.einsum(I("equation", r15, e, t10), ...I("tensors", r15, e, t10))];
    case "Transpose":
      return [o.transpose(I("x", r15, e, t10), I("perm", r15, e, t10))];
    case "_FusedMatMul":
      let [n, s] = I("fusedOps", r15, e, t10), a = n === "biasadd", i = s === "prelu", p = I("numArgs", r15, e, t10), u = I("leakyreluAlpha", r15, e, t10);
      if (a) {
        if (i && p !== 2) throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");
        if (!i && p !== 1) throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.");
      }
      let [c, l] = I("args", r15, e, t10);
      return [o.fused.matMul({ a: I("a", r15, e, t10), b: I("b", r15, e, t10), transposeA: I("transposeA", r15, e, t10), transposeB: I("transposeB", r15, e, t10), bias: c, activation: s, preluActivationWeights: l, leakyreluAlpha: u })];
    case "MatrixBandPart":
      return [o.linalg.bandPart(I("a", r15, e, t10), I("numLower", r15, e, t10), I("numUpper", r15, e, t10))];
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var HT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "EuclideanNorm":
      return [o.euclideanNorm(I("x", r15, e, t10), I("axis", r15, e, t10), I("keepDims", r15, e, t10))];
    case "FusedBatchNorm":
    case "FusedBatchNormV2":
      return [o.batchNorm(I("x", r15, e, t10), I("mean", r15, e, t10), I("variance", r15, e, t10), I("offset", r15, e, t10), I("scale", r15, e, t10), I("epsilon", r15, e, t10))];
    case "FusedBatchNormV3":
      return [o.batchNorm(I("x", r15, e, t10), I("mean", r15, e, t10), I("variance", r15, e, t10), I("offset", r15, e, t10), I("scale", r15, e, t10), I("epsilon", r15, e, t10))];
    case "LRN":
      return [o.localResponseNormalization(I("x", r15, e, t10), I("radius", r15, e, t10), I("bias", r15, e, t10), I("alpha", r15, e, t10), I("beta", r15, e, t10))];
    case "Softmax":
      return [o.softmax(I("x", r15, e, t10))];
    case "LogSoftmax":
      return [o.logSoftmax(I("x", r15, e, t10))];
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var KT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "RaggedGather": {
      let { outputNestedSplits: n, outputDenseValues: s } = o.raggedGather(I("paramsNestedSplits", r15, e, t10), I("paramsDenseValues", r15, e, t10), I("indices", r15, e, t10), I("outputRaggedRank", r15, e, t10));
      return n.concat(s);
    }
    case "RaggedRange": {
      let { rtNestedSplits: n, rtDenseValues: s } = o.raggedRange(I("starts", r15, e, t10), I("limits", r15, e, t10), I("splits", r15, e, t10));
      return [n, s];
    }
    case "RaggedTensorToTensor":
      return [o.raggedTensorToTensor(I("shape", r15, e, t10), I("values", r15, e, t10), I("defaultValue", r15, e, t10), I("rowPartitionTensors", r15, e, t10), I("rowPartitionTypes", r15, e, t10))];
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var qT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "Max": {
      let i = I("axis", r15, e, t10), p = I("keepDims", r15, e, t10);
      return [o.max(I("x", r15, e, t10), i, p)];
    }
    case "Mean": {
      let i = I("axis", r15, e, t10), p = I("keepDims", r15, e, t10);
      return [o.mean(I("x", r15, e, t10), i, p)];
    }
    case "Min": {
      let i = I("axis", r15, e, t10), p = I("keepDims", r15, e, t10);
      return [o.min(I("x", r15, e, t10), i, p)];
    }
    case "Sum": {
      let i = I("axis", r15, e, t10), p = I("keepDims", r15, e, t10);
      return [o.sum(I("x", r15, e, t10), i, p)];
    }
    case "All": {
      let i = I("axis", r15, e, t10), p = I("keepDims", r15, e, t10);
      return [o.all(I("x", r15, e, t10), i, p)];
    }
    case "Any": {
      let i = I("axis", r15, e, t10), p = I("keepDims", r15, e, t10);
      return [o.any(I("x", r15, e, t10), i, p)];
    }
    case "ArgMax": {
      let i = I("axis", r15, e, t10);
      return [o.argMax(I("x", r15, e, t10), i)];
    }
    case "ArgMin": {
      let i = I("axis", r15, e, t10);
      return [o.argMin(I("x", r15, e, t10), i)];
    }
    case "Prod": {
      let i = I("axis", r15, e, t10), p = I("keepDims", r15, e, t10);
      return [o.prod(I("x", r15, e, t10), i, p)];
    }
    case "Cumprod": {
      let i = I("axis", r15, e, t10), p = I("exclusive", r15, e, t10), u = I("reverse", r15, e, t10);
      return [o.cumprod(I("x", r15, e, t10), i, p, u)];
    }
    case "Cumsum": {
      let i = I("axis", r15, e, t10), p = I("exclusive", r15, e, t10), u = I("reverse", r15, e, t10);
      return [o.cumsum(I("x", r15, e, t10), i, p, u)];
    }
    case "Bincount":
      let n = I("x", r15, e, t10), s = I("weights", r15, e, t10), a = I("size", r15, e, t10);
      return [o.bincount(n, s, a)];
    case "DenseBincount": {
      let i = I("x", r15, e, t10), p = I("weights", r15, e, t10), u = I("size", r15, e, t10), c = I("binaryOutput", r15, e, t10);
      return [o.denseBincount(i, p, u, c)];
    }
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var jT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "ConcatV2":
    case "Concat": {
      let n = I("n", r15, e, t10), s = I("axis", r15, e, t10), a = I("tensors", r15, e, t10);
      return a = a.slice(0, n), [o.concat(a, s)];
    }
    case "Gather": {
      let n = I("x", r15, e, t10), s = I("indices", r15, e, t10);
      return [o.gather(n, o.cast(s, "int32"), 0)];
    }
    case "GatherV2": {
      let n = I("axis", r15, e, t10), s = I("batchDims", r15, e, t10), a = I("x", r15, e, t10), i = I("indices", r15, e, t10);
      return [o.gather(a, o.cast(i, "int32"), n, s)];
    }
    case "Reverse": {
      let n = I("dims", r15, e, t10), s = [];
      for (let i = 0; i < n.length; i++) n[i] && s.push(i);
      let a = I("x", r15, e, t10);
      return [o.reverse(a, s)];
    }
    case "ReverseV2": {
      let n = I("axis", r15, e, t10), s = I("x", r15, e, t10);
      return [o.reverse(s, n)];
    }
    case "Slice": {
      let n = I("begin", r15, e, t10), s = I("size", r15, e, t10);
      return [o.slice(I("x", r15, e, t10), n, s)];
    }
    case "StridedSlice": {
      let n = I("begin", r15, e, t10), s = I("end", r15, e, t10), a = I("strides", r15, e, t10), i = I("beginMask", r15, e, t10), p = I("endMask", r15, e, t10), u = I("ellipsisMask", r15, e, t10), c = I("newAxisMask", r15, e, t10), l = I("shrinkAxisMask", r15, e, t10), m = I("x", r15, e, t10);
      return [o.stridedSlice(m, n, s, a, i, p, u, c, l)];
    }
    case "Pack":
      return De(() => {
        let n = I("axis", r15, e, t10), s = I("tensors", r15, e, t10), a = s[0].shape, i = o.squeeze(s[0]).shape, p = s.map((u) => {
          let c = y.arraysEqual(u.shape, a);
          if (!c && !y.arraysEqual(o.squeeze(u).shape, i)) throw new Error("the input tensors shape does not match");
          return c ? u : o.reshape(u, a);
        });
        return [o.stack(p, n)];
      });
    case "Unpack": {
      let n = I("axis", r15, e, t10), s = I("tensor", r15, e, t10);
      return o.unstack(s, n);
    }
    case "Tile": {
      let n = I("reps", r15, e, t10);
      return [o.tile(I("x", r15, e, t10), n)];
    }
    case "Split":
    case "SplitV": {
      let n = I("axis", r15, e, t10), s = I("numOrSizeSplits", r15, e, t10), a = I("x", r15, e, t10);
      return o.split(a, s, n);
    }
    case "ScatterNd": {
      let n = I("indices", r15, e, t10), s = I("values", r15, e, t10), a = I("shape", r15, e, t10);
      return [o.scatterND(n, s, a)];
    }
    case "GatherNd": {
      let n = I("x", r15, e, t10), s = I("indices", r15, e, t10);
      return [o.gatherND(n, s)];
    }
    case "SparseToDense": {
      let n = I("sparseIndices", r15, e, t10), s = I("outputShape", r15, e, t10), a = I("sparseValues", r15, e, t10), i = I("defaultValue", r15, e, t10);
      return [o.sparseToDense(n, a, s, a.dtype === i.dtype ? i : o.cast(i, a.dtype))];
    }
    case "TensorScatterUpdate": {
      let n = I("indices", r15, e, t10), s = I("values", r15, e, t10), a = I("tensor", r15, e, t10);
      return [o.tensorScatterUpdate(a, n, s)];
    }
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var XT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "SparseFillEmptyRows": {
      let { outputIndices: n, outputValues: s, emptyRowIndicator: a, reverseIndexMap: i } = o.sparse.sparseFillEmptyRows(I("indices", r15, e, t10), I("values", r15, e, t10), I("denseShape", r15, e, t10), I("defaultValue", r15, e, t10));
      return [n, s, a, i];
    }
    case "SparseReshape": {
      let { outputIndices: n, outputShape: s } = o.sparse.sparseReshape(I("inputIndices", r15, e, t10), I("inputShape", r15, e, t10), I("newShape", r15, e, t10));
      return [n, s];
    }
    case "SparseSegmentMean":
      return [o.sparse.sparseSegmentMean(I("data", r15, e, t10), I("indices", r15, e, t10), I("segmentIds", r15, e, t10))];
    case "SparseSegmentSum":
      return [o.sparse.sparseSegmentSum(I("data", r15, e, t10), I("indices", r15, e, t10), I("segmentIds", r15, e, t10))];
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var YT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "FFT":
      return [o.fft(I("x", r15, e, t10))];
    case "IFFT":
      return [o.ifft(I("x", r15, e, t10))];
    case "RFFT":
      return [o.rfft(I("x", r15, e, t10))];
    case "IRFFT":
      return [o.irfft(I("x", r15, e, t10))];
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var QT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "StaticRegexReplace":
      return [o.string.staticRegexReplace(I("input", r15, e, t10), I("pattern", r15, e, t10), I("rewrite", r15, e, t10), I("replaceGlobal", r15, e, t10))];
    case "StringNGrams": {
      let { nGrams: n, nGramsSplits: s } = o.string.stringNGrams(I("data", r15, e, t10), I("dataSplits", r15, e, t10), I("separator", r15, e, t10), I("nGramWidths", r15, e, t10), I("leftPad", r15, e, t10), I("rightPad", r15, e, t10), I("padWidth", r15, e, t10), I("preserveShortSequences", r15, e, t10));
      return [n, s];
    }
    case "StringSplit": {
      let { indices: n, values: s, shape: a } = o.string.stringSplit(I("input", r15, e, t10), I("delimiter", r15, e, t10), I("skipEmpty", r15, e, t10));
      return [n, s, a];
    }
    case "StringToHashBucketFast":
      return [o.string.stringToHashBucketFast(I("input", r15, e, t10), I("numBuckets", r15, e, t10))];
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
var ZT = (r15, e, t10, o = Je) => {
  switch (r15.op) {
    case "Cast":
      return [o.cast(I("x", r15, e, t10), I("dtype", r15, e, t10))];
    case "ExpandDims": {
      let n = I("axis", r15, e, t10);
      return [o.expandDims(I("x", r15, e, t10), n)];
    }
    case "Squeeze": {
      let n = I("axis", r15, e, t10);
      return [o.squeeze(I("x", r15, e, t10), n)];
    }
    case "Reshape":
      return [o.reshape(I("x", r15, e, t10), I("shape", r15, e, t10))];
    case "EnsureShape":
      return [o.ensureShape(I("x", r15, e, t10), I("shape", r15, e, t10))];
    case "MirrorPad":
      return [o.mirrorPad(I("x", r15, e, t10), I("padding", r15, e, t10), I("mode", r15, e, t10))];
    case "PadV2":
    case "Pad":
      return [o.pad(I("x", r15, e, t10), I("padding", r15, e, t10), I("constantValue", r15, e, t10))];
    case "SpaceToBatchND": {
      let n = I("blockShape", r15, e, t10), s = I("paddings", r15, e, t10);
      return [o.spaceToBatchND(I("x", r15, e, t10), n, s)];
    }
    case "BatchToSpaceND": {
      let n = I("blockShape", r15, e, t10), s = I("crops", r15, e, t10);
      return [o.batchToSpaceND(I("x", r15, e, t10), n, s)];
    }
    case "DepthToSpace": {
      let n = I("blockSize", r15, e, t10), s = I("dataFormat", r15, e, t10).toUpperCase();
      return [o.depthToSpace(I("x", r15, e, t10), n, s)];
    }
    case "BroadcastTo":
      return [o.broadcastTo(I("x", r15, e, t10), I("shape", r15, e, t10))];
    case "BroadcastArgs":
      return [o.broadcastArgs(I("s0", r15, e, t10), I("s1", r15, e, t10))];
    default:
      throw TypeError(`Node type ${r15.op} is not implemented`);
  }
};
function MS(r15, e, t10, o, n = De) {
  let s = ((a, i, p) => {
    switch (a.category) {
      case "arithmetic":
        return n(() => TT(a, i, p));
      case "basic_math":
        return n(() => _T(a, i, p));
      case "control":
        return FT(a, i, p);
      case "convolution":
        return n(() => OT(a, i, p));
      case "creation":
        return n(() => MT(a, i, p));
      case "dynamic":
        return LT(a, i, p);
      case "evaluation":
        return n(() => BT(a, i, p));
      case "image":
        return n(() => WT(a, i, p));
      case "graph":
        return n(() => zT(a, i, p));
      case "logical":
        return n(() => UT(a, i, p));
      case "matrices":
        return n(() => GT(a, i, p));
      case "normalization":
        return n(() => HT(a, i, p));
      case "ragged":
        return n(() => KT(a, i, p));
      case "reduction":
        return n(() => qT(a, i, p));
      case "slice_join":
        return n(() => jT(a, i, p));
      case "sparse":
        return n(() => XT(a, i, p));
      case "spectral":
        return n(() => YT(a, i, p));
      case "string":
        return n(() => QT(a, i, p));
      case "transformation":
        return n(() => ZT(a, i, p));
      case "hash_table":
        return VT(a, i, p, o);
      case "custom":
        let u = pf(a.op);
        if (u && u.customExecutor) return u.customExecutor(new wf(a, i, p));
        throw TypeError(`Custom op ${a.op} is not registered.`);
      default:
        throw TypeError(`Unknown op '${a.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`);
    }
  })(r15, e, t10);
  return y.isPromise(s) ? s.then((a) => [].concat(a)) : [].concat(s);
}
var Ml = class {
  constructor(e = {}, t10 = {}, o = {}, n = {}, s) {
    this.weightMap = e, this.tensorArrayMap = t10, this.tensorListMap = o, this.functionMap = n, this.parseNodeNameCache = s, this.rootContext = { id: 0, frameName: "", iterationId: 0 }, this.contexts = [this.rootContext], this.lastId = 0, this.generateCurrentContextIds();
  }
  newFrame(e, t10) {
    return { id: e, frameName: t10, 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 t10 = 0; t10 < this.contexts.length - 1; t10++) {
      let o = this.contexts.slice(0, this.contexts.length - t10);
      e.push(this.contextIdforContexts(o));
    }
    e.push(""), this._currentContextIds = e;
  }
  contextIdforContexts(e) {
    return e ? e.map((t10) => t10.id === 0 && t10.iterationId === 0 ? "" : `${t10.frameName}-${t10.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 t10 in this.tensorArrayMap) this.tensorArrayMap[t10].clearAndClose(e);
    for (let t10 in this.tensorListMap) this.tensorListMap[t10].clearAndClose(e);
  }
};
function LS(r15, e, t10, o) {
  let n = /* @__PURE__ */ new Set(), s = [], a = null, i = null, p = /* @__PURE__ */ new Set(), u = new Set(Object.keys(r15).map((m) => Nr(m)[0]));
  o = o || [];
  let c = new Set(o.map((m) => Nr(m.name)[0])), l = [...e];
  for (; l.length > 0; ) {
    let m = l.pop();
    if ((fu(m) || A8(m) || F8(m)) && a == null && (a = m, i = a.children.map((d) => d.name).filter((d) => n.has(d))), n.add(m.name), t10[m.name] == null && !u.has(m.name) && !c.has(m.name)) {
      if (m.inputs.length === 0) {
        s.push(m.name);
        continue;
      }
      m.inputs.forEach((d) => {
        p.has(d.name) || (p.add(d.name), l.push(d));
      });
    }
  }
  return { inputs: r15, outputs: e, usedNodes: n, missingInputs: s, dynamicNode: a, syncInputs: i };
}
function JT(r15, e) {
  let { usedNodes: t10, inputs: o } = e, n = Object.keys(o).map((g) => Nr(g)[0]).map((g) => r15.nodes[g]), s = r15.initNodes || [], a = (g) => t10.has(typeof g == "string" ? g : g.name);
  function i(g) {
    return [...new Map(g.map((x) => [x.name, x])).values()];
  }
  let p = i([...n, ...r15.weights, ...s]).filter(a), u = i([...p, ...Object.values(r15.nodes)]).filter(a), c = new Map(u.map((g) => [g.name, g])), l = {};
  for (let g of u) {
    l[g.name] = l[g.name] || 0;
    for (let x of g.children) a(x) || (l[x.name] = Number.POSITIVE_INFINITY), l[x.name] = (l[x.name] || 0) + 1;
  }
  let m = Object.entries(l).filter(([, g]) => g === 0).map(([g]) => g), d = [...m];
  for (; m.length > 0; ) {
    let g = m.pop(), x = c.get(g);
    for (let b of x.children.filter(a)) --l[b.name] === 0 && (d.push(b.name), m.push(b.name));
  }
  let f = d.map((g) => c.get(g)), h = _8(f, p);
  return E8(h, p), h;
}
function _8(r15, e) {
  let t10 = new Map(r15.map((a) => [a.name, a])), o = e.map((a) => a.name), n = new Set(o);
  for (; o.length > 0; ) {
    let a = o.pop(), i = t10.get(a);
    for (let p of i.children) !t10.has(p.name) || n.has(p.name) || (n.add(p.name), o.push(p.name));
  }
  return r15.filter((a) => n.has(a.name));
}
var gc = class extends Error {
  constructor(e) {
    super(`NodesExecutionOrderError: ${e}`);
  }
};
function E8(r15, e) {
  let t10 = new Map(r15.map((i, p) => [i.name, p])), o = new Set(e.map((i) => i.name)), n = (i) => o.has(typeof i == "string" ? i : i.name), s = new Set(r15.map((i) => i.name)), a = (i) => s.has(typeof i == "string" ? i : i.name);
  for (let i of r15) {
    for (let p of i.children.filter(a)) {
      if (!t10.has(p.name)) throw new gc(`Child ${p.name} of node ${i.name} is unreachable.`);
      if (t10.get(i.name) > t10.get(p.name)) throw new gc(`Node ${i.name} is scheduled to run after its child ${p.name}.`);
    }
    if (!n(i)) for (let p of i.inputs) {
      if (!t10.has(p.name)) throw new gc(`Input ${p.name} of node ${i.name} is unreachable.`);
      if (t10.get(p.name) > t10.get(i.name)) throw new gc(`Node ${i.name} is scheduled to run before its input ${p.name}.`);
    }
  }
}
function e_(r15) {
  let e = new Map(r15.map((i, p) => [i.name, p])), t10 = Number.MAX_SAFE_INTEGER, o = r15.map((i, p) => fu(i) ? t10 : p), n = (i) => {
    let p = o[e.get(i.name)];
    return p == null ? -1 : p;
  }, s = r15.map((i, p) => i.children.map(n).reduce((u, c) => Math.max(u, c), o[p])), a = /* @__PURE__ */ new Map();
  for (let i = 0; i < r15.length; ++i) {
    let p = s[i];
    if (p === t10) continue;
    let u = r15[i], c = r15[p];
    a.has(c.name) || a.set(c.name, []), a.get(c.name).push(u);
  }
  return a;
}
var $8 = /* @__PURE__ */ new Set(["Switch", "Merge", "Enter", "Exit", "NextIteration", "StatelessIf", "StatelessWhile", "if", "While"]);
var R8 = /* @__PURE__ */ new Set(["NonMaxSuppressionV2", "NonMaxSuppressionV3", "NonMaxSuppressionV5", "Where"]);
var D8 = /* @__PURE__ */ new Set(["HashTable", "HashTableV2", "LookupTableImport", "LookupTableImportV2", "LookupTableFind", "LookupTableFindV2", "LookupTableSize", "LookupTableSizeV2"]);
function fu(r15) {
  return $8.has(r15.op);
}
function A8(r15) {
  return R8.has(r15.op);
}
function F8(r15) {
  return D8.has(r15.op);
}
var Ll = class r10 {
  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 t10 = Object.keys(e).map((o) => e[o].map((n) => n.id));
    this._weightIds = [].concat(...t10), 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 t10 = e.signatureKey || e.name;
      return e.defaultOutput ? `${t10}:${e.defaultOutput}` : t10;
    });
  }
  get functions() {
    return Object.keys(this._functions).reduce((e, t10) => (e[t10] = this._functions[t10].signature, e), {});
  }
  constructor(e, t10) {
    this.graph = e, this.parent = t10, this.compiledMap = /* @__PURE__ */ new Map(), this.parseNodeNameCache = /* @__PURE__ */ new Map(), this._weightMap = {}, this.SEPARATOR = ",", this._functions = {}, this._functionExecutorMap = {}, this.keepIntermediateTensors = false, 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((o) => {
      this._functionExecutorMap[o] = new r10(e.functions[o], this);
    });
  }
  getCompilationKey(e, t10) {
    let o = e.map((s) => s.name).sort(), n = t10.map((s) => s.name).sort();
    return o.join(this.SEPARATOR) + "--" + n.join(this.SEPARATOR);
  }
  compile(e, t10) {
    let o = LS(e, t10, this.weightMap, this._initNodes), { missingInputs: n, dynamicNode: s, syncInputs: a } = o;
    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 (n.length > 0) {
      let u = t10.map((l) => l.name), c = Object.keys(e);
      throw new Error(`Cannot compute the outputs [${u}] from the provided inputs [${c}]. Missing the following inputs: [${n}]`);
    }
    let i = JT(this.graph, o), p = e_(i);
    return { orderedNodes: i, nodeLiveUntilMap: p };
  }
  cloneAndKeepTensor(e) {
    if (e == null) return null;
    let t10 = e.clone();
    return $r(t10), t10;
  }
  cloneTensorList(e) {
    return e ? e.map((o) => this.cloneAndKeepTensor(o)) : null;
  }
  cloneTensorMap(e) {
    return Object.fromEntries(Object.entries(e).map(([t10, o]) => [t10, this.cloneTensorList(o)]));
  }
  execute(e, t10) {
    this.disposeIntermediateTensors(), e = this.mapInputs(e);
    let o = Object.keys(e).sort();
    this.checkInputs(e), this.checkInputShapeAndType(e), t10 = this.mapOutputs(t10), this.checkOutputs(t10);
    let n = o.map((m) => this.graph.nodes[Nr(m)[0]]), s = t10.map((m) => Nr(m)[0]), a = new Set(s), i = s.map((m) => this.graph.nodes[m]);
    i.length === 0 && (i = this._outputs);
    let p = this.getCompilationKey(n, i), u = this.compiledMap.get(p);
    u == null && (u = this.compile(e, i), this.compiledMap.set(p, u));
    try {
      this.keepIntermediateTensors = A().getBool("KEEP_INTERMEDIATE_TENSORS");
    } catch (m) {
      this.keepIntermediateTensors = false, console.warn(m.message);
    }
    let c = {}, l = {};
    return De(() => {
      let m = new Ml(this.weightMap, c, l, this.functionExecutorMap, this.parseNodeNameCache), d = Object.assign({}, this.weightMap);
      this.keepIntermediateTensors && (this.clonedTensorsMap = this.cloneTensorMap(this.weightMap)), Object.keys(e).forEach((x) => {
        let [b, C] = Nr(x, m), S = [];
        S[C] = e[x], d[b] = S, this.keepIntermediateTensors && (this.clonedTensorsMap[b] = this.cloneTensorList(S));
      });
      let f = this.getFrozenTensorIds(d), { orderedNodes: h, nodeLiveUntilMap: g } = u;
      for (let x of h) {
        if (d[x.name]) continue;
        let b = MS(x, d, m, this._resourceManager);
        if (y.isPromise(b)) throw new Error(`The execution of the op '${x.op}' returned a promise. Please use model.executeAsync() instead.`);
        d[x.name] = b, this.keepIntermediateTensors && (this.clonedTensorsMap[x.name] = this.cloneTensorList(b)), this.checkTensorForDisposalWithNodeLiveUntilInfo(x, d, m, f, a, g.get(x.name));
      }
      return this.parent == null && m.dispose(f), t10.map((x) => Bt(x, d, m));
    });
  }
  getFrozenTensorIds(e) {
    let t10 = [].concat.apply([], Object.keys(e).map((o) => e[o]).map((o) => o.map((n) => n.id)));
    return new Set(t10);
  }
  checkTensorForDisposal(e, t10, o, n, s, a, i) {
    if (!(fu(t10) || a.has(e))) {
      for (let p of o[e]) p != null && (i[p.id] = (i[p.id] || 0) + t10.children.length);
      for (let p of t10.inputs) {
        if (fu(p)) continue;
        let u = hS(p.name, o, n);
        if (u != null) for (let c of u) {
          if (!c || c.kept || s.has(c.id)) continue;
          let l = i[c.id];
          l === 1 ? (c.dispose(), delete i[c.id]) : l != null && i[c.id]--;
        }
      }
    }
  }
  checkTensorForDisposalWithNodeLiveUntilInfo(e, t10, o, n, s, a) {
    function i(p) {
      return fu(p) || s.has(p.name);
    }
    if (!(fu(e) || a == null)) for (let p of a) {
      if (i(p)) continue;
      let u = hS(p.name, t10, o);
      for (let c of u) !c || c.kept || n.has(c.id) || c.dispose();
    }
  }
  async executeAsync(e, t10) {
    return this._executeAsync(e, t10);
  }
  disposeIntermediateTensors() {
    this.clonedTensorsMap && (Object.values(this.clonedTensorsMap).forEach((e) => {
      for (let t10 of e) t10 && !t10.isDisposed && t10.dispose();
    }), this.clonedTensorsMap = null);
  }
  getIntermediateTensors() {
    return this.clonedTensorsMap;
  }
  async _executeAsync(e, t10, o = false, n = {}, s = {}) {
    this.disposeIntermediateTensors(), o || (e = this.mapInputs(e), this.checkInputs(e), this.checkInputShapeAndType(e), t10 = this.mapOutputs(t10), this.checkOutputs(t10));
    try {
      this.keepIntermediateTensors = A().getBool("KEEP_INTERMEDIATE_TENSORS");
    } catch (m) {
      this.keepIntermediateTensors = false, console.warn(m.message);
    }
    let a = new Ml(this.weightMap, n, s, this.functionExecutorMap, this.parseNodeNameCache);
    this.keepIntermediateTensors && (this.clonedTensorsMap = this.cloneTensorMap(this.weightMap));
    let i = await this.executeWithControlFlow(e, a, t10, o), p = t10.map((m) => Bt(m, i, a)), u = p.map((m) => m.id), c = Object.keys(e).map((m) => e[m].id), l = /* @__PURE__ */ new Set([...u, ...c, ...this.weightIds]);
    return Object.values(i).forEach((m) => {
      m.forEach((d) => {
        d && !d.isDisposed && !l.has(d.id) && d.dispose();
      });
    }), this.parent == null && a.dispose(l), p;
  }
  async executeFunctionAsync(e, t10, o) {
    let n = e.reduce((s, a, i) => (s[this.inputs[i].name] = a, s), {});
    return this._executeAsync(n, this.outputNodes, true, t10, o);
  }
  async executeWithControlFlow(e, t10, o, n) {
    let s = Object.keys(e), a = s.map((S) => this.graph.nodes[Nr(S)[0]]), i = o.map((S) => Nr(S)[0]), p = new Set(i), u = i.map((S) => this.graph.nodes[S]);
    u.length === 0 && (u = this._outputs);
    let { usedNodes: c, missingInputs: l, dynamicNode: m, syncInputs: d } = LS(e, u, this.weightMap, this._initNodes), f = [...a, ...this.graph.weights, ...this._initNodes || []].map((S) => ({ node: S, contexts: t10.currentContext })), h = Object.assign({}, this.weightMap);
    Object.keys(e).forEach((S) => {
      let [k, _] = Nr(S), $ = [];
      $[_] = e[S], h[k] = $;
    });
    let g = {}, x = this.getFrozenTensorIds(h), b = {};
    for (; f.length > 0; ) {
      let S = this.processStack(a, f, t10, h, b, x, p, g, c);
      await Promise.all(S);
    }
    m == null && !n && console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");
    let C = u.filter((S) => !fu(S) && !Bt(S.name, h, t10)).map((S) => S.name);
    if (C.length > 0) {
      let S = "";
      throw m != null && (S = `Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${d}]`), new Error(`Cannot compute the outputs [${C}] from the provided inputs [${s}]. Consider providing the following inputs: [${l}]. ${S}`);
    }
    return h;
  }
  processStack(e, t10, o, n, s, a, i, p, u) {
    let c = [];
    for (; t10.length > 0; ) {
      let l = t10.pop();
      o.currentContext = l.contexts;
      let m = "";
      if (l.node.op === "Enter" && I("isConstant", l.node, n, o) && ([m] = Ls(l.node.name, o)), n[l.node.name] == null) {
        let d = MS(l.node, n, o, this._resourceManager);
        m || ([m] = Ls(l.node.name, o));
        let f = o.currentContext;
        y.isPromise(d) ? c.push(d.then((h) => (n[m] = h, this.keepIntermediateTensors && (this.clonedTensorsMap[m] = this.cloneTensorList(h)), o.currentContext = f, this.checkTensorForDisposal(m, l.node, n, o, a, i, p), this.processChildNodes(l.node, t10, o, n, s, u), h))) : (n[m] = d, this.keepIntermediateTensors && (this.clonedTensorsMap[m] = this.cloneTensorList(d)), this.checkTensorForDisposal(m, l.node, n, o, a, i, p), this.processChildNodes(l.node, t10, o, n, s, u));
      } else this.processChildNodes(l.node, t10, o, n, s, u);
    }
    return c;
  }
  processChildNodes(e, t10, o, n, s, a) {
    e.children.forEach((i) => {
      let [p] = Ls(i.name, o);
      s[p] || !a.has(i.name) || (i.op === "Merge" ? i.inputNames.some((u) => !!Bt(u, n, o)) && (s[p] = true, t10.push({ contexts: o.currentContext, node: i })) : i.inputNames.every((u) => !!Bt(u, n, o)) && (s[p] = true, t10.push({ contexts: o.currentContext, node: i })));
    });
  }
  dispose() {
    Object.keys(this.weightMap).forEach((e) => this.weightMap[e].forEach((t10) => t10.dispose()));
  }
  checkInputShapeAndType(e) {
    Object.keys(e).forEach((t10) => {
      let o = e[t10], [n] = Nr(t10), s = this.graph.nodes[n];
      if (s.attrParams.shape && s.attrParams.shape.value) {
        let a = s.attrParams.shape.value, i = a.length === o.shape.length && o.shape.every((p, u) => a[u] === -1 || a[u] === p);
        y.assert(i, () => `The shape of dict['${s.name}'] provided in model.execute(dict) must be [${a}], but was [${o.shape}]`);
      }
      s.attrParams.dtype && s.attrParams.dtype.value && y.assert(o.dtype === s.attrParams.dtype.value, () => `The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${o.dtype}`);
    });
  }
  mapInputs(e) {
    var t10, o;
    let n = {};
    for (let s in e) {
      let a = (o = (t10 = this._signature) === null || t10 === void 0 ? void 0 : t10.inputs) === null || o === void 0 ? void 0 : o[s];
      a != null ? n[a.name] = e[s] : n[s] = e[s];
    }
    return n;
  }
  checkInputs(e) {
    let t10 = Object.keys(e).filter((o) => {
      let [n] = Nr(o);
      return this.graph.nodes[n] == null;
    });
    if (t10.length > 0) throw new Error(`The dict provided in model.execute(dict) has keys: [${t10}] that are not part of graph`);
  }
  mapOutputs(e) {
    return e.map((t10) => {
      var o, n;
      let s = (n = (o = this._signature) === null || o === void 0 ? void 0 : o.outputs) === null || n === void 0 ? void 0 : n[t10];
      return s != null ? s.name : t10;
    }, {});
  }
  checkOutputs(e) {
    e.forEach((t10) => {
      let [o] = Nr(t10);
      if (!this.graph.nodes[o]) throw new Error(`The output '${t10}' is not found in the graph`);
    });
  }
};
var kf = class {
  constructor(e = {}, t10 = {}) {
    this.hashTableNameToHandle = e, this.hashTableMap = t10;
  }
  addHashTable(e, t10) {
    this.hashTableNameToHandle[e] = t10.handle, this.hashTableMap[t10.id] = t10;
  }
  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 P8 = "?tfjs-format=file";
var O8 = "model.json";
var Bl = class {
  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;
  }
  get modelStructuredOutputKeys() {
    return this.structuredOutputKeys;
  }
  constructor(e, t10 = {}, o = di) {
    this.modelUrl = e, this.loadOptions = t10, this.version = "n/a", this.io = o, t10 == null && (this.loadOptions = {}), this.resourceManager = new kf();
  }
  findIOHandler() {
    let e = this.modelUrl;
    if (e.load != null) this.handler = e;
    else if (this.loadOptions.requestInit != null) this.handler = this.io.browserHTTPRequest(e, this.loadOptions);
    else {
      let t10 = this.io.getLoadHandlers(e, this.loadOptions);
      if (t10.length === 0) t10.push(this.io.browserHTTPRequest(e, this.loadOptions));
      else if (t10.length > 1) throw new Error(`Found more than one (${t10.length}) load handlers for URL '${[e]}'`);
      this.handler = t10[0];
    }
  }
  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 = this.handler.load();
    return y.isPromise(e) ? e.then((t10) => t10.getWeightStream == null ? this.loadSync(t10) : this.loadStreaming(t10)) : this.loadSync(e);
  }
  loadSync(e) {
    let t10 = this.io.decodeWeights(e.weightData, e.weightSpecs);
    return this.loadWithWeightMap(e, t10);
  }
  async loadStreaming(e) {
    if (e.getWeightStream == null) throw new Error("Model artifacts missing streamWeights function");
    let t10 = await ad(e.getWeightStream(), e.weightSpecs);
    return this.loadWithWeightMap(e, t10);
  }
  loadWithWeightMap(e, t10) {
    this.artifacts = e;
    let o = this.artifacts.modelTopology, n = this.artifacts.signature;
    if (this.artifacts.userDefinedMetadata != null) {
      let s = this.artifacts.userDefinedMetadata;
      s.signature != null && (n = s.signature), s.structuredOutputKeys != null && (this.structuredOutputKeys = s.structuredOutputKeys);
    }
    if (this.signature = n, this.version = `${o.versions.producer}.${o.versions.minConsumer}`, this.executor = new Ll(Ol.Instance.transformGraph(o, this.signature)), this.executor.weightMap = this.convertTensorMapToTensorsMap(t10), this.executor.resourceManager = this.resourceManager, e.modelInitializer != null && e.modelInitializer.node != null) {
      let s = Ol.Instance.transformGraph(e.modelInitializer);
      this.initializer = new Ll(s), this.initializer.weightMap = this.executor.weightMap, this.initializer.resourceManager = this.resourceManager, this.initializerSignature = e.initializerSignature;
    }
    return true;
  }
  async save(e, t10) {
    if (typeof e == "string") {
      let o = this.io.getSaveHandlers(e);
      if (o.length === 0) throw new Error(`Cannot find any save handlers for URL '${e}'`);
      if (o.length > 1) throw new Error(`Found more than one (${o.length}) save handlers for URL '${e}'`);
      e = o[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);
  }
  addStructuredOutputNames(e) {
    if (this.structuredOutputKeys) {
      let t10 = e instanceof mt ? [e] : e, o = {};
      return t10.forEach((n, s) => o[this.structuredOutputKeys[s]] = n), o;
    }
    return e;
  }
  predict(e, t10) {
    let o = this.execute(e, this.outputNodes);
    return this.addStructuredOutputNames(o);
  }
  async predictAsync(e, t10) {
    let o = await this.executeAsync(e, this.outputNodes);
    return this.addStructuredOutputNames(o);
  }
  normalizeInputs(e) {
    var t10;
    if (!(e instanceof mt) && !Array.isArray(e)) {
      let s = (t10 = this.signature) === null || t10 === void 0 ? void 0 : t10.inputs;
      if (s != null) for (let a in s) {
        let i = s[a];
        i.resourceId != null && (e[a] = this.resourceIdToCapturedInput[i.resourceId]);
      }
      return e;
    }
    e = Array.isArray(e) ? e : [e];
    let o = Object.keys(this.resourceIdToCapturedInput).length;
    if (e.length + o !== this.inputNodes.length) throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length - o} non-resource placeholders, while there are ${e.length} input tensors provided.`);
    let n = 0;
    return this.inputNodes.reduce((s, a) => {
      var i, p, u;
      let c = (u = (p = (i = this.signature) === null || i === void 0 ? void 0 : i.inputs) === null || p === void 0 ? void 0 : p[a]) === null || u === void 0 ? void 0 : u.resourceId;
      return c != null ? s[a] = this.resourceIdToCapturedInput[c] : s[a] = e[n++], s;
    }, {});
  }
  normalizeOutputs(e) {
    return e = e || this.outputNodes, Array.isArray(e) ? e : [e];
  }
  executeInitializerGraph() {
    return this.initializer == null ? [] : this.initializerSignature == null ? this.initializer.execute({}, []) : this.initializer.execute({}, Object.keys(this.initializerSignature.outputs));
  }
  async executeInitializerGraphAsync() {
    return this.initializer == null ? [] : this.initializerSignature == null ? this.initializer.executeAsync({}, []) : this.initializer.executeAsync({}, Object.keys(this.initializerSignature.outputs));
  }
  setResourceIdToCapturedInput(e) {
    if (this.resourceIdToCapturedInput = {}, this.initializerSignature) {
      let t10 = this.initializerSignature.outputs, o = Object.keys(t10);
      for (let n = 0; n < o.length; n++) {
        let s = o[n], a = t10[s];
        this.resourceIdToCapturedInput[a.resourceId] = e[n];
      }
    }
  }
  execute(e, t10) {
    this.resourceIdToCapturedInput == null && this.setResourceIdToCapturedInput(this.executeInitializerGraph()), e = this.normalizeInputs(e), t10 = this.normalizeOutputs(t10);
    let o = this.executor.execute(e, t10);
    return o.length > 1 ? o : o[0];
  }
  async executeAsync(e, t10) {
    this.resourceIdToCapturedInput == null && this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()), e = this.normalizeInputs(e), t10 = this.normalizeOutputs(t10);
    let o = await this.executor.executeAsync(e, t10);
    return o.length > 1 ? o : o[0];
  }
  getIntermediateTensors() {
    return this.executor.getIntermediateTensors();
  }
  disposeIntermediateTensors() {
    this.executor.disposeIntermediateTensors();
  }
  convertTensorMapToTensorsMap(e) {
    return Object.keys(e).reduce((t10, o) => (t10[o] = [e[o]], t10), {});
  }
  dispose() {
    this.executor.dispose(), this.initializer && (this.initializer.dispose(), this.resourceIdToCapturedInput && Ot(this.resourceIdToCapturedInput)), this.resourceManager.dispose();
  }
};
async function M8(r15, e = {}, t10 = di) {
  if (r15 == 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 && typeof r15 == "string" && (r15 = B8(r15));
  let o = new Bl(r15, e, t10);
  return await o.load(), o;
}
function L8(r15) {
  if (r15 == null) throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");
  let e;
  if (r15 instanceof Array) {
    let [o, n] = r15;
    if (!o) throw new Error("modelJSON must be the first element of the array");
    if (!n || !(n instanceof ArrayBuffer)) throw new Error("An ArrayBuffer of weights must be the second element of the array");
    if (!("modelTopology" in o)) throw new Error("Model JSON is missing 'modelTopology'");
    if (!("weightsManifest" in o)) throw new Error("Model JSON is missing 'weightsManifest'");
    let s = di.getWeightSpecs(o.weightsManifest), a = di.getModelArtifactsForJSONSync(o, s, n);
    e = di.fromMemorySync(a);
  } else if ("load" in r15) e = r15;
  else if ("modelTopology" in r15 && "weightSpecs" in r15 && "weightData" in r15) e = di.fromMemorySync(r15);
  else throw new Error("Unknown model format");
  let t10 = new Bl(e);
  return t10.load(), t10;
}
function B8(r15) {
  return r15.endsWith("/") || (r15 = r15 + "/"), `${r15}${O8}${P8}`;
}
var z8 = "4.22.0";
function Q(r15, e) {
  Array.isArray(r15) || (r15 = [r15]), r15.forEach((t10) => {
    t10 != null && y.assert(t10.dtype !== "complex64", () => `${e} does not support complex64 tensors in the CPU backend.`);
  });
}
var V8 = Vt.whereImpl;
var xc = class r11 extends ao {
  nextDataId() {
    return r11.nextDataId++;
  }
  constructor() {
    super(), this.blockSize = 48, this.firstUse = true, this.data = new Bo(this, ur());
  }
  write(e, t10, o) {
    this.firstUse && (this.firstUse = false, A().get("IS_NODE") && w.warn(`
============================
Hi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. 
============================`));
    let n = { id: this.nextDataId() };
    return this.data.set(n, { values: e, dtype: o, refCount: 1 }), n;
  }
  makeTensorInfo(e, t10, o) {
    let n;
    if (t10 === "string" && o != null && o.length > 0 && y.isString(o[0])) {
      let s = o.map((a) => y.encodeString(a));
      n = this.write(s, e, t10);
    } else n = this.write(o, e, t10);
    return { dataId: n, shape: e, dtype: t10 };
  }
  refCount(e) {
    return this.data.has(e) ? this.data.get(e).refCount : 0;
  }
  incRef(e) {
    let t10 = this.data.get(e);
    t10.refCount++;
  }
  decRef(e) {
    if (this.data.has(e)) {
      let t10 = this.data.get(e);
      t10.refCount--;
    }
  }
  move(e, t10, o, n, s) {
    this.data.set(e, { values: t10, dtype: n, refCount: s });
  }
  numDataIds() {
    return this.data.numDataIds();
  }
  async read(e) {
    return this.readSync(e);
  }
  readSync(e) {
    let { dtype: t10, complexTensorInfos: o } = this.data.get(e);
    if (t10 === "complex64") {
      let n = this.readSync(o.real.dataId), s = this.readSync(o.imag.dataId);
      return w.mergeRealAndImagArrays(n, s);
    }
    return y.convertBackendValuesAndArrayBuffer(this.data.get(e).values, t10);
  }
  bufferSync(e) {
    let t10 = this.readSync(e.dataId);
    if (e.dtype === "string") try {
      let o = t10.map((n) => y.decodeString(n));
      return me(e.shape, e.dtype, o);
    } catch (o) {
      throw new Error("Failed to decode encoded string bytes into utf-8");
    }
    return me(e.shape, e.dtype, t10);
  }
  makeOutput(e, t10, o) {
    return ur().makeTensorFromTensorInfo(this.makeTensorInfo(t10, o, e), this);
  }
  disposeData(e, t10 = false) {
    if (this.data.has(e)) {
      if (this.data.get(e).refCount--, !t10 && this.data.get(e).refCount > 0) return false;
      let { complexTensorInfos: o } = this.data.get(e);
      o != null && (this.disposeData(o.real.dataId, true), this.disposeData(o.imag.dataId, true)), this.data.delete(e);
    }
    return true;
  }
  disposeIntermediateTensorInfo(e) {
    this.disposeData(e.dataId);
  }
  async time(e) {
    let t10 = y.now();
    return e(), { kernelMs: y.now() - t10 };
  }
  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) {
    Q([e], "where");
    let t10 = this.readSync(e.dataId);
    return V8(e.shape, t10);
  }
  dispose() {
  }
  floatPrecision() {
    return 32;
  }
  epsilon() {
    return super.epsilon();
  }
};
xc.nextDataId = 0;
var Ic = {};
qe(Ic, { addImpl: () => VS, bincountImpl: () => Cc, bincountReduceImpl: () => Nf, bitwiseAndImpl: () => WS, castImpl: () => zS, ceilImpl: () => US, concatImpl: () => ap, equalImpl: () => GS, expImpl: () => KS, expm1Impl: () => jS, floorDivImpl: () => YS, floorImpl: () => XS, gatherNdImpl: () => Tf, gatherV2Impl: () => _f, greaterEqualImpl: () => ZS, greaterImpl: () => QS, lessEqualImpl: () => eI, lessImpl: () => JS, linSpaceImpl: () => Ef, logImpl: () => tI, maxImpl: () => $f, maximumImpl: () => rI, minimumImpl: () => oI, multiplyImpl: () => zl, negImpl: () => nI, notEqualImpl: () => sI, prodImpl: () => aI, raggedGatherImpl: () => Rf, raggedRangeImpl: () => Df, raggedTensorToTensorImpl: () => Af, rangeImpl: () => up, rsqrtImpl: () => uI, scatterImpl: () => zs, sigmoidImpl: () => R_, simpleAbsImpl: () => BS, sliceImpl: () => pp, sparseFillEmptyRowsImpl: () => Ff, sparseReshapeImpl: () => Pf, sparseSegmentReductionImpl: () => Sc, sqrtImpl: () => F_, squaredDifferenceImpl: () => cI, staticRegexReplaceImpl: () => lI, stridedSliceImpl: () => Of, stringNGramsImpl: () => cp, stringSplitImpl: () => lp, stringToHashBucketFastImpl: () => mp, subImpl: () => dI, tileImpl: () => Mf, topKImpl: () => Lf, transposeImpl: () => wc, uniqueImpl: () => dp });
function BS(r15) {
  let e = new Float32Array(r15.length);
  for (let t10 = 0; t10 < r15.length; ++t10) e[t10] = Math.abs(r15[t10]);
  return e;
}
var W8 = (r15) => {
  let { x: e } = r15.inputs, t10 = r15.backend;
  Q(e, "abs");
  let o = new Float32Array(y.sizeFromShape(e.shape)), n = t10.data.get(e.dataId).values;
  return o = BS(n), t10.makeOutput(o, e.shape, e.dtype);
};
var t_ = { kernelName: "Abs", backendName: "cpu", kernelFunc: W8 };
function Ve(r15) {
  return (e, t10, o, n, s) => {
    let a = w.assertAndGetBroadcastShape(e, t10), i = a.length, p = y.computeStrides(a), u = y.sizeFromShape(a), c = y.getTypedArrayFromDType(s, u), l = e.length, m = t10.length, d = y.computeStrides(e), f = y.computeStrides(t10), h = w.getBroadcastDims(e, a), g = w.getBroadcastDims(t10, a);
    if (h.length + g.length === 0) for (let x = 0; x < c.length; ++x) c[x] = r15(o[x % o.length], n[x % n.length]);
    else for (let x = 0; x < c.length; ++x) {
      let b = y.indexToLoc(x, i, p), C = b.slice(-l);
      h.forEach(($) => C[$] = 0);
      let S = y.locToIndex(C, l, d), k = b.slice(-m);
      g.forEach(($) => k[$] = 0);
      let _ = y.locToIndex(k, m, f);
      c[x] = r15(o[S], n[_]);
    }
    return [c, a];
  };
}
function Ht(r15) {
  let { inputs: e, backend: t10 } = r15, { real: o, imag: n } = e, s = t10.data.get(o.dataId).values, a = t10.data.get(n.dataId).values, i = t10.makeTensorInfo(o.shape, "complex64"), p = t10.data.get(i.dataId);
  return p.complexTensorInfos = { real: t10.makeTensorInfo(o.shape, "float32", s), imag: t10.makeTensorInfo(n.shape, "float32", a) }, i;
}
var r_ = { kernelName: Di, backendName: "cpu", kernelFunc: Ht };
function yc(r15, e, t10 = "float32") {
  if (t10 === "complex64") {
    let n = yc(r15, e, "float32"), s = yc(r15, e, "float32");
    return Ht({ inputs: { real: n, imag: s }, backend: r15 });
  }
  let o = y.makeZerosTypedArray(y.sizeFromShape(e), t10);
  return r15.makeTensorInfo(e, t10, o);
}
function lr(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e;
  return t10.incRef(o.dataId), { dataId: o.dataId, shape: o.shape, dtype: o.dtype };
}
var o_ = { kernelName: Co, backendName: "cpu", kernelFunc: lr };
function $o(r15) {
  let { inputs: e, backend: t10 } = r15, { input: o } = e, n = t10.data.get(o.dataId).complexTensorInfos.real, s = t10.data.get(n.dataId).values;
  return t10.makeTensorInfo(n.shape, n.dtype, s);
}
var n_ = { kernelName: Hi, backendName: "cpu", kernelFunc: $o };
function zS(r15, e, t10, o) {
  if (o === "int32") {
    let n = Int32Array.from(r15);
    return [e, "int32", n];
  }
  if (o === "bool") {
    let n = y.toTypedArray([0], t10), [s, a] = Ve((i, p) => i !== p ? 1 : 0)(e, [], r15, n, "bool");
    return [a, "bool", s];
  }
  throw new Error(`Error in Cast: failed to cast ${t10} to ${o}`);
}
function Ro(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { dtype: s } = o;
  if (s === "complex64") {
    if (n.dtype === "complex64") return lr({ inputs: { x: n }, backend: t10 });
    let c = yc(t10, n.shape, n.dtype), l = Ro({ inputs: { x: n }, backend: t10, attrs: { dtype: "float32" } }), m = Ht({ inputs: { real: l, imag: c }, backend: t10 });
    return t10.disposeIntermediateTensorInfo(c), t10.disposeIntermediateTensorInfo(l), m;
  }
  if (n.dtype === "complex64") {
    let c = $o({ inputs: { input: n }, backend: t10 }), l = Ro({ inputs: { x: c }, backend: t10, attrs: { dtype: s } });
    return t10.disposeIntermediateTensorInfo(c), l;
  }
  if (!y.hasEncodingLoss(n.dtype, s)) {
    let c = lr({ inputs: { x: n }, backend: t10 });
    return { dataId: c.dataId, shape: c.shape, dtype: s };
  }
  let a = t10.data.get(n.dataId).values, [i, p, u] = zS(a, n.shape, n.dtype, s);
  return t10.makeTensorInfo(i, p, u);
}
var s_ = { kernelName: yo, backendName: "cpu", kernelFunc: Ro };
function Ye(r15, e, t10, o) {
  return t10 == null ? ({ inputs: n, backend: s }) => {
    let { a, b: i } = n, p = s;
    Q([a, i], r15);
    let u = p.data.get(a.dataId).values, c = p.data.get(i.dataId).values, l = a.dtype === "string" ? w.fromUint8ToStringArray(u) : u, m = a.dtype === "string" ? w.fromUint8ToStringArray(c) : c, d = o || a.dtype, [f, h] = e(a.shape, i.shape, l, m, d);
    return p.makeTensorInfo(h, d, f);
  } : ({ inputs: n, backend: s }) => {
    let { a, b: i } = n, p = s;
    if (a.dtype === "complex64" || i.dtype === "complex64") {
      let u = Ro({ inputs: { x: a }, backend: p, attrs: { dtype: "complex64" } }), c = p.data.get(u.dataId), l = c.complexTensorInfos.real, m = c.complexTensorInfos.imag, d = p.data.get(l.dataId).values, f = p.data.get(m.dataId).values, h = Ro({ inputs: { x: i }, backend: p, attrs: { dtype: "complex64" } }), g = p.data.get(h.dataId), x = g.complexTensorInfos.real, b = g.complexTensorInfos.imag, C = p.data.get(x.dataId).values, S = p.data.get(b.dataId).values, [k, _, $] = t10(a.shape, i.shape, d, f, C, S), R = p.makeTensorInfo($, "float32", k), D = p.makeTensorInfo($, "float32", _), P = Ht({ inputs: { real: R, imag: D }, backend: p });
      return p.disposeIntermediateTensorInfo(u), p.disposeIntermediateTensorInfo(h), p.disposeIntermediateTensorInfo(R), p.disposeIntermediateTensorInfo(D), P;
    } else {
      let u = p.data.get(a.dataId).values, c = p.data.get(i.dataId).values, l = o || a.dtype, [m, d] = e(a.shape, i.shape, u, c, l);
      return p.makeTensorInfo(d, l, m);
    }
  };
}
function bc(r15) {
  return (e, t10, o, n, s, a) => {
    let i = w.assertAndGetBroadcastShape(e, t10), p = y.sizeFromShape(i), u = i.length, c = y.computeStrides(i), l = y.getTypedArrayFromDType("float32", p), m = y.getTypedArrayFromDType("float32", p), d = w.getBroadcastDims(e, i), f = w.getBroadcastDims(t10, i), h = w.mergeRealAndImagArrays(o, n), g = w.mergeRealAndImagArrays(s, a), x = e.length, b = y.computeStrides(e), C = t10.length, S = y.computeStrides(t10);
    if (d.length + f.length === 0) for (let k = 0; k < l.length; k++) {
      let _ = k % h.length, $ = k % g.length, R = r15(h[_ * 2], h[_ * 2 + 1], g[$ * 2], g[$ * 2 + 1]);
      l[k] = R.real, m[k] = R.imag;
    }
    else for (let k = 0; k < l.length; k++) {
      let _ = y.indexToLoc(k, u, c), $ = _.slice(-x);
      d.forEach((M) => $[M] = 0);
      let R = y.locToIndex($, x, b), D = _.slice(-C);
      f.forEach((M) => D[M] = 0);
      let P = y.locToIndex(D, C, S), O = r15(h[R * 2], h[R * 2 + 1], g[P * 2], g[P * 2 + 1]);
      l[k] = O.real, m[k] = O.imag;
    }
    return [l, m, i];
  };
}
var VS = Ve(((r15, e) => r15 + e));
var U8 = bc(((r15, e, t10, o) => ({ real: r15 + t10, imag: e + o })));
var Pa = Ye("Add", VS, U8);
var a_ = { kernelName: "Add", backendName: "cpu", kernelFunc: Pa };
function Cc(r15, e, t10, o, n) {
  let s = y.sizeFromShape(o), a = y.makeZerosTypedArray(n, t10);
  for (let i = 0; i < r15.length; i++) {
    let p = r15[i];
    if (p < 0) throw new Error("Input x must be non-negative!");
    p >= n || (s > 0 ? a[p] += e[i] : a[p] += 1);
  }
  return a;
}
function Nf(r15, e, t10, o = false) {
  let n = r15.shape[0], s = r15.shape[1], a = me([n, t10], e.dtype);
  for (let i = 0; i < n; i++) for (let p = 0; p < s; p++) {
    let u = r15.get(i, p);
    if (u < 0) throw new Error("Input x must be non-negative!");
    u >= t10 || (o ? a.set(1, i, u) : e.size > 0 ? a.set(a.get(i, u) + e.get(i, p), i, u) : a.set(a.get(i, u) + 1, i, u));
  }
  return a;
}
var WS = Ve(((r15, e) => r15 & e));
var G8 = Ye(qa, WS);
var i_ = { kernelName: qa, backendName: "cpu", kernelFunc: G8 };
function jt(r15) {
  return (e, t10, o) => {
    let n = y.getArrayFromDType(t10, e.length);
    for (let s = 0; s < e.length; ++s) n[s] = r15(e[s], o);
    return n;
  };
}
function Ie(r15, e, t10) {
  let o = jt(e);
  return Ar(r15, o, t10);
}
function Ar(r15, e, t10) {
  return ({ inputs: o, attrs: n, backend: s }) => {
    let { x: a } = o;
    Q(a, r15);
    let i = s, p = i.data.get(a.dataId).values, u;
    if (a.dtype === "string") {
      if (!Array.isArray(p)) throw new Error("String tensor's value was not an instance of Array");
      u = w.fromUint8ToStringArray(p);
    } else u = p;
    let c = t10 || a.dtype, l = e(u, c, n);
    return i.makeTensorInfo(a.shape, c, l);
  };
}
var US = jt((r15) => Math.ceil(r15));
var H8 = Ar(en, US);
var u_ = { kernelName: en, backendName: "cpu", kernelFunc: H8 };
function ap(r15, e, t10, o) {
  let n = y.getArrayFromDType(t10, y.sizeFromShape(e));
  if (o && t10 !== "string") {
    let s = 0;
    r15.forEach((a) => {
      let i = y.sizeFromShape(a.shape);
      n.set(a.vals, s), s += i;
    });
  } else {
    let s = 0;
    r15.forEach((a) => {
      let i = t10 === "string" ? w.fromUint8ToStringArray(a.vals) : a.vals, p = 0;
      for (let u = 0; u < a.shape[0]; ++u) {
        let c = u * e[1] + s;
        for (let l = 0; l < a.shape[1]; ++l) n[c + l] = i[p++];
      }
      s += a.shape[1];
    });
  }
  return n;
}
var GS = Ve((r15, e) => r15 === e ? 1 : 0);
var HS = Ye(xn, GS, null, "bool");
var p_ = { kernelName: xn, backendName: "cpu", kernelFunc: HS };
var KS = jt((r15) => Math.exp(r15));
var qS = Ar("Exp", KS, "float32");
var c_ = { kernelName: "Exp", backendName: "cpu", kernelFunc: qS };
var jS = jt((r15) => Math.expm1(r15));
var K8 = Ar(bn, jS);
var l_ = { kernelName: bn, backendName: "cpu", kernelFunc: K8 };
var XS = jt((r15) => Math.floor(r15));
var q8 = Ar(wn, XS);
var m_ = { kernelName: wn, backendName: "cpu", kernelFunc: q8 };
var YS = Ve((r15, e) => Math.floor(r15 / e));
var j8 = Ye(Sn, YS, null, "int32");
var d_ = { kernelName: Sn, backendName: "cpu", kernelFunc: j8 };
function Tf(r15, e, t10, o, n, s, a, i, p) {
  let u = me([o, s], t10);
  for (let c = 0; c < o; c++) {
    let l = [], m = 0;
    for (let d = 0; d < n; d++) {
      let f = r15[c * n + d];
      m += f * a[d], l.push(f);
    }
    if (m < 0 || m >= p / s) throw new Error(`Invalid indices: ${l} does not index into ${i}`);
    for (let d = 0; d < s; d++) u.values[c * s + d] = e.get(...e.indexToLoc(m * s + d));
  }
  return u;
}
function _f(r15, e, t10) {
  let o = me(t10, r15.dtype);
  for (let n = 0; n < o.size; ++n) {
    let a = o.indexToLoc(n).slice(), i = a[0], p = a[2], u = e.locToIndex([i, p]);
    a[2] = e.values[u];
    let c = r15.locToIndex(a);
    0 <= c && c < r15.values.length && (o.values[n] = r15.values[c]);
  }
  return o;
}
var QS = Ve((r15, e) => r15 > e ? 1 : 0);
var X8 = Ye(kn, QS, null, "bool");
var f_ = { kernelName: kn, backendName: "cpu", kernelFunc: X8 };
var ZS = Ve((r15, e) => r15 >= e ? 1 : 0);
var Y8 = Ye(Nn, ZS, null, "bool");
var h_ = { kernelName: Nn, backendName: "cpu", kernelFunc: Y8 };
var JS = Ve((r15, e) => r15 < e ? 1 : 0);
var Q8 = Ye(Rn, JS, null, "bool");
var g_ = { kernelName: Rn, backendName: "cpu", kernelFunc: Q8 };
var eI = Ve((r15, e) => r15 <= e ? 1 : 0);
var Z8 = Ye(Dn, eI, null, "bool");
var x_ = { kernelName: Dn, backendName: "cpu", kernelFunc: Z8 };
function Ef(r15, e, t10) {
  let o = (e - r15) / (t10 - 1), n = y.makeZerosTypedArray(t10, "float32");
  n[0] = r15;
  for (let s = 1; s < n.length; s++) n[s] = n[s - 1] + o;
  return n;
}
var tI = jt((r15) => Math.log(r15));
var J8 = Ar("Log", tI);
var y_ = { kernelName: "Log", backendName: "cpu", kernelFunc: J8 };
function $f(r15, e, t10, o) {
  let n = y.getTypedArrayFromDType(o, y.sizeFromShape(t10));
  for (let s = 0; s < n.length; ++s) {
    let a = s * e, i = r15[a];
    for (let p = 0; p < e; ++p) {
      let u = r15[a + p];
      (Number.isNaN(u) || u > i) && (i = u);
    }
    n[s] = i;
  }
  return n;
}
var rI = Ve(((r15, e) => Math.max(r15, e)));
var eY = Ye(Vn, rI);
var b_ = { kernelName: Vn, backendName: "cpu", kernelFunc: eY };
var oI = Ve(((r15, e) => Math.min(r15, e)));
var tY = Ye(Hn, oI);
var C_ = { kernelName: Hn, backendName: "cpu", kernelFunc: tY };
var zl = Ve(((r15, e) => r15 * e));
var rY = bc(((r15, e, t10, o) => ({ real: r15 * t10 - e * o, imag: r15 * o + e * t10 })));
var ip = Ye(Xn, zl, rY);
var w_ = { kernelName: Xn, backendName: "cpu", kernelFunc: ip };
function nI(r15, e, t10) {
  let o = y.createScalarValue(-1, t10);
  return zl([], e, o, r15, t10);
}
function oY(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e;
  Q(o, "neg");
  let n = t10.data.get(o.dataId).values, [s, a] = nI(n, o.shape, o.dtype);
  return t10.makeTensorInfo(a, o.dtype, s);
}
var S_ = { kernelName: "Neg", backendName: "cpu", kernelFunc: oY };
var sI = Ve(((r15, e) => r15 !== e ? 1 : 0));
var nY = Ye(Yn, sI, null, "bool");
var I_ = { kernelName: Yn, backendName: "cpu", kernelFunc: nY };
function wc(r15, e, t10, o, n) {
  let s = e.length, a = y.sizeFromShape(e), i = y.computeStrides(e), p = y.computeStrides(n), u = y.getTypedArrayFromDType(t10, y.sizeFromShape(n));
  for (let c = 0; c < a; ++c) {
    let l = y.indexToLoc(c, s, i), m = new Array(l.length);
    for (let f = 0; f < m.length; f++) m[f] = l[o[f]];
    let d = y.locToIndex(m, s, p);
    u[d] = r15[c];
  }
  return u;
}
function St(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { x: n } = e, { perm: s } = t10;
  Q(n, "transpose");
  let a = n.shape.length, i = new Array(a);
  for (let l = 0; l < i.length; l++) i[l] = n.shape[s[l]];
  let p = o.data.get(n.dataId).values, u = wc(p, n.shape, n.dtype, s, i);
  return { dataId: o.write(u, i, n.dtype), shape: i, dtype: n.dtype };
}
var v_ = { kernelName: co, backendName: "cpu", kernelFunc: St };
function aI(r15, e, t10, o) {
  let [n, s] = w.computeOutAndReduceShapes(r15, o), a = dt(e, "int32"), i = y.makeZerosTypedArray(y.sizeFromShape(n), a), p = y.sizeFromShape(s);
  for (let u = 0; u < i.length; ++u) {
    let c = u * p, l = 1;
    for (let m = 0; m < p; ++m) l *= t10[c + m];
    i[u] = l;
  }
  return { outVals: i, outShape: n, outDtype: a };
}
function sY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o;
  Q(n, "prod");
  let i = n.shape.length, p = y.parseAxisParam(s, n.shape), u = w.getAxesPermutation(p, i), c = p, l = n, m = [];
  u != null && (l = St({ inputs: { x: n }, backend: t10, attrs: { perm: u } }), m.push(l), c = w.getInnerMostAxes(c.length, i));
  let d = t10.data.get(l.dataId).values, { outVals: f, outShape: h, outDtype: g } = aI(l.shape, l.dtype, d, c), x = h;
  return a && (x = w.expandShapeToKeepDim(h, p)), m.forEach((b) => t10.disposeIntermediateTensorInfo(b)), t10.makeTensorInfo(x, g, f);
}
var k_ = { kernelName: os, backendName: "cpu", kernelFunc: sY };
function aY(r15, e, t10) {
  r15.forEach((o, n) => {
    if (o < 0 || o >= t10) {
      let s = y.indexToLoc(n, e.length, y.computeStrides(e)).join(",");
      throw new Error(`indices[${s}] = ${o} is not in [0, ${t10})`);
    }
  });
}
function iY(r15, e) {
  for (let t10 = 0; t10 < r15.length; ++t10) {
    let o = r15[t10], n = t10 === r15.length - 1 ? e : r15[t10 + 1].length;
    if (o.length === 0) throw new Error("Ragged splits may not be empty");
    if (o[0] < 0) throw new Error("Ragged splits must be non-negative");
    if (o[o.length - 1] > n) throw new Error("Ragged splits must not point past values");
    for (let s = 1; s < o.length; ++s) if (o[s - 1] > o[s]) throw new Error("Ragged splits must be sorted in ascending order");
  }
}
function uY(r15, e, t10, o) {
  let n = [], s = 0, a = e.length - 1 + t10.length, i = new Array(a).fill(null).map(() => [0]);
  iY(t10, o);
  let p = 1;
  for (let u = 0; u < e.length - 1; ++u) {
    p *= e[u];
    let c = e[u + 1];
    for (let l = 1; l < p + 1; ++l) i[u].push(l * c);
  }
  for (let u = 0; u < r15.length; ++u) {
    let c = r15[u], l = r15[u] + 1;
    for (let m = 0; m < t10.length; ++m) {
      let d = t10[m], f = m + e.length - 1;
      if (f >= 0) {
        let h = i[f], g = h[h.length - 1] - d[c];
        for (let x = c; x < l; ++x) i[f].push(d[x + 1] + g);
      }
      c = d[c], l = d[l];
    }
    l !== c && (n.push([c, l]), s += l - c);
  }
  return { outSplits: i, valueSlices: n, numValues: s };
}
function pY(r15) {
  let e = [];
  for (let t10 = 0; t10 < r15.length; ++t10) {
    let o = r15[t10].length, n = y.getArrayFromDType("int32", o);
    e.push(n), r15[t10].forEach((s, a) => n[a] = s);
  }
  return e;
}
function N_(r15, e) {
  let t10 = r15.slice(0, e);
  for (; t10.length < e; ) t10.push(1);
  for (let o = e; o < r15.length; o++) t10[e - 1] *= r15[o];
  return t10;
}
function cY(r15, e, t10, o, n, s) {
  let a = N_(e, 2)[1], i = N_(s, 2)[1], p = 0;
  for (let u of t10) for (let c = u[0]; c < u[1]; ++c) {
    for (let l = 0; l < o; ++l) n[p * i + l] = r15[c * a + l];
    ++p;
  }
}
function lY(r15, e, t10, o, n) {
  let s = e.slice();
  s[0] = n;
  let a = y.getArrayFromDType(t10, y.sizeFromShape(s)), i = r15.length, p = i === 0 ? 0 : i / e[0];
  return cY(r15, e, o, p, a, s), [a, s];
}
function Rf(r15, e, t10, o, n, s, a, i) {
  if (r15.length === 0) throw new Error("paramsNestedSplits must be non empty");
  if (e[0].length === 0) throw new Error("Split tensors must not be scalars");
  let p = e[0][0] - 1;
  if (aY(s, a, p), o.length === 0) throw new Error("params.rank must be nonzero");
  let u = o[0], { outSplits: c, valueSlices: l, numValues: m } = uY(s, a, r15, u), d = pY(c), f = lY(t10, o, n, l, m);
  return [d, f[0], f[1]];
}
var T_ = 2147483647;
function Df(r15, e, t10, o, n, s, a) {
  if (e.length > 1) throw new Error("starts must be a scalar or vector");
  if (n.length > 1) throw new Error("limits must be a scalar or vector");
  if (a.length > 1) throw new Error("deltas must be a scalar or vector");
  let i = e.length === 0, p = n.length === 0, u = a.length === 0, c = [];
  i || c.push(e[0]), p || c.push(n[0]), u || c.push(a[0]);
  for (let g = 1; g < c.length; ++g) if (c[g] !== c[g - 1]) throw new Error("starts, limits, and deltas must have the same shape");
  let l = c.length === 0 ? 1 : c[0], m = y.getArrayFromDType("int32", l + 1);
  m[0] = 0;
  for (let g = 0; g < l; ++g) {
    let x = i ? r15[0] : r15[g], b = p ? o[0] : o[g], C = u ? s[0] : s[g];
    if (C === 0) throw new Error("Requires delta != 0");
    let S;
    if (C > 0 && b < x || C < 0 && b > x) S = 0;
    else if (S = Math.ceil(Math.abs((b - x) / C)), S > T_) throw new Error(`Requires ((limit - start) / delta) <= ${T_}`);
    m[g + 1] = m[g] + S;
  }
  let d = m[l], f = y.getArrayFromDType(t10, d), h = 0;
  for (let g = 0; g < l; ++g) {
    let x = m[g + 1] - m[g], b = i ? r15[0] : r15[g], C = u ? s[0] : s[g];
    for (let S = 0; S < x; ++S) f[h++] = b, b += C;
  }
  return [m, f];
}
var Do = w.RowPartitionType;
var iI = class r12 {
  constructor(e, t10, o, n, s, a, i, p, u, c) {
    this.shape = e, this.shapeShape = t10, this.values = o, this.valuesShape = n, this.valuesDType = s, this.defaultValue = a, this.defaultValueShape = i, this.rowPartitionValues = p, this.rowPartitionValuesShapes = u, this.rowPartitionTypes = w.getRowPartitionTypesHelper(c), this.raggedRank = w.getRaggedRank(this.rowPartitionTypes);
  }
  getRowPartitionTypeByDimension(e) {
    return this.rowPartitionTypes[0] === Do.FIRST_DIM_SIZE ? this.rowPartitionTypes[e + 1] : this.rowPartitionTypes[e];
  }
  getRowPartitionTensor(e) {
    return this.rowPartitionTypes[0] === Do.FIRST_DIM_SIZE ? this.rowPartitionValues[e + 1] : this.rowPartitionValues[e];
  }
  getMaxWidth(e) {
    let t10 = this.getRowPartitionTensor(e - 1);
    switch (this.getRowPartitionTypeByDimension(e - 1)) {
      case Do.VALUE_ROWIDS:
        return r12.getMaxWidthValueRowID(t10);
      case Do.ROW_SPLITS:
        return r12.getMaxWidthRowSplit(t10);
      default:
        throw new Error(`Cannot handle partition type ${Do[this.getRowPartitionTypeByDimension(e - 1)]}`);
    }
  }
  static getMaxWidthRowSplit(e) {
    let t10 = e.length;
    if (t10 === 0 || t10 === 1) return 0;
    let o = 0;
    for (let n = 0; n < t10 - 1; ++n) {
      let s = e[n + 1] - e[n];
      s > o && (o = s);
    }
    return o;
  }
  static getMaxWidthValueRowID(e) {
    let t10 = e.length;
    if (t10 === 0) return 0;
    let o = 0, n = e[0], s = 0;
    for (let a = 1; a < t10; ++a) {
      let i = e[a];
      i !== n && (n = i, s = Math.max(a - o, s), o = a);
    }
    return Math.max(t10 - o, s);
  }
  tensorShapeFromTensor(e, t10, o = true) {
    if (t10.length === 0) {
      if (e[0] === -1) return [];
      throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.");
    }
    return E_(e, o);
  }
  calculateOutputSize(e) {
    let t10 = this.valuesShape, o = this.defaultValueShape;
    w.validateDefaultValueShape(o, t10);
    let n = this.tensorShapeFromTensor(this.shape, this.shapeShape), a = w.combineRaggedTensorToTensorShapes(this.raggedRank, n, t10);
    a[0] < 0 && (a[0] = e);
    for (let i = 1; i <= this.raggedRank; ++i) a[i] < 0 && (a[i] = this.getMaxWidth(i));
    return a;
  }
  calculateFirstParentOutputIndex(e, t10, o) {
    let n = Math.min(e, o), s = [], a = 0;
    for (let i = 0; i < n; ++i, a += t10) s.push(a);
    for (let i = n; i < e; ++i) s.push(-1);
    return y.assert(s.length === e, () => "Final length of result must be equal to firstDimension."), s;
  }
  calculateOutputIndexRowSplit(e, t10, o, n) {
    let s = e.length, a = [];
    for (let i = 0; i < s - 1; ++i) {
      let p = e[i + 1] - e[i], u = Math.min(n, p), c = t10[i];
      c === -1 && (u = 0);
      for (let l = 0; l < u; ++l) a.push(c), c += o;
      for (let l = 0; l < p - u; ++l) a.push(-1);
    }
    if (s > 0 && a.length !== e[s - 1]) throw new Error("Invalid row split size.");
    return a;
  }
  calculateOutputIndexValueRowID(e, t10, o, n) {
    let s = e.length, a = [];
    if (s === 0) return [];
    let i = 0, p = e[0];
    if (p >= t10.length) throw new Error(`Got currentValueRowId=${p}, which is not less than ${t10.length}`);
    let u = t10[p];
    a.push(u);
    for (let c = 1; c < s; ++c) {
      let l = e[c];
      if (l === p) u >= 0 && (++i, i < n ? u += o : u = -1);
      else {
        if (i = 0, p = l, l >= t10.length) throw new Error(`Got nextValueRowId=${l} which is not less than ${t10.length}`);
        u = t10[l];
      }
      a.push(u);
    }
    if (a.length !== e.length) throw new Error("Invalid row ids.");
    return a;
  }
  calculateOutputIndex(e, t10, o, n) {
    let s = this.getRowPartitionTensor(e), a = this.getRowPartitionTypeByDimension(e);
    switch (a) {
      case Do.VALUE_ROWIDS:
        return this.calculateOutputIndexValueRowID(s, t10, o, n);
      case Do.ROW_SPLITS:
        if (s.length - 1 > t10.length) throw new Error(`Row partition size is greater than output size: ${s.length - 1} > ${t10.length}`);
        return this.calculateOutputIndexRowSplit(s, t10, o, n);
      default:
        throw new Error(`Unsupported partition type: ${Do[a]}`);
    }
  }
  getFirstDimensionSize() {
    let e = this.rowPartitionValues[0];
    if (this.rowPartitionTypes.length === 0) throw new Error("No row_partition_types given.");
    let t10 = this.rowPartitionTypes[0];
    switch (t10) {
      case Do.FIRST_DIM_SIZE:
        return e[0];
      case Do.VALUE_ROWIDS:
        throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");
      case Do.ROW_SPLITS:
        return this.rowPartitionValuesShapes[0][0] - 1;
      default:
        throw new Error(`Cannot handle type ${Do[t10]}`);
    }
  }
  compute() {
    if (this.rowPartitionValues[0].length <= 0) throw new Error("Invalid first partition input. Tensor requires at least one element.");
    let t10 = this.getFirstDimensionSize(), o = this.calculateOutputSize(t10), n = new Array(this.raggedRank + 1);
    n[n.length - 1] = 1;
    for (let p = n.length - 2; p >= 0; --p) n[p] = n[p + 1] * o[p + 1];
    let s = E_(o, false), a = y.getArrayFromDType(this.valuesDType, y.sizeFromShape(s));
    if (n[0] * o[0] > 0) {
      let p = this.calculateFirstParentOutputIndex(t10, n[0], o[0]);
      for (let u = 1; u <= this.raggedRank; ++u) p = this.calculateOutputIndex(u - 1, p, n[u], o[u]);
      this.setOutput(this.raggedRank, p, a, s);
    }
    return [s, a];
  }
  setOutput(e, t10, o, n) {
    if (o.length === 0) return;
    let s = this.values, a = o, i = n.slice();
    i = i.slice(e + 1);
    let p = y.sizeFromShape(i), u = t10.length, c = this.defaultValue;
    if (c.length !== p && c.length !== 1) {
      let f = this.defaultValueShape;
      De(() => {
        let h = W(c, f);
        c = su(h, i).dataSync();
      });
    }
    let l = 0, m = 0, d = 0;
    for (let f = 0; f <= u; ++f) {
      let h = f < u ? t10[f] : -1;
      if (h === d) {
        ++d;
        continue;
      }
      if (m < d) {
        let g = s.subarray(l * p), x = a.subarray(m * p), b = (d - m) * p;
        __(x, g, b);
      }
      if (f >= u) {
        let g = o.length;
        h = Math.floor(g / p);
      }
      if (h > d) if (this.defaultValue.length === 1) a.subarray(d * p, h * p).fill(this.defaultValue[0]), d = h;
      else for (; h > d; ) {
        let g = a.slice(d * p);
        __(g, c, p), ++d;
      }
      h < 0 ? (l = f + 1, m = d) : (l = f, m = d, d = m + 1);
    }
  }
};
function __(r15, e, t10) {
  for (let o = 0; o < t10; o++) r15[o] = e[o];
}
function E_(r15, e) {
  let t10 = [];
  for (let o of r15) {
    if (o < 0) {
      if (!e) throw new Error(`Dimension ${o} must be >= 0`);
      if (o < -1) throw new Error(`Dimension ${o} must be >= -1`);
      o = -1;
    }
    t10.push(o);
  }
  return t10;
}
function Af(r15, e, t10, o, n, s, a, i, p, u) {
  return new iI(r15, e, t10, o, n, s, a, i, p, u).compute();
}
function up(r15, e, t10, o) {
  let n = r15 === e, s = r15 < e && t10 < 0, a = e < r15 && t10 > 1;
  if (n || s || a) return y.makeZerosTypedArray(0, o);
  let i = Math.abs(Math.ceil((e - r15) / t10)), p = y.makeZerosTypedArray(i, o);
  e < r15 && t10 === 1 && (t10 = -1), p[0] = r15;
  for (let u = 1; u < p.length; u++) p[u] = p[u - 1] + t10;
  return p;
}
var uI = jt((r15) => 1 / Math.sqrt(r15));
var mY = Ar(ls, uI);
var $_ = { kernelName: ls, backendName: "cpu", kernelFunc: mY };
function zs(r15, e, t10, o, n, s, a, i, p, u) {
  let c = [o / n, n], l = r15.values, m = e.values;
  if (o === 0) return me(t10, e.dtype);
  let d = p instanceof tt ? p : me(c, e.dtype);
  typeof p == "string" || typeof p == "number" ? d.values.fill(p) : typeof p == "boolean" && d.values.fill(+p);
  for (let f = 0; f < s; f++) {
    let h = [], g = 0;
    for (let x = 0; x < a; x++) {
      let b = l[f * a + x];
      h.push(b), g += b * i[x];
    }
    if (g < 0 || g >= o / n) throw new Error(`Invalid indices: ${h} does not index into ${t10}`);
    for (let x = 0; x < n; x++) u ? d.values[g * n + x] += m[f * n + x] : d.values[g * n + x] = e.rank === 0 ? m[0] : m[f * n + x];
  }
  return d;
}
var R_ = jt((r15) => 1 / (1 + Math.exp(-r15)));
var pI = Ie(bs, (r15) => 1 / (1 + Math.exp(-r15)));
var D_ = { kernelName: bs, backendName: "cpu", kernelFunc: pI };
function pp(r15, e, t10, o, n) {
  let s = pt.isSliceContinous(o, e, t10), a = y.sizeFromShape(t10), i = y.computeStrides(o);
  if (s) {
    let l = pt.computeFlatOffset(e, i);
    return n === "string" ? r15.slice(l, l + a) : r15.subarray(l, l + a);
  }
  let p = n === "string" ? w.fromUint8ToStringArray(r15) : r15, u = me(o, n, p), c = me(t10, n);
  for (let l = 0; l < c.size; ++l) {
    let m = c.indexToLoc(l), d = m.map((f, h) => f + e[h]);
    c.set(u.get(...d), ...m);
  }
  return n === "string" ? w.fromStringArrayToUint8(c.values) : c.values;
}
function Ao(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { begin: s, size: a } = o;
  Q(n, "slice");
  let [i, p] = pt.parseSliceParams(n, s, a);
  pt.assertParamsValid(n, i, p);
  let u = t10.data.get(n.dataId).values, c = pp(u, i, p, n.shape, n.dtype);
  return t10.makeTensorInfo(p, n.dtype, c);
}
var A_ = { kernelName: ha, backendName: "cpu", kernelFunc: Ao };
function Ff(r15, e, t10, o, n, s, a) {
  let i = e[0], p = s[0], u = new Array(p), c = new Array(i), l = e[1];
  if (p === 0) {
    if (i !== 0) throw new Error(w.getSparseFillEmptyRowsIndicesDenseShapeMismatch(i));
    let g = y.getArrayFromDType(t10, 0), x = y.getArrayFromDType(n, 0);
    return [g, [0, l], x, u, c];
  }
  let m = true, d = 0, f = new Array(p).fill(0);
  for (let g = 0; g < i; ++g) {
    let x = r15[g * l];
    if (x < 0) throw new Error(w.getSparseFillEmptyRowsNegativeIndexErrorMessage(g, x));
    if (x >= p) throw new Error(w.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g, x, p));
    ++f[x], m = m && x >= d, d = x;
  }
  let h = true;
  for (let g = 0; g < p; ++g) {
    let x = f[g] === 0;
    u[g] = x, h = h && !x, f[g] = Math.max(f[g], 1), g > 0 && (f[g] += f[g - 1]);
  }
  if (h && m) {
    let g = r15, x = o;
    for (let b = 0; b < i; ++b) c[b] = b;
    return [g, [i, l], x, u, c];
  } else {
    let g = f[p - 1], x = y.getArrayFromDType(t10, g * l), b = y.getArrayFromDType(n, g), C = new Array(p).fill(0);
    for (let S = 0; S < i; ++S) {
      let k = r15[S * l], _ = C[k], $ = (k === 0 ? 0 : f[k - 1]) + _;
      C[k]++;
      for (let R = 0; R < l; ++R) x[$ * l + R] = r15[S * l + R];
      b[$] = o[S], c[S] = $;
    }
    for (let S = 0; S < p; ++S) if (C[S] === 0) {
      let _ = S === 0 ? 0 : f[S - 1];
      x[_ * l + 0] = S;
      for (let $ = 1; $ < l; ++$) x[_ * l + $] = 0;
      b[_] = a;
    }
    return [x, [g, l], b, u, c];
  }
}
function Pf(r15, e, t10, o, n) {
  let s = y.sizeFromShape(o), a = e[0], i = n.length, p = [], u = 1, c = -1;
  for (let g = 0; g < i; ++g) {
    let x = n[g];
    if (x === -1) {
      if (c !== -1) throw new Error(w.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(c, g));
      c = g, p.push(1);
    } else {
      if (x < 0) throw new Error(w.getSparseReshapeNegativeOutputDimErrorMessage(g, x));
      u *= x, p.push(x);
    }
  }
  if (c !== -1) {
    if (u <= 0) throw new Error(w.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());
    let g = Math.trunc(s / u);
    if (u * g !== s) throw new Error(w.getSparseReshapeInputOutputMultipleErrorMessage(o, p));
    p[c] = g;
  }
  if (y.sizeFromShape(p) !== s) throw new Error(w.getSparseReshapeInputOutputMismatchErrorMessage(o, p));
  let m = o.length, d = [];
  if (m > 0) {
    d[m - 1] = 1;
    for (let g = m - 2; g >= 0; --g) d[g] = d[g + 1] * o[g + 1];
  }
  let f = [];
  if (i > 0) {
    f[i - 1] = 1;
    for (let g = i - 2; g >= 0; --g) f[g] = f[g + 1] * p[g + 1];
  }
  let h = y.getArrayFromDType(t10, a * i);
  for (let g = 0; g < a; ++g) {
    let x = 0;
    for (let b = 0; b < m; ++b) x += r15[g * m + b] * d[b];
    for (let b = 0; b < i; ++b) h[g * i + b] = Math.trunc(x / f[b]), x %= f[b];
  }
  return [h, [a, i], p];
}
function Sc(r15, e, t10, o, n, s = false, a = 0) {
  let i = o.length, p = [e[0], r15.length / e[0]], u = p[1], l = i > 0 ? n[i - 1] + 1 : 0;
  if (l < 0) throw new Error(w.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());
  let m = e.slice();
  m[0] = l;
  let d = m.reduce((C, S) => C * S, 1), f = y.getArrayFromDType(t10, d);
  if (i === 0) return l > 0 && f.fill(a), [f, m];
  if (l <= 0) throw new Error(w.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());
  let h = 0, g = 1, x = 0, b = n[h];
  for (; ; ) {
    let C = 0;
    if (g < i) {
      if (C = n[g], b === C) {
        ++g;
        continue;
      }
      if (b >= C) throw new Error(w.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage());
    }
    if (b < 0 || b >= l) throw new Error(w.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(b, l));
    b > x && f.fill(a, x * u, b * u);
    for (let S = h; S < g; ++S) {
      let k = o[S];
      if (k < 0 || k >= p[0]) throw new Error(w.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(S, o[S], p[0]));
      for (let _ = 0; _ < u; _++) f[b * u + _] += r15[k * u + _];
    }
    if (s) for (let S = 0; S < u; S++) f[b * u + S] /= g - h;
    if (h = g, ++g, x = b + 1, b = C, g > i) break;
  }
  return x < l && f.fill(a, x * u, l * u), [f, m];
}
var F_ = jt((r15) => Math.sqrt(r15));
var dY = Ie(ws, (r15) => Math.sqrt(r15));
var P_ = { kernelName: ws, backendName: "cpu", kernelFunc: dY };
var cI = Ve(((r15, e) => {
  let t10 = r15 - e;
  return t10 * t10;
}));
var fY = Ye(ks, cI);
var O_ = { kernelName: ks, backendName: "cpu", kernelFunc: fY };
var lI = jt((r15, e) => {
  let { pattern: t10, replaceGlobal: o, rewrite: n } = e;
  return r15.replace(new RegExp(t10, o ? "g" : ""), n);
});
var hY = Ar(Ru, lI);
var M_ = { kernelName: Ru, backendName: "cpu", kernelFunc: hY };
function Of(r15, e, t10, o) {
  let n = me(r15, e.dtype);
  for (let s = 0; s < n.size; s++) {
    let a = n.indexToLoc(s), i = new Array(a.length);
    for (let p = 0; p < i.length; p++) i[p] = a[p] * t10[p] + o[p];
    n.set(e.get(...i), ...a);
  }
  return n;
}
var mI = class {
  constructor(e, t10, o, n, s, a) {
    this.separator = y.encodeString(e), this.nGramWidths = t10, this.leftPad = y.encodeString(o), this.rightPad = y.encodeString(n), this.padWidth = s, this.preserveShort = a;
  }
  getPadWidth(e) {
    return Math.min(this.padWidth < 0 ? e - 1 : this.padWidth, e - 1);
  }
  getNumNGrams(e, t10) {
    let o = this.getPadWidth(t10);
    return Math.max(0, e + 2 * o - t10 + 1);
  }
  createNGrams(e, t10, o, n, s, a) {
    for (let i = 0; i < s; ++i) {
      let p = this.getPadWidth(a), u = Math.max(0, p - i), c = Math.max(0, p - (s - (i + 1))), l = a - (u + c), m = t10 + (u > 0 ? 0 : i - p), d = 0;
      d += u * this.leftPad.length;
      for (let b = 0; b < l; ++b) d += e[m + b].length;
      d += c * this.rightPad.length;
      let f = u + c + l - 1;
      d += f * this.separator.length, o[n + i] = new Uint8Array(d);
      let h = o[n + i], g = 0, x = (b) => b.forEach((C) => h[g++] = C);
      for (let b = 0; b < u; ++b) x(this.leftPad), x(this.separator);
      for (let b = 0; b < l - 1; ++b) x(e[m + b]), x(this.separator);
      if (l > 0) {
        x(e[m + l - 1]);
        for (let b = 0; b < c; ++b) x(this.separator), x(this.rightPad);
      } else {
        for (let b = 0; b < c - 1; ++b) x(this.rightPad), x(this.separator);
        x(this.rightPad);
      }
    }
  }
  compute(e, t10) {
    let o = e.length, n = t10.length;
    if (n > 0) {
      let p = t10[0];
      if (p !== 0) throw new Error(`First split value must be 0, got ${p}`);
      for (let u = 1; u < n; ++u) {
        let c = t10[u] >= p;
        if (c = c && t10[u] <= o, !c) throw new Error(`Invalid split value ${t10[u]}, must be in [${p}, ${o}]`);
        p = t10[u];
      }
      if (p !== o) throw new Error(`Last split value must be data size. Expected ${o}, got ${p}`);
    }
    let s = n - 1, a = y.getArrayFromDType("int32", n);
    if (o === 0 || n === 0) {
      let p = new Array(o);
      for (let u = 0; u <= s; ++u) a[u] = 0;
      return [p, a];
    }
    a[0] = 0;
    for (let p = 1; p <= s; ++p) {
      let u = t10[p] - t10[p - 1], c = 0;
      this.nGramWidths.forEach((l) => {
        c += this.getNumNGrams(u, l);
      }), this.preserveShort && u > 0 && c === 0 && (c = 1), a[p] = a[p - 1] + c;
    }
    let i = new Array(a[s]);
    for (let p = 0; p < s; ++p) {
      let u = t10[p], c = a[p];
      if (this.nGramWidths.forEach((l) => {
        let m = t10[p + 1] - t10[p], d = this.getNumNGrams(m, l);
        this.createNGrams(e, u, i, c, d, l), c += d;
      }), this.preserveShort && c === a[p]) {
        let l = t10[p + 1] - t10[p];
        if (l === 0) continue;
        let m = l + 2 * this.padWidth;
        this.createNGrams(e, u, i, c, 1, m);
      }
    }
    return [i, a];
  }
};
function cp(r15, e, t10, o, n, s, a, i) {
  return new mI(t10, o, n, s, a, i).compute(r15, e);
}
function gY(r15, e, t10, o) {
  if (!r15.length) return;
  if (e.length === 0) {
    for (let s = 0; s < r15.length; ++s) o.push(r15.subarray(s, s + 1));
    return;
  }
  if (e.length === 1) {
    let s = e[0], a = r15.indexOf(s);
    for (; a !== -1; ) {
      let i = r15.subarray(0, a);
      (!t10 || i.length !== 0) && o.push(i), r15 = r15.subarray(a + 1), a = r15.indexOf(s);
    }
    (!t10 || r15.length !== 0) && o.push(r15);
    return;
  }
  let n = 0;
  for (let s = 0; s < r15.length + 1; s++) if (s === r15.length || e.indexOf(r15[s]) !== -1) {
    let a = r15.subarray(n, s);
    (!t10 || a.length !== 0) && o.push(a), n = s + 1;
  }
}
function lp(r15, e, t10) {
  let o = r15.length, n = [], s = 0, a = 0, i = new Array(o);
  for (let m = 0; m < o; ++m) {
    let d = n.length;
    gY(r15[m], e, t10, n);
    let f = n.length - d;
    i[m] = f, s += f, a = Math.max(a, f);
  }
  let p = y.getArrayFromDType("int32", s * 2), u = new Array(s), c = [o, a], l = 0;
  for (let m = 0; m < o; ++m) for (let d = 0; d < i[m]; ++d) p[l * 2] = m, p[l * 2 + 1] = d, u[l] = n[l], ++l;
  return [p, u, c];
}
function mp(r15, e) {
  let t10 = y.getArrayFromDType("int32", r15.length);
  for (let o = 0; o < r15.length; ++o) t10[o] = y.fingerPrint64(r15[o]).modulo(e).getLowBitsUnsigned();
  return t10;
}
var dI = Ve(((r15, e) => r15 - e));
var xY = bc(((r15, e, t10, o) => ({ real: r15 - t10, imag: e - o })));
var Vl = Ye("Sub", dI, xY);
var L_ = { kernelName: "Sub", backendName: "cpu", kernelFunc: Vl };
function Mf(r15, e) {
  let t10 = new Array(r15.rank);
  for (let n = 0; n < t10.length; n++) t10[n] = r15.shape[n] * e[n];
  let o = me(t10, r15.dtype);
  for (let n = 0; n < o.values.length; ++n) {
    let s = o.indexToLoc(n), a = new Array(r15.rank);
    for (let p = 0; p < a.length; p++) a[p] = s[p] % r15.shape[p];
    let i = r15.locToIndex(a);
    o.values[n] = r15.values[i];
  }
  return o;
}
var Wl = (r15, e) => {
  let t10 = e.value - r15.value;
  return t10 === 0 ? r15.index - e.index : t10;
};
function B_(r15, e, t10 = 0, o = r15.length - 1) {
  for (; o > t10; ) {
    if (o - t10 > 600) {
      let i = o - t10 + 1, p = e - t10 + 1, u = Math.log(i), c = 0.5 * Math.exp(2 * u / 3), l = 0.5 * Math.sqrt(u * c * (i - c) / i) * Math.sign(p - i / 2), m = Math.max(t10, Math.floor(e - p * c / i + l)), d = Math.min(o, Math.floor(e + (i - p) * c / i + l));
      B_(r15, e, m, d);
    }
    let n = r15[e], s = t10, a = o;
    for (y.swap(r15, t10, e), Wl(r15[o], n) > 0 && y.swap(r15, t10, o); s < a; ) {
      for (y.swap(r15, s, a), s++, a--; Wl(r15[s], n) < 0; ) s = s + 1;
      for (; Wl(r15[a], n) > 0; ) a = a - 1;
    }
    Wl(r15[t10], n) === 0 ? y.swap(r15, t10, a) : (a = a + 1, y.swap(r15, a, o)), a <= e && (t10 = a + 1), e <= a && (o = a - 1);
  }
}
function Lf(r15, e, t10, o, n) {
  let s = e[e.length - 1], [a, i] = [r15.length / s, s], p = y.getTypedArrayFromDType(t10, a * o), u = y.getTypedArrayFromDType("int32", a * o);
  for (let l = 0; l < a; l++) {
    let m = l * i, d = r15.subarray(m, m + i), f = new Array(d.length);
    d.forEach((b, C) => f[C] = { value: b, index: C }), o < f.length && (B_(f, o), f = f.slice(0, o)), n && f.sort(Wl);
    let h = l * o, g = p.subarray(h, h + o), x = u.subarray(h, h + o);
    for (let b = 0; b < o; b++) g[b] = f[b].value, x[b] = f[b].index;
  }
  let c = e.slice();
  return c[c.length - 1] = o, [me(c, t10, p), me(c, "int32", u)];
}
function dp(r15, e, t10, o) {
  let n = y.parseAxisParam(e, t10)[0], s = [1, t10[0], 1];
  for (let f = 0; f < n; f++) s[0] *= t10[f];
  s[1] = t10[n];
  for (let f = n + 1; f < t10.length; f++) s[2] *= t10[f];
  let a = /* @__PURE__ */ new Map(), i = new Int32Array(t10[n]), p = new tt(s, o, r15), u = [], c = s[0] === 1 && s[2] === 1;
  for (let f = 0; f < t10[n]; f++) {
    let h;
    if (c) h = r15[f].toString();
    else {
      let x = [];
      for (let b = 0; b < s[0]; b++) for (let C = 0; C < s[2]; C++) x.push(p.get(b, f, C));
      h = x.join(",");
    }
    let g = a.get(h);
    if (g != null) i[f] = g;
    else {
      let x = a.size;
      a.set(h, x), i[f] = x, u.push(f);
    }
  }
  let l = s.slice();
  l[1] = a.size;
  let m = new tt(l, o);
  u.forEach((f, h) => {
    for (let g = 0; g < s[0]; g++) for (let x = 0; x < s[2]; x++) m.set(p.get(g, f, x), g, h, x);
  });
  let d = t10.slice();
  return d[n] = l[1], { outputValues: m.values, outputShape: d, indices: i };
}
var yY = "4.22.0";
tu("cpu", () => new xc(), 1);
var fI = Ie("Elu", (r15) => r15 >= 0 ? r15 : Math.exp(r15) - 1);
var z_ = { kernelName: "Elu", backendName: "cpu", kernelFunc: fI };
function hI(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { alpha: s } = o;
  Q([n], "leakyRelu");
  let a = y.sizeFromShape(n.shape), i = t10.data.get(n.dataId).values, p = y.getTypedArrayFromDType("float32", a);
  for (let u = 0; u < i.length; u++) p[u] = i[u] < 0 ? s * i[u] : i[u];
  return t10.makeTensorInfo(n.shape, "float32", p);
}
var V_ = { kernelName: $n, backendName: "cpu", kernelFunc: hI };
var bY = Ve((r15, e) => r15 < 0 ? e * r15 : r15);
function gI(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o, alpha: n } = e;
  Q([o, n], "prelu");
  let s = t10.data.get(o.dataId).values, a = t10.data.get(n.dataId).values, [i, p] = bY(o.shape, n.shape, s, a, "float32");
  return t10.makeTensorInfo(p, "float32", i);
}
var W_ = { kernelName: rs, backendName: "cpu", kernelFunc: gI };
var xI = Ie(ss, (r15) => Math.max(0, r15));
var U_ = { kernelName: ss, backendName: "cpu", kernelFunc: xI };
var yI = Ie(us, (r15) => Math.min(Math.max(0, r15), 6));
var G_ = { kernelName: us, backendName: "cpu", kernelFunc: yI };
function fp(r15, e, t10, o, n) {
  if (t10 === "linear") return lr({ inputs: { x: e }, backend: r15 });
  if (t10 === "relu") return xI({ inputs: { x: e }, backend: r15 });
  if (t10 === "elu") return fI({ inputs: { x: e }, backend: r15 });
  if (t10 === "relu6") return yI({ inputs: { x: e }, backend: r15 });
  if (t10 === "prelu") return gI({ inputs: { x: e, alpha: o }, backend: r15 });
  if (t10 === "leakyrelu") return hI({ inputs: { x: e }, backend: r15, attrs: { alpha: n } });
  if (t10 === "sigmoid") return pI({ inputs: { x: e }, backend: r15 });
  throw new Error(`Activation ${t10} has not been implemented for the CPU backend.`);
}
function We(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { shape: s } = o, a = y.sizeFromShape(n.shape), i = y.inferFromImplicitShape(s, a), p = y.sizeFromShape(i);
  y.assert(a === p, () => `The new shape (${i}) has ${p} elements and the old shape (${n.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`), t10.incRef(n.dataId);
  let u = t10.data.get(n.dataId);
  if (u.complexTensorInfos != null) {
    let c = u.complexTensorInfos.real, l = u.complexTensorInfos.imag;
    c.shape = i, l.shape = i;
  }
  return { dataId: n.dataId, shape: i, dtype: n.dtype };
}
var H_ = { kernelName: da, backendName: "cpu", kernelFunc: We };
function bI(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { a: n, b: s } = e, { transposeA: a, transposeB: i } = o;
  Q([n, s], "matMul");
  let p = n.shape.length, u = s.shape.length, c = a ? n.shape[p - 2] : n.shape[p - 1], l = i ? s.shape[u - 1] : s.shape[u - 2], m = a ? n.shape[p - 1] : n.shape[p - 2], d = i ? s.shape[u - 2] : s.shape[u - 1], f = n.shape.slice(0, -2), h = s.shape.slice(0, -2), g = y.sizeFromShape(f), x = y.sizeFromShape(h), C = Sr.assertAndGetBroadcastShape(n.shape.slice(0, -2), s.shape.slice(0, -2)).concat([m, d]);
  y.assert(c === l, () => `Error in matMul: inner shapes (${c}) and (${l}) of Tensors with shapes ${n.shape} and ${s.shape} and transposeA=${a} and transposeB=${i} must match.`);
  let S = a ? [g, c, m] : [g, m, c], k = i ? [x, d, l] : [x, l, d], _ = We({ inputs: { x: n }, backend: t10, attrs: { shape: S } }), $ = We({ inputs: { x: s }, backend: t10, attrs: { shape: k } }), R = a ? _.shape[1] : _.shape[2], D = a ? _.shape[2] : _.shape[1], P = i ? $.shape[1] : $.shape[2], O = Math.max(g, x), M = t10.data.get(_.dataId).values, L = t10.data.get($.dataId).values, B = y.computeStrides(_.shape), z = y.computeStrides($.shape), [U, j, q] = a ? [B[0], 1, B[1]] : [B[0], B[1], 1], [Y, J, re] = i ? [1, z[1], z[0]] : [z[1], 1, z[0]], ne = D * P, ee = me([O, D, P], _.dtype), oe = ee.values, ie = t10.blockSize;
  for (let le = 0; le < O; le++) {
    let be = le % g, _e = le % x;
    for (let ve = 0; ve < D; ve += ie) {
      let Fe = Math.min(ve + ie, D);
      for (let Pe = 0; Pe < P; Pe += ie) {
        let st = Math.min(Pe + ie, P);
        for (let ct = 0; ct < R; ct += ie) {
          let He = Math.min(ct + ie, R);
          for (let lt = ve; lt < Fe; lt++) for (let it = Pe; it < st; it++) {
            let ht = 0;
            for (let gt = ct; gt < He; gt++) {
              let Lr = M[be * U + lt * j + gt * q], Mt = L[gt * Y + it * J + _e * re];
              ht += Lr * Mt;
            }
            oe[le * ne + (lt * P + it)] += ht;
          }
        }
      }
    }
  }
  return t10.disposeIntermediateTensorInfo(_), t10.disposeIntermediateTensorInfo($), t10.makeTensorInfo(C, ee.dtype, ee.values);
}
var K_ = { kernelName: Zo, backendName: "cpu", kernelFunc: bI };
function CY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { a: n, b: s, bias: a, preluActivationWeights: i } = e, { transposeA: p, transposeB: u, activation: c, leakyreluAlpha: l } = o, m, d, f, h = [];
  m = bI({ inputs: { a: n, b: s }, attrs: { transposeA: p, transposeB: u }, backend: t10 }), a && (d = Pa({ inputs: { a: m, b: a }, backend: t10 }), h.push(m), m = d), c && (f = fp(t10, m, c, i, l), h.push(m), m = f);
  for (let x of h) t10.disposeIntermediateTensorInfo(x);
  return m;
}
var q_ = { kernelName: So, backendName: "cpu", kernelFunc: CY };
var wY = Ie(Vo, (r15) => Math.acos(r15));
var j_ = { kernelName: Vo, backendName: "cpu", kernelFunc: wY };
var SY = Ie(Wo, (r15) => Math.acosh(r15));
var X_ = { kernelName: Wo, backendName: "cpu", kernelFunc: SY };
function IY(r15) {
  let { inputs: e, backend: t10 } = r15, o = e;
  Q(e, "addN");
  let n = o.map((i) => t10.data.get(i.dataId).values), s = me(o[0].shape, o[0].dtype), a = s.values;
  for (let i = 0; i < o.length; i++) {
    let p = n[i];
    for (let u = 0; u < a.length; u++) a[u] += p[u];
  }
  return t10.makeTensorInfo(s.shape, s.dtype, s.values);
}
var Y_ = { kernelName: Uo, backendName: "cpu", kernelFunc: IY };
function vY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o;
  Q(n, "all");
  let i = y.parseAxisParam(s, n.shape), p = i, u = w.getAxesPermutation(p, n.shape.length), c = n;
  u != null && (c = St({ inputs: { x: n }, backend: t10, attrs: { perm: u } }), p = w.getInnerMostAxes(p.length, n.shape.length)), w.assertAxesAreInnerMostDims("all", p, c.shape.length);
  let [l, m] = w.computeOutAndReduceShapes(c.shape, p), d = y.sizeFromShape(m), f = y.makeZerosTypedArray(y.sizeFromShape(l), c.dtype), h = t10.data.get(c.dataId).values;
  for (let x = 0; x < f.length; ++x) {
    let b = x * d, C = h[b];
    for (let S = 0; S < d; ++S) {
      let k = h[b + S];
      C = C && k;
    }
    f[x] = C;
  }
  u != null && t10.disposeIntermediateTensorInfo(c);
  let g = t10.makeTensorInfo(l, c.dtype, f);
  if (a) {
    let x = w.expandShapeToKeepDim(l, i), b = We({ inputs: { x: g }, backend: t10, attrs: { shape: x } });
    return t10.disposeIntermediateTensorInfo(g), b;
  }
  return g;
}
var Q_ = { kernelName: "All", backendName: "cpu", kernelFunc: vY };
function kY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o;
  Q(n, "any");
  let i = y.parseAxisParam(s, n.shape), p = i, u = w.getAxesPermutation(p, n.shape.length), c = n;
  u != null && (c = St({ inputs: { x: n }, backend: t10, attrs: { perm: u } }), p = w.getInnerMostAxes(p.length, n.shape.length)), w.assertAxesAreInnerMostDims("any", p, c.shape.length);
  let [l, m] = w.computeOutAndReduceShapes(c.shape, p), d = y.sizeFromShape(m), f = y.makeZerosTypedArray(y.sizeFromShape(l), c.dtype), h = t10.data.get(c.dataId).values;
  for (let x = 0; x < f.length; ++x) {
    let b = x * d, C = h[b];
    for (let S = 0; S < d; ++S) {
      let k = h[b + S];
      C = C || k;
    }
    f[x] = C;
  }
  u != null && t10.disposeIntermediateTensorInfo(c);
  let g = t10.makeTensorInfo(l, c.dtype, f);
  if (a) {
    let x = w.expandShapeToKeepDim(l, i), b = We({ inputs: { x: g }, backend: t10, attrs: { shape: x } });
    return t10.disposeIntermediateTensorInfo(g), b;
  }
  return g;
}
var Z_ = { kernelName: "Any", backendName: "cpu", kernelFunc: kY };
function NY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s } = o;
  Q(n, "argMax");
  let a = y.parseAxisParam(s, n.shape), i = w.getAxesPermutation(a, n.shape.length), p = n, u = [];
  i != null && (p = St({ inputs: { x: n }, backend: t10, attrs: { perm: i } }), u.push(p), a = w.getInnerMostAxes(a.length, p.shape.length)), a = [a[0]], w.assertAxesAreInnerMostDims("argMax", a, p.shape.length);
  let [c, l] = w.computeOutAndReduceShapes(p.shape, a), m = y.sizeFromShape(c), d = y.makeZerosTypedArray(m, "int32"), f = y.sizeFromShape(l), h = t10.data.get(p.dataId).values;
  for (let g = 0; g < d.length; ++g) {
    let x = g * f, b = h[x], C = 0;
    for (let S = 0; S < f; ++S) {
      let k = h[x + S];
      k > b && (b = k, C = S);
    }
    d[g] = C;
  }
  return u.forEach((g) => t10.disposeIntermediateTensorInfo(g)), t10.makeTensorInfo(c, "int32", d);
}
var J_ = { kernelName: Ys, backendName: "cpu", kernelFunc: NY };
function TY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s } = o;
  Q(n, "argMin");
  let a = y.parseAxisParam(s, n.shape), i = w.getAxesPermutation(a, n.shape.length), p = n, u = [];
  i != null && (p = St({ inputs: { x: n }, backend: t10, attrs: { perm: i } }), u.push(p), a = w.getInnerMostAxes(a.length, p.shape.length)), a = [a[0]], w.assertAxesAreInnerMostDims("argMin", a, p.shape.length);
  let [c, l] = w.computeOutAndReduceShapes(p.shape, a), m = y.sizeFromShape(c), d = y.makeZerosTypedArray(m, "int32"), f = y.sizeFromShape(l), h = t10.data.get(p.dataId).values;
  for (let g = 0; g < d.length; ++g) {
    let x = g * f, b = h[x], C = 0;
    for (let S = 0; S < f; ++S) {
      let k = h[x + S];
      k < b && (b = k, C = S);
    }
    d[g] = C;
  }
  return u.forEach((g) => t10.disposeIntermediateTensorInfo(g)), t10.makeTensorInfo(c, "int32", d);
}
var eE = { kernelName: Qs, backendName: "cpu", kernelFunc: TY };
var _Y = Ie(Ko, (r15) => Math.asin(r15));
var tE = { kernelName: Ko, backendName: "cpu", kernelFunc: _Y };
var EY = Ie(qo, (r15) => Math.asinh(r15));
var rE = { kernelName: qo, backendName: "cpu", kernelFunc: EY };
var $Y = Ie(jo, (r15) => Math.atan(r15));
var oE = { kernelName: jo, backendName: "cpu", kernelFunc: $Y };
var RY = Ve((r15, e) => Math.atan2(r15, e));
var DY = Ye(Yo, RY);
var nE = { kernelName: Yo, backendName: "cpu", kernelFunc: DY };
var AY = Ie(Xo, (r15) => Math.atanh(r15));
var sE = { kernelName: Xo, backendName: "cpu", kernelFunc: AY };
function vc(r15, e, t10, o, n, s) {
  let a = n.strideHeight, i = n.strideWidth, p = n.dilationHeight, u = n.dilationWidth, c = n.effectiveFilterHeight, l = n.effectiveFilterWidth, m = n.padInfo.top, d = n.padInfo.left, f = s === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, h = me(n.outShape, t10), g = h.values, x = n.outShape[1] * n.outShape[2] * n.outShape[3], b = n.outShape[2] * n.outShape[3], C = n.outShape[3];
  for (let S = 0; S < n.batchSize; ++S) {
    let k = S * x, _ = S * o[0];
    for (let $ = 0; $ < n.inChannels; ++$) for (let R = 0; R < n.outHeight; ++R) {
      let D = R * a - m, P = Math.max(0, D), O = Math.min(n.inHeight, c + D), M = k + R * b;
      for (let L = 0; L < n.outWidth; ++L) {
        let B = L * i - d, z = Math.max(0, B), U = Math.min(n.inWidth, l + B), j = f, q = 0, Y = 0;
        for (let re = P; re < O; re += p) {
          let ne = _ + re * o[1];
          for (let ee = z; ee < U; ee += u) {
            let oe = ne + ee * o[2], ie = r15[oe + $];
            s === "max" && ie > j ? j = ie : s === "avg" && (q += ie, Y++);
          }
          if (isNaN(j)) break;
        }
        let J = M + L * C + $;
        g[J] = s === "avg" ? q / Y : j;
      }
    }
  }
  return h;
}
function Bf(r15, e, t10, o, n = false, s = false) {
  let a = me(o.outShape, "int32"), i = o.strideHeight, p = o.strideWidth, u = o.dilationHeight, c = o.dilationWidth, l = o.effectiveFilterHeight, m = o.effectiveFilterWidth, d = o.padInfo.top, f = o.padInfo.left, h = me(e, t10, r15);
  for (let g = 0; g < o.batchSize; ++g) for (let x = 0; x < o.inChannels; ++x) for (let b = 0; b < o.outHeight; ++b) {
    let C = b * i - d, S = C;
    for (; S < 0; ) S += u;
    let k = Math.min(o.inHeight, l + C);
    for (let _ = 0; _ < o.outWidth; ++_) {
      let $ = _ * p - f, R = $;
      for (; R < 0; ) R += c;
      let D = Math.min(o.inWidth, m + $), P = Number.NEGATIVE_INFINITY, O = -1;
      for (let M = S; M < k; M += u) {
        let L = M - C;
        for (let B = R; B < D; B += c) {
          let z = B - $, U = h.get(g, M, B, x);
          U > P && (P = U, n ? O = s ? ((g * o.inHeight + M) * o.inWidth + B) * o.inChannels + x : (M * o.inWidth + B) * o.inChannels + x : O = L * m + z);
        }
      }
      a.set(O, g, b, _, x);
    }
  }
  return a;
}
function zf(r15, e, t10, o, n, s) {
  let a = n.strideDepth, i = n.strideHeight, p = n.strideWidth, u = n.dilationDepth, c = n.dilationHeight, l = n.dilationWidth, m = n.effectiveFilterDepth, d = n.effectiveFilterHeight, f = n.effectiveFilterWidth, h = n.padInfo.front, g = n.padInfo.top, x = n.padInfo.left, b = s === "max" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, C = me(n.outShape, t10), S = C.values, k = n.outShape[1] * n.outShape[2] * n.outShape[3] * n.outShape[4], _ = n.outShape[2] * n.outShape[3] * n.outShape[4], $ = n.outShape[3] * n.outShape[4], R = n.outShape[4];
  for (let D = 0; D < n.batchSize; ++D) {
    let P = D * k, O = D * o[0];
    for (let M = 0; M < n.inChannels; ++M) for (let L = 0; L < n.outDepth; ++L) {
      let B = L * a - h, z = B;
      for (; z < 0; ) z += u;
      let U = Math.min(n.inDepth, m + B), j = P + L * _;
      for (let q = 0; q < n.outHeight; ++q) {
        let Y = q * i - g, J = Y;
        for (; J < 0; ) J += c;
        let re = Math.min(n.inHeight, d + Y), ne = j + q * $;
        for (let ee = 0; ee < n.outWidth; ++ee) {
          let oe = ee * p - x, ie = oe;
          for (; ie < 0; ) ie += l;
          let le = Math.min(n.inWidth, f + oe), be = ne + ee * R, _e = b, ve = 0, Fe = 0;
          for (let st = z; st < U; st += u) {
            let ct = O + st * o[1];
            for (let He = J; He < re; He += c) {
              let lt = ct + He * o[2];
              for (let it = ie; it < le; it += l) {
                let ht = lt + it * o[3], gt = r15[ht + M];
                if (s === "max" && gt > _e ? _e = gt : s === "avg" && (ve += gt, Fe++), isNaN(_e)) break;
              }
              if (isNaN(_e)) break;
            }
            if (isNaN(_e)) break;
          }
          let Pe = be + M;
          S[Pe] = s === "avg" ? ve / Math.max(Fe, 1) : _e;
        }
      }
    }
  }
  return C;
}
function aE(r15, e) {
  let t10 = me(e.outShape, "int32"), o = e.strideDepth, n = e.strideHeight, s = e.strideWidth, a = e.dilationDepth, i = e.dilationHeight, p = e.dilationWidth, u = e.effectiveFilterDepth, c = e.effectiveFilterHeight, l = e.effectiveFilterWidth, m = e.padInfo.front, d = e.padInfo.top, f = 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 b = x * o - m, C = b;
    for (; C < 0; ) C += a;
    let S = Math.min(e.inDepth, u + b);
    for (let k = 0; k < e.outHeight; ++k) {
      let _ = k * n - d, $ = _;
      for (; $ < 0; ) $ += i;
      let R = Math.min(e.inHeight, c + _);
      for (let D = 0; D < e.outWidth; ++D) {
        let P = D * s - f, O = P;
        for (; O < 0; ) O += p;
        let M = Math.min(e.inWidth, l + P), L = Number.NEGATIVE_INFINITY, B = -1;
        for (let z = C; z < S; z += a) {
          let U = z - b;
          for (let j = $; j < R; j += i) {
            let q = j - _;
            for (let Y = O; Y < M; Y += p) {
              let J = Y - P, re = r15.get(h, z, j, Y, g);
              re >= L && (L = re, B = U * c * l + q * c + J);
            }
          }
        }
        t10.set(B, h, x, k, D, g);
      }
    }
  }
  return t10;
}
function FY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e;
  Q(n, "avgPool");
  let { filterSize: s, strides: a, pad: i, dimRoundingMode: p } = o, u = 1;
  y.assert(w.eitherStridesOrDilationsAreOne(a, u), () => `Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);
  let c = w.computePool2DInfo(n.shape, s, a, u, i, p), l;
  if (c.filterWidth === 1 && c.filterHeight === 1 && y.arraysEqual(c.inShape, c.outShape)) l = lr({ inputs: { x: n }, backend: t10 });
  else {
    let m = t10.data.get(n.dataId).values, d = y.computeStrides(n.shape), f = vc(m, n.shape, n.dtype, d, c, "avg");
    l = t10.makeTensorInfo(c.outShape, n.dtype, f.values);
  }
  return l;
}
var iE = { kernelName: Qo, backendName: "cpu", kernelFunc: FY };
function PY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { filterSize: s, strides: a, pad: i, dimRoundingMode: p, dataFormat: u } = o;
  Q(n, "avgPool3d");
  let c = w.computePool3DInfo(n.shape, s, a, 1, i, p, u), l = t10.data.get(n.dataId).values, m = zf(l, n.shape, n.dtype, y.computeStrides(n.shape), c, "avg");
  return t10.makeTensorInfo(m.shape, "float32", m.values);
}
var uE = { kernelName: Zs, backendName: "cpu", kernelFunc: PY };
function OY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s } = e, { filterSize: a, strides: i, pad: p, dimRoundingMode: u } = o;
  Q([n, s], "avgPool3DGrad");
  let c = w.computePool3DInfo(s.shape, a, i, 1, p, u), l = c.strideDepth, m = c.strideHeight, d = c.strideWidth, f = c.filterDepth, h = c.filterHeight, g = c.filterWidth, x = c.dilationDepth, b = c.dilationHeight, C = c.dilationWidth, S = c.effectiveFilterDepth, k = c.effectiveFilterHeight, _ = c.effectiveFilterWidth, $ = S - 1 - c.padInfo.front, R = _ - 1 - c.padInfo.left, D = k - 1 - c.padInfo.top, P = me(s.shape, "float32"), O = 1 / (f * h * g), M = t10.bufferSync(n);
  for (let L = 0; L < c.batchSize; ++L) for (let B = 0; B < c.inChannels; ++B) for (let z = 0; z < c.inDepth; ++z) for (let U = 0; U < c.inHeight; ++U) for (let j = 0; j < c.inWidth; ++j) {
    let q = z - $, Y = U - D, J = j - R, re = 0;
    for (let ne = 0; ne < S; ne += x) {
      let ee = (q + ne) / l;
      if (!(ee < 0 || ee >= c.outDepth || Math.floor(ee) !== ee)) for (let oe = 0; oe < k; oe += b) {
        let ie = (Y + oe) / m;
        if (!(ie < 0 || ie >= c.outHeight || Math.floor(ie) !== ie)) for (let le = 0; le < _; le += C) {
          let be = (J + le) / d;
          if (be < 0 || be >= c.outWidth || Math.floor(be) !== be) continue;
          let _e = M.get(L, ee, ie, be, B);
          re += _e;
        }
      }
    }
    P.set(re * O, L, z, U, j, B);
  }
  return t10.makeTensorInfo(P.shape, P.dtype, P.values);
}
var pE = { kernelName: Ri, backendName: "cpu", kernelFunc: OY };
function MY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s } = e, a = s;
  Q([n, s], "avgPoolGrad");
  let { filterSize: i, strides: p, pad: u } = o, c = w.computePool2DInfo(a.shape, i, p, 1, u), l = c.strideHeight, m = c.strideWidth, d = c.filterHeight, f = c.filterWidth, h = c.dilationHeight, g = c.dilationWidth, x = c.effectiveFilterHeight, b = c.effectiveFilterWidth, C = b - 1 - c.padInfo.left, S = x - 1 - c.padInfo.top, k = me(a.shape, "float32"), _ = 1 / (d * f), $ = t10.data.get(n.dataId).values, R = me(n.shape, "float32", $);
  for (let D = 0; D < c.batchSize; ++D) for (let P = 0; P < c.inChannels; ++P) for (let O = 0; O < c.inHeight; ++O) for (let M = 0; M < c.inWidth; ++M) {
    let L = O - S, B = M - C, z = 0;
    for (let U = 0; U < x; U += h) {
      let j = (L + U) / l;
      if (!(j < 0 || j >= c.outHeight || Math.floor(j) !== j)) for (let q = 0; q < b; q += g) {
        let Y = (B + q) / m;
        if (Y < 0 || Y >= c.outWidth || Math.floor(Y) !== Y) continue;
        let J = R.get(D, j, Y, P);
        z += J;
      }
    }
    k.set(z * _, D, O, M, P);
  }
  return t10.makeTensorInfo(k.shape, k.dtype, k.values);
}
var cE = { kernelName: $i, backendName: "cpu", kernelFunc: MY };
function LY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, scale: s, offset: a, mean: i, variance: p } = e;
  y.assert(i.shape.length === p.shape.length, () => "Batch normalization gradient requires mean and variance to have equal ranks."), y.assert(a == null || i.shape.length === a.shape.length, () => "Batch normalization gradient requires mean and offset to have equal ranks."), y.assert(s == null || i.shape.length === s.shape.length, () => "Batch normalization gradient requires mean and scale to have equal ranks."), Q([n, i, p, s, a], "batchNorm");
  let { varianceEpsilon: u } = o;
  u == null && (u = 1e-3);
  let c = t10.data.get(n.dataId).values, l = t10.data.get(i.dataId).values, m = t10.data.get(p.dataId).values, d = s ? t10.data.get(s.dataId).values : new Float32Array([1]), f = a ? t10.data.get(a.dataId).values : new Float32Array([0]), h = new Float32Array(c.length), g = f.length, x = d.length, b = m.length, C = l.length, S = 0, k = 0, _ = 0, $ = 0;
  for (let R = 0; R < c.length; ++R) h[R] = f[S++] + (c[R] - l[k++]) * d[_++] / Math.sqrt(m[$++] + u), S >= g && (S = 0), k >= C && (k = 0), _ >= x && (_ = 0), $ >= b && ($ = 0);
  return t10.makeTensorInfo(n.shape, n.dtype, h);
}
var lE = { kernelName: In, backendName: "cpu", kernelFunc: LY };
function BY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { blockShape: s, crops: a } = o;
  Q([n], "batchToSpaceND");
  let i = s.reduce((x, b) => x * b), p = w.getReshaped(n.shape, s, i), u = w.getPermuted(p.length, s.length), c = w.getReshapedPermuted(n.shape, s, i), l = w.getSliceBeginCoords(a, s.length), m = w.getSliceSize(c, a, s.length), d = We({ inputs: { x: n }, backend: t10, attrs: { shape: p } }), f = St({ inputs: { x: d }, backend: t10, attrs: { perm: u } }), h = We({ inputs: { x: f }, backend: t10, attrs: { shape: c } }), g = Ao({ inputs: { x: h }, backend: t10, attrs: { begin: l, size: m } });
  return t10.disposeIntermediateTensorInfo(d), t10.disposeIntermediateTensorInfo(f), t10.disposeIntermediateTensorInfo(h), g;
}
var mE = { kernelName: Js, backendName: "cpu", kernelFunc: BY };
function zY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, weights: s } = e, { size: a } = o, i = t10.data.get(n.dataId).values, p = t10.data.get(s.dataId).values, u = Cc(i, p, s.dtype, s.shape, a);
  return t10.makeTensorInfo([a], s.dtype, u);
}
var dE = { kernelName: Jo, backendName: "cpu", kernelFunc: zY };
function VY(r15) {
  let { inputs: e, backend: t10 } = r15, { s0: o, s1: n } = e, s = t10.data.get(o.dataId).values, a = t10.data.get(n.dataId).values, i = w.assertAndGetBroadcastShape(Array.from(s), Array.from(a));
  return t10.makeTensorInfo([i.length], "int32", Int32Array.from(i));
}
var fE = { kernelName: ea, backendName: "cpu", kernelFunc: VY };
var WY = Ie(bo, (r15, e) => {
  let t10 = e;
  return r15 > t10.clipValueMax ? t10.clipValueMax : r15 < t10.clipValueMin ? t10.clipValueMin : r15;
});
var hE = { kernelName: bo, backendName: "cpu", kernelFunc: WY };
var UY = (r15) => {
  let { x: e } = r15.inputs, t10 = r15.backend, o = new Float32Array(y.sizeFromShape(e.shape)), n = t10.data.get(e.dataId), s = n.complexTensorInfos.real, a = n.complexTensorInfos.imag, i = t10.data.get(s.dataId).values, p = t10.data.get(a.dataId).values;
  for (let u = 0; u < i.length; u++) {
    let c = i[u], l = p[u];
    o[u] = Math.hypot(c, l);
  }
  return t10.makeOutput(o, e.shape, "float32");
};
var gE = { kernelName: Ai, backendName: "cpu", kernelFunc: UY };
function Oa(r15) {
  let { inputs: e, backend: t10 } = r15, { input: o } = e, n = t10.data.get(o.dataId).complexTensorInfos.imag, s = t10.data.get(n.dataId).values;
  return t10.makeTensorInfo(n.shape, n.dtype, s);
}
var xE = { kernelName: Wi, backendName: "cpu", kernelFunc: Oa };
function hu(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { axis: n } = o, s = y.parseAxisParam(n, e[0].shape)[0], a = e.map((h) => h.shape);
  w.assertParamsConsistent(a, s);
  let i = w.computeOutShape(e.map((h) => h.shape), s);
  if (y.sizeFromShape(i) === 0) return t10.makeTensorInfo(i, e[0].dtype, []);
  let p = e.filter((h) => y.sizeFromShape(h.shape) > 0);
  if (p.length === 1) return lr({ inputs: { x: p[0] }, backend: t10 });
  if (p[0].dtype === "complex64") {
    let h = p.map((S) => $o({ inputs: { input: S }, backend: t10 })), g = p.map((S) => Oa({ inputs: { input: S }, backend: t10 })), x = hu({ inputs: h, backend: t10, attrs: { axis: s } }), b = hu({ inputs: g, backend: t10, attrs: { axis: s } }), C = Ht({ inputs: { real: x, imag: b }, backend: t10 });
    return h.forEach((S) => t10.disposeIntermediateTensorInfo(S)), g.forEach((S) => t10.disposeIntermediateTensorInfo(S)), t10.disposeIntermediateTensorInfo(x), t10.disposeIntermediateTensorInfo(b), C;
  }
  let u = p.map((h) => {
    let x = [-1, y.sizeFromShape(h.shape.slice(s))];
    return We({ inputs: { x: h }, backend: t10, attrs: { shape: x } });
  }), c = u.map((h) => ({ vals: t10.data.get(h.dataId).values, shape: h.shape }));
  i = w.computeOutShape(u.map((h) => h.shape), 1);
  let l = u[0].shape[0] === 1, m = ap(c, i, e[0].dtype, l), d = w.computeOutShape(p.map((h) => h.shape), s), f = t10.makeTensorInfo(d, e[0].dtype, m);
  return u.forEach((h) => t10.disposeIntermediateTensorInfo(h)), f;
}
var yE = { kernelName: ta, backendName: "cpu", kernelFunc: hu };
function CI(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s } = e, { strides: a, pad: i, dataFormat: p, dilations: u, dimRoundingMode: c } = o;
  Q([n, s], "conv2d");
  let l = w.convertConv2DDataFormat(p), m = w.computeConv2DInfo(n.shape, s.shape, a, u, i, c, false, l), d = m.filterHeight, f = m.filterWidth, h = m.dilationHeight, g = m.dilationWidth, x = m.padInfo.left, b = m.padInfo.top, C = m.dataFormat === "channelsLast", S = new tt(m.outShape, n.dtype), k = y.computeStrides(n.shape), _ = y.computeStrides(s.shape), $ = k[0], R = C ? k[1] : k[2], D = C ? k[2] : 1, P = C ? 1 : k[1], O = S.strides[0], M = C ? S.strides[1] : S.strides[2], L = C ? S.strides[2] : 1, B = C ? 1 : S.strides[1], z = t10.data.get(n.dataId).values, U = t10.data.get(s.dataId).values, j = S.values;
  for (let q = 0; q < m.batchSize; ++q) {
    let Y = q * $, J = q * O;
    for (let re = 0; re < m.outHeight; ++re) {
      let ne = J + re * M, ee = re * m.strideHeight - b;
      for (let oe = 0; oe < d; ++oe) {
        let ie = ee + oe * h;
        if (ie < 0 || ie >= m.inHeight) continue;
        let le = oe * _[0], be = Y + ie * R;
        for (let _e = 0; _e < m.outWidth; ++_e) {
          let ve = ne + _e * L, Fe = _e * m.strideWidth - x;
          for (let Pe = 0; Pe < f; ++Pe) {
            let st = Fe + Pe * g;
            if (st < 0 || st >= m.inWidth) continue;
            let ct = le + Pe * _[1], He = be + st * D, lt = ct;
            for (let it = 0; it < m.inChannels; ++it) {
              let ht = z[He + it * P];
              for (let gt = 0; gt < m.outChannels; ++gt) j[ve + gt * B] += ht * U[lt + gt];
              lt += m.outChannels;
            }
          }
        }
      }
    }
  }
  return t10.makeTensorInfo(S.shape, S.dtype, j);
}
var bE = { kernelName: tn, backendName: "cpu", kernelFunc: CI };
function GY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, dy: s } = e, { strides: a, pad: i, dataFormat: p, dimRoundingMode: u, filterShape: c } = o;
  Q([n, s], "conv2dBackpropFilter");
  let l = w.convertConv2DDataFormat(p), m = w.computeConv2DInfo(n.shape, c, a, 1, i, u, false, l), { strideHeight: d, strideWidth: f, filterHeight: h, filterWidth: g } = m, x = m.dataFormat === "channelsLast", b = new tt(m.filterShape, "float32"), C = m.padInfo.left, S = m.padInfo.top, k = t10.data.get(n.dataId).values, _ = t10.data.get(s.dataId).values, $ = new tt(n.shape, n.dtype, k), R = new tt(s.shape, s.dtype, _);
  for (let D = 0; D < h; ++D) {
    let P = Math.max(0, Math.ceil((S - D) / d)), O = Math.min(m.outHeight, (m.inHeight + S - D) / d);
    for (let M = 0; M < g; ++M) {
      let L = Math.max(0, Math.ceil((C - M) / f)), B = Math.min(m.outWidth, (m.inWidth + C - M) / f);
      for (let z = 0; z < m.inChannels; ++z) for (let U = 0; U < m.outChannels; ++U) {
        let j = 0;
        for (let q = 0; q < m.batchSize; ++q) for (let Y = P; Y < O; ++Y) {
          let J = D + Y * d - S;
          for (let re = L; re < B; ++re) {
            let ne = M + re * f - C;
            x ? j += $.get(q, J, ne, z) * R.get(q, Y, re, U) : j += $.get(q, z, J, ne) * R.get(q, U, Y, re);
          }
        }
        b.set(j, D, M, z, U);
      }
    }
  }
  return t10.makeTensorInfo(b.shape, b.dtype, b.values);
}
var CE = { kernelName: Fi, backendName: "cpu", kernelFunc: GY };
function HY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, filter: s } = e, { inputShape: a, strides: i, pad: p, dataFormat: u, dimRoundingMode: c } = o;
  Q([n, s], "conv2dBackpropInput");
  let l = y.computeStrides(s.shape), m = y.computeStrides(n.shape), d = w.convertConv2DDataFormat(u), f = w.computeConv2DInfo(a, s.shape, i, 1, p, c, false, d), h = new tt(f.inShape, "float32"), g = h.values, x = t10.data.get(n.dataId).values, b = t10.data.get(s.dataId).values, [C, S, k] = l, { batchSize: _, filterHeight: $, filterWidth: R, inChannels: D, inHeight: P, inWidth: O, outChannels: M, outHeight: L, outWidth: B, strideHeight: z, strideWidth: U } = f;
  d = f.dataFormat;
  let j = $ - 1 - f.padInfo.top, q = R - 1 - f.padInfo.left, Y = d === "channelsLast", J = h.strides[0], re = Y ? h.strides[1] : h.strides[2], ne = Y ? h.strides[2] : 1, ee = Y ? 1 : h.strides[1], oe = m[0], ie = Y ? m[1] : m[2], le = Y ? m[2] : 1, be = Y ? 1 : m[1];
  for (let _e = 0; _e < _; ++_e) for (let ve = 0; ve < D; ++ve) for (let Fe = 0; Fe < P; ++Fe) {
    let Pe = Fe - j, st = Math.max(0, Math.ceil(Pe / z)), ct = Math.min(L, ($ + Pe) / z);
    for (let He = 0; He < O; ++He) {
      let lt = He - q, it = Math.max(0, Math.ceil(lt / U)), ht = Math.min(B, (R + lt) / U), gt = 0;
      for (let Mt = st; Mt < ct; ++Mt) {
        let to = Mt * z - Pe;
        for (let rr = it; rr < ht; ++rr) {
          let Tt = rr * U - lt, or = oe * _e + ie * Mt + le * rr, nr = C * ($ - 1 - to) + S * (R - 1 - Tt) + k * ve;
          for (let ro = 0; ro < M; ++ro) {
            let oo = x[or + be * ro], fr = b[nr + ro];
            gt += oo * fr;
          }
        }
      }
      let Lr = J * _e + re * Fe + ne * He + ee * ve;
      g[Lr] = gt;
    }
  }
  return t10.makeTensorInfo(h.shape, h.dtype, h.values);
}
var wE = { kernelName: rn, backendName: "cpu", kernelFunc: HY };
function KY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s } = e, { strides: a, pad: i, dilations: p } = o;
  Q([n, s], "conv3d");
  let u = w.computeConv3DInfo(n.shape, s.shape, a, p, i), { filterDepth: c, filterHeight: l, filterWidth: m, dilationDepth: d, dilationHeight: f, dilationWidth: h, padInfo: g } = u, x = g.front, b = g.left, C = g.top, S = new tt(u.outShape, n.dtype), k = t10.data.get(n.dataId).values, _ = t10.data.get(s.dataId).values, $ = S.values, R = y.computeStrides(n.shape), D = y.computeStrides(s.shape);
  for (let P = 0; P < u.batchSize; ++P) {
    let O = P * R[0], M = P * S.strides[0];
    for (let L = 0; L < u.outDepth; ++L) {
      let B = M + L * S.strides[1], z = L * u.strideDepth - x;
      for (let U = 0; U < c; ++U) {
        let j = z + U * d;
        if (j < 0 || j >= u.inDepth) continue;
        let q = U * D[0], Y = O + j * R[1];
        for (let J = 0; J < u.outHeight; ++J) {
          let re = B + J * S.strides[2], ne = J * u.strideHeight - C;
          for (let ee = 0; ee < l; ++ee) {
            let oe = ne + ee * f;
            if (oe < 0 || oe >= u.inHeight) continue;
            let ie = q + ee * D[1], le = Y + oe * R[2];
            for (let be = 0; be < u.outWidth; ++be) {
              let _e = re + be * u.outChannels, ve = be * u.strideWidth - b;
              for (let Fe = 0; Fe < m; ++Fe) {
                let Pe = ve + Fe * h;
                if (Pe < 0 || Pe >= u.inWidth) continue;
                let st = ie + Fe * D[2], ct = le + Pe * u.inChannels, He = st;
                for (let lt = 0; lt < u.inChannels; ++lt) {
                  let it = k[ct + lt];
                  for (let ht = 0; ht < u.outChannels; ++ht) $[_e + ht] += it * _[He + ht];
                  He += u.outChannels;
                }
              }
            }
          }
        }
      }
    }
  }
  return t10.makeTensorInfo(S.shape, S.dtype, S.values);
}
var SE = { kernelName: on, backendName: "cpu", kernelFunc: KY };
function qY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, dy: s } = e, { strides: a, pad: i, filterShape: p } = o;
  Q([n, s], "conv3dBackpropFilterV2");
  let u = y.computeStrides(n.shape), c = y.computeStrides(s.shape), l = w.computeConv3DInfo(n.shape, p, a, 1, i), m = l.strideDepth, d = l.strideHeight, f = l.strideWidth, h = l.filterDepth, g = l.filterHeight, x = l.filterWidth, b = new tt(l.filterShape, "float32"), C = b.values, [S, k, _, $] = b.strides, R = t10.data.get(s.dataId).values, [D, P, O, M] = c, L = t10.data.get(n.dataId).values, [B, z, U, j] = u, q = l.padInfo.front, Y = l.padInfo.left, J = l.padInfo.top;
  for (let re = 0; re < h; ++re) {
    let ne = Math.max(0, Math.ceil((q - re) / m)), ee = Math.min(l.outDepth, (l.inDepth + q - re) / m), oe = re * S;
    for (let ie = 0; ie < g; ++ie) {
      let le = Math.max(0, Math.ceil((J - ie) / d)), be = Math.min(l.outHeight, (l.inHeight + J - ie) / d), _e = ie * k + oe;
      for (let ve = 0; ve < x; ++ve) {
        let Fe = Math.max(0, Math.ceil((Y - ve) / f)), Pe = Math.min(l.outWidth, (l.inWidth + Y - ve) / f), st = ve * _ + _e;
        for (let ct = 0; ct < l.inChannels; ++ct) {
          let He = ct * $ + st;
          for (let lt = 0; lt < l.outChannels; ++lt) {
            let it = 0;
            for (let ht = 0; ht < l.batchSize; ++ht) {
              let gt = ht * B, Lr = ht * D;
              for (let Mt = ne; Mt < ee; ++Mt) {
                let rr = (re + Mt * m - q) * z + gt, Tt = Mt * P + Lr;
                for (let or = le; or < be; ++or) {
                  let ro = (ie + or * d - J) * U + rr, oo = or * O + Tt;
                  for (let fr = Fe; fr < Pe; ++fr) {
                    let Lo = (ve + fr * f - Y) * j + ro, Ks = fr * M + oo;
                    it += L[Lo + ct] * R[Ks + lt];
                  }
                }
              }
            }
            C[He + lt] = it;
          }
        }
      }
    }
  }
  return t10.makeTensorInfo(b.shape, b.dtype, b.values);
}
var IE = { kernelName: ja, backendName: "cpu", kernelFunc: qY };
function jY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, filter: s } = e, { pad: a, strides: i, inputShape: p } = o;
  Q([n], "conv3dBackpropInputV2");
  let u = y.computeStrides(n.shape), c = y.computeStrides(s.shape), l = w.computeConv3DInfo(p, s.shape, i, 1, a), m = new tt(l.inShape, "float32"), d = m.values, [f, h, g, x] = m.strides, b = t10.data.get(n.dataId).values, [C, S, k, _] = u, $ = t10.data.get(s.dataId).values, [R, D, P, O] = c, { batchSize: M, filterDepth: L, filterHeight: B, filterWidth: z, inChannels: U, inDepth: j, inHeight: q, inWidth: Y, outChannels: J, outDepth: re, outHeight: ne, outWidth: ee, strideDepth: oe, strideHeight: ie, strideWidth: le } = l, be = L - 1 - l.padInfo.front, _e = B - 1 - l.padInfo.top, ve = z - 1 - l.padInfo.left;
  for (let Fe = 0; Fe < M; ++Fe) for (let Pe = 0; Pe < U; ++Pe) for (let st = 0; st < j; ++st) {
    let ct = st - be, He = Math.max(0, Math.ceil(ct / oe)), lt = Math.min(re, (L + ct) / oe);
    for (let it = 0; it < q; ++it) {
      let ht = it - _e, gt = Math.max(0, Math.ceil(ht / ie)), Lr = Math.min(ne, (B + ht) / ie);
      for (let Mt = 0; Mt < Y; ++Mt) {
        let to = Mt - ve, rr = Math.max(0, Math.ceil(to / le)), Tt = Math.min(ee, (z + to) / le), or = 0;
        for (let nr = He; nr < lt; ++nr) {
          let ro = nr * oe - ct;
          for (let oo = gt; oo < Lr; ++oo) {
            let fr = oo * ie - ht;
            for (let Va = rr; Va < Tt; ++Va) {
              let Lo = Va * le - to, Ks = C * Fe + S * nr + k * oo + _ * Va, Xt = R * (L - 1 - ro) + D * (B - 1 - fr) + P * (z - 1 - Lo) + O * Pe;
              for (let Wa = 0; Wa < J; ++Wa) {
                let ol = b[Ks + Wa], nl = $[Xt + Wa];
                or += ol * nl;
              }
            }
          }
        }
        d[f * Fe + h * st + g * it + x * Mt + Pe] = or;
      }
    }
  }
  return t10.makeTensorInfo(m.shape, m.dtype, m.values);
}
var vE = { kernelName: nn, backendName: "cpu", kernelFunc: jY };
var XY = Ie("Cos", (r15) => Math.cos(r15));
var kE = { kernelName: "Cos", backendName: "cpu", kernelFunc: XY };
var YY = Ie(an, (r15) => Math.cosh(r15));
var NE = { kernelName: an, backendName: "cpu", kernelFunc: YY };
function QY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { image: n, boxes: s, boxInd: a } = e, { cropSize: i, method: p, extrapolationValue: u } = o, [c, l, m, d] = n.shape, f = s.shape[0], [h, g] = i, x = me([f, h, g, d], "float32"), b = t10.data.get(s.dataId).values, C = t10.data.get(a.dataId).values, S = t10.data.get(n.dataId).values, k = y.computeStrides(n.shape), _ = y.computeStrides(x.shape);
  for (let $ = 0; $ < f; $++) {
    let R = $ * 4, D = b[R], P = b[R + 1], O = b[R + 2], M = b[R + 3], L = C[$];
    if (L >= c) continue;
    let B = h > 1 ? (O - D) * (l - 1) / (h - 1) : 0, z = g > 1 ? (M - P) * (m - 1) / (g - 1) : 0;
    for (let U = 0; U < h; U++) {
      let j = h > 1 ? D * (l - 1) + U * B : 0.5 * (D + O) * (l - 1);
      if (j < 0 || j > l - 1) {
        for (let q = 0; q < g; q++) for (let Y = 0; Y < d; Y++) {
          let J = Y + q * _[2] + U * _[1] + $ * _[0];
          x.values[J] = u;
        }
        continue;
      }
      if (p === "bilinear") {
        let q = Math.floor(j), Y = Math.ceil(j), J = j - q;
        for (let re = 0; re < g; re++) {
          let ne = g > 1 ? P * (m - 1) + re * z : 0.5 * (P + M) * (m - 1);
          if (ne < 0 || ne > m - 1) {
            for (let le = 0; le < d; le++) {
              let be = le + re * _[2] + U * _[1] + $ * _[0];
              x.values[be] = u;
            }
            continue;
          }
          let ee = Math.floor(ne), oe = Math.ceil(ne), ie = ne - ee;
          for (let le = 0; le < d; le++) {
            let be = le + ee * k[2] + q * k[1] + L * k[0], _e = S[be];
            be = le + oe * k[2] + q * k[1] + L * k[0];
            let ve = S[be];
            be = le + ee * k[2] + Y * k[1] + L * k[0];
            let Fe = S[be];
            be = le + oe * k[2] + Y * k[1] + L * k[0];
            let Pe = S[be], st = _e + (ve - _e) * ie, ct = Fe + (Pe - Fe) * ie;
            be = le + re * _[2] + U * _[1] + $ * _[0], x.values[be] = st + (ct - st) * J;
          }
        }
      } else for (let q = 0; q < g; ++q) {
        let Y = g > 1 ? P * (m - 1) + q * z : 0.5 * (P + M) * (m - 1);
        if (Y < 0 || Y > m - 1) {
          for (let ne = 0; ne < d; ne++) {
            let ee = ne + q * _[2] + U * _[1] + $ * _[0];
            x.values[ee] = u;
          }
          continue;
        }
        let J = Math.round(Y), re = Math.round(j);
        for (let ne = 0; ne < d; ne++) {
          let ee = ne + J * k[2] + re * k[1] + L * k[0], oe = ne + q * _[2] + U * _[1] + $ * _[0];
          x.values[oe] = S[ee];
        }
      }
    }
  }
  return t10.makeTensorInfo(x.shape, x.dtype, x.values);
}
var TE = { kernelName: cn, backendName: "cpu", kernelFunc: QY };
function ZY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, exclusive: a, reverse: i } = o;
  Q(n, "cumprod");
  let p = w.getAxesPermutation([s], n.shape.length), u = n;
  p != null && (u = St({ inputs: { x: n }, backend: t10, attrs: { perm: p } }));
  let c = w.getInnerMostAxes(1, n.shape.length)[0];
  if (c !== u.shape.length - 1) throw new Error(`backend.cumprod in CPU expects an inner-most axis=${u.shape.length - 1} but got axis=${c}`);
  let l = dt(u.dtype, "int32"), m = y.makeOnesTypedArray(y.sizeFromShape(u.shape), l), d = t10.data.get(u.dataId).values, f = u.shape[u.shape.length - 1], h = i ? (x, b) => x + f - b - 1 : (x, b) => x + b;
  for (let x = 0; x < d.length; x += f) for (let b = 0; b < f; b++) {
    let C = h(x, b);
    if (b === 0) m[C] = a ? 1 : d[C];
    else {
      let S = h(x, b - 1);
      m[C] = a ? d[S] * m[S] : d[C] * m[S];
    }
  }
  let g = t10.makeTensorInfo(u.shape, l, m);
  if (p != null) {
    let x = w.getUndoAxesPermutation(p), b = St({ inputs: { x: g }, backend: t10, attrs: { perm: x } });
    return t10.disposeIntermediateTensorInfo(g), t10.disposeIntermediateTensorInfo(u), b;
  }
  return g;
}
var _E = { kernelName: un, backendName: "cpu", kernelFunc: ZY };
function JY(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, exclusive: a, reverse: i } = o;
  Q(n, "cumsum");
  let p = w.getAxesPermutation([s], n.shape.length), u = n;
  p != null && (u = St({ inputs: { x: n }, backend: t10, attrs: { perm: p } }));
  let c = w.getInnerMostAxes(1, n.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 l = dt(u.dtype, "int32"), m = y.makeZerosTypedArray(y.sizeFromShape(u.shape), l), d = t10.data.get(u.dataId).values, f = u.shape[u.shape.length - 1], h = i ? (x, b) => x + f - b - 1 : (x, b) => x + b;
  for (let x = 0; x < d.length; x += f) for (let b = 0; b < f; b++) {
    let C = h(x, b);
    if (b === 0) m[C] = a ? 0 : d[C];
    else {
      let S = h(x, b - 1);
      m[C] = a ? d[S] + m[S] : d[C] + m[S];
    }
  }
  let g = t10.makeTensorInfo(u.shape, l, m);
  if (p != null) {
    let x = w.getUndoAxesPermutation(p), b = St({ inputs: { x: g }, backend: t10, attrs: { perm: x } });
    return t10.disposeIntermediateTensorInfo(g), t10.disposeIntermediateTensorInfo(u), b;
  }
  return g;
}
var EE = { kernelName: pn, backendName: "cpu", kernelFunc: JY };
function eQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, weights: s } = e, { size: a, binaryOutput: i } = o;
  if (n.shape.length === 1) {
    let p = t10.data.get(n.dataId).values, u = t10.data.get(s.dataId).values, c = Cc(p, u, s.dtype, s.shape, a);
    return t10.makeTensorInfo([a], s.dtype, c);
  } else if (n.shape.length === 2) {
    let p = t10.bufferSync(n), u = t10.bufferSync(s), c = Nf(p, u, a, i);
    return t10.makeTensorInfo(c.shape, s.dtype, c.values);
  }
  throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${n.shape.length}.`);
}
var $E = { kernelName: ra, backendName: "cpu", kernelFunc: eQ };
function tQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { blockSize: s, dataFormat: a } = o;
  y.assert(a === "NHWC", () => `Only NHWC dataFormat supported on CPU for depthToSpace. Got ${a}`);
  let i = n.shape[0], p = n.shape[1], u = n.shape[2], c = n.shape[3], l = p * s, m = u * s, d = c / (s * s), f = t10.data.get(n.dataId).values, h = new Float32Array(i * l * m * d), g = 0;
  for (let x = 0; x < i; ++x) for (let b = 0; b < l; ++b) {
    let C = Math.floor(b / s), S = b % s;
    for (let k = 0; k < m; ++k) {
      let _ = Math.floor(k / s), $ = k % s, R = (S * s + $) * d;
      for (let D = 0; D < d; ++D) {
        let O = D + R + c * (_ + u * (C + p * x));
        h[g++] = f[O];
      }
    }
  }
  return t10.makeTensorInfo([i, l, m, d], n.dtype, h);
}
var RE = { kernelName: ln, backendName: "cpu", kernelFunc: tQ };
function wI(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s } = e, { strides: a, pad: i, dilations: p, dimRoundingMode: u } = o;
  Q([n, s], "depthwiseConv2DNative");
  let c = y.computeStrides(n.shape), l = y.computeStrides(s.shape), m = p;
  m == null && (m = [1, 1]), y.assert(w.eitherStridesOrDilationsAreOne(a, m), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${m}'`);
  let d = w.computeConv2DInfo(n.shape, s.shape, a, m, i, u, true), { filterHeight: f, filterWidth: h, dilationHeight: g, dilationWidth: x, padInfo: b } = d, C = b.left, S = b.top, k = d.outChannels / d.inChannels, _ = new tt(d.outShape, n.dtype), $ = t10.data.get(n.dataId).values, R = t10.data.get(s.dataId).values, D = _.values;
  for (let P = 0; P < d.batchSize; ++P) {
    let O = P * c[0], M = P * _.strides[0];
    for (let L = 0; L < d.outHeight; ++L) {
      let B = M + L * _.strides[1], z = L * d.strideHeight - S;
      for (let U = 0; U < f; ++U) {
        let j = z + U * g;
        if (j < 0 || j >= d.inHeight) continue;
        let q = U * l[0], Y = O + j * c[1];
        for (let J = 0; J < d.outWidth; ++J) {
          let re = B + J * _.strides[2], ne = J * d.strideWidth - C;
          for (let ee = 0; ee < h; ++ee) {
            let oe = ne + ee * x;
            if (oe < 0 || oe >= d.inWidth) continue;
            let ie = q + ee * l[1], le = Y + oe * d.inChannels, be = re, _e = ie;
            for (let ve = 0; ve < d.inChannels; ++ve) {
              let Fe = $[le + ve];
              for (let Pe = 0; Pe < k; ++Pe) D[be + Pe] += Fe * R[_e + Pe];
              be += k, _e += k;
            }
          }
        }
      }
    }
  }
  return t10.makeTensorInfo(_.shape, _.dtype, _.values);
}
var DE = { kernelName: mn, backendName: "cpu", kernelFunc: wI };
function rQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, dy: s } = e, { strides: a, dilations: i, pad: p, dimRoundingMode: u, filterShape: c } = o;
  Q([n, s], "depthwiseConv2dNativeBackpropFilter");
  let l = w.computeConv2DInfo(n.shape, c, a, i, p, u, true), { strideHeight: m, strideWidth: d, filterHeight: f, filterWidth: h } = l, g = new tt(l.filterShape, "float32"), x = l.padInfo.left, b = l.padInfo.top, C = l.outChannels / l.inChannels, S = t10.data.get(n.dataId).values, k = new tt(n.shape, n.dtype, S), _ = t10.data.get(s.dataId).values, $ = new tt(s.shape, s.dtype, _);
  for (let R = 0; R < f; ++R) {
    let D = Math.max(0, Math.ceil((b - R) / m)), P = Math.min(l.outHeight, (l.inHeight + b - R) / m);
    for (let O = 0; O < h; ++O) {
      let M = Math.max(0, Math.ceil((x - O) / d)), L = Math.min(l.outWidth, (l.inWidth + x - O) / d);
      for (let B = 0; B < l.outChannels; ++B) {
        let z = Math.trunc(B / C), U = B % C, j = 0;
        for (let q = 0; q < l.batchSize; ++q) for (let Y = D; Y < P; ++Y) {
          let J = R + Y * m - b;
          for (let re = M; re < L; ++re) {
            let ne = O + re * d - x;
            j += k.get(q, J, ne, z) * $.get(q, Y, re, B);
          }
        }
        g.set(j, R, O, z, U);
      }
    }
  }
  return t10.makeTensorInfo(g.shape, g.dtype, g.values);
}
var AE = { kernelName: Pi, backendName: "cpu", kernelFunc: rQ };
function oQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, filter: s } = e, { strides: a, dilations: i, pad: p, dimRoundingMode: u, inputShape: c } = o;
  Q([n, s], "depthwiseConv2DNativeBackpropInput");
  let l = y.computeStrides(n.shape), m = y.computeStrides(s.shape), d = w.computeConv2DInfo(c, s.shape, a, i, p, u, true), f = new tt(d.inShape, "float32"), h = f.values, [g, x, b] = f.strides, C = t10.data.get(n.dataId).values, [S, k, _] = l, $ = t10.data.get(s.dataId).values, [R, D, P] = m, { batchSize: O, filterHeight: M, filterWidth: L, inChannels: B, inHeight: z, inWidth: U, outChannels: j, outHeight: q, outWidth: Y, strideHeight: J, strideWidth: re } = d, ne = M - 1 - d.padInfo.top, ee = L - 1 - d.padInfo.left, oe = j / B;
  for (let ie = 0; ie < O; ++ie) for (let le = 0; le < B; ++le) for (let be = 0; be < z; ++be) {
    let _e = be - ne, ve = Math.max(0, Math.ceil(_e / J)), Fe = Math.min(q, (M + _e) / J);
    for (let Pe = 0; Pe < U; ++Pe) {
      let st = Pe - ee, ct = Math.max(0, Math.ceil(st / re)), He = Math.min(Y, (L + st) / re), lt = 0;
      for (let it = ve; it < Fe; ++it) {
        let ht = it * J - _e;
        for (let gt = ct; gt < He; ++gt) {
          let Lr = gt * re - st, Mt = S * ie + k * it + _ * gt, to = R * (M - 1 - ht) + D * (L - 1 - Lr) + P * le;
          for (let rr = 0; rr < oe; ++rr) {
            let Tt = le * oe + rr, or = C[Mt + Tt], nr = $[to + rr];
            lt += or * nr;
          }
        }
      }
      h[g * ie + x * be + b * Pe + le] = lt;
    }
  }
  return t10.makeTensorInfo(f.shape, f.dtype, f.values);
}
var FE = { kernelName: Oi, backendName: "cpu", kernelFunc: oQ };
function nQ(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e, n = y.sizeFromShape(o.shape), s = t10.data.get(o.dataId).values, a = me([n, n], o.dtype), i = a.values;
  for (let u = 0; u < s.length; u++) i[u * n + u] = s[u];
  let p = [...o.shape, ...o.shape];
  return t10.makeTensorInfo(p, a.dtype, a.values);
}
var PE = { kernelName: oa, backendName: "cpu", kernelFunc: nQ };
var OE = { kernelName: dn, backendName: "cpu", kernelFunc: ({ inputs: r15, backend: e, attrs: t10 }) => {
  let { x: o, filter: n } = r15, { strides: s, pad: a, dilations: i } = t10, p = e, u = p.data.get(o.dataId).values, c = o.shape.length, l = p.data.get(n.dataId).values, m = n.shape.length, { batchSize: d, inHeight: f, inWidth: h, inChannels: g, outHeight: x, outWidth: b, padInfo: C, strideHeight: S, strideWidth: k, filterHeight: _, filterWidth: $, dilationHeight: R, dilationWidth: D, outShape: P } = w.computeDilation2DInfo(o.shape, n.shape, s, a, "NHWC", i), O = y.sizeFromShape(P), M = P.length, L = y.getArrayFromDType(o.dtype, O);
  for (let z = 0; z < d; ++z) for (let U = 0; U < x; ++U) {
    let j = U * S - C.top;
    for (let q = 0; q < b; ++q) {
      let Y = q * k - C.left;
      for (let J = 0; J < g; ++J) {
        let re = Number.MIN_SAFE_INTEGER;
        for (let ee = 0; ee < _; ++ee) {
          let oe = j + ee * R;
          if (oe >= 0 && oe < f) for (let ie = 0; ie < $; ++ie) {
            let le = Y + ie * D;
            if (le >= 0 && le < h) {
              let be = y.locToIndex([z, oe, le, J], c, y.computeStrides(o.shape)), _e = y.locToIndex([ee, ie, J], m, y.computeStrides(n.shape)), ve = u[be] + l[_e];
              ve > re && (re = ve);
            }
          }
        }
        let ne = y.locToIndex([z, U, q, J], M, y.computeStrides(P));
        L[ne] = re;
      }
    }
  }
  return { dataId: p.write(y.toTypedArray(L, o.dtype), P, o.dtype), shape: P, dtype: o.dtype };
} };
var ME = { kernelName: Li, backendName: "cpu", kernelFunc: ({ inputs: r15, backend: e, attrs: t10 }) => {
  let { x: o, filter: n, dy: s } = r15, { strides: a, pad: i, dilations: p } = t10, u = e, c = y.toNestedArray(o.shape, u.data.get(o.dataId).values), l = y.toNestedArray(n.shape, u.data.get(n.dataId).values), { batchSize: m, inHeight: d, inWidth: f, inChannels: h, outHeight: g, outWidth: x, padInfo: b, strideHeight: C, strideWidth: S, filterHeight: k, filterWidth: _, dilationHeight: $, dilationWidth: R, outShape: D } = w.computeDilation2DInfo(o.shape, n.shape, a, i, "NHWC", p);
  y.assert(s.rank === D.length, () => `Error in ${Li}, dy must have the same rank as output ${D.length}, but got ${s.rank}`);
  let P = y.toNestedArray(D, u.data.get(s.dataId).values), O = y.makeZerosNestedTypedArray(n.shape, n.dtype);
  for (let L = 0; L < m; ++L) for (let B = 0; B < g; ++B) {
    let z = B * C - b.top;
    for (let U = 0; U < x; ++U) {
      let j = U * S - b.left;
      for (let q = 0; q < h; ++q) {
        let Y = Number.MIN_SAFE_INTEGER, J = 0, re = 0;
        for (let ne = 0; ne < k; ++ne) {
          let ee = z + ne * $;
          if (ee >= 0 && ee < d) for (let oe = 0; oe < _; ++oe) {
            let ie = j + oe * R;
            if (ie >= 0 && ie < f) {
              let le = c[L][ee][ie][q] + l[ne][oe][q];
              le > Y && (Y = le, J = ne, re = oe);
            }
          }
        }
        O[J][re][q] += P[L][B][U][q];
      }
    }
  }
  return { dataId: u.write(y.toTypedArray(O, o.dtype), n.shape, n.dtype), shape: n.shape, dtype: n.dtype };
} };
var LE = { kernelName: Mi, backendName: "cpu", kernelFunc: ({ inputs: r15, backend: e, attrs: t10 }) => {
  let { x: o, filter: n, dy: s } = r15, { strides: a, pad: i, dilations: p } = t10, u = e, c = y.toNestedArray(o.shape, u.data.get(o.dataId).values), l = y.toNestedArray(n.shape, u.data.get(n.dataId).values), { batchSize: m, inHeight: d, inWidth: f, inChannels: h, outHeight: g, outWidth: x, padInfo: b, strideHeight: C, strideWidth: S, filterHeight: k, filterWidth: _, dilationHeight: $, dilationWidth: R, outShape: D } = w.computeDilation2DInfo(o.shape, n.shape, a, i, "NHWC", p);
  y.assert(s.rank === D.length, () => `Error in ${Mi}, dy must have the same rank as output ${D.length}, but got ${s.rank}`);
  let P = y.toNestedArray(D, u.data.get(s.dataId).values), O = y.makeZerosNestedTypedArray(o.shape, o.dtype);
  for (let L = 0; L < m; ++L) for (let B = 0; B < g; ++B) {
    let z = B * C - b.top;
    for (let U = 0; U < x; ++U) {
      let j = U * S - b.left;
      for (let q = 0; q < h; ++q) {
        let Y = Number.MIN_SAFE_INTEGER, J = z < 0 ? 0 : z, re = j < 0 ? 0 : j;
        for (let ne = 0; ne < k; ++ne) {
          let ee = z + ne * $;
          if (ee >= 0 && ee < d) for (let oe = 0; oe < _; ++oe) {
            let ie = j + oe * R;
            if (ie >= 0 && ie < f) {
              let le = c[L][ee][ie][q] + l[ne][oe][q];
              le > Y && (Y = le, J = ee, re = ie);
            }
          }
        }
        O[L][J][re][q] += P[L][B][U][q];
      }
    }
  }
  return { dataId: u.write(y.toTypedArray(O, o.dtype), o.shape, o.dtype), shape: o.shape, dtype: o.dtype };
} };
function sQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { image: n } = e, { canvas: s, options: a } = o, { contextOptions: i, imageOptions: p } = a || {}, u = (p == null ? void 0 : p.alpha) || 1, c = (i == null ? void 0 : i.contextType) || "2d";
  if (c !== "2d") throw new Error(`Context type ${i.contextType} is not supported by the CPU backend.`);
  let l = s.getContext(c, (i == null ? void 0 : i.contextAttributes) || {});
  if (l == null) throw new Error(`Could not get the context with ${c} type.`);
  let [m, d] = n.shape.slice(0, 2), f = n.shape.length === 2 ? 1 : n.shape[2], h = t10.data.get(n.dataId).values, g = n.dtype === "float32" ? 255 : 1, x = new Uint8ClampedArray(d * m * 4);
  for (let C = 0; C < m * d; ++C) {
    let S = [0, 0, 0, 255 * u];
    for (let _ = 0; _ < f; _++) {
      let $ = h[C * f + _];
      if (n.dtype === "float32") {
        if ($ < 0 || $ > 1) throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${$}.`);
      } else if (n.dtype === "int32" && ($ < 0 || $ > 255)) throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${$}.`);
      f === 1 ? (S[0] = $ * g, S[1] = $ * g, S[2] = $ * g) : S[_] = $ * g;
    }
    let k = C * 4;
    x[k + 0] = Math.round(S[0]), x[k + 1] = Math.round(S[1]), x[k + 2] = Math.round(S[2]), x[k + 3] = Math.round(S[3]);
  }
  s.width = d, s.height = m;
  let b = new ImageData(x, d, m);
  return l.putImageData(b, 0, 0), n;
}
var BE = { kernelName: $u, backendName: "cpu", kernelFunc: sQ };
function fi(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o;
  Q(n, "sum");
  let i;
  n.dtype === "bool" ? i = Ro({ inputs: { x: n }, backend: t10, attrs: { dtype: "int32" } }) : i = lr({ inputs: { x: n }, backend: t10 });
  let p = i.shape.length, u = y.parseAxisParam(s, i.shape), c = w.getAxesPermutation(u, p), l = u, m = i;
  c != null && (m = St({ inputs: { x: i }, backend: t10, attrs: { perm: c } }), l = w.getInnerMostAxes(l.length, p)), w.assertAxesAreInnerMostDims("sum", l, m.shape.length);
  let [d, f] = w.computeOutAndReduceShapes(m.shape, l), h = w.upcastType(m.dtype, "int32"), g = yc(t10, d, h), x = y.sizeFromShape(f), b = t10.data.get(g.dataId).values, C = t10.data.get(m.dataId).values;
  for (let S = 0; S < b.length; ++S) {
    let k = S * x, _ = 0;
    for (let $ = 0; $ < x; ++$) _ += C[k + $];
    b[S] = _;
  }
  if (a) {
    let S = w.expandShapeToKeepDim(g.shape, u), k = g;
    g = We({ inputs: { x: g }, backend: t10, attrs: { shape: S } }), t10.disposeIntermediateTensorInfo(k);
  }
  return t10.disposeIntermediateTensorInfo(i), c != null && t10.disposeIntermediateTensorInfo(m), g;
}
var zE = { kernelName: "Sum", backendName: "cpu", kernelFunc: fi };
function aQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { equation: n } = o, s = e, { allDims: a, summedDims: i, idDims: p } = w.decodeEinsumEquation(n, s.length);
  w.checkEinsumDimSizes(a.length, p, s);
  let { path: u, steps: c } = w.getEinsumComputePath(i, p), l = c.length, m = null, d = a.length, f = [];
  for (let h = 0; h < l; ++h) {
    for (let g of c[h]) {
      let { permutationIndices: x, expandDims: b } = w.getEinsumPermutation(d, p[g]), C;
      w.isIdentityPermutation(x) ? C = s[g] : (C = St({ inputs: { x: s[g] }, backend: t10, attrs: { perm: x } }), f.push(C));
      let S = C.shape.slice();
      for (let k = 0; k < b.length; ++k) S.splice(b[k], 0, 1);
      y.arraysEqual(C.shape, S) || (C = We({ inputs: { x: C }, backend: t10, attrs: { shape: S } }), f.push(C)), m === null ? m = C : (m = ip({ inputs: { a: C, b: m }, backend: t10 }), f.push(m));
    }
    h < l - 1 && (u[h] >= 0 && (m = fi({ inputs: { x: m }, backend: t10, attrs: { axis: u[h] - (a.length - d), keepDims: false } }), f.push(m)), d--);
  }
  for (let h of f) h !== m && t10.disposeIntermediateTensorInfo(h);
  return m;
}
var VE = { kernelName: Bi, backendName: "cpu", kernelFunc: aQ };
function iQ(r15) {
  let { inputs: e, backend: t10 } = r15, { dy: o, y: n } = e;
  Q([o, n], "eluGrad");
  let s = new Float32Array(y.sizeFromShape(n.shape)), a = t10.data.get(n.dataId).values, i = t10.data.get(o.dataId).values;
  for (let p = 0; p < a.length; ++p) {
    let u = a[p];
    u >= 0 ? s[p] = i[p] : s[p] = i[p] * (u + 1);
  }
  return t10.makeTensorInfo(n.shape, "float32", s);
}
var WE = { kernelName: Xa, backendName: "cpu", kernelFunc: iQ };
var uQ = w.ERF_P;
var pQ = w.ERF_A1;
var cQ = w.ERF_A2;
var lQ = w.ERF_A3;
var mQ = w.ERF_A4;
var dQ = w.ERF_A5;
var fQ = Ie("Erf", (r15) => {
  let e = Math.sign(r15), t10 = Math.abs(r15), o = 1 / (1 + uQ * t10);
  return e * (1 - ((((dQ * o + mQ) * o + lQ) * o + cQ) * o + pQ) * o * Math.exp(-t10 * t10));
});
var UE = { kernelName: "Erf", backendName: "cpu", kernelFunc: fQ };
function kc(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { input: n } = e, { dim: s } = o, a = n.shape.length, i = n.shape.slice(), p = s;
  return s < 0 && (y.assert(-(a + 1) <= s, () => `Axis must be in the interval [${-(a + 1)}, ${a}]`), p = a + s + 1), i.splice(p, 0, 1), We({ inputs: { x: n }, backend: t10, attrs: { shape: i } });
}
var GE = { kernelName: na, backendName: "cpu", kernelFunc: kc };
var hQ = Ve((r15, e) => r15 / e);
var Ul = Ye(fn, hQ);
var Gl = { kernelName: fn, backendName: "cpu", kernelFunc: Ul };
function Vf(r15, e, t10) {
  let o = r15.shape, n = o[0], s = o[1], a = t10.data.get(r15.dataId), i = a.complexTensorInfos.real, p = a.complexTensorInfos.imag, u = [n, s], c = y.sizeFromShape(u), l = y.getTypedArrayFromDType("float32", c), m = y.getTypedArrayFromDType("float32", c);
  for (let g = 0; g < n; g++) {
    let x = Ao({ inputs: { x: i }, backend: t10, attrs: { begin: [g, 0], size: [1, s] } }), b = Ao({ inputs: { x: p }, backend: t10, attrs: { begin: [g, 0], size: [1, s] } }), C = Ht({ inputs: { real: x, imag: b }, backend: t10 }), { real: S, imag: k } = gQ(C, e, t10), _ = w.mergeRealAndImagArrays(S, k);
    for (let $ = 0; $ < s; $++) {
      let R = w.getComplexWithIndex(_, $);
      l[g * s + $] = R.real, m[g * s + $] = R.imag;
    }
    t10.disposeIntermediateTensorInfo(x), t10.disposeIntermediateTensorInfo(b), t10.disposeIntermediateTensorInfo(C);
  }
  let d = t10.makeTensorInfo(u, "float32", l), f = t10.makeTensorInfo(u, "float32", m), h = Ht({ inputs: { real: d, imag: f }, backend: t10 });
  return t10.disposeIntermediateTensorInfo(d), t10.disposeIntermediateTensorInfo(f), h;
}
function gQ(r15, e, t10) {
  let o = y.sizeFromShape(r15.shape), n = t10.data.get(r15.dataId), s = t10.data.get(n.complexTensorInfos.real.dataId).values, a = t10.data.get(n.complexTensorInfos.imag.dataId).values;
  if (xQ(o)) {
    let i = SI(s, a, o, e, t10), p = [r15.shape[0], r15.shape[1]];
    if (e) {
      let u = t10.makeTensorInfo(p, "float32", i.real), c = t10.makeTensorInfo(p, "float32", i.imag), l = t10.makeTensorInfo([], "float32", y.createScalarValue(o, "float32")), m = lr({ inputs: { x: l }, backend: t10 }), d = Gl.kernelFunc({ inputs: { a: u, b: l }, backend: t10 }), f = Gl.kernelFunc({ inputs: { a: c, b: m }, backend: t10 }), h = t10.data.get(d.dataId).values, g = t10.data.get(f.dataId).values;
      return t10.disposeIntermediateTensorInfo(u), t10.disposeIntermediateTensorInfo(c), t10.disposeIntermediateTensorInfo(l), t10.disposeIntermediateTensorInfo(m), t10.disposeIntermediateTensorInfo(d), t10.disposeIntermediateTensorInfo(f), { real: h, imag: g };
    }
    return i;
  } else {
    let i = w.mergeRealAndImagArrays(s, a), p = yQ(i, o, e);
    return w.splitRealAndImagArrays(p);
  }
}
function xQ(r15) {
  return (r15 & r15 - 1) === 0;
}
function SI(r15, e, t10, o, n) {
  if (t10 === 1) return { real: r15, imag: e };
  let s = w.mergeRealAndImagArrays(r15, e), a = t10 / 2, i = w.complexWithEvenIndex(s), p = i.real, u = i.imag, c = [p.length], l = n.makeTensorInfo(c, "float32", p), m = n.makeTensorInfo(c, "float32", u), d = Ht({ inputs: { real: l, imag: m }, backend: n }), f = w.complexWithOddIndex(s), h = f.real, g = f.imag, x = [h.length], b = n.makeTensorInfo(x, "float32", h), C = n.makeTensorInfo(x, "float32", g), S = Ht({ inputs: { real: b, imag: C }, backend: n }), k = SI(p, u, a, o, n), _ = k.real, $ = k.imag, R = [_.length], D = n.makeTensorInfo(R, "float32", _), P = n.makeTensorInfo(R, "float32", $), O = Ht({ inputs: { real: D, imag: P }, backend: n }), M = SI(h, g, a, o, n), L = M.real, B = M.imag, z = [L.length], U = n.makeTensorInfo(z, "float32", L), j = n.makeTensorInfo(z, "float32", B), q = Ht({ inputs: { real: U, imag: j }, backend: n }), Y = w.exponents(t10, o), J = [Y.real.length], re = n.makeTensorInfo(J, "float32", Y.real), ne = n.makeTensorInfo(J, "float32", Y.imag), ee = Ht({ inputs: { real: re, imag: ne }, backend: n }), oe = ip({ inputs: { a: ee, b: q }, backend: n }), ie = Pa({ inputs: { a: O, b: oe }, backend: n }), le = Vl({ inputs: { a: O, b: oe }, backend: n }), be = $o({ inputs: { input: ie }, backend: n }), _e = $o({ inputs: { input: le }, backend: n }), ve = Oa({ inputs: { input: ie }, backend: n }), Fe = Oa({ inputs: { input: le }, backend: n }), Pe = hu({ inputs: [be, _e], backend: n, attrs: { axis: 0 } }), st = hu({ inputs: [ve, Fe], backend: n, attrs: { axis: 0 } }), ct = n.data.get(Pe.dataId).values, He = n.data.get(st.dataId).values;
  return n.disposeIntermediateTensorInfo(l), n.disposeIntermediateTensorInfo(m), n.disposeIntermediateTensorInfo(d), n.disposeIntermediateTensorInfo(b), n.disposeIntermediateTensorInfo(C), n.disposeIntermediateTensorInfo(S), n.disposeIntermediateTensorInfo(D), n.disposeIntermediateTensorInfo(P), n.disposeIntermediateTensorInfo(O), n.disposeIntermediateTensorInfo(U), n.disposeIntermediateTensorInfo(j), n.disposeIntermediateTensorInfo(q), n.disposeIntermediateTensorInfo(re), n.disposeIntermediateTensorInfo(ne), n.disposeIntermediateTensorInfo(ee), n.disposeIntermediateTensorInfo(oe), n.disposeIntermediateTensorInfo(ie), n.disposeIntermediateTensorInfo(le), n.disposeIntermediateTensorInfo(be), n.disposeIntermediateTensorInfo(ve), n.disposeIntermediateTensorInfo(_e), n.disposeIntermediateTensorInfo(Fe), n.disposeIntermediateTensorInfo(Pe), n.disposeIntermediateTensorInfo(st), { real: ct, imag: He };
}
function yQ(r15, e, t10) {
  let o = new Float32Array(e * 2);
  for (let n = 0; n < e; n++) {
    let s = 0, a = 0;
    for (let i = 0; i < e; i++) {
      let p = w.exponent(n * i, e, t10), u = w.getComplexWithIndex(r15, i);
      s += u.real * p.real - u.imag * p.imag, a += u.real * p.imag + u.imag * p.real;
    }
    t10 && (s /= e, a /= e), w.assignToTypedArray(o, s, a, n);
  }
  return o;
}
function bQ(r15) {
  let { inputs: e, backend: t10 } = r15, { input: o } = e, n = y.sizeFromShape(o.shape), s = o.shape[o.shape.length - 1], a = n / s, i = We({ inputs: { x: o }, backend: t10, attrs: { shape: [a, s] } }), p = Vf(i, false, t10), u = We({ inputs: { x: p }, backend: t10, attrs: { shape: o.shape } });
  return t10.disposeIntermediateTensorInfo(i), t10.disposeIntermediateTensorInfo(p), u;
}
var HE = { kernelName: "FFT", backendName: "cpu", kernelFunc: bQ };
function Hl(r15) {
  let { backend: e, attrs: t10 } = r15, { shape: o, value: n, dtype: s } = t10, a = s || y.inferDtype(n), i = y.getArrayFromDType(a, y.sizeFromShape(o));
  return CQ(i, n, a), e.makeTensorInfo(o, a, i);
}
var KE = { kernelName: sa, backendName: "cpu", kernelFunc: Hl };
function CQ(r15, e, t10) {
  r15.fill(e);
}
var qE = { kernelName: Cn, backendName: "cpu", kernelFunc: ({ inputs: r15, attrs: e, backend: t10 }) => {
  let { image: o } = r15, n = t10, s = y.getTypedArrayFromDType(o.dtype, y.sizeFromShape(o.shape)), [a, i, p, u] = o.shape, c = n.data.get(o.dataId).values;
  for (let m = 0; m < a; m++) {
    let d = m * p * i * u;
    for (let f = 0; f < i; f++) {
      let h = f * (p * u);
      for (let g = 0; g < p; g++) {
        let x = g * u;
        for (let b = 0; b < u; b++) {
          let C = Math.round(p - g - 1), S = d + h + x + b, k = c[S];
          if (C >= 0 && C < p) {
            let _ = C * u, $ = d + h + _ + b;
            k = c[$];
          }
          s[S] = k;
        }
      }
    }
  }
  return { dataId: n.write(s, o.shape, o.dtype), shape: o.shape, dtype: o.dtype };
} };
function wQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s, bias: a, preluActivationWeights: i } = e, { strides: p, pad: u, dataFormat: c, dilations: l, dimRoundingMode: m, activation: d, leakyreluAlpha: f } = o, h = CI({ inputs: { x: n, filter: s }, backend: t10, attrs: { strides: p, pad: u, dataFormat: c, dilations: l, dimRoundingMode: m } });
  if (a) {
    let g = h;
    if (c === "NCHW" && a.shape.length === 1 && a.shape[0] !== 1) {
      let x = We({ inputs: { x: a }, backend: t10, attrs: { shape: [a.shape[0], 1, 1] } });
      h = Pa({ inputs: { a: h, b: x }, backend: t10 }), t10.disposeIntermediateTensorInfo(x);
    } else h = Pa({ inputs: { a: h, b: a }, backend: t10 });
    t10.disposeIntermediateTensorInfo(g);
  }
  if (d) {
    let g = h;
    if (c === "NCHW" && d === "prelu" && i.shape.length === 1 && i.shape[0] !== 1) {
      let x = We({ inputs: { x: i }, backend: t10, attrs: { shape: [i.shape[0], 1, 1] } });
      h = fp(t10, h, d, x, f), t10.disposeIntermediateTensorInfo(x);
    } else h = fp(t10, h, d, i, f);
    t10.disposeIntermediateTensorInfo(g);
  }
  return h;
}
var jE = { kernelName: Io, backendName: "cpu", kernelFunc: wQ };
function SQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s, bias: a, preluActivationWeights: i } = e, { strides: p, pad: u, dataFormat: c, dilations: l, dimRoundingMode: m, activation: d, leakyreluAlpha: f } = o, h = wI({ inputs: { x: n, filter: s }, backend: t10, attrs: { strides: p, pad: u, dataFormat: c, dilations: l, dimRoundingMode: m } });
  if (a) {
    let g = h;
    h = Pa({ inputs: { a: h, b: a }, backend: t10 }), t10.disposeIntermediateTensorInfo(g);
  }
  if (d) {
    let g = h;
    h = fp(t10, h, d, i, f), t10.disposeIntermediateTensorInfo(g);
  }
  return h;
}
var XE = { kernelName: vo, backendName: "cpu", kernelFunc: SQ };
function IQ(r15) {
  let { inputs: e, backend: t10 } = r15, { params: o, indices: n } = e, s = y.sizeFromShape(o.shape), a = n.shape, i = a[a.length - 1], [p, u, c, l] = w.prepareAndValidate(o, n);
  if (u === 0) return t10.makeTensorInfo(p, o.dtype, []);
  let m = t10.data.get(n.dataId).values, d = t10.bufferSync(o), f = Tf(m, d, o.dtype, u, i, c, l, o.shape, s);
  return t10.makeTensorInfo(p, o.dtype, f.values);
}
var YE = { kernelName: vn, backendName: "cpu", kernelFunc: IQ };
function vQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, indices: s } = e, { axis: a, batchDims: i } = o;
  Q([n, s], "gatherV2");
  let p = y.parseAxisParam(a, n.shape)[0], u = t10.data.get(s.dataId).values, c = n.shape[p];
  for (let S = 0; S < u.length; ++S) {
    let k = u[S];
    y.assert(k <= c - 1 && k >= 0, () => `GatherV2: the index value ${k} is not in [0, ${c - 1}]`);
  }
  let l = i;
  i == null && (l = 0);
  let m = y.sizeFromShape(s.shape), d = w.segment_util.collectGatherOpShapeInfo(n, s, p, l), f = We({ inputs: { x: n }, backend: t10, attrs: { shape: [d.batchSize, d.outerSize, d.dimSize, d.sliceSize] } }), h = We({ inputs: { x: s }, backend: t10, attrs: { shape: [d.batchSize, m / d.batchSize] } }), g = [d.batchSize, d.outerSize, m / d.batchSize, d.sliceSize], x = t10.bufferSync(h), b = t10.bufferSync(f), C = _f(b, x, g);
  return t10.disposeIntermediateTensorInfo(f), t10.disposeIntermediateTensorInfo(h), t10.makeTensorInfo(d.outputShape, C.dtype, C.values);
}
var QE = { kernelName: aa, backendName: "cpu", kernelFunc: vQ };
function kQ(r15) {
  let { inputs: e, backend: t10 } = r15, { input: o } = e, n = y.sizeFromShape(o.shape), s = o.shape[o.shape.length - 1], a = n / s, i = We({ inputs: { x: o }, backend: t10, attrs: { shape: [a, s] } }), p = Vf(i, true, t10), u = We({ inputs: { x: p }, backend: t10, attrs: { shape: o.shape } });
  return t10.disposeIntermediateTensorInfo(i), t10.disposeIntermediateTensorInfo(p), u;
}
var ZE = { kernelName: Vi, backendName: "cpu", kernelFunc: kQ };
var NQ = Ie(Tn, (r15) => Number.isFinite(r15) ? 1 : 0, "bool");
var JE = { kernelName: Tn, backendName: "cpu", kernelFunc: NQ };
var TQ = Ie(_n, (r15) => Math.abs(r15) === 1 / 0 ? 1 : 0, "bool");
var e$ = { kernelName: _n, backendName: "cpu", kernelFunc: TQ };
var _Q = Ie(En, (r15) => Number.isNaN(r15) ? 1 : 0, "bool");
var t$ = { kernelName: En, backendName: "cpu", kernelFunc: _Q };
function EQ(r15) {
  let { backend: e, attrs: t10 } = r15, { start: o, stop: n, num: s } = t10, a = Ef(o, n, s);
  return e.makeTensorInfo([a.length], "float32", a);
}
var r$ = { kernelName: An, backendName: "cpu", kernelFunc: EQ };
var $Q = Ie(Pn, (r15) => Math.log1p(r15));
var o$ = { kernelName: Pn, backendName: "cpu", kernelFunc: $Q };
var RQ = Ve((r15, e) => r15 && e);
var DQ = Ye(On, RQ, null, "bool");
var n$ = { kernelName: On, backendName: "cpu", kernelFunc: DQ };
var AQ = Ie(Mn, (r15) => r15 ? 0 : 1, "bool");
var s$ = { kernelName: Mn, backendName: "cpu", kernelFunc: AQ };
var FQ = Ve((r15, e) => r15 || e);
var PQ = Ye(Ln, FQ, null, "bool");
var a$ = { kernelName: Ln, backendName: "cpu", kernelFunc: PQ };
function OQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { depthRadius: s, bias: a, alpha: i, beta: p } = o;
  Q(n, "LRN");
  let u = n.shape[3], c = u - 1, l = t10.data.get(n.dataId).values, m = y.sizeFromShape(n.shape), d = new Float32Array(m);
  function f(h) {
    let g = h % u, x = h - g + Math.max(0, g - s), b = h - g + Math.min(g + s, c), C = 0;
    for (; x <= b; x++) {
      let S = l[x];
      C += S * S;
    }
    return C;
  }
  for (let h = 0; h < m; h++) {
    let g = f(h), x = l[h] * Math.pow(a + i * g, -p);
    d[h] = x;
  }
  return t10.makeTensorInfo(n.shape, n.dtype, d);
}
var i$ = { kernelName: "LRN", backendName: "cpu", kernelFunc: OQ };
function MQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, y: s, dy: a } = e, { depthRadius: i, bias: p, alpha: u, beta: c } = o;
  Q(a, "LRNGrad");
  let l = y.sizeFromShape(a.shape), m = a.shape[3], d = t10.data.get(a.dataId).values, f = t10.data.get(n.dataId).values, h = t10.data.get(s.dataId).values, g = new Float32Array(l), x = l;
  for (let b = 0; b < x; b++) {
    let C = b % m, S = b - C + Math.max(0, C - i), k = b - C + Math.min(m, C + i + 1), _ = 0;
    for (let $ = S; $ < k; $++) _ += Math.pow(f[$], 2);
    _ = u * _ + p;
    for (let $ = S; $ < k; $++) {
      let R = -2 * u * c * f[$] * h[b] / _;
      b === $ && (R += Math.pow(_, -c)), R *= d[b], g[$] += R;
    }
  }
  return t10.makeTensorInfo(a.shape, n.dtype, g);
}
var u$ = { kernelName: Ya, backendName: "cpu", kernelFunc: MQ };
function II(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { reductionIndices: s, keepDims: a } = o, i = t10, p = n.shape, u = p.length, c = y.parseAxisParam(s, p), l = c, m = w.getAxesPermutation(l, u), d = i.data.get(n.dataId).values;
  if (m != null) {
    let S = new Array(u);
    for (let k = 0; k < S.length; k++) S[k] = p[m[k]];
    d = wc(d, p, n.dtype, m, S), l = w.getInnerMostAxes(l.length, u), p = S;
  }
  Q(n, "max"), w.assertAxesAreInnerMostDims("max", l, u);
  let [f, h] = w.computeOutAndReduceShapes(p, l), g = y.sizeFromShape(h), x = $f(d, g, f, n.dtype), b = i.write(x, f, n.dtype), C = f;
  return a && (C = w.expandShapeToKeepDim(f, c)), { dataId: b, shape: C, dtype: n.dtype };
}
var p$ = { kernelName: "Max", backendName: "cpu", kernelFunc: II };
function LQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e;
  Q(n, "maxPool");
  let { filterSize: s, strides: a, pad: i, dimRoundingMode: p } = o, u = 1;
  y.assert(w.eitherStridesOrDilationsAreOne(a, u), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);
  let c = w.computePool2DInfo(n.shape, s, a, u, i, p), l;
  if (c.filterWidth === 1 && c.filterHeight === 1 && y.arraysEqual(c.inShape, c.outShape)) l = lr({ inputs: { x: n }, backend: t10 });
  else {
    let m = t10.data.get(n.dataId).values, d = y.computeStrides(n.shape), f = vc(m, n.shape, n.dtype, d, c, "max");
    l = t10.makeTensorInfo(c.outShape, n.dtype, f.values);
  }
  return l;
}
var c$ = { kernelName: Wn, backendName: "cpu", kernelFunc: LQ };
function BQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { filterSize: s, strides: a, pad: i, dimRoundingMode: p, dataFormat: u } = o;
  Q(n, "maxPool3d");
  let c = w.computePool3DInfo(n.shape, s, a, 1, i, p, u), l = t10.data.get(n.dataId).values, m = zf(l, n.shape, n.dtype, y.computeStrides(n.shape), c, "max");
  return t10.makeTensorInfo(m.shape, "float32", m.values);
}
var l$ = { kernelName: ia, backendName: "cpu", kernelFunc: BQ };
function zQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s } = e, { filterSize: a, strides: i, pad: p, dimRoundingMode: u } = o;
  Q([n, s], "maxPool3DGrad");
  let c = w.computePool3DInfo(s.shape, a, i, 1, p, u), l = t10.bufferSync(s), m = aE(l, c), d = c.strideDepth, f = c.strideHeight, h = c.strideWidth, g = c.dilationDepth, x = c.dilationHeight, b = c.dilationWidth, C = c.effectiveFilterDepth, S = c.effectiveFilterHeight, k = c.effectiveFilterWidth, _ = C - 1 - c.padInfo.front, $ = k - 1 - c.padInfo.left, R = S - 1 - c.padInfo.top, D = me(s.shape, "float32"), P = t10.bufferSync(n);
  for (let O = 0; O < c.batchSize; ++O) for (let M = 0; M < c.inChannels; ++M) for (let L = 0; L < c.inDepth; ++L) for (let B = 0; B < c.inHeight; ++B) for (let z = 0; z < c.inWidth; ++z) {
    let U = L - _, j = B - R, q = z - $, Y = 0;
    for (let J = 0; J < C; J += g) {
      let re = (U + J) / d;
      if (!(re < 0 || re >= c.outDepth || Math.floor(re) !== re)) for (let ne = 0; ne < S; ne += x) {
        let ee = (j + ne) / f;
        if (!(ee < 0 || ee >= c.outHeight || Math.floor(ee) !== ee)) for (let oe = 0; oe < k; oe += b) {
          let ie = (q + oe) / h;
          if (ie < 0 || ie >= c.outWidth || Math.floor(ie) !== ie) continue;
          let le = C * S * k - 1 - m.get(O, re, ee, ie, M), be = J * S * k + ne * k + oe, _e = le === be ? 1 : 0;
          if (_e === 0) continue;
          let ve = P.get(O, re, ee, ie, M);
          Y += ve * _e;
        }
      }
    }
    D.set(Y, O, L, B, z, M);
  }
  return t10.makeTensorInfo(D.shape, D.dtype, D.values);
}
var m$ = { kernelName: Gi, backendName: "cpu", kernelFunc: zQ };
function VQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s, output: a } = e, i = s;
  Q([s, a], "maxPoolGrad");
  let { filterSize: p, strides: u, pad: c, dimRoundingMode: l } = o, m = w.computePool2DInfo(i.shape, p, u, 1, c, l), d = t10.data.get(i.dataId).values, f = me(m.outShape, i.dtype, Bf(d, i.shape, i.dtype, m).values), h = m.strideHeight, g = m.strideWidth, x = m.dilationHeight, b = m.dilationWidth, C = m.effectiveFilterHeight, S = m.effectiveFilterWidth, k = S - 1 - m.padInfo.left, _ = C - 1 - m.padInfo.top, $ = me(i.shape, "float32"), R = t10.data.get(n.dataId).values, D = me(n.shape, "float32", R);
  for (let P = 0; P < m.batchSize; ++P) for (let O = 0; O < m.inChannels; ++O) for (let M = 0; M < m.inHeight; ++M) for (let L = 0; L < m.inWidth; ++L) {
    let B = M - _, z = L - k, U = 0;
    for (let j = 0; j < C; j += x) {
      let q = (B + j) / h;
      if (!(q < 0 || q >= m.outHeight || Math.floor(q) !== q)) for (let Y = 0; Y < S; Y += b) {
        let J = (z + Y) / g;
        if (J < 0 || J >= m.outWidth || Math.floor(J) !== J) continue;
        let re = C * S - 1 - f.get(P, q, J, O), ne = j * S + Y, ee = re === ne ? 1 : 0;
        if (ee === 0) continue;
        let oe = D.get(P, q, J, O);
        U += oe * ee;
      }
    }
    $.set(U, P, M, L, O);
  }
  return t10.makeTensorInfo($.shape, $.dtype, $.values);
}
var d$ = { kernelName: Ui, backendName: "cpu", kernelFunc: VQ };
function f$(r15, e, t10, o, n) {
  let s = y.computeStrides(e), a = vc(r15, e, t10, s, n, "max"), i = Bf(r15, e, t10, n, true, o);
  return [a.values, i.values];
}
var h$ = { kernelName: ua, backendName: "cpu", kernelFunc: ({ inputs: r15, attrs: e, backend: t10 }) => {
  let { x: o } = r15, { filterSize: n, strides: s, pad: a, includeBatchInIndex: i } = e, p = t10;
  Q(o, "MaxPoolWithArgmax");
  let u = p.data.get(o.dataId).values, c = w.computePool2DInfo(o.shape, n, s, [1, 1], a), [l, m] = f$(u, o.shape, o.dtype, i, c), d = p.write(l, c.outShape, o.dtype), f = p.write(m, c.outShape, o.dtype);
  return [{ dataId: d, shape: c.outShape, dtype: o.dtype }, { dataId: f, shape: c.outShape, dtype: "int32" }];
} };
function WQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o, i = y.parseAxisParam(s, n.shape), u = w.computeOutAndReduceShapes(n.shape, i)[1], c = y.sizeFromShape(u), l = [], m = t10.makeTensorInfo([], "float32", new Float32Array([c]));
  l.push(m);
  let d = Ro({ inputs: { x: n }, backend: t10, attrs: { dtype: "float32" } });
  l.push(d);
  let f = Ul({ inputs: { a: d, b: m }, backend: t10 });
  l.push(f);
  let h = fi({ inputs: { x: f }, backend: t10, attrs: { axis: s, keepDims: a } });
  return l.forEach((g) => t10.disposeIntermediateTensorInfo(g)), h;
}
var g$ = { kernelName: Un, backendName: "cpu", kernelFunc: WQ };
function UQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o;
  Q(n, "min");
  let i = y.parseAxisParam(s, n.shape), p = i, u = w.getAxesPermutation(p, n.shape.length), c = n;
  u != null && (c = St({ inputs: { x: n }, backend: t10, attrs: { perm: u } }), p = w.getInnerMostAxes(p.length, n.shape.length)), w.assertAxesAreInnerMostDims("min", p, c.shape.length);
  let [l, m] = w.computeOutAndReduceShapes(c.shape, p), d = y.sizeFromShape(m), f = y.makeZerosTypedArray(y.sizeFromShape(l), c.dtype), h = t10.data.get(c.dataId).values;
  for (let x = 0; x < f.length; ++x) {
    let b = x * d, C = h[b];
    for (let S = 0; S < d; ++S) {
      let k = h[b + S];
      (Number.isNaN(k) || k < C) && (C = k);
    }
    f[x] = C;
  }
  u != null && t10.disposeIntermediateTensorInfo(c);
  let g = t10.makeTensorInfo(l, c.dtype, f);
  if (a) {
    let x = w.expandShapeToKeepDim(l, i), b = We({ inputs: { x: g }, backend: t10, attrs: { shape: x } });
    return t10.disposeIntermediateTensorInfo(g), b;
  }
  return g;
}
var x$ = { kernelName: "Min", backendName: "cpu", kernelFunc: UQ };
function GQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { paddings: s, mode: a } = o;
  Q(n, "mirrorPad");
  let i = s.map((C, S) => C[0] + n.shape[S] + C[1]), p = s.map((C) => C[0]), u = s.map((C, S) => C[0] + n.shape[S]), c = a === "reflect" ? 0 : 1, l = t10.data.get(n.dataId).values, m = n.shape.length, d = y.computeStrides(n.shape), f = y.sizeFromShape(i), h = i.length, g = y.computeStrides(i), x = y.getTypedArrayFromDType(n.dtype, f);
  for (let C = 0; C < f; C++) {
    let S = y.indexToLoc(C, h, g);
    for (let _ = 0; _ < h; _++) S[_] < p[_] ? S[_] = p[_] * 2 - S[_] - c : S[_] >= u[_] && (S[_] = (u[_] - 1) * 2 - S[_] + c);
    S = S.map((_, $) => _ - p[$]);
    let k = y.locToIndex(S, m, d);
    x[C] = l[k];
  }
  return { dataId: t10.write(x, i, n.dtype), shape: i, dtype: n.dtype };
}
var y$ = { kernelName: Kn, backendName: "cpu", kernelFunc: GQ };
var HQ = Ve(((r15, e) => {
  let t10 = r15 % e;
  return r15 < 0 && e < 0 || r15 >= 0 && e >= 0 ? t10 : (t10 + e) % e;
}));
var KQ = Ye("Mod", HQ);
var b$ = { kernelName: "Mod", backendName: "cpu", kernelFunc: KQ };
var w$ = zp(jw());
function vI(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { logits: n } = e, { dim: s } = o, a = n.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 p = y.parseAxisParam([i], n.shape), u = II({ inputs: { x: n }, backend: t10, attrs: { reductionIndices: p, keepDims: false } }), c = w.expandShapeToKeepDim(u.shape, p), l = We({ inputs: { x: u }, backend: t10, attrs: { shape: c } }), m = Vl({ inputs: { a: n, b: l }, backend: t10 }), d = qS({ inputs: { x: m }, backend: t10 }), f = fi({ inputs: { x: d }, backend: t10, attrs: { axis: p, keepDims: false } }), h = We({ inputs: { x: f }, backend: t10, attrs: { shape: c } }), g = Ul({ inputs: { a: d, b: h }, backend: t10 });
  return t10.disposeIntermediateTensorInfo(u), t10.disposeIntermediateTensorInfo(l), t10.disposeIntermediateTensorInfo(m), t10.disposeIntermediateTensorInfo(d), t10.disposeIntermediateTensorInfo(f), t10.disposeIntermediateTensorInfo(h), g;
}
var C$ = { kernelName: Is, backendName: "cpu", kernelFunc: vI };
function qQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { logits: n } = e, { numSamples: s, seed: a, normalized: i } = o;
  Q(n, "multinomial");
  let p = i ? n : vI({ inputs: { logits: n }, backend: t10, attrs: { dim: -1 } }), u = p.shape[0], c = p.shape[1], l = t10.data.get(p.dataId).values, m = [u, s], d = y.makeZerosTypedArray(y.sizeFromShape(m), "int32");
  for (let f = 0; f < u; ++f) {
    let h = f * c, g = new Float32Array(c - 1);
    g[0] = l[h];
    for (let C = 1; C < g.length; ++C) g[C] = g[C - 1] + l[h + C];
    let x = w$.alea(a.toString()), b = f * s;
    for (let C = 0; C < s; ++C) {
      let S = x();
      d[b + C] = g.length;
      for (let k = 0; k < g.length; k++) if (S < g[k]) {
        d[b + C] = k;
        break;
      }
    }
  }
  return i || t10.disposeIntermediateTensorInfo(p), t10.makeTensorInfo(m, "int32", d);
}
var S$ = { kernelName: jn, backendName: "cpu", kernelFunc: qQ };
var jQ = Vt.nonMaxSuppressionV3Impl;
function XQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { boxes: n, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: p } = o;
  Q(n, "NonMaxSuppression");
  let u = t10.data.get(n.dataId).values, c = t10.data.get(s.dataId).values, { selectedIndices: l } = jQ(u, c, a, i, p);
  return t10.makeTensorInfo([l.length], "int32", new Int32Array(l));
}
var I$ = { kernelName: Qn, backendName: "cpu", kernelFunc: XQ };
var YQ = Vt.nonMaxSuppressionV4Impl;
function QQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { boxes: n, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: p, padToMaxOutputSize: u } = o;
  Q(n, "NonMaxSuppressionPadded");
  let c = t10.data.get(n.dataId).values, l = t10.data.get(s.dataId).values, { selectedIndices: m, validOutputs: d } = YQ(c, l, a, i, p, u);
  return [t10.makeTensorInfo([m.length], "int32", new Int32Array(m)), t10.makeTensorInfo([], "int32", new Int32Array([d]))];
}
var v$ = { kernelName: Qa, backendName: "cpu", kernelFunc: QQ };
var ZQ = Vt.nonMaxSuppressionV5Impl;
function JQ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { boxes: n, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: p, softNmsSigma: u } = o;
  Q(n, "NonMaxSuppressionWithScore");
  let c = t10.data.get(n.dataId).values, l = t10.data.get(s.dataId).values, m = a, d = i, f = p, h = u, { selectedIndices: g, selectedScores: x } = ZQ(c, l, m, d, f, h);
  return [t10.makeTensorInfo([g.length], "int32", new Int32Array(g)), t10.makeTensorInfo([x.length], "float32", new Float32Array(x))];
}
var k$ = { kernelName: Zn, backendName: "cpu", kernelFunc: JQ };
function e7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { indices: n } = e, { dtype: s, depth: a, onValue: i, offValue: p } = o;
  Q(n, "oneHot");
  let u = y.sizeFromShape(n.shape), c = new Float32Array(u * a);
  c.fill(p);
  let l = t10.data.get(n.dataId).values;
  for (let m = 0; m < u; ++m) l[m] >= 0 && l[m] < a && (c[m * a + l[m]] = i);
  return t10.makeTensorInfo([...n.shape, a], s, c);
}
var N$ = { kernelName: Jn, backendName: "cpu", kernelFunc: e7 };
function Kl(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e;
  if (o.dtype === "string") throw new Error("zerosLike is not supported for string tensors");
  if (o.dtype === "complex64") {
    let n = $o({ inputs: { input: o }, backend: t10 }), s = Kl({ inputs: { x: n }, backend: t10 }), a = Oa({ inputs: { input: o }, backend: t10 }), i = Kl({ inputs: { x: a }, backend: t10 }), p = Ht({ inputs: { real: s, imag: i }, backend: t10 });
    return t10.disposeIntermediateTensorInfo(n), t10.disposeIntermediateTensorInfo(s), t10.disposeIntermediateTensorInfo(a), t10.disposeIntermediateTensorInfo(i), p;
  } else return Hl({ backend: t10, attrs: { shape: o.shape, value: 0, dtype: o.dtype } });
}
var T$ = { kernelName: Sa, backendName: "cpu", kernelFunc: Kl };
function _$(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e;
  if (o.dtype === "string") throw new Error("onesLike is not supported for string tensors");
  if (o.dtype === "complex64") {
    let n = $o({ inputs: { input: o }, backend: t10 }), s = _$({ inputs: { x: n }, backend: t10 }), a = Oa({ inputs: { input: o }, backend: t10 }), i = Kl({ inputs: { x: a }, backend: t10 }), p = Ht({ inputs: { real: s, imag: i }, backend: t10 });
    return t10.disposeIntermediateTensorInfo(n), t10.disposeIntermediateTensorInfo(s), t10.disposeIntermediateTensorInfo(a), t10.disposeIntermediateTensorInfo(i), p;
  } else return Hl({ backend: t10, attrs: { shape: o.shape, value: 1, dtype: o.dtype } });
}
var E$ = { kernelName: ca, backendName: "cpu", kernelFunc: _$ };
function kI(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { axis: n } = o;
  if (e.length === 1) return kc({ inputs: { input: e[0] }, backend: t10, attrs: { dim: n } });
  let s = e[0].shape, a = e[0].dtype;
  e.forEach((c) => {
    y.assertShapesMatch(s, c.shape, "All tensors passed to stack must have matching shapes"), y.assert(a === c.dtype, () => "All tensors passed to stack must have matching dtypes");
  });
  let i = [], p = e.map((c) => {
    let l = kc({ inputs: { input: c }, backend: t10, attrs: { dim: n } });
    return i.push(l), l;
  }), u = hu({ inputs: p, backend: t10, attrs: { axis: n } });
  return i.forEach((c) => t10.disposeIntermediateTensorInfo(c)), u;
}
var $$ = { kernelName: la, backendName: "cpu", kernelFunc: kI };
function t7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { paddings: s, constantValue: a } = o;
  Q(n, "pad");
  let i = s.map((b, C) => b[0] + n.shape[C] + b[1]), p = s.map((b) => b[0]), u = t10.data.get(n.dataId).values, c = y.sizeFromShape(n.shape), l = n.shape.length, m = y.computeStrides(n.shape), d = y.sizeFromShape(i), f = i.length, h = y.computeStrides(i), g = y.getTypedArrayFromDType(n.dtype, d);
  a !== 0 && g.fill(a);
  for (let b = 0; b < c; b++) {
    let S = y.indexToLoc(b, l, m).map((_, $) => _ + p[$]), k = y.locToIndex(S, f, h);
    g[k] = u[b];
  }
  return { dataId: t10.write(g, i, n.dtype), shape: i, dtype: n.dtype };
}
var Wf = { kernelName: es, backendName: "cpu", kernelFunc: t7 };
var r72 = Ve((r15, e) => Math.pow(r15, e));
var o7 = Ye("Pow", r72);
var R$ = { kernelName: "Pow", backendName: "cpu", kernelFunc: o7 };
function n7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { paramsNestedSplits: n, paramsDenseValues: s, indices: a } = e, { outputRaggedRank: i } = o, p = n.map((x) => t10.data.get(x.dataId).values), u = n.map((x) => x.shape), c = t10.data.get(s.dataId).values, l = t10.data.get(a.dataId).values, [m, d, f] = Rf(p, u, c, s.shape, s.dtype, l, a.shape, i), h = m.map((x) => t10.makeTensorInfo([x.length], "int32", x)), g = t10.makeTensorInfo(f, s.dtype, d);
  return h.concat([g]);
}
var D$ = { kernelName: Hp, backendName: "cpu", kernelFunc: n7 };
function s7(r15) {
  let { inputs: e, backend: t10 } = r15, { starts: o, limits: n, deltas: s } = e, a = t10.data.get(o.dataId).values, i = t10.data.get(n.dataId).values, p = t10.data.get(s.dataId).values, [u, c] = Df(a, o.shape, o.dtype, i, n.shape, p, s.shape), l = t10.makeTensorInfo([u.length], "int32", u), m = t10.makeTensorInfo([c.length], o.dtype, c);
  return [l, m];
}
var A$ = { kernelName: Kp, backendName: "cpu", kernelFunc: s7 };
function a7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { shape: n, values: s, defaultValue: a, rowPartitionTensors: i } = e, { rowPartitionTypes: p } = o, u = t10.data.get(n.dataId).values, c = t10.data.get(s.dataId).values, l = t10.data.get(a.dataId).values, m = i.map((g) => t10.data.get(g.dataId).values), d = i.map((g) => g.shape), [f, h] = Af(u, n.shape, c, s.shape, s.dtype, l, a.shape, m, d, p);
  return t10.makeTensorInfo(f, s.dtype, h);
}
var F$ = { kernelName: qp, backendName: "cpu", kernelFunc: a7 };
function i7(r15) {
  let { backend: e, attrs: t10 } = r15, { start: o, stop: n, dtype: s, step: a } = t10, i = up(o, n, a, s);
  return e.makeTensorInfo([i.length], s, i);
}
var P$ = { kernelName: ma, backendName: "cpu", kernelFunc: i7 };
var u7 = Ie(ns, (r15) => 1 / r15);
var O$ = { kernelName: ns, backendName: "cpu", kernelFunc: u7 };
function p7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n } = e, { alignCorners: s, halfPixelCenters: a, size: i } = o;
  Q(n, "resizeBilinear");
  let p = y.computeStrides(n.shape), [u, c] = i, [l, m, d, f] = n.shape, h = t10.data.get(n.dataId).values, g = new Float32Array(y.sizeFromShape([l, u, c, f])), x = [s && u > 1 ? m - 1 : m, s && c > 1 ? d - 1 : d], b = [s && u > 1 ? u - 1 : u, s && c > 1 ? c - 1 : c], C = 0, S = x[0] / b[0], k = x[1] / b[1];
  for (let _ = 0; _ < l; _++) for (let $ = 0; $ < u; $++) {
    let R;
    a ? R = S * ($ + 0.5) - 0.5 : R = S * $;
    let D = Math.max(0, Math.floor(R)), P = R - D, O = Math.min(m - 1, Math.ceil(R)), M = _ * p[0] + D * p[1], L = _ * p[0] + O * p[1];
    for (let B = 0; B < c; B++) {
      let z;
      a ? z = k * (B + 0.5) - 0.5 : z = k * B;
      let U = Math.max(0, Math.floor(z)), j = z - U, q = Math.min(d - 1, Math.ceil(z)), Y = M + U * p[2], J = L + U * p[2], re = M + q * p[2], ne = L + q * p[2];
      for (let ee = 0; ee < f; ee++) {
        let oe = h[Y + ee], ie = h[J + ee], le = h[re + ee], be = h[ne + ee], _e = oe + (le - oe) * j, ve = ie + (be - ie) * j, Fe = _e + (ve - _e) * P;
        g[C++] = Fe;
      }
    }
  }
  return t10.makeTensorInfo([l, u, c, f], "float32", g);
}
var M$ = { kernelName: is, backendName: "cpu", kernelFunc: p7 };
function c7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n, dy: s } = e, { alignCorners: a } = o;
  Q([s, n], "resizeBilinearGrad");
  let i = y.computeStrides(n.shape), [p, u, c, l] = n.shape, [, m, d] = s.shape, f = new Float32Array(p * u * c * l), h = [a && m > 1 ? u - 1 : u, a && d > 1 ? c - 1 : c], g = [a && m > 1 ? m - 1 : m, a && d > 1 ? d - 1 : d], x = h[0] / g[0], b = h[1] / g[1], C = t10.data.get(s.dataId).values, S = 0;
  for (let k = 0; k < p; k++) {
    let _ = k * i[0];
    for (let $ = 0; $ < m; $++) {
      let R = $ * x, D = Math.floor(R), P = Math.min(Math.ceil(R), u - 1), O = _ + D * i[1], M = _ + P * i[1], L = R - D, B = 1 - L;
      for (let z = 0; z < d; z++) {
        let U = z * b, j = Math.floor(U), q = Math.min(Math.ceil(U), c - 1), Y = U - j, J = 1 - Y, re = O + j * i[2], ne = O + q * i[2], ee = M + j * i[2], oe = M + q * i[2], ie = B * J, le = B * Y, be = L * J, _e = L * Y;
        for (let ve = 0; ve < l; ve++) {
          let Fe = C[S++];
          f[re + ve] += Fe * ie, f[ne + ve] += Fe * le, f[ee + ve] += Fe * be, f[oe + ve] += Fe * _e;
        }
      }
    }
  }
  return t10.makeTensorInfo([p, c, u, l], "float32", f);
}
var L$ = { kernelName: Ja, backendName: "cpu", kernelFunc: c7 };
function l7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n } = e, { alignCorners: s, halfPixelCenters: a, size: i } = o;
  Q(n, "resizeNearestNeighbor");
  let p = y.computeStrides(n.shape), [u, c] = i, [l, m, d, f] = n.shape, h = t10.data.get(n.dataId).values, g = new Float32Array(l * u * c * f), x = [s && u > 1 ? m - 1 : m, s && c > 1 ? d - 1 : d], b = [s && u > 1 ? u - 1 : u, s && c > 1 ? c - 1 : c], C = x[0] / b[0], S = x[1] / b[1], k = 0;
  for (let _ = 0; _ < l; _++) {
    let $ = _ * p[0];
    for (let R = 0; R < u; R++) {
      let D = a ? C * (R + 0.5) : C * R, P = Math.min(m - 1, s ? Math.round(D) : Math.floor(D));
      a && (P = Math.max(0, P));
      let O = $ + P * p[1];
      for (let M = 0; M < c; M++) {
        let L = a ? S * (M + 0.5) : S * M, B = Math.min(d - 1, s ? Math.round(L) : Math.floor(L));
        a && (B = Math.max(0, B));
        let z = O + B * p[2];
        for (let U = 0; U < f; U++) {
          let j = h[z + U];
          g[k++] = j;
        }
      }
    }
  }
  return t10.makeTensorInfo([l, u, c, f], n.dtype, g);
}
var B$ = { kernelName: as, backendName: "cpu", kernelFunc: l7 };
function m7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n, dy: s } = e, { alignCorners: a } = o;
  Q([s, n], "resizeNearestNeighborGrad");
  let i = y.computeStrides(n.shape), p = y.computeStrides(s.shape), [u, c, l, m] = n.shape, [, d, f] = s.shape, h = new Float32Array(u * c * l * m), g = t10.data.get(s.dataId).values, x = [a && d > 1 ? c - 1 : c, a && f > 1 ? l - 1 : l], b = [a && d > 1 ? d - 1 : d, a && f > 1 ? f - 1 : f], C = x[0] / b[0], S = x[1] / b[1], k = 1 / C, _ = 1 / S, $ = Math.ceil(k) * 2 + 2, R = Math.ceil(_) * 2 + 2;
  for (let D = 0; D < u; D++) {
    let P = D * i[0];
    for (let O = 0; O < c; O++) {
      let M = P + O * i[1], L = Math.floor(O * k), B = Math.floor(L - $ / 2);
      for (let z = 0; z < l; z++) {
        let U = M + z * i[2], j = Math.floor(z * _), q = Math.floor(j - R / 2);
        for (let Y = 0; Y < m; Y++) {
          let J = 0;
          for (let re = 0; re < $; re++) {
            let ne = re + B;
            if (ne < 0 || ne >= d) continue;
            let ee = P + ne * p[1], oe = ne * C, ie = Math.min(c - 1, a ? Math.round(oe) : Math.floor(oe));
            if (O === ie) for (let le = 0; le < R; le++) {
              let be = le + q;
              if (be < 0 || be >= f) continue;
              let _e = ee + be * p[2], ve = be * S, Fe = Math.min(l - 1, a ? Math.round(ve) : Math.floor(ve));
              z === Fe && (J += g[_e + Y]);
            }
          }
          h[U + Y] = J;
        }
      }
    }
  }
  return t10.makeTensorInfo(n.shape, n.dtype, h);
}
var z$ = { kernelName: Za, backendName: "cpu", kernelFunc: m7 };
function d7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { dims: s } = o;
  Q(n, "reverse");
  let a = n.shape.length, i = y.parseAxisParam(s, n.shape);
  if (a === 0) return lr({ inputs: { x: n }, backend: t10 });
  let p = new tt(n.shape, n.dtype), u = t10.bufferSync(n);
  for (let c = 0; c < p.size; c++) {
    let l = p.indexToLoc(c), m = l.slice();
    i.forEach((d) => m[d] = n.shape[d] - 1 - m[d]), p.set(u.get(...m), ...l);
  }
  return t10.makeTensorInfo(p.shape, p.dtype, p.values);
}
var V$ = { kernelName: ps, backendName: "cpu", kernelFunc: d7 };
var W$ = { kernelName: Ds, backendName: "cpu", kernelFunc: ({ inputs: r15, attrs: e, backend: t10 }) => {
  let { image: o } = r15, { radians: n, fillValue: s, center: a } = e, i = t10, p = y.getTypedArrayFromDType(o.dtype, y.sizeFromShape(o.shape)), [u, c, l, m] = o.shape, [d, f] = w.getImageCenter(a, c, l), h = 255, g = Math.sin(n), x = Math.cos(n), b = i.data.get(o.dataId).values;
  for (let S = 0; S < u; S++) {
    let k = S * l * c * m;
    for (let _ = 0; _ < c; _++) {
      let $ = _ * (l * m);
      for (let R = 0; R < l; R++) {
        let D = R * m;
        for (let P = 0; P < m; P++) {
          let O = [u, _, R, P], M = O[2], L = O[1], B = (M - d) * x - (L - f) * g, z = (M - d) * g + (L - f) * x;
          B = Math.round(B + d), z = Math.round(z + f);
          let U = s;
          if (typeof s != "number" && (P === 3 ? U = h : U = s[P]), B >= 0 && B < l && z >= 0 && z < c) {
            let q = z * (l * m), Y = B * m, J = k + q + Y + P;
            U = b[J];
          }
          let j = k + $ + D + P;
          p[j] = U;
        }
      }
    }
  }
  return { dataId: i.write(p, o.shape, o.dtype), shape: o.shape, dtype: o.dtype };
} };
var f7 = Ie(cs, (r15) => {
  let e = Math.floor(r15);
  return r15 - e < 0.5 ? Math.floor(r15) : r15 - e > 0.5 ? Math.ceil(r15) : e % 2 === 0 ? e : e + 1;
});
var U$ = { kernelName: cs, backendName: "cpu", kernelFunc: f7 };
function h7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { indices: n, updates: s } = e, { shape: a } = o, { sliceRank: i, numUpdates: p, sliceSize: u, strides: c, outputSize: l } = w.calculateShapes(s, n, a), m = true, d = t10.bufferSync(n), f = t10.bufferSync(s), h = zs(d, f, a, l, u, p, i, c, 0, m);
  return t10.makeTensorInfo(a, h.dtype, h.values);
}
var G$ = { kernelName: ms, backendName: "cpu", kernelFunc: h7 };
function g7(r15, e) {
  let t10 = 0, o = r15.length, n = 0;
  for (; t10 < o; ) n = Math.floor((t10 + o) / 2), r15[n] < e ? t10 = n + 1 : o = n;
  return o;
}
function x7(r15, e) {
  let t10 = 0, o = r15.length, n = 0;
  for (; t10 < o; ) n = Math.floor((t10 + o) / 2), r15[n] <= e ? t10 = n + 1 : o = n;
  return o;
}
function H$(r15, e, t10, o, n, s) {
  let a = y.getArrayFromDType("int32", t10 * n);
  for (let i = 0; i < t10; ++i) {
    let p = r15.slice(i * o, (i + 1) * o), u = i * n;
    for (let c = 0; c < n; ++c) a[u + c] = s === "left" ? g7(p, e[c + u]) : x7(p, e[c + u]);
  }
  return a;
}
function y7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { sortedSequence: n, values: s } = e, { side: a } = o, i = t10.data.get(n.dataId).values, p = t10.data.get(s.dataId).values, u = H$(i, p, n.shape[0], n.shape[1], s.shape[1], a);
  return t10.makeTensorInfo(s.shape, "int32", u);
}
var K$ = { kernelName: fs, backendName: "cpu", kernelFunc: y7 };
function b7(r15) {
  let { inputs: e, backend: t10 } = r15, { condition: o, t: n, e: s } = e;
  Q([o, n, s], "select");
  let a = o.shape.length, i = t10.data.get(o.dataId).values, p = t10.data.get(n.dataId).values, u = t10.data.get(s.dataId).values, c = dt(n.dtype, s.dtype), l = y.makeZerosTypedArray(y.sizeFromShape(n.shape), c), m = 0, d = a === 0 || a > 1 || n.shape.length === 1 ? 1 : y.sizeFromShape(n.shape.slice(1));
  for (let f = 0; f < i.length; f++) for (let h = 0; h < d; h++) i[f] === 1 ? l[m++] = p[f] : l[m++] = u[f];
  return t10.makeTensorInfo(n.shape, c, l);
}
var q$ = { kernelName: fa, backendName: "cpu", kernelFunc: b7 };
var C7 = w.SELU_SCALEALPHA;
var w7 = w.SELU_SCALE;
var S7 = Ie(hs, (r15) => r15 >= 0 ? w7 * r15 : C7 * (Math.exp(r15) - 1));
var j$ = { kernelName: hs, backendName: "cpu", kernelFunc: S7 };
var I7 = Ie(ys, (r15) => r15 < 0 ? -1 : r15 > 0 ? 1 : 0);
var X$ = { kernelName: ys, backendName: "cpu", kernelFunc: I7 };
var v7 = Ie("Sin", (r15) => Math.sin(r15));
var Y$ = { kernelName: "Sin", backendName: "cpu", kernelFunc: v7 };
var k7 = Ie(xs, (r15) => Math.sinh(r15));
var Q$ = { kernelName: xs, backendName: "cpu", kernelFunc: k7 };
var N7 = 11920928955078125e-23;
var Z$ = Math.log(N7) + 2;
var T7 = Ie(Cs, (r15) => {
  let e = r15 > -Z$, t10 = r15 < Z$, o = Math.exp(r15), n;
  return t10 ? n = o : e ? n = r15 : n = Math.log(1 + o), n;
});
var J$ = { kernelName: Cs, backendName: "cpu", kernelFunc: T7 };
function _7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { blockShape: s, paddings: a } = o;
  Q([n], "spaceToBatchND");
  let i = y.sizeFromShape(s), p = [[0, 0]];
  p.push(...a);
  for (let _ = 1 + s.length; _ < n.shape.length; ++_) p.push([0, 0]);
  let u = Wf.kernelFunc({ inputs: { x: n }, backend: t10, attrs: { paddings: p, constantValue: 0 } }), c = w.getReshaped(u.shape, s, i, false), l = w.getPermuted(c.length, s.length, false), m = w.getReshapedPermuted(u.shape, s, i, false), h = We({ inputs: { x: u }, backend: t10, attrs: { shape: c } }), b = St({ inputs: { x: h }, backend: t10, attrs: { perm: l } }), k = We({ inputs: { x: b }, backend: t10, attrs: { shape: m } });
  return t10.disposeIntermediateTensorInfo(u), t10.disposeIntermediateTensorInfo(h), t10.disposeIntermediateTensorInfo(b), k;
}
var eR = { kernelName: ga, backendName: "cpu", kernelFunc: _7 };
function E7(r15) {
  let { inputs: e, backend: t10 } = r15, { indices: o, values: n, denseShape: s, defaultValue: a } = e;
  if (s.shape.length !== 1) throw new Error(`Dense shape must be a vector, saw:
        ${s.shape}`);
  if (o.shape.length !== 2) throw new Error(`Indices must be a matrix, saw:
        ${o.shape}`);
  if (n.shape.length !== 1) throw new Error(`Values must be a vector, saw:
        ${n.shape}`);
  if (a.shape.length !== 0) throw new Error(`Default value must be a scalar, saw:
        ${a.shape}`);
  let i = t10.data.get(o.dataId).values, p = t10.data.get(n.dataId).values, u = t10.data.get(s.dataId).values, c = t10.data.get(a.dataId).values[0], [l, m, d, f, h] = Ff(i, o.shape, o.dtype, p, n.dtype, u, c);
  return [t10.makeTensorInfo(m, o.dtype, l), t10.makeTensorInfo([m[0]], n.dtype, d), t10.makeTensorInfo([f.length], "bool", new Uint8Array(f.map((g) => Number(g)))), t10.makeTensorInfo([h.length], o.dtype, new Int32Array(h))];
}
var tR = { kernelName: Ki, backendName: "cpu", kernelFunc: E7 };
function $7(r15) {
  let { inputs: e, backend: t10 } = r15, { inputIndices: o, inputShape: n, newShape: s } = e;
  if (o.shape.length !== 2) throw new Error(`Input indices should be a matrix but received shape
        ${o.shape}`);
  if (n.shape.length !== 1) throw new Error(`Input shape should be a vector but received shape
        ${n.shape}`);
  if (s.shape.length !== 1) throw new Error(`Target shape should be a vector but received shape ${s.shape}`);
  let a = Array.from(t10.data.get(n.dataId).values), i = t10.data.get(o.dataId).values, p = Array.from(t10.data.get(s.dataId).values), [u, c, l] = Pf(i, o.shape, o.dtype, a, p);
  return [t10.makeTensorInfo(c, o.dtype, u), t10.makeTensorInfo([l.length], s.dtype, new Int32Array(l))];
}
var rR = { kernelName: ei, backendName: "cpu", kernelFunc: $7 };
function R7(r15) {
  let { inputs: e, backend: t10 } = r15, { data: o, indices: n, segmentIds: s } = e;
  if (o.shape.length < 1) throw new Error("Data should be at least 1 dimensional but received scalar");
  if (n.shape.length !== 1) throw new Error(`Indices should be a vector but received shape
          ${n.shape}`);
  if (s.shape.length !== 1) throw new Error(`Segment ids should be a vector but received shape
          ${s.shape}`);
  if (n.shape[0] !== s.shape[0]) throw new Error("segmentIds and indices should have same size.");
  let a = t10.data.get(o.dataId).values, i = t10.data.get(n.dataId).values, p = t10.data.get(s.dataId).values, [u, c] = Sc(a, o.shape, o.dtype, i, p, true);
  return t10.makeTensorInfo(c, o.dtype, u);
}
var oR = { kernelName: ya, backendName: "cpu", kernelFunc: R7 };
function D7(r15) {
  let { inputs: e, backend: t10 } = r15, { data: o, indices: n, segmentIds: s } = e;
  if (o.shape.length < 1) throw new Error("Data should be at least 1 dimensional but received scalar");
  if (n.shape.length !== 1) throw new Error(`Indices should be a vector but received shape
         ${n.shape}`);
  if (s.shape.length !== 1) throw new Error(`Segment ids should be a vector but received shape
         ${s.shape}`);
  if (n.shape[0] !== s.shape[0]) throw new Error("segmentIds and indices should have same size.");
  let a = t10.data.get(o.dataId).values, i = t10.data.get(n.dataId).values, p = t10.data.get(s.dataId).values, [u, c] = Sc(a, o.shape, o.dtype, i, p);
  return t10.makeTensorInfo(c, o.dtype, u);
}
var nR = { kernelName: ba, backendName: "cpu", kernelFunc: D7 };
function A7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { sparseIndices: n, sparseValues: s, defaultValue: a } = e, { outputShape: i } = o, { sliceRank: p, numUpdates: u, sliceSize: c, strides: l, outputSize: m } = w.calculateShapes(s, n, i), d = false, f = t10.bufferSync(n), h;
  switch (s.dtype) {
    case "bool": {
      let g = t10.bufferSync(s), x = !!t10.data.get(a.dataId).values[0];
      h = zs(f, g, i, m, c, u, p, l, x, d);
      break;
    }
    case "float32": {
      let g = t10.bufferSync(s), x = t10.data.get(a.dataId).values[0];
      h = zs(f, g, i, m, c, u, p, l, x, d);
      break;
    }
    case "int32": {
      let g = t10.bufferSync(s), x = t10.data.get(a.dataId).values[0];
      h = zs(f, g, i, m, c, u, p, l, x, d);
      break;
    }
    case "string": {
      let g = t10.bufferSync(s), x = y.decodeString(t10.data.get(a.dataId).values[0]);
      h = zs(f, g, i, m, c, u, p, l, x, d);
      break;
    }
    default:
      throw new Error(`Unsupported type ${s.dtype}`);
  }
  return t10.makeTensorInfo(i, h.dtype, h.values);
}
var sR = { kernelName: vs, backendName: "cpu", kernelFunc: A7 };
function F7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { numOrSizeSplits: s, axis: a } = o, i = y.parseAxisParam(a, n.shape)[0], p = w.prepareSplitSize(n, s, i), u = new Array(n.shape.length).fill(0), c = n.shape.slice();
  return p.map((l) => {
    let m = [...c];
    m[i] = l;
    let d = Ao({ inputs: { x: n }, backend: t10, attrs: { begin: u, size: m } });
    return u[i] += l, d;
  });
}
var aR = { kernelName: xa, backendName: "cpu", kernelFunc: F7 };
var iR = { kernelName: qi, backendName: "cpu", kernelFunc: ({ inputs: r15, backend: e }) => {
  let { x: t10 } = r15, o = e;
  Q(t10, "square");
  let n = o.data.get(t10.dataId).values, s = new Float32Array(n.length);
  for (let i = 0; i < n.length; ++i) {
    let p = n[i];
    s[i] = p * p;
  }
  return { dataId: o.write(s, t10.shape, t10.dtype), shape: t10.shape, dtype: t10.dtype };
} };
var P7 = Ie(wo, (r15, e) => {
  let t10 = e;
  return isNaN(r15) ? NaN : r15 > 0 ? 1 : t10.alpha;
});
var uR = { kernelName: wo, backendName: "cpu", kernelFunc: P7 };
function O7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { begin: s, end: a, strides: i, beginMask: p, endMask: u, ellipsisMask: c, newAxisMask: l, shrinkAxisMask: m } = o;
  Q(n, "stridedSlice");
  let { finalShapeSparse: d, finalShape: f, isIdentity: h, sliceDim0: g, isSimpleSlice: x, begin: b, end: C, strides: S } = pt.sliceInfo(n.shape, s, a, i, p, u, c, l, m), k;
  if (h) k = We({ inputs: { x: n }, backend: t10, attrs: { shape: f } });
  else if (g || x) {
    y.assert(n.shape.length >= 1, () => `Input must have rank at least 1, got: ${n.shape.length}`);
    let _ = pt.computeOutShape(b, C, S), $ = Ao({ inputs: { x: n }, backend: t10, attrs: { begin: b, size: _ } });
    k = We({ inputs: { x: $ }, backend: t10, attrs: { shape: f } }), t10.disposeIntermediateTensorInfo($);
  } else {
    let _ = t10.bufferSync(n), $ = Of(d, _, S, b);
    k = t10.makeTensorInfo(f, $.dtype, $.values);
  }
  return k;
}
var pR = { kernelName: Ns, backendName: "cpu", kernelFunc: O7 };
function M7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { separator: n, nGramWidths: s, leftPad: a, rightPad: i, padWidth: p, preserveShortSequences: u } = o, { data: c, dataSplits: l } = e, m = t10.data.get(c.dataId).values, d = t10.data.get(l.dataId).values, [f, h] = cp(m, d, n, s, a, i, p, u);
  return [t10.makeTensorInfo([f.length], "string", f), t10.makeTensorInfo(l.shape, "int32", h)];
}
var cR = { kernelName: Ca, backendName: "cpu", kernelFunc: M7 };
function L7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { skipEmpty: n } = o, { 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 = t10.data.get(s.dataId).values, p = t10.data.get(a.dataId).values[0], [u, c, l] = lp(i, p, n), m = c.length;
  return [t10.makeTensorInfo([m, 2], "int32", u), t10.makeTensorInfo([m], "string", c), t10.makeTensorInfo([2], "int32", new Int32Array(l))];
}
var lR = { kernelName: ji, backendName: "cpu", kernelFunc: L7 };
function B7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { numBuckets: n } = o, { input: s } = e;
  if (s.dtype !== "string") throw new Error("Input must be of datatype string");
  if (n <= 0) throw new Error("Number of buckets must be at least 1");
  let a = t10.data.get(s.dataId).values, i = mp(a, n);
  return t10.makeTensorInfo(s.shape, "int32", i);
}
var mR = { kernelName: Xi, backendName: "cpu", kernelFunc: B7 };
var z7 = Ie("Tan", (r15) => Math.tan(r15));
var dR = { kernelName: "Tan", backendName: "cpu", kernelFunc: z7 };
var V7 = Ie(Es, (r15) => Math.tanh(r15));
var fR = { kernelName: Es, backendName: "cpu", kernelFunc: V7 };
function W7(r15) {
  let { inputs: e, backend: t10 } = r15, { tensor: o, indices: n, updates: s } = e, { sliceRank: a, numUpdates: i, sliceSize: p, strides: u, outputSize: c } = w.calculateShapes(s, n, o.shape), l = false, m = t10.bufferSync(n), d = t10.bufferSync(s), f = t10.bufferSync(o), h = zs(m, d, o.shape, c, p, i, a, u, f, l);
  return t10.makeTensorInfo(o.shape, h.dtype, h.values);
}
var hR = { kernelName: ds, backendName: "cpu", kernelFunc: W7 };
function U7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { reps: s } = o;
  Q(n, "tile");
  let a = Mf(t10.bufferSync(n), s);
  return t10.makeTensorInfo(a.shape, a.dtype, a.values);
}
var gR = { kernelName: po, backendName: "cpu", kernelFunc: U7 };
function G7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { k: s, sorted: a } = o;
  Q(n, "topk");
  let i = t10.data.get(n.dataId).values, [p, u] = Lf(i, n.shape, n.dtype, s, a);
  return [t10.makeTensorInfo(p.shape, p.dtype, p.values), t10.makeTensorInfo(u.shape, u.dtype, u.values)];
}
var xR = { kernelName: $s, backendName: "cpu", kernelFunc: G7 };
function H7(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { image: n, transforms: s } = e, { interpolation: a, fillMode: i, fillValue: p, outputShape: u } = t10, [c, l, m, d] = n.shape, [f, h] = u != null ? u : [l, m], g = [c, f, h, d], x = y.computeStrides(n.shape), b = x[0], C = x[1], S = x[2], k = y.computeStrides(g), _ = k[0], $ = k[1], R = k[2], D = y.getTypedArrayFromDType(n.dtype, y.sizeFromShape(g));
  D.fill(p);
  let P = o.data.get(n.dataId).values, O = o.data.get(s.dataId).values;
  for (let L = 0; L < c; ++L) {
    let B = s.shape[0] === 1 ? O : O.subarray(L * 8, L * 8 + 8);
    for (let z = 0; z < f; ++z) for (let U = 0; U < h; ++U) for (let j = 0; j < d; ++j) {
      let q, Y = B[6] * U + B[7] * z + 1;
      if (Y === 0) continue;
      let J = (B[0] * U + B[1] * z + B[2]) / Y, re = (B[3] * U + B[4] * z + B[5]) / Y, ne = yR(J, m, i), ee = yR(re, l, i);
      switch (a) {
        case "nearest":
          q = Y7(P, l, m, b, C, S, L, ee, ne, j, p);
          break;
        case "bilinear":
          q = Q7(P, l, m, b, C, S, L, ee, ne, j, p);
          break;
        default:
          throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${a}`);
      }
      let oe = L * _ + z * $ + U * R + j;
      D[oe] = q;
    }
    return o.makeTensorInfo(g, n.dtype, D);
  }
  return { dataId: o.write(D, g, n.dtype), shape: n.shape, dtype: n.dtype };
}
var bR = { kernelName: Rs, backendName: "cpu", kernelFunc: H7 };
function yR(r15, e, t10) {
  switch (t10) {
    case "reflect":
      return K7(r15, e);
    case "wrap":
      return q7(r15, e);
    case "nearest":
      return X7(r15, e);
    case "constant":
    default:
      return j7(r15, e);
  }
}
function K7(r15, e) {
  let t10 = r15;
  if (t10 < 0) if (e <= 1) t10 = 0;
  else {
    let o = 2 * e;
    t10 < o && (t10 = o * Math.trunc(-t10 / o) + t10), t10 = t10 < -e ? t10 + o : -t10 - 1;
  }
  else if (t10 > e - 1) if (e <= 1) t10 = 0;
  else {
    let o = 2 * e;
    t10 -= o * Math.trunc(t10 / o), t10 >= e && (t10 = o - t10 - 1);
  }
  return y.clamp(0, t10, e - 1);
}
function q7(r15, e) {
  let t10 = r15;
  if (t10 < 0) if (e <= 1) t10 = 0;
  else {
    let o = e - 1;
    t10 += e * (Math.trunc(-t10 / o) + 1);
  }
  else if (t10 > e - 1) if (e <= 1) t10 = 0;
  else {
    let o = e - 1;
    t10 -= e * Math.trunc(t10 / o);
  }
  return y.clamp(0, t10, e - 1);
}
function j7(r15, e) {
  return r15;
}
function X7(r15, e) {
  return y.clamp(0, r15, e - 1);
}
function ql(r15, e, t10, o, n, s, a, i, p, u, c) {
  let l = a * o + i * n + p * s + u;
  return 0 <= i && i < e && 0 <= p && p < t10 ? r15[l] : c;
}
function Y7(r15, e, t10, o, n, s, a, i, p, u, c) {
  let l = Math.round(i), m = Math.round(p);
  return ql(r15, e, t10, o, n, s, a, l, m, u, c);
}
function Q7(r15, e, t10, o, n, s, a, i, p, u, c) {
  let l = Math.floor(i), m = Math.floor(p), d = l + 1, f = m + 1, h = (f - p) * ql(r15, e, t10, o, n, s, a, l, m, u, c) + (p - m) * ql(r15, e, t10, o, n, s, a, l, f, u, c), g = (f - p) * ql(r15, e, t10, o, n, s, a, d, m, u, c) + (p - m) * ql(r15, e, t10, o, n, s, a, d, f, u, c);
  return (d - i) * h + (i - l) * g;
}
function Z7(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { axis: n } = t10, { x: s } = e;
  Q(s, "unique");
  let a = o.data.get(s.dataId).values, { outputValues: i, outputShape: p, indices: u } = dp(a, n, s.shape, s.dtype);
  return [o.makeTensorInfo(p, s.dtype, i), o.makeTensorInfo([u.length], "int32", u)];
}
var CR = { kernelName: Yi, backendName: "cpu", kernelFunc: Z7 };
function J7(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { value: n } = e, { axis: s } = o;
  s < 0 && (s += n.shape.length);
  let a = n.shape.length, i = n.shape[s], p = new Array(a - 1), u = 0;
  for (let d = 0; d < a; d++) d !== s && (p[u++] = n.shape[d]);
  let c = new Array(a).fill(0), l = n.shape.slice();
  l[s] = 1;
  let m = new Array(i);
  for (let d = 0; d < m.length; d++) {
    c[s] = d;
    let f = Ao({ inputs: { x: n }, backend: t10, attrs: { begin: c, size: l } });
    m[d] = We({ inputs: { x: f }, backend: t10, attrs: { shape: p } }), t10.disposeIntermediateTensorInfo(f);
  }
  return m;
}
var wR = { kernelName: wa, backendName: "cpu", kernelFunc: J7 };
function eZ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, segmentIds: s } = e, { numSegments: a } = o;
  Q(n, "unsortedSegmentSum");
  let i = n.shape.length, p = s.shape.length, u = [], c = [], l = i - p, m = s;
  for (let f = 0; f < l; ++f) {
    let h = kc({ inputs: { input: m }, backend: t10, attrs: { dim: f + 1 } });
    m = h, c.push(h);
  }
  for (let f = 0; f < a; ++f) {
    let h = y.createScalarValue(f, "int32"), g = t10.makeTensorInfo([], "int32", h), x = HS({ inputs: { a: g, b: m }, backend: t10 }), b = Ro({ inputs: { x }, backend: t10, attrs: { dtype: "float32" } }), C = ip({ inputs: { a: b, b: n }, backend: t10 }), S = fi({ inputs: { x: C }, backend: t10, attrs: { axis: 0, keepDims: false } });
    u.push(S), c.push(g), c.push(x), c.push(b), c.push(C), c.push(S);
  }
  let d = kI({ inputs: u, backend: t10, attrs: { axis: 0 } });
  return c.forEach((f) => t10.disposeIntermediateTensorInfo(f)), d;
}
var SR = { kernelName: Qi, backendName: "cpu", kernelFunc: eZ };
var tZ = [q_, t_, j_, X_, a_, Y_, Q_, Z_, J_, eE, tE, rE, oE, nE, sE, iE, uE, pE, cE, K_, lE, mE, dE, i_, fE, s_, u_, hE, r_, gE, yE, bE, CE, wE, SE, IE, vE, kE, NE, TE, _E, EE, $E, RE, DE, AE, FE, PE, OE, ME, LE, BE, VE, z_, WE, p_, UE, c_, GE, l_, HE, KE, qE, m_, d_, jE, XE, YE, QE, f_, h_, o_, ZE, xE, JE, e$, t$, V_, g_, x_, r$, y_, o$, n$, s$, a$, i$, u$, p$, b_, c$, l$, m$, d$, h$, g$, x$, C_, y$, b$, S$, w_, S_, I$, v$, k$, I_, N$, E$, $$, Wf, R$, W_, k_, D$, A$, F$, P$, n_, Gl, O$, U_, G_, H_, M$, L$, B$, z$, V$, W$, U$, $_, G$, K$, q$, j$, D_, X$, Y$, Q$, A_, C$, J$, eR, tR, rR, oR, nR, sR, aR, P_, iR, O_, M_, uR, pR, cR, lR, mR, L_, zE, dR, fR, hR, gR, xR, bR, v_, CR, wR, SR, T$];
for (let r15 of tZ) ti(r15);
var Ec = {};
qe(Ec, { assertNotComplex: () => Vs, bindCanvasToFramebuffer: () => cZ, bindColorTextureToFramebuffer: () => Ql, bindTextureToProgramUniformSampler: () => VI, bindTextureUnit: () => NR, bindVertexBufferToProgramAttribute: () => jf, callAndCheck: () => ce, canBeRepresented: () => EI, createFragmentShader: () => RI, createFramebuffer: () => LI, createProgram: () => DI, createStaticIndexBuffer: () => PI, createStaticVertexBuffer: () => FI, createTexture: () => OI, createVertexShader: () => $I, getBatchDim: () => gi, getExtensionOrThrow: () => Nc, getFramebufferErrorMessage: () => TR, getMaxTexturesInShader: () => GI, getNumChannels: () => uZ, getProgramUniformLocation: () => zI, getProgramUniformLocationOrThrow: () => BI, getRowsCols: () => xi, getShapeAs3D: () => _c, getTextureShapeFromLogicalShape: () => WI, getWebGLDisjointQueryTimerVersion: () => HI, getWebGLErrorMessage: () => kR, getWebGLMaxTextureSize: () => UI, hasExtension: () => qr, isCapableOfRenderingToFloatTexture: () => KI, isDownloadFloatTextureEnabled: () => qI, isReshapeFree: () => xu, isWebGLFenceEnabled: () => jI, isWebGLVersionEnabled: () => Yf, linkProgram: () => AI, logShaderSourceAndInfoLog: () => qf, resetMaxTextureSize: () => lZ, resetMaxTexturesInShader: () => mZ, unbindColorTextureFromFramebuffer: () => Xf, unbindTextureUnit: () => pZ, validateFramebuffer: () => Tc, validateProgram: () => Yl, validateTextureSize: () => MI });
var hp = {};
var Uf = { alpha: false, antialias: false, premultipliedAlpha: false, preserveDrawingBuffer: false, depth: false, stencil: false, failIfMajorPerformanceCaveat: true };
function NI(r15, e) {
  hp[r15] = e;
}
function Kr(r15, e) {
  if (!(r15 in hp) || e != null) {
    let o = oZ(r15, e);
    if (o !== null) hp[r15] = o;
    else return console.log("Could not get context for WebGL version", r15), null;
  }
  let t10 = hp[r15];
  return t10 == null || t10.isContextLost() ? (delete hp[r15], Kr(r15)) : (t10.disable(t10.DEPTH_TEST), t10.disable(t10.STENCIL_TEST), t10.disable(t10.BLEND), t10.disable(t10.DITHER), t10.disable(t10.POLYGON_OFFSET_FILL), t10.disable(t10.SAMPLE_COVERAGE), t10.enable(t10.SCISSOR_TEST), t10.enable(t10.CULL_FACE), t10.cullFace(t10.BACK), hp[r15]);
}
function rZ(r15) {
  if (!A().getBool("IS_SAFARI") && typeof OffscreenCanvas != "undefined" && r15 === 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 oZ(r15, e) {
  if (r15 !== 1 && r15 !== 2) throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");
  let t10 = e == null ? rZ(r15) : e;
  return t10.addEventListener("webglcontextlost", (o) => {
    o.preventDefault(), delete hp[r15];
  }, false), A().getBool("SOFTWARE_WEBGL_ENABLED") && (Uf.failIfMajorPerformanceCaveat = false), r15 === 1 ? t10.getContext("webgl", Uf) || t10.getContext("experimental-webgl", Uf) : t10.getContext("webgl2", Uf);
}
var gu;
(function(r15) {
  r15[r15.DENSE = 0] = "DENSE", r15[r15.SHARED_BATCH = 1] = "SHARED_BATCH";
})(gu || (gu = {}));
var mr;
(function(r15) {
  r15[r15.RENDER = 0] = "RENDER", r15[r15.UPLOAD = 1] = "UPLOAD", r15[r15.PIXELS = 2] = "PIXELS", r15[r15.DOWNLOAD = 3] = "DOWNLOAD";
})(mr || (mr = {}));
var er;
(function(r15) {
  r15[r15.UNPACKED_FLOAT16 = 0] = "UNPACKED_FLOAT16", r15[r15.UNPACKED_FLOAT32 = 1] = "UNPACKED_FLOAT32", r15[r15.PACKED_4X1_UNSIGNED_BYTE = 2] = "PACKED_4X1_UNSIGNED_BYTE", r15[r15.PACKED_2X2_FLOAT32 = 3] = "PACKED_2X2_FLOAT32", r15[r15.PACKED_2X2_FLOAT16 = 4] = "PACKED_2X2_FLOAT16";
})(er || (er = {}));
function gp(r15, e) {
  return [e, r15];
}
function IR(r15, e) {
  return r15 * e;
}
function jl(r15) {
  let e = y.sizeFromShape(r15), t10 = Math.ceil(e / 4);
  return y.sizeToSquarishShape(t10);
}
function Ma(r15, e) {
  return [Math.max(1, Math.ceil(e / 2)), Math.max(1, Math.ceil(r15 / 2))];
}
function vR(r15, e) {
  let [t10, o] = Ma(r15, e);
  return t10 * o * 4;
}
function Xl(r15, e) {
  let t10 = r15, o, n, s, a, i, p, u, c, l, m;
  return A().getNumber("WEBGL_VERSION") === 2 ? (o = t10.R32F, n = t10.R16F, s = t10.RGBA16F, a = t10.RGBA32F, i = t10.RED, u = 4, c = 1, l = t10.HALF_FLOAT, m = t10.FLOAT, p = t10.RGBA8) : (o = r15.RGBA, n = r15.RGBA, s = r15.RGBA, a = t10.RGBA, i = r15.RGBA, u = 4, c = 4, l = e != null ? e.HALF_FLOAT_OES : null, m = r15.FLOAT, p = r15.RGBA), { internalFormatFloat: o, internalFormatHalfFloat: n, internalFormatPackedHalfFloat: s, internalFormatPackedFloat: a, textureFormatFloat: i, downloadTextureFormat: p, downloadUnpackNumChannels: u, defaultNumChannels: c, textureTypeHalfFloat: l, textureTypeFloat: m };
}
function ce(r15, e) {
  let t10 = e();
  return A().getBool("DEBUG") && nZ(r15), t10;
}
function nZ(r15) {
  let e = r15.getError();
  if (e !== r15.NO_ERROR) throw new Error("WebGL Error: " + kR(r15, e));
}
var sZ = 596e-10;
var aZ = 65504;
function EI(r15) {
  return !!(A().getBool("WEBGL_RENDER_FLOAT32_ENABLED") || r15 === 0 || sZ < Math.abs(r15) && Math.abs(r15) < aZ);
}
function kR(r15, e) {
  switch (e) {
    case r15.NO_ERROR:
      return "NO_ERROR";
    case r15.INVALID_ENUM:
      return "INVALID_ENUM";
    case r15.INVALID_VALUE:
      return "INVALID_VALUE";
    case r15.INVALID_OPERATION:
      return "INVALID_OPERATION";
    case r15.INVALID_FRAMEBUFFER_OPERATION:
      return "INVALID_FRAMEBUFFER_OPERATION";
    case r15.OUT_OF_MEMORY:
      return "OUT_OF_MEMORY";
    case r15.CONTEXT_LOST_WEBGL:
      return "CONTEXT_LOST_WEBGL";
    default:
      return `Unknown error code ${e}`;
  }
}
function Nc(r15, e) {
  return hi(r15, () => r15.getExtension(e), 'Extension "' + e + '" not supported on this browser.');
}
function $I(r15, e) {
  let t10 = hi(r15, () => r15.createShader(r15.VERTEX_SHADER), "Unable to create vertex WebGLShader.");
  if (ce(r15, () => r15.shaderSource(t10, e)), ce(r15, () => r15.compileShader(t10)), r15.getShaderParameter(t10, r15.COMPILE_STATUS) === false) throw console.log(r15.getShaderInfoLog(t10)), new Error("Failed to compile vertex shader.");
  return t10;
}
function RI(r15, e) {
  let t10 = hi(r15, () => r15.createShader(r15.FRAGMENT_SHADER), "Unable to create fragment WebGLShader.");
  if (ce(r15, () => r15.shaderSource(t10, e)), ce(r15, () => r15.compileShader(t10)), A().get("ENGINE_COMPILE_ONLY")) return t10;
  if (r15.getShaderParameter(t10, r15.COMPILE_STATUS) === false) throw qf(e, r15.getShaderInfoLog(t10)), new Error("Failed to compile fragment shader.");
  return t10;
}
var iZ = /ERROR: [0-9]+:([0-9]+):/g;
function qf(r15, e) {
  let t10 = iZ.exec(e);
  if (t10 == null) {
    console.log(`Couldn't parse line number in error: ${e}`), console.log(r15);
    return;
  }
  let o = +t10[1], n = r15.split(`
`), s = n.length.toString().length + 2, a = n.map((l, m) => y.rightPad((m + 1).toString(), s) + l), i = 0;
  for (let l = 0; l < a.length; l++) i = Math.max(a[l].length, i);
  let p = a.slice(0, o - 1), u = a.slice(o - 1, o), c = a.slice(o);
  console.log(p.join(`
`)), console.log(e.split(`
`)[0]), console.log(`%c ${y.rightPad(u[0], i)}`, "border:1px solid red; background-color:#e3d2d2; color:#a61717"), console.log(c.join(`
`));
}
function DI(r15) {
  return hi(r15, () => r15.createProgram(), "Unable to create WebGLProgram.");
}
function AI(r15, e) {
  if (ce(r15, () => r15.linkProgram(e)), !A().get("ENGINE_COMPILE_ONLY") && r15.getProgramParameter(e, r15.LINK_STATUS) === false) throw console.log(r15.getProgramInfoLog(e)), new Error("Failed to link vertex and fragment shaders.");
}
function Yl(r15, e) {
  if (ce(r15, () => r15.validateProgram(e)), r15.getProgramParameter(e, r15.VALIDATE_STATUS) === false) throw console.log(r15.getProgramInfoLog(e)), new Error("Shader program validation failed.");
}
function FI(r15, e) {
  let t10 = hi(r15, () => r15.createBuffer(), "Unable to create WebGLBuffer");
  return ce(r15, () => r15.bindBuffer(r15.ARRAY_BUFFER, t10)), ce(r15, () => r15.bufferData(r15.ARRAY_BUFFER, e, r15.STATIC_DRAW)), t10;
}
function PI(r15, e) {
  let t10 = hi(r15, () => r15.createBuffer(), "Unable to create WebGLBuffer");
  return ce(r15, () => r15.bindBuffer(r15.ELEMENT_ARRAY_BUFFER, t10)), ce(r15, () => r15.bufferData(r15.ELEMENT_ARRAY_BUFFER, e, r15.STATIC_DRAW)), t10;
}
function uZ() {
  return A().getNumber("WEBGL_VERSION") === 2 ? 1 : 4;
}
function OI(r15) {
  return hi(r15, () => r15.createTexture(), "Unable to create WebGLTexture.");
}
function MI(r15, e) {
  let t10 = A().getNumber("WEBGL_MAX_TEXTURE_SIZE");
  if (r15 <= 0 || e <= 0) {
    let o = `[${r15}x${e}]`;
    throw new Error("Requested texture size " + o + " is invalid.");
  }
  if (r15 > t10 || e > t10) {
    let o = `[${r15}x${e}]`, n = `[${t10}x${t10}]`;
    throw new Error("Requested texture size " + o + " greater than WebGL maximum on this browser / GPU " + n + ".");
  }
}
function LI(r15) {
  return hi(r15, () => r15.createFramebuffer(), "Unable to create WebGLFramebuffer.");
}
function jf(r15, e, t10, o, n, s, a) {
  let i = r15.getAttribLocation(e, t10);
  return i === -1 ? false : (ce(r15, () => r15.bindBuffer(r15.ARRAY_BUFFER, o)), ce(r15, () => r15.vertexAttribPointer(i, n, r15.FLOAT, false, s, a)), ce(r15, () => r15.enableVertexAttribArray(i)), true);
}
function NR(r15, e, t10) {
  _R(r15, t10), ce(r15, () => r15.activeTexture(r15.TEXTURE0 + t10)), ce(r15, () => r15.bindTexture(r15.TEXTURE_2D, e));
}
function pZ(r15, e) {
  _R(r15, e), ce(r15, () => r15.activeTexture(r15.TEXTURE0 + e)), ce(r15, () => r15.bindTexture(r15.TEXTURE_2D, null));
}
function BI(r15, e, t10) {
  return hi(r15, () => r15.getUniformLocation(e, t10), 'uniform "' + t10 + '" not present in program.');
}
function zI(r15, e, t10) {
  return r15.getUniformLocation(e, t10);
}
function VI(r15, e, t10, o) {
  ce(r15, () => NR(r15, e, o)), ce(r15, () => r15.uniform1i(t10, o));
}
function cZ(r15) {
  ce(r15, () => r15.bindFramebuffer(r15.FRAMEBUFFER, null)), ce(r15, () => r15.viewport(0, 0, r15.canvas.width, r15.canvas.height)), ce(r15, () => r15.scissor(0, 0, r15.canvas.width, r15.canvas.height));
}
function Ql(r15, e, t10) {
  ce(r15, () => r15.bindFramebuffer(r15.FRAMEBUFFER, t10)), ce(r15, () => r15.framebufferTexture2D(r15.FRAMEBUFFER, r15.COLOR_ATTACHMENT0, r15.TEXTURE_2D, e, 0));
}
function Xf(r15, e) {
  ce(r15, () => r15.bindFramebuffer(r15.FRAMEBUFFER, e)), ce(r15, () => r15.framebufferTexture2D(r15.FRAMEBUFFER, r15.COLOR_ATTACHMENT0, r15.TEXTURE_2D, null, 0));
}
function Tc(r15) {
  let e = r15.checkFramebufferStatus(r15.FRAMEBUFFER);
  if (e !== r15.FRAMEBUFFER_COMPLETE) throw new Error("Error binding framebuffer: " + TR(r15, e));
}
function TR(r15, e) {
  switch (e) {
    case r15.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
      return "FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
    case r15.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
      return "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
    case r15.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
      return "FRAMEBUFFER_INCOMPLETE_DIMENSIONS";
    case r15.FRAMEBUFFER_UNSUPPORTED:
      return "FRAMEBUFFER_UNSUPPORTED";
    default:
      return `unknown error ${e}`;
  }
}
function hi(r15, e, t10) {
  let o = ce(r15, () => e());
  if (o == null) throw new Error(t10);
  return o;
}
function _R(r15, e) {
  let t10 = r15.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1, o = e + r15.TEXTURE0;
  if (o < r15.TEXTURE0 || o > t10) {
    let n = `[gl.TEXTURE0, gl.TEXTURE${t10}]`;
    throw new Error(`textureUnit must be in ${n}.`);
  }
}
function gi(r15, e = 2) {
  return y.sizeFromShape(r15.slice(0, r15.length - e));
}
function xi(r15) {
  if (r15.length === 0) throw Error("Cannot get rows and columns of an empty shape array.");
  return [r15.length > 1 ? r15[r15.length - 2] : 1, r15[r15.length - 1]];
}
function _c(r15) {
  let e = [1, 1, 1];
  return r15.length === 0 || r15.length === 1 && r15[0] === 1 || (e = [gi(r15), ...xi(r15)]), e;
}
function WI(r15, e = false) {
  let t10 = A().getNumber("WEBGL_MAX_TEXTURE_SIZE"), o = A().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");
  o === 1 / 0 && A().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE") && (o = t10 / 2), e && (t10 = t10 * 2, o = o * 2, r15 = r15.map((i, p) => p >= r15.length - 2 ? y.nearestLargerEven(r15[p]) : r15[p]), r15.length === 1 && (r15 = [2, r15[0]])), r15.length !== 2 && (r15 = y.squeezeShape(r15).newShape);
  let n = y.sizeFromShape(r15), s = null;
  r15.length <= 1 && n <= t10 ? s = [1, n] : r15.length === 2 && r15[0] <= t10 && r15[1] <= t10 ? s = r15 : r15.length === 3 && r15[0] * r15[1] <= t10 && r15[2] <= t10 ? s = [r15[0] * r15[1], r15[2]] : r15.length === 3 && r15[0] <= t10 && r15[1] * r15[2] <= t10 ? s = [r15[0], r15[1] * r15[2]] : r15.length === 4 && r15[0] * r15[1] * r15[2] <= t10 && r15[3] <= t10 ? s = [r15[0] * r15[1] * r15[2], r15[3]] : r15.length === 4 && r15[0] <= t10 && r15[1] * r15[2] * r15[3] <= t10 && (s = [r15[0], r15[1] * r15[2] * r15[3]]);
  let a = s != null && Math.max(...s) > o && Math.min(...s) <= (e ? 2 : 1) && Math.min(...s) > 0;
  if (s == null || a) if (e) {
    let i = gi(r15), p = 2, u = 2;
    r15.length && ([p, u] = xi(r15)), n = i * (p / 2) * (u / 2), s = y.sizeToSquarishShape(n).map((c) => c * 2);
  } else s = y.sizeToSquarishShape(n);
  return s;
}
function Gf(r15) {
  return r15 % 2 === 0;
}
function xu(r15, e) {
  if (r15 = r15.slice(-2), e = e.slice(-2), y.arraysEqual(r15, e) || !r15.length || !e.length || r15[0] === 0 || r15[1] === 0 || e[0] === 0 || e[1] === 0) return true;
  if (r15.length !== e.length) {
    let t10 = r15[r15.length - 1], o = e[e.length - 1];
    if (t10 === o || Gf(t10) && Gf(o) && (r15[0] === 1 || e[0] === 1)) return true;
  }
  return r15[1] === e[1] && Gf(r15[0]) && Gf(e[0]);
}
var Hf;
var Kf;
function UI(r15) {
  if (Hf == null) {
    let e = Kr(r15);
    Hf = e.getParameter(e.MAX_TEXTURE_SIZE);
  }
  return Hf;
}
function lZ() {
  Hf = null;
}
function mZ() {
  Kf = null;
}
function GI(r15) {
  if (Kf == null) {
    let e = Kr(r15);
    Kf = e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS);
  }
  return Math.min(16, Kf);
}
function HI(r15) {
  if (r15 === 0) return 0;
  let e, t10 = Kr(r15);
  return qr(t10, "EXT_disjoint_timer_query_webgl2") && r15 === 2 ? e = 2 : qr(t10, "EXT_disjoint_timer_query") ? e = 1 : e = 0, e;
}
function qr(r15, e) {
  return r15.getExtension(e) != null;
}
function Yf(r15) {
  try {
    if (Kr(r15) != null) return true;
  } catch (e) {
    return console.log("Error when getting WebGL context: ", e), false;
  }
  return false;
}
function KI(r15) {
  if (r15 === 0) return false;
  let e = Kr(r15);
  if (r15 === 1) {
    if (!qr(e, "OES_texture_float")) return false;
  } else if (!qr(e, "EXT_color_buffer_float")) return false;
  return _I(e);
}
function qI(r15) {
  if (r15 === 0) return false;
  let e = Kr(r15);
  if (r15 === 1) {
    if (!qr(e, "OES_texture_float") || !qr(e, "WEBGL_color_buffer_float")) return false;
  } else {
    if (qr(e, "EXT_color_buffer_float")) return _I(e);
    let o = "EXT_color_buffer_half_float";
    if (qr(e, o)) {
      let n = e.getExtension(o);
      return dZ(e, n);
    }
    return false;
  }
  return _I(e);
}
function _I(r15) {
  let e = Xl(r15), t10 = r15.createTexture();
  r15.bindTexture(r15.TEXTURE_2D, t10), r15.texImage2D(r15.TEXTURE_2D, 0, e.internalFormatFloat, 1, 1, 0, e.textureFormatFloat, e.textureTypeFloat, null);
  let s = r15.createFramebuffer();
  r15.bindFramebuffer(r15.FRAMEBUFFER, s), r15.framebufferTexture2D(r15.FRAMEBUFFER, r15.COLOR_ATTACHMENT0, r15.TEXTURE_2D, t10, 0);
  let a = r15.checkFramebufferStatus(r15.FRAMEBUFFER) === r15.FRAMEBUFFER_COMPLETE;
  return r15.bindTexture(r15.TEXTURE_2D, null), r15.bindFramebuffer(r15.FRAMEBUFFER, null), r15.deleteTexture(t10), r15.deleteFramebuffer(s), a;
}
function dZ(r15, e) {
  let t10 = Xl(r15, e), o = r15.createTexture();
  r15.bindTexture(r15.TEXTURE_2D, o), r15.texImage2D(r15.TEXTURE_2D, 0, t10.internalFormatHalfFloat, 1, 1, 0, t10.textureFormatFloat, t10.textureTypeHalfFloat, null);
  let a = r15.createFramebuffer();
  r15.bindFramebuffer(r15.FRAMEBUFFER, a), r15.framebufferTexture2D(r15.FRAMEBUFFER, r15.COLOR_ATTACHMENT0, r15.TEXTURE_2D, o, 0);
  let i = r15.checkFramebufferStatus(r15.FRAMEBUFFER) === r15.FRAMEBUFFER_COMPLETE;
  return r15.bindTexture(r15.TEXTURE_2D, null), r15.bindFramebuffer(r15.FRAMEBUFFER, null), r15.deleteTexture(o), r15.deleteFramebuffer(a), i;
}
function jI(r15) {
  return r15 !== 2 ? false : Kr(r15).fenceSync != null;
}
function Vs(r15, e) {
  Array.isArray(r15) || (r15 = [r15]), r15.forEach((t10) => {
    t10 != null && y.assert(t10.dtype !== "complex64", () => `${e} does not support complex64 tensors in the WebGL backend.`);
  });
}
var Se = A();
Se.registerFlag("HAS_WEBGL", () => Se.getNumber("WEBGL_VERSION") > 0);
Se.registerFlag("WEBGL_VERSION", () => Yf(2) ? 2 : Yf(1) ? 1 : 0);
Se.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS", () => false);
Se.registerFlag("WEBGL_BUFFER_SUPPORTED", () => Se.get("WEBGL_VERSION") === 2);
Se.registerFlag("WEBGL_CPU_FORWARD", () => true);
Se.registerFlag("WEBGL_FORCE_F16_TEXTURES", () => false);
Se.registerFlag("WEBGL_PACK", () => Se.getBool("HAS_WEBGL"));
Se.registerFlag("WEBGL_PACK_NORMALIZATION", () => Se.getBool("WEBGL_PACK"));
Se.registerFlag("WEBGL_PACK_CLIP", () => Se.getBool("WEBGL_PACK"));
Se.registerFlag("WEBGL_PACK_DEPTHWISECONV", () => Se.getBool("WEBGL_PACK"));
Se.registerFlag("WEBGL_PACK_BINARY_OPERATIONS", () => Se.getBool("WEBGL_PACK"));
Se.registerFlag("WEBGL_PACK_UNARY_OPERATIONS", () => Se.getBool("WEBGL_PACK"));
Se.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS", () => Se.getBool("WEBGL_PACK"));
Se.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS", () => Se.getBool("WEBGL_PACK"));
Se.registerFlag("WEBGL_PACK_REDUCE", () => Se.getBool("WEBGL_PACK"));
Se.registerFlag("WEBGL_LAZILY_UNPACK", () => Se.getBool("WEBGL_PACK"));
Se.registerFlag("WEBGL_CONV_IM2COL", () => Se.getBool("WEBGL_PACK"));
Se.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE", () => Se.getBool("WEBGL_PACK"));
Se.registerFlag("WEBGL_MAX_TEXTURE_SIZE", () => UI(Se.getNumber("WEBGL_VERSION")));
Se.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER", () => GI(Se.getNumber("WEBGL_VERSION")));
Se.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION", () => {
  let r15 = Se.getNumber("WEBGL_VERSION");
  return r15 === 0 ? 0 : HI(r15);
});
Se.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE", () => Se.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") > 0 && !eu.isMobile());
Se.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE", () => KI(Se.getNumber("WEBGL_VERSION")));
Se.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED", () => Se.getBool("WEBGL_FORCE_F16_TEXTURES") ? false : Se.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));
Se.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED", () => qI(Se.getNumber("WEBGL_VERSION")));
Se.registerFlag("WEBGL_FENCE_API_ENABLED", () => jI(Se.getNumber("WEBGL_VERSION")));
Se.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM", () => Se.getBool("WEBGL_RENDER_FLOAT32_ENABLED") ? 4 : 0);
Se.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD", () => -1, (r15) => {
  if (typeof r15 != "number") throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${r15}.`);
  if (r15 < 0 && r15 !== -1) throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${r15}.`);
});
Se.registerFlag("WEBGL_FLUSH_THRESHOLD", () => eu.isMobile() ? 1 : -1, (r15) => {
  if (typeof r15 != "number") throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${r15}.`);
  if (r15 < 0 && r15 !== -1) throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${r15}.`);
});
Se.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD", () => 128);
Se.registerFlag("WEBGL_USE_SHAPES_UNIFORMS", () => false);
Se.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD", () => 1e5);
Se.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD", () => 128);
Se.registerFlag("WEBGL_EXP_CONV", () => false);
Se.registerFlag("SOFTWARE_WEBGL_ENABLED", () => Se.getBool("IS_TEST"));
Se.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE", () => 1 / 0);
Se.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE", () => false);
Se.registerFlag("WEBGL2_ISNAN_CUSTOM", () => false);
Se.registerFlag("ENGINE_COMPILE_ONLY", () => false);
function It() {
  let r15, e, t10, o, n, s, a, i, p, u;
  return A().getNumber("WEBGL_VERSION") === 2 ? (r15 = "#version 300 es", e = "in", t10 = "out", o = "in", n = "texture", s = "outputColor", a = "out vec4 outputColor;", i = A().getBool("WEBGL2_ISNAN_CUSTOM") ? `
      bool isnan_custom(float val) {
        uint floatToUint = floatBitsToUint(val);
        return (floatToUint & 0x7fffffffu) > 0x7f800000u;
      }

      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)
    ` : "", p = "", 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)));
      }
    `) : (r15 = "", e = "attribute", t10 = "varying", o = "varying", n = "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));
      }
    `, p = `
      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: r15, attribute: e, varyingVs: t10, varyingFs: o, texture2D: n, output: s, defineOutput: a, defineSpecialNaN: i, defineSpecialInf: p, defineRound: u };
}
function Ws(r15, e, t10 = "index") {
  let o = y.computeStrides(e);
  return o.map((n, s) => {
    let a = `int ${r15[s]} = ${t10} / ${n}`, i = s === o.length - 1 ? `int ${r15[s + 1]} = ${t10} - ${r15[s]} * ${n}` : `index -= ${r15[s]} * ${n}`;
    return `${a}; ${i};`;
  }).join("");
}
function xp(r15, e, t10 = "index") {
  let o = y.computeStrides(e);
  return o.map((n, s) => {
    let a = `int ${r15[s]} = ${t10} / outShapeStrides[${s}]`, i = s === o.length - 1 ? `int ${r15[s + 1]} = ${t10} - ${r15[s]} * outShapeStrides[${s}]` : `index -= ${r15[s]} * outShapeStrides[${s}]`;
    return `${a}; ${i};`;
  }).join("");
}
function fZ(r15, e) {
  let t10 = r15.length, o = r15.map((s) => `${e}[${s}]`), n = new Array(t10 - 1);
  n[t10 - 2] = o[t10 - 1];
  for (let s = t10 - 3; s >= 0; --s) n[s] = `(${n[s + 1]} * ${o[s + 1]})`;
  return n;
}
function ER(r15, e, t10 = "index") {
  let o = r15.map((s, a) => a), n = fZ(o, e);
  return n.map((s, a) => {
    let i = `int ${r15[a]} = ${t10} / ${n[a]}`, p = a === n.length - 1 ? `int ${r15[a + 1]} = ${t10} - ${r15[a]} * ${n[a]}` : `index -= ${r15[a]} * ${n[a]}`;
    return `${i}; ${p};`;
  }).join("");
}
function $c(r15) {
  let e = y.computeStrides(r15).map((t10) => t10.toString());
  return `
  int getFlatIndex(ivec3 coords) {
    return coords.x * ${e[0]} + coords.y * ${e[1]} + coords.z;
  }
`;
}
function Rc() {
  return `
  int getFlatIndex(ivec3 coords) {
    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
  }
`;
}
var Qf = `
  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: $R } = w;
function RR(r15, e, t10) {
  let o = [];
  if (r15.forEach((d) => {
    let f = y.sizeFromShape(d.shapeInfo.logicalShape);
    if (d.shapeInfo.isUniform ? o.push(`uniform float ${d.name}${f > 1 ? `[${f}]` : ""};`) : (o.push(`uniform sampler2D ${d.name};`), o.push(`uniform int offset${d.name};`)), t10.enableShapeUniforms) {
      let { uniformShape: h } = Zf(t10.packedInputs, d.shapeInfo.logicalShape, d.shapeInfo.texShape);
      switch (h.length) {
        case 1:
          o.push(`uniform int ${d.name}Shape;`);
          break;
        case 2:
          o.push(`uniform ivec2 ${d.name}Shape;`);
          break;
        case 3:
          o.push(`uniform ivec3 ${d.name}Shape;`);
          break;
        case 4:
          o.push(`uniform ivec4 ${d.name}Shape;`);
          break;
        default:
          break;
      }
      o.push(`uniform ivec2 ${d.name}TexShape;`);
    }
  }), t10.enableShapeUniforms) {
    switch (e.logicalShape.length) {
      case 1:
        o.push("uniform int outShape;");
        break;
      case 2:
        o.push("uniform ivec2 outShape;"), o.push("uniform int outShapeStrides;");
        break;
      case 3:
        o.push("uniform ivec3 outShape;"), o.push("uniform ivec2 outShapeStrides;");
        break;
      case 4:
        o.push("uniform ivec4 outShape;"), o.push("uniform ivec3 outShapeStrides;");
        break;
      default:
        break;
    }
    o.push("uniform ivec2 outTexShape;");
  }
  t10.customUniforms && t10.customUniforms.forEach((d) => {
    o.push(`uniform ${d.type} ${d.name}${d.arrayIndex ? `[${d.arrayIndex}]` : ""};`);
  });
  let n = o.join(`
`), s = r15.map((d) => hZ(d, e, t10.packedInputs, t10.enableShapeUniforms)).join(`
`), a = e.texShape, i = It(), p = yZ(i), u, c, l = wZ(i);
  return e.isPacked ? (u = gZ(e.logicalShape, a, t10.enableShapeUniforms), c = CZ(i)) : (u = xZ(e.logicalShape, a, t10.enableShapeUniforms), c = bZ(i)), t10.packedInputs && (l += kZ), [l, p, c, n, u, s, t10.userCode].join(`
`);
}
function Ac(r15, e = false) {
  let t10 = r15.shapeInfo.logicalShape;
  switch (t10.length) {
    case 0:
      return MZ(r15, e);
    case 1:
      return BZ(r15, e);
    case 2:
      return VZ(r15, e);
    case 3:
      return UZ(r15, e);
    case 4:
      return HZ(r15, e);
    case 5:
      return KZ(r15);
    case 6:
      return qZ(r15);
    default:
      throw new Error(`${t10.length}-D input sampling is not yet supported`);
  }
}
function DR(r15, e) {
  switch (r15.shapeInfo.logicalShape.length) {
    case 0:
      return OZ(r15);
    case 1:
      return LZ(r15, e);
    case 2:
      return zZ(r15, e);
    case 3:
      return WZ(r15, e);
    default:
      return GZ(r15, e);
  }
}
function hZ(r15, e, t10 = false, o) {
  let n = "";
  t10 ? n += DR(r15, o) : n += Ac(r15, o);
  let s = r15.shapeInfo.logicalShape, a = e.logicalShape;
  return s.length <= a.length && (t10 ? n += jZ(r15, e) : n += XZ(r15, e)), n;
}
function gZ(r15, e, t10) {
  switch (r15.length) {
    case 0:
      return AR();
    case 1:
      return NZ(r15, e, t10);
    case 2:
      return FZ(r15, e, t10);
    case 3:
      return _Z(r15, e, t10);
    default:
      return $Z(r15, e, t10);
  }
}
function xZ(r15, e, t10) {
  switch (r15.length) {
    case 0:
      return AR();
    case 1:
      return TZ(r15, e, t10);
    case 2:
      return PZ(r15, e, t10);
    case 3:
      return EZ(r15, e, t10);
    case 4:
      return RZ(r15, e, t10);
    case 5:
      return DZ(r15, e);
    case 6:
      return AZ(r15, e);
    default:
      throw new Error(`${r15.length}-D output sampling is not yet supported`);
  }
}
function yZ(r15) {
  return `
    float sampleTexture(sampler2D textureSampler, vec2 uv) {
      return ${r15.texture2D}(textureSampler, uv).r;
    }
  `;
}
function bZ(r15) {
  return `
    void setOutput(float val) {
      ${r15.output} = vec4(val, 0, 0, 0);
    }
  `;
}
function CZ(r15) {
  return `
    void setOutput(vec4 val) {
      ${r15.output} = val;
    }
  `;
}
function wZ(r15) {
  return `${r15.version}
    precision highp float;
    precision highp int;
    precision highp sampler2D;
    ${r15.varyingFs} vec2 resultUV;
    ${r15.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;
    ${r15.defineSpecialNaN}
    ${r15.defineSpecialInf}
    ${r15.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);
    }

    ${SZ}
    ${IZ}
    ${vZ}
  `;
}
var SZ = `
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 IZ = `
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 vZ = `
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 kZ = `
  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 AR() {
  return `
    int getOutputCoords() {
      return 0;
    }
  `;
}
function NZ(r15, e, t10) {
  let o = [Math.ceil(e[0] / 2), Math.ceil(e[1] / 2)];
  return o[0] === 1 ? t10 ? `
      int getOutputCoords() {
        return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
      }
    ` : `
      int getOutputCoords() {
        return 2 * int(resultUV.x * ${o[1]}.0);
      }
    ` : o[1] === 1 ? t10 ? `
      int getOutputCoords() {
        return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
      }
    ` : `
      int getOutputCoords() {
        return 2 * int(resultUV.y * ${o[0]}.0);
      }
    ` : t10 ? `
    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(${o[0]}, ${o[1]}));
      return 2 * (resTexRC.x * ${o[1]} + resTexRC.y);
    }
  `;
}
function TZ(r15, e, t10) {
  return e[0] === 1 ? t10 ? `
      int getOutputCoords() {
        return int(resultUV.x * float(outTexShape[1]));
      }
    ` : `
      int getOutputCoords() {
        return int(resultUV.x * ${e[1]}.0);
      }
    ` : e[1] === 1 ? t10 ? `
      int getOutputCoords() {
        return int(resultUV.y * float(outTexShape[0]));
      }
    ` : `
      int getOutputCoords() {
        return int(resultUV.y * ${e[0]}.0);
      }
    ` : t10 ? `
    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 _Z(r15, e, t10) {
  if (t10) 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 o = [Math.ceil(e[0] / 2), Math.ceil(e[1] / 2)], n = Math.ceil(r15[2] / 2), s = n * Math.ceil(r15[1] / 2);
  return `
    ivec3 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(${o[0]}, ${o[1]}));
      int index = resTexRC.x * ${o[1]} + resTexRC.y;

      int b = index / ${s};
      index -= b * ${s};

      int r = 2 * (index / ${n});
      int c = imod(index, ${n}) * 2;

      return ivec3(b, r, c);
    }
  `;
}
function EZ(r15, e, t10) {
  if (t10) return `
  ivec3 getOutputCoords() {
    ivec2 resTexRC = ivec2(resultUV.yx *
                           vec2(outTexShape[0], outTexShape[1]));
    int index = resTexRC.x * outTexShape[1] + resTexRC.y;
    ${xp(["r", "c", "d"], r15)}
    return ivec3(r, c, d);
  }
`;
  let o = Ws(["r", "c", "d"], r15);
  return `
    ivec3 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(${e[0]}, ${e[1]}));
      int index = resTexRC.x * ${e[1]} + resTexRC.y;
      ${o}
      return ivec3(r, c, d);
    }
  `;
}
function $Z(r15, e, t10) {
  if (t10) 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 o = [Math.ceil(e[0] / 2), Math.ceil(e[1] / 2)], n = Math.ceil(r15[r15.length - 1] / 2), s = n * Math.ceil(r15[r15.length - 2] / 2), a = s, i = "", p = "b, r, c";
  for (let u = 2; u < r15.length - 1; u++) a *= r15[r15.length - u - 1], i = `
      int b${u} = index / ${a};
      index -= b${u} * ${a};
    ` + i, p = `b${u}, ` + p;
  return `
    ivec${r15.length} getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(${o[0]}, ${o[1]}));
      int index = resTexRC.x * ${o[1]} + resTexRC.y;

      ${i}

      int b = index / ${s};
      index -= b * ${s};

      int r = 2 * (index / ${n});
      int c = imod(index, ${n}) * 2;

      return ivec${r15.length}(${p});
    }
  `;
}
function RZ(r15, e, t10) {
  if (t10) return `
    ivec4 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
        vec2(outTexShape[0], outTexShape[1]));
      int index = resTexRC.x * outTexShape[1] + resTexRC.y;
      ${xp(["r", "c", "d", "d2"], r15)}
      return ivec4(r, c, d, d2);
    }
  `;
  let o = Ws(["r", "c", "d", "d2"], r15);
  return `
    ivec4 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
        vec2(${e[0]}, ${e[1]}));
      int index = resTexRC.x * ${e[1]} + resTexRC.y;
      ${o}
      return ivec4(r, c, d, d2);
    }
  `;
}
function DZ(r15, e) {
  let t10 = Ws(["r", "c", "d", "d2", "d3"], r15);
  return `
    ivec5 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx * vec2(${e[0]},
                             ${e[1]}));

      int index = resTexRC.x * ${e[1]} + resTexRC.y;

      ${t10}

      ivec5 outShape = ivec5(r, c, d, d2, d3);
      return outShape;
    }
  `;
}
function AZ(r15, e) {
  let t10 = Ws(["r", "c", "d", "d2", "d3", "d4"], r15);
  return `
    ivec6 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
        vec2(${e[0]}, ${e[1]}));
      int index = resTexRC.x * ${e[1]} + resTexRC.y;

      ${t10}

      ivec6 result = ivec6(r, c, d, d2, d3, d4);
      return result;
    }
  `;
}
function FZ(r15, e, t10) {
  let o = [Math.ceil(e[0] / 2), Math.ceil(e[1] / 2)];
  if (y.arraysEqual(r15, e)) return t10 ? `
      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(${o[0]}, ${o[1]}));
      }
    `;
  let n = Math.ceil(r15[1] / 2);
  return t10 ? `
    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(${o[0]}, ${o[1]}));

      int index = resTexRC.x * ${o[1]} + resTexRC.y;
      int r = 2 * (index / ${n});
      int c = imod(index, ${n}) * 2;

      return ivec2(r, c);
    }
  `;
}
function PZ(r15, e, t10) {
  return y.arraysEqual(r15, e) ? t10 ? `
      ivec2 getOutputCoords() {
        return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
      }
    ` : `
      ivec2 getOutputCoords() {
        return ivec2(resultUV.yx * vec2(${e[0]}, ${e[1]}));
      }
    ` : r15[1] === 1 ? t10 ? `
      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);
      }
    ` : r15[0] === 1 ? t10 ? `
      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);
      }
    ` : t10 ? `
    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 / ${r15[1]};
      int c = index - r * ${r15[1]};
      return ivec2(r, c);
    }
  `;
}
function yp(r15) {
  return `offset${r15}`;
}
function OZ(r15) {
  let e = r15.name, t10 = "get" + e.charAt(0).toUpperCase() + e.slice(1), o = It();
  return `
    vec4 ${t10}() {
      return ${o.texture2D}(${e}, halfCR);
    }
  `;
}
function MZ(r15, e) {
  let t10 = r15.name, o = "get" + t10.charAt(0).toUpperCase() + t10.slice(1);
  if (r15.shapeInfo.isUniform) return `float ${o}() {return ${t10};}`;
  let [n, s] = r15.shapeInfo.texShape;
  if (n === 1 && s === 1) return `
      float ${o}() {
        return sampleTexture(${t10}, halfCR);
      }
    `;
  let a = yp(t10);
  if (e) return `
    float ${o}() {
      vec2 uv = uvFromFlat(${t10}TexShape[0], ${t10}TexShape[1], ${a});
      return sampleTexture(${t10}, uv);
    }
  `;
  let [i, p] = r15.shapeInfo.texShape;
  return `
    float ${o}() {
      vec2 uv = uvFromFlat(${i}, ${p}, ${a});
      return sampleTexture(${t10}, uv);
    }
  `;
}
function LZ(r15, e) {
  let t10 = r15.name, o = "get" + t10.charAt(0).toUpperCase() + t10.slice(1), n = r15.shapeInfo.texShape, s = It();
  if (e) return `
    vec4 ${o}(int index) {
      ivec2 packedTexShape = ivec2(ceil(float(${t10}TexShape[0]) / 2.0), ceil(float(${t10}TexShape[1]) / 2.0));
      vec2 uv = packedUVfrom1D(
        packedTexShape[0], packedTexShape[1], index);
      return ${s.texture2D}(${t10}, uv);
    }
  `;
  let a = [Math.ceil(n[0] / 2), Math.ceil(n[1] / 2)];
  return `
    vec4 ${o}(int index) {
      vec2 uv = packedUVfrom1D(
        ${a[0]}, ${a[1]}, index);
      return ${s.texture2D}(${t10}, uv);
    }
  `;
}
function BZ(r15, e) {
  let t10 = r15.name, o = "get" + t10.charAt(0).toUpperCase() + t10.slice(1);
  if (r15.shapeInfo.isUniform) return `
      float ${o}(int index) {
        ${Fc(r15)}
      }
    `;
  let n = r15.shapeInfo.texShape, s = n[0], a = n[1];
  if (a === 1 && s === 1) return `
      float ${o}(int index) {
        return sampleTexture(${t10}, halfCR);
      }
    `;
  let i = yp(t10);
  return a === 1 ? e ? `
      float ${o}(int index) {
        vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / float(${t10}TexShape[0]));
        return sampleTexture(${t10}, uv);
      }
    ` : `
      float ${o}(int index) {
        vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${s}.0);
        return sampleTexture(${t10}, uv);
      }
    ` : s === 1 ? e ? `
      float ${o}(int index) {
        vec2 uv = vec2((float(index + ${i}) + 0.5) / float(${t10}TexShape[1]), 0.5);
        return sampleTexture(${t10}, uv);
      }
    ` : `
      float ${o}(int index) {
        vec2 uv = vec2((float(index + ${i}) + 0.5) / ${a}.0, 0.5);
        return sampleTexture(${t10}, uv);
      }
    ` : e ? `
    float ${o}(int index) {
      vec2 uv = uvFromFlat(${t10}TexShape[0], ${t10}TexShape[1], index + ${i});
      return sampleTexture(${t10}, uv);
    }
  ` : `
    float ${o}(int index) {
      vec2 uv = uvFromFlat(${s}, ${a}, index + ${i});
      return sampleTexture(${t10}, uv);
    }
  `;
}
function zZ(r15, e) {
  let t10 = r15.shapeInfo.logicalShape, o = r15.name, n = "get" + o.charAt(0).toUpperCase() + o.slice(1), s = r15.shapeInfo.texShape, a = s[0], i = s[1], p = It();
  if (s != null && y.arraysEqual(t10, s)) return e ? `
      vec4 ${n}(int row, int col) {
        vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}TexShape[1], ${o}TexShape[0]);

        return ${p.texture2D}(${o}, uv);
      }
    ` : `
      vec4 ${n}(int row, int col) {
        vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${a}.0);

        return ${p.texture2D}(${o}, uv);
      }
    `;
  if (e) return `
    vec4 ${n}(int row, int col) {
      ivec2 packedTexShape = ivec2(ceil(float(${o}TexShape[0]) / 2.0), ceil(float(${o}TexShape[1]) / 2.0));
      int valuesPerRow = int(ceil(float(${o}Shape[1]) / 2.0));
      vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
      return ${p.texture2D}(${o}, uv);
    }
  `;
  let u = [Math.ceil(s[0] / 2), Math.ceil(s[1] / 2)], c = Math.ceil(t10[1] / 2);
  return `
    vec4 ${n}(int row, int col) {
      vec2 uv = packedUVfrom2D(${c}, ${u[0]}, ${u[1]}, row, col);
      return ${p.texture2D}(${o}, uv);
    }
  `;
}
function VZ(r15, e) {
  let t10 = r15.shapeInfo.logicalShape, o = r15.name, n = "get" + o.charAt(0).toUpperCase() + o.slice(1), s = r15.shapeInfo.texShape;
  if (s != null && y.arraysEqual(t10, s)) {
    if (e) return `
      float ${n}(int row, int col) {
        vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}TexShape[1], ${o}TexShape[0]);
        return sampleTexture(${o}, uv);
      }
    `;
    let m = s[0], d = s[1];
    return `
    float ${n}(int row, int col) {
      vec2 uv = (vec2(col, row) + halfCR) / vec2(${d}.0, ${m}.0);
      return sampleTexture(${o}, uv);
    }
  `;
  }
  let { newShape: a, keptDims: i } = y.squeezeShape(t10), p = a;
  if (p.length < t10.length) {
    let m = Pc(r15, p), d = ["row", "col"];
    return `
      ${Ac(m, e)}
      float ${n}(int row, int col) {
        return ${n}(${Oc(d, i)});
      }
    `;
  }
  if (r15.shapeInfo.isUniform) return `
      float ${n}(int row, int col) {
        int index = round(dot(vec2(row, col), vec2(${t10[1]}, 1)));
        ${Fc(r15)}
      }
    `;
  let u = s[0], c = s[1], l = yp(o);
  return c === 1 ? e ? `
      float ${n}(int row, int col) {
        float index = dot(vec3(row, col, ${l}), vec3(${o}Shape[1], 1, 1));
        vec2 uv = vec2(0.5, (index + 0.5) / float(${o}TexShape[0]));
        return sampleTexture(${o}, uv);
      }
    ` : `
    float ${n}(int row, int col) {
      float index = dot(vec3(row, col, ${l}), vec3(${t10[1]}, 1, 1));
      vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);
      return sampleTexture(${o}, uv);
    }
  ` : u === 1 ? e ? `
      float ${n}(int row, int col) {
        float index = dot(vec3(row, col, ${l}), vec3(${o}Shape[1], 1, 1));
        vec2 uv = vec2((index + 0.5) / float(${o}TexShape[1]), 0.5);
        return sampleTexture(${o}, uv);
      }
    ` : `
    float ${n}(int row, int col) {
      float index = dot(vec3(row, col, ${l}), vec3(${t10[1]}, 1, 1));
      vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);
      return sampleTexture(${o}, uv);
    }
  ` : e ? `
      float ${n}(int row, int col) {
        // Explicitly use integer operations as dot() only works on floats.
        int index = row * ${o}Shape[1] + col + ${l};
        vec2 uv = uvFromFlat(${o}TexShape[0], ${o}TexShape[1], index);
        return sampleTexture(${o}, uv);
      }
    ` : `
  float ${n}(int row, int col) {
    // Explicitly use integer operations as dot() only works on floats.
    int index = row * ${t10[1]} + col + ${l};
    vec2 uv = uvFromFlat(${u}, ${c}, index);
    return sampleTexture(${o}, uv);
  }
`;
}
function WZ(r15, e) {
  let t10 = r15.shapeInfo.logicalShape, o = r15.name, n = "get" + o.charAt(0).toUpperCase() + o.slice(1), s = r15.shapeInfo.texShape, a = [Math.ceil(s[0] / 2), Math.ceil(s[1] / 2)];
  if (t10[0] === 1) {
    let m = t10.slice(1), d = [1, 2], f = Pc(r15, m), h = ["b", "row", "col"];
    return `
        ${DR(f, e)}
        vec4 ${n}(int b, int row, int col) {
          return ${n}(${Oc(h, d)});
        }
      `;
  }
  let i = It();
  if (e) return `
    vec4 ${n}(int b, int row, int col) {
      ivec2 packedTexShape = ivec2(ceil(float(${o}TexShape[0]) / 2.0), ceil(float(${o}TexShape[1]) / 2.0));
      int valuesPerRow = int(ceil(float(${o}Shape[2]) / 2.0));
      int texelsInBatch = valuesPerRow * int(ceil(float(${o}Shape[1]) / 2.0));
      vec2 uv = packedUVfrom3D(
        packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
      return ${i.texture2D}(${o}, uv);
    }
  `;
  let p = a[0], u = a[1], c = Math.ceil(t10[2] / 2), l = c * Math.ceil(t10[1] / 2);
  return `
    vec4 ${n}(int b, int row, int col) {
      vec2 uv = packedUVfrom3D(
        ${p}, ${u}, ${l}, ${c}, b, row, col);
      return ${i.texture2D}(${o}, uv);
    }
  `;
}
function UZ(r15, e) {
  let t10 = r15.shapeInfo.logicalShape, o = r15.name, n = "get" + o.charAt(0).toUpperCase() + o.slice(1), s = t10[1] * t10[2], a = t10[2], { newShape: i, keptDims: p } = y.squeezeShape(t10), u = i;
  if (u.length < t10.length) {
    let h = Pc(r15, u), g = ["row", "col", "depth"];
    return `
        ${Ac(h, e)}
        float ${n}(int row, int col, int depth) {
          return ${n}(${Oc(g, p)});
        }
      `;
  }
  if (r15.shapeInfo.isUniform) return `
      float ${n}(int row, int col, int depth) {
        int index = round(dot(vec3(row, col, depth),
                          vec3(${s}, ${a}, 1)));
        ${Fc(r15)}
      }
    `;
  let c = r15.shapeInfo.texShape, l = c[0], m = c[1], d = r15.shapeInfo.flatOffset;
  if (m === s && d == null) return e ? `
      float ${n}(int row, int col, int depth) {
        int stride1 = ${o}Shape[2];
        float texR = float(row);
        float texC = dot(vec2(col, depth), vec2(stride1, 1));
        vec2 uv = (vec2(texC, texR) + halfCR) /
                   vec2(${o}TexShape[1], ${o}TexShape[0]);
        return sampleTexture(${o}, uv);
      }
    ` : `
        float ${n}(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, ${l}.0);
          return sampleTexture(${o}, uv);
        }
      `;
  if (m === a && d == null) return e ? `
      float ${n}(int row, int col, int depth) {
        float texR = dot(vec2(row, col), vec2(${o}Shape[1], 1));
        float texC = float(depth);
        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${o}TexShape[1], ${o}TexShape[0]);
        return sampleTexture(${o}, uv);
      }
    ` : `
    float ${n}(int row, int col, int depth) {
      float texR = dot(vec2(row, col), vec2(${t10[1]}, 1));
      float texC = float(depth);
      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${m}.0, ${l}.0);
      return sampleTexture(${o}, uv);
    }
  `;
  let f = yp(o);
  return e ? `
    float ${n}(int row, int col, int depth) {
      // Explicitly use integer operations as dot() only works on floats.
      int stride0 = ${o}Shape[1] * ${o}Shape[2];
      int stride1 = ${o}Shape[2];
      int index = row * stride0 + col * stride1 + depth + ${f};
      vec2 uv = uvFromFlat(${o}TexShape[0], ${o}TexShape[1], index);
      return sampleTexture(${o}, uv);
    }
    ` : `
      float ${n}(int row, int col, int depth) {
        // Explicitly use integer operations as dot() only works on floats.
        int index = row * ${s} + col * ${a} + depth + ${f};
        vec2 uv = uvFromFlat(${l}, ${m}, index);
        return sampleTexture(${o}, uv);
      }
  `;
}
function GZ(r15, e) {
  let t10 = r15.name, o = "get" + t10.charAt(0).toUpperCase() + t10.slice(1), n = It();
  if (e) return `
    vec4 ${o}(int b2, int b, int row, int col) {
      int valuesPerRow = int(ceil(float(${t10}Shape[3]) / 2.0));
      int texelsInBatch = valuesPerRow * int(ceil(float(${t10}Shape[2]) / 2.0));
      int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
      texelsInBatch *= ${t10}Shape[1];
      index = b2 * texelsInBatch + index;
      ivec2 packedTexShape = ivec2(ceil(float(${t10}TexShape[0]) / 2.0), ceil(float(${t10}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 ${n.texture2D}(${t10}, uv);
    }
  `;
  let s = r15.shapeInfo.logicalShape, a = s.length, i = r15.shapeInfo.texShape, p = [Math.ceil(i[0] / 2), Math.ceil(i[1] / 2)], u = p[0], c = p[1], l = Math.ceil(s[a - 1] / 2), m = l * Math.ceil(s[a - 2] / 2), d = "int b, int row, int col", f = `b * ${m} + (row / 2) * ${l} + (col / 2)`;
  for (let h = 2; h < a - 1; h++) d = `int b${h}, ` + d, m *= s[a - h - 1], f = `b${h} * ${m} + ` + f;
  return `
    vec4 ${o}(${d}) {
      int index = ${f};
      int texR = index / ${c};
      int texC = index - texR * ${c};
      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${u});
      return ${n.texture2D}(${t10}, uv);
    }
  `;
}
function HZ(r15, e) {
  let t10 = r15.shapeInfo.logicalShape, o = r15.name, n = "get" + o.charAt(0).toUpperCase() + o.slice(1), s = t10[3], a = t10[2] * s, i = t10[1] * a, { newShape: p, keptDims: u } = y.squeezeShape(t10);
  if (p.length < t10.length) {
    let b = Pc(r15, p), C = ["row", "col", "depth", "depth2"];
    return `
      ${Ac(b, e)}
      float ${n}(int row, int col, int depth, int depth2) {
        return ${n}(${Oc(C, u)});
      }
    `;
  }
  if (r15.shapeInfo.isUniform) return `
      float ${n}(int row, int col, int depth, int depth2) {
        int index = round(dot(vec4(row, col, depth, depth2),
                          vec4(${i}, ${a}, ${s}, 1)));
        ${Fc(r15)}
      }
    `;
  let c = r15.shapeInfo.flatOffset, l = r15.shapeInfo.texShape, m = l[0], d = l[1], f = `int stride2 = ${o}Shape[3];`, h = `int stride1 = ${o}Shape[2] * stride2;`, g = `int stride0 = ${o}Shape[1] * stride1;`;
  if (d === i && c == null) return e ? `
      float ${n}(int row, int col, int depth, int depth2) {
        ${f}
        ${h}
        float texR = float(row);
        float texC =
            dot(vec3(col, depth, depth2),
                vec3(stride1, stride2, 1));
        vec2 uv = (vec2(texC, texR) + halfCR) /
                   vec2(${o}TexShape[1], ${o}TexShape[0]);
        return sampleTexture(${o}, uv);
      }
    ` : `
      float ${n}(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(${d}.0, ${m}.0);
        return sampleTexture(${o}, uv);
      }
    `;
  if (d === s && c == null) return e ? `
      float ${n}(int row, int col, int depth, int depth2) {
        float texR = dot(vec3(row, col, depth),
                         vec3(${o}Shape[1] * ${o}Shape[2], ${o}Shape[2], 1));
        float texC = float(depth2);
        vec2 uv = (vec2(texC, texR) + halfCR) /
                  vec2(${o}TexShape[1], ${o}TexShape[0]);
        return sampleTexture(${o}, uv);
      }
    ` : `
      float ${n}(int row, int col, int depth, int depth2) {
        float texR = dot(vec3(row, col, depth),
                         vec3(${t10[1] * t10[2]}, ${t10[2]}, 1));
        float texC = float(depth2);
        vec2 uv = (vec2(texC, texR) + halfCR) /
                  vec2(${d}.0, ${m}.0);
        return sampleTexture(${o}, uv);
      }
    `;
  let x = yp(o);
  return e ? `
    float ${n}(int row, int col, int depth, int depth2) {
      // Explicitly use integer operations as dot() only works on floats.
      ${f}
      ${h}
      ${g}
      int index = row * stride0 + col * stride1 +
          depth * stride2 + depth2;
      vec2 uv = uvFromFlat(${o}TexShape[0], ${o}TexShape[1], index + ${x});
      return sampleTexture(${o}, uv);
    }
  ` : `
    float ${n}(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}, ${d}, index + ${x});
      return sampleTexture(${o}, uv);
    }
  `;
}
function KZ(r15) {
  let e = r15.shapeInfo.logicalShape, t10 = r15.name, o = "get" + t10.charAt(0).toUpperCase() + t10.slice(1), n = e[4], s = e[3] * n, a = e[2] * s, i = e[1] * a, { newShape: p, keptDims: u } = y.squeezeShape(e);
  if (p.length < e.length) {
    let h = Pc(r15, p), g = ["row", "col", "depth", "depth2", "depth3"];
    return `
      ${Ac(h)}
      float ${o}(int row, int col, int depth, int depth2, int depth3) {
        return ${o}(${Oc(g, u)});
      }
    `;
  }
  if (r15.shapeInfo.isUniform) return `
      float ${o}(int row, int col, int depth, int depth2, int depth3) {
        float index = dot(
          vec4(row, col, depth, depth2),
          vec4(${i}, ${a}, ${s}, ${n})) +
          depth3;
        ${Fc(r15)}
      }
    `;
  let c = r15.shapeInfo.flatOffset, l = r15.shapeInfo.texShape, m = l[0], d = l[1];
  if (d === i && c == null) return `
      float ${o}(int row, int col, int depth, int depth2, int depth3) {
        int texR = row;
        float texC = dot(vec4(col, depth, depth2, depth3),
                         vec4(${a}, ${s}, ${n}, 1));
        vec2 uv = (vec2(texC, texR) + halfCR) /
                   vec2(${d}.0, ${m}.0);
        return sampleTexture(${t10}, uv);
      }
    `;
  if (d === n && c == null) return `
      float ${o}(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(${d}.0, ${m}.0);
        return sampleTexture(${t10}, uv);
      }
    `;
  let f = yp(t10);
  return `
    float ${o}(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 * ${n} + depth3 + ${f};
      vec2 uv = uvFromFlat(${m}, ${d}, index);
      return sampleTexture(${t10}, uv);
    }
  `;
}
function qZ(r15) {
  let e = r15.shapeInfo.logicalShape, t10 = r15.name, o = "get" + t10.charAt(0).toUpperCase() + t10.slice(1), { newShape: n, keptDims: s } = y.squeezeShape(e);
  if (n.length < e.length) {
    let g = Pc(r15, n), x = ["row", "col", "depth", "depth2", "depth3", "depth4"];
    return `
      ${Ac(g)}
      float ${o}(int row, int col, int depth,
                    int depth2, int depth3, int depth4) {
        return ${o}(${Oc(x, s)});
      }
    `;
  }
  let a = e[5], i = e[4] * a, p = e[3] * i, u = e[2] * p, c = e[1] * u;
  if (r15.shapeInfo.isUniform) return `
      float ${o}(int row, int col, int depth,
                  int depth2, int depth3, int depth4) {
        int index = round(dot(
          vec4(row, col, depth, depth2),
          vec4(${c}, ${u}, ${p}, ${i})) +
          dot(
            vec2(depth3, depth4),
            vec2(${a}, 1)));
        ${Fc(r15)}
      }
    `;
  let l = r15.shapeInfo.flatOffset, m = r15.shapeInfo.texShape, d = m[0], f = m[1];
  if (f === c && l == null) return `
      float ${o}(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}, ${p}, ${i}, ${a})) +
               float(depth4);
        vec2 uv = (vec2(texC, texR) + halfCR) /
                   vec2(${f}.0, ${d}.0);
        return sampleTexture(${t10}, uv);
      }
    `;
  if (f === a && l == null) return `
      float ${o}(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(${f}.0, ${d}.0);
        return sampleTexture(${t10}, uv);
      }
    `;
  let h = yp(t10);
  return `
    float ${o}(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 * ${p} +
          depth2 * ${i} + depth3 * ${a} + depth4 + ${h};
      vec2 uv = uvFromFlat(${d}, ${f}, index);
      return sampleTexture(${t10}, uv);
    }
  `;
}
function Fc(r15) {
  let e = r15.name, t10 = y.sizeFromShape(r15.shapeInfo.logicalShape);
  return t10 < 2 ? `return ${e};` : `
    for (int i = 0; i < ${t10}; i++) {
      if (i == index) {
        return ${e}[i];
      }
    }
  `;
}
function jZ(r15, e) {
  let t10 = r15.name, o = t10.charAt(0).toUpperCase() + t10.slice(1), n = "get" + o + "AtOutCoords", s = r15.shapeInfo.logicalShape.length, a = e.logicalShape.length, i = $R(r15.shapeInfo.logicalShape, e.logicalShape), p = Re(a), u = a - s, c, l = ["x", "y", "z", "w", "u", "v"];
  s === 0 ? c = "" : a < 2 && i.length >= 1 ? c = "coords = 0;" : c = i.map((b) => `coords.${l[b + u]} = 0;`).join(`
`);
  let m = "";
  a < 2 && s > 0 ? m = "coords" : m = r15.shapeInfo.logicalShape.map((b, C) => `coords.${l[C + u]}`).join(", ");
  let d = "return outputValue;", h = y.sizeFromShape(r15.shapeInfo.logicalShape) === 1, x = y.sizeFromShape(e.logicalShape) === 1;
  if (s === 1 && !h && !x) d = `
      return vec4(outputValue.xy, outputValue.xy);
    `;
  else if (h && !x) a === 1 ? d = `
        return vec4(outputValue.x, outputValue.x, 0., 0.);
      ` : d = `
        return vec4(outputValue.x);
      `;
  else if (i.length) {
    let b = s - 2, C = s - 1;
    i.indexOf(b) > -1 && i.indexOf(C) > -1 ? d = "return vec4(outputValue.x);" : i.indexOf(b) > -1 ? d = "return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);" : i.indexOf(C) > -1 && (d = "return vec4(outputValue.xx, outputValue.zz);");
  }
  return `
    vec4 ${n}() {
      ${p} coords = getOutputCoords();
      ${c}
      vec4 outputValue = get${o}(${m});
      ${d}
    }
  `;
}
function XZ(r15, e) {
  let t10 = r15.name, o = t10.charAt(0).toUpperCase() + t10.slice(1), n = "get" + o + "AtOutCoords", s = e.texShape, a = r15.shapeInfo.texShape, i = r15.shapeInfo.logicalShape.length, p = e.logicalShape.length;
  if (!r15.shapeInfo.isUniform && i === p && r15.shapeInfo.flatOffset == null && y.arraysEqual(a, s)) return `
      float ${n}() {
        return sampleTexture(${t10}, resultUV);
      }
    `;
  let u = Re(p), c = $R(r15.shapeInfo.logicalShape, e.logicalShape), l = p - i, m, d = ["x", "y", "z", "w", "u", "v"];
  i === 0 ? m = "" : p < 2 && c.length >= 1 ? m = "coords = 0;" : m = c.map((h) => `coords.${d[h + l]} = 0;`).join(`
`);
  let f = "";
  return p < 2 && i > 0 ? f = "coords" : f = r15.shapeInfo.logicalShape.map((h, g) => `coords.${d[g + l]}`).join(", "), `
    float ${n}() {
      ${u} coords = getOutputCoords();
      ${m}
      return get${o}(${f});
    }
  `;
}
function Re(r15) {
  if (r15 <= 1) return "int";
  if (r15 === 2) return "ivec2";
  if (r15 === 3) return "ivec3";
  if (r15 === 4) return "ivec4";
  if (r15 === 5) return "ivec5";
  if (r15 === 6) return "ivec6";
  throw Error(`GPU for rank ${r15} is not yet supported`);
}
function Zf(r15, e, t10) {
  let { newShape: o, keptDims: n } = y.squeezeShape(e), s = e.length, a = r15 && s === 3 && e[0] === 1, i = a ? e.slice(1) : o, p = !r15 && s > 1 && !y.arraysEqual(e, t10) && o.length < s || a;
  return { useSqueezeShape: p, uniformShape: p ? i : e, keptDims: n };
}
function Pc(r15, e) {
  let t10 = JSON.parse(JSON.stringify(r15));
  return t10.shapeInfo.logicalShape = e, t10;
}
function Oc(r15, e) {
  return e.map((t10) => r15[t10]).join(", ");
}
function PR(r15, e, t10, o) {
  let n = t10.map((c, l) => {
    let m = { logicalShape: c.shape, texShape: c.isUniform ? null : c.texData.texShape, isUniform: c.isUniform, isPacked: c.isUniform ? false : c.texData.isPacked, flatOffset: null };
    return c.texData != null && c.texData.slice != null && c.texData.slice.flatOffset > 0 && (m.flatOffset = c.texData.slice.flatOffset), { name: e.variableNames[l], shapeInfo: m };
  }), s = n.map((c) => c.shapeInfo), a = { logicalShape: o.shape, texShape: o.texData.texShape, isUniform: false, isPacked: o.texData.isPacked, flatOffset: null }, i = RR(n, a, e), p = RI(r15.gl, i), u = r15.createProgram(p);
  return A().get("ENGINE_COMPILE_ONLY") ? { program: e, fragmentShader: p, source: i, webGLProgram: u, inShapeInfos: s, outShapeInfo: a, variablesLocations: null, customUniformLocations: null, infLoc: null, nanLoc: null, outShapeLocation: null, outShapeStridesLocation: null, outTexShapeLocation: null } : (r15.buildVao(u), Object.assign({ program: e, fragmentShader: p, source: i, webGLProgram: u, inShapeInfos: s, outShapeInfo: a }, XI(r15, e, u)));
}
function XI(r15, e, t10) {
  let o = [], n = [], s, a, i, p = null, u = null;
  u = r15.getUniformLocation(t10, "NAN", false), A().getNumber("WEBGL_VERSION") === 1 && (p = r15.getUniformLocation(t10, "INFINITY", false));
  let c = false;
  for (let l of e.variableNames) {
    let m = { name: l, uniform: r15.getUniformLocation(t10, l, c), offset: r15.getUniformLocation(t10, `offset${l}`, c) };
    e.enableShapeUniforms && (m.shape = r15.getUniformLocation(t10, `${l}Shape`, c), m.texShape = r15.getUniformLocation(t10, `${l}TexShape`, c)), o.push(m);
  }
  if (e.enableShapeUniforms && (s = r15.getUniformLocation(t10, "outShape", c), i = r15.getUniformLocation(t10, "outShapeStrides", c), a = r15.getUniformLocation(t10, "outTexShape", c)), e.customUniforms) for (let l of e.customUniforms) n.push(r15.getUniformLocation(t10, l.name, c));
  return { variablesLocations: o, customUniformLocations: n, infLoc: p, nanLoc: u, outShapeLocation: s, outShapeStridesLocation: i, outTexShapeLocation: a };
}
function FR(r15, e) {
  if (r15.length !== e.length) throw Error(`Binary was compiled with ${r15.length} inputs, but was executed with ${e.length} inputs`);
  r15.forEach((t10, o) => {
    let n = t10.logicalShape, s = e[o], a = s.shape;
    if (!y.arraysEqual(n, a)) throw Error(`Binary was compiled with different shapes than the current args. Shapes ${n} and ${a} must match`);
    if (t10.isUniform && s.isUniform) return;
    let i = t10.texShape, p = s.isUniform ? null : s.texData.texShape;
    if (!y.arraysEqual(i, p)) throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${p} must match`);
  });
}
function OR(r15, e, t10, o, n) {
  e.program.enableShapeUniforms || (FR(e.inShapeInfos, t10), FR([e.outShapeInfo], [o]));
  let s = o.texData.texture, a = o.texData.texShape;
  o.texData.isPacked ? r15.setOutputPackedMatrixTexture(s.texture, a[0], a[1]) : r15.setOutputMatrixTexture(s.texture, a[0], a[1]), r15.setProgram(e.webGLProgram), r15.bindVertexArray(e.webGLProgram.vao), A().getNumber("WEBGL_VERSION") === 1 && e.infLoc !== null && r15.gl.uniform1f(e.infLoc, 1 / 0), e.nanLoc !== null && r15.gl.uniform1f(e.nanLoc, NaN);
  for (let p = 0; p < t10.length; ++p) {
    let u = t10[p], { uniform: c, offset: l, shape: m, texShape: d } = e.variablesLocations[p];
    if (m) {
      let { uniformShape: f } = Zf(e.program.packedInputs, u.shape, u.texData.texShape);
      switch (f.length) {
        case 1:
          r15.gl.uniform1iv(m, new Int32Array(f));
          break;
        case 2:
          r15.gl.uniform2iv(m, new Int32Array(f));
          break;
        case 3:
          r15.gl.uniform3iv(m, new Int32Array(f));
          break;
        case 4:
          r15.gl.uniform4iv(m, new Int32Array(f));
          break;
        default:
          break;
      }
    }
    if (d && r15.gl.uniform2i(d, u.texData.texShape[0], u.texData.texShape[1]), c != null) {
      if (u.isUniform) {
        if (y.sizeFromShape(u.shape) < 2) r15.gl.uniform1f(c, u.uniformValues[0]);
        else {
          let f = u.uniformValues;
          f instanceof Float32Array || (f = new Float32Array(f)), r15.gl.uniform1fv(c, f);
        }
        continue;
      }
      u.texData.slice != null && l != null && r15.gl.uniform1i(l, u.texData.slice.flatOffset), r15.setInputMatrixTexture(u.texData.texture.texture, c, p);
    }
  }
  let i = e.outShapeLocation;
  if (i) switch (o.shape.length) {
    case 1:
      r15.gl.uniform1iv(i, new Int32Array(o.shape));
      break;
    case 2:
      r15.gl.uniform2iv(i, new Int32Array(o.shape));
      break;
    case 3:
      r15.gl.uniform3iv(i, new Int32Array(o.shape));
      break;
    case 4:
      r15.gl.uniform4iv(i, new Int32Array(o.shape));
      break;
    default:
      break;
  }
  if (e.outShapeStridesLocation) {
    let p = y.computeStrides(o.shape);
    switch (o.shape.length) {
      case 2:
        r15.gl.uniform1iv(e.outShapeStridesLocation, new Int32Array(p));
        break;
      case 3:
        r15.gl.uniform2iv(e.outShapeStridesLocation, new Int32Array(p));
        break;
      case 4:
        r15.gl.uniform3iv(e.outShapeStridesLocation, new Int32Array(p));
        break;
      default:
        break;
    }
  }
  if (e.outTexShapeLocation && r15.gl.uniform2i(e.outTexShapeLocation, o.texData.texShape[0], o.texData.texShape[1]), e.program.customUniforms && n) for (let p = 0; p < e.program.customUniforms.length; ++p) {
    let u = e.program.customUniforms[p], c = e.customUniformLocations[p], l = n[p];
    if (u.type === "float") r15.gl.uniform1fv(c, l);
    else if (u.type === "vec2") r15.gl.uniform2fv(c, l);
    else if (u.type === "vec3") r15.gl.uniform3fv(c, l);
    else if (u.type === "vec4") r15.gl.uniform4fv(c, l);
    else if (u.type === "int") r15.gl.uniform1iv(c, l);
    else if (u.type === "ivec2") r15.gl.uniform2iv(c, l);
    else if (u.type === "ivec3") r15.gl.uniform3iv(c, l);
    else if (u.type === "ivec4") r15.gl.uniform4iv(c, l);
    else throw Error(`uniform type ${u.type} is not supported yet.`);
  }
  r15.executeProgram();
}
function MR(r15, e, t10) {
  let o = "";
  e.concat(t10).forEach((a) => {
    let i = a.texData != null && a.texData.slice != null && a.texData.slice.flatOffset > 0;
    if (r15.enableShapeUniforms && !a.isUniform) {
      let p = a.texData.texShape, { useSqueezeShape: u, uniformShape: c, keptDims: l } = Zf(r15.packedInputs, a.shape, p), m = "", d = "", f = "";
      if (c.length === 1 && r15.packedInputs) {
        let k = [Math.ceil(p[0] / 2), Math.ceil(p[1] / 2)];
        m = `${k[0] > 1}_${k[1] > 1}`;
      } else if (c.length === 2 && !r15.packedInputs) d = `${c[0] > 1}_${c[1] > 1}`;
      else if (c.length > 2 && !r15.packedInputs) {
        let k = y.computeStrides(c);
        f = `${k[0] === p[1]}_${k[k.length - 1] === p[1]}`;
      }
      let h = a.shape.length, g = c.length === 2 && y.arraysEqual(a.shape, p), x = y.sizeFromShape(a.shape) === 1, b = w.getBroadcastDims(a.shape, t10.shape), C = !r15.packedInputs && h === t10.shape.length && y.arraysEqual(p, t10.texData.texShape), S = r15.packedInputs || c.length > 2 ? "" : `${p[0] > 1}_${p[1] > 1}`;
      o += `${h}_${C}_${u ? l : ""}_${c.length}_${x}_${b}_${g}_${m}_${d}_${f}_${S}_${i}`;
    } else {
      let p = a.isUniform ? "uniform" : a.texData.texShape;
      o += `${a.shape}_${p}_${i}`;
    }
  });
  let n = r15.userCode, s = r15.constructor.name;
  return s += "_" + o + "_" + n + `${A().getNumber("WEBGL_VERSION")}`, s;
}
function ut(r15) {
  return A().getBool("WEBGL_USE_SHAPES_UNIFORMS") && r15 <= 4;
}
var Jf = class {
  constructor(e) {
    this.variableNames = ["A"], this.packedInputs = false, this.packedOutput = true, this.outPackingScheme = gu.DENSE, this.customUniforms = [{ name: "texShape", type: "ivec2" }];
    let t10 = It();
    this.outputShape = e, this.enableShapeUniforms = ut(this.outputShape.length), this.userCode = `
      ivec3 outCoordsFromFlatIndex(int index) {
        ${this.enableShapeUniforms ? xp(["r", "c", "d"], e) : Ws(["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);
        }

        ${t10.output} = result;
      }
    `;
  }
};
var eh = class {
  constructor(e) {
    this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.outPackingScheme = gu.DENSE, this.customUniforms = [{ name: "texShape", type: "ivec2" }];
    let t10 = It();
    this.outputShape = e, this.enableShapeUniforms = ut(this.outputShape.length), this.userCode = `
      ivec3 outCoordsFromFlatIndex(int index) {
        ${this.enableShapeUniforms ? xp(["r", "c", "d"], e) : Ws(["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));
        }

        ${t10.output} = result;
      }
    `;
  }
};
var th = class {
  constructor(e) {
    this.variableNames = ["A"], this.outTexUsage = mr.DOWNLOAD;
    let t10 = It();
    this.outputShape = e, this.userCode = `
      ${Qf}

      void main() {
        float x = getAAtOutCoords();
        ${t10.output} = encode_float(x);
      }
    `;
  }
};
var rh = class {
  constructor(e) {
    this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = false, this.outTexUsage = mr.DOWNLOAD;
    let t10 = It();
    this.outputShape = e, this.userCode = `
      ${Qf}

      void main() {
        ivec3 coords = getOutputCoords();
        float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
        ${t10.output} = encode_float(x);
      }
    `;
  }
};
var ZZ = { R: 0, G: 1, B: 2, A: 3 };
var Zl = class {
  constructor(e, t10 = false, o = "RGBA") {
    this.variableNames = ["A"], this.customUniforms = [{ name: "texShape", type: "ivec2" }];
    let n = It();
    this.outputShape = e, this.enableShapeUniforms = ut(this.outputShape.length);
    let s = "result";
    t10 && (s = "floor(result * 255. + 0.5)");
    let a = "";
    for (let i = 0; i < o.length; i++) {
      let p = o[i];
      a += `
          if(offset == ${i}) {
            result = values[${ZZ[p]}];
          }`;
    }
    this.userCode = `
      ${this.enableShapeUniforms ? Rc() : $c(e)}

      void main() {
        ivec3 coords = getOutputCoords();
        int flatIndex = getFlatIndex(coords);
        float result = 0.;
        int offset = imod(flatIndex, ${o.length});

        flatIndex = idiv(flatIndex, ${o.length}, 1.);

        int r = flatIndex / texShape[1];
        if (r < texShape[0]) {
          int c = imod(flatIndex, texShape[1]);
          vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
          vec4 values = ${n.texture2D}(A, uv);
          ${a}
        }
        ${n.output} = vec4(${s}, 0., 0., 0.);
      }
    `;
  }
};
var oh = class {
  constructor(e, t10 = false) {
    this.variableNames = ["A"], this.packedInputs = false, this.packedOutput = true, this.customUniforms = [{ name: "texShape", type: "ivec2" }];
    let o = It();
    this.outputShape = e, this.enableShapeUniforms = ut(this.outputShape.length);
    let n = "", s = "result";
    t10 && (s = "floor(result * 255. + 0.5)");
    for (let a = 0; a <= 1; a++) for (let i = 0; i <= 1; i++) {
      let p = a * 2 + i;
      n += `
          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 = ${o.texture2D}(A, uv);

            if (offset == 0) {
              result[${p}] = values[0];
            } else if (offset == 1) {
              result[${p}] = values[1];
            } else if (offset == 2) {
              result[${p}] = values[2];
            } else {
              result[${p}] = values[3];
            }
          }
        }
        `;
    }
    this.userCode = `
        ${this.enableShapeUniforms ? Rc() : $c(e)}

        void main() {
          ivec3 coords = getOutputCoords();

          vec4 result = vec4(0.);
          int flatIndex, r, c, offset;
          ivec3 localCoords;
          vec2 uv;
          vec4 values;

          ${n}

          ${o.output} = ${s};
        }
    `;
  }
};
var mv = {};
qe(mv, { bindVertexProgramAttributeStreams: () => nv, createBufferFromOutputTexture: () => iv, createFloat16MatrixTexture: () => ev, createFloat16PackedMatrixTexture: () => ov, createFloat32MatrixTexture: () => JI, createIndexBuffer: () => ZI, createPackedMatrixTexture: () => rv, createUnsignedBytesMatrixTexture: () => tv, createVertexBuffer: () => QI, createVertexShader: () => YI, downloadByteEncodedFloatMatrixFromOutputTexture: () => pv, downloadFloat32MatrixFromBuffer: () => uv, downloadMatrixFromPackedOutputTexture: () => lv, downloadPackedMatrixFromBuffer: () => cv, getInternalFormatForFloat16MatrixTexture: () => sh, getInternalFormatForFloat16PackedMatrixTexture: () => uh, getInternalFormatForFloat32MatrixTexture: () => nh, getInternalFormatForPackedMatrixTexture: () => ih, getInternalFormatForUnsignedBytesMatrixTexture: () => ah, uploadDenseMatrixToTexture: () => sv, uploadPixelDataToTexture: () => av });
function YI(r15) {
  let e = It(), t10 = `${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 $I(r15, t10);
}
function QI(r15) {
  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 FI(r15, e);
}
function ZI(r15) {
  let e = new Uint16Array([0, 1, 2, 2, 1, 3]);
  return PI(r15, e);
}
function Jl(r15, e, t10, o, n, s) {
  MI(e, t10);
  let a = OI(r15), i = r15.TEXTURE_2D;
  return ce(r15, () => r15.bindTexture(i, a)), ce(r15, () => r15.texParameteri(i, r15.TEXTURE_WRAP_S, r15.CLAMP_TO_EDGE)), ce(r15, () => r15.texParameteri(i, r15.TEXTURE_WRAP_T, r15.CLAMP_TO_EDGE)), ce(r15, () => r15.texParameteri(i, r15.TEXTURE_MIN_FILTER, r15.NEAREST)), ce(r15, () => r15.texParameteri(i, r15.TEXTURE_MAG_FILTER, r15.NEAREST)), A().getNumber("WEBGL_VERSION") === 1 ? ce(r15, () => r15.texImage2D(i, 0, o, e, t10, 0, n, s, null)) : ce(r15, () => r15.texStorage2D(i, 1, o, e, t10)), ce(r15, () => r15.bindTexture(r15.TEXTURE_2D, null)), { texture: a, texShape: [t10, e] };
}
function nh(r15) {
  return r15.internalFormatFloat;
}
function JI(r15, e, t10, o) {
  let [n, s] = gp(e, t10);
  return Jl(r15, n, s, nh(o), o.textureFormatFloat, r15.FLOAT);
}
function sh(r15) {
  return r15.internalFormatHalfFloat;
}
function ev(r15, e, t10, o) {
  let [n, s] = gp(e, t10);
  return Jl(r15, n, s, sh(o), o.textureFormatFloat, o.textureTypeHalfFloat);
}
function ah(r15) {
  return r15.downloadTextureFormat;
}
function tv(r15, e, t10, o) {
  let [n, s] = gp(e, t10);
  return Jl(r15, n, s, ah(o), r15.RGBA, r15.UNSIGNED_BYTE);
}
function ih(r15) {
  return r15.internalFormatPackedFloat;
}
function rv(r15, e, t10, o) {
  let [n, s] = Ma(e, t10);
  return Jl(r15, n, s, ih(o), r15.RGBA, r15.FLOAT);
}
function uh(r15) {
  return r15.internalFormatPackedHalfFloat;
}
function ov(r15, e, t10, o) {
  let [n, s] = Ma(e, t10);
  return Jl(r15, n, s, uh(o), r15.RGBA, o.textureTypeHalfFloat);
}
function nv(r15, e, t10) {
  return ce(r15, () => r15.bindBuffer(r15.ARRAY_BUFFER, t10)), jf(r15, e, "clipSpacePos", t10, 3, 20, 0) && jf(r15, e, "uv", t10, 2, 20, 12);
}
function sv(r15, e, t10, o, n, s) {
  ce(r15, () => r15.bindTexture(r15.TEXTURE_2D, e));
  let a, i, p;
  n instanceof Uint8Array ? (a = new Uint8Array(t10 * o * 4), i = r15.UNSIGNED_BYTE, p = r15.RGBA) : (a = new Float32Array(t10 * o * 4), i = r15.FLOAT, p = s.internalFormatPackedFloat), a.set(n), A().getNumber("WEBGL_VERSION") === 2 ? ce(r15, () => r15.texSubImage2D(r15.TEXTURE_2D, 0, 0, 0, t10, o, r15.RGBA, i, a)) : ce(r15, () => r15.texImage2D(r15.TEXTURE_2D, 0, p, t10, o, 0, r15.RGBA, i, a)), ce(r15, () => r15.bindTexture(r15.TEXTURE_2D, null));
}
function av(r15, e, t10) {
  ce(r15, () => r15.bindTexture(r15.TEXTURE_2D, e)), t10.data instanceof Uint8Array ? A().getNumber("WEBGL_VERSION") === 2 ? ce(r15, () => r15.texSubImage2D(r15.TEXTURE_2D, 0, 0, 0, t10.width, t10.height, r15.RGBA, r15.UNSIGNED_BYTE, t10.data)) : ce(r15, () => r15.texImage2D(r15.TEXTURE_2D, 0, r15.RGBA, t10.width, t10.height, 0, r15.RGBA, r15.UNSIGNED_BYTE, t10.data)) : A().getNumber("WEBGL_VERSION") === 2 ? ce(r15, () => r15.texSubImage2D(r15.TEXTURE_2D, 0, 0, 0, r15.RGBA, r15.UNSIGNED_BYTE, t10)) : ce(r15, () => r15.texImage2D(r15.TEXTURE_2D, 0, r15.RGBA, r15.RGBA, r15.UNSIGNED_BYTE, t10)), ce(r15, () => r15.bindTexture(r15.TEXTURE_2D, null));
}
function iv(r15, e, t10, o) {
  let n = r15.createBuffer();
  ce(r15, () => r15.bindBuffer(r15.PIXEL_PACK_BUFFER, n));
  let i = 4 * 4 * e * t10;
  return ce(r15, () => r15.bufferData(r15.PIXEL_PACK_BUFFER, i, r15.STREAM_READ)), ce(r15, () => r15.readPixels(0, 0, t10, e, r15.RGBA, r15.FLOAT, 0)), ce(r15, () => r15.bindBuffer(r15.PIXEL_PACK_BUFFER, null)), n;
}
function uv(r15, e, t10) {
  let o = r15, n = new Float32Array(t10);
  return o.bindBuffer(o.PIXEL_PACK_BUFFER, e), o.getBufferSubData(o.PIXEL_PACK_BUFFER, 0, n), o.bindBuffer(o.PIXEL_PACK_BUFFER, null), n;
}
function pv(r15, e, t10, o) {
  let [n, s] = gp(e, t10), a = 4, i = new Uint8Array(IR(e * t10, a));
  return ce(r15, () => r15.readPixels(0, 0, n, s, o.downloadTextureFormat, r15.UNSIGNED_BYTE, i)), new Float32Array(i.buffer);
}
function cv(r15, e, t10, o, n, s, a, i) {
  let p = r15, u = new Float32Array(vR(s, a));
  return p.bindBuffer(p.PIXEL_PACK_BUFFER, e), p.getBufferSubData(p.PIXEL_PACK_BUFFER, 0, u), p.bindBuffer(p.PIXEL_PACK_BUFFER, null), u;
}
function lv(r15, e, t10) {
  let o = new Float32Array(e * t10 * 4);
  return ce(r15, () => r15.readPixels(0, 0, t10, e, r15.RGBA, r15.FLOAT, o)), o;
}
var bp = class {
  constructor(e) {
    this.outputTexture = null, this.program = null, this.disposed = false, this.itemsToPoll = [];
    let t10 = A().getNumber("WEBGL_VERSION");
    if (e != null ? (this.gl = e, NI(t10, e)) : this.gl = Kr(t10), e = this.gl, A().getNumber("WEBGL_VERSION") === 2) {
      let s = e;
      this.createVertexArray = () => ce(s, () => s.createVertexArray()), this.bindVertexArray = (a) => ce(s, () => s.bindVertexArray(a)), this.deleteVertexArray = (a) => ce(s, () => s.deleteVertexArray(a)), this.getVertexArray = () => ce(s, () => s.getParameter(s.VERTEX_ARRAY_BINDING));
    } else if (e != null) {
      let s = e.getExtension("OES_vertex_array_object");
      if (s == null) throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");
      this.createVertexArray = () => ce(e, () => s.createVertexArrayOES()), this.bindVertexArray = (a) => ce(e, () => s.bindVertexArrayOES(a)), this.deleteVertexArray = (a) => ce(e, () => s.deleteVertexArrayOES(a)), this.getVertexArray = () => ce(e, () => e.getParameter(s.VERTEX_ARRAY_BINDING_OES));
    }
    let o = "WEBGL_color_buffer_float", n = "EXT_color_buffer_half_float";
    if (this.parallelCompilationExtension = this.gl.getExtension("KHR_parallel_shader_compile"), A().getNumber("WEBGL_VERSION") === 1) {
      let s = "OES_texture_float", a = "OES_texture_half_float";
      if (this.textureFloatExtension = Nc(this.gl, s), qr(this.gl, a)) this.textureHalfFloatExtension = Nc(this.gl, a);
      else if (A().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(o), qr(this.gl, n)) this.colorBufferHalfFloatExtension = Nc(this.gl, n);
      else if (A().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 (o = "EXT_color_buffer_float", qr(this.gl, o)) this.colorBufferFloatExtension = this.gl.getExtension(o);
    else if (qr(this.gl, n)) this.colorBufferHalfFloatExtension = this.gl.getExtension(n);
    else throw new Error("GL context does not support color renderable floats");
    this.vertexBuffer = QI(this.gl), this.indexBuffer = ZI(this.gl), this.framebuffer = LI(this.gl), this.textureConfig = Xl(this.gl, this.textureHalfFloatExtension);
  }
  get debug() {
    return A().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;
    ce(e, () => e.finish()), ce(e, () => e.bindFramebuffer(e.FRAMEBUFFER, null)), ce(e, () => e.deleteFramebuffer(this.framebuffer)), ce(e, () => e.bindBuffer(e.ARRAY_BUFFER, null)), ce(e, () => e.bindBuffer(e.ELEMENT_ARRAY_BUFFER, null)), ce(e, () => e.deleteBuffer(this.indexBuffer)), this.disposed = true;
  }
  createFloat32MatrixTexture(e, t10) {
    return this.throwIfDisposed(), JI(this.gl, e, t10, this.textureConfig);
  }
  createFloat16MatrixTexture(e, t10) {
    return this.throwIfDisposed(), ev(this.gl, e, t10, this.textureConfig);
  }
  createUnsignedBytesMatrixTexture(e, t10) {
    return this.throwIfDisposed(), tv(this.gl, e, t10, this.textureConfig);
  }
  uploadPixelDataToTexture(e, t10) {
    this.throwIfDisposed(), av(this.gl, e, t10);
  }
  uploadDenseMatrixToTexture(e, t10, o, n) {
    this.throwIfDisposed(), sv(this.gl, e, t10, o, n, this.textureConfig);
  }
  createFloat16PackedMatrixTexture(e, t10) {
    return this.throwIfDisposed(), ov(this.gl, e, t10, this.textureConfig);
  }
  createPackedMatrixTexture(e, t10) {
    return this.throwIfDisposed(), rv(this.gl, e, t10, this.textureConfig);
  }
  deleteMatrixTexture(e) {
    this.throwIfDisposed(), this.outputTexture === e && (Xf(this.gl, this.framebuffer), this.outputTexture = null), ce(this.gl, () => this.gl.deleteTexture(e));
  }
  downloadByteEncodedFloatMatrixFromOutputTexture(e, t10, o) {
    return this.downloadMatrixDriver(e, () => pv(this.gl, t10, o, this.textureConfig));
  }
  downloadPackedMatrixFromBuffer(e, t10, o, n, s, a) {
    return cv(this.gl, e, t10, o, n, s, a, this.textureConfig);
  }
  downloadFloat32MatrixFromBuffer(e, t10) {
    return uv(this.gl, e, t10);
  }
  createBufferFromTexture(e, t10, o) {
    this.bindTextureToFrameBuffer(e);
    let n = iv(this.gl, t10, o, this.textureConfig);
    return this.unbindTextureToFrameBuffer(), n;
  }
  createAndWaitForFence() {
    let e = this.createFence(this.gl);
    return this.pollFence(e);
  }
  createFence(e) {
    let t10, o;
    if (A().getBool("WEBGL_FENCE_API_ENABLED")) {
      let n = e, s = n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE, 0);
      e.flush(), o = () => {
        let a = n.clientWaitSync(s, 0, 0);
        return a === n.ALREADY_SIGNALED || a === n.CONDITION_SATISFIED;
      }, t10 = s;
    } else A().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") > 0 ? (t10 = this.beginQuery(), this.endQuery(), o = () => this.isQueryAvailable(t10, A().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))) : o = () => true;
    return { query: t10, isFencePassed: o };
  }
  downloadMatrixFromPackedTexture(e, t10, o) {
    return this.downloadMatrixDriver(e, () => lv(this.gl, t10, o));
  }
  createProgram(e) {
    this.throwIfDisposed();
    let t10 = this.gl;
    this.vertexShader == null && (this.vertexShader = YI(t10));
    let o = DI(t10);
    ce(t10, () => t10.attachShader(o, this.vertexShader)), ce(t10, () => t10.attachShader(o, e)), AI(t10, o);
    let n = Object.assign(o, { vao: this.createVertexArray() });
    return this.debug && Yl(t10, n), n;
  }
  buildVao(e) {
    this.setProgram(e), this.bindVertexArray(e.vao);
    let t10 = this.gl;
    ce(t10, () => t10.bindBuffer(t10.ELEMENT_ARRAY_BUFFER, this.indexBuffer)), nv(t10, e, this.vertexBuffer);
  }
  deleteProgram(e) {
    this.throwIfDisposed(), e === this.program && (this.program = null), e != null && (ce(this.gl, () => this.gl.deleteProgram(e)), this.deleteVertexArray(e.vao));
  }
  setProgram(e) {
    this.throwIfDisposed(), this.program = e, this.program != null && this.debug && Yl(this.gl, this.program), ce(this.gl, () => this.gl.useProgram(e));
  }
  getUniformLocation(e, t10, o = true) {
    return this.throwIfDisposed(), o ? BI(this.gl, e, t10) : zI(this.gl, e, t10);
  }
  getAttributeLocation(e, t10) {
    return this.throwIfDisposed(), ce(this.gl, () => this.gl.getAttribLocation(e, t10));
  }
  getUniformLocationNoThrow(e, t10) {
    return this.throwIfDisposed(), this.gl.getUniformLocation(e, t10);
  }
  setInputMatrixTexture(e, t10, o) {
    this.throwIfDisposed(), this.throwIfNoProgram(), VI(this.gl, e, t10, o);
  }
  setOutputMatrixTexture(e, t10, o) {
    this.setOutputMatrixTextureDriver(e, o, t10);
  }
  setOutputPackedMatrixTexture(e, t10, o) {
    this.throwIfDisposed();
    let [n, s] = Ma(t10, o);
    this.setOutputMatrixTextureDriver(e, n, s);
  }
  setOutputMatrixWriteRegion(e, t10, o, n) {
    this.setOutputMatrixWriteRegionDriver(o, e, n, t10);
  }
  setOutputPackedMatrixWriteRegion(e, t10, o, n) {
    throw new Error("setOutputPackedMatrixWriteRegion not implemented.");
  }
  debugValidate() {
    this.program != null && Yl(this.gl, this.program), Tc(this.gl);
  }
  executeProgram() {
    this.throwIfDisposed(), this.throwIfNoProgram();
    let e = this.gl;
    if (this.debug) {
      let t10 = this.getVertexArray();
      console.assert(t10 === this.program.vao, "VAO changed between setProgram and executeProgram!"), this.debugValidate();
    }
    ce(e, () => e.drawElements(e.TRIANGLES, 6, e.UNSIGNED_SHORT, 0));
  }
  blockUntilAllProgramsCompleted() {
    this.throwIfDisposed(), ce(this.gl, () => this.gl.finish());
  }
  getQueryTimerExtension() {
    return this.disjointQueryTimerExtension == null && (this.disjointQueryTimerExtension = Nc(this.gl, A().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 (A().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2) {
      let o = this.gl, n = this.getQueryTimerExtensionWebGL2(), s = o.createQuery();
      return o.beginQuery(n.TIME_ELAPSED_EXT, s), s;
    }
    let e = this.getQueryTimerExtensionWebGL1(), t10 = e.createQueryEXT();
    return e.beginQueryEXT(e.TIME_ELAPSED_EXT, t10), t10;
  }
  endQuery() {
    if (A().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION") === 2) {
      let t10 = this.gl, o = this.getQueryTimerExtensionWebGL2();
      t10.endQuery(o.TIME_ELAPSED_EXT);
      return;
    }
    let e = this.getQueryTimerExtensionWebGL1();
    e.endQueryEXT(e.TIME_ELAPSED_EXT);
  }
  async waitForQueryAndGetTime(e) {
    return await y.repeatedTry(() => this.disposed || this.isQueryAvailable(e, A().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))), this.getQueryTime(e, A().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"));
  }
  getQueryTime(e, t10) {
    if (t10 === 0) return null;
    if (t10 === 2) {
      let o = this.gl;
      return o.getQueryParameter(e, o.QUERY_RESULT) / 1e6;
    } else {
      let o = this.getQueryTimerExtensionWebGL1();
      return o.getQueryObjectEXT(e, o.QUERY_RESULT_EXT) / 1e6;
    }
  }
  isQueryAvailable(e, t10) {
    if (t10 === 0) return true;
    if (t10 === 2) {
      let o = this.gl, n = this.getQueryTimerExtensionWebGL2(), s = o.getQueryParameter(e, o.QUERY_RESULT_AVAILABLE);
      return this.disjoint == null && (this.disjoint = this.gl.getParameter(n.GPU_DISJOINT_EXT)), s && !this.disjoint;
    } else {
      let o = this.getQueryTimerExtensionWebGL1(), n = o.getQueryObjectEXT(e, o.QUERY_RESULT_AVAILABLE_EXT);
      return this.disjoint == null && (this.disjoint = this.gl.getParameter(o.GPU_DISJOINT_EXT)), n && !this.disjoint;
    }
  }
  pollFence(e) {
    return new Promise((t10) => {
      this.addItemToPoll(() => e.isFencePassed(), () => t10());
    });
  }
  pollItems() {
    let e = JZ(this.itemsToPoll.map((t10) => t10.isDoneFn));
    for (let t10 = 0; t10 <= e; ++t10) {
      let { resolveFn: o } = this.itemsToPoll[t10];
      o();
    }
    this.itemsToPoll = this.itemsToPoll.slice(e + 1);
  }
  addItemToPoll(e, t10) {
    if (this.itemsToPoll.push({ isDoneFn: e, resolveFn: t10 }), this.itemsToPoll.length > 1) return;
    let o;
    "setTimeoutCustom" in A().platform && (o = A().platform.setTimeoutCustom.bind(A().platform)), y.repeatedTry(() => (this.pollItems(), this.itemsToPoll.length === 0), () => 0, null, o);
  }
  bindTextureToFrameBuffer(e) {
    this.throwIfDisposed(), Ql(this.gl, e, this.framebuffer), this.debug && Tc(this.gl);
  }
  unbindTextureToFrameBuffer() {
    this.outputTexture != null ? (Ql(this.gl, this.outputTexture, this.framebuffer), this.debug && Tc(this.gl)) : Xf(this.gl, this.framebuffer);
  }
  downloadMatrixDriver(e, t10) {
    this.bindTextureToFrameBuffer(e);
    let o = t10();
    return this.unbindTextureToFrameBuffer(), o;
  }
  setOutputMatrixTextureDriver(e, t10, o) {
    this.throwIfDisposed();
    let n = this.gl;
    Ql(n, e, this.framebuffer), this.debug && Tc(n), this.outputTexture = e, ce(n, () => n.viewport(0, 0, t10, o)), ce(n, () => n.scissor(0, 0, t10, o));
  }
  setOutputMatrixWriteRegionDriver(e, t10, o, n) {
    this.throwIfDisposed(), ce(this.gl, () => this.gl.scissor(e, t10, o, n));
  }
  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 JZ(r15) {
  let e = 0;
  for (; e < r15.length && r15[e](); ++e) ;
  return e - 1;
}
var { addImpl: LR, bincountImpl: ph, bincountReduceImpl: BR, bitwiseAndImpl: zR, castImpl: VR, ceilImpl: WR, concatImpl: UR, equalImpl: GR, expImpl: HR, expm1Impl: KR, floorImpl: qR, gatherNdImpl: jR, gatherV2Impl: XR, greaterImpl: YR, greaterEqualImpl: QR, lessImpl: ZR, lessEqualImpl: JR, linSpaceImpl: eD, logImpl: tD, maxImpl: rD, maximumImpl: oD, minimumImpl: nD, multiplyImpl: sD, negImpl: aD, notEqualImpl: iD, prodImpl: uD, raggedGatherImpl: pD, raggedRangeImpl: cD, raggedTensorToTensorImpl: lD, rangeImpl: mD, rsqrtImpl: dD, scatterImpl: fD, sigmoidImpl: hD, simpleAbsImpl: ch, sliceImpl: gD, sparseFillEmptyRowsImpl: xD, sparseReshapeImpl: yD, sparseSegmentReductionImpl: lh, sqrtImpl: bD, staticRegexReplaceImpl: CD, stridedSliceImpl: wD, stringNGramsImpl: SD, stringSplitImpl: ID, stringToHashBucketFastImpl: vD, subImpl: kD, tileImpl: ND, topKImpl: TD, transposeImpl: Cp, uniqueImpl: _D } = Ic;
function dv(r15, e) {
  return ["x", "y", "z", "w", "u", "v"].slice(0, e).map((t10) => `${r15}.${t10}`);
}
function Rt(r15, e) {
  return e === 1 ? [r15] : dv(r15, e);
}
function ED(r15, e) {
  if (r15 === 1) return "rc";
  let t10 = "";
  for (let o = 0; o < r15; o++) t10 += e[o], o < r15 - 1 && (t10 += ",");
  return t10;
}
var mh = class {
  constructor(e) {
    if (this.variableNames = ["A"], this.packedInputs = false, this.packedOutput = true, this.outputShape = e, this.rank = e.length, this.enableShapeUniforms = ut(this.outputShape.length), this.rank === 0) this.userCode = `
        void main() {
          setOutput(vec4(getA(), 0., 0., 0.));
        }
      `;
    else {
      let t10 = Rt("rc", this.rank), o = Re(this.rank), n = this.getOutOfBoundsCondition(t10), s = this.getSetup(t10), a = this.getOutput(t10);
      this.userCode = `
        void main() {
          ${o} rc = getOutputCoords();

          if(${n}) {
            setOutput(vec4(0));
          } else {
            ${s}

            setOutput(vec4(${a}));
          }
        }
      `;
    }
  }
  getSourceCoordsArr(e) {
    let t10 = [];
    for (let o = 0; o <= 1; o++) for (let n = 0; n <= 1; n++) {
      let s = `${o === 0 ? "r" : "rp1"}, ${n === 0 ? "c" : "cp1"}`;
      for (let a = 2; a < this.rank; a++) s = `${e[e.length - 1 - a]},` + s;
      t10.push(s);
    }
    return t10;
  }
  getOutOfBoundsCondition(e) {
    if (this.rank === 1) return `rc > ${this.enableShapeUniforms ? "outShape" : this.outputShape[0]}`;
    let t10 = "";
    for (let o = this.rank - 2; o < this.rank; o++) t10 += `${e[o]} >= ${this.enableShapeUniforms ? `outShape[${o}]` : this.outputShape[o]}`, o < this.rank - 1 && (t10 += "||");
    return t10;
  }
  getSetup(e) {
    if (this.rank === 1) return "";
    let t10 = e.slice(-2), o = this.enableShapeUniforms ? `outShape[${this.rank} - 1]` : this.outputShape[this.rank - 1], n = this.enableShapeUniforms ? `outShape[${this.rank} - 2]` : this.outputShape[this.rank - 2];
    return `
      int r = ${t10[0]};
      int c = ${t10[1]};
      int rp1 = r + 1;
      int cp1 = c + 1;

      bool cEdge = cp1 >= ${o};
      bool rEdge = rp1 >= ${n};
    `;
  }
  getOutput(e) {
    let t10 = this.getSourceCoordsArr(e);
    return this.rank === 1 ? `getA(rc), (rc + 1 >= ${this.enableShapeUniforms ? "outShape" : this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0` : `getA(${t10[0]}),
            cEdge ? 0. : getA(${t10[1]}),
            rEdge ? 0. : getA(${t10[2]}),
            rEdge || cEdge ? 0. : getA(${t10[3]})`;
  }
};
var Mc = class {
  constructor(e, t10) {
    this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "inputShape", type: "ivec3" }], this.outputShape = e, this.enableShapeUniforms = ut(this.outputShape.length);
    let o = "";
    for (let n = 0; n < 4; n++) {
      let s = "thisRC = rc;";
      n % 2 === 1 && (s += "thisRC.z += 1;"), n > 1 && (s += "thisRC.y += 1;"), o += `
        ${s}
        ${n > 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[${n}] =
            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
        ${n > 0 ? "}" : ""}
      `;
    }
    this.userCode = `
      ${e9(t10, this.enableShapeUniforms)}
      ${this.enableShapeUniforms ? Rc() : $c(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]};

        ${o}

        setOutput(result);
      }
    `;
  }
};
function e9(r15, e) {
  return `
    ivec3 inputCoordsFromReshapedOutCoords(int index) {
      ${e ? ER(["r", "c", "d"], "inputShape") : Ws(["r", "c", "d"], r15)}
      return ivec3(r, c, d);
    }
  `;
}
var dh = class {
  constructor(e) {
    this.gpgpu = e, this.numUsedTextures = 0, this.numFreeTextures = 0, this._numBytesAllocated = 0, this._numBytesFree = 0, this.freeTextures = {}, this.usedTextures = {}, this.logEnabled = false;
  }
  acquireTexture(e, t10, o) {
    let n = RD(t10, o), s = DD(e, n, o);
    s in this.freeTextures || (this.freeTextures[s] = []), s in this.usedTextures || (this.usedTextures[s] = []);
    let a = $D(e, n, this.gpgpu.gl, this.gpgpu.textureConfig, o);
    if (this.freeTextures[s].length > 0) {
      this.numFreeTextures--, this.numUsedTextures++, this._numBytesFree -= a, this.log();
      let p = this.freeTextures[s].pop();
      return this.usedTextures[s].push(p), p;
    }
    let i;
    return n === er.PACKED_2X2_FLOAT32 ? i = this.gpgpu.createPackedMatrixTexture(e[0], e[1]) : n === er.PACKED_2X2_FLOAT16 ? i = this.gpgpu.createFloat16PackedMatrixTexture(e[0], e[1]) : n === er.UNPACKED_FLOAT32 ? i = this.gpgpu.createFloat32MatrixTexture(e[0], e[1]) : n === er.UNPACKED_FLOAT16 ? i = this.gpgpu.createFloat16MatrixTexture(e[0], e[1]) : n === er.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, t10, o, n) {
    if (this.freeTextures == null) return;
    let s = RD(o, n), a = DD(t10, s, n);
    a in this.freeTextures || (this.freeTextures[a] = []);
    let i = $D(t10, s, this.gpgpu.gl, this.gpgpu.textureConfig, n), p = A().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");
    p !== -1 && this._numBytesAllocated > p ? (this.gpgpu.deleteMatrixTexture(e.texture), this._numBytesAllocated -= i) : (this.freeTextures[a].push(e), this.numFreeTextures++, this._numBytesFree += i), this.numUsedTextures--;
    let u = this.usedTextures[a], c = u && u.indexOf(e);
    if (c == null || c < 0) throw new Error("Cannot release a texture that was never provided by this texture manager");
    u[c] = u[u.length - 1], u.pop(), this.log();
  }
  log() {
    if (!this.logEnabled) return;
    let e = this.numFreeTextures + this.numUsedTextures;
    console.log("Free/Used", `${this.numFreeTextures} / ${this.numUsedTextures}`, `(${e})`);
    let t10 = this._numBytesFree / this._numBytesAllocated;
    console.log(`Bytes allocated: ${this._numBytesAllocated}`), console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100 * t10)}%)`);
  }
  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((t10) => {
        this.gpgpu.deleteMatrixTexture(t10.texture);
      });
      for (let e in this.usedTextures) this.usedTextures[e].forEach((t10) => {
        this.gpgpu.deleteMatrixTexture(t10.texture);
      });
      this.freeTextures = null, this.usedTextures = null, this.numUsedTextures = 0, this.numFreeTextures = 0, this._numBytesAllocated = 0, this._numBytesFree = 0;
    }
  }
};
function t9(r15, e) {
  let t10 = r15;
  if (e === t10.R32F) return 4;
  if (e === t10.R16F) return 2;
  if (e === t10.RGBA32F) return 16;
  if (e === r15.RGBA) return 16;
  if (e === t10.RGBA16F) return 8;
  if (e === t10.RGBA8) return 4;
  throw new Error(`Unknown internal format ${e}`);
}
function $D(r15, e, t10, o, n) {
  let s = r92(e, o), a;
  if (n) {
    let [p, u] = Ma(r15[0], r15[1]);
    a = p * u;
  } else {
    let [p, u] = gp(r15[0], r15[1]);
    a = p * u;
  }
  let i = t9(t10, s);
  return a * i;
}
function r92(r15, e) {
  switch (r15) {
    case er.PACKED_2X2_FLOAT32:
      return ih(e);
    case er.PACKED_2X2_FLOAT16:
      return uh(e);
    case er.UNPACKED_FLOAT32:
      return nh(e);
    case er.UNPACKED_FLOAT16:
      return sh(e);
    case er.PACKED_4X1_UNSIGNED_BYTE:
      return ah(e);
    default:
      throw new Error(`Unknown physical texture type ${r15}`);
  }
}
function o9(r15) {
  return A().getBool("WEBGL_RENDER_FLOAT32_ENABLED") ? r15 ? er.PACKED_2X2_FLOAT32 : er.UNPACKED_FLOAT32 : r15 ? er.PACKED_2X2_FLOAT16 : er.UNPACKED_FLOAT16;
}
function RD(r15, e) {
  if (r15 === mr.UPLOAD) return er.PACKED_2X2_FLOAT32;
  if (r15 === mr.RENDER || r15 == null) return o9(e);
  if (r15 === mr.DOWNLOAD || r15 === mr.PIXELS) return er.PACKED_4X1_UNSIGNED_BYTE;
  throw new Error(`Unknown logical texture type ${r15}`);
}
function DD(r15, e, t10) {
  return `${r15[0]}_${r15[1]}_${e}_${t10}`;
}
var tr = class {
  constructor(e, t10) {
    this.variableNames = ["A"], this.outputShape = e, this.enableShapeUniforms = ut(this.outputShape.length), this.userCode = `
      float unaryOperation(float x) {
        ${t10}
      }

      void main() {
        float x = getAAtOutCoords();
        float y = unaryOperation(x);

        setOutput(y);
      }
    `;
  }
};
var Wt = "if (isnan(x)) return x;";
var AD = "return x;";
var fv = "return abs(x);";
var FD = "return (x >= 0.0) ? x : (exp(x) - 1.0);";
var PD = Wt + `
  return (x < 0.0) ? 0.0 : x;
`;
var OD = Wt + `
  return (x < 0.0) ? 0.0 : min(6.0, x);
`;
var La = "return x;";
var MD = "return 1.0 / (1.0 + exp(-1.0 * x));";
var BD = "return x;";
var zD = `
  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 VD = `
  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 WD = `
  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 UD = "return 1.0 / (1.0 + exp(-1.0 * x));";
var Fr = class {
  constructor(e, t10) {
    this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.outputShape = e, this.enableShapeUniforms = ut(this.outputShape.length), this.userCode = `
      vec4 unaryOperation(vec4 x) {
        ${t10}
      }

      void main() {
        vec4 x = getAAtOutCoords();
        vec4 y = unaryOperation(x);

        setOutput(y);
      }
    `;
  }
};
var fh = class {
  constructor(e) {
    this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = false, this.outputShape = e, this.enableShapeUniforms = ut(this.outputShape.length);
    let t10 = e.length, o = Rt("rc", t10), n = Re(t10), s = ED(t10, o), a = o.slice(-2), i = t10 <= 1 ? "rc" : `vec2(${a.join(",")})`;
    this.userCode = `
      void main() {
        ${n} rc = getOutputCoords();
        vec4 packedInput = getA(${s});

        setOutput(getChannel(packedInput, ${i}));
      }
    `;
  }
};
var s9 = Vt.whereImpl;
var a9 = 1e-7;
var i9 = 1e-4;
var hh = {};
function u9(r15) {
  return r15 in hh || (hh[r15] = {}), hh[r15];
}
var p9 = A().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");
var c9 = 600;
function l9() {
  return A().global.screen == null ? 1024 : A().global.screen.height * A().global.screen.width * window.devicePixelRatio * c9 / 1024 / 1024;
}
var Lc = class r13 extends ao {
  nextDataId() {
    return r13.nextDataId++;
  }
  constructor(e) {
    if (super(), this.pendingRead = /* @__PURE__ */ new WeakMap(), this.pendingDisposal = /* @__PURE__ */ new WeakSet(), this.dataRefCount = /* @__PURE__ */ new WeakMap(), this.numBytesInGPU = 0, this.uploadWaitMs = 0, this.downloadWaitMs = 0, this.lastGlFlushTime = 0, this.warnedAboutMemory = false, this.pendingDeletes = 0, this.disposed = false, !A().getBool("HAS_WEBGL")) throw new Error("WebGL is not supported on this device");
    let t10;
    if (e != null) {
      if (e instanceof bp) t10 = e;
      else {
        let o = Kr(A().getNumber("WEBGL_VERSION"), e);
        t10 = new bp(o);
      }
      this.binaryCache = {}, this.gpgpuCreatedLocally = false;
    } else {
      let o = Kr(A().getNumber("WEBGL_VERSION"));
      t10 = new bp(o), this.binaryCache = u9(A().getNumber("WEBGL_VERSION")), this.gpgpuCreatedLocally = true;
    }
    this.gpgpu = t10, this.canvas = this.gpgpu.gl.canvas, this.textureManager = new dh(this.gpgpu), this.numMBBeforeWarning = l9(), this.texData = new Bo(this, ur());
  }
  numDataIds() {
    return this.texData.numDataIds() - this.pendingDeletes;
  }
  writeTexture(e, t10, o, n, s, a) {
    let i = this.makeTensorInfo(t10, o), p = this.texData.get(i.dataId);
    p.isPacked = false, p.texture = { texture: e, texShape: [n, s] }, p.texShape = [n, s];
    let u = _c(t10), c = new Zl(u, false, a), l = this.runWebGLProgram(c, [i], o, [[n, s]]);
    return l.shape = t10, p.texture = null, this.disposeIntermediateTensorInfo(i), l.dataId;
  }
  write(e, t10, o) {
    if ((A().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS") || A().getBool("DEBUG")) && this.checkNumericalProblems(e), o === "complex64" && e != null) throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
    let n = { id: this.nextDataId() };
    return this.texData.set(n, { shape: t10, dtype: o, values: e, usage: mr.UPLOAD, refCount: 1 }), n;
  }
  refCount(e) {
    return this.texData.has(e) ? this.texData.get(e).refCount : 0;
  }
  incRef(e) {
    let t10 = this.texData.get(e);
    t10.refCount++;
  }
  decRef(e) {
    if (this.texData.has(e)) {
      let t10 = this.texData.get(e);
      t10.refCount--;
    }
  }
  move(e, t10, o, n, s) {
    if (A().getBool("DEBUG") && this.checkNumericalProblems(t10), n === "complex64") throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
    this.texData.set(e, { shape: o, dtype: n, values: t10, usage: mr.UPLOAD, refCount: s });
  }
  disposeIntermediateTensorInfo(e) {
    this.disposeData(e.dataId);
  }
  readSync(e) {
    let t10 = this.texData.get(e), { values: o, dtype: n, complexTensorInfos: s, slice: a, shape: i, isPacked: p } = t10;
    if (a != null) {
      let m;
      p ? m = new Fr(i, La) : m = new tr(i, La);
      let d = this.runWebGLProgram(m, [{ dataId: e, shape: i, dtype: n }], n), f = this.readSync(d.dataId);
      return this.disposeIntermediateTensorInfo(d), f;
    }
    if (o != null) return this.convertAndCacheOnCPU(e);
    if (n === "string") return o;
    let u = this.activeTimers != null, c;
    u && (c = y.now());
    let l;
    if (n === "complex64") {
      let m = this.readSync(s.real.dataId), d = this.readSync(s.imag.dataId);
      l = w.mergeRealAndImagArrays(m, d);
    } else l = this.getValuesFromTexture(e);
    return u && (this.downloadWaitMs += y.now() - c), this.convertAndCacheOnCPU(e, l);
  }
  async read(e) {
    if (this.pendingRead.has(e)) {
      let f = this.pendingRead.get(e);
      return new Promise((h) => f.push(h));
    }
    let t10 = this.texData.get(e), { values: o, shape: n, slice: s, dtype: a, complexTensorInfos: i, isPacked: p } = t10;
    if (s != null) {
      let f;
      p ? f = new Fr(n, La) : f = new tr(n, La);
      let h = this.runWebGLProgram(f, [{ dataId: e, shape: n, dtype: a }], a), g = this.read(h.dataId);
      return this.disposeIntermediateTensorInfo(h), g;
    }
    if (o != null) return this.convertAndCacheOnCPU(e);
    if (A().getBool("DEBUG") && !A().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED") && A().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" && A().get("WEBGL_BUFFER_SUPPORTED")) {
      c = this.decode(e);
      let f = this.texData.get(c.dataId);
      u = this.gpgpu.createBufferFromTexture(f.texture.texture, ...jl(n));
    }
    this.pendingRead.set(e, []), a !== "complex64" && await this.gpgpu.createAndWaitForFence();
    let l;
    if (a === "complex64") {
      let f = await Promise.all([this.read(i.real.dataId), this.read(i.imag.dataId)]), h = f[0], g = f[1];
      l = w.mergeRealAndImagArrays(h, g);
    } else if (u == null) l = this.getValuesFromTexture(e);
    else {
      let f = y.sizeFromShape(n);
      l = this.gpgpu.downloadFloat32MatrixFromBuffer(u, f);
    }
    if (c != null && this.disposeIntermediateTensorInfo(c), u != null) {
      let f = this.gpgpu.gl;
      ce(f, () => f.deleteBuffer(u));
    }
    let m = this.convertAndCacheOnCPU(e, l), d = this.pendingRead.get(e);
    return this.pendingRead.delete(e), d.forEach((f) => f(m)), this.pendingDisposal.has(e) && (this.pendingDisposal.delete(e), this.disposeData(e) && ur().removeDataId(e, this), this.pendingDeletes--), m;
  }
  readToGPU(e, t10 = {}) {
    let o = this.texData.get(e), { values: n, shape: s, slice: a, dtype: i, isPacked: p, texture: u } = o;
    if (i === "complex64") throw new Error("Does not support reading texture for complex64 dtype.");
    if (a != null) {
      let d;
      p ? d = new Fr(s, La) : d = new tr(s, La);
      let f = this.runWebGLProgram(d, [{ dataId: e, shape: s, dtype: i }], i), h = this.readToGPU(f, t10);
      return this.disposeIntermediateTensorInfo(f), h;
    }
    if (u == null) throw n != null ? new Error("Data is not on GPU but on CPU.") : new Error("There is no data on GPU or CPU.");
    let c = this.decode(e, t10.customTexShape), l = ur().makeTensorFromTensorInfo(c), m = this.texData.get(c.dataId);
    return Object.assign({ tensorRef: l }, m.texture);
  }
  bufferSync(e) {
    let t10 = this.readSync(e.dataId);
    if (e.dtype === "string") try {
      let o = t10.map((n) => y.decodeString(n));
      return me(e.shape, e.dtype, o);
    } catch (o) {
      throw new Error("Failed to decode encoded string bytes into utf-8");
    }
    return me(e.shape, e.dtype, t10);
  }
  checkNumericalProblems(e) {
    if (e != null) for (let t10 = 0; t10 < e.length; t10++) {
      let o = e[t10];
      if (!EI(o)) throw A().getBool("WEBGL_RENDER_FLOAT32_CAPABLE") ? Error(`The value ${o} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`) : Error(`The value ${o} cannot be represented on this device.`);
    }
  }
  getValuesFromTexture(e) {
    let { shape: t10, dtype: o, isPacked: n } = this.texData.get(e), s = y.sizeFromShape(t10);
    if (A().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")) {
      let m = this.decode(e), d = this.texData.get(m.dataId), f = this.gpgpu.downloadMatrixFromPackedTexture(d.texture.texture, ...jl(t10)).subarray(0, s);
      return this.disposeIntermediateTensorInfo(m), f;
    }
    let a = A().getBool("WEBGL_PACK") && n === true, i = a ? _c(t10) : t10, p = a ? new rh(i) : new th(i), u = this.runWebGLProgram(p, [{ shape: i, dtype: o, dataId: e }], "float32"), c = this.texData.get(u.dataId), l = this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(c.texture.texture, c.texShape[0], c.texShape[1]).subarray(0, s);
    return this.disposeIntermediateTensorInfo(u), l;
  }
  timerAvailable() {
    return A().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0;
  }
  time(e) {
    let t10 = this.activeTimers, o = [], n = false;
    this.programTimersStack == null ? (this.programTimersStack = o, n = true) : this.activeTimers.push(o), this.activeTimers = o, e();
    let s = y.flatten(this.activeTimers.map((p) => p.query)).filter((p) => p != null), a = y.flatten(this.activeTimers.map((p) => p.name)).filter((p) => p != null);
    this.activeTimers = t10, n && (this.programTimersStack = null);
    let i = { uploadWaitMs: this.uploadWaitMs, downloadWaitMs: this.downloadWaitMs, kernelMs: null, wallMs: null };
    return (async () => {
      if (A().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0) {
        let p = await Promise.all(s);
        i.kernelMs = y.sum(p), i.getExtraProfileInfo = () => p.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 A().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0 ? this.gpgpu.beginQuery() : { startMs: y.now(), endMs: null };
  }
  endTimer(e) {
    return A().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0 ? (this.gpgpu.endQuery(), e) : (e.endMs = y.now(), e);
  }
  async getQueryTime(e) {
    if (A().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE") > 0) return this.gpgpu.waitForQueryAndGetTime(e);
    let t10 = e;
    return t10.endMs - t10.startMs;
  }
  disposeData(e, t10 = false) {
    if (this.pendingDisposal.has(e)) return false;
    if (!this.texData.has(e)) return true;
    if (t10 ? this.texData.get(e).refCount = 0 : this.texData.get(e).refCount--, !t10 && 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: o } = this.texData.get(e);
    return o != null && (this.disposeData(o.real.dataId, t10), this.disposeData(o.imag.dataId, t10)), this.texData.delete(e), true;
  }
  releaseGPUData(e) {
    let { texture: t10, dtype: o, texShape: n, usage: s, isPacked: a, slice: i } = this.texData.get(e), p = i && i.origDataId || e, u = this.dataRefCount.get(p);
    u > 1 ? this.dataRefCount.set(p, u - 1) : (this.dataRefCount.delete(p), t10 != null && (this.numBytesInGPU -= this.computeBytes(n, o), this.textureManager.releaseTexture(t10, n, 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.texture;
  }
  getDataInfo(e) {
    return this.texData.get(e);
  }
  shouldExecuteOnCPU(e, t10 = p9) {
    return A().getBool("WEBGL_CPU_FORWARD") && e.every((o) => this.texData.get(o.dataId).texture == null && y.sizeFromShape(o.shape) < t10);
  }
  getGPGPUContext() {
    return this.gpgpu;
  }
  where(e) {
    w.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");
    let t10 = e.dataSync();
    return s9(e.shape, t10);
  }
  packedUnaryOp(e, t10, o) {
    let n = new Fr(e.shape, t10), s = this.compileAndRun(n, [e], o);
    return ur().makeTensorFromTensorInfo(s);
  }
  abs(e) {
    if (this.shouldExecuteOnCPU([e]) && e.dtype !== "complex64") {
      let n = ch(this.texData.get(e.dataId).values);
      return this.makeOutput(e.shape, e.dtype, n);
    }
    if (A().getBool("WEBGL_PACK_UNARY_OPERATIONS")) return this.packedUnaryOp(e, fv, e.dtype);
    let t10 = new tr(e.shape, fv), o = this.compileAndRun(t10, [e]);
    return ur().makeTensorFromTensorInfo(o);
  }
  makeTensorInfo(e, t10, o) {
    let n;
    if (t10 === "string" && o != null && o.length > 0 && y.isString(o[0])) {
      let s = o.map((a) => y.encodeString(a));
      n = this.write(s, e, t10);
    } else n = this.write(o, e, t10);
    return this.texData.get(n).usage = null, { dataId: n, shape: e, dtype: t10 };
  }
  makeOutput(e, t10, o) {
    return ur().makeTensorFromTensorInfo(this.makeTensorInfo(e, t10, o), this);
  }
  unpackTensor(e) {
    let t10 = new fh(e.shape);
    return this.runWebGLProgram(t10, [e], e.dtype);
  }
  packTensor(e) {
    let t10 = new mh(e.shape);
    return this.runWebGLProgram(t10, [e], e.dtype, null, true);
  }
  packedReshape(e, t10) {
    let o = [gi(e.shape), ...xi(e.shape)], n = { dtype: e.dtype, shape: o, dataId: e.dataId }, s = [gi(t10), ...xi(t10)], a = new Mc(s, o), i = true, p = [o], u = this.runWebGLProgram(a, [n], e.dtype, p, i);
    return { dataId: u.dataId, shape: t10, dtype: u.dtype };
  }
  decode(e, t10) {
    let o = this.texData.get(e), { isPacked: n, shape: s, dtype: a } = o;
    if (t10 != null) {
      let m = y.sizeFromShape(s), d = t10[0] * t10[1] * 4;
      y.assert(m <= d, () => "customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.");
    }
    let i = _c(s), p;
    n ? p = new eh(i) : p = new Jf(i);
    let u = true, c = [t10 != null ? t10 : jl(i)], l = this.runWebGLProgram(p, [{ shape: i, dtype: a, dataId: e }], a, c, u, t10);
    return { dtype: a, shape: s, dataId: l.dataId };
  }
  runWebGLProgram(e, t10, o, n, s = false, a) {
    let i = this.makeTensorInfo(e.outputShape, o), p = this.texData.get(i.dataId);
    if (e.packedOutput && (p.isPacked = true), e.outPackingScheme === gu.DENSE) {
      let x = a != null ? a : jl(e.outputShape);
      p.texShape = x.map((b) => b * 2);
    }
    if (e.outTexUsage != null && (p.usage = e.outTexUsage), y.sizeFromShape(i.shape) === 0) return p.values = y.getTypedArrayFromDType(i.dtype, 0), i;
    let u = [], c = t10.map((x) => {
      if (x.dtype === "complex64") throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");
      let b = this.texData.get(x.dataId);
      if (b.texture == null) {
        if (!e.packedInputs && y.sizeFromShape(x.shape) <= A().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM")) return { shape: x.shape, texData: null, isUniform: true, uniformValues: b.values };
        e.packedInputs && (b.isPacked = true, b.shape = x.shape);
      }
      if (this.uploadToGPU(x.dataId), !!b.isPacked != !!e.packedInputs) x = b.isPacked ? this.unpackTensor(x) : this.packTensor(x), u.push(x), b = this.texData.get(x.dataId);
      else if (b.isPacked && !xu(b.shape, x.shape)) {
        let C = x, S = x.shape;
        x.shape = b.shape, x = this.packedReshape(x, S), u.push(x), b = this.texData.get(x.dataId), C.shape = S;
      }
      return { shape: x.shape, texData: b, isUniform: false };
    });
    this.uploadToGPU(i.dataId);
    let l = { shape: i.shape, texData: p, isUniform: false }, m = MR(e, c, l), d = this.getAndSaveBinary(m, () => PR(this.gpgpu, e, c, l)), f = this.activeTimers != null, h;
    f && (h = this.startTimer()), A().get("ENGINE_COMPILE_ONLY") || OR(this.gpgpu, d, c, l, n), u.forEach((x) => this.disposeIntermediateTensorInfo(x)), f && (h = this.endTimer(h), this.activeTimers.push({ name: e.constructor.name, query: this.getQueryTime(h) }));
    let g = A().getNumber("WEBGL_FLUSH_THRESHOLD");
    if (g > 0) {
      let x = y.now();
      x - this.lastGlFlushTime > g && (this.gpgpu.gl.flush(), this.lastGlFlushTime = x);
    }
    if (!A().getBool("WEBGL_LAZILY_UNPACK") && p.isPacked && s === false) {
      let x = this.unpackTensor(i);
      return this.disposeIntermediateTensorInfo(i), x;
    }
    return i;
  }
  compileAndRun(e, t10, o, n, s = false) {
    return o = o || t10[0].dtype, this.runWebGLProgram(e, t10, o, n, s);
  }
  getAndSaveBinary(e, t10) {
    return e in this.binaryCache || (this.binaryCache[e] = t10()), this.binaryCache[e];
  }
  getTextureManager() {
    return this.textureManager;
  }
  dispose() {
    this.disposed || (A().getBool("IS_TEST") || Object.keys(this.binaryCache).forEach((t10) => {
      this.gpgpu.deleteProgram(this.binaryCache[t10].webGLProgram), delete this.binaryCache[t10];
    }), 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 = De(() => {
      if (!A().get("WEBGL_RENDER_FLOAT32_ENABLED")) {
        let e = A().getBool("DEBUG");
        A().set("DEBUG", false);
        let t10 = this.abs(ke(1e-8)).dataSync()[0];
        if (A().set("DEBUG", e), t10 > 0) return 32;
      }
      return 16;
    })), this.floatPrecisionValue;
  }
  epsilon() {
    return this.floatPrecision() === 32 ? a9 : i9;
  }
  uploadToGPU(e) {
    let t10 = this.texData.get(e), { shape: o, dtype: n, values: s, texture: a, usage: i, isPacked: p } = t10;
    if (a != null) return;
    let u = this.activeTimers != null, c;
    u && (c = y.now());
    let l = t10.texShape;
    if (l == null && (l = WI(o, p), t10.texShape = l), s != null) {
      let m = _c(o), d, f = l[1], h = l[0], g = s instanceof Uint8Array || s instanceof Uint8ClampedArray;
      (p || !g) && ([f, h] = Ma(l[0], l[1])), p ? d = new oh(m, g) : d = new Zl(m, g);
      let x = g ? [h, f] : l, b = this.makeTensorInfo(x, n), C = this.texData.get(b.dataId);
      g ? C.usage = mr.PIXELS : C.usage = mr.UPLOAD, C.texShape = x, this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(b.dataId), f, h, s);
      let S = [[h, f]], _ = this.runWebGLProgram(d, [b], n, S, true), $ = this.texData.get(_.dataId);
      t10.texShape = $.texShape, t10.isPacked = $.isPacked, t10.usage = $.usage, A().get("ENGINE_COMPILE_ONLY") ? this.disposeData(_.dataId) : (t10.texture = $.texture, t10.values = null, this.texData.delete(_.dataId)), this.disposeIntermediateTensorInfo(b), u && (this.uploadWaitMs += y.now() - c);
    } else {
      let m = this.acquireTexture(l, i, n, p);
      t10.texture = m;
    }
  }
  convertAndCacheOnCPU(e, t10) {
    let o = this.texData.get(e), { dtype: n } = o;
    return t10 != null && (o.values = m9(t10, n)), o.values;
  }
  acquireTexture(e, t10, o, n) {
    if (this.numBytesInGPU += this.computeBytes(e, o), !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, t10, n);
  }
  computeBytes(e, t10) {
    return e[0] * e[1] * y.bytesPerElement(t10);
  }
  checkCompileCompletion() {
    for (let [, e] of Object.entries(this.binaryCache)) this.checkCompletion_(e);
  }
  async checkCompileCompletionAsync() {
    let e = [];
    if (this.gpgpu.parallelCompilationExtension) {
      for (let [, t10] of Object.entries(this.binaryCache)) e.push(this.checkCompletionAsync_(t10));
      return Promise.all(e);
    } else {
      for (let [, t10] of Object.entries(this.binaryCache)) {
        let o = new Promise((n) => {
          try {
            this.checkCompletion_(t10), n(true);
          } catch (s) {
            throw s;
          }
        });
        e.push(o);
      }
      return Promise.all(e);
    }
  }
  async checkCompletionAsync_(e) {
    return this.gpgpu.gl.getProgramParameter(e.webGLProgram, this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR) ? this.checkCompletion_(e) : (await cS(), this.checkCompletionAsync_(e));
  }
  checkCompletion_(e) {
    if (this.gpgpu.gl.getProgramParameter(e.webGLProgram, this.gpgpu.gl.LINK_STATUS) === false) throw console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)), this.gpgpu.gl.getShaderParameter(e.fragmentShader, this.gpgpu.gl.COMPILE_STATUS) === false ? (qf(e.source, this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)), new Error("Failed to compile fragment shader.")) : new Error("Failed to link vertex and fragment shaders.");
    return true;
  }
  getUniformLocations() {
    for (let e of Object.values(this.binaryCache)) {
      this.gpgpu.buildVao(e.webGLProgram);
      let { variablesLocations: t10, customUniformLocations: o, infLoc: n, nanLoc: s, outShapeLocation: a, outShapeStridesLocation: i, outTexShapeLocation: p } = XI(this.gpgpu, e.program, e.webGLProgram);
      e.variablesLocations = t10, e.customUniformLocations = o, e.infLoc = n, e.nanLoc = s, e.outShapeLocation = a, e.outShapeStridesLocation = i, e.outTexShapeLocation = p;
    }
  }
  createTensorFromGPUData(e, t10, o) {
    e.channels = e.channels || "RGBA";
    let { texture: n, height: s, width: a, channels: i } = e, p = ur().backend;
    if (!p.gpgpu.gl.isTexture(n)) throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");
    let u = p.writeTexture(n, t10, o, s, a, i);
    return ur().makeTensorFromDataId(u, t10, o, p);
  }
};
Lc.nextDataId = 0;
function m9(r15, e) {
  if (e === "float32" || e === "complex64") return r15;
  if (e === "int32" || e === "bool") {
    let t10 = e === "int32" ? new Int32Array(r15.length) : new Uint8Array(r15.length);
    for (let o = 0; o < t10.length; ++o) t10[o] = Math.round(r15[o]);
    return t10;
  } else throw new Error(`Unknown dtype ${e}`);
}
var d9 = "4.22.0";
function GD() {
  A().set("WEBGL_FORCE_F16_TEXTURES", true);
}
eu.isBrowser() && tu("webgl", () => new Lc(), 2);
var $at = { forceHalfFloat: GD };
var Bc = `
  if (isnan(a)) return a;
  if (isnan(b)) return b;
`;
var Pr = class {
  constructor(e, t10, o) {
    this.variableNames = ["A", "B"], this.outputShape = w.assertAndGetBroadcastShape(t10, o), this.enableShapeUniforms = ut(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 Xr = `
  result.r = isNaN.r ? NAN : result.r;
  result.g = isNaN.g ? NAN : result.g;
  result.b = isNaN.b ? NAN : result.b;
  result.a = isNaN.a ? NAN : result.a;
`;
var jr = class {
  constructor(e, t10, o, n = false) {
    this.variableNames = ["A", "B"], this.supportsBroadcasting = true, this.packedInputs = true, this.packedOutput = true, this.outputShape = w.assertAndGetBroadcastShape(t10, o);
    let s = this.outputShape.length;
    this.enableShapeUniforms = ut(s);
    let a = "";
    if (n) if (s === 0 || y.sizeFromShape(this.outputShape) === 1) a = `
          result.y = 0.;
          result.z = 0.;
          result.w = 0.;
        `;
    else if (a = `
          ${Re(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 p = Rt("coords", s);
      this.enableShapeUniforms ? a += `
            bool nextRowOutOfBounds =
              (${p[s - 2]} + 1) >= outShape[${s} - 2];
            bool nextColOutOfBounds =
              (${p[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 =
              (${p[s - 2]} + 1) >= ${this.outputShape[s - 2]};
            bool nextColOutOfBounds =
              (${p[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 Dt(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e;
  return t10.incRef(o.dataId), { dataId: o.dataId, shape: o.shape, dtype: o.dtype };
}
var HD = { kernelName: Co, backendName: "webgl", kernelFunc: Dt };
function Or(r15) {
  let { inputs: e, backend: t10 } = r15, { real: o, imag: n } = e, s = t10.makeTensorInfo(o.shape, "complex64"), a = t10.texData.get(s.dataId), i = Dt({ inputs: { x: o }, backend: t10 }), p = Dt({ inputs: { x: n }, backend: t10 });
  return a.complexTensorInfos = { real: i, imag: p }, s;
}
var KD = { kernelName: Di, backendName: "webgl", kernelFunc: Or };
var hv = "return (a < 0.) ? b * a : a;";
var gv = `
  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;
function f9(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { alpha: s } = o, a = t10.makeTensorInfo([], "float32", y.createScalarValue(s, "float32")), i = A().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new jr(gv, n.shape, a.shape) : new Pr(hv, n.shape, a.shape), p = t10.runWebGLProgram(i, [n, a], "float32");
  return t10.disposeIntermediateTensorInfo(a), p;
}
var qD = { kernelName: $n, backendName: "webgl", kernelFunc: f9 };
var xv = "return (a < 0.) ? b * a : a;";
var yv = `
  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;
function h9(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o, alpha: n } = e, s = A().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new jr(yv, o.shape, n.shape) : new Pr(xv, o.shape, n.shape);
  return t10.runWebGLProgram(s, [o, n], "float32");
}
var jD = { kernelName: rs, backendName: "webgl", kernelFunc: h9 };
var Fo = "if (isnan(x)) return x;";
function xe({ opSnippet: r15, packedOpSnippet: e, cpuKernelImpl: t10, dtype: o }) {
  return ({ inputs: n, backend: s }) => {
    let { x: a } = n, i = s, p = o || a.dtype;
    if (i.shouldExecuteOnCPU([a]) && t10 != null) {
      let l = i.texData.get(a.dataId), m = t10(l.values, p);
      return i.makeTensorInfo(a.shape, p, m);
    }
    let u = A().getBool("WEBGL_PACK_UNARY_OPERATIONS") && e != null, c;
    return u ? c = new Fr(a.shape, e) : c = new tr(a.shape, r15), i.runWebGLProgram(c, [a], p);
  };
}
function nt({ opSnippet: r15, packedOpSnippet: e, checkOutOfBounds: t10 = false, supportsComplex: o = false, cpuKernelImpl: n, dtype: s }) {
  return ({ inputs: a, backend: i }) => {
    let { a: p, b: u } = a, c = i;
    if (o && p.dtype === "complex64") {
      let f = c.texData.get(p.dataId), h = c.texData.get(u.dataId), [g, x] = [[f.complexTensorInfos.real, h.complexTensorInfos.real], [f.complexTensorInfos.imag, h.complexTensorInfos.imag]].map((C) => {
        let [S, k] = C, _ = { dataId: S.dataId, dtype: S.dtype, shape: p.shape }, $ = { dataId: k.dataId, dtype: k.dtype, shape: u.shape }, R = new Pr(r15, p.shape, u.shape);
        return c.runWebGLProgram(R, [_, $], dt(S.dtype, k.dtype));
      }), b = Or({ inputs: { real: g, imag: x }, backend: c });
      return c.disposeIntermediateTensorInfo(g), c.disposeIntermediateTensorInfo(x), b;
    }
    let l = s || dt(p.dtype, u.dtype);
    if ((p.dtype === "string" || u.dtype === "string" || c.shouldExecuteOnCPU([p, u])) && n != null) {
      let f = c.texData.get(p.dataId).values, h = c.texData.get(u.dataId).values, g = p.dtype === "string" ? w.fromUint8ToStringArray(f) : f, x = p.dtype === "string" ? w.fromUint8ToStringArray(h) : h, [b, C] = n(p.shape, u.shape, g, x, l), S = c.makeTensorInfo(C, l), k = c.texData.get(S.dataId);
      return k.values = b, S;
    }
    let m = A().getBool("WEBGL_PACK_BINARY_OPERATIONS") && e != null, d;
    return m ? d = new jr(e, p.shape, u.shape, t10) : d = new Pr(r15, p.shape, u.shape), c.runWebGLProgram(d, [p, u], l);
  };
}
function yi(r15, e = false) {
  if (r15 === "linear") return e ? BD : AD;
  if (r15 === "relu") return e ? VD : PD;
  if (r15 === "elu") return e ? zD : FD;
  if (r15 === "relu6") return e ? WD : OD;
  if (r15 === "prelu") return e ? yv : xv;
  if (r15 === "leakyrelu") return e ? gv : hv;
  if (r15 === "sigmoid") return e ? UD : MD;
  throw new Error(`Activation ${r15} has not been implemented for the WebGL backend.`);
}
var zc = class {
  constructor(e, t10, o, n = false, s = false, a = false, i = null, p = false, u = false) {
    this.variableNames = ["matrixA", "matrixB"], this.packedInputs = true, this.packedOutput = true, this.outputShape = o, this.enableShapeUniforms = ut(this.outputShape.length);
    let c = n ? e[1] : e[2], l = Math.ceil(c / 2), m = n ? "i * 2, rc.y" : "rc.y, i * 2", d = s ? "rc.z, i * 2" : "i * 2, rc.z", f = n ? ["a.xxyy", "a.zzww"] : ["a.xxzz", "a.yyww"], h = s ? ["b.xzxz", "b.ywyw"] : ["b.xyxy", "b.zwzw"], g = "", x = "";
    i && (p ? 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 b = a ? "result += getBiasAtOutCoords();" : "";
    a && this.variableNames.push("bias"), p && this.variableNames.push("preluActivationWeights"), u && this.variableNames.push("leakyreluAlpha");
    let C = "rc.x", S = "rc.x";
    e[0] < t10[0] ? C = `imod(rc.x, ${e[0]})` : t10[0] < e[0] && (S = `imod(rc.x, ${t10[0]})`), this.userCode = `
      ${g}
      // Don't use uniform for sharedDimensionPacked for performance.
      const float sharedDimension = ${l}.0;

      vec4 dot2x2ARowBCol(ivec3 rc) {
        vec4 result = vec4(0);
        int batchA = ${C};
        int batchB = ${S};
        for (int i = 0; i < ${l}; i++) {
          vec4 a = getMatrixA(batchA, ${m});
          vec4 b = getMatrixB(batchB, ${d});

          // These swizzled products need to be separately added.
          // See: https://github.com/tensorflow/tfjs/issues/1735
          result += (${f[0]} * ${h[0]});
          result += (${f[1]} * ${h[1]});
        }
        return result;
      }

      void main() {
        ivec3 rc = getOutputCoords();
        vec4 result = dot2x2ARowBCol(rc);

        ${b}

        ${x}

        setOutput(result);
      }
    `;
  }
};
var bv = { REAL: "return areal * breal - aimag * bimag;", IMAG: "return areal * bimag + aimag * breal;" };
var em = class {
  constructor(e, t10, o) {
    this.variableNames = ["AReal", "AImag", "BReal", "BImag"], this.outputShape = w.assertAndGetBroadcastShape(t10, o), 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 XD = "return a * b;";
function tm(r15) {
  let { inputs: e, backend: t10 } = r15, { a: o, b: n } = e, s = w.upcastType(o.dtype, n.dtype);
  if (o.dtype === "complex64") {
    let i = t10.texData.get(o.dataId), p = t10.texData.get(n.dataId), u = new em(bv.REAL, o.shape, n.shape), c = new em(bv.IMAG, o.shape, n.shape), l = [{ dataId: i.complexTensorInfos.real.dataId, dtype: i.complexTensorInfos.real.dtype, shape: o.shape }, { dataId: i.complexTensorInfos.imag.dataId, dtype: i.complexTensorInfos.imag.dtype, shape: o.shape }, { dataId: p.complexTensorInfos.real.dataId, dtype: p.complexTensorInfos.real.dtype, shape: n.shape }, { dataId: p.complexTensorInfos.imag.dataId, dtype: p.complexTensorInfos.imag.dtype, shape: n.shape }], m = t10.runWebGLProgram(u, l, "float32"), d = t10.runWebGLProgram(c, l, "float32"), f = Or({ inputs: { real: m, imag: d }, backend: t10 });
    return t10.disposeIntermediateTensorInfo(m), t10.disposeIntermediateTensorInfo(d), f;
  }
  if (t10.shouldExecuteOnCPU([o, n])) {
    let i = t10.texData.get(o.dataId), p = t10.texData.get(n.dataId), [u, c] = sD(o.shape, n.shape, i.values, p.values, s), l = t10.makeTensorInfo(c, s), m = t10.texData.get(l.dataId);
    return m.values = u, l;
  }
  let a;
  return A().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? a = new jr(XD, o.shape, n.shape) : a = new Pr(XD, o.shape, n.shape), t10.runWebGLProgram(a, [o, n], s);
}
var YD = { kernelName: Xn, backendName: "webgl", kernelFunc: tm };
function QD(r15, e, t10) {
  let o = [gi(r15.shape), ...xi(r15.shape)], n = { dtype: r15.dtype, shape: o, dataId: r15.dataId }, s = [gi(e), ...xi(e)], a = new Mc(s, o), i = true, p = [o], u = t10.runWebGLProgram(a, [n], r15.dtype, p, i);
  return { dataId: u.dataId, shape: e, dtype: u.dtype };
}
function te(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { shape: s } = o, a = t10, i = y.sizeFromShape(n.shape), p = y.inferFromImplicitShape(s, i), u = y.sizeFromShape(p);
  y.assert(i === u, () => `The new shape (${p}) has ${u} elements and the old shape (${n.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);
  let c = a.texData.get(n.dataId);
  return c.isPacked && !xu(n.shape, p) && !(c.texture !== null && xu(c.shape, p)) ? QD(n, p, a) : (a.incRef(n.dataId), { dataId: n.dataId, shape: p, dtype: n.dtype });
}
var ZD = { kernelName: da, backendName: "webgl", kernelFunc: te };
var rm = class {
  constructor(e, t10) {
    this.variableNames = ["x"];
    let { windowSize: o, batchSize: n, inSize: s, outSize: a } = e;
    this.outputShape = [n, a];
    let i = Math.floor(o / 4) * 4, p = o % 4, u = "sumValue += dot(values, ones);";
    if (t10 != null) {
      let l = 1 / t10;
      u = `sumValue += dot(values * ${y.isInt(l) ? l.toPrecision(2) : l}, ones);`;
    }
    let c = "";
    s % o > 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 * ${o};

        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 (${p === 1}) {
          vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);

          ${u}
        } else if (${p === 2}) {
          vec4 values = vec4(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1), 0.0, 0.0);

          ${u}
        } else if (${p === 3}) {
          vec4 values = vec4(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            getValue(batch, inIdx + 2), 0.0);

          ${u}
        }
        setOutput(sumValue);
      }
    `;
  }
};
var gh = class {
  constructor(e, t10) {
    this.variableNames = ["x"];
    let { windowSize: o, batchSize: n, inSize: s, outSize: a } = e;
    this.outputShape = [n, a];
    let i = "0.0", p = "";
    t10 === "prod" ? i = "1.0" : t10 === "min" ? (i = "1.0 / 1e-20", p = "min") : t10 === "max" && (i = "-1.0 / 1e-20", p = "max");
    let u = `${t10}(${t10}(${t10}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;
    t10 === "sum" ? u = "sumValue" : t10 === "prod" ? u = "prodValue" : t10 === "all" ? u = "allValue" : t10 === "any" && (u = "anyValue");
    let c = Math.floor(o / 4) * 4, l = o % 4, m = `
      if (${t10 === "sum"}) {
        sumValue += dot(values, ones);
      } else if (${t10 === "prod"}) {
        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
        prodValue *= tmp[0] * tmp[1];
      } else {
        minMaxValue = ${p}(values, minMaxValue);
        if (${t10 === "min"} || ${t10 === "max"}) {
          minMaxValue = ${p}(values, minMaxValue);
          bvec4 isNaN = isnan(values);
          if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
            minMaxValue = vec4(NAN);
          }
        }
      }
    `, d = "vec4";
    t10 === "all" ? (i = "1.0", m = `
        bool reducedAllValue = all(values);
        float floatedReducedAllValue = float(reducedAllValue);
        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
      `, d = "bvec4") : t10 === "any" && (i = "0.0", m = `
        bool reducedAnyValue = any(values);
        float floatedReducedAnyValue = float(reducedAnyValue);
        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
      `, d = "bvec4");
    let f = "";
    s % o > 0 && (f = `
        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) {
        ${f}
        return getX(batch, inIdx);
      }

      void main() {
        ivec2 coords = getOutputCoords();
        int batch = coords[0];
        int outIdx = coords[1];
        int inOffset = outIdx * ${o};

        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;
          ${d} values = ${d}(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            getValue(batch, inIdx + 2),
            getValue(batch, inIdx + 3)
          );

          ${m}
        }

        int inIdx = inOffset + ${c};
        if (${l === 1}) {
          ${d} values = ${d}(
            getValue(batch, inIdx),
            initializationValue,
            initializationValue,
            initializationValue
          );

          ${m}
        } else if (${l === 2}) {
          ${d} values = ${d}(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            initializationValue,
            initializationValue
          );

          ${m}
        } else if (${l === 3}) {
          ${d} values = ${d}(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            getValue(batch, inIdx + 2),
            initializationValue
          );

          ${m}
        }
        setOutput(${u});
      }
    `;
  }
};
function x9(r15) {
  let e = [];
  for (; e.length === 0 || e[e.length - 1].outSize !== 1; ) {
    let t10 = e.length ? e[e.length - 1].outSize : r15[1], o = w.computeOptimalWindowSize(t10);
    e.push({ inSize: t10, windowSize: o, outSize: Math.ceil(t10 / o) });
  }
  return e;
}
function Yr(r15, e, t10, o) {
  let n = x9(r15.shape), s = r15;
  for (let a = 0; a < n.length; a++) {
    let { inSize: i, windowSize: p, outSize: u } = n[a], c, l;
    t10 === "mean" ? c = a === 0 ? new rm({ windowSize: p, inSize: i, batchSize: r15.shape[0], outSize: u }, i) : new rm({ windowSize: p, inSize: i, batchSize: r15.shape[0], outSize: u }) : c = new gh({ windowSize: p, inSize: i, batchSize: r15.shape[0], outSize: u }, t10), l = s, s = o.runWebGLProgram(c, [s], e), l.dataId !== r15.dataId && o.disposeIntermediateTensorInfo(l);
  }
  return s;
}
var xh = class {
  constructor(e, t10) {
    this.variableNames = ["A"];
    let o = new Array(e.length);
    for (let a = 0; a < o.length; a++) o[a] = e[t10[a]];
    this.outputShape = o, this.rank = o.length;
    let n = Re(this.rank), s = y9(t10);
    this.userCode = `
    void main() {
      ${n} resRC = getOutputCoords();
      setOutput(getA(${s}));
    }
    `;
  }
};
function y9(r15) {
  let e = r15.length;
  if (e > 6) throw Error(`Transpose for rank ${e} is not yet supported`);
  let t10 = ["resRC.x", "resRC.y", "resRC.z", "resRC.w", "resRC.u", "resRC.v"], o = new Array(e);
  for (let n = 0; n < r15.length; n++) o[r15[n]] = t10[n];
  return o.join();
}
var yh = class {
  constructor(e, t10) {
    this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true;
    let o = new Array(e.length);
    for (let c = 0; c < o.length; c++) o[c] = e[t10[c]];
    if (this.outputShape = o, this.rank = o.length, this.rank > 6) throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);
    let n = Re(this.rank), s = dv("rc", this.rank), a = new Array(this.rank);
    for (let c = 0; c < t10.length; c++) a[t10[c]] = s[c];
    let i = `vec2(${a.slice(-2).join()})`, p = `++${s[this.rank - 1]} < ${o[this.rank - 1]}`, u = `getChannel(getA(${a.join()}), ${i})`;
    this.userCode = `
    void main() {
      ${n} rc = getOutputCoords();
      vec4 result = vec4(0.);
      result[0] = ${u};
      if(${p}) {
        result[1] = ${u};
      }
      --${s[this.rank - 1]};
      if(++${s[this.rank - 2]} < ${o[this.rank - 2]}) {
        result[2] = ${u};
        if(${p}) {
          result[3] = ${u};
        }
      }
      setOutput(result);
    }
    `;
  }
};
function yu(r15, e, t10) {
  let o = A().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new yh(r15.shape, e) : new xh(r15.shape, e);
  return t10.runWebGLProgram(o, [r15], r15.dtype);
}
function JD(r15, e, t10, o) {
  let n = e, s = r15.shape.length, a = y.parseAxisParam(n, r15.shape), i = a, p = w.getAxesPermutation(i, s), u = p != null, c = r15;
  u && (c = yu(r15, p, o), i = w.getInnerMostAxes(i.length, s)), w.assertAxesAreInnerMostDims("sum", i, s);
  let [l, m] = w.computeOutAndReduceShapes(c.shape, i), d = l;
  t10 && (d = w.expandShapeToKeepDim(l, a));
  let f = y.sizeFromShape(m), g = y.sizeFromShape(r15.shape) / f, x = te({ inputs: { x: c }, attrs: { shape: [g, f] }, backend: o }), b = oi(r15.dtype), C = Yr(x, b, "sum", o), S = te({ inputs: { x: C }, attrs: { shape: d }, backend: o });
  return o.disposeIntermediateTensorInfo(x), o.disposeIntermediateTensorInfo(C), u && o.disposeIntermediateTensorInfo(c), S;
}
function wp(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o;
  return JD(n, s, a, t10);
}
var eA = { kernelName: "Sum", backendName: "webgl", kernelFunc: wp };
function bt(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { perm: s } = o, a = t10, i = n.shape.length, p = new Array(i);
  for (let c = 0; c < p.length; c++) p[c] = n.shape[s[c]];
  let u;
  if (a.shouldExecuteOnCPU([n])) {
    let l = a.texData.get(n.dataId).values, m = Cp(l, n.shape, n.dtype, s, p);
    u = a.makeTensorInfo(p, n.dtype);
    let d = a.texData.get(u.dataId);
    d.values = m;
  } else u = yu(n, s, a);
  return u;
}
var tA = { kernelName: co, backendName: "webgl", kernelFunc: bt };
var Cv = 1e3;
function Sp({ a: r15, b: e, transposeA: t10, transposeB: o, backend: n, bias: s = null, preluActivationWeights: a = null, leakyreluAlpha: i = 0, activation: p = null }) {
  let u = r15.shape.length, c = e.shape.length, l = t10 ? r15.shape[u - 2] : r15.shape[u - 1], m = o ? e.shape[c - 1] : e.shape[c - 2], d = t10 ? r15.shape[u - 1] : r15.shape[u - 2], f = o ? e.shape[c - 2] : e.shape[c - 1], h = r15.shape.slice(0, -2), g = e.shape.slice(0, -2), x = y.sizeFromShape(h), b = y.sizeFromShape(g), S = Sr.assertAndGetBroadcastShape(r15.shape.slice(0, -2), e.shape.slice(0, -2)).concat([d, f]);
  y.assert(l === m, () => `Error in matMul: inner shapes (${l}) and (${m}) of Tensors with shapes ${r15.shape} and ${e.shape} and transposeA=${t10} and transposeB=${o} must match.`);
  let k = t10 ? [x, l, d] : [x, d, l], _ = o ? [b, f, m] : [b, m, f], $ = te({ inputs: { x: r15 }, backend: n, attrs: { shape: k } }), R = te({ inputs: { x: e }, backend: n, attrs: { shape: _ } }), D = [$, R], P = Math.max(x, b), O = t10 ? $.shape[1] : $.shape[2], M = s != null, L = a != null, B = p === "leakyrelu", z = p != null ? yi(p, true) : null, U = M || L || B || z != null, j;
  if ((d === 1 || f === 1) && O > Cv && U === false) {
    let Y = $, J = R;
    t10 && (Y = bt({ inputs: { x: $ }, backend: n, attrs: { perm: [0, 2, 1] } }), D.push(Y)), o && (J = bt({ inputs: { x: R }, backend: n, attrs: { perm: [0, 2, 1] } }), D.push(J));
    let re = f !== 1, ne = f === 1, ee = Y;
    re && (ee = te({ inputs: { x: Y }, backend: n, attrs: { shape: [P, O, 1] } }), D.push(ee));
    let oe = f === 1 ? 2 : 1, ie = J;
    ne && (ie = te({ inputs: { x: J }, backend: n, attrs: { shape: [P, 1, O] } }), D.push(ie));
    let le = tm({ inputs: { a: ee, b: ie }, backend: n });
    j = wp({ inputs: { x: le }, backend: n, attrs: { axis: oe, keepDims: true } }), D.push(le);
  } else {
    let Y = dt(r15.dtype, e.dtype), J = new zc(k, _, [P, d, f], t10, o, M, z, L, B), re = [$, R];
    if (s != null && re.push(s), L && re.push(a), B) {
      let ne = n.makeTensorInfo([], "float32", y.createScalarValue(i, "float32"));
      re.push(ne), D.push(ne);
    }
    j = n.runWebGLProgram(J, re, Y);
  }
  let q = te({ inputs: { x: j }, backend: n, attrs: { shape: S } });
  D.push(j);
  for (let Y of D) n.disposeIntermediateTensorInfo(Y);
  return q;
}
function b9(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { a: n, b: s, bias: a, preluActivationWeights: i } = e, { transposeA: p, transposeB: u, activation: c, leakyreluAlpha: l } = o;
  return Sp({ a: n, b: s, transposeA: p, transposeB: u, backend: t10, bias: a, preluActivationWeights: i, leakyreluAlpha: l, activation: c });
}
var rA = { kernelName: So, backendName: "webgl", kernelFunc: b9 };
var oA = "return abs(x);";
function C9(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e;
  if (t10.shouldExecuteOnCPU([o]) && o.dtype !== "complex64") {
    let s = t10.texData.get(o.dataId), a = ch(s.values);
    return t10.makeTensorInfo(o.shape, o.dtype, a);
  }
  let n;
  return A().getBool("WEBGL_PACK_UNARY_OPERATIONS") ? n = new Fr(o.shape, oA) : n = new tr(o.shape, oA), t10.runWebGLProgram(n, [o], o.dtype);
}
var nA = { kernelName: "Abs", backendName: "webgl", kernelFunc: C9 };
var w9 = Wt + `
  if (abs(x) > 1.) {
    return NAN;
  }
  return acos(x);
`;
var S9 = xe({ opSnippet: w9 });
var sA = { kernelName: Vo, backendName: "webgl", kernelFunc: S9 };
var I9 = Wt + `
  if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`;
var v9 = xe({ opSnippet: I9 });
var aA = { kernelName: Wo, backendName: "webgl", kernelFunc: v9 };
var iA = "return a + b;";
var k9 = nt({ opSnippet: iA, packedOpSnippet: iA, supportsComplex: true, cpuKernelImpl: LR });
var uA = { kernelName: "Add", backendName: "webgl", kernelFunc: k9 };
var bh = class {
  constructor(e, t10) {
    this.outputShape = [], this.outputShape = e, this.variableNames = t10.map((s, a) => `T${a}`);
    let o = [];
    this.variableNames.forEach((s) => {
      o.push(`float v${s} = get${s}AtOutCoords();`);
    });
    let n = this.variableNames.map((s) => `v${s}`).join(" + ");
    this.userCode = `
      void main() {
        ${o.join(`
        `)}

        float result = ${n};
        setOutput(result);
      }
    `;
  }
};
var Ch = class {
  constructor(e, t10) {
    this.outputShape = [], this.packedInputs = true, this.packedOutput = true, this.outputShape = e, this.variableNames = t10.map((s, a) => `T${a}`);
    let o = [];
    this.variableNames.forEach((s) => {
      o.push(`vec4 v${s} = get${s}AtOutCoords();`);
    });
    let n = this.variableNames.map((s) => `v${s}`).join(" + ");
    this.userCode = `
      void main() {
        ${o.join(`
        `)}

        vec4 result = ${n};
        setOutput(result);
      }
    `;
  }
};
function wh(r15) {
  let { inputs: e, backend: t10 } = r15, o = e;
  if (o.length === 1) return Dt({ inputs: { x: o[0] }, backend: t10 });
  if (o.length > A().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")) {
    let p = Math.floor(o.length / 2), u = wh({ inputs: o.slice(0, p), backend: t10 }), c = wh({ inputs: o.slice(p), backend: t10 });
    return wh({ inputs: [u, c], backend: t10 });
  }
  let n = o.map((p) => p.dtype).reduce((p, u) => dt(p, u)), s = o.map((p) => p.shape), i = A().getBool("WEBGL_PACK") ? new Ch(o[0].shape, s) : new bh(o[0].shape, s);
  return t10.runWebGLProgram(i, o, n);
}
var pA = { kernelName: Uo, backendName: "webgl", kernelFunc: wh };
function N9(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o, i = n.shape.length, p = y.parseAxisParam(s, n.shape), u = p, c = w.getAxesPermutation(u, i), l = n;
  c != null && (l = bt({ inputs: { x: n }, backend: t10, attrs: { perm: c } }), u = w.getInnerMostAxes(u.length, i)), w.assertAxesAreInnerMostDims("all", u, i);
  let [m, d] = w.computeOutAndReduceShapes(l.shape, u), f = y.sizeFromShape(d), h = te({ inputs: { x: l }, backend: t10, attrs: { shape: [-1, f] } }), g = Yr(h, h.dtype, "all", t10), x;
  if (a) {
    let b = w.expandShapeToKeepDim(m, p);
    x = te({ inputs: { x: g }, backend: t10, attrs: { shape: b } });
  } else x = te({ inputs: { x: g }, backend: t10, attrs: { shape: m } });
  return t10.disposeIntermediateTensorInfo(h), t10.disposeIntermediateTensorInfo(g), c != null && t10.disposeIntermediateTensorInfo(l), x;
}
var cA = { kernelName: "All", backendName: "webgl", kernelFunc: N9 };
function T9(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o, i = n.shape.length, p = y.parseAxisParam(s, n.shape), u = p, c = w.getAxesPermutation(u, i), l = n;
  c != null && (l = bt({ inputs: { x: n }, backend: t10, attrs: { perm: c } }), u = w.getInnerMostAxes(u.length, i)), w.assertAxesAreInnerMostDims("any", u, i);
  let [m, d] = w.computeOutAndReduceShapes(l.shape, u), f = y.sizeFromShape(d), h = te({ inputs: { x: l }, backend: t10, attrs: { shape: [-1, f] } }), g = Yr(h, h.dtype, "any", t10), x;
  if (a) {
    let b = w.expandShapeToKeepDim(m, p);
    x = te({ inputs: { x: g }, backend: t10, attrs: { shape: b } });
  } else x = te({ inputs: { x: g }, backend: t10, attrs: { shape: m } });
  return t10.disposeIntermediateTensorInfo(h), t10.disposeIntermediateTensorInfo(g), c != null && t10.disposeIntermediateTensorInfo(l), x;
}
var lA = { kernelName: "Any", backendName: "webgl", kernelFunc: T9 };
var Sh = class {
  constructor(e, t10, o) {
    this.variableNames = ["A"];
    let { windowSize: n, batchSize: s, outSize: a } = e;
    o || this.variableNames.push("bestIndicesA"), this.outputShape = [s, a];
    let i = t10 === "max" ? ">" : "<", p = o ? "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 * ${n};

        int bestIndex = inOffset;
        float bestValue = getA(batch, bestIndex);

        for (int i = 0; i < ${n}; i++) {
          int inIdx = ${p};
          float candidate = getA(batch, inIdx);
          if (candidate ${i} bestValue) {
            bestValue = candidate;
            bestIndex = inIdx;
          }
        }
        setOutput(float(bestIndex));
      }
    `;
  }
};
var Ih = class {
  constructor(e, t10, o, n) {
    this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, y.assert(e.length > 2, () => `Packed arg${o.charAt(0).toUpperCase() + o.slice(1)} supports only inputs with rank above 2.`);
    let s = e[e.length - 1], a = Math.ceil(s / t10);
    this.outputShape = e.slice(0, -1), a > 1 && this.outputShape.push(a), n || this.variableNames.push("bestIndicesA");
    let i = this.outputShape, p = i.length, u = Re(p), c = Rt("coords", p), l, m;
    if (a === 1) {
      m = p + 1;
      let R = Re(m);
      l = `
        ${R} sourceLocR = ${R}(${c.join()}, 0);
        ++${c[p - 1]};
        ${R} sourceLocG = ${R}(${c.join()}, 0);
        ++${c[p - 2]};
        ${R} sourceLocA = ${R}(${c.join()}, 0);
        --${c[p - 1]};
        ${R} sourceLocB = ${R}(${c.join()}, 0);
        --${c[p - 2]};`;
    } else m = p, l = `
        ${u} sourceLocR = coords;
        ++${c[p - 1]};
        ${u} sourceLocG = coords;
        ++${c[p - 2]};
        ${u} sourceLocA = coords;
        --${c[p - 1]};
        ${u} sourceLocB = coords;
        --${c[p - 2]};`;
    let d = ["x", "y", "z", "w", "u", "v"].slice(0, m), f = "." + d[m - 1], h = d.map((R) => "int " + R), g = Rt("sourceLocR", m - 1).concat("inIdx.r"), x = Rt("sourceLocG", m - 1).concat("inIdx.g"), b = Rt("sourceLocB", m - 1).concat("inIdx.b"), C = Rt("sourceLocA", m - 1).concat("inIdx.a"), S = o === "max" ? "greaterThan" : "lessThan", k = n ? "" : `
          inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),
                             getBestIndicesAChannel(${x.join()}),
                             getBestIndicesAChannel(${b.join()}),
                             getBestIndicesAChannel(${C.join()})));`, _ = `vec4(
            getAChannel(${g.join()}),
            hasNextCol ? getAChannel(${x.join()}) : 0.,
            hasNextRow ? getAChannel(${b.join()}) : 0.,
            hasNextRow && hasNextCol ? getAChannel(${C.join()}) : 0.)`, $ = n ? "" : `
      float getBestIndicesAChannel(${h.join()}) {
        return getChannel(getBestIndicesA(${d.join()}),
                                          vec2(${d.slice(-2).join()}));
      }`;
    this.userCode = `
      float getAChannel(${h.join()}) {
        return getChannel(getA(${d.join()}),
                               vec2(${d.slice(-2).join()}));
      }
      ${$}
      void main() {
        ${u} coords = getOutputCoords();
        bool hasNextCol = ${c[p - 1]} < ${i[p - 1] - 1};
        bool hasNextRow = ${c[p - 2]} < ${i[p - 2] - 1};
        ${l}
        ivec4 srcIdx = ivec4(sourceLocR${f}, sourceLocG${f},
          sourceLocB${f}, sourceLocA${f}) * ${t10};
        ivec4 inIdx = srcIdx;
        vec4 bestIndex = vec4(inIdx);
        vec4 bestValue = ${_};

        for (int i = 0; i < ${t10}; i++) {
          inIdx = srcIdx;
          ${k}
          vec4 candidate = ${_};
          bvec4 nan = isnan(candidate);
          bvec4 replace = bvec4(
            vec4(${S}(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 mA(r15, e, t10, o = null) {
  let n = e.shape[0], s = e.shape[1];
  o != null && (n = o.shape[0], s = o.shape[1]);
  let a = w.computeOptimalWindowSize(s), i = { windowSize: a, inSize: s, batchSize: n, outSize: Math.ceil(s / a) }, p = new Sh(i, t10, o == null), u = [e];
  o != null && u.push(o);
  let c = r15.runWebGLProgram(p, u, "int32");
  if (c.shape[1] === 1) return c;
  let l = mA(r15, e, t10, c);
  return r15.disposeIntermediateTensorInfo(c), l;
}
function dA(r15, e, t10, o = null) {
  let n = o != null ? o.shape : e.shape, s = n[n.length - 1], a = w.computeOptimalWindowSize(s), i = new Ih(n, a, t10, o == null), p = o == null ? [e] : [e, o], u = r15.runWebGLProgram(i, p, "int32");
  if (u.shape.length === e.shape.length) {
    let c = dA(r15, e, t10, u);
    return r15.disposeIntermediateTensorInfo(u), c;
  }
  return u;
}
function vh(r15, e, t10, o) {
  let n = [t10];
  if (w.assertAxesAreInnerMostDims("arg" + o.charAt(0).toUpperCase() + o.slice(1), n, e.shape.length), !A().getBool("WEBGL_PACK_REDUCE") || e.shape.length <= 2) {
    let s = [], a = r15.texData.get(e.dataId), i = a !== null && a.isPacked, p = e;
    i && (p = r15.unpackTensor(e), s.push(p));
    let [u, c] = w.computeOutAndReduceShapes(p.shape, n), l = y.sizeFromShape(c), m = te({ inputs: { x: p }, backend: r15, attrs: { shape: [-1, l] } });
    s.push(m);
    let d = mA(r15, m, o);
    s.push(d);
    let f = te({ inputs: { x: d }, backend: r15, attrs: { shape: u } });
    return s.forEach((h) => r15.disposeIntermediateTensorInfo(h)), f;
  }
  return dA(r15, e, o);
}
function _9(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s } = o, a = y.parseAxisParam(s, n.shape), i = w.getAxesPermutation(a, n.shape.length), p = n, u = [];
  i != null && (p = bt({ inputs: { x: n }, backend: t10, attrs: { perm: i } }), u.push(p), a = w.getInnerMostAxes(a.length, p.shape.length)), w.assertAxesAreInnerMostDims("argMax", [a[0]], p.shape.length);
  let c = vh(t10, p, a[0], "max");
  return u.forEach((l) => t10.disposeIntermediateTensorInfo(l)), c;
}
var fA = { kernelName: Ys, backendName: "webgl", kernelFunc: _9 };
function E9(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s } = o, a = y.parseAxisParam(s, n.shape), i = w.getAxesPermutation(a, n.shape.length), p = n, u = [];
  i != null && (p = bt({ inputs: { x: n }, backend: t10, attrs: { perm: i } }), u.push(p), a = w.getInnerMostAxes(a.length, p.shape.length)), w.assertAxesAreInnerMostDims("argMin", [a[0]], p.shape.length);
  let c = vh(t10, p, a[0], "min");
  return u.forEach((l) => t10.disposeIntermediateTensorInfo(l)), c;
}
var hA = { kernelName: Qs, backendName: "webgl", kernelFunc: E9 };
var $9 = Wt + `
  if (abs(x) > 1.) {
    return NAN;
  }
  return asin(x);
`;
var R9 = xe({ opSnippet: $9 });
var gA = { kernelName: Ko, backendName: "webgl", kernelFunc: R9 };
var D9 = Wt + "return log(x + sqrt(x * x + 1.0));";
var A9 = xe({ opSnippet: D9 });
var xA = { kernelName: qo, backendName: "webgl", kernelFunc: A9 };
var F9 = Wt + `
  return atan(x);
`;
var P9 = xe({ opSnippet: F9 });
var yA = { kernelName: jo, backendName: "webgl", kernelFunc: P9 };
var O9 = Bc + `
  return atan(a, b);
`;
var M9 = `
  vec4 result = atan(a, b);
  bvec4 isNaNA = isnan(a);
  bvec4 isNaNB = isnan(b);
  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
  ` + Xr + `
  return result;
`;
var L9 = nt({ opSnippet: O9, packedOpSnippet: M9 });
var bA = { kernelName: Yo, backendName: "webgl", kernelFunc: L9 };
var B9 = Wt + `
  if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`;
var z9 = xe({ opSnippet: B9 });
var CA = { kernelName: Xo, backendName: "webgl", kernelFunc: z9 };
var Us = class {
  constructor(e, t10, o, n = false, s = false) {
    if (this.variableNames = ["x"], t10 === "avg" && o) throw new Error("Cannot compute positions for average pool.");
    let a = e.filterWidth, i = e.strideHeight, p = e.strideWidth, u = e.dilationHeight, c = e.dilationWidth, l = e.effectiveFilterHeight, m = e.effectiveFilterWidth, d = e.padInfo.top, f = e.padInfo.left;
    this.outputShape = e.outShape;
    let h = t10 === "avg", g = `((batch  * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`, x = `(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`, b = "0.0";
    if (h || (b = "-1.0 / 1e-20"), o) {
      this.userCode = `
        const ivec2 strides = ivec2(${i}, ${p});
        const ivec2 pads = ivec2(${d}, ${f});

        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 < ${l};
              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 >= currMinMaxValue) {
                minMaxValue = value;
                minMaxValueFound = 1.0;
                minMaxPosition = ${n ? s ? g : x : `wR * ${m} + wC`};
              }
            }
          }
          setOutput(float(minMaxPosition));
        }
      `;
      return;
    }
    let C = "max", S = `${t10}(${t10}(${t10}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;
    t10 === "avg" && (S = "avgValue / max(count, 1.0)");
    let k = Math.floor(a / 4) * 4, _ = a % 4, $ = `
      if (${h}) {
        avgValue += dot(values, ones);
      } else {
        minMaxValue = ${C}(values, minMaxValue);
      }
    `;
    this.userCode = `
      const ivec2 strides = ivec2(${i}, ${p});
      const ivec2 pads = ivec2(${d}, ${f});
      const float initializationValue = ${b};
      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(${b});
        float avgValue = 0.0;
        count = 0.0;

        for (int wR = 0; wR < ${l};
            wR += ${u}) {
          int xR = xRCorner + wR;

          if (xR < 0 || xR >= ${e.inHeight}) {
            continue;
          }

          for (int wC = 0; wC < ${k}; 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)
            );

            ${$}
          }

          int xC = xCCorner + ${k};
          if (${_ === 1}) {
            vec4 values = vec4(
              getValue(batch, xR, xC, d),
              initializationValue,
              initializationValue,
              initializationValue
            );

            ${$}
          } else if (${_ === 2}) {
            vec4 values = vec4(
              getValue(batch, xR, xC, d),
              getValue(batch, xR, xC + ${c}, d),
              initializationValue,
              initializationValue
            );

            ${$}
          } else if (${_ === 3}) {
            vec4 values = vec4(
              getValue(batch, xR, xC, d),
              getValue(batch, xR, xC + ${c}, d),
              getValue(batch, xR, xC + 2 * ${c}, d),
              initializationValue
            );

            ${$}
          }
        }
        setOutput(${S});
      }
    `;
  }
};
var bu = class {
  constructor(e, t10, o, n = false, s = false) {
    if (this.variableNames = ["x"], t10 === "avg" && o) throw new Error("Cannot compute positions for average pool.");
    let a = e.filterWidth, i = e.strideDepth, p = e.strideHeight, u = e.strideWidth, c = e.dilationDepth, l = e.dilationHeight, m = e.dilationWidth, d = e.effectiveFilterDepth, f = e.effectiveFilterHeight, h = e.effectiveFilterWidth, g = e.padInfo.front, x = e.padInfo.top, b = e.padInfo.left;
    this.outputShape = e.outShape;
    let C = t10 === "avg", S = "0.0";
    if (C || (S = "-1.0 / 1e-20"), o) {
      this.userCode = `
        const ivec3 strides =
            ivec3(${i}, ${p}, ${u});
        const ivec3 pads = ivec3(${g}, ${x}, ${b});

        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 < ${d};
              wD += ${c}) {
            int xD = xDCorner + wD;

            if (xD < 0 || xD >= ${e.inDepth}) {
              continue;
            }

            for (int wR = 0; wR < ${f};
                wR += ${l}) {
              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 >= currMinMaxValue) {
                  minMaxValue = value;
                  minMaxValueFound = 1.0;
                  minMaxPosition = ${n ? 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 * ${f} * ${h} +
                      wR * ${h} + wC`};
                }
              }
            }
          }
          setOutput(float(minMaxPosition));
        }
      `;
      return;
    }
    let k = "max", _ = `${t10}(${t10}(${t10}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;
    t10 === "avg" && (_ = "avgValue / max(count, 1.0)");
    let $ = Math.floor(a / 4) * 4, R = a % 4, D = `
      if (${C}) {
        avgValue += dot(values, ones);
      } else {
        minMaxValue = ${k}(values, minMaxValue);
      }
    `;
    this.userCode = `
      const ivec3 strides =
        ivec3(${i}, ${p}, ${u});
      const ivec3 pads = ivec3(${g}, ${x}, ${b});
      const float initializationValue = ${S};
      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(${S});
        float avgValue = 0.0;
        count = 0.0;

        for (int wD = 0; wD < ${d};
            wD += ${c}) {
          int xD = xDCorner + wD;

          if (xD < 0 || xD >= ${e.inDepth}) {
            continue;
          }

          for (int wR = 0; wR < ${f};
            wR += ${l}) {
            int xR = xRCorner + wR;

            if (xR < 0 || xR >= ${e.inHeight}) {
              continue;
            }

            for (int wC = 0; wC < ${$}; 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)
              );

              ${D}
            }

            int xC = xCCorner + ${$};
            if (${R === 1}) {
              vec4 values = vec4(
                getValue(batch, xD, xR, xC, ch),
                initializationValue,
                initializationValue,
                initializationValue
              );

              ${D}
            } else if (${R === 2}) {
              vec4 values = vec4(
                getValue(batch, xD, xR, xC, ch),
                getValue(batch, xD, xR, xC + ${m}, ch),
                initializationValue,
                initializationValue
              );

              ${D}
            } 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
              );

              ${D}
            }
          }
        }
        setOutput(${_});
      }
    `;
  }
};
function V9(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e;
  Vs(n, "avgPool");
  let { filterSize: s, strides: a, pad: i, dimRoundingMode: p } = o, u = 1;
  y.assert(w.eitherStridesOrDilationsAreOne(a, u), () => `Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);
  let c = w.computePool2DInfo(n.shape, s, a, u, i, p);
  if (c.filterWidth === 1 && c.filterHeight === 1 && y.arraysEqual(c.inShape, c.outShape)) return Dt({ inputs: { x: n }, backend: t10 });
  let l = new Us(c, "avg", false);
  return t10.runWebGLProgram(l, [n], "float32");
}
var wA = { kernelName: Qo, backendName: "webgl", kernelFunc: V9 };
function W9(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { filterSize: s, strides: a, pad: i, dimRoundingMode: p, dataFormat: u } = o, c = [1, 1, 1], l = w.computePool3DInfo(n.shape, s, a, c, i, p, u), m = new bu(l, "avg", false);
  return t10.runWebGLProgram(m, [n], "float32");
}
var SA = { kernelName: Zs, backendName: "webgl", kernelFunc: W9 };
var kh = class {
  constructor(e) {
    this.variableNames = ["dy"], this.outputShape = e.inShape;
    let t10 = e.filterHeight, o = e.filterWidth, n = e.strideHeight, s = e.strideWidth, a = e.dilationHeight, i = e.dilationWidth, p = e.effectiveFilterHeight, u = e.effectiveFilterWidth, c = p - 1 - e.padInfo.top, l = u - 1 - e.padInfo.left, m = 1 / (t10 * o);
    this.userCode = `
      const ivec2 pads = ivec2(${c}, ${l});
      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 < ${p};
            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 < ${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 Nh = class {
  constructor(e) {
    this.variableNames = ["dy"], this.outputShape = e.inShape;
    let t10 = e.filterDepth, o = e.filterHeight, n = e.filterWidth, s = e.strideDepth, a = e.strideHeight, i = e.strideWidth, p = e.dilationDepth, u = e.dilationHeight, c = e.dilationWidth, l = e.effectiveFilterDepth, m = e.effectiveFilterHeight, d = e.effectiveFilterWidth, f = l - 1 - e.padInfo.front, h = m - 1 - e.padInfo.top, g = d - 1 - e.padInfo.left, x = 1 / (t10 * o * n);
    this.userCode = `
      const ivec3 pads = ivec3(${f}, ${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 < ${l};
            wD += ${p}) {
          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 < ${d};
                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 U9(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s } = e, a = s, { filterSize: i, strides: p, pad: u, dimRoundingMode: c } = o, l = [1, 1, 1], m = w.computePool3DInfo(a.shape, i, p, l, u, c), d = new Nh(m);
  return t10.runWebGLProgram(d, [n], a.dtype);
}
var IA = { kernelName: Ri, backendName: "webgl", kernelFunc: U9 };
function G9(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s } = e, a = s;
  Vs([n, s], "avgPoolGrad");
  let { filterSize: i, strides: p, pad: u } = o, c = w.computePool2DInfo(a.shape, i, p, 1, u), l = new kh(c);
  return t10.runWebGLProgram(l, [n], a.dtype);
}
var vA = { kernelName: $i, backendName: "webgl", kernelFunc: G9 };
function H9(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { a: n, b: s } = e, { transposeA: a, transposeB: i } = o;
  return Sp({ a: n, b: s, transposeA: a, transposeB: i, backend: t10 });
}
var kA = { kernelName: Zo, backendName: "webgl", kernelFunc: H9 };
var Th = class {
  constructor(e, t10, o, n, s, a) {
    this.outputShape = [], this.variableNames = ["x", "mean", "variance"], w.assertAndGetBroadcastShape(e, t10), w.assertAndGetBroadcastShape(e, o);
    let i = "0.0";
    n != null && (w.assertAndGetBroadcastShape(e, n), this.variableNames.push("offset"), i = "getOffsetAtOutCoords()");
    let p = "1.0";
    s != null && (w.assertAndGetBroadcastShape(e, s), this.variableNames.push("scale"), p = "getScaleAtOutCoords()"), this.outputShape = e, this.userCode = `
      void main() {
        float x = getXAtOutCoords();
        float mean = getMeanAtOutCoords();
        float variance = getVarianceAtOutCoords();
        float offset = ${i};
        float scale = ${p};
        float inv = scale * inversesqrt(variance + float(${a}));
        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
      }
    `;
  }
};
var _h = class {
  constructor(e, t10, o, n, s, a) {
    this.packedInputs = true, this.packedOutput = true, this.variableNames = ["x", "mean", "variance"], w.assertAndGetBroadcastShape(e, t10), w.assertAndGetBroadcastShape(e, o);
    let i = "vec4(0.0)";
    n != null && (w.assertAndGetBroadcastShape(e, n), this.variableNames.push("offset"), i = "getOffsetAtOutCoords()");
    let p = "vec4(1.0)";
    s != null && (w.assertAndGetBroadcastShape(e, s), this.variableNames.push("scale"), p = "getScaleAtOutCoords()"), this.outputShape = e, this.userCode = `
      void main() {
        vec4 offset = ${i};
        vec4 scale = ${p};

        vec4 x = getXAtOutCoords();
        vec4 mean = getMeanAtOutCoords();
        vec4 variance = getVarianceAtOutCoords();

        vec4 inv = scale * inversesqrt(variance + vec4(${a}));

        setOutput((x - mean) * inv + offset);
      }
    `;
  }
};
var K9 = ({ inputs: r15, backend: e, attrs: t10 }) => {
  let { x: o, mean: n, variance: s, offset: a, scale: i } = r15;
  y.assert(n.shape.length === s.shape.length, () => "Batch normalization gradient requires mean and variance to have equal ranks."), y.assert(a == null || n.shape.length === a.shape.length, () => "Batch normalization gradient requires mean and offset to have equal ranks."), y.assert(i == null || n.shape.length === i.shape.length, () => "Batch normalization gradient requires mean and scale to have equal ranks.");
  let { varianceEpsilon: p } = t10;
  p == null && (p = 1e-3);
  let u = [o, n, s], c = null;
  a != null && (c = a.shape, u.push(a));
  let l = null;
  i != null && (l = i.shape, u.push(i));
  let m = A().getBool("WEBGL_PACK_NORMALIZATION") ? new _h(o.shape, n.shape, s.shape, c, l, p) : new Th(o.shape, n.shape, s.shape, c, l, p);
  return e.runWebGLProgram(m, u, u[0].dtype);
};
var NA = { kernelName: In, backendName: "webgl", kernelFunc: K9 };
var Eh = class {
  constructor(e) {
    this.variableNames = ["source"], this.outputShape = e, this.rank = e.length;
    let t10 = Re(this.rank);
    this.customUniforms = [{ name: "start", arrayIndex: this.rank, type: "int" }];
    let o = q9(this.rank), n, s = e.map((a, i) => `sourceLoc.${wv[i]} = start[${i}] + coords.${wv[i]};`);
    n = `
        ${t10} sourceLoc;
        ${t10} coords = getOutputCoords();
        ${s.join(`
`)}
      `, this.userCode = `
      void main() {
        ${n}
        setOutput(getSource(${o}));
      }
    `;
  }
};
var wv = ["x", "y", "z", "w", "u", "v"];
function q9(r15) {
  if (r15 === 1) return "sourceLoc";
  if (r15 <= 6) return wv.slice(0, r15).map((e) => "sourceLoc." + e).join(",");
  throw Error(`Slicing for rank ${r15} is not yet supported`);
}
var $h = 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 t10 = Re(this.rank), o = Rt("coords", this.rank), n = Rt("sourceLoc", this.rank), s = this.rank === 1 ? "sourceLoc" : `vec2(${n.slice(-2).join()})`, a = `getChannel(getSource(${n.join()}), ${s})`, i = `
      result.x = ${a};
      if (++${o[this.rank - 1]} < ${e[this.rank - 1]}) {
        ++${n[this.rank - 1]};
        result.y = ${a};
        --${n[this.rank - 1]};
      }
    `, p = this.rank === 1 ? "" : `
      --${o[this.rank - 1]};
      if (++${o[this.rank - 2]} < ${e[this.rank - 2]}) {
        ++${n[this.rank - 2]};
        result.z = ${a};
        if (++${o[this.rank - 1]} < ${e[this.rank - 1]}) {
          ++${n[this.rank - 1]};
          result.w = ${a};
        }
      }
    `, u = this.rank <= 4 ? `sourceLoc = coords +
            ${t10}(${e.map((c, l) => `start[${l}]`).join()});` : e.map((c, l) => `${n[l]} = ${o[l]} + start[${l}];`).join(`
`);
    this.userCode = `
      void main() {
        ${t10} coords = getOutputCoords();
        ${t10} sourceLoc;
        ${u}
        vec4 result = vec4(0.);
        ${i}
        ${p}
        setOutput(result);
      }
    `;
  }
};
function j9(r15, e, t10, o) {
  let n = o.texData.get(r15.dataId), s = o.makeTensorInfo(t10, r15.dtype), a = o.texData.get(s.dataId);
  Object.assign(a, n), a.refCount = 1, a.shape = t10, a.dtype = r15.dtype;
  let i = pt.computeFlatOffset(e, y.computeStrides(r15.shape));
  n.slice && (i += n.slice.flatOffset), a.slice = { flatOffset: i, origDataId: n.slice && n.slice.origDataId || r15.dataId };
  let p = o.dataRefCount.get(a.slice.origDataId) || 1;
  return o.dataRefCount.set(a.slice.origDataId, p + 1), s;
}
function Gs(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { begin: s, size: a } = o, [i, p] = pt.parseSliceParams(n, s, a);
  if (pt.assertParamsValid(n, i, p), y.sizeFromShape(p) === 0) return t10.makeTensorInfo(p, n.dtype, []);
  if (t10.shouldExecuteOnCPU([n]) || n.dtype === "string") {
    let l = t10.texData.get(n.dataId), m = gD(l.values, i, p, n.shape, n.dtype);
    return t10.makeTensorInfo(p, n.dtype, m);
  }
  let { isPacked: u } = t10.texData.get(n.dataId), c = pt.isSliceContinous(n.shape, i, p);
  if (u || !c) {
    let l = A().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new $h(p) : new Eh(p), m = [i];
    return t10.runWebGLProgram(l, [n], n.dtype, m);
  }
  return t10.uploadToGPU(n.dataId), j9(n, i, p, t10);
}
var TA = { kernelName: ha, backendName: "webgl", kernelFunc: Gs };
var X9 = (r15) => {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { blockShape: s, crops: a } = o;
  y.assert(n.shape.length <= 4, () => "batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");
  let i = s.reduce((b, C) => b * C), p = w.getReshaped(n.shape, s, i), u = w.getPermuted(p.length, s.length), c = w.getReshapedPermuted(n.shape, s, i), l = w.getSliceBeginCoords(a, s.length), m = w.getSliceSize(c, a, s.length), d = [], f = te({ inputs: { x: n }, backend: t10, attrs: { shape: p } }), h = bt({ inputs: { x: f }, backend: t10, attrs: { perm: u } }), g = te({ inputs: { x: h }, backend: t10, attrs: { shape: c } }), x = Gs({ inputs: { x: g }, backend: t10, attrs: { begin: l, size: m } });
  return d.push(f), d.push(h), d.push(g), d.forEach((b) => t10.disposeIntermediateTensorInfo(b)), x;
};
var _A = { kernelName: Js, backendName: "webgl", kernelFunc: X9 };
function Y9(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, weights: s } = e, { size: a } = o, i = t10.readSync(n.dataId), p = t10.readSync(s.dataId), u = ph(i, p, s.dtype, s.shape, a);
  return t10.makeTensorInfo([a], s.dtype, u);
}
var EA = { kernelName: Jo, backendName: "webgl", kernelFunc: Y9 };
var Q9 = `
  int r = int(a.r) & int(b.r);
  int g = int(a.g) & int(b.g);
  int rb = int(a.b) & int(b.b);
  int ra = int(a.a) & int(b.a);
  return vec4(r, g, rb, ra);
`;
var Z9 = `
  return float(int(a.r) & int(b.r));
`;
function J9(r15) {
  let { inputs: e, backend: t10 } = r15, { a: o, b: n } = e, s = A().getBool("WEBGL_PACK_BINARY_OPERATIONS"), a = A().getNumber("WEBGL_VERSION");
  if (t10.shouldExecuteOnCPU([o, n]) || a === 1) {
    let p = t10.texData.get(o.dataId).values, u = t10.texData.get(n.dataId).values, [c, l] = zR(o.shape, n.shape, p, u, o.dtype), m = t10.makeTensorInfo(l, o.dtype), d = t10.texData.get(m.dataId);
    return d.values = c, m;
  }
  let i;
  return s ? i = new jr(Q9, o.shape, n.shape, false) : i = new Pr(Z9, o.shape, n.shape), t10.runWebGLProgram(i, [o, n], o.dtype);
}
var $A = { kernelName: qa, backendName: "webgl", kernelFunc: J9 };
function eJ(r15) {
  let { inputs: e, backend: t10 } = r15, { s0: o, s1: n } = e, s = t10.readSync(o.dataId), a = t10.readSync(n.dataId), i = w.assertAndGetBroadcastShape(Array.from(s), Array.from(a));
  return t10.makeTensorInfo([i.length], "int32", Int32Array.from(i));
}
var RA = { kernelName: ea, backendName: "webgl", kernelFunc: eJ };
var tJ = "return float(a != b);";
var Sv = nt({ opSnippet: tJ, cpuKernelImpl: iD, dtype: "bool" });
var DA = { kernelName: Yn, backendName: "webgl", kernelFunc: Sv };
function bi(r15) {
  let { inputs: e, backend: t10 } = r15, { input: o } = e, n = t10.texData.get(o.dataId);
  return Dt({ inputs: { x: n.complexTensorInfos.real }, backend: t10 });
}
var AA = { kernelName: Hi, backendName: "webgl", kernelFunc: bi };
var rJ = "return float(int(x));";
function FA(r15, e) {
  let t10 = new tr(r15.shape, rJ), o = e.runWebGLProgram(t10, [r15], "int32");
  return { dataId: o.dataId, shape: o.shape, dtype: o.dtype };
}
function Iv(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { dtype: s } = o;
  if (s === "complex64") {
    if (n.dtype === "complex64") return Dt({ inputs: { x: n }, backend: t10 });
    let a = Gr(n.shape), i = Iv({ inputs: { x: n }, backend: t10, attrs: { dtype: "float32" } }), p = Or({ inputs: { real: i, imag: a }, backend: t10 });
    return a.dispose(), t10.disposeIntermediateTensorInfo(i), p;
  }
  if (n.dtype === "complex64") {
    let a = bi({ inputs: { input: n }, backend: t10 }), i = Iv({ inputs: { x: a }, backend: t10, attrs: { dtype: s } });
    return t10.disposeIntermediateTensorInfo(a), i;
  }
  if (!y.hasEncodingLoss(n.dtype, s)) {
    let a = Dt({ inputs: { x: n }, backend: t10 });
    return { dataId: a.dataId, shape: a.shape, dtype: s };
  }
  if (t10.shouldExecuteOnCPU([n])) {
    let a = t10.texData.get(n.dataId).values, [i, p, u] = VR(a, n.shape, n.dtype, s);
    return t10.makeTensorInfo(i, p, u);
  }
  if (s === "int32") return FA(n, t10);
  if (s === "bool") {
    let a = t10.makeTensorInfo([], "bool", y.getTypedArrayFromDType("bool", 1)), p = Sv({ inputs: { a: n, b: a }, backend: t10 });
    return t10.disposeIntermediateTensorInfo(a), p;
  }
  throw new Error(`Error in Cast: failed to cast ${n.dtype} to ${s}`);
}
var PA = { kernelName: yo, backendName: "webgl", kernelFunc: Iv };
var OA = "return ceil(x);";
var oJ = xe({ opSnippet: OA, packedOpSnippet: OA, cpuKernelImpl: WR });
var MA = { kernelName: en, backendName: "webgl", kernelFunc: oJ };
var Rh = 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 Dh = 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 nJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { clipValueMin: s, clipValueMax: a } = o, i;
  A().getBool("WEBGL_PACK_CLIP") ? i = new Dh(n.shape) : i = new Rh(n.shape);
  let p = [[s], [a]];
  return t10.runWebGLProgram(i, [n], n.dtype, p);
}
var LA = { kernelName: bo, backendName: "webgl", kernelFunc: nJ };
var Ah = 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 BA(r15, e) {
  return { dataId: e.dataId, dtype: e.dtype, shape: r15.shape };
}
function sJ(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e, n = t10.texData.get(o.dataId), s = new Ah(o.shape), a = [BA(o, n.complexTensorInfos.real), BA(o, n.complexTensorInfos.imag)];
  return t10.runWebGLProgram(s, a, a[0].dtype);
}
var zA = { kernelName: Ai, backendName: "webgl", kernelFunc: sJ };
var Fh = class {
  constructor(e) {
    this.outputShape = [], this.outputShape = w.computeOutShape(e, 1), this.variableNames = e.map((a, i) => `T${i}`);
    let t10 = new Array(e.length - 1);
    t10[0] = e[0][1];
    for (let a = 1; a < t10.length; a++) t10[a] = t10[a - 1] + e[a][1];
    let o = [`if (yC < ${t10[0]}) setOutput(getT0(yR, yC));`];
    for (let a = 1; a < t10.length; a++) {
      let i = t10[a - 1];
      o.push(`else if (yC < ${t10[a]}) setOutput(getT${a}(yR, yC-${i}));`);
    }
    let n = t10.length, s = t10[t10.length - 1];
    o.push(`else setOutput(getT${n}(yR, yC-${s}));`), this.userCode = `
      void main() {
        ivec2 coords = getOutputCoords();
        int yR = coords.x;
        int yC = coords.y;

        ${o.join(`
        `)}
      }
    `;
  }
};
var Oh = class {
  constructor(e, t10) {
    this.packedInputs = true, this.packedOutput = true, this.outputShape = [], this.outputShape = w.computeOutShape(e, t10);
    let o = this.outputShape, n = o.length, s = Re(n), a = Rt("coords", n), i = ["x", "y", "z", "w", "u", "v"].slice(0, n);
    this.variableNames = e.map((h, g) => `T${g}`);
    let p = new Array(e.length - 1);
    p[0] = e[0][t10];
    for (let h = 1; h < p.length; h++) p[h] = p[h - 1] + e[h][t10];
    let u = i[t10], c = i.slice(-2), l = i.join(), m = `if (${u} < ${p[0]}) {
        return getChannel(
            getT0(${l}), vec2(${c.join()}));
        }`;
    for (let h = 1; h < p.length; h++) {
      let g = p[h - 1];
      m += `
        if (${u} < ${p[h]}  && ${u} >= ${p[h - 1]}) {
          return getChannel(
            getT${h}(${Ph(i, u, g)}),
            vec2(${Ph(c, u, g)}));
        }`;
    }
    let d = p.length, f = p[p.length - 1];
    m += `
        return getChannel(
          getT${d}(${Ph(i, u, f)}),
          vec2(${Ph(c, u, f)}));`, this.userCode = `
      float getValue(${i.map((h) => "int " + h)}) {
        ${m}
      }

      void main() {
        ${s} coords = getOutputCoords();
        vec4 result = vec4(getValue(${a}), 0., 0., 0.);

        ${a[n - 1]} = ${a[n - 1]} + 1;
        if (${a[n - 1]} < ${o[n - 1]}) {
          result.g = getValue(${a});
        }

        ${a[n - 2]} = ${a[n - 2]} + 1;
        if (${a[n - 2]} < ${o[n - 2]}) {
          result.a = getValue(${a});
        }

        ${a[n - 1]} = ${a[n - 1]} - 1;
        if (${a[n - 2]} < ${o[n - 2]} &&
            ${a[n - 1]} < ${o[n - 1]}) {
          result.b = getValue(${a});
        }
        setOutput(result);
      }
    `;
  }
};
function Ph(r15, e, t10) {
  let o = r15.indexOf(e);
  return r15.map((s, a) => a === o ? `${s} - ${t10}` : s).join();
}
function Ip(r15) {
  let { inputs: e, backend: t10 } = r15, { input: o } = e, n = t10.texData.get(o.dataId);
  return Dt({ inputs: { x: n.complexTensorInfos.imag }, backend: t10 });
}
var VA = { kernelName: Wi, backendName: "webgl", kernelFunc: Ip };
function Vc(r15, e, t10) {
  let o = r15[0].dtype;
  if (o === "complex64") {
    let d = r15.map((b) => bi({ inputs: { input: b }, backend: t10 })), f = r15.map((b) => Ip({ inputs: { input: b }, backend: t10 })), h = Vc(d, e, t10), g = Vc(f, e, t10), x = Or({ inputs: { real: h, imag: g }, backend: t10 });
    return d.forEach((b) => t10.disposeIntermediateTensorInfo(b)), f.forEach((b) => t10.disposeIntermediateTensorInfo(b)), t10.disposeIntermediateTensorInfo(h), t10.disposeIntermediateTensorInfo(g), x;
  }
  let n = t10.shouldExecuteOnCPU(r15);
  if (o === "string" && (n = true), n) {
    let d = r15.map((S) => {
      let _ = [-1, y.sizeFromShape(S.shape.slice(e))];
      return te({ inputs: { x: S }, backend: t10, attrs: { shape: _ } });
    }), f = d.map((S) => ({ vals: t10.readSync(S.dataId), shape: S.shape })), h = w.computeOutShape(d.map((S) => S.shape), 1), g = d[0].shape[0] === 1, x = UR(f, h, o, g), b = w.computeOutShape(r15.map((S) => S.shape), e), C = t10.makeTensorInfo(b, o, x);
    return d.forEach((S) => t10.disposeIntermediateTensorInfo(S)), C;
  }
  let s = r15.filter((d) => y.sizeFromShape(d.shape) > 0), a = A().getBool("WEBGL_PACK_ARRAY_OPERATIONS") && s[0].shape.length > 1;
  if (s.length === 1) {
    let d = a ? new tr(r15[0].shape, La) : new Fr(r15[0].shape, La);
    return t10.runWebGLProgram(d, r15, o);
  }
  let i = A().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");
  if (s.length > i) {
    let d = [];
    for (let h = 0; h < s.length; h += i) {
      let g = s.slice(h, h + i);
      d.push(Vc(g, e, t10));
    }
    let f = Vc(d, e, t10);
    for (let h of d) t10.disposeIntermediateTensorInfo(h);
    return f;
  }
  if (a) {
    let d = new Oh(s.map((f) => f.shape), e);
    return t10.runWebGLProgram(d, s, o);
  }
  let { tensors2D: p, outShape: u } = aJ(s, e, t10), c = new Fh(p.map((d) => d.shape)), l = t10.runWebGLProgram(c, p, o);
  p.forEach((d) => t10.disposeIntermediateTensorInfo(d));
  let m = te({ inputs: { x: l }, attrs: { shape: u }, backend: t10 });
  return t10.disposeIntermediateTensorInfo(l), m;
}
function aJ(r15, e, t10) {
  let o = w.computeOutShape(r15.map((s) => s.shape), e);
  return { tensors2D: r15.map((s) => te({ inputs: { x: s }, attrs: { shape: [-1, y.sizeFromShape(s.shape.slice(e))] }, backend: t10 })), outShape: o };
}
function vv(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { axis: n } = o, s = y.parseAxisParam(n, e[0].shape)[0], a = e.map((u) => u.shape);
  w.assertParamsConsistent(a, s);
  let i = w.computeOutShape(e.map((u) => u.shape), s);
  if (y.sizeFromShape(i) === 0) return t10.makeTensorInfo(i, e[0].dtype, []);
  let p = e.filter((u) => y.sizeFromShape(u.shape) > 0);
  return p.length === 1 ? Dt({ inputs: { x: p[0] }, backend: t10 }) : Vc(p, s, t10);
}
var WA = { kernelName: ta, backendName: "webgl", kernelFunc: vv };
var Wc = class {
  constructor(e, t10 = false, o = null, n = false, s = false) {
    this.variableNames = ["x", "W"], this.outputShape = e.outShape;
    let a = e.padInfo.top, i = e.padInfo.left, p = e.strideHeight, u = e.strideWidth, c = e.dilationHeight, l = e.dilationWidth, m = e.filterHeight, d = e.filterWidth, f = Math.floor(e.inChannels / 4) * 4, h = e.inChannels % 4, g = e.dataFormat === "channelsLast", x = g ? 1 : 2, b = g ? 2 : 3, C = g ? 3 : 1, S = "", k = "";
    o && (n ? S = `float activation(float a) {
          float b = getPreluActivationWeightsAtOutCoords();
          ${o}
        }` : s ? S = `float activation(float a) {
          float b = getLeakyreluAlphaAtOutCoords();
          ${o}
        }` : S = `
          float activation(float x) {
            ${o}
          }
        `, k = "result = activation(result);");
    let _ = t10 ? "result += getBiasAtOutCoords();" : "";
    t10 && this.variableNames.push("bias"), n && this.variableNames.push("preluActivationWeights"), s && this.variableNames.push("leakyreluAlpha"), this.userCode = `
      ${S}

      const ivec2 strides = ivec2(${p}, ${u});
      const ivec2 pads = ivec2(${a}, ${i});

      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords[0];
        int d2 = coords[${C}];

        ivec2 xRCCorner =
            ivec2(coords[${x}], coords[${b}]) * 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 < ${d}; wC++) {
            int xC = xCCorner + wC * ${l};

            if (xC < 0 || xC >= ${e.inWidth}) {
              continue;
            }

            for (int d1 = 0; d1 < ${f}; 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, ${f}) *
                    getW(wR, wC, ${f}, d2);
              } else {
                dotProd +=
                    getX(batch, ${f}, xR, xC) *
                    getW(wR, wC, ${f}, d2);
              }

            } else if (${h === 2}) {
              vec2 wValues = vec2(
                getW(wR, wC, ${f}, d2),
                getW(wR, wC, ${f} + 1, d2)
              );

              if (${g}) {
                vec2 xValues = vec2(
                  getX(batch, xR, xC, ${f}),
                  getX(batch, xR, xC, ${f} + 1)
                );
                dotProd += dot(xValues, wValues);
              } else {
                vec2 xValues = vec2(
                  getX(batch, ${f}, xR, xC),
                  getX(batch, ${f} + 1, xR, xC)
                );
                dotProd += dot(xValues, wValues);
              }

            } else if (${h === 3}) {
              vec3 wValues = vec3(
                getW(wR, wC, ${f}, d2),
                getW(wR, wC, ${f} + 1, d2),
                getW(wR, wC, ${f} + 2, d2)
              );

              if (${g}) {
                vec3 xValues = vec3(
                  getX(batch, xR, xC, ${f}),
                  getX(batch, xR, xC, ${f} + 1),
                  getX(batch, xR, xC, ${f} + 2)
                );
                dotProd += dot(xValues, wValues);
              } else {
                vec3 xValues = vec3(
                  getX(batch, ${f}, xR, xC),
                  getX(batch, ${f} + 1, xR, xC),
                  getX(batch, ${f} + 2, xR, xC)
                );
                dotProd += dot(xValues, wValues);
              }

            }
          }
        }

        float result = dotProd;
        ${_}
        ${k}
        setOutput(result);
      }
    `;
  }
};
var Mh = class {
  constructor(e) {
    this.variableNames = ["x", "W"], this.outputShape = e.outShape;
    let t10 = e.padInfo.front, o = e.padInfo.top, n = e.padInfo.left, s = e.strideDepth, a = e.strideHeight, i = e.strideWidth, p = e.dilationDepth, u = e.dilationHeight, c = e.dilationWidth, l = e.filterDepth, m = e.filterHeight, d = e.filterWidth, f = Math.floor(e.inChannels / 4) * 4, h = e.inChannels % 4;
    this.userCode = `
      const ivec3 strides = ivec3(${s}, ${a}, ${i});
      const ivec3 pads = ivec3(${t10}, ${o}, ${n});

      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 < ${l}; wF++) {
          int xF = xFCorner + wF * ${p};

          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 < ${d}; wC++) {
              int xC = xCCorner + wC * ${c};

              if (xC < 0 || xC >= ${e.inWidth}) {
                continue;
              }

              for (int d1 = 0; d1 < ${f}; 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, ${f}) *
                  getW(wF, wR, wC, ${f}, d2);
              } else if (${h === 2}) {
                vec2 xValues = vec2(
                  getX(batch, xF, xR, xC, ${f}),
                  getX(batch, xF, xR, xC, ${f} + 1)
                );
                vec2 wValues = vec2(
                  getW(wF, wR, wC, ${f}, d2),
                  getW(wF, wR, wC, ${f} + 1, d2)
                );
                dotProd += dot(xValues, wValues);
              } else if (${h === 3}) {
                vec3 xValues = vec3(
                  getX(batch, xF, xR, xC, ${f}),
                  getX(batch, xF, xR, xC, ${f} + 1),
                  getX(batch, xF, xR, xC, ${f} + 2)
                );
                vec3 wValues = vec3(
                  getW(wF, wR, wC, ${f}, d2),
                  getW(wF, wR, wC, ${f} + 1, d2),
                  getW(wF, wR, wC, ${f} + 2, d2)
                );
                dotProd += dot(xValues, wValues);
              }
            }
          }
        }
        setOutput(dotProd);
      }
    `;
  }
};
var Uc = class {
  constructor(e, t10 = false, o = null, n = 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 = ut(this.outputShape.length);
    let a = e.padInfo.left, i = e.strideWidth, p = e.dilationWidth, u = e.filterHeight, c = e.filterWidth, l = c, m = `
       int xR; int xC; int xCOffset;
       vec4 wTexel; vec4 previous; vec4 final;`;
    for (let g = 0; g < c; g++) m += `
           vec4 xTexelC${g * 2};
           int xTexelC${g * 2}Ready;
           vec4 xTexelC${g * 2 + 1};
           int xTexelC${g * 2 + 1}Ready;
           vec4 xC${g};`;
    m += `
     for (int r = 0; r < ${u}; r++) {
      for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {
       `;
    for (let g = 0; g < c; g++) m += `
           xTexelC${g * 2} = vec4(0.0);
           xTexelC${g * 2}Ready = 0;
           xTexelC${g * 2 + 1} = vec4(0.0);
           xTexelC${g * 2 + 1}Ready = 0;
           xC${g} = vec4(0.0);`;
    m += `
         xR = xRCorner + r * dilations[0];
         if (xR >=0 && xR < inDims[0]) {
       `;
    for (let g = 0; g < (l + 1) / 2; g++) {
      let x = g * 2;
      if (m += `
           xC = xCCorner + ${x * p};
           `, i === 1) {
        if (x < c && (a % 2 === 1 ? (m += `
                 xCOffset = xC + 1;
                 if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {
                   xTexelC${x} = 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${x}.zw = vec2(0.0);
                   }
                   xTexelC${x}Ready = 1;
                 }
               `, p === 1 && x > 0 ? m += `
                 xC${x} = vec4(xTexelC${x - 2}.zw, xTexelC${x}.xy);
                 ` : m += `
                   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${x} = vec4(previous.zw, xTexelC${x}.xy);
                   } else {
                     xC${x} = vec4(0.0, 0.0, xTexelC${x}.xy);
                   }
                   `) : m += `
                 if (xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {
                   xTexelC${x} = getX(batch, xR, xC, d1);
                   if (xC + 1 >= inDims[1]) {
                     xTexelC${x}.zw = vec2(0.0);
                   }
                   xTexelC${x}Ready = 1;
                 }

                 xC${x} = xTexelC${x};
                 `, x + 1 < c)) {
          let b = a % 2 === 0 ? y.nearestLargerEven(p) : p;
          p % 2 === 0 && a % 2 === 1 || p % 2 !== 0 && a % 2 !== 1 ? (m += `
                   xCOffset = xC + imod(pads[1], 2) + ${b};

                   if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x + 1}Ready == 0) {
                     xTexelC${x + 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${x + 1}.zw = vec2(0.0);
                     }
                     xTexelC${x + 1}Ready = 1;
                   }
                   `, p > 1 ? m += `
                     xCOffset -= 2;
                     if (xCOffset >= 0 && xCOffset < inDims[1]) {
                      previous = getX(batch, xR, xCOffset, d1);
                      xC${x + 1} = vec4(previous.zw, xTexelC${x + 1}.xy);
                     } else {
                      xC${x + 1} = vec4(0.0, 0.0, xTexelC${x + 1}.xy);
                     }
                     ` : m += `
                     xC${x + 1} = vec4(xTexelC${x}.zw, xTexelC${x + 1}.xy);
                     `) : b === 1 ? m += `
                     xC${x + 1} = xTexelC${x};
                     ` : m += `
                     xCOffset = xC + ${b};

                     if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x + 1}Ready == 0) {
                       xTexelC${x + 1} = getX(batch, xR, xCOffset, d1);
                       if (xCOffset + 1 >= inDims[1]) {
                         xTexelC${x + 1}.zw = vec2(0.0);
                       }
                       xTexelC${x + 1}Ready = 1;
                     }

                     xC${x + 1} = xTexelC${x + 1};
                     `;
        }
      } else x < c && (a % 2 === 1 ? (m += `
                 xCOffset = xC + 1 - strides[1];
                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {
                   xTexelC${x} = 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${x}.zw = vec2(0.0);
                   }
                   xTexelC${x}Ready = 1;
                 }

                 if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${x + 1}Ready == 0) {
                   xTexelC${x + 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${x + 1}.zw = vec2(0.0);
                   }
                   xTexelC${x + 1}Ready = 1;
                 }

                 xC${x} = vec4(xTexelC${x}.zw, xTexelC${x + 1}.zw);
               `, x + 1 < c && (m += `
                   final = vec4(0.0);
                   xCOffset = xC + 1 + strides[1];
                   if(xCOffset >= 0 && xCOffset < inDims[1]) {
                     final = getX(batch, xR, xCOffset, d1);
                   }
                   xC${x + 1} = vec4(xTexelC${x + 1}.xy, final.xy);
                 `)) : (m += `
                 if(xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {
                   xTexelC${x} = getX(batch, xR, xC, d1);
                   if (xC + 1 >= inDims[1]) {
                     xTexelC${x}.zw = vec2(0.0);
                   }
                   xTexelC${x}Ready = 1;
                 }

                 xCOffset = xC + strides[1];
                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x + 1}Ready == 0) {
                   xTexelC${x + 1} = getX(batch, xR, xCOffset, d1);
                   if (xCOffset + 1 >= inDims[1]) {
                     xTexelC${x + 1}.zw = vec2(0.);
                   }
                   xTexelC${x + 1}Ready = 1;
                 }

                 xC${x} = vec4(
                   xTexelC${x}.xy, xTexelC${x + 1}.xy);
               `, x + 1 < c && (m += `
                   xC${x + 1} = vec4(xTexelC${x}.zw, xTexelC${x + 1}.zw);
                 `)));
      x < c && (m += `
             wTexel = getW(r, ${x}, d1, d2);
             dotProd += xC${x}.xxzz * vec4(wTexel.xy, wTexel.xy);
             if(d1 + 1 < ${e.inChannels}) {
               dotProd += xC${x}.yyww * vec4(wTexel.zw, wTexel.zw);
             }
           `, x + 1 < c && (m += `
               wTexel = getW(r, ${x + 1}, d1, d2);
               dotProd += xC${x + 1}.xxzz * vec4(wTexel.xy, wTexel.xy);
               if(d1 + 1 < ${e.inChannels}) {
                 dotProd += xC${x + 1}.yyww * vec4(wTexel.zw, wTexel.zw);
               }
             `));
    }
    m += `
     }
   `, m += `
     }
   `, m += `
     }
   `;
    let d = "", f = "";
    o && (n ? d = `vec4 activation(vec4 a) {
           vec4 b = getPreluActivationWeightsAtOutCoords();
           ${o}
         }` : s ? d = `vec4 activation(vec4 a) {
           vec4 b = getLeakyreluAlphaAtOutCoords();
           ${o}
         }` : d = `vec4 activation(vec4 x) {
           ${o}
         }`, f = "result = activation(result);");
    let h = t10 ? "result += getBiasAtOutCoords();" : "";
    t10 && this.variableNames.push("bias"), n && 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 xRCorner = xRCCorner.x;
         int xCCorner = xRCCorner.y;

         //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
         vec4 dotProd = vec4(0.000000000000001);

         ${m}

         vec4 result = dotProd - vec4(0.000000000000001);
         ${h}
         ${f}
         setOutput(result);
       }
     `;
  }
};
var Lh = class {
  constructor(e, t10) {
    this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "inputShape", type: "ivec4" }, { 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 = ut(this.outputShape.length);
    let { dataFormat: o } = t10, n = It(), s = o === "channelsLast", a = s ? 1 : 2, i = s ? 2 : 3, p = this.enableShapeUniforms ? "if(blockIndex < outShape[2] && pos < outShape[1]) {" : `if(blockIndex < ${e[2]} && pos < ${e[1]}) {`, u = "";
    for (let c = 0; c <= 1; c++) for (let l = 0; l <= 1; l++) u += `
          blockIndex = rc.z + ${l};
          pos = rc.y + ${c};

          ${p}
            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 + l}] = getChannel(
                    getA(rc.x, d0, int(innerDims.x),
                    int(innerDims.y)), innerDims);
                } else {
                  innerDims = vec2(d0, d1);
                  result[${c * 2 + l}] = getChannel(
                    getA(rc.x, ch, int(innerDims.x),
                    int(innerDims.y)), innerDims);
                }
              }
            }
          }
        `;
    this.userCode = `
      void main() {
        ivec3 rc = getOutputCoords();

        vec4 result = vec4(0);

        int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
        vec2 innerDims;

        ${u}

        ${n.output} = result;
      }
    `;
  }
};
function Bh(r15, e) {
  let t10 = r15.length;
  return t10 >= 3 ? e ? [...r15.slice(0, -3), r15[t10 - 3] * r15[t10 - 2], r15[t10 - 1]] : [...r15.slice(0, -3), r15[t10 - 3], r15[t10 - 2] * r15[t10 - 1]] : !e && t10 === 1 && r15[0] > 1 ? [r15[0], 1] : null;
}
function zh({ x: r15, filter: e, convInfo: t10, backend: o, bias: n = null, preluActivationWeights: s = null, leakyreluAlpha: a = 0, activation: i = null }) {
  let p = r15.shape, u = o.texData.get(r15.dataId), c = t10.inChannels, l = p[0] * p[1] * p[2], m = t10.outChannels, d = t10.dataFormat === "channelsLast", f = false, h = false, g, x = [];
  if (s != null) {
    let S = Bh(s.shape, d);
    S != null && (s = te({ inputs: { x: s }, backend: o, attrs: { shape: S } }), x.push(s));
  }
  if (n != null) {
    let S = Bh(n.shape, d);
    S != null && (n = te({ inputs: { x: n }, backend: o, attrs: { shape: S } }), x.push(n));
  }
  if (!((l === 1 || m === 1) && c > Cv) && u.isPacked && d && u.texture != null && p[2] % 2 !== 0 && y.arraysEqual(u.shape.slice(-3), p.slice(-3))) {
    let S = p[0] * p[1] * (p[2] + 1), k = { dataId: r15.dataId, shape: [1, S, t10.inChannels], dtype: r15.dtype }, _ = u.shape;
    u.shape = u.shape.slice(), u.shape[u.shape.length - 2]++, y.assert(xu(u.shape, k.shape), () => `packed reshape ${u.shape} to ${k.shape} isn't free`);
    let $ = te({ inputs: { x: e }, backend: o, attrs: { shape: [1, t10.inChannels, t10.outChannels] } });
    x.push($);
    let R = Sp({ a: k, b: $, backend: o, transposeA: f, transposeB: h, bias: n, activation: i, preluActivationWeights: s, leakyreluAlpha: a }), D = o.texData.get(R.dataId);
    y.assert(D.isPacked, () => "batchMatMul result is expected to be packed"), u.shape = _, D.shape = t10.outShape, g = Dt({ inputs: { x: R }, backend: o }), g.shape = t10.outShape, x.push(R);
  } else {
    let S = t10.outHeight * t10.outWidth, k = te({ inputs: { x: r15 }, backend: o, attrs: { shape: d ? [t10.batchSize, S, t10.inChannels] : [t10.batchSize, t10.inChannels, S] } }), _ = te({ inputs: { x: e }, backend: o, attrs: { shape: [1, t10.inChannels, t10.outChannels] } }), $ = Sp({ a: d ? k : _, b: d ? _ : k, transposeA: !d, transposeB: h, backend: o, bias: n, activation: i, preluActivationWeights: s, leakyreluAlpha: a });
    g = te({ inputs: { x: $ }, backend: o, attrs: { shape: t10.outShape } }), x.push(k), x.push(_), x.push($);
  }
  for (let S of x) o.disposeIntermediateTensorInfo(S);
  return g;
}
function Vh({ x: r15, filter: e, convInfo: t10, backend: o, bias: n = null, preluActivationWeights: s = null, leakyreluAlpha: a = 0, activation: i = null }) {
  let { filterWidth: p, filterHeight: u, inChannels: c, outWidth: l, outHeight: m, dataFormat: d } = t10, f = d === "channelsLast", h = p * u * c, g = m * l, x = [t10.batchSize, h, g], b = true, C = false, S = [];
  if (s != null) {
    let q = Bh(s.shape, f);
    q != null && (s = te({ inputs: { x: s }, backend: o, attrs: { shape: q } }), S.push(s));
  }
  if (n != null) {
    let q = Bh(n.shape, f);
    q != null && (n = te({ inputs: { x: n }, backend: o, attrs: { shape: q } }), S.push(n));
  }
  let k = te({ inputs: { x: e }, backend: o, attrs: { shape: [1, h, y.sizeFromShape(e.shape) / h] } });
  S.push(k);
  let _ = new Lh(x, t10), $ = [r15.shape, [t10.padInfo.top, t10.padInfo.left], [t10.strideHeight, t10.strideWidth], [t10.dilationHeight, t10.dilationWidth], [t10.inChannels], [t10.filterWidth * t10.inChannels], [t10.outWidth]], R = o.runWebGLProgram(_, [r15], "float32", $), D = te({ inputs: { x: R }, backend: o, attrs: { shape: x } });
  S.push(R), S.push(D);
  let P = n != null, O = s != null, M = i === "leakyrelu", L = i ? yi(i, true) : null, B = new zc(f ? D.shape : k.shape, f ? k.shape : D.shape, f ? [t10.batchSize, g, t10.outChannels] : [t10.batchSize, t10.outChannels, g], b, C, P, L, O, M), z = f ? [D, k] : [k, D];
  if (n && z.push(n), O && z.push(s), M) {
    let q = o.makeTensorInfo([], "float32", y.createScalarValue(a, "float32"));
    z.push(q), S.push(q);
  }
  let U = o.runWebGLProgram(B, z, "float32"), j = te({ inputs: { x: U }, backend: o, attrs: { shape: t10.outShape } });
  S.push(U);
  for (let q of S) o.disposeIntermediateTensorInfo(q);
  return j;
}
function iJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s } = e, { strides: a, pad: i, dataFormat: p, dilations: u, dimRoundingMode: c } = o, l = w.convertConv2DDataFormat(p), m = w.computeConv2DInfo(n.shape, s.shape, a, u, i, c, false, l), d;
  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")) d = zh({ x: n, filter: s, convInfo: m, backend: t10 });
  else if (m.strideWidth <= 2 && l === "channelsLast" && A().getBool("WEBGL_EXP_CONV")) {
    let h = new Uc(m), g = [[m.padInfo.top, m.padInfo.left], [m.strideHeight, m.strideWidth], [m.dilationHeight, m.dilationWidth], [m.inHeight, m.inWidth]];
    d = t10.runWebGLProgram(h, [n, s], "float32", g);
  } else if (A().getBool("WEBGL_CONV_IM2COL")) d = Vh({ x: n, filter: s, convInfo: m, backend: t10 });
  else {
    let h = new Wc(m);
    d = t10.runWebGLProgram(h, [n, s], "float32");
  }
  let f = te({ inputs: { x: d }, backend: t10, attrs: { shape: m.outShape } });
  return t10.disposeIntermediateTensorInfo(d), f;
}
var UA = { kernelName: tn, backendName: "webgl", kernelFunc: iJ };
var Wh = class {
  constructor(e) {
    this.variableNames = ["x", "dy"], this.outputShape = e.filterShape;
    let t10 = e.strideHeight, o = e.strideWidth, n = 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 * ${t10} - ${n};

            if (xR < 0 || xR >= ${e.inHeight}) {
              continue;
            }

            for (int yC = 0; yC < ${e.outWidth}; yC++) {
              int xC = wC + yC * ${o} - ${s};

              if (xC < 0 || xC >= ${e.inWidth}) {
                continue;
              }

              ${a ? `float dyValue = getDy(b, yR, yC, d2);
              float xValue = getX(b, xR, xC, d1);
              dotProd += (xValue * dyValue);` : `float dyValue = getDy(b, d2, yR, yC);
              float xValue = getX(b, d1, xR, xC);
              dotProd += (xValue * dyValue);`}
            }
          }
        }
        setOutput(dotProd);
      }
    `;
  }
};
var Uh = class {
  constructor(e) {
    this.variableNames = ["dy", "W"], this.outputShape = e.inShape;
    let t10 = e.filterHeight, o = e.filterWidth, n = e.strideHeight, s = e.strideWidth, a = e.dataFormat === "channelsLast", i = t10 - 1 - e.padInfo.top, p = o - 1 - e.padInfo.left, u = a ? 1 : 2, c = a ? 2 : 3, l = a ? 3 : 1;
    this.userCode = `
      const ivec2 pads = ivec2(${i}, ${p});

      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords[0];
        int d1 = coords[${l}];

        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 < ${t10}; wR++) {
          float dyR = float(dyRCorner + wR) / ${n}.0;

          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
            continue;
          }
          int idyR = int(dyR);

          int wRPerm = ${t10} - 1 - wR;

          for (int wC = 0; wC < ${o}; 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 = ${o} - 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 Gh = class {
  constructor(e) {
    this.variableNames = ["x", "dy"], this.outputShape = e.filterShape;
    let t10 = e.strideDepth, o = e.strideHeight, n = 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 * ${t10} - ${s};

            if (xF < 0 || xF >= ${e.inDepth}) {
              continue;
            }

            for (int yR = 0; yR < ${e.outHeight}; yR++) {
              int xR = wR + yR * ${o} - ${a};

              if (xR < 0 || xR >= ${e.inHeight}) {
                continue;
              }

              for (int yC = 0; yC < ${e.outWidth}; yC++) {
                int xC = wC + yC * ${n} - ${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 Hh = class {
  constructor(e) {
    this.variableNames = ["dy", "W"], this.outputShape = e.inShape;
    let t10 = e.filterDepth, o = e.filterHeight, n = e.filterWidth, s = e.strideDepth, a = e.strideHeight, i = e.strideWidth, p = t10 - 1 - e.padInfo.front, u = o - 1 - e.padInfo.top, c = n - 1 - e.padInfo.left;
    this.userCode = `
      const ivec3 pads = ivec3(${p}, ${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 < ${t10}; 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 = ${t10} - 1 - wF;

          for (int wR = 0; wR < ${o}; 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 = ${o} - 1 - wR;

            for (int wC = 0; wC < ${n}; 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 = ${n} - 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 uJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, dy: s } = e, { strides: a, pad: i, dataFormat: p, dimRoundingMode: u, filterShape: c } = o, l = w.convertConv2DDataFormat(p), m = w.computeConv2DInfo(n.shape, c, a, 1, i, u, false, l), d = new Wh(m);
  return t10.runWebGLProgram(d, [n, s], "float32");
}
var GA = { kernelName: Fi, backendName: "webgl", kernelFunc: uJ };
var Kh = class {
  constructor(e) {
    this.variableNames = ["dy", "W"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "strides", type: "vec2" }], this.outputShape = e.inShape, this.enableShapeUniforms = ut(this.outputShape.length);
    let t10 = e.filterHeight, o = e.filterWidth, n = t10 - 1 - e.padInfo.top, s = o - 1 - e.padInfo.left;
    this.userCode = `
      const ivec2 pads = ivec2(${n}, ${s});

      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords[0];
        int d1 = coords[3];

        ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;
        int dyRCorner = dyCorner.x;
        int dyCCorner = dyCorner.y;

        vec4 result = vec4(0.);
        for (int wR = 0; wR < ${t10}; wR++) {
          float dyR = float(dyRCorner + wR) / strides[0];
          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
            continue;
          }
          int idyR = int(dyR);
          int wRPerm = ${t10} - 1 - wR;

          for (int wC = 0; wC < ${o}; wC++) {
            int wCPerm = ${o} - 1 - wC;

            float dyC = float(dyCCorner + wC) / strides[1];
            bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0)
              && (fract(dyC) == 0.0);
            int idyC = int(dyC);

            float dyC2 = float(dyCCorner + wC + 1) / strides[1];
            bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0)
              && (fract(dyC2) == 0.0);
            int idyC2 = int(dyC2);

            if (idyCVal && idyCVal2) {
              for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
                vec4 dySample = getDy(batch, idyR, idyC, d2);
                vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?
                  dySample : getDy(batch, idyR, idyC2, d2);

                vec2 dyValue = mod(float(idyC), 2.) == 0. ?
                  dySample.xy : dySample.zw;
                result.xy += vec2(dot(dyValue, wValue.xy),
                  dot(dyValue, wValue.zw));

                dyValue = mod(float(idyC2), 2.) == 0. ?
                  dySample2.xy : dySample2.zw;
                result.zw += vec2(dot(dyValue, wValue.xy),
                  dot(dyValue, wValue.zw));
              }
            } else if (idyCVal) {
              for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
                vec4 dySample = getDy(batch, idyR, idyC, d2);
                vec2 dyValue = mod(float(idyC), 2.) == 0. ?
                  dySample.xy : dySample.zw;
                result.xy += vec2(dot(dyValue, wValue.xy),
                  dot(dyValue, wValue.zw));
              }
            } else if (idyCVal2) {
              for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
                vec4 dySample = getDy(batch, idyR, idyC2, d2);
                vec2 dyValue = mod(float(idyC2), 2.) == 0. ?
                  dySample.xy : dySample.zw;
                result.zw += vec2(dot(dyValue, wValue.xy),
                  dot(dyValue, wValue.zw));
              }
            }
          }
        }
        setOutput(result);
      }
    `;
  }
};
function pJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, filter: s } = e, { inputShape: a, strides: i, pad: p, dataFormat: u, dimRoundingMode: c } = o, l = w.convertConv2DDataFormat(u), m = w.computeConv2DInfo(a, s.shape, i, 1, p, c, false, l);
  if (A().getBool("WEBGL_PACK_CONV2DTRANSPOSE") && l === "channelsLast") {
    let d = [[m.strideHeight, m.strideWidth]], f = new Kh(m);
    return t10.runWebGLProgram(f, [n, s], "float32", d);
  } else {
    let d = new Uh(m);
    return t10.runWebGLProgram(d, [n, s], "float32");
  }
}
var HA = { kernelName: rn, backendName: "webgl", kernelFunc: pJ };
function cJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s } = e, { strides: a, pad: i, dilations: p } = o, u = w.computeConv3DInfo(n.shape, s.shape, a, p, i), c = new Mh(u);
  return t10.runWebGLProgram(c, [n, s], "float32");
}
var KA = { kernelName: on, backendName: "webgl", kernelFunc: cJ };
function lJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, dy: s } = e, { strides: a, pad: i, filterShape: p } = o, u = w.computeConv3DInfo(n.shape, p, a, 1, i), c = new Gh(u);
  return t10.runWebGLProgram(c, [n, s], "float32");
}
var qA = { kernelName: ja, backendName: "webgl", kernelFunc: lJ };
function mJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, filter: s } = e, { pad: a, strides: i, inputShape: p } = o, u = w.computeConv3DInfo(p, s.shape, i, 1, a), c = new Hh(u);
  return t10.runWebGLProgram(c, [n, s], "float32");
}
var jA = { kernelName: nn, backendName: "webgl", kernelFunc: mJ };
var dJ = Fo + `
  return cos(x);
`;
var fJ = `
  vec4 result = cos(x);
  bvec4 isNaN = isnan(x);
  ${Xr}
  return result;
`;
var hJ = xe({ opSnippet: dJ, packedOpSnippet: fJ });
var XA = { kernelName: "Cos", backendName: "webgl", kernelFunc: hJ };
var gJ = `
  float e2x = exp(-x);
  return (e2x + 1.0 / e2x) / 2.0;
`;
var xJ = xe({ opSnippet: gJ });
var YA = { kernelName: an, backendName: "webgl", kernelFunc: xJ };
var qh = class {
  constructor(e, t10, o, n, s) {
    this.variableNames = ["Image", "Boxes", "BoxInd"], this.outputShape = [];
    let [a, i, p, u] = e, [c] = t10, [l, m] = o;
    this.outputShape = [c, l, m, u];
    let d = n === "bilinear" ? 1 : 0, [f, h] = [`${i - 1}.0`, `${p - 1}.0`], [g, x, b] = l > 1 ? [`${(i - 1) / (l - 1)}`, "(y2-y1) * height_ratio", `y1*${f} + float(y)*(height_scale)`] : ["0.0", "0.0", `0.5 * (y1+y2) * ${f}`], [C, S, k] = m > 1 ? [`${(p - 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(${C});
      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 = ${S};

        float in_y = ${b};
        if( in_y < 0.0 || in_y > ${f} ) {
          setOutput(float(${s}));
          return;
        }
        float in_x = ${k};
        if( in_x < 0.0 || in_x > ${h} ) {
          setOutput(float(${s}));
          return;
        }

        vec2 sourceFracIndexCR = vec2(in_x,in_y);
        if(${d} == 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 yJ = (r15) => {
  let { inputs: e, backend: t10, attrs: o } = r15, { image: n, boxes: s, boxInd: a } = e, { cropSize: i, method: p, extrapolationValue: u } = o, c = new qh(n.shape, s.shape, i, p, u);
  return t10.runWebGLProgram(c, [n, s, a], "float32");
};
var QA = { kernelName: cn, backendName: "webgl", kernelFunc: yJ };
var vp;
(function(r15) {
  r15.Prod = "*", r15.Sum = "+";
})(vp || (vp = {}));
var om = class {
  constructor(e, t10, o, n) {
    this.op = e, this.outputShape = t10, this.variableNames = ["x"], this.customUniforms = [{ name: "index", type: "float" }];
    let s = this.outputShape.length, a = this.op === vp.Prod ? "1.0" : "0.0", i = o ? a : `getX(${ZA(s, "coords", this.op)})`, p = this.outputShape[this.outputShape.length - 1], u = "", c = "";
    o ? (u = n ? `end != ${p - 1}` : "end != 0", c = n ? "end + 1" : "end - 1") : (u = n ? `end + pow2 < ${p}` : "end >= pow2", c = n ? "end + pow2" : "end - pow2"), this.userCode = `
      void main() {
        ${Re(s)} coords = getOutputCoords();
        int end = ${JA(s, "coords", this.op)};
        float val = ${i};
        int pow2 = int(pow(2.0, index));
        if (${u}) {
          int idx = ${c};
          ${JA(s, "coords", this.op)} = idx;
          val ${this.op}= getX(${ZA(s, "coords", this.op)});
        }
        setOutput(val);
      }
    `;
  }
};
function ZA(r15, e, t10) {
  if (r15 === 1) return `${e}`;
  if (r15 === 2) return `${e}.x, ${e}.y`;
  if (r15 === 3) return `${e}.x, ${e}.y, ${e}.z`;
  if (r15 === 4) return `${e}.x, ${e}.y, ${e}.z, ${e}.w`;
  throw new Error(`Cumulative ${t10} for rank ${r15} is not yet supported`);
}
function JA(r15, e, t10) {
  if (r15 === 1) return `${e}`;
  if (r15 === 2) return `${e}.y`;
  if (r15 === 3) return `${e}.z`;
  if (r15 === 4) return `${e}.w`;
  throw new Error(`Cumulative ${t10} for rank ${r15} is not yet supported`);
}
function jh(r15, e, t10, o, n, s) {
  let a = e.shape.length, i = w.getAxesPermutation([o], a), p = e;
  i != null && (p = bt({ inputs: { x: e }, backend: t10, attrs: { perm: i } }));
  let u = w.getInnerMostAxes(1, a)[0];
  if (u !== a - 1) throw new Error(`WebGL cumprod shader expects an inner-most axis=${e.shape.length - 1} but got axis=${o}`);
  let c = p.shape[u], l = Dt({ inputs: { x: p }, backend: t10 });
  for (let m = 0; m <= Math.ceil(Math.log2(c)) - 1; m++) {
    let d = new om(r15, p.shape, false, s), f = [[m]], h = l;
    l = t10.runWebGLProgram(d, [l], l.dtype, f), t10.disposeIntermediateTensorInfo(h);
  }
  if (n) {
    let m = new om(r15, p.shape, n, s), d = l;
    l = t10.runWebGLProgram(m, [l], l.dtype), t10.disposeIntermediateTensorInfo(d);
  }
  if (i != null) {
    let m = w.getUndoAxesPermutation(i), d = bt({ inputs: { x: l }, backend: t10, attrs: { perm: m } });
    return t10.disposeIntermediateTensorInfo(l), t10.disposeIntermediateTensorInfo(p), d;
  }
  return l;
}
function bJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, exclusive: a, reverse: i } = o;
  return jh(vp.Prod, n, t10, s, a, i);
}
var eF = { kernelName: un, backendName: "webgl", kernelFunc: bJ };
function CJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, exclusive: a, reverse: i } = o;
  return jh(vp.Sum, n, t10, s, a, i);
}
var tF = { kernelName: pn, backendName: "webgl", kernelFunc: CJ };
function wJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, weights: s } = e, { size: a, binaryOutput: i } = o;
  if (n.shape.length === 1) {
    let p = t10.readSync(n.dataId), u = t10.readSync(s.dataId), c = ph(p, u, s.dtype, s.shape, a);
    return t10.makeTensorInfo([a], s.dtype, c);
  } else if (n.shape.length === 2) {
    let p = t10.bufferSync(n), u = t10.bufferSync(s), c = BR(p, u, a, i);
    return t10.makeTensorInfo(c.shape, s.dtype, c.values);
  }
  throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${n.shape.length}.`);
}
var rF = { kernelName: ra, backendName: "webgl", kernelFunc: wJ };
var Xh = class {
  constructor(e, t10, o) {
    this.variableNames = ["x"], this.outputShape = [], this.outputShape = e, this.blockSize = t10, this.dataFormat = o, 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 / ${t10};
      int offset_h = imod(h, ${t10});
      int in_w = w / ${t10};
      int offset_w = imod(w, ${t10});
      int offset_d = (offset_h * ${t10} + 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 SJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { blockSize: s, dataFormat: a } = o, i = n.shape[0], p = a === "NHWC" ? n.shape[1] : n.shape[2], u = a === "NHWC" ? n.shape[2] : n.shape[3], c = a === "NHWC" ? n.shape[3] : n.shape[1], l = p * s, m = u * s, d = c / (s * s), f = a === "NHWC" ? [i, l, m, d] : [i, d, l, m], h = new Xh(f, s, a);
  return t10.runWebGLProgram(h, [n], n.dtype);
}
var oF = { kernelName: ln, backendName: "webgl", kernelFunc: SJ };
var Gc = class {
  constructor(e, t10 = false, o = null, n = 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 = ut(this.outputShape.length);
    let a = e.filterHeight, i = e.filterWidth, p = e.outChannels / e.inChannels, u = "", c = "";
    o && (n ? u = `float activation(float a) {
          float b = getPreluActivationWeightsAtOutCoords();
          ${o}
        }` : s ? u = `float activation(float a) {
          float b = getLeakyreluAlphaAtOutCoords();
          ${o}
        }` : u = `
          float activation(float x) {
            ${o}
          }
        `, c = "result = activation(result);");
    let l = t10 ? "result += getBiasAtOutCoords();" : "";
    t10 && this.variableNames.push("bias"), n && 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 / ${p};
        int q = d2 - d1 * ${p};

        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;
        ${l}
        ${c}
        setOutput(result);
      }
    `;
  }
};
var Hc = class {
  constructor(e, t10 = false, o = null, n = 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 = ut(this.outputShape.length);
    let a = e.outChannels / e.inChannels, i = e.padInfo.left, p = e.strideWidth, u = e.dilationWidth, c = e.filterHeight, l = e.filterWidth, m = l, d = `
      int xR; int xC; int xCOffset;
      vec4 wTexel; vec4 previous; vec4 final;`;
    for (let x = 0; x < l; x++) d += `
          vec4 xTexelC${x * 2};
          int xTexelC${x * 2}Ready;
          vec4 xTexelC${x * 2 + 1};
          int xTexelC${x * 2 + 1}Ready;
          vec4 xC${x};`;
    d += `
    for (int r = 0; r < ${c}; r++) {
      `;
    for (let x = 0; x < l; x++) d += `
          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);`;
    d += `
        xR = xRCorner + r * dilations[0];
        if (xR >=0 && xR < inDims[0]) {
      `;
    for (let x = 0; x < (m + 1) / 2; x++) {
      let b = x * 2;
      if (d += `
          xC = xCCorner + ${b * u};
          `, p === 1) {
        if (b < l && (i % 2 === 1 ? (d += `
                xCOffset = xC + 1;
                if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
                  xTexelC${b} = 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${b}.zw = vec2(0.0);
                  }
                  xTexelC${b}Ready = 1;
                }
              `, u === 1 && b > 0 ? d += `
                xC${b} = vec4(xTexelC${b - 2}.zw, xTexelC${b}.xy);
                ` : d += `
                  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${b} = vec4(previous.zw, xTexelC${b}.xy);
                  } else {
                    xC${b} = vec4(0.0, 0.0, xTexelC${b}.xy);
                  }
                  `) : d += `
                if (xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
                  xTexelC${b} = getX(batch, xR, xC, d1);
                  if (xC + 1 >= inDims[1]) {
                    xTexelC${b}.zw = vec2(0.0);
                  }
                  xTexelC${b}Ready = 1;
                }

                xC${b} = xTexelC${b};
                `, b + 1 < l)) {
          let C = i % 2 === 0 ? y.nearestLargerEven(u) : u;
          u % 2 === 0 && i % 2 === 1 || u % 2 !== 0 && i % 2 !== 1 ? (d += `
                  xCOffset = xC + imod(pads[1], 2) + ${C};

                  if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b + 1}Ready == 0) {
                    xTexelC${b + 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${b + 1}.zw = vec2(0.0);
                    }
                    xTexelC${b + 1}Ready = 1;
                  }
                  `, u > 1 ? d += `
                    xCOffset -= 2;
                    if (xCOffset >= 0 && xCOffset < inDims[1]) {
                     previous = getX(batch, xR, xCOffset, d1);
                     xC${b + 1} = vec4(previous.zw, xTexelC${b + 1}.xy);
                    } else {
                     xC${b + 1} = vec4(0.0, 0.0, xTexelC${b + 1}.xy);
                    }
                    ` : d += `
                    xC${b + 1} = vec4(xTexelC${b}.zw, xTexelC${b + 1}.xy);
                    `) : C === 1 ? d += `
                    xC${b + 1} = xTexelC${b};
                    ` : d += `
                    xCOffset = xC + ${C};

                    if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b + 1}Ready == 0) {
                      xTexelC${b + 1} = getX(batch, xR, xCOffset, d1);
                      if (xCOffset + 1 >= inDims[1]) {
                        xTexelC${b + 1}.zw = vec2(0.0);
                      }
                      xTexelC${b + 1}Ready = 1;
                    }

                    xC${b + 1} = xTexelC${b + 1};
                    `;
        }
      } else b < l && (i % 2 === 1 ? (d += `
                xCOffset = xC + 1 - strides[1];
                if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
                  xTexelC${b} = 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${b}.zw = vec2(0.0);
                  }
                  xTexelC${b}Ready = 1;
                }

                if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${b + 1}Ready == 0) {
                  xTexelC${b + 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${b + 1}.zw = vec2(0.0);
                  }
                  xTexelC${b + 1}Ready = 1;
                }

                xC${b} = vec4(xTexelC${b}.zw, xTexelC${b + 1}.zw);
              `, b + 1 < l && (d += `
                  final = vec4(0.0);
                  xCOffset = xC + 1 + strides[1];
                  if(xCOffset >= 0 && xCOffset < inDims[1]) {
                    final = getX(batch, xR, xCOffset, d1);
                  }
                  xC${b + 1} = vec4(xTexelC${b + 1}.xy, final.xy);
                `)) : (d += `
                if(xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
                  xTexelC${b} = getX(batch, xR, xC, d1);
                  if (xC + 1 >= inDims[1]) {
                    xTexelC${b}.zw = vec2(0.0);
                  }
                  xTexelC${b}Ready = 1;
                }

                xCOffset = xC + strides[1];
                if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b + 1}Ready == 0) {
                  xTexelC${b + 1} = getX(batch, xR, xCOffset, d1);
                  if (xCOffset + 1 >= inDims[1]) {
                    xTexelC${b + 1}.zw = vec2(0.);
                  }
                  xTexelC${b + 1}Ready = 1;
                }

                xC${b} = vec4(
                  xTexelC${b}.xy, xTexelC${b + 1}.xy);
              `, b + 1 < l && (d += `
                  xC${b + 1} = vec4(xTexelC${b}.zw, xTexelC${b + 1}.zw);
                `)));
      b < l && (d += `
            wTexel = getW(r, ${b}, d1, q);
            dotProd += xC${b} * vec4(wTexel.xz, wTexel.xz);
          `, b + 1 < l && (d += `
              wTexel = getW(r, ${b + 1}, d1, q);
              dotProd += xC${b + 1} * vec4(wTexel.xz, wTexel.xz);
            `));
    }
    d += `
    }
  `, d += `
      }
    `;
    let f = "", h = "";
    o && (n ? f = `vec4 activation(vec4 a) {
          vec4 b = getPreluActivationWeightsAtOutCoords();
          ${o}
        }` : s ? f = `vec4 activation(vec4 a) {
          vec4 b = getLeakyreluAlphaAtOutCoords();
          ${o}
        }` : f = `vec4 activation(vec4 x) {
          ${o}
        }`, h = "result = activation(result);");
    let g = t10 ? "result += getBiasAtOutCoords();" : "";
    t10 && this.variableNames.push("bias"), n && this.variableNames.push("preluActivationWeights"), s && this.variableNames.push("leakyreluAlpha"), this.userCode = `
      ${f}

      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);

        ${d}

        vec4 result = dotProd - vec4(0.000000000000001);
        ${g}
        ${h}
        setOutput(result);
      }
    `;
  }
};
function IJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s } = e, { strides: a, pad: i, dilations: p, dimRoundingMode: u } = o, c = p;
  c == null && (c = [1, 1]), y.assert(w.eitherStridesOrDilationsAreOne(a, c), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${c}'`);
  let l = w.computeConv2DInfo(n.shape, s.shape, a, c, i, u, true), m;
  A().getBool("WEBGL_PACK_DEPTHWISECONV") && l.strideWidth <= 2 && l.outChannels / l.inChannels === 1 ? m = new Hc(l) : m = new Gc(l);
  let d = [[l.padInfo.top, l.padInfo.left], [l.strideHeight, l.strideWidth], [l.dilationHeight, l.dilationWidth], [l.inHeight, l.inWidth]];
  return t10.runWebGLProgram(m, [n, s], "float32", d);
}
var nF = { kernelName: mn, backendName: "webgl", kernelFunc: IJ };
var Yh = class {
  constructor(e) {
    this.variableNames = ["x", "dy"], this.outputShape = e.filterShape;
    let t10 = e.strideHeight, o = e.strideWidth, n = 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 * ${t10} - ${n};

            if (xR < 0 || xR >= ${e.inHeight}) {
              continue;
            }

            for (int yC = 0; yC < ${e.outWidth}; yC++) {
              int xC = wC + yC * ${o} - ${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 Qh = class {
  constructor(e) {
    this.variableNames = ["dy", "W"], this.outputShape = e.inShape;
    let t10 = e.filterHeight, o = e.filterWidth, n = e.strideHeight, s = e.strideWidth, a = t10 - 1 - e.padInfo.top, i = o - 1 - e.padInfo.left, p = 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 < ${t10}; wR++) {
          float dyR = float(dyRCorner + wR) / ${n}.0;

          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
            continue;
          }
          int idyR = int(dyR);

          int wRPerm = ${t10} - 1 - wR;

          for (int wC = 0; wC < ${o}; 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 = ${o} - 1 - wC;

            // TO DO: Vec4 over the channelMul
            for (int dm = 0; dm < ${p}; dm++) {
              int d2 = d1 * ${p} + dm;
              float xValue = getDy(batch, idyR, idyC, d2);
              float wValue = getW(wRPerm, wCPerm, d1, dm);
              dotProd += xValue * wValue;
            }
          }
        }
        setOutput(dotProd);
      }
    `;
  }
};
function vJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, dy: s } = e, { strides: a, dilations: i, pad: p, dimRoundingMode: u, filterShape: c } = o, l = w.computeConv2DInfo(n.shape, c, a, i, p, u, true), m = new Yh(l);
  return t10.runWebGLProgram(m, [n, s], "float32");
}
var sF = { kernelName: Pi, backendName: "webgl", kernelFunc: vJ };
function kJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, filter: s } = e, { strides: a, dilations: i, pad: p, dimRoundingMode: u, inputShape: c } = o, l = w.computeConv2DInfo(c, s.shape, a, i, p, u, true), m = new Qh(l);
  return t10.runWebGLProgram(m, [n, s], "float32");
}
var aF = { kernelName: Oi, backendName: "webgl", kernelFunc: kJ };
var Zh = 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 NJ(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e, n = [...o.shape, ...o.shape], s = y.sizeFromShape(o.shape), a = te({ inputs: { x: o }, backend: t10, attrs: { shape: [s] } }), i = new Zh(s), p = t10.runWebGLProgram(i, [a], a.dtype), u = te({ inputs: { x: p }, backend: t10, attrs: { shape: n } });
  return t10.disposeIntermediateTensorInfo(a), t10.disposeIntermediateTensorInfo(p), u;
}
var iF = { kernelName: oa, backendName: "webgl", kernelFunc: NJ };
var Jh = class {
  constructor(e) {
    this.variableNames = ["x", "W"], this.outputShape = e.outShape;
    let { inHeight: t10, inWidth: o, padInfo: n, strideHeight: s, strideWidth: a, filterHeight: i, filterWidth: p, dilationHeight: u, dilationWidth: c } = e, { top: l, left: m } = n;
    this.userCode = `
      const ivec2 strides = ivec2(${s}, ${a});
      const ivec2 pads = ivec2(${l}, ${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 < ${t10}) {
            for (int w = 0; w < ${p}; w++) {
              int wIn = wBeg + w * ${c};

              if (wIn >= 0 && wIn < ${o}) {
                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 TJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s } = e, { strides: a, pad: i, dilations: p } = o, u = w.computeDilation2DInfo(n.shape, s.shape, a, i, "NHWC", p), c, l = new Jh(u);
  c = t10.runWebGLProgram(l, [n, s], "float32");
  let m = te({ inputs: { x: c }, backend: t10, attrs: { shape: u.outShape } });
  return t10.disposeIntermediateTensorInfo(c), m;
}
var uF = { kernelName: dn, backendName: "webgl", kernelFunc: TJ };
function _J(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { equation: n } = o, s = e, { allDims: a, summedDims: i, idDims: p } = w.decodeEinsumEquation(n, s.length);
  w.checkEinsumDimSizes(a.length, p, s);
  let { path: u, steps: c } = w.getEinsumComputePath(i, p), l = c.length, m = null, d = a.length, f = [];
  for (let h = 0; h < l; ++h) {
    for (let g of c[h]) {
      let { permutationIndices: x, expandDims: b } = w.getEinsumPermutation(d, p[g]), C;
      w.isIdentityPermutation(x) ? C = s[g] : (C = bt({ inputs: { x: s[g] }, backend: t10, attrs: { perm: x } }), f.push(C));
      let S = C.shape.slice();
      for (let k = 0; k < b.length; ++k) S.splice(b[k], 0, 1);
      y.arraysEqual(C.shape, S) || (C = te({ inputs: { x: C }, backend: t10, attrs: { shape: S } }), f.push(C)), m === null ? m = C : (m = tm({ inputs: { a: C, b: m }, backend: t10 }), f.push(m));
    }
    h < l - 1 && (u[h] >= 0 && (m = wp({ inputs: { x: m }, backend: t10, attrs: { axis: u[h] - (a.length - d), keepDims: false } }), f.push(m)), d--);
  }
  for (let h of f) h !== m && t10.disposeIntermediateTensorInfo(h);
  return m;
}
var pF = { kernelName: Bi, backendName: "webgl", kernelFunc: _J };
var EJ = "return (x >= 0.0) ? x : (exp(x) - 1.0);";
var $J = `
  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 RJ = xe({ opSnippet: EJ, packedOpSnippet: $J });
var cF = { kernelName: "Elu", backendName: "webgl", kernelFunc: RJ };
var DJ = "return (b >= 0.0) ? a : a * (b + 1.0);";
var AJ = `
  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`;
var FJ = (r15) => {
  let { inputs: e, backend: t10 } = r15, { dy: o, y: n } = e, s = A().getBool("WEBGL_PACK_BINARY_OPERATIONS") ? new jr(AJ, o.shape, n.shape) : new Pr(DJ, o.shape, n.shape);
  return t10.runWebGLProgram(s, [o, n], o.dtype);
};
var lF = { kernelName: Xa, backendName: "webgl", kernelFunc: FJ };
var PJ = `
  return vec4(equal(a, b));
`;
var OJ = "return float(a == b);";
var MJ = nt({ opSnippet: OJ, packedOpSnippet: PJ, dtype: "bool", cpuKernelImpl: GR });
var mF = { kernelName: xn, backendName: "webgl", kernelFunc: MJ };
var LJ = `
  // Error function is calculated approximately with elementary function.
  // See "Handbook of Mathematical Functions with Formulas,
  // Graphs, and Mathematical Tables", Abramowitz and Stegun.
  float p = ${w.ERF_P};
  float a1 = ${w.ERF_A1};
  float a2 = ${w.ERF_A2};
  float a3 = ${w.ERF_A3};
  float a4 = ${w.ERF_A4};
  float a5 = ${w.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 BJ = xe({ opSnippet: LJ });
var dF = { kernelName: "Erf", backendName: "webgl", kernelFunc: BJ };
var zJ = Fo + `
  return exp(x);
`;
var VJ = `
  vec4 result = exp(x);
  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 kv = xe({ opSnippet: zJ, packedOpSnippet: VJ, cpuKernelImpl: HR, dtype: "float32" });
var fF = { kernelName: "Exp", backendName: "webgl", kernelFunc: kv };
function eg(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { dim: n } = t10, { input: s } = e, a = s.shape.length, i = s.shape.slice(), p = n;
  return n < 0 && (y.assert(-(a + 1) <= n, () => `Axis must be in the interval [${-(a + 1)}, ${a}]`), p = a + n + 1), i.splice(p, 0, 1), te({ inputs: { x: s }, backend: o, attrs: { shape: i } });
}
var hF = { kernelName: na, backendName: "webgl", kernelFunc: eg };
var gF = "return exp(x) - 1.0;";
var WJ = xe({ opSnippet: gF, packedOpSnippet: gF, cpuKernelImpl: KR });
var xF = { kernelName: bn, backendName: "webgl", kernelFunc: WJ };
var nm = class {
  constructor(e, t10, o) {
    this.variableNames = ["real", "imag"];
    let n = t10[1];
    this.outputShape = t10;
    let s = o ? `2.0 * ${Math.PI}` : `-2.0 * ${Math.PI}`, a = o ? `${n}.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(${n});
        float exponentMultiplierTimesIndexRatio =
            exponentMultiplier * indexRatio;

        float result = 0.0;

        for (int i = 0; i < ${n}; 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 tg(r15, e, t10) {
  let o = t10.texData.get(r15.dataId), n = y.sizeFromShape(r15.shape), s = r15.shape[r15.shape.length - 1], a = n / s, i = te({ inputs: { x: r15 }, backend: t10, attrs: { shape: [a, s] } }), p = i.shape, u = new nm("real", p, e), c = new nm("imag", p, e), l = [{ dataId: o.complexTensorInfos.real.dataId, dtype: o.complexTensorInfos.real.dtype, shape: p }, { dataId: o.complexTensorInfos.imag.dataId, dtype: o.complexTensorInfos.imag.dtype, shape: p }], m = t10.runWebGLProgram(u, l, "float32"), d = t10.runWebGLProgram(c, l, "float32"), f = Or({ inputs: { real: m, imag: d }, backend: t10 });
  t10.disposeIntermediateTensorInfo(m), t10.disposeIntermediateTensorInfo(d);
  let h = te({ inputs: { x: f }, backend: t10, attrs: { shape: r15.shape } });
  return t10.disposeIntermediateTensorInfo(i), t10.disposeIntermediateTensorInfo(f), h;
}
function UJ(r15) {
  let { inputs: e, backend: t10 } = r15, { input: o } = e;
  return tg(o, false, t10);
}
var yF = { kernelName: "FFT", backendName: "webgl", kernelFunc: UJ };
var rg = class {
  constructor(e, t10) {
    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 Ci(r15) {
  let { backend: e, attrs: t10 } = r15, { shape: o, value: n } = t10, { dtype: s } = t10;
  if (s = s || y.inferDtype(n), s === "string") {
    let a = y.getArrayFromDType(s, y.sizeFromShape(o));
    return a.fill(n), e.makeTensorInfo(o, s, a);
  } else {
    let a = new rg(o, n), i = [[n]];
    return e.runWebGLProgram(a, [], s, i);
  }
}
var bF = { kernelName: sa, backendName: "webgl", kernelFunc: Ci };
var og = class {
  constructor(e) {
    this.variableNames = ["Image"], this.outputShape = [];
    let t10 = e[2];
    this.outputShape = e, this.userCode = `
        void main() {
          ivec4 coords = getOutputCoords();
          int x = coords[2];

          int coordX = ${t10} - x - 1;
          float outputValue;
          if(coordX >= 0 && coordX < ${t10}) {
            outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
          } else {
            outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
          }
          setOutput(outputValue);
        }
    `;
  }
};
var CF = { kernelName: Cn, backendName: "webgl", kernelFunc: ({ inputs: r15, backend: e }) => {
  let { image: t10 } = r15, o = e, n = new og(t10.shape);
  return o.runWebGLProgram(n, [t10], t10.dtype);
} };
var wF = "return floor(x);";
var GJ = xe({ opSnippet: wF, packedOpSnippet: wF, cpuKernelImpl: qR });
var SF = { kernelName: wn, backendName: "webgl", kernelFunc: GJ };
var HJ = `
  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 KJ = `
  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 qJ = nt({ opSnippet: HJ, packedOpSnippet: KJ, dtype: "int32" });
var IF = { kernelName: Sn, backendName: "webgl", kernelFunc: qJ };
var ng = class {
  constructor(e) {
    this.variableNames = ["A"];
    let t10 = It(), [o, n] = 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(${n}.0, ${o}.0);

        vec4 values = ${t10.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 sg = class {
  constructor(e) {
    this.variableNames = ["A"], this.packedInputs = false, this.packedOutput = true;
    let t10 = It(), [o, n] = 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(${n}.0, ${o}.0);
            vec4 values = ${t10.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);
          }
        }

        ${t10.output} = result;
      }
    `;
  }
};
var vF = { kernelName: Du, backendName: "webgl", kernelFunc: jJ };
var Kc;
var Nv = A().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");
function jJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { pixels: n } = e, { numChannels: s } = o, a = typeof HTMLVideoElement != "undefined" && n instanceof HTMLVideoElement, i = typeof HTMLImageElement != "undefined" && n instanceof HTMLImageElement, [p, u] = a ? [n.videoWidth, n.videoHeight] : [n.width, n.height], c = [u, p], l = [u, p, s];
  if (i || a) {
    let h = A().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");
    (Kc == null || h !== Nv) && (Nv = h, Kc = document.createElement("canvas").getContext("2d", { willReadFrequently: Nv })), Kc.canvas.width = p, Kc.canvas.height = u, Kc.drawImage(n, 0, 0, p, u), n = Kc.canvas;
  }
  let m = t10.makeTensorInfo(c, "int32");
  t10.texData.get(m.dataId).usage = mr.PIXELS, t10.gpgpu.uploadPixelDataToTexture(t10.getTexture(m.dataId), n);
  let d = A().getBool("WEBGL_PACK") ? new sg(l) : new ng(l), f = t10.runWebGLProgram(d, [m], "int32");
  return t10.disposeData(m.dataId), f;
}
function XJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s, bias: a, preluActivationWeights: i } = e, { strides: p, pad: u, dataFormat: c, dilations: l, dimRoundingMode: m, activation: d, leakyreluAlpha: f } = o, h = w.convertConv2DDataFormat(c), g = w.computeConv2DInfo(n.shape, s.shape, p, l, u, m, false, h), x, b = [], C = a != null, S = i != null, k = d === "leakyrelu", _ = () => {
    let R = [n, s], D = (P, O) => {
      if (O === "NCHW" && P.shape.length === 1 && P.shape[0] !== 1) {
        let M = te({ inputs: { x: P }, backend: t10, attrs: { shape: [P.shape[0], 1, 1] } });
        return b.push(M), M;
      }
      return P;
    };
    if (C && R.push(D(a, c)), S && R.push(D(i, c)), k) {
      let P = t10.makeTensorInfo([], "float32", y.createScalarValue(f, "float32"));
      R.push(P), b.push(P);
    }
    return R;
  };
  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 = zh({ x: n, filter: s, convInfo: g, backend: t10, bias: a, activation: d, preluActivationWeights: i, leakyreluAlpha: f });
  else if (g.strideWidth <= 2 && h === "channelsLast" && A().getBool("WEBGL_EXP_CONV")) {
    let R = d ? yi(d, true) : null, D = new Uc(g, C, R, S, k), P = [[g.padInfo.top, g.padInfo.left], [g.strideHeight, g.strideWidth], [g.dilationHeight, g.dilationWidth], [g.inHeight, g.inWidth]], O = _();
    x = t10.runWebGLProgram(D, O, "float32", P);
  } else if (A().getBool("WEBGL_CONV_IM2COL")) x = Vh({ x: n, filter: s, convInfo: g, backend: t10, bias: a, activation: d, preluActivationWeights: i, leakyreluAlpha: f });
  else {
    let R = d ? yi(d, false) : null, D = new Wc(g, C, R, S, k), P = _();
    x = t10.runWebGLProgram(D, P, "float32");
  }
  let $ = te({ inputs: { x }, backend: t10, attrs: { shape: g.outShape } });
  return b.push(x), b.forEach((R) => t10.disposeIntermediateTensorInfo(R)), $;
}
var kF = { kernelName: Io, backendName: "webgl", kernelFunc: XJ };
function YJ(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s, bias: a, preluActivationWeights: i } = e, { strides: p, pad: u, dilations: c, dimRoundingMode: l, activation: m, leakyreluAlpha: d } = o, f = [], h = c;
  h == null && (h = [1, 1]), y.assert(w.eitherStridesOrDilationsAreOne(p, h), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${p} and dilations '${h}'`);
  let g = w.computeConv2DInfo(n.shape, s.shape, p, h, u, l, true), x = A().getBool("WEBGL_PACK_DEPTHWISECONV") && g.strideWidth <= 2 && g.outChannels / g.inChannels === 1, b = m ? yi(m, x) : null, C = [n, s], S = a != null, k = i != null, _ = m === "leakyrelu";
  if (S && C.push(a), k && C.push(i), _) {
    let P = t10.makeTensorInfo([], "float32", y.createScalarValue(d, "float32"));
    C.push(P), f.push(P);
  }
  let $;
  x ? $ = new Hc(g, S, b, k, _) : $ = new Gc(g, S, b, k, _);
  let R = [[g.padInfo.top, g.padInfo.left], [g.strideHeight, g.strideWidth], [g.dilationHeight, g.dilationWidth], [g.inHeight, g.inWidth]], D = t10.runWebGLProgram($, C, "float32", R);
  return f.forEach((P) => t10.disposeIntermediateTensorInfo(P)), D;
}
var NF = { kernelName: vo, backendName: "webgl", kernelFunc: YJ };
var ag = class {
  constructor(e, t10, o, n) {
    this.sliceDim = e, this.strides = t10, this.paramsShape = n, this.variableNames = ["x", "indices"], this.outputShape = o;
    let s = Re(o.length), a = `
    int index;`;
    for (let i = 0; i < this.sliceDim; i++) a += `
          index = round(getIndices(coords[0], ${i}));
          out_of_bounds = out_of_bounds || index < 0;
          out_of_bounds = out_of_bounds || index >= ${this.paramsShape[i]};
          flattenIndex += index * ${this.strides[i]};`;
    this.userCode = `
         void main() {
          ${s} coords = getOutputCoords();
          int flattenIndex = 0;
          bool out_of_bounds = false;

          ${a}

          setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));
        }
      `;
  }
};
function QJ(r15) {
  let { inputs: e, backend: t10 } = r15, { params: o, indices: n } = e, s = n.shape, a = s[s.length - 1], i = y.sizeFromShape(o.shape), [p, u, c, l] = w.prepareAndValidate(o, n), m = te({ inputs: { x: n }, backend: t10, attrs: { shape: [u, a] } }), d = te({ inputs: { x: o }, backend: t10, attrs: { shape: [y.sizeFromShape(o.shape) / c, c] } });
  if (t10.shouldExecuteOnCPU([o, n]) || o.dtype === "string") {
    let x = t10.readSync(n.dataId), b = t10.bufferSync(o), C = jR(x, b, o.dtype, u, a, c, l, o.shape, i);
    return t10.makeTensorInfo(p, o.dtype, C.values);
  }
  let f = new ag(a, l, [u, c], o.shape), h = t10.runWebGLProgram(f, [d, m], d.dtype), g = te({ inputs: { x: h }, backend: t10, attrs: { shape: p } });
  return t10.disposeIntermediateTensorInfo(m), t10.disposeIntermediateTensorInfo(d), t10.disposeIntermediateTensorInfo(h), g;
}
var TF = { kernelName: vn, backendName: "webgl", kernelFunc: QJ };
var ig = class {
  constructor(e, t10) {
    this.variableNames = ["A", "indices"], this.outputShape = t10, this.rank = t10.length;
    let o = Re(this.rank), n = ZJ(e, 2);
    this.userCode = `
      void main() {
        ${o} resRC = getOutputCoords();
        int index = int(getIndices(resRC.x, resRC.z));
        float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;
        setOutput(inBounds * getA(${n}));
      }
    `;
  }
};
function ZJ(r15, e) {
  let t10 = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], o = [];
  for (let n = 0; n < r15.length; n++) n === 2 ? o.push("index") : o.push(`${t10[n]}`);
  return o.join();
}
function Tv(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, indices: s } = e, { axis: a, batchDims: i } = o, p = y.parseAxisParam(a, n.shape)[0];
  if (A().get("DEBUG")) {
    let b = t10.readSync(s.dataId), C = n.shape[p];
    for (let S = 0; S < b.length; ++S) {
      let k = b[S];
      y.assert(k <= C - 1 && k >= 0, () => `GatherV2: the index value ${k} is not in [0, ${C - 1}]`);
    }
  }
  let u = w.segment_util.collectGatherOpShapeInfo(n, s, p, i), c = y.sizeFromShape(s.shape), l = [], m = te({ inputs: { x: n }, backend: t10, attrs: { shape: [u.batchSize, u.outerSize, u.dimSize, u.sliceSize] } }), d = te({ inputs: { x: s }, backend: t10, attrs: { shape: [u.batchSize, c / u.batchSize] } });
  l.push(m), l.push(d);
  let f = [u.batchSize, u.outerSize, c / u.batchSize, u.sliceSize];
  if (t10.shouldExecuteOnCPU([n, s]) || n.dtype === "string") {
    let b = t10.bufferSync(d), C = t10.bufferSync(m), S = XR(C, b, f);
    return l.forEach((k) => t10.disposeIntermediateTensorInfo(k)), t10.makeTensorInfo(u.outputShape, S.dtype, S.values);
  }
  let h = new ig(m.shape, f), g = t10.runWebGLProgram(h, [m, d], m.dtype);
  l.push(g);
  let x = te({ inputs: { x: g }, backend: t10, attrs: { shape: u.outputShape } });
  return l.forEach((b) => t10.disposeIntermediateTensorInfo(b)), x;
}
var _F = { kernelName: aa, backendName: "webgl", kernelFunc: Tv };
var JJ = "return float(a > b);";
var eee = `
  return vec4(greaterThan(a, b));
`;
var tee = nt({ opSnippet: JJ, packedOpSnippet: eee, cpuKernelImpl: YR, dtype: "bool" });
var EF = { kernelName: kn, backendName: "webgl", kernelFunc: tee };
var ree = "return float(a >= b);";
var oee = `
  return vec4(greaterThanEqual(a, b));
`;
var nee = nt({ opSnippet: ree, packedOpSnippet: oee, dtype: "bool", cpuKernelImpl: QR });
var $F = { kernelName: Nn, backendName: "webgl", kernelFunc: nee };
function see(r15) {
  let { inputs: e, backend: t10 } = r15, { input: o } = e;
  return tg(o, true, t10);
}
var RF = { kernelName: Vi, backendName: "webgl", kernelFunc: see };
var aee = "return float(!isnan(x) && !isinf(x));";
var iee = xe({ opSnippet: aee, dtype: "bool" });
var DF = { kernelName: Tn, backendName: "webgl", kernelFunc: iee };
var uee = "return float(isinf(x));";
var pee = xe({ opSnippet: uee, dtype: "bool" });
var AF = { kernelName: _n, backendName: "webgl", kernelFunc: pee };
var cee = "return float(isnan(x));";
var lee = xe({ opSnippet: cee, dtype: "bool" });
var FF = { kernelName: En, backendName: "webgl", kernelFunc: lee };
var mee = "return float(a < b);";
var dee = `
  return vec4(lessThan(a, b));
`;
var fee = nt({ opSnippet: mee, packedOpSnippet: dee, cpuKernelImpl: ZR, dtype: "bool" });
var PF = { kernelName: Rn, backendName: "webgl", kernelFunc: fee };
var hee = "return float(a <= b);";
var gee = `
  return vec4(lessThanEqual(a, b));
`;
var xee = nt({ opSnippet: hee, packedOpSnippet: gee, cpuKernelImpl: JR, dtype: "bool" });
var OF = { kernelName: Dn, backendName: "webgl", kernelFunc: xee };
function yee(r15) {
  let { backend: e, attrs: t10 } = r15, { start: o, stop: n, num: s } = t10, a = eD(o, n, s);
  return e.makeTensorInfo([a.length], "float32", a);
}
var MF = { kernelName: An, backendName: "webgl", kernelFunc: yee };
var bee = Fo + `
  return x < 0.0 ? 0./0. : log(x);
`;
var Cee = `
  vec4 result = log(x);
  bvec4 isNaN = isnan(x);
  result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);
  result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);
  result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);
  result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);
  return result;
`;
var wee = xe({ opSnippet: bee, packedOpSnippet: Cee, cpuKernelImpl: tD });
var LF = { kernelName: "Log", backendName: "webgl", kernelFunc: wee };
var See = Fo + `
  return log(1.0 + x);
`;
var Iee = xe({ opSnippet: See });
var BF = { kernelName: Pn, backendName: "webgl", kernelFunc: Iee };
var vee = "return float(a >= 1.0 && b >= 1.0);";
var kee = `
  return vec4(
    vec4(greaterThanEqual(a, vec4(1.0))) *
    vec4(greaterThanEqual(b, vec4(1.0))));
`;
var Nee = nt({ opSnippet: vee, packedOpSnippet: kee, dtype: "bool" });
var zF = { kernelName: On, backendName: "webgl", kernelFunc: Nee };
var Tee = "return float(!(x >= 1.0));";
var _ee = xe({ opSnippet: Tee });
var VF = { kernelName: Mn, backendName: "webgl", kernelFunc: _ee };
var Eee = "return float(a >= 1.0 || b >= 1.0);";
var $ee = `
  return min(
    vec4(greaterThanEqual(a, vec4(1.0))) +
    vec4(greaterThanEqual(b, vec4(1.0))),
    vec4(1.0));
`;
var Ree = nt({ opSnippet: Eee, packedOpSnippet: $ee, dtype: "bool" });
var WF = { kernelName: Ln, backendName: "webgl", kernelFunc: Ree };
var ug = class {
  constructor(e, t10, o, n, s) {
    this.variableNames = ["x"], this.outputShape = [];
    let a = t10, i = e[3] - 1;
    this.outputShape = e;
    let p, u = `float(${o}) + float(${n}) * sum`;
    s === 0.5 ? p = `inversesqrt(${u})` : s === 1 ? p = `1.0/(${u})` : p = `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 * ${p};
        setOutput(val);
      }
    `;
  }
};
var pg = class {
  constructor(e, t10, o, n, s) {
    this.variableNames = ["x"], this.outputShape = [], this.packedInputs = true, this.packedOutput = true;
    let a = t10, i = e[3] - 1;
    this.outputShape = e;
    let p, u = `float(${o}) + float(${n}) * sum`;
    s === 0.5 ? p = `inversesqrt(${u})` : s === 1 ? p = `1.0/(${u})` : p = `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 * ${p};
        setOutput(result);
      }
    `;
  }
};
var Dee = (r15) => {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { depthRadius: s, bias: a, alpha: i, beta: p } = o, u = A().getBool("WEBGL_PACK_NORMALIZATION") ? new pg(n.shape, s, a, i, p) : new ug(n.shape, s, a, i, p);
  return t10.runWebGLProgram(u, [n], n.dtype);
};
var UF = { kernelName: "LRN", backendName: "webgl", kernelFunc: Dee };
var cg = class {
  constructor(e, t10, o, n, s) {
    this.variableNames = ["inputImage", "outputImage", "dy"], this.outputShape = [], this.outputShape = e, this.depth = e[3], this.depthRadius = t10, this.bias = o, this.alpha = n, 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 - ${t10})));
          int depthEnd = int(min(float(${this.depth}),
              float(d + ${t10} + 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(${n}) * norm + float(${o});

          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(${n})
                * 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 Aee = (r15) => {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, y: s, dy: a } = e, { depthRadius: i, bias: p, alpha: u, beta: c } = o, l = new cg(n.shape, i, p, u, c);
  return t10.runWebGLProgram(l, [n, s, a], n.dtype);
};
var GF = { kernelName: Ya, backendName: "webgl", kernelFunc: Aee };
function HF(r15, e, t10, o) {
  let n = y.sizeFromShape(e), a = y.sizeFromShape(r15.shape) / n, i = te({ inputs: { x: r15 }, attrs: { shape: [a, n] }, backend: o }), p = Yr(i, r15.dtype, "max", o), u = te({ inputs: { x: p }, attrs: { shape: t10 }, backend: o });
  return o.disposeIntermediateTensorInfo(i), o.disposeIntermediateTensorInfo(p), u;
}
function _v(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { reductionIndices: s, keepDims: a } = o, i = n.shape.length, p = y.parseAxisParam(s, n.shape), u = p, c = w.getAxesPermutation(u, i), l = c != null, m = t10.shouldExecuteOnCPU([n]), d = n;
  if (l) {
    if (m) {
      let C = t10.texData.get(d.dataId).values, S = new Array(i);
      for (let $ = 0; $ < S.length; $++) S[$] = n.shape[c[$]];
      let k = Cp(C, n.shape, n.dtype, c, S);
      d = t10.makeTensorInfo(S, n.dtype);
      let _ = t10.texData.get(d.dataId);
      _.values = k;
    } else d = yu(n, c, t10);
    u = w.getInnerMostAxes(u.length, i);
  }
  w.assertAxesAreInnerMostDims("max", u, i);
  let [f, h] = w.computeOutAndReduceShapes(d.shape, u), g = f;
  a && (g = w.expandShapeToKeepDim(f, p));
  let x;
  if (m) {
    let C = t10.texData.get(d.dataId).values, S = rD(C, y.sizeFromShape(h), g, n.dtype);
    x = t10.makeTensorInfo(g, n.dtype);
    let k = t10.texData.get(x.dataId);
    k.values = S;
  } else x = HF(d, h, g, t10);
  return l && t10.disposeIntermediateTensorInfo(d), x;
}
var KF = { kernelName: "Max", backendName: "webgl", kernelFunc: _v };
var Fee = Bc + `
  return max(a, b);
`;
var Pee = `
  vec4 result = vec4(max(a, b));
  bvec4 isNaNA = isnan(a);
  bvec4 isNaNB = isnan(b);
  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
  ` + Xr + `
  return result;
`;
var Oee = nt({ opSnippet: Fee, packedOpSnippet: Pee, cpuKernelImpl: oD });
var qF = { kernelName: Vn, backendName: "webgl", kernelFunc: Oee };
function Mee(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e;
  Vs(n, "maxPool");
  let { filterSize: s, strides: a, pad: i, dimRoundingMode: p } = o, u = 1;
  y.assert(w.eitherStridesOrDilationsAreOne(a, u), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);
  let c = w.computePool2DInfo(n.shape, s, a, u, i, p);
  if (c.filterWidth === 1 && c.filterHeight === 1 && y.arraysEqual(c.inShape, c.outShape)) return Dt({ inputs: { x: n }, backend: t10 });
  let l = new Us(c, "max", false);
  return t10.runWebGLProgram(l, [n], n.dtype);
}
var jF = { kernelName: Wn, backendName: "webgl", kernelFunc: Mee };
function Lee(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { filterSize: s, strides: a, pad: i, dataFormat: p, dimRoundingMode: u } = o, c = [1, 1, 1], l = w.computePool3DInfo(n.shape, s, a, c, i, u, p), m = new bu(l, "max", false);
  return t10.runWebGLProgram(m, [n], n.dtype);
}
var XF = { kernelName: ia, backendName: "webgl", kernelFunc: Lee };
var lg = class {
  constructor(e) {
    this.variableNames = ["dy", "maxPos"], this.outputShape = e.inShape;
    let t10 = e.strideHeight, o = e.strideWidth, n = e.dilationHeight, s = e.effectiveFilterHeight, a = e.effectiveFilterWidth, i = s - 1 - e.padInfo.top, p = a - 1 - e.padInfo.left, u = s * a - 1;
    this.userCode = `
      const ivec2 pads = ivec2(${i}, ${p});

      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 += ${n}) {
          float dyR = float(dyRCorner + wR) / ${t10}.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) / ${o}.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 mg = class {
  constructor(e) {
    this.variableNames = ["dy", "maxPos"], this.outputShape = e.inShape;
    let t10 = e.strideDepth, o = e.strideHeight, n = e.strideWidth, s = e.dilationDepth, a = e.dilationHeight, i = e.dilationWidth, p = e.effectiveFilterDepth, u = e.effectiveFilterHeight, c = e.effectiveFilterWidth, l = p - 1 - e.padInfo.front, m = u - 1 - e.padInfo.top, d = c - 1 - e.padInfo.left, f = p * u * c - 1;
    this.userCode = `
      const ivec3 pads = ivec3(${l}, ${m}, ${d});

      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 < ${p};
           wD += ${s}) {
          float dyD = float(dyDCorner + wD) / ${t10}.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) / ${o}.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) / ${n}.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 = ${f} -
                  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 Bee(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s } = e, a = s, { filterSize: i, strides: p, pad: u, dimRoundingMode: c } = o, l = [1, 1, 1], m = w.computePool3DInfo(a.shape, i, p, l, u, c), d = new bu(m, "max", true), f = t10.runWebGLProgram(d, [a], a.dtype), h = new mg(m), g = t10.runWebGLProgram(h, [n, f], a.dtype);
  return t10.disposeIntermediateTensorInfo(f), g;
}
var YF = { kernelName: Gi, backendName: "webgl", kernelFunc: Bee };
function zee(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s, output: a } = e, i = s;
  Vs([s, a], "maxPoolGrad");
  let { filterSize: p, strides: u, pad: c, dimRoundingMode: l } = o, m = w.computePool2DInfo(i.shape, p, u, 1, c, l), d = true, f = new Us(m, "max", d), h = t10.runWebGLProgram(f, [i], i.dtype), g = new lg(m), x = t10.runWebGLProgram(g, [n, h], i.dtype);
  return t10.disposeIntermediateTensorInfo(h), x;
}
var QF = { kernelName: Ui, backendName: "webgl", kernelFunc: zee };
function ZF(r15, e, t10, o) {
  let n = new Us(t10, "max", false), s = o.runWebGLProgram(n, [r15], "float32");
  n = new Us(t10, "max", true, true, e);
  let a = o.runWebGLProgram(n, [r15], "float32");
  return [s, a];
}
var JF = { kernelName: ua, backendName: "webgl", kernelFunc: ({ inputs: r15, attrs: e, backend: t10 }) => {
  let { x: o } = r15, { filterSize: n, strides: s, pad: a, includeBatchInIndex: i } = e, p = t10;
  y.assert(o.shape.length === 4, () => `Error in maxPool: input must be rank 4 but got rank ${o.shape.length}.`);
  let u = [1, 1];
  y.assert(w.eitherStridesOrDilationsAreOne(s, u), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);
  let c = w.computePool2DInfo(o.shape, n, s, u, a), [l, m] = ZF(o, i, c, p);
  return [l, m];
} };
function e3(r15, e, t10, o) {
  let n = y.sizeFromShape(e), a = y.sizeFromShape(r15.shape) / n, i = te({ inputs: { x: r15 }, attrs: { shape: [a, n] }, backend: o }), p = Yr(i, "float32", "mean", o), u = te({ inputs: { x: p }, attrs: { shape: t10 }, backend: o });
  return o.disposeIntermediateTensorInfo(i), o.disposeIntermediateTensorInfo(p), u;
}
var t3 = { kernelName: Un, backendName: "webgl", kernelFunc: ({ inputs: r15, attrs: e, backend: t10 }) => {
  let { x: o } = r15, { keepDims: n, axis: s } = e, a = t10, i = o.shape.length, p = y.parseAxisParam(s, o.shape), u = p, c = w.getAxesPermutation(u, i), l = c != null, m = a.shouldExecuteOnCPU([o]), d = [], f = o;
  if (l) {
    if (m) {
      let S = a.texData.get(f.dataId).values, k = new Array(i);
      for (let R = 0; R < k.length; R++) k[R] = o.shape[c[R]];
      let _ = Cp(S, o.shape, o.dtype, c, k);
      f = a.makeTensorInfo(k, o.dtype);
      let $ = a.texData.get(f.dataId);
      $.values = _;
    } else f = yu(o, c, a);
    d.push(f), u = w.getInnerMostAxes(u.length, i);
  }
  w.assertAxesAreInnerMostDims("sum", u, i);
  let [h, g] = w.computeOutAndReduceShapes(f.shape, u), x = h;
  n && (x = w.expandShapeToKeepDim(h, p));
  let b = e3(f, g, x, a);
  for (let C of d) a.disposeIntermediateTensorInfo(C);
  return b;
} };
function Vee(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o, i = n.shape.length, p = y.parseAxisParam(s, n.shape), u = p, c = w.getAxesPermutation(u, i), l = n;
  c != null && (l = bt({ inputs: { x: n }, backend: t10, attrs: { perm: c } }), u = w.getInnerMostAxes(u.length, n.shape.length)), w.assertAxesAreInnerMostDims("min", u, i);
  let [m, d] = w.computeOutAndReduceShapes(l.shape, u), f = y.sizeFromShape(d), h = te({ inputs: { x: l }, backend: t10, attrs: { shape: [-1, f] } }), g = Yr(h, h.dtype, "min", t10), x;
  if (a) {
    let b = w.expandShapeToKeepDim(m, p);
    x = te({ inputs: { x: g }, backend: t10, attrs: { shape: b } });
  } else x = te({ inputs: { x: g }, backend: t10, attrs: { shape: m } });
  return t10.disposeIntermediateTensorInfo(h), t10.disposeIntermediateTensorInfo(g), c != null && t10.disposeIntermediateTensorInfo(l), x;
}
var r32 = { kernelName: "Min", backendName: "webgl", kernelFunc: Vee };
var Wee = Bc + `
  return min(a, b);
`;
var Uee = `
  vec4 result = vec4(min(a, b));
  bvec4 isNaNA = isnan(a);
  bvec4 isNaNB = isnan(b);
  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
  ` + Xr + `
  return result;
`;
var Gee = nt({ opSnippet: Wee, packedOpSnippet: Uee, cpuKernelImpl: nD });
var o3 = { kernelName: Hn, backendName: "webgl", kernelFunc: Gee };
var dg = class {
  constructor(e, t10, o) {
    this.variableNames = ["x"], this.outputShape = t10.map((c, l) => c[0] + e[l] + c[1]);
    let n = e.length, s = Re(n), a = t10.map((c) => c[0]).join(","), i = t10.map((c, l) => c[0] + e[l]).join(","), p = ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, n), u = o === "reflect" ? 0 : 1;
    if (n === 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 < ${n}; 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(${p}));
      }
    `;
  }
};
var fg = class {
  constructor(e, t10, o) {
    this.variableNames = ["x"], this.packedInputs = true, this.packedOutput = true, this.outputShape = t10.map((f, h) => f[0] + e[h] + f[1]);
    let n = e.length, s = Re(n), a = t10.map((f) => f[0]).join(","), i = t10.map((f, h) => f[0] + e[h]).join(","), p = Rt("rc", n), u = Rt("source", n), c = `${p[n - 1]} < ${this.outputShape[n - 1]}`, l = n === 1 ? "source" : `vec2(${u.slice(-2).join()})`, m = o === "reflect" ? 0 : 1, d = "";
    if (n === 1) {
      let f = `
        ${s} source = rc;
        if (source < start) {
          source = start * 2 - source - ${m};
        } else if (source >= end) {
          source = (end - 1) * 2 - source + ${m};
        }
        source -= start;
      `;
      d = `
        ${s} rc = outputLoc;
        ${f}
        result[0] = getChannel(getX(${u.join()}), ${l});
        ${p[n - 1]} += 1;
        if(${c}) {
          ${f}
          result[1] = getChannel(getX(${u.join()}), ${l});
        }
      `;
    } else {
      let f = `
        ${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;
      `;
      d = `
        ${s} rc = outputLoc;
        ${f}
        result[0] = getChannel(getX(${u.join()}), ${l});
        ${p[n - 1]} += 1;
        if(${c}) {
          ${f}
          result[1] = getChannel(getX(${u.join()}), ${l});
        }
        rc = outputLoc;
        ${p[n - 2]} += 1;
        if(${p[n - 2]} < ${this.outputShape[n - 2]}) {
          ${f}
          result[2] = getChannel(getX(${u.join()}), ${l});
          ${p[n - 1]} += 1;
          if(${c}) {
            ${f}
            result[3] = getChannel(getX(${u.join()}), ${l});
          }
        }
      `;
    }
    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 Hee = ({ inputs: r15, backend: e, attrs: t10 }) => {
  let { x: o } = r15, { paddings: n, mode: s } = t10, a = A().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new fg(o.shape, n, s) : new dg(o.shape, n, s);
  return e.runWebGLProgram(a, [o], o.dtype);
};
var n3 = { kernelName: Kn, backendName: "webgl", kernelFunc: Hee };
var Kee = `if (b == 0.0) return NAN;
  return mod(a, b);`;
var qee = `
  vec4 result = mod(a, b);
  bvec4 isNaN = equal(b, vec4(0.0));
  ` + Xr + `
  return result;
`;
var jee = nt({ opSnippet: Kee, packedOpSnippet: qee });
var s3 = { kernelName: "Mod", backendName: "webgl", kernelFunc: jee };
var hg = class {
  constructor(e, t10, o) {
    this.variableNames = ["probs"], this.customUniforms = [{ name: "seed", type: "float" }], this.outputShape = [e, o], this.userCode = `
      void main() {
        ivec2 coords = getOutputCoords();
        int batch = coords[0];

        float r = random(seed);
        float cdf = 0.0;

        for (int i = 0; i < ${t10 - 1}; i++) {
          cdf += getProbs(batch, i);

          if (r < cdf) {
            setOutput(float(i));
            return;
          }
        }

        // If no other event happened, last event happened.
        setOutput(float(${t10 - 1}));
      }
    `;
  }
};
var Xee = `
if (a == b) {
  return 1.0;
};
return a / b;`;
var Yee = `
  // 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 Ev = nt({ opSnippet: Xee, packedOpSnippet: Yee, checkOutOfBounds: true });
var a3 = { kernelName: fn, backendName: "webgl", kernelFunc: Ev };
var i3 = "return a - b;";
var $v = nt({ opSnippet: i3, packedOpSnippet: i3, supportsComplex: true, cpuKernelImpl: kD });
var u3 = { kernelName: "Sub", backendName: "webgl", kernelFunc: $v };
function Rv(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { logits: n } = e, { dim: s } = o, a = y.parseAxisParam([s], n.shape), i = _v({ inputs: { x: n }, backend: t10, attrs: { reductionIndices: a, keepDims: false } }), p = w.expandShapeToKeepDim(i.shape, a), u = te({ inputs: { x: i }, backend: t10, attrs: { shape: p } }), c = $v({ inputs: { a: n, b: u }, backend: t10 }), l = kv({ inputs: { x: c }, backend: t10 }), m = wp({ inputs: { x: l }, backend: t10, attrs: { axis: a, keepDims: false } }), d = te({ inputs: { x: m }, backend: t10, attrs: { shape: p } }), f = Ev({ inputs: { a: l, b: d }, backend: t10 });
  return t10.disposeIntermediateTensorInfo(i), t10.disposeIntermediateTensorInfo(u), t10.disposeIntermediateTensorInfo(c), t10.disposeIntermediateTensorInfo(l), t10.disposeIntermediateTensorInfo(m), t10.disposeIntermediateTensorInfo(d), f;
}
var p3 = { kernelName: Is, backendName: "webgl", kernelFunc: Rv };
function Qee(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { logits: n } = e, { numSamples: s, seed: a, normalized: i } = o, p = i ? n : Rv({ inputs: { logits: n }, backend: t10, attrs: { dim: n.shape.length - 1 } }), u = p.shape[0], c = p.shape[1], l = new hg(u, c, s), m = [[a]], d = t10.runWebGLProgram(l, [p], "int32", m);
  return i || t10.disposeIntermediateTensorInfo(p), d;
}
var c3 = { kernelName: jn, backendName: "webgl", kernelFunc: Qee };
var Zee = Wt + `
  return -x;
`;
var Jee = `
  vec4 result = -x;
  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;
`;
function ete(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e;
  if (t10.shouldExecuteOnCPU([o])) {
    let s = t10.texData.get(o.dataId), [a, i] = aD(s.values, o.shape, o.dtype);
    return t10.makeTensorInfo(i, o.dtype, a);
  }
  let n;
  return A().getBool("WEBGL_PACK_UNARY_OPERATIONS") ? n = new Fr(o.shape, Jee) : n = new tr(o.shape, Zee), t10.runWebGLProgram(n, [o], o.dtype);
}
var l3 = { kernelName: "Neg", backendName: "webgl", kernelFunc: ete };
var tte = Vt.nonMaxSuppressionV3Impl;
function rte(r15) {
  w.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
  let { inputs: e, backend: t10, attrs: o } = r15, { boxes: n, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: p } = o, u = t10.readSync(n.dataId), c = t10.readSync(s.dataId), { selectedIndices: l } = tte(u, c, a, i, p);
  return t10.makeTensorInfo([l.length], "int32", new Int32Array(l));
}
var m3 = { kernelName: Qn, backendName: "webgl", kernelFunc: rte };
var ote = Vt.nonMaxSuppressionV4Impl;
function nte(r15) {
  w.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
  let { inputs: e, backend: t10, attrs: o } = r15, { boxes: n, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: p, padToMaxOutputSize: u } = o, c = t10.readSync(n.dataId), l = t10.readSync(s.dataId), { selectedIndices: m, validOutputs: d } = ote(c, l, a, i, p, u);
  return [t10.makeTensorInfo([m.length], "int32", new Int32Array(m)), t10.makeTensorInfo([], "int32", new Int32Array([d]))];
}
var d3 = { kernelName: Qa, backendName: "webgl", kernelFunc: nte };
var ste = Vt.nonMaxSuppressionV5Impl;
function ate(r15) {
  w.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
  let { inputs: e, backend: t10, attrs: o } = r15, { boxes: n, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: p, softNmsSigma: u } = o, c = t10.readSync(n.dataId), l = t10.readSync(s.dataId), m = a, d = i, f = p, h = u, { selectedIndices: g, selectedScores: x } = ste(c, l, m, d, f, h);
  return [t10.makeTensorInfo([g.length], "int32", new Int32Array(g)), t10.makeTensorInfo([x.length], "float32", new Float32Array(x))];
}
var f3 = { kernelName: Zn, backendName: "webgl", kernelFunc: ate };
var gg = class {
  constructor(e, t10, o, n) {
    this.variableNames = ["indices"], this.outputShape = [e, t10], this.userCode = `
      void main() {
        ivec2 coords = getOutputCoords();
        int index = round(getIndices(coords.x));
        setOutput(mix(float(${n}), float(${o}),
                      float(index == coords.y)));
      }
    `;
  }
};
var ite = (r15) => {
  let { inputs: e, backend: t10, attrs: o } = r15, { indices: n } = e, { dtype: s, depth: a, onValue: i, offValue: p } = o, u = y.sizeFromShape(n.shape), c = new gg(u, a, i, p), l = te({ inputs: { x: n }, backend: t10, attrs: { shape: [u] } }), m = t10.runWebGLProgram(c, [l], s);
  t10.disposeIntermediateTensorInfo(l);
  let d = [...n.shape, a], f = te({ inputs: { x: m }, backend: t10, attrs: { shape: d } });
  return t10.disposeIntermediateTensorInfo(m), f;
};
var h3 = { kernelName: Jn, backendName: "webgl", kernelFunc: ite };
function sm(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e;
  if (o.dtype === "complex64") {
    let n = bi({ inputs: { input: o }, backend: t10 }), s = sm({ inputs: { x: n }, backend: t10 }), a = Ip({ inputs: { input: o }, backend: t10 }), i = sm({ inputs: { x: a }, backend: t10 }), p = Or({ inputs: { real: s, imag: i }, backend: t10 });
    return t10.disposeIntermediateTensorInfo(n), t10.disposeIntermediateTensorInfo(s), t10.disposeIntermediateTensorInfo(a), t10.disposeIntermediateTensorInfo(i), p;
  } else return Ci({ attrs: { shape: o.shape, dtype: o.dtype, value: o.dtype === "string" ? "" : 0 }, backend: t10 });
}
var g3 = { kernelName: Sa, backendName: "webgl", kernelFunc: sm };
function x3(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e;
  if (o.dtype === "string") throw new Error("onesLike is not supported under string dtype");
  if (o.dtype === "complex64") {
    let n = bi({ inputs: { input: o }, backend: t10 }), s = x3({ inputs: { x: n }, backend: t10 }), a = Ip({ inputs: { input: o }, backend: t10 }), i = sm({ inputs: { x: a }, backend: t10 }), p = Or({ inputs: { real: s, imag: i }, backend: t10 });
    return t10.disposeIntermediateTensorInfo(n), t10.disposeIntermediateTensorInfo(s), t10.disposeIntermediateTensorInfo(a), t10.disposeIntermediateTensorInfo(i), p;
  } else return Ci({ attrs: { shape: o.shape, dtype: o.dtype, value: 1 }, backend: t10 });
}
var y3 = { kernelName: ca, backendName: "webgl", kernelFunc: x3 };
function ute(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { axis: n } = o;
  if (e.length === 1) return eg({ inputs: { input: e[0] }, backend: t10, attrs: { dim: n } });
  let s = e[0].shape, a = e[0].dtype;
  e.forEach((c) => {
    y.assertShapesMatch(s, c.shape, "All tensors passed to stack must have matching shapes"), y.assert(a === c.dtype, () => "All tensors passed to stack must have matching dtypes");
  });
  let i = [], p = e.map((c) => {
    let l = eg({ inputs: { input: c }, backend: t10, attrs: { dim: n } });
    return i.push(l), l;
  }), u = vv({ inputs: p, backend: t10, attrs: { axis: n } });
  return i.forEach((c) => t10.disposeIntermediateTensorInfo(c)), u;
}
var b3 = { kernelName: la, backendName: "webgl", kernelFunc: ute };
var xg = class {
  constructor(e, t10, o) {
    this.variableNames = ["x"], this.customUniforms = [{ name: "value", type: "float" }], this.outputShape = t10.map((u, c) => u[0] + e[c] + u[1]);
    let n = e.length, s = Re(n), a = t10.map((u) => u[0]).join(","), i = t10.map((u, c) => u[0] + e[c]).join(","), p = ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, n);
    if (n === 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(${p}));
        }
      }
    `;
  }
};
var yg = class {
  constructor(e, t10, o) {
    this.variableNames = ["x"], this.packedInputs = true, this.packedOutput = true, this.customUniforms = [{ name: "value", type: "float" }], this.outputShape = t10.map((h, g) => h[0] + e[g] + h[1]);
    let n = e.length, s = Re(n), a = t10.map((h) => h[0]).join(","), i = t10.map((h, g) => h[0] + e[g]).join(","), p = Rt("rc", n), u = Rt("source", n), c = `${p[n - 1]} < ${this.outputShape[n - 1]}`, l = n === 1 ? "source" : `vec2(${u.slice(-2).join()})`, m = [`${s} rc = outputLoc;`, `${p[n - 1]} += 1;
       if(${c}) {
      `, n === 1 ? "" : `}
       rc = outputLoc;
       ${p[n - 2]} += 1;
       if(${p[n - 2]} < ${this.outputShape[n - 2]}) {`, n === 1 ? "" : `  ${p[n - 1]} += 1;
         if(${c}) {`], d = n === 1 ? "rc < start || rc >= end" : "any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))", f = "";
    for (let h = 0, g = n === 1 ? 2 : 4; h < g; h++) f += `
        ${m[h]}
        if (${d}) {
          result[${h}] = float(value);
        } else {
          ${s} source = rc - start;
          result[${h}] = getChannel(getX(${u.join()}), ${l});
        }
      `;
    f += n === 1 ? "} " : "}}", 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 Dv = (r15) => {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { paddings: s, constantValue: a } = o;
  if (y.sizeFromShape(n.shape) === 0) {
    let u = s.map((c, l) => c[0] + n.shape[l] + c[1]);
    return Ci({ backend: t10, attrs: { shape: u, value: a, dtype: n.dtype } });
  }
  let i = A().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new yg(n.shape, s, a) : new xg(n.shape, s, a), p = [[a]];
  return t10.runWebGLProgram(i, [n], n.dtype, p);
};
var C3 = { kernelName: es, backendName: "webgl", kernelFunc: Dv };
var pte = `
  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 cte = `
  // 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;

  bvec4 isNaN1 = lessThan(a, vec4(0.0));
  bvec4 isNaN2 = lessThan(floor(b), b);
  bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);
  ` + Xr + `
  return result;
`;
var lte = nt({ opSnippet: pte, packedOpSnippet: cte });
var w3 = { kernelName: "Pow", backendName: "webgl", kernelFunc: lte };
function mte(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o, i = n.shape.length, p = [], u = y.parseAxisParam(s, n.shape), c = u, l = w.getAxesPermutation(c, i), m = n;
  l != null && (m = bt({ inputs: { x: n }, backend: t10, attrs: { perm: l } }), c = w.getInnerMostAxes(c.length, i), p.push(m)), w.assertAxesAreInnerMostDims("prod", c, i);
  let d;
  if (t10.shouldExecuteOnCPU([m])) {
    let f = t10.texData.get(m.dataId).values, { outVals: h, outShape: g, outDtype: x } = uD(m.shape, m.dtype, f, c);
    d = t10.makeTensorInfo(g, x, h);
  } else {
    let [f, h] = w.computeOutAndReduceShapes(m.shape, c), g = y.sizeFromShape(h), x = te({ inputs: { x: m }, backend: t10, attrs: { shape: [-1, g] } }), b = oi(n.dtype), C = Yr(x, b, "prod", t10);
    d = te({ inputs: { x: C }, backend: t10, attrs: { shape: f } }), p.push(x), p.push(C);
  }
  if (a) {
    p.push(d);
    let f = w.expandShapeToKeepDim(d.shape, u);
    d = te({ inputs: { x: d }, backend: t10, attrs: { shape: f } });
  }
  return p.forEach((f) => t10.disposeIntermediateTensorInfo(f)), d;
}
var S3 = { kernelName: os, backendName: "webgl", kernelFunc: mte };
function dte(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { paramsNestedSplits: n, paramsDenseValues: s, indices: a } = e, { outputRaggedRank: i } = o, p = n.map((x) => t10.readSync(x.dataId)), u = n.map((x) => x.shape), c = t10.readSync(s.dataId), l = t10.readSync(a.dataId), [m, d, f] = pD(p, u, c, s.shape, s.dtype, l, a.shape, i), h = m.map((x) => t10.makeTensorInfo([x.length], "int32", x)), g = t10.makeTensorInfo(f, s.dtype, d);
  return h.concat([g]);
}
var I3 = { kernelName: Hp, backendName: "webgl", kernelFunc: dte };
function fte(r15) {
  let { inputs: e, backend: t10 } = r15, { starts: o, limits: n, deltas: s } = e, a = t10.readSync(o.dataId), i = t10.readSync(n.dataId), p = t10.readSync(s.dataId), [u, c] = cD(a, o.shape, o.dtype, i, n.shape, p, s.shape), l = t10.makeTensorInfo([u.length], "int32", u), m = t10.makeTensorInfo([c.length], o.dtype, c);
  return [l, m];
}
var v3 = { kernelName: Kp, backendName: "webgl", kernelFunc: fte };
function hte(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { shape: n, values: s, defaultValue: a, rowPartitionTensors: i } = e, { rowPartitionTypes: p } = o, u = t10.readSync(n.dataId), c = t10.readSync(s.dataId), l = t10.readSync(a.dataId), m = i.map((g) => t10.readSync(g.dataId)), d = i.map((g) => g.shape), [f, h] = lD(u, n.shape, c, s.shape, s.dtype, l, a.shape, m, d, p);
  return t10.makeTensorInfo(f, s.dtype, h);
}
var k3 = { kernelName: qp, backendName: "webgl", kernelFunc: hte };
var Av = (r15) => {
  let { backend: e, attrs: t10 } = r15, { start: o, stop: n, step: s, dtype: a } = t10, i = mD(o, n, s, a);
  return e.makeTensorInfo([i.length], a, i);
};
var N3 = { kernelName: ma, backendName: "webgl", kernelFunc: Av };
var gte = "return 1.0 / x;";
var xte = xe({ opSnippet: gte });
var T3 = { kernelName: ns, backendName: "webgl", kernelFunc: xte };
var yte = Wt + `
  return (x < 0.0) ? 0.0 : x;
`;
var bte = `
  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 Cte = xe({ opSnippet: yte, packedOpSnippet: bte });
var _3 = { kernelName: ss, backendName: "webgl", kernelFunc: Cte };
var wte = Wt + `
  return (x < 0.0) ? 0.0 : min(6.0, x);
`;
var Ste = `
  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 Ite = xe({ opSnippet: wte, packedOpSnippet: Ste });
var E3 = { kernelName: us, backendName: "webgl", kernelFunc: Ite };
var bg = class {
  constructor(e, t10, o, n, s) {
    this.variableNames = ["A"], this.outputShape = [];
    let [a, i, p, u] = e;
    this.outputShape = [a, t10, o, u];
    let c = [n && t10 > 1 ? i - 1 : i, n && o > 1 ? p - 1 : p], l = [n && t10 > 1 ? t10 - 1 : t10, n && o > 1 ? o - 1 : o], m;
    s ? m = "(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)" : m = "vec2(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
      const vec2 effectiveInputOverOutputRatioRC = vec2(
          ${c[0] / l[0]},
          ${c[1] / l[1]});
      const vec2 inputShapeRC = vec2(${i}.0, ${p}.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 Cg = class {
  constructor(e, t10, o, n, s) {
    this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.outputShape = [];
    let [a, i, p, u] = e;
    this.outputShape = [a, t10, o, u];
    let c = [n && t10 > 1 ? i - 1 : i, n && o > 1 ? p - 1 : p], l = [n && t10 > 1 ? t10 - 1 : t10, n && o > 1 ? o - 1 : o], m;
    s ? m = "(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)" : m = "vec3(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
      const vec3 effectiveInputOverOutputRatioRC = vec3(
          ${c[0] / l[0]},
          ${c[1] / l[1]},
          ${c[1] / l[1]});
      const vec3 inputShapeRC = vec3(${i}.0, ${p}.0,
                                     ${p}.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 < ${o - 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 vte(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n } = e, { alignCorners: s, halfPixelCenters: a, size: i } = o, [p, u] = i, c = A().getBool("WEBGL_PACK_IMAGE_OPERATIONS") ? new Cg(n.shape, p, u, s, a) : new bg(n.shape, p, u, s, a);
  return t10.runWebGLProgram(c, [n], "float32");
}
var $3 = { kernelName: is, backendName: "webgl", kernelFunc: vte };
var wg = class {
  constructor(e, t10, o) {
    this.variableNames = ["dy"], this.outputShape = [], this.outputShape = t10;
    let [, n, s] = t10, [, a, i] = e, p = [o && a > 1 ? n - 1 : n, o && i > 1 ? s - 1 : s], u = [o && a > 1 ? a - 1 : a, o && i > 1 ? i - 1 : i], c = p[0] / u[0], l = p[1] / u[1], m = 1 / c, d = 1 / l, f = Math.ceil(m) * 2 + 2, h = Math.ceil(d) * 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(${l});

        const float invHeightScale = float(${m});
        const float invWidthScale = float(${d});

        const int winHeight = int(${f});
        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), ${n - 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 kte(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n, dy: s } = e, { alignCorners: a } = o, i = new wg(s.shape, n.shape, a);
  return t10.runWebGLProgram(i, [s], s.dtype);
}
var R3 = { kernelName: Ja, backendName: "webgl", kernelFunc: kte };
var Sg = class {
  constructor(e, t10, o, n, s) {
    this.variableNames = ["A"], this.outputShape = [];
    let [a, i, p, u] = e;
    this.outputShape = [a, t10, o, u];
    let c = [n && t10 > 1 ? i - 1 : i, n && o > 1 ? p - 1 : p], l = [n && t10 > 1 ? t10 - 1 : t10, n && o > 1 ? o - 1 : o], m = n ? "0.5" : "0.0", d;
    s ? d = "max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))" : d = "vec2(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
      const vec2 effectiveInputOverOutputRatioRC = vec2(
          ${c[0] / l[0]},
          ${c[1] / l[1]});
      const vec2 inputShapeRC = vec2(${i}.0, ${p}.0);

      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int d = coords[3];
        ivec2 yRC = coords.yz;

        // Fractional source index.
        vec2 sourceFracIndexRC = ${d};

        // 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 Ig = class {
  constructor(e, t10, o, n, s) {
    this.variableNames = ["A"], this.packedInputs = true, this.packedOutput = true, this.outputShape = [];
    let [a, i, p, u] = e;
    this.outputShape = [a, t10, o, u];
    let c = [n && t10 > 1 ? i - 1 : i, n && o > 1 ? p - 1 : p], l = [n && t10 > 1 ? t10 - 1 : t10, n && o > 1 ? o - 1 : o], m = n ? "0.5" : "0.0", d;
    s ? d = "max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))" : d = "vec3(yRC) * effectiveInputOverOutputRatioRC", this.userCode = `
      const vec3 effectiveInputOverOutputRatioRC = vec3(
          ${c[0] / l[0]},
          ${c[1] / l[1]},
          ${c[1] / l[1]});
      const vec3 inputShapeRC = vec3(${i}.0, ${p}.0,
                                     ${p}.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 = ${d};

        // 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 < ${o - 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 Nte(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n } = e, { alignCorners: s, halfPixelCenters: a, size: i } = o, [p, u] = i, c = A().getBool("WEBGL_PACK_IMAGE_OPERATIONS") ? new Ig(n.shape, p, u, s, a) : new Sg(n.shape, p, u, s, a);
  return t10.runWebGLProgram(c, [n], n.dtype);
}
var D3 = { kernelName: as, backendName: "webgl", kernelFunc: Nte };
var vg = class {
  constructor(e, t10, o) {
    this.variableNames = ["dy"], this.outputShape = [], this.outputShape = t10;
    let [, n, s] = t10, [, a, i] = e, p = [o && a > 1 ? n - 1 : n, o && i > 1 ? s - 1 : s], u = [o && a > 1 ? a - 1 : a, o && i > 1 ? i - 1 : i], c = p[0] / u[0], l = p[1] / u[1], m = 1 / c, d = 1 / l, f = Math.ceil(m) * 2 + 2, h = Math.ceil(d) * 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(${l});

        const float invHeightScale = float(${m});
        const float invWidthScale = float(${d});

        const int winHeight = int(${f});
        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(${p[0]}) *
                (float(dyR) / float(${u[0]}));

            float sourceFracCol =
                float(${p[1]}) *
                  (float(dyC) / float(${u[1]}));

            int sourceNearestRow = int(min(
                float(int(${n}) - 1),
                ${o} ? float(round(sourceFracRow)) :
                                  float(floor(sourceFracRow))));

            int sourceNearestCol = int(min(
                float(int(${s}) - 1),
                ${o} ? float(round(sourceFracCol)) :
                                  float(floor(sourceFracCol))));

            if (r == sourceNearestRow && c == sourceNearestCol) {
              accumulator += getDy(b, dyR, dyC, d);
            }
          }
        }
        // End loop over dy

        setOutput(accumulator);
      }
    `;
  }
};
function Tte(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n, dy: s } = e, { alignCorners: a } = o, i = new vg(s.shape, n.shape, a);
  return t10.runWebGLProgram(i, [s], s.dtype);
}
var A3 = { kernelName: Za, backendName: "webgl", kernelFunc: Tte };
var kg = class {
  constructor(e, t10) {
    this.variableNames = ["x"];
    let o = e.length;
    if (o > 4) throw new Error(`WebGL backend: Reverse of rank-${o} tensor is not yet supported`);
    if (this.outputShape = e, o === 1) {
      this.userCode = `
        void main() {
          int coord = getOutputCoords();
          setOutput(getX(${e[0]} - coord - 1));
        }
      `;
      return;
    }
    let n = (i) => t10.indexOf(i) !== -1 && e[i] !== 1 ? `${e[i]} - coords[${i}] - 1` : `coords[${i}]`, s = e.map((i, p) => n(p)).join(","), a = Re(o);
    this.userCode = `
      void main() {
        ${a} coords = getOutputCoords();
        setOutput(getX(${s}));
      }
    `;
  }
};
var Ng = class {
  constructor(e, t10) {
    this.variableNames = ["x"], this.packedInputs = true, this.packedOutput = true;
    let o = e.length;
    if (o > 4) throw new Error(`WebGL backend: Reverse of rank-${o} tensor is not yet supported`);
    this.outputShape = e;
    let n = Rt("rc", o), s = `${n[o - 1]} + 1 < ${this.outputShape[o - 1]}`, a = `${n[o - 2]} + 1 < ${this.outputShape[o - 2]}`, i = Re(o);
    o === 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 = ${p(n.slice())};
          if(${s}){
            result.g = ${u(n.slice())};
          }
          if(${a}) {
            result.b = ${c(n.slice())};
            if(${s}) {
              result.a = ${l(n.slice())};
            }
          }
          setOutput(result);
        }
    `;
    function p(f) {
      return m(f);
    }
    function u(f) {
      return f[o - 1] = "(" + f[o - 1] + " + 1)", m(f);
    }
    function c(f) {
      return f[o - 2] = "(" + f[o - 2] + " + 1)", m(f);
    }
    function l(f) {
      return f[o - 1] = "(" + f[o - 1] + " + 1)", f[o - 2] = "(" + f[o - 2] + " + 1)", m(f);
    }
    function m(f) {
      let h = e.map((b, C) => d(C, f)), g = h.join(","), x = h.slice(-2).join(",");
      return `getChannel(getX(${g}), vec2(${x}))`;
    }
    function d(f, h) {
      return t10.indexOf(f) !== -1 && e[f] !== 1 ? `${e[f]} - ${h[f]} - 1` : `${h[f]}`;
    }
  }
};
function _te(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { dims: s } = o, a = n.shape.length, i = y.parseAxisParam(s, n.shape);
  if (a === 0) return Dt({ inputs: { x: n }, backend: t10 });
  let p = A().getBool("WEBGL_PACK_ARRAY_OPERATIONS") ? new Ng(n.shape, i) : new kg(n.shape, i);
  return t10.runWebGLProgram(p, [n], n.dtype);
}
var F3 = { kernelName: ps, backendName: "webgl", kernelFunc: _te };
var Tg = class {
  constructor(e, t10) {
    this.variableNames = ["Image"], this.outputShape = [], this.customUniforms = [{ name: "params", type: "vec4" }];
    let o = e[1], n = e[2];
    this.outputShape = e;
    let s = "";
    typeof t10 == "number" ? s = `float outputValue = ${t10.toFixed(2)};` : s = `
        vec3 fill = vec3(${t10.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 < ${n} && coordY >= 0 && coordY < ${o}) {
            outputValue = getImage(coords[0], coordY, coordX, coords[3]);
          }
          setOutput(outputValue);
        }
    `;
  }
};
var P3 = { kernelName: Ds, backendName: "webgl", kernelFunc: ({ inputs: r15, attrs: e, backend: t10 }) => {
  let { image: o } = r15, { radians: n, fillValue: s, center: a } = e, i = t10, p = new Tg(o.shape, s), [u, c] = w.getImageCenter(a, o.shape[1], o.shape[2]), l = [[u, c, Math.sin(n), Math.cos(n)]];
  return i.runWebGLProgram(p, [o], o.dtype, l);
} };
var Ete = `
  // 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 $te = xe({ opSnippet: Ete });
var O3 = { kernelName: cs, backendName: "webgl", kernelFunc: $te };
var Rte = "return inversesqrt(x);";
var Dte = xe({ opSnippet: Rte, cpuKernelImpl: dD });
var M3 = { kernelName: ls, backendName: "webgl", kernelFunc: Dte };
var Cu = class {
  constructor(e, t10, o, n, s, a, i = true, p = false) {
    this.variableNames = ["updates", "indices", "defaultValue"], this.outputShape = a;
    let u = Re(s.length), c = Re(a.length), l = "";
    o === 1 ? l = "i" : o === 2 && (l = "i, j");
    let m = `getIndices(${l})`, d = "";
    n === 1 ? d = "i" : n === 2 && (d = "i, coords[1]");
    let f = `getUpdates(${d})`, h = "";
    p && (h = "coords[0], coords[1]");
    let g = `getDefaultValue(${h})`, x = t10 > 1 ? "strides[j]" : "strides";
    this.userCode = `
        ${u} strides = ${u}(${s});

        void main() {
          ${c} coords = getOutputCoords();
          float sum = 0.0;
          bool found = false;
          for (int i = 0; i < ${e}; i++) {
            int flattenedIndex = 0;
            for (int j = 0; j < ${t10}; j++) {
              int index = round(${m});
              flattenedIndex += index * ${x};
            }
            if (flattenedIndex == coords[0]) {
              sum += ${f};
              found = true;
            }
          }
          setOutput(mix(${g}, sum, float(found)));
        }
      `;
  }
};
var _g = class {
  constructor(e, t10, o, n, s, a, i = true, p = false) {
    this.variableNames = ["updates", "indices", "defaultValue"], this.packedInputs = true, this.packedOutput = true, this.outputShape = a;
    let u = Re(s.length), c = Re(a.length), l = "";
    o === 1 ? l = "i" : o === 2 && (l = "i, j");
    let m = `getIndices(${l})`, d = "";
    n === 1 ? d = "i" : n === 2 && (d = "i, coords[1]");
    let f = `getUpdates(${d})`, h = "";
    p && (h = "coords[0], coords[1]");
    let g = `getDefaultValue(${h})`, x = t10 > 1 ? "strides[j]" : "strides", b = t10 > 1 ? "strides[j + 1]" : "strides";
    this.userCode = `
        ${u} strides = ${u}(${s});

        void main() {
          ${c} coords = getOutputCoords();
          vec4 sum = vec4(0.);
          vec4 found = vec4(0.);
          for (int i = 0; i < ${e}; i+=2) {
            ivec2 flattenedIndex = ivec2(0);
            for (int j = 0; j < ${t10}; j+=2) {
              ivec4 index = round(${m});
              flattenedIndex += index.xz * ${x};
              if (j + 1 < ${t10}) {
                flattenedIndex += index.yw * ${b};
              }
            }
            if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||
                flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {
              vec4 updVals = ${f};
              if (flattenedIndex[0] == coords[0]) {
                sum.xy += updVals.xy;
                found.xy = vec2(1.);
              } else if (flattenedIndex[0] == coords[0] + 1) {
                sum.zw += updVals.xy;
                found.zw = vec2(1.);
              }
              if (flattenedIndex[1] == coords[0]) {
                sum.xy += updVals.zw;
                found.xy = vec2(1.);
              } else if (flattenedIndex[1] == coords[0] + 1) {
                sum.zw += updVals.zw;
                found.zw = vec2(1.);
              }
            }
          }
          setOutput(mix(${g}, sum, found));
        }
      `;
  }
};
function Ate(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { indices: n, updates: s } = e, { shape: a } = o, { sliceRank: i, numUpdates: p, sliceSize: u, strides: c, outputSize: l } = w.calculateShapes(s, n, a), m = [l / u, u];
  if (l === 0) return t10.makeTensorInfo(a, n.dtype);
  let d = te({ inputs: { x: n }, backend: t10, attrs: { shape: [p, i] } }), f = te({ inputs: { x: s }, backend: t10, attrs: { shape: [p, u] } }), h = t10.makeTensorInfo([], "float32", new Float32Array([0])), g;
  A().getBool("WEBGL_PACK") ? g = new _g(p, i, d.shape.length, f.shape.length, c, m) : g = new Cu(p, i, d.shape.length, f.shape.length, c, m);
  let x = t10.runWebGLProgram(g, [f, d, h], f.dtype), b = te({ inputs: { x }, backend: t10, attrs: { shape: a } });
  return t10.disposeIntermediateTensorInfo(d), t10.disposeIntermediateTensorInfo(f), t10.disposeIntermediateTensorInfo(x), t10.disposeIntermediateTensorInfo(h), b;
}
var L3 = { kernelName: ms, backendName: "webgl", kernelFunc: Ate };
var Eg = class {
  constructor(e, t10, o, n) {
    this.variableNames = ["sortedSequence", "values"], this.customUniforms = [{ name: "numInputs", type: "int" }], this.outputShape = [e, o];
    let s = "while (left < right) {", a = `for (int i = 0; i < ${Math.ceil(Math.log2(t10 + 1))}; ++i) { if (left >= right) break;`, i = A().getNumber("WEBGL_VERSION") === 2 ? s : a, p = n === "left" ? "<" : "<=";
    this.userCode = `
       int findBound(int batch, float value) {
         int left = 0;
         int right = numInputs;
         int mid;
         ${i}
           mid = (left + right) / 2;
           if (getSortedSequence(batch, mid) ${p} value) {
             left = mid + 1;
           } else {
             right = mid;
           }
         }
         return right;
       }

       void main() {
         ivec2 coords = getOutputCoords();
         int batch = coords[0];
         int valueIndex = coords[1];

         float value = getValues(batch, valueIndex);

         setOutput(float(findBound(batch, value)));
       }
     `;
  }
};
function Fte(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { sortedSequence: n, values: s } = e, { side: a } = o, i = new Eg(n.shape[0], n.shape[1], s.shape[1], a), p = [[n.shape[1]]];
  return t10.runWebGLProgram(i, [n, s], "int32", p);
}
var B3 = { kernelName: fs, backendName: "webgl", kernelFunc: Fte };
var $g = class {
  constructor(e, t10, o) {
    this.variableNames = ["c", "a", "b"], this.outputShape = t10;
    let n, s;
    if (o > 4) throw Error(`Where for rank ${o} is not yet supported`);
    if (o === 1) s = "resRC", n = "resRC";
    else {
      let i = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], p = [], u = [];
      for (let c = 0; c < t10.length; c++) u.push(`${i[c]}`), c < e && p.push(`${i[c]}`);
      n = p.join(), s = u.join();
    }
    let a = Re(o);
    this.userCode = `
      void main() {
        ${a} resRC = getOutputCoords();
        float cVal = getC(${n});
        if (cVal >= 1.0) {
          setOutput(getA(${s}));
        } else {
          setOutput(getB(${s}));
        }
      }
    `;
  }
};
function Pte(r15) {
  let { inputs: e, backend: t10 } = r15, { condition: o, t: n, e: s } = e, a = new $g(o.shape.length, n.shape, n.shape.length);
  return t10.runWebGLProgram(a, [o, n, s], dt(n.dtype, s.dtype));
}
var z3 = { kernelName: fa, backendName: "webgl", kernelFunc: Pte };
var Ote = `
  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
  // see: https://arxiv.org/abs/1706.02515
  float scaleAlpha = ${w.SELU_SCALEALPHA};
  float scale = ${w.SELU_SCALE};
  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`;
var Mte = xe({ opSnippet: Ote });
var V3 = { kernelName: hs, backendName: "webgl", kernelFunc: Mte };
var Lte = Fo + `
  return 1.0 / (1.0 + exp(-1.0 * x));
`;
var Bte = `
  vec4 result = 1.0 / (1.0 + exp(-1.0 * x));
  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 zte = xe({ opSnippet: Lte, packedOpSnippet: Bte, cpuKernelImpl: hD });
var W3 = { kernelName: bs, backendName: "webgl", kernelFunc: zte };
var Vte = `
  if (isnan(x)) { return 0.0; }
  return sign(x);
`;
var Wte = xe({ opSnippet: Vte });
var U3 = { kernelName: ys, backendName: "webgl", kernelFunc: Wte };
var Ute = Fo + `
  return sin(x);
`;
var Gte = `
  vec4 result = sin(x);
  bvec4 isNaN = isnan(x);
  ${Xr}
  return result;
`;
var Hte = xe({ opSnippet: Ute, packedOpSnippet: Gte });
var G3 = { kernelName: "Sin", backendName: "webgl", kernelFunc: Hte };
var Kte = `
  float e2x = exp(x);
  return (e2x - 1.0 / e2x) / 2.0;
`;
var qte = xe({ opSnippet: Kte });
var H3 = { kernelName: xs, backendName: "webgl", kernelFunc: qte };
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 Xte = xe({ opSnippet: jte });
var K3 = { kernelName: Cs, backendName: "webgl", kernelFunc: Xte };
var Yte = (r15) => {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { blockShape: s, paddings: a } = o;
  y.assert(n.shape.length <= 4, () => "spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");
  let i = s.reduce((x, b) => x * b), p = [[0, 0]];
  p.push(...a);
  for (let x = 1 + s.length; x < n.shape.length; ++x) p.push([0, 0]);
  let u = [], c = Dv({ inputs: { x: n }, backend: t10, attrs: { paddings: p, constantValue: 0 } }), l = w.getReshaped(c.shape, s, i, false), m = w.getPermuted(l.length, s.length, false), d = w.getReshapedPermuted(c.shape, s, i, false), f = te({ inputs: { x: c }, backend: t10, attrs: { shape: l } }), h = bt({ inputs: { x: f }, backend: t10, attrs: { perm: m } }), g = te({ inputs: { x: h }, backend: t10, attrs: { shape: d } });
  return u.push(c), u.push(f), u.push(h), u.forEach((x) => t10.disposeIntermediateTensorInfo(x)), g;
};
var q3 = { kernelName: ga, backendName: "webgl", kernelFunc: Yte };
function Qte(r15) {
  let { inputs: e, backend: t10 } = r15, { indices: o, values: n, denseShape: s, defaultValue: a } = e;
  if (s.shape.length !== 1) throw new Error(`Dense shape must be a vector, saw:
         ${s.shape}`);
  if (o.shape.length !== 2) throw new Error(`Indices must be a matrix, saw:
         ${o.shape}`);
  if (n.shape.length !== 1) throw new Error(`Values must be a vector, saw:
         ${n.shape}`);
  if (a.shape.length !== 0) throw new Error(`Default value must be a scalar, saw:
        ${a.shape}`);
  let i = t10.readSync(o.dataId), p = t10.readSync(n.dataId), u = t10.readSync(s.dataId), c = t10.readSync(a.dataId)[0], [l, m, d, f, h] = xD(i, o.shape, o.dtype, p, n.dtype, u, c);
  return [t10.makeTensorInfo(m, o.dtype, l), t10.makeTensorInfo([m[0]], n.dtype, d), t10.makeTensorInfo([f.length], "bool", new Uint8Array(f.map((g) => Number(g)))), t10.makeTensorInfo([h.length], o.dtype, new Int32Array(h))];
}
var j3 = { kernelName: Ki, backendName: "webgl", kernelFunc: Qte };
function Zte(r15) {
  let { inputs: e, backend: t10 } = r15, { inputIndices: o, inputShape: n, newShape: s } = e;
  if (o.shape.length !== 2) throw new Error(`Input indices should be a matrix but received shape ${o.shape}`);
  if (n.shape.length !== 1) throw new Error(`Input shape should be a vector but received shape ${n.shape}`);
  if (s.shape.length !== 1) throw new Error(`Target shape should be a vector but received shape ${s.shape}`);
  let a = Array.from(t10.readSync(n.dataId)), i = t10.readSync(o.dataId), p = Array.from(t10.readSync(s.dataId)), [u, c, l] = yD(i, o.shape, o.dtype, a, p);
  return [t10.makeTensorInfo(c, o.dtype, u), t10.makeTensorInfo([l.length], s.dtype, new Int32Array(l))];
}
var X3 = { kernelName: ei, backendName: "webgl", kernelFunc: Zte };
function Jte(r15) {
  let { inputs: e, backend: t10 } = r15, { data: o, indices: n, segmentIds: s } = e;
  if (o.shape.length < 1) throw new Error("Data should be at least 1 dimensional but received scalar");
  if (n.shape.length !== 1) throw new Error(`Indices should be a vector but received shape
              ${n.shape}`);
  if (s.shape.length !== 1) throw new Error(`Segment ids should be a vector but received shape
              ${s.shape}`);
  let a = t10.readSync(o.dataId), i = t10.readSync(n.dataId), p = t10.readSync(s.dataId), [u, c] = lh(a, o.shape, o.dtype, i, p, true);
  return t10.makeTensorInfo(c, o.dtype, u);
}
var Y3 = { kernelName: ya, backendName: "webgl", kernelFunc: Jte };
function ere(r15) {
  let { inputs: e, backend: t10 } = r15, { data: o, indices: n, segmentIds: s } = e;
  if (o.shape.length < 1) throw new Error("Data should be at least 1 dimensional but received scalar");
  if (n.shape.length !== 1) throw new Error(`Indices should be a vector but received shape
             ${n.shape}`);
  if (s.shape.length !== 1) throw new Error(`Segment ids should be a vector but received shape
             ${s.shape}`);
  let a = t10.readSync(o.dataId), i = t10.readSync(n.dataId), p = t10.readSync(s.dataId), [u, c] = lh(a, o.shape, o.dtype, i, p);
  return t10.makeTensorInfo(c, o.dtype, u);
}
var Q3 = { kernelName: ba, backendName: "webgl", kernelFunc: ere };
function tre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { sparseIndices: n, sparseValues: s, defaultValue: a } = e, { outputShape: i } = o, { sliceRank: p, numUpdates: u, sliceSize: c, strides: l, outputSize: m } = w.calculateShapes(s, n, i), d = false;
  if (s.dtype === "string") {
    let x = t10.bufferSync(n), b = t10.bufferSync(s), C = y.decodeString(t10.readSync(a.dataId)[0]), S = fD(x, b, i, m, c, u, p, l, C, d);
    return t10.makeTensorInfo(i, S.dtype, S.values);
  }
  let f = new Cu(u, p, n.shape.length, s.shape.length, l, [m, 1], d), h = t10.runWebGLProgram(f, [s, n, a], s.dtype), g = te({ inputs: { x: h }, backend: t10, attrs: { shape: i } });
  return t10.disposeIntermediateTensorInfo(h), g;
}
var Z3 = { kernelName: vs, backendName: "webgl", kernelFunc: tre };
function rre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { numOrSizeSplits: s, axis: a } = o, i = y.parseAxisParam(a, n.shape)[0], p = w.prepareSplitSize(n, s, i), u = n.shape.length, c = new Array(u).fill(0), l = n.shape.slice();
  return p.map((m) => {
    let d = [...l];
    d[i] = m;
    let f = Gs({ inputs: { x: n }, backend: t10, attrs: { begin: c, size: d } });
    return c[i] += m, f;
  });
}
var J3 = { kernelName: xa, backendName: "webgl", kernelFunc: rre };
var eP = "return sqrt(x);";
var ore = xe({ opSnippet: eP, packedOpSnippet: eP, cpuKernelImpl: bD });
var tP = { kernelName: ws, backendName: "webgl", kernelFunc: ore };
var nre = "return x * x;";
var sre = xe({ opSnippet: nre });
var rP = { kernelName: qi, backendName: "webgl", kernelFunc: sre };
var oP = "return (a - b) * (a - b);";
var are = nt({ opSnippet: oP, packedOpSnippet: oP });
var nP = { kernelName: ks, backendName: "webgl", kernelFunc: are };
function ire(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e;
  if (n.dtype !== "string") throw new Error("Input must be of datatype string");
  let s = t10.readSync(n.dataId), a = w.fromUint8ToStringArray(s), i = CD(a, "string", o);
  return t10.makeTensorInfo(n.shape, "string", i);
}
var sP = { kernelName: Ru, backendName: "webgl", kernelFunc: ire };
function ure({ inputs: r15, attrs: e, backend: t10 }) {
  let { x: o } = r15, n = Wt + `
    return x > 0.0 ? 1.0 : float(${e.alpha});
  `, s = new tr(o.shape, n);
  return t10.runWebGLProgram(s, [o], o.dtype);
}
var aP = { kernelName: wo, backendName: "webgl", kernelFunc: ure };
var Rg = class {
  constructor(e, t10, o) {
    this.variableNames = ["x"], this.outputShape = o;
    let n = o.length, s = Re(o.length), a = Re(o.length), i = "";
    if (n === 1) i = "coords * strides + begin";
    else {
      let p = 0;
      i = o.map((u, c) => (p++, o.length === 1 ? `coords * strides[${c}] + begin[${c}]` : `coords[${p - 1}] * strides[${c}] + begin[${c}]`)).join(",");
    }
    this.userCode = `
      ${s} begin = ${s}(${e});
      ${s} strides = ${s}(${t10});

      void main() {
        ${a} coords = getOutputCoords();
        setOutput(getX(${i}));
      }
    `;
  }
};
function pre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { begin: s, end: a, strides: i, beginMask: p, endMask: u, ellipsisMask: c, newAxisMask: l, shrinkAxisMask: m } = o, { finalShapeSparse: d, finalShape: f, isIdentity: h, sliceDim0: g, isSimpleSlice: x, begin: b, end: C, strides: S } = pt.sliceInfo(n.shape, s, a, i, p, u, c, l, m), k;
  if (h) k = te({ inputs: { x: n }, backend: t10, attrs: { shape: f } });
  else if (g || x) {
    y.assert(n.shape.length >= 1, () => `Input must have rank at least 1, got: ${n.shape.length}`);
    let $ = pt.computeOutShape(b, C, S), R = Gs({ inputs: { x: n }, backend: t10, attrs: { begin: b, size: $ } });
    k = te({ inputs: { x: R }, backend: t10, attrs: { shape: f } }), t10.disposeIntermediateTensorInfo(R);
  } else if (t10.shouldExecuteOnCPU([n])) {
    let R = t10.readSync(n.dataId), D = me(n.shape, n.dtype, R), P = wD(d, D, S, b);
    k = t10.makeTensorInfo(f, n.dtype, P.values);
  } else {
    let R = new Rg(b, S, d);
    k = t10.runWebGLProgram(R, [n], n.dtype);
  }
  let _ = te({ inputs: { x: k }, backend: t10, attrs: { shape: f } });
  return t10.disposeIntermediateTensorInfo(k), _;
}
var iP = { kernelName: Ns, backendName: "webgl", kernelFunc: pre };
function cre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { separator: n, nGramWidths: s, leftPad: a, rightPad: i, padWidth: p, preserveShortSequences: u } = o, { data: c, dataSplits: l } = e, m = t10.readSync(c.dataId), d = t10.readSync(l.dataId), [f, h] = SD(m, d, n, s, a, i, p, u);
  return [t10.makeTensorInfo([f.length], "string", f), t10.makeTensorInfo(l.shape, "int32", h)];
}
var uP = { kernelName: Ca, backendName: "webgl", kernelFunc: cre };
function lre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { skipEmpty: n } = o, { 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 = t10.readSync(s.dataId), p = t10.readSync(a.dataId)[0], [u, c, l] = ID(i, p, n), m = c.length;
  return [t10.makeTensorInfo([m, 2], "int32", u), t10.makeTensorInfo([m], "string", c), t10.makeTensorInfo([2], "int32", new Int32Array(l))];
}
var pP = { kernelName: ji, backendName: "webgl", kernelFunc: lre };
function mre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { numBuckets: n } = o, { input: s } = e;
  if (s.dtype !== "string") throw new Error("Input must be of datatype string");
  if (n <= 0) throw new Error("Number of buckets must be at least 1");
  let a = t10.readSync(s.dataId), i = vD(a, n);
  return t10.makeTensorInfo(s.shape, "int32", i);
}
var cP = { kernelName: Xi, backendName: "webgl", kernelFunc: mre };
var dre = "return tan(x);";
var fre = xe({ opSnippet: dre });
var lP = { kernelName: "Tan", backendName: "webgl", kernelFunc: fre };
var hre = `
  float e2x = exp(-2.0 * abs(x));
  return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`;
var gre = xe({ opSnippet: hre });
var mP = { kernelName: Es, backendName: "webgl", kernelFunc: gre };
function xre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { tensor: n, indices: s, updates: a } = e, {} = o, { sliceRank: i, numUpdates: p, sliceSize: u, strides: c, outputSize: l } = w.calculateShapes(a, s, n.shape), m = [l / u, u];
  if (l === 0) return t10.makeTensorInfo(n.shape, s.dtype);
  let d = te({ inputs: { x: s }, backend: t10, attrs: { shape: [p, i] } }), f = te({ inputs: { x: a }, backend: t10, attrs: { shape: [p, u] } }), h = te({ inputs: { x: n }, backend: t10, attrs: { shape: m } }), g = new Cu(p, i, d.shape.length, f.shape.length, c, m, false, true), x = t10.runWebGLProgram(g, [f, d, h], h.dtype), b = te({ inputs: { x }, backend: t10, attrs: { shape: n.shape } });
  return t10.disposeIntermediateTensorInfo(d), t10.disposeIntermediateTensorInfo(f), t10.disposeIntermediateTensorInfo(h), t10.disposeIntermediateTensorInfo(x), b;
}
var dP = { kernelName: ds, backendName: "webgl", kernelFunc: xre };
var Dg = class {
  constructor(e, t10) {
    this.variableNames = ["A"];
    let o = new Array(e.length);
    for (let a = 0; a < o.length; a++) o[a] = e[a] * t10[a];
    this.outputShape = o, this.rank = o.length;
    let n = Re(this.rank), s = yre(e);
    this.userCode = `
      void main() {
        ${n} resRC = getOutputCoords();
        setOutput(getA(${s}));
      }
    `;
  }
};
function yre(r15) {
  let e = r15.length;
  if (e > 5) throw Error(`Tile for rank ${e} is not yet supported`);
  if (e === 1) return `imod(resRC, ${r15[0]})`;
  let t10 = ["resRC.x", "resRC.y", "resRC.z", "resRC.w", "resRC.u"], o = [];
  for (let n = 0; n < r15.length; n++) o.push(`imod(${t10[n]}, ${r15[n]})`);
  return o.join();
}
function Fv(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { reps: s } = o;
  if (n.dtype === "string" || n.shape.length > 5) {
    let p = t10.readSync(n.dataId), u = n.dtype === "string" ? p.map((m) => y.decodeString(m)) : p, c = me(n.shape, n.dtype, u), l = ND(c, s);
    return t10.makeTensorInfo(l.shape, l.dtype, l.values);
  }
  let a = new Dg(n.shape, s);
  return t10.runWebGLProgram(a, [n], n.dtype);
}
var fP = { kernelName: po, backendName: "webgl", kernelFunc: Fv };
var Ag = 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 Fg = 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 kp(r15, e) {
  e !== null && r15.disposeIntermediateTensorInfo(e);
}
function hP(r15) {
  let e = 1;
  for (; e < r15; ) e *= 2;
  return e;
}
function bre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { k: s, sorted: a } = o, i = A().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"), p = A().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"), u = n.shape, c = u[u.length - 1];
  if (t10.shouldExecuteOnCPU([n]) || c < i || s > p) {
    let P = t10.readSync(n.dataId), [O, M] = TD(P, u, n.dtype, s, a);
    return [t10.makeTensorInfo(O.shape, O.dtype, O.values), t10.makeTensorInfo(M.shape, M.dtype, M.values)];
  }
  if (s === 0) return u[u.length - 1] = 0, [t10.makeTensorInfo(u, n.dtype, []), t10.makeTensorInfo(u, "int32", [])];
  if (c === 1) return [n, Ci({ attrs: { shape: u, dtype: "int32", value: 0 }, backend: t10 })];
  let l = t10.texData.get(n.dataId), m = l !== null && l.isPacked, d = m ? t10.unpackTensor(n) : n, h = y.sizeFromShape(u) / c, g = te({ inputs: { x: d }, attrs: { shape: [h, c] }, backend: t10 });
  m && kp(t10, d);
  let x = hP(s), b = hP(c), C = null, S = () => C === null ? [g, g] : [g, C], k = (P, O, M) => {
    let L = S(), B = new Ag(M), U = [[c], [C === null ? 1 : 0], [Number.NEGATIVE_INFINITY], [P], [O]], j = C;
    C = t10.runWebGLProgram(B, L, "int32", U), kp(t10, j);
  };
  for (let P = 1; P < x; P *= 2) {
    let O = P * 2;
    for (let M = P; M >= 1; M /= 2) k(O, M, [h, b]);
  }
  for (let P = b; P > x; P /= 2) {
    let O = S(), M = new Fg([h, P / 2]), B = [[c], [C === null ? 1 : 0], [x]], z = C;
    C = t10.runWebGLProgram(M, O, "int32", B), kp(t10, z);
    let U = x / 2, j = U * 2;
    for (let q = U; q >= 1; q /= 2) k(j, q, C.shape);
  }
  let _ = C;
  C = Gs({ inputs: { x: C }, backend: t10, attrs: { begin: 0, size: [h, s] } }), kp(t10, _);
  let $ = Tv({ inputs: { x: g, indices: C }, backend: t10, attrs: { axis: 1, batchDims: 1 } });
  kp(t10, g);
  let R = u.slice(0, -1);
  R.push(s), _ = C, C = te({ inputs: { x: C }, attrs: { shape: R }, backend: t10 }), kp(t10, _);
  let D = $;
  return $ = te({ inputs: { x: $ }, attrs: { shape: R }, backend: t10 }), kp(t10, D), [$, C];
}
var gP = { kernelName: $s, backendName: "webgl", kernelFunc: bre };
var Pg = class {
  constructor(e, t10, o, n, s, a) {
    this.variableNames = ["Image", "Transforms"], this.outputShape = a;
    let i = o === "nearest" ? 1 : 2, p;
    switch (n) {
      case "constant":
        p = 1;
        break;
      case "reflect":
        p = 2;
        break;
      case "wrap":
        p = 3;
        break;
      case "nearest":
        p = 4;
        break;
      default:
        p = 1;
        break;
    }
    this.userCode = `
            float mapCoord(float outCoord, float len) {
              float inCoord = outCoord;
              if(${p} == 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 (${p} == 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 (${p} == 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 < ${t10}) {
                  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(${t10}));
                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 Cre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { image: n, transforms: s } = e, { interpolation: a, fillMode: i, fillValue: p, outputShape: u } = o, [c, l, m, d] = n.shape, [f, h] = u != null ? u : [l, m], g = [c, f, h, d], x = new Pg(l, m, a, i, p, g);
  return t10.runWebGLProgram(x, [n, s], "float32");
}
var xP = { kernelName: Rs, backendName: "webgl", kernelFunc: Cre };
function wre(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { axis: n } = t10, { x: s } = e;
  Vs(s, "unique"), console.warn("WARNING: ", "UI might be locked temporarily as data is being downloaded");
  let a = o.readSync(s.dataId), { outputValues: i, outputShape: p, indices: u } = _D(a, n, s.shape, s.dtype);
  return [o.makeTensorInfo(p, s.dtype, i), o.makeTensorInfo([u.length], "int32", u)];
}
var yP = { kernelName: Yi, backendName: "webgl", kernelFunc: wre };
function Sre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { value: n } = e, { axis: s } = o;
  s < 0 && (s += n.shape.length);
  let a = n, i = a.shape.length, p = n.shape[s], u = new Array(i - 1), c = 0;
  for (let h = 0; h < i; h++) h !== s && (u[c++] = a.shape[h]);
  let l = [], m = new Array(i).fill(0), d = a.shape.slice();
  d[s] = 1;
  let f = new Array(p);
  for (let h = 0; h < f.length; h++) {
    m[s] = h;
    let g = Gs({ inputs: { x: a }, backend: t10, attrs: { begin: m, size: d } }), x = te({ inputs: { x: g }, backend: t10, attrs: { shape: u } });
    f[h] = x, l.push(g);
  }
  return l.forEach((h) => t10.disposeIntermediateTensorInfo(h)), f;
}
var bP = { kernelName: wa, backendName: "webgl", kernelFunc: Sre };
var Og = class {
  constructor(e, t10) {
    this.variableNames = ["x", "segmentIds"];
    let o = e.windowSize, n = e.batchSize, s = e.inSize, a = e.numSegments, i = a * Math.ceil(s / o);
    this.outputShape = [n, i];
    let p = "0.0", u = "sumValue", c = Math.floor(o / 4) * 4, l = o % 4, m = `
        sumValue += dot(values, segFilter);
    `, d = "";
    s % o > 0 && (d = `
        if (inIdx < 0 || inIdx >= ${s}) {
          return initializationValue;
        }
      `);
    let f = "";
    s % o > 0 && (f = `
        if (inIdx < 0 || inIdx >= ${s}) {
          return -1.0;
        }
      `), this.userCode = `
      const float initializationValue = ${p};

      float getValue(int batch, int inIdx) {
        ${d}
        return getX(batch, inIdx);
      }

      float getSegmentIdAtIndex(int inIdx) {
        ${f}
        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(${o}));
        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 (${l === 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 (${l === 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 (${l === 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(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, segmentIds: s } = e, { numSegments: a } = o, i = n.shape.length, p = [], u = 0, c = w.getAxesPermutation([u], i), l = n;
  c != null && (l = bt({ inputs: { x: n }, backend: t10, attrs: { perm: c } }), p.push(l), u = w.getInnerMostAxes(1, i)[0]);
  let m = w.segment_util.computeOutShape(l.shape, u, a), d = y.sizeFromShape([l.shape[u]]), f = te({ inputs: { x: l }, backend: t10, attrs: { shape: [-1, d] } });
  p.push(f);
  let h = oi(n.dtype), g = (S, k, _, $, R) => {
    let D = S.shape[0], P = S.shape[1], O = w.segment_util.segOpComputeOptimalWindowSize(P, R), M = { windowSize: O, inSize: P, batchSize: D, numSegments: R }, L = new Og(M, k), B = t10.compileAndRun(L, [S, _], $);
    if (p.push(B), B.shape[1] === R) return B;
    let z = Av({ backend: t10, attrs: { start: 0, stop: R, step: 1, dtype: "float32" } }), U = Fv({ inputs: { x: z }, backend: t10, attrs: { reps: [P / O] } });
    return p.push(z), p.push(U), g(B, k, U, $, R);
  }, x = g(f, "unsortedSegmentSum", s, h, a), b = te({ inputs: { x }, backend: t10, attrs: { shape: m } }), C = b;
  if (c != null) {
    p.push(b);
    let S = w.getUndoAxesPermutation(c);
    C = bt({ inputs: { x: C }, backend: t10, attrs: { perm: S } });
  }
  return p.forEach((S) => t10.disposeIntermediateTensorInfo(S)), C;
}
var CP = { kernelName: Qi, backendName: "webgl", kernelFunc: Ire };
var vre = [rA, nA, sA, aA, uA, pA, cA, lA, fA, hA, gA, xA, yA, bA, CA, wA, SA, IA, vA, kA, NA, _A, EA, $A, RA, PA, MA, LA, KD, zA, WA, UA, GA, HA, KA, qA, jA, XA, YA, QA, eF, tF, rF, oF, nF, sF, aF, iF, uF, pF, cF, lF, mF, dF, fF, hF, xF, yF, bF, CF, SF, IF, vF, kF, NF, TF, _F, EF, $F, HD, RF, VA, DF, AF, FF, qD, PF, OF, MF, LF, BF, zF, VF, WF, UF, GF, KF, qF, jF, XF, YF, QF, JF, t3, r32, o3, n3, s3, c3, YD, l3, m3, d3, f3, DA, h3, y3, b3, C3, w3, jD, S3, I3, v3, k3, N3, AA, a3, T3, _3, E3, ZD, $3, R3, D3, A3, F3, P3, O3, M3, L3, B3, z3, V3, W3, U3, G3, H3, TA, p3, K3, q3, j3, X3, Y3, Q3, Z3, J3, tP, rP, nP, sP, aP, iP, uP, pP, cP, u3, eA, lP, mP, dP, fP, gP, xP, tA, yP, bP, CP, g3];
for (let r15 of vre) ti(r15);
var we;
(function(r15) {
  r15[r15.float32 = 0] = "float32", r15[r15.int32 = 1] = "int32", r15[r15.bool = 2] = "bool", r15[r15.string = 3] = "string", r15[r15.complex64 = 4] = "complex64";
})(we || (we = {}));
var wu;
(function(r15) {
  r15[r15.linear = 0] = "linear", r15[r15.relu = 1] = "relu", r15[r15.relu6 = 2] = "relu6", r15[r15.prelu = 3] = "prelu", r15[r15.leakyrelu = 4] = "leakyrelu", r15[r15.sigmoid = 5] = "sigmoid", r15[r15.elu = 6] = "elu";
})(wu || (wu = {}));
var wP;
function kre(r15) {
  wP = r15.wasm.cwrap(So, null, ["number", "array", "number", "number", "array", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Nre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { a: n, b: s, bias: a, preluActivationWeights: i } = e;
  if (n.dtype !== "float32" || s.dtype !== "float32") throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");
  let { transposeA: p, transposeB: u, activation: c, leakyreluAlpha: l } = o, m = t10.dataIdMap.get(n.dataId).id, d = t10.dataIdMap.get(s.dataId).id, f = 0;
  if (a != null) {
    let R = t10.dataIdMap.get(a.dataId);
    if (R.shape.length !== 1) throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${R.shape.length}.`);
    f = R.id;
  }
  let h = i == null ? 0 : t10.dataIdMap.get(i.dataId).id, g = wu[c];
  if (g == null) throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);
  let x = p ? n.shape[2] : n.shape[1], b = u ? s.shape[1] : s.shape[2], C = Sr.assertAndGetBroadcastShape(n.shape.slice(0, -2), s.shape.slice(0, -2)), S = t10.makeOutput([...C, x, b], n.dtype), k = t10.dataIdMap.get(S.dataId).id, _ = new Uint8Array(new Int32Array(n.shape).buffer), $ = new Uint8Array(new Int32Array(s.shape).buffer);
  return wP(m, _, n.shape.length, d, $, s.shape.length, p, u, g, f, h, l || 0, k), S;
}
var SP = { kernelName: So, backendName: "wasm", setupFunc: kre, kernelFunc: Nre };
function he(r15, e) {
  let t10;
  function o(s) {
    t10 = s.wasm.cwrap(r15, null, ["number", "number", "number"]);
  }
  function n(s) {
    let { backend: a, inputs: { x: i } } = s, p = a.dataIdMap.get(i.dataId).id, u = a.makeOutput(i.shape, e || i.dtype), c = a.dataIdMap.get(u.dataId).id;
    return y.sizeFromShape(u.shape) === 0 || t10(p, we[i.dtype], c), u;
  }
  return { kernelName: r15, backendName: "wasm", setupFunc: o, kernelFunc: n };
}
var IP = he("Abs");
var vP = he(Vo);
var kP = he(Wo);
function Ge(r15, e, t10) {
  let o;
  function n(a) {
    o = a.wasm.cwrap(r15, null, ["number", "array", "number", "number", "array", "number", "number", "number"]);
  }
  function s(a) {
    let { backend: i, inputs: p } = a, { a: u, b: c } = p, l = i.dataIdMap.get(u.dataId).id, m = i.dataIdMap.get(c.dataId).id, d = t10 != null ? t10 : u.dtype, f = w.assertAndGetBroadcastShape(u.shape, c.shape), h = i.makeOutput(f, d);
    if (y.sizeFromShape(f) === 0) return h;
    let g = new Uint8Array(new Int32Array(u.shape).buffer), x = new Uint8Array(new Int32Array(c.shape).buffer), b = i.dataIdMap.get(h.dataId).id;
    return o(l, g, u.shape.length, m, x, c.shape.length, we[u.dtype], b), h;
  }
  return { kernelName: r15, backendName: "wasm", setupFunc: n, kernelFunc: s };
}
var Tre = true;
var NP = Ge("Add", Tre);
var TP;
function _re(r15) {
  TP = r15.wasm.cwrap(Uo, null, ["array", "number", "number", "number"]);
}
function Ere(r15) {
  let { inputs: e, backend: t10 } = r15, o = t10.makeOutput(e[0].shape, e[0].dtype);
  if (y.sizeFromShape(o.shape) === 0) return o;
  let n = e.map((i) => t10.dataIdMap.get(i.dataId).id), s = new Uint8Array(new Int32Array(n).buffer), a = t10.dataIdMap.get(o.dataId).id;
  return TP(s, n.length, we[o.dtype], a), o;
}
var _P = { kernelName: Uo, backendName: "wasm", setupFunc: _re, kernelFunc: Ere };
function Np(r15) {
  let { inputs: { x: e }, backend: t10 } = r15;
  if (e.dtype === "string") return ar(t10.readSync(e.dataId), e.shape, e.dtype);
  let o = t10.makeOutput(e.shape, e.dtype), n = t10.typedArrayFromHeap(e);
  return t10.typedArrayFromHeap(o).set(n), o;
}
var EP = { kernelName: Co, backendName: "wasm", kernelFunc: Np };
var $P;
function $re(r15) {
  $P = r15.wasm.cwrap(co, null, ["number", "array", "number", "number", "number", "array", "number"]);
}
function ho(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, [n, s] = Dre(e.x.shape, o.perm), a = true;
  for (let f = 0; f < s.length; f++) s[f] !== f && (a = false);
  let i = Rre(e.x.shape, o.perm), p = { dataId: e.x.dataId, shape: n, dtype: e.x.dtype };
  if (a) {
    let f = Np({ inputs: e, backend: t10 });
    return f.shape = i, f;
  }
  let u = t10.makeOutput(i, p.dtype), c = t10.dataIdMap.get(p.dataId).id, l = t10.dataIdMap.get(u.dataId).id, m = new Uint8Array(new Int32Array(s).buffer), d = new Uint8Array(new Int32Array(p.shape).buffer);
  return $P(c, d, p.shape.length, we[p.dtype], l, m, s.length), u;
}
function Rre(r15, e) {
  let t10 = new Array(r15.length);
  for (let o = 0; o < t10.length; o++) t10[o] = r15[e[o]];
  return t10;
}
function Dre(r15, e) {
  let t10 = [], o = [];
  for (let n = 0; n < r15.length; ++n) r15[n] !== 1 && t10.push(r15[n]), r15[e[n]] !== 1 && o.push(e[n]);
  for (let n = 0; n < o.length; ++n) {
    let s = -1;
    for (let a = 0; a < o.length; ++a) o[a] >= n && (s === -1 || o[s] > o[a]) && (s = a);
    o[s] = n;
  }
  return [t10, o];
}
var RP = { kernelName: co, backendName: "wasm", kernelFunc: ho, setupFunc: $re };
function Tr(r15, e, t10) {
  let o = r15.shape, n = r15.shape.length, s = y.parseAxisParam(e, o), a = s, i = w.getAxesPermutation(a, n), p = null, u = false;
  if (i != null) {
    let c = new Array(n);
    for (let d = 0; d < c.length; d++) c[d] = o[i[d]];
    a = w.getInnerMostAxes(a.length, n), p = ho({ inputs: { x: r15 }, attrs: { perm: i }, backend: t10 });
    let l = t10.dataIdMap.get(r15.dataId).id;
    t10.dataIdMap.get(p.dataId).id !== l && (u = true);
  }
  return { transposed: p, originalAxes: s, axes: a, inputWasTransposed: u };
}
var DP;
function Are(r15) {
  DP = r15.wasm.cwrap("All", null, ["number, number, number"]);
}
function Fre(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { axis: n, keepDims: s } = o, { x: a } = t10, p = e.dataIdMap.get(a.dataId).id, u = a, { transposed: c, axes: l, originalAxes: m, inputWasTransposed: d } = Tr(a, n, e);
  if (d) {
    let C = e.dataIdMap.get(c.dataId).id;
    u = c, p = C;
  }
  let f = u.shape.length;
  w.assertAxesAreInnerMostDims("all", l, f);
  let [h, g] = w.computeOutAndReduceShapes(u.shape, l), x = y.sizeFromShape(g), b = e.makeOutput(h, a.dtype);
  if (y.sizeFromShape(u.shape) !== 0) {
    let C = e.dataIdMap.get(b.dataId).id;
    DP(p, x, C);
  }
  if (d && e.disposeData(c.dataId), s) {
    let C = w.expandShapeToKeepDim(b.shape, m);
    b.shape = C;
  }
  return b;
}
var AP = { kernelName: "All", backendName: "wasm", setupFunc: Are, kernelFunc: Fre };
var FP;
function Pre(r15) {
  FP = r15.wasm.cwrap("Any", null, ["number, number, number"]);
}
function Ore(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { axis: n, keepDims: s } = o, { x: a } = t10, p = e.dataIdMap.get(a.dataId).id, u = a, { transposed: c, axes: l, originalAxes: m, inputWasTransposed: d } = Tr(a, n, e);
  if (d) {
    let C = e.dataIdMap.get(c.dataId).id;
    u = c, p = C;
  }
  let f = u.shape.length;
  w.assertAxesAreInnerMostDims("any", l, f);
  let [h, g] = w.computeOutAndReduceShapes(u.shape, l), x = y.sizeFromShape(g), b = e.makeOutput(h, a.dtype);
  if (y.sizeFromShape(u.shape) !== 0) {
    let C = e.dataIdMap.get(b.dataId).id;
    FP(p, x, C);
  }
  if (d && e.disposeData(c.dataId), s) {
    let C = w.expandShapeToKeepDim(b.shape, m);
    b.shape = C;
  }
  return b;
}
var PP = { kernelName: "Any", backendName: "wasm", setupFunc: Pre, kernelFunc: Ore };
function Mg(r15) {
  let e;
  function t10(n) {
    e = n.wasm.cwrap(r15, null, ["number", "number", "number", "number", "number"]);
  }
  function o(n) {
    let { backend: s, inputs: a, attrs: i } = n, { axis: p } = i, { x: u } = a, c = s.dataIdMap.get(u.dataId).id, l = c, m = u, { transposed: d, axes: f, inputWasTransposed: h } = Tr(u, p, s);
    if (h) {
      let k = s.dataIdMap.get(d.dataId).id;
      k !== c && (m = d, l = k);
    }
    let g = m.shape.slice(0, -1), x = s.makeOutput(g, "int32"), b = s.dataIdMap.get(x.dataId).id, C = y.sizeFromShape(x.shape), S = m.shape[f[0]];
    return e(l, we[m.dtype], C, S, b), h && s.disposeData(d.dataId), x;
  }
  return { kernelName: r15, backendName: "wasm", setupFunc: t10, kernelFunc: o };
}
var OP = Mg(Ys);
var MP = Mg(Qs);
var LP = he(Ko);
var BP = he(qo);
var zP = he(jo);
var VP = Ge(Yo, false);
var WP = he(Xo);
var UP;
function Mre(r15) {
  UP = r15.wasm.cwrap(Qo, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Lre(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, n = e.x, s = o.dataIdMap.get(n.dataId).id, { filterSize: a, strides: i, pad: p, dimRoundingMode: u } = t10, c = w.computePool2DInfo(n.shape, a, i, 1, p, u), l = c.filterHeight, m = c.filterWidth, d = c.padInfo.top, f = c.padInfo.right, h = c.padInfo.bottom, g = c.padInfo.left, x = c.strideHeight, b = c.strideWidth, C = 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 S = o.makeOutput(c.outShape, "float32"), k = o.dataIdMap.get(S.dataId).id;
  return UP(s, n.shape[0], n.shape[1], n.shape[2], l, m, d, f, h, g, x, b, C, k), S;
}
var GP = { kernelName: Qo, backendName: "wasm", setupFunc: Mre, kernelFunc: Lre };
var HP;
function Bre(r15) {
  HP = r15.wasm.cwrap("AvgPool3D", null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function zre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { filterSize: s, strides: a, pad: i, dimRoundingMode: p, dataFormat: u } = o, c = w.computePool3DInfo(n.shape, s, a, 1, i, p, u), l = t10.makeOutput(c.outShape, n.dtype);
  return HP(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(l.dataId).id, c.batchSize, c.inChannels, c.inDepth, c.inHeight, c.inWidth, c.outDepth, c.outHeight, c.outWidth, c.strideDepth, c.strideHeight, c.strideWidth, c.dilationDepth, c.dilationHeight, c.dilationWidth, c.effectiveFilterDepth, c.effectiveFilterHeight, c.effectiveFilterWidth, c.padInfo.front, c.padInfo.top, c.padInfo.left), l;
}
var KP = { kernelName: Zs, backendName: "wasm", setupFunc: Bre, kernelFunc: zre };
var qP;
function Vre(r15) {
  qP = r15.wasm.cwrap("AvgPool3DGrad", 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"]);
}
function Wre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s } = e, { filterSize: a, strides: i, pad: p, dimRoundingMode: u } = o, c = w.computePool3DInfo(s.shape, a, i, 1, p, u), l = t10.makeOutput(s.shape, s.dtype);
  return qP(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(l.dataId).id, c.batchSize, c.inChannels, c.inDepth, c.inHeight, c.inWidth, c.outDepth, c.outHeight, c.outWidth, c.strideDepth, c.strideHeight, c.strideWidth, c.dilationDepth, c.dilationHeight, c.dilationWidth, c.effectiveFilterDepth, c.effectiveFilterHeight, c.effectiveFilterWidth, c.padInfo.front, c.padInfo.top, c.padInfo.left, c.filterDepth, c.filterHeight, c.filterWidth), l;
}
var jP = { kernelName: Ri, backendName: "wasm", setupFunc: Vre, kernelFunc: Wre };
var XP;
function Ure(r15) {
  XP = r15.wasm.cwrap("AvgPoolGrad", null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Gre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s } = e, { filterSize: a, strides: i, pad: p } = o, u = w.computePool2DInfo(s.shape, a, i, 1, p), c = t10.makeOutput(s.shape, s.dtype);
  return XP(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(c.dataId).id, u.batchSize, u.inChannels, u.inHeight, u.inWidth, u.outHeight, u.outWidth, u.strideHeight, u.strideWidth, u.dilationHeight, u.dilationWidth, u.effectiveFilterHeight, u.effectiveFilterWidth, u.padInfo.top, u.padInfo.left, u.filterHeight, u.filterWidth), c;
}
var YP = { kernelName: $i, backendName: "wasm", setupFunc: Ure, kernelFunc: Gre };
function zt(r15) {
  let { inputs: e, attrs: t10 } = r15, { x: o } = e, { shape: n } = t10, s = y.sizeFromShape(o.shape), a = y.inferFromImplicitShape(n, s);
  return y.assert(s === y.sizeFromShape(a), () => `new shape: ${a}, old shape: ${o.shape}. New shape and old shape must have the same number of elements.`), r15.backend.incRef(o.dataId), { dataId: o.dataId, shape: a, dtype: o.dtype };
}
var QP = { kernelName: da, backendName: "wasm", kernelFunc: zt };
var ZP;
function Hre(r15) {
  ZP = r15.wasm.cwrap(Zo, null, ["number", "array", "number", "number", "array", "number", "number", "number", "number"]);
}
function Kre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { a: n, b: s } = e, { transposeA: a, transposeB: i } = o;
  if (n.dtype !== "float32" || s.dtype !== "float32") throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");
  let p = n.shape.length, u = s.shape.length, c = a ? n.shape[p - 2] : n.shape[p - 1], l = i ? s.shape[u - 1] : s.shape[u - 2], m = a ? n.shape[p - 1] : n.shape[p - 2], d = i ? s.shape[u - 2] : s.shape[u - 1], f = n.shape.slice(0, -2), h = s.shape.slice(0, -2), g = y.sizeFromShape(f), x = y.sizeFromShape(h), C = Sr.assertAndGetBroadcastShape(n.shape.slice(0, -2), s.shape.slice(0, -2)).concat([m, d]);
  y.assert(c === l, () => `Error in matMul: inner shapes (${c}) and (${l}) of Tensors with shapes ${n.shape} and ${s.shape} and transposeA=${a} and transposeB=${i} must match.`);
  let S = a ? [g, c, m] : [g, m, c], k = i ? [x, d, l] : [x, l, d], _ = zt({ inputs: { x: n }, backend: t10, attrs: { shape: S } }), $ = zt({ inputs: { x: s }, backend: t10, attrs: { shape: k } }), R = t10.dataIdMap.get(_.dataId).id, D = t10.dataIdMap.get($.dataId).id, P = a ? _.shape[2] : _.shape[1], O = i ? $.shape[1] : $.shape[2], M = Math.max(g, x), L = t10.makeOutput([M, P, O], _.dtype), B = t10.dataIdMap.get(L.dataId).id, z = new Uint8Array(new Int32Array(_.shape).buffer), U = new Uint8Array(new Int32Array($.shape).buffer);
  return ZP(R, z, _.shape.length, D, U, $.shape.length, a, i, B), t10.disposeData(_.dataId), t10.disposeData($.dataId), L.shape = C, L;
}
var JP = { kernelName: Zo, backendName: "wasm", setupFunc: Hre, kernelFunc: Kre };
function Po(r15) {
  let { inputs: { x: e }, attrs: { begin: t10, size: o }, backend: n } = r15, [s, a] = pt.parseSliceParams(e, t10, o), i = pt.isSliceContinous(e.shape, s, a), p = n.readSync(e.dataId), u = n.makeOutput(a, e.dtype), c = y.computeStrides(e.shape), l = n.dataIdMap.get(u.dataId);
  if (i) {
    let f = pt.computeFlatOffset(s, c);
    return e.dtype === "string" ? l.stringBytes = p.slice(f, f + y.sizeFromShape(a)) : n.typedArrayFromHeap(u).set(p.subarray(f, f + y.sizeFromShape(a))), u;
  }
  if (e.dtype === "string") {
    let f = pp(p, s, a, e.shape, e.dtype);
    return l.stringBytes = f, u;
  }
  let m = n.typedArrayFromHeap(u), d = e.shape.length;
  if (d === 2) qre(p, c[0], m, s, a);
  else if (d === 3) jre(p, c[0], c[1], m, s, a);
  else if (d === 4) Xre(p, c[0], c[1], c[2], m, s, a);
  else {
    let f = pp(p, s, a, e.shape, e.dtype);
    m.set(f);
  }
  return u;
}
function qre(r15, e, t10, o, n) {
  let s = 0, a = o[0], i = o[1], p = a + n[0];
  for (let u = a; u < p; u++) {
    let c = u * e + i;
    t10.set(r15.subarray(c, c + n[1]), s), s += n[1];
  }
}
function jre(r15, e, t10, o, n, s) {
  let a = 0, i = n[0], p = n[1], u = n[2], c = i + s[0], l = p + s[1];
  for (let m = i; m < c; m++) for (let d = p; d < l; d++) {
    let f = m * e + d * t10 + u;
    o.set(r15.subarray(f, f + s[2]), a), a += s[2];
  }
}
function Xre(r15, e, t10, o, n, s, a) {
  let i = 0, p = s[0], u = s[1], c = s[2], l = p + a[0], m = u + a[1], d = c + a[2], f = s[3];
  for (let h = p; h < l; h++) for (let g = u; g < m; g++) for (let x = c; x < d; x++) {
    let b = h * e + g * t10 + x * o + f;
    n.set(r15.subarray(b, b + a[3]), i), i += a[3];
  }
}
var eO = { kernelName: ha, backendName: "wasm", kernelFunc: Po };
function Yre(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { blockShape: s, crops: a } = o, i = s.reduce((x, b) => x * b), p = w.getReshaped(n.shape, s, i), u = w.getPermuted(p.length, s.length), c = w.getReshapedPermuted(n.shape, s, i), l = w.getSliceBeginCoords(a, s.length), m = w.getSliceSize(c, a, s.length), d = zt({ inputs: { x: n }, backend: t10, attrs: { shape: p } }), f = ho({ inputs: { x: d }, backend: t10, attrs: { perm: u } }), h = zt({ inputs: { x: f }, backend: t10, attrs: { shape: c } }), g = Po({ inputs: { x: h }, backend: t10, attrs: { begin: l, size: m } });
  return t10.disposeData(d.dataId), t10.disposeData(f.dataId), t10.disposeData(h.dataId), g;
}
var tO = { kernelName: Js, backendName: "wasm", kernelFunc: Yre };
var rO;
function Qre(r15) {
  rO = r15.wasm.cwrap(Jo, null, ["number", "number", "boolean", "number", "number", "number"]);
}
function Zre(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { x: n, weights: s } = t10, { size: a } = o, i = s.shape.reduce((l, m) => l * m, 1) !== 0, p = n.shape.length === 1 ? [a] : [n.shape[0], a], u = e.makeOutput(p, s.dtype);
  function c(l) {
    return e.dataIdMap.get(l.dataId).id;
  }
  return rO(c(n), a, i, c(s), we[s.dtype], c(u)), u;
}
var oO = { kernelName: Jo, backendName: "wasm", setupFunc: Qre, kernelFunc: Zre };
var Jre = true;
var nO = Ge(qa, Jre);
function eoe(r15) {
  let { inputs: e, backend: t10 } = r15, { s0: o, s1: n } = e, s = t10.typedArrayFromHeap(o), a = t10.typedArrayFromHeap(n), i = w.assertAndGetBroadcastShape(Array.from(s), Array.from(a));
  return t10.makeOutput([i.length], "int32", void 0, new Int32Array(i));
}
var sO = { kernelName: ea, backendName: "wasm", kernelFunc: eoe };
function Mr(r15) {
  let { inputs: { x: e }, attrs: { dtype: t10 }, backend: o } = r15, n = o.makeOutput(e.shape, t10), s = o.typedArrayFromHeap(e);
  return o.typedArrayFromHeap(n).set(s), n;
}
var aO = { kernelName: yo, backendName: "wasm", kernelFunc: Mr };
var iO = he(en);
var uO;
function toe(r15) {
  uO = r15.wasm.cwrap(bo, null, ["number", "number", "number", "number"]);
}
function roe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { clipValueMin: s, clipValueMax: a } = o, i = t10.dataIdMap.get(n.dataId).id, p = t10.makeOutput(n.shape, n.dtype), u = t10.dataIdMap.get(p.dataId).id;
  return uO(i, s, a, u), p;
}
var pO = { kernelName: bo, backendName: "wasm", setupFunc: toe, kernelFunc: roe };
function Pv(r15) {
  let { inputs: e, backend: t10 } = r15, o = y.parseAxisParam(r15.attrs.axis, e[0].shape)[0], n = e.map((d) => d.shape);
  w.assertParamsConsistent(n, o);
  let s = w.computeOutShape(e.map((d) => d.shape), o), a = e.filter((d) => y.sizeFromShape(d.shape) > 0);
  if (a.length === 1) return Np({ inputs: { x: a[0] }, backend: t10 });
  let i = t10.makeOutput(s, e[0].dtype);
  if (y.sizeFromShape(s) === 0) return i;
  if (a[0].dtype === "string") {
    let d = a.map((C) => {
      let k = [-1, y.sizeFromShape(C.shape.slice(o))];
      return zt({ inputs: { x: C }, backend: t10, attrs: { shape: k } });
    }), f = d.map((C) => ({ vals: t10.readSync(C.dataId), shape: C.shape }));
    s = w.computeOutShape(d.map((C) => C.shape), 1);
    let h = d[0].shape[0] === 1, g = ap(f, s, e[0].dtype, h), x = w.computeOutShape(a.map((C) => C.shape), o);
    i.shape = x;
    let b = t10.dataIdMap.get(i.dataId);
    return b.stringBytes = w.fromStringArrayToUint8(g), d.forEach((C) => t10.disposeData(C.dataId)), i;
  }
  let p = y.sizeFromShape(a[0].shape.slice(0, o)), u = 0, c = a.map((d) => {
    let f = y.sizeFromShape(d.shape.slice(o));
    return u += f, f;
  }), l = a.map((d) => t10.typedArrayFromHeap(d)), m = t10.typedArrayFromHeap(i);
  for (let d = 0; d < p; d++) {
    let f = d * u;
    for (let h = 0; h < l.length; h++) {
      let g = c[h], x = d * g, b = l[h].subarray(x, x + g);
      m.set(b, f), f += g;
    }
  }
  return i;
}
var cO = { kernelName: ta, backendName: "wasm", kernelFunc: Pv };
var lO;
function ooe(r15) {
  lO = r15.wasm.cwrap(tn, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function noe(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { x: n, filter: s } = e, a = o.dataIdMap.get(n.dataId).id, i = o.dataIdMap.get(s.dataId).id, { strides: p, dilations: u, pad: c, dimRoundingMode: l, dataFormat: m } = t10, d = w.convertConv2DDataFormat(m), f = w.computeConv2DInfo(n.shape, s.shape, p, u, c, l, false, d), h = f.filterHeight, g = f.filterWidth, x = f.padInfo.top, b = f.padInfo.right, C = f.padInfo.bottom, S = f.padInfo.left, k = f.dilationHeight, _ = f.dilationWidth, $ = f.strideHeight, R = f.strideWidth, D = f.inChannels, P = f.outChannels, O = f.padInfo.type === "SAME" ? 1 : 0;
  if (f.dataFormat !== "channelsLast") throw new Error(`wasm backend Conv2D does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);
  let M = o.makeOutput(f.outShape, "float32"), L = o.dataIdMap.get(M.dataId).id;
  return lO(a, n.shape[0], n.shape[1], n.shape[2], i, h, g, x, b, C, S, O, k, _, $, R, D, P, L), M;
}
var mO = { kernelName: tn, backendName: "wasm", setupFunc: ooe, kernelFunc: noe };
var dO;
function soe(r15) {
  dO = r15.wasm.cwrap(rn, 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 aoe(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { dy: n, filter: s } = t10, { strides: a, pad: i, dataFormat: p, dimRoundingMode: u, inputShape: c } = o, l = 1, m = w.convertConv2DDataFormat(p), d = w.computeConv2DInfo(c, s.shape, a, l, i, u, false, m), { batchSize: f, filterHeight: h, filterWidth: g, inChannels: x, inHeight: b, inWidth: C, outChannels: S, outHeight: k, outWidth: _, strideHeight: $, strideWidth: R } = d, D = h - 1 - d.padInfo.top, P = g - 1 - d.padInfo.left, O = d.dataFormat === "channelsLast", M = y.computeStrides(d.inShape), L = y.computeStrides(n.shape), [B, z, U] = y.computeStrides(s.shape), j = M[0], q = O ? M[1] : M[2], Y = O ? M[2] : 1, J = O ? 1 : M[1], re = L[0], ne = O ? L[1] : L[2], ee = O ? L[2] : 1, oe = O ? 1 : L[1], ie = e.makeOutput(d.inShape, "float32"), le = e.dataIdMap.get(ie.dataId).id, be = e.dataIdMap.get(n.dataId).id, _e = e.dataIdMap.get(s.dataId).id;
  return dO(be, _e, f, h, g, b, C, x, k, _, S, $, R, D, P, B, z, U, j, q, Y, J, re, ne, ee, oe, le), ie;
}
var fO = { kernelName: rn, backendName: "wasm", setupFunc: soe, kernelFunc: aoe };
var hO;
function ioe(r15) {
  hO = r15.wasm.cwrap(on, 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"]);
}
function uoe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s } = e, { strides: a, pad: i, dilations: p } = o;
  if (n.dtype !== "float32") throw new Error(`Tensor x must have dtype float32, got ${n.dtype}`);
  if (s.dtype !== "float32") throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);
  let u = w.computeConv3DInfo(n.shape, s.shape, a, p, i), c = t10.makeOutput(u.outShape, n.dtype);
  return hO(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(s.dataId).id, t10.dataIdMap.get(c.dataId).id, u.batchSize, u.inDepth, u.inHeight, u.inWidth, u.inChannels, u.outDepth, u.outHeight, u.outWidth, u.outChannels, u.strideDepth, u.strideHeight, u.strideWidth, u.dilationDepth, u.dilationHeight, u.dilationWidth, u.filterDepth, u.filterHeight, u.filterWidth, u.padInfo.front, u.padInfo.top, u.padInfo.left), c;
}
var gO = { kernelName: on, backendName: "wasm", setupFunc: ioe, kernelFunc: uoe };
var xO;
function poe(r15) {
  xO = r15.wasm.cwrap(ja, 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"]);
}
function coe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, dy: s } = e, { strides: a, pad: i, filterShape: p } = o;
  if (n.dtype !== "float32") throw new Error(`Tensor dy must have dtype float32, got ${n.dtype}`);
  if (s.dtype !== "float32") throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);
  let u = w.computeConv3DInfo(n.shape, p, a, 1, i), c = t10.makeOutput(u.filterShape, s.dtype);
  return xO(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(s.dataId).id, t10.dataIdMap.get(c.dataId).id, u.batchSize, u.inDepth, u.inHeight, u.inWidth, u.inChannels, u.outDepth, u.outHeight, u.outWidth, u.outChannels, u.strideDepth, u.strideHeight, u.strideWidth, u.dilationDepth, u.dilationHeight, u.dilationWidth, u.filterDepth, u.filterHeight, u.filterWidth, u.padInfo.front, u.padInfo.top, u.padInfo.left), c;
}
var yO = { kernelName: ja, backendName: "wasm", setupFunc: poe, kernelFunc: coe };
var bO;
function loe(r15) {
  bO = r15.wasm.cwrap(nn, 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"]);
}
function moe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, filter: s } = e, { pad: a, strides: i, inputShape: p } = o;
  if (n.dtype !== "float32") throw new Error(`Tensor dy must have dtype float32, got ${n.dtype}`);
  if (s.dtype !== "float32") throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);
  let u = w.computeConv3DInfo(p, s.shape, i, 1, a), c = t10.makeOutput(u.inShape, n.dtype);
  return bO(t10.dataIdMap.get(s.dataId).id, t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(c.dataId).id, u.batchSize, u.inDepth, u.inHeight, u.inWidth, u.inChannels, u.outDepth, u.outHeight, u.outWidth, u.outChannels, u.strideDepth, u.strideHeight, u.strideWidth, u.dilationDepth, u.dilationHeight, u.dilationWidth, u.filterDepth, u.filterHeight, u.filterWidth, u.padInfo.front, u.padInfo.top, u.padInfo.left), c;
}
var CO = { kernelName: nn, backendName: "wasm", setupFunc: loe, kernelFunc: moe };
var wO = he("Cos");
var SO = he(an);
var Ov;
(function(r15) {
  r15[r15.bilinear = 0] = "bilinear", r15[r15.nearest = 1] = "nearest";
})(Ov || (Ov = {}));
var IO;
function doe(r15) {
  IO = r15.wasm.cwrap(cn, null, ["number", "number", "number", "number", "array", "number", "number", "number", "number", "number"]);
}
function foe(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { method: n, extrapolationValue: s, cropSize: a } = o, { image: i, boxes: p, boxInd: u } = t10, c = p.shape[0], [l, m] = a, d = [c, l, m, i.shape[3]], f = e.dataIdMap.get(i.dataId), h;
  i.dtype !== "float32" && (h = Mr({ backend: e, inputs: { x: i }, attrs: { dtype: "float32" } }), f = e.dataIdMap.get(h.dataId));
  let g = f.id, x = e.dataIdMap.get(p.dataId).id, b = e.dataIdMap.get(u.dataId).id, C = e.makeOutput(d, "float32"), S = e.dataIdMap.get(C.dataId).id, k = new Uint8Array(new Int32Array(i.shape).buffer);
  return IO(g, x, b, c, k, l, m, Ov[n], s, S), h != null && e.disposeData(h.dataId), C;
}
var vO = { kernelName: cn, backendName: "wasm", setupFunc: doe, kernelFunc: foe };
var kO;
function hoe(r15) {
  kO = r15.wasm.cwrap(un, null, ["number", "number", "number", "number", "number", "number"]);
}
function goe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, exclusive: a, reverse: i } = o, p = n.shape.length;
  y.assert(n.dtype === "float32" || n.dtype === "int32", () => `cumprod does not support ${n.dtype} tensors in the WASM backend`);
  let u = w.getAxesPermutation([s], p), c = n;
  u !== null && (c = ho({ inputs: { x: n }, attrs: { perm: u }, backend: t10 }));
  let l = w.getInnerMostAxes(1, p)[0];
  w.assertAxesAreInnerMostDims("cumprod", [l], p);
  let m = t10.makeOutput(c.shape, c.dtype), d = c.shape[l], f = t10.dataIdMap.get(c.dataId).id, h = t10.dataIdMap.get(m.dataId).id;
  kO(f, a ? 1 : 0, i ? 1 : 0, d, h, we[n.dtype]);
  let g = m;
  if (u !== null) {
    let x = w.getUndoAxesPermutation(u);
    g = ho({ inputs: { x: m }, attrs: { perm: x }, backend: t10 }), t10.disposeData(c.dataId), t10.disposeData(m.dataId);
  }
  return g;
}
var NO = { kernelName: un, backendName: "wasm", setupFunc: hoe, kernelFunc: goe };
var TO;
function xoe(r15) {
  TO = r15.wasm.cwrap(pn, null, ["number", "number", "number", "number", "number", "number"]);
}
function yoe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, exclusive: a, reverse: i } = o, p = n.shape.length;
  y.assert(n.dtype === "float32" || n.dtype === "int32", () => `cumsum does not support ${n.dtype} tensors in the WASM backend`);
  let u = w.getAxesPermutation([s], p), c = n;
  u !== null && (c = ho({ inputs: { x: n }, attrs: { perm: u }, backend: t10 }));
  let l = w.getInnerMostAxes(1, p)[0];
  w.assertAxesAreInnerMostDims("cumsum", [l], p);
  let m = t10.makeOutput(c.shape, c.dtype), d = c.shape[l], f = t10.dataIdMap.get(c.dataId).id, h = t10.dataIdMap.get(m.dataId).id;
  TO(f, a ? 1 : 0, i ? 1 : 0, d, h, we[n.dtype]);
  let g = m;
  if (u !== null) {
    let x = w.getUndoAxesPermutation(u);
    g = ho({ inputs: { x: m }, attrs: { perm: x }, backend: t10 }), t10.disposeData(c.dataId), t10.disposeData(m.dataId);
  }
  return g;
}
var _O = { kernelName: pn, backendName: "wasm", setupFunc: xoe, kernelFunc: yoe };
var EO;
function boe(r15) {
  EO = r15.wasm.cwrap("DenseBincount", null, ["number", "array", "number", "number", "boolean", "number", "number", "boolean", "number"]);
}
function Coe(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { x: n, weights: s } = t10, { size: a, binaryOutput: i } = o, p = s.shape.reduce((m, d) => m * d, 1) !== 0, u = n.shape.length === 1 ? [a] : [n.shape[0], a], c = e.makeOutput(u, s.dtype);
  function l(m) {
    return e.dataIdMap.get(m.dataId).id;
  }
  return EO(l(n), new Uint8Array(new Int32Array(n.shape).buffer), n.shape.length, a, p, l(s), we[s.dtype], i, l(c)), c;
}
var $O = { kernelName: ra, backendName: "wasm", setupFunc: boe, kernelFunc: Coe };
var RO;
function woe(r15) {
  RO = r15.wasm.cwrap(ln, null, ["number", "number", "number", "array", "number", "array", "array", "number", "number"]);
}
function Soe(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { x: n } = t10, { blockSize: s, dataFormat: a } = o, i = n.shape[0], p = a === "NHWC" ? n.shape[1] : n.shape[2], u = a === "NHWC" ? n.shape[2] : n.shape[3], c = a === "NHWC" ? n.shape[3] : n.shape[1], l = p * s, m = u * s, d = c / (s * s), f = a === "NHWC" ? [i, l, m, d] : [i, d, l, m], h = e.makeOutput(f, "float32"), x = e.dataIdMap.get(n.dataId).id, b = new Uint8Array(new Int32Array(y.computeStrides(n.shape)).buffer), C = new Uint8Array(new Int32Array(f).buffer), S = new Uint8Array(new Int32Array(y.computeStrides(f)).buffer), k = e.dataIdMap.get(h.dataId).id;
  return RO(x, s, a === "NHWC" ? 1 : 0, b, n.shape.length - 1, C, S, f.length, k), h;
}
var DO = { kernelName: ln, backendName: "wasm", setupFunc: woe, kernelFunc: Soe };
var AO;
function Ioe(r15) {
  AO = r15.wasm.cwrap(mn, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function voe(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { x: n, filter: s } = e, a = o.dataIdMap.get(n.dataId).id, i = o.dataIdMap.get(s.dataId).id, { strides: p, dilations: u, pad: c, dimRoundingMode: l } = t10, m = u == null ? [1, 1] : u, d = w.computeConv2DInfo(n.shape, s.shape, p, m, c, l, true), f = d.filterHeight, h = d.filterWidth, g = d.padInfo.top, x = d.padInfo.right, b = d.padInfo.bottom, C = d.padInfo.left, S = d.dilationHeight, k = d.dilationWidth, _ = d.strideHeight, $ = d.strideWidth, R = d.inChannels, D = d.outChannels, P = d.padInfo.type === "SAME" ? 1 : 0;
  if (d.dataFormat !== "channelsLast") throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);
  let O = o.makeOutput(d.outShape, "float32"), M = o.dataIdMap.get(O.dataId).id;
  return AO(a, n.shape[0], n.shape[1], n.shape[2], i, f, h, g, x, b, C, P, S, k, _, $, R, D, M), O;
}
var FO = { kernelName: mn, backendName: "wasm", setupFunc: Ioe, kernelFunc: voe };
var PO;
function koe(r15) {
  PO = r15.wasm.cwrap("Diag", null, ["number", "number", "number", "number"]);
}
function Noe(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e, n = y.sizeFromShape(o.shape), s = t10.makeOutput([...o.shape, ...o.shape], o.dtype);
  return PO(t10.dataIdMap.get(o.dataId).id, we[o.dtype], n, t10.dataIdMap.get(s.dataId).id), s;
}
var OO = { kernelName: oa, backendName: "wasm", setupFunc: koe, kernelFunc: Noe };
var MO;
function Toe(r15) {
  MO = r15.wasm.cwrap(dn, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function _oe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s } = e, { strides: a, pad: i, dilations: p } = o;
  if (n.dtype !== s.dtype) throw new Error(`Dilation2D error: x must have the same dtype as filter. Got ${n.dtype} and ${s.dtype}`);
  let u = w.computeDilation2DInfo(n.shape, s.shape, a, i, "NHWC", p), c = t10.makeOutput(u.outShape, n.dtype);
  return MO(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(s.dataId).id, t10.dataIdMap.get(c.dataId).id, we[n.dtype], u.batchSize, u.inChannels, u.inHeight, u.inWidth, u.outHeight, u.outWidth, u.strideHeight, u.strideWidth, u.dilationHeight, u.dilationWidth, u.filterHeight, u.filterWidth, u.padInfo.top, u.padInfo.left), c;
}
var LO = { kernelName: dn, backendName: "wasm", setupFunc: Toe, kernelFunc: _oe };
var BO;
function Eoe(r15) {
  BO = r15.wasm.cwrap(Li, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function $oe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s, dy: a } = e, { strides: i, pad: p, dilations: u } = o;
  if (n.dtype !== s.dtype || n.dtype !== a.dtype) throw new Error(`Dilation2DBackpropFilter error: x must have the same dtype as filter and dy. Got ${n.dtype}, ${s.dtype}, and ${a.dtype}`);
  let c = w.computeDilation2DInfo(n.shape, s.shape, i, p, "NHWC", u), l = t10.makeOutput(s.shape, s.dtype);
  return BO(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(s.dataId).id, t10.dataIdMap.get(a.dataId).id, t10.dataIdMap.get(l.dataId).id, we[n.dtype], c.batchSize, c.inChannels, c.inHeight, c.inWidth, c.outHeight, c.outWidth, c.strideHeight, c.strideWidth, c.dilationHeight, c.dilationWidth, c.filterHeight, c.filterWidth, c.padInfo.top, c.padInfo.left), l;
}
var zO = { kernelName: Li, backendName: "wasm", setupFunc: Eoe, kernelFunc: $oe };
var VO;
function Roe(r15) {
  VO = r15.wasm.cwrap(Mi, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Doe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s, dy: a } = e, { strides: i, pad: p, dilations: u } = o;
  if (n.dtype !== s.dtype || n.dtype !== a.dtype) throw new Error(`Dilation2DBackpropInput error: x must have the same dtype as filter and dy. Got ${n.dtype}, ${s.dtype}, and ${a.dtype}`);
  let c = w.computeDilation2DInfo(n.shape, s.shape, i, p, "NHWC", u), l = t10.makeOutput(n.shape, n.dtype);
  return VO(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(s.dataId).id, t10.dataIdMap.get(a.dataId).id, t10.dataIdMap.get(l.dataId).id, we[n.dtype], c.batchSize, c.inChannels, c.inHeight, c.inWidth, c.outHeight, c.outWidth, c.strideHeight, c.strideWidth, c.dilationHeight, c.dilationWidth, c.filterHeight, c.filterWidth, c.padInfo.top, c.padInfo.left), l;
}
var WO = { kernelName: Mi, backendName: "wasm", setupFunc: Roe, kernelFunc: Doe };
var UO = he("Elu");
var GO;
function Aoe(r15) {
  GO = r15.wasm.cwrap(Xa, null, ["number", "number", "number"]);
}
function Foe(r15) {
  let { inputs: e, backend: t10 } = r15, { dy: o, y: n } = e, s = t10.makeOutput(n.shape, "float32"), a = (i) => t10.dataIdMap.get(i.dataId).id;
  return GO(a(n), a(o), a(s)), s;
}
var HO = { kernelName: Xa, backendName: "wasm", setupFunc: Aoe, kernelFunc: Foe };
var Poe = false;
var KO = Ge(xn, Poe, "bool");
var qO = he("Erf");
var jO = he("Exp", "float32");
function Lg(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { input: n } = e, { dim: s } = t10, a = n.shape.length, i = n.shape.slice(), p = s;
  return s < 0 && (y.assert(-(a + 1) <= s, () => `Axis must be in the interval [${-(a + 1)}, ${a}]`), p = a + s + 1), i.splice(p, 0, 1), zt({ inputs: { x: n }, backend: o, attrs: { shape: i } });
}
var XO = { kernelName: na, backendName: "wasm", kernelFunc: Lg };
var YO = he(bn, "float32");
function Mv(r15) {
  let { attrs: { shape: e, value: t10 }, backend: o } = r15, { attrs: { dtype: n } } = r15;
  n = n || y.inferDtype(t10);
  let s = o.makeOutput(e, n);
  return o.typedArrayFromHeap(s).fill(t10), s;
}
var QO = { kernelName: sa, backendName: "wasm", kernelFunc: Mv };
var ZO;
function Ooe(r15) {
  ZO = r15.wasm.cwrap(Cn, null, ["number", "number", "number", "number", "number", "number"]);
}
function Moe(r15) {
  let { inputs: e, backend: t10 } = r15, { image: o } = e, n = t10.makeOutput(o.shape, o.dtype), s = t10.dataIdMap.get(o.dataId).id, a = t10.dataIdMap.get(n.dataId).id, [i, p, u, c] = o.shape;
  return ZO(s, i, p, u, c, a), n;
}
var JO = { kernelName: Cn, backendName: "wasm", kernelFunc: Moe, setupFunc: Ooe };
var eM = he(wn);
var Loe = false;
var tM = Ge(Sn, Loe);
var rM;
function Boe(r15) {
  rM = r15.wasm.cwrap(In, null, ["number", "number", "number", "number", "number", "number", "number"]);
}
function zoe(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { varianceEpsilon: n } = o, { x: s, mean: a, variance: i, offset: p, scale: u } = t10, c = e.dataIdMap.get(s.dataId).id, l = e.dataIdMap.get(a.dataId).id, m = e.dataIdMap.get(i.dataId).id, d = p != null ? e.dataIdMap.get(p.dataId).id : 0, f = u != null ? e.dataIdMap.get(u.dataId).id : 0, h = e.makeOutput(s.shape, s.dtype);
  if (y.sizeFromShape(s.shape) === 0) return h;
  let g = e.dataIdMap.get(h.dataId).id;
  return rM(c, l, m, d, f, n, g), h;
}
var oM = { kernelName: In, backendName: "wasm", setupFunc: Boe, kernelFunc: zoe };
var nM;
function Voe(r15) {
  nM = r15.wasm.cwrap(Io, 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 Woe(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { x: n, filter: s, bias: a, preluActivationWeights: i } = e, { strides: p, pad: u, dilations: c, dataFormat: l, dimRoundingMode: m, activation: d, leakyreluAlpha: f } = t10, h = w.computeConv2DInfo(n.shape, s.shape, p, c, u, m), g = wu[d];
  if (g == null) throw new Error(`${d} activation not yet supported for FusedConv2D in the wasm backend.`);
  let x = o.dataIdMap.get(n.dataId).id, b = o.dataIdMap.get(s.dataId).id, C = h.outChannels, S = 0;
  if (a != null) {
    let ee = o.dataIdMap.get(a.dataId);
    if (ee.shape.length !== 1) throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${ee.shape.length}.`);
    if (ee.shape[0] !== C) throw new Error(`FusedConv2D bias shape (${ee.shape}) does not match the number of output channels (${C})`);
    S = ee.id;
  }
  let k = h.filterHeight, _ = h.filterWidth, $ = h.padInfo.top, R = h.padInfo.right, D = h.padInfo.bottom, P = h.padInfo.left, O = h.dilationHeight, M = h.dilationWidth, L = h.strideHeight, B = h.strideWidth, z = h.inChannels, U = h.padInfo.type === "SAME" ? 1 : 0, j = h.batchSize, q = h.inHeight, Y = h.inWidth;
  if (l !== "NHWC") throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${l}'. Please use 'NHWC'.`);
  let J = o.makeOutput(h.outShape, "float32"), re = o.dataIdMap.get(J.dataId).id, ne = i == null ? 0 : o.dataIdMap.get(i.dataId).id;
  return nM(x, j, q, Y, b, k, _, S, $, R, D, P, U, O, M, L, B, z, C, g, ne, f || 0, re), J;
}
var sM = { kernelName: Io, backendName: "wasm", setupFunc: Voe, kernelFunc: Woe };
var aM;
function Uoe(r15) {
  aM = r15.wasm.cwrap(vo, 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 Goe(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { x: n, filter: s, bias: a, preluActivationWeights: i } = e, { strides: p, pad: u, dilations: c, dataFormat: l, dimRoundingMode: m, activation: d, leakyreluAlpha: f } = t10, h = w.computeConv2DInfo(n.shape, s.shape, p, c, u, m, true), g = wu[d];
  if (g == null) throw new Error(`${d} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);
  let x = o.dataIdMap.get(n.dataId).id, b = o.dataIdMap.get(s.dataId).id, C = h.outChannels, S = 0;
  if (a != null) {
    let ee = o.dataIdMap.get(a.dataId);
    if (ee.shape.length !== 1) throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${ee.shape.length}.`);
    if (ee.shape[0] !== C) throw new Error(`FusedDepthwiseConv2D bias shape (${ee.shape}) does not match the number of output channels (${C})`);
    S = ee.id;
  }
  let k = h.filterHeight, _ = h.filterWidth, $ = h.padInfo.top, R = h.padInfo.right, D = h.padInfo.bottom, P = h.padInfo.left, O = h.dilationHeight, M = h.dilationWidth, L = h.strideHeight, B = h.strideWidth, z = h.inChannels, U = h.padInfo.type === "SAME" ? 1 : 0, j = h.batchSize, q = h.inHeight, Y = h.inWidth;
  if (l !== "NHWC") throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${l}'. Please use 'NHWC'.`);
  let J = o.makeOutput(h.outShape, "float32"), re = o.dataIdMap.get(J.dataId).id, ne = i == null ? 0 : o.dataIdMap.get(i.dataId).id;
  return aM(x, j, q, Y, b, k, _, S, $, R, D, P, U, O, M, L, B, z, C, g, ne, f || 0, re), J;
}
var iM = { kernelName: vo, backendName: "wasm", setupFunc: Uoe, kernelFunc: Goe };
var uM;
function Hoe(r15) {
  uM = r15.wasm.cwrap(vn, null, ["number", "number", "number", "number", "number", "number", "array", "number"]);
}
function Koe(r15) {
  let { backend: e, inputs: t10 } = r15, { params: o, indices: n } = t10, [s, a, i, p] = af.prepareAndValidate(o, n), u = e.makeOutput(s, o.dtype);
  if (a === 0) return u;
  let c = n.shape, l = c[c.length - 1], d = e.dataIdMap.get(o.dataId).id, h = e.dataIdMap.get(n.dataId).id, g = new Uint8Array(new Int32Array(p).buffer), x = e.dataIdMap.get(u.dataId).id;
  return uM(d, we[o.dtype], h, a, l, i, g, x), u;
}
var pM = { kernelName: vn, backendName: "wasm", setupFunc: Hoe, kernelFunc: Koe };
var cM;
function qoe(r15) {
  cM = r15.wasm.cwrap("Gather", null, ["number", "number", "array", "number", "number", "number", "array", "number"]);
}
function joe(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { x: n, indices: s } = t10, { axis: a, batchDims: i } = o, p = y.parseAxisParam(a, n.shape)[0], u = e.readSync(s.dataId), c = n.shape[p];
  for (let D = 0; D < u.length; ++D) {
    let P = u[D];
    y.assert(P <= c - 1 && P >= 0, () => `GatherV2: the index value ${P} is not in [0, ${c - 1}]`);
  }
  let l = w.segment_util.collectGatherOpShapeInfo(n, s, p, i), m = zt({ inputs: { x: n }, attrs: { shape: [l.batchSize, l.outerSize, l.dimSize, l.sliceSize] }, backend: e }), d = y.sizeFromShape(s.shape), f = zt({ inputs: { x: s }, attrs: { shape: [l.batchSize, d / l.batchSize] }, backend: e }), h = [l.batchSize, l.outerSize, d / l.batchSize, l.sliceSize], g = e.makeOutput(h, n.dtype);
  if (y.sizeFromShape(n.shape) === 0) return g;
  let x = m.shape.length - 1, C = e.dataIdMap.get(m.dataId).id, k = e.dataIdMap.get(f.dataId).id, _ = e.dataIdMap.get(g.dataId).id, $ = new Uint8Array(new Int32Array(y.computeStrides(m.shape)).buffer), R = new Uint8Array(new Int32Array(y.computeStrides(h)).buffer);
  return cM(C, we[n.dtype], $, x, k, l.batchSize, R, _), e.disposeData(m.dataId), e.disposeData(f.dataId), g.shape = l.outputShape, g;
}
var lM = { kernelName: aa, backendName: "wasm", setupFunc: qoe, kernelFunc: joe };
var Xoe = false;
var mM = Ge(kn, Xoe, "bool");
var Yoe = false;
var dM = Ge(Nn, Yoe, "bool");
var fM = he(Tn, "bool");
var hM = he(_n, "bool");
var gM = he(En, "bool");
var xM;
function Qoe(r15) {
  xM = r15.wasm.cwrap($n, null, ["number", "number", "number", "number"]);
}
function Zoe(r15) {
  let { inputs: { x: e }, attrs: { alpha: t10 }, backend: o } = r15, n = o.dataIdMap.get(e.dataId).id, s = o.makeOutput(e.shape, "float32");
  if (y.sizeFromShape(e.shape) !== 0) {
    let a = o.dataIdMap.get(s.dataId).id;
    xM(n, we[e.dtype], t10, a);
  }
  return s;
}
var yM = { kernelName: $n, backendName: "wasm", setupFunc: Qoe, kernelFunc: Zoe };
var Joe = false;
var bM = Ge(Rn, Joe, "bool");
var ene = false;
var CM = Ge(Dn, ene, "bool");
var wM;
function tne(r15) {
  wM = r15.wasm.cwrap(An, null, ["number", "number", "number", "number"]);
}
function rne(r15) {
  let { attrs: e, backend: t10 } = r15, { start: o, stop: n, num: s } = e, a = Math.floor(s), i = t10.makeOutput([a], "float32");
  return wM(t10.dataIdMap.get(i.dataId).id, o, n, a), i;
}
var SM = { kernelName: An, backendName: "wasm", setupFunc: tne, kernelFunc: rne };
var IM = he("Log");
var vM = he(Pn);
var one = false;
var kM = Ge(On, one, "bool");
var NM = he(Mn);
var nne = false;
var TM = Ge(Ln, nne, "bool");
var sne = false;
var _M = Ge(R0, sne, "bool");
var EM;
function ane(r15) {
  EM = r15.wasm.cwrap("LRN", null, ["number", "number", "number", "number", "number", "number", "number"]);
}
function ine(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { depthRadius: s, bias: a, alpha: i, beta: p } = o;
  if (n.dtype !== "float32") throw new Error("LRN error: x must have dtype float32");
  let u = t10.makeOutput(n.shape, n.dtype);
  return EM(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(u.dataId).id, n.shape[3], s, a, i, p), u;
}
var $M = { kernelName: "LRN", backendName: "wasm", setupFunc: ane, kernelFunc: ine };
var RM;
function une(r15) {
  RM = r15.wasm.cwrap(Ya, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function pne(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, y: s, dy: a } = e, { depthRadius: i, bias: p, alpha: u, beta: c } = o;
  if (n.dtype !== "float32" || s.dtype !== "float32" || a.dtype !== "float32") throw new Error("LRNGrad error: x, y, and dy must have dtype float32");
  let l = t10.makeOutput(n.shape, n.dtype);
  return RM(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(s.dataId).id, t10.dataIdMap.get(a.dataId).id, t10.dataIdMap.get(l.dataId).id, a.shape[3], i, p, u, c), l;
}
var DM = { kernelName: Ya, backendName: "wasm", setupFunc: une, kernelFunc: pne };
var AM;
function cne(r15) {
  AM = r15.wasm.cwrap("Max", null, ["number", "number", "number", "number"]);
}
function lne(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { reductionIndices: n, keepDims: s } = o, { x: a } = t10, p = e.dataIdMap.get(a.dataId).id, u = a, { transposed: c, axes: l, originalAxes: m, inputWasTransposed: d } = Tr(a, n, e);
  if (d) {
    let C = e.dataIdMap.get(c.dataId).id;
    u = c, p = C;
  }
  let f = u.shape.length;
  w.assertAxesAreInnerMostDims("max", l, f);
  let [h, g] = w.computeOutAndReduceShapes(u.shape, l), x = y.sizeFromShape(g), b = e.makeOutput(h, a.dtype);
  if (y.sizeFromShape(u.shape) !== 0) {
    let C = e.dataIdMap.get(b.dataId).id;
    AM(p, we[a.dtype], x, C);
  }
  if (d && e.disposeData(c.dataId), s) {
    let C = w.expandShapeToKeepDim(b.shape, m);
    b.shape = C;
  }
  return b;
}
var FM = { kernelName: "Max", backendName: "wasm", setupFunc: cne, kernelFunc: lne };
var mne = false;
var PM = Ge(Vn, mne);
var OM;
function dne(r15) {
  OM = r15.wasm.cwrap(Wn, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function fne(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, n = e.x, s = o.dataIdMap.get(n.dataId).id;
  y.assert(n.dtype === "float32", () => `Error in MaxPool: only float32 input is supported. Got ${n.dtype}.`);
  let { filterSize: a, strides: i, pad: p, dimRoundingMode: u } = t10, c = w.computePool2DInfo(n.shape, a, i, 1, p, u), l = c.filterHeight, m = c.filterWidth, d = c.padInfo.top, f = c.padInfo.right, h = c.padInfo.bottom, g = c.padInfo.left, x = c.dilationHeight, b = c.dilationWidth, C = c.strideHeight, S = c.strideWidth, k = c.inChannels, _ = c.outChannels;
  if (c.dataFormat !== "channelsLast") throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);
  let $ = o.makeOutput(c.outShape, "float32"), R = o.dataIdMap.get($.dataId).id;
  return OM(s, n.shape[0], n.shape[1], n.shape[2], l, m, d, f, h, g, x, b, C, S, k, _, R), $;
}
var MM = { kernelName: Wn, backendName: "wasm", setupFunc: dne, kernelFunc: fne };
var LM;
function hne(r15) {
  LM = r15.wasm.cwrap("MaxPool3D", null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function gne(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { filterSize: s, strides: a, pad: i, dimRoundingMode: p, dataFormat: u } = o, c = w.computePool3DInfo(n.shape, s, a, 1, i, p, u), l = t10.makeOutput(c.outShape, n.dtype);
  return LM(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(l.dataId).id, c.batchSize, c.inChannels, c.inDepth, c.inHeight, c.inWidth, c.outDepth, c.outHeight, c.outWidth, c.strideDepth, c.strideHeight, c.strideWidth, c.dilationDepth, c.dilationHeight, c.dilationWidth, c.effectiveFilterDepth, c.effectiveFilterHeight, c.effectiveFilterWidth, c.padInfo.front, c.padInfo.top, c.padInfo.left), l;
}
var BM = { kernelName: ia, backendName: "wasm", setupFunc: hne, kernelFunc: gne };
var zM;
function xne(r15) {
  zM = r15.wasm.cwrap("MaxPool3DGrad", 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(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s } = e, { filterSize: a, strides: i, pad: p, dimRoundingMode: u } = o, c = w.computePool3DInfo(s.shape, a, i, 1, p, u), l = t10.makeOutput(s.shape, s.dtype);
  return zM(t10.dataIdMap.get(s.dataId).id, t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(l.dataId).id, c.batchSize, c.inChannels, c.inDepth, c.inHeight, c.inWidth, c.outDepth, c.outHeight, c.outWidth, c.strideDepth, c.strideHeight, c.strideWidth, c.dilationDepth, c.dilationHeight, c.dilationWidth, c.effectiveFilterDepth, c.effectiveFilterHeight, c.effectiveFilterWidth, c.padInfo.front, c.padInfo.top, c.padInfo.left), l;
}
var VM = { kernelName: Gi, backendName: "wasm", setupFunc: xne, kernelFunc: yne };
var WM;
function bne(r15) {
  WM = r15.wasm.cwrap("MaxPoolGrad", null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Cne(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s } = e, { filterSize: a, strides: i, pad: p, dimRoundingMode: u } = o, c = w.computePool2DInfo(s.shape, a, i, 1, p, u), l = t10.makeOutput(s.shape, s.dtype);
  return WM(t10.dataIdMap.get(s.dataId).id, t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(l.dataId).id, c.batchSize, c.inChannels, c.inHeight, c.inWidth, c.outHeight, c.outWidth, c.strideHeight, c.strideWidth, c.dilationHeight, c.dilationWidth, c.effectiveFilterHeight, c.effectiveFilterWidth, c.padInfo.top, c.padInfo.left), l;
}
var UM = { kernelName: Ui, backendName: "wasm", setupFunc: bne, kernelFunc: Cne };
var GM;
function wne(r15) {
  GM = r15.wasm.cwrap("MaxPoolWithArgmax", null, ["number", "number", "number", "number", "boolean", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Sne(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { filterSize: s, strides: a, pad: i, includeBatchInIndex: p } = o;
  y.assert(n.shape.length === 4, () => `Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);
  let u = [1, 1];
  y.assert(w.eitherStridesOrDilationsAreOne(a, u), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);
  let c = w.computePool2DInfo(n.shape, s, a, [1, 1], i), l = t10.makeOutput(c.outShape, n.dtype), m = t10.makeOutput(c.outShape, "int32");
  return GM(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(l.dataId).id, t10.dataIdMap.get(m.dataId).id, we[n.dtype], p, c.batchSize, c.inChannels, c.inHeight, c.inWidth, c.outHeight, c.outWidth, c.strideHeight, c.strideWidth, c.dilationHeight, c.dilationWidth, c.effectiveFilterHeight, c.effectiveFilterWidth, c.padInfo.top, c.padInfo.left), [l, m];
}
var HM = { kernelName: ua, backendName: "wasm", setupFunc: wne, kernelFunc: Sne };
var KM;
function Ine(r15) {
  KM = r15.wasm.cwrap(Un, null, ["number, number, number"]);
}
function vne(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { axis: n, keepDims: s } = o, { x: a } = t10, i = e.dataIdMap.get(a.dataId).id, p = i, u = a, { transposed: c, axes: l, originalAxes: m, inputWasTransposed: d } = Tr(a, n, e), f = l;
  if (d) {
    let S = e.dataIdMap.get(c.dataId).id;
    S !== i && (u = c, p = S, f = w.getInnerMostAxes(f.length, u.shape.length));
  }
  w.assertAxesAreInnerMostDims("mean", f, u.shape.length);
  let [h, g] = w.computeOutAndReduceShapes(u.shape, f), x = y.sizeFromShape(g), b = u;
  u.dtype !== "float32" && (b = Mr({ backend: e, inputs: { x: u }, attrs: { dtype: "float32" } }), p = e.dataIdMap.get(b.dataId).id);
  let C = e.makeOutput(h, "float32");
  if (y.sizeFromShape(u.shape) !== 0) {
    let S = e.dataIdMap.get(C.dataId).id;
    KM(p, x, S);
  }
  if (d && e.disposeData(c.dataId), s) {
    let S = w.expandShapeToKeepDim(C.shape, m);
    C.shape = S;
  }
  return u.dtype !== "float32" && e.disposeData(b.dataId), C;
}
var qM = { kernelName: Un, backendName: "wasm", setupFunc: Ine, kernelFunc: vne };
var jM;
function kne(r15) {
  jM = r15.wasm.cwrap("Min", null, ["number", "number", "number", "number"]);
}
function Nne(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { axis: n, keepDims: s } = o, { x: a } = t10, i = e.dataIdMap.get(a.dataId).id, p = i, u = a, { transposed: c, axes: l, originalAxes: m, inputWasTransposed: d } = Tr(a, n, e);
  if (d) {
    let C = e.dataIdMap.get(c.dataId).id;
    C !== i && (u = c, p = C);
  }
  let f = u.shape.length;
  w.assertAxesAreInnerMostDims("min", l, f);
  let [h, g] = w.computeOutAndReduceShapes(u.shape, l), x = y.sizeFromShape(g), b = e.makeOutput(h, u.dtype);
  if (y.sizeFromShape(u.shape) !== 0) {
    let C = e.dataIdMap.get(b.dataId).id;
    jM(p, we[a.dtype], x, C);
  }
  if (d && e.disposeData(c.dataId), s) {
    let C = w.expandShapeToKeepDim(b.shape, m);
    b.shape = C;
  }
  return b;
}
var XM = { kernelName: "Min", backendName: "wasm", setupFunc: kne, kernelFunc: Nne };
var Tne = false;
var YM = Ge(Hn, Tne);
var Lv;
(function(r15) {
  r15[r15.reflect = 0] = "reflect", r15[r15.symmetric = 1] = "symmetric";
})(Lv || (Lv = {}));
var QM;
function _ne(r15) {
  QM = r15.wasm.cwrap(Kn, null, ["number", "array", "number", "number", "array", "array", "number", "number"]);
}
function Ene(r15) {
  let { inputs: { x: e }, backend: t10, attrs: { paddings: o, mode: n } } = r15, s = o.map((f, h) => f[0] + e.shape[h] + f[1]), a = t10.dataIdMap.get(e.dataId).id, i = t10.makeOutput(s, e.dtype), p = t10.dataIdMap.get(i.dataId).id, u = new Uint8Array(new Int32Array(e.shape).buffer), c = o.map((f) => f[0]), l = o.map((f) => f[1]), m = new Uint8Array(new Int32Array(c).buffer), d = new Uint8Array(new Int32Array(l).buffer);
  return QM(a, u, e.shape.length, we[e.dtype], m, d, Lv[n], p), i;
}
var ZM = { kernelName: Kn, backendName: "wasm", kernelFunc: Ene, setupFunc: _ne };
var JM;
function $ne(r15) {
  JM = r15.wasm.cwrap(Is, null, ["number", "number", "number", "number"]);
}
function Bv(r15) {
  let { backend: e, inputs: { logits: t10 }, attrs: { dim: o } } = r15, n = e.dataIdMap.get(t10.dataId).id, s = e.makeOutput(t10.shape, t10.dtype), a = e.dataIdMap.get(s.dataId).id, i = t10.shape[o], p = y.sizeFromShape(t10.shape) / i;
  return y.sizeFromShape(s.shape) === 0 || JM(n, a, i, p), s;
}
var eL = { kernelName: Is, backendName: "wasm", setupFunc: $ne, kernelFunc: Bv };
var tL;
function Rne(r15) {
  tL = r15.wasm.cwrap(jn, null, ["number", "number", "number", "number", "number", "number"]);
}
function Dne(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { logits: n } = e, { numSamples: s, seed: a, normalized: i } = o;
  if (n.dtype !== "float32") throw new Error(`Tensor logits must have dtype float32, got ${n.dtype}`);
  let p = i ? n : Bv({ inputs: { logits: n }, backend: t10, attrs: { dim: n.shape.length - 1 } }), [u, c] = p.shape, l = t10.makeOutput([u, s], "int32");
  return tL(t10.dataIdMap.get(p.dataId).id, u, c, s, a, t10.dataIdMap.get(l.dataId).id), i || t10.disposeData(p.dataId), l;
}
var rL = { kernelName: jn, backendName: "wasm", setupFunc: Rne, kernelFunc: Dne };
var oL = Ge("Mod", true);
var Ane = true;
var nL = Ge(Xn, Ane);
var sL = he("Neg");
function qc(r15, e) {
  let t10 = new Int32Array(r15.wasm.HEAPU8.buffer, e, 4), o = t10[0], n = t10[1], s = t10[2], a = t10[3];
  return r15.wasm._free(e), { pSelectedIndices: o, selectedSize: n, pSelectedScores: s, pValidOutputs: a };
}
var aL;
function Fne(r15) {
  aL = r15.wasm.cwrap(Qn, "number", ["number", "number", "number", "number", "number"]);
}
function Pne(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { iouThreshold: n, maxOutputSize: s, scoreThreshold: a } = o, { boxes: i, scores: p } = t10, u = e.dataIdMap.get(i.dataId).id, c = e.dataIdMap.get(p.dataId).id, l = aL(u, c, s, n, a), { pSelectedIndices: m, selectedSize: d, pSelectedScores: f, pValidOutputs: h } = qc(e, l);
  return e.wasm._free(f), e.wasm._free(h), e.makeOutput([d], "int32", m);
}
var iL = { kernelName: Qn, backendName: "wasm", setupFunc: Fne, kernelFunc: Pne };
var uL;
function One(r15) {
  uL = r15.wasm.cwrap(Qa, "number", ["number", "number", "number", "number", "number", "bool"]);
}
function Mne(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { iouThreshold: n, maxOutputSize: s, scoreThreshold: a, padToMaxOutputSize: i } = o, { boxes: p, scores: u } = t10, c = e.dataIdMap.get(p.dataId).id, l = e.dataIdMap.get(u.dataId).id, m = uL(c, l, s, n, a, i), { pSelectedIndices: d, selectedSize: f, pSelectedScores: h, pValidOutputs: g } = qc(e, m);
  e.wasm._free(h);
  let x = e.makeOutput([f], "int32", d), b = e.makeOutput([], "int32", g);
  return [x, b];
}
var pL = { kernelName: Qa, backendName: "wasm", setupFunc: One, kernelFunc: Mne };
var cL;
function Lne(r15) {
  cL = r15.wasm.cwrap(Zn, "number", ["number", "number", "number", "number", "number", "number"]);
}
function Bne(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { iouThreshold: n, maxOutputSize: s, scoreThreshold: a, softNmsSigma: i } = o, { boxes: p, scores: u } = t10, c = e.dataIdMap.get(p.dataId).id, l = e.dataIdMap.get(u.dataId).id, m = cL(c, l, s, n, a, i), { pSelectedIndices: d, selectedSize: f, pSelectedScores: h, pValidOutputs: g } = qc(e, m);
  e.wasm._free(g);
  let x = e.makeOutput([f], "int32", d), b = e.makeOutput([f], "float32", h);
  return [x, b];
}
var lL = { kernelName: Zn, backendName: "wasm", setupFunc: Lne, kernelFunc: Bne };
var zne = false;
var mL = Ge(Yn, zne, "bool");
var dL;
function Vne(r15) {
  dL = r15.wasm.cwrap(Jn, null, ["number", "number", "number", "number", "number"]);
}
function Wne(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { indices: n } = e, { dtype: s, depth: a, onValue: i, offValue: p } = o, u = t10.makeOutput([...n.shape, a], s), c = t10.dataIdMap.get(u.dataId).id, m = t10.dataIdMap.get(n.dataId).id;
  return dL(m, a, i, p, c), u;
}
var fL = { kernelName: Jn, backendName: "wasm", setupFunc: Vne, kernelFunc: Wne };
function Une(r15) {
  let { inputs: { x: e }, backend: t10 } = r15, o = t10.makeOutput(e.shape, e.dtype);
  return t10.typedArrayFromHeap(o).fill(1), o;
}
var hL = { kernelName: ca, backendName: "wasm", kernelFunc: Une };
function Gne(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { axis: n } = o;
  if (e.length === 1) return Lg({ inputs: { input: e[0] }, backend: t10, attrs: { dim: n } });
  let s = e[0].shape, a = e[0].dtype;
  e.forEach((c) => {
    y.assertShapesMatch(s, c.shape, "All tensors passed to stack must have matching shapes"), y.assert(a === c.dtype, () => "All tensors passed to stack must have matching dtypes");
  });
  let i = [], p = e.map((c) => {
    let l = Lg({ inputs: { input: c }, backend: t10, attrs: { dim: n } });
    return i.push(l), l;
  }), u = Pv({ inputs: p, backend: t10, attrs: { axis: n } });
  return i.forEach((c) => t10.disposeData(c.dataId)), u;
}
var gL = { kernelName: la, backendName: "wasm", kernelFunc: Gne };
var xL;
function Hne(r15) {
  xL = r15.wasm.cwrap(es, null, ["number", "array", "number", "number", "array", "array", "number", "number"]);
}
function Kne(r15) {
  let { inputs: { x: e }, backend: t10, attrs: { paddings: o, constantValue: n } } = r15, s = o.map((h, g) => h[0] + e.shape[g] + h[1]);
  if (y.sizeFromShape(e.shape) === 0) return Mv({ backend: t10, attrs: { shape: s, value: n, dtype: e.dtype } });
  let a = t10.dataIdMap.get(e.dataId).id, i = t10.makeOutput(s, e.dtype), u = t10.dataIdMap.get(i.dataId).id, c = new Uint8Array(new Int32Array(e.shape).buffer), l = o.map((h) => h[0]), m = o.map((h) => h[1]), d = new Uint8Array(new Int32Array(l).buffer), f = new Uint8Array(new Int32Array(m).buffer);
  return xL(a, c, e.shape.length, we[e.dtype], d, f, n, u), i;
}
var Bg = { kernelName: es, backendName: "wasm", kernelFunc: Kne, setupFunc: Hne };
var qne = false;
var yL = Ge("Pow", qne);
var bL;
function jne(r15) {
  bL = r15.wasm.cwrap(rs, null, ["number", "number", "number"]);
}
function Xne(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o, alpha: n } = e, s = t10.dataIdMap.get(o.dataId).id, a = t10.dataIdMap.get(n.dataId).id, i = s, p = o, u = p;
  p.dtype !== "float32" && (u = Mr({ backend: t10, inputs: { x: o }, attrs: { dtype: "float32" } }), i = t10.dataIdMap.get(u.dataId).id);
  let c = t10.makeOutput(o.shape, "float32"), l = t10.dataIdMap.get(c.dataId).id;
  return bL(i, a, l), p.dtype !== "float32" && t10.disposeData(u.dataId), c;
}
var CL = { kernelName: rs, backendName: "wasm", setupFunc: jne, kernelFunc: Xne };
var wL;
function Yne(r15) {
  wL = r15.wasm.cwrap(os, null, ["number", "number", "number", "number"]);
}
function Qne(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { axis: n, keepDims: s } = o, { x: a } = t10, i = e.dataIdMap.get(a.dataId).id, p = i, u = a, { transposed: c, axes: l, originalAxes: m, inputWasTransposed: d } = Tr(a, n, e), f = l;
  if (d) {
    let C = e.dataIdMap.get(c.dataId).id;
    C !== i && (u = c, p = C, f = w.getInnerMostAxes(f.length, u.shape.length));
  }
  w.assertAxesAreInnerMostDims("prod", f, u.shape.length);
  let [h, g] = w.computeOutAndReduceShapes(u.shape, f), x = y.sizeFromShape(g), b = e.makeOutput(h, u.dtype);
  if (y.sizeFromShape(u.shape) !== 0) {
    let C = e.dataIdMap.get(b.dataId).id;
    wL(p, x, we[b.dtype], C);
  }
  if (d && e.disposeData(c.dataId), s) {
    let C = w.expandShapeToKeepDim(b.shape, m);
    b.shape = C;
  }
  return b;
}
var SL = { kernelName: os, backendName: "wasm", setupFunc: Yne, kernelFunc: Qne };
var Zne = (r15) => {
  let { backend: e, attrs: t10 } = r15, { start: o, stop: n, step: s, dtype: a } = t10, i = up(o, n, s, a), p = e.makeOutput([i.length], a);
  return e.typedArrayFromHeap(p).set(i), p;
};
var IL = { kernelName: ma, backendName: "wasm", kernelFunc: Zne };
var Jne = true;
var vL = Ge(fn, Jne);
var kL = he(ns);
var NL = he(ss);
var TL = he(us);
var _L;
function ese(r15) {
  _L = r15.wasm.cwrap(is, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function tse(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { images: n } = t10, { alignCorners: s, halfPixelCenters: a, size: i } = o, [p, u] = i, [c, l, m, d] = n.shape, f = [c, p, u, d], h = e.dataIdMap.get(n.dataId), g;
  h.dtype !== "float32" && (g = Mr({ backend: e, inputs: { x: n }, attrs: { dtype: "float32" } }), h = e.dataIdMap.get(g.dataId));
  let x = h.id, b = e.makeOutput(f, "float32");
  if (y.sizeFromShape(n.shape) === 0) return b;
  let C = e.dataIdMap.get(b.dataId).id;
  return _L(x, c, l, m, d, p, u, s ? 1 : 0, a ? 1 : 0, C), g != null && e.disposeData(g.dataId), b;
}
var EL = { kernelName: is, backendName: "wasm", setupFunc: ese, kernelFunc: tse };
var $L;
function rse(r15) {
  $L = r15.wasm.cwrap(Ja, null, ["number", "number", "number", "array", "array", "boolean"]);
}
function ose(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n, dy: s } = e, { alignCorners: a } = o, i = t10.makeOutput(n.shape, "float32"), p = t10.dataIdMap.get(n.dataId), u;
  return p.dtype !== "float32" && (u = Mr({ backend: t10, inputs: { x: n }, attrs: { dtype: "float32" } }), p = t10.dataIdMap.get(u.dataId)), $L(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(s.dataId).id, t10.dataIdMap.get(i.dataId).id, new Uint8Array(new Int32Array(n.shape).buffer), new Uint8Array(new Int32Array(s.shape).buffer), a), u != null && t10.disposeData(u.dataId), i;
}
var RL = { kernelName: Ja, backendName: "wasm", setupFunc: rse, kernelFunc: ose };
var DL;
function nse(r15) {
  DL = r15.wasm.cwrap(as, null, ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function sse(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { images: n } = t10, { alignCorners: s, halfPixelCenters: a, size: i } = o, [p, u] = i, [c, l, m, d] = n.shape, f = [c, p, u, d], h = e.makeOutput(f, "float32");
  if (y.sizeFromShape(n.shape) === 0) return h;
  let g = e.dataIdMap.get(n.dataId), x;
  g.dtype !== "float32" && (x = Mr({ backend: e, inputs: { x: n }, attrs: { dtype: "float32" } }), g = e.dataIdMap.get(x.dataId));
  let b = g.id, C = e.dataIdMap.get(h.dataId).id;
  return DL(b, c, l, m, d, p, u, s ? 1 : 0, a ? 1 : 0, C), x != null && e.disposeData(x.dataId), h;
}
var AL = { kernelName: as, backendName: "wasm", setupFunc: nse, kernelFunc: sse };
var FL;
function ase(r15) {
  FL = r15.wasm.cwrap(Za, null, ["number", "number", "number", "array", "array", "boolean"]);
}
function ise(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n, dy: s } = e, { alignCorners: a } = o, i = t10.makeOutput(n.shape, "float32"), p = t10.dataIdMap.get(n.dataId), u;
  return p.dtype !== "float32" && (u = Mr({ backend: t10, inputs: { x: n }, attrs: { dtype: "float32" } }), p = t10.dataIdMap.get(u.dataId)), FL(t10.dataIdMap.get(n.dataId).id, t10.dataIdMap.get(s.dataId).id, t10.dataIdMap.get(i.dataId).id, new Uint8Array(new Int32Array(n.shape).buffer), new Uint8Array(new Int32Array(s.shape).buffer), a), u != null && t10.disposeData(u.dataId), i;
}
var PL = { kernelName: Za, backendName: "wasm", setupFunc: ase, kernelFunc: ise };
var OL;
function use(r15) {
  OL = r15.wasm.cwrap(ps, null, ["number", "array", "number", "array", "number", "number"]);
}
function pse(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { dims: s } = o, a = y.parseAxisParam(s, n.shape);
  if (n.shape.length === 0) return Np({ inputs: { x: n }, backend: t10 });
  let i = t10.makeOutput(n.shape, n.dtype), p = t10.dataIdMap.get(n.dataId).id, u = t10.dataIdMap.get(i.dataId).id, c = new Uint8Array(new Int32Array(a).buffer), l = new Uint8Array(new Int32Array(n.shape).buffer);
  OL(p, c, a.length, l, n.shape.length, u);
  let m = zt({ inputs: { x: i }, attrs: { shape: n.shape }, backend: t10 });
  return t10.disposeData(i.dataId), m;
}
var ML = { kernelName: ps, backendName: "wasm", kernelFunc: pse, setupFunc: use };
var LL;
function cse(r15) {
  LL = r15.wasm.cwrap(Ds, null, ["number", "number", "number", "number", "number", "number", "number", "number", "array", "number", "number"]);
}
function lse(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { image: n } = e, { radians: s, fillValue: a, center: i } = o, p = t10.makeOutput(n.shape, n.dtype), u = t10.dataIdMap.get(n.dataId).id, c = t10.dataIdMap.get(p.dataId).id, [l, m, d, f] = n.shape, [h, g] = w.getImageCenter(i, m, d), x = a === 0, b = 255, C = typeof a == "number" ? [a, a, a, x ? 0 : b] : [...a, b], S = new Uint8Array(new Int32Array(C).buffer);
  return LL(u, l, m, d, f, s, h, g, S, C.length, c), p;
}
var BL = { kernelName: Ds, backendName: "wasm", kernelFunc: lse, setupFunc: cse };
var zL = he(cs);
var VL = he(ls);
var WL;
function mse(r15) {
  WL = r15.wasm.cwrap(ms, null, ["number", "number", "number", "number", "number", "number", "array", "number", "number"]);
}
function dse(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { indices: n, updates: s } = t10, { shape: a } = o, i = e.makeOutput(a, s.dtype);
  if (y.sizeFromShape(a) === 0) return i;
  let { sliceRank: p, numUpdates: u, sliceSize: c, strides: l, outputSize: m } = du.calculateShapes(s, n, a), f = e.dataIdMap.get(n.dataId).id, g = e.dataIdMap.get(s.dataId).id, x = new Uint8Array(new Int32Array(l).buffer), b = e.dataIdMap.get(i.dataId).id;
  return WL(f, g, we[s.dtype], p, u, c, x, m, b), i;
}
var UL = { kernelName: ms, backendName: "wasm", setupFunc: mse, kernelFunc: dse };
var GL;
function fse(r15) {
  GL = r15.wasm.cwrap(fs, null, ["number", "number", "number", "number", "number", "number", "bool", "number"]);
}
function hse(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { sortedSequence: n, values: s } = e, { side: a } = o;
  if (n.dtype !== s.dtype) throw new Error(`SearchSorted error: sorted_sequence must have the same dtype as values. Got ${n.dtype} and ${s.dtype}`);
  let i = t10.makeOutput(s.shape, "int32");
  function p(u) {
    return t10.dataIdMap.get(u.dataId).id;
  }
  return GL(p(n), p(s), n.shape[0], n.shape[1], s.shape[1], we[n.dtype], a === "left", p(i)), i;
}
var HL = { kernelName: fs, backendName: "wasm", setupFunc: fse, kernelFunc: hse };
var KL;
function gse(r15) {
  KL = r15.wasm.cwrap("SelectV2", null, ["number", "number", "number", "number", "number"]);
}
function xse(r15) {
  let { inputs: e, backend: t10 } = r15, { condition: o, t: n, e: s } = e, a = t10.dataIdMap.get(o.dataId).id, i = t10.dataIdMap.get(n.dataId).id, p = t10.dataIdMap.get(s.dataId).id, u = t10.makeOutput(n.shape, n.dtype), c = t10.dataIdMap.get(u.dataId).id, l = o.shape.length, m = n.shape.length, d = l === 0 || l > 1 || m === 1 ? 1 : y.sizeFromShape(n.shape.slice(1));
  return KL(a, i, p, d, c), u;
}
var qL = { kernelName: fa, backendName: "wasm", kernelFunc: xse, setupFunc: gse };
var jL = he(hs);
var XL;
function yse(r15) {
  XL = r15.wasm.cwrap(bs, null, ["number", "number"]);
}
function bse(r15) {
  let { backend: e, inputs: { x: t10 } } = r15, o = e.dataIdMap.get(t10.dataId).id, n = e.makeOutput(t10.shape, t10.dtype), s = e.dataIdMap.get(n.dataId).id;
  return y.sizeFromShape(n.shape) === 0 || XL(o, s), n;
}
var YL = { kernelName: "Sigmoid", backendName: "wasm", setupFunc: yse, kernelFunc: bse };
var QL = he(ys);
var ZL = he("Sin");
var JL = he(xs);
var eB = he(Cs);
function Cse(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { blockShape: s, paddings: a } = o, i = y.sizeFromShape(s), p = [[0, 0]];
  p.push(...a);
  for (let _ = 1 + s.length; _ < n.shape.length; ++_) p.push([0, 0]);
  let u = Bg.kernelFunc({ inputs: { x: n }, backend: t10, attrs: { paddings: p, constantValue: 0 } }), c = w.getReshaped(u.shape, s, i, false), l = w.getPermuted(c.length, s.length, false), m = w.getReshapedPermuted(u.shape, s, i, false), h = zt({ inputs: { x: u }, backend: t10, attrs: { shape: c } }), b = ho({ inputs: { x: h }, backend: t10, attrs: { perm: l } }), k = zt({ inputs: { x: b }, backend: t10, attrs: { shape: m } });
  return t10.disposeData(u.dataId), t10.disposeData(h.dataId), t10.disposeData(b.dataId), k;
}
var tB = { kernelName: ga, backendName: "wasm", kernelFunc: Cse };
var rB;
function wse(r15) {
  rB = r15.wasm.cwrap("SparseFillEmptyRows", "number", ["number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Sse(r15) {
  let { backend: e, inputs: t10 } = r15, { indices: o, values: n, denseShape: s, defaultValue: a } = t10, i = o.shape[0], p = o.shape[1], u = e.readSync(s.dataId)[0], c = [i + u, p], l = e.dataIdMap.get(o.dataId).id, m = e.dataIdMap.get(n.dataId).id, d = e.dataIdMap.get(a.dataId).id, f = e.makeOutput(c, o.dtype), h = e.dataIdMap.get(f.dataId).id, g = e.makeOutput(c.slice(0, 1), n.dtype), x = e.dataIdMap.get(g.dataId).id, b = e.makeOutput([u], "bool"), C = e.dataIdMap.get(b.dataId).id, S = e.makeOutput([i], o.dtype), k = e.dataIdMap.get(S.dataId).id, _ = e.makeOutput([4], "int32"), $ = e.dataIdMap.get(_.dataId).id, R = rB(l, m, we[n.dtype], i, u, p, d, h, x, C, k, $), D = e.readSync(_.dataId), P;
  switch (D[0]) {
    case 1: {
      P = w.getSparseFillEmptyRowsIndicesDenseShapeMismatch(D[1]);
      break;
    }
    case 2: {
      P = w.getSparseFillEmptyRowsNegativeIndexErrorMessage(D[1], D[2]);
      break;
    }
    case 3:
      P = w.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(D[1], D[2], D[3]);
      break;
    default:
      P = "";
  }
  if (e.disposeData(_.dataId), P) throw e.disposeData(f.dataId), e.disposeData(g.dataId), e.disposeData(b.dataId), e.disposeData(S.dataId), new Error(P);
  let O = f, M = g;
  return R !== c[0] && (O = Po({ inputs: { x: f }, attrs: { begin: 0, size: [R, p] }, backend: e }), M = Po({ inputs: { x: g }, attrs: { begin: 0, size: R }, backend: e }), e.disposeData(f.dataId), e.disposeData(g.dataId)), [O, M, b, S];
}
var oB = { kernelName: Ki, backendName: "wasm", setupFunc: wse, kernelFunc: Sse };
var nB;
function Ise(r15) {
  nB = r15.wasm.cwrap(ei, null, ["number", "number", "number", "number", "number", "number", "number"]);
}
function vse(r15) {
  let { backend: e, inputs: t10 } = r15, { inputIndices: o, inputShape: n, newShape: s } = t10;
  if (o.shape.length !== 2) throw new Error(`Input indices should be a matrix but received shape
        ${o.shape}`);
  if (n.shape.length !== 1) throw new Error(`Input shape should be a vector but received shape
        ${n.shape}`);
  if (s.shape.length !== 1) throw new Error(`Target shape should be a vector but received shape ${s.shape}`);
  let a = e.dataIdMap.get(o.dataId).id, i = e.dataIdMap.get(n.dataId).id, p = e.dataIdMap.get(s.dataId).id, u = o.shape[0], c = y.sizeFromShape(s.shape), l = e.makeOutput([u, c], o.dtype), m = e.dataIdMap.get(l.dataId).id, d = e.makeOutput([c], s.dtype), f = e.dataIdMap.get(d.dataId).id, h = e.makeOutput([3], "int32"), g = e.dataIdMap.get(h.dataId).id;
  nB(a, i, p, u, m, f, g);
  let x = e.readSync(h.dataId), b;
  switch (x[0]) {
    case 0: {
      b = w.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(x[1], x[2]);
      break;
    }
    case 1: {
      b = w.getSparseReshapeNegativeOutputDimErrorMessage(x[1], x[2]);
      break;
    }
    case 2:
      b = w.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();
      break;
    case 3: {
      let C = Array.from(e.readSync(n.dataId)), S = Array.from(e.readSync(d.dataId));
      b = w.getSparseReshapeInputOutputMultipleErrorMessage(C, S);
      break;
    }
    case 4: {
      let C = Array.from(e.readSync(n.dataId)), S = Array.from(e.readSync(d.dataId));
      b = w.getSparseReshapeInputOutputMismatchErrorMessage(C, S);
      break;
    }
    default:
      b = "";
  }
  if (e.disposeData(h.dataId), b) throw e.disposeData(l.dataId), e.disposeData(d.dataId), new Error(b);
  return [l, d];
}
var sB = { kernelName: ei, backendName: "wasm", setupFunc: Ise, kernelFunc: vse };
var aB;
function zg(r15) {
  aB = r15.wasm.cwrap("SparseSegmentReduction", null, ["number", "number", "number", "number", "number", "number", "number", "number", "number"]);
}
function Vg(r15, e) {
  let { backend: t10, inputs: o } = r15, { data: n, indices: s, segmentIds: a } = o, i = s.shape[0], p = t10.readSync(a.dataId, i - 1, i)[0], c = i > 0 ? p + 1 : 0;
  if (c < 0) throw new Error(w.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());
  let l = n.shape.slice();
  l[0] = c;
  let m = t10.dataIdMap.get(n.dataId).id, d = t10.dataIdMap.get(s.dataId).id, f = t10.dataIdMap.get(a.dataId).id, h = t10.makeOutput(l, n.dtype), g = t10.dataIdMap.get(h.dataId).id, x = t10.makeOutput([4], "int32"), b = t10.dataIdMap.get(x.dataId).id;
  aB(m, we[n.dtype], n.shape[0], d, f, g, b, e, 0);
  let C = t10.readSync(x.dataId), S;
  switch (C[0]) {
    case 0: {
      S = w.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();
      break;
    }
    case 1: {
      S = w.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();
      break;
    }
    case 2:
      S = w.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(C[1], C[2]);
      break;
    case 3:
      S = w.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(C[1], C[2], C[3]);
      break;
    default:
      S = "";
  }
  if (t10.disposeData(x.dataId), S) throw t10.disposeData(h.dataId), new Error(S);
  return h;
}
function kse(r15) {
  return Vg(r15, true);
}
var iB = { kernelName: ya, backendName: "wasm", setupFunc: zg, kernelFunc: kse };
function Nse(r15) {
  return Vg(r15, false);
}
var uB = { kernelName: ba, backendName: "wasm", setupFunc: zg, kernelFunc: Nse };
var pB;
function Tse(r15) {
  pB = r15.wasm.cwrap(vs, null, ["number", "number", "number", "number", "number", "number", "number", "number", "array", "number", "number"]);
}
function _se(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { sparseIndices: n, sparseValues: s, defaultValue: a } = t10, { outputShape: i } = o, p = e.makeOutput(i, a.dtype);
  if (y.sizeFromShape(i) === 0) return p;
  let { sliceRank: u, numUpdates: c, sliceSize: l, strides: m, outputSize: d } = w.calculateShapes(s, n, i), f = e.dataIdMap.get(n.dataId).id, h = e.dataIdMap.get(s.dataId).id, g = e.dataIdMap.get(a.dataId).id, x = new Uint8Array(new Int32Array(m).buffer), b = e.dataIdMap.get(p.dataId).id;
  return pB(f, h, s.shape.length, g, we[a.dtype], u, c, l, x, d, b), p;
}
var cB = { kernelName: vs, backendName: "wasm", setupFunc: Tse, kernelFunc: _se };
function Ese(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { x: n } = e, { numOrSizeSplits: s, axis: a } = t10, i = y.parseAxisParam(a, n.shape)[0], p = w.prepareSplitSize(n, s, i), u = new Array(n.shape.length).fill(0), c = n.shape.slice();
  return p.map((l) => {
    let m = [...c];
    m[i] = l;
    let d = Po({ inputs: { x: n }, attrs: { begin: u, size: m }, backend: o });
    return u[i] += l, d;
  });
}
var lB = { kernelName: xa, backendName: "wasm", kernelFunc: Ese };
var mB = he(ws);
var dB = he(qi);
var $se = true;
var fB = Ge(ks, $se);
var hB;
function Rse(r15) {
  hB = r15.wasm.cwrap(wo, null, ["number", "number", "number", "number"]);
}
function Dse(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { alpha: n } = o, { x: s } = t10, a = e.dataIdMap.get(s.dataId).id, i = e.makeOutput(s.shape, s.dtype), p = e.dataIdMap.get(i.dataId).id;
  return hB(a, n, we[s.dtype], p), i;
}
var gB = { kernelName: wo, backendName: "wasm", setupFunc: Rse, kernelFunc: Dse };
var xB;
function Ase(r15) {
  xB = r15.wasm.cwrap(Ns, null, ["number", "array", "number", "array", "array", "array", "array", "array", "number", "number"]);
}
function Fse(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { x: n } = t10, { begin: s, end: a, strides: i, beginMask: p, endMask: u, ellipsisMask: c, newAxisMask: l, shrinkAxisMask: m } = o, { finalShapeSparse: d, finalShape: f, isIdentity: h, sliceDim0: g, isSimpleSlice: x, begin: b, end: C, strides: S } = pt.sliceInfo(n.shape, s, a, i, p, u, c, l, m), k;
  if (h) k = zt({ inputs: { x: n }, backend: e, attrs: { shape: f } });
  else if (g || x) {
    y.assert(n.shape.length >= 1, () => `Input must have rank at least 1, got: ${n.shape.length}`);
    let _ = pt.computeOutShape(b, C, S), $ = Po({ inputs: { x: n }, backend: e, attrs: { begin: b, size: _ } });
    k = zt({ inputs: { x: $ }, backend: e, attrs: { shape: f } }), e.disposeData($.dataId);
  } else {
    let _ = e.makeOutput(d, "float32"), $ = e.dataIdMap.get(n.dataId).id, R = new Uint8Array(new Int32Array(y.computeStrides(n.shape)).buffer), D = new Uint8Array(new Int32Array(b).buffer), P = new Uint8Array(new Int32Array(C).buffer), O = new Uint8Array(new Int32Array(S).buffer), M = new Uint8Array(new Int32Array(d).buffer), L = new Uint8Array(new Int32Array(y.computeStrides(d)).buffer), B = e.dataIdMap.get(_.dataId).id;
    xB($, R, n.shape.length, D, P, O, M, L, d.length, B), k = zt({ inputs: { x: _ }, backend: e, attrs: { shape: f } }), e.disposeData(_.dataId);
  }
  return k;
}
var yB = { kernelName: Ns, backendName: "wasm", setupFunc: Ase, kernelFunc: Fse };
function Pse(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { data: n, dataSplits: s } = t10, { separator: a, nGramWidths: i, leftPad: p, rightPad: u, padWidth: c, preserveShortSequences: l } = o, m = e.readSync(n.dataId), d = e.readSync(s.dataId), [f, h] = cp(m, d, a, i, p, u, c, l), g = e.makeOutput([f.length], "string"), x = e.dataIdMap.get(g.dataId);
  x.stringBytes = f;
  let b = e.makeOutput(s.shape, "int32");
  return e.typedArrayFromHeap(b).set(h), [g, b];
}
var bB = { kernelName: Ca, backendName: "wasm", kernelFunc: Pse };
function Ose(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { input: n, delimiter: s } = t10, { skipEmpty: a } = o, i = e.readSync(n.dataId), p = e.readSync(s.dataId), [u, c, l] = lp(i, p[0], a), m = c.length, d = e.makeOutput([m, 2], "int32");
  e.typedArrayFromHeap(d).set(u);
  let h = e.makeOutput([m], "string"), g = e.dataIdMap.get(h.dataId);
  g.stringBytes = c;
  let x = e.makeOutput([2], "int32");
  return e.typedArrayFromHeap(x).set(l), [d, h, x];
}
var CB = { kernelName: ji, backendName: "wasm", kernelFunc: Ose };
function Mse(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { input: n } = t10, { numBuckets: s } = o, a = e.readSync(n.dataId), i = mp(a, s), p = e.makeOutput(n.shape, "int32");
  return e.typedArrayFromHeap(p).set(i), p;
}
var wB = { kernelName: Xi, backendName: "wasm", kernelFunc: Mse };
var Lse = true;
var SB = Ge("Sub", Lse);
var IB;
function Bse(r15) {
  IB = r15.wasm.cwrap("Sum", null, ["number", "number", "number", "number"]);
}
function zse(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { axis: n, keepDims: s } = o, { x: a } = t10, i = e.dataIdMap.get(a.dataId).id, p = i, u = a, { transposed: c, axes: l, originalAxes: m, inputWasTransposed: d } = Tr(a, n, e), f = l;
  if (d) {
    let C = e.dataIdMap.get(c.dataId).id;
    C !== i && (u = c, p = C, f = w.getInnerMostAxes(f.length, u.shape.length));
  }
  w.assertAxesAreInnerMostDims("sum", f, u.shape.length);
  let [h, g] = w.computeOutAndReduceShapes(u.shape, f), x = y.sizeFromShape(g), b = e.makeOutput(h, u.dtype);
  if (y.sizeFromShape(u.shape) !== 0) {
    let C = e.dataIdMap.get(b.dataId).id;
    IB(p, x, we[b.dtype], C);
  }
  if (d && e.disposeData(c.dataId), s) {
    let C = w.expandShapeToKeepDim(b.shape, m);
    b.shape = C;
  }
  return b;
}
var vB = { kernelName: "Sum", backendName: "wasm", setupFunc: Bse, kernelFunc: zse };
var kB = he("Tan");
var NB = he(Es);
var TB;
function Vse(r15) {
  TB = r15.wasm.cwrap(ds, null, ["number", "number", "number", "number", "number", "number", "array", "number", "number", "number"]);
}
function Wse(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { tensor: n, indices: s, updates: a } = t10, {} = o, i = e.makeOutput(n.shape, n.dtype);
  if (y.sizeFromShape(n.shape) === 0) return i;
  let { sliceRank: p, numUpdates: u, sliceSize: c, strides: l, outputSize: m } = du.calculateShapes(a, s, n.shape), f = e.dataIdMap.get(s.dataId).id, g = e.dataIdMap.get(a.dataId).id, b = e.dataIdMap.get(n.dataId).id, C = new Uint8Array(new Int32Array(l).buffer), S = e.dataIdMap.get(i.dataId).id;
  return TB(f, g, we[a.dtype], p, u, c, C, m, S, b), i;
}
var _B = { kernelName: ds, backendName: "wasm", setupFunc: Vse, kernelFunc: Wse };
var EB;
function Use(r15) {
  EB = r15.wasm.cwrap(po, null, ["number", "array", "number", "array", "number", "number"]);
}
function Gse(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, s = t10.dataIdMap.get(n.dataId).id, { reps: a } = o, i = new Array(n.shape.length);
  for (let m = 0; m < i.length; m++) i[m] = n.shape[m] * a[m];
  let p = new Uint8Array(new Int32Array(n.shape).buffer), u = new Uint8Array(new Int32Array(i).buffer), c = t10.makeOutput(i, n.dtype), l = t10.dataIdMap.get(c.dataId).id;
  return EB(s, p, n.shape.length, u, i.length, we[c.dtype], l), c;
}
var $B = { kernelName: po, backendName: "wasm", setupFunc: Use, kernelFunc: Gse };
var RB;
function Hse(r15) {
  RB = r15.wasm.cwrap($s, null, ["number", "array", "number", "number", "number", "bool", "number", "number"]);
}
var Kse = ({ inputs: r15, backend: e, attrs: t10 }) => {
  let { x: o } = r15, { k: n, sorted: s } = t10, a = e.dataIdMap.get(o.dataId).id, i = new Uint8Array(new Int32Array(o.shape).buffer), p = o.shape.slice();
  p[p.length - 1] = n;
  let u = e.makeOutput(p, o.dtype), c = e.dataIdMap.get(u.dataId).id, l = e.makeOutput(p, "int32"), m = e.dataIdMap.get(l.dataId).id;
  return RB(a, i, o.shape.length, we[o.dtype], n, s, c, m), [u, l];
};
var DB = { kernelName: $s, backendName: "wasm", setupFunc: Hse, kernelFunc: Kse };
var AB;
function qse(r15) {
  AB = r15.wasm.cwrap(Rs, null, ["number", "number", "bool", "number", "number", "number", "number", "number", "number", "array", "number", "array", "number", "number", "number", "number", "number"]);
}
function jse(r15) {
  let { backend: e, inputs: t10, attrs: o } = r15, { image: n, transforms: s } = t10, { interpolation: a, fillMode: i, fillValue: p, outputShape: u } = o, [c, l, m, d] = n.shape, [f, h] = u != null ? u : [l, m], g = [c, f, h, d], x = new Uint8Array(new Int32Array(y.computeStrides(n.shape)).buffer), b = new Uint8Array(new Int32Array(y.computeStrides(g)).buffer), C = e.makeOutput(g, n.dtype), S = e.dataIdMap.get(C.dataId).id, _ = e.dataIdMap.get(n.dataId).id, R = e.dataIdMap.get(s.dataId).id, D = 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 AB(_, R, s.shape[0] > 1, c, f, h, d, m, l, x, n.shape.length - 1, b, g.length - 1, D, P, p, S), C;
}
var FB = { kernelName: Rs, backendName: "wasm", setupFunc: qse, kernelFunc: jse };
function Xse(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { axis: n } = t10, { x: s } = e, { outputValues: a, outputShape: i, indices: p } = dp(o.readSync(s.dataId), n, s.shape, s.dtype);
  return [o.makeOutput(i, s.dtype, void 0, a), o.makeOutput([p.length], "int32", void 0, p)];
}
var PB = { kernelName: Yi, backendName: "wasm", kernelFunc: Xse };
function Yse(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { value: n } = e, { axis: s } = o;
  s < 0 && (s += n.shape.length);
  let a = n.shape[s], i = n.shape.length, p = new Array(i - 1), u = 0;
  for (let d = 0; d < i; d++) d !== s && (p[u++] = n.shape[d]);
  let c = new Array(a), l = new Array(i).fill(0), m = n.shape.slice();
  m[s] = 1;
  for (let d = 0; d < c.length; d++) l[s] = d, c[d] = Po({ inputs: { x: n }, attrs: { begin: l, size: m }, backend: t10 });
  return c.map(({ dataId: d, dtype: f }) => ({ dataId: d, dtype: f, shape: p }));
}
var OB = { kernelName: wa, backendName: "wasm", kernelFunc: Yse };
function Qse(r15) {
  let { inputs: { x: e }, backend: t10 } = r15, o = t10.makeOutput(e.shape, e.dtype);
  return t10.typedArrayFromHeap(o).fill(0), o;
}
var MB = { kernelName: Sa, backendName: "wasm", kernelFunc: Qse };
var Zse = [SP, IP, vP, kP, NP, _P, AP, PP, OP, MP, LP, BP, zP, VP, WP, GP, YP, KP, jP, JP, tO, oO, nO, sO, aO, iO, pO, cO, mO, fO, gO, yO, CO, wO, SO, vO, NO, _O, $O, DO, FO, OO, LO, zO, WO, UO, HO, KO, qO, jO, XO, YO, QO, JO, eM, tM, oM, sM, iM, pM, lM, mM, dM, EP, fM, hM, gM, yM, bM, CM, SM, vM, IM, kM, NM, TM, _M, $M, DM, FM, PM, MM, BM, VM, UM, HM, qM, XM, YM, ZM, rL, oL, nL, sL, iL, pL, lL, mL, fL, hL, gL, Bg, yL, CL, SL, IL, vL, kL, NL, TL, QP, EL, RL, AL, PL, ML, BL, zL, VL, UL, HL, qL, jL, YL, QL, ZL, JL, eO, eL, eB, tB, oB, sB, iB, uB, cB, lB, mB, dB, fB, gB, yB, bB, CB, wB, SB, vB, kB, NB, _B, $B, DB, FB, RP, PB, OB, MB];
for (let r15 of Zse) ti(r15);
var zv = A();
zv.registerFlag("WASM_HAS_SIMD_SUPPORT", async () => {
  try {
    return 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]));
  } catch (r15) {
    return false;
  }
});
zv.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT", async () => {
  if (zv.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 (r15) {
    return false;
  }
});
var jv = zp(VB());
var qB = zp(UB());
var Xv = zp(GB());
var HB = jv.default || jv;
var Jse = Xv.default || Xv;
var pm = class extends ao {
  constructor(e) {
    super(), this.wasm = e, this.dataIdNextNumber = 1, this.wasm.tfjs.initWithThreadsCount(XB), qv = this.wasm.tfjs.getThreadsCount(), this.dataIdMap = new Bo(this, ur());
  }
  write(e, t10, o) {
    let n = { id: this.dataIdNextNumber++ };
    return this.move(n, e, t10, o, 1), n;
  }
  numDataIds() {
    return this.dataIdMap.numDataIds();
  }
  async time(e) {
    let t10 = y.now();
    return e(), { kernelMs: y.now() - t10 };
  }
  move(e, t10, o, n, s) {
    let a = this.dataIdNextNumber++;
    if (n === "string") {
      let c = t10;
      this.dataIdMap.set(e, { id: a, stringBytes: c, shape: o, dtype: n, memoryOffset: null, refCount: s });
      return;
    }
    let i = y.sizeFromShape(o), p = i * y.bytesPerElement(n), u = this.wasm._malloc(p) >>> 0;
    this.dataIdMap.set(e, { id: a, memoryOffset: u, shape: o, dtype: n, refCount: s }), this.wasm.tfjs.registerTensor(a, i, u), t10 != null && this.wasm.HEAPU8.set(new Uint8Array(t10.buffer, t10.byteOffset, p), u);
  }
  async read(e) {
    return this.readSync(e);
  }
  readSync(e, t10, o) {
    let { memoryOffset: n, dtype: s, shape: a, stringBytes: i } = this.dataIdMap.get(e);
    if (s === "string") return (t10 == null || t10 === 0) && (o == null || o >= i.length) ? i : i.slice(t10, o);
    t10 = t10 || 0, o = o || y.sizeFromShape(a);
    let p = y.bytesPerElement(s), u = this.wasm.HEAPU8.slice(n + t10 * p, n + o * p);
    return tae(u.buffer, s);
  }
  disposeData(e, t10 = false) {
    if (this.dataIdMap.has(e)) {
      let o = this.dataIdMap.get(e);
      if (o.refCount--, !t10 && o.refCount > 0) return false;
      this.wasm._free(o.memoryOffset), this.wasm.tfjs.disposeData(o.id), this.dataIdMap.delete(e);
    }
    return true;
  }
  refCount(e) {
    return this.dataIdMap.has(e) ? this.dataIdMap.get(e).refCount : 0;
  }
  incRef(e) {
    let t10 = this.dataIdMap.get(e);
    t10 != null && t10.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, t10, o, n) {
    let s;
    if (o == null) s = this.write(n != null ? n : null, e, t10);
    else {
      let a = this.dataIdNextNumber++;
      s = { id: a }, this.dataIdMap.set(s, { id: a, memoryOffset: o, shape: e, dtype: t10, refCount: 1 });
      let i = y.sizeFromShape(e);
      this.wasm.tfjs.registerTensor(a, i, o);
    }
    return { dataId: s, shape: e, dtype: t10 };
  }
  typedArrayFromHeap({ shape: e, dtype: t10, dataId: o }) {
    let n = this.wasm.HEAPU8.buffer, { memoryOffset: s } = this.dataIdMap.get(o), a = y.sizeFromShape(e);
    switch (t10) {
      case "float32":
        return new Float32Array(n, s, a);
      case "int32":
        return new Int32Array(n, s, a);
      case "bool":
        return new Uint8Array(n, s, a);
      default:
        throw new Error(`Unknown dtype ${t10}`);
    }
  }
};
function eae(r15) {
  return (e, t10) => (y.fetch(r15, { credentials: "same-origin" }).then((o) => {
    o.ok || e.env.a(`failed to load wasm binary file at '${r15}'`), o.arrayBuffer().then((n) => {
      WebAssembly.instantiate(n, e).then((s) => {
        t10(s.instance, s.module);
      });
    });
  }), {});
}
function KB(r15, e, t10) {
  if (Gg != null) return Gg;
  let o = "tfjs-backend-wasm.wasm";
  return r15 && e ? o = "tfjs-backend-wasm-threaded-simd.wasm" : r15 && (o = "tfjs-backend-wasm-simd.wasm"), im != null && im[o] != null ? im[o] : t10 + o;
}
async function jB() {
  let [r15, e] = await Promise.all([A().getAsync("WASM_HAS_SIMD_SUPPORT"), A().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);
  return new Promise((t10, o) => {
    let n = {};
    n.locateFile = (i, p) => {
      if (i.endsWith(".worker.js")) {
        let u = qB.wasmWorkerContents.replace(/\n/g, "\\n"), c = new Blob([u], { type: "application/javascript" });
        return URL.createObjectURL(c);
      }
      return i.endsWith(".wasm") ? KB(r15, e, am != null ? am : p) : p + i;
    }, Yv && (n.instantiateWasm = eae(KB(r15, e, am != null ? am : "")));
    let s = false;
    n.onAbort = () => {
      if (s || um) return;
      um = true, o({ 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 && r15 && Gg == null ? (n.mainScriptUrlOrBlob = new Blob(["var WasmBackendModuleThreadedSimd = " + HB.toString()], { type: "text/javascript" }), a = HB(n)) : a = Jse(n), a.then((i) => {
      s = true, um = false;
      let p = 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", p, ["number"]), dispose: i.cwrap("dispose", p, []) }, t10({ wasm: i });
    }).catch(o);
  });
}
function tae(r15, e) {
  switch (e) {
    case "float32":
      return new Float32Array(r15);
    case "int32":
      return new Int32Array(r15);
    case "bool":
      return new Uint8Array(r15);
    default:
      throw new Error(`Unknown dtype ${e}`);
  }
}
var rae = ["tfjs-backend-wasm.wasm", "tfjs-backend-wasm-simd.wasm", "tfjs-backend-wasm-threaded-simd.wasm"];
var Gg = null;
var am = null;
var im = {};
var um = false;
var Yv = false;
function oae(r15, e = false) {
  if (Tw("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."), um) throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");
  Gg = r15, Yv = e;
}
function nae(r15, e = false) {
  if (um) throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");
  if (typeof r15 == "string") am = r15;
  else {
    im = r15;
    let t10 = rae.filter((o) => im[o] == null);
    if (t10.length > 0) throw new Error(`There were no entries found for the following binaries: ${t10.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.`);
  }
  Yv = e;
}
var XB = -1;
var qv = -1;
function sae(r15) {
  XB = r15;
}
function aae() {
  if (qv === -1) throw new Error("WASM backend not initialized.");
  return qv;
}
var iae = "4.22.0";
var uae = 2;
tu("wasm", async () => {
  let { wasm: r15 } = await jB();
  return new pm(r15);
}, uae);
var go = A();
go.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE", () => 15);
go.registerFlag("WEBGPU_CPU_FORWARD", () => true);
go.registerFlag("WEBGPU_MATMUL_PROGRAM_TYPE", () => -1);
go.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE", () => true);
go.registerFlag("WEBGPU_USE_LOW_POWER_GPU", () => false);
go.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD", () => 1e3);
go.registerFlag("WEBGPU_USE_PROFILE_TOOL", () => false);
go.registerFlag("WEBGPU_IMPORT_EXTERNAL_TEXTURE", () => true);
go.registerFlag("WEBGPU_USE_NAIVE_CONV2D_DEBUG", () => false);
go.registerFlag("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL", () => -1);
go.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER", () => false);
go.registerFlag("WEBGPU_PRINT_SHADER", () => "");
go.registerFlag("WEBGPU_ENGINE_COMPILE_ONLY", () => false);
var Hg = class {
  constructor(e) {
    e && (this.vendor = e.vendor, this.architecture = e.architecture, this.intelGPUGeneration = this.getIntelGPUGeneration());
  }
  getIntelGPUGeneration() {
    if (this.isIntel()) {
      if (this.architecture.startsWith("gen")) return Number(this.architecture.match(/\d+/));
      if (this.architecture.startsWith("xe")) return 12;
    }
    return 0;
  }
  isIntel() {
    return this.vendor === "intel";
  }
};
var Kg = class {
  constructor(e) {
    this.device = e, this.numUsedBuffers = 0, this.numFreeBuffers = 0, this.freeBuffers = /* @__PURE__ */ new Map(), this.usedBuffers = /* @__PURE__ */ new Map(), this.numBytesUsed = 0, this.numBytesAllocated = 0;
  }
  acquireBuffer(e, t10, o = false, n = true) {
    let s, a = YB(e, t10);
    return n ? (this.freeBuffers.has(a) || this.freeBuffers.set(a, []), this.freeBuffers.get(a).length > 0 ? (s = this.freeBuffers.get(a).pop(), this.numFreeBuffers--) : (s = this.device.createBuffer({ size: e, usage: t10, mappedAtCreation: o }), this.numBytesAllocated += e)) : (s = this.device.createBuffer({ size: e, usage: t10, mappedAtCreation: o }), this.numBytesAllocated += e), this.usedBuffers.has(a) || this.usedBuffers.set(a, []), this.usedBuffers.get(a).push(s), this.numUsedBuffers++, this.numBytesUsed += e, s;
  }
  releaseBuffer(e, t10 = true) {
    if (this.freeBuffers.size === 0) return;
    let o = e.size, n = e.usage, s = YB(o, n), a = this.usedBuffers.get(s), i = a.indexOf(e);
    if (i < 0) throw new Error("Cannot find the buffer in buffer manager");
    a[i] = a[a.length - 1], a.pop(), this.numUsedBuffers--, this.numBytesUsed -= o, t10 ? (this.freeBuffers.get(s).push(e), this.numFreeBuffers++) : (e.destroy(), this.numBytesAllocated -= o);
  }
  getNumUsedBuffers() {
    return this.numUsedBuffers;
  }
  getNumFreeBuffers() {
    return this.numFreeBuffers;
  }
  dispose() {
    this.freeBuffers.forEach((e, t10) => {
      e.forEach((o) => {
        o.destroy();
      });
    }), this.usedBuffers.forEach((e, t10) => {
      e.forEach((o) => {
        o.destroy();
      });
    }), this.freeBuffers = /* @__PURE__ */ new Map(), this.usedBuffers = /* @__PURE__ */ new Map(), this.numUsedBuffers = 0, this.numFreeBuffers = 0, this.numBytesUsed = 0, this.numBytesAllocated = 0;
  }
};
function YB(r15, e) {
  return `${r15}_${e}`;
}
var qg = class {
  constructor(e) {
    this.device = e, this.numUsedTextures = 0, this.numFreeTextures = 0, this.freeTextures = /* @__PURE__ */ new Map(), this.usedTextures = /* @__PURE__ */ new Map(), this.numBytesUsed = 0, this.numBytesAllocated = 0;
  }
  acquireTexture(e, t10, o, n) {
    let s = ZB(o), a = e * t10 * s, i = QB(e, t10, o, n);
    if (this.freeTextures.has(i) || this.freeTextures.set(i, []), this.usedTextures.has(i) || this.usedTextures.set(i, []), this.numBytesUsed += a, this.numUsedTextures++, this.freeTextures.get(i).length > 0) {
      this.numFreeTextures--;
      let u = this.freeTextures.get(i).shift();
      return this.usedTextures.get(i).push(u), u;
    }
    this.numBytesAllocated += a;
    let p = this.device.createTexture({ size: [e, t10], format: o, usage: n });
    return this.usedTextures.get(i).push(p), p;
  }
  releaseTexture(e) {
    if (this.freeTextures.size === 0) return;
    let t10 = e.width, o = e.height, n = e.format, s = e.usage, a = QB(t10, o, n, s);
    this.freeTextures.has(a) || this.freeTextures.set(a, []), this.freeTextures.get(a).push(e), this.numFreeTextures++, this.numUsedTextures--;
    let i = this.usedTextures.get(a), p = i.indexOf(e);
    if (p < 0) throw new Error("Cannot release a texture that was never provided by this texture manager");
    i.splice(p, 1);
    let u = ZB(n), c = t10 * o * u;
    this.numBytesUsed -= c;
  }
  getNumUsedTextures() {
    return this.numUsedTextures;
  }
  getNumFreeTextures() {
    return this.numFreeTextures;
  }
  dispose() {
    this.freeTextures.forEach((e, t10) => {
      e.forEach((o) => {
        o.destroy();
      });
    }), this.usedTextures.forEach((e, t10) => {
      e.forEach((o) => {
        o.destroy();
      });
    }), this.freeTextures = /* @__PURE__ */ new Map(), this.usedTextures = /* @__PURE__ */ new Map(), this.numUsedTextures = 0, this.numFreeTextures = 0, this.numBytesUsed = 0, this.numBytesAllocated = 0;
  }
};
function QB(r15, e, t10, o) {
  return `${r15}_${e}_${t10}_${o}`;
}
function ZB(r15) {
  if (r15 === "rgba8unorm") return 16;
  throw new Error(`${r15} is not supported!`);
}
function JB(r15, e) {
  if (Math.max(...r15) > 5) throw new Error("Cannot symbolically compute strides for rank > 6 tensor.");
  let t10 = r15.length, o = "xyzwuv", n = r15.map((a) => `${e}.${o[a]}`), s = new Array(t10 - 1);
  s[t10 - 2] = n[t10 - 1];
  for (let a = t10 - 3; a >= 0; --a) s[a] = `(${s[a + 1]} * ${n[a + 1]})`;
  return s;
}
var Qr = (r15, e, t10) => t10 === "int32" ? `atomicAdd(${r15}, bitcast<i32>(${e}));` : `
          {
            var oldValue = 0;
            loop {
              let newValueF32 = bitcast<f32>(oldValue) + (${e});
              let newValue = bitcast<i32>(newValueF32);
              let res = atomicCompareExchangeWeak(${r15}, oldValue, newValue);
              if res.exchanged {
                break;
              }
              oldValue = res.old_value;
            }
          }`;
var wi;
(function(r15) {
  r15[r15.FROM_PIXELS = 0] = "FROM_PIXELS", r15[r15.DRAW = 1] = "DRAW";
})(wi || (wi = {}));
var oz = (r15, e, t10, o, n) => {
  let s = { dtype: o.dtype, shape: o.shape }, a = cae(t10, s, e), i = r15.createShaderModule({ code: a, label: e.constructor.name }), p = A().get("WEBGPU_PRINT_SHADER");
  if (p !== "") {
    p = p.toLowerCase();
    let u = p.split(",");
    (p === "all" || u.some((c) => e.shaderKey.toLowerCase().includes(c))) && (console.group(e.shaderKey), console.debug(a), console.groupEnd());
  }
  return n ? r15.createComputePipelineAsync({ compute: { module: i, entryPoint: "_start" }, label: e.constructor.name, layout: "auto" }) : r15.createComputePipeline({ compute: { module: i, entryPoint: "_start" }, label: e.constructor.name, layout: "auto" });
};
var Ae = (r15, e = "f32") => {
  switch (r15) {
    case 1:
      return `${e}`;
    case 2:
      return `vec2<${e}>`;
    case 3:
      return `vec3<${e}>`;
    case 4:
      return `vec4<${e}>`;
    default:
      throw new Error(`${r15}-component ${e} is not supported.`);
  }
};
function ft(r15) {
  if (r15 <= 1) return "i32";
  if (r15 === 2) return "vec2<i32>";
  if (r15 === 3) return "vec3<i32>";
  if (r15 === 4) return "vec4<i32>";
  if (r15 === 5) return "vec5";
  if (r15 === 6) return "vec6";
  throw Error(`GPU for rank ${r15} is not yet supported`);
}
function Oo(r15) {
  if (r15 === 0) return "x";
  if (r15 === 1) return "y";
  if (r15 === 2) return "z";
  if (r15 === 3) return "w";
  if (r15 === 4) return "u";
  if (r15 === 5) return "v";
  throw Error(`Index ${r15} is not yet supported`);
}
function G(...r15) {
  let e;
  switch (r15.length) {
    case 0:
      e = `
        fn main()
      `;
      break;
    case 1:
      e = `
        fn main(${r15[0]} : i32)
      `;
      break;
    default:
      throw Error("Unreachable");
  }
  return e;
}
function ez(r15, e) {
  let t10;
  return t10 = `
     ${pae(e)}
      fn _start(@builtin(local_invocation_id) LocalId : vec3<u32>,
                @builtin(global_invocation_id) GlobalId : vec3<u32>,
                @builtin(local_invocation_index) LocalIndex: u32,
                @builtin(workgroup_id) WorkgroupId : vec3<u32>,
                @builtin(num_workgroups) NumWorkgroups : vec3<u32>) {
        localId = LocalId;
        localIndex = LocalIndex;
        globalId = GlobalId;
        numWorkgroups = NumWorkgroups;
        workgroupId = WorkgroupId;
        ${r15 ? "main(getGlobalIndex());" : "main();"};
      }
    `, t10;
}
function pae(r15) {
  return `
  @compute @workgroup_size(${r15.workgroupSize[0]}, ${r15.workgroupSize[1]}, ${r15.workgroupSize[2]})
`;
}
function cae(r15, e, t10) {
  let o = [], n = t10.workgroupSize[0] * t10.workgroupSize[1] * t10.workgroupSize[2];
  if (t10.outputComponent = t10.outputComponent ? t10.outputComponent : 1, o.push(`

      var<private> localId: vec3<u32>;
      var<private> localIndex: u32;
      var<private> globalId: vec3<u32>;
      var<private> numWorkgroups: vec3<u32>;
      var<private> workgroupId: vec3<u32>;

      // Only used when the y/z dimension of workgroup size is 1.
      fn getGlobalIndex() -> i32 {
        ${sz(t10) ? "  return i32(globalId.x);" : `  return i32((workgroupId.z * numWorkgroups.x * numWorkgroups.y +
                workgroupId.y * numWorkgroups.x + workgroupId.x) * ${n}u +
                localIndex);
        `}
      }
    `), t10.pixelsOpType != null) {
    let f = t10.pixelsOpType === wi.FROM_PIXELS ? `@group(0) @binding(0) var<storage, read_write> result: array<${Su(e.dtype, t10.outputComponent)}>;` : `@group(0) @binding(1) var<storage, read> inBuf : array<${Su(r15[0].dtype, t10.outputComponent)}>;`, h = e.shape.length === 3 ? "vec2<i32>" : "i32";
    o.push(`
        struct Uniform {
          outShapeStrides : ${h},
          size            : i32,
          numChannels     : i32,
          alpha           : f32,
        };

        ${f}
        @group(0) @binding(2) var<uniform> uniforms: Uniform;
      `);
    let g = rz(t10);
    return [tz, o.join(`
`), cm(e.shape), t10.getUserCode(), ez(g, t10)].join(`
`);
  }
  let s, a, i = "struct Uniforms { NAN : f32, INFINITY : f32, ";
  t10.variableNames.forEach((f, h) => {
    let g = ft(r15[h].shape.length);
    i += `${f.charAt(0).toLowerCase() + f.slice(1)}Shape : ${g}, `, s = r15[h].shape.length - 1, a = ft(s), i += `${f.charAt(0).toLowerCase() + f.slice(1)}ShapeStrides: ${a}, `;
  });
  let p = ft(e.shape.length);
  i += `outShape : ${p}, `, s = e.shape.length - 1, a = ft(s), i += `
         outShapeStrides: ${a}, `, t10.size && (i += "size : i32, "), t10.uniforms && (i += t10.uniforms), i += "};", i = yae(i), o.push(i), t10.atomic ? o.push(`
      @group(0) @binding(0) var<storage, read_write> result: array<atomic<i32>>;
    `) : o.push(`
      @group(0) @binding(0) var<storage, read_write> result: array<${Su(e.dtype, t10.outputComponent)}>;
    `), t10.variableNames.forEach((f, h) => {
    o.push(`
      @group(0) @binding(${1 + h}) var<storage, read> ${f}: array<${t10.variableComponents ? Su(r15[h].dtype, t10.variableComponents[h]) : Su(r15[h].dtype, t10.outputComponent)}>;
        `);
  }), i !== "" && o.push(`
      @group(0) @binding(${1 + t10.variableNames.length}) var<uniform> uniforms: Uniforms;
      `);
  let u = hae(e.shape, t10.dispatchLayout), c = [tz, o.join(`
`) + lae, cm(e.shape), u, gae(e.shape.length)];
  t10.atomic || c.push(xae(e.shape, e.dtype, t10.outputComponent)), t10.variableNames.forEach((f, h) => {
    c.push(`${cm(r15[h].shape, f)}`);
  });
  let l = r15.map((f, h) => fae(f, e.shape, t10.variableComponents ? t10.variableComponents[h] : t10.outputComponent, t10.dispatchLayout.x.length === e.shape.length)).join(`
`);
  c.push(l), c.push(t10.getUserCode());
  let m = rz(t10);
  return c.push(ez(m, t10)), c.join(`
`);
}
function nz(r15, e, t10) {
  let o = r15.shaderKey;
  if (r15.pixelsOpType != null) return o;
  let n = [], s = [];
  e.forEach((c) => {
    n.push(c.shape), s.push(c.dtype);
  }), n.push(t10.shape), s.push(t10.dtype);
  let a = e.map((c) => w.getBroadcastDims(c.shape, t10.shape)), i = e.map((c) => y.arraysEqual(c.shape, t10.shape)).join("_"), p = a.map((c) => c.join("_")).join(";"), u = sz(r15) ? "flatDispatch" : "";
  return o += "_" + (r15.workgroupSize ? r15.workgroupSize.join(",") : "") + n.map((c) => c.length).join(",") + s.join(",") + r15.variableNames.join(",") + p + i + u, o;
}
var tz = `
  struct vec5 {x: i32, y: i32, z: i32, w: i32, u: i32};
  struct vec6 {x: i32, y: i32, z: i32, w: i32, u: i32, v: i32};

  // Checks whether coordinates lie within the bounds of the shape.
  fn coordsInBounds2D(coord : vec2<i32>, shape : vec2<i32>) -> bool {
    return all(coord >= vec2<i32>(0)) && all(coord < shape);
  }
  fn coordsInBounds3D(coord : vec3<i32>, shape : vec3<i32>) -> bool {
    return all(coord >= vec3<i32>(0)) && all(coord < shape);
  }
  fn coordsInBounds4D(coord : vec4<i32>, shape : vec4<i32>) -> bool {
    return all(coord >= vec4<i32>(0)) && all(coord < shape);
  }

  fn getIndexFromCoords1D(coord : i32, shape : i32) -> i32 {
    return coord;
  }
  fn getIndexFromCoords2D(coords : vec2<i32>, shape : vec2<i32>) -> i32 {
    return dot(coords, vec2<i32>(shape.y, 1));
  }
  fn getIndexFromCoords3D(coords : vec3<i32>, shape : vec3<i32>) -> i32 {
    return dot(coords, vec3<i32>(shape.y * shape.z, shape.z, 1));
  }
  fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
    return dot(coords, vec4<i32>(
        shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
  }
  fn getIndexFromCoords5D(coords : vec5, shape : vec5) -> i32 {
    let shapeStrides: vec5 = vec5(shape.y * shape.z * shape.w * shape.u, shape.z * shape.w * shape.u, shape.w * shape.u, shape.u, 1);
    return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u;
  }
  fn getIndexFromCoords6D(coords : vec6, shape : vec6) -> i32 {
    let shapeStrides: vec6 = vec6(shape.y * shape.z * shape.w * shape.u * shape.v, shape.z * shape.w * shape.u * shape.v, shape.w * shape.u * shape.v, shape.u * shape.v, shape.v, 1);
    return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u + coords.v*shapeStrides.v;
  }

  // NaN defination in IEEE 754-1985 is :
  //   - sign = either 0 or 1.
  //   - biased exponent = all 1 bits.
  //   - fraction = anything except all 0 bits (since all 0 bits represents infinity).
  // https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers
  fn isnan(val: f32) -> bool {
    let floatToUint: u32 = bitcast<u32>(val);
    return (floatToUint & 0x7fffffffu) > 0x7f800000u;
  }
  fn isnanVec4(val : vec4<f32>) -> vec4<bool> {
    let floatToUint: vec4<u32> = bitcast<vec4<u32>>(val);
    return (floatToUint & vec4<u32>(0x7fffffffu)) > vec4<u32>(0x7f800000u);
  }
`;
var lae = `
  fn isinf(val: f32) -> bool {
    return abs(val) == uniforms.INFINITY;
  }
`;
function cm(r15, e = "") {
  let t10 = r15.length, o = e !== "" ? `get${e.charAt(0).toUpperCase() + e.slice(1)}CoordsFromIndex` : "getCoordsFromIndex", n = e !== "" ? `${e.charAt(0).toLowerCase() + e.slice(1)}ShapeStrides` : "outShapeStrides";
  if (t10 <= 1) return `fn ${o}(index : i32) -> i32 { return index; }`;
  let s = y.computeStrides(r15), a = ft(t10), i = [];
  for (let u = 0; u < t10; u++) i.push(`d${u}`);
  if (s.length === 1) return `    fn ${o}(index : i32) -> vec2<i32> {
      let d0 = index / uniforms.${n}; let d1 = index - d0 * uniforms.${n};
      return vec2<i32>(d0, d1);
    }`;
  let p;
  return p = "var index2 = index;" + s.map((u, c) => {
    let l = `let ${i[c]} = index2 / uniforms.${n}.${Oo(c)}`, m = c === s.length - 1 ? `let ${i[c + 1]} = index2 - ${i[c]} * uniforms.${n}.${Oo(c)}` : `index2 = index2 - ${i[c]} * uniforms.${n}.${Oo(c)}`;
    return `${l}; ${m};`;
  }).join(""), `
    fn ${o}(index : i32) -> ${a} {
      ${p}
      return ${a}(${i.join(",")});
    }
  `;
}
function mae(r15, e) {
  let t10 = r15.name, o = r15.shape.length, n = ft(o), s = "get" + t10.charAt(0).toUpperCase() + t10.slice(1), a = ["d0", "d1", "d2", "d3", "d4", "d5"].slice(0, o), i = a.map((c) => `${c} : i32`).join(", ");
  if (o < 1) return `
      fn ${s}() -> ${Ae(e)} {
        return ${Ae(e)}(${t10}[0]);
      }
    `;
  let p = `uniforms.${t10.charAt(0).toLowerCase() + t10.slice(1)}Shape`, u = `${o}D`;
  return o === 0 && (u = "1D"), `
    fn ${s}(${i}) -> ${Ae(e)} {
      return ${Ae(e)}(${t10}[getIndexFromCoords${u}(${n}(${a.join(",")}),
        ${p})${e === 1 ? "" : ` / ${e}`}]);
    }
   `;
}
function dae(r15, e, t10, o) {
  let n = r15.name, s = n.charAt(0).toUpperCase() + n.slice(1), a = "get" + s + "ByOutput", i = r15.shape.length, p = e.length, u = ft(p);
  if (y.arraysEqual(r15.shape, e) && o) return `
    fn ${a}Index(globalIndex : i32) -> ${Ae(t10)} {
      return ${Ae(t10)}(${n}[globalIndex]);
    }

    fn ${a}Coords(coords : ${u}) -> ${Ae(t10)} {
      return ${Ae(t10)}(${n}[${p > 1 ? "getOutputIndexFromCoords(coords)" : "coords"}${t10 === 1 ? "" : ` / ${t10}`}]);
    }
    `;
  let c = w.getBroadcastDims(r15.shape, e), l = p - i, m = "";
  if (i === 0) return `
    fn ${a}Index(globalIndex : i32) -> ${Ae(t10)}{
      return get${s}();
    }

    fn ${a}Coords(coords : ${u}) -> ${Ae(t10)}{
      return get${s}();
    }
  `;
  p < 2 && c.length >= 1 ? m = "coords = 0;" : m = c.map((g) => `coords.${Oo(g + l)} = 0;`).join(`
`);
  let d = "";
  if (p < 2 && i > 0) d = "coords";
  else if (p > 1) {
    let g = ft(i), x = r15.shape.map((b, C) => `coords.${Oo(C + l)}`).join(", ");
    d = `${g}(${x})`;
  } else d = "coords";
  let f = `uniforms.${n.charAt(0).toLowerCase() + n.slice(1)}Shape`, h = `${i}D`;
  return `
  fn ${a}Index(globalIndex : i32) -> ${Ae(t10)} {
    var coords = getCoordsFromIndex(globalIndex);
    ${m}
    return ${Ae(t10)}(${n}[getIndexFromCoords${h}(${d}, ${f})${t10 === 1 ? "" : ` / ${t10}`}]);
  }

  fn ${a}Coords(coordsIn : ${u}) -> ${Ae(t10)} {
    var coords = coordsIn;
    ${m}
    return ${Ae(t10)}(${n}[getIndexFromCoords${h}(${d}, ${f})${t10 === 1 ? "" : ` / ${t10}`}]);
  }
`;
}
function fae(r15, e, t10, o) {
  let n = mae(r15, t10);
  return r15.shape.length <= e.length && (n += dae(r15, e, t10, o)), n;
}
function hae(r15, e) {
  let { x: t10, y: o = [], z: n = [] } = e, s = r15.length, a = t10.length + o.length + n.length;
  if (a !== s) return "";
  if (t10.length === s) return `fn getOutputCoords() -> ${ft(s)}{
    let globalIndex = getGlobalIndex();
    return getCoordsFromIndex(globalIndex);
  }
  `;
  let i = "", p = [t10, o, n];
  for (let m = 0; m < p.length; m++) {
    let d = p[m];
    if (d.length !== 0) if (d.length === 1) i += `let d${d[0]} = i32(globalId[${m}]);`;
    else {
      let f = JB(d, "uniforms.outShape");
      i += `var index${m} = i32(globalId[${m}]);`;
      for (let h = 0; h < f.length; h++) i += `let d${d[h]} = index${m} / ${f[h]};`, h === f.length - 1 ? i += `let d${d[h + 1]} = index${m} - d${d[h]} * ${f[h]};` : i += `index${m} = index${m} - d${d[h]} * ${f[h]};`;
    }
  }
  let u = [];
  for (let m = 0; m < a; m++) u.push(`d${m}`);
  let c = ft(a), l = `fn getOutputCoords() -> ${c} {
  ${i}
`;
  return u.length === 0 ? l += `return ${c}(0); }` : l += `return ${c}(${u.join(",")}); }`, l;
}
function gae(r15) {
  let e = "";
  switch (r15) {
    case 0:
    case 1:
      e += `
        fn getOutputIndexFromCoords(coords : i32) -> i32 {
          return coords;
        }
        `;
      break;
    case 2:
      e += `
        fn getOutputIndexFromCoords(coords : vec2<i32>) -> i32 {
          return dot(coords, vec2<i32>(uniforms.outShapeStrides, 1));
        }
        `;
      break;
    case 3:
      e += `
        fn getOutputIndexFromCoords(coords : vec3<i32>) -> i32 {
          return dot(coords, vec3<i32>(uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, 1));
        }
        `;
      break;
    case 4:
      e += `
        fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
          return dot(coords, vec4<i32>(
            uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, uniforms.outShapeStrides.z, 1));
        }
        `;
      break;
    case 5:
      e += `
        fn getOutputIndexFromCoords(coords : vec5) -> i32 {
          return coords.x * uniforms.outShapeStrides.x +
              coords.y * uniforms.outShapeStrides.y +
              coords.z * uniforms.outShapeStrides.z +
              coords.w * uniforms.outShapeStrides.w +
              coords.u;
        }
        `;
      break;
    case 6:
      e += `
        fn getOutputIndexFromCoords(coords : vec6) -> i32 {
          return coords.x * uniforms.outShapeStrides.x +
              coords.y * uniforms.outShapeStrides.y +
              coords.z * uniforms.outShapeStrides.z +
              coords.w * uniforms.outShapeStrides.w +
              coords.u * uniforms.outShapeStrides.u +
              coords.v;
        }
        `;
      break;
    default:
      y.assert(false, () => `Unsupported ${r15}D shape`);
      break;
  }
  return e;
}
function sz(r15) {
  return r15.dispatch[1] === 1 && r15.dispatch[2] === 1;
}
function Su(r15, e = 1) {
  if (r15 === "float32") return Ae(e, "f32");
  if (r15 === "int32" || r15 === "bool") return Ae(e, "i32");
  throw new Error(`type ${r15} is not supported.`);
}
function xae(r15, e, t10) {
  let o = r15.length, n = Su(e, t10), s = `fn setOutputAtIndex(flatIndex : i32, value : ${Ae(t10)}) {
      result[flatIndex] = ${n}(value);
    }

    fn setOutputAtIndexI32(flatIndex : i32, value : ${Ae(t10, "i32")}) {
      result[flatIndex] = ${n}(value);
    }
    `;
  if (o >= 2) {
    let a = ["d0", "d1", "d2", "d3", "d4", "d5"].slice(0, o), i = ft(o);
    s += `
      fn setOutputAtCoords(${a.map((p) => `${p} : i32`).join(", ")}, value : ${Ae(t10)}) {
        let flatIndex = getOutputIndexFromCoords(${i}(${a.join(", ")}));
        setOutputAtIndex(flatIndex${t10 === 1 ? "" : ` / ${t10}`}, value);
      }
      fn setOutputAtCoordsI32(${a.map((p) => `${p} : i32`).join(", ")}, value : ${Ae(t10, "i32")}) {
        let flatIndex = getOutputIndexFromCoords(${i}(${a.join(", ")}));
        setOutputAtIndexI32(flatIndex${t10 === 1 ? "" : ` / ${t10}`}, value);
      }
    `;
  }
  return s;
}
function yae(r15) {
  let e = /(\w+)\s*:\s*vec(5|6)/g;
  r15 = r15.replace(e, (o) => "@align(16) " + o);
  let t10 = /vec(5|6)\s*,\s*(\w+)/g;
  return r15 = r15.replace(t10, (o, n, s) => `vec${n}, @align(16) ${s}`), r15;
}
function rz(r15) {
  return !(r15.dispatchLayout.hasOwnProperty("y") && r15.dispatchLayout.y.length !== 0 || r15.dispatchLayout.hasOwnProperty("z") && r15.dispatchLayout.z.length !== 0);
}
var Zv = {};
qe(Zv, { GPUBytesPerElement: () => jg, MatMulProgramType: () => Mo, assertNotComplex: () => fm, computeDispatch: () => H, computeWorkPerThreadForConv2d: () => mm, computeWorkgroupInfoForMatMul: () => Qv, computeWorkgroupSizeForConv2d: () => lm, flatDispatchLayout: () => X, isWebGPUSupported: () => dm, tilesFitEvenlyIntoShape: () => Cae });
var Tp = (r15) => {
  let e = 1;
  for (let t10 = 0; t10 < r15.length; t10++) e *= r15[t10];
  return e;
};
function Cae(r15, e) {
  if (r15.length !== e.length) throw new Error(`Cannot compute whether rank ${r15.length} tiles fit evenly into rank ${e.length} shape - ranks must match.`);
  return e.every((t10, o) => t10 % r15[o] === 0);
}
function H(r15, e, t10 = [1, 1, 1], o = [1, 1, 1]) {
  let [n, s, a] = [Math.ceil(Tp(r15.x.map((i) => e[i])) / (t10[0] * o[0])), r15.y ? Math.ceil(Tp(r15.y.map((i) => e[i])) / (t10[1] * o[1])) : 1, r15.z ? Math.ceil(Tp(r15.z.map((i) => e[i])) / (t10[2] * o[2])) : 1];
  return [n, s, a];
}
function Qv(r15, e, t10, o = false) {
  let n = [8, 8, 1], s = [4, 4, 1];
  return o || (r15 <= 8 && (s[1] = 1), e <= 16 && t10 <= 16 && (n[0] = 4)), { workgroupSize: n, elementsPerThread: s };
}
function lm(r15, e, t10 = false) {
  if (t10) return [8, 8, 1];
  let o = Tp(r15.x.map((s) => e[s])), n = Tp(r15.y.map((s) => e[s]));
  return o <= 4 ? [4, 16, 1] : n <= 4 ? [16, 4, 1] : [16, 16, 1];
}
function mm(r15, e, t10 = false) {
  if (t10) return [4, 4, 1];
  let o = Tp(r15.x.map((s) => e[s])), n = Tp(r15.y.map((s) => e[s]));
  return o <= 4 ? [1, 2, 1] : n <= 4 ? [2, 1, 1] : [2, 2, 1];
}
function X(r15) {
  return { x: r15.map((e, t10) => t10) };
}
function jg(r15) {
  if (r15 === "float32" || r15 === "int32" || r15 === "bool" || r15 === "string") return 4;
  if (r15 === "complex64") return 8;
  throw new Error(`Unknown dtype ${r15}`);
}
function dm() {
  return !!(typeof globalThis != "undefined" && globalThis.navigator && globalThis.navigator.gpu);
}
function fm(r15, e) {
  Array.isArray(r15) || (r15 = [r15]), r15.forEach((t10) => {
    t10 != null && y.assert(t10.dtype !== "complex64", () => `${e} does not support complex64 tensors in the WebGPU backend.`);
  });
}
var Mo;
(function(r15) {
  r15[r15.MatMulReduceProgram = 0] = "MatMulReduceProgram", r15[r15.MatMulSplitKProgram = 1] = "MatMulSplitKProgram", r15[r15.MatMulSmallOutputSizeProgram = 2] = "MatMulSmallOutputSizeProgram", r15[r15.MatMulPackedProgram = 3] = "MatMulPackedProgram", r15[r15.MatMulMax = 4] = "MatMulMax";
})(Mo || (Mo = {}));
var wae = A().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD");
var Sae = (r15, e) => {
  let t10 = r15.limits.maxComputeWorkgroupsPerDimension, o = e.dispatchLayout, n = e.dispatch;
  if (n.every((a) => a <= t10)) return n;
  y.assert(n[0] > t10 && o.y === void 0 && o.z === void 0, () => "Dispatch size exceeds WebGPU limits in Y or Z dimension.");
  let s = Math.ceil(Math.sqrt(n[0]));
  return s > t10 ? (s = Math.ceil(Math.cbrt(n[0])), y.assert(s <= t10, () => "Total dispatch size exceeds WebGPU maximum."), [s, s, s]) : [s, s, 1];
};
var jc = class r14 extends ao {
  nextDataId() {
    return r14.nextDataId++;
  }
  constructor(e, t10) {
    if (super(), this.commandQueueOwnedIds = /* @__PURE__ */ new WeakSet(), this.dispatchCountInPass = 0, this.disposed = false, this.downloadWaitMs = 0, this.tensorDataPendingDisposal = [], this.queryResolveBuffer = null, this.querySet = null, this.querySetCount = 2, this.stagingPendingDisposal = [], this.uniformPendingDisposal = [], this.uploadWaitMs = 0, this.hasReadSyncWarned = false, this.hasTimestampQueryWarned = false, !dm()) throw new Error("WebGPU is not supported on this device");
    this.pipelineCache = {}, this.device = e, this.queue = e.queue, this.commandEncoder = null, this.computePassEncoder = null, this.adapterInfo = new Hg(t10), this.supportTimestampQuery = this.device.features.has("timestamp-query"), this.thresholdToIncreaseWorkgroups = this.adapterInfo.intelGPUGeneration >= 12 ? 16 : 8, this.bufferManager = new Kg(this.device), this.textureManager = new qg(this.device), this.tensorMap = new Bo(this, ur()), A().getBool("WEBGPU_USE_PROFILE_TOOL") && (this.dummyCanvas = document.createElement("canvas"), this.dummyCanvas.width = 1, this.dummyCanvas.height = 1, this.dummyContext = this.dummyCanvas.getContext("webgpu"), this.dummyContext.configure({ device: e, format: "bgra8unorm" }), document.body.appendChild(this.dummyCanvas));
  }
  floatPrecision() {
    return 32;
  }
  disposeData(e, t10 = false) {
    if (!this.tensorMap.has(e)) return true;
    let o = this.tensorMap.get(e);
    return t10 ? o.refCount = 0 : o.refCount--, o.refCount > 0 ? false : (o.complexTensorInfos != null && (this.disposeData(o.complexTensorInfos.real.dataId), this.disposeData(o.complexTensorInfos.imag.dataId)), this.commandQueueOwnedIds.has(e) ? (this.tensorDataPendingDisposal.push(e), true) : (this.releaseResource(e), this.tensorMap.delete(e), true));
  }
  memory() {
    return { numBytesInGPU: this.bufferManager.numBytesUsed, numBytesAllocatedInGPU: this.bufferManager.numBytesAllocated, unreliable: false };
  }
  releaseResource(e) {
    let t10 = this.tensorMap.get(e);
    if (!(!t10 || !t10.resource)) {
      if (t10.external) {
        t10.resource = null;
        return;
      }
      t10.resource instanceof GPUBuffer ? this.bufferManager.releaseBuffer(t10.resource) : t10.resource instanceof GPUTexture && this.textureManager.releaseTexture(t10.resource), t10.resource = null;
    }
  }
  refCount(e) {
    return this.tensorMap.has(e) ? this.tensorMap.get(e).refCount : 0;
  }
  incRef(e) {
    let t10 = this.tensorMap.get(e);
    t10.refCount++;
  }
  decRef(e) {
    if (this.tensorMap.has(e)) {
      let t10 = this.tensorMap.get(e);
      t10.refCount--;
    }
  }
  write(e, t10, o) {
    if (o === "complex64" && e != null) throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
    let n = { id: this.nextDataId() };
    return this.tensorMap.set(n, { dtype: o, shape: t10, values: e, refCount: 1 }), n;
  }
  move(e, t10, o, n, s) {
    if (n === "complex64") throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
    this.tensorMap.set(e, { dtype: n, shape: o, values: t10, refCount: s });
  }
  submitQueue() {
    this.queue.submit([this.commandEncoder.finish()]), this.commandEncoder = null, this.dispatchCountInPass = 0, this.commandQueueOwnedIds = /* @__PURE__ */ new WeakSet(), this.tensorDataPendingDisposal.forEach((e) => {
      this.releaseResource(e), this.tensorMap.delete(e);
    }), this.uniformPendingDisposal.forEach((e) => this.bufferManager.releaseBuffer(e)), this.stagingPendingDisposal.forEach((e) => this.bufferManager.releaseBuffer(e, false)), this.tensorDataPendingDisposal = [], this.uniformPendingDisposal = [], this.stagingPendingDisposal = [];
  }
  ensureCommandEncoderReady() {
    this.commandEncoder || (this.commandEncoder = this.device.createCommandEncoder());
  }
  endComputePassEncoder() {
    this.computePassEncoder && (this.computePassEncoder.end(), this.computePassEncoder = null);
  }
  async checkCompileCompletionAsync() {
    let e;
    try {
      e = await Promise.all(Object.values(this.pipelineCache));
    } catch (t10) {
      throw new Error(t10.message);
    }
    Object.keys(this.pipelineCache).map((t10, o) => {
      this.pipelineCache[t10] = e[o];
    });
  }
  async getBufferData(e) {
    if (A().getBool("WEBGPU_ENGINE_COMPILE_ONLY")) return console.warn("The data may be invalid since WEBGPU_ENGINE_COMPILE_ONLY is true, this can only be called when WEBGPU_ENGINE_COMPILE_ONLY is false"), null;
    let t10 = e.size, o = this.bufferManager.acquireBuffer(t10, GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ);
    this.ensureCommandEncoderReady(), this.endComputePassEncoder(), this.commandEncoder.copyBufferToBuffer(e, 0, o, 0, t10), this.submitQueue(), await o.mapAsync(GPUMapMode.READ);
    let n = o.getMappedRange().slice(0);
    return o.unmap(), o != null && this.bufferManager.releaseBuffer(o), A().getBool("WEBGPU_USE_PROFILE_TOOL") && (y.assert(this.dummyContext !== void 0, () => "Fail to get context for profiling tool"), this.dummyContext.getCurrentTexture()), n;
  }
  convertAndCacheOnCPU(e, t10) {
    let o = this.tensorMap.get(e);
    return o.values = t10, o.values;
  }
  readSync(e) {
    let t10 = this.tensorMap.get(e), { values: o, complexTensorInfos: n } = t10;
    if (o != null || t10.dtype === "string") return o;
    if (t10.dtype === "complex64") {
      let h = this.readSync(n.real.dataId), g = this.readSync(n.imag.dataId), x = y.convertBackendValuesAndArrayBuffer(w.mergeRealAndImagArrays(h, g).buffer, "float32");
      return this.convertAndCacheOnCPU(e, x), x;
    }
    this.hasReadSyncWarned || (this.hasReadSyncWarned = true, console.warn("The performance of synchronously reading data from GPU to CPU is poor on the webgpu backend, please use asynchronous APIs instead."));
    let s = ["opaque", "premultiplied"], a = t10.resource, i = a.size;
    y.assert(i % 4 === 0, () => "Because there is 4 bytes for one pixel, buffer size must be multiple of 4.");
    let p = i / 4, u = new ArrayBuffer(i), c = 256, l = 256, m = s.map((h) => new OffscreenCanvas(c, l)), d = new OffscreenCanvas(c, l);
    this.endComputePassEncoder(), m.map((h, g) => {
      let x = h.getContext("webgpu");
      return x.configure({ device: this.device, format: "bgra8unorm", usage: GPUTextureUsage.COPY_DST, alphaMode: s[g] }), x.getCurrentTexture();
    }).map((h, g) => {
      let x = c * 4, b = (R, D, P) => {
        this.ensureCommandEncoderReady(), this.commandEncoder.copyBufferToTexture({ buffer: a, bytesPerRow: x, offset: P }, { texture: h }, { width: R, height: D }), this.submitQueue();
        let O = d.getContext("2d", { willReadFrequently: true });
        O.clearRect(0, 0, R, D), O.drawImage(m[g], 0, 0);
        let M = O.getImageData(0, 0, R, D).data, L = s[g], B = new Uint8ClampedArray(u, P, R * D * 4);
        for (let z = 0; z < B.length; z += 4) if (L === "premultiplied") B[z + 3] = M[z + 3];
        else {
          let U = M[z];
          B[z] = M[z + 2], B[z + 1] = M[z + 1], B[z + 2] = U;
        }
      }, C = Math.floor(p / (c * l)), S = c, k = l, _ = 0;
      for (let R = 0; R < C; R++) b(S, k, _), _ += c * l * 4;
      let $ = p % (c * l);
      k = Math.floor($ / c), k > 0 && (b(S, k, _), _ += k * (c * 4)), S = $ % c, S > 0 && b(S, 1, _);
    });
    let f = y.convertBackendValuesAndArrayBuffer(u, t10.dtype);
    return this.convertAndCacheOnCPU(e, f), f;
  }
  async read(e) {
    if (!this.tensorMap.has(e)) throw new Error(`Tensor ${e} was not registered!`);
    let t10 = this.tensorMap.get(e), { values: o } = t10;
    if (o != null) return o;
    let n;
    if (t10.dtype === "complex64") {
      let s = await Promise.all([this.read(t10.complexTensorInfos.real.dataId), this.read(t10.complexTensorInfos.imag.dataId)]), a = s[0], i = s[1];
      n = w.mergeRealAndImagArrays(a, i);
    } else {
      let s = await this.getBufferData(t10.resource);
      n = y.convertBackendValuesAndArrayBuffer(s, t10.dtype);
    }
    return this.convertAndCacheOnCPU(e, n), n;
  }
  copyBuffer(e) {
    let t10 = e.size, o = e.usage, n = this.bufferManager.acquireBuffer(t10, o);
    return this.ensureCommandEncoderReady(), this.endComputePassEncoder(), this.commandEncoder.copyBufferToBuffer(e, 0, n, 0, t10), this.submitQueue(), n;
  }
  createTensorFromGPUData(e, t10, o) {
    let n = e.buffer;
    if (o === "complex64") throw new Error("Cannot write to a complex64 dtype. ");
    let s = { id: this.nextDataId() };
    this.tensorMap.set(s, { dtype: o, shape: t10, values: null, refCount: 1, external: e.zeroCopy });
    let a = this.tensorMap.get(s), i = jg(a.dtype) * y.sizeFromShape(a.shape);
    if (e.buffer.size < i) throw new Error(`GPUBuffer size(${e.buffer.size}) is smaller than tensor size(${i})!`);
    if ((e.buffer.usage & (GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC)) !== (GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC)) throw new Error("GPUBuffer.usage should include GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC!");
    return e.zeroCopy !== true && (n = this.copyBuffer(n)), a.resource = n, ur().makeTensorFromDataId(s, t10, o, this);
  }
  readToGPU(e) {
    let t10 = this.tensorMap.get(e), { values: o, dtype: n, shape: s, resource: a } = t10;
    if (n === "complex64") throw new Error("Does not support reading buffer for complex64 dtype.");
    if (a == null) throw o != null ? new Error("Data is not on GPU but on CPU.") : new Error("There is no data on GPU or CPU.");
    let i = a, p = i.size, u = i.usage, c = this.bufferManager.acquireBuffer(p, u);
    this.ensureCommandEncoderReady(), this.endComputePassEncoder(), this.commandEncoder.copyBufferToBuffer(a, 0, c, 0, p), this.submitQueue();
    let l = this.makeTensorInfo(s, n), m = ur().makeTensorFromTensorInfo(l), d = this.tensorMap.get(l.dataId);
    return d.resource = c, { tensorRef: m, buffer: c };
  }
  bufferSync(e) {
    let t10 = this.readSync(e.dataId);
    if (e.dtype === "string") try {
      let o = t10.map((n) => y.decodeString(n));
      return me(e.shape, e.dtype, o);
    } catch (o) {
      throw new Error("Failed to decode encoded string bytes into utf-8");
    }
    return me(e.shape, e.dtype, t10);
  }
  async time(e) {
    !this.supportTimestampQuery && !this.hasTimestampQueryWarned && (console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --enable-dawn-features=allow_unsafe_apis to try it again. Otherwise, zero will be shown for the kernel time when profiling mode is enabled."), this.hasTimestampQueryWarned = true);
    let t10 = this.activeTimers, o = [], n = false;
    this.programTimersStack == null ? (this.programTimersStack = o, n = true) : this.activeTimers.push(o), this.activeTimers = o, e();
    let s = y.flatten(this.activeTimers.map((u) => u.query)).filter((u) => u != null), a = y.flatten(this.activeTimers.map((u) => u.name)).filter((u) => u != null);
    this.activeTimers = t10, n && (this.programTimersStack = null);
    let i = { uploadWaitMs: this.uploadWaitMs, downloadWaitMs: this.downloadWaitMs, kernelMs: null, wallMs: null }, p = await Promise.all(s);
    return i.kernelMs = y.sum(p), i.getExtraProfileInfo = () => p.map((u, c) => ({ name: a[c], ms: u })).map((u) => `${u.name}: ${u.ms}`).join(", "), this.uploadWaitMs = 0, this.downloadWaitMs = 0, i;
  }
  makeTensorInfo(e, t10, o) {
    return t10 === "string" && o != null && o.length > 0 && y.isString(o[0]) && (o = o.map((s) => y.encodeString(s))), { dataId: this.write(o, e, t10), shape: e, dtype: t10 };
  }
  tensorToBinding(e) {
    if (!e) return null;
    let o = this.tensorMap.get(e.dataId).resource;
    return o instanceof GPUBuffer ? { buffer: o } : o instanceof GPUTexture ? o.createView() : o;
  }
  uploadToGPU(e) {
    let t10 = this.tensorMap.get(e);
    if (t10.resource != null) return;
    let o = jg(t10.dtype) * y.sizeFromShape(t10.shape), n, s = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
    if (t10.values) {
      if (n = this.bufferManager.acquireBuffer(o, s, true), n.mapState === "unmapped") {
        let a = this.bufferManager.acquireBuffer(o, GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC, true, false), i = a.getMappedRange();
        t10.dtype === "int32" || t10.dtype === "bool" ? new Int32Array(i).set(t10.values) : new Float32Array(i).set(t10.values), a.unmap(), this.ensureCommandEncoderReady(), this.endComputePassEncoder(), this.commandEncoder.copyBufferToBuffer(a, 0, n, 0, o), this.stagingPendingDisposal.push(a);
      } else {
        let a = n.getMappedRange();
        t10.dtype === "int32" || t10.dtype === "bool" ? new Int32Array(a).set(t10.values) : new Float32Array(a).set(t10.values), n.unmap();
      }
      t10.values = null;
    } else n = this.bufferManager.acquireBuffer(o, s);
    t10.resource = n;
  }
  makeUniforms(e) {
    let t10 = 0, o = 0, n = [], s = 1;
    e.forEach((p) => {
      p.data.length === 0 && (p.data = [1]);
      let u;
      switch (p.data.length) {
        case 1:
          u = 4;
          break;
        case 2:
          u = 8;
          break;
        case 3:
          u = 16;
          break;
        case 4:
          u = 16;
          break;
        case 5:
          u = 16;
          break;
        case 6:
          u = 16;
          break;
        default:
          y.assert(false, () => `Unsupported ${p.data.length}D shape`);
      }
      (o === 5 || o === 6) && (u = 16), u > s && (s = u), t10 = Math.ceil(t10 / u) * u, o = p.data.length, n.push(t10), t10 += p.data.length * 4;
    }), t10 = Math.ceil(t10 / s) * s;
    let a = new ArrayBuffer(t10);
    e.forEach((p, u) => {
      let c = n[u];
      p.type === "int32" ? new Int32Array(a, c, p.data.length).set(p.data) : p.type === "uint32" ? new Uint32Array(a, c, p.data.length).set(p.data) : new Float32Array(a, c, p.data.length).set(p.data);
    });
    let i = this.bufferManager.acquireBuffer(t10, GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM);
    return this.queue.writeBuffer(i, 0, a, 0, t10), this.uniformPendingDisposal.push(i), { offset: 0, size: t10, buffer: i };
  }
  runWebGPUProgram(e, t10, o, n, s) {
    if (s || (s = this.makeTensorInfo(e.outputShape, o)), y.sizeFromShape(s.shape) === 0) return this.tensorMap.get(s.dataId).values = y.getTypedArrayFromDType(s.dtype, 0), s;
    this.uploadToGPU(s.dataId), e.dispatch = Sae(this.device, e);
    let a = t10.map((p, u) => {
      if (p.dtype === "complex64") throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");
      return this.uploadToGPU(p.dataId), { dtype: this.tensorMap.get(p.dataId).dtype, shape: p.shape, name: e.variableNames[u] };
    });
    e.shaderKey = nz(e, a, s);
    let i = A().getBool("WEBGPU_ENGINE_COMPILE_ONLY");
    return e.shaderKey in this.pipelineCache || (this.pipelineCache[e.shaderKey] = oz(this.device, e, a, s, i)), e.pipeline = this.pipelineCache[e.shaderKey], i || this.recordAndSubmit(e, s, t10, n), s;
  }
  recordAndSubmit(e, t10, o, n) {
    if (e.pipeline instanceof Promise) throw new Error("Please call checkCompileCompletionAsync to ensure parallel compilation is done!");
    let s = [], a = [], i = "int32";
    if (e.pixelsOpType == null) {
      s.push({ type: "float32", data: [NaN] }, { type: "float32", data: [1 / 0] }), a = o.concat(t10).map((d) => d.shape);
      let m = "int32";
      a.map((d) => {
        s.push({ type: m, data: d });
        let f = y.computeStrides(d);
        s.push({ type: m, data: f });
      });
    } else {
      let m = y.computeStrides(t10.shape);
      s.push({ type: i, data: m });
    }
    if (e.size) {
      let m = y.sizeFromShape(e.outputShape);
      s.push({ type: i, data: [e.outputComponent ? m / e.outputComponent : m] });
    }
    n && (s = [...s, ...n]);
    let p = [this.tensorToBinding(t10), ...o.map((m) => this.tensorToBinding(m)), this.makeUniforms(s)];
    o.forEach((m) => {
      this.commandQueueOwnedIds.add(m.dataId);
    }), this.commandQueueOwnedIds.add(t10.dataId);
    let u = this.device.createBindGroup({ layout: e.pipeline.getBindGroupLayout(0), entries: p.map((m, d) => ({ binding: d, resource: m })) }), c = this.activeTimers != null;
    this.ensureCommandEncoderReady();
    let l = {};
    c && this.supportTimestampQuery ? (this.endComputePassEncoder(), this.querySet == null && (this.querySet = this.device.createQuerySet({ type: "timestamp", count: this.querySetCount })), l.timestampWrites = { querySet: this.querySet, beginningOfPassWriteIndex: 0, endOfPassWriteIndex: 1 }, this.computePassEncoder = this.commandEncoder.beginComputePass(l)) : this.computePassEncoder || (this.computePassEncoder = this.commandEncoder.beginComputePass(l)), this.computePassEncoder.setPipeline(e.pipeline), this.computePassEncoder.setBindGroup(0, u), this.computePassEncoder.dispatchWorkgroups(e.dispatch[0], e.dispatch[1], e.dispatch[2]), this.dispatchCountInPass++, (c || A().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE") <= this.dispatchCountInPass || e.pixelsOpType === wi.DRAW) && (this.endComputePassEncoder(), c ? this.activeTimers.push({ name: e.constructor.name, query: this.getQueryTime() }) : this.submitQueue());
  }
  async getQueryTime() {
    if (!this.supportTimestampQuery) return 0;
    this.queryResolveBuffer == null && (this.queryResolveBuffer = this.bufferManager.acquireBuffer(this.querySetCount * 8, GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST | GPUBufferUsage.QUERY_RESOLVE)), this.commandEncoder.resolveQuerySet(this.querySet, 0, this.querySetCount, this.queryResolveBuffer, 0);
    let e = this.bufferManager.acquireBuffer(this.querySetCount * 8, GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST);
    this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer, 0, e, 0, this.querySetCount * 8), this.submitQueue(), await e.mapAsync(GPUMapMode.READ);
    let t10 = new BigUint64Array(e.getMappedRange()), o = Number(t10[1] - t10[0]) / 1e6;
    return e.unmap(), this.bufferManager.releaseBuffer(e), o;
  }
  shouldExecuteOnCPU(e, t10 = wae) {
    return A().getBool("WEBGPU_CPU_FORWARD") && e.every((o) => this.tensorMap.get(o.dataId).resource == null && y.sizeFromShape(o.shape) < t10);
  }
  numDataIds() {
    return this.tensorMap.numDataIds() - this.tensorDataPendingDisposal.length;
  }
  dispose() {
    this.disposed || (this.querySet != null && this.querySet.destroy(), this.bufferManager.dispose(), this.textureManager.dispose(), this.disposed = true);
  }
};
jc.nextDataId = 0;
dm() && tu("webgpu", async () => {
  let r15 = { powerPreference: A().get("WEBGPU_USE_LOW_POWER_GPU") ? "low-power" : "high-performance" }, e = await navigator.gpu.requestAdapter(r15), t10 = {}, o = [];
  e.features.has("timestamp-query") && o.push("timestamp-query"), e.features.has("bgra8unorm-storage") && o.push(["bgra8unorm-storage"]), t10.requiredFeatures = o;
  let n = e.limits;
  t10.requiredLimits = { maxComputeWorkgroupStorageSize: n.maxComputeWorkgroupStorageSize, maxComputeWorkgroupsPerDimension: n.maxComputeWorkgroupsPerDimension, maxStorageBufferBindingSize: n.maxStorageBufferBindingSize, maxBufferSize: n.maxBufferSize, maxComputeWorkgroupSizeX: n.maxComputeWorkgroupSizeX, maxComputeInvocationsPerWorkgroup: n.maxComputeInvocationsPerWorkgroup };
  let s = await e.requestDevice(t10), a = "info" in e ? e.info : "requestAdapterInfo" in e ? await e.requestAdapterInfo() : void 0;
  return new jc(s, a);
}, 3);
var fe;
(function(r15) {
  r15[r15.ADD = 0] = "ADD", r15[r15.ATAN2 = 1] = "ATAN2", r15[r15.COMPLEX_MULTIPLY_IMAG = 2] = "COMPLEX_MULTIPLY_IMAG", r15[r15.COMPLEX_MULTIPLY_REAL = 3] = "COMPLEX_MULTIPLY_REAL", r15[r15.DIV = 4] = "DIV", r15[r15.ELU_DER = 5] = "ELU_DER", r15[r15.EQUAL = 6] = "EQUAL", r15[r15.FLOOR_DIV = 7] = "FLOOR_DIV", r15[r15.GREATER = 8] = "GREATER", r15[r15.GREATER_EQUAL = 9] = "GREATER_EQUAL", r15[r15.LESS = 10] = "LESS", r15[r15.LESS_EQUAL = 11] = "LESS_EQUAL", r15[r15.LOGICAL_AND = 12] = "LOGICAL_AND", r15[r15.LOGICAL_OR = 13] = "LOGICAL_OR", r15[r15.MAX = 14] = "MAX", r15[r15.MIN = 15] = "MIN", r15[r15.MOD = 16] = "MOD", r15[r15.MUL = 17] = "MUL", r15[r15.NOT_EQUAL = 18] = "NOT_EQUAL", r15[r15.POW = 19] = "POW", r15[r15.PRELU = 20] = "PRELU", r15[r15.SQUARED_DIFFERENCE = 21] = "SQUARED_DIFFERENCE", r15[r15.SUB = 22] = "SUB";
})(fe || (fe = {}));
var Iae = "let resultTemp = a + b;";
var vae = "let resultTemp = atan2(a, b);";
var kae = "let resultTemp = areal * breal - aimag * bimag;";
var Nae = "let resultTemp = areal * bimag + aimag * breal;";
var Tae = "let resultTemp = a / b;";
var _ae = "let resultTemp = select(a * (b + 1.0), a, b >= b - b);";
var Eae = `
  let zero = sign(a) * 0 + 0;
  let one = sign(b) * 0 + 1;
  let resultTemp = select(zero, one, a == b);
`;
var $ae = `
  let remainder =
      select(a % b, round(a % b), (round(a) == a) & (round(b) == b));
  let quotient = (a - remainder) / b;
  let resultTemp =
      round(select(quotient, quotient - 1, sign(remainder) == -sign(b)));
`;
var Rae = `
  let zero = sign(a) * 0 + 0;
  let one = sign(b) * 0 + 1;
  let resultTemp = select(zero, one, a > b);
`;
var Dae = `
  let zero = sign(a) * 0 + 0;
  let one = sign(b) * 0 + 1;
  let resultTemp = select(zero, one, a >= b);
`;
var Aae = `
  let zero = sign(a) * 0 + 0;
  let one = sign(b) * 0 + 1;
  let resultTemp = select(zero, one, a < b);
`;
var Fae = `
  let zero = sign(a) * 0 + 0;
  let one = sign(b) * 0 + 1;
  let resultTemp = select(zero, one, a <= b);
`;
var Pae = "return f32(a >= 1.0 && b >= 1.0);";
var Oae = `return (vec4<f32>(a >= vec4<f32>(1.0)) *
  vec4<f32>(b >= vec4<f32>(1.0)));`;
var Mae = "return f32(a >= 1.0 || b >= 1.0);";
var Lae = `return min(vec4<f32>(a >= vec4<f32>(1.0)) +
  vec4<f32>(b >= vec4<f32>(1.0)), vec4<f32>(1.0));`;
var Bae = "let resultTemp = max(a, b);";
var zae = "let resultTemp = min(a, b);";
var Vae = `
  let isNaN = b == 0.;
  var resultTemp = a % b;
  resultTemp = select((resultTemp + b) % b, resultTemp,
      (a < 0. && b < 0.) || (a >= 0. && b > 0.));
`;
var Wae = `
  let isNaN = !vec4<bool>(b);
  var resultTemp = vec4<f32>(a % b);
  if (!((a[0] < 0. && b[0] < 0.) || (a[0] >= 0. && b[0] > 0.))) {
    resultTemp[0] = (resultTemp[0] + b[0]) % b[0];
  }
  if (!((a[1] < 0. && b[1] < 0.) || (a[1] >= 0. && b[1] > 0.))) {
    resultTemp[1] = (resultTemp[1] + b[1]) % b[1];
  }
  if (!((a[2] < 0. && b[2] < 0.) || (a[2] >= 0. && b[2] > 0.))) {
    resultTemp[2] = (resultTemp[2] + b[2]) % b[2];
  }
  if (!((a[3] < 0. && b[3] < 0.) || (a[3] >= 0. && b[3] > 0.))) {
    resultTemp[3] = (resultTemp[3] + b[3]) % b[3];
  }
`;
var Uae = "let resultTemp = a * b;";
var Gae = `
  var resultTemp = f32(a != b);
  let valueForNaN = 1.0;
`;
var Hae = `
  var resultTemp = vec4<f32>(a != b);
  let valueForNaN = 1.0;
`;
var Kae = `
  let isNaN = a < 0.0 && floor(b) < b;
  if (b == 0.0) {
    return 1.0;
  }
  var resultTemp = select(sign(a) * pow(abs(a), b), pow(abs(a), b),
      round(abs(b) % 2.0) != 1.0);
`;
var qae = `
  let isModRound1Bool = vec4<i32>(round(abs(b) % vec4<f32>(2.0))) == vec4<i32>(1);
  let isModRound1 = vec4<f32>(isModRound1Bool);
  let multiplier = sign(a) * isModRound1 + (vec4<f32>(1.0) - isModRound1);
  var resultTemp = multiplier * pow(abs(a), b);

  // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
  let isExpZero = b == vec4<f32>(0.0);
  if (isExpZero.r) {
    resultTemp.r = 1.0;
  }
  if (isExpZero.g) {
    resultTemp.g = 1.0;
  }
  if (isExpZero.b) {
    resultTemp.b = 1.0;
  }
  if (isExpZero.a) {
    resultTemp.a = 1.0;
  }
  let isNaN = (a < vec4<f32>(0.0)) & (floor(b) < b);
`;
var jae = "if (a < 0.0) { return b * a; }  return a;";
var Xae = `
  let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
  return (aLessThanZero * (b * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
`;
var Yae = "let resultTemp = (a - b) * (a - b);";
var Qae = "let resultTemp = a - b;";
function Xc(r15, e) {
  let t10;
  do {
    switch (r15) {
      case fe.ATAN2:
        t10 = vae;
        break;
      case fe.MAX:
        t10 = Bae;
        break;
      case fe.MIN:
        t10 = zae;
        break;
      case fe.MOD:
        t10 = e ? Wae : Vae;
        break;
      case fe.NOT_EQUAL:
        t10 = e ? Hae : Gae;
        break;
      case fe.POW:
        t10 = e ? qae : Kae;
        break;
      default:
        continue;
    }
    let o, n, s;
    return e ? (o = "isnanVec4", n = "vec4<f32>", s = "vec4<bool>") : (o = "isnan", n = "f32", s = "bool"), `
      let aIsNaN = ${o}(a);
      let aPostLegalization = select(a, ${n}(42), aIsNaN);
      let bIsNaN = ${o}(b);
      let bPostLegalization = select(b, ${n}(42), bIsNaN);
      let isNaN = false;
      let valueForNaN = uniforms.NAN;
      {
        let a = aPostLegalization;
        let b = bPostLegalization;
        ${t10}
        return select(
            resultTemp, ${n}(valueForNaN),
            ${s}(isNaN) | aIsNaN | bIsNaN);
      }
    `;
  } while (false);
  switch (r15) {
    case fe.ADD:
      t10 = Iae;
      break;
    case fe.COMPLEX_MULTIPLY_IMAG:
      t10 = Nae;
      break;
    case fe.COMPLEX_MULTIPLY_REAL:
      t10 = kae;
      break;
    case fe.DIV:
      t10 = Tae;
      break;
    case fe.ELU_DER:
      t10 = _ae;
      break;
    case fe.EQUAL:
      t10 = Eae;
      break;
    case fe.FLOOR_DIV:
      t10 = $ae;
      break;
    case fe.GREATER:
      t10 = Rae;
      break;
    case fe.GREATER_EQUAL:
      t10 = Dae;
      break;
    case fe.LESS:
      t10 = Aae;
      break;
    case fe.LESS_EQUAL:
      t10 = Fae;
      break;
    case fe.LOGICAL_AND:
      return e ? Oae : Pae;
    case fe.LOGICAL_OR:
      return e ? Lae : Mae;
    case fe.MUL:
      t10 = Uae;
      break;
    case fe.PRELU:
      return e ? Xae : jae;
    case fe.SQUARED_DIFFERENCE:
      t10 = Yae;
      break;
    case fe.SUB:
      t10 = Qae;
      break;
    default:
  }
  return `
    ${t10}
    return resultTemp;
  `;
}
var Z;
(function(r15) {
  r15[r15.ABS = 0] = "ABS", r15[r15.ACOS = 1] = "ACOS", r15[r15.ACOSH = 2] = "ACOSH", r15[r15.ASIN = 3] = "ASIN", r15[r15.ASINH = 4] = "ASINH", r15[r15.ATAN = 5] = "ATAN", r15[r15.ATANH = 6] = "ATANH", r15[r15.CEIL = 7] = "CEIL", r15[r15.COS = 8] = "COS", r15[r15.COSH = 9] = "COSH", r15[r15.ELU = 10] = "ELU", r15[r15.ERF = 11] = "ERF", r15[r15.EXP = 12] = "EXP", r15[r15.EXPM1 = 13] = "EXPM1", r15[r15.FLOOR = 14] = "FLOOR", r15[r15.IS_FINITE = 15] = "IS_FINITE", r15[r15.IS_INF = 16] = "IS_INF", r15[r15.IS_NAN = 17] = "IS_NAN", r15[r15.LINEAR = 18] = "LINEAR", r15[r15.LOG = 19] = "LOG", r15[r15.LOG1P = 20] = "LOG1P", r15[r15.LOGICAL_NOT = 21] = "LOGICAL_NOT", r15[r15.NEG = 22] = "NEG", r15[r15.RELU = 23] = "RELU", r15[r15.RELU6 = 24] = "RELU6", r15[r15.LEAKYRELU = 25] = "LEAKYRELU", r15[r15.RECIPROCAL = 26] = "RECIPROCAL", r15[r15.ROUND = 27] = "ROUND", r15[r15.RSQRT = 28] = "RSQRT", r15[r15.SELU = 29] = "SELU", r15[r15.SIGMOID = 30] = "SIGMOID", r15[r15.SIGN = 31] = "SIGN", r15[r15.SIN = 32] = "SIN", r15[r15.SINH = 33] = "SINH", r15[r15.SOFTPLUS = 34] = "SOFTPLUS", r15[r15.SQRT = 35] = "SQRT", r15[r15.SQUARE = 36] = "SQUARE", r15[r15.STEP = 37] = "STEP", r15[r15.TAN = 38] = "TAN", r15[r15.TANH = 39] = "TANH", r15[r15.TO_INT = 40] = "TO_INT";
})(Z || (Z = {}));
var Zae = "return abs(a);";
var Jae = `
  if (abs(a) > 1.) {
    return uniforms.NAN;
  }
  return acos(a);
`;
var eie = `
  if (a < 1.) {
    return uniforms.NAN;
  }
  return acosh(a);
`;
var tie = `
  if (abs(a) > 1.) {
    return uniforms.NAN;
  }
  return asin(a);
`;
var rie = "return asinh(a);";
var oie = `
  if (isnan(a)) {
    return uniforms.NAN;
  }
  return atan(a);
`;
var nie = `
  if (abs(a) > 1.) {
    return uniforms.NAN;
  }
  if (a == 1.) {
    return uniforms.INFINITY;
  }
  if (a == -1.) {
    return -uniforms.INFINITY;
  }
  return atanh(a);
`;
var sie = "return ceil(a);";
var aie = "return cos(a);";
var iie = `
  let e2x = exp(-a);
  return (e2x + 1.0 / e2x) / 2.0;
`;
var uie = "return exp(a) - 1.0;";
var pie = "if (a >= 0.0) { return a; }  return (exp(a) - 1.0);";
var cie = `
  var resFloat = exp(a) - vec4<f32>(1.0);
  if (a.r >= 0.0) {
    resFloat.r = a.r;
  }
  if (a.g >= 0.0) {
    resFloat.g = a.g;
  }
  if (a.b >= 0.0) {
    resFloat.b = a.b;
  }
  if (a.a >= 0.0) {
    resFloat.a = a.a;
  }
  return resFloat;
`;
var lie = `
  // Error function is calculated approximately with elementary function.
  // See "Handbook of Mathematical Functions with Formulas,
  // Graphs, and Mathematical Tables", Abramowitz and Stegun.
  let p = ${w.ERF_P};
  let a1 = ${w.ERF_A1};
  let a2 = ${w.ERF_A2};
  let a3 = ${w.ERF_A3};
  let a4 = ${w.ERF_A4};
  let a5 = ${w.ERF_A5};

  let sign = sign(a);
  let absA = abs(a);
  let t = 1.0 / (1.0 + p * absA);
  return sign * (1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * exp(-absA * absA));
`;
var mie = "return exp(a);";
var die = "return floor(a);";
var fie = "return f32(!isnan(a) && !isinf(a));";
var hie = "return f32(isinf(a));";
var gie = "return f32(isnan(a));";
var xie = "return a;";
var yie = `if (a < 0.0) { return uniforms.NAN; }
  return log(a);`;
var bie = `
  if (isnan(a)) { return a; }
  return log(1.0 + a);
`;
var Cie = "return f32(!(a >= 1.0));";
var wie = "return -a;";
var Sie = "if (a < 0.0) { return uniforms.alpha * a; } return a;";
var Iie = `
  let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
  return (aLessThanZero * (uniforms.alpha * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
`;
var vie = "return 1.0 / a;";
var kie = "return select(a, 0.0, a < 0.0);";
var Nie = "return clamp(a, 0.0, 6.0);";
var Tie = "return clamp(a, vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(6.0, 6.0, 6.0, 6.0));";
var _ie = `
  return select(a, vec4<f32>(0.0), a < vec4<f32>(0.0));
`;
var Eie = "return round(a);";
var $ie = "return inverseSqrt(a);";
var Rie = `
  if (a >= 0.0) {
    return ${w.SELU_SCALE} * a;
  } else {
    return ${w.SELU_SCALEALPHA} * (exp(a) - 1.0);
  }
`;
var Die = "return 1.0 / (1.0 + exp(-1.0 * a));";
var Aie = "return sign(a);";
var Fie = "return sin(a);";
var Pie = `
  let e2x = exp(a);
  return (e2x - 1.0 / e2x) / 2.0;
`;
var Oie = `
  let epsilon = 1.1920928955078125e-7;
  let threshold = log(epsilon) + 2.0;

  let too_large = a > -threshold;
  let too_small = a < threshold;
  let exp_a = exp(a);

  if (too_large) {
    return a;
  } else if (too_small) {
    return exp_a;
  } else {
    return log(exp_a + 1.0);
  }
`;
var Mie = "return sqrt(a);";
var Lie = "return a * a;";
var Bie = `
  if (isnan(a)) {
    return a;
  }

  return select(uniforms.stepAlpha, 1.0, a > 0.0);
`;
var zie = "return tan(a);";
var Vie = `
  let e2x = exp(-2.0 * abs(a));
  return sign(a) * (1.0 - e2x) / (1.0 + e2x);
`;
var Wie = "return f32(i32((a)));";
function Si(r15, e) {
  switch (r15) {
    case Z.ABS:
      return Zae;
    case Z.ACOS:
      return Jae;
    case Z.ACOSH:
      return eie;
    case Z.ASIN:
      return tie;
    case Z.ASINH:
      return rie;
    case Z.ATAN:
      return oie;
    case Z.ATANH:
      return nie;
    case Z.COS:
      return aie;
    case Z.COSH:
      return iie;
    case Z.CEIL:
      return sie;
    case Z.ELU:
      return e ? cie : pie;
    case Z.ERF:
      return lie;
    case Z.EXP:
      return mie;
    case Z.EXPM1:
      return uie;
    case Z.FLOOR:
      return die;
    case Z.IS_FINITE:
      return fie;
    case Z.IS_INF:
      return hie;
    case Z.IS_NAN:
      return gie;
    case Z.LINEAR:
      return xie;
    case Z.LOG:
      return yie;
    case Z.LOG1P:
      return bie;
    case Z.LOGICAL_NOT:
      return Cie;
    case Z.NEG:
      return wie;
    case Z.LEAKYRELU:
      return e ? Iie : Sie;
    case Z.RECIPROCAL:
      return vie;
    case Z.RELU:
      return e ? _ie : kie;
    case Z.RELU6:
      return e ? Tie : Nie;
    case Z.ROUND:
      return Eie;
    case Z.RSQRT:
      return $ie;
    case Z.SELU:
      return Rie;
    case Z.SIGMOID:
      return Die;
    case Z.SIGN:
      return Aie;
    case Z.SIN:
      return Fie;
    case Z.SINH:
      return Pie;
    case Z.SOFTPLUS:
      return Oie;
    case Z.SQRT:
      return Mie;
    case Z.SQUARE:
      return Lie;
    case Z.STEP:
      return Bie;
    case Z.TAN:
      return zie;
    case Z.TANH:
      return Vie;
    case Z.TO_INT:
      return Wie;
    default:
      throw new Error(`BinaryType ${r15} is not implemented!`);
  }
}
function dr(r15, e = false, t10 = false, o = 3) {
  if (r15 === null) return "";
  let n = "";
  if (r15 === "linear") n = Si(Z.LINEAR);
  else if (r15 === "relu") n = Si(Z.RELU, t10);
  else if (r15 === "elu") n = Si(Z.ELU, t10);
  else if (r15 === "relu6") n = Si(Z.RELU6, t10);
  else if (r15 === "prelu") n = Xc(fe.PRELU, t10);
  else if (r15 === "sigmoid") n = Si(Z.SIGMOID, t10);
  else if (r15 === "leakyrelu") n = Si(Z.LEAKYRELU, t10);
  else throw new Error(`Activation ${r15} has not been implemented for the WebGPU backend.`);
  let a = Ae(t10 ? 4 : 1), i = "";
  return e ? i = `
      fn activation(a : ${a}, coords : vec${o}<i32>) -> ${a} {
        let b = getPreluActivationWeightsByOutputCoords(coords);
        ${n}
      }` : i = `
      fn activation(a : ${a}, coords : vec${o}<i32>) -> ${a} {
        ${n}
      }`, i;
}
function Zr(r15, e) {
  return `
      ${r15 ? "value = value + getBiasByOutputCoords(coords);" : ""}
      ${e ? "value = activation(value, coords);" : ""}
      `;
}
function Jv(r15, e, t10 = false, o = false, n = false, s = 1) {
  y.assert(r15 && s === 1 || !r15, () => `transposeA ${r15} is not compatible with component size ${s}`);
  let a = `
      ${r15 ? "value = getA(batch, col, row);" : "value = getA(batch, row, col);"}

    `, i = e ? "value = getB(batch, col, row);" : "value = getB(batch, row, col);";
  return `
  fn mm_readA(batch: i32, row: i32, col: i32) -> ${Ae(s)} {
    var value = ${Ae(s)}(0.0);
    ${t10 && n ? a : `
    ${r15 ? "if(row < uniforms.dimAOuter && col < uniforms.dimInner)" : "if(row < uniforms.aShape[1] && col < uniforms.aShape[2])"}
    {
      ${a}
    }
    `}
    return value;
  }

  fn mm_readB(batch: i32, row: i32, col: i32) -> ${Ae(s)} {
    var value = ${Ae(s)}(0.0);
    ${i}
    return value;
  }
  `;
}
function hm(r15, e, t10, o, n = false, s = false, a = false, i = 1) {
  return `
  ${Jv(t10, o, n, s, a, i)}
  fn mm_write(batch: i32, row: i32, col: i32, valueIn: ${Ae(i)}) {
    ${n && s ? "" : "if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)"}
    {
      var value = valueIn;
      let coords = vec3<i32>(batch, row, col);
      ${Zr(r15, e)}
      setOutputAtCoords(coords[0], coords[1], coords[2], value);
    }
  }
  `;
}
var Uie = (r15, e) => r15 ? `
        mm_Asub[inputRow][inputCol] = mm_readA(batchA,
          kStart + inputRow,
          globalRowStart + inputCol * ${e});
        ` : `
        mm_Asub[inputRow][inputCol] = mm_readA(batchA,
          globalRow + innerRow,
          kStart + inputCol * ${e});
        `;
var Gie = (r15, e, t10, o) => {
  if (r15) return `
      for (var k = 0; k < ${o}; k++) {
        let BCached0 = mm_Bsub[k][tileCol];
        let ACached0 = mm_Asub[k][localRow];
        for (var i = 0; i < ${t10}; i++) {
          acc[i] = fma(BCached0, vec4<f32>(ACached0[i]), acc[i]);
        }
      }`;
  {
    let n = "", s = "";
    for (let a = 0; a < e; a++) n += `let BCached${a} = mm_Bsub[k * ${e} + ${a}][tileCol];`, s += `acc[i] = fma(BCached${a}, vec4<f32>(ACached[${a}]), acc[i]);`;
    return `
      for (var k = 0; k < ${o / e}; k++) {
        ${n}
        for (var i = 0; i < ${t10}; i++) {
          let ACached = mm_Asub[tileRow + i][k];
          ${s}
        }
      }`;
  }
};
function _p(r15, e, t10 = false, o = 32, n = false, s = 32, a = false) {
  let i = e[1] * r15[1], p = e[0] * r15[0], u = t10 ? i : o, c = t10 ? o : i, l = u / e[0], m = o / e[1], d = r15[1], f = r15[0];
  return y.assert((t10 && l === 4 && r15[1] === 4 || !t10 && (l === 3 || l === 4)) && u % e[0] === 0 && o % e[1] === 0 && r15[0] === 4, () => `If transposeA ${t10} is true, innerElementSize ${l} and workPerThread[1] ${r15[1]} must be 4.
          Otherwise, innerElementSize ${l} must be 3 or 4.
      tileAWidth ${u} must be divisible by workgroupSize[0]${e[0]}. tileInner ${o} must be divisible by workgroupSize[1] ${e[1]}. colPerThread ${r15[0]} must be 4.`), `
  var<workgroup> mm_Asub : array<array<vec${l}<f32>, ${u / l}>, ${c}>;
  var<workgroup> mm_Bsub : array<array<vec4<f32>, ${p / r15[0]}>, ${o}>;

  ${G()} {
    let localRow = i32(localId.y);
    let tileRow = localRow * ${d};
    let tileCol = i32(localId.x);

    let globalRow = i32(globalId.y) * ${d};
    let globalCol = i32(globalId.x) * ${f};
    let batch = ${n ? "0" : "i32(globalId.z)"};
    let batchA = ${n || !a ? "batch" : "batch % uniforms.aShape[0]"};
    let batchB = ${n || !a ? "batch" : "batch % uniforms.bShape[0]"};
    let globalRowStart = i32(workgroupId.y) * ${i};

    let numTiles = ${n ? `${Math.ceil(s / o)}` : `(uniforms.dimInner - 1) / ${o} + 1`};
    var kStart = ${n ? `i32(globalId.z) * ${s}` : "0"};

    var acc: array<vec4<f32>, ${d}>;

    // Loop over shared dimension.
    let tileRowB = localRow * ${m};
    for (var t = 0; t < numTiles; t++) {
        // Load one tile of A into local memory.
        for (var innerRow = 0; innerRow < ${d}; innerRow++) {
            let inputRow = tileRow + innerRow;
            let inputCol = tileCol;
            ${Uie(t10, l)}
        }

        // Load one tile of B into local memory.
        for (var innerRow = 0; innerRow < ${m}; innerRow++) {
            let inputRow = tileRowB + innerRow;
            let inputCol = tileCol;
            mm_Bsub[inputRow][inputCol] = mm_readB(batchB, kStart + inputRow, globalCol);
        }
        kStart = kStart + ${o};
        workgroupBarrier();

        // Compute acc values for a single thread.
        ${Gie(t10, l, d, o)}
        workgroupBarrier();
    }

    for (var innerRow = 0; innerRow < ${d}; innerRow++) {
        mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);
    }
  }`;
}
var az = (r15) => r15 ? `
        mm_Asub[inputRow][inputCol] = mm_readA(batchA,
          kStart + inputRow,
          globalRowStart + inputCol);
        ` : `
        mm_Asub[inputRow][inputCol] = mm_readA(batchA,
          globalRowStart + inputRow,
          kStart + inputCol);
        `;
var Hie = (r15) => r15 ? "let ACached = mm_Asub[k][tileRow + innerRow];" : "let ACached = mm_Asub[tileRow + innerRow][k];";
function Ep(r15, e, t10 = false, o = 32, n = false, s = 32, a = false, i = false) {
  let p = r15[1] * e[1], u = r15[0] * e[0], c = t10 ? p : o, l = t10 ? o : p;
  y.assert(l % e[1] === 0 && c % e[0] === 0 && o % e[1] === 0, () => `tileAHight ${l} must be divisible by workgroupSize[1]${e[1]}, tileAWidth ${c} must be divisible by workgroupSize[0]${e[0]}, tileInner ${o} must be divisible by workgroupSize[1]${e[1]}`);
  let m = l / e[1], d = c / e[0], f = o / e[1], h = r15[1], g = r15[0], x = a ? `
      let localRow = i32(localId.y);
      let localCol = i32(localId.x);
      let globalRowStart = i32(workgroupId.y) * ${p};
      let globalColStart = i32(workgroupId.x) * ${u};

      // Loop over shared dimension.
      for (var t = 0; t < numTiles; t++) {
        // Load one tile of A into local memory.
        for (var inputRow = localRow; inputRow < ${l}; inputRow = inputRow + ${e[1]}) {
          for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${e[0]}) {
            ${az(t10)}
          }
        }
        // Load one tile of B into local memory.
        for (var inputRow = localRow; inputRow < ${o}; inputRow = inputRow + ${e[1]}) {
              for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${e[0]}) {
            mm_Bsub[inputRow][inputCol] = mm_readB(batchB,
              kStart + inputRow,
              globalColStart + inputCol);
          }
        }
        kStart = kStart + ${o};
        workgroupBarrier();

        // Compute acc values for a single thread.
        var BCached : array<f32, ${g}>;
        for (var k = 0; k < ${o}; k++) {
          for (var inner = 0; inner < ${g}; inner++) {
            BCached[inner] = mm_Bsub[k][localCol + inner * ${e[0]}];
          }
          for (var innerRow = 0; innerRow < ${h}; innerRow++) {
            let ACached = ${t10 ? `mm_Asub[k][localRow + innerRow * ${e[1]}];` : `mm_Asub[localRow + innerRow * ${e[1]}][k];`}
            for (var innerCol = 0; innerCol < ${g}; innerCol++) {
              acc[innerRow][innerCol] =
                  fma(ACached, BCached[innerCol], acc[innerRow][innerCol]);
            }
          }
        }
        workgroupBarrier();
      }
      for (var innerRow = 0; innerRow < ${h}; innerRow++) {
        let gRow = globalRowStart + localRow + innerRow * ${e[1]};
        for (var innerCol = 0; innerCol < ${g}; innerCol++) {
          let gCol = globalColStart + localCol + innerCol * ${e[0]};
          mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);
        }
      }
      ` : `
  let tileRow = i32(localId.y) * ${h};
  let tileCol = i32(localId.x) * ${g};

  let globalRow = i32(globalId.y) * ${h};
  let globalCol = i32(globalId.x) * ${g};
  let globalRowStart = i32(workgroupId.y) * ${p};

  let tileRowA = i32(localId.y) * ${m};
  let tileColA = i32(localId.x) * ${d};
  let tileRowB = i32(localId.y) * ${f};
  // Loop over shared dimension.
  for (var t = 0; t < numTiles; t++) {
    // Load one tile of A into local memory.
    for (var innerRow = 0; innerRow < ${m}; innerRow++) {
      for (var innerCol = 0; innerCol < ${d}; innerCol++) {
        let inputRow = tileRowA + innerRow;
        let inputCol = tileColA + innerCol;
        ${az(t10)}
      }
    }

    // Load one tile of B into local memory.
    for (var innerRow = 0; innerRow < ${f}; innerRow++) {
      for (var innerCol = 0; innerCol < ${g}; innerCol++) {
        let inputRow = tileRowB + innerRow;
        let inputCol = tileCol + innerCol;
        mm_Bsub[inputRow][inputCol] = mm_readB(batchB,
          kStart + inputRow,
          globalCol + innerCol);
      }
    }
    kStart = kStart + ${o};
    workgroupBarrier();

    // Compute acc values for a single thread.
    var BCached : array<f32, ${g}>;
    for (var k = 0; k < ${o}; k++) {
      for (var inner = 0; inner < ${g}; inner++) {
        BCached[inner] = mm_Bsub[k][tileCol + inner];
      }

      for (var innerRow = 0; innerRow < ${h}; innerRow++) {
        ${Hie(t10)}
        for (var innerCol = 0; innerCol < ${g}; innerCol++) {
          acc[innerRow][innerCol] =
              fma(ACached, BCached[innerCol], acc[innerRow][innerCol]);
        }
      }
    }

    workgroupBarrier();
  }

  for (var innerRow = 0; innerRow < ${h}; innerRow++) {
    for (var innerCol = 0; innerCol < ${g}; innerCol++) {
      mm_write(batch, globalRow + innerRow, globalCol + innerCol,
          acc[innerRow][innerCol]);
    }
  }
  `;
  return `
    var<workgroup> mm_Asub : array<array<f32, ${c}>, ${l}>;
    var<workgroup> mm_Bsub : array<array<f32, ${u}>, ${o}>;

    ${G()} {
      let batch = ${n ? "0" : "i32(globalId.z)"};
      let batchA = ${n || !i ? "batch" : "batch % uniforms.aShape[0]"};
      let batchB = ${n || !i ? "batch" : "batch % uniforms.bShape[0]"};
      let numTiles = ${n ? `${Math.ceil(s / o)}` : `(uniforms.dimInner - 1) / ${o} + 1`};
      var kStart = ${n ? `i32(globalId.z) * ${s}` : "0"};

      var acc : array<array<f32, ${g}>, ${h}>;

      // Without this initialization strange values show up in acc.
      for (var innerRow = 0; innerRow < ${h}; innerRow++) {
        for (var innerCol = 0; innerCol < ${g}; innerCol++) {
          acc[innerRow][innerCol] = 0.0;
        }
      }
      ${x}
    }
  `;
}
var Kie = (r15) => r15 ? `
      mm_readA(batchA, colA, globalRow),
      mm_readA(batchA, colA + 1, globalRow),
      mm_readA(batchA, colA + 2, globalRow),
      mm_readA(batchA, colA + 3, globalRow)
  ` : `
      mm_readA(batchA, globalRow, colA),
      mm_readA(batchA, globalRow, colA + 1),
      mm_readA(batchA, globalRow, colA + 2),
      mm_readA(batchA, globalRow, colA + 3)
  `;
function qie(r15, e = false) {
  y.assert(r15[1] === 1 && r15[2] === 1, () => `A linear work group size is required. But got ${r15}.`);
  let t10 = r15[0] * 4;
  return `
    var<workgroup> mm_Asub : array<vec4<f32>, ${r15[0]}>;

    ${G()} {
      let tileCol = i32(localId.x);
      let globalCol = i32(globalId.x);
      let globalRow = i32(globalId.y);

      let numTiles = (uniforms.dimInner - 1) / ${t10} + 1;
      let batch = i32(globalId.z);
      let batchA = batch % uniforms.aShape[0];
      let batchB = batch % uniforms.bShape[0];
      // Without this initialization strange values show up in acc.
      var acc = 0.0;

      // Loop over shared dimension.
      for (var t = 0; t < numTiles; t++) {
        // Load one tile of A into local memory.
        let colA = t * ${t10} + tileCol * 4;
        mm_Asub[tileCol] = vec4<f32>(${Kie(e)});
        workgroupBarrier();

        // Compute acc values for a single thread.
        for (var k = 0; k < ${t10 / 4}; k++) {
          let rowB = t * ${t10} + k * 4;
          let BCached = vec4<f32>(mm_readB(batchB, rowB, globalCol),
                              mm_readB(batchB, rowB + 1, globalCol),
                              mm_readB(batchB, rowB + 2, globalCol),
                              mm_readB(batchB, rowB + 3, globalCol));

          let ACached = mm_Asub[k];
          acc = acc + dot(ACached, BCached);
        }

        workgroupBarrier();
      }

      mm_write(batch, globalRow, globalCol, acc);
    }
  `;
}
var Xg = class {
  constructor(e, t10, o = false, n = false, s = null, a = null, i = null, p = false) {
    this.variableNames = ["A", "B"], this.uniforms = "dimAOuter : i32, dimBOuter : i32, dimInner : i32,", this.outputShape = t10, this.dispatchLayout = { x: [2], y: [1], z: [0] };
    let u = o ? e[1] : e[2];
    if (this.isVec4 = (u % 4 === 0 && !o || t10[1] % 4 === 0 && o) && t10[2] % 4 === 0 && !n, this.outputComponent = this.isVec4 ? 4 : 1, this.isVectorA = t10[1] === 1 && !o, !this.isVec4 && this.isVectorA) this.elementsPerThread = [1, 1, 1], this.workgroupSize = [32, 1, 1];
    else {
      let m = Qv(t10[1], u, t10[2], o);
      this.workgroupSize = m.workgroupSize, this.elementsPerThread = m.elementsPerThread;
    }
    this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize, this.elementsPerThread);
    let c = s != null, l = i != null;
    c && this.variableNames.push("bias"), l && this.variableNames.push("preluActivationWeights"), this.sequentialAccessByThreads = p, this.transposeA = o, this.transposeB = n, this.addBias = c, this.activation = a, this.hasPreluActivationWeights = l, [this.fitAOuter, this.fitBOuter, this.fitInner] = this.getShapeFit(t10[1], t10[2], u), this.shaderKey = `matMulPacked_${this.elementsPerThread}_${o}_${n}_${this.activation}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.isVectorA}_${this.sequentialAccessByThreads}`;
  }
  getShapeFit(e, t10, o) {
    let n = this.workgroupSize[1] * this.elementsPerThread[1], s = this.workgroupSize[0] * this.elementsPerThread[0];
    !this.isVec4 && this.isVectorA ? this.tileInner = this.workgroupSize[0] * 4 : this.tileInner = s;
    let a = e % n === 0, i = t10 % s === 0, p = o % this.tileInner === 0;
    return [a, i, p];
  }
  getUserCode() {
    return `
      ${dr(this.activation, this.hasPreluActivationWeights, this.isVec4)}
      ${hm(this.addBias, this.activation, false, this.transposeB, this.fitAOuter, this.fitBOuter, this.fitInner, this.isVec4 ? 4 : 1)}
      ${this.isVec4 ? _p(this.elementsPerThread, this.workgroupSize, this.transposeA, this.tileInner, false, null, true) : this.isVectorA ? qie(this.workgroupSize, this.transposeA) : Ep(this.elementsPerThread, this.workgroupSize, this.transposeA, this.tileInner, false, null, this.sequentialAccessByThreads, true)}
    `;
  }
};
function jie(r15) {
  return `
    var<workgroup> sumValues : array<f32, ${r15}>;
    ${G()} {
      let coords = getOutputCoords();
      let batch = coords[0];
      let batchA = batch % uniforms.aShape[0];
      let batchB = batch % uniforms.bShape[0];
      let row = coords[1];
      let col = coords[2];
      var sum = 0.0;
      let Length = uniforms.dimInner;
      for (var k = i32(localId.x); k < Length; k = k + ${r15}) {
        let dataA = mm_readA(batchA, row, k);
        let dataB = mm_readB(batchB, k, col);
        sum = sum + dataA * dataB;
      }
      sumValues[localId.x] = sum;
      workgroupBarrier();

      for(var currentSize = ${r15 / 2}u; currentSize > 1u;
          currentSize = currentSize / 2u) {
        if (localId.x < currentSize)
        {
          sumValues[localId.x] = sumValues[localId.x] + sumValues[localId.x + currentSize];
        }
        workgroupBarrier();
      }

      if (localId.x == 0u) {
        sum = sumValues[0] + sumValues[1];
        mm_write(batch, row, col, sum);
      }
    }
  `;
}
var Yg = class {
  constructor(e, t10 = false, o = false, n = null, s = null, a = null) {
    this.variableNames = ["A", "B"], this.uniforms = "dimAOuter : i32, dimBOuter : i32, dimInner : i32,", this.workgroupSize = [256, 1, 1], this.outputShape = e, this.dispatchLayout = { x: [], y: [1, 2], z: [0] }, this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize);
    let i = n != null, p = a != null;
    i && this.variableNames.push("bias"), p && this.variableNames.push("preluActivationWeights"), this.transposeA = t10, this.transposeB = o, this.addBias = i, this.activation = s, this.hasPreluActivationWeights = p, this.shaderKey = `matMulReduce_${this.activation}_${t10}_${o}`;
  }
  getUserCode() {
    return `
      ${dr(this.activation, this.hasPreluActivationWeights)}
      ${hm(this.addBias, this.activation, this.transposeA, this.transposeB)}
      ${jie(this.workgroupSize[0])}
    `;
  }
};
function Xie(r15) {
  let e = r15[1], t10 = r15[0], o = e > t10 ? e : t10;
  return `
  var<workgroup> mm_Asub : array<array<f32, ${o}>, ${e}>;
  var<workgroup> mm_Bsub : array<array<f32, ${t10}>, ${o}>;

  // If the output size is small for matrix multiplication, avoid to use vec4
  // and handle some elements per thread to optimally utilize the ALU.
  // Read data from global memory to registers firstly, then store them into
  // shared memory, so it is instruction-Level parallelism for arithmetic
  // operations and others handle IO operations between barrier api, makes ALU
  // and load/store units work simultaneously, could improves the performance.
  ${G()} {
    let tileRow = i32(localId.y);
    let tileCol = i32(localId.x);
    let globalRow = i32(globalId.y);
    let globalCol = i32(globalId.x);
    let batch = i32(globalId.z);
    let batchA = batch % uniforms.aShape[0];
    let batchB = batch % uniforms.bShape[0];

    // uniforms.dimInner should be greater than 0.
    let numTiles = (uniforms.dimInner - 1) / ${o} + 1;
    var acc = 0.0;

    var globalColA = tileCol;
    var globalRowB = 0;
    var regA = mm_readA(batchA, globalRow, globalColA);
    var regB0 = mm_readB(batchB, globalRowB + 2 * tileRow, globalCol);
    var regB1 = mm_readB(batchB, globalRowB + 2 * tileRow + 1, globalCol);
    globalColA = globalColA + ${o};
    globalRowB = globalRowB + ${o};

    for (var t = 0; t < numTiles; t = t + 1) {
      mm_Asub[tileRow][tileCol] = regA;
      mm_Bsub[2 * tileRow][tileCol] = regB0;
      mm_Bsub[2 * tileRow + 1][tileCol] = regB1;

      workgroupBarrier();

      regA = mm_readA(batchA, globalRow, globalColA);
      regB0 = mm_readB(batchB, globalRowB + 2 * tileRow, globalCol);
      regB1 = mm_readB(batchB, globalRowB + 2 * tileRow + 1, globalCol);
      globalColA = globalColA + ${o};
      globalRowB = globalRowB + ${o};

      for (var k = 0; k < ${o}; k = k + 1) {
        acc = acc + mm_Asub[tileRow][k] * mm_Bsub[k][tileCol];
      }
      workgroupBarrier();
    }

    mm_write(batch, globalRow, globalCol, acc);
  }
  `;
}
var Qg = class {
  constructor(e, t10, o, n = false, s = false, a = null, i = null, p = null) {
    this.variableNames = ["A", "B"], this.uniforms = "dimAOuter : i32, dimBOuter : i32, dimInner : i32,", this.workgroupSize = [16, 8, 1], this.outputShape = o, this.dispatchLayout = { x: [2], y: [1], z: [0] }, this.dispatch = [Math.ceil(o[2] / this.workgroupSize[0]), Math.ceil(o[1] / this.workgroupSize[1]), o[0]];
    let u = a != null;
    u && this.variableNames.push("bias");
    let c = p != null;
    c && this.variableNames.push("preluActivationWeights"), this.transposeA = n, this.transposeB = s, this.addBias = u, this.activation = i, this.hasPreluActivationWeights = c, this.shaderKey = `matMulSmallOutputSize_${this.activation}_${n}_${s}`;
  }
  getUserCode() {
    return `
      ${dr(this.activation, this.hasPreluActivationWeights)}
      ${hm(this.addBias, this.activation, this.transposeA, this.transposeB)}
      ${Xie(this.workgroupSize)}
    `;
  }
};
var Zg = class {
  constructor(e, t10, o = false, n = false) {
    this.variableNames = ["A", "B"], this.uniforms = "dimAOuter : i32, dimBOuter : i32, dimInner : i32,", this.workgroupSize = [8, 8, 1], this.atomic = true, this.splitedDimInner = 128, y.assert(e[0] === 1, () => "MatMulSplitKProgram only supports batch = 1."), this.outputShape = e, this.dispatchLayout = { x: [2], y: [1], z: [0, 3] };
    let s = (o && this.outputShape[1] % 4 === 0 || !o && t10 % 4 === 0) && this.outputShape[2] % 4 === 0;
    this.elementsPerThread = [4, 4, this.splitedDimInner], this.outputComponent = s ? 4 : 1, s || (this.outputShape[1] < 16 && (this.elementsPerThread[1] = 1), this.outputShape[2] < 16 && (this.elementsPerThread[0] = 1)), this.dispatch = H(this.dispatchLayout, [this.outputShape[0], this.outputShape[1], this.outputShape[2], t10], this.workgroupSize, this.elementsPerThread), this.transposeA = o, this.transposeB = n, this.shaderKey = `matMulSplitK_${o}_${n}_${this.elementsPerThread}_${this.outputComponent}`;
  }
  getUserCode() {
    let e = this.outputComponent;
    return `
      ${Jv(false, this.transposeB, false, false, false, e)}
      fn mm_write(batch: i32, row : i32, col : i32, value : ${Ae(e)}) {
        if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) {
          let coords = vec3<i32>(batch, row, col);
          let flatIndex = getOutputIndexFromCoords(coords);
          // The problem is that we should initialize output to zero before using.
          // Otherwise, the original value will be added to the result.
          for (var i = 0; i < ${e}; i = i + 1) {
            ${Qr("&result[flatIndex + i]", `${e > 1 ? "value[i]" : "value"}`, "float32")}
          }
        }
      }
      ${e === 4 ? _p(this.elementsPerThread, this.workgroupSize, this.transposeA, 32, true, this.splitedDimInner) : Ep(this.elementsPerThread, this.workgroupSize, this.transposeA, 32, true, this.splitedDimInner)}
    `;
  }
};
var Jg = class {
  constructor(e, t10 = null, o = null, n = null) {
    this.uniforms = "", this.variableNames = ["x"], this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.addBias = t10 != null, this.hasPreluActivationWeights = n != null, this.activation = o, this.addBias && this.variableNames.push("bias"), this.hasPreluActivationWeights && this.variableNames.push("preluActivationWeights"), this.shaderKey = `biasActivation_${o}`;
  }
  getUserCode() {
    return `
    ${dr(this.activation, this.hasPreluActivationWeights)}
    ${G("index")} {
      if (index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
        var value = getXByOutputIndex(index);
        ${Zr(this.addBias, this.activation)}
        setOutputAtIndex(index, value);
      }
    }
    `;
  }
};
var ex = class {
  constructor(e) {
    this.variableNames = [], this.outputShape = [], this.uniforms = "value : f32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "fill";
  }
  getUserCode() {
    return `
    ${G("index")} {
      if (index < uniforms.size) {
        setOutputAtIndex(index, uniforms.value);
      }
    }
  `;
  }
};
function vt(r15) {
  let { backend: e, attrs: t10 } = r15, { shape: o, value: n } = t10, { dtype: s } = t10;
  if (s = s || y.inferDtype(n), s === "string") {
    let a = y.getArrayFromDType(s, y.sizeFromShape(o));
    return a.fill(n), e.makeTensorInfo(o, s, a);
  } else {
    let a = new ex(o), i = [{ type: "float32", data: [n] }];
    return e.runWebGPUProgram(a, [], s, i);
  }
}
var iz = { kernelName: sa, backendName: "webgpu", kernelFunc: vt };
function pe(r15) {
  let { inputs: e, attrs: t10 } = r15, { x: o } = e, { shape: n } = t10, s = y.sizeFromShape(o.shape), a = y.inferFromImplicitShape(n, s), i = y.sizeFromShape(a);
  return y.assert(s === i, () => `The new shape (${a}) has ${i} elements and the old shape (${o.shape}) has ${s} elements. The new shape and old shape must have the same number of elements.`), r15.backend.incRef(o.dataId), { dataId: o.dataId, shape: a, dtype: o.dtype };
}
var uz = { kernelName: da, backendName: "webgpu", kernelFunc: pe };
function $p({ a: r15, b: e, transposeA: t10, transposeB: o, backend: n, bias: s = null, preluActivationWeights: a = null, leakyreluAlpha: i = 0, activation: p = null }) {
  let u = r15.shape.length, c = e.shape.length, l = t10 ? r15.shape[u - 2] : r15.shape[u - 1], m = o ? e.shape[c - 1] : e.shape[c - 2], d = t10 ? r15.shape[u - 1] : r15.shape[u - 2], f = o ? e.shape[c - 2] : e.shape[c - 1], h = r15.shape.slice(0, -2), g = e.shape.slice(0, -2), x = y.sizeFromShape(h), b = y.sizeFromShape(g), S = Sr.assertAndGetBroadcastShape(r15.shape.slice(0, -2), e.shape.slice(0, -2)).concat([d, f]);
  y.assert(l === m, () => `Error in matMul: inner shapes (${l}) and (${m}) of Tensors with shapes ${r15.shape} and ${e.shape} and transposeA=${t10} and transposeB=${o} must match.`);
  let k = t10 ? [x, l, d] : [x, d, l], _ = o ? [b, f, m] : [b, m, f], $ = pe({ inputs: { x: r15 }, backend: n, attrs: { shape: k } }), R = pe({ inputs: { x: e }, backend: n, attrs: { shape: _ } }), D = [$, R], P = Math.max(x, b), O = [$, R], M = [{ type: "int32", data: [d] }, { type: "int32", data: [f] }, { type: "int32", data: [l] }], L, B, z = [P, d, f], U = A().get("WEBGPU_MATMUL_PROGRAM_TYPE");
  if (U < 0) {
    let q = A().getNumber("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL"), Y = q > 0 ? q : n.thresholdToIncreaseWorkgroups, J = P * Math.ceil(d / 32) * Math.ceil(f / 32);
    J <= Y || d <= 8 && J <= Y * 2 ? P * d * f <= 128 ? U = Mo.MatMulReduceProgram : P === 1 && m >= 2e3 ? U = Mo.MatMulSplitKProgram : U = Mo.MatMulSmallOutputSizeProgram : U = Mo.MatMulPackedProgram;
  }
  switch (U) {
    case Mo.MatMulReduceProgram:
      L = new Yg(z, t10, o, s, p, a);
      break;
    case Mo.MatMulSplitKProgram: {
      if (B = vt({ backend: n, attrs: { shape: z, value: 0, dtype: r15.dtype } }), L = new Zg(z, m, t10, o), s || p) {
        B = n.runWebGPUProgram(L, O, r15.dtype, M, B);
        let Y = new Jg(B.shape, s, p, a), J = null, re = [B];
        s && re.push(s), a && re.push(a), p === "leakyrelu" && (J = [{ type: "float32", data: [i] }], Y.uniforms += " alpha : f32,");
        let ne = n.runWebGPUProgram(Y, re, B.dtype, J);
        D.push(B);
        let ee = pe({ inputs: { x: ne }, backend: n, attrs: { shape: S } });
        D.push(ne);
        for (let oe of D) n.disposeData(oe.dataId);
        return ee;
      }
      break;
    }
    case Mo.MatMulSmallOutputSizeProgram:
      L = new Qg(k, _, z, t10, o, s, p, a);
      break;
    case Mo.MatMulPackedProgram:
      let q = n.adapterInfo.isIntel();
      L = new Xg(k, z, t10, o, s, p, a, q);
      break;
    default:
      throw new Error(`Unsupported MatMulProgramType ${U}.`);
  }
  s && O.push(s), a && O.push(a), p === "leakyrelu" && (M.push({ type: "float32", data: [i] }), L.uniforms += " alpha : f32,"), B = n.runWebGPUProgram(L, O, r15.dtype, M, B);
  let j = pe({ inputs: { x: B }, backend: n, attrs: { shape: S } });
  D.push(B);
  for (let q of D) n.disposeData(q.dataId);
  return j;
}
function Yie(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { a: n, b: s, bias: a, preluActivationWeights: i } = e, { transposeA: p, transposeB: u, activation: c, leakyreluAlpha: l } = o;
  return $p({ a: n, b: s, transposeA: p, transposeB: u, backend: t10, bias: a, preluActivationWeights: i, leakyreluAlpha: l, activation: c });
}
var pz = { kernelName: So, backendName: "webgpu", kernelFunc: Yie };
var gm = class {
  constructor(e, t10, o) {
    this.variableNames = ["AReal", "AImag", "BReal", "BImag"], this.workgroupSize = [128, 1, 1], this.size = true, this.outputShape = w.assertAndGetBroadcastShape(t10, o), this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = `binaryOpComplex_${e}`, this.op = e;
  }
  getUserCode() {
    return `
      fn binaryOpComplex(
          areal : f32, aimag : f32, breal : f32, bimag : f32) -> f32 {
        ${Xc(this.op, false)}
      }

      ${G("index")} {
        if(index < uniforms.size) {
          let areal = getARealByOutputIndex(index);
          let aimag = getAImagByOutputIndex(index);
          let breal = getBRealByOutputIndex(index);
          let bimag = getBImagByOutputIndex(index);
          setOutputAtIndex(index, binaryOpComplex(areal, aimag, breal, bimag));
        }
      }
    `;
  }
};
var Ii = class {
  constructor(e, t10, o) {
    if (this.size = true, this.variableNames = ["A", "B"], this.outputShape = w.assertAndGetBroadcastShape(t10, o), this.dispatchLayout = X(this.outputShape), this.op = e, this.useSharedMemoryWithA = t10.length <= 1 && o.length > 1 && t10[0] < 128, this.useSharedMemoryWithB = o.length <= 1 && t10.length > 1 && o[0] < 128, this.useSharedMemoryWithA || this.useSharedMemoryWithB) this.outputComponent = 1, this.variableComponents = [1, 1], this.lastDimensionSize = this.useSharedMemoryWithB ? o[0] : t10[0], this.shaderKey = `binary_${e}_${this.lastDimensionSize}`, this.type = "shared", this.workgroupSize = [256, 1, 1];
    else {
      let n = t10.length > 0 && t10[t10.length - 1] % 4 === 0, s = o.length > 0 && o[o.length - 1] % 4 === 0;
      n && s ? (this.outputComponent = 4, this.variableComponents = [4, 4]) : n && (y.isScalarShape(o) || o[o.length - 1] === 1) || s && (y.isScalarShape(t10) || t10[t10.length - 1] === 1) ? (this.outputComponent = 4, this.variableComponents = n ? [4, 1] : [1, 4]) : (this.outputComponent = 1, this.variableComponents = [1, 1]), this.type = "nonshared", this.shaderKey = `binary_${e}_${this.variableComponents}`, this.workgroupSize = [128, 1, 1];
    }
    this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize, [this.outputComponent, 1, 1]);
  }
  getUserCode() {
    let e, t10 = this.outputComponent === 4 ? "vec4<f32>" : "f32", o = `
    fn binaryOperation(a : ${t10}, b : ${t10}) -> ${t10} {
      ${Xc(this.op, this.outputComponent === 4)}
    };
    `;
    if (this.type === "shared") {
      let n = this.lastDimensionSize > 1 ? `coords[${this.outputShape.length - 1}]` : "0", s = this.useSharedMemoryWithB ? `let a = getAByOutputIndex(index);
          let b = sharedBuf[${n}];` : `let a = sharedBuf[${n}];
          let b = getBByOutputIndex(index);`;
      e = `
        ${o}
        var<workgroup> sharedBuf : array<f32, ${this.lastDimensionSize}>;
        ${G("index")} {
          // Fill in the shared memory buffer.
          let localIndex = i32(localId.x);
          if(localIndex < ${this.lastDimensionSize}) {
            sharedBuf[localIndex] = f32(${this.useSharedMemoryWithB ? "B" : "A"}[localIndex]);
          }
          workgroupBarrier();

          if(index < uniforms.size) {
            let coords = getCoordsFromIndex(index);
            ${s}
            setOutputAtIndex(index, binaryOperation(a, b));
          }
        }
        `;
    } else e = `
       ${o}
       ${G("index")} {
         if (index < uniforms.size) {
           let coords = getCoordsFromIndex(index * ${this.outputComponent});
           let a = ${t10}(getAByOutputCoords(coords));
           let b = ${t10}(getBByOutputCoords(coords));
           setOutputAtIndex(index, binaryOperation(a, b));
         }
       }
       `;
    return e;
  }
};
function At(r15) {
  let { inputs: e } = r15, { x: t10 } = e;
  return r15.backend.incRef(t10.dataId), { dataId: t10.dataId, shape: t10.shape, dtype: t10.dtype };
}
var cz = { kernelName: Co, backendName: "webgpu", kernelFunc: At };
function xo(r15) {
  let { inputs: e, backend: t10 } = r15, { real: o, imag: n } = e, s = t10.makeTensorInfo(o.shape, "complex64"), a = t10.tensorMap.get(s.dataId), i = At({ inputs: { x: o }, backend: t10 }), p = At({ inputs: { x: n }, backend: t10 });
  return a.complexTensorInfos = { real: i, imag: p }, s;
}
var lz = { kernelName: Di, backendName: "webgpu", kernelFunc: xo };
var Jr = class {
  constructor(e, t10, o = "") {
    this.variableNames = ["A"], this.size = true;
    let n = 128;
    this.workgroupSize = [n, 1, 1], this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.op = t10, o !== "" && (this.uniforms = o), this.shaderKey = `unary_${t10}`;
  }
  getUserCode() {
    return `
      fn unaryOperation(a : f32) -> f32 {
        ${Si(this.op, false)}
      }
      ${G("index")} {
        if (index < uniforms.size) {
          let a = getAByOutputIndex(index);
          setOutputAtIndex(index, unaryOperation(a));
        }
      }
      `;
  }
};
function ye({ opType: r15, cpuKernelImpl: e, dtype: t10 }) {
  return ({ inputs: o, backend: n }) => {
    let { x: s } = o, a = n, i = t10 || s.dtype;
    if (a.shouldExecuteOnCPU([s]) && e != null) {
      let u = a.tensorMap.get(s.dataId), c = e(u.values, i);
      return a.makeTensorInfo(s.shape, i, c);
    }
    let p = new Jr(s.shape, r15);
    return a.runWebGPUProgram(p, [s], i);
  };
}
function et({ opType: r15, cpuKernelImpl: e, supportsComplex: t10 = false, dtype: o }) {
  return ({ inputs: n, backend: s }) => {
    let { a, b: i } = n, p = s;
    if (t10 && a.dtype === "complex64") {
      let l = p.tensorMap.get(a.dataId), m = p.tensorMap.get(i.dataId), d, f;
      if (r15 !== fe.MUL) [d, f] = [[l.complexTensorInfos.real, m.complexTensorInfos.real], [l.complexTensorInfos.imag, m.complexTensorInfos.imag]].map((g) => {
        let [x, b] = g, C = { dataId: x.dataId, dtype: x.dtype, shape: a.shape }, S = { dataId: b.dataId, dtype: b.dtype, shape: i.shape }, k = new Ii(r15, a.shape, i.shape);
        return p.runWebGPUProgram(k, [C, S], dt(x.dtype, b.dtype));
      });
      else {
        let g = new gm(fe.COMPLEX_MULTIPLY_REAL, a.shape, i.shape), x = new gm(fe.COMPLEX_MULTIPLY_IMAG, a.shape, i.shape), b = [{ dataId: l.complexTensorInfos.real.dataId, dtype: l.complexTensorInfos.real.dtype, shape: a.shape }, { dataId: l.complexTensorInfos.imag.dataId, dtype: l.complexTensorInfos.imag.dtype, shape: a.shape }, { dataId: m.complexTensorInfos.real.dataId, dtype: m.complexTensorInfos.real.dtype, shape: i.shape }, { dataId: m.complexTensorInfos.imag.dataId, dtype: m.complexTensorInfos.imag.dtype, shape: i.shape }];
        d = p.runWebGPUProgram(g, b, "float32"), f = p.runWebGPUProgram(x, b, "float32");
      }
      let h = xo({ inputs: { real: d, imag: f }, backend: p });
      return p.disposeData(d.dataId), p.disposeData(f.dataId), h;
    }
    let u = o || dt(a.dtype, i.dtype);
    if ((a.dtype === "string" || i.dtype === "string" || p.shouldExecuteOnCPU([a, i])) && e != null) {
      let l = p.tensorMap.get(a.dataId).values, m = p.tensorMap.get(i.dataId).values, d = a.dtype === "string" ? w.fromUint8ToStringArray(l) : l, f = a.dtype === "string" ? w.fromUint8ToStringArray(m) : m, [h, g] = e(a.shape, i.shape, d, f, u);
      return p.makeTensorInfo(g, u, h);
    }
    let c = new Ii(r15, a.shape, i.shape);
    return p.runWebGPUProgram(c, [a, i], u);
  };
}
var { addImpl: mz, castImpl: dz, ceilImpl: fz, concatImpl: hz, equalImpl: gz, expImpl: xz, expm1Impl: yz, floorImpl: bz, floorDivImpl: Cz, gatherNdImpl: wz, gatherV2Impl: Sz, greaterEqualImpl: Iz, greaterImpl: vz, lessEqualImpl: kz, lessImpl: Nz, logImpl: Tz, maxImpl: _z, maximumImpl: Ez, minimumImpl: $z, multiplyImpl: Rz, negImpl: Dz, notEqualImpl: Az, prodImpl: Fz, rangeImpl: Pz, rsqrtImpl: Oz, scatterImpl: Mz, simpleAbsImpl: Lz, sliceImpl: Bz, stridedSliceImpl: zz, stringNGramsImpl: Vz, subImpl: Wz, tileImpl: Uz, topKImpl: Gz, transposeImpl: Hz, uniqueImpl: rOt } = Ic;
var Qie = ye({ opType: Z.ABS, cpuKernelImpl: Lz });
var Kz = { kernelName: "Abs", backendName: "webgpu", kernelFunc: Qie };
var Zie = ye({ opType: Z.ACOS });
var qz = { kernelName: Vo, backendName: "webgpu", kernelFunc: Zie };
var Jie = ye({ opType: Z.ACOSH });
var jz = { kernelName: Wo, backendName: "webgpu", kernelFunc: Jie };
var eue = et({ opType: fe.ADD, cpuKernelImpl: mz, supportsComplex: true });
var Xz = { kernelName: "Add", backendName: "webgpu", kernelFunc: eue };
var tx = class {
  constructor(e) {
    this.workPerThread = 1, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e[0], this.variableNames = e.map((t10, o) => `T${o}`), this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize, [this.workPerThread, 1, 1]), this.shaderKey = "addN";
  }
  getUserCode() {
    let e = [];
    this.variableNames.forEach((n) => {
      e.push(`let v${n} = get${n}ByOutputCoords(coords);`);
    });
    let t10 = this.variableNames.map((n) => `v${n}`).join(" + ");
    return `
      ${G("index")} {
        for (var i = 0; i < ${this.workPerThread}; i = i + 1) {
          let flatIndex = index * ${this.workPerThread} + i;
          if (flatIndex < uniforms.size) {
            let coords = getCoordsFromIndex(flatIndex);
            ${e.join(`
        `)}
            setOutputAtIndex(flatIndex, ${t10});
          }
        }
      }
    `;
  }
};
function tue(r15) {
  let { inputs: e, backend: t10 } = r15, o = e;
  if (o.length === 1) return At({ inputs: { x: o[0] }, backend: t10 });
  let n = o.map((i) => i.dtype).reduce((i, p) => dt(i, p)), s = o.map((i) => i.shape), a = new tx(s);
  return t10.runWebGPUProgram(a, o, n);
}
var Yz = { kernelName: Uo, backendName: "webgpu", kernelFunc: tue };
var rx = class {
  constructor(e, t10) {
    this.variableNames = ["A"], this.workgroupSize = [16, 16, 1];
    let o = new Array(e.length);
    for (let n = 0; n < o.length; n++) o[n] = e[t10[n]];
    this.outputShape = o, this.dispatchLayout = { x: [0], y: [1] }, this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize, [1, 1, 1]), this.shaderKey = "transposeShared";
  }
  getUserCode() {
    y.assert(this.workgroupSize[0] === this.workgroupSize[1], () => `Must be a square tile, current tile shape is ${this.workgroupSize[0]} x ${this.workgroupSize[1]}`);
    let e = this.workgroupSize[0];
    return `
      var<workgroup> tile : array<array<f32, ${this.workgroupSize[0] + 1}>, ${this.workgroupSize[0]}>;
      ${G()} {
        var x = i32(workgroupId.x) * ${e} + i32(localId.x);
        var y = i32(workgroupId.y) * ${e} + i32(localId.y);
        let width = uniforms.outShape[0];
        let height = uniforms.outShape[1];
        if (x < width && y < height) {
          tile[localId.y][localId.x] = f32(A[y * width + x]);
        }
        workgroupBarrier();

        x = i32(workgroupId.y) * ${e} + i32(localId.x);
        y = i32(workgroupId.x) * ${e} + i32(localId.y);
        if (x < height && y < width) {
          setOutputAtIndex((y * height + x), tile[localId.x]
            [localId.y]);
        }
      }
    `;
  }
};
var ox = class {
  constructor(e, t10) {
    this.variableNames = ["A"], this.workPerThread = 1, this.workgroupSize = [64, 1, 1], this.size = true;
    let o = new Array(e.length);
    for (let n = 0; n < o.length; n++) o[n] = e[t10[n]];
    this.outputShape = o, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize, [this.workPerThread, 1, 1]), this.newDim = t10, this.shaderKey = `transpose_${t10}`;
  }
  getUserCode() {
    let e = ft(this.outputShape.length), t10 = e0(this.newDim);
    return `
      ${G("index")} {
        for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
          let flatIndex = index * ${this.workPerThread} + i;
          if(flatIndex < uniforms.size) {
            let coords = getCoordsFromIndex(flatIndex);
            setOutputAtIndex(flatIndex, A[getIndexFromCoords${this.outputShape.length}D(
              ${e}(${t10}), uniforms.aShape)]);
          }
        }
      }
    `;
  }
};
function e0(r15) {
  let e = r15.length;
  if (e > 6) throw Error(`Transpose for rank ${e} is not yet supported`);
  let t10 = new Array(e);
  for (let o = 0; o < r15.length; o++) t10[r15[o]] = `coords.${Oo(o)}`;
  return t10.join();
}
function xr(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { perm: s } = o, a = t10, i = n.shape.length, p = new Array(i);
  for (let c = 0; c < p.length; c++) p[c] = n.shape[s[c]];
  if (t10.shouldExecuteOnCPU([n])) {
    let l = a.tensorMap.get(n.dataId).values, m = Hz(l, n.shape, n.dtype, s, p);
    return t10.makeTensorInfo(p, n.dtype, m);
  }
  if (n.shape.length === 2 && y.arraysEqual(s, [1, 0])) {
    let c = new rx(n.shape, s);
    return a.runWebGPUProgram(c, [n], n.dtype);
  }
  let u = new ox(n.shape, s);
  return a.runWebGPUProgram(u, [n], n.dtype);
}
var Qz = { kernelName: co, backendName: "webgpu", kernelFunc: xr };
var nx = class {
  constructor(e, t10, o) {
    this.variableNames = ["x"], this.uniforms = "reduceSize : i32,", this.size = true, this.inputShape = [e.batchSize, e.inSize];
    let [n] = w.computeOutAndReduceShapes(this.inputShape, [1]);
    this.outputShape = n.length === 0 ? [1] : n, e.inSize >= 32768 && o >= 512 ? this.workgroupSize = [512, 1, 1] : e.inSize >= 4096 ? this.workgroupSize = [256, 1, 1] : this.workgroupSize = [64, 1, 1], this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, [1, 1, 1]), this.reduceType = t10, this.shaderKey = `reduce_${t10}`;
  }
  getUserCode() {
    let e = "", t10 = "0.0", o = this.workgroupSize[0];
    this.reduceType === "min" || this.reduceType === "max" ? (e = `
         if (isnan(candidate)) {
          bestValue = uniforms.NAN;
         } else if (!isnan(bestValue) && candidate ${this.reduceType === "min" ? "<" : ">"} bestValue)
           {  bestValue = candidate; }`, t10 = "f32(x[offset])") : this.reduceType === "sum" || this.reduceType === "mean" ? e = " bestValue = bestValue + candidate; " : this.reduceType === "prod" ? (e = " bestValue = bestValue * candidate; ", t10 = "1.0") : this.reduceType === "all" ? (e = " bestValue = f32(bestValue >= 1.0 && candidate >= 1.0); ", t10 = "1.0") : this.reduceType === "any" && (e = " bestValue = f32(bestValue >= 1.0 || candidate >= 1.0); ", t10 = "0.0");
    let n = this.reduceType === "mean" ? "setOutputAtIndex(outputIndex, bestValue / f32(uniforms.reduceSize));" : "setOutputAtIndex(outputIndex, bestValue);";
    return `
       fn DIV_CEIL(a : u32, b : u32) -> u32 {
        return ((a - 1u) / b + 1u);
       }

       ${`
         var<workgroup> xBestValues : array<f32, ${o}>;
       `}
       fn getOffset(outputIndex : i32) -> i32 {
         let outputCoords = getCoordsFromIndex(outputIndex);
         let offset = ${this.outputShape.length === 1 ? "outputCoords" : "outputCoords[0]"} * uniforms.reduceSize;
          return offset;
       }
       ${G("index")} {
         let outputIndex = index / ${o};
         let offset = getOffset(outputIndex);
         var bestValue = ${t10};
         let Length = uniforms.reduceSize;
         let WorkPerThread = DIV_CEIL(u32(Length), ${o}u);
         for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size;
             k = k + ${o}) {
           let candidate = f32(x[offset + k]);
           ${e}
         }
         xBestValues[localId.x] = bestValue;
         workgroupBarrier();

         var reduceSize = min(u32(Length), ${o}u);
         for (var currentSize = reduceSize / 2u; reduceSize > 1u;
             currentSize = reduceSize / 2u) {
           let interval = DIV_CEIL(reduceSize, 2u);
           if (localId.x < currentSize) {
            let candidate = xBestValues[localId.x + interval];
            ${e}
            xBestValues[localId.x] = bestValue;
           }
           reduceSize = interval;
           workgroupBarrier();
         }

         if (localId.x == 0u && outputIndex < uniforms.size) {
          ${n}
        }
       }
     `;
  }
};
var rue = { mean: "float32", all: "bool", any: "bool" };
function eo(r15, e, t10, o, n) {
  let s = r15.shape.length, a = [], i = y.parseAxisParam(e, r15.shape), p = i, u = w.getAxesPermutation(p, s), c = r15;
  u != null && (c = xr({ inputs: { x: r15 }, attrs: { perm: u }, backend: n }), p = w.getInnerMostAxes(p.length, s), a.push(c)), w.assertAxesAreInnerMostDims(o, p, s);
  let [l, m] = w.computeOutAndReduceShapes(c.shape, p), d = l;
  t10 && (d = w.expandShapeToKeepDim(l, i));
  let f;
  if ((o === "max" || o === "prod") && n.shouldExecuteOnCPU([c])) {
    let h = n.tensorMap.get(c.dataId).values;
    switch (o) {
      case "max":
        let g = _z(h, y.sizeFromShape(m), d, r15.dtype);
        f = n.makeTensorInfo(d, r15.dtype, g);
        break;
      case "prod":
        let { outVals: x, outShape: b, outDtype: C } = Fz(c.shape, c.dtype, h, p);
        f = n.makeTensorInfo(b, C, x);
        break;
      default:
        throw new Error(`${o} CPU implementation is not yet supported.`);
    }
  } else {
    let h = y.sizeFromShape(m), x = y.sizeFromShape(c.shape) / h, b = { windowSize: h, inSize: h, batchSize: x, outSize: 1 }, C = rue[o] || oi(r15.dtype), S = [{ type: "int32", data: [h] }], k = new nx(b, o, n.device.limits.maxComputeWorkgroupSizeX), _ = n.runWebGPUProgram(k, [c], C, S);
    a.push(_), f = pe({ inputs: { x: _ }, attrs: { shape: d }, backend: n });
  }
  return a.forEach((h) => n.disposeData(h.dataId)), f;
}
function oue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { keepDims: s, axis: a } = o;
  return eo(n, a, s, "all", t10);
}
var Zz = { kernelName: "All", backendName: "webgpu", kernelFunc: oue };
function nue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { keepDims: s, axis: a } = o;
  return eo(n, a, s, "any", t10);
}
var Jz = { kernelName: "Any", backendName: "webgpu", kernelFunc: nue };
var Yc = class {
  constructor(e, t10, o) {
    this.workgroupSize = [64, 1, 1], this.variableNames = ["x"], this.uniforms = "infinityValue : f32,", this.size = true;
    let n = [t10];
    this.op = o === "min" ? "<" : ">";
    let [s, a] = w.computeOutAndReduceShapes(e, n);
    this.outputShape = s.length === 0 ? [1] : s, this.dispatchLayout = X(this.outputShape), y.sizeFromShape(a) < 32 ? (this.type = "plain", this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize)) : (this.type = "shared", this.dispatch = H(this.dispatchLayout, this.outputShape, [1, 1, 1])), this.inputShape = e, this.shaderKey = `argMinMax_${this.op}_${this.type}`;
  }
  getUserCode() {
    let e = this.workgroupSize[0], t10 = () => this.inputShape.length === 1 ? "uniforms.xShape" : `uniforms.xShape.${Oo(this.inputShape.length - 1)}`, o = () => {
      let n = "";
      if (this.outputShape.length === 1) this.inputShape.length !== 1 && (n += "outputCoords,");
      else for (let s = 0; s < this.outputShape.length; s++) n += `outputCoords.${Oo(s)},`;
      return n;
    };
    return this.type === "shared" ? `
      fn DIV_CEIL(a : u32, b : u32) -> u32 {
        return ((a - 1u) / b + 1u);
      }

      ${`
      var<workgroup> xBestIndices : array<i32, ${e}>;
      var<workgroup> xBestValues : array<f32, ${e}>;
    `}

      ${G("index")} {
        let outputIndex = index / ${e};
        let reduceLength = ${t10()};

        var bestIndex = i32(localId.x);
        var bestValue = uniforms.infinityValue;
        let outputCoords = getCoordsFromIndex(outputIndex);
        for (var k = i32(localId.x); k < reduceLength && outputIndex < uniforms.size;
            k = k + ${e}) {
          let candidate = getX(${o()} k);
          if (!isnan(candidate) && candidate ${this.op} bestValue) {
            bestValue = candidate;
            bestIndex = k;
          }
        }
        xBestValues[localId.x] = bestValue;
        xBestIndices[localId.x] = bestIndex;
        workgroupBarrier();

        var reduceSize = min(u32(reduceLength), ${e}u);
        for (var currentSize = reduceSize / 2u; reduceSize > 1u;
            currentSize = reduceSize / 2u) {
          let interval = DIV_CEIL(reduceSize, 2u);
          if (localId.x < currentSize) {
            let candidate = xBestValues[localId.x + interval];
            if (candidate ${this.op} bestValue) {
              bestValue = candidate;
              xBestValues[localId.x] = bestValue;
              xBestIndices[localId.x] = xBestIndices[localId.x + interval];
            }
          }
          reduceSize = interval;
          workgroupBarrier();
        }

        if (localId.x == 0u && outputIndex < uniforms.size) {
          setOutputAtIndexI32(outputIndex, xBestIndices[localId.x]);
        }
      }
    ` : `
      ${G("index")} {
        if (index < uniforms.size) {
          let outputCoords = getCoordsFromIndex(index);
          var bestIndex = 0;
          var bestValue = getX(${o()} 0);
          let reduceLength = ${t10()};
          for (var i = 1; i < reduceLength; i++) {
            let candidate = getX(${o()} i);
            if (candidate ${this.op} bestValue) {
              bestValue = candidate;
              bestIndex = i;
            }
          }
          setOutputAtIndexI32(index, bestIndex);
        }
      }
      `;
  }
};
function sue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s } = o, a = y.parseAxisParam(s, n.shape), i = w.getAxesPermutation(a, n.shape.length), p = n, u = [];
  i != null && (p = xr({ inputs: { x: n }, backend: t10, attrs: { perm: i } }), u.push(p), a = w.getInnerMostAxes(a.length, p.shape.length)), w.assertAxesAreInnerMostDims("argMax", [a[0]], p.shape.length);
  let c = new Yc(p.shape, a[0], "max"), l = [{ type: "float32", data: [Number.NEGATIVE_INFINITY] }], m = t10.runWebGPUProgram(c, [p], "int32", l);
  return u.forEach((d) => t10.disposeData(d.dataId)), m;
}
var eV = { kernelName: Ys, backendName: "webgpu", kernelFunc: sue };
function aue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s } = o, a = y.parseAxisParam(s, n.shape), i = w.getAxesPermutation(a, n.shape.length), p = n, u = [];
  i != null && (p = xr({ inputs: { x: n }, backend: t10, attrs: { perm: i } }), u.push(p), a = w.getInnerMostAxes(a.length, p.shape.length)), w.assertAxesAreInnerMostDims("argMin", [a[0]], p.shape.length);
  let c = new Yc(p.shape, a[0], "min"), l = [{ type: "float32", data: [Number.POSITIVE_INFINITY] }], m = t10.runWebGPUProgram(c, [p], "int32", l);
  return u.forEach((d) => t10.disposeData(d.dataId)), m;
}
var tV = { kernelName: Qs, backendName: "webgpu", kernelFunc: aue };
var iue = ye({ opType: Z.ASIN });
var rV = { kernelName: Ko, backendName: "webgpu", kernelFunc: iue };
var uue = ye({ opType: Z.ASINH });
var oV = { kernelName: qo, backendName: "webgpu", kernelFunc: uue };
var pue = ye({ opType: Z.ATAN });
var nV = { kernelName: jo, backendName: "webgpu", kernelFunc: pue };
var cue = et({ opType: fe.ATAN2 });
var sV = { kernelName: Yo, backendName: "webgpu", kernelFunc: cue };
var lue = ye({ opType: Z.ATANH });
var aV = { kernelName: Xo, backendName: "webgpu", kernelFunc: lue };
var sx = class {
  constructor(e) {
    this.variableNames = ["x"], this.uniforms = "strides : vec2<i32>,", this.workgroupSize = [256, 1, 1], this.size = true, this.outputShape = e.outShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "poolWithFilterSizeEqualsOne";
  }
  getUserCode() {
    return `
      ${G("index")} {
        if (index < uniforms.size) {
          let coords = getCoordsFromIndex(index);
          let batch = coords[0];
          let d = coords[3];

          let xRCCorner = coords.yz * uniforms.strides;
          let xRCorner = xRCCorner.x;
          let xCCorner = xRCCorner.y;

          let value = getX(batch, xRCorner, xCCorner, d);
          setOutputAtIndex(index, value);
        }
      }
    `;
  }
};
var Ba = class {
  constructor(e, t10, o = false, n = false, s = false) {
    if (this.variableNames = ["x"], this.uniforms = "strides : vec2<i32>, pads : vec2<i32>, dilations : vec2<i32>, convDims : vec2<i32>, filterDims : vec2<i32>,", this.workgroupSize = [128, 1, 1], this.size = true, t10 === "avg" && o) throw new Error("Cannot compute positions for average pool.");
    this.outputShape = e.outShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.poolType = t10, this.computePositions = o, this.flattenPositions = n, this.includeBatchIndex = s, this.shaderKey = `pool2D_${t10}_${o}_${n}_${s}`;
  }
  getUserCode() {
    let e;
    this.poolType === "avg" ? e = "resultValue = resultValue + value; count = count + 1.0;" : this.computePositions ? e = `let currMaxValue = mix(value, maxValue, maxValueFound);
      if (value >= currMaxValue) {
        maxValue = value;
        maxValueFound = 1.0;
        maxPosition = ${this.flattenPositions ? this.includeBatchIndex ? "((batch * uniforms.xShape[1] + xR) * uniforms.xShape[2] + xC) * uniforms.xShape[3] + d" : "(xR * uniforms.xShape[2] + xC) * uniforms.xShape[3] + d" : "wR * uniforms.filterDims.y + wC"};
      }` : e = "resultValue = max(value, resultValue);";
    let t10 = "resultValue";
    return this.poolType === "avg" && (t10 = "resultValue / max(count, 1.0)"), `
      ${G("index")} {
      if (index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
          let batch = coords[0];
          let d = coords[3];
          let xRCCorner = vec2<i32>(coords.yz) * uniforms.strides - uniforms.pads;
          let xRCorner = xRCCorner.x;
          let xCCorner = xRCCorner.y;

          ${this.computePositions ? `var maxValue = 0.0;
            var maxValueFound = 0.0;
            var maxPosition = 0;` : `var resultValue = ${this.poolType === "avg" ? "0.0" : "-1.0 / pow(10.0, -20.0)"};`}

          var count = 0.0;
          for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + uniforms.dilations.x) {
            let xR = xRCorner + wR;

            if (xR < 0 || xR >= uniforms.convDims.x) {
              continue;
            }

            for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + uniforms.dilations.y) {
              let xC = xCCorner + wC;
              if (xC < 0 || xC >= uniforms.convDims.y) {
                continue;
              }

              let value = getX(batch, xR, xC, d);
              ${e}
            }
          }

          ${this.computePositions ? "setOutputAtIndexI32(index, maxPosition);" : `setOutputAtIndex(index, ${t10});`}
        }
      }
    `;
  }
};
var Iu = class {
  constructor(e, t10, o = false, n = false, s = false) {
    if (this.variableNames = ["x"], this.uniforms = "strides : vec3<i32>, pads : vec3<i32>, convDims : vec3<i32>, filterDims : vec3<i32>,", this.workgroupSize = [128, 1, 1], this.size = true, t10 === "avg" && o) throw new Error("Cannot compute positions for average pool.");
    this.outputShape = e.outShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.poolType = t10, this.computePositions = o, this.flattenPositions = n, this.includeBatchIndex = s, this.shaderKey = `pool3D_${t10}_${o}_${n}_${s}`;
  }
  getUserCode() {
    let e;
    this.poolType === "avg" ? e = "resultValue += value; count += 1.0;" : this.computePositions ? e = `let currMaxValue = mix(value, maxValue, maxValueFound);
      if (value >= currMaxValue) {
        maxValue = value;
        maxValueFound = 1.0;
        maxPosition = ${this.flattenPositions ? this.includeBatchIndex ? "(((batch * uniforms.xShape.y + xD) * uniforms.xShape.z + xR) * uniforms.xShape.w + xC) * uniforms.xShape.u + ch" : "((xD * uniforms.xShape.z + xR) * uniforms.xShape.w + xC) * uniforms.xShape.u + ch" : "wD * uniforms.filterDims.y * uniforms.filterDims.y + wR * uniforms.filterDims.z + wC"};
      }` : e = "resultValue = max(value, resultValue);";
    let t10 = "resultValue";
    return this.poolType === "avg" && (t10 = "resultValue / max(count, 1.0)"), `
      ${G("index")} {
        if (index < uniforms.size) {
          let coords = getCoordsFromIndex(index);
          let batch = coords.x;
          let ch = coords.u;

          let xCorner = vec3<i32>(coords.y, coords.z, coords.w) * uniforms.strides - uniforms.pads;
          let xDCorner = xCorner.x;
          let xRCorner = xCorner.y;
          let xCCorner = xCorner.z;

          ${this.computePositions ? `var maxValue = 0.0;
            var maxValueFound = 0.0;
            var maxPosition = 0;` : `var resultValue = ${this.poolType === "avg" ? "0.0" : "-1.0 / pow(10.0, -20.0)"};`}

          var count = 0.0;
          for (var wD = 0; wD < uniforms.filterDims.x; wD++) {
            let xD = xDCorner + wD;
            if (xD < 0 || xD >= uniforms.convDims.x) {
              continue;
            }

            for (var wR = 0; wR < uniforms.filterDims.y; wR++) {
              let xR = xRCorner + wR;
              if (xR < 0 || xR >= uniforms.convDims.y) {
                continue;
              }

              for (var wC = 0; wC < uniforms.filterDims.z; wC++) {
                let xC = xCCorner + wC;
                if (xC < 0 || xC >= uniforms.convDims.z) {
                  continue;
                }

                let value = getX(batch, xD, xR, xC, ch);
                ${e}
              }
            }
          }

          ${this.computePositions ? "setOutputAtIndexI32(index, maxPosition);" : `setOutputAtIndex(index, ${t10});`}
        }
      }
    `;
  }
};
function t0(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { reductionIndices: s, keepDims: a } = o;
  return eo(n, s, a, "max", t10);
}
var iV = { kernelName: "Max", backendName: "webgpu", kernelFunc: t0 };
function r0(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { keepDims: s, axis: a } = o;
  return eo(n, a, s, "mean", t10);
}
var uV = { kernelName: Un, backendName: "webgpu", kernelFunc: r0 };
function ax(r15, e, t10, o) {
  if (e.filterWidth === 1 && e.filterHeight === 1 && y.arraysEqual(e.inShape, e.outShape)) return At({ inputs: { x: r15 }, backend: o });
  if (e.filterWidth === e.inWidth && e.filterHeight === e.inHeight && e.batchSize === 1 && e.padInfo.type === "VALID") {
    let a = r15.shape.length, i = pe({ inputs: { x: r15 }, backend: o, attrs: { shape: [r15.shape[a - 3] * r15.shape[a - 2], r15.shape[a - 1]] } }), p;
    t10 === "avg" ? p = r0({ inputs: { x: i }, backend: o, attrs: { axis: 0, keepDims: false } }) : (y.assert(t10 === "max", () => `Invalid pool type ${t10}`), p = t0({ inputs: { x: i }, backend: o, attrs: { reductionIndices: 0, keepDims: false } }));
    let u = pe({ inputs: { x: p }, backend: o, attrs: { shape: e.outShape } });
    return o.disposeData(i.dataId), o.disposeData(p.dataId), u;
  }
  let n, s = [{ type: "int32", data: [e.strideHeight, e.strideWidth] }];
  return e.filterHeight === 1 && e.filterWidth === 1 ? n = new sx(e) : (t10 === "avg" ? n = new Ba(e, "avg") : (y.assert(t10 === "max", () => `Invalid pool type ${t10}`), n = new Ba(e, "max")), s.push({ type: "int32", data: [e.padInfo.top, e.padInfo.left] }, { type: "int32", data: [e.dilationHeight, e.dilationWidth] }, { type: "int32", data: [e.inHeight, e.inWidth] }, { type: "int32", data: [e.effectiveFilterHeight, e.effectiveFilterWidth] })), o.runWebGPUProgram(n, [r15], r15.dtype, s);
}
function mue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { filterSize: s, strides: a, pad: i, dimRoundingMode: p } = o, c = w.computePool2DInfo(n.shape, s, a, 1, i, p);
  return ax(n, c, "avg", t10);
}
var pV = { kernelName: Qo, backendName: "webgpu", kernelFunc: mue };
function due(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { filterSize: s, strides: a, pad: i, dataFormat: p, dimRoundingMode: u } = o, c = [1, 1, 1], l = w.computePool3DInfo(n.shape, s, a, c, i, u, p), m = new Iu(l, "avg"), d = [{ type: "int32", data: [l.strideDepth, l.strideHeight, l.strideWidth] }, { type: "int32", data: [l.padInfo.front, l.padInfo.top, l.padInfo.left] }, { type: "int32", data: [l.inDepth, l.inHeight, l.inWidth] }, { type: "int32", data: [l.effectiveFilterDepth, l.effectiveFilterHeight, l.effectiveFilterWidth] }];
  return t10.runWebGPUProgram(m, [n], n.dtype, d);
}
var cV = { kernelName: Zs, backendName: "webgpu", kernelFunc: due };
var ix = class {
  constructor(e) {
    this.variableNames = ["dy"], this.uniforms = `strides : vec2<i32>, pads : vec2<i32>, dilations : vec2<i32>, filterDims : vec2<i32>,
       outHeight : i32, outWidth : i32, avgMultiplier : f32,`, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e.inShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "avgPool2DBackprop";
  }
  getUserCode() {
    return `
      ${G("index")} {
      if (index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
        let batch = coords[0];
        let d = coords[3];

        let dyRCCorner = vec2<i32>(coords.yz) - uniforms.pads;
        let dyRCorner = dyRCCorner.x;
        let 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.
        var dotProd = 0.0;
        for (var wR = 0; wR < uniforms.filterDims[0]; wR = wR + uniforms.dilations[0]) {
          let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]);

          if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
            continue;
          }
          let idyR = i32(dyR);

          for (var wC = 0; wC < uniforms.filterDims[1]; wC = wC + uniforms.dilations[1]) {
            let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]);

            if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
              continue;
            }
            let idyC = i32(dyC);

            let dyValue = getDy(batch, idyR, idyC, d);

            dotProd = dotProd + dyValue * uniforms.avgMultiplier;
          }
        }
        setOutputAtIndex(index, dotProd);
      }
    }
    `;
  }
};
var ux = class {
  constructor(e) {
    this.variableNames = ["dy"], this.uniforms = `strides : vec3<i32>, pads : vec3<i32>, filterDims : vec3<i32>,
       outDepth : i32, outHeight : i32, outWidth : i32, avgMultiplier : f32,`, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e.inShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "avgPool3DBackprop";
  }
  getUserCode() {
    return `
      ${G("index")} {
      if (index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
        let batch = coords.x;
        let ch = coords.u;

        let dyCorner = vec3<i32>(coords.y, coords.z, coords.w) - uniforms.pads;
        let dyDCorner = dyCorner.x;
        let dyRCorner = dyCorner.y;
        let 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.
        var dotProd = 0.0;
        for (var wD = 0; wD < uniforms.filterDims[0]; wD++) {
          let dyD = f32(dyDCorner + wD) / f32(uniforms.strides[0]);

          if (dyD < 0.0 || dyD >= f32(uniforms.outDepth) || fract(dyD) > 0.0) {
            continue;
          }
          let idyD = i32(dyD);

          for (var wR = 0; wR < uniforms.filterDims[1]; wR++) {
            let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]);

            if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
              continue;
            }
            let idyR = i32(dyR);

            for (var wC = 0; wC < uniforms.filterDims[2]; wC++) {
              let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]);

              if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
                continue;
              }
              let idyC = i32(dyC);

              let dyValue = getDy(batch, idyD, idyR, idyC, ch);
              dotProd += dyValue * uniforms.avgMultiplier;
            }
          }
        }
        setOutputAtIndex(index, dotProd);
      }
    }
    `;
  }
};
function fue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s } = e, a = s, { filterSize: i, strides: p, pad: u, dimRoundingMode: c } = o, l = w.computePool3DInfo(a.shape, i, p, 1, u, c), m = new ux(l), d = 1 / (l.filterDepth * l.filterHeight * l.filterWidth), f = [{ type: "int32", data: [l.strideDepth, l.strideHeight, l.strideWidth] }, { type: "int32", data: [l.effectiveFilterDepth - 1 - l.padInfo.front, l.effectiveFilterHeight - 1 - l.padInfo.top, l.effectiveFilterWidth - 1 - l.padInfo.left] }, { type: "int32", data: [l.effectiveFilterDepth, l.effectiveFilterHeight, l.effectiveFilterWidth] }, { type: "int32", data: [l.outDepth] }, { type: "int32", data: [l.outHeight] }, { type: "int32", data: [l.outWidth] }, { type: "float32", data: [d] }];
  return t10.runWebGPUProgram(m, [n], a.dtype, f);
}
var lV = { kernelName: Ri, backendName: "webgpu", kernelFunc: fue };
function hue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s } = e, a = s;
  fm([n, s], "avgPoolGrad");
  let { filterSize: i, strides: p, pad: u } = o, c = w.computePool2DInfo(a.shape, i, p, 1, u), l = new ix(c), m = 1 / (c.filterHeight * c.filterWidth), d = [{ type: "int32", data: [c.strideHeight, c.strideWidth] }, { type: "int32", data: [c.effectiveFilterHeight - 1 - c.padInfo.top, c.effectiveFilterWidth - 1 - c.padInfo.left] }, { type: "int32", data: [c.dilationHeight, c.dilationWidth] }, { type: "int32", data: [c.effectiveFilterHeight, c.effectiveFilterWidth] }, { type: "int32", data: [c.outHeight] }, { type: "int32", data: [c.outWidth] }, { type: "float32", data: [m] }];
  return t10.runWebGPUProgram(l, [n], a.dtype, d);
}
var mV = { kernelName: $i, backendName: "webgpu", kernelFunc: hue };
function gue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { a: n, b: s } = e, { transposeA: a, transposeB: i } = o;
  return $p({ a: n, b: s, transposeA: a, transposeB: i, backend: t10 });
}
var dV = { kernelName: Zo, backendName: "webgpu", kernelFunc: gue };
var px = class {
  constructor(e, t10) {
    this.variableNames = ["source"], this.workPerThread = 1, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = t10, this.rank = t10.length, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize, [this.workPerThread, 1, 1]), this.start = e, this.uniforms = `start : ${ft(e.length)}, `, this.shaderKey = "slice";
  }
  getUserCode() {
    let e = ft(this.rank), t10 = xue(this.rank), o;
    return this.start.length === 1 ? o = this.outputShape.map((s, a) => "sourceLoc = uniforms.start + coords;") : o = this.outputShape.map((s, a) => `sourceLoc.${o0[a]} = uniforms.start.${Oo(a)} + coords.${o0[a]};`), `
      ${G("index")} {
        if (index < uniforms.size) {
          var sourceLoc : ${e};
          let coords = getCoordsFromIndex(index);
          ${o.join(`
`)}
          setOutputAtIndex(index, getSource(${t10}));
        }
      }
    `;
  }
};
var o0 = ["x", "y", "z", "w", "u", "v"];
function xue(r15) {
  if (r15 === 1) return "sourceLoc";
  if (r15 <= 6) return o0.slice(0, r15).map((e) => `sourceLoc.${e}`).join(",");
  throw Error(`Slicing for rank ${r15} is not yet supported`);
}
function Hs(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { begin: s, size: a } = o, [i, p] = pt.parseSliceParams(n, s, a);
  if (pt.assertParamsValid(n, i, p), t10.shouldExecuteOnCPU([n]) || n.dtype === "string") {
    let l = t10.tensorMap.get(n.dataId), m = Bz(l.values, i, p, n.shape, n.dtype);
    return t10.makeTensorInfo(p, n.dtype, m);
  }
  if (y.sizeFromShape(p) === 0) return t10.makeTensorInfo(p, n.dtype, []);
  let u = new px(i, p), c = [{ type: "int32", data: i }];
  return t10.runWebGPUProgram(u, [n], n.dtype, c);
}
var fV = { kernelName: ha, backendName: "webgpu", kernelFunc: Hs };
var yue = (r15) => {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { blockShape: s, crops: a } = o;
  y.assert(n.shape.length <= 4, () => "batchToSpaceND for rank > 4 with a WebGPU backend not implemented yet");
  let i = s.reduce((b, C) => b * C), p = w.getReshaped(n.shape, s, i), u = w.getPermuted(p.length, s.length), c = w.getReshapedPermuted(n.shape, s, i), l = w.getSliceBeginCoords(a, s.length), m = w.getSliceSize(c, a, s.length), d = [], f = pe({ inputs: { x: n }, backend: t10, attrs: { shape: p } }), h = xr({ inputs: { x: f }, backend: t10, attrs: { perm: u } }), g = pe({ inputs: { x: h }, backend: t10, attrs: { shape: c } }), x = Hs({ inputs: { x: g }, backend: t10, attrs: { begin: l, size: m } });
  return d.push(f), d.push(h), d.push(g), d.forEach((b) => t10.disposeData(b.dataId)), x;
};
var hV = { kernelName: Js, backendName: "webgpu", kernelFunc: yue };
var bue = `
  fn bincount_write(index: i32, value: f32) {
    ${Qr("&result[index]", "value", "float32")}
  }
`;
var Cue = `
  fn bincount_write(index: i32, value: f32) {
    atomicStore(&result[index], bitcast<i32>(value));
  }
`;
var Qc = class {
  constructor(e, t10, o = false) {
    this.outputShape = [], this.variableNames = ["x"], this.uniforms = "binCountSize : i32,", this.workgroupSize = [64, 1, 1], this.atomic = true, this.hasWeights = true, this.binaryOutput = false, this.outputShape = e, this.rank = e.length, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.binaryOutput = o, o && (this.atomic = false), this.hasWeights = t10, this.hasWeights && this.variableNames.push("w"), this.shaderKey = `bincount_${this.hasWeights}_${this.binaryOutput}_${this.rank}`;
  }
  getUserCode() {
    return `
    ${this.binaryOutput ? Cue : bue}
  ${G("index")} {
    ${this.rank === 1 ? `if (index < uniforms.xShape) {
      let indexVal = i32(getX(index));
      if (indexVal < uniforms.binCountSize) {
        let value = ${this.binaryOutput ? 1 : this.hasWeights ? "getW(index)" : "1."};
        bincount_write(indexVal, value);
      }
    }` : `let coord = getCoordsFromIndex(index);
    if (coordsInBounds2D(coord, uniforms.xShape)) {
      let indexVal = i32(getX(coord[0], coord[1]));
      if (indexVal < uniforms.binCountSize) {
        let value = ${this.binaryOutput ? 1 : this.hasWeights ? "getW(coord[0], coord[1])" : "1."};
        bincount_write(coord.x * uniforms.binCountSize + indexVal, value);
      }
    }`}
  }
  `;
  }
};
function wue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, weights: s } = e, { size: a } = o, i = y.sizeFromShape(n.shape), u = y.sizeFromShape(s.shape) > 0, c = [a], l = s.dtype, m = vt({ backend: t10, attrs: { shape: c, value: 0, dtype: l } }), d = new Qc([i], u), f = [{ type: "int32", data: [a] }], h = u ? [n, s] : [n];
  return t10.runWebGPUProgram(d, h, l, f, m);
}
var gV = { kernelName: Jo, backendName: "webgpu", kernelFunc: wue };
var cx = class {
  constructor(e) {
    this.outputShape = [], this.variableNames = ["s0", "s1"], this.uniforms = "s0Size : i32, s1Size : i32, ", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = [e], this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "broadcastArgs";
  }
  getUserCode() {
    return `
  ${G("index")} {
    if (index < uniforms.size) {
      var s0 = 1.0;
      var s1 = 1.0;
      let indexS0 = index - uniforms.size + uniforms.s0Size;
      let indexS1 = index - uniforms.size + uniforms.s1Size;
      if (indexS0 >= 0) {
        s0 = getS0(indexS0);
      }
      if (indexS1 >= 0) {
        s1 = getS1(indexS1);
      }

      if (s0 == 1.0) {
        setOutputAtIndex(index, s1);
      } else if (s1 == 1.0) {
        setOutputAtIndex(index, s0);
      } else if (s0 != s1) {
        setOutputAtIndex(index, uniforms.NAN);
      } else {
        setOutputAtIndex(index, s0);
      }
    }
  }
  `;
  }
};
function Sue(r15) {
  let { inputs: e, backend: t10 } = r15, { s0: o, s1: n } = e;
  if (t10.shouldExecuteOnCPU([o, n])) {
    let c = t10.tensorMap.get(o.dataId), l = t10.tensorMap.get(n.dataId), m = c.values, d = l.values, f = w.assertAndGetBroadcastShape(Array.from(m), Array.from(d));
    return t10.makeTensorInfo([f.length], "int32", Int32Array.from(f));
  }
  let s = y.sizeFromShape(o.shape), a = y.sizeFromShape(n.shape), i = Math.max(s, a), p = new cx(i), u = [{ type: "int32", data: [s] }, { type: "int32", data: [a] }];
  return t10.runWebGPUProgram(p, [o, n], "int32", u);
}
var xV = { kernelName: ea, backendName: "webgpu", kernelFunc: Sue };
var n0 = et({ opType: fe.NOT_EQUAL, dtype: "bool", cpuKernelImpl: Az });
var yV = { kernelName: Yn, backendName: "webgpu", kernelFunc: n0 };
function vi(r15) {
  let { inputs: e, backend: t10 } = r15, { input: o } = e, n = t10.tensorMap.get(o.dataId);
  return At({ inputs: { x: n.complexTensorInfos.real }, backend: t10 });
}
var bV = { kernelName: Hi, backendName: "webgpu", kernelFunc: vi };
function CV(r15, e) {
  let t10 = new Jr(r15.shape, Z.TO_INT), o = e.runWebGPUProgram(t10, [r15], "int32");
  return { dataId: o.dataId, shape: o.shape, dtype: o.dtype };
}
function s0(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { dtype: s } = o;
  if (s === "complex64") {
    if (n.dtype === "complex64") return At({ inputs: { x: n }, backend: t10 });
    let a = Gr(n.shape), i = s0({ inputs: { x: n }, backend: t10, attrs: { dtype: "float32" } }), p = xo({ inputs: { real: i, imag: a }, backend: t10 });
    return a.dispose(), t10.disposeData(i.dataId), p;
  }
  if (n.dtype === "complex64") {
    let a = vi({ inputs: { input: n }, backend: t10 }), i = s0({ inputs: { x: a }, backend: t10, attrs: { dtype: s } });
    return t10.disposeData(a.dataId), i;
  }
  if (!y.hasEncodingLoss(n.dtype, s)) {
    let a = At({ inputs: { x: n }, backend: t10 });
    return { dataId: a.dataId, shape: a.shape, dtype: s };
  }
  if (t10.shouldExecuteOnCPU([n])) {
    let a = t10.tensorMap.get(n.dataId).values, [i, p, u] = dz(a, n.shape, n.dtype, s);
    return t10.makeTensorInfo(i, p, u);
  }
  if (s === "int32") return CV(n, t10);
  if (s === "bool") {
    let a = t10.makeTensorInfo([], "bool", y.getTypedArrayFromDType("bool", 1)), p = n0({ inputs: { a: n, b: a }, backend: t10 });
    return t10.disposeData(a.dataId), p;
  }
  throw new Error(`Error in Cast: failed to cast ${n.dtype} to ${s}`);
}
var wV = { kernelName: yo, backendName: "webgpu", kernelFunc: s0 };
var Iue = ye({ opType: Z.CEIL, cpuKernelImpl: fz });
var SV = { kernelName: en, backendName: "webgpu", kernelFunc: Iue };
var lx = class {
  constructor(e) {
    this.variableNames = ["A"], this.uniforms = "minVal : f32, maxVal : f32,", this.workPerThread = 4, this.workgroupSize = [64, 1, 1], this.outputComponent = 4, this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize, [this.workPerThread, 1, 1]), this.shaderKey = "clipVec4";
  }
  getUserCode() {
    return `
      ${G("index")} {
        if(index < uniforms.size) {
          let value = getAByOutputIndex(index);
          var clampedValue = clamp(
              value, vec4<f32>(uniforms.minVal), vec4<f32>(uniforms.maxVal));
          clampedValue = select(clampedValue, value, isnanVec4(value));
          setOutputAtIndex(index, clampedValue);
        }
      }
    `;
  }
};
var mx = class {
  constructor(e) {
    this.variableNames = ["A"], this.uniforms = "minVal : f32, maxVal : f32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "clip";
  }
  getUserCode() {
    return `
      ${G("index")} {
        if(index < uniforms.size) {
          let value = getAByOutputIndex(index);
          if (isnan(value)) {
            setOutputAtIndex(index, value);
            return;
          }
          setOutputAtIndex(index, clamp(value, uniforms.minVal, uniforms.maxVal));
        }
      }
    `;
  }
};
function vue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { clipValueMin: s, clipValueMax: a } = o, i, p = [{ type: "float32", data: [s] }, { type: "float32", data: [a] }];
  return y.sizeFromShape(n.shape) % 4 === 0 ? i = new lx(n.shape) : i = new mx(n.shape), t10.runWebGPUProgram(i, [n], n.dtype, p);
}
var IV = { kernelName: bo, backendName: "webgpu", kernelFunc: vue };
var dx = class {
  constructor(e) {
    this.outputShape = [], this.variableNames = ["real", "imag"], this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "complexAbs";
  }
  getUserCode() {
    return `
    ${G("index")} {
      if (index < uniforms.size) {
        let re = abs(getRealByOutputIndex(index));
        let im = abs(getImagByOutputIndex(index));
        let mx = max(re, im);

        // The length function in wgsl may be not underflow-safe on some GPUs.
        // So the safe solution is to ensure underflow-safety in all cases.
        setOutputAtIndex(index, select(mx * length(vec2<f32>(1, min(re, im)/mx)), 0.0, mx == 0.0));
      }
    }
  `;
  }
};
function vV(r15, e) {
  return { dataId: e.dataId, dtype: e.dtype, shape: r15.shape };
}
function kue(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e, n = t10.tensorMap.get(o.dataId), s = new dx(o.shape), a = [vV(o, n.complexTensorInfos.real), vV(o, n.complexTensorInfos.imag)];
  return t10.runWebGPUProgram(s, a, a[0].dtype);
}
var kV = { kernelName: Ai, backendName: "webgpu", kernelFunc: kue };
var fx = class {
  constructor(e) {
    this.uniforms = "", this.workPerThread = 1, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = w.computeOutShape(e, 1), this.variableNames = e.map((t10, o) => `T${o}`), this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize, [this.workPerThread, 1, 1]), this.offsetLength = e.length - 1;
    for (let t10 = 0; t10 < this.offsetLength; t10++) this.uniforms += `offset${t10} : i32,`;
    this.shaderKey = "concat";
  }
  getUserCode() {
    let e = [];
    if (this.offsetLength > 0) {
      e.push("if (yC < uniforms.offset0){ setOutputAtCoords(coords.x, coords.y, getT0(yR, yC)); }");
      for (let s = 1; s < this.offsetLength; s++) e.push(`else if (yC < uniforms.offset${[s]}){ setOutputAtCoords(coords.x, coords.y, getT${s}(yR, yC - uniforms.offset${s - 1})); }`);
      let o = this.offsetLength, n = this.offsetLength - 1;
      e.push(`else { setOutputAtCoords(coords.x, coords.y, getT${o}(yR, yC - uniforms.offset${n})); }`);
    } else e.push("setOutputAtCoords(coords.x, coords.y, getT0(yR, yC));");
    return `
      ${G("index")} {
        for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
          let flatIndex = index * ${this.workPerThread} + i;
          if(flatIndex < uniforms.size) {
            let coords = getCoordsFromIndex(flatIndex);
            let yR = coords.x;
            let yC = coords.y;

            ${e.join(`
        `)}
          }
        }
      }
    `;
  }
};
function Rp(r15) {
  let { inputs: e, backend: t10 } = r15, { input: o } = e, n = t10.tensorMap.get(o.dataId);
  return At({ inputs: { x: n.complexTensorInfos.imag }, backend: t10 });
}
var NV = { kernelName: Wi, backendName: "webgpu", kernelFunc: Rp };
function Zc(r15, e, t10) {
  let o = r15[0].dtype;
  if (o === "complex64") {
    let f = r15.map((C) => vi({ inputs: { input: C }, backend: t10 })), h = r15.map((C) => Rp({ inputs: { input: C }, backend: t10 })), g = Zc(f, e, t10), x = Zc(h, e, t10), b = xo({ inputs: { real: g, imag: x }, backend: t10 });
    return f.forEach((C) => t10.disposeData(C.dataId)), h.forEach((C) => t10.disposeData(C.dataId)), t10.disposeData(g.dataId), t10.disposeData(x.dataId), b;
  }
  let n = t10.shouldExecuteOnCPU(r15);
  if (o === "string" && (n = true), n) {
    let f = r15.map((k) => {
      let $ = [-1, y.sizeFromShape(k.shape.slice(e))];
      return pe({ inputs: { x: k }, backend: t10, attrs: { shape: $ } });
    }), h = f.map((k) => ({ vals: t10.readSync(k.dataId), shape: k.shape })), g = w.computeOutShape(f.map((k) => k.shape), 1), x = f[0].shape[0] === 1, b = hz(h, g, o, x), C = w.computeOutShape(r15.map((k) => k.shape), e), S = t10.makeTensorInfo(C, o, b);
    return f.forEach((k) => t10.disposeData(k.dataId)), S;
  }
  let s = t10.device.limits.maxStorageBuffersPerShaderStage - 1;
  if (r15.length > s) {
    let f = [];
    for (let g = 0; g < r15.length; g += s) {
      let x = r15.slice(g, g + s);
      f.push(Zc(x, e, t10));
    }
    let h = Zc(f, e, t10);
    for (let g of f) t10.disposeData(g.dataId);
    return h;
  }
  let { tensors2D: a, outShape: i } = Nue(r15, e, t10), p = a.map((f) => f.shape), u = new fx(p), c = [], l = new Array(p.length - 1);
  if (l.length > 0) {
    l[0] = p[0][1], c.push({ type: "int32", data: [l[0]] });
    for (let f = 1; f < l.length; f++) l[f] = l[f - 1] + p[f][1], c.push({ type: "int32", data: [l[f]] });
  }
  let m = t10.runWebGPUProgram(u, a, a[0].dtype, c);
  a.forEach((f) => t10.disposeData(f.dataId));
  let d = pe({ inputs: { x: m }, backend: t10, attrs: { shape: i } });
  return t10.disposeData(m.dataId), d;
}
function Nue(r15, e, t10) {
  let o = w.computeOutShape(r15.map((s) => s.shape), e);
  return { tensors2D: r15.map((s) => pe({ inputs: { x: s }, backend: t10, attrs: { shape: [y.sizeFromShape(s.shape.slice(0, e)), y.sizeFromShape(s.shape.slice(e))] } })), outShape: o };
}
function a0(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { axis: n } = o, s = y.parseAxisParam(n, e[0].shape)[0], a = e.map((u) => u.shape);
  w.assertParamsConsistent(a, s);
  let i = w.computeOutShape(e.map((u) => u.shape), s);
  if (y.sizeFromShape(i) === 0) return t10.makeTensorInfo(i, e[0].dtype, []);
  let p = e.filter((u) => y.sizeFromShape(u.shape) > 0);
  return p.length === 1 ? At({ inputs: { x: p[0] }, backend: t10 }) : Zc(p, s, t10);
}
var TV = { kernelName: ta, backendName: "webgpu", kernelFunc: a0 };
function Tue(r15, e, t10, o, n = false, s = null, a = false, i = 4, p = 4, u = 4) {
  let c = (D) => {
    switch (D) {
      case 1:
        return "resData = f32(x[xIndex]);";
      case 3:
        return "resData = vec3<f32>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);";
      case 4:
        return "resData = vec4<f32>(x[xIndex / 4]);";
      default:
        throw new Error(`innerElementSize ${D} is not supported.`);
    }
  }, l = (D) => {
    switch (D) {
      case 1:
        return "return f32(W[row * uniforms.wShape[3] + col]);";
      case 4:
        return "return vec4<f32>(W[(row * uniforms.wShape[3] + col) / 4]);";
      default:
        throw new Error(`innerElementSize ${D} is not supported.`);
    }
  }, m = r15 ? `
      let coord = vec4<i32>(batch, xRow, xCol, xCh);
      ` : `
      let coord = vec4<i32>(batch, xCh, xRow, xCol);
      `, d = r15 ? `
      let coords = vec4<i32>(
        batch,
        row / outWidth,
        row % outWidth,
        col);
      ` : `
      let coords = vec4<i32>(
        batch,
        row,
        col / outWidth,
        col % outWidth);
      `, f = r15 ? "uniforms.xShape[1]" : "uniforms.xShape[2]", h = r15 ? "uniforms.xShape[2]" : "uniforms.xShape[3]", g = r15 ? "row" : "col", x = r15 ? "col" : "row", b = `
      let inChannels = uniforms.wShape[2];
      let outWidth = ${r15 ? "uniforms.outShape[2]" : "uniforms.outShape[3]"};
      let outRow = ${g} / outWidth;
      let outCol = ${g} % outWidth;

      let WRow = ${x} / (uniforms.filterDims[1] * inChannels);
      let WCol = ${x} / inChannels % uniforms.filterDims[1];
      let xRow = outRow * uniforms.strides[0] + uniforms.dilations[0] * WRow - uniforms.pads[0];
      let xCol = outCol * uniforms.strides[1] + uniforms.dilations[1] * WCol - uniforms.pads[1];
      let xCh = ${x} % inChannels;
      var resData = ${Ae(i)}(0.0);
      // The bounds checking is always needed since we use it to pad zero for
      // the 'same' padding type.
      if (xRow >= 0 && xRow < ${f} && xCol >= 0 && xCol < ${h}) {
        ${m}
        let xIndex = getIndexFromCoords4D(coord, uniforms.xShape);
        ${c(i)}
      }
      return resData;`, C = r15 ? e && o ? `
      ${b}` : `
      if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
        ${b}
      }
      return ${Ae(i)}(0.0);` : o && t10 ? `
      ${b}` : `
      if (row < uniforms.dimInner && col < uniforms.dimBOuter) {
        ${b}
      }
      return ${Ae(i)}(0.0);`, S = `${l(p)}`, k = Ae(u), _ = r15 ? Ae(i) : Ae(p), $ = r15 ? Ae(p) : Ae(i);
  return `
      ${dr(s, a, u === 4, 4)}
      fn mm_readA(batch: i32, row : i32, col : i32) -> ${_} {
        ${r15 ? C : S}
      }

      fn mm_readB(batch: i32, row : i32, col : i32) -> ${$} {
        ${r15 ? S : C}
      }

      fn mm_write(batch: i32, row : i32, col : i32, valueIn : ${k}) {
        if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)
        {
        var value = valueIn;
        let outWidth = ${r15 ? "uniforms.outShape[2]" : "uniforms.outShape[3]"};
        ${d}
        ${Zr(n, s)}
        setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
        }
      }`;
}
var hx = class {
  constructor(e, t10, o, n, s = false, a = null, i = false, p = false) {
    this.variableNames = ["x", "W"], this.uniforms = "filterDims : vec2<i32>, pads : vec2<i32>, strides : vec2<i32>, dilations : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32,", this.outputShape = e.outShape, this.isChannelsLast = e.dataFormat === "channelsLast", this.isVec4 = ((e.inChannels % 4 === 0 || e.inChannels % 3 === 0) && this.isChannelsLast || e.outWidth % 4 === 0 && !this.isChannelsLast) && e.outChannels % 4 === 0, this.dispatchLayout = this.isChannelsLast ? { x: [3], y: [1, 2], z: [0] } : { x: [2, 3], y: [1], z: [0] }, this.workgroupSize = lm(this.dispatchLayout, this.outputShape, this.isVec4), this.elementsPerThread = mm(this.dispatchLayout, this.outputShape, this.isVec4), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize, this.elementsPerThread), this.isVec4 ? (this.outputComponent = 4, this.isChannelsLast && e.inChannels % 4 !== 0 ? (this.innerElementSize = 3, this.variableComponents = [1, 4]) : (this.innerElementSize = 4, this.variableComponents = [4, 4]), s && (this.variableNames.push("bias"), this.variableComponents.push(4)), i && (this.variableNames.push("preluActivationWeights"), this.variableComponents.push(4))) : (this.innerElementSize = this.elementsPerThread[0], s && this.variableNames.push("bias"), i && this.variableNames.push("preluActivationWeights")), this.sequentialAccessByThreads = p, this.addBias = s, this.activation = a, this.hasPreluActivationWeights = i, this.tileAOuter = this.workgroupSize[1] * this.elementsPerThread[1], this.tileBOuter = this.workgroupSize[0] * this.elementsPerThread[0], this.tileInner = Math.max(this.workgroupSize[0] * this.innerElementSize, this.workgroupSize[1]), this.fitAOuter = t10 % this.tileAOuter === 0, this.fitBOuter = o % this.tileBOuter === 0, this.fitInner = n % this.tileInner === 0, this.shaderKey = `conv2DMM_${this.elementsPerThread}_${this.activation}}_${this.fitAOuter}_${this.fitBOuter}_${this.fitInner}_${this.isVec4}_${this.innerElementSize}_${this.isChannelsLast}_${this.sequentialAccessByThreads}`;
  }
  getUserCode() {
    let e = this.isVec4 ? _p(this.elementsPerThread, this.workgroupSize, !this.isChannelsLast, this.tileInner) : Ep(this.elementsPerThread, this.workgroupSize, !this.isChannelsLast, this.tileInner, false, null, this.sequentialAccessByThreads), t10 = this.isVec4 ? [this.innerElementSize, 4, 4] : [1, 1, 1];
    return `
    ${Tue(this.isChannelsLast, this.fitAOuter, this.fitBOuter, this.fitInner, this.addBias, this.activation, this.hasPreluActivationWeights, t10[0], t10[1], t10[2])}
    ${e}
  `;
  }
};
var gx = class {
  constructor(e, t10 = false, o = null, n = false) {
    this.variableNames = ["x", "W"], this.uniforms = "filterDims: vec2<i32>, pads: vec2<i32>, strides: vec2<i32>, dilations: vec2<i32>,", this.workgroupSize = [4, 4, 8], this.outputShape = e.outShape, this.isChannelsLast = e.dataFormat === "channelsLast", this.dispatchLayout = this.isChannelsLast ? { x: [2], y: [1], z: [0, 3] } : { x: [3], y: [2], z: [0, 1] }, this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.addBias = t10, this.activation = o, this.hasPreluActivationWeights = n, t10 && this.variableNames.push("bias"), n && this.variableNames.push("preluActivationWeights"), this.shaderKey = `conv2dnaive_${this.activation}_${this.isChannelsLast}`;
  }
  getUserCode() {
    return `
       ${dr(this.activation, this.hasPreluActivationWeights, false, 4)}
       fn readInp(batch : i32, row : i32, col : i32, chan : i32) -> f32{
         let coords = vec4<i32>(batch, row, col, chan);
         if (coordsInBounds4D(coords, uniforms.xShape)) {
           return  getX(batch, row, col, chan);
         } else {
          return 0.0;
         }
       }
       fn readFilt(row : i32, col : i32, xChannel : i32, outChannel : i32) -> f32{
         let coords = vec4<i32>(row, col, xChannel, outChannel);
         if(coordsInBounds4D(coords, uniforms.wShape)) {
           return getW(row, col, xChannel, outChannel);
          } else {
            return 0.0;
          }
       }
       fn writeResult(batch : i32, row : i32, col : i32, chan : i32, valueIn : f32) {
         let coords = ${this.isChannelsLast ? "vec4<i32>(batch, row, col, chan);" : "vec4<i32>(batch, chan, row, col);"}
         if (coordsInBounds4D(coords, uniforms.outShape)) {
           var value = valueIn;
           ${Zr(this.addBias, this.activation)}
           setOutputAtCoords(coords.x, coords.y, coords.z, coords.w, value);
         }
       }
       ${G("index")} {
         let coords = getOutputCoords();
         let batch = coords[0];
         let outChannel = ${this.isChannelsLast ? "coords[3];" : "coords[1];"}
         let outRow = ${this.isChannelsLast ? "coords[1];" : "coords[2];"}
         let outCol = ${this.isChannelsLast ? "coords[2];" : "coords[3];"}
         var acc : f32 = 0.0;
         for (var row = 0; row < uniforms.filterDims[0]; row = row + 1) {
           for (var col = 0; col < uniforms.filterDims[1]; col = col + 1) {
             let xRow = outRow * uniforms.strides[0] + uniforms.dilations[0] * row - uniforms.pads[0];
             let xCol = outCol * uniforms.strides[1] + uniforms.dilations[1] * col - uniforms.pads[1];
             for (var xChannel = 0; xChannel < ${this.isChannelsLast ? "uniforms.xShape[3];" : "uniforms.xShape[1];"} xChannel = xChannel + 1) {
               ${this.isChannelsLast ? "let v = readInp(batch, xRow, xCol, xChannel);" : "let v = readInp(batch, xChannel, xRow, xCol);"}
               let f = readFilt(row, col, xChannel, outChannel);
               acc = acc + v * f;
             }
           }
         }
         writeResult(batch, outRow, outCol, outChannel, acc);
       }
     `;
  }
};
var xx = class {
  constructor(e, t10) {
    this.variableNames = ["x"], this.uniforms = `pads : vec2<i32>, strides : vec2<i32>, dilations : vec2<i32>, outWidth : i32, itemsPerBlockRow : i32,
       inChannels : i32,`, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.isChannelsLast = t10, this.shaderKey = `im2col_${this.isChannelsLast}`;
  }
  getUserCode() {
    let e = this.isChannelsLast ? 1 : 2, t10 = this.isChannelsLast ? 2 : 3, o = this.isChannelsLast ? "coords[1]" : "coords[2]", n = this.isChannelsLast ? "coords[2]" : "coords[1]", s = this.isChannelsLast ? "getX(batch, xRow, xCol, ch)" : "getX(batch, ch, xRow, xCol)";
    return `
    ${G("index")} {
      let coords = getCoordsFromIndex(index);
      if(index < uniforms.size) {
        let batch = coords[0];
        let row = ${o};
        let col = ${n};
        let offsetY = (row / uniforms.outWidth) * uniforms.strides[0] - uniforms.pads[0];
        let xRow = offsetY + uniforms.dilations[0] * (col / uniforms.itemsPerBlockRow);
        var value = 0.0;
        if(xRow < uniforms.xShape[${e}] && xRow >= 0) {
          let offsetX = (row % uniforms.outWidth) * uniforms.strides[1] -
              uniforms.pads[1];
          let xCol = offsetX + uniforms.dilations[1] * ((col %
              uniforms.itemsPerBlockRow) / uniforms.inChannels);
          let ch = col % uniforms.inChannels;
          if(xCol < uniforms.xShape[${t10}] && xCol >= 0) {
            value = ${s};
          }
        }
        setOutputAtIndex(index, value);
      }
    }
   `;
  }
};
function yx(r15, e) {
  let t10 = r15.length;
  return t10 >= 3 ? e ? [...r15.slice(0, -3), r15[t10 - 3] * r15[t10 - 2], r15[t10 - 1]] : [...r15.slice(0, -3), r15[t10 - 3], r15[t10 - 2] * r15[t10 - 1]] : !e && t10 === 1 && r15[0] > 1 ? [r15[0], 1] : null;
}
function _ue({ x: r15, filter: e, convInfo: t10, backend: o, bias: n = null, preluActivationWeights: s = null, leakyreluAlpha: a = 0, activation: i = null }) {
  let p = t10.dataFormat === "channelsLast", u = !p, c = false, l = p && t10.filterHeight === t10.inHeight && t10.filterWidth === t10.inWidth && t10.padInfo.type === "VALID", m = [], d, f;
  if (l) {
    let x = t10.inHeight * t10.inWidth * t10.inChannels;
    d = pe({ inputs: { x: r15 }, backend: o, attrs: { shape: [1, t10.batchSize, x] } }), f = pe({ inputs: { x: e }, backend: o, attrs: { shape: [1, x, t10.outChannels] } });
  } else d = pe({ inputs: { x: r15 }, backend: o, attrs: { shape: p ? [t10.batchSize, t10.inHeight * t10.inWidth, t10.inChannels] : [t10.batchSize, t10.inChannels, t10.inHeight * t10.inWidth] } }), f = pe({ inputs: { x: e }, backend: o, attrs: { shape: [1, t10.inChannels, t10.outChannels] } });
  if (m.push(d), m.push(f), s != null) {
    let x = yx(s.shape, p);
    x != null && (s = pe({ inputs: { x: s }, backend: o, attrs: { shape: x } }), m.push(s));
  }
  if (n != null) {
    let x = yx(n.shape, p);
    x != null && (n = pe({ inputs: { x: n }, backend: o, attrs: { shape: x } }), m.push(n));
  }
  let h = $p({ a: p ? d : f, b: p ? f : d, transposeA: u, transposeB: c, backend: o, bias: n, activation: i, preluActivationWeights: s, leakyreluAlpha: a }), g = pe({ inputs: { x: h }, backend: o, attrs: { shape: t10.outShape } });
  m.push(h);
  for (let x of m) o.disposeData(x.dataId);
  return g;
}
function Eue({ x: r15, filter: e, convInfo: t10, backend: o, bias: n = null, preluActivationWeights: s = null, leakyreluAlpha: a = 0, activation: i = null }) {
  let { filterWidth: p, filterHeight: u, inChannels: c, strideWidth: l, strideHeight: m, padInfo: d, outWidth: f, outHeight: h, dilationWidth: g, dilationHeight: x, dataFormat: b } = t10, C = b === "channelsLast", S = p * u * c, k = h * f, _ = C ? [t10.batchSize, k, S] : [t10.batchSize, S, k], $ = new xx(_, C), R = [{ type: "int32", data: [d.top, d.left] }, { type: "int32", data: [m, l] }, { type: "int32", data: [x, g] }, { type: "int32", data: [f] }, { type: "int32", data: [c * p] }, { type: "int32", data: [c] }], D = o.runWebGPUProgram($, [r15], r15.dtype, R), P = [];
  P.push(D);
  let O = pe({ inputs: { x: e }, backend: o, attrs: { shape: [1, S, -1] } });
  if (P.push(O), s != null) {
    let U = yx(s.shape, C);
    U != null && (s = pe({ inputs: { x: s }, backend: o, attrs: { shape: U } }), P.push(s));
  }
  if (n != null) {
    let U = yx(n.shape, C);
    U != null && (n = pe({ inputs: { x: n }, backend: o, attrs: { shape: U } }), P.push(n));
  }
  let B = $p({ a: C ? D : O, b: C ? O : D, transposeA: !C, transposeB: false, backend: o, bias: n, activation: i, preluActivationWeights: s, leakyreluAlpha: a }), z = pe({ inputs: { x: B }, backend: o, attrs: { shape: t10.outShape } });
  P.push(B);
  for (let U of P) o.disposeData(U.dataId);
  return z;
}
function bx({ x: r15, filter: e, convInfo: t10, backend: o, bias: n = null, preluActivationWeights: s = null, leakyreluAlpha: a = 0, activation: i = null }) {
  let p = n != null, u = s != null, c = t10.dataFormat === "channelsLast", l = c && t10.filterHeight === t10.inHeight && t10.filterWidth === t10.inWidth && t10.padInfo.type === "VALID", m = A().getBool("WEBGPU_USE_NAIVE_CONV2D_DEBUG");
  if (!m && (l || t10.filterHeight === 1 && t10.filterWidth === 1 && t10.dilationHeight === 1 && t10.dilationWidth === 1 && t10.strideHeight === 1 && t10.strideWidth === 1 && (t10.padInfo.type === "SAME" || t10.padInfo.type === "VALID"))) return _ue({ x: r15, filter: e, convInfo: t10, backend: o, bias: n, activation: i, preluActivationWeights: s, leakyreluAlpha: a });
  let d = A().getNumber("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL"), f = d > -1 ? d : o.thresholdToIncreaseWorkgroups, h = t10.batchSize * Math.ceil(t10.outHeight * t10.outWidth / 32) * Math.ceil(t10.outChannels / 32);
  if (A().getBool("WEBGPU_CONV_SEPARATE_IM2COL_SHADER") || h <= f) return Eue({ x: r15, filter: e, convInfo: t10, backend: o, bias: n, preluActivationWeights: s, leakyreluAlpha: a, activation: i });
  let g, x = [t10.padInfo.top, t10.padInfo.left], b = [{ type: "int32", data: [t10.filterHeight, t10.filterWidth] }, { type: "int32", data: [...x] }, { type: "int32", data: [t10.strideHeight, t10.strideWidth] }, { type: "int32", data: [t10.dilationHeight, t10.dilationWidth] }];
  if (m) g = new gx(t10, p, i, u);
  else {
    let _ = c ? t10.outHeight * t10.outWidth : t10.outChannels, $ = c ? t10.outChannels : t10.outHeight * t10.outWidth, R = t10.filterHeight * t10.filterWidth * t10.inChannels;
    b.push({ type: "int32", data: [_] }, { type: "int32", data: [$] }, { type: "int32", data: [R] });
    let D = o.adapterInfo.isIntel();
    g = new hx(t10, _, $, R, p, i, u, D);
  }
  let C = [], S = [r15, e];
  p && (!c && n.shape.length === 1 && (n = pe({ inputs: { x: n }, backend: o, attrs: { shape: [n.shape[0], 1, 1] } }), C.push(n)), S.push(n)), u && (!c && s.shape.length === 1 && (s = pe({ inputs: { x: s }, backend: o, attrs: { shape: [s.shape[0], 1, 1] } }), C.push(s)), S.push(s)), i === "leakyrelu" && (b.push({ type: "float32", data: [a] }), g.uniforms += " alpha : f32,");
  let k = o.runWebGPUProgram(g, S, r15.dtype, b);
  for (let _ of C) o.disposeData(_.dataId);
  return k;
}
function $ue(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { x: n, filter: s } = e, { strides: a, pad: i, dataFormat: p, dilations: u, dimRoundingMode: c } = t10, l = w.convertConv2DDataFormat(p), m = w.computeConv2DInfo(n.shape, s.shape, a, u, i, c, false, l);
  return bx({ x: n, filter: s, convInfo: m, backend: o });
}
var _V = { kernelName: tn, backendName: "webgpu", kernelFunc: $ue };
var Cx = class {
  constructor(e) {
    this.variableNames = ["dy", "W"], this.uniforms = "filterDims : vec2<i32>, pads : vec2<i32>, strides : vec2<i32>, outBackprop : vec4<i32>,", this.workgroupSize = [64, 1, 1], this.size = false, this.isVec4 = false, this.workPerThread = 1, this.outputShape = e.inShape, this.isChannelsLast = e.dataFormat === "channelsLast", this.isVec4 = this.isChannelsLast && e.outChannels % 4 === 0 && e.inChannels % 4 === 0, this.isVec4 ? (this.workPerThread = 2, this.outputComponent = 4, this.workgroupSize = [4, 4, 4], this.dispatchLayout = { x: [3], y: [2], z: [0, 1] }, this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize, [4, this.workPerThread, 1])) : (this.size = true, this.workPerThread = 1, this.workgroupSize = [64, 1, 1], this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize)), this.shaderKey = `conv2DDerInput_${this.isChannelsLast}_${this.isVec4}_${this.workPerThread}`;
  }
  getUserCode() {
    let e = this.isChannelsLast ? 1 : 2, t10 = this.isChannelsLast ? 2 : 3, o = this.isChannelsLast ? 3 : 1, n = `
    ${G()} {
      let batch = i32(globalId.z) / uniforms.outShape[1];
      let r = i32(globalId.z) % uniforms.outShape[1];
      let c = i32(globalId.y) * ${this.workPerThread};
      let d1 = i32(globalId.x) * 4;

      let dyCorner = vec2<i32>(r, c) - uniforms.pads;

      // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
      // ? = to be determined. : = across all values in that axis.
      var dotProd: array<vec4<f32>, ${this.workPerThread}>;
      for (var i = 0; i < ${this.workPerThread}; i++) {
        dotProd[i] = vec4<f32>(0.0);
      }
      for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) {
        let dyR = f32(dyCorner.x + wR) / f32(uniforms.strides.x);
        let wRPerm = uniforms.filterDims.x - 1 - wR;
        if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) ||
            fract(dyR) > 0.0) {
          continue;
        }
        let idyR = i32(dyR);

        for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) {
          let dyC = f32(dyCorner.y + wC) / f32(uniforms.strides.y);
          let dyC2 = f32(dyCorner.y + 1 + wC) / f32(uniforms.strides.y);
          let wCPerm = uniforms.filterDims.y - 1 - wC;
          var bDyCVal = true;
          var bDyCVal2 = true;
          if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) ||
              fract(dyC) > 0.0) {
            bDyCVal = false;
          }
          if (dyC2 < 0.0 || dyC2 >= f32(uniforms.outBackprop[2]) ||
              fract(dyC2) > 0.0) {
            bDyCVal2 = false;
          }

          let idyC = i32(dyC);
          let idyC2 = i32(dyC2);
          if (bDyCVal && bDyCVal2) {
            let d2Length = uniforms.outBackprop[3];
            for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) {
              let wValue0 = getW(wRPerm, wCPerm, d1, d2);
              let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2);
              let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2);
              let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2);
              var xValue =  getDy(batch, idyR, idyC, d2);
              let tmpval = vec4<f32>(dot(xValue, wValue0),
                                     dot(xValue, wValue1),
                                     dot(xValue, wValue2),
                                     dot(xValue, wValue3));
              dotProd[0] = dotProd[0] + tmpval;
              xValue = getDy(batch, idyR, idyC2, d2);
              dotProd[1] = dotProd[1] + vec4<f32>(dot(xValue, wValue0),
                                                  dot(xValue, wValue1),
                                                  dot(xValue, wValue2),
                                                  dot(xValue, wValue3));
            }
          } else if (bDyCVal) {
            let d2Length = uniforms.outBackprop[3];
            for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) {
              let wValue0 = getW(wRPerm, wCPerm, d1, d2);
              let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2);
              let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2);
              let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2);
              var xValue =  getDy(batch, idyR, idyC, d2);
              let tmpval = vec4<f32>(dot(xValue, wValue0),
                                     dot(xValue, wValue1),
                                     dot(xValue, wValue2),
                                     dot(xValue, wValue3));
              dotProd[0] = dotProd[0] + tmpval;
            }
          } else if (bDyCVal2) {
            let d2Length = uniforms.outBackprop[3];
            for (var d2 = 0; d2 < d2Length; d2 = d2 + 4) {
              let wValue0 = getW(wRPerm, wCPerm, d1, d2);
              let wValue1 = getW(wRPerm, wCPerm, d1 + 1, d2);
              let wValue2 = getW(wRPerm, wCPerm, d1 + 2, d2);
              let wValue3 = getW(wRPerm, wCPerm, d1 + 3, d2);
              var xValue =  getDy(batch, idyR, idyC2, d2);
              let tmpval = vec4<f32>(dot(xValue, wValue0),
                                     dot(xValue, wValue1),
                                     dot(xValue, wValue2),
                                     dot(xValue, wValue3));
              dotProd[1] = dotProd[1] + tmpval;
            }
          }
        }
      }

      for (var i = 0; i < ${this.workPerThread}; i = i + 1) {
        let coords = vec4<i32>(batch, r, c + i, d1);
        if (coordsInBounds4D(coords, uniforms.outShape)) {
          setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], dotProd[i]);
        }
      }
    }
    `;
    return this.isVec4 ? `
    ${n}
    ` : `
    ${G("index")} {
      if(index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
        let batch = coords[0];
        let d1 = coords[${o}];

        let dyCorner = vec2<i32>(coords[${e}], coords[${t10}]) - uniforms.pads;
        let dyRCorner = dyCorner.x;
        let 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.
        var dotProd = 0.0;
        for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) {
          let dyR = (f32(dyRCorner) + f32(wR)) / f32(uniforms.strides.x);
          let wRPerm = uniforms.filterDims.x - 1 - wR;
          if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) || fract(dyR) > 0.0 ||
              wRPerm < 0) {
            continue;
          }
          let idyR = i32(dyR);

          for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) {
            let dyC = (f32(dyCCorner) + f32(wC)) / f32(uniforms.strides.y);
            let wCPerm = uniforms.filterDims.y - 1 - wC;
            if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) ||
                fract(dyC) > 0.0 || wCPerm < 0) {
              continue;
            }
            let idyC = i32(dyC);

            for (var d2 = 0; d2 < uniforms.outBackprop[3]; d2 = d2 + 1) {
              let xValue = ${this.isChannelsLast ? "getDy(batch, idyR, idyC, d2)" : "getDy(batch, d2, idyR, idyC)"};
              let wValue = getW(wRPerm, wCPerm, d1, d2);
              dotProd = dotProd + xValue * wValue;
            }
          }
        }
        setOutputAtIndex(index, dotProd);
      }
    }
  `;
  }
};
var wx = class {
  constructor(e) {
    this.variableNames = ["x", "dy"], this.uniforms = "pads : vec2<i32>, strides : vec2<i32>, batchSize : i32, outHeight : i32, outWidth : i32, inHeight : i32, inWidth : i32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e.filterShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.isChannelsLast = e.dataFormat === "channelsLast", this.shaderKey = `conv2DDerFilter_${this.isChannelsLast}`;
  }
  getUserCode() {
    return `
    ${G("index")} {
      if(index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
        let wR = coords[0];
        let wC = coords[1];
        let d1 = coords[2];
        let d2 = coords[3];

        // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
        // ? = to be determined. : = across all values in that axis.
        var dotProd = 0.0;
        for (var b = 0; b < uniforms.batchSize; b = b + 1) {
          for (var yR = 0; yR < uniforms.outHeight; yR = yR + 1) {
            let xR = wR + yR * uniforms.strides[0] - uniforms.pads[0];
            if (xR < 0 || xR >= uniforms.inHeight) {
              continue;
            }

            for (var yC = 0; yC < uniforms.outWidth; yC = yC + 1) {
              let xC = wC + yC * uniforms.strides[1] - uniforms.pads[1];

              if (xC < 0 || xC >= uniforms.inWidth) {
                continue;
              }

              if (${this.isChannelsLast}) {
                let dyValue = getDy(b, yR, yC, d2);
                let xValue = getX(b, xR, xC, d1);
                dotProd = dotProd + xValue * dyValue;
              } else {
                let dyValue = getDy(b, d2, yR, yC);
                let xValue = getX(b, d1, xR, xC);
                dotProd = dotProd + xValue * dyValue;
              }
            }
          }
        }
        setOutputAtIndex(index, dotProd);
      }
    }
  `;
  }
};
var Sx = class {
  constructor(e) {
    this.variableNames = ["x", "dy"], this.uniforms = `pads : vec3<i32>, strides : vec3<i32>, batchSize : i32, outDepth : i32,
       outHeight : i32, outWidth : i32, inDepth : i32, inHeight : i32, inWidth : i32,`, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e.filterShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "conv3DDerFilter";
  }
  getUserCode() {
    return `
    ${G("index")} {
      if(index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
        let wF = coords.x;
        let wR = coords.y;
        let wC = coords.z;
        let d1 = coords.w;
        let d2 = coords.u;

        var dotProd = 0.0;
        for (var b = 0; b < uniforms.batchSize; b++) {
          for (var yF = 0; yF < uniforms.outDepth; yF++) {
            let xF = wF + yF * uniforms.strides[0] - uniforms.pads[0];
            if (xF < 0 || xF >= uniforms.inDepth) {
              continue;
            }

            for (var yR = 0; yR < uniforms.outHeight; yR++) {
              let xR = wR + yR * uniforms.strides[1] - uniforms.pads[1];
              if (xR < 0 || xR >= uniforms.inHeight) {
                continue;
              }

              for (var yC = 0; yC < uniforms.outWidth; yC++) {
                let xC = wC + yC * uniforms.strides[2] - uniforms.pads[2];
                if (xC < 0 || xC >= uniforms.inWidth) {
                  continue;
                }

                let dyValue = getDy(b, yF, yR, yC, d2);
                let xValue = getX(b, xF, xR, xC, d1);
                dotProd += xValue * dyValue;
              }
            }
          }
        }
        setOutputAtIndex(index, dotProd);
      }
    }
  `;
  }
};
var Ix = class {
  constructor(e) {
    this.variableNames = ["dy", "W"], this.uniforms = `filterDims : vec3<i32>, pads : vec3<i32>, strides : vec3<i32>,
      outDepth : i32, outHeight : i32, outWidth : i32, outChannels : i32,`, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e.inShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "conv3DDerInput";
  }
  getUserCode() {
    return `
    ${G("index")} {
      if(index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
        let batch = coords.x;
        let d1 = coords.u;

        let dyCorner = vec3<i32>(coords.y, coords.z, coords.w) - uniforms.pads;
        let dyFCorner = dyCorner.x;
        let dyRCorner = dyCorner.y;
        let dyCCorner = dyCorner.z;

        var dotProd = 0.0;
        for (var wF = 0; wF < uniforms.filterDims[0]; wF++) {
          let dyF = f32(dyFCorner + wF) / f32(uniforms.strides[0]);
          if (dyF < 0.0 || dyF >= f32(uniforms.outDepth) || fract(dyF) > 0.0) {
            continue;
          }
          let idyF = i32(dyF);

          let wFPerm = uniforms.filterDims[0] - 1 - wF;

          for (var wR = 0; wR < uniforms.filterDims[1]; wR++) {
            let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]);

            if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
              continue;
            }
            let idyR = i32(dyR);

            let wRPerm = uniforms.filterDims[1] - 1 - wR;

            for (var wC = 0; wC < uniforms.filterDims[2]; wC++) {
              let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]);

              if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
                continue;
              }
              let idyC = i32(dyC);

              let wCPerm = uniforms.filterDims[2] - 1 - wC;

              for (var d2 = 0; d2 < uniforms.outChannels; d2++) {
                let xValue = getDy(batch, idyF, idyR, idyC, d2);
                let wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
                dotProd += xValue * wValue;
              }
            }
          }
        }
        setOutputAtIndex(index, dotProd);
      }
    }
  `;
  }
};
function Rue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, dy: s } = e, { strides: a, pad: i, dataFormat: p, dimRoundingMode: u, filterShape: c } = o, l = w.convertConv2DDataFormat(p), m = w.computeConv2DInfo(n.shape, c, a, 1, i, u, false, l), d = new wx(m), f = [{ type: "int32", data: [m.padInfo.top, m.padInfo.left] }, { type: "int32", data: [m.strideHeight, m.strideWidth] }, { type: "int32", data: [m.batchSize] }, { type: "int32", data: [m.outHeight] }, { type: "int32", data: [m.outWidth] }, { type: "int32", data: [m.inHeight] }, { type: "int32", data: [m.inWidth] }];
  return t10.runWebGPUProgram(d, [n, s], n.dtype, f);
}
var EV = { kernelName: Fi, backendName: "webgpu", kernelFunc: Rue };
function Due(r15 = 4) {
  let e = (s) => {
    switch (s) {
      case 1:
        return "return W[getIndexFromCoords4D(coord, uniforms.wShape)];";
      case 4:
        return `
            let coord1 = vec4<i32>(coordX, coordY, col + 1, rowInner);
            let coord2 = vec4<i32>(coordX, coordY, col + 2, rowInner);
            let coord3 = vec4<i32>(coordX, coordY, col + 3, rowInner);
            let v0 = W[getIndexFromCoords4D(coord, uniforms.wShape)];
            let v1 = W[getIndexFromCoords4D(coord1, uniforms.wShape)];
            let v2 = W[getIndexFromCoords4D(coord2, uniforms.wShape)];
            let v3 = W[getIndexFromCoords4D(coord3, uniforms.wShape)];
            return vec4<f32>(v0, v1, v2, v3);
            `;
      default:
        throw new Error(`innerElementSize ${s} is not supported.`);
    }
  }, o = `if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
        ${`
      let outRow = row / uniforms.outShape[2];
      let outCol = row % uniforms.outShape[2];

      let WRow = col / (uniforms.filterDims[1] * uniforms.outBackprop[3]);
      let WCol = col / uniforms.outBackprop[3] % uniforms.filterDims[1];
      let xR = f32(outRow - uniforms.pads[0] + WRow) / f32(uniforms.strides[0]);
      let xC = f32(outCol - uniforms.pads[1] + WCol) / f32(uniforms.strides[1]);
      if (xR < 0.0 || xR >= f32(uniforms.outBackprop[1]) || fract(xR) > 0.0) {
        return ${Ae(r15)}(0.0);
      }
      if (xC < 0.0 || xC >= f32(uniforms.outBackprop[2]) || fract(xC) > 0.0) {
        return ${Ae(r15)}(0.0);
      }
      let coord = vec4<i32>(
          batch,
          i32(xR),
          i32(xC),
          col % uniforms.outBackprop[3]);
      return x[getIndexFromCoords4D(coord, uniforms.xShape)/${r15}];`}
      }
      return ${Ae(r15)}(0.0);`;
  return `
  fn mm_readA(batch: i32, row : i32, col : i32) -> ${Ae(r15)} {
    ${o}
  }

  fn mm_readB(batch: i32, row : i32, col : i32) -> ${Ae(r15)} {
    let coordX = uniforms.filterDims.x - 1 -
        row / (uniforms.filterDims[1] * uniforms.outBackprop[3]);
    let coordY = uniforms.filterDims.y - 1 -
        (row / uniforms.outBackprop[3]) % uniforms.filterDims[1];
    if (row < uniforms.dimInner && col < uniforms.dimBOuter &&
        coordX >= 0 && coordY >= 0) {
      let rowInner = row % uniforms.outBackprop[3];
      let coord = vec4<i32>(coordX, coordY, col, rowInner);
      ${e(r15)}
    }
    return ${Ae(r15)}(0.0);
  }

  fn mm_write(batch: i32, row : i32, col : i32, valueInput : ${Ae(r15)}) {
    if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) {
      var value = valueInput;
      let outCoord = vec4<i32>(
          batch,
          row / uniforms.outShape[2],
          row % uniforms.outShape[2],
          col);
      result[getIndexFromCoords4D(outCoord, uniforms.outShape)/${r15}] = value;
    }
  }`;
}
var vx = class {
  constructor(e) {
    this.variableNames = ["x", "W"], this.uniforms = "filterDims : vec2<i32>, pads : vec2<i32>, strides : vec2<i32>, outBackprop : vec4<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32,", this.outputShape = e.inShape, y.assert(e.dataFormat === "channelsLast", () => "TODO: NCHW is unimplemented"), this.isVec4 = e.inChannels % 4 === 0 && e.outChannels % 4 === 0, this.dispatchLayout = { x: [3], y: [1, 2], z: [0] }, this.workgroupSize = lm(this.dispatchLayout, this.outputShape, this.isVec4), this.elementsPerThread = mm(this.dispatchLayout, this.outputShape, this.isVec4), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize, this.elementsPerThread), this.isVec4 && (this.outputComponent = 4, this.variableComponents = [4, 1]), this.shaderKey = `conv2DDerInputMM_${this.isVec4}_${this.elementsPerThread}`;
  }
  getUserCode() {
    let e = this.isVec4 ? _p(this.elementsPerThread, this.workgroupSize) : Ep(this.elementsPerThread, this.workgroupSize);
    return `
    ${Due(this.isVec4 ? 4 : 1)}
    ${e}
    `;
  }
};
function Aue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, filter: s } = e, { inputShape: a, strides: i, pad: p, dataFormat: u, dimRoundingMode: c } = o, l = w.convertConv2DDataFormat(u), m = w.computeConv2DInfo(a, s.shape, i, 1, p, c, false, l), d = [{ type: "int32", data: [m.filterHeight, m.filterWidth] }, { type: "int32", data: [m.filterHeight - 1 - m.padInfo.top, m.filterWidth - 1 - m.padInfo.left] }, { type: "int32", data: [m.strideHeight, m.strideWidth] }, { type: "int32", data: [m.batchSize, m.outHeight, m.outWidth, m.outChannels] }], f;
  if (A().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE") || m.dataFormat !== "channelsLast") f = new Cx(m);
  else {
    f = new vx(m);
    let h = m.inHeight * m.inWidth, g = m.inChannels, x = m.filterHeight * m.filterWidth * m.outChannels;
    d.push({ type: "uint32", data: [h] }, { type: "uint32", data: [g] }, { type: "uint32", data: [x] });
  }
  return t10.runWebGPUProgram(f, [n, s], "float32", d);
}
var $V = { kernelName: rn, backendName: "webgpu", kernelFunc: Aue };
var kx = class {
  constructor(e) {
    this.variableNames = ["x", "W"], this.uniforms = "filterDims: vec3<i32>, pads: vec3<i32>, strides: vec3<i32>, dilations: vec3<i32>,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e.outShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "conv3dnaive";
  }
  getUserCode() {
    return `
    ${G("index")} {
      if (index < uniforms.size) {
        let coords = getOutputCoords();
        let batch = coords.x;
        let d2 = coords.u;

        let xFRCCorner = vec3<i32>(coords.y, coords.z, coords.w) * uniforms.strides - uniforms.pads;
        let xFCorner = xFRCCorner.x;
        let xRCorner = xFRCCorner.y;
        let xCCorner = xFRCCorner.z;

        let inputDepthNearestVec4 = (uniforms.xShape.u / 4) * 4;
        let inputDepthVec4Remainder = uniforms.xShape.u % 4;

        var dotProd = 0.0;
        for (var wF = 0; wF < uniforms.filterDims[0]; wF++) {
          let xF = xFCorner + wF * uniforms.dilations[0];
          if (xF < 0 || xF >= uniforms.xShape.y) {
            continue;
          }

          for (var wR = 0; wR < uniforms.filterDims[1]; wR++) {
            let xR = xRCorner + wR * uniforms.dilations[1];
            if (xR < 0 || xR >= uniforms.xShape.z) {
              continue;
            }

            for (var wC = 0; wC < uniforms.filterDims[2]; wC++) {
              let xC = xCCorner + wC * uniforms.dilations[2];
              if (xC < 0 || xC >= uniforms.xShape.w) {
                continue;
              }

              for (var d1 = 0; d1 < inputDepthNearestVec4; d1 += 4) {
                let xValues = vec4<f32>(
                  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)
                );
                let wValues = vec4<f32>(
                  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 (inputDepthVec4Remainder == 1) {
                dotProd += getX(batch, xF, xR, xC, inputDepthNearestVec4) *
                  getW(wF, wR, wC, inputDepthNearestVec4, d2);
              } else if (inputDepthVec4Remainder == 2) {
                let xValues = vec2<f32>(
                  getX(batch, xF, xR, xC, inputDepthNearestVec4),
                  getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)
                );
                let wValues = vec2<f32>(
                  getW(wF, wR, wC, inputDepthNearestVec4, d2),
                  getW(wF, wR, wC, inputDepthNearestVec4 + 1, d2)
                );
                dotProd += dot(xValues, wValues);
              } else if (inputDepthVec4Remainder == 3) {
                let xValues = vec3<f32>(
                  getX(batch, xF, xR, xC, inputDepthNearestVec4),
                  getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),
                  getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)
                );
                let wValues = vec3<f32>(
                  getW(wF, wR, wC, inputDepthNearestVec4, d2),
                  getW(wF, wR, wC, inputDepthNearestVec4 + 1, d2),
                  getW(wF, wR, wC, inputDepthNearestVec4 + 2, d2)
                );
                dotProd += dot(xValues, wValues);
              }
            }
          }
        }
        setOutputAtIndex(index, dotProd);
      }
    }`;
  }
};
function Fue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s } = e, { strides: a, pad: i, dilations: p } = o, u = w.computeConv3DInfo(n.shape, s.shape, a, p, i), c = [u.padInfo.front, u.padInfo.top, u.padInfo.left], l = [{ type: "int32", data: [u.filterDepth, u.filterHeight, u.filterWidth] }, { type: "int32", data: [...c] }, { type: "int32", data: [u.strideDepth, u.strideHeight, u.strideWidth] }, { type: "int32", data: [u.dilationDepth, u.dilationHeight, u.dilationWidth] }], m = new kx(u), d = dt(n.dtype, s.dtype);
  return t10.runWebGPUProgram(m, [n, s], d, l);
}
var RV = { kernelName: on, backendName: "webgpu", kernelFunc: Fue };
function Pue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, dy: s } = e, { strides: a, pad: i, filterShape: p } = o, u = w.computeConv3DInfo(n.shape, p, a, 1, i), c = new Sx(u), l = [{ type: "int32", data: [u.padInfo.front, u.padInfo.top, u.padInfo.left] }, { type: "int32", data: [u.strideDepth, u.strideHeight, u.strideWidth] }, { type: "int32", data: [u.batchSize] }, { type: "int32", data: [u.outDepth] }, { type: "int32", data: [u.outHeight] }, { type: "int32", data: [u.outWidth] }, { type: "int32", data: [u.inDepth] }, { type: "int32", data: [u.inHeight] }, { type: "int32", data: [u.inWidth] }];
  return t10.runWebGPUProgram(c, [n, s], s.dtype, l);
}
var DV = { kernelName: ja, backendName: "webgpu", kernelFunc: Pue };
function Oue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, filter: s } = e, { strides: a, pad: i, inputShape: p } = o, u = w.computeConv3DInfo(p, s.shape, a, 1, i), c = new Ix(u), l = [{ type: "int32", data: [u.filterDepth, u.filterHeight, u.filterWidth] }, { type: "int32", data: [u.filterDepth - 1 - u.padInfo.front, u.filterHeight - 1 - u.padInfo.top, u.filterWidth - 1 - u.padInfo.left] }, { type: "int32", data: [u.strideDepth, u.strideHeight, u.strideWidth] }, { type: "int32", data: [u.outDepth] }, { type: "int32", data: [u.outHeight] }, { type: "int32", data: [u.outWidth] }, { type: "int32", data: [u.outChannels] }];
  return t10.runWebGPUProgram(c, [n, s], n.dtype, l);
}
var AV = { kernelName: nn, backendName: "webgpu", kernelFunc: Oue };
var Mue = ye({ opType: Z.COS });
var FV = { kernelName: "Cos", backendName: "webgpu", kernelFunc: Mue };
var Lue = ye({ opType: Z.COSH });
var PV = { kernelName: an, backendName: "webgpu", kernelFunc: Lue };
var Nx = class {
  constructor(e, t10, o, n) {
    this.variableNames = ["Image", "Boxes", "BoxInd"], this.uniforms = "extrapolationValue : f32,", this.workgroupSize = [64, 1, 1], this.size = true;
    let [s] = t10;
    this.outputShape = [s, o[0], o[1], e], this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.methodId = n === "bilinear" ? 1 : 0, this.cropHeightBiggerThan1 = this.outputShape[1] > 1, this.cropWidthBiggerThan1 = this.outputShape[2] > 1, this.shaderKey = `cropAndResize_${this.methodId}_${this.cropHeightBiggerThan1}_${this.cropWidthBiggerThan1}`;
  }
  getUserCode() {
    let [e, t10] = ["f32(uniforms.imageShape[1] - 1)", "f32(uniforms.imageShape[2] - 1)"], [o, n, s] = this.cropHeightBiggerThan1 ? [`(${e} / f32(uniforms.outShape[1] - 1))`, "(y2-y1) * height_ratio", `y1*${e} + f32(y)*(height_scale)`] : ["0.0", "0.0", `0.5 * (y1+y2) * ${e}`], [a, i, p] = this.cropWidthBiggerThan1 ? [`(${t10} / f32(uniforms.outShape[2] - 1))`, "(x2-x1) * width_ratio", `x1*${t10} + f32(x)*(width_scale)`] : ["0.0", "0.0", `0.5 * (x1+x2) * ${t10}`];
    return `
    ${G("index")} {
      if (index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
        let height_ratio = f32(${o});
        let width_ratio = f32(${a});
        let b = coords[0];
        let y = coords[1];
        let x = coords[2];
        let d = coords[3];
        // get box vals
        let y1 = getBoxes(b, 0);
        let x1 = getBoxes(b, 1);
        let y2 = getBoxes(b, 2);
        let x2 = getBoxes(b, 3);
        // get image in batch index
        let bInd = i32(round(getBoxInd(b)));
        if(bInd < 0 || bInd >= uniforms.outShape[0]) {
          return;
        }
        let height_scale = ${n};
        let width_scale = ${i};
        let in_y = ${s};
        if( in_y < 0.0 || in_y > ${e} ) {
          setOutputAtIndex(index, uniforms.extrapolationValue);
          return;
        }
        let in_x = ${p};
        if( in_x < 0.0 || in_x > ${t10} ) {
          setOutputAtIndex(index, uniforms.extrapolationValue);
          return;
        }
        let sourceFracIndexCR = vec2<f32>(in_x,in_y);
        if(${this.methodId} == 1) {
          // Compute the four integer indices.
          let sourceFloorCR = vec2<i32>(sourceFracIndexCR);
          let sourceCeilCR = vec2<i32>(ceil(sourceFracIndexCR));
          let topLeft = getImage(bInd, sourceFloorCR.y, sourceFloorCR.x, d);
          let bottomLeft = getImage(bInd, sourceCeilCR.y, sourceFloorCR.x, d);
          let topRight = getImage(bInd, sourceFloorCR.y, sourceCeilCR.x, d);
          let bottomRight = getImage(bInd, sourceCeilCR.y, sourceCeilCR.x, d);
          let fracCR = sourceFracIndexCR - vec2<f32>(sourceFloorCR);
          let top = topLeft + (topRight - topLeft) * fracCR.x;
          let bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
          let newValue = top + (bottom - top) * fracCR.y;
          setOutputAtIndex(index, newValue);
        } else {
          // Compute the coordinators of nearest neighbor point.
          let sourceNearestCR = vec2<i32>(floor(
            sourceFracIndexCR + vec2<f32>(0.5,0.5)));
          let newValue = getImage(
            bInd, sourceNearestCR.y, sourceNearestCR.x, d);
          setOutputAtIndex(index, newValue);
        }
      }
    }
    `;
  }
};
var Bue = (r15) => {
  let { inputs: e, backend: t10, attrs: o } = r15, { image: n, boxes: s, boxInd: a } = e, { cropSize: i, method: p, extrapolationValue: u } = o, c = new Nx(n.shape[3], s.shape, i, p), l = [{ type: "float32", data: [u] }];
  return t10.runWebGPUProgram(c, [n, s, a], "float32", l);
};
var OV = { kernelName: cn, backendName: "webgpu", kernelFunc: Bue };
var Dp;
(function(r15) {
  r15.Prod = "*", r15.Sum = "+";
})(Dp || (Dp = {}));
var xm = class {
  constructor(e, t10, o, n) {
    this.variableNames = ["x"], this.uniforms = "index : f32,", this.size = true, this.workgroupSize = [128, 1, 1], this.outputShape = t10, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.exclusive = o, this.reverse = n, this.op = e, this.shaderKey = `cum_${this.op}_${this.exclusive}_${this.reverse}`;
  }
  getUserCode() {
    let e = this.outputShape.length, t10 = this.op === Dp.Prod ? "1.0" : "0.0", o = this.exclusive ? t10 : `getX(${MV(e, "coords", this.op)})`, n = this.outputShape[this.outputShape.length - 1], s = "", a = "";
    return this.exclusive ? (s = this.reverse ? `end != ${n - 1}` : "end != 0", a = this.reverse ? "end + 1" : "end - 1") : (s = this.reverse ? `end + pow2 < ${n}` : "end >= pow2", a = this.reverse ? "end + pow2" : "end - pow2"), `
      ${G("index")} {
       if (index < uniforms.size) {
         var coords = getCoordsFromIndex(index);

         let end = ${LV(e, "coords", this.op)};
         var val = ${o};
         let pow2 = i32(pow(2.0, uniforms.index));
         if (${s}) {
           let idx = ${a};
           ${LV(e, "coords", this.op)} = idx;
           val ${this.op}= getX(${MV(e, "coords", this.op)});
         }
         setOutputAtIndex(index, val);
       }
      }
    `;
  }
};
function MV(r15, e, t10) {
  if (r15 === 1) return `${e}`;
  if (r15 === 2) return `${e}.x, ${e}.y`;
  if (r15 === 3) return `${e}.x, ${e}.y, ${e}.z`;
  if (r15 === 4) return `${e}.x, ${e}.y, ${e}.z, ${e}.w`;
  throw Error(`Cumulative ${t10} for rank ${r15} is not yet supported`);
}
function LV(r15, e, t10) {
  if (r15 === 1) return `${e}`;
  if (r15 === 2) return `${e}.y`;
  if (r15 === 3) return `${e}.z`;
  if (r15 === 4) return `${e}.w`;
  throw Error(`Cumulative ${t10} for rank ${r15} is not yet supported`);
}
function Tx(r15, e, t10, o, n, s) {
  let a = e.shape.length, i = w.getAxesPermutation([o], a), p = e;
  i != null && (p = xr({ inputs: { x: e }, backend: t10, attrs: { perm: i } }));
  let u = w.getInnerMostAxes(1, a)[0];
  if (u !== a - 1) throw new Error(`WebGPU cumprod shader expects an inner-most axis=${e.shape.length - 1} but got axis=${o}`);
  let c = p.shape[u], l = At({ inputs: { x: p }, backend: t10 });
  for (let m = 0; m <= Math.ceil(Math.log2(c)) - 1; m++) {
    let d = new xm(r15, p.shape, false, s), f = l, h = [{ type: "float32", data: [m] }];
    l = t10.runWebGPUProgram(d, [l], l.dtype, h), t10.disposeData(f.dataId);
  }
  if (n) {
    let m = new xm(r15, p.shape, n, s), d = l, f = [{ type: "float32", data: [0] }];
    l = t10.runWebGPUProgram(m, [l], l.dtype, f), t10.disposeData(d.dataId);
  }
  if (i != null) {
    let m = w.getUndoAxesPermutation(i), d = xr({ inputs: { x: l }, backend: t10, attrs: { perm: m } });
    return t10.disposeData(l.dataId), t10.disposeData(p.dataId), d;
  }
  return l;
}
function zue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, exclusive: a, reverse: i } = o;
  return Tx(Dp.Prod, n, t10, s, a, i);
}
var BV = { kernelName: un, backendName: "webgpu", kernelFunc: zue };
function Vue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, exclusive: a, reverse: i } = o;
  return Tx(Dp.Sum, n, t10, s, a, i);
}
var zV = { kernelName: pn, backendName: "webgpu", kernelFunc: Vue };
function Wue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, weights: s } = e, { size: a, binaryOutput: i } = o, p = n.shape.length === 1, c = y.sizeFromShape(s.shape) > 0, l = s.dtype, m = p ? [n.shape[0]] : [n.shape[0], n.shape[1]], d = p ? [a] : [n.shape[0], a], f = vt({ backend: t10, attrs: { shape: d, value: 0, dtype: l } }), h = new Qc(m, c, i), g = [{ type: "int32", data: [a] }], x = c ? [n, s] : [n];
  return t10.runWebGPUProgram(h, x, l, g, f);
}
var VV = { kernelName: ra, backendName: "webgpu", kernelFunc: Wue };
var _x = class {
  constructor(e, t10) {
    this.variableNames = ["x"], this.workgroupSize = [64, 1, 1], this.size = true, this.uniforms = "blockSize : i32,", this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = `depthToSpace_${t10}`, this.dataFormat = t10;
  }
  getUserCode() {
    return `
      ${G("index")} {
        if (index < uniforms.size) {
          let coords = getCoordsFromIndex(index);
          let b = coords[0];
          let h = ${this.getHeightCoordString()};
          let w = ${this.getWidthCoordString()};
          let d = ${this.getDepthCoordString()};

          let in_h = h / uniforms.blockSize;
          let offset_h = h % uniforms.blockSize;
          let in_w = w / uniforms.blockSize;
          let offset_w = w % uniforms.blockSize;
          let offset_d = (offset_h * uniforms.blockSize + offset_w) *
            ${this.getOutputDepthSize()};
          let in_d = d + offset_d;

          let rlt = ${this.getInputSamplingString()};
          setOutputAtIndex(index, rlt);
        }
      }`;
  }
  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" ? "uniforms.outShape[3]" : "uniforms.outShape[1]";
  }
  getInputSamplingString() {
    return this.dataFormat === "NHWC" ? "getX(b, in_h, in_w, in_d)" : "getX(b, in_d, in_h, in_w)";
  }
};
function Uue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { blockSize: s, dataFormat: a } = o, i = n.shape[0], p = a === "NHWC" ? n.shape[1] : n.shape[2], u = a === "NHWC" ? n.shape[2] : n.shape[3], c = a === "NHWC" ? n.shape[3] : n.shape[1], l = p * s, m = u * s, d = c / (s * s), f = a === "NHWC" ? [i, l, m, d] : [i, d, l, m], h = [{ type: "int32", data: [s] }], g = new _x(f, a);
  return t10.runWebGPUProgram(g, [n], n.dtype, h);
}
var WV = { kernelName: ln, backendName: "webgpu", kernelFunc: Uue };
var Ex = class {
  constructor(e, t10, o, n = false, s = null, a = false) {
    this.variableNames = ["x", "W"], this.uniforms = "pads : vec2<i32>, inDims : vec2<i32>,", this.workgroupSize = [16, 16, 1], this.outputShape = e, this.dispatchLayout = { x: [3], y: [2], z: [0, 1] }, this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), n && this.variableNames.push("bias"), a && this.variableNames.push("preluActivationWeights"), this.addBias = n, this.activation = s, this.hasPreluActivation = a, this.filterHeight = t10, this.filterWidth = o, this.shaderKey = `depthwiseNCHW_${this.activation}_${this.filterHeight}_${this.filterWidth}`;
  }
  getUserCode() {
    let e = this.filterWidth * this.filterHeight, t10 = this.workgroupSize[0] * this.workgroupSize[1] * this.workgroupSize[2], o = this.workgroupSize[1] + this.filterHeight - 1, n = this.workgroupSize[0] + this.filterWidth - 1;
    return `
      ${dr(this.activation, this.hasPreluActivation, false, 4)}

      var<workgroup> mm_Asub : array<array<f32, ${n}>, ${o}>;
      var<workgroup> mm_Bsub : array<array<f32, ${this.filterWidth}>, ${this.filterHeight}>;
      fn readX(batch : i32, channel : i32, row : i32, col : i32) -> f32 {
        var value = 0.0;
        if (row >=0 && row < uniforms.inDims[0] && col >=0 && col < uniforms.inDims[1])
        {
          value = getX(batch, channel, row, col);
        }
        return value;
      }

      ${G()} {
        let coords = getOutputCoords();
        let batch = coords[0];
        let xRCCorner = vec2<i32>(coords.zw) - uniforms.pads;
        let channelMul = uniforms.wShape[3];
        let d1 = coords[1] / channelMul;
        let q = coords[1] % channelMul;

        let inputRowStart = xRCCorner.x;
        let inputColStart = xRCCorner.y;

        let localRow = i32(localId.y);
        let localCol = i32(localId.x);

        // Load one tile of X into local memory.
        for (var inputRow = localRow; inputRow < ${o}; inputRow = inputRow + ${this.workgroupSize[1]}) {
          for (var inputCol = localCol; inputCol < ${n}; inputCol = inputCol + ${this.workgroupSize[0]}) {
            let rowOffset = inputRow - localRow;
            let colOffset = inputCol - localCol;
            mm_Asub[inputRow][inputCol] = readX(batch, d1, inputRowStart + rowOffset, inputColStart + colOffset);
          }
        }

        // Load one tile of W into local memory.
        var wIndex = i32(localIndex);
        ${e < t10 ? `if (wIndex < ${e})` : `for(; wIndex < ${e}; wIndex = wIndex + ${t10})`}

        {
          let wRow = wIndex / ${this.filterWidth};
          let wCol = wIndex % ${this.filterWidth};
          mm_Bsub[wRow][wCol] = getW(wRow, wCol, d1, q);
        }

        workgroupBarrier();

        var value = 0.0;
        for (var wR = 0; wR < ${this.filterHeight}; wR = wR + 1) {
          for (var wC = 0; wC < ${this.filterWidth}; wC = wC + 1) {
            let xVal = mm_Asub[localRow + wR][localCol + wC];
            let wVal = mm_Bsub[wR][wC];
            value = fma(xVal, wVal, value);
          }
        }
        ${Zr(this.addBias, this.activation)}
        if (coordsInBounds4D(coords, uniforms.outShape)) {
          setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
        }
      }
    `;
  }
};
var Jc = class {
  constructor(e, t10 = false, o = null, n = false) {
    this.variableNames = ["x", "W"], this.uniforms = "pads : vec2<i32>, inDims : vec2<i32>, virtualWidth : i32,", this.workgroupSize = [64, 1, 1], this.workPerThread = 4, this.outputComponent = 4, this.outputShape = e.outShape, this.virtualWidth = Math.ceil(this.outputShape[2] / this.workPerThread) * this.workPerThread;
    let s = [this.outputShape[0], this.outputShape[1], this.virtualWidth, this.outputShape[3]];
    this.dispatchLayout = X(s), this.dispatch = H(this.dispatchLayout, s, this.workgroupSize, [this.outputComponent * this.workPerThread, 1, 1]), y.assert(e.dataFormat === "channelsLast", () => "TODO: NCHW is unimplemented"), t10 && this.variableNames.push("bias"), n && this.variableNames.push("preluActivationWeights"), this.convInfo = e, this.addBias = t10, this.activation = o, this.hasPreluActivation = n, this.shaderKey = `depthwiseVec4_${o}_${this.convInfo.filterHeight}_${this.convInfo.filterWidth}_${this.convInfo.strideHeight}_${this.convInfo.strideWidth}_${this.workPerThread}`;
  }
  getUserCode() {
    let e = (this.workPerThread - 1) * this.convInfo.strideWidth + this.convInfo.filterWidth, t10 = this.convInfo.strideHeight, o = this.convInfo.strideWidth;
    return `
      ${dr(this.activation, this.hasPreluActivation, true, 4)}
      fn readX(batch : i32, row : i32, col : i32, channel : i32) -> vec4<f32> {
        var value = vec4<f32>(0.0);
        if (col >=0 && col < uniforms.inDims[1]) {
          value = getX(batch, row, col, channel);
        }
        return value;
      }

      ${G("index")} {
        let width0 = uniforms.outShape[3] / ${this.outputComponent};
        let d1 = (index % width0) * ${this.outputComponent};
        var index1 = index / width0;
        let width1 = uniforms.virtualWidth / ${this.workPerThread};
        let c = (index1 % width1) * ${this.workPerThread};
        index1 = index1 / width1;
        let r = index1 % uniforms.outShape[1];
        let batch = index1 / uniforms.outShape[1];

        let xRCCorner = vec2<i32>(r, c) * vec2<i32>(${t10}, ${o}) - uniforms.pads;

        let xRCorner = xRCCorner.x;
        let xCCorner = xRCCorner.y;
        var xVals : array<vec4<f32>, ${e}>;
        var dotProd : array<vec4<f32>, ${this.workPerThread}>;
        for (var i = 0; i < ${this.workPerThread}; i++) {
          dotProd[i] = vec4<f32>(0.0);
        }

        // Use constant instead of uniform can give better performance.
        for (var wR = 0; wR < ${this.convInfo.filterHeight}; wR = wR + 1) {
          let xR = xRCorner + wR;
          if (xR >=0 && xR < uniforms.inDims[0]) {
            for (var i = 0; i < ${e}; i++) {
              xVals[i] = readX(batch, xR, xCCorner + i, d1);
            }
            for (var wC = 0; wC < ${this.convInfo.filterWidth}; wC = wC + 1) {
              let wValue = getW(wR, wC, d1, 0);
              for (var i = 0; i < ${this.workPerThread}; i++) {
                dotProd[i] = fma(xVals[i * ${o} + wC], wValue, dotProd[i]);
              }
            }
          }
        }

        for (var i = 0; i < ${this.workPerThread}; i = i + 1) {
          let coords = vec4<i32>(batch, r, c + i, d1);
          if (coordsInBounds4D(coords, uniforms.outShape)) {
            var value = dotProd[i];
            ${Zr(this.addBias, this.activation)}
            setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
          }
        }
      }
    `;
  }
};
var el = class {
  constructor(e, t10 = false, o = null, n = false) {
    this.variableNames = ["x", "W"], this.uniforms = `pads : vec2<i32>, inDims : vec2<i32>, filterHeight : i32,
      filterWidth : i32, strides : vec2<i32>, dilations : vec2<i32>,`, this.workgroupSize = [256, 1, 1], this.size = true, this.outputShape = e.outShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.isChannelsLast = e.dataFormat === "channelsLast", t10 && this.variableNames.push("bias"), n && this.variableNames.push("preluActivationWeights"), this.convInfo = e, this.addBias = t10, this.activation = o, this.hasPreluActivation = n, this.shaderKey = `depthwise_${this.activation}_${this.isChannelsLast}`;
  }
  getUserCode() {
    let e = this.isChannelsLast ? "getX(batch, xR, xC, d1);" : "getX(batch, d1, xR, xC);";
    return `
      ${dr(this.activation, this.hasPreluActivation, false, 4)}

      ${G("index")} {
        if (index < uniforms.size) {
          let coords = getOutputCoords();
          let batch = coords[0];
          let xRCCorner = vec2<i32>(coords.${this.isChannelsLast ? "yz" : "zw"}) * uniforms.strides - uniforms.pads;
          let d2 = coords[${this.isChannelsLast ? 3 : 1}];
          let channelMul = uniforms.wShape[3];
          let d1 = d2 / channelMul;
          let q = d2 % channelMul;

          let inputRowStart = xRCCorner.x;
          let inputColStart = xRCCorner.y;
          let inputRowEnd = inputRowStart + uniforms.filterHeight *
              uniforms.dilations[0];
          let inputColEnd = inputColStart + uniforms.filterWidth *
              uniforms.dilations[1];

          // Convolve x(?, ?, d1)|x(d1, ?, ?) with w(:, :, d1, q) to get
          // y(yR, yC, d2)|y(d2, yR, yC). ? = to be determined. : = across all
          // values in that axis. x(?, ?, d1) and y(yR, yC, d2) is for NHWC.
          // x(d1, ?, ?) and y(d2, yR, yC) is for NCHW.
          var value = 0.0;

          // Extract if checking out of for loop for performance.
          if (inputRowStart >= 0 && inputColStart >= 0 &&
            inputRowEnd < uniforms.inDims[0] &&
                inputColEnd < uniforms.inDims[1]) {
              for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) {
                let xR = inputRowStart + wR * uniforms.dilations[0];

                for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {
                  let xC = inputColStart + wC * uniforms.dilations[1];

                  let xVal = ${e};
                  let wVal = getW(wR, wC, d1, q);
                  value = value + xVal * wVal;
                }
              }
            } else {
              for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) {
                let xR = inputRowStart + wR * uniforms.dilations[0];

                if (xR < 0 || xR >= uniforms.inDims[0]) {
                  continue;
                }

                for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {
                  let xC = inputColStart + wC * uniforms.dilations[1];

                  if (xC < 0 || xC >= uniforms.inDims[1]) {
                    continue;
                  }

                  let xVal = ${e};
                  let wVal = getW(wR, wC, d1, q);
                  value = value + xVal * wVal;
                }
              }
            }
            ${Zr(this.addBias, this.activation)}
          setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
        }
      }
    `;
  }
};
function Gue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s } = e, { strides: a, pad: i, dataFormat: p, dilations: u, dimRoundingMode: c } = o, l = w.convertConv2DDataFormat(p), m = u;
  m == null && (m = [1, 1]);
  let d = w.computeConv2DInfo(n.shape, s.shape, a, m, i, c, true, l), f = [{ type: "int32", data: [d.padInfo.top, d.padInfo.left] }, { type: "int32", data: [d.inHeight, d.inWidth] }], h = d.dataFormat === "channelsLast", g;
  return !h && d.inHeight > 16 && d.inWidth > 16 && d.strideHeight === 1 && d.strideWidth === 1 && d.dilationWidth === 1 && d.dilationHeight === 1 && d.inChannels === d.outChannels ? g = new Ex(d.outShape, d.filterHeight, d.filterWidth) : h && d.outHeight > 4 && d.outWidth > 4 && d.strideWidth <= 2 && d.inChannels === d.outChannels && d.dilationHeight === 1 && d.dilationWidth === 1 && d.inChannels % 4 === 0 ? (g = new Jc(d), f.push({ type: "int32", data: [g.virtualWidth] })) : (g = new el(d), f.push({ type: "int32", data: [d.filterHeight] }, { type: "int32", data: [d.filterWidth] }, { type: "int32", data: [d.strideHeight, d.strideWidth] }, { type: "int32", data: [d.dilationHeight, d.dilationWidth] })), t10.runWebGPUProgram(g, [n, s], n.dtype, f);
}
var UV = { kernelName: mn, backendName: "webgpu", kernelFunc: Gue };
var $x = class {
  constructor(e) {
    this.variableNames = ["x", "dy"], this.uniforms = `strides : vec2<i32>, pads : vec2<i32>, filterDims : vec2<i32>, outHeight : i32,
      outWidth : i32, inHeight : i32, inWidth : i32, batchSize : i32, channelMul : i32,`, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e.filterShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "depthwise_conv2d_backprop_filter";
  }
  getUserCode() {
    return `
      ${G("index")} {
      if (index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
        let wR = coords[0];
        let wC = coords[1];
        let d1 = coords[2];
        let dm = coords[3];
        let d2 = d1 * uniforms.channelMul + dm;

        var dotProd = 0.0;
        for (var b = 0; b < uniforms.batchSize; b++) {
          for (var yR = 0; yR < uniforms.outHeight; yR++) {
            let xR = wR + yR * uniforms.strides[0] - uniforms.pads[0];

            if (xR < 0 || xR >= uniforms.inHeight) {
              continue;
            }

            for (var yC = 0; yC < uniforms.outWidth; yC++) {
              let xC = wC + yC * uniforms.strides[1] - uniforms.pads[1];

              if (xC < 0 || xC >= uniforms.inWidth) {
                continue;
              }

              let dyValue = getDy(b, yR, yC, d2);
              let xValue = getX(b, xR, xC, d1);
              dotProd += xValue * dyValue;
            }
          }
        }
        setOutputAtIndex(index, dotProd);
      }
    }
    `;
  }
};
var Rx = class {
  constructor(e) {
    this.variableNames = ["dy", "W"], this.uniforms = `strides : vec2<i32>, pads : vec2<i32>, filterDims : vec2<i32>,
       outHeight : i32, outWidth : i32, channelMul : i32,`, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e.inShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "depthwise_conv2d_backprop_input";
  }
  getUserCode() {
    return `
      ${G("index")} {
      if (index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
        let batch = coords[0];
        let d1 = coords[3];
        let dyCorner = coords.yz - uniforms.pads;
        let dyRCorner = dyCorner.x;
        let dyCCorner = dyCorner.y;

        var dotProd = 0.0;
        for (var wR = 0; wR < uniforms.filterDims[0]; wR++) {
          let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]);

          if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
            continue;
          }

          let idyR = i32(dyR);
          let wRPerm = uniforms.filterDims[0] - 1 - wR;

          for (var wC = 0; wC < uniforms.filterDims[1]; wC++) {
            let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]);

            if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
              continue;
            }

            let idyC = i32(dyC);
            let wCPerm = uniforms.filterDims[1] - 1 - wC;

            for (var dm = 0; dm < uniforms.channelMul; dm++) {
              let d2 = d1 * uniforms.channelMul + dm;
              let xValue = getDy(batch, idyR, idyC, d2);
              let wValue = getW(wRPerm, wCPerm, d1, dm);
              dotProd += xValue * wValue;
            }
          }
        }
        setOutputAtIndex(index, dotProd);
      }
    }
    `;
  }
};
function Hue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, dy: s } = e, { strides: a, dilations: i, pad: p, dimRoundingMode: u, filterShape: c } = o, l = w.computeConv2DInfo(n.shape, c, a, i, p, u, true), m = new $x(l), d = [{ type: "int32", data: [l.strideHeight, l.strideWidth] }, { type: "int32", data: [l.padInfo.top, l.padInfo.left] }, { type: "int32", data: [l.filterHeight, l.filterWidth] }, { type: "int32", data: [l.outHeight] }, { type: "int32", data: [l.outWidth] }, { type: "int32", data: [l.inHeight] }, { type: "int32", data: [l.inWidth] }, { type: "int32", data: [l.batchSize] }, { type: "int32", data: [l.outChannels / l.inChannels] }];
  return t10.runWebGPUProgram(m, [n, s], "float32", d);
}
var GV = { kernelName: Pi, backendName: "webgpu", kernelFunc: Hue };
function Kue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, filter: s } = e, { strides: a, dilations: i, pad: p, dimRoundingMode: u, inputShape: c } = o, l = w.computeConv2DInfo(c, s.shape, a, i, p, u, true), m = new Rx(l), d = [{ type: "int32", data: [l.strideHeight, l.strideWidth] }, { type: "int32", data: [l.filterHeight - 1 - l.padInfo.top, l.filterWidth - 1 - l.padInfo.left] }, { type: "int32", data: [l.filterHeight, l.filterWidth] }, { type: "int32", data: [l.outHeight] }, { type: "int32", data: [l.outWidth] }, { type: "int32", data: [l.outChannels / l.inChannels] }];
  return t10.runWebGPUProgram(m, [n, s], n.dtype, d);
}
var HV = { kernelName: Oi, backendName: "webgpu", kernelFunc: Kue };
var Dx = class {
  constructor(e) {
    this.variableNames = ["x"], this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = [e, e], this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "diag";
  }
  getUserCode() {
    return `
      ${G("index")} {
        if (index < uniforms.size) {
          let coords = getOutputCoords();
          let value = select(0.0, getX(coords[0]), coords[0] == coords[1]);
          setOutputAtIndex(index, value);
        }
      }
    `;
  }
};
function que(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e, n = [...o.shape, ...o.shape], s = y.sizeFromShape(o.shape), a = pe({ inputs: { x: o }, backend: t10, attrs: { shape: [s] } }), i = new Dx(s), p = t10.runWebGPUProgram(i, [a], a.dtype), u = pe({ inputs: { x: p }, backend: t10, attrs: { shape: n } });
  return t10.disposeData(a.dataId), t10.disposeData(p.dataId), u;
}
var KV = { kernelName: oa, backendName: "webgpu", kernelFunc: que };
var Ax = class {
  constructor(e) {
    this.variableNames = ["x", "w"], this.uniforms = "filterDims: vec2<i32>, pads: vec2<i32>, strides: vec2<i32>, dilations: vec2<i32>", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e.outShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "dilation2d";
  }
  getUserCode() {
    return `
       ${G("index")} {
         if (index < uniforms.size) {
           let neg_infinity = -3.4e38;
           let coords = getOutputCoords();
           let batch = coords.x;
           let d1 = coords.w;
           let outTopLeftCorner = coords.yz * uniforms.strides - uniforms.pads;
           let hBeg = outTopLeftCorner.x;
           let wBeg = outTopLeftCorner.y;

           var curVal = neg_infinity;
           for (var h = 0; h < uniforms.filterDims[0]; h = h + 1) {
             let hIn = hBeg + h * uniforms.dilations[0];

             if (hIn >= 0 && hIn < uniforms.xShape[1]) {
               for (var w = 0; w < uniforms.filterDims[1]; w = w + 1) {
                 let wIn = wBeg + w * uniforms.dilations[1];

                 if (wIn >= 0 && wIn < uniforms.xShape[2]) {
                   let val = getX(batch, hIn, wIn, d1) + getW(h, w, d1);
                   if (val > curVal) {
                     curVal = val;
                   }
                 }
               }
             }
           }

           setOutputAtIndex(index, curVal);
         }
       }
     `;
  }
};
function jue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s } = e, { strides: a, pad: i, dilations: p } = o, u = w.computeDilation2DInfo(n.shape, s.shape, a, i, "NHWC", p), c = [u.padInfo.top, u.padInfo.left], l = [{ type: "int32", data: [u.filterHeight, u.filterWidth] }, { type: "int32", data: [...c] }, { type: "int32", data: [u.strideHeight, u.strideWidth] }, { type: "int32", data: [u.dilationHeight, u.dilationWidth] }], m = new Ax(u);
  return t10.runWebGPUProgram(m, [n, s], n.dtype, l);
}
var qV = { kernelName: dn, backendName: "webgpu", kernelFunc: jue };
var Fx = class {
  constructor(e, t10) {
    if (this.variableNames = ["x", "w", "dy"], this.uniforms = "filterDims: vec2<i32>, pads: vec2<i32>, strides: vec2<i32>, dilations: vec2<i32>, dySize: i32,", this.workgroupSize = [64, 1, 1], this.atomic = true, this.outputShape = e.inShape, this.dispatchLayout = X(e.outShape), this.dispatch = H(this.dispatchLayout, e.outShape, this.workgroupSize), t10 !== "float32" && t10 !== "int32") throw new Error(`Dilation2DBackpropInput only supports float32 and int32
          types, does not support ${t10} type.`);
    this.type = t10, this.shaderKey = "dilation2DBackpropInput";
  }
  getUserCode() {
    return `
       ${G("index")} {
         if (index < uniforms.dySize) {
           let coords = getDyCoordsFromIndex(index);
           let b = coords[0];
           let r = coords[1];
           let c = coords[2];
           let d = coords[3];

           let dyCorner = vec2<i32>(r, c) * uniforms.strides - uniforms.pads;
           var curVal = -3.4e38;  // neg_infinity
           var xRMax = 0;
           var xCMax = 0;

           // In the case of multiple argmax branches, we only back-propagate
           // along the last branch, i.e., the one with largest value of
           // 'wR * uniforms.filterDims[1] + wC', similarly to the max-pooling
           // backward routines.
           for (var wR = 0; wR < uniforms.filterDims[0]; wR++) {
             let xR = dyCorner.x + wR * uniforms.dilations[0];

             if (xR >= 0 && xR < uniforms.xShape[1]) {
               for (var wC = 0; wC < uniforms.filterDims[1]; wC++) {
                 let xC = dyCorner.y + wC * uniforms.dilations[1];

                 if (xC >= 0 && xC < uniforms.xShape[2]) {
                   let val = getX(b, xR, xC, d) + getW(wR, wC, d);
                   if (val > curVal) {
                     curVal = val;
                     xRMax = xR;
                     xCMax = xC;
                   }
                 }
               }
             }
           }

           let flatIndexIn = d + uniforms.xShape[3] *
               (xCMax + uniforms.xShape[2] * (xRMax + uniforms.xShape[1] * b));
           let value = getDy(b, r, c, d);
           ${Qr("&result[flatIndexIn]", "value", this.type)}
         }
       }
     `;
  }
};
var Px = class {
  constructor(e, t10, o) {
    if (this.variableNames = ["x", "w", "dy"], this.uniforms = "filterDims: vec2<i32>, pads: vec2<i32>, strides: vec2<i32>, dilations: vec2<i32>, dySize: i32,", this.workgroupSize = [64, 1, 1], this.atomic = true, this.outputShape = e.filterShape, this.dispatchLayout = X(e.outShape), this.dispatch = H(this.dispatchLayout, e.outShape, this.workgroupSize), o !== "float32" && o !== "int32") throw new Error(`Dilation2DBackpropFilter only supports float32 and int32
          types, does not support ${o} type.`);
    this.type = o, this.shaderKey = "dilation2DBackpropFilter";
  }
  getUserCode() {
    return `
       ${G("index")} {
         if (index < uniforms.dySize) {
           let coords = getDyCoordsFromIndex(index);
           let b = coords[0];
           let r = coords[1];
           let c = coords[2];
           let d = coords[3];

           let dyCorner = vec2<i32>(r, c) * uniforms.strides - uniforms.pads;
           var curVal = -3.4e38;  // neg_infinity
           var wRMax = 0;
           var wCMax = 0;

           // In the case of multiple argmax branches, we only back-propagate
           // along the last branch, i.e., the one with largest value of
           // 'wR * uniforms.filterDims[1] + wC', similarly to the max-pooling
           // backward routines.
           for (var wR = 0; wR < uniforms.filterDims[0]; wR++) {
             let xR = dyCorner.x + wR * uniforms.dilations[0];

             if (xR >= 0 && xR < uniforms.xShape[1]) {
               for (var wC = 0; wC < uniforms.filterDims[1]; wC++) {
                 let xC = dyCorner.y + wC * uniforms.dilations[1];

                 if (xC >= 0 && xC < uniforms.xShape[2]) {
                   let val = getX(b, xR, xC, d) + getW(wR, wC, d);
                   if (val > curVal) {
                     curVal = val;
                     wRMax = wR;
                     wCMax = wC;
                   }
                 }
               }
             }
           }

           let flatIndexIn = d + uniforms.wShape[2] * (wCMax + wRMax * uniforms.wShape[1]);
           let value = getDy(b, r, c, d);
           ${Qr("&result[flatIndexIn]", "value", this.type)}
         }
       }
     `;
  }
};
function Xue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s, dy: a } = e, { strides: i, pad: p, dilations: u } = o, c = w.computeDilation2DInfo(n.shape, s.shape, i, p, "NHWC", u), l = s.dtype, m = new Px(c, s.shape, l), d = [{ type: "int32", data: [c.filterHeight, c.filterWidth] }, { type: "int32", data: [c.padInfo.top, c.padInfo.left] }, { type: "int32", data: [c.strideHeight, c.strideWidth] }, { type: "int32", data: [c.dilationHeight, c.dilationWidth] }, { type: "int32", data: [y.sizeFromShape(c.outShape)] }], f = vt({ backend: t10, attrs: { shape: s.shape, value: 0, dtype: l } });
  return t10.runWebGPUProgram(m, [n, s, a], l, d, f);
}
var jV = { kernelName: Li, backendName: "webgpu", kernelFunc: Xue };
function Yue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s, dy: a } = e, { strides: i, pad: p, dilations: u } = o, c = w.computeDilation2DInfo(n.shape, s.shape, i, p, "NHWC", u), l = n.dtype, m = new Fx(c, l), d = [{ type: "int32", data: [c.filterHeight, c.filterWidth] }, { type: "int32", data: [c.padInfo.top, c.padInfo.left] }, { type: "int32", data: [c.strideHeight, c.strideWidth] }, { type: "int32", data: [c.dilationHeight, c.dilationWidth] }, { type: "int32", data: [y.sizeFromShape(c.outShape)] }], f = vt({ backend: t10, attrs: { shape: c.inShape, value: 0, dtype: l } });
  return t10.runWebGPUProgram(m, [n, s, a], l, d, f);
}
var XV = { kernelName: Mi, backendName: "webgpu", kernelFunc: Yue };
var Ox = class {
  constructor(e, t10, o) {
    this.variableNames = ["Image"], this.uniforms = "alpha: f32,", this.workgroupSize = [64, 1, 1], this.pixelsOpType = wi.DRAW, this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.type = t10, this.textureFormat = o, this.shaderKey = `draw_${t10}_${o}`;
  }
  getUserCode() {
    let e, t10 = this.type === "float32" ? "value" : "value / 255.0";
    return e = `
      if (uniforms.numChannels == 1) {
        rgba[0] = ${t10};
        rgba[1] = ${t10};
        rgba[2] = ${t10};
      } else {
        rgba[d] = ${t10};
      }`, `
       @group(0) @binding(0) var outImage : texture_storage_2d<${this.textureFormat}, write>;
       ${G("index")} {
         if (index < uniforms.size) {
           var rgba = vec4<f32>(0.0, 0.0, 0.0, uniforms.alpha);
           for (var d = 0; d < uniforms.numChannels; d = d + 1) {
             let value = f32(inBuf[index * uniforms.numChannels + d]);
             ${e}
           }
           rgba.x = rgba.x * rgba.w;
           rgba.y = rgba.y * rgba.w;
           rgba.z = rgba.z * rgba.w;
           let coords = getCoordsFromIndex(index);
           textureStore(outImage, vec2<i32>(coords.yx), rgba);
         }
       }
      `;
  }
};
function Que(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { image: n } = e, { canvas: s, options: a } = o, [i, p] = n.shape.slice(0, 2), { imageOptions: u } = a || {}, c = (u == null ? void 0 : u.alpha) || 1, l = t10.device.features.has("bgra8unorm-storage") ? "bgra8unorm" : "rgba8unorm", m = [i, p], d = new Ox(m, n.dtype, l);
  s.width = p, s.height = i;
  let f = "webgpu", h = s.getContext(f), g;
  h || (g = new OffscreenCanvas(p, i), h = g.getContext(f));
  let x = n.shape.length === 3 ? n.shape[2] : 1;
  h.configure({ device: t10.device, format: l, usage: GPUTextureUsage.STORAGE_BINDING, alphaMode: "premultiplied" });
  let b = "int32", C = t10.makeTensorInfo(m, b), S = t10.tensorMap.get(C.dataId);
  S.resource = h.getCurrentTexture(), S.external = true;
  let k = [{ type: "uint32", data: [x] }, { type: "float32", data: [c] }];
  if (t10.runWebGPUProgram(d, [n], b, k, C), g) {
    let _ = s.getContext("2d");
    if (!_) throw new Error("Please make sure this canvas has only been used for 2d or webgpu context!");
    _.drawImage(g, 0, 0);
  }
  return t10.disposeData(C.dataId), n;
}
var YV = { kernelName: $u, backendName: "webgpu", kernelFunc: Que };
var i0 = et({ opType: fe.MUL, cpuKernelImpl: Rz, supportsComplex: true });
var QV = { kernelName: Xn, backendName: "webgpu", kernelFunc: i0 };
function u0(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o;
  return eo(n, s, a, "sum", t10);
}
var ZV = { kernelName: "Sum", backendName: "webgpu", kernelFunc: u0 };
function Zue(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { equation: n } = o, s = e, { allDims: a, summedDims: i, idDims: p } = w.decodeEinsumEquation(n, s.length);
  w.checkEinsumDimSizes(a.length, p, s);
  let { path: u, steps: c } = w.getEinsumComputePath(i, p), l = c.length, m = null, d = a.length, f = [];
  for (let h = 0; h < l; ++h) {
    for (let g of c[h]) {
      let { permutationIndices: x, expandDims: b } = w.getEinsumPermutation(d, p[g]), C;
      w.isIdentityPermutation(x) ? C = s[g] : (C = xr({ inputs: { x: s[g] }, backend: t10, attrs: { perm: x } }), f.push(C));
      let S = C.shape.slice();
      for (let k = 0; k < b.length; ++k) S.splice(b[k], 0, 1);
      y.arraysEqual(C.shape, S) || (C = pe({ inputs: { x: C }, backend: t10, attrs: { shape: S } }), f.push(C)), m === null ? m = C : (m = i0({ inputs: { a: C, b: m }, backend: t10 }), f.push(m));
    }
    h < l - 1 && (u[h] >= 0 && (m = u0({ inputs: { x: m }, backend: t10, attrs: { axis: u[h] - (a.length - d), keepDims: false } }), f.push(m)), d--);
  }
  for (let h of f) h !== m && t10.disposeData(h.dataId);
  return m;
}
var JV = { kernelName: Bi, backendName: "webgpu", kernelFunc: Zue };
var Jue = ye({ opType: Z.ELU });
var eW = { kernelName: "Elu", backendName: "webgpu", kernelFunc: Jue };
var epe = (r15) => {
  let { inputs: e, backend: t10 } = r15, { dy: o, y: n } = e, s = new Ii(fe.ELU_DER, o.shape, n.shape);
  return t10.runWebGPUProgram(s, [o, n], o.dtype);
};
var tW = { kernelName: Xa, backendName: "webgpu", kernelFunc: epe };
var tpe = et({ opType: fe.EQUAL, dtype: "bool", cpuKernelImpl: gz });
var rW = { kernelName: xn, backendName: "webgpu", kernelFunc: tpe };
var rpe = ye({ opType: Z.ERF });
var oW = { kernelName: "Erf", backendName: "webgpu", kernelFunc: rpe };
var ope = ye({ opType: Z.EXP, cpuKernelImpl: xz, dtype: "float32" });
var nW = { kernelName: "Exp", backendName: "webgpu", kernelFunc: ope };
function Mx(r15) {
  let { inputs: e, attrs: t10, backend: o } = r15, { dim: n } = t10, { input: s } = e, a = s.shape.length, i = s.shape.slice(), p = n;
  return n < 0 && (y.assert(-(a + 1) <= n, () => `Axis must be in the interval [${-(a + 1)}, ${a}]`), p = a + n + 1), i.splice(p, 0, 1), pe({ inputs: { x: s }, backend: o, attrs: { shape: i } });
}
var sW = { kernelName: na, backendName: "webgpu", kernelFunc: Mx };
var npe = ye({ opType: Z.EXPM1, cpuKernelImpl: yz });
var aW = { kernelName: bn, backendName: "webgpu", kernelFunc: npe };
var ym = class {
  constructor(e, t10) {
    this.variableNames = ["real", "imag"], this.outputShape = [], this.uniforms = "exponentMultiplier : f32, denominator: f32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = t10, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.component = e, this.shaderKey = `fft_${e}`;
  }
  getUserCode() {
    return `
    fn unaryOpComplex(real: f32, expR: f32, imag: f32, expI: f32) -> f32 {
      ${this.component === "real" ? "return real * expR - imag * expI;" : "return real * expI + imag * expR;"}
    }

    fn mulMatDFT(batch: i32, index: i32) -> f32 {
      let indexRatio = f32(index) / f32(uniforms.realShape[1]);
      let exponentMultiplierTimesIndexRatio =
          uniforms.exponentMultiplier * indexRatio;

      var result = 0.0;

      for (var i = 0; i < uniforms.realShape[1]; i = i + 1) {
        // x = (-2|2 * PI / N) * index * i;
        let x = exponentMultiplierTimesIndexRatio * f32(i);
        let expR = cos(x);
        let expI = sin(x);
        let real = getReal(batch, i);
        let imag = getImag(batch, i);

        result = result +
            unaryOpComplex(real, expR, imag, expI) / uniforms.denominator;
      }

      return result;
    }

    ${G("index")} {
      if (index < uniforms.size) {
        let coords = getOutputCoords();
        setOutputAtIndex(index, mulMatDFT(coords[0], coords[1]));
      }
    }
  `;
  }
};
function Lx(r15, e, t10) {
  let o = t10.tensorMap.get(r15.dataId), n = y.sizeFromShape(r15.shape), s = r15.shape[r15.shape.length - 1], a = n / s, i = [], p = pe({ inputs: { x: r15 }, backend: t10, attrs: { shape: [a, s] } });
  i.push(p);
  let u = p.shape, c = new ym("real", u), l = new ym("imag", u), m = [{ dataId: o.complexTensorInfos.real.dataId, dtype: o.complexTensorInfos.real.dtype, shape: u }, { dataId: o.complexTensorInfos.imag.dataId, dtype: o.complexTensorInfos.imag.dtype, shape: u }], d = e ? 2 * Math.PI : -2 * Math.PI, f = e ? u[1] : 1, h = [{ type: "float32", data: [d] }, { type: "float32", data: [f] }], g = t10.runWebGPUProgram(c, m, "float32", h);
  i.push(g);
  let x = t10.runWebGPUProgram(l, m, "float32", h);
  i.push(x);
  let b = xo({ inputs: { real: g, imag: x }, backend: t10 });
  i.push(b);
  let C = pe({ inputs: { x: b }, backend: t10, attrs: { shape: r15.shape } });
  return i.forEach((S) => t10.disposeData(S.dataId)), C;
}
function spe(r15) {
  let { inputs: e, backend: t10 } = r15, { input: o } = e;
  return Lx(o, false, t10);
}
var iW = { kernelName: "FFT", backendName: "webgpu", kernelFunc: spe };
var Bx = class {
  constructor(e) {
    this.outputShape = [], this.variableNames = ["x"], this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "flipLeftRight";
  }
  getUserCode() {
    return `
      ${G("index")} {
        if (index < uniforms.size) {
          let coords = getCoordsFromIndex(index);
          let coordX = uniforms.xShape[2] - coords[2] - 1;
          let outputValue = getX(coords[0], coords[1], coordX, coords[3]);
          setOutputAtIndex(index, outputValue);
        }
      }
    `;
  }
};
var uW = { kernelName: Cn, backendName: "webgpu", kernelFunc: ({ inputs: r15, backend: e }) => {
  let { image: t10 } = r15, o = e, n = new Bx(t10.shape);
  return o.runWebGPUProgram(n, [t10], t10.dtype);
} };
var ape = ye({ opType: Z.FLOOR, cpuKernelImpl: bz });
var pW = { kernelName: wn, backendName: "webgpu", kernelFunc: ape };
var ipe = et({ opType: fe.FLOOR_DIV, cpuKernelImpl: Cz, dtype: "int32" });
var cW = { kernelName: Sn, backendName: "webgpu", kernelFunc: ipe };
var zx = class {
  constructor(e, t10, o = false) {
    this.pixelsOpType = wi.FROM_PIXELS, this.outputShape = [0], this.variableNames = [], this.workgroupSize = [256, 1, 1], this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize, [t10, 1, 1]), this.importVideo = o, this.shaderKey = `fromPixels_${this.importVideo}`;
  }
  getUserCode() {
    let e = this.importVideo ? "textureLoad(src, vec2<i32>(coords.yx));" : "textureLoad(src, vec2<i32>(coords.yx), 0)";
    return `
      @binding(1) @group(0) var src: ${this.importVideo ? "texture_external" : "texture_2d<f32>"};
      ${G("index")} {
        let flatIndex = index * uniforms.numChannels;
        if (flatIndex < uniforms.size) {
          let coords = getCoordsFromIndex(flatIndex);
          let values = ${e};
          for (var i = 0; i < uniforms.numChannels; i = i + 1) {
            result[flatIndex + i] = i32(floor(255.0 * values[i]));
          }
        }
      }
  `;
  }
};
var lW = { kernelName: Du, backendName: "webgpu", kernelFunc: upe };
var tl;
var p0 = A().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");
function upe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { pixels: n } = e, { numChannels: s } = o;
  if (n == null) throw new Error("pixels passed to tf.browser.fromPixels() can not be null");
  let a = typeof HTMLVideoElement != "undefined" && n instanceof HTMLVideoElement, i = typeof HTMLImageElement != "undefined" && n instanceof HTMLImageElement, p = typeof HTMLCanvasElement != "undefined" && n instanceof HTMLCanvasElement || typeof OffscreenCanvas != "undefined" && n instanceof OffscreenCanvas, u = typeof ImageBitmap != "undefined" && n instanceof ImageBitmap, [c, l] = a ? [n.videoWidth, n.videoHeight] : [n.width, n.height], m = [l, c, s], d = A().getBool("WEBGPU_IMPORT_EXTERNAL_TEXTURE") && a, f = a || i;
  if (u || p || f) {
    let b;
    if (d) b = t10.device.importExternalTexture({ source: n });
    else {
      if (f) {
        let L = A().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");
        (tl == null || L !== p0) && (p0 = L, tl = document.createElement("canvas").getContext("2d", { willReadFrequently: p0 })), tl.canvas.width = c, tl.canvas.height = l, tl.drawImage(n, 0, 0, c, l), n = tl.canvas;
      }
      let P = GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING, M = t10.textureManager.acquireTexture(m[1], m[0], "rgba8unorm", P);
      t10.queue.copyExternalImageToTexture({ source: n }, { texture: M }, [m[1], m[0]]), b = M;
    }
    let C = y.sizeFromShape(m), S = y.computeStrides(m), k = new zx(m, s, d), _ = [{ type: "uint32", data: [C] }, { type: "uint32", data: [s] }, { type: "uint32", data: [...S] }], $ = t10.makeTensorInfo([l, c], "int32"), R = t10.tensorMap.get($.dataId);
    R.resource = b;
    let D = t10.runWebGPUProgram(k, [$], "int32", _);
    return t10.disposeData($.dataId), D;
  }
  let h = n.data, g = h;
  if (s != null && s !== 4) {
    g = new Uint8Array(n.width * n.height * s);
    let b = h.length, C = 0;
    for (let S = 0; S < b; S++) S % 4 < s && (g[C++] = h[S]);
  }
  let x = t10.makeTensorInfo(m, "int32", new Int32Array(g));
  return t10.uploadToGPU(x.dataId), x;
}
var Vx = class {
  constructor(e, t10, o, n, s) {
    this.uniforms = "varianceEpsilon : f32,", this.workgroupSize = [128, 1, 1], this.size = true, this.variableNames = ["x", "mean", "variance"], w.assertAndGetBroadcastShape(e, t10), w.assertAndGetBroadcastShape(e, o), this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), n != null && (w.assertAndGetBroadcastShape(e, n), this.variableNames.push("offset")), s != null && (w.assertAndGetBroadcastShape(e, s), this.variableNames.push("scale")), this.offsetShape = n, this.scaleShape = s, this.shaderKey = "batchNorm";
  }
  getUserCode() {
    let e = "0.0";
    this.offsetShape != null && (e = "getOffsetByOutputIndex(index)");
    let t10 = "1.0";
    return this.scaleShape != null && (t10 = "getScaleByOutputIndex(index)"), `
      ${G("index")} {
        if (index < uniforms.size)
        {
          let xValue = getXByOutputIndex(index);
          let meanValue = getMeanByOutputIndex(index);
          let varianValue = getVarianceByOutputIndex(index);
          let offsetValue = ${e};
          let scaleValue = ${t10};
          let inv = scaleValue * inverseSqrt(varianValue + f32(uniforms.varianceEpsilon));
          setOutputAtIndex(index,dot(vec3<f32>(xValue, -meanValue, offsetValue), vec3<f32>(inv, inv, 1.0)));
        }
      }
  `;
  }
};
var mW = { kernelName: In, backendName: "webgpu", kernelFunc: ({ inputs: r15, attrs: e, backend: t10 }) => {
  let { x: o, scale: n, offset: s, mean: a, variance: i } = r15, { varianceEpsilon: p } = e, u = t10, c = [o, a, i], l = null;
  s != null && (l = s.shape, c.push(s));
  let m = null;
  n != null && (m = n.shape, c.push(n));
  let d = new Vx(o.shape, a.shape, i.shape, l, m), f = [{ type: "float32", data: [p] }];
  return u.runWebGPUProgram(d, c, o.dtype, f);
} };
function ppe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s, bias: a, preluActivationWeights: i } = e, { strides: p, pad: u, dataFormat: c, dilations: l, dimRoundingMode: m, activation: d, leakyreluAlpha: f } = o, h = w.convertConv2DDataFormat(c), g = w.computeConv2DInfo(n.shape, s.shape, p, l, u, m, false, h);
  return bx({ x: n, filter: s, convInfo: g, backend: t10, bias: a, preluActivationWeights: i, leakyreluAlpha: f, activation: d });
}
var dW = { kernelName: Io, backendName: "webgpu", kernelFunc: ppe };
function cpe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, filter: s, bias: a, preluActivationWeights: i } = e, { strides: p, pad: u, dilations: c, dimRoundingMode: l, activation: m, leakyreluAlpha: d } = o, f = c;
  f == null && (f = [1, 1]), y.assert(w.eitherStridesOrDilationsAreOne(p, f), () => `Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${p} and dilations '${f}'`);
  let h = w.computeConv2DInfo(n.shape, s.shape, p, f, u, l, true), g = [n, s], x = a != null, b = i != null;
  x && g.push(a), b && g.push(i);
  let C = [{ type: "int32", data: [h.padInfo.top, h.padInfo.left] }, { type: "int32", data: [h.inHeight, h.inWidth] }], S;
  return h.outHeight > 4 && h.outWidth > 4 && h.strideWidth <= 2 && h.inChannels === h.outChannels && h.dilationHeight === 1 && h.dilationWidth === 1 && h.inChannels % 4 === 0 ? (S = new Jc(h, x, m, b), C.push({ type: "int32", data: [S.virtualWidth] })) : (S = new el(h, x, m, b), C.push({ type: "int32", data: [h.filterHeight] }, { type: "int32", data: [h.filterWidth] }, { type: "int32", data: [h.strideHeight, h.strideWidth] }, { type: "int32", data: [h.dilationHeight, h.dilationWidth] })), m === "leakyrelu" && (C.push({ type: "float32", data: [d] }), S.uniforms += " alpha : f32,"), t10.runWebGPUProgram(S, g, "float32", C);
}
var fW = { kernelName: vo, backendName: "webgpu", kernelFunc: cpe };
var Wx = class {
  constructor(e, t10) {
    this.variableNames = ["A", "indices"], this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = t10, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = `gathernd_${e}`, this.sliceDim = e, this.uniforms = `sliceDim : i32, strides : ${ft(e)},`;
  }
  getUserCode() {
    let e;
    return this.sliceDim > 1 ? e = "uniforms.strides[j]" : e = "uniforms.strides", `
      ${G("index")} {
        if (index < uniforms.size) {
          let coords = getCoordsFromIndex(index);
          var flattenIndex = 0;
          for (var j = 0; j < uniforms.sliceDim; j = j + 1) {
            let indexTemp = i32(round(getIndices(coords[0], j)));
            let strideNum = ${e};
            flattenIndex = flattenIndex + indexTemp * strideNum;
          }

          setOutputAtIndex(index, getA(flattenIndex, coords[1]));
        }
      }
      `;
  }
};
function lpe(r15) {
  let { inputs: e, backend: t10 } = r15, { params: o, indices: n } = e, s = n.shape, a = s[s.length - 1], i = y.sizeFromShape(o.shape), [p, u, c, l] = w.prepareAndValidate(o, n), m = pe({ inputs: { x: n }, backend: t10, attrs: { shape: [u, a] } }), d = pe({ inputs: { x: o }, backend: t10, attrs: { shape: [y.sizeFromShape(o.shape) / c, c] } });
  if (t10.shouldExecuteOnCPU([o, n]) || o.dtype === "string") {
    let b = t10.readSync(n.dataId), C = t10.bufferSync(o), S = wz(b, C, o.dtype, u, a, c, l, o.shape, i);
    return t10.makeTensorInfo(p, o.dtype, S.values);
  }
  let f = new Wx(a, [u, c]), h = [{ type: "int32", data: [a] }, { type: "int32", data: l }], g = t10.runWebGPUProgram(f, [d, m], d.dtype, h), x = pe({ inputs: { x: g }, backend: t10, attrs: { shape: p } });
  return t10.disposeData(m.dataId), t10.disposeData(d.dataId), t10.disposeData(g.dataId), x;
}
var hW = { kernelName: vn, backendName: "webgpu", kernelFunc: lpe };
var Ux = class {
  constructor(e, t10) {
    this.variableNames = ["A", "indices"], this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e.slice(), this.aShape = e, this.outputShape = t10, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "gather";
  }
  getUserCode() {
    let e = mpe(this.aShape);
    return `
      ${G("index")} {
        if (index < uniforms.size) {
          let resRC = getCoordsFromIndex(index);
          let indexZ = i32(getIndices(resRC.x, resRC.z));
          let inBounds = select(0.0, 1.0, indexZ >= 0 && indexZ < uniforms.aShape[2]);
          setOutputAtIndex(index, inBounds * getA(${e}));
        }
      }
    `;
  }
};
function mpe(r15) {
  let e = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], t10 = [];
  for (let o = 0; o < r15.length; o++) o === 2 ? t10.push("indexZ") : t10.push(`${e[o]}`);
  return t10.join();
}
function c0(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, indices: s } = e, { axis: a, batchDims: i } = o, p = y.parseAxisParam(a, n.shape)[0], u = w.segment_util.collectGatherOpShapeInfo(n, s, p, i), c = y.sizeFromShape(s.shape), l = [], m = pe({ inputs: { x: n }, backend: t10, attrs: { shape: [u.batchSize, u.outerSize, u.dimSize, u.sliceSize] } }), d = pe({ inputs: { x: s }, backend: t10, attrs: { shape: [u.batchSize, c / u.batchSize] } });
  l.push(m), l.push(d);
  let f = [u.batchSize, u.outerSize, c / u.batchSize, u.sliceSize];
  if (t10.shouldExecuteOnCPU([n, s])) {
    let C = t10.tensorMap.get(d.dataId).values, S = me(d.shape, d.dtype, C), _ = t10.tensorMap.get(m.dataId).values, $ = me(m.shape, m.dtype, _), R = Sz($, S, f);
    return l.forEach((D) => t10.disposeData(D.dataId)), t10.makeTensorInfo(u.outputShape, R.dtype, R.values);
  }
  let h = new Ux(m.shape, f), g = t10.runWebGPUProgram(h, [m, d], m.dtype);
  l.push(g);
  let x = pe({ inputs: { x: g }, backend: t10, attrs: { shape: u.outputShape } });
  return l.forEach((b) => t10.disposeData(b.dataId)), x;
}
var gW = { kernelName: aa, backendName: "webgpu", kernelFunc: c0 };
var dpe = et({ opType: fe.GREATER, cpuKernelImpl: vz, dtype: "bool" });
var xW = { kernelName: kn, backendName: "webgpu", kernelFunc: dpe };
var fpe = et({ opType: fe.GREATER_EQUAL, dtype: "bool", cpuKernelImpl: Iz });
var yW = { kernelName: Nn, backendName: "webgpu", kernelFunc: fpe };
function hpe(r15) {
  let { inputs: e, backend: t10 } = r15, { input: o } = e;
  return Lx(o, true, t10);
}
var bW = { kernelName: Vi, backendName: "webgpu", kernelFunc: hpe };
var gpe = ye({ opType: Z.IS_FINITE, dtype: "bool" });
var CW = { kernelName: Tn, backendName: "webgpu", kernelFunc: gpe };
var xpe = ye({ opType: Z.IS_INF, dtype: "bool" });
var wW = { kernelName: _n, backendName: "webgpu", kernelFunc: xpe };
var ype = ye({ opType: Z.IS_NAN, dtype: "bool" });
var SW = { kernelName: En, backendName: "webgpu", kernelFunc: ype };
function bpe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { alpha: s } = o, a = [{ type: "float32", data: [s] }], i = new Jr(n.shape, Z.LEAKYRELU, "alpha : f32,");
  return t10.runWebGPUProgram(i, [n], "float32", a);
}
var IW = { kernelName: $n, backendName: "webgpu", kernelFunc: bpe };
var Cpe = et({ opType: fe.LESS, dtype: "bool", cpuKernelImpl: Nz });
var vW = { kernelName: Rn, backendName: "webgpu", kernelFunc: Cpe };
var wpe = et({ opType: fe.LESS_EQUAL, dtype: "bool", cpuKernelImpl: kz });
var kW = { kernelName: Dn, backendName: "webgpu", kernelFunc: wpe };
var Gx = class {
  constructor(e) {
    this.variableNames = [], this.outputShape = [], this.uniforms = "start : f32, step : f32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = [e], this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "linSpace";
  }
  getUserCode() {
    return `
      ${G("index")} {
        if (index < uniforms.size) {
          setOutputAtIndex(index, uniforms.start + f32(index) * uniforms.step);
        }
      }
    `;
  }
};
function Spe(r15) {
  let { backend: e, attrs: t10 } = r15, { start: o, stop: n, num: s } = t10, a = (n - o) / (s - 1), i = new Gx(s), p = [{ type: "float32", data: [o] }, { type: "float32", data: [a] }];
  return e.runWebGPUProgram(i, [], "float32", p);
}
var NW = { kernelName: An, backendName: "webgpu", kernelFunc: Spe };
var Ipe = ye({ opType: Z.LOG, cpuKernelImpl: Tz });
var TW = { kernelName: "Log", backendName: "webgpu", kernelFunc: Ipe };
var vpe = ye({ opType: Z.LOG1P });
var _W = { kernelName: Pn, backendName: "webgpu", kernelFunc: vpe };
var kpe = et({ opType: fe.LOGICAL_AND, dtype: "bool" });
var EW = { kernelName: On, backendName: "webgpu", kernelFunc: kpe };
var Npe = ye({ opType: Z.LOGICAL_NOT });
var $W = { kernelName: Mn, backendName: "webgpu", kernelFunc: Npe };
var Tpe = et({ opType: fe.LOGICAL_OR });
var RW = { kernelName: Ln, backendName: "webgpu", kernelFunc: Tpe };
var DW = `
  var powValue = 0.0;
  let basis = uniforms.bias + uniforms.alpha * sum;
  if (uniforms.beta == 0.5) {
    powValue = inverseSqrt(basis);
  } else if (uniforms.beta == 1.0) {
    powValue = 1.0 / basis;
  } else {
    powValue = exp(log(basis) * (-uniforms.beta));
  }
`;
var Hx = class {
  constructor(e) {
    this.outputShape = [], this.variableNames = ["x"], this.uniforms = "radius : i32, bias : f32, alpha : f32, beta : f32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "lrn";
  }
  getUserCode() {
    return `
    ${G("index")} {
      if (index < uniforms.size) {
        let coords = getOutputCoords();
        let b = coords[0];
        let r = coords[1];
        let c = coords[2];
        let d = coords[3];

        let x = getX(b, r, c, d);
        var sum = 0.0;
        for (var i = -uniforms.radius; i <= uniforms.radius; i = i + 1) {
          let idx = d + i;
          if (idx >= 0 && idx < uniforms.xShape[3]) {
            let z = getX(b, r, c, idx);
            sum = sum + z * z;
          }
        }
        ${DW}

        setOutputAtIndex(index, x * powValue);
      }
    }
  `;
  }
};
var Kx = class {
  constructor(e, t10) {
    this.outputShape = [], this.variableNames = ["x"], this.uniforms = "radius : i32, bias : f32, alpha : f32, beta : f32,", this.workgroupSize = [256, 1, 1], this.maxAllowRadius = 16, y.assert(t10 <= this.maxAllowRadius, () => `Radius must be less than or equal to ${this.maxAllowRadius}, current radius is ${t10}`), this.outputShape = e, this.elementsPerWorkgroup = this.workgroupSize[0] - 2 * this.maxAllowRadius, this.dispatchLayout = { x: [3], y: [2], z: [0, 1] }, this.dispatch = H(this.dispatchLayout, this.outputShape, [this.elementsPerWorkgroup, this.workgroupSize[1], this.workgroupSize[2]]), this.shaderKey = "lrn_shared";
  }
  getUserCode() {
    return `
    var <workgroup>lrnSub: array<f32, ${this.workgroupSize[0]}>;
    const elementsPerWorkgroup = ${this.elementsPerWorkgroup};
    const maxAllowRadius = ${this.maxAllowRadius};

    ${G()} {
      let localDepth = i32(localId.x);
      let workgroupDepth = i32(workgroupId.x) * elementsPerWorkgroup;
      let xDepth = workgroupDepth + localDepth - maxAllowRadius;
      let b = i32(globalId.z) / uniforms.xShape[1];
      let r = i32(globalId.z) - b * uniforms.xShape[1];
      let c = i32(globalId.y);
      let d = workgroupDepth + localDepth;

      var x = 0.0;
      if (xDepth >= 0 && xDepth < uniforms.xShape[3]) {
        x = getX(b, r, c, xDepth);
      }
      lrnSub[localDepth] = x;
      workgroupBarrier();

      if (localDepth < elementsPerWorkgroup && d < uniforms.outShape[3]) {
        var sum = 0.0;
        let index = localDepth + maxAllowRadius;
        for (var i = -uniforms.radius; i <= uniforms.radius; i = i + 1) {
          let z = lrnSub[index + i];
          sum = sum + z * z;
        }
        ${DW}

        setOutputAtCoords(b, r, c, d, lrnSub[index] * powValue);
      }
    } `;
  }
};
function _pe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { depthRadius: s, bias: a, alpha: i, beta: p } = o, u;
  s > 16 ? u = new Hx(n.shape) : u = new Kx(n.shape, s);
  let c = [{ type: "int32", data: [s] }, { type: "float32", data: [a] }, { type: "float32", data: [i] }, { type: "float32", data: [p] }];
  return t10.runWebGPUProgram(u, [n], n.dtype, c);
}
var AW = { kernelName: "LRN", backendName: "webgpu", kernelFunc: _pe };
var qx = class {
  constructor(e) {
    this.outputShape = [], this.variableNames = ["inputImage", "outputImage", "dy"], this.uniforms = "depthRadius : i32, bias : f32, alpha : f32, beta : f32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "lrn_grad";
  }
  getUserCode() {
    return `
    ${G("index")} {
      if (index < uniforms.size) {
        let coords = getOutputCoords();
        let b = coords[0];
        let r = coords[1];
        let c = coords[2];

        let MIN_DEPTH_BEGIN = 0;
        let MAX_DEPTH_END = uniforms.outShape[3];
        var result = 0.0;
        for (var d = MIN_DEPTH_BEGIN; d < MAX_DEPTH_END; d++) {
          let depthBegin = max(MIN_DEPTH_BEGIN, d - uniforms.depthRadius);
          let depthEnd = min(MAX_DEPTH_END, d + uniforms.depthRadius + 1);

          var norm = 0.0;
          for (var 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 = uniforms.alpha * norm + uniforms.bias;

          for (var k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; k++) {
            if (k < depthBegin) {
              continue;
            } else if (k >= depthBegin && k < depthEnd) {
              var dyi = -2.0 * uniforms.alpha * uniforms.beta
                * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d) / norm;
              if (k == d) {
                dyi += pow(norm, -1.0 * uniforms.beta);
              }
              if (k == coords[3]) {
                dyi *= getDy(b, r, c, d);
                result += dyi;
              }
            } else {
              break;
            }
          }
        }

        setOutputAtIndex(index, result);
      }
    }
  `;
  }
};
function Epe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, y: s, dy: a } = e, { depthRadius: i, bias: p, alpha: u, beta: c } = o, l = new qx(n.shape), m = [{ type: "int32", data: [i] }, { type: "float32", data: [p] }, { type: "float32", data: [u] }, { type: "float32", data: [c] }];
  return t10.runWebGPUProgram(l, [n, s, a], n.dtype, m);
}
var FW = { kernelName: Ya, backendName: "webgpu", kernelFunc: Epe };
var $pe = et({ opType: fe.MAX, cpuKernelImpl: Ez });
var PW = { kernelName: Vn, backendName: "webgpu", kernelFunc: $pe };
function Rpe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { filterSize: s, strides: a, pad: i, dimRoundingMode: p } = o, c = w.computePool2DInfo(n.shape, s, a, 1, i, p);
  return ax(n, c, "max", t10);
}
var OW = { kernelName: Wn, backendName: "webgpu", kernelFunc: Rpe };
function Dpe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { filterSize: s, strides: a, pad: i, dataFormat: p, dimRoundingMode: u } = o, c = [1, 1, 1], l = w.computePool3DInfo(n.shape, s, a, c, i, u, p), m = new Iu(l, "max"), d = [{ type: "int32", data: [l.strideDepth, l.strideHeight, l.strideWidth] }, { type: "int32", data: [l.padInfo.front, l.padInfo.top, l.padInfo.left] }, { type: "int32", data: [l.inDepth, l.inHeight, l.inWidth] }, { type: "int32", data: [l.effectiveFilterDepth, l.effectiveFilterHeight, l.effectiveFilterWidth] }];
  return t10.runWebGPUProgram(m, [n], n.dtype, d);
}
var MW = { kernelName: ia, backendName: "webgpu", kernelFunc: Dpe };
var jx = class {
  constructor(e) {
    this.variableNames = ["dy", "maxPos"], this.uniforms = `strides : vec2<i32>, pads : vec2<i32>, dilations : vec2<i32>, filterDims : vec2<i32>,
       outHeight : i32, outWidth : i32`, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e.inShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "maxPool2DBackprop";
  }
  getUserCode() {
    return `
      ${G("index")} {
      if (index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
        let batch = coords[0];
        let d = coords[3];

        let dyRCCorner = vec2<i32>(coords.yz) - uniforms.pads;
        let dyRCorner = dyRCCorner.x;
        let 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.
        var dotProd = 0.0;
        let lastIndex = uniforms.filterDims[0] * uniforms.filterDims[1] - 1;
        for (var wR = 0; wR < uniforms.filterDims[0]; wR += uniforms.dilations[0]) {
          let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[0]);

          if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
            continue;
          }
          let idyR = i32(dyR);

          for (var wC = 0; wC < uniforms.filterDims[1]; wC += uniforms.dilations[1]) {
            let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[1]);

            if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
              continue;
            }
            let idyC = i32(dyC);

            let dyValue = getDy(batch, idyR, idyC, d);
            let maxPosValue = lastIndex - i32(getMaxPos(batch, idyR, idyC, d));

            // Get the current value, check it against the value from the
            // position matrix.
            let curPosValue = wR * uniforms.filterDims[1] + wC;
            let mask = select(0.0, 1.0, maxPosValue == curPosValue);
            dotProd += dyValue * mask;
          }
        }
        setOutputAtIndex(index, dotProd);
      }
    }
    `;
  }
};
var Xx = class {
  constructor(e) {
    this.variableNames = ["dy", "maxPos"], this.uniforms = `strides : vec3<i32>, pads : vec3<i32>, filterDims : vec3<i32>,
      outDepth : i32, outHeight : i32, outWidth : i32`, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e.inShape, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "maxPool3DBackprop";
  }
  getUserCode() {
    return `
      ${G("index")} {
      if (index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
        let batch = coords.x;
        let ch = coords.u;

        let dyCorner = vec3<i32>(coords.y, coords.z, coords.w) - uniforms.pads;
        let dyDCorner = dyCorner.x;
        let dyRCorner = dyCorner.y;
        let 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.
        var dotProd = 0.0;
        let lastIndex = uniforms.filterDims[0] * uniforms.filterDims[1] * uniforms.filterDims[2] - 1;

        for (var wD = 0; wD < uniforms.filterDims[0]; wD++) {
          let dyD = f32(dyDCorner + wD) / f32(uniforms.strides[0]);

          if (dyD < 0.0 || dyD >= f32(uniforms.outDepth) || fract(dyD) > 0.0) {
            continue;
          }
          let idyD = i32(dyD);

          for (var wR = 0; wR < uniforms.filterDims[1]; wR++) {
            let dyR = f32(dyRCorner + wR) / f32(uniforms.strides[1]);

            if (dyR < 0.0 || dyR >= f32(uniforms.outHeight) || fract(dyR) > 0.0) {
              continue;
            }
            let idyR = i32(dyR);

            for (var wC = 0; wC < uniforms.filterDims[2]; wC++) {
              let dyC = f32(dyCCorner + wC) / f32(uniforms.strides[2]);

              if (dyC < 0.0 || dyC >= f32(uniforms.outWidth) || fract(dyC) > 0.0) {
                continue;
              }
              let idyC = i32(dyC);

              let dyValue = getDy(batch, idyD, idyR, idyC, ch);
              let maxPosValue = lastIndex - i32(getMaxPos(batch, idyD, idyR, idyC, ch));

              // Get the current value, check it against the value from the
              // position matrix.
              let curPosValue = wD * uniforms.filterDims[1] * uniforms.filterDims[2] + wR * uniforms.filterDims[2] + wC;
              let mask = select(0.0, 1.0, maxPosValue == curPosValue);
              dotProd += dyValue * mask;
            }
          }
        }

        setOutputAtIndex(index, dotProd);
      }
    }
    `;
  }
};
function Ape(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s } = e, a = s, { filterSize: i, strides: p, pad: u, dimRoundingMode: c } = o, l = [1, 1, 1], m = w.computePool3DInfo(a.shape, i, p, l, u, c), d = new Iu(m, "max", true), f = [{ type: "int32", data: [m.strideDepth, m.strideHeight, m.strideWidth] }, { type: "int32", data: [m.padInfo.front, m.padInfo.top, m.padInfo.left] }, { type: "int32", data: [m.inDepth, m.inHeight, m.inWidth] }, { type: "int32", data: [m.effectiveFilterDepth, m.effectiveFilterHeight, m.effectiveFilterWidth] }], h = t10.runWebGPUProgram(d, [a], "int32", f), g = new Xx(m);
  f = [{ type: "int32", data: [m.strideDepth, m.strideHeight, m.strideWidth] }, { type: "int32", data: [m.effectiveFilterDepth - 1 - m.padInfo.front, m.effectiveFilterHeight - 1 - m.padInfo.top, m.effectiveFilterWidth - 1 - m.padInfo.left] }, { type: "int32", data: [m.effectiveFilterDepth, m.effectiveFilterHeight, m.effectiveFilterWidth] }, { type: "int32", data: [m.outDepth] }, { type: "int32", data: [m.outHeight] }, { type: "int32", data: [m.outWidth] }];
  let x = t10.runWebGPUProgram(g, [n, h], a.dtype, f);
  return t10.disposeData(h.dataId), x;
}
var LW = { kernelName: Gi, backendName: "webgpu", kernelFunc: Ape };
function Fpe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { dy: n, input: s, output: a } = e, i = s;
  fm([s, a], "maxPoolGrad");
  let { filterSize: p, strides: u, pad: c, dimRoundingMode: l } = o, m = w.computePool2DInfo(i.shape, p, u, 1, c, l), d = new Ba(m, "max", true), f = [{ type: "int32", data: [m.strideHeight, m.strideWidth] }, { type: "int32", data: [m.padInfo.top, m.padInfo.left] }, { type: "int32", data: [m.dilationHeight, m.dilationWidth] }, { type: "int32", data: [m.inHeight, m.inWidth] }, { type: "int32", data: [m.effectiveFilterHeight, m.effectiveFilterWidth] }], h = t10.runWebGPUProgram(d, [i], "int32", f), g = new jx(m);
  f = [{ type: "int32", data: [m.strideHeight, m.strideWidth] }, { type: "int32", data: [m.effectiveFilterHeight - 1 - m.padInfo.top, m.effectiveFilterWidth - 1 - m.padInfo.left] }, { type: "int32", data: [m.dilationHeight, m.dilationWidth] }, { type: "int32", data: [m.effectiveFilterHeight, m.effectiveFilterWidth] }, { type: "int32", data: [m.outHeight] }, { type: "int32", data: [m.outWidth] }];
  let x = t10.runWebGPUProgram(g, [n, h], i.dtype, f);
  return t10.disposeData(h.dataId), x;
}
var BW = { kernelName: Ui, backendName: "webgpu", kernelFunc: Fpe };
function Ppe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { filterSize: n, strides: s, pad: a, includeBatchInIndex: i } = o, { x: p } = e;
  y.assert(p.shape.length === 4, () => `Error in maxPool: input must be rank 4 but got rank ${p.shape.length}.`);
  let u = [1, 1];
  y.assert(w.eitherStridesOrDilationsAreOne(s, u), () => `Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);
  let c = w.computePool2DInfo(p.shape, n, s, u, a), l = [{ type: "int32", data: [c.strideHeight, c.strideWidth] }, { type: "int32", data: [c.padInfo.top, c.padInfo.left] }, { type: "int32", data: [c.dilationHeight, c.dilationWidth] }, { type: "int32", data: [c.inHeight, c.inWidth] }, { type: "int32", data: [c.effectiveFilterHeight, c.effectiveFilterWidth] }], m = new Ba(c, "max", false), d = t10.runWebGPUProgram(m, [p], p.dtype, l);
  m = new Ba(c, "max", true, true, i);
  let f = t10.runWebGPUProgram(m, [p], "int32", l);
  return [d, f];
}
var zW = { kernelName: ua, backendName: "webgpu", kernelFunc: Ppe };
function Ope(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o;
  return eo(n, s, a, "min", t10);
}
var VW = { kernelName: "Min", backendName: "webgpu", kernelFunc: Ope };
var Mpe = et({ opType: fe.MIN, cpuKernelImpl: $z });
var WW = { kernelName: Hn, backendName: "webgpu", kernelFunc: Mpe };
var Yx = class {
  constructor(e, t10, o) {
    this.uniforms = "", this.variableNames = ["x"], this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = t10.map((n, s) => n[0] + e[s] + n[1]), this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.xShape = e, t10.map((n, s) => {
      this.uniforms += ` pad${s} : vec2<i32>,`;
    }), this.offset = o === "reflect" ? 0 : 1, this.shaderKey = `mirrorPad_${o}`;
  }
  getUserCode() {
    let e = this.xShape.length, t10 = this.xShape.map((u, c) => `uniforms.pad${c}[0]`).join(","), o = this.xShape.map((u, c) => `uniforms.pad${c}[0] + uniforms.xShape${e > 1 ? `[${c}]` : ""}`).join(","), n = e === 1 ? "start" : "start[i]", s = e === 1 ? "end" : "end[i]", a = e === 1 ? "outC" : "outC[i]", i = ft(e), p = e > 1 ? ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, e) : "coords";
    return `
      ${G("index")} {
        if (index < uniforms.size) {
          let start = ${i}(${t10});
          let end = ${i}(${o});
          var outC = getCoordsFromIndex(index);
          for (var i = 0; i < ${e}; i = i + 1) {
            if (${a} < ${n}) {
              ${a} = ${n} * 2 - ${a} - ${this.offset};
            } else if(${a} >= ${s}) {
              ${a} = (${s} - 1) * 2 - ${a} + ${this.offset};
            }
          }
          let coords = outC - start;
          setOutputAtIndex(index, getX(${p}));
        }
      }
    `;
  }
};
var UW = { kernelName: Kn, backendName: "webgpu", kernelFunc: ({ inputs: r15, attrs: e, backend: t10 }) => {
  let { x: o } = r15, { paddings: n, mode: s } = e, a = t10, i = n.map((c) => ({ type: "int32", data: [c[0], c[1]] })), p = new Yx(o.shape, n, s);
  return a.runWebGPUProgram(p, [o], o.dtype, i);
} };
var Lpe = et({ opType: fe.MOD });
var GW = { kernelName: "Mod", backendName: "webgpu", kernelFunc: Lpe };
var Qx = class {
  constructor(e, t10) {
    this.variableNames = ["probs"], this.outputShape = [], this.uniforms = "seed : f32, numOutcomes: i32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = [e, t10], this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "multinomial";
  }
  getUserCode() {
    return `
    //Based on the work of Dave Hoskins
    //https://www.shadertoy.com/view/4djSRW
    fn random (seed : f32, resultUV : vec2<f32>) -> f32 {
      let HASHSCALE1 = 443.8975;
      let p = resultUV * seed;
      var p3  = fract(vec3<f32>(p.xyx) * HASHSCALE1);
      p3 = p3 + dot(p3, p3.yzx + 19.19);
      return fract((p3.x + p3.y) * p3.z);
    }

    ${G("index")} {
      if (index < uniforms.size) {
        let coords = getOutputCoords();
        let batch = coords[0];

        let resUV = vec2<f32>(f32(coords[1]) / f32(uniforms.outShape[1]),
            f32(coords[0]) / f32(uniforms.outShape[0]));
        let r = random(uniforms.seed, resUV);
        var cdf = 0.0;
        for (var i = 0; i < uniforms.numOutcomes - 1; i = i + 1) {
          cdf = cdf + getProbs(batch, i);

          if (r < cdf) {
            setOutputAtIndexI32(index, i);
            return;
          }
        }

        // If no other event happened, last event happened.
        setOutputAtIndexI32(index, uniforms.numOutcomes - 1);
      }
    }
  `;
  }
};
var Zx = class {
  constructor(e) {
    this.variableNames = ["logits"], this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = [this.outputShape[0], 1, 1], this.outputShape[1] >= 4096 ? this.workgroupSize = [256, 1, 1] : this.workgroupSize = [64, 1, 1], this.shaderKey = "softmax";
  }
  getUserCode() {
    return `
    var<workgroup> buf : array<f32, ${this.workgroupSize[0]}>;
    var<workgroup> rowMaxShared : f32;
    var<workgroup> rowSumShared : f32;
    const blockSize = ${this.workgroupSize[0]};
    ${G("index")} {
      let row = index / blockSize;
      let tid = i32(localId.x);
      let cols = uniforms.outShape[1];

      var threadMax = -3.402823e+38f;
      for (var col = tid; col < cols; col += blockSize) {
        let value = getLogits(row, col);
        threadMax = max(threadMax, value);
      }
      if (tid < cols) {
        buf[tid] = threadMax;
      }
      workgroupBarrier();

      var reduceSize = min(cols, blockSize);
      for (var currSize = reduceSize >> 1;  currSize > 0; currSize = reduceSize >> 1) {
        reduceSize = currSize + (reduceSize & 1);
        if (tid < currSize) {
          buf[tid] = max(buf[tid], buf[tid + reduceSize]);
        }
        workgroupBarrier();
      }

      if (tid == 0) {
        rowMaxShared = buf[0];
      }
      workgroupBarrier();

      var threadSum = 0.0;
      for (var col = tid; col < cols; col += blockSize) {
        let subExp = exp(getLogits(row, col) - rowMaxShared);
        threadSum += subExp;
      }
      buf[tid] = threadSum;
      workgroupBarrier();

      for (var currSize = blockSize >> 1;  currSize > 0; currSize = currSize >> 1) {
        if (tid < currSize) {
          buf[tid] = buf[tid] + buf[tid + currSize];
        }
        workgroupBarrier();
      }

      if (tid == 0) {
        rowSumShared = buf[0];
      }
      workgroupBarrier();

      for (var col = tid; col < cols; col += blockSize) {
        let value = exp(getLogits(row, col) - rowMaxShared) / rowSumShared;
        setOutputAtCoords(row, col, value);
      }
  }
    `;
  }
};
function l0(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { logits: n } = e, { dim: s } = o, a = pe({ inputs: { x: n }, backend: t10, attrs: { shape: [y.sizeFromShape(n.shape) / n.shape[s], n.shape[s]] } }), i = new Zx(a.shape), p = t10.runWebGPUProgram(i, [a], n.dtype), u = pe({ inputs: { x: p }, backend: t10, attrs: { shape: n.shape } });
  return t10.disposeData(a.dataId), t10.disposeData(p.dataId), u;
}
var HW = { kernelName: Is, backendName: "webgpu", kernelFunc: l0 };
function Bpe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { logits: n } = e, { numSamples: s, seed: a, normalized: i } = o, p = i ? n : l0({ inputs: { logits: n }, backend: t10, attrs: { dim: n.shape.length - 1 } }), u = p.shape[0], c = p.shape[1], l = new Qx(u, s), m = [{ type: "float32", data: [a] }, { type: "int32", data: [c] }], d = t10.runWebGPUProgram(l, [p], "int32", m);
  return i || t10.disposeData(p.dataId), d;
}
var KW = { kernelName: jn, backendName: "webgpu", kernelFunc: Bpe };
function zpe(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e;
  if (t10.shouldExecuteOnCPU([o])) {
    let s = t10.tensorMap.get(o.dataId), [a, i] = Dz(s.values, o.shape, o.dtype);
    return t10.makeTensorInfo(i, o.dtype, a);
  }
  let n = new Jr(o.shape, Z.NEG);
  return t10.runWebGPUProgram(n, [o], o.dtype);
}
var qW = { kernelName: "Neg", backendName: "webgpu", kernelFunc: zpe };
function Vpe(r15) {
  console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
  let { inputs: e, backend: t10, attrs: o } = r15, { boxes: n, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: p } = o, u = t10.readSync(n.dataId), c = t10.readSync(s.dataId), { selectedIndices: l } = Vt.nonMaxSuppressionV3Impl(u, c, a, i, p);
  return t10.makeTensorInfo([l.length], "int32", new Int32Array(l));
}
var jW = { kernelName: Qn, backendName: "webgpu", kernelFunc: Vpe };
function Wpe(r15) {
  console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");
  let { inputs: e, backend: t10, attrs: o } = r15, { boxes: n, scores: s } = e, { maxOutputSize: a, iouThreshold: i, scoreThreshold: p, softNmsSigma: u } = o, c = t10.readSync(n.dataId), l = t10.readSync(s.dataId), m = a, d = i, f = p, h = u, { selectedIndices: g, selectedScores: x } = Vt.nonMaxSuppressionV5Impl(c, l, m, d, f, h);
  return [t10.makeTensorInfo([g.length], "int32", new Int32Array(g)), t10.makeTensorInfo([x.length], "float32", new Float32Array(x))];
}
var XW = { kernelName: Zn, backendName: "webgpu", kernelFunc: Wpe };
var Jx = class {
  constructor(e, t10) {
    this.variableNames = ["x"], this.uniforms = "onValue : f32, offValue : f32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = [e, t10], this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "onehot";
  }
  getUserCode() {
    return `
      ${G("index")} {
        if(index < uniforms.size) {
          let coords = getCoordsFromIndex(index);
          setOutputAtIndex(index, mix(uniforms.offValue, uniforms.onValue,
                                      f32(i32(round(getX(coords.x))) == coords.y)));
        }
      }
    `;
  }
};
function Upe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { indices: n } = e, { dtype: s, depth: a, onValue: i, offValue: p } = o, u = y.sizeFromShape(n.shape), c = new Jx(u, a), l = pe({ inputs: { x: n }, backend: t10, attrs: { shape: [u] } }), m = [{ type: "float32", data: [i] }, { type: "float32", data: [p] }], d = t10.runWebGPUProgram(c, [l], s, m);
  t10.disposeData(l.dataId);
  let f = [...n.shape, a], h = pe({ inputs: { x: d }, backend: t10, attrs: { shape: f } });
  return t10.disposeData(d.dataId), h;
}
var YW = { kernelName: Jn, backendName: "webgpu", kernelFunc: Upe };
function bm(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e;
  if (o.dtype === "complex64") {
    let n = vi({ inputs: { input: o }, backend: t10 }), s = bm({ inputs: { x: n }, backend: t10 }), a = Rp({ inputs: { input: o }, backend: t10 }), i = bm({ inputs: { x: a }, backend: t10 }), p = xo({ inputs: { real: s, imag: i }, backend: t10 });
    return t10.disposeData(n.dataId), t10.disposeData(s.dataId), t10.disposeData(a.dataId), t10.disposeData(i.dataId), p;
  } else return vt({ attrs: { shape: o.shape, dtype: o.dtype, value: o.dtype === "string" ? "" : 0 }, backend: t10 });
}
var QW = { kernelName: Sa, backendName: "webgpu", kernelFunc: bm };
function ZW(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o } = e;
  if (o.dtype === "string") throw new Error("onesLike is not supported under string dtype");
  if (o.dtype === "complex64") {
    let n = vi({ inputs: { input: o }, backend: t10 }), s = ZW({ inputs: { x: n }, backend: t10 }), a = Rp({ inputs: { input: o }, backend: t10 }), i = bm({ inputs: { x: a }, backend: t10 }), p = xo({ inputs: { real: s, imag: i }, backend: t10 });
    return t10.disposeData(n.dataId), t10.disposeData(s.dataId), t10.disposeData(a.dataId), t10.disposeData(i.dataId), p;
  } else return vt({ attrs: { shape: o.shape, dtype: o.dtype, value: 1 }, backend: t10 });
}
var JW = { kernelName: ca, backendName: "webgpu", kernelFunc: ZW };
function Gpe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { axis: n } = o;
  if (e.length === 1) return Mx({ inputs: { input: e[0] }, backend: t10, attrs: { dim: n } });
  let s = e[0].shape, a = e[0].dtype;
  e.forEach((c) => {
    y.assertShapesMatch(s, c.shape, "All tensors passed to stack must have matching shapes"), y.assert(a === c.dtype, () => "All tensors passed to stack must have matching dtypes");
  });
  let i = [], p = e.map((c) => {
    let l = Mx({ inputs: { input: c }, backend: t10, attrs: { dim: n } });
    return i.push(l), l;
  }), u = a0({ inputs: p, backend: t10, attrs: { axis: n } });
  return i.forEach((c) => t10.disposeData(c.dataId)), u;
}
var eU = { kernelName: la, backendName: "webgpu", kernelFunc: Gpe };
function m0(r15, e = false) {
  let t10 = r15.length, o = ft(t10), n = r15.map((l, m) => `uniforms.pad${m}[0]`).join(","), s = r15.map((l, m) => `uniforms.pad${m}[0] + uniforms.xShape${t10 > 1 ? `[${m}]` : ""}`).join(","), a = t10 > 1 ? `${o}(${n})` : `${n}`, i = t10 > 1 ? `${o}(${s})` : `${s}`, p = t10 > 1 ? "any(paddedCoords < start)" : "paddedCoords < start", u = t10 > 1 ? "any(paddedCoords >= end)" : "paddedCoords >= end", c = t10 > 1 ? ["coords[0]", "coords[1]", "coords[2]", "coords[3]"].slice(0, t10) : "coords";
  return `
        let start = ${a};
        let end = ${i};
        if (${p} || ${u}) {
          setOutputAtIndex(index, ${e ? 0 : "uniforms.constantValue"});
        } else {
          let coords = paddedCoords - start;
          setOutputAtIndex(index, getX(${c}));
        }
  `;
}
var ey = class {
  constructor(e, t10) {
    this.variableNames = ["x"], this.uniforms = "constantValue : f32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = t10.map((o, n) => o[0] + e[n] + o[1]), this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), t10.map((o, n) => {
      this.uniforms += ` pad${n} : vec2<i32>,`;
    }), this.xShape = e, this.shaderKey = "pad";
  }
  getUserCode() {
    return `
      ${G("index")} {
        if (index < uniforms.size) {
          let paddedCoords = getCoordsFromIndex(index);
          ${m0(this.xShape)}
        }
      }
    `;
  }
};
var Hpe = (r15) => {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { paddings: s, constantValue: a } = o;
  if (s.every((u) => y.arraysEqual(u, [0, 0]))) return At({ inputs: { x: n }, backend: t10 });
  if (y.sizeFromShape(n.shape) === 0) {
    let u = s.map((c, l) => c[0] + n.shape[l] + c[1]);
    return vt({ backend: t10, attrs: { shape: u, value: a, dtype: n.dtype } });
  }
  let i = [{ type: "float32", data: [a] }];
  s.map((u) => i.push({ type: "int32", data: [u[0], u[1]] }));
  let p = new ey(n.shape, s);
  return t10.runWebGPUProgram(p, [n], n.dtype, i);
};
var tU = { kernelName: es, backendName: "webgpu", kernelFunc: Hpe };
var Kpe = et({ opType: fe.POW });
var rU = { kernelName: "Pow", backendName: "webgpu", kernelFunc: Kpe };
function qpe(r15) {
  let { inputs: e, backend: t10 } = r15, { x: o, alpha: n } = e, s = new Ii(fe.PRELU, o.shape, n.shape);
  return t10.runWebGPUProgram(s, [o, n], "float32");
}
var oU = { kernelName: rs, backendName: "webgpu", kernelFunc: qpe };
function jpe(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { axis: s, keepDims: a } = o;
  return eo(n, s, a, "prod", t10);
}
var nU = { kernelName: os, backendName: "webgpu", kernelFunc: jpe };
var Xpe = (r15) => {
  let { backend: e, attrs: t10 } = r15, { start: o, stop: n, step: s, dtype: a } = t10, i = Pz(o, n, s, a);
  return e.makeTensorInfo([i.length], a, i);
};
var sU = { kernelName: ma, backendName: "webgpu", kernelFunc: Xpe };
var Ype = et({ opType: fe.DIV });
var aU = { kernelName: fn, backendName: "webgpu", kernelFunc: Ype };
var Qpe = ye({ opType: Z.RECIPROCAL });
var iU = { kernelName: ns, backendName: "webgpu", kernelFunc: Qpe };
var Zpe = ye({ opType: Z.RELU });
var uU = { kernelName: ss, backendName: "webgpu", kernelFunc: Zpe };
var Jpe = ye({ opType: Z.RELU6 });
var pU = { kernelName: us, backendName: "webgpu", kernelFunc: Jpe };
var ty = class {
  constructor(e, t10, o) {
    this.variableNames = ["x"], this.uniforms = "adjustHeightWidth : vec2<f32>, halfPixelCenters : f32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = [e[0], t10, o, e[3]], this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "resizeBilinear";
  }
  getUserCode() {
    return `
      ${G("index")} {
        if (index < uniforms.size) {
        let coords = getCoordsFromIndex(index);
          let b = coords[0];
          let d = coords[3];
          let rc = coords.yz;

          let effectiveInSize = vec2<f32>(
            f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0],
            f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]);

          let effectiveOutSize = vec2<f32>(
            f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0],
            f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]);

          let effectiveInputOverOutputRatioRC =
              effectiveInSize / effectiveOutSize;

          // Fractional source index
          let sourceFracIndexRC =
            (vec2<f32>(rc) + vec2<f32>(uniforms.halfPixelCenters)) *
            effectiveInputOverOutputRatioRC - vec2<f32>(uniforms.halfPixelCenters);

          // Compute the four integer indices.
          let sourceFloorRC = vec2<i32>(sourceFracIndexRC);
          let sourceCeilRC = vec2<i32>(
            min(vec2<f32>(uniforms.xShape.yz) - vec2<f32>(1.0), ceil(sourceFracIndexRC)));

          let topLeft = getX(b, sourceFloorRC.x, sourceFloorRC.y, d);
          let bottomLeft = getX(b, sourceCeilRC.x, sourceFloorRC.y, d);
          let topRight = getX(b, sourceFloorRC.x, sourceCeilRC.y, d);
          let bottomRight = getX(b, sourceCeilRC.x, sourceCeilRC.y, d);

          let fracRC = sourceFracIndexRC - vec2<f32>(sourceFloorRC);

          let top = topLeft + (topRight - topLeft) * fracRC.y;
          let bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
          let newValue = top + (bottom - top) * fracRC.x;

          setOutputAtIndex(index, newValue);
        }
      }
    `;
  }
};
function ece(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n } = e, { alignCorners: s, size: a, halfPixelCenters: i } = o, [p, u] = a, c = s && p > 1 ? 1 : 0, l = s && u > 1 ? 1 : 0, d = [{ type: "float32", data: [c, l] }, { type: "float32", data: [i ? 0.5 : 0] }], f = new ty(n.shape, p, u);
  return t10.runWebGPUProgram(f, [n], "float32", d);
}
var cU = { kernelName: is, backendName: "webgpu", kernelFunc: ece };
var ry = class {
  constructor(e, t10) {
    this.variableNames = ["dy"], this.uniforms = `effectiveXSize : vec2<i32>, effectiveYSize : vec2<i32>, heightScale : f32, widthScale : f32,
       invHeightScale : f32, invWidthScale : f32, winHeight : i32, winWidth : i32,`, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.alignCorners = t10, this.shaderKey = `resizeBilinearBackprop_${t10}`;
  }
  getUserCode() {
    return `
      ${G("index")} {
        if (index < uniforms.size) {
          let coords = getOutputCoords();
          let b = coords[0];
          let d = coords[3];
          let r = coords[1];
          let c = coords[2];

          var accumulator = 0.0;

          // Compute bounds for where in dy we will look
          let startRLerp = floor(f32(r) * uniforms.invHeightScale);
          let startDyR = i32(startRLerp - f32(uniforms.winHeight / 2));

          let startCLerp = floor(f32(c) * uniforms.invWidthScale);
          let startDyC = i32(startCLerp - f32(uniforms.winWidth / 2));

          // Loop over dy
          for (var dyROffset = 0; dyROffset < uniforms.winHeight; dyROffset++) {
            let dyR = startDyR + dyROffset;

            // Guard against the window exceeding the bounds of dy
            if (dyR < 0 || dyR >= uniforms.dyShape[1]) {
              continue;
            }

            for (var dyCOffset = 0; dyCOffset < uniforms.winWidth; dyCOffset++) {
              let dyC = startDyC + dyCOffset;

              // Guard against the window exceeding the bounds of dy
              if (dyC < 0 || dyC >= uniforms.dyShape[2]) {
                continue;
              }

              let dxR = f32(dyR) * uniforms.heightScale;
              let topDxRIndex = i32(floor(dxR));
              let bottomDxRIndex = i32(min(ceil(dxR), f32(uniforms.outShape[1] - 1)));
              let dxRLerp = dxR - f32(topDxRIndex);
              let inverseDxRLerp = 1.0 - dxRLerp;

              let dxC = f32(dyC) * uniforms.widthScale;
              let leftDxCIndex = i32(floor(dxC));
              let rightDxCIndex = i32(min(ceil(dxC), f32(uniforms.outShape[2] - 1)));
              let dxCLerp = dxC - f32(leftDxCIndex);
              let 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

          setOutputAtIndex(index, accumulator);
        }
      }
    `;
  }
};
function tce(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n, dy: s } = e, { alignCorners: a } = o, [, i, p] = n.shape, [, u, c] = s.shape, l = [a && u > 1 ? i - 1 : i, a && c > 1 ? p - 1 : p], m = [a && u > 1 ? u - 1 : u, a && c > 1 ? c - 1 : c], d = l[0] / m[0], f = l[1] / m[1], h = 1 / d, g = 1 / f, x = Math.ceil(h) * 2 + 2, b = Math.ceil(g) * 2 + 2, C = new ry(n.shape, a), S = [{ type: "int32", data: l }, { type: "int32", data: m }, { type: "float32", data: [d] }, { type: "float32", data: [f] }, { type: "float32", data: [h] }, { type: "float32", data: [g] }, { type: "int32", data: [x] }, { type: "int32", data: [b] }];
  return t10.runWebGPUProgram(C, [s], s.dtype, S);
}
var lU = { kernelName: Ja, backendName: "webgpu", kernelFunc: tce };
var oy = class {
  constructor(e, t10, o, n) {
    this.variableNames = ["x"], this.uniforms = "adjustHeightWidth : vec2<f32>, roundBase : f32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = [e[0], t10, o, e[3]], this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.halfPixelCenters = n, this.shaderKey = `resizeNearest_${n}`;
  }
  getUserCode() {
    let e;
    return this.halfPixelCenters ? e = "max((vec2<f32>(rc) + vec2<f32>(0.5)) * effectiveInputOverOutputRatioRC, vec2<f32>(0.0))" : e = "vec2<f32>(rc) * effectiveInputOverOutputRatioRC", `
      ${G("index")} {
        if (index < uniforms.size) {
          let coords = getCoordsFromIndex(index);
          let b = coords[0];
          let d = coords[3];
          let rc = coords.yz;

          let effectiveInSize = vec2<f32>(
            f32(uniforms.xShape.y) - uniforms.adjustHeightWidth[0],
            f32(uniforms.xShape.z) - uniforms.adjustHeightWidth[1]);

          let effectiveOutSize = vec2<f32>(
            f32(uniforms.outShape.y) - uniforms.adjustHeightWidth[0],
            f32(uniforms.outShape.z) - uniforms.adjustHeightWidth[1]);

          let effectiveInputOverOutputRatioRC =
              effectiveInSize / effectiveOutSize;

          // Fractional source index
          let sourceFracIndexRC = ${e};

          // Compute the coordinators of nearest neighbor point.
          let inputShapeRC = vec2<f32>(f32(uniforms.xShape.y), f32(uniforms.xShape.z));
          let sourceNearestRC = vec2<i32>(
            min(inputShapeRC - 1.0, floor(sourceFracIndexRC + uniforms.roundBase)));
          let newValue = getX(b, sourceNearestRC.x, sourceNearestRC.y, d);

          setOutputAtIndex(index, newValue);
        }
      }
    `;
  }
};
function rce(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n } = e, { alignCorners: s, halfPixelCenters: a, size: i } = o, [p, u] = i, c = s && p > 1 ? 1 : 0, l = s && u > 1 ? 1 : 0, d = [{ type: "float32", data: [c, l] }, { type: "float32", data: [s ? 0.5 : 0] }], f = new oy(n.shape, p, u, a);
  return t10.runWebGPUProgram(f, [n], n.dtype, d);
}
var mU = { kernelName: as, backendName: "webgpu", kernelFunc: rce };
var ny = class {
  constructor(e, t10) {
    this.variableNames = ["dy"], this.uniforms = `effectiveXSize : vec2<i32>, effectiveYSize : vec2<i32>, invHeightScale : f32, invWidthScale : f32,
       winHeight : i32, winWidth : i32,`, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.alignCorners = t10, this.shaderKey = `resizeNearestNeigborBackprop_${t10}`;
  }
  getUserCode() {
    return `
      ${G("index")} {
        if (index < uniforms.size) {
          let coords = getOutputCoords();
          let b = coords[0];
          let d = coords[3];
          let r = coords[1];
          let c = coords[2];

          var accumulator = 0.0;

          // Compute bounds for where in dy we will look
          let startRLerp = floor(f32(r) * uniforms.invHeightScale);
          let startDyR = i32(floor(startRLerp - f32(uniforms.winHeight / 2)));

          let startCLerp = floor(f32(c) * uniforms.invWidthScale);
          let startDyC = i32(floor(startCLerp - f32(uniforms.winWidth / 2)));

          // Loop over dy
          for (var dyROffset = 0; dyROffset < uniforms.winHeight; dyROffset++) {
            let dyR = startDyR + dyROffset;

            // Guard against the window exceeding the bounds of dy
            if (dyR < 0 || dyR >= uniforms.dyShape[1]) {
              continue;
            }

            for (var dyCOffset = 0; dyCOffset < uniforms.winWidth; dyCOffset++) {
              let dyC = startDyC + dyCOffset;

              // Guard against the window exceeding the bounds of dy
              if (dyC < 0 || dyC >= uniforms.dyShape[2]) {
                continue;
              }

              let sourceFracRow = f32(uniforms.effectiveXSize[0]) *
                  (f32(dyR) / f32(uniforms.effectiveYSize[0]));

              let sourceFracCol = f32(uniforms.effectiveXSize[1]) *
                  (f32(dyC) / f32(uniforms.effectiveYSize[1]));

              let sourceNearestRow =
                  i32(min(f32(uniforms.outShape[1] - 1),
                  ${this.alignCorners ? "floor(sourceFracRow + 0.5)" : "floor(sourceFracRow)"}));

              let sourceNearestCol =
                  i32(min(f32(uniforms.outShape[2] - 1),
                  ${this.alignCorners ? "floor(sourceFracCol + 0.5)" : "floor(sourceFracCol)"}));

              if (r == sourceNearestRow && c == sourceNearestCol) {
                accumulator += getDy(b, dyR, dyC, d);
              }
            }
          }
          // End loop over dy

          setOutputAtIndex(index, accumulator);
        }
      }
    `;
  }
};
function oce(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { images: n, dy: s } = e, { alignCorners: a } = o, [, i, p] = n.shape, [, u, c] = s.shape, l = [a && u > 1 ? i - 1 : i, a && c > 1 ? p - 1 : p], m = [a && u > 1 ? u - 1 : u, a && c > 1 ? c - 1 : c], d = l[0] / m[0], f = l[1] / m[1], h = 1 / d, g = 1 / f, x = Math.ceil(h) * 2 + 2, b = Math.ceil(g) * 2 + 2, C = new ny(n.shape, a), S = [{ type: "int32", data: l }, { type: "int32", data: m }, { type: "float32", data: [h] }, { type: "float32", data: [g] }, { type: "int32", data: [x] }, { type: "int32", data: [b] }];
  return t10.runWebGPUProgram(C, [s], s.dtype, S);
}
var dU = { kernelName: Za, backendName: "webgpu", kernelFunc: oce };
var sy = class {
  constructor(e) {
    this.variableNames = ["x"], this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.uniforms = " axis : vec4<i32>,", this.shaderKey = "reverse";
  }
  getUserCode() {
    return `
      
      // Using uniform variables as judging conditions, so the function has
      // coherent execution within all threads.
      fn getReverseCoords(coords : vec4<i32>) -> vec4<i32> {
        var reverseCoords = coords;
        if (uniforms.axis[0] == 1) {
          reverseCoords[0] = uniforms.xShape[0] - coords[0] - 1;
        }
        if (uniforms.axis[1] == 1) {
          reverseCoords[1] = uniforms.xShape[1] - coords[1] - 1;
        }
        if (uniforms.axis[2] == 1) {
          reverseCoords[2] = uniforms.xShape[2] - coords[2] - 1;
        }
        if (uniforms.axis[3] == 1) {
          reverseCoords[3] = uniforms.xShape[3] - coords[3] - 1;
        }

        return reverseCoords;
      }
    
      ${G("index")} {
        if (index < uniforms.size) {
          let coords = getCoordsFromIndex(index);
          let reverseCoords = getReverseCoords(coords);
          setOutputAtIndex(index, getX(reverseCoords[0],
              reverseCoords[1], reverseCoords[2], reverseCoords[3]));
        }
      }
    `;
  }
};
function nce(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { dims: s } = o, a = n.shape.length;
  if (a === 0) return At({ inputs: { x: n }, backend: t10 });
  let i = n.shape, p = [1, 1, 1, 1];
  i.forEach((g, x) => {
    let b = x + 4 - a;
    p[b] = g;
  });
  let u = y.parseAxisParam(s, n.shape), c = [0, 0, 0, 0];
  u.forEach((g) => {
    let x = g + 4 - a;
    c[x] = 1;
  });
  let l = [{ type: "int32", data: c }], m = pe({ inputs: { x: n }, backend: t10, attrs: { shape: p } }), d = new sy(p), f = t10.runWebGPUProgram(d, [m], m.dtype, l);
  t10.disposeData(m.dataId);
  let h = pe({ inputs: { x: f }, backend: t10, attrs: { shape: i } });
  return t10.disposeData(f.dataId), h;
}
var fU = { kernelName: ps, backendName: "webgpu", kernelFunc: nce };
var ay = class {
  constructor(e, t10) {
    this.outputShape = [], this.variableNames = ["x"], this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.uniforms = `centerX : f32, centerY : f32, sinRadians : f32,
          cosRadians : f32,`, this.shaderKey = "rotate", this.outputShape = e, typeof t10 == "number" ? (this.uniforms += " fillValue : f32,", this.fillSnippet = "var outputValue = uniforms.fillValue;", this.shaderKey += "_float") : (this.uniforms += " fillValue : vec3<f32>,", this.fillSnippet = "var outputValue = uniforms.fillValue[coords[3]];", this.shaderKey += "_vec3");
  }
  getUserCode() {
    return `
        ${G("index")} {
          if (index < uniforms.size) {
            let coords = getCoordsFromIndex(index);
            let coordXFloat = (f32(coords[2]) - uniforms.centerX) *
                uniforms.cosRadians - (f32(coords[1]) - uniforms.centerY) *
                uniforms.sinRadians;
            let coordYFloat = (f32(coords[2]) - uniforms.centerX) *
                uniforms.sinRadians + (f32(coords[1]) - uniforms.centerY) *
                uniforms.cosRadians;
            let coordX = i32(round(coordXFloat + uniforms.centerX));
            let coordY = i32(round(coordYFloat + uniforms.centerY));
            ${this.fillSnippet}
            if(coordX >= 0 && coordX < uniforms.xShape[2] && coordY >= 0 &&
                coordY < uniforms.xShape[1]) {
              outputValue = getX(coords[0], coordY, coordX, coords[3]);
            }
            setOutputAtIndex(index, outputValue);
          }
        }
      `;
  }
};
var hU = { kernelName: Ds, backendName: "webgpu", kernelFunc: ({ inputs: r15, attrs: e, backend: t10 }) => {
  let { image: o } = r15, { radians: n, fillValue: s, center: a } = e, i = t10, p = new ay(o.shape, s), [u, c] = w.getImageCenter(a, o.shape[1], o.shape[2]), l = [{ type: "float32", data: [u] }, { type: "float32", data: [c] }, { type: "float32", data: [Math.sin(n)] }, { type: "float32", data: [Math.cos(n)] }];
  return typeof s == "number" ? l.push({ type: "float32", data: [Number.parseFloat(s.toFixed(2))] }) : l.push({ type: "float32", data: s }), i.runWebGPUProgram(p, [o], o.dtype, l);
} };
var sce = ye({ opType: Z.ROUND });
var gU = { kernelName: cs, backendName: "webgpu", kernelFunc: sce };
var ace = ye({ opType: Z.RSQRT, cpuKernelImpl: Oz });
var xU = { kernelName: ls, backendName: "webgpu", kernelFunc: ace };
var za = class {
  constructor(e, t10, o, n, s, a, i, p = true) {
    this.variableNames = ["updates", "indices"], this.workgroupSize = [64, 1, 1], this.atomic = true, this.outputShape = a, this.type = i, this.sumDupeIndices = p, this.dispatchLayout = X(e), this.dispatch = H(this.dispatchLayout, e, this.workgroupSize), this.sliceDimGreaterThanOne = t10 > 1, this.shaderKey = `scatter_${o}_${n}_${this.sliceDimGreaterThanOne}_${i}_${p}_${s.length}`;
    let u = ft(s.length);
    this.uniforms = `sliceDim : i32, strides: ${u}, updatesSize: i32,`, this.updatesRank = n, this.indicesRank = o;
  }
  getUserCode() {
    let e = "";
    this.indicesRank === 1 ? e = "coords[0]" : this.indicesRank === 2 && (e = "coords[0], j");
    let t10 = `getIndices(${e})`, o = this.sliceDimGreaterThanOne ? "uniforms.strides[j]" : "uniforms.strides", n = "", s = "";
    this.dispatchLayout.x.length === 1 ? (n = "flattenedIndex", s = `
      fn getUpdatesCoordsFromFlatIndex(index : i32) -> i32 {
        return index;
      }
      `) : this.dispatchLayout.x.length === 2 && (n = "vec2<i32>(flattenedIndex, coords[1])", s = `
      fn getUpdatesCoordsFromFlatIndex(index : i32) -> vec2<i32> {
        // N.B. |updates| could be a scalar tensor, conceptually representing a
        // 2D tensor with all values equal to that. By design, its size must be
        // the same as |outShape[1]| in one dimension, and |indicesShape[0]|
        // gives the other.
        let sliceSize = uniforms.outShape[1];
        let d0 = index / sliceSize;
        let d1 = index - d0 * sliceSize;
        return vec2<i32>(d0, d1);
      }
      `);
    let i = `getUpdates(${Array.from({ length: this.updatesRank }, (u, c) => `coords[${c}]`).join(", ")})`;
    return `
    ${s}
      ${G("index")} {
        if (index < uniforms.updatesSize) {
          let coords = getUpdatesCoordsFromFlatIndex(index);
          var flattenedIndex = 0;
          for (var j = 0; j < uniforms.sliceDim; j = j + 1) {
            let indexInside = i32(round(${t10}));
            flattenedIndex = flattenedIndex + indexInside * ${o};
          }
          let updateValue =
              ${Su(this.type)}(${i});
          let flatIndex = getOutputIndexFromCoords(${n});

          ${this.sumDupeIndices ? Qr("&result[flatIndex]", "updateValue", this.type) : "atomicStore(&result[flatIndex], bitcast<i32>(updateValue));"}
        }
      }`;
  }
};
function ice(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { indices: n, updates: s } = e, { shape: a } = o, { sliceRank: i, numUpdates: p, sliceSize: u, strides: c, outputSize: l } = w.calculateShapes(s, n, a), m = [l / u, u];
  if (l === 0) return t10.makeTensorInfo(a, n.dtype);
  let d = pe({ inputs: { x: n }, backend: t10, attrs: { shape: [p, i] } }), f = pe({ inputs: { x: s }, backend: t10, attrs: { shape: [p, u] } }), h = f.dtype, g = vt({ backend: t10, attrs: { shape: m, value: 0, dtype: h } }), x = y.sizeFromShape(f.shape), b = [{ type: "int32", data: [i] }, { type: "int32", data: c }, { type: "int32", data: [x] }], C = new za(f.shape, i, d.shape.length, f.shape.length, c, m, h), S = t10.runWebGPUProgram(C, [f, d], h, b, g), k = pe({ inputs: { x: S }, backend: t10, attrs: { shape: a } });
  return t10.disposeData(d.dataId), t10.disposeData(f.dataId), t10.disposeData(S.dataId), k;
}
var yU = { kernelName: ms, backendName: "webgpu", kernelFunc: ice };
var iy = class {
  constructor(e, t10) {
    this.outputShape = [], this.variableNames = ["sortedSequence", "values"], this.uniforms = "numInputs : i32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.side = t10, this.shaderKey = `search_sorted_${t10}`;
  }
  getUserCode() {
    return `
      fn findBound(batch: i32, value: f32) -> i32 {
        var left = i32(0);
        var right = uniforms.numInputs;
        while (left < right) {
          var mid = (left + right) / 2;
          if (getSortedSequence(batch, mid) ${this.side === "left" ? "<" : "<="} value) {
            left = mid + 1;
          } else {
            right = mid;
          }
        }
        return right;
      }

      ${G("index")} {
        if (index < uniforms.size) {
          let coords = getCoordsFromIndex(index);
          let value = getValuesByOutputIndex(index);
          setOutputAtIndexI32(index, findBound(coords[0], value));
        }
      }
    `;
  }
};
function uce(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { sortedSequence: n, values: s } = e, { side: a } = o, i = new iy([s.shape[0], s.shape[1]], a), p = [{ type: "int32", data: [n.shape[1]] }];
  return t10.runWebGPUProgram(i, [n, s], "int32", p);
}
var bU = { kernelName: fs, backendName: "webgpu", kernelFunc: uce };
var uy = class {
  constructor(e, t10, o) {
    this.variableNames = ["c", "a", "b"], this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = t10, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.cRank = e, this.rank = o, this.shaderKey = "select";
  }
  getUserCode() {
    let e, t10;
    if (this.rank > 4) throw Error(`Where for rank ${this.rank} is not yet supported`);
    if (this.rank === 1) t10 = "resRC", e = "resRC";
    else {
      let n = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], s = [], a = [];
      for (let i = 0; i < this.outputShape.length; i++) a.push(`${n[i]}`), i < this.cRank && s.push(`${n[i]}`);
      e = s.join(), t10 = a.join();
    }
    return `
      ${G("index")} {
        if (index < uniforms.size) {
          let resRC = getCoordsFromIndex(index);
          let cVal = getC(${e});
          if (cVal >= 1.0) {
            setOutputAtIndex(index, getA(${t10}));
          } else {
            setOutputAtIndex(index, getB(${t10}));
          }
        }
      }
    `;
  }
};
function pce(r15) {
  let { inputs: e, backend: t10 } = r15, { condition: o, t: n, e: s } = e, a = new uy(o.shape.length, n.shape, n.shape.length);
  return t10.runWebGPUProgram(a, [o, n, s], dt(n.dtype, s.dtype));
}
var CU = { kernelName: fa, backendName: "webgpu", kernelFunc: pce };
var cce = ye({ opType: Z.SELU });
var wU = { kernelName: hs, backendName: "webgpu", kernelFunc: cce };
var lce = ye({ opType: Z.SIGMOID });
var SU = { kernelName: bs, backendName: "webgpu", kernelFunc: lce };
var mce = ye({ opType: Z.SIGN });
var IU = { kernelName: ys, backendName: "webgpu", kernelFunc: mce };
var dce = ye({ opType: Z.SIN });
var vU = { kernelName: "Sin", backendName: "webgpu", kernelFunc: dce };
var fce = ye({ opType: Z.SINH });
var kU = { kernelName: xs, backendName: "webgpu", kernelFunc: fce };
var hce = ye({ opType: Z.SOFTPLUS });
var NU = { kernelName: Cs, backendName: "webgpu", kernelFunc: hce };
var py = class {
  constructor(e, t10, o, n, s, a) {
    this.variableNames = ["x"], this.outputShape = [], this.uniforms = "", this.workgroupSize = [64, 1, 1], this.size = true;
    let i = new Array(n.length);
    for (let p = 0; p < i.length; p++) i[p] = n[s[p]];
    this.outputShape = i, this.newDim = s, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.xShape = e, this.paddedXShape = t10, this.uniforms += `reshapedPaddedXShape : ${ft(n.length)}, paddedXShapeStrides : ${ft(a)}, `, o.map((p, u) => {
      this.uniforms += ` pad${u} : vec2<i32>,`;
    }), this.shaderKey = `spaceToBatchND_${s}`;
  }
  getUserCode() {
    let e = ft(this.outputShape.length), t10 = e0(this.newDim);
    return `
      ${cm(this.paddedXShape, "PaddedX")}
      ${G("index")} {
        if(index < uniforms.size) {
          let coords = getCoordsFromIndex(index);
          let switchedIndex = getIndexFromCoords${this.outputShape.length}D(${e}(${t10}), uniforms.reshapedPaddedXShape);
          let paddedCoords = getPaddedXCoordsFromIndex(switchedIndex);
          ${m0(this.xShape, true)}
        }
      }
    `;
  }
};
var gce = (r15) => {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { blockShape: s, paddings: a } = o;
  y.assert(n.shape.length <= 4, () => "spaceToBatchND for rank > 4 with a WebGPU backend not implemented yet");
  let i = s.reduce((b, C) => b * C), p = [[0, 0]];
  p.push(...a);
  for (let b = 1 + s.length; b < n.shape.length; ++b) p.push([0, 0]);
  let u = p.map((b, C) => b[0] + n.shape[C] + b[1]), c = w.getReshaped(u, s, i, false), l = w.getPermuted(c.length, s.length, false), m = w.getReshapedPermuted(u, s, i, false), d = y.computeStrides(u), f = new py(n.shape, u, p, c, l, d.length), h = [{ type: "int32", data: c }, { type: "int32", data: d }];
  p.map((b) => h.push({ type: "int32", data: [b[0], b[1]] }));
  let g = t10.runWebGPUProgram(f, [n], n.dtype, h), x = pe({ inputs: { x: g }, backend: t10, attrs: { shape: m } });
  return t10.disposeData(g.dataId), x;
};
var TU = { kernelName: ga, backendName: "webgpu", kernelFunc: gce };
var cy = class {
  constructor(e, t10, o) {
    this.variableNames = ["input", "indices", "segmentIds"], this.outputShape = [], this.uniforms = "segmentSize : i32, sparseSize : i32,", this.workgroupSize = [64, 1, 1], this.atomic = true, this.outputShape = e, this.type = o, this.dispatchLayout = X([t10]), this.dispatch = H(this.dispatchLayout, [t10], this.workgroupSize), this.shaderKey = "sparseSegmentSum";
  }
  getUserCode() {
    return `
    ${G("index")} {
      if (index < uniforms.sparseSize) {
        let indexInSegmentIds = index / uniforms.segmentSize;
        let indexInSegment = index % uniforms.segmentSize;
        let indexInInput = indices[indexInSegmentIds];
        let segmentId = segmentIds[indexInSegmentIds];

        let value = input[indexInInput * uniforms.segmentSize + indexInSegment];
        let outIndex = segmentId * uniforms.segmentSize + indexInSegment;
        ${Qr("&result[outIndex]", "value", this.type)}
      }
    }
  `;
  }
};
var ly = class {
  constructor(e, t10) {
    this.variableNames = ["segmentIds"], this.outputShape = [], this.workgroupSize = [64, 1, 1], this.atomic = true, this.outputShape = [e], this.dispatchLayout = X(t10), this.dispatch = H(this.dispatchLayout, t10, this.workgroupSize), this.shaderKey = "sparseSegmentIdCountProgram";
  }
  getUserCode() {
    return `
    ${G("index")} {
      if (index < uniforms.segmentIdsShape) {
        let segmentId = segmentIds[index];
        ${Qr("&result[segmentId]", "1", "int32")}
      }
    }
  `;
  }
};
var my = class {
  constructor(e, t10) {
    this.variableNames = ["segmentSum", "sameSegmentIdCount"], this.outputShape = [], this.uniforms = "segmentSize : i32", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.type = t10, this.dispatchLayout = X(e), this.dispatch = H(this.dispatchLayout, e, this.workgroupSize), this.shaderKey = "sparseSegmentMean";
  }
  getUserCode() {
    return `
    ${G("index")} {
      if (index < uniforms.size) {
        let segmentId = index / uniforms.segmentSize;
        let count = sameSegmentIdCount[segmentId];
        if (count != 0) {
          ${this.type === "float32" ? "setOutputAtIndex(index, segmentSum[index] / f32(count));" : "setOutputAtIndexI32(index, segmentSum[index] / count);"}
        }
      }
    }
  `;
  }
};
function dy(r15, e, t10, o = false, n) {
  let a = y.sizeFromShape(r15.shape) / r15.shape[0], i = r15.dtype, p = y.sizeFromShape(e.shape), u = n.readSync(t10.dataId), l = p > 0 ? u[p - 1] + 1 : 0, m, d = r15.shape.slice();
  d[0] = l;
  let f = p * a, h = vt({ backend: n, attrs: { shape: d, value: 0, dtype: i } });
  m = new cy(d, f, i);
  let g = [{ type: "int32", data: [a] }, { type: "int32", data: [f] }], x = n.runWebGPUProgram(m, [r15, e, t10], i, g, h);
  if (o) return x;
  let b = vt({ backend: n, attrs: { shape: [l], value: 0, dtype: "int32" } });
  m = new ly(l, t10.shape);
  let C = n.runWebGPUProgram(m, [t10], "int32", null, b), S = vt({ backend: n, attrs: { shape: d, value: 0, dtype: i } });
  m = new my(d, i), g = [{ type: "int32", data: [a] }];
  let k = n.runWebGPUProgram(m, [x, C], i, g, S);
  return n.disposeData(x.dataId), n.disposeData(C.dataId), k;
}
function xce(r15) {
  let { inputs: e, backend: t10 } = r15, { data: o, indices: n, segmentIds: s } = e;
  return dy(o, n, s, false, t10);
}
var _U = { kernelName: ya, backendName: "webgpu", kernelFunc: xce };
function yce(r15) {
  let { inputs: e, backend: t10 } = r15, { data: o, indices: n, segmentIds: s } = e;
  return dy(o, n, s, true, t10);
}
var EU = { kernelName: ba, backendName: "webgpu", kernelFunc: yce };
var fy = class {
  constructor(e, t10) {
    this.variableNames = ["A"], this.workgroupSize = [64, 1, 1], this.size = true;
    let o = new Array(e.length);
    for (let n = 0; n < o.length; n++) o[n] = e[n] * t10[n];
    this.outputShape = o, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.rank = this.outputShape.length, this.shaderKey = "tile";
  }
  getUserCode() {
    let e = bce(this.rank, "uniforms.");
    return `
      ${G("index")} {
        if (index < uniforms.size) {
          let resRC = getCoordsFromIndex(index);
          setOutputAtIndex(index, getA(${e}));
        }
      }
    `;
  }
};
function bce(r15, e = "") {
  if (r15 >= 5) throw Error(`Tile for rank ${r15} is not yet supported`);
  if (r15 === 1) return `(resRC % ${e}aShape)`;
  let t10 = ["resRC.x", "resRC.y", "resRC.z", "resRC.w"], o = [];
  for (let n = 0; n < r15; n++) o.push(`(${t10[n]} % ${e}aShape[${n}])`);
  return o.join();
}
function Cm(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { reps: s } = o;
  if (t10.shouldExecuteOnCPU([n]) || n.dtype === "string" || n.shape.length >= 5) {
    let p = t10.readSync(n.dataId), u = n.dtype === "string" ? p.map((m) => y.decodeString(m)) : p, c = me(n.shape, n.dtype, u), l = Uz(c, s);
    return t10.makeTensorInfo(l.shape, l.dtype, l.values);
  }
  let a = new fy(n.shape, s);
  return t10.runWebGPUProgram(a, [n], n.dtype);
}
var $U = { kernelName: po, backendName: "webgpu", kernelFunc: Cm };
function Cce(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { sparseIndices: n, sparseValues: s, defaultValue: a } = e, { outputShape: i } = o, { sliceRank: p, numUpdates: u, sliceSize: c, strides: l, outputSize: m } = w.calculateShapes(s, n, i), d = false;
  if (s.dtype === "string") {
    let R = t10.bufferSync(n), D = t10.bufferSync(s), P = y.decodeString(t10.readSync(a.dataId)[0]), O = Mz(R, D, i, m, c, u, p, l, P, d);
    return t10.makeTensorInfo(i, O.dtype, O.values);
  }
  let f = [m / c, c], h = pe({ inputs: { x: n }, backend: t10, attrs: { shape: [u, p] } }), g = s.shape.length ? pe({ inputs: { x: s }, backend: t10, attrs: { shape: [u, c] } }) : At({ inputs: { x: s }, backend: t10 }), x = g.dtype, b = t10.makeTensorInfo([], x, y.makeZerosTypedArray(1, x)), C = pe({ inputs: { x: a }, backend: t10, attrs: { shape: Array(f.length).fill(1) } }), S = Cm({ inputs: { x: C }, backend: t10, attrs: { reps: f } }), k = y.sizeFromShape([u, c]), _ = [{ type: "int32", data: [p] }, { type: "int32", data: l }, { type: "int32", data: [k] }];
  switch (u) {
    case 0:
      break;
    case 1:
      {
        let R = new za([u, c], p, h.shape.length, g.shape.length, l, f, x, d);
        t10.runWebGPUProgram(R, [g, h], x, _, S);
      }
      break;
    default:
      {
        let R = new za([u, c], p, h.shape.length, b.shape.length, l, f, x, d);
        t10.runWebGPUProgram(R, [b, h], x, _, S);
      }
      {
        let R = new za([u, c], p, h.shape.length, g.shape.length, l, f, x);
        t10.runWebGPUProgram(R, [g, h], x, _, S);
      }
  }
  let $ = pe({ inputs: { x: S }, backend: t10, attrs: { shape: i } });
  return t10.disposeData(h.dataId), t10.disposeData(g.dataId), t10.disposeData(C.dataId), t10.disposeData(b.dataId), t10.disposeData(S.dataId), $;
}
var RU = { kernelName: vs, backendName: "webgpu", kernelFunc: Cce };
function wce(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { numOrSizeSplits: s, axis: a } = o, i = y.parseAxisParam(a, n.shape)[0], p = w.prepareSplitSize(n, s, i), u = n.shape.length, c = new Array(u).fill(0), l = n.shape.slice();
  return p.map((m) => {
    let d = [...l];
    d[i] = m;
    let f = Hs({ inputs: { x: n }, backend: t10, attrs: { begin: c, size: d } });
    return c[i] += m, f;
  });
}
var DU = { kernelName: xa, backendName: "webgpu", kernelFunc: wce };
var Sce = ye({ opType: Z.SQRT });
var AU = { kernelName: ws, backendName: "webgpu", kernelFunc: Sce };
var FU = { kernelName: qi, backendName: "webgpu", kernelFunc: ({ inputs: r15, backend: e }) => {
  let { x: t10 } = r15, o = e, n = new Jr(t10.shape, Z.SQUARE);
  return o.runWebGPUProgram(n, [t10], t10.dtype);
} };
var Ice = et({ opType: fe.SQUARED_DIFFERENCE });
var PU = { kernelName: ks, backendName: "webgpu", kernelFunc: Ice };
function vce({ inputs: r15, attrs: e, backend: t10 }) {
  let { x: o } = r15, n = new Jr(o.shape, Z.STEP, "stepAlpha : f32,"), s = [{ type: "float32", data: [e.alpha] }];
  return t10.runWebGPUProgram(n, [o], o.dtype, s);
}
var OU = { kernelName: wo, backendName: "webgpu", kernelFunc: vce };
var hy = class {
  constructor(e) {
    this.variableNames = ["x"], this.workPerThread = 1, this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize, [this.workPerThread, 1, 1]);
    let t10 = ft(this.outputShape.length);
    this.uniforms = `begin : ${t10},  strides : ${t10}, `, this.shaderKey = "stridedSlice";
  }
  getUserCode() {
    let e = this.outputShape.length, t10 = "";
    if (e === 1) t10 = "coords * uniforms.strides + uniforms.begin";
    else {
      let n = 0;
      t10 = this.outputShape.map((s, a) => (n++, this.outputShape.length === 1 ? `coords * uniforms.strides[${a}] + uniforms.begin[${a}]` : `coords[${n - 1}] * uniforms.strides[${a}] + uniforms.begin[${a}]`)).join(",");
    }
    return `
       ${G("index")} {
         if (index < uniforms.size) {
           let coords = getCoordsFromIndex(index);
           setOutputAtIndex(index, getX(${t10}));
         }
       }
     `;
  }
};
function kce(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { begin: s, end: a, strides: i, beginMask: p, endMask: u, ellipsisMask: c, newAxisMask: l, shrinkAxisMask: m } = o, { finalShapeSparse: d, finalShape: f, isIdentity: h, sliceDim0: g, isSimpleSlice: x, begin: b, end: C, strides: S } = pt.sliceInfo(n.shape, s, a, i, p, u, c, l, m), k;
  if (h) k = pe({ inputs: { x: n }, backend: t10, attrs: { shape: f } });
  else if (g || x) {
    y.assert(n.shape.length >= 1, () => `Input must have rank at least 1, got: ${n.shape.length}`);
    let _ = pt.computeOutShape(b, C, S), $ = Hs({ inputs: { x: n }, backend: t10, attrs: { begin: b, size: _ } });
    k = pe({ inputs: { x: $ }, backend: t10, attrs: { shape: f } }), t10.disposeData($.dataId);
  } else if (t10.shouldExecuteOnCPU([n])) {
    let $ = t10.readSync(n.dataId), R = me(n.shape, n.dtype, $), D = zz(d, R, S, b);
    k = t10.makeTensorInfo(f, n.dtype, D.values);
  } else {
    let $ = new hy(d), R = [{ type: "int32", data: b }, { type: "int32", data: S }], D = t10.runWebGPUProgram($, [n], n.dtype, R);
    k = pe({ inputs: { x: D }, backend: t10, attrs: { shape: f } }), t10.disposeData(D.dataId);
  }
  return k;
}
var MU = { kernelName: Ns, backendName: "webgpu", kernelFunc: kce };
function Nce(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { separator: n, nGramWidths: s, leftPad: a, rightPad: i, padWidth: p, preserveShortSequences: u } = o, { data: c, dataSplits: l } = e, m = t10.readSync(c.dataId), d = t10.readSync(l.dataId), [f, h] = Vz(m, d, n, s, a, i, p, u);
  return [t10.makeTensorInfo([f.length], "string", f), t10.makeTensorInfo(l.shape, "int32", h)];
}
var LU = { kernelName: Ca, backendName: "webgpu", kernelFunc: Nce };
var Tce = et({ opType: fe.SUB, cpuKernelImpl: Wz, supportsComplex: true });
var BU = { kernelName: "Sub", backendName: "webgpu", kernelFunc: Tce };
var _ce = ye({ opType: Z.TAN });
var zU = { kernelName: "Tan", backendName: "webgpu", kernelFunc: _ce };
var Ece = ye({ opType: Z.TANH });
var VU = { kernelName: Es, backendName: "webgpu", kernelFunc: Ece };
function $ce(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { tensor: n, indices: s, updates: a } = e, {} = o, { sliceRank: i, numUpdates: p, sliceSize: u, strides: c, outputSize: l } = w.calculateShapes(a, s, n.shape), m = [l / u, u];
  if (l === 0) return t10.makeTensorInfo(n.shape, s.dtype);
  let d = [], f = pe({ inputs: { x: s }, backend: t10, attrs: { shape: [p, i] } });
  d.push(f);
  let h = pe({ inputs: { x: a }, backend: t10, attrs: { shape: [p, u] } });
  d.push(h);
  let g = pe({ inputs: { x: n }, backend: t10, attrs: { shape: m } });
  d.push(g);
  let x = Cm({ inputs: { x: g }, backend: t10, attrs: { reps: Array(m.length).fill(1) } }), b = new za([p, u], i, f.shape.length, h.shape.length, c, m, n.dtype, false), C = y.sizeFromShape([p, u]), S = [{ type: "int32", data: [i] }, { type: "int32", data: c }, { type: "int32", data: [C] }], k = t10.runWebGPUProgram(b, [h, f], g.dtype, S, x);
  d.push(k);
  let _ = pe({ inputs: { x: k }, backend: t10, attrs: { shape: n.shape } });
  return d.forEach(($) => t10.disposeData($.dataId)), _;
}
var WU = { kernelName: ds, backendName: "webgpu", kernelFunc: $ce };
var gy = class {
  constructor(e) {
    this.variableNames = ["x", "indices"], this.workgroupSize = [256, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.uniforms = `inputSize : i32, firstPass : i32, negativeInf : f32,
        dir : i32, inc : i32,`, this.shaderKey = "swap";
  }
  getUserCode() {
    return `
        ${G("index")} {
          if (index < uniforms.size) {
            let outC = getCoordsFromIndex(index);
            let batch = outC[0];
            let elemIdx = outC[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.
            let isFirstInPair = elemIdx % (2 * uniforms.inc) < uniforms.inc;
            var i = 0;
            if (isFirstInPair) {
              i = elemIdx;
            } else {
              i = elemIdx - uniforms.inc;
            }

            var i0 = 0;
            if (uniforms.firstPass == 1) {
              i0 = i;
            } else {
              i0 = i32(getIndices(batch, i));
            }

            var i1 = 0;
            if (uniforms.firstPass == 1) {
              i1 = i + uniforms.inc;
            } else {
              i1 = i32(getIndices(batch, i + uniforms.inc));
            }

            var x0 = f32(0.0);
            var x1 = f32(0.0);
            if (i0 < uniforms.inputSize) {
              x0 = getX(batch, i0);
            } else {
              x0 = uniforms.negativeInf;
            }
            if (i1 < uniforms.inputSize) {
              x1 = getX(batch, i1);
            } else {
              x1 = uniforms.negativeInf;
            }

            let reverse = elemIdx % (2 * uniforms.dir) >= uniforms.dir;
            let isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
            if (reverse == isGreater) {
              // Elements in opposite order of direction
              let iTemp = i0;
              i0 = i1;
              i1 = iTemp;
            }
            if (isFirstInPair) {
              setOutputAtIndex(index, f32(i0));
            } else {
              setOutputAtIndex(index, f32(i1));
            }
          }
        }
      `;
  }
};
var xy = class {
  constructor(e) {
    this.variableNames = ["x", "indices"], this.workgroupSize = [256, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.uniforms = "inputSize : i32, firstPass : i32, k : i32,", this.shaderKey = "merge";
  }
  getUserCode() {
    return `
        ${G("index")} {
          if (index < uniforms.size) {
            let outC = getCoordsFromIndex(index);
            let batch = outC[0];
            let elemIdx = outC[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.

            var i = 0;
            if (elemIdx < uniforms.k) {
              i = elemIdx;
            } else {
              i = elemIdx * 2 - elemIdx % uniforms.k;
            }
            var i0 = 0;
            if (uniforms.firstPass == 1) {
              i0 = i;
            } else {
              i0 = i32(getIndices(batch, i));
            }
            var i1 = 0;
            if (uniforms.firstPass == 1) {
              i1 = i + uniforms.k;
            } else {
              i1 = i32(getIndices(batch, i + uniforms.k));
            }

            let x0 = getX(batch, i0);
            var x1 = f32(0.0);
            if (i1 < uniforms.inputSize) {
              x1 = getX(batch, i1);
            } else {
              x1 = x0;
            }

            if (x0 >= x1) {
              setOutputAtIndex(index, f32(i0));
            } else {
              setOutputAtIndex(index, f32(i1));
            }
          }
        }
      `;
  }
};
function rl(r15, e) {
  e !== null && r15.disposeData(e.dataId);
}
function UU(r15) {
  let e = 1;
  for (; e < r15; ) e *= 2;
  return e;
}
function Rce(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n } = e, { k: s, sorted: a } = o, i = n.shape, p = i[i.length - 1];
  if (t10.shouldExecuteOnCPU([n])) {
    let k = t10.readSync(n.dataId), [_, $] = Gz(k, i, n.dtype, s, a);
    return [t10.makeTensorInfo(_.shape, _.dtype, _.values), t10.makeTensorInfo($.shape, $.dtype, $.values)];
  }
  if (s === 0) return i[i.length - 1] = 0, [t10.makeTensorInfo(i, n.dtype, []), t10.makeTensorInfo(i, "int32", [])];
  if (p === 1) return [n, vt({ attrs: { shape: i, dtype: "int32", value: 0 }, backend: t10 })];
  let c = y.sizeFromShape(i) / p, l = pe({ inputs: { x: n }, attrs: { shape: [c, p] }, backend: t10 }), m = UU(s), d = UU(p), f = null, h = () => f === null ? [l, l] : [l, f], g = (k, _, $) => {
    let R = h(), D = new gy($), O = [{ type: "int32", data: [p] }, { type: "int32", data: [f === null ? 1 : 0] }, { type: "float32", data: [Number.NEGATIVE_INFINITY] }, { type: "int32", data: [k] }, { type: "int32", data: [_] }], M = f;
    f = t10.runWebGPUProgram(D, R, "int32", O), rl(t10, M);
  };
  for (let k = 1; k < m; k *= 2) {
    let _ = k * 2;
    for (let $ = k; $ >= 1; $ /= 2) g(_, $, [c, d]);
  }
  for (let k = d; k > m; k /= 2) {
    let _ = h(), $ = new xy([c, k / 2]), D = [{ type: "int32", data: [p] }, { type: "int32", data: [f === null ? 1 : 0] }, { type: "int32", data: [m] }], P = f;
    f = t10.runWebGPUProgram($, _, "int32", D), rl(t10, P);
    let O = m / 2, M = O * 2;
    for (let L = O; L >= 1; L /= 2) g(M, L, f.shape);
  }
  let x = f;
  f = Hs({ inputs: { x: f }, backend: t10, attrs: { begin: 0, size: [c, s] } }), rl(t10, x);
  let b = c0({ inputs: { x: l, indices: f }, backend: t10, attrs: { axis: 1, batchDims: 1 } });
  rl(t10, l);
  let C = i.slice(0, -1);
  C.push(s), x = f, f = pe({ inputs: { x: f }, attrs: { shape: C }, backend: t10 }), rl(t10, x);
  let S = b;
  return b = pe({ inputs: { x: b }, attrs: { shape: C }, backend: t10 }), rl(t10, S), [b, f];
}
var GU = { kernelName: $s, backendName: "webgpu", kernelFunc: Rce };
var yy = class {
  constructor(e) {
    this.variableNames = ["Image", "Transforms"], this.uniforms = "interpolationModeId : i32, fillModeId : i32, fillValue : f32,", this.workgroupSize = [64, 1, 1], this.size = true, this.outputShape = e, this.dispatchLayout = X(this.outputShape), this.dispatch = H(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "transform";
  }
  getUserCode() {
    return `
          fn mapCoord(outCoord : f32, len : f32) -> f32{
            var inCoord = outCoord;
            if(uniforms.fillModeId == 2) {
              if (inCoord < 0.0) {
                if (len <= 1.0) {
                  inCoord = 0.0;
                } else {
                  let sz2 = 2.0 * len;
                  if (inCoord < sz2) {
                    inCoord = sz2 * f32(i32(f32(-inCoord / sz2))) +
                    inCoord;
                  }
                  if (inCoord < -len) {
                    inCoord = inCoord + sz2;
                  } else {
                    inCoord = -inCoord - 1.0;
                  }
                }
              } else if (inCoord > len - 1.0) {
                if (len <= 1.0) {
                  inCoord = 0.0;
                } else {
                  let sz2 = 2.0 * len;
                  inCoord = inCoord - sz2 * f32(i32(f32(inCoord / sz2)));
                  if (inCoord >= len) {
                    inCoord = sz2 - inCoord - 1.0;
                  }
                }
              }
              return clamp(inCoord, 0.0, len - 1.0);
            } else if (uniforms.fillModeId == 3) {
              if (inCoord < 0.0) {
                if (len <= 1.0) {
                  inCoord = 0.0;
                } else {
                  let sz = len - 1.0;
                  inCoord = inCoord + len * (f32(i32(f32(-inCoord / sz))) + 1.0);
                }
              } else if (inCoord > len - 1.0) {
                if (len <= 1.0) {
                  inCoord = 0.0;
                } else {
                  let sz = len - 1.0;
                  inCoord = inCoord - len * f32(i32(f32(inCoord / sz)));
                }
              }
              return clamp(inCoord, 0.0, len - 1.0);
            } else if (uniforms.fillModeId == 4) {
              return clamp(outCoord, 0.0, len - 1.0);
            }
            return outCoord;
          }
          fn readWithFillValue(batch : i32, coordY : i32, coordX : i32,
            channel : i32) -> f32 {
            var outputValue : f32;
            if (0 <= coordY && coordY < uniforms.imageShape[1] && 0 <= coordX && coordX < uniforms.imageShape[2]) {
                outputValue = getImage(batch, coordY, coordX, channel);
            } else {
              outputValue = uniforms.fillValue;
            }
            return outputValue;
          }

          ${G("index")} {
            if (index < uniforms.size) {
              let coords = getCoordsFromIndex(index);
              var outputValue : f32;
              let batch = coords[0];
              let x = coords[2];
              let y = coords[1];
              let channel = coords[3];
              let xf = f32(x);
              let yf = f32(y);
              let a1 = getTransforms(batch, 0);
              let a2 = getTransforms(batch, 1);
              let a3 = getTransforms(batch, 2);
              let b1 = getTransforms(batch, 3);
              let b2 = getTransforms(batch, 4);
              let b3 = getTransforms(batch, 5);
              let c1 = getTransforms(batch, 6);
              let c2 = getTransforms(batch, 7);
              let projection = c1 * xf + c2 * yf + 1.0;
              if (projection == 0.0) {
                outputValue = uniforms.fillValue;
              } else {
                let inX = (a1 * xf + a2 * yf + a3) / projection;
                let inY = (b1 * xf + b2 * yf + b3) / projection;
                let mapX = mapCoord(inX, f32(uniforms.imageShape[2]));
                let mapY = mapCoord(inY, f32(uniforms.imageShape[1]));

                if (uniforms.interpolationModeId == 1) {
                  let coordY = i32(round(mapY));
                  let coordX = i32(round(mapX));
                  outputValue = readWithFillValue(batch, coordY, coordX,
                    channel);
                } else {
                  let yFloor = floor(mapY);
                  let xFloor = floor(mapX);
                  let yCeil = yFloor + 1.0;
                  let xCeil = xFloor + 1.0;
                  let valueYFloor = (xCeil - mapX) *
                  readWithFillValue(batch, i32(yFloor), i32(xFloor), channel) +
                  (mapX - xFloor) *
                  readWithFillValue(batch, i32(yFloor), i32(xCeil), channel);
                  let valueYCeil = (xCeil - mapX) *
                  readWithFillValue(batch, i32(yCeil), i32(xFloor), channel) +
                  (mapX - xFloor) *
                  readWithFillValue(batch, i32(yCeil), i32(xCeil), channel);
                  outputValue = (yCeil - mapY) * valueYFloor +
                  (mapY - yFloor) * valueYCeil;
                }
              }
              setOutputAtIndex(index, outputValue);
            }
          }
        `;
  }
};
function Dce(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { image: n, transforms: s } = e, { interpolation: a, fillMode: i, fillValue: p, outputShape: u } = o, [c, l, m, d] = n.shape, [f, h] = u != null ? u : [l, m], g = [c, f, h, d], x = new yy(g), b = a === "nearest" ? 1 : 2, C;
  switch (i) {
    case "constant":
      C = 1;
      break;
    case "reflect":
      C = 2;
      break;
    case "wrap":
      C = 3;
      break;
    case "nearest":
      C = 4;
      break;
    default:
      C = 1;
      break;
  }
  let S = [{ type: "int32", data: [b] }, { type: "int32", data: [C] }, { type: "float32", data: [p] }];
  return t10.runWebGPUProgram(x, [n, s], "float32", S);
}
var HU = { kernelName: Rs, backendName: "webgpu", kernelFunc: Dce };
function Ace(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { value: n } = e, { axis: s } = o;
  s < 0 && (s += n.shape.length);
  let a = n, i = a.shape.length, p = n.shape[s], u = new Array(i - 1), c = 0;
  for (let h = 0; h < i; h++) h !== s && (u[c++] = a.shape[h]);
  let l = [], m = new Array(i).fill(0), d = a.shape.slice();
  d[s] = 1;
  let f = new Array(p);
  for (let h = 0; h < f.length; h++) {
    m[s] = h;
    let g = Hs({ inputs: { x: a }, backend: t10, attrs: { begin: m, size: d } }), x = pe({ inputs: { x: g }, backend: t10, attrs: { shape: u } });
    f[h] = x, l.push(g);
  }
  return l.forEach((h) => t10.disposeData(h.dataId)), f;
}
var KU = { kernelName: wa, backendName: "webgpu", kernelFunc: Ace };
var by = class {
  constructor(e, t10, o) {
    if (this.outputShape = [], this.variableNames = ["x", "segmentIds"], this.uniforms = "numSegments : i32, xSize: i32,", this.workgroupSize = [64, 1, 1], this.atomic = true, this.outputShape = t10, this.dispatchLayout = X(e), this.dispatch = H(this.dispatchLayout, e, this.workgroupSize), o !== "float32" && o !== "int32") throw new Error(`UnsortedSegmentSum only supports float32 and int32
              types, does not support ${o} type.`);
    this.type = o, this.shaderKey = "unsortedSegmentSum";
  }
  getUserCode() {
    return `
    ${G("index")} {
      if (index < uniforms.xSize) {
        let coords = getXCoordsFromIndex(index);
        let b = coords[0];
        let inCol = coords[1];

        let segmentId = i32(getSegmentIds(inCol));
        if (segmentId >= 0) {
          let flatIndex = b * uniforms.numSegments + segmentId % uniforms.numSegments;
          let value = getX(b, inCol);

          ${Qr("&result[flatIndex]", "value", this.type)}
        }
      }
    }
  `;
  }
};
function Fce(r15) {
  let { inputs: e, backend: t10, attrs: o } = r15, { x: n, segmentIds: s } = e, { numSegments: a } = o, i = n.shape.length, p = [], u = 0, c = w.getAxesPermutation([u], i), l = n;
  c != null && (l = xr({ inputs: { x: n }, backend: t10, attrs: { perm: c } }), p.push(l), u = w.getInnerMostAxes(1, i)[0]);
  let m = w.segment_util.computeOutShape(l.shape, u, a), d = y.sizeFromShape([l.shape[u]]), f = pe({ inputs: { x: l }, backend: t10, attrs: { shape: [-1, d] } });
  p.push(f);
  let h = n.dtype, g = [f.shape[0], a], x = vt({ backend: t10, attrs: { shape: g, value: 0, dtype: h } }), b = new by(f.shape, g, h), C = [{ type: "int32", data: [a] }, { type: "int32", data: [y.sizeFromShape(f.shape)] }], S = t10.runWebGPUProgram(b, [f, s], h, C, x), k = pe({ inputs: { x: S }, backend: t10, attrs: { shape: m } });
  p.push(S);
  let _ = k;
  if (c != null) {
    p.push(k);
    let $ = w.getUndoAxesPermutation(c);
    _ = xr({ inputs: { x: _ }, backend: t10, attrs: { perm: $ } });
  }
  return p.forEach(($) => t10.disposeData($.dataId)), _;
}
var qU = { kernelName: Qi, backendName: "webgpu", kernelFunc: Fce };
var Pce = [pz, Kz, qz, jz, Xz, Yz, Zz, Jz, eV, tV, rV, oV, nV, sV, aV, pV, cV, lV, mV, dV, hV, gV, xV, wV, SV, IV, lz, kV, TV, _V, EV, $V, RV, DV, AV, FV, PV, OV, BV, zV, VV, WV, GV, HV, UV, KV, qV, jV, XV, YV, JV, eW, tW, rW, oW, nW, sW, aW, iW, iz, uW, lW, pW, cW, mW, dW, fW, hW, gW, xW, yW, cz, bW, NV, CW, wW, SW, IW, vW, kW, NW, _W, TW, EW, $W, RW, AW, FW, iV, PW, OW, BW, MW, LW, zW, uV, VW, WW, UW, GW, KW, QV, qW, jW, XW, yV, YW, JW, eU, tU, rU, oU, nU, sU, bV, aU, iU, uU, pU, uz, cU, lU, mU, dU, fU, hU, gU, xU, yU, bU, CU, wU, SU, IU, vU, kU, fV, OU, MU, LU, HW, NU, TU, _U, EU, RU, DU, AU, FU, PU, BU, ZV, zU, VU, WU, $U, GU, HU, Qz, KU, qU, QW];
for (let r15 of Pce) ti(r15);
var jU = "4.22.0";
var Oce = "4.22.0";
var Mce = "4.22.0";
var Lce = "4.22.0";
var Bce = "4.22.0";
var zce = "4.22.0";
var Vce = { tfjs: jU, "tfjs-core": jU, "tfjs-converter": Oce, "tfjs-backend-cpu": Mce, "tfjs-backend-webgl": Lce, "tfjs-backend-wasm": Bce, "tfjs-backend-webgpu": zce };
var EQt = void 0;

// src/util/util.ts
function log(...msg) {
  const dt2 = /* @__PURE__ */ 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);
}
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: expecting json file: ${path}`);
  return path;
}
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: "",
  cacheModels: true,
  validateModels: true,
  wasmPath: "",
  wasmPlatformFetch: false,
  debug: false,
  async: true,
  warmup: "full",
  cacheSensitivity: 0.7,
  skipAllowed: false,
  deallocate: false,
  flags: {},
  softwareKernels: false,
  filter: {
    enabled: true,
    equalization: false,
    width: 0,
    height: 0,
    flip: false,
    return: true,
    autoBrightness: 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: false,
      maxDetected: 1,
      skipFrames: 99,
      skipTime: 2500,
      minConfidence: 0.2,
      minSize: 0,
      iouThreshold: 0.1,
      scale: 1.4,
      mask: false,
      return: false
    },
    mesh: {
      enabled: true,
      modelPath: "facemesh.json",
      keepInvalid: false
    },
    attention: {
      enabled: false,
      modelPath: "facemesh-attention.json"
    },
    iris: {
      enabled: true,
      scale: 2.3,
      modelPath: "iris.json"
    },
    emotion: {
      enabled: true,
      minConfidence: 0.1,
      skipFrames: 99,
      skipTime: 1500,
      modelPath: "emotion.json"
    },
    description: {
      enabled: true,
      modelPath: "faceres.json",
      skipFrames: 99,
      skipTime: 3e3,
      minConfidence: 0.1
    },
    antispoof: {
      enabled: false,
      skipFrames: 99,
      skipTime: 4e3,
      modelPath: "antispoof.json"
    },
    liveness: {
      enabled: false,
      skipFrames: 99,
      skipTime: 4e3,
      modelPath: "liveness.json"
    }
  },
  body: {
    enabled: true,
    modelPath: "movenet-lightning.json",
    maxDetected: -1,
    minConfidence: 0.3,
    skipFrames: 1,
    skipTime: 200
  },
  hand: {
    enabled: true,
    rotation: true,
    skipFrames: 99,
    skipTime: 1e3,
    minConfidence: 0.5,
    iouThreshold: 0.2,
    maxDetected: -1,
    landmarks: true,
    detector: {
      modelPath: "handtrack.json"
    },
    skeleton: {
      modelPath: "handlandmark-lite.json"
    }
  },
  object: {
    enabled: false,
    modelPath: "centernet.json",
    minConfidence: 0.2,
    iouThreshold: 0.4,
    maxDetected: 10,
    skipFrames: 99,
    skipTime: 2e3
  },
  segmentation: {
    enabled: false,
    modelPath: "rvm.json",
    ratio: 0.5,
    mode: "default"
  }
};

// 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 r15 = new RegExp("\\b" + prefix + " \\w+ (\\w+)", "ig");
  source.replace(r15, (match2, name) => {
    collection[name] = 0;
    return match2;
  });
};
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);
      if (!shader) {
        log("filter: could not create shader");
        return null;
      }
      this.gl.shaderSource(shader, source);
      this.gl.compileShader(shader);
      if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) {
        log(`filter: gl compile failed: ${this.gl.getShaderInfoLog(shader) || "unknown"}`);
        return null;
      }
      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();
    if (!vertexShader || !fragmentShader) return;
    if (!this.id) {
      log("filter: could not create webgl program");
      return;
    }
    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)) {
      log(`filter: gl link failed: ${this.gl.getProgramInfoLog(this.id) || "unknown"}`);
      return;
    }
    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) {
    log("filter: cannot get webgl context");
    return;
  }
  this.gl = gl2;
  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(index2) {
    tempFramebuffers[index2] = tempFramebuffers[index2] || createFramebufferTexture(fxcanvas.width, fxcanvas.height);
    return tempFramebuffers[index2];
  }
  function draw(flags = 0) {
    if (!currentProgram) return;
    let source = null;
    let target = null;
    let flipY = false;
    if (drawCount === 0) source = sourceTexture;
    else source = getTempFramebuffer(currentFramebufferIndex).texture || null;
    drawCount++;
    if (lastInChain && !(flags & DRAW.INTERMEDIATE)) {
      target = null;
      flipY = drawCount % 2 === 0;
    } else {
      currentFramebufferIndex = (currentFramebufferIndex + 1) % 2;
      target = getTempFramebuffer(currentFramebufferIndex).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 ? currentProgram.id : null) || null);
      return currentProgram;
    }
    currentProgram = new GLProgram(gl2, vertexIdentity, fragmentSource);
    if (!currentProgram) {
      log("filter: could not get webgl program");
      return null;
    }
    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);
      if (!program) return;
      gl2.uniform1fv(program.uniform["m"], m);
      draw();
    },
    brightness: (brightness) => {
      const b = (brightness || 0) + 1;
      filter.colorMatrix([
        b,
        0,
        0,
        0,
        0,
        0,
        b,
        0,
        0,
        0,
        0,
        0,
        b,
        0,
        0,
        0,
        0,
        0,
        1,
        0
      ]);
    },
    saturation: (amount) => {
      const x = (amount || 0) * 2 / 3 + 1;
      const y8 = (x - 1) * -0.5;
      filter.colorMatrix([
        x,
        y8,
        y8,
        0,
        0,
        y8,
        x,
        y8,
        0,
        0,
        y8,
        y8,
        x,
        0,
        0,
        0,
        0,
        0,
        1,
        0
      ]);
    },
    desaturate: () => {
      filter.saturation(-1);
    },
    contrast: (amount) => {
      const v8 = (amount || 0) + 1;
      const o = -128 * (v8 - 1);
      filter.colorMatrix([
        v8,
        0,
        0,
        0,
        o,
        0,
        v8,
        0,
        0,
        o,
        0,
        0,
        v8,
        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);
      if (!program) return;
      gl2.uniform1fv(program.uniform["m"], m);
      gl2.uniform2f(program.uniform["px"], pixelSizeX, pixelSizeY);
      draw();
    },
    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);
      if (!program) return;
      gl2.uniform2f(program.uniform["px"], 0, blurSizeY);
      draw(DRAW.INTERMEDIATE);
      gl2.uniform2f(program.uniform["px"], blurSizeX, 0);
      draw();
    },
    pixelate: (size2) => {
      const blurSizeX = size2 / fxcanvas.width;
      const blurSizeY = size2 / fxcanvas.height;
      const program = compileShader(pixelate);
      if (!program) return;
      gl2.uniform2f(program.uniform["size"], blurSizeX, blurSizeY);
      draw();
    }
  };
  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(image) {
    resize(image.width, image.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, image);
    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(image) {
    this.add("brightness", 0);
    return this.apply(image);
  };
}

// src/image/enhance.ts
async function histogramEqualization(inputImage) {
  const squeeze = inputImage.shape.length === 4 ? cc(inputImage) : inputImage;
  const rgb3 = li(squeeze, 3, 2);
  const min = [Nl(rgb3[0]), Nl(rgb3[1]), Nl(rgb3[2])];
  const max = [Ra(rgb3[0]), Ra(rgb3[1]), Ra(rgb3[2])];
  const absMax = await Promise.all(max.map((channel) => channel.data()));
  const maxValue = Math.max(absMax[0][0], absMax[1][0], absMax[2][0]);
  const maxRange = maxValue > 1 ? 255 : 1;
  const factor = maxRange / maxValue;
  let final;
  if (factor > 1) {
    const sub = [Te(rgb3[0], min[0]), Te(rgb3[1], min[1]), Te(rgb3[2], min[2])];
    const range = [Te(max[0], min[0]), Te(max[1], min[1]), Te(max[2], min[2])];
    const enh = [se(sub[0], factor), se(sub[1], factor), se(sub[2], factor)];
    const stack = vr([enh[0], enh[1], enh[2]], 2);
    final = W(stack, [1, squeeze.shape[0] || 0, squeeze.shape[1] || 0, 3]);
    Ot([...sub, ...range, ...enh, stack]);
  } else {
    final = Ms(squeeze, 0);
  }
  Ot([...rgb3, ...min, ...max, rgb3, squeeze, inputImage]);
  return final;
}

// src/image/image.ts
var maxSize = 3840;
var inCanvas = null;
var outCanvas = null;
var tmpCanvas = null;
var fx2;
var last = {
  inputSum: 0,
  cacheDiff: 1,
  sumMethod: 0,
  inputTensor: void 0
};
function reset() {
  last.inputSum = 0;
  last.cacheDiff = 1;
  last.sumMethod = 0;
  last.inputTensor = void 0;
}
function canvas(width, height) {
  let c;
  if (env.browser) {
    if (env.worker) {
      if (typeof OffscreenCanvas === "undefined") throw new Error("canvas error: attempted to run in web worker but OffscreenCanvas is not supported");
      c = new OffscreenCanvas(width, height);
    } else {
      if (typeof document !== "undefined") {
        c = document.createElement("canvas");
        c.width = width;
        c.height = height;
      } else if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
        if (typeof env.Canvas !== "undefined") c = new env.Canvas(width, height);
        else if (typeof globalThis.Canvas !== "undefined") c = new globalThis.Canvas(width, height);
        else throw new Error("canvas error: attempted to use canvas in react-native without canvas support installed");
      } else {
        throw new Error("canvas error: attempted to run in browser but DOM is not defined");
      }
    }
  } 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;
}
async function process2(input, config3, getTensor = true) {
  var _a, _b, _c2;
  if (!input) {
    if (config3.debug) log("input error: input is missing");
    return { tensor: null, canvas: null };
  }
  if (!(input instanceof mt) && !(typeof Image !== "undefined" && input instanceof Image) && !(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 error: type not recognized");
  }
  if (input instanceof mt) {
    let tensor3 = null;
    if (input["isDisposedInternal"]) throw new Error("input error: attempted to use tensor but it is disposed");
    if (!input.shape) throw new Error("input error: attempted to use tensor without a shape");
    if (input.shape.length === 3) {
      if (input.shape[2] === 3) {
        tensor3 = Ms(input, 0);
      } else if (input.shape[2] === 4) {
        const rgb3 = B1(input, [0, 0, 0], [-1, -1, 3]);
        tensor3 = Ms(rgb3, 0);
        Ot(rgb3);
      }
    } else if (input.shape.length === 4) {
      if (input.shape[3] === 3) {
        tensor3 = Ur(input);
      } else if (input.shape[3] === 4) {
        tensor3 = z1(input, [0, 0, 0, 0], [-1, -1, -1, 3]);
      }
    }
    if (tensor3 == null || tensor3.shape.length !== 4 || tensor3.shape[0] !== 1 || tensor3.shape[3] !== 3) throw new Error(`input error: attempted to use tensor with unrecognized shape: ${input.shape.toString()}`);
    if (tensor3.dtype === "int32") {
      const cast = Ue(tensor3, "float32");
      Ot(tensor3);
      tensor3 = cast;
    }
    return { tensor: tensor3, canvas: config3.filter.return ? outCanvas : null };
  }
  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 ((((_a = config3.filter) == null ? void 0 : _a.width) || 0) > 0) targetWidth = config3.filter.width;
  else if ((((_b = config3.filter) == null ? void 0 : _b.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 error: cannot determine dimension");
  if (!inCanvas || inCanvas.width !== targetWidth || 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.width, inCanvas.height);
      inCtx.setTransform(1, 0, 0, 1, 0, 0);
    } else {
      inCtx.drawImage(input, 0, 0, originalWidth, originalHeight, 0, 0, inCanvas.width, inCanvas.height);
    }
  }
  if (!outCanvas || inCanvas.width !== outCanvas.width || inCanvas.height !== 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 == null ? void 0 : fx2.add)) {
      if (config3.debug) log("input process error: cannot initialize filters");
      env.webgl.supported = false;
      config3.filter.enabled = false;
      copy(inCanvas, outCanvas);
    } else {
      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 (((_c2 = fx2.get()) == null ? void 0 : _c2.length) > 1) 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("canvas error: cannot create output");
  let pixels;
  let depth = 3;
  if (typeof ImageData !== "undefined" && input instanceof ImageData || input.data && input.width && input.height) {
    if (env.browser && cT) {
      pixels = cT ? cT.fromPixels(input) : null;
    } else {
      depth = input.data.length / input.height / input.width;
      const arr = new Uint8Array(input.data.buffer);
      pixels = ar(arr, [input.height, input.width, depth], "int32");
    }
  } else {
    if (!tmpCanvas || outCanvas.width !== tmpCanvas.width || outCanvas.height !== tmpCanvas.height) tmpCanvas = canvas(outCanvas.width, outCanvas.height);
    if (cT && env.browser) {
      if (config3.backend === "webgl" || config3.backend === "humangl" || config3.backend === "webgpu") {
        pixels = cT.fromPixels(outCanvas);
      } else {
        tmpCanvas = copy(outCanvas);
        pixels = cT.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 = ar(arr, [targetWidth, targetHeight, depth]);
    }
  }
  if (depth === 4) {
    const rgb3 = B1(pixels, [0, 0, 0], [-1, -1, 3]);
    Ot(pixels);
    pixels = rgb3;
  }
  if (!pixels) throw new Error("input error: cannot create tensor");
  const casted = Ue(pixels, "float32");
  const tensor2 = config3.filter.equalization ? await histogramEqualization(casted) : Ms(casted, 0);
  Ot([pixels, casted]);
  if (config3.filter.autoBrightness) {
    const max = Ra(tensor2);
    const maxVal = await max.data();
    config3.filter.brightness = maxVal[0] > 1 ? 1 - maxVal[0] / 255 : 1 - maxVal[0];
    Ot(max);
  }
  return { tensor: tensor2, canvas: config3.filter.return ? outCanvas : null };
}
async function skip(config3, input) {
  let skipFrame = false;
  if (config3.cacheSensitivity === 0 || !input.shape || input.shape.length !== 4 || input.shape[1] > 3840 || input.shape[2] > 2160) return skipFrame;
  if (!last.inputTensor) {
    last.inputTensor = Ur(input);
  } else if (last.inputTensor.shape[1] !== input.shape[1] || last.inputTensor.shape[2] !== input.shape[2]) {
    Ot(last.inputTensor);
    last.inputTensor = Ur(input);
  } else {
    const t10 = {};
    t10.diff = Te(input, last.inputTensor);
    t10.squared = se(t10.diff, t10.diff);
    t10.sum = ot(t10.squared);
    const diffSum = await t10.sum.data();
    const diffRelative = diffSum[0] / (input.shape[1] || 1) / (input.shape[2] || 1) / 255 / 3;
    Ot([last.inputTensor, t10.diff, t10.squared, t10.sum]);
    last.inputTensor = Ur(input);
    skipFrame = diffRelative <= (config3.cacheSensitivity || 0);
  }
  return skipFrame;
}
async function compare(config3, input1, input2) {
  const t10 = {};
  if (!input1 || !input2 || input1.shape.length !== 4 || input1.shape.length !== input2.shape.length) {
    if (!config3.debug) log("invalid input tensor or tensor shapes do not match:", input1.shape, input2.shape);
    return 0;
  }
  if (input1.shape[0] !== 1 || input2.shape[0] !== 1 || input1.shape[3] !== 3 || input2.shape[3] !== 3) {
    if (!config3.debug) log("input tensors must be of shape [1, height, width, 3]:", input1.shape, input2.shape);
    return 0;
  }
  t10.input1 = Ur(input1);
  t10.input2 = input1.shape[1] !== input2.shape[1] || input1.shape[2] !== input2.shape[2] ? eX.resizeBilinear(input2, [input1.shape[1], input1.shape[2]]) : Ur(input2);
  t10.diff = Te(t10.input1, t10.input2);
  t10.squared = se(t10.diff, t10.diff);
  t10.sum = ot(t10.squared);
  const diffSum = await t10.sum.data();
  const diffRelative = diffSum[0] / (input1.shape[1] || 1) / (input1.shape[2] || 1) / 255 / 3;
  Ot([t10.input1, t10.input2, t10.diff, t10.squared, t10.sum]);
  return diffRelative;
}

// src/util/env.ts
var _canvas, _image, _imageData;
var Env = class {
  constructor() {
    /** Running in Browser */
    __publicField(this, "browser");
    /** Running in NodeJS */
    __publicField(this, "node");
    /** Running in WebWorker thread */
    __publicField(this, "worker");
    /** Detected platform */
    __publicField(this, "platform", "");
    /** Detected agent */
    __publicField(this, "agent", "");
    /** List of supported backends */
    __publicField(this, "backends", []);
    /** Has any work been performed so far */
    __publicField(this, "initial");
    /** Are image filters supported? */
    __publicField(this, "filter");
    /** TFJS instance details */
    __publicField(this, "tfjs");
    /** Is offscreenCanvas supported? */
    __publicField(this, "offscreen");
    /** Are performance counter instant values or additive */
    __publicField(this, "perfadd", false);
    /** If using tfjs-node get version of underlying tensorflow shared library and if gpu acceleration is enabled */
    __publicField(this, "tensorflow", {
      version: void 0,
      gpu: void 0
    });
    /** WASM detected capabilities */
    __publicField(this, "wasm", {
      supported: void 0,
      backend: void 0,
      simd: void 0,
      multithread: void 0
    });
    /** WebGL detected capabilities */
    __publicField(this, "webgl", {
      supported: void 0,
      backend: void 0,
      version: void 0,
      renderer: void 0,
      shader: void 0,
      vendor: void 0
    });
    /** WebGPU detected capabilities */
    __publicField(this, "webgpu", {
      supported: void 0,
      backend: void 0,
      adapter: void 0
    });
    /** CPU info */
    __publicField(this, "cpu", {
      model: void 0,
      flags: []
    });
    /** List of supported kernels for current backend */
    __publicField(this, "kernels", []);
    /** MonkeyPatch for Canvas/Image/ImageData */
    __privateAdd(this, _canvas);
    __privateAdd(this, _image);
    __privateAdd(this, _imageData);
    this.browser = typeof navigator !== "undefined" && typeof navigator.appVersion !== "undefined";
    this.node = typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined";
    this.tfjs = { version: Vce["tfjs-core"] };
    this.offscreen = typeof OffscreenCanvas !== "undefined";
    this.initial = true;
    this.worker = this.browser && this.offscreen ? typeof WorkerGlobalScope !== "undefined" : void 0;
    if (typeof navigator !== "undefined" && typeof navigator.userAgent !== "undefined") {
      const agent = navigator.userAgent || "";
      const raw = agent.match(/\(([^()]+)\)/g);
      if (raw == null ? void 0 : raw[0]) {
        const platformMatch = raw[0].match(/\(([^()]+)\)/g);
        this.platform = (platformMatch == null ? void 0 : platformMatch[0]) ? platformMatch[0].replace(/\(|\)/g, "") : "";
        this.agent = agent.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}`;
    }
  }
  get Canvas() {
    return __privateGet(this, _canvas);
  }
  set Canvas(val) {
    __privateSet(this, _canvas, val);
    globalThis.Canvas = val;
  }
  get Image() {
    return __privateGet(this, _image);
  }
  // @ts-ignore monkey-patch;
  set Image(val) {
    __privateSet(this, _image, val);
    globalThis.Image = val;
  }
  get ImageData() {
    return __privateGet(this, _imageData);
  }
  // @ts-ignore monkey-patch;
  set ImageData(val) {
    __privateSet(this, _imageData, val);
    globalThis.ImageData = val;
  }
  /** update backend information */
  async updateBackend() {
    this.backends = Object.keys(ur().registryFactory);
    try {
      this.tensorflow = {
        version: ak()["binding"] ? ak()["binding"].TF_Version : void 0,
        gpu: ak()["binding"] ? ak()["binding"].isUsingGpuDevice() : void 0
      };
    } catch (e) {
    }
    this.wasm.supported = typeof WebAssembly !== "undefined";
    this.wasm.backend = this.backends.includes("wasm");
    if (this.wasm.supported && this.wasm.backend) {
      this.wasm.simd = await A().getAsync("WASM_HAS_SIMD_SUPPORT");
      this.wasm.multithread = await A().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");
    }
    const c = canvas(100, 100);
    const gl2 = c ? c.getContext("webgl2") : void 0;
    this.webgl.supported = typeof gl2 !== "undefined";
    this.webgl.backend = this.backends.includes("webgl");
    if (this.webgl.supported && this.webgl.backend && gl2) {
      this.webgl.version = gl2.getParameter(gl2.VERSION);
      this.webgl.vendor = gl2.getParameter(gl2.VENDOR);
      this.webgl.renderer = gl2.getParameter(gl2.RENDERER);
      this.webgl.shader = gl2.getParameter(gl2.SHADING_LANGUAGE_VERSION);
    }
    this.webgpu.supported = this.browser && typeof navigator !== "undefined" && typeof navigator.gpu !== "undefined";
    this.webgpu.backend = this.backends.includes("webgpu");
    try {
      if (this.webgpu.supported) {
        const adapter = await navigator.gpu.requestAdapter();
        if (adapter) {
          if ("requestAdapterInfo" in adapter) this.webgpu.adapter = await adapter.requestAdapterInfo();
          else this.webgpu.adapter = await adapter.info;
        }
      }
    } catch (e) {
      this.webgpu.supported = false;
    }
    try {
      this.kernels = Ym(sk()).map((kernel) => kernel.kernelName.toLowerCase());
    } catch (e) {
    }
  }
  /** update cpu information */
  updateCPU() {
    const cpu = { model: "", flags: [] };
    if (this.node && this.platform.startsWith("linux")) {
    }
    if (!this.cpu) Object.defineProperty(this, "cpu", { value: cpu });
    else this.cpu = cpu;
  }
};
_canvas = new WeakMap();
_image = new WeakMap();
_imageData = new WeakMap();
var env = new Env();

// src/util/webcam.ts
var WebCam = class {
  constructor() {
    // eslint-disable-line @typescript-eslint/no-extraneous-class
    /** current webcam configuration */
    __publicField(this, "config");
    /** instance of dom element associated with webcam stream */
    __publicField(this, "element");
    /** active webcam stream */
    __publicField(this, "stream");
    /** enumerated video devices */
    __publicField(this, "devices", []);
    __publicField(this, "enumerate", async () => {
      try {
        const devices = await navigator.mediaDevices.enumerateDevices();
        this.devices = devices.filter((device) => device.kind === "videoinput");
      } catch (e) {
        this.devices = [];
      }
      return this.devices;
    });
    /** start method initializizes webcam stream and associates it with a dom video element */
    __publicField(this, "start", async (webcamConfig) => {
      var _a, _b;
      if (webcamConfig == null ? void 0 : webcamConfig.debug) this.config.debug = webcamConfig == null ? void 0 : webcamConfig.debug;
      if (webcamConfig == null ? void 0 : webcamConfig.crop) this.config.crop = webcamConfig == null ? void 0 : webcamConfig.crop;
      if (webcamConfig == null ? void 0 : webcamConfig.mode) this.config.mode = webcamConfig == null ? void 0 : webcamConfig.mode;
      if (webcamConfig == null ? void 0 : webcamConfig.width) this.config.width = webcamConfig == null ? void 0 : webcamConfig.width;
      if (webcamConfig == null ? void 0 : webcamConfig.height) this.config.height = webcamConfig == null ? void 0 : webcamConfig.height;
      if (webcamConfig == null ? void 0 : webcamConfig.id) this.config.id = webcamConfig == null ? void 0 : webcamConfig.id;
      if (webcamConfig == null ? void 0 : webcamConfig.element) {
        if (typeof webcamConfig.element === "string") {
          const el2 = document.getElementById(webcamConfig.element);
          if (el2 && el2 instanceof HTMLVideoElement) {
            this.element = el2;
          } else {
            if (this.config.debug) log("webcam", "cannot get dom element", webcamConfig.element);
            return `webcam error: cannot get dom element: ${webcamConfig.element}`;
          }
        } else if (webcamConfig.element instanceof HTMLVideoElement) {
          this.element = webcamConfig.element;
        } else {
          if (this.config.debug) log("webcam", "unknown dom element", webcamConfig.element);
          return `webcam error: unknown dom element: ${webcamConfig.element}`;
        }
      } else {
        this.element = document.createElement("video");
      }
      const requestedConstraints = {
        audio: false,
        video: {
          facingMode: this.config.mode === "front" ? "user" : "environment",
          // @ts-ignore // resizeMode is still not defined in tslib
          resizeMode: this.config.crop ? "crop-and-scale" : "none"
        }
      };
      if (((_a = this.config) == null ? void 0 : _a.width) > 0) requestedConstraints.video.width = { ideal: this.config.width };
      if (((_b = this.config) == null ? void 0 : _b.height) > 0) requestedConstraints.video.height = { ideal: this.config.height };
      if (this.config.id) requestedConstraints.video.deviceId = this.config.id;
      this.element.addEventListener("play", () => {
        if (this.config.debug) log("webcam", "play");
      });
      this.element.addEventListener("pause", () => {
        if (this.config.debug) log("webcam", "pause");
      });
      this.element.addEventListener("click", async () => {
        if (!this.element || !this.stream) return;
        if (this.element.paused) await this.element.play();
        else this.element.pause();
      });
      if (!(navigator == null ? void 0 : navigator.mediaDevices)) {
        if (this.config.debug) log("webcam error", "no devices");
        return "webcam error: no devices";
      }
      try {
        this.stream = await navigator.mediaDevices.getUserMedia(requestedConstraints);
      } catch (err) {
        log("webcam", err);
        return `webcam error: ${err}`;
      }
      if (!this.stream) {
        if (this.config.debug) log("webcam error", "no stream");
        return "webcam error no stream";
      }
      this.element.srcObject = this.stream;
      const ready = new Promise((resolve) => {
        if (!this.element) resolve(false);
        else this.element.onloadeddata = () => resolve(true);
      });
      await ready;
      await this.element.play();
      if (this.config.debug) {
        log("webcam", {
          width: this.width,
          height: this.height,
          label: this.label,
          stream: this.stream,
          track: this.track,
          settings: this.settings,
          constraints: this.constraints,
          capabilities: this.capabilities
        });
      }
      return `webcam: ${this.label}`;
    });
    /** pause webcam video method */
    __publicField(this, "pause", () => {
      if (this.element) this.element.pause();
    });
    /** play webcam video method */
    __publicField(this, "play", async () => {
      if (this.element) await this.element.play();
    });
    /** stop method stops active webcam stream track and disconnects webcam */
    __publicField(this, "stop", () => {
      if (this.config.debug) log("webcam", "stop");
      if (this.track) this.track.stop();
    });
    this.config = {
      element: void 0,
      debug: true,
      mode: "front",
      crop: false,
      width: 0,
      height: 0
    };
  }
  /** get active webcam stream track */
  get track() {
    if (!this.stream) return void 0;
    return this.stream.getVideoTracks()[0];
  }
  /** get webcam capabilities */
  get capabilities() {
    if (!this.track) return void 0;
    return this.track.getCapabilities ? this.track.getCapabilities() : void 0;
  }
  /** get webcam constraints */
  get constraints() {
    if (!this.track) return void 0;
    return this.track.getConstraints ? this.track.getConstraints() : void 0;
  }
  /** get webcam settings */
  get settings() {
    if (!this.stream) return void 0;
    const track = this.stream.getVideoTracks()[0];
    return track.getSettings ? track.getSettings() : void 0;
  }
  /** get webcam label */
  get label() {
    if (!this.track) return "";
    return this.track.label;
  }
  /** is webcam paused */
  get paused() {
    var _a;
    return ((_a = this.element) == null ? void 0 : _a.paused) || false;
  }
  /** webcam current width */
  get width() {
    var _a;
    return ((_a = this.element) == null ? void 0 : _a.videoWidth) || 0;
  }
  /** webcam current height */
  get height() {
    var _a;
    return ((_a = this.element) == null ? void 0 : _a.videoHeight) || 0;
  }
};

// models/models.json
var models_exports = {};
__export(models_exports, {
  "affectnet-mobilenet": () => affectnet_mobilenet,
  age: () => age,
  "anti-spoofing": () => anti_spoofing,
  antispoof: () => antispoof,
  blazeface: () => blazeface,
  "blazeface-back": () => blazeface_back,
  "blazeface-front": () => blazeface_front,
  "blazepose-detector": () => blazepose_detector,
  "blazepose-full": () => blazepose_full,
  "blazepose-heavy": () => blazepose_heavy,
  "blazepose-lite": () => blazepose_lite,
  centernet: () => centernet,
  default: () => models_default,
  efficientpose: () => efficientpose,
  "efficientpose-i-lite": () => efficientpose_i_lite,
  "efficientpose-ii-lite": () => efficientpose_ii_lite,
  "efficientpose-iv": () => efficientpose_iv,
  emotion: () => emotion,
  faceboxes: () => faceboxes,
  facemesh: () => facemesh,
  "facemesh-attention": () => facemesh_attention,
  "facemesh-attention-pinto": () => facemesh_attention_pinto,
  "facemesh-detection-full": () => facemesh_detection_full,
  "facemesh-detection-short": () => facemesh_detection_short,
  faceres: () => faceres,
  "faceres-deep": () => faceres_deep,
  gear: () => gear,
  "gear-e1": () => gear_e1,
  "gear-e2": () => gear_e2,
  gender: () => gender,
  "gender-ssrnet-imdb": () => gender_ssrnet_imdb,
  handdetect: () => handdetect,
  "handlandmark-full": () => handlandmark_full,
  "handlandmark-lite": () => handlandmark_lite,
  "handlandmark-sparse": () => handlandmark_sparse,
  handskeleton: () => handskeleton,
  handtrack: () => handtrack,
  "insightface-efficientnet-b0": () => insightface_efficientnet_b0,
  "insightface-ghostnet-strides1": () => insightface_ghostnet_strides1,
  "insightface-ghostnet-strides2": () => insightface_ghostnet_strides2,
  "insightface-mobilenet-emore": () => insightface_mobilenet_emore,
  "insightface-mobilenet-swish": () => insightface_mobilenet_swish,
  iris: () => iris,
  liveness: () => liveness,
  meet: () => meet,
  mobileface: () => mobileface,
  mobilefacenet: () => mobilefacenet,
  models: () => models,
  "movenet-lightning": () => movenet_lightning,
  "movenet-multipose": () => movenet_multipose,
  "movenet-thunder": () => movenet_thunder,
  nanodet: () => nanodet,
  "nanodet-e": () => nanodet_e,
  "nanodet-g": () => nanodet_g,
  "nanodet-m": () => nanodet_m,
  "nanodet-t": () => nanodet_t,
  posenet: () => posenet,
  rvm: () => rvm,
  selfie: () => selfie
});
var antispoof = 853098;
var blazeface = 538928;
var centernet = 4030290;
var emotion = 820516;
var facemesh = 1477958;
var faceres = 6978814;
var handlandmark_lite = 2023432;
var handtrack = 2964837;
var iris = 2599092;
var liveness = 592976;
var models = 0;
var movenet_lightning = 4650216;
var affectnet_mobilenet = 6920630;
var age = 161240;
var blazeface_back = 538928;
var blazeface_front = 402048;
var blazepose_detector = 5928856;
var blazepose_full = 6339202;
var blazepose_heavy = 27502466;
var blazepose_lite = 2726402;
var efficientpose = 5651240;
var faceboxes = 2013002;
var facemesh_attention_pinto = 2387598;
var facemesh_attention = 2382414;
var facemesh_detection_full = 1026192;
var facemesh_detection_short = 201268;
var faceres_deep = 13957620;
var gear_e1 = 112438;
var gear_e2 = 112438;
var gear = 1498916;
var gender_ssrnet_imdb = 161236;
var gender = 201808;
var handdetect = 3515612;
var handlandmark_full = 5431368;
var handlandmark_sparse = 5286322;
var handskeleton = 5502280;
var meet = 372228;
var mobileface = 2183192;
var mobilefacenet = 5171976;
var movenet_multipose = 9448838;
var movenet_thunder = 12477112;
var nanodet = 7574558;
var posenet = 5032780;
var rvm = 3739355;
var selfie = 212886;
var anti_spoofing = 853098;
var efficientpose_i_lite = 2269064;
var efficientpose_ii_lite = 5651240;
var efficientpose_iv = 25643252;
var insightface_efficientnet_b0 = 13013224;
var insightface_ghostnet_strides1 = 8093408;
var insightface_ghostnet_strides2 = 8049584;
var insightface_mobilenet_emore = 6938536;
var insightface_mobilenet_swish = 12168584;
var nanodet_e = 12319156;
var nanodet_g = 7574558;
var nanodet_m = 1887474;
var nanodet_t = 5294216;
var models_default = {
  antispoof,
  blazeface,
  centernet,
  emotion,
  facemesh,
  faceres,
  "handlandmark-lite": handlandmark_lite,
  handtrack,
  iris,
  liveness,
  models,
  "movenet-lightning": movenet_lightning,
  "affectnet-mobilenet": affectnet_mobilenet,
  age,
  "blazeface-back": blazeface_back,
  "blazeface-front": blazeface_front,
  "blazepose-detector": blazepose_detector,
  "blazepose-full": blazepose_full,
  "blazepose-heavy": blazepose_heavy,
  "blazepose-lite": blazepose_lite,
  efficientpose,
  faceboxes,
  "facemesh-attention-pinto": facemesh_attention_pinto,
  "facemesh-attention": facemesh_attention,
  "facemesh-detection-full": facemesh_detection_full,
  "facemesh-detection-short": facemesh_detection_short,
  "faceres-deep": faceres_deep,
  "gear-e1": gear_e1,
  "gear-e2": gear_e2,
  gear,
  "gender-ssrnet-imdb": gender_ssrnet_imdb,
  gender,
  handdetect,
  "handlandmark-full": handlandmark_full,
  "handlandmark-sparse": handlandmark_sparse,
  handskeleton,
  meet,
  mobileface,
  mobilefacenet,
  "movenet-multipose": movenet_multipose,
  "movenet-thunder": movenet_thunder,
  nanodet,
  posenet,
  rvm,
  selfie,
  "anti-spoofing": anti_spoofing,
  "efficientpose-i-lite": efficientpose_i_lite,
  "efficientpose-ii-lite": efficientpose_ii_lite,
  "efficientpose-iv": efficientpose_iv,
  "insightface-efficientnet-b0": insightface_efficientnet_b0,
  "insightface-ghostnet-strides1": insightface_ghostnet_strides1,
  "insightface-ghostnet-strides2": insightface_ghostnet_strides2,
  "insightface-mobilenet-emore": insightface_mobilenet_emore,
  "insightface-mobilenet-swish": insightface_mobilenet_swish,
  "nanodet-e": nanodet_e,
  "nanodet-g": nanodet_g,
  "nanodet-m": nanodet_m,
  "nanodet-t": nanodet_t
};

// src/tfjs/load.ts
var options = {
  cacheModels: true,
  cacheSupported: true,
  verbose: true,
  debug: false,
  modelBasePath: ""
};
var modelStats = {};
async function httpHandler(url, init4) {
  if (options.debug) log("load model fetch:", url, init4);
  return fetch(url, init4);
}
function setModelLoadOptions(config3) {
  options.cacheModels = config3.cacheModels;
  options.verbose = config3.debug;
  options.modelBasePath = config3.modelBasePath;
}
async function loadModel(modelPath) {
  var _a, _b, _c2, _d2, _e, _f2;
  let modelUrl = join(options.modelBasePath, modelPath || "");
  if (!modelUrl.toLowerCase().endsWith(".json")) modelUrl += ".json";
  const modelPathSegments = modelUrl.includes("/") ? modelUrl.split("/") : modelUrl.split("\\");
  const shortModelName = modelPathSegments[modelPathSegments.length - 1].replace(".json", "");
  const cachedModelName = "indexeddb://" + shortModelName;
  modelStats[shortModelName] = {
    name: shortModelName,
    loaded: false,
    sizeFromManifest: 0,
    sizeLoadedWeights: 0,
    sizeDesired: models_exports[shortModelName],
    inCache: false,
    url: ""
  };
  options.cacheSupported = typeof indexedDB !== "undefined";
  let cachedModels = {};
  try {
    cachedModels = options.cacheSupported && options.cacheModels ? await di.listModels() : {};
  } catch (e) {
    options.cacheSupported = false;
  }
  modelStats[shortModelName].inCache = options.cacheSupported && options.cacheModels && Object.keys(cachedModels).includes(cachedModelName);
  modelStats[shortModelName].url = modelStats[shortModelName].inCache ? cachedModelName : modelUrl;
  const tfLoadOptions = typeof fetch === "undefined" ? {} : { fetchFunc: (url, init4) => httpHandler(url, init4) };
  let model23 = new Bl(modelStats[shortModelName].url, tfLoadOptions);
  modelStats[shortModelName].loaded = false;
  try {
    model23.findIOHandler();
    if (options.debug) log("model load handler:", model23["handler"]);
  } catch (err) {
    log("error finding model i/o handler:", modelUrl, err);
  }
  try {
    const artifacts = await ((_a = model23.handler) == null ? void 0 : _a.load()) || null;
    modelStats[shortModelName].sizeFromManifest = ((_b = artifacts == null ? void 0 : artifacts.weightData) == null ? void 0 : _b.byteLength) || 0;
    if (artifacts) model23.loadSync(artifacts);
    else model23 = await M8(modelStats[shortModelName].inCache ? cachedModelName : modelUrl, tfLoadOptions);
    modelStats[shortModelName].sizeLoadedWeights = ((_d2 = (_c2 = model23.artifacts) == null ? void 0 : _c2.weightData) == null ? void 0 : _d2.byteLength) || ((_f2 = (_e = model23.artifacts) == null ? void 0 : _e.weightData) == null ? void 0 : _f2[0].byteLength) || 0;
    if (options.verbose) log("load:", { model: shortModelName, url: model23["modelUrl"], bytes: modelStats[shortModelName].sizeLoadedWeights });
    modelStats[shortModelName].loaded = true;
  } catch (err) {
    log("error loading model:", modelUrl, err);
  }
  if (modelStats[shortModelName].loaded && options.cacheModels && options.cacheSupported && !modelStats[shortModelName].inCache) {
    try {
      const saveResult = await model23.save(cachedModelName);
      if (options.debug) log("model saved:", cachedModelName, saveResult);
    } catch (err) {
      log("error saving model:", modelUrl, err);
    }
  }
  return model23;
}

// package.json
var version = "3.3.6";

// src/tfjs/humangl.ts
var config2 = {
  name: "humangl",
  priority: 999,
  canvas: null,
  gl: null,
  extensions: [],
  webGLattr: {
    // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.2
    alpha: false,
    antialias: false,
    premultipliedAlpha: false,
    preserveDrawingBuffer: false,
    depth: false,
    stencil: false,
    failIfMajorPerformanceCaveat: false,
    // default=true
    desynchronized: true
    // default=undefined
  }
};
function extensions() {
  const gl2 = config2.gl;
  if (!gl2) return;
  config2.extensions = gl2.getSupportedExtensions();
}
function register(instance) {
  var _a;
  if (instance.config.backend !== "humangl") return;
  if (config2.name in ur().registry && !((_a = config2 == null ? void 0 : config2.gl) == null ? void 0 : _a.getParameter(config2.gl.VERSION))) {
    log("humangl error: backend invalid context");
    instance.models.reset();
  }
  if (!kme(config2.name)) {
    try {
      config2.canvas = canvas(100, 100);
    } catch (err) {
      log("humangl error: cannot create canvas:", err);
      return;
    }
    try {
      config2.gl = config2.canvas.getContext("webgl2", config2.webGLattr);
      if (!config2.gl) {
        log("humangl error: cannot get webgl context");
        return;
      }
      const glv2 = config2.gl.getParameter(config2.gl.VERSION).includes("2.0");
      if (!glv2) {
        log("backend override: using fallback webgl backend as webgl 2.0 is not detected");
        instance.config.backend = "webgl";
        return;
      }
      if (config2.canvas) {
        config2.canvas.addEventListener("webglcontextlost", (e) => {
          log("humangl error:", e.type);
          log("possible browser memory leak using webgl or conflict with multiple backend registrations");
          instance.emit("error");
          throw new Error("backend error: webgl context lost");
        });
        config2.canvas.addEventListener("webglcontextrestored", (e) => {
          log("humangl error: context restored:", e);
        });
        config2.canvas.addEventListener("webglcontextcreationerror", (e) => {
          log("humangl error: context create:", e);
        });
      }
    } catch (err) {
      log("humangl error: cannot get webgl context:", err);
      return;
    }
    try {
      NI(2, config2.gl);
    } catch (err) {
      log("humangl error: cannot set webgl context:", err);
      return;
    }
    try {
      const ctx = new bp(config2.gl);
      tu(config2.name, () => new Lc(ctx), config2.priority);
    } catch (err) {
      log("humangl error: cannot register webgl backend:", err);
      return;
    }
    try {
      const kernels = Ym("webgl");
      kernels.forEach((kernelConfig) => {
        const newKernelConfig = { ...kernelConfig, backendName: config2.name };
        ti(newKernelConfig);
      });
    } catch (err) {
      log("humangl error: cannot update webgl backend registration:", err);
      return;
    }
    try {
      if (A().flagRegistry.WEBGL_VERSION) A().set("WEBGL_VERSION", 2);
    } catch (err) {
      log("humangl error: cannot set WebGL backend flags:", err);
      return;
    }
    extensions();
    const backend = ak();
    const current = typeof backend["gpgpu"] !== "undefined" ? backend["getGPGPUContext"]().gl : null;
    if (current) {
      if (instance.config.debug) log("humangl backend registered:", { webgl: current.getParameter(current.VERSION), renderer: current.getParameter(current.RENDERER) });
    } else {
      log("humangl error: no current gl context:", current, config2.gl);
    }
  }
}

// src/tfjs/constants.ts
var constants = {
  tf255: 255,
  tf1: 1,
  tf2: 2,
  tf05: 0.5,
  tf127: 127.5,
  rgb: [0.2989, 0.587, 0.114]
};
function init() {
  constants.tf255 = ke(255, "float32");
  constants.tf1 = ke(1, "float32");
  constants.tf2 = ke(2, "float32");
  constants.tf05 = ke(0.5, "float32");
  constants.tf127 = ke(127.5, "float32");
  constants.rgb = Jt([0.2989, 0.587, 0.114], "float32");
}

// src/tfjs/backend.ts
async function getBestBackend() {
  var _a;
  await env.updateBackend();
  if ((_a = env.tensorflow) == null ? void 0 : _a.version) return "tensorflow";
  if (env.webgpu.supported && env.webgpu.backend) return "webgpu";
  if (env.webgl.supported && env.webgl.backend) return "webgl";
  if (env.wasm.supported && env.wasm.backend) return "wasm";
  return "cpu";
}
function registerCustomOps(config3) {
  const newKernels = [];
  if (!env.kernels.includes("mod")) {
    const kernelMod = {
      kernelName: "Mod",
      backendName: sk(),
      kernelFunc: (op2) => De(() => Te(op2.inputs.a, se(je(op2.inputs.a, op2.inputs.b), op2.inputs.b)))
    };
    ti(kernelMod);
    env.kernels.push("mod");
    newKernels.push("mod");
  }
  if (!env.kernels.includes("floormod")) {
    const kernelFloorMod = {
      kernelName: "FloorMod",
      backendName: sk(),
      kernelFunc: (op2) => De(() => Ce(se(md(op2.inputs.a, op2.inputs.b), op2.inputs.b), z2(op2.inputs.a, op2.inputs.b)))
    };
    ti(kernelFloorMod);
    env.kernels.push("floormod");
    newKernels.push("floormod");
  }
  if (!env.kernels.includes("rotatewithoffset") && config3.softwareKernels) {
    const kernelRotateWithOffset = {
      kernelName: "RotateWithOffset",
      backendName: sk(),
      kernelFunc: (op2) => De(() => {
        const backend = sk();
        Sme("cpu");
        const t10 = eX.rotateWithOffset(op2.inputs.image, op2.attrs.radians, op2.attrs.fillValue, op2.attrs.center);
        Sme(backend);
        return t10;
      })
    };
    ti(kernelRotateWithOffset);
    env.kernels.push("rotatewithoffset");
    newKernels.push("rotatewithoffset");
  }
  if (newKernels.length > 0 && config3.debug) log("registered kernels:", newKernels);
}
var defaultFlags = {};
async function check(instance, force = false) {
  var _a, _b;
  instance.state = "backend";
  if (((_a = instance.config.backend) == null ? void 0 : _a.length) === 0) instance.config.backend = await getBestBackend();
  if (force || env.initial || instance.config.backend && instance.config.backend.length > 0 && sk() !== 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 (typeof navigator !== "undefined" && ((_b = navigator == null ? void 0 : navigator.userAgent) == null ? void 0 : _b.toLowerCase().includes("electron"))) {
        if (instance.config.debug) log("running inside electron");
      }
      let available = Object.keys(ur().registryFactory);
      if (instance.config.backend === "humangl" && !available.includes("humangl")) {
        register(instance);
        available = Object.keys(ur().registryFactory);
      }
      if (instance.config.debug) log("available backends:", available);
      if (env.browser && !env.node && instance.config.backend === "tensorflow" && available.includes("webgl")) {
        if (instance.config.debug) log("override: backend set to tensorflow while running in browser");
        instance.config.backend = "webgl";
      }
      if (env.node && !env.browser && (instance.config.backend === "webgl" || instance.config.backend === "humangl") && available.includes("tensorflow")) {
        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 = "webgl";
        } else {
          const adapter = await navigator.gpu.requestAdapter();
          if (instance.config.debug) log("enumerated webgpu adapter:", adapter);
          if (!adapter) {
            log("override: backend set to webgpu but browser reports no available gpu");
            instance.config.backend = "webgl";
          } else {
            let adapterInfo;
            if ("requestAdapterInfo" in adapter) adapterInfo = await (adapter == null ? void 0 : adapter.requestAdapterInfo());
            else adapterInfo = adapter.info;
            log("webgpu adapter info:", adapterInfo);
          }
        }
      }
      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 (A().flagRegistry.CANVAS2D_WILL_READ_FREQUENTLY) A().set("CANVAS2D_WILL_READ_FREQUENTLY", true);
        if (instance.config.debug) log("wasm path:", instance.config.wasmPath);
        if (typeof nae !== "undefined") nae(instance.config.wasmPath, instance.config.wasmPlatformFetch);
        else throw new Error("backend error: attempting to use wasm backend but wasm path is not set");
        let mt2 = false;
        let simd = false;
        try {
          mt2 = await A().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");
          simd = await A().getAsync("WASM_HAS_SIMD_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");
        } catch (e) {
          log("wasm detection failed");
        }
      }
      try {
        await Sme(instance.config.backend);
        await Ime();
      } catch (err) {
        log("error: cannot set backend:", instance.config.backend, err);
        return false;
      }
      if (instance.config.debug) defaultFlags = JSON.parse(JSON.stringify(A().flags));
    }
    if (sk() === "humangl" || sk() === "webgl") {
      if (A().flagRegistry.WEBGL_USE_SHAPES_UNIFORMS) A().set("WEBGL_USE_SHAPES_UNIFORMS", true);
      if (A().flagRegistry.WEBGL_EXP_CONV) A().set("WEBGL_EXP_CONV", true);
      if (instance.config.debug && typeof instance.config.deallocate !== "undefined" && instance.config.deallocate) {
        log("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:", true);
        A().set("WEBGL_DELETE_TEXTURE_THRESHOLD", 0);
      }
    }
    if (sk() === "webgpu") {
    }
    if (instance.config.debug) {
      const newFlags = A().flags;
      const updatedFlags = {};
      for (const key of Object.keys(newFlags)) {
        if (defaultFlags[key] === newFlags[key]) continue;
        updatedFlags[key] = newFlags[key];
      }
      if (instance.config.debug && Object.keys(updatedFlags).length > 0) log("backend:", sk(), "flags:", updatedFlags);
    }
    if (instance.config.flags && Object.keys(instance.config.flags).length > 0) {
      if (instance.config.debug) log("flags:", instance.config["flags"]);
      for (const [key, val] of Object.entries(instance.config.flags)) {
        A().set(key, val);
      }
    }
    hme();
    init();
    instance.performance.initBackend = Math.trunc(now() - timeStamp);
    instance.config.backend = sk();
    await env.updateBackend();
    registerCustomOps(instance.config);
  }
  return true;
}
function fakeOps(kernelNames, config3) {
  for (const kernelName of kernelNames) {
    const kernelConfig = {
      kernelName,
      backendName: config3.backend,
      kernelFunc: (param) => {
        var _a;
        if (config3.debug) log("kernelFunc", kernelName, config3.backend, param);
        return (_a = param == null ? void 0 : param.inputs) == null ? void 0 : _a.info;
      }
      // setupFunc: () => { if (config.debug) log('kernelFunc', kernelName, config.backend); },
      // disposeFunc: () => { if (config.debug) log('kernelFunc', kernelName, config.backend); },
    };
    ti(kernelConfig);
  }
  env.kernels = Ym(sk()).map((kernel) => kernel.kernelName.toLowerCase());
}

// src/draw/draw.ts
var draw_exports = {};
__export(draw_exports, {
  all: () => all,
  body: () => body,
  canvas: () => canvas2,
  face: () => face,
  gesture: () => gesture,
  hand: () => hand,
  init: () => init2,
  object: () => object,
  options: () => options2,
  person: () => person,
  tensor: () => tensor
});

// src/draw/primitives.ts
var getCanvasContext = (input) => {
  if (!input) log("draw error: invalid canvas");
  else if (!input.getContext) log("draw error: canvas context not defined");
  else {
    const ctx = input.getContext("2d", { willReadFrequently: true });
    if (!ctx) log("draw error: cannot get canvas context");
    else return ctx;
  }
  return null;
};
var rad2deg = (theta) => Math.round(theta * 180 / Math.PI);
var replace = (str, source, target) => str.replace(source, typeof target === "number" ? target.toFixed(1) : target);
var colorDepth = (z, opt) => {
  if (!opt.useDepth || typeof z === "undefined") return opt.color;
  const rgb3 = Uint8ClampedArray.from([127 + 2 * z, 127 - 2 * z, 255]);
  return `rgba(${rgb3[0]}, ${rgb3[1]}, ${rgb3[2]}, ${opt.alpha})`;
};
function labels(ctx, str, startX, startY, localOptions2) {
  const line = str.replace(/\[.*\]/g, "").split("\n").map((l) => l.trim());
  const x = Math.max(0, startX);
  for (let i = line.length - 1; i >= 0; i--) {
    const y8 = i * localOptions2.lineHeight + startY;
    if (localOptions2.shadowColor && localOptions2.shadowColor !== "") {
      ctx.fillStyle = localOptions2.shadowColor;
      ctx.fillText(line[i], x + 5, y8 + 16);
    }
    ctx.fillStyle = localOptions2.labelColor;
    ctx.fillText(line[i], x + 4, y8 + 15);
  }
}
function point(ctx, x, y8, z, localOptions2) {
  ctx.fillStyle = colorDepth(z, localOptions2);
  ctx.beginPath();
  ctx.arc(x, y8, localOptions2.pointSize, 0, 2 * Math.PI);
  ctx.fill();
}
function rect(ctx, x, y8, width, height, localOptions2) {
  ctx.beginPath();
  ctx.lineWidth = localOptions2.lineWidth;
  if (localOptions2.useCurves) {
    const cx2 = (x + x + width) / 2;
    const cy2 = (y8 + y8 + height) / 2;
    ctx.ellipse(cx2, cy2, width / 2, height / 2, 0, 0, 2 * Math.PI);
  } else {
    ctx.moveTo(x + localOptions2.roundRect, y8);
    ctx.lineTo(x + width - localOptions2.roundRect, y8);
    ctx.quadraticCurveTo(x + width, y8, x + width, y8 + localOptions2.roundRect);
    ctx.lineTo(x + width, y8 + height - localOptions2.roundRect);
    ctx.quadraticCurveTo(x + width, y8 + height, x + width - localOptions2.roundRect, y8 + height);
    ctx.lineTo(x + localOptions2.roundRect, y8 + height);
    ctx.quadraticCurveTo(x, y8 + height, x, y8 + height - localOptions2.roundRect);
    ctx.lineTo(x, y8 + localOptions2.roundRect);
    ctx.quadraticCurveTo(x, y8, x + localOptions2.roundRect, y8);
    ctx.closePath();
  }
  ctx.stroke();
}
function lines(ctx, points, localOptions2) {
  if (points.length < 2) return;
  ctx.beginPath();
  ctx.moveTo(points[0][0], points[0][1]);
  for (const pt2 of points) {
    ctx.strokeStyle = colorDepth(pt2[2] || 0, localOptions2);
    ctx.lineTo(Math.trunc(pt2[0]), Math.trunc(pt2[1]));
  }
  ctx.stroke();
  if (localOptions2.fillPolygons) {
    ctx.closePath();
    ctx.fill();
  }
}
function curves(ctx, points, localOptions2) {
  if (points.length < 2) return;
  ctx.lineWidth = localOptions2.lineWidth;
  if (!localOptions2.useCurves || points.length <= 2) {
    lines(ctx, points, localOptions2);
    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 (localOptions2.fillPolygons) {
    ctx.closePath();
    ctx.fill();
  }
}
function arrow(ctx, from, to, radius = 5) {
  let angle;
  let x;
  let y8;
  ctx.beginPath();
  ctx.moveTo(from[0], from[1]);
  ctx.lineTo(to[0], to[1]);
  angle = Math.atan2(to[1] - from[1], to[0] - from[0]);
  x = radius * Math.cos(angle) + to[0];
  y8 = radius * Math.sin(angle) + to[1];
  ctx.moveTo(x, y8);
  angle += 1 / 3 * (2 * Math.PI);
  x = radius * Math.cos(angle) + to[0];
  y8 = radius * Math.sin(angle) + to[1];
  ctx.lineTo(x, y8);
  angle += 1 / 3 * (2 * Math.PI);
  x = radius * Math.cos(angle) + to[0];
  y8 = radius * Math.sin(angle) + to[1];
  ctx.lineTo(x, y8);
  ctx.closePath();
  ctx.stroke();
  ctx.fill();
}

// src/draw/options.ts
var options2 = {
  color: "rgba(173, 216, 230, 0.6)",
  // 'lightblue' with light alpha channel
  labelColor: "rgba(173, 216, 230, 1)",
  // 'lightblue' with dark alpha channel
  shadowColor: "black",
  alpha: 0.5,
  font: 'small-caps 16px "Segoe UI"',
  lineHeight: 18,
  lineWidth: 4,
  pointSize: 2,
  roundRect: 8,
  drawPoints: false,
  drawLabels: true,
  drawBoxes: true,
  drawAttention: true,
  drawGestures: true,
  drawPolygons: true,
  drawGaze: true,
  fillPolygons: false,
  useDepth: true,
  useCurves: false,
  faceLabels: "",
  bodyLabels: "",
  bodyPartLabels: "",
  objectLabels: "",
  handLabels: "",
  fingerLabels: "",
  gestureLabels: ""
};

// 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], // 11
  // lipsLowerOuter: [146, 91, 181, 84, 17, 314, 405, 321, 375, 291], // 10
  // lipsUpperInner: [78, 191, 80, 81, 82, 13, 312, 311, 310, 415, 308], // 11
  // lipsLowerInner: [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308], // 11
  lipsUpperOuter: [185, 40, 39, 37, 0, 267, 269, 270, 409],
  lipsLowerOuter: [61, 146, 91, 181, 84, 17, 314, 405, 321, 375, 291],
  lipsUpperInner: [191, 80, 81, 82, 13, 312, 311, 310, 415],
  lipsLowerInner: [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308],
  lipsLowerSemiOuter: [76, 77, 90, 180, 85, 16, 315, 404, 320, 307, 306],
  lipsUpperSemiOuter: [184, 74, 73, 72, 11, 302, 303, 304, 408],
  lipsLowerSemiInner: [62, 96, 89, 179, 86, 15, 316, 403, 319, 325, 292],
  lipsUpperSemiInner: [183, 42, 41, 38, 12, 268, 271, 272, 407],
  rightEyeUpper0: [246, 161, 160, 159, 158, 157, 173],
  // 7
  rightEyeLower0: [33, 7, 163, 144, 145, 153, 154, 155, 133],
  // 9
  rightEyeUpper1: [247, 30, 29, 27, 28, 56, 190],
  // 7
  rightEyeLower1: [130, 25, 110, 24, 23, 22, 26, 112, 243],
  // 9
  rightEyeUpper2: [113, 225, 224, 223, 222, 221, 189],
  // 7
  rightEyeLower2: [226, 31, 228, 229, 230, 231, 232, 233, 244],
  // 9
  rightEyeLower3: [143, 111, 117, 118, 119, 120, 121, 128, 245],
  // 9
  rightEyebrowUpper: [156, 70, 63, 105, 66, 107, 55, 193],
  // 8
  rightEyebrowLower: [35, 124, 46, 53, 52, 65],
  // 6
  rightEyeIris: [473, 474, 475, 476, 477],
  // 5
  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 irisIndices = [
  // A mapping from facemesh model keypoints to iris model keypoints.
  { key: "EyeUpper0", indices: [9, 10, 11, 12, 13, 14, 15] },
  // 7 x 3d
  { key: "EyeUpper1", indices: [25, 26, 27, 28, 29, 30, 31] },
  // 7 x 3d
  { key: "EyeUpper2", indices: [41, 42, 43, 44, 45, 46, 47] },
  // 7 x 3d
  { key: "EyeLower0", indices: [0, 1, 2, 3, 4, 5, 6, 7, 8] },
  // 7 x 3d
  { key: "EyeLower1", indices: [16, 17, 18, 19, 20, 21, 22, 23, 24] },
  // 9 x 3d
  { key: "EyeLower2", indices: [32, 33, 34, 35, 36, 37, 38, 39, 40] },
  // 9 x 3d
  { key: "EyeLower3", indices: [54, 55, 56, 57, 58, 59, 60, 61, 62] },
  // 9 x 3d
  { key: "EyebrowUpper", indices: [63, 64, 65, 66, 67, 68, 69, 70] },
  // 8 x 3d
  { key: "EyebrowLower", indices: [48, 49, 50, 51, 52, 53] }
  // 6 x 3d
];
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 = [
  /* cont  */
  127,
  234,
  132,
  58,
  172,
  150,
  149,
  148,
  152,
  377,
  378,
  379,
  397,
  288,
  361,
  454,
  356,
  /* brows */
  70,
  63,
  105,
  66,
  107,
  336,
  296,
  334,
  293,
  300,
  /* nose  */
  168,
  6,
  195,
  4,
  98,
  97,
  2,
  326,
  327,
  /* eyes  */
  33,
  160,
  158,
  133,
  153,
  144,
  362,
  385,
  387,
  263,
  373,
  380,
  /* lip   */
  57,
  40,
  37,
  0,
  267,
  270,
  287,
  321,
  314,
  17,
  84,
  91,
  /* mouth */
  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]);
function connectionsToIndices(connections) {
  const indices = connections.map((connection) => connection[0]);
  indices.push(connections[connections.length - 1][1]);
  return indices;
}
var pairsLips = [
  [61, 146],
  [146, 91],
  [91, 181],
  [181, 84],
  [84, 17],
  [17, 314],
  [314, 405],
  [405, 321],
  [321, 375],
  [375, 291],
  [61, 185],
  [185, 40],
  [40, 39],
  [39, 37],
  [37, 0],
  [0, 267],
  [267, 269],
  [269, 270],
  [270, 409],
  [409, 291],
  [78, 95],
  [95, 88],
  [88, 178],
  [178, 87],
  [87, 14],
  [14, 317],
  [317, 402],
  [402, 318],
  [318, 324],
  [324, 308],
  [78, 191],
  [191, 80],
  [80, 81],
  [81, 82],
  [82, 13],
  [13, 312],
  [312, 311],
  [311, 310],
  [310, 415],
  [415, 308]
];
var pairsLeftEye = [[263, 249], [249, 390], [390, 373], [373, 374], [374, 380], [380, 381], [381, 382], [382, 362], [263, 466], [466, 388], [388, 387], [387, 386], [386, 385], [385, 384], [384, 398], [398, 362]];
var pairsLeftEyebrow = [[276, 283], [283, 282], [282, 295], [295, 285], [300, 293], [293, 334], [334, 296], [296, 336]];
var pairsLeftIris = [[474, 475], [475, 476], [476, 477], [477, 474]];
var pairsRightEye = [[33, 7], [7, 163], [163, 144], [144, 145], [145, 153], [153, 154], [154, 155], [155, 133], [33, 246], [246, 161], [161, 160], [160, 159], [159, 158], [158, 157], [157, 173], [173, 133]];
var pairsRightEyebrow = [[46, 53], [53, 52], [52, 65], [65, 55], [70, 63], [63, 105], [105, 66], [66, 107]];
var pairsRightIris = [[469, 470], [470, 471], [471, 472], [472, 469]];
var pairsFaceContour = [
  [10, 338],
  [338, 297],
  [297, 332],
  [332, 284],
  [284, 251],
  [251, 389],
  [389, 356],
  [356, 454],
  [454, 323],
  [323, 361],
  [361, 288],
  [288, 397],
  [397, 365],
  [365, 379],
  [379, 378],
  [378, 400],
  [400, 377],
  [377, 152],
  [152, 148],
  [148, 176],
  [176, 149],
  [149, 150],
  [150, 136],
  [136, 172],
  [172, 58],
  [58, 132],
  [132, 93],
  [93, 234],
  [234, 127],
  [127, 162],
  [162, 21],
  [21, 54],
  [54, 103],
  [103, 67],
  [67, 109],
  [109, 10]
];
var contourKeypoints = {
  lips: connectionsToIndices(pairsLips),
  leftEye: connectionsToIndices(pairsLeftEye),
  leftEyebrow: connectionsToIndices(pairsLeftEyebrow),
  leftIris: connectionsToIndices(pairsLeftIris),
  rightEye: connectionsToIndices(pairsRightEye),
  rightEyebrow: connectionsToIndices(pairsRightEyebrow),
  rightIris: connectionsToIndices(pairsRightIris),
  faceOval: connectionsToIndices(pairsFaceContour)
};

// src/face/constants.ts
var LIPS_CONNECTIONS = [
  [61, 146],
  [146, 91],
  [91, 181],
  [181, 84],
  [84, 17],
  [17, 314],
  [314, 405],
  [405, 321],
  [321, 375],
  [375, 291],
  [61, 185],
  [185, 40],
  [40, 39],
  [39, 37],
  [37, 0],
  [0, 267],
  [267, 269],
  [269, 270],
  [270, 409],
  [409, 291],
  [78, 95],
  [95, 88],
  [88, 178],
  [178, 87],
  [87, 14],
  [14, 317],
  [317, 402],
  [402, 318],
  [318, 324],
  [324, 308],
  [78, 191],
  [191, 80],
  [80, 81],
  [81, 82],
  [82, 13],
  [13, 312],
  [312, 311],
  [311, 310],
  [310, 415],
  [415, 308]
];
var LEFT_EYE_CONNECTIONS = [[263, 249], [249, 390], [390, 373], [373, 374], [374, 380], [380, 381], [381, 382], [382, 362], [263, 466], [466, 388], [388, 387], [387, 386], [386, 385], [385, 384], [384, 398], [398, 362]];
var LEFT_EYEBROW_CONNECTIONS = [[276, 283], [283, 282], [282, 295], [295, 285], [300, 293], [293, 334], [334, 296], [296, 336]];
var LEFT_IRIS_CONNECTIONS = [[474, 475], [475, 476], [476, 477], [477, 474]];
var RIGHT_EYE_CONNECTIONS = [[33, 7], [7, 163], [163, 144], [144, 145], [145, 153], [153, 154], [154, 155], [155, 133], [33, 246], [246, 161], [161, 160], [160, 159], [159, 158], [158, 157], [157, 173], [173, 133]];
var RIGHT_EYEBROW_CONNECTIONS = [[46, 53], [53, 52], [52, 65], [65, 55], [70, 63], [63, 105], [105, 66], [66, 107]];
var RIGHT_IRIS_CONNECTIONS = [[469, 470], [470, 471], [471, 472], [472, 469]];
var FACE_OVAL_CONNECTIONS = [
  [10, 338],
  [338, 297],
  [297, 332],
  [332, 284],
  [284, 251],
  [251, 389],
  [389, 356],
  [356, 454],
  [454, 323],
  [323, 361],
  [361, 288],
  [288, 397],
  [397, 365],
  [365, 379],
  [379, 378],
  [378, 400],
  [400, 377],
  [377, 152],
  [152, 148],
  [148, 176],
  [176, 149],
  [149, 150],
  [150, 136],
  [136, 172],
  [172, 58],
  [58, 132],
  [132, 93],
  [93, 234],
  [234, 127],
  [127, 162],
  [162, 21],
  [21, 54],
  [54, 103],
  [103, 67],
  [67, 109],
  [109, 10]
];
function connectionsToIndices2(connections) {
  const indices = connections.map((connection) => connection[0]);
  indices.push(connections[connections.length - 1][1]);
  return indices;
}
var MEDIAPIPE_FACE_MESH_KEYPOINTS_BY_CONTOUR = {
  lips: connectionsToIndices2(LIPS_CONNECTIONS),
  leftEye: connectionsToIndices2(LEFT_EYE_CONNECTIONS),
  leftEyebrow: connectionsToIndices2(LEFT_EYEBROW_CONNECTIONS),
  leftIris: connectionsToIndices2(LEFT_IRIS_CONNECTIONS),
  rightEye: connectionsToIndices2(RIGHT_EYE_CONNECTIONS),
  rightEyebrow: connectionsToIndices2(RIGHT_EYEBROW_CONNECTIONS),
  rightIris: connectionsToIndices2(RIGHT_IRIS_CONNECTIONS),
  faceOval: connectionsToIndices2(FACE_OVAL_CONNECTIONS)
};
var indexLabelPairs = Object.entries(MEDIAPIPE_FACE_MESH_KEYPOINTS_BY_CONTOUR).map(([label, indices]) => indices.map((index2) => [index2, label])).flat();
var MEDIAPIPE_FACE_MESH_KEYPOINTS = new Map(indexLabelPairs);
var LANDMARKS_REFINEMENT_LIPS_CONFIG = [
  61,
  146,
  91,
  181,
  84,
  17,
  314,
  405,
  321,
  375,
  291,
  // Lower outer.
  185,
  40,
  39,
  37,
  0,
  267,
  269,
  270,
  409,
  // Upper outer(excluding corners).
  78,
  95,
  88,
  178,
  87,
  14,
  317,
  402,
  318,
  324,
  308,
  // Lower inner.
  191,
  80,
  81,
  82,
  13,
  312,
  311,
  310,
  415,
  // Upper inner(excluding corners).
  76,
  77,
  90,
  180,
  85,
  16,
  315,
  404,
  320,
  307,
  306,
  // Lower semi - outer.
  184,
  74,
  73,
  72,
  11,
  302,
  303,
  304,
  408,
  // Upper semi - outer(excluding corners).
  62,
  96,
  89,
  179,
  86,
  15,
  316,
  403,
  319,
  325,
  292,
  // Lower semi - inner.
  183,
  42,
  41,
  38,
  12,
  268,
  271,
  272,
  407
  // Upper semi - inner(excluding corners).
];
var LANDMARKS_REFINEMENT_LEFT_EYE_CONFIG = [
  33,
  7,
  163,
  144,
  145,
  153,
  154,
  155,
  133,
  // Lower contour.
  246,
  161,
  160,
  159,
  158,
  157,
  173,
  // upper contour (excluding corners).
  130,
  25,
  110,
  24,
  23,
  22,
  26,
  112,
  243,
  // Halo x2 lower contour.
  247,
  30,
  29,
  27,
  28,
  56,
  190,
  // Halo x2 upper contour (excluding corners).
  226,
  31,
  228,
  229,
  230,
  231,
  232,
  233,
  244,
  // Halo x3 lower contour.
  113,
  225,
  224,
  223,
  222,
  221,
  189,
  // Halo x3 upper contour (excluding corners).
  35,
  124,
  46,
  53,
  52,
  65,
  // Halo x4 upper contour (no lower because of mesh structure) or eyebrow inner contour.
  143,
  111,
  117,
  118,
  119,
  120,
  121,
  128,
  245,
  // Halo x5 lower contour.
  156,
  70,
  63,
  105,
  66,
  107,
  55,
  193
  // Halo x5 upper contour (excluding corners) or eyebrow outer contour.
];
var LANDMARKS_REFINEMENT_RIGHT_EYE_CONFIG = [
  263,
  249,
  390,
  373,
  374,
  380,
  381,
  382,
  362,
  // Lower contour.
  466,
  388,
  387,
  386,
  385,
  384,
  398,
  // Upper contour (excluding corners).
  359,
  255,
  339,
  254,
  253,
  252,
  256,
  341,
  463,
  // Halo x2 lower contour.
  467,
  260,
  259,
  257,
  258,
  286,
  414,
  // Halo x2 upper contour (excluding corners).
  446,
  261,
  448,
  449,
  450,
  451,
  452,
  453,
  464,
  // Halo x3 lower contour.
  342,
  445,
  444,
  443,
  442,
  441,
  413,
  // Halo x3 upper contour (excluding corners).
  265,
  353,
  276,
  283,
  282,
  295,
  // Halo x4 upper contour (no lower because of mesh structure) or/ eyebrow inner contour.
  372,
  340,
  346,
  347,
  348,
  349,
  350,
  357,
  465,
  // Halo x5 lower contour.
  383,
  300,
  293,
  334,
  296,
  336,
  285,
  417
  // Halo x5 upper contour (excluding corners) or eyebrow outer contour.
];

// src/draw/face.ts
var localOptions;
function drawLabels(f, ctx) {
  var _a, _b, _c2, _d2, _e, _f2, _g2, _h2, _i2;
  if (!localOptions.drawLabels || ((_a = localOptions.faceLabels) == null ? void 0 : _a.length) === 0) return;
  let l = localOptions.faceLabels.slice();
  l = replace(l, "[id]", f.id.toFixed(0));
  if (f.score) l = replace(l, "[score]", 100 * f.score);
  if (f.gender) l = replace(l, "[gender]", f.gender);
  if (f.genderScore) l = replace(l, "[genderScore]", 100 * f.genderScore);
  if (f.age) l = replace(l, "[age]", f.age);
  if (f.distance) l = replace(l, "[distance]", 100 * f.distance);
  if (f.real) l = replace(l, "[real]", 100 * f.real);
  if (f.live) l = replace(l, "[live]", 100 * f.live);
  if (f.emotion && f.emotion.length > 0) {
    const emotion2 = f.emotion.map((a) => `${Math.trunc(100 * a.score)}% ${a.emotion}`);
    if (emotion2.length > 3) emotion2.length = 3;
    l = replace(l, "[emotions]", emotion2.join(" "));
  }
  if ((_c2 = (_b = f.rotation) == null ? void 0 : _b.angle) == null ? void 0 : _c2.roll) l = replace(l, "[roll]", rad2deg(f.rotation.angle.roll));
  if ((_e = (_d2 = f.rotation) == null ? void 0 : _d2.angle) == null ? void 0 : _e.yaw) l = replace(l, "[yaw]", rad2deg(f.rotation.angle.yaw));
  if ((_g2 = (_f2 = f.rotation) == null ? void 0 : _f2.angle) == null ? void 0 : _g2.pitch) l = replace(l, "[pitch]", rad2deg(f.rotation.angle.pitch));
  if ((_i2 = (_h2 = f.rotation) == null ? void 0 : _h2.gaze) == null ? void 0 : _i2.bearing) l = replace(l, "[gaze]", rad2deg(f.rotation.gaze.bearing));
  labels(ctx, l, f.box[0], f.box[1], localOptions);
}
function drawIrisElipse(f, ctx) {
  var _a, _b, _c2, _d2;
  if (((_a = f.annotations) == null ? void 0 : _a.leftEyeIris) && ((_b = f.annotations) == null ? void 0 : _b.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 (((_c2 = f.annotations) == null ? void 0 : _c2.rightEyeIris) && ((_d2 = f.annotations) == null ? void 0 : _d2.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();
    }
  }
}
function drawGazeSpheres(f, ctx) {
  var _a;
  if (localOptions.drawGaze && ((_a = f.rotation) == null ? void 0 : _a.angle) && typeof Path2D !== "undefined") {
    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);
  }
}
function drawGazeArrows(f, ctx) {
  var _a;
  if (localOptions.drawGaze && ((_a = f.rotation) == null ? void 0 : _a.gaze.strength) && f.rotation.gaze.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);
  }
}
function drawFacePolygons(f, ctx) {
  if (localOptions.drawPolygons && f.mesh.length >= 468) {
    ctx.lineWidth = 1;
    for (let i = 0; i < TRI468.length / 3; i++) {
      const points = [TRI468[i * 3 + 0], TRI468[i * 3 + 1], TRI468[i * 3 + 2]].map((index2) => f.mesh[index2]);
      lines(ctx, points, localOptions);
    }
    drawIrisElipse(f, ctx);
  }
}
function drawFacePoints(f, ctx) {
  if (localOptions.drawPoints) {
    if ((f == null ? void 0 : f.mesh.length) >= 468) {
      for (let i = 0; i < f.mesh.length; i++) {
        point(ctx, f.mesh[i][0], f.mesh[i][1], f.mesh[i][2], localOptions);
        if (localOptions.drawAttention) {
          if (LANDMARKS_REFINEMENT_LIPS_CONFIG.includes(i)) point(ctx, f.mesh[i][0], f.mesh[i][1], f.mesh[i][2] + 127, localOptions);
          if (LANDMARKS_REFINEMENT_LEFT_EYE_CONFIG.includes(i)) point(ctx, f.mesh[i][0], f.mesh[i][1], f.mesh[i][2] - 127, localOptions);
          if (LANDMARKS_REFINEMENT_RIGHT_EYE_CONFIG.includes(i)) point(ctx, f.mesh[i][0], f.mesh[i][1], f.mesh[i][2] - 127, localOptions);
        }
      }
    } else {
      for (const [k, v8] of Object.entries((f == null ? void 0 : f.annotations) || {})) {
        if (!(v8 == null ? void 0 : v8[0])) continue;
        const pt2 = v8[0];
        point(ctx, pt2[0], pt2[1], 0, localOptions);
        if (localOptions.drawLabels) labels(ctx, k, pt2[0], pt2[1], localOptions);
      }
    }
  }
}
function drawFaceBoxes(f, ctx) {
  if (localOptions.drawBoxes) {
    rect(ctx, f.box[0], f.box[1], f.box[2], f.box[3], localOptions);
  }
}
function face(inCanvas2, result, drawOptions) {
  localOptions = mergeDeep(options2, drawOptions);
  if (!result || !inCanvas2) return;
  const ctx = getCanvasContext(inCanvas2);
  if (!ctx) return;
  ctx.font = localOptions.font;
  ctx.strokeStyle = localOptions.color;
  ctx.fillStyle = localOptions.color;
  for (const f of result) {
    drawFaceBoxes(f, ctx);
    drawLabels(f, ctx);
    if (f.mesh && f.mesh.length > 0) {
      drawFacePoints(f, ctx);
      drawFacePolygons(f, ctx);
      drawGazeSpheres(f, ctx);
      drawGazeArrows(f, ctx);
    }
  }
}

// src/draw/body.ts
function body(inCanvas2, result, drawOptions) {
  var _a, _b;
  const localOptions2 = mergeDeep(options2, drawOptions);
  if (!result || !inCanvas2) return;
  const ctx = getCanvasContext(inCanvas2);
  if (!ctx) return;
  ctx.lineJoin = "round";
  for (let i = 0; i < result.length; i++) {
    ctx.strokeStyle = localOptions2.color;
    ctx.fillStyle = localOptions2.color;
    ctx.lineWidth = localOptions2.lineWidth;
    ctx.font = localOptions2.font;
    if (localOptions2.drawBoxes && result[i].box && result[i].box.length === 4) {
      rect(ctx, result[i].box[0], result[i].box[1], result[i].box[2], result[i].box[3], localOptions2);
      if (localOptions2.drawLabels && ((_a = localOptions2.bodyLabels) == null ? void 0 : _a.length) > 0) {
        let l = localOptions2.bodyLabels.slice();
        l = replace(l, "[id]", result[i].id.toFixed(0));
        l = replace(l, "[score]", 100 * result[i].score);
        labels(ctx, l, result[i].box[0], result[i].box[1], localOptions2);
      }
    }
    if (localOptions2.drawPoints && result[i].keypoints) {
      for (let pt2 = 0; pt2 < result[i].keypoints.length; pt2++) {
        if (!result[i].keypoints[pt2].score || result[i].keypoints[pt2].score === 0) continue;
        ctx.fillStyle = colorDepth(result[i].keypoints[pt2].position[2], localOptions2);
        point(ctx, result[i].keypoints[pt2].position[0], result[i].keypoints[pt2].position[1], 0, localOptions2);
      }
    }
    if (localOptions2.drawLabels && ((_b = localOptions2.bodyPartLabels) == null ? void 0 : _b.length) > 0 && result[i].keypoints) {
      ctx.font = localOptions2.font;
      for (const pt2 of result[i].keypoints) {
        if (!pt2.score || pt2.score === 0) continue;
        let l = localOptions2.bodyPartLabels.slice();
        l = replace(l, "[label]", pt2.part);
        l = replace(l, "[score]", 100 * pt2.score);
        labels(ctx, l, pt2.position[0], pt2.position[1], localOptions2);
      }
    }
    if (localOptions2.drawPolygons && result[i].keypoints && result[i].annotations) {
      for (const part of Object.values(result[i].annotations)) {
        for (const connected4 of part) curves(ctx, connected4, localOptions2);
      }
    }
  }
}

// src/draw/hand.ts
function hand(inCanvas2, result, drawOptions) {
  var _a, _b;
  const localOptions2 = mergeDeep(options2, drawOptions);
  if (!result || !inCanvas2) return;
  const ctx = getCanvasContext(inCanvas2);
  if (!ctx) return;
  ctx.lineJoin = "round";
  ctx.font = localOptions2.font;
  for (const h of result) {
    if (localOptions2.drawBoxes) {
      ctx.strokeStyle = localOptions2.color;
      ctx.fillStyle = localOptions2.color;
      rect(ctx, h.box[0], h.box[1], h.box[2], h.box[3], localOptions2);
      if (localOptions2.drawLabels && ((_a = localOptions2.handLabels) == null ? void 0 : _a.length) > 0) {
        let l = localOptions2.handLabels.slice();
        l = replace(l, "[id]", h.id.toFixed(0));
        l = replace(l, "[label]", h.label);
        l = replace(l, "[score]", 100 * h.score);
        labels(ctx, l, h.box[0], h.box[1], localOptions2);
      }
      ctx.stroke();
    }
    if (localOptions2.drawPoints) {
      if (h.keypoints && h.keypoints.length > 0) {
        for (const pt2 of h.keypoints) {
          ctx.fillStyle = colorDepth(pt2[2], localOptions2);
          point(ctx, pt2[0], pt2[1], 0, localOptions2);
        }
      }
    }
    if (localOptions2.drawLabels && h.annotations && ((_b = localOptions2.fingerLabels) == null ? void 0 : _b.length) > 0) {
      for (const [part, pt2] of Object.entries(h.annotations)) {
        let l = localOptions2.fingerLabels.slice();
        l = replace(l, "[label]", part);
        labels(ctx, l, pt2[pt2.length - 1][0], pt2[pt2.length - 1][1], localOptions2);
      }
    }
    if (localOptions2.drawPolygons && h.annotations) {
      const addHandLine = (part) => {
        if (!part || part.length === 0 || !part[0]) return;
        for (let i = 0; i < part.length; i++) {
          ctx.beginPath();
          const z = part[i][2] || 0;
          ctx.strokeStyle = colorDepth(i * z, localOptions2);
          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 = localOptions2.lineWidth;
      addHandLine(h.annotations.index);
      addHandLine(h.annotations.middle);
      addHandLine(h.annotations.ring);
      addHandLine(h.annotations.pinky);
      addHandLine(h.annotations.thumb);
    }
  }
}

// src/draw/object.ts
function object(inCanvas2, result, drawOptions) {
  var _a;
  const localOptions2 = mergeDeep(options2, drawOptions);
  if (!result || !inCanvas2) return;
  const ctx = getCanvasContext(inCanvas2);
  if (!ctx) return;
  ctx.lineJoin = "round";
  ctx.font = localOptions2.font;
  for (const h of result) {
    if (localOptions2.drawBoxes) {
      ctx.strokeStyle = localOptions2.color;
      ctx.fillStyle = localOptions2.color;
      rect(ctx, h.box[0], h.box[1], h.box[2], h.box[3], localOptions2);
      if (localOptions2.drawLabels && ((_a = localOptions2.objectLabels) == null ? void 0 : _a.length) > 0) {
        let l = localOptions2.objectLabels.slice();
        l = replace(l, "[id]", h.id.toFixed(0));
        l = replace(l, "[label]", h.label);
        l = replace(l, "[score]", 100 * h.score);
        labels(ctx, l, h.box[0], h.box[1], localOptions2);
      }
      ctx.stroke();
    }
  }
}

// src/draw/gesture.ts
function gesture(inCanvas2, result, drawOptions) {
  var _a;
  const localOptions2 = mergeDeep(options2, drawOptions);
  if (!result || !inCanvas2) return;
  if (localOptions2.drawGestures && ((_a = localOptions2.gestureLabels) == null ? void 0 : _a.length) > 0) {
    const ctx = getCanvasContext(inCanvas2);
    if (!ctx) return;
    ctx.font = localOptions2.font;
    ctx.fillStyle = localOptions2.color;
    let i = 1;
    for (let j = 0; j < result.length; j++) {
      const [where, what] = Object.entries(result[j]);
      if (what.length > 1 && what[1].length > 0) {
        const who = where[1] > 0 ? `#${where[1]}` : "";
        let l = localOptions2.gestureLabels.slice();
        l = replace(l, "[where]", where[0]);
        l = replace(l, "[who]", who);
        l = replace(l, "[what]", what[1]);
        labels(ctx, l, 8, 2 + i * localOptions2.lineHeight, localOptions2);
        i += 1;
      }
    }
  }
}

// src/draw/labels.ts
var defaultLabels = {
  face: `face
    confidence: [score]%
    [gender] [genderScore]%
    age: [age] years
    distance: [distance]cm
    real: [real]%
    live: [live]%
    [emotions]
    roll: [roll]\xB0 yaw:[yaw]\xB0 pitch:[pitch]\xB0
    gaze: [gaze]\xB0`,
  body: "body [score]%",
  bodyPart: "[label] [score]%",
  object: "[label] [score]%",
  hand: "[label] [score]%",
  finger: "[label]",
  gesture: "[where] [who]: [what]"
};

// src/draw/draw.ts
var drawTime = 0;
function person(inCanvas2, result, drawOptions) {
  const localOptions2 = mergeDeep(options2, drawOptions);
  if (!result || !inCanvas2) return;
  const ctx = getCanvasContext(inCanvas2);
  if (!ctx) return;
  ctx.lineJoin = "round";
  ctx.font = localOptions2.font;
  for (let i = 0; i < result.length; i++) {
    if (localOptions2.drawBoxes) {
      ctx.strokeStyle = localOptions2.color;
      ctx.fillStyle = localOptions2.color;
      rect(ctx, result[i].box[0], result[i].box[1], result[i].box[2], result[i].box[3], localOptions2);
      if (localOptions2.drawLabels) {
        const label = `person #${i}`;
        if (localOptions2.shadowColor && localOptions2.shadowColor !== "") {
          ctx.fillStyle = localOptions2.shadowColor;
          ctx.fillText(label, result[i].box[0] + 3, 1 + result[i].box[1] + localOptions2.lineHeight, result[i].box[2]);
        }
        ctx.fillStyle = localOptions2.labelColor;
        ctx.fillText(label, result[i].box[0] + 2, 0 + result[i].box[1] + localOptions2.lineHeight, result[i].box[2]);
      }
      ctx.stroke();
    }
  }
}
function canvas2(input, output) {
  if (!input || !output) return;
  const ctx = getCanvasContext(output);
  if (!ctx) return;
  ctx.drawImage(input, 0, 0);
}
async function tensor(input, output) {
  if (!input || !output) return;
  if (!env.browser) return;
  await cT.toPixels(input, output);
}
async function all(inCanvas2, result, drawOptions) {
  if (!(result == null ? void 0 : result.performance) || !inCanvas2) return null;
  const timeStamp = now();
  const localOptions2 = mergeDeep(options2, drawOptions);
  const promise = Promise.all([
    face(inCanvas2, result.face, localOptions2),
    body(inCanvas2, result.body, localOptions2),
    hand(inCanvas2, result.hand, localOptions2),
    object(inCanvas2, result.object, localOptions2),
    gesture(inCanvas2, result.gesture, localOptions2)
    // gestures do not have buffering
    // person(inCanvas, result.persons, localOptions); // already included above
  ]);
  drawTime = env.perfadd ? drawTime + Math.round(now() - timeStamp) : Math.round(now() - timeStamp);
  result.performance.draw = drawTime;
  return promise;
}
function init2() {
  options2.faceLabels = defaultLabels.face;
  options2.bodyLabels = defaultLabels.body;
  options2.bodyPartLabels = defaultLabels.bodyPart;
  options2.handLabels = defaultLabels.hand;
  options2.fingerLabels = defaultLabels.finger;
  options2.objectLabels = defaultLabels.object;
  options2.gestureLabels = defaultLabels.gesture;
}

// src/body/blazeposecoords.ts
var blazeposecoords_exports = {};
__export(blazeposecoords_exports, {
  connected: () => connected,
  kpt: () => kpt
});
var kpt = [
  "nose",
  //  0
  "leftEyeInside",
  //  1
  "leftEye",
  //  2
  "leftEyeOutside",
  //  3
  "rightEyeInside",
  //  4
  "rightEye",
  //  5
  "rightEyeOutside",
  //  6
  "leftEar",
  //  7
  "rightEar",
  //  8
  "leftMouth",
  //  9
  "rightMouth",
  // 10
  "leftShoulder",
  // 11
  "rightShoulder",
  // 12
  "leftElbow",
  // 13
  "rightElbow",
  // 14
  "leftWrist",
  // 15
  "rightWrist",
  // 16
  "leftPinky",
  // 17
  "rightPinky",
  // 18
  "leftIndex",
  // 19
  "rightIndex",
  // 20
  "leftThumb",
  // 21
  "rightThumb",
  // 22
  "leftHip",
  // 23
  "rightHip",
  // 24
  "leftKnee",
  // 25
  "rightKnee",
  // 26
  "leftAnkle",
  // 27
  "rightAnkle",
  // 28
  "leftHeel",
  // 29
  "rightHeel",
  // 30
  "leftFoot",
  // 31
  "rightFoot",
  // 32
  "bodyCenter",
  // 33
  "bodyTop",
  // 34
  "leftPalm",
  // 35 // z-coord not ok
  "leftHand",
  // 36 // similar to wrist but z-coord not ok
  "rightPalm",
  // 37 // z-coord not ok
  "rightHand"
  // 38 // similar to wrist but z-coord not ok
];
var connected = {
  shoulders: ["leftShoulder", "rightShoulder"],
  hips: ["rightHip", "leftHip"],
  mouth: ["leftMouth", "rightMouth"],
  leftLegUpper: ["leftHip", "leftKnee"],
  leftLegLower: ["leftKnee", "leftAnkle"],
  leftFoot: ["leftAnkle", "leftHeel", "leftFoot"],
  leftTorso: ["leftShoulder", "leftHip"],
  leftArmUpper: ["leftShoulder", "leftElbow"],
  leftArmLower: ["leftElbow", "leftWrist"],
  leftHand: ["leftWrist", "leftPalm"],
  leftHandPinky: ["leftPalm", "leftPinky"],
  leftHandIndex: ["leftPalm", "leftIndex"],
  leftHandThumb: ["leftPalm", "leftThumb"],
  leftEyeOutline: ["leftEyeInside", "leftEyeOutside"],
  rightLegUpper: ["rightHip", "rightKnee"],
  rightLegLower: ["rightKnee", "rightAnkle"],
  rightFoot: ["rightAnkle", "rightHeel", "rightFoot"],
  rightTorso: ["rightShoulder", "rightHip"],
  rightArmUpper: ["rightShoulder", "rightElbow"],
  rightArmLower: ["rightElbow", "rightWrist"],
  rightHand: ["rightWrist", "rightPalm"],
  rightHandPinky: ["rightPalm", "rightPinky"],
  rightHandIndex: ["rightPalm", "rightIndex"],
  rightHandThumb: ["rightPalm", "rightThumb"],
  rightEyeOutline: ["rightEyeInside", "rightEyeOutside"]
};

// src/body/blazeposedetector.ts
var model;
var inputSize = 224;
var anchorTensor;
var numLayers = 5;
var strides = [8, 16, 32, 32, 32];
function createAnchors() {
  const anchors3 = [];
  let layerId = 0;
  while (layerId < numLayers) {
    let anchorCount = 0;
    let lastSameStrideLayer = layerId;
    while (lastSameStrideLayer < strides.length && strides[lastSameStrideLayer] === strides[layerId]) {
      anchorCount += 2;
      lastSameStrideLayer++;
    }
    const stride = strides[layerId];
    const featureMapHeight = Math.ceil(inputSize / stride);
    const featureMapWidth = Math.ceil(inputSize / stride);
    for (let y8 = 0; y8 < featureMapHeight; ++y8) {
      for (let x = 0; x < featureMapWidth; ++x) {
        for (let anchorId = 0; anchorId < anchorCount; ++anchorId) {
          anchors3.push({ x: (x + 0.5) / featureMapWidth, y: (y8 + 0.5) / featureMapHeight });
        }
      }
    }
    layerId = lastSameStrideLayer;
  }
  anchorTensor = { x: Jt(anchors3.map((a) => a.x)), y: Jt(anchors3.map((a) => a.y)) };
}
async function loadDetector(config3) {
  if (env.initial) model = null;
  if (!model && config3.body["detector"] && config3.body["detector"].modelPath || "") {
    model = await loadModel(config3.body["detector"].modelPath);
    const inputs = (model == null ? void 0 : model["executor"]) ? Object.values(model.modelSignature["inputs"]) : void 0;
    inputSize = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[1].size) : 0;
  } else if (config3.debug && model) log("cached model:", model["modelUrl"]);
  createAnchors();
  return model;
}
var cropFactor = [5, 5];
function decodeBoxes(boxesTensor, anchor) {
  return De(() => {
    const split = li(boxesTensor, 12, 1);
    let xCenter = cc(split[0]);
    let yCenter = cc(split[1]);
    let width = cc(split[2]);
    let height = cc(split[3]);
    xCenter = Ce(je(xCenter, inputSize), anchor.x);
    yCenter = Ce(je(yCenter, inputSize), anchor.y);
    width = se(je(width, inputSize), cropFactor[0]);
    height = se(je(height, inputSize), cropFactor[1]);
    const xMin = Te(xCenter, je(width, 2));
    const yMin = Te(yCenter, je(height, 2));
    const xMax = Ce(xMin, width);
    const yMax = Ce(yMin, height);
    const boxes = vr([xMin, yMin, xMax, yMax], 1);
    return boxes;
  });
}
async function decodeResults(boxesTensor, logitsTensor, config3, outputSize2) {
  var _a, _b;
  const detectedBoxes = [];
  const t10 = {};
  t10.boxes = decodeBoxes(boxesTensor, anchorTensor);
  t10.scores = Ea(logitsTensor);
  t10.nms = await eX.nonMaxSuppressionAsync(t10.boxes, t10.scores, 1, ((_a = config3.body["detector"]) == null ? void 0 : _a.minConfidence) || 0.1, ((_b = config3.body["detector"]) == null ? void 0 : _b.iouThreshold) || 0.1);
  const nms = await t10.nms.data();
  const scores = await t10.scores.data();
  const boxes = await t10.boxes.array();
  for (const i of Array.from(nms)) {
    const score = scores[i];
    const boxRaw = boxes[i];
    const box = [Math.round(boxRaw[0] * outputSize2[0]), Math.round(boxRaw[1] * outputSize2[1]), Math.round(boxRaw[2] * outputSize2[0]), Math.round(boxRaw[3] * outputSize2[1])];
    const detectedBox = { score, boxRaw, box };
    detectedBoxes.push(detectedBox);
  }
  Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
  return detectedBoxes;
}
async function detectBoxes(input, config3, outputSize2) {
  const t10 = {};
  t10.res = model == null ? void 0 : model.execute(input, ["Identity"]);
  t10.logitsRaw = Xe(t10.res, [0, 0, 0], [1, -1, 1]);
  t10.boxesRaw = Xe(t10.res, [0, 0, 1], [1, -1, -1]);
  t10.logits = cc(t10.logitsRaw);
  t10.boxes = cc(t10.boxesRaw);
  const boxes = await decodeResults(t10.boxes, t10.logits, config3, outputSize2);
  Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
  return boxes;
}

// src/util/box.ts
function calc(keypoints, outputSize2 = [1, 1]) {
  const coords = [keypoints.map((pt2) => pt2[0]), keypoints.map((pt2) => pt2[1])];
  const min = [Math.min(...coords[0]), Math.min(...coords[1])];
  const max = [Math.max(...coords[0]), Math.max(...coords[1])];
  const box = [min[0], min[1], max[0] - min[0], max[1] - min[1]];
  const boxRaw = [box[0] / outputSize2[0], box[1] / outputSize2[1], box[2] / outputSize2[0], box[3] / outputSize2[1]];
  return { box, boxRaw };
}
function square(keypoints, outputSize2 = [1, 1]) {
  const coords = [keypoints.map((pt2) => pt2[0]), keypoints.map((pt2) => pt2[1])];
  const min = [Math.min(...coords[0]), Math.min(...coords[1])];
  const max = [Math.max(...coords[0]), Math.max(...coords[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 box = [Math.trunc(center[0] - dist), Math.trunc(center[1] - dist), Math.trunc(2 * dist), Math.trunc(2 * dist)];
  const boxRaw = [box[0] / outputSize2[0], box[1] / outputSize2[1], box[2] / outputSize2[0], box[3] / outputSize2[1]];
  return { box, boxRaw };
}
function scale(box, scaleFact) {
  const dist = [box[2] * scaleFact, box[3] * scaleFact];
  const newBox = [
    box[0] - (dist[0] - box[2]) / 2,
    box[1] - (dist[1] - box[3]) / 2,
    dist[0],
    dist[1]
  ];
  return newBox;
}

// src/body/blazepose.ts
var model2;
var inputSize2 = 256;
var skipped = Number.MAX_SAFE_INTEGER;
var outputNodes = {
  landmarks: ["ld_3d", "activation_segmentation", "activation_heatmap", "world_3d", "output_poseflag"],
  detector: []
};
var cache = [];
var padding = [[0, 0], [0, 0], [0, 0], [0, 0]];
var lastTime = 0;
var sigmoid = (x) => 1 - 1 / (1 + Math.exp(x));
var loadDetect = (config3) => loadDetector(config3);
async function loadPose(config3) {
  if (env.initial) model2 = null;
  if (!model2) {
    model2 = await loadModel(config3.body.modelPath);
    const inputs = (model2 == null ? void 0 : model2["executor"]) ? Object.values(model2.modelSignature["inputs"]) : void 0;
    inputSize2 = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[1].size) : 0;
  } else if (config3.debug) log("cached model:", model2["modelUrl"]);
  return model2;
}
function prepareImage(input, size2, cropBox) {
  var _a, _b;
  const t10 = {};
  if (!((_a = input == null ? void 0 : input.shape) == null ? void 0 : _a[1]) || !((_b = input == null ? void 0 : input.shape) == null ? void 0 : _b[2])) return input;
  let final;
  if (cropBox) {
    t10.cropped = eX.cropAndResize(input, [cropBox], [0], [input.shape[1], input.shape[2]]);
  }
  if (input.shape[1] !== input.shape[2]) {
    const height = [
      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
    ];
    const width = [
      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
    ];
    padding = [
      [0, 0],
      // dont touch batch
      height,
      // height before&after
      width,
      // width before&after
      [0, 0]
      // dont touch rbg
    ];
    t10.pad = Aa(t10.cropped || input, padding);
    t10.resize = eX.resizeBilinear(t10.pad, [size2, size2]);
    final = je(t10.resize, constants.tf255);
  } else if (input.shape[1] !== size2) {
    t10.resize = eX.resizeBilinear(t10.cropped || input, [size2, size2]);
    final = je(t10.resize, constants.tf255);
  } else {
    final = je(t10.cropped || input, constants.tf255);
  }
  Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
  return final;
}
function rescaleKeypoints(keypoints, outputSize2, cropBox) {
  for (const kpt4 of keypoints) {
    kpt4.position = [
      Math.trunc(kpt4.position[0] * (outputSize2[0] + padding[2][0] + padding[2][1]) / outputSize2[0] - padding[2][0]),
      Math.trunc(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], 2 * kpt4.position[2] / (outputSize2[0] + outputSize2[1])];
  }
  if (cropBox) {
    const width = cropBox[2] - cropBox[0];
    const height = cropBox[3] - cropBox[1];
    for (const kpt4 of keypoints) {
      kpt4.positionRaw = [
        kpt4.positionRaw[0] / height + cropBox[1],
        // correct offset due to crop
        kpt4.positionRaw[1] / width + cropBox[0],
        // correct offset due to crop
        kpt4.positionRaw[2]
      ];
      kpt4.position = [
        Math.trunc(kpt4.positionRaw[0] * outputSize2[0]),
        Math.trunc(kpt4.positionRaw[1] * outputSize2[1]),
        kpt4.positionRaw[2]
      ];
    }
  }
  return keypoints;
}
function fixKeypoints(keypoints) {
  const leftPalm = keypoints.find((k) => k.part === "leftPalm");
  const leftWrist = keypoints.find((k) => k.part === "leftWrist");
  const leftIndex = keypoints.find((k) => k.part === "leftIndex");
  leftPalm.position[2] = ((leftWrist.position[2] || 0) + (leftIndex.position[2] || 0)) / 2;
  const rightPalm = keypoints.find((k) => k.part === "rightPalm");
  const rightWrist = keypoints.find((k) => k.part === "rightWrist");
  const rightIndex = keypoints.find((k) => k.part === "rightIndex");
  rightPalm.position[2] = ((rightWrist.position[2] || 0) + (rightIndex.position[2] || 0)) / 2;
}
async function detectLandmarks(input, config3, outputSize2) {
  if (!(model2 == null ? void 0 : model2["executor"])) return null;
  const t10 = {};
  [
    t10.ld,
    t10.segmentation,
    t10.heatmap,
    t10.world,
    t10.poseflag
    /* 1,1 */
  ] = model2 == null ? void 0 : model2.execute(input, outputNodes.landmarks);
  const poseScore = (await t10.poseflag.data())[0];
  const points = await t10.ld.data();
  const distances = await t10.world.data();
  Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
  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, points[depth * i + 1] / inputSize2, points[depth * i + 2] + 0];
    const position = [Math.trunc(outputSize2[0] * positionRaw[0]), Math.trunc(outputSize2[1] * positionRaw[1]), positionRaw[2]];
    const distance2 = [distances[depth * i + 0], distances[depth * i + 1], distances[depth * i + 2] + 0];
    keypointsRelative.push({ part: kpt[i], positionRaw, position, distance: distance2, score: adjScore });
  }
  if (poseScore < (config3.body.minConfidence || 0)) return null;
  fixKeypoints(keypointsRelative);
  const keypoints = rescaleKeypoints(keypointsRelative, outputSize2);
  const kpts = keypoints.map((k) => k.position);
  const boxes = calc(kpts, [outputSize2[0], outputSize2[1]]);
  const annotations2 = {};
  for (const [name, indexes] of Object.entries(connected)) {
    const pt2 = [];
    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) pt2.push([pt0.position, pt1.position]);
    }
    annotations2[name] = pt2;
  }
  const body4 = { id: 0, score: Math.trunc(100 * poseScore) / 100, box: boxes.box, boxRaw: boxes.boxRaw, keypoints, annotations: annotations2 };
  return body4;
}
async function predict(input, config3) {
  var _a, _b, _c2;
  const outputSize2 = [input.shape[2] || 0, input.shape[1] || 0];
  const skipTime = (config3.body.skipTime || 0) > now() - lastTime;
  const skipFrame = skipped < (config3.body.skipFrames || 0);
  if (config3.skipAllowed && skipTime && skipFrame && cache !== null) {
    skipped++;
  } else {
    let boxes = [];
    if ((_b = (_a = config3.body) == null ? void 0 : _a["detector"]) == null ? void 0 : _b["enabled"]) {
      const preparedImage = prepareImage(input, 224);
      boxes = await detectBoxes(preparedImage, config3, outputSize2);
      Ot(preparedImage);
    } else {
      boxes = [{ box: [0, 0, 0, 0], boxRaw: [0, 0, 1, 1], score: 0 }];
    }
    for (let i = 0; i < boxes.length; i++) {
      const preparedBox = prepareImage(input, 256, (_c2 = boxes[i]) == null ? void 0 : _c2.boxRaw);
      cache.length = 0;
      const bodyResult = await detectLandmarks(preparedBox, config3, outputSize2);
      Ot(preparedBox);
      if (!bodyResult) continue;
      bodyResult.id = i;
      cache.push(bodyResult);
    }
    lastTime = now();
    skipped = 0;
  }
  return cache;
}

// src/object/labels.ts
var labels2 = [
  { 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 model3;
var inputSize3 = 0;
var last2 = [];
var lastTime2 = 0;
var skipped2 = Number.MAX_SAFE_INTEGER;
async function load(config3) {
  if (env.initial) model3 = null;
  if (!model3) {
    model3 = await loadModel(config3.object.modelPath);
    const inputs = (model3 == null ? void 0 : model3["executor"]) ? Object.values(model3.modelSignature["inputs"]) : void 0;
    inputSize3 = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
  } else if (config3.debug) log("cached model:", model3["modelUrl"]);
  return model3;
}
async function process3(res, outputShape, config3) {
  if (!res) return [];
  const t10 = {};
  const results = [];
  const detections = await res.array();
  t10.squeeze = cc(res);
  const arr = li(t10.squeeze, 6, 1);
  t10.stack = vr([arr[1], arr[0], arr[3], arr[2]], 1);
  t10.boxes = cc(t10.stack);
  t10.scores = cc(arr[4]);
  t10.classes = cc(arr[5]);
  Ot([res, ...arr]);
  t10.nms = await eX.nonMaxSuppressionAsync(t10.boxes, t10.scores, config3.object.maxDetected || 0, config3.object.iouThreshold, config3.object.minConfidence || 0);
  const nms = await t10.nms.data();
  let i = 0;
  for (const id2 of Array.from(nms)) {
    const score = Math.trunc(100 * detections[0][id2][4]) / 100;
    const classVal = detections[0][id2][5];
    if (Number.isNaN(classVal)) continue;
    const label = labels2[classVal].label;
    const [x, y8] = [
      detections[0][id2][0] / inputSize3,
      detections[0][id2][1] / inputSize3
    ];
    const boxRaw = [
      x,
      y8,
      detections[0][id2][2] / inputSize3 - x,
      detections[0][id2][3] / inputSize3 - y8
    ];
    const box = [
      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, boxRaw });
  }
  Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
  return results;
}
async function predict2(input, config3) {
  if (!(model3 == null ? void 0 : model3["executor"])) return [];
  const skipTime = (config3.object.skipTime || 0) > now() - lastTime2;
  const skipFrame = skipped2 < (config3.object.skipFrames || 0);
  if (config3.skipAllowed && skipTime && skipFrame && last2.length > 0) {
    skipped2++;
    return last2;
  }
  skipped2 = 0;
  return new Promise(async (resolve) => {
    const outputSize2 = [input.shape[2] || 0, input.shape[1] || 0];
    const resize = eX.resizeBilinear(input, [inputSize3, inputSize3]);
    const objectT = config3.object.enabled ? model3 == null ? void 0 : model3.execute(resize, ["tower_0/detections"]) : null;
    lastTime2 = now();
    Ot(resize);
    const obj = await process3(objectT, outputSize2, config3);
    last2 = 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 model4;
var lastTime3 = 0;
var cache2 = { id: 0, keypoints: [], box: [0, 0, 0, 0], boxRaw: [0, 0, 0, 0], score: 0, annotations: {} };
var skipped3 = Number.MAX_SAFE_INTEGER;
async function load2(config3) {
  if (env.initial) model4 = null;
  if (!model4) model4 = await loadModel(config3.body.modelPath);
  else if (config3.debug) log("cached model:", model4["modelUrl"]);
  return model4;
}
async function max2d(inputs, minScore) {
  const [width, height] = inputs.shape;
  const reshaped = W(inputs, [height * width]);
  const max = Ra(reshaped, 0);
  const newScore = (await max.data())[0];
  if (newScore > minScore) {
    const coordinates = Ok(reshaped, 0);
    const mod = z2(coordinates, width);
    const x = (await mod.data())[0];
    const div = je(coordinates, width);
    const y8 = (await div.data())[0];
    Ot([reshaped, max, coordinates, mod, div]);
    return [x, y8, newScore];
  }
  Ot([reshaped, max]);
  return [0, 0, newScore];
}
async function predict3(image, config3) {
  if (!(model4 == null ? void 0 : model4["executor"]) || !(model4 == null ? void 0 : model4.inputs[0].shape)) return [];
  const skipTime = (config3.body.skipTime || 0) > now() - lastTime3;
  const skipFrame = skipped3 < (config3.body.skipFrames || 0);
  if (config3.skipAllowed && skipTime && skipFrame && Object.keys(cache2.keypoints).length > 0) {
    skipped3++;
    return [cache2];
  }
  skipped3 = 0;
  return new Promise(async (resolve) => {
    const tensor2 = De(() => {
      var _a, _b;
      const resize = eX.resizeBilinear(image, [((_a = model4 == null ? void 0 : model4.inputs[0].shape) == null ? void 0 : _a[2]) || 0, ((_b = model4 == null ? void 0 : model4.inputs[0].shape) == null ? void 0 : _b[1]) || 0], false);
      const enhance2 = se(resize, constants.tf2);
      const norm = Te(enhance2, constants.tf1);
      return norm;
    });
    let resT;
    if (config3.body.enabled) resT = model4 == null ? void 0 : model4.execute(tensor2);
    lastTime3 = now();
    Ot(tensor2);
    if (resT) {
      cache2.keypoints.length = 0;
      const squeeze = cc(resT);
      Ot(resT);
      const stack = fo(squeeze, 2);
      Ot(squeeze);
      for (let id2 = 0; id2 < stack.length; id2++) {
        const [x8, y10, partScore] = await max2d(stack[id2], config3.body.minConfidence);
        if (partScore > (config3.body.minConfidence || 0)) {
          cache2.keypoints.push({
            score: Math.round(100 * partScore) / 100,
            part: kpt2[id2],
            positionRaw: [
              // normalized to 0..1
              // @ts-ignore model is not undefined here
              x8 / model4.inputs[0].shape[2],
              y10 / model4.inputs[0].shape[1]
            ],
            position: [
              // normalized to input image size
              // @ts-ignore model is not undefined here
              Math.round(image.shape[2] * x8 / model4.inputs[0].shape[2]),
              Math.round(image.shape[1] * y10 / model4.inputs[0].shape[1])
            ]
          });
        }
      }
      stack.forEach((s) => Ot(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 y8 = cache2.keypoints.map((a) => a.position[1]);
    cache2.box = [
      Math.min(...x),
      Math.min(...y8),
      Math.max(...x) - Math.min(...x),
      Math.max(...y8) - Math.min(...y8)
    ];
    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 pt2 = [];
      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)) pt2.push([pt0.position, pt1.position]);
      }
      cache2.annotations[name] = pt2;
    }
    resolve([cache2]);
  });
}

// src/face/facemeshutil.ts
var getBoxSize = (box) => [Math.abs(box.endPoint[0] - box.startPoint[0]), Math.abs(box.endPoint[1] - box.startPoint[1])];
var getBoxCenter = (box) => [box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2, box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2, 1];
var clampBox = (box, input) => box ? [
  Math.trunc(Math.max(0, box.startPoint[0])),
  Math.trunc(Math.max(0, box.startPoint[1])),
  Math.trunc(Math.min(input.shape[2] || 0, box.endPoint[0]) - Math.max(0, box.startPoint[0])),
  Math.trunc(Math.min(input.shape[1] || 0, box.endPoint[1]) - Math.max(0, box.startPoint[1]))
] : [0, 0, 0, 0];
var getRawBox = (box, input) => box ? [
  box.startPoint[0] / (input.shape[2] || 0),
  box.startPoint[1] / (input.shape[1] || 0),
  (box.endPoint[0] - box.startPoint[0]) / (input.shape[2] || 0),
  (box.endPoint[1] - box.startPoint[1]) / (input.shape[1] || 0)
] : [0, 0, 0, 0];
var scaleBoxCoordinates = (box, factor, anchor) => {
  const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];
  const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];
  const landmarks = box.landmarks.map((pt2) => [(pt2[0] + anchor[0]) * factor[0], (pt2[1] + anchor[1]) * factor[1]]);
  return { startPoint, endPoint, landmarks, confidence: box.confidence };
};
var cutAndResize = (box, image, cropSize) => {
  const h = image.shape[1];
  const w8 = image.shape[2];
  const cutBox = [box.startPoint[1] / h, box.startPoint[0] / w8, box.endPoint[1] / h, box.endPoint[0] / w8];
  const crop = eX.cropAndResize(image, [cutBox], [0], cropSize);
  const norm = je(crop, constants.tf255);
  Ot(crop);
  return norm;
};
var enlargeBox = (box, factor) => {
  const center = getBoxCenter(box);
  const size2 = getBoxSize(box);
  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: box.landmarks,
    confidence: box.confidence,
    size: size2
  };
};
var squarifyBox = (box) => {
  const centers = getBoxCenter(box);
  const size2 = getBoxSize(box);
  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: box.landmarks,
    confidence: box.confidence,
    size: [Math.round(size2[0]), Math.round(size2[1])]
  };
};
var calculateLandmarksBoundingBox = (landmarks) => {
  const x = landmarks.map((d) => d[0]);
  const y8 = landmarks.map((d) => d[1]);
  return {
    startPoint: [Math.min(...x), Math.min(...y8)],
    endPoint: [Math.max(...x), Math.max(...y8)],
    landmarks
  };
};
var fixedRotationMatrix = [[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, y8) => [[1, 0, x], [0, 1, y8], [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(inputSize10) {
  const spec = inputSize10 === 192 ? { strides: [4], anchors: [1] } : { strides: [inputSize10 / 16, inputSize10 / 8], anchors: [2, 6] };
  const anchors3 = [];
  for (let i = 0; i < spec.strides.length; i++) {
    const stride = spec.strides[i];
    const gridRows = Math.floor((inputSize10 + stride - 1) / stride);
    const gridCols = Math.floor((inputSize10 + 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++) anchors3.push([anchorX, anchorY]);
      }
    }
  }
  return anchors3;
}
function transformRawCoords(coordsRaw, box, angle, rotationMatrix, inputSize10) {
  const boxSize = getBoxSize(box);
  const coordsScaled = coordsRaw.map((coord) => [
    // scaled around zero-point
    boxSize[0] / inputSize10 * (coord[0] - inputSize10 / 2),
    boxSize[1] / inputSize10 * (coord[1] - inputSize10 / 2),
    coord[2] || 0
  ]);
  const largeAngle = angle && angle !== 0 && Math.abs(angle) > 0.2;
  const coordsRotationMatrix = largeAngle ? buildRotationMatrix(angle, [0, 0]) : fixedRotationMatrix;
  const coordsRotated = largeAngle ? coordsScaled.map((coord) => [...rotatePoint(coord, coordsRotationMatrix), coord[2]]) : coordsScaled;
  const inverseRotationMatrix = largeAngle ? invertTransformMatrix(rotationMatrix) : fixedRotationMatrix;
  const boxCenter = getBoxCenter(box);
  const offsets = [dot(boxCenter, inverseRotationMatrix[0]), dot(boxCenter, inverseRotationMatrix[1])];
  return coordsRotated.map((coord) => [
    Math.trunc(coord[0] + offsets[0]),
    Math.trunc(coord[1] + offsets[1]),
    Math.trunc(coord[2] || 0)
  ]);
}
function correctFaceRotation(rotate, box, input, inputSize10) {
  const symmetryLine = box.landmarks.length >= meshLandmarks.count ? meshLandmarks.symmetryLine : blazeFaceLandmarks.symmetryLine;
  let angle = 0;
  let rotationMatrix = fixedRotationMatrix;
  let face4;
  if (rotate && env.kernels.includes("rotatewithoffset")) {
    angle = computeRotation(box.landmarks[symmetryLine[0]], box.landmarks[symmetryLine[1]]);
    const largeAngle = angle && angle !== 0 && Math.abs(angle) > 0.2;
    if (largeAngle) {
      const center = getBoxCenter(box);
      const centerRaw = [center[0] / input.shape[2], center[1] / input.shape[1]];
      const rotated = eX.rotateWithOffset(input, angle, 0, [centerRaw[0], centerRaw[1]]);
      rotationMatrix = buildRotationMatrix(-angle, center);
      face4 = cutAndResize(box, rotated, [inputSize10, inputSize10]);
      Ot(rotated);
    } else {
      face4 = cutAndResize(box, input, [inputSize10, inputSize10]);
    }
  } else {
    face4 = cutAndResize(box, input, [inputSize10, inputSize10]);
  }
  return [angle, rotationMatrix, face4];
}
var findFaceCenter = (mesh) => {
  const x = mesh.map((m) => m[0]);
  const y8 = mesh.map((m) => m[1]);
  return [Math.min(...x) + (Math.max(...x) - Math.min(...x)) / 2, Math.min(...y8) + (Math.max(...y8) - Math.min(...y8)) / 2];
};
var calculateFaceBox = (mesh, previousBox) => {
  const center = findFaceCenter(mesh);
  const boxSize = getBoxSize(previousBox);
  const calculatedBox = {
    startPoint: [center[0] - boxSize[0] / 2, center[1] - boxSize[1] / 2],
    endPoint: [center[0] + boxSize[0] / 2, center[1] + boxSize[1] / 2]
  };
  return calculatedBox;
};

// src/face/blazeface.ts
var keypointsCount = 6;
var model5;
var anchors = null;
var inputSize4 = 0;
var inputSizeT = null;
var size = () => inputSize4;
async function load3(config3) {
  var _a;
  if (env.initial) model5 = null;
  if (!model5) model5 = await loadModel((_a = config3.face.detector) == null ? void 0 : _a.modelPath);
  else if (config3.debug) log("cached model:", model5["modelUrl"]);
  inputSize4 = model5["executor"] && model5.inputs[0].shape ? model5.inputs[0].shape[2] : 256;
  inputSizeT = ke(inputSize4, "int32");
  anchors = mu(generateAnchors(inputSize4));
  return model5;
}
function decodeBoxes2(boxOutputs) {
  if (!anchors || !inputSizeT) return Gr([0, 0]);
  const t10 = {};
  t10.boxStarts = Xe(boxOutputs, [0, 1], [-1, 2]);
  t10.centers = Ce(t10.boxStarts, anchors);
  t10.boxSizes = Xe(boxOutputs, [0, 3], [-1, 2]);
  t10.boxSizesNormalized = je(t10.boxSizes, inputSizeT);
  t10.centersNormalized = je(t10.centers, inputSizeT);
  t10.halfBoxSize = je(t10.boxSizesNormalized, constants.tf2);
  t10.starts = Te(t10.centersNormalized, t10.halfBoxSize);
  t10.ends = Ce(t10.centersNormalized, t10.halfBoxSize);
  t10.startNormalized = se(t10.starts, inputSizeT);
  t10.endNormalized = se(t10.ends, inputSizeT);
  const boxes = r22([t10.startNormalized, t10.endNormalized], 1);
  Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
  return boxes;
}
async function getBoxes(inputImage, config3) {
  var _a, _b, _c2, _d2, _e, _f2, _g2, _h2, _i2;
  if (!inputImage || inputImage["isDisposedInternal"] || inputImage.shape.length !== 4 || inputImage.shape[1] < 1 || inputImage.shape[2] < 1) return [];
  const t10 = {};
  let pad = [0, 0];
  let scale2 = [1, 1];
  if ((_b = (_a = config3 == null ? void 0 : config3.face) == null ? void 0 : _a.detector) == null ? void 0 : _b.square) {
    const xy2 = Math.max(inputImage.shape[2], inputImage.shape[1]);
    pad = [Math.floor((xy2 - inputImage.shape[2]) / 2), Math.floor((xy2 - inputImage.shape[1]) / 2)];
    t10.padded = Aa(inputImage, [[0, 0], [pad[1], pad[1]], [pad[0], pad[0]], [0, 0]]);
    scale2 = [inputImage.shape[2] / xy2, inputImage.shape[1] / xy2];
    pad = [pad[0] / inputSize4, pad[1] / inputSize4];
  } else {
    t10.padded = inputImage.clone();
  }
  t10.resized = eX.resizeBilinear(t10.padded, [inputSize4, inputSize4]);
  t10.div = je(t10.resized, constants.tf127);
  t10.normalized = Te(t10.div, constants.tf1);
  const res = model5 == null ? void 0 : model5.execute(t10.normalized);
  if (Array.isArray(res) && res.length > 2) {
    const sorted = res.sort((a, b) => a.size - b.size);
    t10.concat384 = yt([sorted[0], sorted[2]], 2);
    t10.concat512 = yt([sorted[1], sorted[3]], 2);
    t10.concat = yt([t10.concat512, t10.concat384], 1);
    t10.batch = cc(t10.concat, [0]);
  } else if (Array.isArray(res)) {
    t10.batch = cc(res[0]);
  } else {
    t10.batch = cc(res);
  }
  Ot(res);
  t10.boxes = decodeBoxes2(t10.batch);
  t10.logits = Xe(t10.batch, [0, 0], [-1, 1]);
  t10.sigmoid = Ea(t10.logits);
  t10.scores = cc(t10.sigmoid);
  t10.nms = await eX.nonMaxSuppressionAsync(t10.boxes, t10.scores, ((_c2 = config3.face.detector) == null ? void 0 : _c2.maxDetected) || 0, ((_d2 = config3.face.detector) == null ? void 0 : _d2.iouThreshold) || 0, ((_e = config3.face.detector) == null ? void 0 : _e.minConfidence) || 0);
  const nms = await t10.nms.array();
  const boxes = [];
  const scores = await t10.scores.data();
  for (let i = 0; i < nms.length; i++) {
    const confidence = scores[nms[i]];
    if (confidence > (((_f2 = config3.face.detector) == null ? void 0 : _f2.minConfidence) || 0)) {
      const b = {};
      b.bbox = Xe(t10.boxes, [nms[i], 0], [1, -1]);
      b.slice = Xe(t10.batch, [nms[i], keypointsCount - 1], [1, -1]);
      b.squeeze = cc(b.slice);
      b.landmarks = W(b.squeeze, [keypointsCount, -1]);
      const points = await b.bbox.data();
      const unpadded = [
        // TODO fix this math
        points[0] * scale2[0] - pad[0],
        points[1] * scale2[1] - pad[1],
        points[2] * scale2[0] - pad[0],
        points[3] * scale2[1] - pad[1]
      ];
      const rawBox = {
        startPoint: [unpadded[0], unpadded[1]],
        endPoint: [unpadded[2], unpadded[3]],
        landmarks: await b.landmarks.array(),
        confidence
      };
      b.anchor = Xe(anchors, [nms[i], 0], [1, 2]);
      const anchor = await b.anchor.data();
      const scaledBox = scaleBoxCoordinates(rawBox, [(inputImage.shape[2] || 0) / inputSize4, (inputImage.shape[1] || 0) / inputSize4], anchor);
      const enlargedBox = enlargeBox(scaledBox, ((_g2 = config3.face.detector) == null ? void 0 : _g2.scale) || 1.4);
      const squaredBox = squarifyBox(enlargedBox);
      if (squaredBox.size[0] > (((_h2 = config3.face.detector) == null ? void 0 : _h2["minSize"]) || 0) && squaredBox.size[1] > (((_i2 = config3.face.detector) == null ? void 0 : _i2["minSize"]) || 0)) boxes.push(squaredBox);
      Object.keys(b).forEach((tensor2) => Ot(b[tensor2]));
    }
  }
  Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
  return boxes;
}

// src/face/iris.ts
var model6;
var inputSize5 = 0;
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 load4(config3) {
  var _a, _b;
  if (env.initial) model6 = null;
  if (!model6) model6 = await loadModel((_a = config3.face.iris) == null ? void 0 : _a.modelPath);
  else if (config3.debug) log("cached model:", model6["modelUrl"]);
  inputSize5 = (model6 == null ? void 0 : model6["executor"]) && ((_b = model6.inputs) == null ? void 0 : _b[0].shape) ? model6.inputs[0].shape[2] : 0;
  if (inputSize5 === -1) inputSize5 = 64;
  return model6;
}
function replaceIrisCoords(rawCoords, newCoords, prefix, keys) {
  for (let i = 0; i < irisIndices.length; i++) {
    const { key, indices } = irisIndices[i];
    const originalIndices = meshAnnotations[`${prefix}${key}`];
    if (!keys || keys.includes(key)) {
      for (let j = 0; j < indices.length; j++) {
        const index2 = indices[j];
        rawCoords[originalIndices[j]] = [
          newCoords[index2][0],
          newCoords[index2][1],
          (newCoords[index2][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, face4, eyeInnerCornerIndex, eyeOuterCornerIndex, meshSize, flip = false, scale2 = 2.3) => {
  const box = squarifyBox(enlargeBox(calculateLandmarksBoundingBox([rawCoords[eyeInnerCornerIndex], rawCoords[eyeOuterCornerIndex]]), scale2));
  const boxSize = getBoxSize(box);
  let crop = eX.cropAndResize(face4, [[
    box.startPoint[1] / meshSize,
    box.startPoint[0] / meshSize,
    box.endPoint[1] / meshSize,
    box.endPoint[0] / meshSize
  ]], [0], [inputSize5, inputSize5]);
  if (flip && env.kernels.includes("flipleftright")) {
    const flipped = eX.flipLeftRight(crop);
    Ot(crop);
    crop = flipped;
  }
  return { box, boxSize, crop };
};
var getEyeCoords = (eyeData, eyeBox, eyeBoxSize, flip = false) => {
  const eyeRawCoords = [];
  for (let i = 0; i < irisLandmarks.numCoordinates; i++) {
    const x = eyeData[i * 3];
    const y8 = eyeData[i * 3 + 1];
    const z = eyeData[i * 3 + 2];
    eyeRawCoords.push([
      (flip ? 1 - x / inputSize5 : x / inputSize5) * eyeBoxSize[0] + eyeBox.startPoint[0],
      y8 / inputSize5 * eyeBoxSize[1] + eyeBox.startPoint[1],
      z
    ]);
  }
  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 z = averageZ;
    if (i === 2) {
      z = upperCenterZ;
    } else if (i === 4) {
      z = lowerCenterZ;
    }
    return [coord[0], coord[1], z];
  });
};
async function augmentIris(rawCoords, face4, meshSize, config3) {
  var _a, _b;
  if (!(model6 == null ? void 0 : model6["executor"])) return rawCoords;
  const { box: leftEyeBox, boxSize: leftEyeBoxSize, crop: leftEyeCrop } = getEyeBox(rawCoords, face4, eyeLandmarks.leftBounds[0], eyeLandmarks.leftBounds[1], meshSize, true, ((_a = config3.face.iris) == null ? void 0 : _a.scale) || 2.3);
  const { box: rightEyeBox, boxSize: rightEyeBoxSize, crop: rightEyeCrop } = getEyeBox(rawCoords, face4, eyeLandmarks.rightBounds[0], eyeLandmarks.rightBounds[1], meshSize, true, ((_b = config3.face.iris) == null ? void 0 : _b.scale) || 2.3);
  const combined = yt([leftEyeCrop, rightEyeCrop]);
  Ot(leftEyeCrop);
  Ot(rightEyeCrop);
  const eyePredictions = model6.execute(combined);
  Ot(combined);
  const eyePredictionsData = await eyePredictions.data();
  Ot(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, false);
  const leftToRightEyeDepthDifference = getLeftToRightEyeDepthDifference(rawCoords);
  if (Math.abs(leftToRightEyeDepthDifference) < 30) {
    replaceIrisCoords(rawCoords, leftEyeRawCoords, "left", null);
    replaceIrisCoords(rawCoords, rightEyeRawCoords, "right", null);
  } else if (leftToRightEyeDepthDifference < 1) {
    replaceIrisCoords(rawCoords, leftEyeRawCoords, "left", ["EyeUpper0", "EyeLower0"]);
  } else {
    replaceIrisCoords(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/attention.ts
async function augment(rawCoords, results) {
  var _a, _b, _c2, _d2, _e, _f2, _g2, _h2, _i2, _j2;
  const t10 = {
    // all attention models produce 2d results so it needs to be later augmented with correct z-coords
    // mesh: results[0], // already have it in rawCoords // output_mesh_identity
    // flag: results[1], // already processed in parent // conv_faceflag
    lips: await ((_b = (_a = results.filter((r15) => r15.size === 160)) == null ? void 0 : _a[0]) == null ? void 0 : _b.data()),
    // 80 x 2d = 160 // output_lips
    irisL: await ((_d2 = (_c2 = results.filter((r15) => r15.size === 10)) == null ? void 0 : _c2[0]) == null ? void 0 : _d2.data()),
    // 5 x 2d = 10 // output_right_iris
    eyeL: await ((_f2 = (_e = results.filter((r15) => r15.size === 142)) == null ? void 0 : _e[0]) == null ? void 0 : _f2.data()),
    // 71 x 2d = 142 // output_right_eye
    irisR: await ((_h2 = (_g2 = results.filter((r15) => r15.size === 10)) == null ? void 0 : _g2[1]) == null ? void 0 : _h2.data()),
    // 5 x 2d = 10 // output_left_iris
    eyeR: await ((_j2 = (_i2 = results.filter((r15) => r15.size === 142)) == null ? void 0 : _i2[1]) == null ? void 0 : _j2.data())
    // 71 x 2d = 142// output_left_eye
  };
  for (const val of Object.values(t10)) {
    if (!val) return rawCoords;
  }
  const irisLDepth = LANDMARKS_REFINEMENT_LEFT_EYE_CONFIG.reduce((prev, curr) => prev += rawCoords[curr][2], 0) / LANDMARKS_REFINEMENT_LEFT_EYE_CONFIG.length;
  for (let i = 0; i < t10.irisL.length / 2; i++) rawCoords.push([t10.irisL[2 * i + 0], t10.irisL[2 * i + 1], irisLDepth]);
  const irisRDepth = LANDMARKS_REFINEMENT_RIGHT_EYE_CONFIG.reduce((prev, curr) => prev += rawCoords[curr][2], 0) / LANDMARKS_REFINEMENT_RIGHT_EYE_CONFIG.length;
  for (let i = 0; i < t10.irisR.length / 2; i++) rawCoords.push([t10.irisR[2 * i + 0], t10.irisR[2 * i + 1], irisRDepth]);
  for (let i = 0; i < t10.eyeL.length / 2; i++) rawCoords[LANDMARKS_REFINEMENT_LEFT_EYE_CONFIG[i]] = [t10.eyeL[2 * i + 0], t10.eyeL[2 * i + 1], rawCoords[LANDMARKS_REFINEMENT_LEFT_EYE_CONFIG[i]][2]];
  for (let i = 0; i < t10.eyeR.length / 2; i++) rawCoords[LANDMARKS_REFINEMENT_RIGHT_EYE_CONFIG[i]] = [t10.eyeR[2 * i + 0], t10.eyeR[2 * i + 1], rawCoords[LANDMARKS_REFINEMENT_RIGHT_EYE_CONFIG[i]][2]];
  for (let i = 0; i < t10.lips.length / 2; i++) rawCoords[LANDMARKS_REFINEMENT_LIPS_CONFIG[i]] = [t10.lips[2 * i + 0], t10.lips[2 * i + 1], rawCoords[LANDMARKS_REFINEMENT_LIPS_CONFIG[i]][2]];
  return rawCoords;
}

// src/face/facemesh.ts
var cache3 = {
  boxes: [],
  skipped: Number.MAX_SAFE_INTEGER,
  timestamp: 0
};
var model7 = null;
var inputSize6 = 0;
async function predict4(input, config3) {
  var _a, _b, _c2, _d2, _e, _f2, _g2, _h2, _i2, _j2;
  const skipTime = (((_a = config3.face.detector) == null ? void 0 : _a.skipTime) || 0) > now() - cache3.timestamp;
  const skipFrame = cache3.skipped < (((_b = config3.face.detector) == null ? void 0 : _b.skipFrames) || 0);
  if (!config3.skipAllowed || !skipTime || !skipFrame || cache3.boxes.length === 0) {
    cache3.boxes = await getBoxes(input, config3);
    cache3.timestamp = now();
    cache3.skipped = 0;
  } else {
    cache3.skipped++;
  }
  const faces = [];
  const newCache = [];
  let id2 = 0;
  const size2 = inputSize6;
  for (let i = 0; i < cache3.boxes.length; i++) {
    const box = cache3.boxes[i];
    let angle = 0;
    let rotationMatrix;
    const face4 = {
      // init face result
      id: id2++,
      mesh: [],
      meshRaw: [],
      box: [0, 0, 0, 0],
      boxRaw: [0, 0, 0, 0],
      score: 0,
      boxScore: 0,
      faceScore: 0,
      size: [0, 0],
      // contoursRaw: [],
      // contours: [],
      annotations: {}
    };
    [angle, rotationMatrix, face4.tensor] = correctFaceRotation((_c2 = config3.face.detector) == null ? void 0 : _c2.rotation, box, input, ((_d2 = config3.face.mesh) == null ? void 0 : _d2.enabled) ? inputSize6 : size());
    if (config3.filter.equalization) {
      const equilized = face4.tensor ? await histogramEqualization(face4.tensor) : void 0;
      Ot(face4.tensor);
      if (equilized) face4.tensor = equilized;
    }
    face4.boxScore = Math.round(100 * box.confidence) / 100;
    if (!((_e = config3.face.mesh) == null ? void 0 : _e.enabled) || !(model7 == null ? void 0 : model7["executor"])) {
      face4.box = clampBox(box, input);
      face4.boxRaw = getRawBox(box, input);
      face4.score = face4.boxScore;
      face4.size = box.size;
      face4.mesh = box.landmarks;
      face4.meshRaw = face4.mesh.map((pt2) => [pt2[0] / (input.shape[2] || 0), pt2[1] / (input.shape[1] || 0), (pt2[2] || 0) / size2]);
      for (const key of Object.keys(blazeFaceLandmarks)) face4.annotations[key] = [face4.mesh[blazeFaceLandmarks[key]]];
    } else if (!model7) {
      if (config3.debug) log("face mesh detection requested, but model is not loaded");
    } else {
      if (((_f2 = config3.face.attention) == null ? void 0 : _f2.enabled) && !env.kernels.includes("atan2")) {
        config3.face.attention.enabled = false;
        Ot(face4.tensor);
        return faces;
      }
      const results = model7.execute(face4.tensor);
      const confidenceT = results.find((t10) => t10.shape[t10.shape.length - 1] === 1);
      const faceConfidence = await confidenceT.data();
      face4.faceScore = Math.round(100 * faceConfidence[0]) / 100;
      if (face4.faceScore < (((_g2 = config3.face.detector) == null ? void 0 : _g2.minConfidence) || 1)) {
        box.confidence = face4.faceScore;
        if (config3.face.mesh["keepInvalid"]) {
          face4.box = clampBox(box, input);
          face4.boxRaw = getRawBox(box, input);
          face4.size = box.size;
          face4.score = face4.boxScore;
          face4.mesh = box.landmarks;
          face4.meshRaw = face4.mesh.map((pt2) => [pt2[0] / (input.shape[2] || 1), pt2[1] / (input.shape[1] || 1), (pt2[2] || 0) / size2]);
          for (const key of Object.keys(blazeFaceLandmarks)) {
            face4.annotations[key] = [face4.mesh[blazeFaceLandmarks[key]]];
          }
        }
      } else {
        const meshT = results.find((t10) => t10.shape[t10.shape.length - 1] === 1404);
        const coordsReshaped = W(meshT, [-1, 3]);
        let rawCoords = await coordsReshaped.array();
        Ot(coordsReshaped);
        if ((_h2 = config3.face.attention) == null ? void 0 : _h2.enabled) {
          rawCoords = await augment(rawCoords, results);
        } else if ((_i2 = config3.face.iris) == null ? void 0 : _i2.enabled) {
          rawCoords = await augmentIris(rawCoords, face4.tensor, inputSize6, config3);
        }
        face4.mesh = transformRawCoords(rawCoords, box, angle, rotationMatrix, inputSize6);
        face4.meshRaw = face4.mesh.map((pt2) => [pt2[0] / (input.shape[2] || 0), pt2[1] / (input.shape[1] || 0), (pt2[2] || 0) / size2]);
        for (const key of Object.keys(meshAnnotations)) face4.annotations[key] = meshAnnotations[key].map((index2) => face4.mesh[index2]);
        face4.score = face4.faceScore;
        const calculatedBox = {
          ...calculateFaceBox(face4.mesh, box),
          confidence: box.confidence,
          landmarks: box.landmarks,
          size: box.size
        };
        face4.box = clampBox(calculatedBox, input);
        face4.boxRaw = getRawBox(calculatedBox, input);
        face4.size = calculatedBox.size;
        newCache.push(calculatedBox);
      }
      Ot(results);
    }
    if (face4.score > (((_j2 = config3.face.detector) == null ? void 0 : _j2.minConfidence) || 1)) faces.push(face4);
    else Ot(face4.tensor);
  }
  cache3.boxes = newCache;
  return faces;
}
async function load5(config3) {
  var _a, _b, _c2, _d2, _e, _f2;
  if (env.initial) model7 = null;
  if (((_a = config3.face.attention) == null ? void 0 : _a.enabled) && (model7 == null ? void 0 : model7["signature"])) {
    if (Object.keys(((_b = model7 == null ? void 0 : model7["signature"]) == null ? void 0 : _b.outputs) || {}).length < 6) model7 = null;
  }
  if (!model7) {
    if ((_c2 = config3.face.attention) == null ? void 0 : _c2.enabled) model7 = await loadModel(config3.face.attention.modelPath);
    else model7 = await loadModel((_d2 = config3.face.mesh) == null ? void 0 : _d2.modelPath);
  } else if (config3.debug) {
    log("cached model:", model7["modelUrl"]);
  }
  inputSize6 = model7["executor"] && ((_e = model7 == null ? void 0 : model7.inputs) == null ? void 0 : _e[0].shape) ? (_f2 = model7 == null ? void 0 : model7.inputs) == null ? void 0 : _f2[0].shape[2] : 256;
  return model7;
}
var triangulation = TRI468;
var uvmap = UV468;

// src/gear/emotion.ts
var annotations = [];
var model8;
var last3 = [];
var lastCount = 0;
var lastTime4 = 0;
var skipped4 = Number.MAX_SAFE_INTEGER;
var rgb = false;
async function load6(config3) {
  var _a, _b, _c2;
  if (env.initial) model8 = null;
  if (!model8) {
    model8 = await loadModel((_a = config3.face.emotion) == null ? void 0 : _a.modelPath);
    rgb = ((_c2 = (_b = model8 == null ? void 0 : model8.inputs) == null ? void 0 : _b[0].shape) == null ? void 0 : _c2[3]) === 3;
    if (!rgb) annotations = ["angry", "disgust", "fear", "happy", "sad", "surprise", "neutral"];
    else annotations = ["angry", "disgust", "fear", "happy", "neutral", "sad", "surprise"];
  } else if (config3.debug) {
    log("cached model:", model8["modelUrl"]);
  }
  return model8;
}
async function predict5(image, config3, idx, count2) {
  var _a, _b;
  if (!model8) return [];
  const skipFrame = skipped4 < (((_a = config3.face.emotion) == null ? void 0 : _a.skipFrames) || 0);
  const skipTime = (((_b = config3.face.emotion) == null ? void 0 : _b.skipTime) || 0) > now() - lastTime4;
  if (config3.skipAllowed && skipTime && skipFrame && lastCount === count2 && last3[idx] && last3[idx].length > 0) {
    skipped4++;
    return last3[idx];
  }
  skipped4 = 0;
  return new Promise(async (resolve) => {
    var _a2, _b2, _c2;
    const obj = [];
    if ((_a2 = config3.face.emotion) == null ? void 0 : _a2.enabled) {
      const t10 = {};
      const inputSize10 = (model8 == null ? void 0 : model8.inputs[0].shape) ? model8.inputs[0].shape[2] : 0;
      if (((_b2 = config3.face.emotion) == null ? void 0 : _b2["crop"]) > 0) {
        const crop = (_c2 = config3.face.emotion) == null ? void 0 : _c2["crop"];
        const box = [[crop, crop, 1 - crop, 1 - crop]];
        t10.resize = eX.cropAndResize(image, box, [0], [inputSize10, inputSize10]);
      } else {
        t10.resize = eX.resizeBilinear(image, [inputSize10, inputSize10], false);
      }
      if (rgb) {
        t10.mul = se(t10.resize, 255);
        t10.normalize = Te(t10.mul, [103.939, 116.779, 123.68]);
        t10.emotion = model8 == null ? void 0 : model8.execute(t10.normalize);
      } else {
        t10.channels = se(t10.resize, constants.rgb);
        t10.grayscale = ot(t10.channels, 3, true);
        t10.grayscaleSub = Te(t10.grayscale, constants.tf05);
        t10.grayscaleMul = se(t10.grayscaleSub, constants.tf2);
        t10.emotion = model8 == null ? void 0 : model8.execute(t10.grayscaleMul);
      }
      lastTime4 = now();
      const data = await t10.emotion.data();
      for (let i = 0; i < data.length; i++) {
        if (data[i] > (config3.face.emotion.minConfidence || 0)) obj.push({ score: Math.min(0.99, Math.trunc(100 * data[i]) / 100), emotion: annotations[i] });
      }
      obj.sort((a, b) => b.score - a.score);
      Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
    }
    last3[idx] = obj;
    lastCount = count2;
    resolve(obj);
  });
}

// src/face/faceres.ts
var model9;
var last4 = [];
var lastTime5 = 0;
var lastCount2 = 0;
var skipped5 = Number.MAX_SAFE_INTEGER;
async function load7(config3) {
  var _a;
  if (env.initial) model9 = null;
  if (!model9) model9 = await loadModel((_a = config3.face.description) == null ? void 0 : _a.modelPath);
  else if (config3.debug) log("cached model:", model9["modelUrl"]);
  return model9;
}
function enhance(input, config3) {
  var _a, _b;
  const tensor2 = input.image || input.tensor || input;
  if (!(model9 == null ? void 0 : model9.inputs[0].shape)) return tensor2;
  let crop;
  if (((_a = config3.face.description) == null ? void 0 : _a["crop"]) > 0) {
    const cropval = (_b = config3.face.description) == null ? void 0 : _b["crop"];
    const box = [[cropval, cropval, 1 - cropval, 1 - cropval]];
    crop = eX.cropAndResize(tensor2, box, [0], [model9.inputs[0].shape[2], model9.inputs[0].shape[1]]);
  } else {
    crop = eX.resizeBilinear(tensor2, [model9.inputs[0].shape[2], model9.inputs[0].shape[1]], false);
  }
  const norm = se(crop, constants.tf255);
  Ot(crop);
  return norm;
}
async function predict6(image, config3, idx, count2) {
  var _a, _b, _c2, _d2;
  const obj = {
    age: 0,
    gender: "unknown",
    genderScore: 0,
    descriptor: []
  };
  if (!(model9 == null ? void 0 : model9["executor"])) return obj;
  const skipFrame = skipped5 < (((_a = config3.face.description) == null ? void 0 : _a.skipFrames) || 0);
  const skipTime = (((_b = config3.face.description) == null ? void 0 : _b.skipTime) || 0) > now() - lastTime5;
  if (config3.skipAllowed && skipFrame && skipTime && lastCount2 === count2 && ((_c2 = last4 == null ? void 0 : last4[idx]) == null ? void 0 : _c2.age) > 0 && ((_d2 = last4 == null ? void 0 : last4[idx]) == null ? void 0 : _d2.genderScore) > 0) {
    skipped5++;
    return last4[idx];
  }
  skipped5 = 0;
  return new Promise(async (resolve) => {
    var _a2;
    if ((_a2 = config3.face.description) == null ? void 0 : _a2.enabled) {
      const enhanced = enhance(image, config3);
      const resT = model9 == null ? void 0 : model9.execute(enhanced);
      lastTime5 = now();
      Ot(enhanced);
      const genderT = resT.find((t10) => t10.shape[1] === 1);
      const gender2 = await genderT.data();
      const confidence = Math.trunc(200 * Math.abs(gender2[0] - 0.5)) / 100;
      if (confidence > (config3.face.description.minConfidence || 0)) {
        obj.gender = gender2[0] <= 0.5 ? "female" : "male";
        obj.genderScore = Math.min(0.99, confidence);
      }
      const argmax = Ok(resT.find((t10) => t10.shape[1] === 100), 1);
      const ageIdx = (await argmax.data())[0];
      Ot(argmax);
      const ageT = resT.find((t10) => t10.shape[1] === 100);
      const all2 = await ageT.data();
      obj.age = Math.round(all2[ageIdx - 1] > all2[ageIdx + 1] ? 10 * ageIdx - 100 * all2[ageIdx - 1] : 10 * ageIdx + 100 * all2[ageIdx + 1]) / 10;
      if (Number.isNaN(gender2[0]) || Number.isNaN(all2[0])) log("faceres error:", { model: model9, result: resT });
      const desc = resT.find((t10) => t10.shape[1] === 1024);
      const descriptor = desc ? await desc.data() : [];
      obj.descriptor = Array.from(descriptor);
      resT.forEach((t10) => Ot(t10));
    }
    last4[idx] = obj;
    lastCount2 = count2;
    resolve(obj);
  });
}

// src/face/mask.ts
var expandFact = 0.1;
var alpha = 0.5;
function insidePoly(x, y8, polygon) {
  let inside = false;
  let j = polygon.length - 1;
  for (let i = 0; i < polygon.length; j = i++) {
    if (polygon[i].y > y8 !== polygon[j].y > y8 && x < (polygon[j].x - polygon[i].x) * (y8 - polygon[i].y) / (polygon[j].y - polygon[i].y) + polygon[i].x) inside = !inside;
  }
  return inside;
}
async function mask(face4) {
  if (!face4.tensor) return face4.tensor;
  if (!face4.mesh || face4.mesh.length < 100) return face4.tensor;
  const width = face4.tensor.shape[2] || 0;
  const height = face4.tensor.shape[1] || 0;
  const buffer = await face4.tensor.buffer();
  let silhouette = [];
  for (const pt2 of meshAnnotations.silhouette) silhouette.push({ x: (face4.mesh[pt2][0] - face4.box[0]) / face4.box[2], y: (face4.mesh[pt2][1] - face4.box[1]) / face4.box[3] });
  if (expandFact && expandFact > 0) silhouette = silhouette.map((pt2) => ({ x: pt2.x > 0.5 ? pt2.x + expandFact : pt2.x - expandFact, y: pt2.y > 0.5 ? pt2.y + expandFact : pt2.y - expandFact }));
  for (let x = 0; x < width; x++) {
    for (let y8 = 0; y8 < height; y8++) {
      const inside = insidePoly(x / width, y8 / width, silhouette);
      if (!inside) {
        buffer.set(alpha * buffer.get(0, y8, x, 0), 0, y8, x, 0);
        buffer.set(alpha * buffer.get(0, y8, x, 1), 0, y8, x, 1);
        buffer.set(alpha * buffer.get(0, y8, x, 2), 0, y8, x, 2);
      }
    }
  }
  const output = buffer.toTensor();
  return output;
}

// src/face/antispoof.ts
var model10;
var cached = [];
var skipped6 = Number.MAX_SAFE_INTEGER;
var lastCount3 = 0;
var lastTime6 = 0;
async function load8(config3) {
  var _a;
  if (env.initial) model10 = null;
  if (!model10) model10 = await loadModel((_a = config3.face.antispoof) == null ? void 0 : _a.modelPath);
  else if (config3.debug) log("cached model:", model10["modelUrl"]);
  return model10;
}
async function predict7(image, config3, idx, count2) {
  var _a, _b;
  if (!(model10 == null ? void 0 : model10["executor"])) return 0;
  const skipTime = (((_a = config3.face.antispoof) == null ? void 0 : _a.skipTime) || 0) > now() - lastTime6;
  const skipFrame = skipped6 < (((_b = config3.face.antispoof) == null ? void 0 : _b.skipFrames) || 0);
  if (config3.skipAllowed && skipTime && skipFrame && lastCount3 === count2 && cached[idx]) {
    skipped6++;
    return cached[idx];
  }
  skipped6 = 0;
  return new Promise(async (resolve) => {
    const resize = eX.resizeBilinear(image, [(model10 == null ? void 0 : model10.inputs[0].shape) ? model10.inputs[0].shape[2] : 0, (model10 == null ? void 0 : model10.inputs[0].shape) ? model10.inputs[0].shape[1] : 0], false);
    const res = model10 == null ? void 0 : model10.execute(resize);
    const num = (await res.data())[0];
    cached[idx] = Math.round(100 * num) / 100;
    lastCount3 = count2;
    lastTime6 = now();
    Ot([resize, res]);
    resolve(cached[idx]);
  });
}

// src/face/liveness.ts
var model11;
var cached2 = [];
var skipped7 = Number.MAX_SAFE_INTEGER;
var lastCount4 = 0;
var lastTime7 = 0;
async function load9(config3) {
  var _a;
  if (env.initial) model11 = null;
  if (!model11) model11 = await loadModel((_a = config3.face.liveness) == null ? void 0 : _a.modelPath);
  else if (config3.debug) log("cached model:", model11["modelUrl"]);
  return model11;
}
async function predict8(image, config3, idx, count2) {
  var _a, _b;
  if (!(model11 == null ? void 0 : model11["executor"])) return 0;
  const skipTime = (((_a = config3.face.liveness) == null ? void 0 : _a.skipTime) || 0) > now() - lastTime7;
  const skipFrame = skipped7 < (((_b = config3.face.liveness) == null ? void 0 : _b.skipFrames) || 0);
  if (config3.skipAllowed && skipTime && skipFrame && lastCount4 === count2 && cached2[idx]) {
    skipped7++;
    return cached2[idx];
  }
  skipped7 = 0;
  return new Promise(async (resolve) => {
    const resize = eX.resizeBilinear(image, [(model11 == null ? void 0 : model11.inputs[0].shape) ? model11.inputs[0].shape[2] : 0, (model11 == null ? void 0 : model11.inputs[0].shape) ? model11.inputs[0].shape[1] : 0], false);
    const res = model11 == null ? void 0 : model11.execute(resize);
    const num = (await res.data())[0];
    cached2[idx] = Math.round(100 * num) / 100;
    lastCount4 = count2;
    lastTime7 = now();
    Ot([resize, res]);
    resolve(cached2[idx]);
  });
}

// src/gear/gear.ts
var model12;
var last5 = [];
var raceNames = ["white", "black", "asian", "indian", "other"];
var ageWeights = [15, 23, 28, 35.5, 45.5, 55.5, 65];
var lastCount5 = 0;
var lastTime8 = 0;
var skipped8 = Number.MAX_SAFE_INTEGER;
async function load10(config3) {
  var _a;
  if (env.initial) model12 = null;
  if (!model12) model12 = await loadModel((_a = config3.face.gear) == null ? void 0 : _a.modelPath);
  else if (config3.debug) log("cached model:", model12["modelUrl"]);
  return model12;
}
async function predict9(image, config3, idx, count2) {
  var _a, _b;
  if (!model12) return { age: 0, gender: "unknown", genderScore: 0, race: [] };
  const skipFrame = skipped8 < (((_a = config3.face.gear) == null ? void 0 : _a.skipFrames) || 0);
  const skipTime = (((_b = config3.face.gear) == null ? void 0 : _b.skipTime) || 0) > now() - lastTime8;
  if (config3.skipAllowed && skipTime && skipFrame && lastCount5 === count2 && last5[idx]) {
    skipped8++;
    return last5[idx];
  }
  skipped8 = 0;
  return new Promise(async (resolve) => {
    var _a2, _b2, _c2, _d2;
    if (!(model12 == null ? void 0 : model12.inputs[0].shape)) return;
    const t10 = {};
    let box = [[0, 0.1, 0.9, 0.9]];
    if (((_a2 = config3.face.gear) == null ? void 0 : _a2["crop"]) > 0) {
      const crop = (_b2 = config3.face.gear) == null ? void 0 : _b2["crop"];
      box = [[crop, crop, 1 - crop, 1 - crop]];
    }
    t10.resize = eX.cropAndResize(image, box, [0], [model12.inputs[0].shape[2], model12.inputs[0].shape[1]]);
    const obj = { age: 0, gender: "unknown", genderScore: 0, race: [] };
    if ((_c2 = config3.face.gear) == null ? void 0 : _c2.enabled) [t10.age, t10.gender, t10.race] = model12.execute(t10.resize, ["age_output", "gender_output", "race_output"]);
    const gender2 = await t10.gender.data();
    obj.gender = gender2[0] > gender2[1] ? "male" : "female";
    obj.genderScore = Math.round(100 * (gender2[0] > gender2[1] ? gender2[0] : gender2[1])) / 100;
    const race = await t10.race.data();
    for (let i = 0; i < race.length; i++) {
      if (race[i] > (((_d2 = config3.face.gear) == null ? void 0 : _d2.minConfidence) || 0.2)) obj.race.push({ score: Math.round(100 * race[i]) / 100, race: raceNames[i] });
    }
    obj.race.sort((a, b) => b.score - a.score);
    const ageDistribution = Array.from(await t10.age.data());
    const ageSorted = ageDistribution.map((a, i) => [ageWeights[i], a]).sort((a, b) => b[1] - a[1]);
    let age2 = ageSorted[0][0];
    for (let i = 1; i < ageSorted.length; i++) age2 += ageSorted[i][1] * (ageSorted[i][0] - age2);
    obj.age = Math.round(10 * age2) / 10;
    Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
    last5[idx] = obj;
    lastCount5 = count2;
    lastTime8 = now();
    resolve(obj);
  });
}

// src/gear/ssrnet-age.ts
var model13;
var last6 = [];
var lastCount6 = 0;
var lastTime9 = 0;
var skipped9 = Number.MAX_SAFE_INTEGER;
async function load11(config3) {
  if (env.initial) model13 = null;
  if (!model13) model13 = await loadModel(config3.face["ssrnet"].modelPathAge);
  else if (config3.debug) log("cached model:", model13["modelUrl"]);
  return model13;
}
async function predict10(image, config3, idx, count2) {
  var _a, _b, _c2, _d2;
  if (!model13) return { age: 0 };
  const skipFrame = skipped9 < (((_a = config3.face["ssrnet"]) == null ? void 0 : _a.skipFrames) || 0);
  const skipTime = (((_b = config3.face["ssrnet"]) == null ? void 0 : _b.skipTime) || 0) > now() - lastTime9;
  if (config3.skipAllowed && skipFrame && skipTime && lastCount6 === count2 && ((_c2 = last6[idx]) == null ? void 0 : _c2.age) && ((_d2 = last6[idx]) == null ? void 0 : _d2.age) > 0) {
    skipped9++;
    return last6[idx];
  }
  skipped9 = 0;
  return new Promise(async (resolve) => {
    var _a2, _b2, _c3;
    if (!(model13 == null ? void 0 : model13.inputs) || !model13.inputs[0] || !model13.inputs[0].shape) return;
    const t10 = {};
    if (((_a2 = config3.face["ssrnet"]) == null ? void 0 : _a2["crop"]) > 0) {
      const crop = (_b2 = config3.face["ssrnet"]) == null ? void 0 : _b2["crop"];
      const box = [[crop, crop, 1 - crop, 1 - crop]];
      t10.resize = eX.cropAndResize(image, box, [0], [model13.inputs[0].shape[2], model13.inputs[0].shape[1]]);
    } else {
      t10.resize = eX.resizeBilinear(image, [model13.inputs[0].shape[2], model13.inputs[0].shape[1]], false);
    }
    t10.enhance = se(t10.resize, constants.tf255);
    const obj = { age: 0 };
    if ((_c3 = config3.face["ssrnet"]) == null ? void 0 : _c3.enabled) t10.age = model13.execute(t10.enhance);
    if (t10.age) {
      const data = await t10.age.data();
      obj.age = Math.trunc(10 * data[0]) / 10;
    }
    Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
    last6[idx] = obj;
    lastCount6 = count2;
    lastTime9 = now();
    resolve(obj);
  });
}

// src/gear/ssrnet-gender.ts
var model14;
var last7 = [];
var lastCount7 = 0;
var lastTime10 = 0;
var skipped10 = Number.MAX_SAFE_INTEGER;
var rgb2 = [0.2989, 0.587, 0.114];
async function load12(config3) {
  var _a;
  if (env.initial) model14 = null;
  if (!model14) model14 = await loadModel((_a = config3.face["ssrnet"]) == null ? void 0 : _a.modelPathGender);
  else if (config3.debug) log("cached model:", model14["modelUrl"]);
  return model14;
}
async function predict11(image, config3, idx, count2) {
  var _a, _b, _c2, _d2;
  if (!model14) return { gender: "unknown", genderScore: 0 };
  const skipFrame = skipped10 < (((_a = config3.face["ssrnet"]) == null ? void 0 : _a.skipFrames) || 0);
  const skipTime = (((_b = config3.face["ssrnet"]) == null ? void 0 : _b.skipTime) || 0) > now() - lastTime10;
  if (config3.skipAllowed && skipFrame && skipTime && lastCount7 === count2 && ((_c2 = last7[idx]) == null ? void 0 : _c2.gender) && ((_d2 = last7[idx]) == null ? void 0 : _d2.genderScore) > 0) {
    skipped10++;
    return last7[idx];
  }
  skipped10 = 0;
  return new Promise(async (resolve) => {
    var _a2, _b2, _c3;
    if (!(model14 == null ? void 0 : model14.inputs[0].shape)) return;
    const t10 = {};
    if (((_a2 = config3.face["ssrnet"]) == null ? void 0 : _a2["crop"]) > 0) {
      const crop = (_b2 = config3.face["ssrnet"]) == null ? void 0 : _b2["crop"];
      const box = [[crop, crop, 1 - crop, 1 - crop]];
      t10.resize = eX.cropAndResize(image, box, [0], [model14.inputs[0].shape[2], model14.inputs[0].shape[1]]);
    } else {
      t10.resize = eX.resizeBilinear(image, [model14.inputs[0].shape[2], model14.inputs[0].shape[1]], false);
    }
    t10.enhance = De(() => {
      var _a3, _b3;
      let normalize2;
      if (((_b3 = (_a3 = model14 == null ? void 0 : model14.inputs) == null ? void 0 : _a3[0].shape) == null ? void 0 : _b3[3]) === 1) {
        const [red, green, blue] = li(t10.resize, 3, 3);
        const redNorm = se(red, rgb2[0]);
        const greenNorm = se(green, rgb2[1]);
        const blueNorm = se(blue, rgb2[2]);
        const grayscale = Ak([redNorm, greenNorm, blueNorm]);
        normalize2 = se(Te(grayscale, constants.tf05), 2);
      } else {
        normalize2 = se(Te(t10.resize, constants.tf05), 2);
      }
      return normalize2;
    });
    const obj = { gender: "unknown", genderScore: 0 };
    if ((_c3 = config3.face["ssrnet"]) == null ? void 0 : _c3.enabled) t10.gender = model14.execute(t10.enhance);
    const data = await t10.gender.data();
    obj.gender = data[0] > data[1] ? "female" : "male";
    obj.genderScore = data[0] > data[1] ? Math.trunc(100 * data[0]) / 100 : Math.trunc(100 * data[1]) / 100;
    Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
    last7[idx] = obj;
    lastCount7 = count2;
    lastTime10 = now();
    resolve(obj);
  });
}

// src/face/mobilefacenet.ts
var model15;
var last8 = [];
var lastCount8 = 0;
var lastTime11 = 0;
var skipped11 = Number.MAX_SAFE_INTEGER;
async function load13(config3) {
  var _a;
  if (env.initial) model15 = null;
  if (!model15) model15 = await loadModel((_a = config3.face["mobilefacenet"]) == null ? void 0 : _a.modelPath);
  else if (config3.debug) log("cached model:", model15["modelUrl"]);
  return model15;
}
async function predict12(input, config3, idx, count2) {
  var _a, _b;
  if (!(model15 == null ? void 0 : model15["executor"])) return [];
  const skipFrame = skipped11 < (((_a = config3.face["mobilefacenet"]) == null ? void 0 : _a.skipFrames) || 0);
  const skipTime = (((_b = config3.face["mobilefacenet"]) == null ? void 0 : _b.skipTime) || 0) > now() - lastTime11;
  if (config3.skipAllowed && skipTime && skipFrame && lastCount8 === count2 && last8[idx]) {
    skipped11++;
    return last8[idx];
  }
  return new Promise(async (resolve) => {
    var _a2;
    let data = [];
    if (((_a2 = config3.face["mobilefacenet"]) == null ? void 0 : _a2.enabled) && (model15 == null ? void 0 : model15.inputs[0].shape)) {
      const t10 = {};
      t10.crop = eX.resizeBilinear(input, [model15.inputs[0].shape[2], model15.inputs[0].shape[1]], false);
      t10.data = model15.execute(t10.crop);
      const output = await t10.data.data();
      data = Array.from(output);
      Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
    }
    last8[idx] = data;
    lastCount8 = count2;
    lastTime11 = now();
    resolve(data);
  });
}

// src/face/insightface.ts
var model16;
var last9 = [];
var lastCount9 = 0;
var lastTime12 = 0;
var skipped12 = Number.MAX_SAFE_INTEGER;
async function load14(config3) {
  if (env.initial) model16 = null;
  if (!model16) model16 = await loadModel(config3.face["insightface"].modelPath);
  else if (config3.debug) log("cached model:", model16["modelUrl"]);
  return model16;
}
async function predict13(input, config3, idx, count2) {
  var _a, _b;
  if (!(model16 == null ? void 0 : model16["executor"])) return [];
  const skipFrame = skipped12 < (((_a = config3.face["insightface"]) == null ? void 0 : _a.skipFrames) || 0);
  const skipTime = (((_b = config3.face["insightface"]) == null ? void 0 : _b.skipTime) || 0) > now() - lastTime12;
  if (config3.skipAllowed && skipTime && skipFrame && lastCount9 === count2 && last9[idx]) {
    skipped12++;
    return last9[idx];
  }
  return new Promise(async (resolve) => {
    var _a2;
    let data = [];
    if (((_a2 = config3.face["insightface"]) == null ? void 0 : _a2.enabled) && (model16 == null ? void 0 : model16.inputs[0].shape)) {
      const t10 = {};
      t10.crop = eX.resizeBilinear(input, [model16.inputs[0].shape[2], model16.inputs[0].shape[1]], false);
      t10.data = model16.execute(t10.crop);
      const output = await t10.data.data();
      data = Array.from(output);
      Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
    }
    last9[idx] = data;
    lastCount9 = count2;
    lastTime12 = now();
    resolve(data);
  });
}

// src/face/angles.ts
var calculateGaze = (face4) => {
  const radians = (pt1, pt2) => Math.atan2(pt1[1] - pt2[1], pt1[0] - pt2[0]);
  if (!face4.annotations.rightEyeIris || !face4.annotations.leftEyeIris) return { bearing: 0, strength: 0 };
  const offsetIris = [0, -0.1];
  const eyeRatio = 1;
  const left = (face4.mesh[33][2] || 0) > (face4.mesh[263][2] || 0);
  const irisCenter = left ? face4.mesh[473] : face4.mesh[468];
  const eyeCenter = left ? [(face4.mesh[133][0] + face4.mesh[33][0]) / 2, (face4.mesh[133][1] + face4.mesh[33][1]) / 2] : [(face4.mesh[263][0] + face4.mesh[362][0]) / 2, (face4.mesh[263][1] + face4.mesh[362][1]) / 2];
  const eyeSize = left ? [face4.mesh[133][0] - face4.mesh[33][0], face4.mesh[23][1] - face4.mesh[27][1]] : [face4.mesh[263][0] - face4.mesh[362][0], face4.mesh[253][1] - face4.mesh[257][1]];
  const eyeDiff = [
    // x distance between extreme point and center point normalized with eye size
    (eyeCenter[0] - irisCenter[0]) / eyeSize[0] - offsetIris[0],
    eyeRatio * (irisCenter[1] - eyeCenter[1]) / eyeSize[1] - offsetIris[1]
  ];
  let strength = Math.sqrt(eyeDiff[0] * eyeDiff[0] + eyeDiff[1] * eyeDiff[1]);
  strength = Math.min(strength, face4.boxRaw[2] / 2, face4.boxRaw[3] / 2);
  const bearing = (radians([0, 0], eyeDiff) + Math.PI / 2) % Math.PI;
  return { bearing, strength };
};
var calculateFaceAngle = (face4, imageSize) => {
  const normalize2 = (v8) => {
    const length = Math.sqrt(v8[0] * v8[0] + v8[1] * v8[1] + v8[2] * v8[2]);
    v8[0] /= length;
    v8[1] /= length;
    v8[2] /= length;
    return v8;
  };
  const subVectors = (a, b) => {
    const x = a[0] - b[0];
    const y8 = a[1] - b[1];
    const z = a[2] - b[2];
    return [x, y8, z];
  };
  const crossVectors = (a, b) => {
    const x = a[1] * b[2] - a[2] * b[1];
    const y8 = a[2] * b[0] - a[0] * b[2];
    const z = a[0] * b[1] - a[1] * b[0];
    return [x, y8, z];
  };
  const rotationMatrixToEulerAngle = (r15) => {
    const [r00, _r01, _r02, r102, r112, r122, r20, r21, r222] = r15;
    let thetaX;
    let thetaY;
    let thetaZ;
    if (r102 < 1) {
      if (r102 > -1) {
        const cosThetaZ = Math.sqrt(r00 * r00 + r20 * r20);
        thetaZ = Math.atan2(r102, cosThetaZ);
        thetaY = Math.atan2(-r20, r00);
        thetaX = Math.atan2(-r122, r112);
      } else {
        thetaZ = -Math.PI / 2;
        thetaY = -Math.atan2(r21, r222);
        thetaX = 0;
      }
    } else {
      thetaZ = Math.PI / 2;
      thetaY = Math.atan2(r21, r222);
      thetaX = 0;
    }
    if (Number.isNaN(thetaX)) thetaX = 0;
    if (Number.isNaN(thetaY)) thetaY = 0;
    if (Number.isNaN(thetaZ)) thetaZ = 0;
    return { pitch: -thetaX, yaw: -thetaY, roll: -thetaZ };
  };
  const mesh = face4.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(face4.boxRaw[2] * imageSize[0], face4.boxRaw[3] * imageSize[1]) / 1.5;
  const pts = [mesh[10], mesh[152], mesh[234], mesh[454]].map((pt2) => [pt2[0] * imageSize[0] / size2, pt2[1] * imageSize[1] / size2, pt2[2]]);
  const yAxis = normalize2(subVectors(pts[1], pts[0]));
  let xAxis = normalize2(subVectors(pts[3], pts[2]));
  const zAxis = normalize2(crossVectors(xAxis, yAxis));
  xAxis = crossVectors(yAxis, zAxis);
  const matrix = [
    xAxis[0],
    xAxis[1],
    xAxis[2],
    yAxis[0],
    yAxis[1],
    yAxis[2],
    zAxis[0],
    zAxis[1],
    zAxis[2]
  ];
  const angle = rotationMatrixToEulerAngle(matrix);
  const gaze = mesh.length === 478 ? calculateGaze(face4) : { bearing: 0, strength: 0 };
  return { angle, matrix, gaze };
};

// src/face/anthropometry.ts
function calculateCameraDistance(face4, width) {
  const f = face4 == null ? void 0 : face4.annotations;
  if (!(f == null ? void 0 : f.leftEyeIris) || !(f == null ? void 0 : f.rightEyeIris)) return 0;
  const irisSize = Math.max(Math.abs(f.leftEyeIris[3][0] - f.leftEyeIris[1][0]), Math.abs(f.rightEyeIris[3][0] - f.rightEyeIris[1][0])) / width;
  const cameraDistance = Math.round(1.17 / irisSize) / 100;
  return cameraDistance;
}

// src/face/face.ts
var detectFace = async (instance, input) => {
  var _a, _b, _c2, _d2, _e, _f2, _g2, _h2, _i2, _j2, _k2, _l2, _m, _n2, _o2, _p2, _q2, _r2, _s2, _t, _u2, _v2, _w2;
  let timeStamp = now();
  let ageRes;
  let gearRes;
  let genderRes;
  let emotionRes;
  let mobilefacenetRes;
  let insightfaceRes;
  let antispoofRes;
  let livenessRes;
  let descRes;
  const faceRes = [];
  instance.state = "run:face";
  const faces = await predict4(input, instance.config);
  instance.performance.face = env.perfadd ? (instance.performance.face || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
  if (!input.shape || input.shape.length !== 4) return [];
  if (!faces) return [];
  for (let i = 0; i < faces.length; i++) {
    instance.analyze("Get Face");
    if (!faces[i].tensor || faces[i].tensor.isDisposedInternal) {
      log("Face object is disposed:", faces[i].tensor);
      continue;
    }
    if ((_a = instance.config.face.detector) == null ? void 0 : _a.mask) {
      const masked = await mask(faces[i]);
      Ot(faces[i].tensor);
      if (masked) faces[i].tensor = masked;
    }
    const rotation = faces[i].mesh && faces[i].mesh.length > 200 ? calculateFaceAngle(faces[i], [input.shape[2], input.shape[1]]) : null;
    instance.analyze("Start Emotion:");
    if (instance.config.async) {
      emotionRes = ((_b = instance.config.face.emotion) == null ? void 0 : _b.enabled) ? predict5(faces[i].tensor || ar([]), instance.config, i, faces.length) : [];
    } else {
      instance.state = "run:emotion";
      timeStamp = now();
      emotionRes = ((_c2 = instance.config.face.emotion) == null ? void 0 : _c2.enabled) ? await predict5(faces[i].tensor || ar([]), instance.config, i, faces.length) : [];
      instance.performance.emotion = env.perfadd ? (instance.performance.emotion || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
    }
    instance.analyze("End Emotion:");
    instance.analyze("Start AntiSpoof:");
    if (instance.config.async) {
      antispoofRes = ((_d2 = instance.config.face.antispoof) == null ? void 0 : _d2.enabled) ? predict7(faces[i].tensor || ar([]), instance.config, i, faces.length) : 0;
    } else {
      instance.state = "run:antispoof";
      timeStamp = now();
      antispoofRes = ((_e = instance.config.face.antispoof) == null ? void 0 : _e.enabled) ? await predict7(faces[i].tensor || ar([]), instance.config, i, faces.length) : 0;
      instance.performance.antispoof = env.perfadd ? (instance.performance.antispoof || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
    }
    instance.analyze("End AntiSpoof:");
    instance.analyze("Start Liveness:");
    if (instance.config.async) {
      livenessRes = ((_f2 = instance.config.face.liveness) == null ? void 0 : _f2.enabled) ? predict8(faces[i].tensor || ar([]), instance.config, i, faces.length) : 0;
    } else {
      instance.state = "run:liveness";
      timeStamp = now();
      livenessRes = ((_g2 = instance.config.face.liveness) == null ? void 0 : _g2.enabled) ? await predict8(faces[i].tensor || ar([]), instance.config, i, faces.length) : 0;
      instance.performance.liveness = env.perfadd ? (instance.performance.antispoof || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
    }
    instance.analyze("End Liveness:");
    instance.analyze("Start GEAR:");
    if (instance.config.async) {
      gearRes = ((_h2 = instance.config.face.gear) == null ? void 0 : _h2.enabled) ? predict9(faces[i].tensor || ar([]), instance.config, i, faces.length) : null;
    } else {
      instance.state = "run:gear";
      timeStamp = now();
      gearRes = ((_i2 = instance.config.face.gear) == null ? void 0 : _i2.enabled) ? await predict9(faces[i].tensor || ar([]), instance.config, i, faces.length) : null;
      instance.performance.gear = Math.trunc(now() - timeStamp);
    }
    instance.analyze("End GEAR:");
    instance.analyze("Start SSRNet:");
    if (instance.config.async) {
      ageRes = ((_j2 = instance.config.face["ssrnet"]) == null ? void 0 : _j2.enabled) ? predict10(faces[i].tensor || ar([]), instance.config, i, faces.length) : null;
      genderRes = ((_k2 = instance.config.face["ssrnet"]) == null ? void 0 : _k2.enabled) ? predict11(faces[i].tensor || ar([]), instance.config, i, faces.length) : null;
    } else {
      instance.state = "run:ssrnet";
      timeStamp = now();
      ageRes = ((_l2 = instance.config.face["ssrnet"]) == null ? void 0 : _l2.enabled) ? await predict10(faces[i].tensor || ar([]), instance.config, i, faces.length) : null;
      genderRes = ((_m = instance.config.face["ssrnet"]) == null ? void 0 : _m.enabled) ? await predict11(faces[i].tensor || ar([]), instance.config, i, faces.length) : null;
      instance.performance.ssrnet = Math.trunc(now() - timeStamp);
    }
    instance.analyze("End SSRNet:");
    instance.analyze("Start MobileFaceNet:");
    if (instance.config.async) {
      mobilefacenetRes = ((_n2 = instance.config.face["mobilefacenet"]) == null ? void 0 : _n2.enabled) ? predict12(faces[i].tensor || ar([]), instance.config, i, faces.length) : null;
    } else {
      instance.state = "run:mobilefacenet";
      timeStamp = now();
      mobilefacenetRes = ((_o2 = instance.config.face["mobilefacenet"]) == null ? void 0 : _o2.enabled) ? await predict12(faces[i].tensor || ar([]), instance.config, i, faces.length) : null;
      instance.performance.mobilefacenet = Math.trunc(now() - timeStamp);
    }
    instance.analyze("End MobileFaceNet:");
    instance.analyze("Start InsightFace:");
    if (instance.config.async) {
      insightfaceRes = ((_p2 = instance.config.face["insightface"]) == null ? void 0 : _p2.enabled) ? predict13(faces[i].tensor || ar([]), instance.config, i, faces.length) : null;
    } else {
      instance.state = "run:mobilefacenet";
      timeStamp = now();
      insightfaceRes = ((_q2 = instance.config.face["insightface"]) == null ? void 0 : _q2.enabled) ? await predict13(faces[i].tensor || ar([]), instance.config, i, faces.length) : null;
      instance.performance.mobilefacenet = Math.trunc(now() - timeStamp);
    }
    instance.analyze("End InsightFace:");
    instance.analyze("Start Description:");
    if (instance.config.async) {
      descRes = predict6(faces[i].tensor || ar([]), instance.config, i, faces.length);
    } else {
      instance.state = "run:description";
      timeStamp = now();
      descRes = await predict6(faces[i].tensor || ar([]), instance.config, i, faces.length);
      instance.performance.description = env.perfadd ? (instance.performance.description || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
    }
    instance.analyze("End Description:");
    if (instance.config.async) {
      [ageRes, genderRes, emotionRes, mobilefacenetRes, insightfaceRes, descRes, gearRes, antispoofRes, livenessRes] = await Promise.all([ageRes, genderRes, emotionRes, mobilefacenetRes, insightfaceRes, descRes, gearRes, antispoofRes, livenessRes]);
    }
    instance.analyze("Finish Face:");
    if (((_r2 = instance.config.face["ssrnet"]) == null ? void 0 : _r2.enabled) && ageRes && genderRes) {
      descRes = {
        ...descRes,
        age: ageRes.age,
        gender: genderRes.gender,
        genderScore: genderRes.genderScore
      };
    }
    if (((_s2 = instance.config.face.gear) == null ? void 0 : _s2.enabled) && gearRes) {
      descRes = {
        ...descRes,
        age: gearRes.age,
        gender: gearRes.gender,
        genderScore: gearRes.genderScore,
        race: gearRes.race
      };
    }
    if (((_t = instance.config.face["mobilefacenet"]) == null ? void 0 : _t.enabled) && mobilefacenetRes) {
      descRes.descriptor = mobilefacenetRes;
    }
    if (((_u2 = instance.config.face["insightface"]) == null ? void 0 : _u2.enabled) && insightfaceRes) {
      descRes.descriptor = insightfaceRes;
    }
    const irisSize = ((_v2 = instance.config.face.iris) == null ? void 0 : _v2.enabled) ? calculateCameraDistance(faces[i], input.shape[2]) : 0;
    const tensor2 = ((_w2 = instance.config.face.detector) == null ? void 0 : _w2.return) ? cc(faces[i].tensor) : null;
    Ot(faces[i].tensor);
    if (faces[i].tensor) delete faces[i].tensor;
    const res = {
      ...faces[i],
      id: i
    };
    if (descRes.age) res.age = descRes.age;
    if (descRes.gender) res.gender = descRes.gender;
    if (descRes.genderScore) res.genderScore = descRes.genderScore;
    if (descRes.descriptor) res.embedding = descRes.descriptor;
    if (descRes.race) res.race = descRes.race;
    if (emotionRes) res.emotion = emotionRes;
    if (antispoofRes) res.real = antispoofRes;
    if (livenessRes) res.live = livenessRes;
    if (irisSize > 0) res.distance = irisSize;
    if (rotation) res.rotation = rotation;
    if (tensor2) res.tensor = tensor2;
    faceRes.push(res);
    instance.analyze("End Face");
  }
  instance.analyze("End FaceMesh:");
  if (instance.config.async) {
    if (instance.performance.face) delete instance.performance.face;
    if (instance.performance.age) delete instance.performance.age;
    if (instance.performance.gender) delete instance.performance.gender;
    if (instance.performance.emotion) delete instance.performance.emotion;
  }
  return faceRes;
};

// src/hand/fingerdef.ts
var Finger = {
  thumb: 0,
  index: 1,
  middle: 2,
  ring: 3,
  pinky: 4,
  all: [0, 1, 2, 3, 4],
  // just for convenience
  nameMapping: { 0: "thumb", 1: "index", 2: "middle", 3: "ring", 4: "pinky" },
  // Describes mapping of joints based on the 21 points returned by handpose.
  // [0]     Palm
  // [1-4]   Thumb
  // [5-8]   Index
  // [9-12]  Middle
  // [13-16] Ring
  // [17-20] 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];
  }
  curl(finger, curl, confidence) {
    if (typeof this.curls[finger] === "undefined") this.curls[finger] = [];
    this.curls[finger].push([curl, confidence]);
  }
  direction(finger, position, confidence) {
    if (!this.directions[finger]) this.directions[finger] = [];
    this.directions[finger].push([position, confidence]);
  }
  weight(finger, weight) {
    this.weights[finger] = weight;
    const total = this.weights.reduce((a, b) => a + b, 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 { thumb, index, middle, ring, pinky } = Finger;
var { none, half, full } = FingerCurl;
var { verticalUp, verticalDown, horizontalLeft, horizontalRight, diagonalUpRight, diagonalUpLeft, diagonalDownRight, diagonalDownLeft } = FingerDirection;
var ThumbsUp = new FingerGesture("thumbs up");
ThumbsUp.curl(thumb, none, 1);
ThumbsUp.direction(thumb, verticalUp, 1);
ThumbsUp.direction(thumb, diagonalUpLeft, 0.25);
ThumbsUp.direction(thumb, diagonalUpRight, 0.25);
for (const finger of [Finger.index, Finger.middle, Finger.ring, Finger.pinky]) {
  ThumbsUp.curl(finger, full, 1);
  ThumbsUp.direction(finger, horizontalLeft, 1);
  ThumbsUp.direction(finger, horizontalRight, 1);
}
var Victory = new FingerGesture("victory");
Victory.curl(thumb, half, 0.5);
Victory.curl(thumb, none, 0.5);
Victory.direction(thumb, verticalUp, 1);
Victory.direction(thumb, diagonalUpLeft, 1);
Victory.curl(index, none, 1);
Victory.direction(index, verticalUp, 0.75);
Victory.direction(index, diagonalUpLeft, 1);
Victory.curl(middle, none, 1);
Victory.direction(middle, verticalUp, 1);
Victory.direction(middle, diagonalUpLeft, 0.75);
Victory.curl(ring, full, 1);
Victory.direction(ring, verticalUp, 0.2);
Victory.direction(ring, diagonalUpLeft, 1);
Victory.direction(ring, horizontalLeft, 0.2);
Victory.curl(pinky, full, 1);
Victory.direction(pinky, verticalUp, 0.2);
Victory.direction(pinky, diagonalUpLeft, 1);
Victory.direction(pinky, horizontalLeft, 0.2);
Victory.weight(index, 2);
Victory.weight(middle, 2);
var Point = new FingerGesture("point");
Point.curl(thumb, full, 1);
Point.curl(index, none, 0.5);
Point.curl(middle, full, 0.5);
Point.curl(ring, full, 0.5);
Point.curl(pinky, full, 0.5);
Point.weight(index, 2);
Point.weight(middle, 2);
var MiddleFinger = new FingerGesture("middle finger");
MiddleFinger.curl(thumb, none, 1);
MiddleFinger.curl(index, full, 0.5);
MiddleFinger.curl(middle, full, 0.5);
MiddleFinger.curl(ring, full, 0.5);
MiddleFinger.curl(pinky, full, 0.5);
MiddleFinger.weight(index, 2);
MiddleFinger.weight(middle, 2);
var OpenPalm = new FingerGesture("open palm");
OpenPalm.curl(thumb, none, 0.75);
OpenPalm.curl(index, none, 0.75);
OpenPalm.curl(middle, none, 0.75);
OpenPalm.curl(ring, none, 0.75);
OpenPalm.curl(pinky, none, 0.75);
var fingergesture_default = [ThumbsUp, Victory, Point, MiddleFinger, OpenPalm];

// src/hand/fingerpose.ts
var minConfidence = 0.7;
var options3 = {
  // curl estimation
  HALF_CURL_START_LIMIT: 60,
  NO_CURL_START_LIMIT: 130,
  // direction estimation
  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 > options3.NO_CURL_START_LIMIT) fingerCurl = FingerCurl.none;
  else if (angleOfCurve > options3.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 += options3.DISTANCE_VOTE_POWER;
  else if (start_end_x_y_dist_ratio > 0.66) voteDiagonal += options3.DISTANCE_VOTE_POWER;
  else voteHorizontal += options3.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, options3.TOTAL_ANGLE_VOTE_POWER);
  voteVertical += votes[0];
  voteDiagonal += votes[1];
  voteHorizontal += votes[2];
  for (const fingerSlope of fingerSlopes) {
    const fingerVotes = angleOrientationAt(fingerSlope, options3.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 gesture2 of fingergesture_default) {
    const confidence = gesture2.matchAgainst(estimatorRes.curls, estimatorRes.directions);
    if (confidence >= minConfidence) poses.push({ name: gesture2.name, confidence });
  }
  return poses;
}

// 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 && Math.abs(leftShoulder.positionRaw[1] - rightShoulder.positionRaw[1]) > 0.1) {
      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 zDiff = (res[i].mesh[33][2] || 0) - (res[i].mesh[263][2] || 0);
      const xDiff = res[i].mesh[33][0] - res[i].mesh[263][0];
      if (Math.abs(zDiff / xDiff) <= 0.15) gestures.push({ face: i, gesture: "facing center" });
      else gestures.push({ face: i, gesture: `facing ${zDiff < 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] || 0;
      if (Math.abs(chinDepth) > 10) gestures.push({ face: i, gesture: `head ${chinDepth < 0 ? "up" : "down"}` });
    }
  }
  return gestures;
};
var iris2 = (res) => {
  var _a, _b, _c2, _d2;
  if (!res) return [];
  const gestures = [];
  for (let i = 0; i < res.length; i++) {
    if (!((_b = (_a = res[i].annotations) == null ? void 0 : _a.leftEyeIris) == null ? void 0 : _b[0]) || !((_d2 = (_c2 = res[i].annotations) == null ? void 0 : _c2.rightEyeIris) == null ? void 0 : _d2[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 leftIrisCenterX = Math.abs(res[i].mesh[263][0] - res[i].annotations.leftEyeIris[0][0]) / res[i].box[2];
    const rightIrisCenterX = Math.abs(res[i].mesh[33][0] - res[i].annotations.rightEyeIris[0][0]) / res[i].box[2];
    if (leftIrisCenterX > 0.06 || rightIrisCenterX > 0.06) center = false;
    if (leftIrisCenterX > rightIrisCenterX) {
      if (rightIrisCenterX > 0.04) gestures.push({ iris: i, gesture: "looking right" });
    } else {
      if (leftIrisCenterX > 0.04) 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] || 0) < (a.position[2] || 0) ? 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/hand/handposeutil.ts
function getBoxSize2(box) {
  return [
    Math.abs(box.endPoint[0] - box.startPoint[0]),
    Math.abs(box.endPoint[1] - box.startPoint[1])
  ];
}
function getBoxCenter2(box) {
  return [
    box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2,
    box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2
  ];
}
function cutBoxFromImageAndResize(box, image, cropSize) {
  const h = image.shape[1];
  const w8 = image.shape[2];
  const boxes = [[
    box.startPoint[1] / h,
    box.startPoint[0] / w8,
    box.endPoint[1] / h,
    box.endPoint[0] / w8
  ]];
  return eX.cropAndResize(image, boxes, [0], cropSize);
}
function scaleBoxCoordinates2(box, factor) {
  const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];
  const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];
  const palmLandmarks = box.palmLandmarks.map((coord) => {
    const scaledCoord = [coord[0] * factor[0], coord[1] * factor[1]];
    return scaledCoord;
  });
  return { startPoint, endPoint, palmLandmarks, confidence: box.confidence };
}
function enlargeBox2(box, factor = 1.5) {
  const center = getBoxCenter2(box);
  const size2 = getBoxSize2(box);
  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: box.palmLandmarks };
}
function squarifyBox2(box) {
  const centers = getBoxCenter2(box);
  const size2 = getBoxSize2(box);
  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: box.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, y8) => [[1, 0, x], [0, 1, y8], [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(model23) {
    __publicField(this, "model");
    __publicField(this, "anchors");
    __publicField(this, "anchorsTensor");
    __publicField(this, "inputSize");
    __publicField(this, "inputSizeTensor");
    __publicField(this, "doubleInputSizeTensor");
    var _a, _b, _c2, _d2;
    this.model = model23;
    this.anchors = anchors2.map((anchor) => [anchor.x, anchor.y]);
    this.anchorsTensor = mu(this.anchors);
    this.inputSize = ((_d2 = (_c2 = (_b = (_a = this == null ? void 0 : this.model) == null ? void 0 : _a.inputs) == null ? void 0 : _b[0]) == null ? void 0 : _c2.shape) == null ? void 0 : _d2[2]) || 0;
    this.inputSizeTensor = Jt([this.inputSize, this.inputSize]);
    this.doubleInputSizeTensor = Jt([this.inputSize * 2, this.inputSize * 2]);
  }
  normalizeBoxes(boxes) {
    const t10 = {};
    t10.boxOffsets = Xe(boxes, [0, 0], [-1, 2]);
    t10.boxSizes = Xe(boxes, [0, 2], [-1, 2]);
    t10.div = je(t10.boxOffsets, this.inputSizeTensor);
    t10.boxCenterPoints = Ce(t10.div, this.anchorsTensor);
    t10.halfBoxSizes = je(t10.boxSizes, this.doubleInputSizeTensor);
    t10.sub = Te(t10.boxCenterPoints, t10.halfBoxSizes);
    t10.startPoints = se(t10.sub, this.inputSizeTensor);
    t10.add = Ce(t10.boxCenterPoints, t10.halfBoxSizes);
    t10.endPoints = se(t10.add, this.inputSizeTensor);
    const res = r22([t10.startPoints, t10.endPoints], 1);
    Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
    return res;
  }
  normalizeLandmarks(rawPalmLandmarks, index2) {
    const t10 = {};
    t10.reshape = W(rawPalmLandmarks, [-1, 7, 2]);
    t10.div = je(t10.reshape, this.inputSizeTensor);
    t10.landmarks = Ce(t10.div, this.anchors[index2] ? this.anchors[index2] : 0);
    const res = se(t10.landmarks, this.inputSizeTensor);
    Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
    return res;
  }
  async predict(input, config3) {
    var _a;
    const t10 = {};
    t10.resize = eX.resizeBilinear(input, [this.inputSize, this.inputSize]);
    t10.div = je(t10.resize, constants.tf127);
    t10.image = Te(t10.div, constants.tf1);
    t10.batched = this.model.execute(t10.image);
    t10.predictions = cc(t10.batched);
    t10.slice = Xe(t10.predictions, [0, 0], [-1, 1]);
    t10.sigmoid = Ea(t10.slice);
    t10.scores = cc(t10.sigmoid);
    const scores = await t10.scores.data();
    t10.boxes = Xe(t10.predictions, [0, 1], [-1, 4]);
    t10.norm = this.normalizeBoxes(t10.boxes);
    t10.nms = await eX.nonMaxSuppressionAsync(t10.norm, t10.scores, 3 * (((_a = config3.hand) == null ? void 0 : _a.maxDetected) || 1), config3.hand.iouThreshold, config3.hand.minConfidence);
    const nms = await t10.nms.array();
    const hands = [];
    for (const index2 of nms) {
      const p = {};
      p.box = Xe(t10.norm, [index2, 0], [1, -1]);
      p.slice = Xe(t10.predictions, [index2, 5], [1, 14]);
      p.norm = this.normalizeLandmarks(p.slice, index2);
      p.palmLandmarks = W(p.norm, [-1, 2]);
      const box = await p.box.data();
      const startPoint = box.slice(0, 2);
      const endPoint = box.slice(2, 4);
      const palmLandmarks = await p.palmLandmarks.array();
      const hand3 = { startPoint, endPoint, palmLandmarks, confidence: scores[index2] };
      const scaled = scaleBoxCoordinates2(hand3, [(input.shape[2] || 1) / this.inputSize, (input.shape[1] || 0) / this.inputSize]);
      hands.push(scaled);
      Object.keys(p).forEach((tensor2) => Ot(p[tensor2]));
    }
    Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
    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 lastTime13 = 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");
    var _a, _b, _c2;
    this.handDetector = handDetector;
    this.handPoseModel = handPoseModel2;
    this.inputSize = ((_c2 = (_b = (_a = this.handPoseModel) == null ? void 0 : _a.inputs) == null ? void 0 : _b[0].shape) == null ? void 0 : _c2[2]) || 0;
    this.storedBoxes = [];
    this.skipped = Number.MAX_SAFE_INTEGER;
    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, box2, angle, rotationMatrix) {
    const boxSize = getBoxSize2(box2);
    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(box2), 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(image, config3) {
    let useFreshBox = false;
    let boxes;
    const skipTime = (config3.hand.skipTime || 0) > now() - lastTime13;
    const skipFrame = this.skipped < (config3.hand.skipFrames || 0);
    if (config3.skipAllowed && skipTime && skipFrame) {
      this.skipped++;
    } else {
      boxes = await this.handDetector.predict(image, config3);
      this.skipped = 0;
    }
    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] / image.shape[2], palmCenter[1] / image.shape[1]];
        const rotatedImage = config3.hand.rotation && env.kernels.includes("rotatewithoffset") ? eX.rotateWithOffset(image, angle, 0, palmCenterNormalized) : image.clone();
        const rotationMatrix = buildRotationMatrix2(-angle, palmCenter);
        const newBox = useFreshBox ? this.getBoxForPalmLandmarks(currentBox.palmLandmarks, rotationMatrix) : currentBox;
        const croppedInput = cutBoxFromImageAndResize(newBox, rotatedImage, [this.inputSize, this.inputSize]);
        const handImage = je(croppedInput, constants.tf255);
        Ot(croppedInput);
        Ot(rotatedImage);
        const [confidenceT, keypoints] = this.handPoseModel.execute(handImage);
        lastTime13 = now();
        Ot(handImage);
        const confidence = (await confidenceT.data())[0];
        Ot(confidenceT);
        if (confidence >= config3.hand.minConfidence / 4) {
          const keypointsReshaped = W(keypoints, [-1, 3]);
          const rawCoords = await keypointsReshaped.array();
          Ot(keypoints);
          Ot(keypointsReshaped);
          const coords = this.transformRawCoords(rawCoords, newBox, angle, rotationMatrix);
          const nextBoundingBox = this.getBoxForHandLandmarks(coords);
          this.storedBoxes[i] = { ...nextBoundingBox, confidence };
          const result = {
            landmarks: coords,
            confidence,
            boxConfidence: currentBox.confidence,
            fingerConfidence: confidence,
            box: { topLeft: nextBoundingBox.startPoint, bottomRight: nextBoundingBox.endPoint }
          };
          hands.push(result);
        } else {
          this.storedBoxes[i] = null;
        }
        Ot(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/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;
function initPipeline() {
  const handDetector = handDetectorModel ? new HandDetector(handDetectorModel) : void 0;
  if (handDetector && handPoseModel) handPipeline = new HandPipeline(handDetector, handPoseModel);
}
async function predict14(input, config3) {
  if (!handPipeline) initPipeline();
  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((index2) => predictions[i].landmarks[index2]);
      }
    }
    const keypoints = predictions[i].landmarks;
    let box = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, 0, 0];
    let boxRaw = [0, 0, 0, 0];
    if (keypoints && keypoints.length > 0) {
      for (const pt2 of keypoints) {
        if (pt2[0] < box[0]) box[0] = pt2[0];
        if (pt2[1] < box[1]) box[1] = pt2[1];
        if (pt2[0] > box[2]) box[2] = pt2[0];
        if (pt2[1] > box[3]) box[3] = pt2[1];
      }
      box[2] -= box[0];
      box[3] -= box[1];
      boxRaw = [box[0] / (input.shape[2] || 0), box[1] / (input.shape[1] || 0), box[2] / (input.shape[2] || 0), box[3] / (input.shape[1] || 0)];
    } else {
      box = 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,
      boxRaw,
      keypoints,
      annotations: annotations2,
      landmarks
    });
  }
  return hands;
}
async function loadDetect2(config3) {
  var _a;
  if (env.initial) handDetectorModel = null;
  if (!handDetectorModel) handDetectorModel = await loadModel((_a = config3.hand.detector) == null ? void 0 : _a.modelPath);
  else if (config3.debug) log("cached model:", handDetectorModel["modelUrl"]);
  return handDetectorModel;
}
async function loadSkeleton(config3) {
  var _a;
  if (env.initial) handPoseModel = null;
  if (!handPoseModel) handPoseModel = await loadModel((_a = config3.hand.skeleton) == null ? void 0 : _a.modelPath);
  else if (config3.debug) log("cached model:", handPoseModel["modelUrl"]);
  return handPoseModel;
}

// src/hand/handtrack.ts
var models2 = [null, null];
var modelOutputNodes = ["StatefulPartitionedCall/Postprocessor/Slice", "StatefulPartitionedCall/Postprocessor/ExpandDims_1"];
var inputSize7 = [[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 skipped13 = Number.MAX_SAFE_INTEGER;
var lastTime14 = 0;
var outputSize = [0, 0];
var cache4 = {
  boxes: [],
  hands: []
};
var fingerMap = {
  /*
  thumb: [0, 1, 2, 3, 4],
  index: [0, 5, 6, 7, 8],
  middle: [0, 9, 10, 11, 12],
  ring: [0, 13, 14, 15, 16],
  pinky: [0, 17, 18, 19, 20],
  palm: [0],
  */
  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],
  base: [0],
  palm: [0, 17, 13, 9, 5, 1, 0]
};
async function loadDetect3(config3) {
  var _a;
  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 loadModel((_a = config3.hand.detector) == null ? void 0 : _a.modelPath);
    const inputs = models2[0]["executor"] ? Object.values(models2[0].modelSignature["inputs"]) : void 0;
    inputSize7[0][0] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[1].size) : 0;
    inputSize7[0][1] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
  } else if (config3.debug) log("cached model:", models2[0]["modelUrl"]);
  return models2[0];
}
async function loadSkeleton2(config3) {
  var _a;
  if (env.initial) models2[1] = null;
  if (!models2[1]) {
    models2[1] = await loadModel((_a = config3.hand.skeleton) == null ? void 0 : _a.modelPath);
    const inputs = models2[1]["executor"] ? Object.values(models2[1].modelSignature["inputs"]) : void 0;
    inputSize7[1][0] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[1].size) : 0;
    inputSize7[1][1] = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 0;
  } 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 t10 = {};
  const ratio2 = (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 * ratio2 / 8) * 8;
  t10.resize = eX.resizeBilinear(input, [height, width]);
  t10.cast = Ue(t10.resize, "int32");
  [t10.rawScores, t10.rawBoxes] = await models2[0].executeAsync(t10.cast, modelOutputNodes);
  t10.boxes = cc(t10.rawBoxes, [0, 2]);
  t10.scores = cc(t10.rawScores, [0]);
  const classScores = fo(t10.scores, 1);
  Ot(classScores[faceIndex]);
  classScores.splice(faceIndex, 1);
  t10.filtered = vr(classScores, 1);
  Ot(classScores);
  t10.max = Ra(t10.filtered, 1);
  t10.argmax = Ok(t10.filtered, 1);
  let id2 = 0;
  t10.nms = await eX.nonMaxSuppressionAsync(t10.boxes, t10.max, (config3.hand.maxDetected || 0) + 1, config3.hand.iouThreshold || 0, config3.hand.minConfidence || 1);
  const nms = await t10.nms.data();
  const scores = await t10.max.data();
  const classNum = await t10.argmax.data();
  for (const nmsIndex of Array.from(nms)) {
    const boxSlice = Xe(t10.boxes, nmsIndex, 1);
    const boxYX = await boxSlice.data();
    Ot(boxSlice);
    const boxData = [boxYX[1], boxYX[0], boxYX[3] - boxYX[1], boxYX[2] - boxYX[0]];
    const boxRaw = scale(boxData, detectorExpandFact);
    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, label };
    hands.push(hand3);
  }
  Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
  hands.sort((a, b) => b.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 = {
    // initial values inherited from hand detect
    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 t10 = {};
    const boxCrop = [h.boxRaw[1], h.boxRaw[0], h.boxRaw[3] + h.boxRaw[1], h.boxRaw[2] + h.boxRaw[0]];
    t10.crop = eX.cropAndResize(input, [boxCrop], [0], [inputSize7[1][0], inputSize7[1][1]], "bilinear");
    t10.div = je(t10.crop, constants.tf255);
    [t10.score, t10.keypoints] = models2[1].execute(t10.div, ["Identity_1", "Identity"]);
    const rawScore = (await t10.score.data())[0];
    const score = (100 - Math.trunc(100 / (1 + Math.exp(rawScore)))) / 100;
    if (score >= (config3.hand.minConfidence || 0)) {
      hand3.fingerScore = score;
      t10.reshaped = W(t10.keypoints, [-1, 3]);
      const coordsData = await t10.reshaped.array();
      const coordsRaw = coordsData.map((kpt4) => [kpt4[0] / inputSize7[1][1], kpt4[1] / inputSize7[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((index2) => hand3.landmarks && hand3.keypoints[index2] ? hand3.keypoints[index2] : null);
      }
    }
    Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
  }
  return hand3;
}
async function predict15(input, config3) {
  var _a, _b;
  if (!((_a = models2[0]) == null ? void 0 : _a["executor"]) || !((_b = models2[1]) == null ? void 0 : _b["executor"]) || !models2[0].inputs[0].shape || !models2[1].inputs[0].shape) return [];
  outputSize = [input.shape[2] || 0, input.shape[1] || 0];
  skipped13++;
  const skipTime = (config3.hand.skipTime || 0) > now() - lastTime14;
  const skipFrame = skipped13 < (config3.hand.skipFrames || 0);
  if (config3.skipAllowed && skipTime && skipFrame) {
    return cache4.hands;
  }
  return new Promise(async (resolve) => {
    const skipTimeExtended = 3 * (config3.hand.skipTime || 0) > now() - lastTime14;
    const skipFrameExtended = skipped13 < 3 * (config3.hand.skipFrames || 0);
    if (config3.skipAllowed && cache4.hands.length === config3.hand.maxDetected) {
      cache4.hands = await Promise.all(cache4.boxes.map((handBox) => detectFingers(input, handBox, config3)));
    } else if (config3.skipAllowed && skipTimeExtended && skipFrameExtended && cache4.hands.length > 0) {
      cache4.hands = await Promise.all(cache4.boxes.map((handBox) => detectFingers(input, handBox, config3)));
    } else {
      cache4.boxes = await detectHands(input, config3);
      lastTime14 = now();
      cache4.hands = await Promise.all(cache4.boxes.map((handBox) => detectFingers(input, handBox, config3)));
      skipped13 = 0;
    }
    const oldCache = [...cache4.boxes];
    cache4.boxes.length = 0;
    if (config3.cacheSensitivity > 0) {
      for (let i = 0; i < cache4.hands.length; i++) {
        const boxKpt = square(cache4.hands[i].keypoints, outputSize);
        if (boxKpt.box[2] / (input.shape[2] || 1) > 0.05 && boxKpt.box[3] / (input.shape[1] || 1) > 0.05 && cache4.hands[i].fingerScore && cache4.hands[i].fingerScore > (config3.hand.minConfidence || 0)) {
          const boxScale = scale(boxKpt.box, boxExpandFact);
          const boxScaleRaw = scale(boxKpt.boxRaw, boxExpandFact);
          cache4.boxes.push({ ...oldCache[i], box: boxScale, boxRaw: boxScaleRaw });
        }
      }
    }
    for (let i = 0; i < cache4.hands.length; i++) {
      const bbox = calc(cache4.hands[i].keypoints, outputSize);
      cache4.hands[i].box = bbox.box;
      cache4.hands[i].boxRaw = bbox.boxRaw;
    }
    resolve(cache4.hands);
  });
}

// src/result.ts
var empty = (error = null) => ({ face: [], body: [], hand: [], gesture: [], object: [], persons: [], performance: {}, timestamp: 0, width: 0, height: 0, error });

// src/body/movenetcoords.ts
var movenetcoords_exports = {};
__export(movenetcoords_exports, {
  connected: () => connected3,
  horizontal: () => horizontal,
  kpt: () => kpt3,
  relative: () => relative,
  vertical: () => vertical
});
var kpt3 = [
  // used to create part labels
  "nose",
  "leftEye",
  "rightEye",
  "leftEar",
  "rightEar",
  "leftShoulder",
  "rightShoulder",
  "leftElbow",
  "rightElbow",
  "leftWrist",
  "rightWrist",
  "leftHip",
  "rightHip",
  "leftKnee",
  "rightKnee",
  "leftAnkle",
  "rightAnkle"
];
var horizontal = [
  // used to fix left vs right
  ["leftEye", "rightEye"],
  ["leftEar", "rightEar"],
  ["leftShoulder", "rightShoulder"],
  ["leftElbow", "rightElbow"],
  ["leftWrist", "rightWrist"],
  ["leftHip", "rightHip"],
  ["leftKnee", "rightKnee"],
  ["leftAnkle", "rightAnkle"]
];
var vertical = [
  // used to remove unlikely keypoint positions
  ["leftKnee", "leftShoulder"],
  ["rightKnee", "rightShoulder"],
  ["leftAnkle", "leftKnee"],
  ["rightAnkle", "rightKnee"]
];
var relative = [
  // used to match relative body parts
  [["leftHip", "rightHip"], ["leftShoulder", "rightShoulder"]],
  [["leftElbow", "rightElbow"], ["leftShoulder", "rightShoulder"]]
];
var connected3 = {
  // used to create body outline in annotations
  leftLeg: ["leftHip", "leftKnee", "leftAnkle"],
  rightLeg: ["rightHip", "rightKnee", "rightAnkle"],
  torso: ["leftShoulder", "rightShoulder", "rightHip", "leftHip", "leftShoulder"],
  leftArm: ["leftShoulder", "leftElbow", "leftWrist"],
  rightArm: ["rightShoulder", "rightElbow", "rightWrist"],
  head: []
};

// src/util/interpolate.ts
var bufferedResult = empty();
var interpolateTime = 0;
function calc2(newResult, config3) {
  var _a, _b, _c2, _d2, _e, _f2, _g2, _h2, _i2, _j2, _k2, _l2, _m, _n2, _o2, _p2, _q2, _r2, _s2, _t, _u2, _v2, _w2, _x2, _y, _z2;
  const t02 = now();
  if (!newResult) return empty();
  const elapsed = Date.now() - newResult.timestamp;
  const bufferedFactor = elapsed < 1e3 ? 8 - Math.log(elapsed + 1) : 1;
  if (newResult.canvas) bufferedResult.canvas = newResult.canvas;
  if (newResult.error) bufferedResult.error = newResult.error;
  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 box = newResult.body[i].box.map((newBoxCoord, j) => ((bufferedFactor - 1) * bufferedResult.body[i].box[j] + newBoxCoord) / bufferedFactor);
      const boxRaw = newResult.body[i].boxRaw.map((newBoxCoord, j) => ((bufferedFactor - 1) * bufferedResult.body[i].boxRaw[j] + newBoxCoord) / bufferedFactor);
      const keypoints = newResult.body[i].keypoints.map((newKpt, j) => {
        var _a2, _b2, _c3, _d3, _e2, _f3, _g3, _h3, _i3;
        return {
          score: newKpt.score,
          part: newKpt.part,
          position: [
            bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (bufferedResult.body[i].keypoints[j].position[0] || 0) + (newKpt.position[0] || 0)) / bufferedFactor : newKpt.position[0],
            bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (bufferedResult.body[i].keypoints[j].position[1] || 0) + (newKpt.position[1] || 0)) / bufferedFactor : newKpt.position[1],
            bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (bufferedResult.body[i].keypoints[j].position[2] || 0) + (newKpt.position[2] || 0)) / bufferedFactor : newKpt.position[2]
          ],
          positionRaw: [
            bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (bufferedResult.body[i].keypoints[j].positionRaw[0] || 0) + (newKpt.positionRaw[0] || 0)) / bufferedFactor : newKpt.positionRaw[0],
            bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (bufferedResult.body[i].keypoints[j].positionRaw[1] || 0) + (newKpt.positionRaw[1] || 0)) / bufferedFactor : newKpt.positionRaw[1],
            bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (bufferedResult.body[i].keypoints[j].positionRaw[2] || 0) + (newKpt.positionRaw[2] || 0)) / bufferedFactor : newKpt.positionRaw[2]
          ],
          distance: [
            bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (((_a2 = bufferedResult.body[i].keypoints[j].distance) == null ? void 0 : _a2[0]) || 0) + (((_b2 = newKpt.distance) == null ? void 0 : _b2[0]) || 0)) / bufferedFactor : (_c3 = newKpt.distance) == null ? void 0 : _c3[0],
            bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (((_d3 = bufferedResult.body[i].keypoints[j].distance) == null ? void 0 : _d3[1]) || 0) + (((_e2 = newKpt.distance) == null ? void 0 : _e2[1]) || 0)) / bufferedFactor : (_f3 = newKpt.distance) == null ? void 0 : _f3[1],
            bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * (((_g3 = bufferedResult.body[i].keypoints[j].distance) == null ? void 0 : _g3[2]) || 0) + (((_h3 = newKpt.distance) == null ? void 0 : _h3[2]) || 0)) / bufferedFactor : (_i3 = newKpt.distance) == null ? void 0 : _i3[2]
          ]
        };
      });
      const annotations2 = {};
      let coords = { connected: {} };
      if ((_a = config3.body.modelPath) == null ? void 0 : _a.includes("efficientpose")) coords = efficientposecoords_exports;
      else if ((_b = config3.body.modelPath) == null ? void 0 : _b.includes("blazepose")) coords = blazeposecoords_exports;
      else if ((_c2 = config3.body.modelPath) == null ? void 0 : _c2.includes("movenet")) coords = movenetcoords_exports;
      for (const [name, indexes] of Object.entries(coords.connected)) {
        const pt2 = [];
        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) pt2.push([pt0.position, pt1.position]);
        }
        annotations2[name] = pt2;
      }
      bufferedResult.body[i] = { ...newResult.body[i], box, 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 box = newResult.hand[i].box.map((b, j) => ((bufferedFactor - 1) * bufferedResult.hand[i].box[j] + b) / bufferedFactor);
      const boxRaw = newResult.hand[i].boxRaw.map((b, j) => ((bufferedFactor - 1) * bufferedResult.hand[i].boxRaw[j] + b) / 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, k) => ((bufferedFactor - 1) * (bufferedResult.hand[i].keypoints[j][k] || 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] = ((_f2 = (_e = (_d2 = newResult.hand[i]) == null ? void 0 : _d2.annotations) == null ? void 0 : _e[key]) == null ? void 0 : _f2[0]) ? newResult.hand[i].annotations[key].map((val, j) => val.map((coord, k) => ((bufferedFactor - 1) * bufferedResult.hand[i].annotations[key][j][k] + coord) / bufferedFactor)) : null;
        }
      }
      bufferedResult.hand[i] = { ...newResult.hand[i], box, 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 box = newResult.face[i].box.map((b, j) => ((bufferedFactor - 1) * bufferedResult.face[i].box[j] + b) / bufferedFactor);
      const boxRaw = newResult.face[i].boxRaw.map((b, j) => ((bufferedFactor - 1) * bufferedResult.face[i].boxRaw[j] + b) / bufferedFactor);
      let annotations2 = newResult.face[i].annotations;
      if (Object.keys(bufferedResult.face[i].annotations).length !== Object.keys(newResult.face[i].annotations).length) {
        bufferedResult.face[i].annotations = newResult.face[i].annotations;
        annotations2 = bufferedResult.face[i].annotations;
      } else if (newResult.face[i].annotations) {
        for (const key of Object.keys(newResult.face[i].annotations)) {
          annotations2[key] = ((_i2 = (_h2 = (_g2 = newResult.face[i]) == null ? void 0 : _g2.annotations) == null ? void 0 : _h2[key]) == null ? void 0 : _i2[0]) ? newResult.face[i].annotations[key].map((val, j) => val.map((coord, k) => ((bufferedFactor - 1) * bufferedResult.face[i].annotations[key][j][k] + coord) / bufferedFactor)) : null;
        }
      }
      if (newResult.face[i].rotation) {
        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 = (_j2 = newResult.face[i].rotation) == null ? void 0 : _j2.matrix;
        rotation.angle = {
          roll: ((bufferedFactor - 1) * (((_l2 = (_k2 = bufferedResult.face[i].rotation) == null ? void 0 : _k2.angle) == null ? void 0 : _l2.roll) || 0) + (((_n2 = (_m = newResult.face[i].rotation) == null ? void 0 : _m.angle) == null ? void 0 : _n2.roll) || 0)) / bufferedFactor,
          yaw: ((bufferedFactor - 1) * (((_p2 = (_o2 = bufferedResult.face[i].rotation) == null ? void 0 : _o2.angle) == null ? void 0 : _p2.yaw) || 0) + (((_r2 = (_q2 = newResult.face[i].rotation) == null ? void 0 : _q2.angle) == null ? void 0 : _r2.yaw) || 0)) / bufferedFactor,
          pitch: ((bufferedFactor - 1) * (((_t = (_s2 = bufferedResult.face[i].rotation) == null ? void 0 : _s2.angle) == null ? void 0 : _t.pitch) || 0) + (((_v2 = (_u2 = newResult.face[i].rotation) == null ? void 0 : _u2.angle) == null ? void 0 : _v2.pitch) || 0)) / bufferedFactor
        };
        rotation.gaze = {
          // not fully correct due projection on circle, also causes wrap-around draw on jump from negative to positive
          bearing: ((bufferedFactor - 1) * (((_w2 = bufferedResult.face[i].rotation) == null ? void 0 : _w2.gaze.bearing) || 0) + (((_x2 = newResult.face[i].rotation) == null ? void 0 : _x2.gaze.bearing) || 0)) / bufferedFactor,
          strength: ((bufferedFactor - 1) * (((_y = bufferedResult.face[i].rotation) == null ? void 0 : _y.gaze.strength) || 0) + (((_z2 = newResult.face[i].rotation) == null ? void 0 : _z2.gaze.strength) || 0)) / bufferedFactor
        };
        bufferedResult.face[i] = { ...newResult.face[i], rotation, box, boxRaw, annotations: annotations2 };
      } else {
        bufferedResult.face[i] = { ...newResult.face[i], box, boxRaw, annotations: annotations2 };
      }
    }
  }
  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 box = newResult.object[i].box.map((b, j) => ((bufferedFactor - 1) * bufferedResult.object[i].box[j] + b) / bufferedFactor);
      const boxRaw = newResult.object[i].boxRaw.map((b, j) => ((bufferedFactor - 1) * bufferedResult.object[i].boxRaw[j] + b) / bufferedFactor);
      bufferedResult.object[i] = { ...newResult.object[i], box, 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((box, j) => ((bufferedFactor - 1) * bufferedResult.persons[i].box[j] + box) / bufferedFactor);
      }
    }
  }
  if (newResult.gesture) bufferedResult.gesture = newResult.gesture;
  bufferedResult.width = newResult.width;
  bufferedResult.height = newResult.height;
  const t12 = now();
  interpolateTime = env.perfadd ? interpolateTime + Math.round(t12 - t02) : Math.round(t12 - t02);
  if (newResult.performance) bufferedResult.performance = { ...newResult.performance, interpolate: interpolateTime };
  return bufferedResult;
}

// src/segmentation/meet.ts
var model17;
async function load15(config3) {
  if (!model17 || env.initial) model17 = await loadModel(config3.segmentation.modelPath);
  else if (config3.debug) log("cached model:", model17["modelUrl"]);
  return model17;
}
async function predict16(input, config3) {
  var _a;
  if (!model17) model17 = await load15(config3);
  if (!(model17 == null ? void 0 : model17["executor"]) || !((_a = model17 == null ? void 0 : model17.inputs) == null ? void 0 : _a[0].shape)) return null;
  const t10 = {};
  t10.resize = eX.resizeBilinear(input, [model17.inputs[0].shape ? model17.inputs[0].shape[1] : 0, model17.inputs[0].shape ? model17.inputs[0].shape[2] : 0], false);
  t10.norm = je(t10.resize, constants.tf255);
  t10.res = model17.execute(t10.norm);
  t10.squeeze = cc(t10.res, [0]);
  [t10.bgRaw, t10.fgRaw] = fo(t10.squeeze, 2);
  t10.fg = V1(t10.fgRaw);
  t10.mul = se(t10.fg, constants.tf255);
  t10.expand = Ms(t10.mul, 2);
  t10.output = eX.resizeBilinear(t10.expand, [input.shape[1] || 0, input.shape[2] || 0]);
  let rgba;
  switch (config3.segmentation.mode || "default") {
    case "default":
      t10.input = cc(input);
      t10.concat = yt([t10.input, t10.output], -1);
      rgba = Ue(t10.concat, "int32");
      break;
    case "alpha":
      rgba = Ue(t10.output, "int32");
      break;
    default:
      rgba = ar(0);
  }
  Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
  return rgba;
}

// src/face/match.ts
var match_exports = {};
__export(match_exports, {
  distance: () => distance,
  find: () => find,
  similarity: () => similarity
});
function distance(descriptor1, descriptor2, options4 = { order: 2, multiplier: 25 }) {
  if (!descriptor1 || !descriptor1) return Number.MAX_SAFE_INTEGER;
  let sum = 0;
  for (let i = 0; i < descriptor1.length; i++) {
    const diff = !options4.order || options4.order === 2 ? descriptor1[i] - descriptor2[i] : Math.abs(descriptor1[i] - descriptor2[i]);
    sum += !options4.order || options4.order === 2 ? diff * diff : diff ** options4.order;
  }
  const dist = Math.round(100 * (options4.multiplier || 20) * sum) / 100;
  return dist;
}
var normalizeDistance = (dist, order, min, max) => {
  if (dist === 0) return 1;
  const root = order === 2 ? Math.sqrt(dist) : dist ** (1 / order);
  const norm = (1 - root / 100 - min) / (max - min);
  const clamp2 = Math.round(100 * Math.max(Math.min(norm, 1), 0)) / 100;
  return clamp2;
};
function similarity(descriptor1, descriptor2, options4 = { order: 2, multiplier: 25, min: 0.2, max: 0.8 }) {
  const dist = distance(descriptor1, descriptor2, options4);
  return normalizeDistance(dist, options4.order || 2, options4.min || 0, options4.max || 1);
}
function find(descriptor, descriptors, options4 = { order: 2, multiplier: 25, threshold: 0, min: 0.2, max: 0.8 }) {
  if (!Array.isArray(descriptor) || !Array.isArray(descriptors) || descriptor.length < 64 || descriptors.length === 0) {
    return { index: -1, distance: Number.POSITIVE_INFINITY, similarity: 0 };
  }
  let lowestDistance = Number.MAX_SAFE_INTEGER;
  let index2 = -1;
  for (let i = 0; i < descriptors.length; i++) {
    const res = descriptors[i].length === descriptor.length ? distance(descriptor, descriptors[i], options4) : Number.MAX_SAFE_INTEGER;
    if (res < lowestDistance) {
      lowestDistance = res;
      index2 = i;
    }
    if (lowestDistance < (options4.threshold || 0)) break;
  }
  const normalizedSimilarity = normalizeDistance(lowestDistance, options4.order || 2, options4.min || 0, options4.max || 1);
  return { index: index2, distance: lowestDistance, similarity: normalizedSimilarity };
}

// src/models.ts
var models_exports2 = {};
__export(models_exports2, {
  Models: () => Models,
  validateModel: () => validateModel
});

// src/body/movenetfix.ts
var maxJitter = 5e-3;
var cache5 = {
  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, compare2] 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 === compare2[0]);
    const rightTo = body4.keypoints.findIndex((kp2) => kp2 && kp2.part === compare2[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] && cache5.keypoints[i]) {
      const diff = [Math.abs(keypoints[i].positionRaw[0] - cache5.keypoints[i].positionRaw[0]), Math.abs(keypoints[i].positionRaw[1] - cache5.keypoints[i].positionRaw[1])];
      if (diff[0] < maxJitter && diff[1] < maxJitter) {
        keypoints[i] = cache5.keypoints[i];
      } else {
        cache5.keypoints[i] = keypoints[i];
      }
    } else {
      cache5.keypoints[i] = keypoints[i];
    }
  }
  return keypoints;
}
function padInput(input, inputSize10) {
  var _a, _b;
  const t10 = {};
  if (!((_a = input == null ? void 0 : input.shape) == null ? void 0 : _a[1]) || !((_b = input == null ? void 0 : input.shape) == null ? void 0 : _b[2])) return input;
  cache5.padding = [
    [0, 0],
    // dont touch batch
    [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],
    // height before&after
    [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],
    // width before&after
    [0, 0]
    // dont touch rbg
  ];
  t10.pad = Aa(input, cache5.padding);
  t10.resize = eX.resizeBilinear(t10.pad, [inputSize10, inputSize10]);
  const final = Ue(t10.resize, "int32");
  Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
  return final;
}
function rescaleBody(body4, outputSize2) {
  body4.keypoints = body4.keypoints.filter((kpt4) => kpt4 == null ? void 0 : kpt4.position);
  for (const kpt4 of body4.keypoints) {
    kpt4.position = [
      kpt4.position[0] * (outputSize2[0] + cache5.padding[2][0] + cache5.padding[2][1]) / outputSize2[0] - cache5.padding[2][0],
      kpt4.position[1] * (outputSize2[1] + cache5.padding[1][0] + cache5.padding[1][1]) / outputSize2[1] - cache5.padding[1][0]
    ];
    kpt4.positionRaw = [
      kpt4.position[0] / outputSize2[0],
      kpt4.position[1] / outputSize2[1]
    ];
  }
  const rescaledBoxes = calc(body4.keypoints.map((pt2) => pt2.position), outputSize2);
  body4.box = rescaledBoxes.box;
  body4.boxRaw = rescaledBoxes.boxRaw;
  return body4;
}

// src/body/movenet.ts
var model18;
var inputSize8 = 0;
var skipped14 = Number.MAX_SAFE_INTEGER;
var cache6 = {
  boxes: [],
  bodies: [],
  last: 0
};
async function load16(config3) {
  var _a;
  if (env.initial) model18 = null;
  if (!model18) {
    fakeOps(["size"], config3);
    model18 = await loadModel(config3.body.modelPath);
  } else if (config3.debug) log("cached model:", model18["modelUrl"]);
  inputSize8 = (model18 == null ? void 0 : model18["executor"]) && ((_a = model18 == null ? void 0 : model18.inputs) == null ? void 0 : _a[0].shape) ? model18.inputs[0].shape[2] : 0;
  if (inputSize8 < 64) inputSize8 = 256;
  if (A().flagRegistry.WEBGL_USE_SHAPES_UNIFORMS) A().set("WEBGL_USE_SHAPES_UNIFORMS", false);
  return model18;
}
function parseSinglePose(res, config3, image) {
  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 = [kpt4[id2][1], kpt4[id2][0]];
      keypoints.push({
        score: Math.round(100 * score) / 100,
        part: kpt3[id2],
        positionRaw,
        position: [
          // normalized to input image size
          Math.round((image.shape[2] || 0) * positionRaw[0]),
          Math.round((image.shape[1] || 0) * positionRaw[1])
        ]
      });
    }
  }
  score = keypoints.reduce((prev, curr) => curr.score > prev ? curr.score : prev, 0);
  const bodies = [];
  const newBox = calc(keypoints.map((pt2) => pt2.position), [image.shape[2], image.shape[1]]);
  const annotations2 = {};
  for (const [name, indexes] of Object.entries(connected3)) {
    const pt2 = [];
    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)) pt2.push([pt0.position, pt1.position]);
    }
    annotations2[name] = pt2;
  }
  const body4 = { id: 0, score, box: newBox.box, boxRaw: newBox.boxRaw, keypoints, annotations: annotations2 };
  bodyParts(body4);
  bodies.push(body4);
  return bodies;
}
function parseMultiPose(res, config3, image) {
  const bodies = [];
  for (let id2 = 0; id2 < res[0].length; id2++) {
    const kpt4 = res[0][id2];
    const boxScore = Math.round(100 * kpt4[51 + 4]) / 100;
    if (boxScore > 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 = [kpt4[3 * i + 1], kpt4[3 * i + 0]];
          keypoints.push({
            part: kpt3[i],
            score: Math.round(100 * score) / 100,
            positionRaw,
            position: [Math.round((image.shape[2] || 0) * positionRaw[0]), Math.round((image.shape[1] || 0) * positionRaw[1])]
          });
        }
      }
      const boxRaw = [kpt4[51 + 1], kpt4[51 + 0], kpt4[51 + 3] - kpt4[51 + 1], kpt4[51 + 2] - kpt4[51 + 0]];
      const boxNorm = [Math.trunc(boxRaw[0] * (image.shape[2] || 0)), Math.trunc(boxRaw[1] * (image.shape[1] || 0)), Math.trunc(boxRaw[2] * (image.shape[2] || 0)), Math.trunc(boxRaw[3] * (image.shape[1] || 0))];
      const annotations2 = {};
      for (const [name, indexes] of Object.entries(connected3)) {
        const pt2 = [];
        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)) pt2.push([pt0.position, pt1.position]);
        }
        annotations2[name] = pt2;
      }
      const body4 = { id: id2, score: boxScore, box: boxNorm, boxRaw, keypoints: [...keypoints], annotations: annotations2 };
      bodyParts(body4);
      bodies.push(body4);
    }
  }
  bodies.sort((a, b) => b.score - a.score);
  if (bodies.length > config3.body.maxDetected) bodies.length = config3.body.maxDetected;
  return bodies;
}
async function predict17(input, config3) {
  var _a;
  if (!(model18 == null ? void 0 : model18["executor"]) || !((_a = model18 == null ? void 0 : model18.inputs) == null ? void 0 : _a[0].shape)) return [];
  if (!config3.skipAllowed) cache6.boxes.length = 0;
  skipped14++;
  const skipTime = (config3.body.skipTime || 0) > now() - cache6.last;
  const skipFrame = skipped14 < (config3.body.skipFrames || 0);
  if (config3.skipAllowed && skipTime && skipFrame) {
    return cache6.bodies;
  }
  return new Promise(async (resolve) => {
    const t10 = {};
    skipped14 = 0;
    t10.input = padInput(input, inputSize8);
    t10.res = model18 == null ? void 0 : model18.execute(t10.input);
    cache6.last = now();
    const res = await t10.res.array();
    cache6.bodies = t10.res.shape[2] === 17 ? parseSinglePose(res, config3, input) : parseMultiPose(res, config3, input);
    for (const body4 of cache6.bodies) {
      rescaleBody(body4, [input.shape[2] || 1, input.shape[1] || 1]);
      jitter(body4.keypoints);
    }
    Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
    resolve(cache6.bodies);
  });
}

// src/object/nanodet.ts
var model19;
var last10 = [];
var lastTime15 = 0;
var skipped15 = Number.MAX_SAFE_INTEGER;
var inputSize9 = 0;
var scaleBox = 2.5;
async function load17(config3) {
  if (!model19 || env.initial) {
    model19 = await loadModel(config3.object.modelPath);
    const inputs = (model19 == null ? void 0 : model19["executor"]) ? Object.values(model19.modelSignature["inputs"]) : void 0;
    inputSize9 = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : 416;
  } else if (config3.debug) log("cached model:", model19["modelUrl"]);
  return model19;
}
async function process4(res, outputShape, config3) {
  var _a, _b;
  let id2 = 0;
  let results = [];
  const size2 = inputSize9;
  for (const strideSize of [1, 2, 4]) {
    const baseSize = strideSize * 13;
    const scoresT = cc(res.find((a) => a.shape[1] === baseSize ** 2 && (a.shape[2] || 0) === labels2.length));
    const scores = await scoresT.array();
    const featuresT = cc(res.find((a) => a.shape[1] === baseSize ** 2 && (a.shape[2] || 0) < labels2.length));
    const boxesMaxT = W(featuresT, [-1, 4, (((_a = featuresT.shape) == null ? void 0 : _a[1]) || 0) / 4]);
    const boxIdxT = Ok(boxesMaxT, 2);
    const boxIdx = await boxIdxT.array();
    for (let i = 0; i < scoresT.shape[0]; i++) {
      for (let j = 0; j < (((_b = scoresT.shape) == null ? void 0 : _b[1]) || 0); j++) {
        const score = scores[i][j];
        if (score > (config3.object.minConfidence || 0) && 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 / size2));
          const [x, y8] = [
            cx2 - scaleBox / strideSize * boxOffset[0],
            cy2 - scaleBox / strideSize * boxOffset[1]
          ];
          const [w8, h] = [
            cx2 + scaleBox / strideSize * boxOffset[2] - x,
            cy2 + scaleBox / strideSize * boxOffset[3] - y8
          ];
          let boxRaw = [x, y8, w8, h];
          boxRaw = boxRaw.map((a) => Math.max(0, Math.min(a, 1)));
          const box = [
            // results normalized to input image pixels
            boxRaw[0] * outputShape[0],
            boxRaw[1] * outputShape[1],
            boxRaw[2] * outputShape[0],
            boxRaw[3] * outputShape[1]
          ];
          const result = {
            id: id2++,
            // strideSize,
            score: Math.round(100 * score) / 100,
            class: j + 1,
            label: labels2[j].label,
            // center: [Math.trunc(outputShape[0] * cx), Math.trunc(outputShape[1] * cy)],
            // centerRaw: [cx, cy],
            box: box.map((a) => Math.trunc(a)),
            boxRaw
          };
          results.push(result);
        }
      }
    }
    Ot([scoresT, featuresT, boxesMaxT, boxIdxT]);
  }
  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 eX.nonMaxSuppressionAsync(nmsBoxes, nmsScores, config3.object.maxDetected || 0, config3.object.iouThreshold, config3.object.minConfidence);
    nmsIdx = Array.from(await nms.data());
    Ot(nms);
  }
  results = results.filter((_val, idx) => nmsIdx.includes(idx)).sort((a, b) => b.score - a.score);
  return results;
}
async function predict18(image, config3) {
  if (!(model19 == null ? void 0 : model19["executor"])) return [];
  const skipTime = (config3.object.skipTime || 0) > now() - lastTime15;
  const skipFrame = skipped15 < (config3.object.skipFrames || 0);
  if (config3.skipAllowed && skipTime && skipFrame && last10.length > 0) {
    skipped15++;
    return last10;
  }
  skipped15 = 0;
  if (!env.kernels.includes("mod") || !env.kernels.includes("sparsetodense")) return last10;
  return new Promise(async (resolve) => {
    const outputSize2 = [image.shape[2] || 0, image.shape[1] || 0];
    const resizeT = eX.resizeBilinear(image, [inputSize9, inputSize9], false);
    const normT = je(resizeT, constants.tf255);
    const transposeT = mc(normT, [0, 3, 1, 2]);
    let objectT;
    if (config3.object.enabled) objectT = model19.execute(transposeT);
    lastTime15 = now();
    const obj = await process4(objectT, outputSize2, config3);
    last10 = obj;
    Ot([resizeT, normT, transposeT, ...objectT]);
    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: y8 } }) => ({
    maxX: Math.max(maxX, x),
    maxY: Math.max(maxY, y8),
    minX: Math.min(minX, x),
    minY: Math.min(minY, y8)
  }), {
    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]
    })),
    annotations: {}
  });
  const scaledPoses = poses.map((pose, i) => scalePose(pose, i));
  return scaledPoses;
}
var MaxHeap = class {
  // function call
  constructor(maxSize2, getElementValue) {
    __publicField(this, "priorityQueue");
    // don't touch
    __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(k) {
    while (k > 0 && this.less(Math.floor(k / 2), k)) {
      this.exchange(k, Math.floor(k / 2));
      k = Math.floor(k / 2);
    }
  }
  sink(k) {
    while (2 * k <= this.numberOfElements) {
      let j = 2 * k;
      if (j < this.numberOfElements && this.less(j, j + 1)) j++;
      if (!this.less(k, j)) break;
      this.exchange(k, j);
      k = j;
    }
  }
  getValueAt(i) {
    return this.getElementValue(this.priorityQueue[i]);
  }
  less(i, j) {
    return this.getValueAt(i) < this.getValueAt(j);
  }
  exchange(i, j) {
    const t10 = this.priorityQueue[i];
    this.priorityQueue[i] = this.priorityQueue[j];
    this.priorityQueue[j] = t10;
  }
};
function getOffsetPoint(y8, x, keypoint, offsets) {
  return {
    y: offsets.get(y8, x, keypoint),
    x: offsets.get(y8, x, keypoint + count)
  };
}
function getImageCoords(part, outputStride2, offsets) {
  const { heatmapY, heatmapX, id: keypoint } = part;
  const { y: y8, x } = getOffsetPoint(heatmapY, heatmapX, keypoint, offsets);
  return {
    x: part.heatmapX * outputStride2 + x,
    y: part.heatmapY * outputStride2 + y8
  };
}
function clamp(a, min, max) {
  if (a < min) return min;
  if (a > max) return max;
  return a;
}
function squaredDistance(y12, x1, y22, x22) {
  const dy2 = y22 - y12;
  const dx2 = x22 - x1;
  return dy2 * dy2 + dx2 * dx2;
}
function addVectors(a, b) {
  return { x: a.x + b.x, y: a.y + b.y };
}

// src/body/posenet.ts
var model20;
var poseNetOutputs = [
  "MobilenetV1/offset_2/BiasAdd",
  "MobilenetV1/heatmap_2/BiasAdd",
  "MobilenetV1/displacement_fwd_2/BiasAdd",
  "MobilenetV1/displacement_bwd_2/BiasAdd"
  /* displacementBwd */
];
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: y8 }, keypointId) {
  return poses.some(({ keypoints }) => {
    var _a;
    const correspondingKeypoint = (_a = keypoints[keypointId]) == null ? void 0 : _a.position;
    if (!correspondingKeypoint) return false;
    return squaredDistance(y8, 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 box = getBoundingBox(keypoints);
    if (score > minConfidence2) poses.push({ keypoints, box, score: Math.round(100 * score) / 100 });
  }
  return poses;
}
async function predict19(input, config3) {
  if (!(model20 == null ? void 0 : model20["executor"])) return [];
  const res = De(() => {
    if (!model20.inputs[0].shape) return [];
    const resized = eX.resizeBilinear(input, [model20.inputs[0].shape[2], model20.inputs[0].shape[1]]);
    const normalized = Te(je(Ue(resized, "float32"), 127.5), 1);
    const results = model20.execute(normalized, poseNetOutputs);
    const results3d = results.map((y8) => cc(y8, [0]));
    results3d[1] = Ea(results3d[1]);
    return results3d;
  });
  const buffers = await Promise.all(res.map((tensor2) => tensor2.buffer()));
  for (const t10 of res) Ot(t10);
  const decoded = decode(buffers[0], buffers[1], buffers[2], buffers[3], config3.body.maxDetected, config3.body.minConfidence);
  if (!model20.inputs[0].shape) return [];
  const scaled = scalePoses(decoded, [input.shape[1], input.shape[2]], [model20.inputs[0].shape[2], model20.inputs[0].shape[1]]);
  return scaled;
}
async function load18(config3) {
  if (!model20 || env.initial) model20 = await loadModel(config3.body.modelPath);
  else if (config3.debug) log("cached model:", model20["modelUrl"]);
  return model20;
}

// src/segmentation/rvm.ts
var model21;
var outputNodes2 = ["fgr", "pha", "r1o", "r2o", "r3o", "r4o"];
var t = {};
var ratio = 0;
function init3(config3) {
  Ot([t.r1i, t.r2i, t.r3i, t.r4i, t.downsample_ratio]);
  t.r1i = ar(0);
  t.r2i = ar(0);
  t.r3i = ar(0);
  t.r4i = ar(0);
  ratio = config3.segmentation.ratio || 0.5;
  t.downsample_ratio = ar(ratio);
}
async function load19(config3) {
  if (!model21 || env.initial) model21 = await loadModel(config3.segmentation.modelPath);
  else if (config3.debug) log("cached model:", model21["modelUrl"]);
  init3(config3);
  return model21;
}
var normalize = (r15) => De(() => {
  const squeeze = cc(r15, [0]);
  const mul = se(squeeze, constants.tf255);
  const cast = Ue(mul, "int32");
  return cast;
});
function getRGBA(fgr, pha) {
  const rgb3 = fgr ? normalize(fgr) : $a([pha.shape[1] || 0, pha.shape[2] || 0, 3], 255, "int32");
  const a = pha ? normalize(pha) : $a([fgr.shape[1] || 0, fgr.shape[2] || 0, 1], 255, "int32");
  const rgba = yt([rgb3, a], -1);
  Ot([rgb3, a]);
  return rgba;
}
function getState(state) {
  return De(() => {
    const r15 = {};
    r15.unstack = fo(state, -1);
    r15.concat = yt(r15.unstack, 1);
    r15.split = li(r15.concat, 4, 1);
    r15.stack = yt(r15.split, 2);
    r15.squeeze = cc(r15.stack, [0]);
    r15.expand = Ms(r15.squeeze, -1);
    r15.add = Ce(r15.expand, 1);
    r15.mul = se(r15.add, 127.5);
    r15.cast = Ue(r15.mul, "int32");
    r15.tile = uu(r15.cast, [1, 1, 3]);
    r15.alpha = $a([r15.tile.shape[0] || 0, r15.tile.shape[1] || 0, 1], 255, "int32");
    return yt([r15.tile, r15.alpha], -1);
  });
}
async function predict20(input, config3) {
  if (!model21) model21 = await load19(config3);
  if (!(model21 == null ? void 0 : model21["executor"])) return null;
  t.src = je(input, 255);
  if (ratio !== config3.segmentation.ratio) init3(config3);
  const [fgr, pha, r1o, r2o, r3o, r4o] = await model21.executeAsync(t, outputNodes2);
  let rgba;
  switch (config3.segmentation.mode || "default") {
    case "default":
      rgba = getRGBA(fgr, pha);
      break;
    case "alpha":
      rgba = getRGBA(null, pha);
      break;
    case "foreground":
      rgba = getRGBA(fgr, null);
      break;
    case "state":
      rgba = getState(r1o);
      break;
    default:
      rgba = ar(0);
  }
  Ot([t.src, fgr, pha, t.r1i, t.r2i, t.r3i, t.r4i]);
  [t.r1i, t.r2i, t.r3i, t.r4i] = [r1o, r2o, r3o, r4o];
  return rgba;
}

// src/segmentation/selfie.ts
var model22;
async function load20(config3) {
  if (!model22 || env.initial) model22 = await loadModel(config3.segmentation.modelPath);
  else if (config3.debug) log("cached model:", model22["modelUrl"]);
  return model22;
}
async function predict21(input, config3) {
  var _a;
  if (!model22) model22 = await load20(config3);
  if (!(model22 == null ? void 0 : model22["executor"]) || !((_a = model22 == null ? void 0 : model22.inputs) == null ? void 0 : _a[0].shape)) return null;
  const t10 = {};
  t10.resize = eX.resizeBilinear(input, [model22.inputs[0].shape ? model22.inputs[0].shape[1] : 0, model22.inputs[0].shape ? model22.inputs[0].shape[2] : 0], false);
  t10.norm = je(t10.resize, constants.tf255);
  t10.res = model22.execute(t10.norm);
  t10.squeeze = cc(t10.res, [0]);
  t10.alpha = eX.resizeBilinear(t10.squeeze, [input.shape[1] || 0, input.shape[2] || 0]);
  t10.mul = se(t10.alpha, constants.tf255);
  let rgba;
  switch (config3.segmentation.mode || "default") {
    case "default":
      t10.input = cc(input);
      t10.concat = yt([t10.input, t10.mul], -1);
      rgba = Ue(t10.concat, "int32");
      break;
    case "alpha":
      rgba = Ue(t10.mul, "int32");
      break;
    default:
      rgba = ar(0);
  }
  Object.keys(t10).forEach((tensor2) => Ot(t10[tensor2]));
  return rgba;
}

// src/models.ts
function validateModel(instance, model23, name) {
  var _a, _b;
  if (!model23) return null;
  if (!((_a = instance == null ? void 0 : instance.config) == null ? void 0 : _a.validateModels)) return null;
  const simpleOps = ["const", "placeholder", "noop", "pad", "squeeze", "add", "sub", "mul", "div"];
  const ignoreOps = ["biasadd", "fusedbatchnormv3", "matmul", "switch", "shape", "merge", "split", "broadcastto"];
  const ops = [];
  const missing = [];
  const url = model23["modelUrl"];
  const executor = model23["executor"];
  if ((_b = executor == null ? void 0 : executor.graph) == null ? void 0 : _b.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 not loaded", name);
    }
  }
  for (const op2 of ops) {
    if (!simpleOps.includes(op2) && !ignoreOps.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 (instance.config.debug && missing.length > 0) log("model validation failed:", name, missing);
  return missing.length > 0 ? { name, missing, ops, url } : null;
}
var Models = class {
  constructor(currentInstance) {
    __publicField(this, "instance");
    __publicField(this, "models", {});
    this.models = {};
    this.instance = currentInstance;
  }
  stats() {
    let totalSizeFromManifest = 0;
    let totalSizeWeights = 0;
    let totalSizeLoading = 0;
    for (const m of Object.values(modelStats)) {
      totalSizeFromManifest += Number.isNaN(+m.sizeFromManifest) ? 0 : m.sizeFromManifest;
      totalSizeWeights += Number.isNaN(+m.sizeLoadedWeights) ? 0 : m.sizeLoadedWeights;
      totalSizeLoading += Number.isNaN(+m.sizeDesired) ? 0 : m.sizeDesired;
    }
    const percentageLoaded = totalSizeLoading > 0 ? totalSizeWeights / totalSizeLoading : 0;
    return {
      numLoadedModels: Object.values(modelStats).filter((m) => m == null ? void 0 : m.loaded).length,
      numDefinedModels: Object.keys(this.models).length,
      percentageLoaded,
      totalSizeFromManifest,
      totalSizeWeights,
      totalSizeLoading,
      modelStats: Object.values(modelStats)
    };
  }
  reset() {
    for (const model23 of Object.keys(this.models)) this.models[model23] = null;
  }
  async load(instance) {
    var _a, _b, _c2, _d2, _e, _f2, _g2, _h2, _i2, _j2, _k2, _l2, _m, _n2, _o2, _p2, _q2, _r2, _s2, _t, _u2, _v2, _w2, _x2, _y, _z2, _A2;
    if (env.initial) this.reset();
    if (instance) this.instance = instance;
    const m = {};
    m.blazeface = this.instance.config.face.enabled && !this.models.blazeface ? load3(this.instance.config) : null;
    m.antispoof = this.instance.config.face.enabled && ((_a = this.instance.config.face.antispoof) == null ? void 0 : _a.enabled) && !this.models.antispoof ? load8(this.instance.config) : null;
    m.liveness = this.instance.config.face.enabled && ((_b = this.instance.config.face.liveness) == null ? void 0 : _b.enabled) && !this.models.liveness ? load9(this.instance.config) : null;
    m.faceres = this.instance.config.face.enabled && ((_c2 = this.instance.config.face.description) == null ? void 0 : _c2.enabled) && !this.models.faceres ? load7(this.instance.config) : null;
    m.emotion = this.instance.config.face.enabled && ((_d2 = this.instance.config.face.emotion) == null ? void 0 : _d2.enabled) && !this.models.emotion ? load6(this.instance.config) : null;
    m.iris = this.instance.config.face.enabled && ((_e = this.instance.config.face.iris) == null ? void 0 : _e.enabled) && !((_f2 = this.instance.config.face.attention) == null ? void 0 : _f2.enabled) && !this.models.iris ? load4(this.instance.config) : null;
    m.facemesh = this.instance.config.face.enabled && ((_g2 = this.instance.config.face.mesh) == null ? void 0 : _g2.enabled) && !this.models.facemesh ? load5(this.instance.config) : null;
    m.gear = this.instance.config.face.enabled && ((_h2 = this.instance.config.face["gear"]) == null ? void 0 : _h2.enabled) && !this.models.gear ? load10(this.instance.config) : null;
    m.ssrnetage = this.instance.config.face.enabled && ((_i2 = this.instance.config.face["ssrnet"]) == null ? void 0 : _i2.enabled) && !this.models.ssrnetage ? load11(this.instance.config) : null;
    m.ssrnetgender = this.instance.config.face.enabled && ((_j2 = this.instance.config.face["ssrnet"]) == null ? void 0 : _j2.enabled) && !this.models.ssrnetgender ? load12(this.instance.config) : null;
    m.mobilefacenet = this.instance.config.face.enabled && ((_k2 = this.instance.config.face["mobilefacenet"]) == null ? void 0 : _k2.enabled) && !this.models.mobilefacenet ? load13(this.instance.config) : null;
    m.insightface = this.instance.config.face.enabled && ((_l2 = this.instance.config.face["insightface"]) == null ? void 0 : _l2.enabled) && !this.models.insightface ? load14(this.instance.config) : null;
    m.blazepose = this.instance.config.body.enabled && !this.models.blazepose && ((_m = this.instance.config.body.modelPath) == null ? void 0 : _m.includes("blazepose")) ? loadPose(this.instance.config) : null;
    m.blazeposedetect = this.instance.config.body.enabled && !this.models.blazeposedetect && this.instance.config.body["detector"] && this.instance.config.body["detector"].modelPath ? loadDetect(this.instance.config) : null;
    m.efficientpose = this.instance.config.body.enabled && !this.models.efficientpose && ((_n2 = this.instance.config.body.modelPath) == null ? void 0 : _n2.includes("efficientpose")) ? load2(this.instance.config) : null;
    m.movenet = this.instance.config.body.enabled && !this.models.movenet && ((_o2 = this.instance.config.body.modelPath) == null ? void 0 : _o2.includes("movenet")) ? load16(this.instance.config) : null;
    m.posenet = this.instance.config.body.enabled && !this.models.posenet && ((_p2 = this.instance.config.body.modelPath) == null ? void 0 : _p2.includes("posenet")) ? load18(this.instance.config) : null;
    m.handtrack = this.instance.config.hand.enabled && !this.models.handtrack && ((_r2 = (_q2 = this.instance.config.hand.detector) == null ? void 0 : _q2.modelPath) == null ? void 0 : _r2.includes("handtrack")) ? loadDetect3(this.instance.config) : null;
    m.handskeleton = this.instance.config.hand.enabled && this.instance.config.hand.landmarks && !this.models.handskeleton && ((_t = (_s2 = this.instance.config.hand.detector) == null ? void 0 : _s2.modelPath) == null ? void 0 : _t.includes("handtrack")) ? loadSkeleton2(this.instance.config) : null;
    if (this.instance.config.hand.enabled && !this.models.handdetect && ((_v2 = (_u2 = this.instance.config.hand.detector) == null ? void 0 : _u2.modelPath) == null ? void 0 : _v2.includes("handdetect"))) {
      m.handdetect = loadDetect2(this.instance.config);
      m.handskeleton = loadSkeleton(this.instance.config);
    }
    m.centernet = this.instance.config.object.enabled && !this.models.centernet && ((_w2 = this.instance.config.object.modelPath) == null ? void 0 : _w2.includes("centernet")) ? load(this.instance.config) : null;
    m.nanodet = this.instance.config.object.enabled && !this.models.nanodet && ((_x2 = this.instance.config.object.modelPath) == null ? void 0 : _x2.includes("nanodet")) ? load17(this.instance.config) : null;
    m.selfie = this.instance.config.segmentation.enabled && !this.models.selfie && ((_y = this.instance.config.segmentation.modelPath) == null ? void 0 : _y.includes("selfie")) ? load20(this.instance.config) : null;
    m.meet = this.instance.config.segmentation.enabled && !this.models.meet && ((_z2 = this.instance.config.segmentation.modelPath) == null ? void 0 : _z2.includes("meet")) ? load15(this.instance.config) : null;
    m.rvm = this.instance.config.segmentation.enabled && !this.models.rvm && ((_A2 = this.instance.config.segmentation.modelPath) == null ? void 0 : _A2.includes("rvm")) ? load19(this.instance.config) : null;
    for (const [model23, promise] of Object.entries(m)) {
      if (promise == null ? void 0 : promise["then"]) promise["then"]((val) => this.models[model23] = val);
    }
    await Promise.all(Object.values(m));
  }
  list() {
    const models3 = Object.keys(this.models).map((model23) => {
      var _a;
      return { name: model23, loaded: this.models[model23] !== null, size: 0, url: this.models[model23] ? (_a = this.models[model23]) == null ? void 0 : _a["modelUrl"] : null };
    });
    for (const m of models3) {
      const stats = Object.keys(modelStats).find((s) => s.startsWith(m.name));
      if (!stats) continue;
      m.size = modelStats[stats].sizeLoadedWeights;
      m.url = modelStats[stats].url;
    }
    return models3;
  }
  loaded() {
    const list = this.list();
    const loaded = list.filter((model23) => model23.loaded).map((model23) => model23.name);
    return loaded;
  }
  validate() {
    const missing = [];
    for (const defined of Object.keys(this.models)) {
      const model23 = this.models[defined];
      if (!model23) continue;
      const res = validateModel(this.instance, model23, defined);
      if (res) missing.push(res);
    }
    return missing;
  }
};

// src/util/persons.ts
function join2(faces, bodies, hands, gestures, shape) {
  var _a, _b, _c2, _d2, _e, _f2;
  let id2 = 0;
  const persons = [];
  for (const face4 of faces) {
    const person2 = { id: id2++, face: face4, body: null, hands: { left: null, right: null }, gestures: [], box: [0, 0, 0, 0] };
    for (const body4 of bodies) {
      if (face4.box[0] > body4.box[0] && face4.box[0] < body4.box[0] + body4.box[2] && face4.box[1] + face4.box[3] > body4.box[1] && face4.box[1] + face4.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 gesture2 of gestures) {
      if (gesture2["face"] !== void 0 && gesture2["face"] === face4.id) person2.gestures.push(gesture2);
      else if (gesture2["iris"] !== void 0 && gesture2["iris"] === face4.id) person2.gestures.push(gesture2);
      else if (gesture2["body"] !== void 0 && gesture2["body"] === ((_a = person2.body) == null ? void 0 : _a.id)) person2.gestures.push(gesture2);
      else if (gesture2["hand"] !== void 0 && gesture2["hand"] === ((_b = person2.hands.left) == null ? void 0 : _b.id)) person2.gestures.push(gesture2);
      else if (gesture2["hand"] !== void 0 && gesture2["hand"] === ((_c2 = person2.hands.right) == null ? void 0 : _c2.id)) person2.gestures.push(gesture2);
    }
    const x = [];
    const y8 = [];
    const extractXY = (box) => {
      if (box && box.length === 4) {
        x.push(box[0], box[0] + box[2]);
        y8.push(box[1], box[1] + box[3]);
      }
    };
    extractXY(person2.face.box);
    extractXY((_d2 = person2.body) == null ? void 0 : _d2.box);
    extractXY((_e = person2.hands.left) == null ? void 0 : _e.box);
    extractXY((_f2 = person2.hands.right) == null ? void 0 : _f2.box);
    const minX = Math.min(...x);
    const minY = Math.min(...y8);
    person2.box = [minX, minY, Math.max(...x) - minX, Math.max(...y8) - minY];
    if ((shape == null ? void 0 : shape[1]) && (shape == null ? void 0 : shape[2])) person2.boxRaw = [person2.box[0] / shape[2], person2.box[1] / shape[1], person2.box[2] / shape[2], person2.box[3] / shape[1]];
    persons.push(person2);
  }
  return persons;
}

// 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 = "";
    }
    let img;
    if (typeof Image !== "undefined") img = new Image();
    else if (env.Image) img = new env.Image();
    else {
      resolve(void 0);
      return;
    }
    img.onload = async () => {
      const canvas3 = canvas(img.naturalWidth, img.naturalHeight);
      if (!canvas3) {
        log("Warmup: Canvas not found");
        resolve(void 0);
      } else {
        const ctx = canvas3.getContext("2d");
        if (ctx) ctx.drawImage(img, 0, 0);
        const tensor2 = await instance.image(canvas3, true);
        const res = tensor2.tensor ? await instance.detect(tensor2.tensor, instance.config) : void 0;
        resolve(res);
      }
    };
    if (src) img.src = src;
    else resolve(void 0);
  });
}
async function warmupNode(instance) {
  const atob2 = (str) => Buffer.from(str, "base64");
  let img;
  if (instance.config.warmup === "face") img = atob2(face3);
  else img = atob2(body3);
  let res;
  if ("node" in tfjs_esm_exports && sk() === "tensorflow") {
    const data = EQt.decodeJpeg(img);
    const expanded = Ms(data, 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 runInference(instance) {
  let res;
  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);
  return res;
}
async function runCompile(instance) {
  var _a, _b, _c2, _d2;
  if (!A().flagRegistry.ENGINE_COMPILE_ONLY) return;
  const backendType = sk();
  const webGLBackend = ak();
  if (backendType !== "webgl" && backendType !== "humangl" || !(webGLBackend == null ? void 0 : webGLBackend["checkCompileCompletion"])) {
    return;
  }
  A().set("ENGINE_COMPILE_ONLY", true);
  const numTensorsStart = ur().state.numTensors;
  const compiledModels = [];
  for (const [modelName, model23] of Object.entries(instance.models.models)) {
    if (!model23) continue;
    const shape = (model23 == null ? void 0 : model23.modelSignature) && ((_b = (_a = model23 == null ? void 0 : model23.inputs) == null ? void 0 : _a[0]) == null ? void 0 : _b.shape) ? [...model23.inputs[0].shape] : [1, 64, 64, 3];
    const dtype = (model23 == null ? void 0 : model23.modelSignature) && ((_d2 = (_c2 = model23 == null ? void 0 : model23.inputs) == null ? void 0 : _c2[0]) == null ? void 0 : _d2.dtype) ? model23.inputs[0].dtype : "float32";
    for (let dim = 0; dim < shape.length; dim++) {
      if (shape[dim] === -1) shape[dim] = dim === 0 ? 1 : 64;
    }
    const tensor2 = Gr(shape, dtype);
    try {
      const res = model23.execute(tensor2);
      compiledModels.push(modelName);
      if (Array.isArray(res)) res.forEach((t10) => Ot(t10));
      else Ot(res);
    } catch (e) {
      if (instance.config.debug) log("compile fail model:", modelName);
    }
    Ot(tensor2);
  }
  const kernels = await webGLBackend["checkCompileCompletionAsync"]();
  webGLBackend["getUniformLocations"]();
  if (instance.config.debug) log("compile pass:", { models: compiledModels, kernels: kernels.length });
  A().set("ENGINE_COMPILE_ONLY", false);
  const numTensorsEnd = ur().state.numTensors;
  if (numTensorsEnd - numTensorsStart > 0) log("tensor leak:", numTensorsEnd - numTensorsStart);
}
async function warmup(instance, userConfig) {
  await check(instance, false);
  const t02 = now();
  instance.state = "warmup";
  if (userConfig) instance.config = mergeDeep(instance.config, userConfig);
  if (!instance.config.warmup || instance.config.warmup.length === 0 || instance.config.warmup === "none") {
    return empty();
  }
  return new Promise(async (resolve) => {
    await instance.models.load();
    await Ime();
    await runCompile(instance);
    const res = await runInference(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, _loops;
var Human = class {
  // definition end
  /** Constructor for **Human** library that is futher used for all operations
   * @param userConfig - user configuration object {@link Config}
   */
  constructor(userConfig) {
    /** Current version of Human library in *semver* format */
    __publicField(this, "version");
    /** Current configuration
     * - Defaults: [config](https://github.com/vladmandic/human/blob/main/src/config.ts#L262)
     */
    __publicField(this, "config");
    /** Last known result of detect run
     * - Can be accessed anytime after initial detection
    */
    __publicField(this, "result");
    /** Current state of Human library
     * - Can be polled to determine operations that are currently executed
     * - Progresses through: 'config', 'check', 'backend', 'load', 'run:<model>', 'idle'
     */
    __publicField(this, "state");
    /** currenty processed image tensor and canvas */
    __publicField(this, "process");
    /** Instance of TensorFlow/JS used by Human
     *  - Can be embedded or externally provided
     * [TFJS API](https://js.tensorflow.org/api/latest/)
     */
    __publicField(this, "tf");
    /** Object containing environment information used for diagnostics */
    __publicField(this, "env", env);
    /** Draw helper classes that can draw detected objects on canvas using specified draw
     * - canvas: draws input to canvas
     * - options: are global settings for all draw operations, can be overriden for each draw method {@link DrawOptions}
     * - face, body, hand, gesture, object, person: draws detected results as overlays on canvas
     */
    // draw: { canvas: typeof draw.canvas, face: typeof draw.face, body: typeof draw.body, hand: typeof draw.hand, gesture: typeof draw.gesture, object: typeof draw.object, person: typeof draw.person, all: typeof draw.all, options: DrawOptions };
    __publicField(this, "draw", draw_exports);
    /** Face Matching
     * - similarity: compare two face descriptors and return similarity index
     * - distance: compare two face descriptors and return raw calculated differences
     * - find: compare face descriptor to array of face descriptors and return best match
     */
    __publicField(this, "match", match_exports);
    /** Currently loaded models
     * @internal
     * {@link models#Models}
    */
    __publicField(this, "models");
    /** Container for events dispatched by Human
     * Possible events:
     * - `create`: triggered when Human object is instantiated
     * - `load`: triggered when models are loaded (explicitly or on-demand)
     * - `image`: triggered when input image is processed
     * - `result`: triggered when detection is complete
     * - `warmup`: triggered when warmup is complete
     * - `error`: triggered on some errors
     */
    __publicField(this, "events");
    /** Reference face triangualtion array of 468 points, used for triangle references between points */
    __publicField(this, "faceTriangulation");
    /** Refernce UV map of 468 values, used for 3D mapping of the face mesh */
    __publicField(this, "faceUVMap");
    /** Performance object that contains values for all recently performed operations */
    __publicField(this, "performance");
    // perf members are dynamically defined as needed
    __privateAdd(this, _numTensors);
    __privateAdd(this, _analyzeMemoryLeaks);
    __privateAdd(this, _checkSanity);
    /** internal function to measure tensor leaks */
    __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);
    });
    /** internal function for quick sanity check on inputs @hidden */
    __privateAdd(this, _sanity, (input) => {
      if (!__privateGet(this, _checkSanity)) return null;
      if (!input) return "input is not defined";
      if (this.env.node && !(input instanceof mt)) return "input must be a tensor";
      try {
        this.tf.getBackend();
      } catch (e) {
        return "backend not loaded";
      }
      return null;
    });
    /** WebCam helper methods
     *
     */
    __publicField(this, "webcam", new WebCam());
    /** emit event */
    __publicField(this, "emit", (event) => {
      var _a;
      if ((_a = this.events) == null ? void 0 : _a.dispatchEvent) this.events.dispatchEvent(new Event(event));
    });
    /** internal structure that keeps track of processed videos @hidden */
    __privateAdd(this, _loops, {});
    const tfVersion = (Vce.tfjs || OX).replace(/-(.*)/, "");
    config.wasmPath = `https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${tfVersion}/dist/`;
    config.modelBasePath = env.browser ? "../models/" : "file://models/";
    this.version = version;
    Object.defineProperty(this, "version", { value: version });
    this.config = JSON.parse(JSON.stringify(config));
    Object.seal(this.config);
    this.config.cacheModels = typeof indexedDB !== "undefined";
    if (userConfig) this.config = mergeDeep(this.config, userConfig);
    setModelLoadOptions(this.config);
    this.tf = tfjs_esm_exports;
    this.state = "idle";
    __privateSet(this, _numTensors, 0);
    __privateSet(this, _analyzeMemoryLeaks, false);
    __privateSet(this, _checkSanity, false);
    this.performance = {};
    this.events = typeof EventTarget !== "undefined" ? new EventTarget() : void 0;
    this.models = new Models(this);
    init2();
    this.result = empty();
    this.process = { tensor: null, canvas: null };
    this.faceTriangulation = triangulation;
    this.faceUVMap = uvmap;
    validateModel(this, null, "");
    this.emit("create");
    if (this.config.debug || this.env.browser) log(`version: ${this.version}`);
    if (this.config.debug) log(`tfjs version: ${this.tf.version["tfjs-core"]}`);
    const envTemp = JSON.parse(JSON.stringify(this.env));
    delete envTemp.kernels;
    delete envTemp.initial;
    delete envTemp.perfadd;
    if (this.config.debug) log("environment:", envTemp);
  }
  /** Reset configuration to default values */
  reset() {
    const currentBackend = this.config.backend;
    this.config = JSON.parse(JSON.stringify(config));
    this.config.backend = currentBackend;
    reset();
    env.initial = true;
  }
  /** Validate current configuration schema */
  validate(userConfig) {
    const msgs = validate(config, userConfig || this.config);
    if (msgs.length === 0) this.config = mergeDeep(this.config, userConfig);
    return msgs;
  }
  /** Utility wrapper for performance.now() */
  now() {
    return now();
  }
  /** Process input as return canvas and tensor
   *
   * @param input - any input {@link Input}
   * @param getTensor - should image processing also return tensor or just canvas
   * Returns object with `tensor` and `canvas`
   */
  image(input, getTensor = false) {
    return process2(input, this.config, getTensor);
  }
  /** Segmentation method takes any input and returns RGBA tensor
   * Note: Segmentation is not triggered as part of detect process
   *
   * @param input - {@link Input}
   * Returns tensor which contains image data in RGBA format
   */
  async segmentation(input, userConfig) {
    var _a, _b, _c2;
    if (userConfig) this.config = mergeDeep(this.config, userConfig);
    if (!this.config.segmentation.enabled) return null;
    const processed = await process2(input, this.config);
    if (!processed.tensor) return null;
    let tensor2 = null;
    if ((_a = this.config.segmentation.modelPath) == null ? void 0 : _a.includes("rvm")) tensor2 = await predict20(processed.tensor, this.config);
    if ((_b = this.config.segmentation.modelPath) == null ? void 0 : _b.includes("meet")) tensor2 = await predict16(processed.tensor, this.config);
    if ((_c2 = this.config.segmentation.modelPath) == null ? void 0 : _c2.includes("selfie")) tensor2 = await predict21(processed.tensor, this.config);
    Ot(processed.tensor);
    return tensor2;
  }
  /** Compare two input tensors for pixel similarity
   * - use `human.image` to process any valid input and get a tensor that can be used for compare
   * - when passing manually generated tensors:
   *  - both input tensors must be in format [1, height, width, 3]
   *  - if resolution of tensors does not match, second tensor will be resized to match resolution of the first tensor
   * - return value is pixel similarity score normalized by input resolution and rgb channels
  */
  compare(firstImageTensor, secondImageTensor) {
    return compare(this.config, firstImageTensor, secondImageTensor);
  }
  /** Explicit backend initialization
   *  - Normally done implicitly during initial load phase
   *  - Call to explictly register and initialize TFJS backend without any other operations
   *  - Use when changing backend during runtime
   */
  async init() {
    await check(this, true);
    await this.tf.ready();
    reset();
  }
  /** Load method preloads all configured models on-demand
   * - Not explicitly required as any required model is load implicitly on it's first run
   *
   * @param userConfig - {@link Config}
  */
  async load(userConfig) {
    this.state = "load";
    const timeStamp = now();
    const count2 = Object.values(this.models.models).filter((model23) => model23).length;
    if (userConfig) this.config = mergeDeep(this.config, userConfig);
    if (this.env.initial) {
      if (!await check(this, false)) log("error: backend check failed");
      await Ime();
      if (this.env.browser) {
        if (this.config.debug) log("configuration:", this.config);
        if (this.config.debug) log("tf flags:", this.tf.ENV.flags);
      }
    }
    await this.models.load(this);
    if (this.env.initial && this.config.debug) log("tf engine state:", this.tf.engine().state.numBytes, "bytes", this.tf.engine().state.numTensors, "tensors");
    this.env.initial = false;
    const loaded = Object.values(this.models.models).filter((model23) => model23).length;
    if (loaded !== count2) {
      this.models.validate();
      this.emit("load");
    }
    const current = Math.trunc(now() - timeStamp);
    if (current > (this.performance.loadModels || 0)) this.performance.loadModels = this.env.perfadd ? (this.performance.loadModels || 0) + current : current;
  }
  /** Runs interpolation using last known result and returns smoothened result
   * Interpolation is based on time since last known result so can be called independently
   *
   * @param result - {@link Result} optional use specific result set to run interpolation on
   * @returns result - {@link Result}
   */
  next(result = this.result) {
    return calc2(result, this.config);
  }
  /** Warmup method pre-initializes all configured models for faster inference
   * - can take significant time on startup
   * - only used for `webgl` and `humangl` backends
   * @param userConfig - {@link Config}
   * @returns result - {@link Result}
  */
  async warmup(userConfig) {
    const t02 = now();
    const res = await warmup(this, userConfig);
    const t12 = now();
    this.performance.warmup = Math.trunc(t12 - t02);
    return res;
  }
  /** Run detect with tensorflow profiling
   * - result object will contain total exeuction time information for top-20 kernels
   * - actual detection object can be accessed via `human.result`
  */
  async profile(input, userConfig) {
    const profile = await this.tf.profile(() => this.detect(input, userConfig));
    const kernels = {};
    let total = 0;
    for (const kernel of profile.kernels) {
      const ms2 = Number(kernel.kernelTimeMs) || 0;
      if (kernels[kernel.name]) kernels[kernel.name] += ms2;
      else kernels[kernel.name] = ms2;
      total += ms2;
    }
    const kernelArr = [];
    Object.entries(kernels).forEach((key) => kernelArr.push({ kernel: key[0], time: key[1], perc: 0 }));
    for (const kernel of kernelArr) {
      kernel.perc = Math.round(1e3 * kernel.time / total) / 1e3;
      kernel.time = Math.round(1e3 * kernel.time) / 1e3;
    }
    kernelArr.sort((a, b) => b.time - a.time);
    kernelArr.length = 20;
    return kernelArr;
  }
  /** Main detection method
   * - Analyze configuration: {@link Config}
   * - Pre-process input: {@link Input}
   * - Run inference for all configured models
   * - Process and return result: {@link Result}
   *
   * @param input - {@link Input}
   * @param userConfig - {@link Config}
   * @returns result - {@link Result}
  */
  async detect(input, userConfig) {
    this.state = "detect";
    return new Promise(async (resolve) => {
      var _a, _b, _c2, _d2, _e, _f2, _g2, _h2, _i2, _j2, _k2, _l2, _m, _n2, _o2, _p2, _q2, _r2, _s2, _t, _u2;
      this.state = "config";
      let timeStamp;
      this.config = mergeDeep(this.config, userConfig);
      this.state = "check";
      const error = __privateGet(this, _sanity).call(this, input);
      if (error) {
        log(error, input);
        this.emit("error");
        resolve(empty(error));
      }
      const timeStart = now();
      await this.load();
      timeStamp = now();
      this.state = "image";
      const img = await process2(input, this.config);
      this.process = img;
      this.performance.inputProcess = this.env.perfadd ? (this.performance.inputProcess || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
      this.analyze("Get Image:");
      if (!img.tensor) {
        if (this.config.debug) log("could not convert input to tensor");
        this.emit("error");
        resolve(empty("could not convert input to tensor"));
        return;
      }
      this.emit("image");
      timeStamp = now();
      this.config.skipAllowed = await skip(this.config, img.tensor);
      this.config.filter.autoBrightness = (this.config.filter.autoBrightness || false) && this.config.skipAllowed;
      if (!this.performance.totalFrames) this.performance.totalFrames = 0;
      if (!this.performance.cachedFrames) this.performance.cachedFrames = 0;
      this.performance.totalFrames++;
      if (this.config.skipAllowed) this.performance.cachedFrames++;
      this.performance.cacheCheck = this.env.perfadd ? (this.performance.cacheCheck || 0) + Math.trunc(now() - timeStamp) : 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) : [];
        this.performance.face = this.env.perfadd ? (this.performance.face || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
      }
      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 ((_a = this.config.body.modelPath) == null ? void 0 : _a.includes("posenet")) bodyRes = this.config.body.enabled ? predict19(img.tensor, bodyConfig) : [];
        else if ((_b = this.config.body.modelPath) == null ? void 0 : _b.includes("blazepose")) bodyRes = this.config.body.enabled ? predict(img.tensor, bodyConfig) : [];
        else if ((_c2 = this.config.body.modelPath) == null ? void 0 : _c2.includes("efficientpose")) bodyRes = this.config.body.enabled ? predict3(img.tensor, bodyConfig) : [];
        else if ((_d2 = this.config.body.modelPath) == null ? void 0 : _d2.includes("movenet")) bodyRes = this.config.body.enabled ? predict17(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 predict19(img.tensor, bodyConfig) : [];
        else if ((_f2 = this.config.body.modelPath) == null ? void 0 : _f2.includes("blazepose")) bodyRes = this.config.body.enabled ? await predict(img.tensor, bodyConfig) : [];
        else if ((_g2 = this.config.body.modelPath) == null ? void 0 : _g2.includes("efficientpose")) bodyRes = this.config.body.enabled ? await predict3(img.tensor, bodyConfig) : [];
        else if ((_h2 = this.config.body.modelPath) == null ? void 0 : _h2.includes("movenet")) bodyRes = this.config.body.enabled ? await predict17(img.tensor, bodyConfig) : [];
        this.performance.body = this.env.perfadd ? (this.performance.body || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
      }
      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 ? predict14(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 ? predict15(img.tensor, handConfig) : [];
        if (this.performance.hand) delete this.performance.hand;
      } else {
        timeStamp = now();
        if ((_n2 = (_m = this.config.hand.detector) == null ? void 0 : _m.modelPath) == null ? void 0 : _n2.includes("handdetect")) handRes = this.config.hand.enabled ? await predict14(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 predict15(img.tensor, handConfig) : [];
        this.performance.hand = this.env.perfadd ? (this.performance.hand || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
      }
      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 ? predict18(img.tensor, this.config) : [];
        else if ((_r2 = this.config.object.modelPath) == null ? void 0 : _r2.includes("centernet")) objectRes = this.config.object.enabled ? predict2(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 predict18(img.tensor, this.config) : [];
        else if ((_t = this.config.object.modelPath) == null ? void 0 : _t.includes("centernet")) objectRes = this.config.object.enabled ? await predict2(img.tensor, this.config) : [];
        this.performance.object = this.env.perfadd ? (this.performance.object || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
      }
      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), ...iris2(faceRes)];
        if (!this.config.async) this.performance.gesture = this.env.perfadd ? (this.performance.gesture || 0) + Math.trunc(now() - timeStamp) : Math.trunc(now() - timeStamp);
        else if (this.performance.gesture) delete this.performance.gesture;
      }
      this.performance.total = this.env.perfadd ? (this.performance.total || 0) + Math.trunc(now() - timeStart) : Math.trunc(now() - timeStart);
      const shape = ((_u2 = this.process.tensor) == null ? void 0 : _u2.shape) || [0, 0, 0, 0];
      this.result = {
        face: faceRes,
        body: bodyRes,
        hand: handRes,
        gesture: gestureRes,
        object: objectRes,
        performance: this.performance,
        canvas: this.process.canvas,
        timestamp: Date.now(),
        error: null,
        width: shape[2],
        height: shape[1],
        get persons() {
          return join2(faceRes, bodyRes, handRes, gestureRes, shape);
        }
      };
      Ot(img.tensor);
      this.emit("detect");
      this.state = "idle";
      resolve(this.result);
    });
  }
  /** Helper function
   * @param ms - sleep time in miliseconds
   */
  async sleep(ms2) {
    return new Promise((resolve) => {
      setTimeout(resolve, ms2);
    });
  }
  /** Continously detect video frames
   * @param element - HTMLVideoElement input
   * @param run - boolean run continously or stop if already running, default true
   * @param delay - number delay detection between frames for number of miliseconds, default 0
   */
  async video(element, run = true, delay = 0) {
    if (run) {
      if (!__privateGet(this, _loops)[element.id]) {
        if (this.config.debug) log("video start", element.id);
        __privateGet(this, _loops)[element.id] = true;
      }
      if (!element.paused && __privateGet(this, _loops)[element.id] && element.readyState >= 2) await this.detect(element);
      if (delay > 0) await this.sleep(delay);
      if (__privateGet(this, _loops)[element.id]) requestAnimationFrame(() => this.video(element, run, delay));
    } else {
      if (this.config.debug) log("video stop", element.id);
      __privateGet(this, _loops)[element.id] = false;
    }
  }
};
_numTensors = new WeakMap();
_analyzeMemoryLeaks = new WeakMap();
_checkSanity = new WeakMap();
_sanity = new WeakMap();
_loops = new WeakMap();
export {
  Env,
  Human,
  Human as default,
  config as defaults,
  draw_exports as draw,
  empty,
  env,
  match_exports as match,
  models_exports2 as models
};
//# sourceMappingURL=human.esm.js.map
