commit 1609abd0d8bb088e364e01c35d577abce43c5692 Author: Araragi Date: Tue Aug 2 22:20:38 2022 -0400 initial commit diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..d85961e --- /dev/null +++ b/.eslintignore @@ -0,0 +1,2 @@ +src/weights.js +main.user.js \ No newline at end of file diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000..08d80e9 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,15 @@ +{ + "env": { + "browser": true, + "es2021": true + }, + "extends": ["standard"], + "parserOptions": { + "ecmaVersion": "latest", + "sourceType": "module" + }, + "rules": { + "no-undef": ["off"], + "no-unused-vars": "off" + } +} diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..67d8009 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.xpi filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8269eae --- /dev/null +++ b/.gitignore @@ -0,0 +1,51 @@ +node_modules +.rollup.cache +*.c +*~ +*.jpg +*.gif +*.exe +*.cs +*.out +*.zip +ext +*.mp4 +*.webm +yarn.lock +out +*.data +ext.js +core.js +rollup.config.js +.vscode/settings.json +key.pem +chrome.pem +1641560780544.png +1642033228102.png +a.png +converted.png +cuck.png +dd.png +f106d2459fc348494ae39e33c0905e885f3fe6b4ae7d1f8dc171ad85b94132b1.png +file.png +index.html +localstorage.html +out.png +rtlt7x.png +test.png +chrome/1449696017588.png +firefox/1449696017588.png +rev/index.html +rev/out.png +1641737123922.png +1449696017588-128.png +a.js +a.py +aa +aa.json +bu.json +efdb47d2f0e04144bbaa-0.235.xpi +efdb47d2f0e04144bbaa-0.245.xpi +build-test.js +dist/test.js +src/pngv4.ts diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..f87a044 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +auto-install-peers=true \ No newline at end of file diff --git a/1449696017588-comp.png b/1449696017588-comp.png new file mode 100644 index 0000000..1720dd2 Binary files /dev/null and b/1449696017588-comp.png differ diff --git a/1449696017588.png b/1449696017588.png new file mode 100644 index 0000000..1bc3a4b Binary files /dev/null and b/1449696017588.png differ diff --git a/842173-2.png b/842173-2.png new file mode 100644 index 0000000..d96eb58 Binary files /dev/null and b/842173-2.png differ diff --git a/JKCS.meta.js b/JKCS.meta.js new file mode 100644 index 0000000..b52ee6c --- /dev/null +++ b/JKCS.meta.js @@ -0,0 +1,11 @@ +// ==UserScript== +// @name Janny Skiller's Captcha Solver +// @namespace /cumg/ +// @match https://boards.4channel.org/* +// @match https://boards.4chan.org/* +// @grant none +// @version 1.1 +// @author /cumg/, formerly AUTOMATIC +// @description The Janny Skillers Captcha Solver of choice +// ==/UserScript== +const _DOMParser = DOMParser diff --git a/JKCS.user.js b/JKCS.user.js new file mode 100644 index 0000000..97877b8 --- /dev/null +++ b/JKCS.user.js @@ -0,0 +1,49315 @@ +// ==UserScript== +// @name Janny Skiller's Captcha Solver +// @namespace /cumg/ +// @match https://boards.4channel.org/* +// @match https://boards.4chan.org/* +// @grant none +// @version 1.1 +// @author /cumg/, formerly AUTOMATIC +// @description The Janny Skillers Captcha Solver of choice +// ==/UserScript== +const _DOMParser = DOMParser; +(() => { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; + }; + var __commonJS = (cb, mod4) => function __require() { + return mod4 || (0, cb[__getOwnPropNames(cb)[0]])((mod4 = { exports: {} }).exports, mod4), mod4.exports; + }; + var __export = (target, all4) => { + for (var name in all4) + __defProp(target, name, { get: all4[name], enumerable: true }); + }; + var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM = (mod4, isNodeMode, target) => (target = mod4 != null ? __create(__getProtoOf(mod4)) : {}, __copyProps( + isNodeMode || !mod4 || !mod4.__esModule ? __defProp(target, "default", { value: mod4, enumerable: true }) : target, + mod4 + )); + + // + var init_define_BUILD_VERSION = __esm({ + ""() { + } + }); + + // node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js + var require_long = __commonJS({ + "node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js"(exports, module) { + init_define_BUILD_VERSION(); + module.exports = Long2; + var wasm = null; + try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([ + 0, + 97, + 115, + 109, + 1, + 0, + 0, + 0, + 1, + 13, + 2, + 96, + 0, + 1, + 127, + 96, + 4, + 127, + 127, + 127, + 127, + 1, + 127, + 3, + 7, + 6, + 0, + 1, + 1, + 1, + 1, + 1, + 6, + 6, + 1, + 127, + 1, + 65, + 0, + 11, + 7, + 50, + 6, + 3, + 109, + 117, + 108, + 0, + 1, + 5, + 100, + 105, + 118, + 95, + 115, + 0, + 2, + 5, + 100, + 105, + 118, + 95, + 117, + 0, + 3, + 5, + 114, + 101, + 109, + 95, + 115, + 0, + 4, + 5, + 114, + 101, + 109, + 95, + 117, + 0, + 5, + 8, + 103, + 101, + 116, + 95, + 104, + 105, + 103, + 104, + 0, + 0, + 10, + 191, + 1, + 6, + 4, + 0, + 35, + 0, + 11, + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 126, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11, + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 127, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11, + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 128, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11, + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 129, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11, + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 130, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11 + ])), {}).exports; + } catch (e) { + } + function Long2(low, high, unsigned) { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + Long2.prototype.__isLong__; + Object.defineProperty(Long2.prototype, "__isLong__", { value: true }); + function isLong(obj) { + return (obj && obj["__isLong__"]) === true; + } + Long2.isLong = isLong; + var INT_CACHE = {}; + var UINT_CACHE = {}; + function fromInt(value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if (cache = 0 <= value && value < 256) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } else { + value |= 0; + if (cache = -128 <= value && value < 128) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } + } + Long2.fromInt = fromInt; + function fromNumber(value, unsigned) { + if (isNaN(value)) + return unsigned ? UZERO : ZERO; + if (unsigned) { + if (value < 0) + return UZERO; + if (value >= TWO_PWR_64_DBL) + return MAX_UNSIGNED_VALUE; + } else { + if (value <= -TWO_PWR_63_DBL) + return MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return MAX_VALUE; + } + if (value < 0) + return fromNumber(-value, unsigned).neg(); + return fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned); + } + Long2.fromNumber = fromNumber; + function fromBits(lowBits, highBits, unsigned) { + return new Long2(lowBits, highBits, unsigned); + } + Long2.fromBits = fromBits; + var pow_dbl = Math.pow; + function fromString(str, unsigned, radix) { + if (str.length === 0) + throw Error("empty string"); + if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity") + return ZERO; + if (typeof unsigned === "number") { + radix = unsigned, unsigned = false; + } else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError("radix"); + var p2; + if ((p2 = str.indexOf("-")) > 0) + throw Error("interior hyphen"); + else if (p2 === 0) { + return fromString(str.substring(1), unsigned, radix).neg(); + } + var radixToPower = fromNumber(pow_dbl(radix, 8)); + var result = ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = fromNumber(pow_dbl(radix, size)); + result = result.mul(power).add(fromNumber(value)); + } else { + result = result.mul(radixToPower); + result = result.add(fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + } + Long2.fromString = fromString; + function fromValue(val, unsigned) { + if (typeof val === "number") + return fromNumber(val, unsigned); + if (typeof val === "string") + return fromString(val, unsigned); + return fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned); + } + Long2.fromValue = fromValue; + var TWO_PWR_16_DBL = 1 << 16; + var TWO_PWR_24_DBL = 1 << 24; + var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; + var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; + var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); + var ZERO = fromInt(0); + Long2.ZERO = ZERO; + var UZERO = fromInt(0, true); + Long2.UZERO = UZERO; + var ONE = fromInt(1); + Long2.ONE = ONE; + var UONE = fromInt(1, true); + Long2.UONE = UONE; + var NEG_ONE = fromInt(-1); + Long2.NEG_ONE = NEG_ONE; + var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false); + Long2.MAX_VALUE = MAX_VALUE; + var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true); + Long2.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; + var MIN_VALUE = fromBits(0, 2147483648 | 0, false); + Long2.MIN_VALUE = MIN_VALUE; + var LongPrototype = Long2.prototype; + LongPrototype.toInt = function toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + }; + LongPrototype.toNumber = function toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + }; + LongPrototype.toString = function toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError("radix"); + if (this.isZero()) + return "0"; + if (this.isNegative()) { + if (this.eq(MIN_VALUE)) { + var radixLong = fromNumber(radix), div3 = this.div(radixLong), rem1 = div3.mul(radixLong).sub(this); + return div3.toString(radix) + rem1.toInt().toString(radix); + } else + return "-" + this.neg().toString(radix); + } + var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this; + var result = ""; + while (true) { + var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) + return digits + result; + else { + while (digits.length < 6) + digits = "0" + digits; + result = "" + digits + result; + } + } + }; + LongPrototype.getHighBits = function getHighBits() { + return this.high; + }; + LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { + return this.high >>> 0; + }; + LongPrototype.getLowBits = function getLowBits() { + return this.low; + }; + LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { + return this.low >>> 0; + }; + LongPrototype.getNumBitsAbs = function getNumBitsAbs() { + if (this.isNegative()) + return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + var val = this.high != 0 ? this.high : this.low; + for (var bit = 31; bit > 0; bit--) + if ((val & 1 << bit) != 0) + break; + return this.high != 0 ? bit + 33 : bit + 1; + }; + LongPrototype.isZero = function isZero() { + return this.high === 0 && this.low === 0; + }; + LongPrototype.eqz = LongPrototype.isZero; + LongPrototype.isNegative = function isNegative() { + return !this.unsigned && this.high < 0; + }; + LongPrototype.isPositive = function isPositive() { + return this.unsigned || this.high >= 0; + }; + LongPrototype.isOdd = function isOdd() { + return (this.low & 1) === 1; + }; + LongPrototype.isEven = function isEven2() { + return (this.low & 1) === 0; + }; + LongPrototype.equals = function equals(other) { + if (!isLong(other)) + other = fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + }; + LongPrototype.eq = LongPrototype.equals; + LongPrototype.notEquals = function notEquals(other) { + return !this.eq(other); + }; + LongPrototype.neq = LongPrototype.notEquals; + LongPrototype.ne = LongPrototype.notEquals; + LongPrototype.lessThan = function lessThan(other) { + return this.comp(other) < 0; + }; + LongPrototype.lt = LongPrototype.lessThan; + LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { + return this.comp(other) <= 0; + }; + LongPrototype.lte = LongPrototype.lessThanOrEqual; + LongPrototype.le = LongPrototype.lessThanOrEqual; + LongPrototype.greaterThan = function greaterThan(other) { + return this.comp(other) > 0; + }; + LongPrototype.gt = LongPrototype.greaterThan; + LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { + return this.comp(other) >= 0; + }; + LongPrototype.gte = LongPrototype.greaterThanOrEqual; + LongPrototype.ge = LongPrototype.greaterThanOrEqual; + LongPrototype.compare = function compare(other) { + if (!isLong(other)) + other = fromValue(other); + if (this.eq(other)) + return 0; + var thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1; + }; + LongPrototype.comp = LongPrototype.compare; + LongPrototype.negate = function negate() { + if (!this.unsigned && this.eq(MIN_VALUE)) + return MIN_VALUE; + return this.not().add(ONE); + }; + LongPrototype.neg = LongPrototype.negate; + LongPrototype.add = function add4(addend) { + if (!isLong(addend)) + addend = fromValue(addend); + var a48 = this.high >>> 16; + var a32 = this.high & 65535; + var a16 = this.low >>> 16; + var a00 = this.low & 65535; + var b48 = addend.high >>> 16; + var b32 = addend.high & 65535; + var b16 = addend.low >>> 16; + var b00 = addend.low & 65535; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 65535; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 65535; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 65535; + c48 += a48 + b48; + c48 &= 65535; + return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); + }; + LongPrototype.subtract = function subtract(subtrahend) { + if (!isLong(subtrahend)) + subtrahend = fromValue(subtrahend); + return this.add(subtrahend.neg()); + }; + LongPrototype.sub = LongPrototype.subtract; + LongPrototype.multiply = function multiply3(multiplier) { + if (this.isZero()) + return ZERO; + if (!isLong(multiplier)) + multiplier = fromValue(multiplier); + if (wasm) { + var low = wasm.mul( + this.low, + this.high, + multiplier.low, + multiplier.high + ); + return fromBits(low, wasm.get_high(), this.unsigned); + } + if (multiplier.isZero()) + return ZERO; + if (this.eq(MIN_VALUE)) + return multiplier.isOdd() ? MIN_VALUE : ZERO; + if (multiplier.eq(MIN_VALUE)) + return this.isOdd() ? MIN_VALUE : ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) + return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + var a48 = this.high >>> 16; + var a32 = this.high & 65535; + var a16 = this.low >>> 16; + var a00 = this.low & 65535; + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 65535; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 65535; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 65535; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 65535; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 65535; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 65535; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 65535; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 65535; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 65535; + return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); + }; + LongPrototype.mul = LongPrototype.multiply; + LongPrototype.divide = function divide(divisor) { + if (!isLong(divisor)) + divisor = fromValue(divisor); + if (divisor.isZero()) + throw Error("division by zero"); + if (wasm) { + if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) { + return this; + } + var low = (this.unsigned ? wasm.div_u : wasm.div_s)( + this.low, + this.high, + divisor.low, + divisor.high + ); + return fromBits(low, wasm.get_high(), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? UZERO : ZERO; + var approx, rem, res; + if (!this.unsigned) { + if (this.eq(MIN_VALUE)) { + if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) + return MIN_VALUE; + else if (divisor.eq(MIN_VALUE)) + return ONE; + else { + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(ZERO)) { + return divisor.isNegative() ? ONE : NEG_ONE; + } else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } else if (divisor.eq(MIN_VALUE)) + return this.unsigned ? UZERO : ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = ZERO; + } else { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return UZERO; + if (divisor.gt(this.shru(1))) + return UONE; + res = UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + var log22 = Math.ceil(Math.log(approx) / Math.LN2), delta = log22 <= 48 ? 1 : pow_dbl(2, log22 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + if (approxRes.isZero()) + approxRes = ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + }; + LongPrototype.div = LongPrototype.divide; + LongPrototype.modulo = function modulo(divisor) { + if (!isLong(divisor)) + divisor = fromValue(divisor); + if (wasm) { + var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)( + this.low, + this.high, + divisor.low, + divisor.high + ); + return fromBits(low, wasm.get_high(), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + }; + LongPrototype.mod = LongPrototype.modulo; + LongPrototype.rem = LongPrototype.modulo; + LongPrototype.not = function not() { + return fromBits(~this.low, ~this.high, this.unsigned); + }; + LongPrototype.and = function and(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low & other.low, this.high & other.high, this.unsigned); + }; + LongPrototype.or = function or(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low | other.low, this.high | other.high, this.unsigned); + }; + LongPrototype.xor = function xor(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + }; + LongPrototype.shiftLeft = function shiftLeft(numBits) { + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned); + else + return fromBits(0, this.low << numBits - 32, this.unsigned); + }; + LongPrototype.shl = LongPrototype.shiftLeft; + LongPrototype.shiftRight = function shiftRight(numBits) { + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned); + else + return fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned); + }; + LongPrototype.shr = LongPrototype.shiftRight; + LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { + if (isLong(numBits)) + numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) + return this; + else { + var high = this.high; + if (numBits < 32) { + var low = this.low; + return fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned); + } else if (numBits === 32) + return fromBits(high, 0, this.unsigned); + else + return fromBits(high >>> numBits - 32, 0, this.unsigned); + } + }; + LongPrototype.shru = LongPrototype.shiftRightUnsigned; + LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; + LongPrototype.toSigned = function toSigned() { + if (!this.unsigned) + return this; + return fromBits(this.low, this.high, false); + }; + LongPrototype.toUnsigned = function toUnsigned() { + if (this.unsigned) + return this; + return fromBits(this.low, this.high, true); + }; + LongPrototype.toBytes = function toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + }; + LongPrototype.toBytesLE = function toBytesLE() { + var hi = this.high, lo = this.low; + return [ + lo & 255, + lo >>> 8 & 255, + lo >>> 16 & 255, + lo >>> 24, + hi & 255, + hi >>> 8 & 255, + hi >>> 16 & 255, + hi >>> 24 + ]; + }; + LongPrototype.toBytesBE = function toBytesBE() { + var hi = this.high, lo = this.low; + return [ + hi >>> 24, + hi >>> 16 & 255, + hi >>> 8 & 255, + hi & 255, + lo >>> 24, + lo >>> 16 & 255, + lo >>> 8 & 255, + lo & 255 + ]; + }; + Long2.fromBytes = function fromBytes(bytes, unsigned, le) { + return le ? Long2.fromBytesLE(bytes, unsigned) : Long2.fromBytesBE(bytes, unsigned); + }; + Long2.fromBytesLE = function fromBytesLE(bytes, unsigned) { + return new Long2( + bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, + bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, + unsigned + ); + }; + Long2.fromBytesBE = function fromBytesBE(bytes, unsigned) { + return new Long2( + bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], + bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], + unsigned + ); + }; + } + }); + + // (disabled):node_modules/.pnpm/node-fetch@2.6.7/node_modules/node-fetch/browser.js + var require_browser = __commonJS({ + "(disabled):node_modules/.pnpm/node-fetch@2.6.7/node_modules/node-fetch/browser.js"() { + init_define_BUILD_VERSION(); + } + }); + + // (disabled):util + var require_util = __commonJS({ + "(disabled):util"() { + init_define_BUILD_VERSION(); + } + }); + + // node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js + var require_alea = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js"(exports, module) { + init_define_BUILD_VERSION(); + (function(global2, module2, define2) { + function Alea(seed) { + var me = this, mash = Mash(); + me.next = function() { + var t = 2091639 * me.s0 + me.c * 23283064365386963e-26; + me.s0 = me.s1; + me.s1 = me.s2; + return me.s2 = t - (me.c = t | 0); + }; + me.c = 1; + me.s0 = mash(" "); + me.s1 = mash(" "); + me.s2 = mash(" "); + me.s0 -= mash(seed); + if (me.s0 < 0) { + me.s0 += 1; + } + me.s1 -= mash(seed); + if (me.s1 < 0) { + me.s1 += 1; + } + me.s2 -= mash(seed); + if (me.s2 < 0) { + me.s2 += 1; + } + mash = null; + } + function copy(f, t) { + t.c = f.c; + t.s0 = f.s0; + t.s1 = f.s1; + t.s2 = f.s2; + return t; + } + function impl(seed, opts) { + var xg = new Alea(seed), state = opts && opts.state, prng = xg.next; + prng.int32 = function() { + return xg.next() * 4294967296 | 0; + }; + prng.double = function() { + return prng() + (prng() * 2097152 | 0) * 11102230246251565e-32; + }; + prng.quick = prng; + if (state) { + if (typeof state == "object") + copy(state, xg); + prng.state = function() { + return copy(xg, {}); + }; + } + return prng; + } + function Mash() { + var n = 4022871197; + var mash = function(data) { + data = String(data); + for (var i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + var h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 4294967296; + } + return (n >>> 0) * 23283064365386963e-26; + }; + return mash; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.alea = impl; + } + })( + exports, + typeof module == "object" && module, + typeof define == "function" && define + ); + } + }); + + // node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js + var require_xor128 = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(exports, module) { + init_define_BUILD_VERSION(); + (function(global2, module2, define2) { + function XorGen(seed) { + var me = this, strseed = ""; + me.x = 0; + me.y = 0; + me.z = 0; + me.w = 0; + me.next = function() { + var t = me.x ^ me.x << 11; + me.x = me.y; + me.y = me.z; + me.z = me.w; + return me.w ^= me.w >>> 19 ^ t ^ t >>> 8; + }; + if (seed === (seed | 0)) { + me.x = seed; + } else { + strseed += seed; + } + for (var k = 0; k < strseed.length + 64; k++) { + me.x ^= strseed.charCodeAt(k) | 0; + me.next(); + } + } + function copy(f, t) { + t.x = f.x; + t.y = f.y; + t.z = f.z; + t.w = f.w; + return t; + } + function impl(seed, opts) { + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof state == "object") + copy(state, xg); + prng.state = function() { + return copy(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.xor128 = impl; + } + })( + exports, + typeof module == "object" && module, + typeof define == "function" && define + ); + } + }); + + // node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js + var require_xorwow = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(exports, module) { + init_define_BUILD_VERSION(); + (function(global2, module2, define2) { + function XorGen(seed) { + var me = this, strseed = ""; + me.next = function() { + var t = me.x ^ me.x >>> 2; + me.x = me.y; + me.y = me.z; + me.z = me.w; + me.w = me.v; + return (me.d = me.d + 362437 | 0) + (me.v = me.v ^ me.v << 4 ^ (t ^ t << 1)) | 0; + }; + me.x = 0; + me.y = 0; + me.z = 0; + me.w = 0; + me.v = 0; + if (seed === (seed | 0)) { + me.x = seed; + } else { + strseed += seed; + } + for (var k = 0; k < strseed.length + 64; k++) { + me.x ^= strseed.charCodeAt(k) | 0; + if (k == strseed.length) { + me.d = me.x << 10 ^ me.x >>> 4; + } + me.next(); + } + } + function copy(f, t) { + t.x = f.x; + t.y = f.y; + t.z = f.z; + t.w = f.w; + t.v = f.v; + t.d = f.d; + return t; + } + function impl(seed, opts) { + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof state == "object") + copy(state, xg); + prng.state = function() { + return copy(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.xorwow = impl; + } + })( + exports, + typeof module == "object" && module, + typeof define == "function" && define + ); + } + }); + + // node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js + var require_xorshift7 = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(exports, module) { + init_define_BUILD_VERSION(); + (function(global2, module2, define2) { + function XorGen(seed) { + var me = this; + me.next = function() { + var X = me.x, i = me.i, t, v, w; + t = X[i]; + t ^= t >>> 7; + v = t ^ t << 24; + t = X[i + 1 & 7]; + v ^= t ^ t >>> 10; + t = X[i + 3 & 7]; + v ^= t ^ t >>> 3; + t = X[i + 4 & 7]; + v ^= t ^ t << 7; + t = X[i + 7 & 7]; + t = t ^ t << 13; + v ^= t ^ t << 9; + X[i] = v; + me.i = i + 1 & 7; + return v; + }; + function init(me2, seed2) { + var j, w, X = []; + if (seed2 === (seed2 | 0)) { + w = X[0] = seed2; + } else { + seed2 = "" + seed2; + for (j = 0; j < seed2.length; ++j) { + X[j & 7] = X[j & 7] << 15 ^ seed2.charCodeAt(j) + X[j + 1 & 7] << 13; + } + } + while (X.length < 8) + X.push(0); + for (j = 0; j < 8 && X[j] === 0; ++j) + ; + if (j == 8) + w = X[7] = -1; + else + w = X[j]; + me2.x = X; + me2.i = 0; + for (j = 256; j > 0; --j) { + me2.next(); + } + } + init(me, seed); + } + function copy(f, t) { + t.x = f.x.slice(); + t.i = f.i; + return t; + } + function impl(seed, opts) { + if (seed == null) + seed = +new Date(); + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (state.x) + copy(state, xg); + prng.state = function() { + return copy(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.xorshift7 = impl; + } + })( + exports, + typeof module == "object" && module, + typeof define == "function" && define + ); + } + }); + + // node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js + var require_xor4096 = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(exports, module) { + init_define_BUILD_VERSION(); + (function(global2, module2, define2) { + function XorGen(seed) { + var me = this; + me.next = function() { + var w = me.w, X = me.X, i = me.i, t, v; + me.w = w = w + 1640531527 | 0; + v = X[i + 34 & 127]; + t = X[i = i + 1 & 127]; + v ^= v << 13; + t ^= t << 17; + v ^= v >>> 15; + t ^= t >>> 12; + v = X[i] = v ^ t; + me.i = i; + return v + (w ^ w >>> 16) | 0; + }; + function init(me2, seed2) { + var t, v, i, j, w, X = [], limit = 128; + if (seed2 === (seed2 | 0)) { + v = seed2; + seed2 = null; + } else { + seed2 = seed2 + "\0"; + v = 0; + limit = Math.max(limit, seed2.length); + } + for (i = 0, j = -32; j < limit; ++j) { + if (seed2) + v ^= seed2.charCodeAt((j + 32) % seed2.length); + if (j === 0) + w = v; + v ^= v << 10; + v ^= v >>> 15; + v ^= v << 4; + v ^= v >>> 13; + if (j >= 0) { + w = w + 1640531527 | 0; + t = X[j & 127] ^= v + w; + i = 0 == t ? i + 1 : 0; + } + } + if (i >= 128) { + X[(seed2 && seed2.length || 0) & 127] = -1; + } + i = 127; + for (j = 4 * 128; j > 0; --j) { + v = X[i + 34 & 127]; + t = X[i = i + 1 & 127]; + v ^= v << 13; + t ^= t << 17; + v ^= v >>> 15; + t ^= t >>> 12; + X[i] = v ^ t; + } + me2.w = w; + me2.X = X; + me2.i = i; + } + init(me, seed); + } + function copy(f, t) { + t.i = f.i; + t.w = f.w; + t.X = f.X.slice(); + return t; + } + ; + function impl(seed, opts) { + if (seed == null) + seed = +new Date(); + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (state.X) + copy(state, xg); + prng.state = function() { + return copy(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.xor4096 = impl; + } + })( + exports, + typeof module == "object" && module, + typeof define == "function" && define + ); + } + }); + + // node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js + var require_tychei = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(exports, module) { + init_define_BUILD_VERSION(); + (function(global2, module2, define2) { + function XorGen(seed) { + var me = this, strseed = ""; + me.next = function() { + var b = me.b, c = me.c, d = me.d, a = me.a; + b = b << 25 ^ b >>> 7 ^ c; + c = c - d | 0; + d = d << 24 ^ d >>> 8 ^ a; + a = a - b | 0; + me.b = b = b << 20 ^ b >>> 12 ^ c; + me.c = c = c - d | 0; + me.d = d << 16 ^ c >>> 16 ^ a; + return me.a = a - b | 0; + }; + me.a = 0; + me.b = 0; + me.c = 2654435769 | 0; + me.d = 1367130551; + if (seed === Math.floor(seed)) { + me.a = seed / 4294967296 | 0; + me.b = seed | 0; + } else { + strseed += seed; + } + for (var k = 0; k < strseed.length + 20; k++) { + me.b ^= strseed.charCodeAt(k) | 0; + me.next(); + } + } + function copy(f, t) { + t.a = f.a; + t.b = f.b; + t.c = f.c; + t.d = f.d; + return t; + } + ; + function impl(seed, opts) { + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof state == "object") + copy(state, xg); + prng.state = function() { + return copy(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.tychei = impl; + } + })( + exports, + typeof module == "object" && module, + typeof define == "function" && define + ); + } + }); + + // (disabled):crypto + var require_crypto = __commonJS({ + "(disabled):crypto"() { + init_define_BUILD_VERSION(); + } + }); + + // node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js + var require_seedrandom = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js"(exports, module) { + init_define_BUILD_VERSION(); + (function(global2, pool3, math) { + var width = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask = width - 1, nodecrypto; + function seedrandom5(seed, options, callback) { + var key = []; + options = options == true ? { entropy: true } : options || {}; + var shortseed = mixkey(flatten3( + options.entropy ? [seed, tostring(pool3)] : seed == null ? autoseed() : seed, + 3 + ), key); + var arc4 = new ARC4(key); + var prng = function() { + var n = arc4.g(chunks), d = startdenom, x = 0; + while (n < significance) { + n = (n + x) * width; + d *= width; + x = arc4.g(1); + } + while (n >= overflow) { + n /= 2; + d /= 2; + x >>>= 1; + } + return (n + x) / d; + }; + prng.int32 = function() { + return arc4.g(4) | 0; + }; + prng.quick = function() { + return arc4.g(4) / 4294967296; + }; + prng.double = prng; + mixkey(tostring(arc4.S), pool3); + return (options.pass || callback || function(prng2, seed2, is_math_call, state) { + if (state) { + if (state.S) { + copy(state, arc4); + } + prng2.state = function() { + return copy(arc4, {}); + }; + } + if (is_math_call) { + math[rngname] = prng2; + return seed2; + } else + return prng2; + })( + prng, + shortseed, + "global" in options ? options.global : this == math, + options.state + ); + } + function ARC4(key) { + var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; + if (!keylen) { + key = [keylen++]; + } + while (i < width) { + s[i] = i++; + } + for (i = 0; i < width; i++) { + s[i] = s[j = mask & j + key[i % keylen] + (t = s[i])]; + s[j] = t; + } + (me.g = function(count2) { + var t2, r = 0, i2 = me.i, j2 = me.j, s2 = me.S; + while (count2--) { + t2 = s2[i2 = mask & i2 + 1]; + r = r * width + s2[mask & (s2[i2] = s2[j2 = mask & j2 + t2]) + (s2[j2] = t2)]; + } + me.i = i2; + me.j = j2; + return r; + })(width); + } + function copy(f, t) { + t.i = f.i; + t.j = f.j; + t.S = f.S.slice(); + return t; + } + ; + function flatten3(obj, depth) { + var result = [], typ = typeof obj, prop; + if (depth && typ == "object") { + for (prop in obj) { + try { + result.push(flatten3(obj[prop], depth - 1)); + } catch (e) { + } + } + } + return result.length ? result : typ == "string" ? obj : obj + "\0"; + } + function mixkey(seed, key) { + var stringseed = seed + "", smear, j = 0; + while (j < stringseed.length) { + key[mask & j] = mask & (smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++); + } + return tostring(key); + } + function autoseed() { + try { + var out; + if (nodecrypto && (out = nodecrypto.randomBytes)) { + out = out(width); + } else { + out = new Uint8Array(width); + (global2.crypto || global2.msCrypto).getRandomValues(out); + } + return tostring(out); + } catch (e) { + var browser = global2.navigator, plugins = browser && browser.plugins; + return [+new Date(), global2, plugins, global2.screen, tostring(pool3)]; + } + } + function tostring(a) { + return String.fromCharCode.apply(0, a); + } + mixkey(math.random(), pool3); + if (typeof module == "object" && module.exports) { + module.exports = seedrandom5; + try { + nodecrypto = require_crypto(); + } catch (ex) { + } + } else if (typeof define == "function" && define.amd) { + define(function() { + return seedrandom5; + }); + } else { + math["seed" + rngname] = seedrandom5; + } + })( + typeof self !== "undefined" ? self : exports, + [], + Math + ); + } + }); + + // node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/index.js + var require_seedrandom2 = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/index.js"(exports, module) { + init_define_BUILD_VERSION(); + var alea5 = require_alea(); + var xor128 = require_xor128(); + var xorwow = require_xorwow(); + var xorshift7 = require_xorshift7(); + var xor4096 = require_xor4096(); + var tychei = require_tychei(); + var sr = require_seedrandom(); + sr.alea = alea5; + sr.xor128 = xor128; + sr.xorwow = xorwow; + sr.xorshift7 = xorshift7; + sr.xor4096 = xor4096; + sr.tychei = tychei; + module.exports = sr; + } + }); + + // (disabled):node_modules/.pnpm/string_decoder@1.3.0/node_modules/string_decoder/lib/string_decoder.js + var require_string_decoder = __commonJS({ + "(disabled):node_modules/.pnpm/string_decoder@1.3.0/node_modules/string_decoder/lib/string_decoder.js"() { + init_define_BUILD_VERSION(); + } + }); + + // src/main.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs@3.19.0_seedrandom@3.0.5/node_modules/@tensorflow/tfjs/dist/index.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/index.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/base_side_effects.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/engine.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/backends/backend.js + init_define_BUILD_VERSION(); + var EPSILON_FLOAT32 = 1e-7; + var EPSILON_FLOAT16 = 1e-4; + var DataStorage = class { + constructor(backend2, dataMover) { + this.backend = backend2; + this.dataMover = dataMover; + this.data = /* @__PURE__ */ new WeakMap(); + this.dataIdsCount = 0; + } + get(dataId) { + if (!this.data.has(dataId)) { + this.dataMover.moveData(this.backend, dataId); + } + return this.data.get(dataId); + } + set(dataId, value) { + this.dataIdsCount++; + this.data.set(dataId, value); + } + has(dataId) { + return this.data.has(dataId); + } + delete(dataId) { + this.dataIdsCount--; + return this.data.delete(dataId); + } + numDataIds() { + return this.dataIdsCount; + } + }; + var KernelBackend = class { + refCount(dataId) { + return notYetImplemented("refCount"); + } + incRef(dataId) { + return notYetImplemented("incRef"); + } + timerAvailable() { + return true; + } + time(f) { + return notYetImplemented("time"); + } + read(dataId) { + return notYetImplemented("read"); + } + readSync(dataId) { + return notYetImplemented("readSync"); + } + readToGPU(dataId, options) { + return notYetImplemented("readToGPU"); + } + numDataIds() { + return notYetImplemented("numDataIds"); + } + disposeData(dataId, force) { + return notYetImplemented("disposeData"); + } + write(values, shape, dtype) { + return notYetImplemented("write"); + } + move(dataId, values, shape, dtype, refCount) { + return notYetImplemented("move"); + } + memory() { + return notYetImplemented("memory"); + } + floatPrecision() { + return notYetImplemented("floatPrecision"); + } + epsilon() { + return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16; + } + dispose() { + return notYetImplemented("dispose"); + } + }; + function notYetImplemented(kernelName) { + throw new Error(`'${kernelName}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/environment.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/util_base.js + init_define_BUILD_VERSION(); + function shuffle(array2) { + let counter = array2.length; + let index = 0; + while (counter > 0) { + index = Math.random() * counter | 0; + counter--; + swap(array2, counter, index); + } + } + function shuffleCombo(array2, array22) { + if (array2.length !== array22.length) { + throw new Error(`Array sizes must match to be shuffled together First array length was ${array2.length}Second array length was ${array22.length}`); + } + let counter = array2.length; + let index = 0; + while (counter > 0) { + index = Math.random() * counter | 0; + counter--; + swap(array2, counter, index); + swap(array22, counter, index); + } + } + function clamp(min5, x, max5) { + return Math.max(min5, Math.min(x, max5)); + } + function nearestLargerEven(val) { + return val % 2 === 0 ? val : val + 1; + } + function swap(object, left, right) { + const temp = object[left]; + object[left] = object[right]; + object[right] = temp; + } + function sum(arr) { + let sum5 = 0; + for (let i = 0; i < arr.length; i++) { + sum5 += arr[i]; + } + return sum5; + } + function randUniform(a, b) { + const r = Math.random(); + return b * r + (1 - r) * a; + } + function distSquared(a, b) { + let result = 0; + for (let i = 0; i < a.length; i++) { + const diff = Number(a[i]) - Number(b[i]); + result += diff * diff; + } + return result; + } + function assert(expr, msg) { + if (!expr) { + throw new Error(typeof msg === "string" ? msg : msg()); + } + } + function assertShapesMatch(shapeA, shapeB, errorMessagePrefix = "") { + assert(arraysEqual(shapeA, shapeB), () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`); + } + function assertNonNull(a) { + assert(a != null, () => `The input to the tensor constructor must be a non-null value.`); + } + function flatten(arr, result = [], skipTypedArray = false) { + if (result == null) { + result = []; + } + if (Array.isArray(arr) || isTypedArray(arr) && !skipTypedArray) { + for (let i = 0; i < arr.length; ++i) { + flatten(arr[i], result, skipTypedArray); + } + } else { + result.push(arr); + } + return result; + } + function sizeFromShape(shape) { + if (shape.length === 0) { + return 1; + } + let size = shape[0]; + for (let i = 1; i < shape.length; i++) { + size *= shape[i]; + } + return size; + } + function isScalarShape(shape) { + return shape.length === 0; + } + function arraysEqual(n1, n2) { + if (n1 === n2) { + return true; + } + if (n1 == null || n2 == null) { + return false; + } + if (n1.length !== n2.length) { + return false; + } + for (let i = 0; i < n1.length; i++) { + if (n1[i] !== n2[i]) { + return false; + } + } + return true; + } + function isInt(a) { + return a % 1 === 0; + } + function tanh(x) { + if (Math.tanh != null) { + return Math.tanh(x); + } + if (x === Infinity) { + return 1; + } else if (x === -Infinity) { + return -1; + } else { + const e2x = Math.exp(2 * x); + return (e2x - 1) / (e2x + 1); + } + } + function sizeToSquarishShape(size) { + const width = Math.ceil(Math.sqrt(size)); + return [width, Math.ceil(size / width)]; + } + function createShuffledIndices(n) { + const shuffledIndices = new Uint32Array(n); + for (let i = 0; i < n; ++i) { + shuffledIndices[i] = i; + } + shuffle(shuffledIndices); + return shuffledIndices; + } + function rightPad(a, size) { + if (size <= a.length) { + return a; + } + return a + " ".repeat(size - a.length); + } + function repeatedTry(checkFn, delayFn = (counter) => 0, maxCounter) { + return new Promise((resolve, reject) => { + let tryCount = 0; + const tryFn = () => { + if (checkFn()) { + resolve(); + return; + } + tryCount++; + const nextBackoff = delayFn(tryCount); + if (maxCounter != null && tryCount >= maxCounter) { + reject(); + return; + } + setTimeout(tryFn, nextBackoff); + }; + tryFn(); + }); + } + function inferFromImplicitShape(shape, size) { + let shapeProd = 1; + let implicitIdx = -1; + for (let i = 0; i < shape.length; ++i) { + if (shape[i] >= 0) { + shapeProd *= shape[i]; + } else if (shape[i] === -1) { + if (implicitIdx !== -1) { + throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${implicitIdx} and dim ${i}`); + } + implicitIdx = i; + } else if (shape[i] < 0) { + throw Error(`Shapes can not be < 0. Found ${shape[i]} at dim ${i}`); + } + } + if (implicitIdx === -1) { + if (size > 0 && size !== shapeProd) { + throw Error(`Size(${size}) must match the product of shape ${shape}`); + } + return shape; + } + if (shapeProd === 0) { + throw Error(`Cannot infer the missing size in [${shape}] when there are 0 elements`); + } + if (size % shapeProd !== 0) { + throw Error(`The implicit shape can't be a fractional number. Got ${size} / ${shapeProd}`); + } + const newShape = shape.slice(); + newShape[implicitIdx] = size / shapeProd; + return newShape; + } + function parseAxisParam(axis, shape) { + const rank = shape.length; + axis = axis == null ? shape.map((s, i) => i) : [].concat(axis); + assert(axis.every((ax) => ax >= -rank && ax < rank), () => `All values in axis param must be in range [-${rank}, ${rank}) but got axis ${axis}`); + assert(axis.every((ax) => isInt(ax)), () => `All values in axis param must be integers but got axis ${axis}`); + return axis.map((a) => a < 0 ? rank + a : a); + } + function squeezeShape(shape, axis) { + const newShape = []; + const keptDims = []; + const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0; + const axes = axis == null || isEmptyArray ? null : parseAxisParam(axis, shape).sort(); + let j = 0; + for (let i = 0; i < shape.length; ++i) { + if (axes != null) { + if (axes[j] === i && shape[i] !== 1) { + throw new Error(`Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`); + } + if ((axes[j] == null || axes[j] > i) && shape[i] === 1) { + newShape.push(shape[i]); + keptDims.push(i); + } + if (axes[j] <= i) { + j++; + } + } + if (shape[i] !== 1) { + newShape.push(shape[i]); + keptDims.push(i); + } + } + return { newShape, keptDims }; + } + function getTypedArrayFromDType(dtype, size) { + let values = null; + if (dtype == null || dtype === "float32") { + values = new Float32Array(size); + } else if (dtype === "int32") { + values = new Int32Array(size); + } else if (dtype === "bool") { + values = new Uint8Array(size); + } else { + throw new Error(`Unknown data type ${dtype}`); + } + return values; + } + function getArrayFromDType(dtype, size) { + let values = null; + if (dtype == null || dtype === "float32") { + values = new Float32Array(size); + } else if (dtype === "int32") { + values = new Int32Array(size); + } else if (dtype === "bool") { + values = new Uint8Array(size); + } else if (dtype === "string") { + values = new Array(size); + } else { + throw new Error(`Unknown data type ${dtype}`); + } + return values; + } + function checkConversionForErrors(vals, dtype) { + for (let i = 0; i < vals.length; i++) { + const num = vals[i]; + if (isNaN(num) || !isFinite(num)) { + throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`); + } + } + } + function isValidDtype(dtype) { + return dtype === "bool" || dtype === "complex64" || dtype === "float32" || dtype === "int32" || dtype === "string"; + } + function hasEncodingLoss(oldType, newType) { + if (newType === "complex64") { + return false; + } + if (newType === "float32" && oldType !== "complex64") { + return false; + } + if (newType === "int32" && oldType !== "float32" && oldType !== "complex64") { + return false; + } + if (newType === "bool" && oldType === "bool") { + return false; + } + return true; + } + function isTypedArray(a) { + return a instanceof Float32Array || a instanceof Int32Array || a instanceof Uint8Array || a instanceof Uint8ClampedArray; + } + function bytesPerElement(dtype) { + if (dtype === "float32" || dtype === "int32") { + return 4; + } else if (dtype === "complex64") { + return 8; + } else if (dtype === "bool") { + return 1; + } else { + throw new Error(`Unknown dtype ${dtype}`); + } + } + function bytesFromStringArray(arr) { + if (arr == null) { + return 0; + } + let bytes = 0; + arr.forEach((x) => bytes += x.length); + return bytes; + } + function isString(value) { + return typeof value === "string" || value instanceof String; + } + function isBoolean(value) { + return typeof value === "boolean"; + } + function isNumber(value) { + return typeof value === "number"; + } + function inferDtype(values) { + if (Array.isArray(values)) { + return inferDtype(values[0]); + } + if (values instanceof Float32Array) { + return "float32"; + } else if (values instanceof Int32Array || values instanceof Uint8Array || values instanceof Uint8ClampedArray) { + return "int32"; + } else if (isNumber(values)) { + return "float32"; + } else if (isString(values)) { + return "string"; + } else if (isBoolean(values)) { + return "bool"; + } + return "float32"; + } + function isFunction(f) { + return !!(f && f.constructor && f.call && f.apply); + } + function nearestDivisor(size, start) { + for (let i = start; i < size; ++i) { + if (size % i === 0) { + return i; + } + } + return size; + } + function computeStrides(shape) { + const rank = shape.length; + if (rank < 2) { + return []; + } + const strides = new Array(rank - 1); + strides[rank - 2] = shape[rank - 1]; + for (let i = rank - 3; i >= 0; --i) { + strides[i] = strides[i + 1] * shape[i + 1]; + } + return strides; + } + function createNestedArray(offset, shape, a, isComplex = false) { + const ret = new Array(); + if (shape.length === 1) { + const d = shape[0] * (isComplex ? 2 : 1); + for (let i = 0; i < d; i++) { + ret[i] = a[offset + i]; + } + } else { + const d = shape[0]; + const rest = shape.slice(1); + const len = rest.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1); + for (let i = 0; i < d; i++) { + ret[i] = createNestedArray(offset + i * len, rest, a, isComplex); + } + } + return ret; + } + function toNestedArray(shape, a, isComplex = false) { + if (shape.length === 0) { + return a[0]; + } + const size = shape.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1); + if (size === 0) { + return []; + } + if (size !== a.length) { + throw new Error(`[${shape}] does not match the input size ${a.length}${isComplex ? " for a complex tensor" : ""}.`); + } + return createNestedArray(0, shape, a, isComplex); + } + function makeOnesTypedArray(size, dtype) { + const array2 = makeZerosTypedArray(size, dtype); + for (let i = 0; i < array2.length; i++) { + array2[i] = 1; + } + return array2; + } + function makeZerosTypedArray(size, dtype) { + if (dtype == null || dtype === "float32" || dtype === "complex64") { + return new Float32Array(size); + } else if (dtype === "int32") { + return new Int32Array(size); + } else if (dtype === "bool") { + return new Uint8Array(size); + } else { + throw new Error(`Unknown data type ${dtype}`); + } + } + function makeZerosNestedTypedArray(shape, dtype) { + const size = shape.reduce((prev, curr) => prev * curr, 1); + if (dtype == null || dtype === "float32") { + return toNestedArray(shape, new Float32Array(size)); + } else if (dtype === "int32") { + return toNestedArray(shape, new Int32Array(size)); + } else if (dtype === "bool") { + return toNestedArray(shape, new Uint8Array(size)); + } else { + throw new Error(`Unknown data type ${dtype}`); + } + } + function assertNonNegativeIntegerDimensions(shape) { + shape.forEach((dimSize) => { + assert(Number.isInteger(dimSize) && dimSize >= 0, () => `Tensor must have a shape comprised of positive integers but got shape [${shape}].`); + }); + } + function locToIndex(locs, rank, strides) { + if (rank === 0) { + return 0; + } else if (rank === 1) { + return locs[0]; + } + let index = locs[locs.length - 1]; + for (let i = 0; i < locs.length - 1; ++i) { + index += strides[i] * locs[i]; + } + return index; + } + function indexToLoc(index, rank, strides) { + if (rank === 0) { + return []; + } else if (rank === 1) { + return [index]; + } + const locs = new Array(rank); + for (let i = 0; i < locs.length - 1; ++i) { + locs[i] = Math.floor(index / strides[i]); + index -= locs[i] * strides[i]; + } + locs[locs.length - 1] = index; + return locs; + } + function isPromise(object) { + return object && object.then && typeof object.then === "function"; + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/environment.js + var TENSORFLOWJS_FLAGS_PREFIX = "tfjsflags"; + var Environment = class { + constructor(global2) { + this.global = global2; + this.flags = {}; + this.flagRegistry = {}; + this.urlFlags = {}; + this.getQueryParams = getQueryParams; + this.populateURLFlags(); + } + setPlatform(platformName, platform) { + if (this.platform != null) { + if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) { + console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${platformName}.`); + } + } + this.platformName = platformName; + this.platform = platform; + } + registerFlag(flagName, evaluationFn, setHook) { + this.flagRegistry[flagName] = { evaluationFn, setHook }; + if (this.urlFlags[flagName] != null) { + const flagValue = this.urlFlags[flagName]; + if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) { + console.warn(`Setting feature override from URL ${flagName}: ${flagValue}.`); + } + this.set(flagName, flagValue); + } + } + async getAsync(flagName) { + if (flagName in this.flags) { + return this.flags[flagName]; + } + this.flags[flagName] = await this.evaluateFlag(flagName); + return this.flags[flagName]; + } + get(flagName) { + if (flagName in this.flags) { + return this.flags[flagName]; + } + const flagValue = this.evaluateFlag(flagName); + if (isPromise(flagValue)) { + throw new Error(`Flag ${flagName} cannot be synchronously evaluated. Please use getAsync() instead.`); + } + this.flags[flagName] = flagValue; + return this.flags[flagName]; + } + getNumber(flagName) { + return this.get(flagName); + } + getBool(flagName) { + return this.get(flagName); + } + getFlags() { + return this.flags; + } + get features() { + return this.flags; + } + set(flagName, value) { + if (this.flagRegistry[flagName] == null) { + throw new Error(`Cannot set flag ${flagName} as it has not been registered.`); + } + this.flags[flagName] = value; + if (this.flagRegistry[flagName].setHook != null) { + this.flagRegistry[flagName].setHook(value); + } + } + evaluateFlag(flagName) { + if (this.flagRegistry[flagName] == null) { + throw new Error(`Cannot evaluate flag '${flagName}': no evaluation function found.`); + } + return this.flagRegistry[flagName].evaluationFn(); + } + setFlags(flags) { + this.flags = Object.assign({}, flags); + } + reset() { + this.flags = {}; + this.urlFlags = {}; + this.populateURLFlags(); + } + populateURLFlags() { + if (typeof this.global === "undefined" || typeof this.global.location === "undefined" || typeof this.global.location.search === "undefined") { + return; + } + const urlParams = this.getQueryParams(this.global.location.search); + if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) { + const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(","); + keyValues.forEach((keyValue) => { + const [key, value] = keyValue.split(":"); + this.urlFlags[key] = parseValue(key, value); + }); + } + } + }; + function getQueryParams(queryString) { + const params = {}; + queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => { + decodeParam(params, t[0], t[1]); + return t.join("="); + }); + return params; + } + function decodeParam(params, name, value) { + params[decodeURIComponent(name)] = decodeURIComponent(value || ""); + } + function parseValue(flagName, value) { + value = value.toLowerCase(); + if (value === "true" || value === "false") { + return value === "true"; + } else if (`${+value}` === value) { + return +value; + } + throw new Error(`Could not parse value flag value ${value} for flag ${flagName}.`); + } + function env() { + return ENV; + } + var ENV = null; + function setEnvironmentGlobal(environment) { + ENV = environment; + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/global_util.js + init_define_BUILD_VERSION(); + var globalNameSpace; + function getGlobalNamespace() { + if (globalNameSpace == null) { + let ns; + if (typeof window !== "undefined") { + ns = window; + } else if (typeof window !== "undefined") { + ns = window; + } else if (typeof process !== "undefined") { + ns = process; + } else if (typeof self !== "undefined") { + ns = self; + } else { + throw new Error("Could not find a global object"); + } + globalNameSpace = ns; + } + return globalNameSpace; + } + function getGlobalMap() { + const ns = getGlobalNamespace(); + if (ns._tfGlobals == null) { + ns._tfGlobals = /* @__PURE__ */ new Map(); + } + return ns._tfGlobals; + } + function getGlobal(key, init) { + const globalMap = getGlobalMap(); + if (globalMap.has(key)) { + return globalMap.get(key); + } else { + const singleton = init(); + globalMap.set(key, singleton); + return globalMap.get(key); + } + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/kernel_names.js + init_define_BUILD_VERSION(); + var Abs = "Abs"; + var Acos = "Acos"; + var Acosh = "Acosh"; + var Add = "Add"; + var AddN = "AddN"; + var All = "All"; + var Any = "Any"; + var ArgMax = "ArgMax"; + var ArgMin = "ArgMin"; + var Asin = "Asin"; + var Asinh = "Asinh"; + var Atan = "Atan"; + var Atanh = "Atanh"; + var Atan2 = "Atan2"; + var AvgPool = "AvgPool"; + var AvgPoolGrad = "AvgPoolGrad"; + var AvgPool3D = "AvgPool3D"; + var AvgPool3DGrad = "AvgPool3DGrad"; + var BatchMatMul = "BatchMatMul"; + var BatchToSpaceND = "BatchToSpaceND"; + var Bincount = "Bincount"; + var BroadcastTo = "BroadcastTo"; + var BroadcastArgs = "BroadcastArgs"; + var Cast = "Cast"; + var Ceil = "Ceil"; + var ClipByValue = "ClipByValue"; + var Complex = "Complex"; + var ComplexAbs = "ComplexAbs"; + var Concat = "Concat"; + var Conv2D = "Conv2D"; + var Conv2DBackpropFilter = "Conv2DBackpropFilter"; + var Conv2DBackpropInput = "Conv2DBackpropInput"; + var Conv3D = "Conv3D"; + var Conv3DBackpropFilterV2 = "Conv3DBackpropFilterV2"; + var Conv3DBackpropInputV2 = "Conv3DBackpropInputV2"; + var Cos = "Cos"; + var Cosh = "Cosh"; + var Cumprod = "Cumprod"; + var Cumsum = "Cumsum"; + var CropAndResize = "CropAndResize"; + var DenseBincount = "DenseBincount"; + var DepthToSpace = "DepthToSpace"; + var DepthwiseConv2dNative = "DepthwiseConv2dNative"; + var DepthwiseConv2dNativeBackpropFilter = "DepthwiseConv2dNativeBackpropFilter"; + var DepthwiseConv2dNativeBackpropInput = "DepthwiseConv2dNativeBackpropInput"; + var Diag = "Diag"; + var Dilation2D = "Dilation2D"; + var Dilation2DBackpropInput = "Dilation2DBackpropInput"; + var Dilation2DBackpropFilter = "Dilation2DBackpropFilter"; + var RealDiv = "RealDiv"; + var Einsum = "Einsum"; + var Elu = "Elu"; + var EluGrad = "EluGrad"; + var Erf = "Erf"; + var Equal = "Equal"; + var Exp = "Exp"; + var ExpandDims = "ExpandDims"; + var Expm1 = "Expm1"; + var FFT = "FFT"; + var Fill = "Fill"; + var FlipLeftRight = "FlipLeftRight"; + var Floor = "Floor"; + var FloorDiv = "FloorDiv"; + var FusedBatchNorm = "FusedBatchNorm"; + var GatherV2 = "GatherV2"; + var GatherNd = "GatherNd"; + var Greater = "Greater"; + var GreaterEqual = "GreaterEqual"; + var Identity = "Identity"; + var IFFT = "IFFT"; + var Imag = "Imag"; + var IsFinite = "IsFinite"; + var IsInf = "IsInf"; + var IsNan = "IsNan"; + var LeakyRelu = "LeakyRelu"; + var Less = "Less"; + var LessEqual = "LessEqual"; + var LinSpace = "LinSpace"; + var Log = "Log"; + var Log1p = "Log1p"; + var LogicalAnd = "LogicalAnd"; + var LogicalNot = "LogicalNot"; + var LogicalOr = "LogicalOr"; + var LogSoftmax = "LogSoftmax"; + var LRN = "LRN"; + var LRNGrad = "LRNGrad"; + var Max = "Max"; + var Maximum = "Maximum"; + var MaxPool = "MaxPool"; + var MaxPoolGrad = "MaxPoolGrad"; + var MaxPool3D = "MaxPool3D"; + var MaxPool3DGrad = "MaxPool3DGrad"; + var MaxPoolWithArgmax = "MaxPoolWithArgmax"; + var Mean = "Mean"; + var Min = "Min"; + var Minimum = "Minimum"; + var MirrorPad = "MirrorPad"; + var Mod = "Mod"; + var Multinomial = "Multinomial"; + var Multiply = "Multiply"; + var Neg = "Neg"; + var NotEqual = "NotEqual"; + var NonMaxSuppressionV3 = "NonMaxSuppressionV3"; + var NonMaxSuppressionV4 = "NonMaxSuppressionV4"; + var NonMaxSuppressionV5 = "NonMaxSuppressionV5"; + var OnesLike = "OnesLike"; + var OneHot = "OneHot"; + var Pack = "Pack"; + var PadV2 = "PadV2"; + var Pow = "Pow"; + var Prelu = "Prelu"; + var Prod = "Prod"; + var Range = "Range"; + var Real = "Real"; + var Reciprocal = "Reciprocal"; + var Relu = "Relu"; + var Reshape = "Reshape"; + var ResizeNearestNeighbor = "ResizeNearestNeighbor"; + var ResizeNearestNeighborGrad = "ResizeNearestNeighborGrad"; + var ResizeBilinear = "ResizeBilinear"; + var ResizeBilinearGrad = "ResizeBilinearGrad"; + var Relu6 = "Relu6"; + var Reverse = "Reverse"; + var Round = "Round"; + var Rsqrt = "Rsqrt"; + var ScatterNd = "ScatterNd"; + var SearchSorted = "SearchSorted"; + var Select = "Select"; + var Selu = "Selu"; + var Slice = "Slice"; + var Sin = "Sin"; + var Sinh = "Sinh"; + var Sign = "Sign"; + var Sigmoid = "Sigmoid"; + var Softplus = "Softplus"; + var Sqrt = "Sqrt"; + var Sum = "Sum"; + var SpaceToBatchND = "SpaceToBatchND"; + var SplitV = "SplitV"; + var Softmax = "Softmax"; + var SparseFillEmptyRows = "SparseFillEmptyRows"; + var SparseReshape = "SparseReshape"; + var SparseSegmentMean = "SparseSegmentMean"; + var SparseSegmentSum = "SparseSegmentSum"; + var SparseToDense = "SparseToDense"; + var SquaredDifference = "SquaredDifference"; + var Square = "Square"; + var StridedSlice = "StridedSlice"; + var StringNGrams = "StringNGrams"; + var StringSplit = "StringSplit"; + var StringToHashBucketFast = "StringToHashBucketFast"; + var Sub = "Sub"; + var Tan = "Tan"; + var Tanh = "Tanh"; + var Tile = "Tile"; + var TopK = "TopK"; + var Transform = "Transform"; + var Transpose = "Transpose"; + var Unique = "Unique"; + var Unpack = "Unpack"; + var UnsortedSegmentSum = "UnsortedSegmentSum"; + var ZerosLike = "ZerosLike"; + var Step = "Step"; + var FromPixels = "FromPixels"; + var RotateWithOffset = "RotateWithOffset"; + var _FusedMatMul = "_FusedMatMul"; + var FusedConv2D = "FusedConv2D"; + var FusedDepthwiseConv2D = "FusedDepthwiseConv2D"; + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/kernel_registry.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/log.js + init_define_BUILD_VERSION(); + function warn(...msg) { + if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) { + console.warn(...msg); + } + } + function log(...msg) { + if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) { + console.log(...msg); + } + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/kernel_registry.js + var kernelRegistry = getGlobal("kernelRegistry", () => /* @__PURE__ */ new Map()); + var gradRegistry = getGlobal("gradRegistry", () => /* @__PURE__ */ new Map()); + function getKernel(kernelName, backendName) { + const key = makeKey(kernelName, backendName); + return kernelRegistry.get(key); + } + function getGradient(kernelName) { + return gradRegistry.get(kernelName); + } + function getKernelsForBackend(backendName) { + const it = kernelRegistry.entries(); + const result = []; + while (true) { + const { done, value } = it.next(); + if (done) { + break; + } + const [key, config] = value; + const [backend2] = key.split("_"); + if (backend2 === backendName) { + result.push(config); + } + } + return result; + } + function registerKernel(config) { + const { kernelName, backendName } = config; + const key = makeKey(kernelName, backendName); + if (kernelRegistry.has(key)) { + warn(`The kernel '${kernelName}' for backend '${backendName}' is already registered`); + } + kernelRegistry.set(key, config); + } + function registerGradient(config) { + const { kernelName } = config; + if (gradRegistry.has(kernelName)) { + if (env().getBool("DEBUG")) { + warn(`Overriding the gradient for '${kernelName}'`); + } + } + gradRegistry.set(kernelName, config); + } + function makeKey(kernelName, backendName) { + return `${backendName}_${kernelName}`; + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/profiler.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/util.js + var util_exports = {}; + __export(util_exports, { + arraysEqual: () => arraysEqual, + assert: () => assert, + assertNonNegativeIntegerDimensions: () => assertNonNegativeIntegerDimensions, + assertNonNull: () => assertNonNull, + assertShapesMatch: () => assertShapesMatch, + bytesFromStringArray: () => bytesFromStringArray, + bytesPerElement: () => bytesPerElement, + checkConversionForErrors: () => checkConversionForErrors, + clamp: () => clamp, + computeStrides: () => computeStrides, + createScalarValue: () => createScalarValue, + createShuffledIndices: () => createShuffledIndices, + decodeString: () => decodeString, + distSquared: () => distSquared, + encodeString: () => encodeString, + fetch: () => fetch3, + fingerPrint64: () => fingerPrint64, + flatten: () => flatten, + getArrayFromDType: () => getArrayFromDType, + getTypedArrayFromDType: () => getTypedArrayFromDType, + hasEncodingLoss: () => hasEncodingLoss, + hexToLong: () => hexToLong, + indexToLoc: () => indexToLoc, + inferDtype: () => inferDtype, + inferFromImplicitShape: () => inferFromImplicitShape, + isBoolean: () => isBoolean, + isFunction: () => isFunction, + isInt: () => isInt, + isNumber: () => isNumber, + isPromise: () => isPromise, + isScalarShape: () => isScalarShape, + isString: () => isString, + isTypedArray: () => isTypedArray, + isValidDtype: () => isValidDtype, + locToIndex: () => locToIndex, + makeOnesTypedArray: () => makeOnesTypedArray, + makeZerosNestedTypedArray: () => makeZerosNestedTypedArray, + makeZerosTypedArray: () => makeZerosTypedArray, + nearestDivisor: () => nearestDivisor, + nearestLargerEven: () => nearestLargerEven, + now: () => now, + parseAxisParam: () => parseAxisParam, + randUniform: () => randUniform, + repeatedTry: () => repeatedTry, + rightPad: () => rightPad, + shuffle: () => shuffle, + shuffleCombo: () => shuffleCombo, + sizeFromShape: () => sizeFromShape, + sizeToSquarishShape: () => sizeToSquarishShape, + squeezeShape: () => squeezeShape, + sum: () => sum, + swap: () => swap, + tanh: () => tanh, + toNestedArray: () => toNestedArray, + toTypedArray: () => toTypedArray + }); + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/hash_util.js + init_define_BUILD_VERSION(); + var LongExports = __toESM(require_long()); + var Long = LongExports.default || LongExports; + function hexToLong(hex) { + return Long.fromString(hex, true, 16); + } + var k0 = hexToLong("c3a5c85c97cb3127"); + var k1 = hexToLong("b492b66fbe98f273"); + var k2 = hexToLong("9ae16a3b2f90404f"); + function shiftMix(val) { + return val.xor(val.shru(47)); + } + function fetch2(s, offset, numBytes) { + const bytes = s.slice(offset, offset + numBytes); + return Long.fromBytes(Array.from(bytes), true, true); + } + function fetch64(s, offset) { + return fetch2(s, offset, 8); + } + function fetch32(s, offset) { + return fetch2(s, offset, 4); + } + function rotate64(val, shift) { + return shift === 0 ? val : val.shru(shift).or(val.shl(64 - shift)); + } + function hashLen16(u, v, mul2 = hexToLong("9ddfea08eb382d69")) { + let a = u.xor(v).mul(mul2); + a = a.xor(a.shru(47)); + let b = v.xor(a).mul(mul2); + b = b.xor(b.shru(47)); + b = b.mul(mul2); + return b; + } + function weakHashLen32WithSeeds(w, x, y, z, a, b) { + a = a.add(w); + b = rotate64(b.add(a).add(z), 21); + const c = a; + a = a.add(x); + a = a.add(y); + b = b.add(rotate64(a, 44)); + return [a.add(z), b.add(c)]; + } + function weakHashLen32WithSeedsStr(s, offset, a, b) { + return weakHashLen32WithSeeds(fetch64(s, offset), fetch64(s, offset + 8), fetch64(s, offset + 16), fetch64(s, offset + 24), a, b); + } + function hashLen0to16(s, len = s.length) { + if (len >= 8) { + const mul2 = k2.add(len * 2); + const a = fetch64(s, 0).add(k2); + const b = fetch64(s, len - 8); + const c = rotate64(b, 37).mul(mul2).add(a); + const d = rotate64(a, 25).add(b).mul(mul2); + return hashLen16(c, d, mul2); + } + if (len >= 4) { + const mul2 = k2.add(len * 2); + const a = fetch32(s, 0); + return hashLen16(a.shl(3).add(len), fetch32(s, len - 4), mul2); + } + if (len > 0) { + const a = s[0]; + const b = s[len >> 1]; + const c = s[len - 1]; + const y = a + (b << 8); + const z = len + (c << 2); + return shiftMix(k2.mul(y).xor(k0.mul(z))).mul(k2); + } + return k2; + } + function hashLen17to32(s, len = s.length) { + const mul2 = k2.add(len * 2); + const a = fetch64(s, 0).mul(k1); + const b = fetch64(s, 8); + const c = fetch64(s, len - 8).mul(mul2); + const d = fetch64(s, len - 16).mul(k2); + return hashLen16(rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d), a.add(rotate64(b.add(k2), 18)).add(c), mul2); + } + function hashLen33to64(s, len = s.length) { + const mul2 = k2.add(len * 2); + const a = fetch64(s, 0).mul(k2); + const b = fetch64(s, 8); + const c = fetch64(s, len - 8).mul(mul2); + const d = fetch64(s, len - 16).mul(k2); + const y = rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d); + const z = hashLen16(y, a.add(rotate64(b.add(k2), 18)).add(c), mul2); + const e = fetch64(s, 16).mul(mul2); + const f = fetch64(s, 24); + const g = y.add(fetch64(s, len - 32)).mul(mul2); + const h = z.add(fetch64(s, len - 24)).mul(mul2); + return hashLen16(rotate64(e.add(f), 43).add(rotate64(g, 30)).add(h), e.add(rotate64(f.add(a), 18)).add(g), mul2); + } + function fingerPrint64(s, len = s.length) { + const seed = Long.fromNumber(81, true); + if (len <= 32) { + if (len <= 16) { + return hashLen0to16(s, len); + } else { + return hashLen17to32(s, len); + } + } else if (len <= 64) { + return hashLen33to64(s, len); + } + let x = seed; + let y = seed.mul(k1).add(113); + let z = shiftMix(y.mul(k2).add(113)).mul(k2); + let v = [Long.UZERO, Long.UZERO]; + let w = [Long.UZERO, Long.UZERO]; + x = x.mul(k2).add(fetch64(s, 0)); + let offset = 0; + const end = (len - 1 >> 6) * 64; + const last64 = end + (len - 1 & 63) - 63; + do { + x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(k1); + y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(k1); + x = x.xor(w[1]); + y = y.add(v[0]).add(fetch64(s, offset + 40)); + z = rotate64(z.add(w[0]), 33).mul(k1); + v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(k1), x.add(w[0])); + w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16))); + [z, x] = [x, z]; + offset += 64; + } while (offset !== end); + const mul2 = k1.add(z.and(255).shl(1)); + offset = last64; + w[0] = w[0].add(len - 1 & 63); + v[0] = v[0].add(w[0]); + w[0] = w[0].add(v[0]); + x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(mul2); + y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(mul2); + x = x.xor(w[1].mul(9)); + y = y.add(v[0].mul(9).add(fetch64(s, offset + 40))); + z = rotate64(z.add(w[0]), 33).mul(mul2); + v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(mul2), x.add(w[0])); + w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16))); + [z, x] = [x, z]; + return hashLen16(hashLen16(v[0], w[0], mul2).add(shiftMix(y).mul(k0)).add(z), hashLen16(v[1], w[1], mul2).add(x), mul2); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/util.js + function createScalarValue(value, dtype) { + if (dtype === "string") { + return encodeString(value); + } + return toTypedArray([value], dtype); + } + function noConversionNeeded(a, dtype) { + return a instanceof Float32Array && dtype === "float32" || a instanceof Int32Array && dtype === "int32" || a instanceof Uint8Array && dtype === "bool"; + } + function toTypedArray(a, dtype) { + if (dtype === "string") { + throw new Error("Cannot convert a string[] to a TypedArray"); + } + if (Array.isArray(a)) { + a = flatten(a); + } + if (env().getBool("DEBUG")) { + checkConversionForErrors(a, dtype); + } + if (noConversionNeeded(a, dtype)) { + return a; + } + if (dtype == null || dtype === "float32" || dtype === "complex64") { + return new Float32Array(a); + } else if (dtype === "int32") { + return new Int32Array(a); + } else if (dtype === "bool") { + const bool = new Uint8Array(a.length); + for (let i = 0; i < bool.length; ++i) { + if (Math.round(a[i]) !== 0) { + bool[i] = 1; + } + } + return bool; + } else { + throw new Error(`Unknown data type ${dtype}`); + } + } + function now() { + return env().platform.now(); + } + function fetch3(path, requestInits) { + return env().platform.fetch(path, requestInits); + } + function encodeString(s, encoding = "utf-8") { + encoding = encoding || "utf-8"; + return env().platform.encode(s, encoding); + } + function decodeString(bytes, encoding = "utf-8") { + encoding = encoding || "utf-8"; + return env().platform.decode(bytes, encoding); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/profiler.js + var Profiler = class { + constructor(backendTimer, logger) { + this.backendTimer = backendTimer; + this.logger = logger; + if (logger == null) { + this.logger = new Logger(); + } + } + profileKernel(kernelName, inputs, f) { + let outputs; + const holdResultWrapperFn = () => { + outputs = f(); + }; + let timer; + const start = now(); + if (this.backendTimer.timerAvailable()) { + timer = this.backendTimer.time(holdResultWrapperFn); + } else { + holdResultWrapperFn(); + for (const output of outputs) { + output.dataSync(); + } + timer = Promise.resolve({ kernelMs: now() - start }); + } + if (env().getBool("CHECK_COMPUTATION_FOR_ERRORS")) { + for (let i = 0; i < outputs.length; i++) { + const output = outputs[i]; + output.data().then((tensorVals) => { + checkComputationForErrors(tensorVals, output.dtype, kernelName); + }); + } + } + const kernelProfile = { + kernelName, + outputs, + inputs, + timeMs: timer.then((timing) => timing.kernelMs), + extraInfo: timer.then((timing) => timing.getExtraProfileInfo != null ? timing.getExtraProfileInfo() : "") + }; + return kernelProfile; + } + logKernelProfile(kernelProfile) { + const { kernelName, outputs, timeMs, inputs, extraInfo } = kernelProfile; + outputs.forEach((result) => { + Promise.all([result.data(), timeMs, extraInfo]).then((valueContainer) => { + this.logger.logKernelProfile(kernelName, result, valueContainer[0], valueContainer[1], inputs, valueContainer[2]); + }); + }); + } + }; + function checkComputationForErrors(vals, dtype, kernelName) { + if (dtype !== "float32") { + return false; + } + for (let i = 0; i < vals.length; i++) { + const num = vals[i]; + if (isNaN(num) || !isFinite(num)) { + console.warn(`Found ${num} in the result of '${kernelName}'`); + return true; + } + } + return false; + } + var Logger = class { + logKernelProfile(name, result, vals, timeMs, inputs, extraInfo) { + const time = typeof timeMs === "number" ? rightPad(`${timeMs}ms`, 9) : timeMs["error"]; + const paddedName = rightPad(name, 25); + const rank = result.rank; + const size = result.size; + const shape = rightPad(result.shape.toString(), 14); + let inputShapesDescription = ""; + for (const name2 in inputs) { + const input2 = inputs[name2]; + if (input2 != null) { + const inputShape = input2.shape || result.shape; + const inputRank = inputShape.length; + inputShapesDescription += `${name2}: ${inputRank}D ${inputRank > 0 ? inputShape : ""} `; + } + } + console.log(`%c${paddedName} %c${time} %c${rank}D ${shape} %c${size} %c${inputShapesDescription} %c${extraInfo}`, "font-weight:bold", "color:red", "color:blue", "color: orange", "color: green", "color: steelblue"); + } + }; + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/tape.js + init_define_BUILD_VERSION(); + function getFilteredNodesXToY(tape, xs, y) { + const tensorsFromX = {}; + const nodesFromX = {}; + for (let i = 0; i < xs.length; i++) { + tensorsFromX[xs[i].id] = true; + } + for (let i = 0; i < tape.length; i++) { + const node = tape[i]; + const nodeInputs = node.inputs; + for (const inputName in nodeInputs) { + const input2 = nodeInputs[inputName]; + let anyInputFromX = false; + for (let j = 0; j < xs.length; j++) { + if (tensorsFromX[input2.id]) { + node.outputs.forEach((output) => tensorsFromX[output.id] = true); + anyInputFromX = true; + nodesFromX[node.id] = true; + break; + } + } + if (anyInputFromX) { + break; + } + } + } + const tensorsLeadToY = {}; + tensorsLeadToY[y.id] = true; + const nodesToY = {}; + for (let i = tape.length - 1; i >= 0; i--) { + const node = tape[i]; + const nodeInputs = node.inputs; + for (let j = 0; j < node.outputs.length; j++) { + if (tensorsLeadToY[node.outputs[j].id]) { + for (const inputName in nodeInputs) { + tensorsLeadToY[nodeInputs[inputName].id] = true; + nodesToY[node.id] = true; + } + break; + } + } + } + const filteredTape = []; + for (let i = 0; i < tape.length; i++) { + const node = tape[i]; + if (nodesFromX[node.id] && nodesToY[node.id]) { + const prunedInputs = {}; + for (const inputName in node.inputs) { + const nodeInput = node.inputs[inputName]; + if (tensorsFromX[nodeInput.id]) { + prunedInputs[inputName] = nodeInput; + } + } + const prunedNode = Object.assign({}, node); + prunedNode.inputs = prunedInputs; + prunedNode.outputs = node.outputs; + filteredTape.push(prunedNode); + } + } + return filteredTape; + } + function backpropagateGradients(tensorAccumulatedGradientMap, filteredTape, tidy2, add4) { + for (let i = filteredTape.length - 1; i >= 0; i--) { + const node = filteredTape[i]; + const dys = []; + node.outputs.forEach((o) => { + const gradTensor = tensorAccumulatedGradientMap[o.id]; + if (gradTensor != null) { + dys.push(gradTensor); + } else { + dys.push(null); + } + }); + if (node.gradient == null) { + throw new Error(`Cannot compute gradient: gradient function not found for ${node.kernelName}.`); + } + const inputGradients = node.gradient(dys); + for (const inputName in node.inputs) { + if (!(inputName in inputGradients)) { + throw new Error(`Cannot backprop through input ${inputName}. Available gradients found: ${Object.keys(inputGradients)}.`); + } + const dx = tidy2(() => inputGradients[inputName]()); + if (dx.dtype !== "float32") { + throw new Error(`Error in gradient for op ${node.kernelName}. The gradient of input ${inputName} must have 'float32' dtype, but has '${dx.dtype}'`); + } + const x = node.inputs[inputName]; + if (!arraysEqual(dx.shape, x.shape)) { + throw new Error(`Error in gradient for op ${node.kernelName}. The gradient of input '${inputName}' has shape '${dx.shape}', which does not match the shape of the input '${x.shape}'`); + } + if (tensorAccumulatedGradientMap[x.id] == null) { + tensorAccumulatedGradientMap[x.id] = dx; + } else { + const curGradient = tensorAccumulatedGradientMap[x.id]; + tensorAccumulatedGradientMap[x.id] = add4(curGradient, dx); + curGradient.dispose(); + } + } + } + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/tensor.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/tensor_format.js + init_define_BUILD_VERSION(); + var FORMAT_LIMIT_NUM_VALS = 20; + var FORMAT_NUM_FIRST_LAST_VALS = 3; + var FORMAT_NUM_SIG_DIGITS = 7; + function tensorToString(vals, shape, dtype, verbose) { + const strides = computeStrides(shape); + const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides); + const rank = shape.length; + const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol); + const lines = ["Tensor"]; + if (verbose) { + lines.push(` dtype: ${dtype}`); + lines.push(` rank: ${rank}`); + lines.push(` shape: [${shape}]`); + lines.push(` values:`); + } + lines.push(valsLines.map((l) => " " + l).join("\n")); + return lines.join("\n"); + } + function computeMaxSizePerColumn(vals, shape, dtype, strides) { + const n = sizeFromShape(shape); + const numCols = strides[strides.length - 1]; + const padPerCol = new Array(numCols).fill(0); + const rank = shape.length; + const valuesOrTuples = dtype === "complex64" ? createComplexTuples(vals) : vals; + if (rank > 1) { + for (let row = 0; row < n / numCols; row++) { + const offset = row * numCols; + for (let j = 0; j < numCols; j++) { + padPerCol[j] = Math.max(padPerCol[j], valToString(valuesOrTuples[offset + j], 0, dtype).length); + } + } + } + return padPerCol; + } + function valToString(val, pad2, dtype) { + let valStr; + if (Array.isArray(val)) { + valStr = `${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`; + } else if (isString(val)) { + valStr = `'${val}'`; + } else if (dtype === "bool") { + valStr = boolNumToString(val); + } else { + valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString(); + } + return rightPad(valStr, pad2); + } + function boolNumToString(v) { + return v === 0 ? "false" : "true"; + } + function subTensorToString(vals, shape, dtype, strides, padPerCol, isLast = true) { + const storagePerElement = dtype === "complex64" ? 2 : 1; + const size = shape[0]; + const rank = shape.length; + if (rank === 0) { + if (dtype === "complex64") { + const complexTuple = createComplexTuples(vals); + return [valToString(complexTuple[0], 0, dtype)]; + } + if (dtype === "bool") { + return [boolNumToString(vals[0])]; + } + return [vals[0].toString()]; + } + if (rank === 1) { + if (size > FORMAT_LIMIT_NUM_VALS) { + const firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement; + let firstVals = Array.from(vals.slice(0, firstValsSize)); + let lastVals = Array.from(vals.slice((size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement, size * storagePerElement)); + if (dtype === "complex64") { + firstVals = createComplexTuples(firstVals); + lastVals = createComplexTuples(lastVals); + } + return [ + "[" + firstVals.map((x, i) => valToString(x, padPerCol[i], dtype)).join(", ") + ", ..., " + lastVals.map((x, i) => valToString(x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype)).join(", ") + "]" + ]; + } + const displayVals = dtype === "complex64" ? createComplexTuples(vals) : Array.from(vals); + return [ + "[" + displayVals.map((x, i) => valToString(x, padPerCol[i], dtype)).join(", ") + "]" + ]; + } + const subshape = shape.slice(1); + const substrides = strides.slice(1); + const stride = strides[0] * storagePerElement; + const lines = []; + if (size > FORMAT_LIMIT_NUM_VALS) { + for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) { + const start = i * stride; + const end = start + stride; + lines.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, false)); + } + lines.push("..."); + for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) { + const start = i * stride; + const end = start + stride; + lines.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, i === size - 1)); + } + } else { + for (let i = 0; i < size; i++) { + const start = i * stride; + const end = start + stride; + lines.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, i === size - 1)); + } + } + const sep = rank === 2 ? "," : ""; + lines[0] = "[" + lines[0] + sep; + for (let i = 1; i < lines.length - 1; i++) { + lines[i] = " " + lines[i] + sep; + } + let newLineSep = ",\n"; + for (let i = 2; i < rank; i++) { + newLineSep += "\n"; + } + lines[lines.length - 1] = " " + lines[lines.length - 1] + "]" + (isLast ? "" : newLineSep); + return lines; + } + function createComplexTuples(vals) { + const complexTuples = []; + for (let i = 0; i < vals.length; i += 2) { + complexTuples.push([vals[i], vals[i + 1]]); + } + return complexTuples; + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/tensor.js + var TensorBuffer = class { + constructor(shape, dtype, values) { + this.dtype = dtype; + this.shape = shape.slice(); + this.size = sizeFromShape(shape); + if (values != null) { + const n = values.length; + assert(n === this.size, () => `Length of values '${n}' does not match the size inferred by the shape '${this.size}'.`); + } + if (dtype === "complex64") { + throw new Error(`complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).`); + } + this.values = values || getArrayFromDType(dtype, this.size); + this.strides = computeStrides(shape); + } + set(value, ...locs) { + if (locs.length === 0) { + locs = [0]; + } + assert(locs.length === this.rank, () => `The number of provided coordinates (${locs.length}) must match the rank (${this.rank})`); + const index = this.locToIndex(locs); + this.values[index] = value; + } + get(...locs) { + if (locs.length === 0) { + locs = [0]; + } + let i = 0; + for (const loc of locs) { + if (loc < 0 || loc >= this.shape[i]) { + const msg = `Requested out of range element at ${locs}. Buffer shape=${this.shape}`; + throw new Error(msg); + } + i++; + } + let index = locs[locs.length - 1]; + for (let i2 = 0; i2 < locs.length - 1; ++i2) { + index += this.strides[i2] * locs[i2]; + } + return this.values[index]; + } + locToIndex(locs) { + if (this.rank === 0) { + return 0; + } else if (this.rank === 1) { + return locs[0]; + } + let index = locs[locs.length - 1]; + for (let i = 0; i < locs.length - 1; ++i) { + index += this.strides[i] * locs[i]; + } + return index; + } + indexToLoc(index) { + if (this.rank === 0) { + return []; + } else if (this.rank === 1) { + return [index]; + } + const locs = new Array(this.shape.length); + for (let i = 0; i < locs.length - 1; ++i) { + locs[i] = Math.floor(index / this.strides[i]); + index -= locs[i] * this.strides[i]; + } + locs[locs.length - 1] = index; + return locs; + } + get rank() { + return this.shape.length; + } + toTensor() { + return trackerFn().makeTensor(this.values, this.shape, this.dtype); + } + }; + var trackerFn = null; + var opHandler = null; + var deprecationWarningFn = null; + function setTensorTracker(fn) { + trackerFn = fn; + } + function setOpHandler(handler) { + opHandler = handler; + } + function setDeprecationWarningFn(fn) { + deprecationWarningFn = fn; + } + var Tensor = class { + constructor(shape, dtype, dataId, id) { + this.kept = false; + this.isDisposedInternal = false; + this.shape = shape.slice(); + this.dtype = dtype || "float32"; + this.size = sizeFromShape(shape); + this.strides = computeStrides(shape); + this.dataId = dataId; + this.id = id; + this.rankType = this.rank < 5 ? this.rank.toString() : "higher"; + } + get rank() { + return this.shape.length; + } + async buffer() { + const vals = await this.data(); + return opHandler.buffer(this.shape, this.dtype, vals); + } + bufferSync() { + return opHandler.buffer(this.shape, this.dtype, this.dataSync()); + } + async array() { + const vals = await this.data(); + return toNestedArray(this.shape, vals, this.dtype === "complex64"); + } + arraySync() { + return toNestedArray(this.shape, this.dataSync(), this.dtype === "complex64"); + } + async data() { + this.throwIfDisposed(); + const data = trackerFn().read(this.dataId); + if (this.dtype === "string") { + const bytes = await data; + try { + return bytes.map((b) => decodeString(b)); + } catch (_a) { + throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes()."); + } + } + return data; + } + dataToGPU(options) { + this.throwIfDisposed(); + return trackerFn().readToGPU(this.dataId, options); + } + dataSync() { + this.throwIfDisposed(); + const data = trackerFn().readSync(this.dataId); + if (this.dtype === "string") { + try { + return data.map((b) => decodeString(b)); + } catch (_a) { + throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes()."); + } + } + return data; + } + async bytes() { + this.throwIfDisposed(); + const data = await trackerFn().read(this.dataId); + if (this.dtype === "string") { + return data; + } else { + return new Uint8Array(data.buffer); + } + } + dispose() { + if (this.isDisposed) { + return; + } + trackerFn().disposeTensor(this); + this.isDisposedInternal = true; + } + get isDisposed() { + return this.isDisposedInternal; + } + throwIfDisposed() { + if (this.isDisposed) { + throw new Error(`Tensor is disposed.`); + } + } + print(verbose = false) { + return opHandler.print(this, verbose); + } + clone() { + this.throwIfDisposed(); + return opHandler.clone(this); + } + toString(verbose = false) { + const vals = this.dataSync(); + return tensorToString(vals, this.shape, this.dtype, verbose); + } + cast(dtype) { + this.throwIfDisposed(); + return opHandler.cast(this, dtype); + } + variable(trainable = true, name, dtype) { + this.throwIfDisposed(); + return trackerFn().makeVariable(this, trainable, name, dtype); + } + }; + Object.defineProperty(Tensor, Symbol.hasInstance, { + value: (instance) => { + return !!instance && instance.data != null && instance.dataSync != null && instance.throwIfDisposed != null; + } + }); + function getGlobalTensorClass() { + return getGlobal("Tensor", () => { + return Tensor; + }); + } + getGlobalTensorClass(); + var Variable = class extends Tensor { + constructor(initialValue, trainable, name, tensorId) { + super(initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId); + this.trainable = trainable; + this.name = name; + } + assign(newValue) { + if (newValue.dtype !== this.dtype) { + throw new Error(`dtype of the new value (${newValue.dtype}) and previous value (${this.dtype}) must match`); + } + if (!arraysEqual(newValue.shape, this.shape)) { + throw new Error(`shape of the new value (${newValue.shape}) and previous value (${this.shape}) must match`); + } + trackerFn().disposeTensor(this); + this.dataId = newValue.dataId; + trackerFn().incRef(this, null); + } + dispose() { + trackerFn().disposeVariable(this); + this.isDisposedInternal = true; + } + }; + Object.defineProperty(Variable, Symbol.hasInstance, { + value: (instance) => { + return instance instanceof Tensor && instance.assign != null && instance.assign instanceof Function; + } + }); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/tensor_util.js + var tensor_util_exports = {}; + __export(tensor_util_exports, { + assertTypesMatch: () => assertTypesMatch, + getTensorsInContainer: () => getTensorsInContainer, + isTensorInList: () => isTensorInList, + makeTypesMatch: () => makeTypesMatch + }); + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/types.js + init_define_BUILD_VERSION(); + var Rank; + (function(Rank2) { + Rank2["R0"] = "R0"; + Rank2["R1"] = "R1"; + Rank2["R2"] = "R2"; + Rank2["R3"] = "R3"; + Rank2["R4"] = "R4"; + Rank2["R5"] = "R5"; + Rank2["R6"] = "R6"; + })(Rank || (Rank = {})); + var UpcastInt32AndMap; + (function(UpcastInt32AndMap2) { + UpcastInt32AndMap2["float32"] = "float32"; + UpcastInt32AndMap2["int32"] = "int32"; + UpcastInt32AndMap2["bool"] = "int32"; + UpcastInt32AndMap2["complex64"] = "complex64"; + })(UpcastInt32AndMap || (UpcastInt32AndMap = {})); + var UpcastBoolAndMap; + (function(UpcastBoolAndMap2) { + UpcastBoolAndMap2["float32"] = "float32"; + UpcastBoolAndMap2["int32"] = "int32"; + UpcastBoolAndMap2["bool"] = "bool"; + UpcastBoolAndMap2["complex64"] = "complex64"; + })(UpcastBoolAndMap || (UpcastBoolAndMap = {})); + var UpcastFloat32AndMap; + (function(UpcastFloat32AndMap2) { + UpcastFloat32AndMap2["float32"] = "float32"; + UpcastFloat32AndMap2["int32"] = "float32"; + UpcastFloat32AndMap2["bool"] = "float32"; + UpcastFloat32AndMap2["complex64"] = "complex64"; + })(UpcastFloat32AndMap || (UpcastFloat32AndMap = {})); + var UpcastComplex64AndMap; + (function(UpcastComplex64AndMap2) { + UpcastComplex64AndMap2["float32"] = "complex64"; + UpcastComplex64AndMap2["int32"] = "complex64"; + UpcastComplex64AndMap2["bool"] = "complex64"; + UpcastComplex64AndMap2["complex64"] = "complex64"; + })(UpcastComplex64AndMap || (UpcastComplex64AndMap = {})); + var upcastTypeMap = { + "float32": UpcastFloat32AndMap, + "int32": UpcastInt32AndMap, + "bool": UpcastBoolAndMap, + "complex64": UpcastComplex64AndMap + }; + function upcastType(typeA, typeB) { + if (typeA === "string" || typeB === "string") { + if (typeA === "string" && typeB === "string") { + return "string"; + } + throw new Error(`Can not upcast ${typeA} with ${typeB}`); + } + return upcastTypeMap[typeA][typeB]; + } + function sumOutType(type) { + return upcastType(type, "int32"); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/tensor_util.js + function makeTypesMatch(a, b) { + if (a.dtype === b.dtype) { + return [a, b]; + } + const dtype = upcastType(a.dtype, b.dtype); + return [a.cast(dtype), b.cast(dtype)]; + } + function assertTypesMatch(a, b) { + assert(a.dtype === b.dtype, () => `The dtypes of the first(${a.dtype}) and second(${b.dtype}) input must match`); + } + function isTensorInList(tensor3, tensorList) { + return tensorList.some((x) => x.id === tensor3.id); + } + function getTensorsInContainer(result) { + const list = []; + const seen = /* @__PURE__ */ new Set(); + walkTensorContainer(result, list, seen); + return list; + } + function walkTensorContainer(container, list, seen) { + if (container == null) { + return; + } + if (container instanceof Tensor) { + list.push(container); + return; + } + if (!isIterable(container)) { + return; + } + const iterable = container; + for (const k in iterable) { + const val = iterable[k]; + if (!seen.has(val)) { + seen.add(val); + walkTensorContainer(val, list, seen); + } + } + } + function isIterable(obj) { + return Array.isArray(obj) || typeof obj === "object"; + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/engine.js + function isRegisteredKernelInvocation(kernelInvocation) { + return kernelInvocation.kernelName != null; + } + var EngineState = class { + constructor() { + this.registeredVariables = {}; + this.nextTapeNodeId = 0; + this.numBytes = 0; + this.numTensors = 0; + this.numStringTensors = 0; + this.numDataBuffers = 0; + this.gradientDepth = 0; + this.kernelDepth = 0; + this.scopeStack = []; + this.numDataMovesStack = []; + this.nextScopeId = 0; + this.tensorInfo = /* @__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((k) => k.name))); + } + }; + } + dispose() { + for (const variableName in this.registeredVariables) { + this.registeredVariables[variableName].dispose(); + } + } + }; + var Engine = class { + constructor(ENV6) { + this.ENV = ENV6; + this.registry = {}; + this.registryFactory = {}; + this.pendingBackendInitId = 0; + this.state = new EngineState(); + } + async ready() { + if (this.pendingBackendInit != null) { + return this.pendingBackendInit.then(() => { + }); + } + if (this.backendInstance != null) { + return; + } + const sortedBackends = this.getSortedBackends(); + for (let i = 0; i < sortedBackends.length; i++) { + const backendName = sortedBackends[i]; + const success = await this.initializeBackend(backendName).success; + if (success) { + await this.setBackend(backendName); + return; + } + } + throw new Error(`Could not initialize any backends, all backend initializations failed.`); + } + get backend() { + if (this.pendingBackendInit != null) { + throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`); + } + if (this.backendInstance == null) { + const { name, asyncInit } = this.initializeBackendsAndReturnBest(); + if (asyncInit) { + throw new Error(`The highest priority backend '${name}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`); + } + this.setBackend(name); + } + return this.backendInstance; + } + backendNames() { + return Object.keys(this.registryFactory); + } + findBackend(backendName) { + if (!(backendName in this.registry)) { + if (backendName in this.registryFactory) { + const { asyncInit } = this.initializeBackend(backendName); + if (asyncInit) { + return null; + } + } else { + return null; + } + } + return this.registry[backendName]; + } + findBackendFactory(backendName) { + if (!(backendName in this.registryFactory)) { + return null; + } + return this.registryFactory[backendName].factory; + } + registerBackend(backendName, factory, priority = 1) { + if (backendName in this.registryFactory) { + warn(`${backendName} backend was already registered. Reusing existing backend factory.`); + return false; + } + this.registryFactory[backendName] = { factory, priority }; + return true; + } + async setBackend(backendName) { + if (this.registryFactory[backendName] == null) { + throw new Error(`Backend name '${backendName}' not found in registry`); + } + this.backendName = backendName; + if (this.registry[backendName] == null) { + this.backendInstance = null; + const { success, asyncInit } = this.initializeBackend(backendName); + const result = asyncInit ? await success : success; + if (!result) { + return false; + } + } + this.backendInstance = this.registry[backendName]; + this.setupRegisteredKernels(); + this.profiler = new Profiler(this.backendInstance); + return true; + } + setupRegisteredKernels() { + const kernels = getKernelsForBackend(this.backendName); + kernels.forEach((kernel) => { + if (kernel.setupFunc != null) { + kernel.setupFunc(this.backendInstance); + } + }); + } + disposeRegisteredKernels(backendName) { + const kernels = getKernelsForBackend(backendName); + kernels.forEach((kernel) => { + if (kernel.disposeFunc != null) { + kernel.disposeFunc(this.registry[backendName]); + } + }); + } + initializeBackend(backendName) { + const registryFactoryEntry = this.registryFactory[backendName]; + if (registryFactoryEntry == null) { + throw new Error(`Cannot initialize backend ${backendName}, no registration found.`); + } + try { + const backend2 = registryFactoryEntry.factory(); + if (backend2 && !(backend2 instanceof KernelBackend) && typeof backend2.then === "function") { + const promiseId = ++this.pendingBackendInitId; + const success = backend2.then((backendInstance) => { + if (promiseId < this.pendingBackendInitId) { + return false; + } + this.registry[backendName] = backendInstance; + this.pendingBackendInit = null; + return true; + }).catch((err) => { + if (promiseId < this.pendingBackendInitId) { + return false; + } + this.pendingBackendInit = null; + warn(`Initialization of backend ${backendName} failed`); + warn(err.stack || err.message); + return false; + }); + this.pendingBackendInit = success; + return { success, asyncInit: true }; + } else { + this.registry[backendName] = backend2; + return { success: true, asyncInit: false }; + } + } catch (err) { + warn(`Initialization of backend ${backendName} failed`); + warn(err.stack || err.message); + return { success: false, asyncInit: false }; + } + } + removeBackend(backendName) { + if (!(backendName in this.registryFactory)) { + throw new Error(`${backendName} backend not found in registry`); + } + if (this.backendName === backendName && this.pendingBackendInit != null) { + this.pendingBackendInitId++; + } + if (backendName in this.registry) { + this.disposeRegisteredKernels(backendName); + this.registry[backendName].dispose(); + delete this.registry[backendName]; + } + delete this.registryFactory[backendName]; + if (this.backendName === backendName) { + this.pendingBackendInit = null; + this.backendName = null; + this.backendInstance = null; + } + } + getSortedBackends() { + if (Object.keys(this.registryFactory).length === 0) { + throw new Error("No backend found in registry."); + } + return Object.keys(this.registryFactory).sort((a, b) => { + return this.registryFactory[b].priority - this.registryFactory[a].priority; + }); + } + initializeBackendsAndReturnBest() { + const sortedBackends = this.getSortedBackends(); + for (let i = 0; i < sortedBackends.length; i++) { + const backendName = sortedBackends[i]; + const { success, asyncInit } = this.initializeBackend(backendName); + if (asyncInit || success) { + return { name: backendName, asyncInit }; + } + } + throw new Error(`Could not initialize any backends, all backend initializations failed.`); + } + moveData(backend2, dataId) { + const info = this.state.tensorInfo.get(dataId); + const srcBackend = info.backend; + const values = this.readSync(dataId); + const refCount = srcBackend.refCount(dataId); + srcBackend.disposeData(dataId, true); + info.backend = backend2; + backend2.move(dataId, values, info.shape, info.dtype, refCount); + if (this.shouldCheckForMemLeaks()) { + this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++; + } + } + tidy(nameOrFn, fn) { + let name = null; + if (fn == null) { + if (typeof nameOrFn !== "function") { + throw new Error("Please provide a function to tidy()"); + } + fn = nameOrFn; + } else { + if (typeof nameOrFn !== "string" && !(nameOrFn instanceof String)) { + throw new Error("When calling with two arguments, the first argument to tidy() must be a string"); + } + if (typeof fn !== "function") { + throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function"); + } + name = nameOrFn; + } + let result; + return this.scopedRun(() => this.startScope(name), () => this.endScope(result), () => { + result = fn(); + if (result instanceof Promise) { + console.error("Cannot return a Promise inside of tidy."); + } + return result; + }); + } + scopedRun(start, end, f) { + start(); + try { + const res = f(); + end(); + return res; + } catch (ex) { + end(); + throw ex; + } + } + nextTensorId() { + return Engine.nextTensorId++; + } + nextVariableId() { + return Engine.nextVariableId++; + } + clone(x) { + const y = ENGINE.runKernel(Identity, { x }); + const inputs = { x }; + const grad = (dy) => ({ + x: () => { + const dtype = "float32"; + const gradInputs = { x: dy }; + const attrs = { dtype }; + return ENGINE.runKernel( + Cast, + gradInputs, + attrs + ); + } + }); + const saved = []; + this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {}); + return y; + } + runKernel(kernelName, inputs, attrs) { + if (this.backendName == null) { + this.backend; + } + const hasKernel = getKernel(kernelName, this.backendName) != null; + if (!hasKernel) { + throw new Error(`Kernel '${kernelName}' not registered for backend '${this.backendName}'`); + } + return this.runKernelFunc({ kernelName, inputs, attrs }); + } + shouldCheckForMemLeaks() { + return this.ENV.getBool("IS_TEST"); + } + checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos) { + const numDataIdsAfter = this.backend.numDataIds(); + let numOutputDataIds = 0; + outInfos.forEach((info) => { + numOutputDataIds += info.dtype === "complex64" ? 3 : 1; + }); + const numMoves = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]; + const dataIdsLeaked = numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves; + if (dataIdsLeaked > 0) { + throw new Error(`Backend '${this.backendName}' has an internal memory leak (${dataIdsLeaked} data ids) after running '${kernelName}'`); + } + } + runKernelFunc(kernelParams) { + let outputs; + let saved = []; + const isTapeOn = this.isTapeOn(); + const startingBytecount = this.state.numBytes; + const startingNumTensors = this.state.numTensors; + if (this.shouldCheckForMemLeaks()) { + this.state.numDataMovesStack.push(0); + } + let kernelFunc; + if (this.backendName == null) { + this.backend; + } + let out; + const kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ? kernelParams.kernelName : this.state.activeScope != null ? this.state.activeScope.name : ""; + if (isRegisteredKernelInvocation(kernelParams)) { + const { kernelName, inputs: inputs2, attrs: attrs2 } = kernelParams; + if (this.backendName == null) { + this.backend; + } + const kernel = getKernel(kernelName, this.backendName); + assert(kernel != null, () => `Cannot find registered kernel '${kernelName}' for backend '${this.backendName}'`); + kernelFunc = () => { + const numDataIdsBefore = this.backend.numDataIds(); + out = kernel.kernelFunc({ inputs: inputs2, attrs: attrs2, backend: this.backend }); + const outInfos = Array.isArray(out) ? out : [out]; + if (this.shouldCheckForMemLeaks()) { + this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos); + } + const outTensors = outInfos.map((outInfo) => { + if (outInfo.rank != null) { + return outInfo; + } + return this.makeTensorFromTensorInfo(outInfo); + }); + if (isTapeOn) { + const tensorsToSave = this.getTensorsForGradient(kernelName, inputs2, outTensors); + saved = this.saveTensorsForBackwardMode(tensorsToSave); + } + return outTensors; + }; + } else { + const { forwardFunc } = kernelParams; + const saveFunc = (tensors) => { + if (!isTapeOn) { + return; + } + saved = tensors.map((tensor3) => this.keep(this.clone(tensor3))); + }; + kernelFunc = () => { + const numDataIdsBefore = this.backend.numDataIds(); + out = this.tidy(() => forwardFunc(this.backend, saveFunc)); + const outs = Array.isArray(out) ? out : [out]; + if (this.shouldCheckForMemLeaks()) { + this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs); + } + return outs; + }; + } + const { inputs, attrs } = kernelParams; + const backwardsFunc = isRegisteredKernelInvocation(kernelParams) ? null : kernelParams.backwardsFunc; + let kernelProfile; + this.scopedRun( + () => this.state.kernelDepth++, + () => this.state.kernelDepth--, + () => { + if (!this.ENV.getBool("DEBUG") && !this.state.profiling) { + outputs = kernelFunc(); + } else { + kernelProfile = this.profiler.profileKernel(kernelOrScopeName, inputs, () => kernelFunc()); + if (this.ENV.getBool("DEBUG")) { + this.profiler.logKernelProfile(kernelProfile); + } + outputs = kernelProfile.outputs; + } + } + ); + if (isTapeOn) { + this.addTapeNode(kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs); + } + if (this.state.profiling) { + this.state.activeProfile.kernels.push({ + name: kernelOrScopeName, + bytesAdded: this.state.numBytes - startingBytecount, + totalBytesSnapshot: this.state.numBytes, + tensorsAdded: this.state.numTensors - startingNumTensors, + totalTensorsSnapshot: this.state.numTensors, + inputShapes: Object.keys(inputs).map((key) => inputs[key] != null ? inputs[key].shape : null), + outputShapes: outputs.map((item) => item.shape), + kernelTimeMs: kernelProfile.timeMs, + extraInfo: kernelProfile.extraInfo + }); + } + return Array.isArray(out) ? outputs : outputs[0]; + } + saveTensorsForBackwardMode(tensors) { + const saved = tensors.map((tensor3) => this.keep(this.clone(tensor3))); + return saved; + } + getTensorsForGradient(kernelName, inputs, outputs) { + const gradConfig = getGradient(kernelName); + if (gradConfig != null) { + const inputsToSave = gradConfig.inputsToSave || []; + const outputsToSave = gradConfig.outputsToSave || []; + let inputTensorsToSave; + if (gradConfig.saveAllInputs) { + assert(Array.isArray(inputs), () => "saveAllInputs is true, expected inputs to be an array."); + inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]); + } else { + inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]); + } + const outputTensorsToSave = outputs.filter((_, i) => outputsToSave[i]); + return inputTensorsToSave.concat(outputTensorsToSave); + } + return []; + } + makeTensor(values, shape, dtype, backend2) { + if (values == null) { + throw new Error("Values passed to engine.makeTensor() are null"); + } + dtype = dtype || "float32"; + backend2 = backend2 || this.backend; + let backendVals = values; + if (dtype === "string" && isString(values[0])) { + backendVals = values.map((d) => encodeString(d)); + } + const dataId = backend2.write(backendVals, shape, dtype); + const t = new Tensor(shape, dtype, dataId, this.nextTensorId()); + this.trackTensor(t, backend2); + if (dtype === "string") { + const info = this.state.tensorInfo.get(dataId); + const newBytes = bytesFromStringArray(backendVals); + this.state.numBytes += newBytes - info.bytes; + info.bytes = newBytes; + } + return t; + } + makeTensorFromDataId(dataId, shape, dtype, backend2) { + dtype = dtype || "float32"; + const tensorInfo = { dataId, shape, dtype }; + return this.makeTensorFromTensorInfo(tensorInfo, backend2); + } + makeTensorFromTensorInfo(tensorInfo, backend2) { + const { dataId, shape, dtype } = tensorInfo; + const t = new Tensor(shape, dtype, dataId, this.nextTensorId()); + this.trackTensor(t, backend2); + return t; + } + makeVariable(initialValue, trainable = true, name, dtype) { + name = name || this.nextVariableId().toString(); + if (dtype != null && dtype !== initialValue.dtype) { + initialValue = initialValue.cast(dtype); + } + const v = new Variable(initialValue, trainable, name, this.nextTensorId()); + if (this.state.registeredVariables[v.name] != null) { + throw new Error(`Variable with name ${v.name} was already registered`); + } + this.state.registeredVariables[v.name] = v; + this.incRef(v, this.backend); + return v; + } + trackTensor(a, backend2) { + this.state.numTensors++; + if (a.dtype === "string") { + this.state.numStringTensors++; + } + let bytes = 0; + if (a.dtype !== "complex64" && a.dtype !== "string") { + bytes = a.size * bytesPerElement(a.dtype); + } + this.state.numBytes += bytes; + if (!this.state.tensorInfo.has(a.dataId)) { + this.state.numDataBuffers++; + this.state.tensorInfo.set(a.dataId, { + backend: backend2 || this.backend, + dtype: a.dtype, + shape: a.shape, + bytes + }); + } + if (!(a instanceof Variable)) { + this.track(a); + } + } + incRef(a, backend2) { + this.trackTensor(a, backend2); + this.backend.incRef(a.dataId); + } + removeDataId(dataId, backend2) { + if (this.state.tensorInfo.has(dataId) && this.state.tensorInfo.get(dataId).backend === backend2) { + this.state.tensorInfo.delete(dataId); + this.state.numDataBuffers--; + } + } + disposeTensor(a) { + if (!this.state.tensorInfo.has(a.dataId)) { + return; + } + const info = this.state.tensorInfo.get(a.dataId); + this.state.numTensors--; + if (a.dtype === "string") { + this.state.numStringTensors--; + this.state.numBytes -= info.bytes; + } + if (a.dtype !== "complex64" && a.dtype !== "string") { + const bytes = a.size * bytesPerElement(a.dtype); + this.state.numBytes -= bytes; + } + if (info.backend.disposeData(a.dataId)) { + this.removeDataId(a.dataId, info.backend); + } + } + disposeVariables() { + for (const varName in this.state.registeredVariables) { + const v = this.state.registeredVariables[varName]; + this.disposeVariable(v); + } + } + disposeVariable(v) { + this.disposeTensor(v); + if (this.state.registeredVariables[v.name] != null) { + delete this.state.registeredVariables[v.name]; + } + } + memory() { + const info = this.backend.memory(); + info.numTensors = this.state.numTensors; + info.numDataBuffers = this.state.numDataBuffers; + info.numBytes = this.state.numBytes; + if (this.state.numStringTensors > 0) { + info.unreliable = true; + if (info.reasons == null) { + info.reasons = []; + } + info.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)"); + } + return info; + } + async profile(query) { + this.state.profiling = true; + const startBytes = this.state.numBytes; + const startNumTensors = this.state.numTensors; + this.state.activeProfile.kernels = []; + this.state.activeProfile.result = await query(); + this.state.profiling = false; + this.state.activeProfile.peakBytes = Math.max(...this.state.activeProfile.kernels.map((d) => d.totalBytesSnapshot)); + this.state.activeProfile.newBytes = this.state.numBytes - startBytes; + this.state.activeProfile.newTensors = this.state.numTensors - startNumTensors; + for (const kernel of this.state.activeProfile.kernels) { + kernel.kernelTimeMs = await kernel.kernelTimeMs; + kernel.extraInfo = await kernel.extraInfo; + } + return this.state.activeProfile; + } + isTapeOn() { + return this.state.gradientDepth > 0 && this.state.kernelDepth === 0; + } + addTapeNode(kernelName, inputs, outputs, gradientsFunc, saved, attrs) { + const tapeNode = { id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved }; + const gradConfig = getGradient(kernelName); + if (gradConfig != null) { + gradientsFunc = gradConfig.gradFunc; + } + if (gradientsFunc != null) { + tapeNode.gradient = (dys) => { + dys = dys.map((dy, i) => { + if (dy == null) { + const output = outputs[i]; + const vals = makeZerosTypedArray(output.size, output.dtype); + return this.makeTensor(vals, output.shape, output.dtype); + } + return dy; + }); + return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs); + }; + } + this.state.activeTape.push(tapeNode); + } + keep(result) { + result.kept = true; + return result; + } + startTape() { + if (this.state.gradientDepth === 0) { + this.state.activeTape = []; + } + this.state.gradientDepth++; + } + endTape() { + this.state.gradientDepth--; + } + startScope(name) { + const scopeInfo = { + track: [], + name: "unnamed scope", + id: this.state.nextScopeId++ + }; + if (name) { + scopeInfo.name = name; + } + this.state.scopeStack.push(scopeInfo); + this.state.activeScope = scopeInfo; + } + endScope(result) { + const tensorsToTrackInParent = getTensorsInContainer(result); + const tensorsToTrackInParentSet = new Set(tensorsToTrackInParent.map((t) => t.id)); + for (let i = 0; i < this.state.activeScope.track.length; i++) { + const tensor3 = this.state.activeScope.track[i]; + if (!tensor3.kept && !tensorsToTrackInParentSet.has(tensor3.id)) { + tensor3.dispose(); + } + } + const oldScope = this.state.scopeStack.pop(); + this.state.activeScope = this.state.scopeStack.length === 0 ? null : this.state.scopeStack[this.state.scopeStack.length - 1]; + tensorsToTrackInParent.forEach((tensor3) => { + if (!tensor3.kept && tensor3.scopeId === oldScope.id) { + this.track(tensor3); + } + }); + } + gradients(f, xs, dy, allowNoGradients = false) { + assert(xs.length > 0, () => "gradients() received an empty list of xs."); + if (dy != null && dy.dtype !== "float32") { + throw new Error(`dy must have 'float32' dtype, but has '${dy.dtype}'`); + } + const y = this.scopedRun(() => this.startTape(), () => this.endTape(), () => this.tidy("forward", f)); + assert(y instanceof Tensor, () => "The result y returned by f() must be a tensor."); + const filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y); + if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) { + throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y."); + } + return this.tidy("backward", () => { + const accumulatedGradientMap = {}; + accumulatedGradientMap[y.id] = dy == null ? ones(y.shape) : dy; + backpropagateGradients( + accumulatedGradientMap, + filteredTape, + (f2) => this.tidy(f2), + add + ); + const grads = xs.map((x) => accumulatedGradientMap[x.id]); + if (this.state.gradientDepth === 0) { + this.state.activeTape.forEach((node) => { + for (const tensor3 of node.saved) { + tensor3.dispose(); + } + }); + this.state.activeTape = null; + } + return { value: y, grads }; + }); + } + customGrad(f) { + assert(isFunction(f), () => "The f passed in customGrad(f) must be a function."); + return (...inputs) => { + assert(inputs.every((t) => t instanceof Tensor), () => "The args passed in customGrad(f)(x1, x2,...) must all be tensors"); + let res; + const inputMap = {}; + inputs.forEach((input2, i) => { + inputMap[i] = input2; + }); + const forwardFunc = (_, save) => { + res = f(...[...inputs, save]); + assert(res.value instanceof Tensor, () => "The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"); + assert(isFunction(res.gradFunc), () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."); + return res.value; + }; + const backwardsFunc = (dy, saved) => { + const gradRes = res.gradFunc(dy, saved); + const grads = Array.isArray(gradRes) ? gradRes : [gradRes]; + assert(grads.length === inputs.length, () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."); + assert(grads.every((t) => t instanceof Tensor), () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."); + const gradMap = {}; + grads.forEach((grad, i) => { + gradMap[i] = () => grad; + }); + return gradMap; + }; + return this.runKernelFunc({ + forwardFunc, + backwardsFunc, + inputs: inputMap + }); + }; + } + readSync(dataId) { + const info = this.state.tensorInfo.get(dataId); + return info.backend.readSync(dataId); + } + read(dataId) { + const info = this.state.tensorInfo.get(dataId); + return info.backend.read(dataId); + } + readToGPU(dataId, options) { + const info = this.state.tensorInfo.get(dataId); + return info.backend.readToGPU(dataId, options); + } + async time(query) { + const start = now(); + const timingInfo = await this.backend.time(query); + timingInfo.wallMs = now() - start; + return timingInfo; + } + track(result) { + if (this.state.activeScope != null) { + result.scopeId = this.state.activeScope.id; + this.state.activeScope.track.push(result); + } + return result; + } + get registeredVariables() { + return this.state.registeredVariables; + } + reset() { + this.pendingBackendInitId++; + this.state.dispose(); + this.ENV.reset(); + this.state = new EngineState(); + for (const backendName in this.registry) { + this.disposeRegisteredKernels(backendName); + this.registry[backendName].dispose(); + delete this.registry[backendName]; + } + this.backendName = null; + this.backendInstance = null; + this.pendingBackendInit = null; + } + }; + Engine.nextTensorId = 0; + Engine.nextVariableId = 0; + function ones(shape) { + const values = makeOnesTypedArray(sizeFromShape(shape), "float32"); + return ENGINE.makeTensor(values, shape, "float32"); + } + function getOrMakeEngine() { + const ns = getGlobalNamespace(); + if (ns._tfengine == null) { + const environment = new Environment(ns); + ns._tfengine = new Engine(environment); + } + setEnvironmentGlobal(ns._tfengine.ENV); + setTensorTracker(() => ns._tfengine); + return ns._tfengine; + } + var ENGINE = getOrMakeEngine(); + function add(a, b) { + const inputs = { a, b }; + return ENGINE.runKernel(Add, inputs); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/flags.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/device_util.js + var device_util_exports = {}; + __export(device_util_exports, { + isBrowser: () => isBrowser, + isMobile: () => isMobile, + mockIsMobile: () => mockIsMobile + }); + init_define_BUILD_VERSION(); + function _isNavigatorDefined() { + return typeof navigator !== "undefined" && navigator != null; + } + var isMobileMockValue; + function mockIsMobile(value) { + isMobileMockValue = value; + } + function isMobile(nav) { + if (isMobileMockValue !== void 0) { + return isMobileMockValue; + } + if (nav || _isNavigatorDefined()) { + if (!nav) { + nav = navigator; + } + if (nav.product === "ReactNative") { + return true; + } + const a = nav.userAgent || nav.vendor || (typeof window !== "undefined" ? window.opera : ""); + if (!a) { + const navAny = nav; + return navAny.userAgentData && navAny.userAgentData.mobile; + } + return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4)); + } + return false; + } + function isBrowser() { + return typeof window !== "undefined" && window.document != null || typeof WorkerGlobalScope !== "undefined"; + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/flags.js + var ENV2 = env(); + ENV2.registerFlag("DEBUG", () => false, (debugValue) => { + if (debugValue) { + console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance."); + } + }); + ENV2.registerFlag("IS_BROWSER", () => isBrowser()); + ENV2.registerFlag("IS_NODE", () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined"); + ENV2.registerFlag("IS_CHROME", () => typeof navigator !== "undefined" && navigator != null && navigator.userAgent != null && /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)); + ENV2.registerFlag("PROD", () => false); + ENV2.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", () => ENV2.getBool("DEBUG")); + ENV2.registerFlag("DEPRECATION_WARNINGS_ENABLED", () => true); + ENV2.registerFlag("IS_TEST", () => false); + ENV2.registerFlag("CHECK_COMPUTATION_FOR_ERRORS", () => true); + ENV2.registerFlag("WRAP_TO_IMAGEBITMAP", () => false); + ENV2.registerFlag("ENGINE_COMPILE_ONLY", () => false); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/platforms/platform_browser.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/indexed_db.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/io_utils.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/complex.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/tensor_util_env.js + init_define_BUILD_VERSION(); + function inferShape(val, dtype) { + let firstElem = val; + if (isTypedArray(val)) { + return dtype === "string" ? [] : [val.length]; + } + if (!Array.isArray(val)) { + return []; + } + const shape = []; + while (Array.isArray(firstElem) || isTypedArray(firstElem) && dtype !== "string") { + shape.push(firstElem.length); + firstElem = firstElem[0]; + } + if (Array.isArray(val) && env().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")) { + deepAssertShapeConsistency(val, shape, []); + } + return shape; + } + function deepAssertShapeConsistency(val, shape, indices) { + indices = indices || []; + if (!Array.isArray(val) && !isTypedArray(val)) { + assert(shape.length === 0, () => `Element arr[${indices.join("][")}] is a primitive, but should be an array/TypedArray of ${shape[0]} elements`); + return; + } + assert(shape.length > 0, () => `Element arr[${indices.join("][")}] should be a primitive, but is an array of ${val.length} elements`); + assert(val.length === shape[0], () => `Element arr[${indices.join("][")}] should have ${shape[0]} elements, but has ${val.length} elements`); + const subShape = shape.slice(1); + for (let i = 0; i < val.length; ++i) { + deepAssertShapeConsistency(val[i], subShape, indices.concat(i)); + } + } + function assertDtype(expectedDtype, actualDType, argName, functionName) { + if (expectedDtype === "string_or_numeric") { + return; + } + if (expectedDtype == null) { + throw new Error(`Expected dtype cannot be null.`); + } + if (expectedDtype !== "numeric" && expectedDtype !== actualDType || expectedDtype === "numeric" && actualDType === "string") { + throw new Error(`Argument '${argName}' passed to '${functionName}' must be ${expectedDtype} tensor, but got ${actualDType} tensor`); + } + } + function convertToTensor(x, argName, functionName, parseAsDtype = "numeric") { + if (x instanceof Tensor) { + assertDtype(parseAsDtype, x.dtype, argName, functionName); + return x; + } + let inferredDtype = inferDtype(x); + if (inferredDtype !== "string" && ["bool", "int32", "float32"].indexOf(parseAsDtype) >= 0) { + inferredDtype = parseAsDtype; + } + assertDtype(parseAsDtype, inferredDtype, argName, functionName); + if (x == null || !isTypedArray(x) && !Array.isArray(x) && typeof x !== "number" && typeof x !== "boolean" && typeof x !== "string") { + const type = x == null ? "null" : x.constructor.name; + throw new Error(`Argument '${argName}' passed to '${functionName}' must be a Tensor or TensorLike, but got '${type}'`); + } + const inferredShape = inferShape(x, inferredDtype); + if (!isTypedArray(x) && !Array.isArray(x)) { + x = [x]; + } + const skipTypedArray = true; + const values = inferredDtype !== "string" ? toTypedArray(x, inferredDtype) : flatten(x, [], skipTypedArray); + return ENGINE.makeTensor(values, inferredShape, inferredDtype); + } + function convertToTensorArray(arg, argName, functionName, parseAsDtype = "numeric") { + if (!Array.isArray(arg)) { + throw new Error(`Argument ${argName} passed to ${functionName} must be a \`Tensor[]\` or \`TensorLike[]\``); + } + const tensors = arg; + return tensors.map((t, i) => convertToTensor(t, `${argName}[${i}]`, functionName, parseAsDtype)); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/operation.js + init_define_BUILD_VERSION(); + var OP_SCOPE_SUFFIX = "__op"; + function op(f) { + const keys = Object.keys(f); + if (keys.length !== 1) { + throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${keys.length} keys.`); + } + let opName = keys[0]; + const fn = f[opName]; + if (opName.endsWith("_")) { + opName = opName.substring(0, opName.length - 1); + } + opName = opName + OP_SCOPE_SUFFIX; + const f2 = (...args) => { + ENGINE.startScope(opName); + try { + const result = fn(...args); + if (isPromise(result)) { + console.error("Cannot return a Promise inside of tidy."); + } + ENGINE.endScope(result); + return result; + } catch (ex) { + ENGINE.endScope(null); + throw ex; + } + }; + Object.defineProperty(f2, "name", { value: opName, configurable: true }); + return f2; + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/complex.js + function complex_(real4, imag4) { + const $real = convertToTensor(real4, "real", "complex"); + const $imag = convertToTensor(imag4, "imag", "complex"); + assertShapesMatch($real.shape, $imag.shape, `real and imag shapes, ${$real.shape} and ${$imag.shape}, must match in call to tf.complex().`); + const inputs = { real: $real, imag: $imag }; + return ENGINE.runKernel(Complex, inputs); + } + var complex = op({ complex_ }); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/tensor.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/tensor_ops_util.js + init_define_BUILD_VERSION(); + function makeTensor(values, shape, inferredShape, dtype) { + if (dtype == null) { + dtype = inferDtype(values); + } + if (dtype === "complex64") { + throw new Error(`Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).`); + } + if (!isTypedArray(values) && !Array.isArray(values) && typeof values !== "number" && typeof values !== "boolean" && typeof values !== "string") { + throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray"); + } + if (shape != null) { + assertNonNegativeIntegerDimensions(shape); + const providedSize = sizeFromShape(shape); + const inferredSize = sizeFromShape(inferredShape); + assert(providedSize === inferredSize, () => `Based on the provided shape, [${shape}], the tensor should have ${providedSize} values but has ${inferredSize}`); + for (let i = 0; i < inferredShape.length; ++i) { + const inferred = inferredShape[i]; + const flatDimsDontMatch = i === inferredShape.length - 1 ? inferred !== sizeFromShape(shape.slice(i)) : true; + assert(inferredShape[i] === shape[i] || !flatDimsDontMatch, () => `Error creating a new Tensor. Inferred shape (${inferredShape}) does not match the provided shape (${shape}). `); + } + } + if (!isTypedArray(values) && !Array.isArray(values)) { + values = [values]; + } + shape = shape || inferredShape; + values = dtype !== "string" ? toTypedArray(values, dtype) : flatten(values, [], true); + return ENGINE.makeTensor(values, shape, dtype); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/tensor.js + function tensor2(values, shape, dtype) { + const inferredShape = inferShape(values, dtype); + return makeTensor(values, shape, inferredShape, dtype); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/types.js + init_define_BUILD_VERSION(); + var DTYPE_VALUE_SIZE_MAP = { + "float32": 4, + "float16": 2, + "int32": 4, + "uint16": 2, + "uint8": 1, + "bool": 1, + "complex64": 8 + }; + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/io_utils.js + var NUM_BYTES_STRING_LENGTH = 4; + async function encodeWeights(tensors, group) { + const specs = []; + const dataPromises = []; + const names = Array.isArray(tensors) ? tensors.map((tensor3) => tensor3.name) : Object.keys(tensors); + for (let i = 0; i < names.length; ++i) { + const name = names[i]; + const t = Array.isArray(tensors) ? tensors[i].tensor : tensors[name]; + if (t.dtype !== "float32" && t.dtype !== "int32" && t.dtype !== "bool" && t.dtype !== "string" && t.dtype !== "complex64") { + throw new Error(`Unsupported dtype in weight '${name}': ${t.dtype}`); + } + const spec = { name, shape: t.shape, dtype: t.dtype }; + if (t.dtype === "string") { + const utf8bytes = new Promise(async (resolve) => { + const vals = await t.bytes(); + const totalNumBytes = vals.reduce((p2, c) => p2 + c.length, 0) + NUM_BYTES_STRING_LENGTH * vals.length; + const bytes = new Uint8Array(totalNumBytes); + let offset = 0; + for (let i2 = 0; i2 < vals.length; i2++) { + const val = vals[i2]; + const bytesOfLength = new Uint8Array(new Uint32Array([val.length]).buffer); + bytes.set(bytesOfLength, offset); + offset += NUM_BYTES_STRING_LENGTH; + bytes.set(val, offset); + offset += val.length; + } + resolve(bytes); + }); + dataPromises.push(utf8bytes); + } else { + dataPromises.push(t.data()); + } + if (group != null) { + spec.group = group; + } + specs.push(spec); + } + const tensorValues = await Promise.all(dataPromises); + return { data: concatenateTypedArrays(tensorValues), specs }; + } + function decodeWeights(buffer2, specs) { + const out = {}; + let float16Decode; + let offset = 0; + for (const spec of specs) { + const name = spec.name; + const dtype = spec.dtype; + const shape = spec.shape; + const size = sizeFromShape(shape); + let values; + if ("quantization" in spec) { + const quantization = spec.quantization; + if (quantization.dtype === "uint8" || quantization.dtype === "uint16") { + if (!("min" in quantization && "scale" in quantization)) { + throw new Error(`Weight ${spec.name} with quantization ${quantization.dtype} doesn't have corresponding metadata min and scale.`); + } + } else if (quantization.dtype === "float16") { + if (dtype !== "float32") { + throw new Error(`Weight ${spec.name} is quantized with ${quantization.dtype} which only supports weights of type float32 not ${dtype}.`); + } + } else { + throw new Error(`Weight ${spec.name} has unknown quantization dtype ${quantization.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`); + } + const quantizationSizeFactor = DTYPE_VALUE_SIZE_MAP[quantization.dtype]; + const byteBuffer = buffer2.slice(offset, offset + size * quantizationSizeFactor); + const quantizedArray = quantization.dtype === "uint8" ? new Uint8Array(byteBuffer) : new Uint16Array(byteBuffer); + if (dtype === "float32") { + if (quantization.dtype === "uint8" || quantization.dtype === "uint16") { + values = new Float32Array(quantizedArray.length); + for (let i = 0; i < quantizedArray.length; i++) { + const v = quantizedArray[i]; + values[i] = v * quantization.scale + quantization.min; + } + } else if (quantization.dtype === "float16") { + if (float16Decode === void 0) { + float16Decode = getFloat16Decoder(); + } + values = float16Decode(quantizedArray); + } else { + throw new Error(`Unsupported quantization type ${quantization.dtype} for weight type float32.`); + } + } else if (dtype === "int32") { + if (quantization.dtype !== "uint8" && quantization.dtype !== "uint16") { + throw new Error(`Unsupported quantization type ${quantization.dtype} for weight type int32.`); + } + values = new Int32Array(quantizedArray.length); + for (let i = 0; i < quantizedArray.length; i++) { + const v = quantizedArray[i]; + values[i] = Math.round(v * quantization.scale + quantization.min); + } + } else { + throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`); + } + offset += size * quantizationSizeFactor; + } else if (dtype === "string") { + const size2 = sizeFromShape(spec.shape); + values = []; + for (let i = 0; i < size2; i++) { + const byteLength = new Uint32Array(buffer2.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0]; + offset += NUM_BYTES_STRING_LENGTH; + const bytes = new Uint8Array(buffer2.slice(offset, offset + byteLength)); + values.push(bytes); + offset += byteLength; + } + } else { + const dtypeFactor = DTYPE_VALUE_SIZE_MAP[dtype]; + const byteBuffer = buffer2.slice(offset, offset + size * dtypeFactor); + if (dtype === "float32") { + values = new Float32Array(byteBuffer); + } else if (dtype === "int32") { + values = new Int32Array(byteBuffer); + } else if (dtype === "bool") { + values = new Uint8Array(byteBuffer); + } else if (dtype === "complex64") { + values = new Float32Array(byteBuffer); + const real4 = new Float32Array(values.length / 2); + const image3 = new Float32Array(values.length / 2); + for (let i = 0; i < real4.length; i++) { + real4[i] = values[i * 2]; + image3[i] = values[i * 2 + 1]; + } + const realTensor = tensor2(real4, shape, "float32"); + const imageTensor = tensor2(image3, shape, "float32"); + out[name] = complex(realTensor, imageTensor); + realTensor.dispose(); + imageTensor.dispose(); + } else { + throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`); + } + offset += size * dtypeFactor; + } + if (dtype !== "complex64") { + out[name] = tensor2(values, shape, dtype); + } + } + return out; + } + function concatenateTypedArrays(xs) { + if (xs === null) { + throw new Error(`Invalid input value: ${JSON.stringify(xs)}`); + } + let totalByteLength = 0; + const normalizedXs = []; + xs.forEach((x) => { + totalByteLength += x.byteLength; + normalizedXs.push(x.byteLength === x.buffer.byteLength ? x : new x.constructor(x)); + if (!(x instanceof Float32Array || x instanceof Int32Array || x instanceof Uint8Array)) { + throw new Error(`Unsupported TypedArray subtype: ${x.constructor.name}`); + } + }); + const y = new Uint8Array(totalByteLength); + let offset = 0; + normalizedXs.forEach((x) => { + y.set(new Uint8Array(x.buffer), offset); + offset += x.byteLength; + }); + return y.buffer; + } + var useNodeBuffer = typeof Buffer !== "undefined" && (typeof Blob === "undefined" || typeof atob === "undefined" || typeof btoa === "undefined"); + function stringByteLength(str) { + if (useNodeBuffer) { + return Buffer.byteLength(str); + } + return new Blob([str]).size; + } + function arrayBufferToBase64String(buffer2) { + if (useNodeBuffer) { + return Buffer.from(buffer2).toString("base64"); + } + const buf = new Uint8Array(buffer2); + let s = ""; + for (let i = 0, l = buf.length; i < l; i++) { + s += String.fromCharCode(buf[i]); + } + return btoa(s); + } + function base64StringToArrayBuffer(str) { + if (useNodeBuffer) { + const buf = Buffer.from(str, "base64"); + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + } + const s = atob(str); + const buffer2 = new Uint8Array(s.length); + for (let i = 0; i < s.length; ++i) { + buffer2.set([s.charCodeAt(i)], i); + } + return buffer2.buffer; + } + function concatenateArrayBuffers(buffers) { + if (buffers.length === 1) { + return buffers[0]; + } + let totalByteLength = 0; + buffers.forEach((buffer2) => { + totalByteLength += buffer2.byteLength; + }); + const temp = new Uint8Array(totalByteLength); + let offset = 0; + buffers.forEach((buffer2) => { + temp.set(new Uint8Array(buffer2), offset); + offset += buffer2.byteLength; + }); + return temp.buffer; + } + function basename(path) { + const SEPARATOR = "/"; + path = path.trim(); + while (path.endsWith(SEPARATOR)) { + path = path.slice(0, path.length - 1); + } + const items = path.split(SEPARATOR); + return items[items.length - 1]; + } + function getModelJSONForModelArtifacts(artifacts, manifest) { + const result = { + modelTopology: artifacts.modelTopology, + format: artifacts.format, + generatedBy: artifacts.generatedBy, + convertedBy: artifacts.convertedBy, + weightsManifest: manifest + }; + if (artifacts.signature != null) { + result.signature = artifacts.signature; + } + if (artifacts.userDefinedMetadata != null) { + result.userDefinedMetadata = artifacts.userDefinedMetadata; + } + if (artifacts.modelInitializer != null) { + result.modelInitializer = artifacts.modelInitializer; + } + if (artifacts.trainingConfig != null) { + result.trainingConfig = artifacts.trainingConfig; + } + return result; + } + async function getModelArtifactsForJSON(modelJSON, loadWeights2) { + const modelArtifacts = { + modelTopology: modelJSON.modelTopology, + format: modelJSON.format, + generatedBy: modelJSON.generatedBy, + convertedBy: modelJSON.convertedBy + }; + if (modelJSON.trainingConfig != null) { + modelArtifacts.trainingConfig = modelJSON.trainingConfig; + } + if (modelJSON.weightsManifest != null) { + const [weightSpecs, weightData] = await loadWeights2(modelJSON.weightsManifest); + modelArtifacts.weightSpecs = weightSpecs; + modelArtifacts.weightData = weightData; + } + if (modelJSON.signature != null) { + modelArtifacts.signature = modelJSON.signature; + } + if (modelJSON.userDefinedMetadata != null) { + modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata; + } + if (modelJSON.modelInitializer != null) { + modelArtifacts.modelInitializer = modelJSON.modelInitializer; + } + return modelArtifacts; + } + function getModelArtifactsInfoForJSON(modelArtifacts) { + if (modelArtifacts.modelTopology instanceof ArrayBuffer) { + throw new Error("Expected JSON model topology, received ArrayBuffer."); + } + return { + dateSaved: new Date(), + modelTopologyType: "JSON", + modelTopologyBytes: modelArtifacts.modelTopology == null ? 0 : stringByteLength(JSON.stringify(modelArtifacts.modelTopology)), + weightSpecsBytes: modelArtifacts.weightSpecs == null ? 0 : stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)), + weightDataBytes: modelArtifacts.weightData == null ? 0 : modelArtifacts.weightData.byteLength + }; + } + function computeFloat16MantisaTable() { + const convertMantissa = (i) => { + let m = i << 13; + let e = 0; + while ((m & 8388608) === 0) { + e -= 8388608; + m <<= 1; + } + m &= ~8388608; + e += 947912704; + return m | e; + }; + const mantisaTable = new Uint32Array(2048); + mantisaTable[0] = 0; + for (let i = 1; i < 1024; i++) { + mantisaTable[i] = convertMantissa(i); + } + for (let i = 1024; i < 2048; i++) { + mantisaTable[i] = 939524096 + (i - 1024 << 13); + } + return mantisaTable; + } + function computeFloat16ExponentTable() { + const exponentTable = new Uint32Array(64); + exponentTable[0] = 0; + exponentTable[31] = 1199570944; + exponentTable[32] = 2147483648; + exponentTable[63] = 3347054592; + for (let i = 1; i < 31; i++) { + exponentTable[i] = i << 23; + } + for (let i = 33; i < 63; i++) { + exponentTable[i] = 2147483648 + (i - 32 << 23); + } + return exponentTable; + } + function computeFloat16OffsetTable() { + const offsetTable = new Uint32Array(64); + for (let i = 0; i < 64; i++) { + offsetTable[i] = 1024; + } + offsetTable[0] = offsetTable[32] = 0; + return offsetTable; + } + function getFloat16Decoder() { + const mantisaTable = computeFloat16MantisaTable(); + const exponentTable = computeFloat16ExponentTable(); + const offsetTable = computeFloat16OffsetTable(); + return (quantizedArray) => { + const buffer2 = new ArrayBuffer(4 * quantizedArray.length); + const bufferUint32View = new Uint32Array(buffer2); + for (let index = 0; index < quantizedArray.length; index++) { + const float16Bits = quantizedArray[index]; + const float32Bits = mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 1023)] + exponentTable[float16Bits >> 10]; + bufferUint32View[index] = float32Bits; + } + return new Float32Array(buffer2); + }; + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/router_registry.js + init_define_BUILD_VERSION(); + var IORouterRegistry = class { + constructor() { + this.saveRouters = []; + this.loadRouters = []; + } + static getInstance() { + if (IORouterRegistry.instance == null) { + IORouterRegistry.instance = new IORouterRegistry(); + } + return IORouterRegistry.instance; + } + static registerSaveRouter(saveRouter) { + IORouterRegistry.getInstance().saveRouters.push(saveRouter); + } + static registerLoadRouter(loadRouter) { + IORouterRegistry.getInstance().loadRouters.push(loadRouter); + } + static getSaveHandlers(url) { + return IORouterRegistry.getHandlers(url, "save"); + } + static getLoadHandlers(url, loadOptions) { + return IORouterRegistry.getHandlers(url, "load", loadOptions); + } + static getHandlers(url, handlerType, loadOptions) { + const validHandlers = []; + const routers = handlerType === "load" ? IORouterRegistry.getInstance().loadRouters : IORouterRegistry.getInstance().saveRouters; + routers.forEach((router) => { + const handler = router(url, loadOptions); + if (handler !== null) { + validHandlers.push(handler); + } + }); + return validHandlers; + } + }; + var registerSaveRouter = (loudRouter) => IORouterRegistry.registerSaveRouter(loudRouter); + var registerLoadRouter = (loudRouter) => IORouterRegistry.registerLoadRouter(loudRouter); + var getSaveHandlers = (url) => IORouterRegistry.getSaveHandlers(url); + var getLoadHandlers = (url, loadOptions) => IORouterRegistry.getLoadHandlers(url, loadOptions); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/indexed_db.js + var DATABASE_NAME = "tensorflowjs"; + var DATABASE_VERSION = 1; + var MODEL_STORE_NAME = "models_store"; + var INFO_STORE_NAME = "model_info_store"; + function getIndexedDBFactory() { + if (!env().getBool("IS_BROWSER")) { + throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser."); + } + const theWindow = typeof window === "undefined" ? self : window; + const factory = theWindow.indexedDB || theWindow.mozIndexedDB || theWindow.webkitIndexedDB || theWindow.msIndexedDB || theWindow.shimIndexedDB; + if (factory == null) { + throw new Error("The current browser does not appear to support IndexedDB."); + } + return factory; + } + function setUpDatabase(openRequest) { + const db = openRequest.result; + db.createObjectStore(MODEL_STORE_NAME, { keyPath: "modelPath" }); + db.createObjectStore(INFO_STORE_NAME, { keyPath: "modelPath" }); + } + var BrowserIndexedDB = class { + constructor(modelPath) { + this.indexedDB = getIndexedDBFactory(); + if (modelPath == null || !modelPath) { + throw new Error("For IndexedDB, modelPath must not be null, undefined or empty."); + } + this.modelPath = modelPath; + } + async save(modelArtifacts) { + if (modelArtifacts.modelTopology instanceof ArrayBuffer) { + throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet."); + } + return this.databaseAction(this.modelPath, modelArtifacts); + } + async load() { + return this.databaseAction(this.modelPath); + } + databaseAction(modelPath, modelArtifacts) { + return new Promise((resolve, reject) => { + const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION); + openRequest.onupgradeneeded = () => setUpDatabase(openRequest); + openRequest.onsuccess = () => { + const db = openRequest.result; + if (modelArtifacts == null) { + const modelTx = db.transaction(MODEL_STORE_NAME, "readonly"); + const modelStore = modelTx.objectStore(MODEL_STORE_NAME); + const getRequest = modelStore.get(this.modelPath); + getRequest.onsuccess = () => { + if (getRequest.result == null) { + db.close(); + return reject(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`)); + } else { + resolve(getRequest.result.modelArtifacts); + } + }; + getRequest.onerror = (error) => { + db.close(); + return reject(getRequest.error); + }; + modelTx.oncomplete = () => db.close(); + } else { + const modelArtifactsInfo = getModelArtifactsInfoForJSON(modelArtifacts); + const infoTx = db.transaction(INFO_STORE_NAME, "readwrite"); + let infoStore = infoTx.objectStore(INFO_STORE_NAME); + const putInfoRequest = infoStore.put({ modelPath: this.modelPath, modelArtifactsInfo }); + let modelTx; + putInfoRequest.onsuccess = () => { + modelTx = db.transaction(MODEL_STORE_NAME, "readwrite"); + const modelStore = modelTx.objectStore(MODEL_STORE_NAME); + const putModelRequest = modelStore.put({ + modelPath: this.modelPath, + modelArtifacts, + modelArtifactsInfo + }); + putModelRequest.onsuccess = () => resolve({ modelArtifactsInfo }); + putModelRequest.onerror = (error) => { + infoStore = infoTx.objectStore(INFO_STORE_NAME); + const deleteInfoRequest = infoStore.delete(this.modelPath); + deleteInfoRequest.onsuccess = () => { + db.close(); + return reject(putModelRequest.error); + }; + deleteInfoRequest.onerror = (error2) => { + db.close(); + return reject(putModelRequest.error); + }; + }; + }; + putInfoRequest.onerror = (error) => { + db.close(); + return reject(putInfoRequest.error); + }; + infoTx.oncomplete = () => { + if (modelTx == null) { + db.close(); + } else { + modelTx.oncomplete = () => db.close(); + } + }; + } + }; + openRequest.onerror = (error) => reject(openRequest.error); + }); + } + }; + BrowserIndexedDB.URL_SCHEME = "indexeddb://"; + var indexedDBRouter = (url) => { + if (!env().getBool("IS_BROWSER")) { + return null; + } else { + if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) { + return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length)); + } else { + return null; + } + } + }; + IORouterRegistry.registerSaveRouter(indexedDBRouter); + IORouterRegistry.registerLoadRouter(indexedDBRouter); + function browserIndexedDB(modelPath) { + return new BrowserIndexedDB(modelPath); + } + function maybeStripScheme(key) { + return key.startsWith(BrowserIndexedDB.URL_SCHEME) ? key.slice(BrowserIndexedDB.URL_SCHEME.length) : key; + } + var BrowserIndexedDBManager = class { + constructor() { + this.indexedDB = getIndexedDBFactory(); + } + async listModels() { + return new Promise((resolve, reject) => { + const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION); + openRequest.onupgradeneeded = () => setUpDatabase(openRequest); + openRequest.onsuccess = () => { + const db = openRequest.result; + const tx = db.transaction(INFO_STORE_NAME, "readonly"); + const store = tx.objectStore(INFO_STORE_NAME); + const getAllInfoRequest = store.getAll(); + getAllInfoRequest.onsuccess = () => { + const out = {}; + for (const item of getAllInfoRequest.result) { + out[item.modelPath] = item.modelArtifactsInfo; + } + resolve(out); + }; + getAllInfoRequest.onerror = (error) => { + db.close(); + return reject(getAllInfoRequest.error); + }; + tx.oncomplete = () => db.close(); + }; + openRequest.onerror = (error) => reject(openRequest.error); + }); + } + async removeModel(path) { + path = maybeStripScheme(path); + return new Promise((resolve, reject) => { + const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION); + openRequest.onupgradeneeded = () => setUpDatabase(openRequest); + openRequest.onsuccess = () => { + const db = openRequest.result; + const infoTx = db.transaction(INFO_STORE_NAME, "readwrite"); + const infoStore = infoTx.objectStore(INFO_STORE_NAME); + const getInfoRequest = infoStore.get(path); + let modelTx; + getInfoRequest.onsuccess = () => { + if (getInfoRequest.result == null) { + db.close(); + return reject(new Error(`Cannot find model with path '${path}' in IndexedDB.`)); + } else { + const deleteInfoRequest = infoStore.delete(path); + const deleteModelData = () => { + modelTx = db.transaction(MODEL_STORE_NAME, "readwrite"); + const modelStore = modelTx.objectStore(MODEL_STORE_NAME); + const deleteModelRequest = modelStore.delete(path); + deleteModelRequest.onsuccess = () => resolve(getInfoRequest.result.modelArtifactsInfo); + deleteModelRequest.onerror = (error) => reject(getInfoRequest.error); + }; + deleteInfoRequest.onsuccess = deleteModelData; + deleteInfoRequest.onerror = (error) => { + deleteModelData(); + db.close(); + return reject(getInfoRequest.error); + }; + } + }; + getInfoRequest.onerror = (error) => { + db.close(); + return reject(getInfoRequest.error); + }; + infoTx.oncomplete = () => { + if (modelTx == null) { + db.close(); + } else { + modelTx.oncomplete = () => db.close(); + } + }; + }; + openRequest.onerror = (error) => reject(openRequest.error); + }); + } + }; + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/local_storage.js + init_define_BUILD_VERSION(); + var PATH_SEPARATOR = "/"; + var PATH_PREFIX = "tensorflowjs_models"; + var INFO_SUFFIX = "info"; + var MODEL_TOPOLOGY_SUFFIX = "model_topology"; + var WEIGHT_SPECS_SUFFIX = "weight_specs"; + var WEIGHT_DATA_SUFFIX = "weight_data"; + var MODEL_METADATA_SUFFIX = "model_metadata"; + function getModelKeys(path) { + return { + info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR), + topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR), + weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR), + weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR), + modelMetadata: [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR) + }; + } + function removeItems(keys) { + for (const key of Object.values(keys)) { + window.localStorage.removeItem(key); + } + } + function getModelPathFromKey(key) { + const items = key.split(PATH_SEPARATOR); + if (items.length < 3) { + throw new Error(`Invalid key format: ${key}`); + } + return items.slice(1, items.length - 1).join(PATH_SEPARATOR); + } + function maybeStripScheme2(key) { + return key.startsWith(BrowserLocalStorage.URL_SCHEME) ? key.slice(BrowserLocalStorage.URL_SCHEME.length) : key; + } + var BrowserLocalStorage = class { + constructor(modelPath) { + if (!env().getBool("IS_BROWSER") || typeof window === "undefined" || typeof window.localStorage === "undefined") { + throw new Error("The current environment does not support local storage."); + } + this.LS = window.localStorage; + if (modelPath == null || !modelPath) { + throw new Error("For local storage, modelPath must not be null, undefined or empty."); + } + this.modelPath = modelPath; + this.keys = getModelKeys(this.modelPath); + } + async save(modelArtifacts) { + if (modelArtifacts.modelTopology instanceof ArrayBuffer) { + throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet."); + } else { + const topology = JSON.stringify(modelArtifacts.modelTopology); + const weightSpecs = JSON.stringify(modelArtifacts.weightSpecs); + const modelArtifactsInfo = getModelArtifactsInfoForJSON(modelArtifacts); + try { + this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo)); + this.LS.setItem(this.keys.topology, topology); + this.LS.setItem(this.keys.weightSpecs, weightSpecs); + this.LS.setItem(this.keys.weightData, arrayBufferToBase64String(modelArtifacts.weightData)); + const metadata = { + format: modelArtifacts.format, + generatedBy: modelArtifacts.generatedBy, + convertedBy: modelArtifacts.convertedBy, + signature: modelArtifacts.signature != null ? modelArtifacts.signature : void 0, + userDefinedMetadata: modelArtifacts.userDefinedMetadata != null ? modelArtifacts.userDefinedMetadata : void 0, + modelInitializer: modelArtifacts.modelInitializer != null ? modelArtifacts.modelInitializer : void 0, + trainingConfig: modelArtifacts.trainingConfig != null ? modelArtifacts.trainingConfig : void 0 + }; + this.LS.setItem(this.keys.modelMetadata, JSON.stringify(metadata)); + return { modelArtifactsInfo }; + } catch (err) { + removeItems(this.keys); + throw new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${modelArtifactsInfo.modelTopologyBytes}, weightSpecsBytes=${modelArtifactsInfo.weightSpecsBytes}, weightDataBytes=${modelArtifactsInfo.weightDataBytes}.`); + } + } + } + async load() { + const info = JSON.parse(this.LS.getItem(this.keys.info)); + if (info == null) { + throw new Error(`In local storage, there is no model with name '${this.modelPath}'`); + } + if (info.modelTopologyType !== "JSON") { + throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet."); + } + const out = {}; + const topology = JSON.parse(this.LS.getItem(this.keys.topology)); + if (topology == null) { + throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`); + } + out.modelTopology = topology; + const weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs)); + if (weightSpecs == null) { + throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`); + } + out.weightSpecs = weightSpecs; + const metadataString = this.LS.getItem(this.keys.modelMetadata); + if (metadataString != null) { + const metadata = JSON.parse(metadataString); + out.format = metadata.format; + out.generatedBy = metadata.generatedBy; + out.convertedBy = metadata.convertedBy; + if (metadata.signature != null) { + out.signature = metadata.signature; + } + if (metadata.userDefinedMetadata != null) { + out.userDefinedMetadata = metadata.userDefinedMetadata; + } + if (metadata.modelInitializer != null) { + out.modelInitializer = metadata.modelInitializer; + } + if (metadata.trainingConfig != null) { + out.trainingConfig = metadata.trainingConfig; + } + } + const weightDataBase64 = this.LS.getItem(this.keys.weightData); + if (weightDataBase64 == null) { + throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`); + } + out.weightData = base64StringToArrayBuffer(weightDataBase64); + return out; + } + }; + BrowserLocalStorage.URL_SCHEME = "localstorage://"; + var localStorageRouter = (url) => { + if (!env().getBool("IS_BROWSER")) { + return null; + } else { + if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) { + return browserLocalStorage(url.slice(BrowserLocalStorage.URL_SCHEME.length)); + } else { + return null; + } + } + }; + IORouterRegistry.registerSaveRouter(localStorageRouter); + IORouterRegistry.registerLoadRouter(localStorageRouter); + function browserLocalStorage(modelPath) { + return new BrowserLocalStorage(modelPath); + } + var BrowserLocalStorageManager = class { + constructor() { + assert(env().getBool("IS_BROWSER"), () => "Current environment is not a web browser"); + assert(typeof window === "undefined" || typeof window.localStorage !== "undefined", () => "Current browser does not appear to support localStorage"); + this.LS = window.localStorage; + } + async listModels() { + const out = {}; + const prefix = PATH_PREFIX + PATH_SEPARATOR; + const suffix = PATH_SEPARATOR + INFO_SUFFIX; + for (let i = 0; i < this.LS.length; ++i) { + const key = this.LS.key(i); + if (key.startsWith(prefix) && key.endsWith(suffix)) { + const modelPath = getModelPathFromKey(key); + out[modelPath] = JSON.parse(this.LS.getItem(key)); + } + } + return out; + } + async removeModel(path) { + path = maybeStripScheme2(path); + const keys = getModelKeys(path); + if (this.LS.getItem(keys.info) == null) { + throw new Error(`Cannot find model at path '${path}'`); + } + const info = JSON.parse(this.LS.getItem(keys.info)); + removeItems(keys); + return info; + } + }; + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/model_management.js + init_define_BUILD_VERSION(); + var URL_SCHEME_SUFFIX = "://"; + var ModelStoreManagerRegistry = class { + constructor() { + this.managers = {}; + } + static getInstance() { + if (ModelStoreManagerRegistry.instance == null) { + ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry(); + } + return ModelStoreManagerRegistry.instance; + } + static registerManager(scheme, manager) { + assert(scheme != null, () => "scheme must not be undefined or null."); + if (scheme.endsWith(URL_SCHEME_SUFFIX)) { + scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX)); + } + assert(scheme.length > 0, () => "scheme must not be an empty string."); + const registry = ModelStoreManagerRegistry.getInstance(); + assert(registry.managers[scheme] == null, () => `A model store manager is already registered for scheme '${scheme}'.`); + registry.managers[scheme] = manager; + } + static getManager(scheme) { + const manager = ModelStoreManagerRegistry.getInstance().managers[scheme]; + if (manager == null) { + throw new Error(`Cannot find model manager for scheme '${scheme}'`); + } + return manager; + } + static getSchemes() { + return Object.keys(ModelStoreManagerRegistry.getInstance().managers); + } + }; + function parseURL(url) { + if (url.indexOf(URL_SCHEME_SUFFIX) === -1) { + throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${ModelStoreManagerRegistry.getSchemes().join(",")}`); + } + return { + scheme: url.split(URL_SCHEME_SUFFIX)[0], + path: url.split(URL_SCHEME_SUFFIX)[1] + }; + } + async function cloneModelInternal(sourceURL, destURL, deleteSource = false) { + assert(sourceURL !== destURL, () => `Old path and new path are the same: '${sourceURL}'`); + const loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL); + assert(loadHandlers.length > 0, () => `Copying failed because no load handler is found for source URL ${sourceURL}.`); + assert(loadHandlers.length < 2, () => `Copying failed because more than one (${loadHandlers.length}) load handlers for source URL ${sourceURL}.`); + const loadHandler = loadHandlers[0]; + const saveHandlers = IORouterRegistry.getSaveHandlers(destURL); + assert(saveHandlers.length > 0, () => `Copying failed because no save handler is found for destination URL ${destURL}.`); + assert(saveHandlers.length < 2, () => `Copying failed because more than one (${loadHandlers.length}) save handlers for destination URL ${destURL}.`); + const saveHandler = saveHandlers[0]; + const sourceScheme = parseURL(sourceURL).scheme; + const sourcePath = parseURL(sourceURL).path; + const sameMedium = sourceScheme === parseURL(sourceURL).scheme; + const modelArtifacts = await loadHandler.load(); + if (deleteSource && sameMedium) { + await ModelStoreManagerRegistry.getManager(sourceScheme).removeModel(sourcePath); + } + const saveResult = await saveHandler.save(modelArtifacts); + if (deleteSource && !sameMedium) { + await ModelStoreManagerRegistry.getManager(sourceScheme).removeModel(sourcePath); + } + return saveResult.modelArtifactsInfo; + } + async function listModels() { + const schemes = ModelStoreManagerRegistry.getSchemes(); + const out = {}; + for (const scheme of schemes) { + const schemeOut = await ModelStoreManagerRegistry.getManager(scheme).listModels(); + for (const path in schemeOut) { + const url = scheme + URL_SCHEME_SUFFIX + path; + out[url] = schemeOut[path]; + } + } + return out; + } + async function removeModel(url) { + const schemeAndPath = parseURL(url); + const manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme); + return manager.removeModel(schemeAndPath.path); + } + async function copyModel(sourceURL, destURL) { + const deleteSource = false; + return cloneModelInternal(sourceURL, destURL, deleteSource); + } + async function moveModel(sourceURL, destURL) { + const deleteSource = true; + return cloneModelInternal(sourceURL, destURL, deleteSource); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/platforms/platform_browser.js + var PlatformBrowser = class { + fetch(path, init) { + return fetch(path, init); + } + now() { + return performance.now(); + } + encode(text, encoding) { + if (encoding !== "utf-8" && encoding !== "utf8") { + throw new Error(`Browser's encoder only supports utf-8, but got ${encoding}`); + } + if (this.textEncoder == null) { + this.textEncoder = new TextEncoder(); + } + return this.textEncoder.encode(text); + } + decode(bytes, encoding) { + return new TextDecoder(encoding).decode(bytes); + } + }; + if (env().get("IS_BROWSER")) { + env().setPlatform("browser", new PlatformBrowser()); + try { + ModelStoreManagerRegistry.registerManager(BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager()); + } catch (err) { + } + try { + ModelStoreManagerRegistry.registerManager(BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager()); + } catch (err) { + } + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/platforms/platform_node.js + init_define_BUILD_VERSION(); + var getNodeFetch = { + importFetch: () => require_browser() + }; + var systemFetch; + var PlatformNode = class { + constructor() { + this.util = require_util(); + this.textEncoder = new this.util.TextEncoder(); + } + fetch(path, requestInits) { + if (env().global.fetch != null) { + return env().global.fetch(path, requestInits); + } + if (systemFetch == null) { + systemFetch = getNodeFetch.importFetch(); + } + return systemFetch(path, requestInits); + } + now() { + const time = process.hrtime(); + return time[0] * 1e3 + time[1] / 1e6; + } + encode(text, encoding) { + if (encoding !== "utf-8" && encoding !== "utf8") { + throw new Error(`Node built-in encoder only supports utf-8, but got ${encoding}`); + } + return this.textEncoder.encode(text); + } + decode(bytes, encoding) { + if (bytes.length === 0) { + return ""; + } + return new this.util.TextDecoder(encoding).decode(bytes); + } + }; + if (env().get("IS_NODE") && !env().get("IS_BROWSER")) { + env().setPlatform("node", new PlatformNode()); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/buffer.js + init_define_BUILD_VERSION(); + function buffer(shape, dtype = "float32", values) { + dtype = dtype || "float32"; + assertNonNegativeIntegerDimensions(shape); + return new TensorBuffer(shape, dtype, values); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/cast.js + init_define_BUILD_VERSION(); + function cast_(x, dtype) { + const $x = convertToTensor(x, "x", "cast"); + if (!isValidDtype(dtype)) { + throw new Error(`Failed to cast to unknown dtype ${dtype}`); + } + if (dtype === "string" && $x.dtype !== "string" || dtype !== "string" && $x.dtype === "string") { + throw new Error("Only strings can be casted to strings"); + } + const inputs = { x: $x }; + const attrs = { dtype }; + return ENGINE.runKernel(Cast, inputs, attrs); + } + var cast = op({ cast_ }); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/clone.js + init_define_BUILD_VERSION(); + function clone_(x) { + const $x = convertToTensor(x, "x", "clone", "string_or_numeric"); + const inputs = { x: $x }; + return ENGINE.runKernel(Identity, inputs); + } + var clone = op({ clone_ }); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/print.js + init_define_BUILD_VERSION(); + function print(x, verbose = false) { + console.log(x.toString(verbose)); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/base_side_effects.js + getOrMakeEngine(); + var opHandler2 = { + buffer, + cast, + clone, + print + }; + setOpHandler(opHandler2); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/base.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/io.js + var io_exports = {}; + __export(io_exports, { + browserFiles: () => browserFiles, + browserHTTPRequest: () => browserHTTPRequest, + concatenateArrayBuffers: () => concatenateArrayBuffers, + copyModel: () => copyModel, + decodeWeights: () => decodeWeights, + encodeWeights: () => encodeWeights, + fromMemory: () => fromMemory, + fromMemorySync: () => fromMemorySync, + getLoadHandlers: () => getLoadHandlers, + getModelArtifactsForJSON: () => getModelArtifactsForJSON, + getModelArtifactsInfoForJSON: () => getModelArtifactsInfoForJSON, + getSaveHandlers: () => getSaveHandlers, + http: () => http, + isHTTPScheme: () => isHTTPScheme, + listModels: () => listModels, + loadWeights: () => loadWeights, + moveModel: () => moveModel, + registerLoadRouter: () => registerLoadRouter, + registerSaveRouter: () => registerSaveRouter, + removeModel: () => removeModel, + weightsLoaderFactory: () => weightsLoaderFactory, + withSaveHandler: () => withSaveHandler, + withSaveHandlerSync: () => withSaveHandlerSync + }); + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/browser_files.js + init_define_BUILD_VERSION(); + var DEFAULT_FILE_NAME_PREFIX = "model"; + var DEFAULT_JSON_EXTENSION_NAME = ".json"; + var DEFAULT_WEIGHT_DATA_EXTENSION_NAME = ".weights.bin"; + function defer(f) { + return new Promise((resolve) => setTimeout(resolve)).then(f); + } + var BrowserDownloads = class { + constructor(fileNamePrefix) { + if (!env().getBool("IS_BROWSER")) { + throw new Error("browserDownloads() cannot proceed because the current environment is not a browser."); + } + if (fileNamePrefix.startsWith(BrowserDownloads.URL_SCHEME)) { + fileNamePrefix = fileNamePrefix.slice(BrowserDownloads.URL_SCHEME.length); + } + if (fileNamePrefix == null || fileNamePrefix.length === 0) { + fileNamePrefix = DEFAULT_FILE_NAME_PREFIX; + } + this.modelJsonFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME; + this.weightDataFileName = fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME; + } + async save(modelArtifacts) { + if (typeof document === "undefined") { + throw new Error("Browser downloads are not supported in this environment since `document` is not present"); + } + const weightsURL = window.URL.createObjectURL(new Blob([modelArtifacts.weightData], { type: "application/octet-stream" })); + if (modelArtifacts.modelTopology instanceof ArrayBuffer) { + throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet."); + } else { + const weightsManifest = [{ + paths: ["./" + this.weightDataFileName], + weights: modelArtifacts.weightSpecs + }]; + const modelJSON = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest); + const modelJsonURL = window.URL.createObjectURL(new Blob([JSON.stringify(modelJSON)], { type: "application/json" })); + const jsonAnchor = this.modelJsonAnchor == null ? document.createElement("a") : this.modelJsonAnchor; + jsonAnchor.download = this.modelJsonFileName; + jsonAnchor.href = modelJsonURL; + await defer(() => jsonAnchor.dispatchEvent(new MouseEvent("click"))); + if (modelArtifacts.weightData != null) { + const weightDataAnchor = this.weightDataAnchor == null ? document.createElement("a") : this.weightDataAnchor; + weightDataAnchor.download = this.weightDataFileName; + weightDataAnchor.href = weightsURL; + await defer(() => weightDataAnchor.dispatchEvent(new MouseEvent("click"))); + } + return { modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts) }; + } + } + }; + BrowserDownloads.URL_SCHEME = "downloads://"; + var BrowserFiles = class { + constructor(files) { + if (files == null || files.length < 1) { + throw new Error(`When calling browserFiles, at least 1 file is required, but received ${files}`); + } + this.jsonFile = files[0]; + this.weightsFiles = files.slice(1); + } + async load() { + return new Promise((resolve, reject) => { + const jsonReader = new FileReader(); + jsonReader.onload = (event) => { + const modelJSON = JSON.parse(event.target.result); + const modelTopology = modelJSON.modelTopology; + if (modelTopology == null) { + reject(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`)); + return; + } + const weightsManifest = modelJSON.weightsManifest; + if (weightsManifest == null) { + reject(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`)); + return; + } + if (this.weightsFiles.length === 0) { + resolve({ modelTopology }); + return; + } + const modelArtifactsPromise = getModelArtifactsForJSON(modelJSON, (weightsManifest2) => this.loadWeights(weightsManifest2)); + resolve(modelArtifactsPromise); + }; + jsonReader.onerror = (error) => reject(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`); + jsonReader.readAsText(this.jsonFile); + }); + } + loadWeights(weightsManifest) { + const weightSpecs = []; + const paths = []; + for (const entry of weightsManifest) { + weightSpecs.push(...entry.weights); + paths.push(...entry.paths); + } + const pathToFile = this.checkManifestAndWeightFiles(weightsManifest); + const promises = paths.map((path) => this.loadWeightsFile(path, pathToFile[path])); + return Promise.all(promises).then((buffers) => [weightSpecs, concatenateArrayBuffers(buffers)]); + } + loadWeightsFile(path, file) { + return new Promise((resolve, reject) => { + const weightFileReader = new FileReader(); + weightFileReader.onload = (event) => { + const weightData = event.target.result; + resolve(weightData); + }; + weightFileReader.onerror = (error) => reject(`Failed to weights data from file of path '${path}'.`); + weightFileReader.readAsArrayBuffer(file); + }); + } + checkManifestAndWeightFiles(manifest) { + const basenames = []; + const fileNames = this.weightsFiles.map((file) => basename(file.name)); + const pathToFile = {}; + for (const group of manifest) { + group.paths.forEach((path) => { + const pathBasename = basename(path); + if (basenames.indexOf(pathBasename) !== -1) { + throw new Error(`Duplicate file basename found in weights manifest: '${pathBasename}'`); + } + basenames.push(pathBasename); + if (fileNames.indexOf(pathBasename) === -1) { + throw new Error(`Weight file with basename '${pathBasename}' is not provided.`); + } else { + pathToFile[path] = this.weightsFiles[fileNames.indexOf(pathBasename)]; + } + }); + } + if (basenames.length !== this.weightsFiles.length) { + throw new Error(`Mismatch in the number of files in weights manifest (${basenames.length}) and the number of weight files provided (${this.weightsFiles.length}).`); + } + return pathToFile; + } + }; + var browserDownloadsRouter = (url) => { + if (!env().getBool("IS_BROWSER")) { + return null; + } else { + if (!Array.isArray(url) && url.startsWith(BrowserDownloads.URL_SCHEME)) { + return browserDownloads(url.slice(BrowserDownloads.URL_SCHEME.length)); + } else { + return null; + } + } + }; + IORouterRegistry.registerSaveRouter(browserDownloadsRouter); + function browserDownloads(fileNamePrefix = "model") { + return new BrowserDownloads(fileNamePrefix); + } + function browserFiles(files) { + return new BrowserFiles(files); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/http.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/weights_loader.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/progress.js + init_define_BUILD_VERSION(); + function monitorPromisesProgress(promises, onProgress, startFraction, endFraction) { + checkPromises(promises); + startFraction = startFraction == null ? 0 : startFraction; + endFraction = endFraction == null ? 1 : endFraction; + checkFraction(startFraction, endFraction); + let resolvedPromise = 0; + const registerMonitor = (promise) => { + promise.then((value) => { + const fraction = startFraction + ++resolvedPromise / promises.length * (endFraction - startFraction); + onProgress(fraction); + return value; + }); + return promise; + }; + function checkPromises(promises2) { + assert(promises2 != null && Array.isArray(promises2) && promises2.length > 0, () => "promises must be a none empty array"); + } + function checkFraction(startFraction2, endFraction2) { + assert(startFraction2 >= 0 && startFraction2 <= 1, () => `Progress fraction must be in range [0, 1], but got startFraction ${startFraction2}`); + assert(endFraction2 >= 0 && endFraction2 <= 1, () => `Progress fraction must be in range [0, 1], but got endFraction ${endFraction2}`); + assert(endFraction2 >= startFraction2, () => `startFraction must be no more than endFraction, but got startFraction ${startFraction2} and endFraction ${endFraction2}`); + } + return Promise.all(promises.map(registerMonitor)); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/weights_loader.js + async function loadWeightsAsArrayBuffer(fetchURLs, loadOptions) { + if (loadOptions == null) { + loadOptions = {}; + } + const fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch : loadOptions.fetchFunc; + const requests = fetchURLs.map((fetchURL) => fetchFunc(fetchURL, loadOptions.requestInit, { isBinary: true })); + const fetchStartFraction = 0; + const fetchEndFraction = 0.5; + const responses = loadOptions.onProgress == null ? await Promise.all(requests) : await monitorPromisesProgress(requests, loadOptions.onProgress, fetchStartFraction, fetchEndFraction); + const bufferPromises = responses.map((response) => response.arrayBuffer()); + const bufferStartFraction = 0.5; + const bufferEndFraction = 1; + const buffers = loadOptions.onProgress == null ? await Promise.all(bufferPromises) : await monitorPromisesProgress(bufferPromises, loadOptions.onProgress, bufferStartFraction, bufferEndFraction); + return buffers; + } + async function loadWeights(manifest, filePathPrefix = "", weightNames, requestInit) { + const fetchWeights = (fetchUrls) => loadWeightsAsArrayBuffer(fetchUrls, { requestInit }); + const loadWeights2 = weightsLoaderFactory(fetchWeights); + return loadWeights2(manifest, filePathPrefix, weightNames); + } + function weightsLoaderFactory(fetchWeightsFunction) { + return async (manifest, filePathPrefix = "", weightNames) => { + const groupIndicesToFetchMap = manifest.map(() => false); + const groupWeightsToFetch = {}; + const weightsFound = weightNames != null ? weightNames.map(() => false) : []; + const allManifestWeightNames = []; + manifest.forEach((manifestGroupConfig, groupIndex) => { + let groupOffset = 0; + manifestGroupConfig.weights.forEach((weightsEntry) => { + const rawDtype = "quantization" in weightsEntry ? weightsEntry.quantization.dtype : weightsEntry.dtype; + const weightsBytes = DTYPE_VALUE_SIZE_MAP[rawDtype] * sizeFromShape(weightsEntry.shape); + const enqueueWeightsForFetchingFn = () => { + groupIndicesToFetchMap[groupIndex] = true; + if (groupWeightsToFetch[groupIndex] == null) { + groupWeightsToFetch[groupIndex] = []; + } + groupWeightsToFetch[groupIndex].push({ + manifestEntry: weightsEntry, + groupOffset, + sizeBytes: weightsBytes + }); + }; + if (weightNames != null) { + weightNames.forEach((weightName, weightIndex) => { + if (weightName === weightsEntry.name) { + enqueueWeightsForFetchingFn(); + weightsFound[weightIndex] = true; + } + }); + } else { + enqueueWeightsForFetchingFn(); + } + allManifestWeightNames.push(weightsEntry.name); + groupOffset += weightsBytes; + }); + }); + if (!weightsFound.every((found) => found)) { + const weightsNotFound = weightNames.filter((_, i) => !weightsFound[i]); + throw new Error(`Could not find weights in manifest with names: ${weightsNotFound.join(", ")}. +Manifest JSON has weights with names: ${allManifestWeightNames.join(", ")}.`); + } + const groupIndicesToFetch = groupIndicesToFetchMap.reduce((accumulator, shouldFetch, i) => { + if (shouldFetch) { + accumulator.push(i); + } + return accumulator; + }, []); + const fetchUrls = []; + groupIndicesToFetch.forEach((i) => { + manifest[i].paths.forEach((filepath) => { + const fetchUrl = filePathPrefix + (!filePathPrefix.endsWith("/") ? "/" : "") + filepath; + fetchUrls.push(fetchUrl); + }); + }); + const buffers = await fetchWeightsFunction(fetchUrls); + const weightsTensorMap = {}; + let bufferIndexOffset = 0; + groupIndicesToFetch.forEach((i) => { + const numBuffers = manifest[i].paths.length; + let groupBytes = 0; + for (let i2 = 0; i2 < numBuffers; i2++) { + groupBytes += buffers[bufferIndexOffset + i2].byteLength; + } + const groupBuffer = new ArrayBuffer(groupBytes); + const groupByteBuffer = new Uint8Array(groupBuffer); + let groupBufferOffset = 0; + for (let i2 = 0; i2 < numBuffers; i2++) { + const buffer2 = new Uint8Array(buffers[bufferIndexOffset + i2]); + groupByteBuffer.set(buffer2, groupBufferOffset); + groupBufferOffset += buffer2.byteLength; + } + const weightsEntries = groupWeightsToFetch[i]; + weightsEntries.forEach((weightsEntry) => { + const byteBuffer = groupBuffer.slice(weightsEntry.groupOffset, weightsEntry.groupOffset + weightsEntry.sizeBytes); + const nameToTensorMap = decodeWeights(byteBuffer, [weightsEntry.manifestEntry]); + for (const name in nameToTensorMap) { + weightsTensorMap[name] = nameToTensorMap[name]; + } + }); + bufferIndexOffset += numBuffers; + }); + return weightsTensorMap; + }; + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/http.js + var OCTET_STREAM_MIME_TYPE = "application/octet-stream"; + var JSON_TYPE = "application/json"; + var HTTPRequest = class { + constructor(path, loadOptions) { + this.DEFAULT_METHOD = "POST"; + if (loadOptions == null) { + loadOptions = {}; + } + this.weightPathPrefix = loadOptions.weightPathPrefix; + this.onProgress = loadOptions.onProgress; + this.weightUrlConverter = loadOptions.weightUrlConverter; + if (loadOptions.fetchFunc != null) { + assert(typeof loadOptions.fetchFunc === "function", () => "Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"); + this.fetch = loadOptions.fetchFunc; + } else { + this.fetch = env().platform.fetch; + } + assert(path != null && path.length > 0, () => "URL path for http must not be null, undefined or empty."); + if (Array.isArray(path)) { + assert(path.length === 2, () => `URL paths for http must have a length of 2, (actual length is ${path.length}).`); + } + this.path = path; + if (loadOptions.requestInit != null && loadOptions.requestInit.body != null) { + throw new Error("requestInit is expected to have no pre-existing body, but has one."); + } + this.requestInit = loadOptions.requestInit || {}; + } + async save(modelArtifacts) { + if (modelArtifacts.modelTopology instanceof ArrayBuffer) { + throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet."); + } + const init = Object.assign({ method: this.DEFAULT_METHOD }, this.requestInit); + init.body = new FormData(); + const weightsManifest = [{ + paths: ["./model.weights.bin"], + weights: modelArtifacts.weightSpecs + }]; + const modelTopologyAndWeightManifest = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest); + init.body.append("model.json", new Blob([JSON.stringify(modelTopologyAndWeightManifest)], { type: JSON_TYPE }), "model.json"); + if (modelArtifacts.weightData != null) { + init.body.append("model.weights.bin", new Blob([modelArtifacts.weightData], { type: OCTET_STREAM_MIME_TYPE }), "model.weights.bin"); + } + const response = await this.fetch(this.path, init); + if (response.ok) { + return { + modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts), + responses: [response] + }; + } else { + throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${response.status}.`); + } + } + async load() { + const modelConfigRequest = await this.fetch(this.path, this.requestInit); + if (!modelConfigRequest.ok) { + throw new Error(`Request to ${this.path} failed with status code ${modelConfigRequest.status}. Please verify this URL points to the model JSON of the model to load.`); + } + let modelJSON; + try { + modelJSON = await modelConfigRequest.json(); + } catch (e) { + let message = `Failed to parse model JSON of response from ${this.path}.`; + if (this.path.endsWith(".pb")) { + message += " Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository."; + } else { + message += " Please make sure the server is serving valid JSON for this request."; + } + throw new Error(message); + } + const modelTopology = modelJSON.modelTopology; + const weightsManifest = modelJSON.weightsManifest; + if (modelTopology == null && weightsManifest == null) { + throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`); + } + return getModelArtifactsForJSON(modelJSON, (weightsManifest2) => this.loadWeights(weightsManifest2)); + } + async loadWeights(weightsManifest) { + const weightPath = Array.isArray(this.path) ? this.path[1] : this.path; + const [prefix, suffix] = parseUrl(weightPath); + const pathPrefix = this.weightPathPrefix || prefix; + const weightSpecs = []; + for (const entry of weightsManifest) { + weightSpecs.push(...entry.weights); + } + const fetchURLs = []; + const urlPromises = []; + for (const weightsGroup of weightsManifest) { + for (const path of weightsGroup.paths) { + if (this.weightUrlConverter != null) { + urlPromises.push(this.weightUrlConverter(path)); + } else { + fetchURLs.push(pathPrefix + path + suffix); + } + } + } + if (this.weightUrlConverter) { + fetchURLs.push(...await Promise.all(urlPromises)); + } + const buffers = await loadWeightsAsArrayBuffer(fetchURLs, { + requestInit: this.requestInit, + fetchFunc: this.fetch, + onProgress: this.onProgress + }); + return [weightSpecs, concatenateArrayBuffers(buffers)]; + } + }; + HTTPRequest.URL_SCHEME_REGEX = /^https?:\/\//; + function parseUrl(url) { + const lastSlash = url.lastIndexOf("/"); + const lastSearchParam = url.lastIndexOf("?"); + const prefix = url.substring(0, lastSlash); + const suffix = lastSearchParam > lastSlash ? url.substring(lastSearchParam) : ""; + return [prefix + "/", suffix]; + } + function isHTTPScheme(url) { + return url.match(HTTPRequest.URL_SCHEME_REGEX) != null; + } + var httpRouter = (url, loadOptions) => { + if (typeof fetch === "undefined" && (loadOptions == null || loadOptions.fetchFunc == null)) { + return null; + } else { + let isHTTP = true; + if (Array.isArray(url)) { + isHTTP = url.every((urlItem) => isHTTPScheme(urlItem)); + } else { + isHTTP = isHTTPScheme(url); + } + if (isHTTP) { + return http(url, loadOptions); + } + } + return null; + }; + IORouterRegistry.registerSaveRouter(httpRouter); + IORouterRegistry.registerLoadRouter(httpRouter); + function http(path, loadOptions) { + return new HTTPRequest(path, loadOptions); + } + function browserHTTPRequest(path, loadOptions) { + return http(path, loadOptions); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/io/passthrough.js + init_define_BUILD_VERSION(); + var PassthroughLoader = class { + constructor(modelArtifacts) { + this.modelArtifacts = modelArtifacts; + } + load() { + return this.modelArtifacts; + } + }; + var PassthroughSaver = class { + constructor(saveHandler) { + this.saveHandler = saveHandler; + } + save(modelArtifacts) { + return this.saveHandler(modelArtifacts); + } + }; + var PassthroughAsync = class { + constructor(handler) { + if (handler.load) { + this.load = () => Promise.resolve(handler.load()); + } + if (handler.save) { + this.save = (modelArtifacts) => Promise.resolve(handler.save(modelArtifacts)); + } + } + }; + function fromMemory(modelArtifacts, weightSpecs, weightData, trainingConfig) { + const args = arguments; + return new PassthroughAsync(fromMemorySync(...args)); + } + function fromMemorySync(modelArtifacts, weightSpecs, weightData, trainingConfig) { + if (arguments.length === 1) { + const isModelArtifacts = modelArtifacts.modelTopology != null || modelArtifacts.weightSpecs != null; + if (isModelArtifacts) { + return new PassthroughLoader(modelArtifacts); + } else { + console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."); + return new PassthroughLoader({ modelTopology: modelArtifacts }); + } + } else { + console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."); + return new PassthroughLoader({ + modelTopology: modelArtifacts, + weightSpecs, + weightData, + trainingConfig + }); + } + } + function withSaveHandler(saveHandler) { + return new PassthroughSaver(saveHandler); + } + function withSaveHandlerSync(saveHandler) { + return new PassthroughSaver(saveHandler); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/mat_mul.js + init_define_BUILD_VERSION(); + function matMul_(a, b, transposeA = false, transposeB = false) { + let $a = convertToTensor(a, "a", "matMul"); + let $b = convertToTensor(b, "b", "matMul"); + [$a, $b] = makeTypesMatch($a, $b); + const inputs = { a: $a, b: $b }; + const attrs = { transposeA, transposeB }; + return ENGINE.runKernel(BatchMatMul, inputs, attrs); + } + var matMul = op({ matMul_ }); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/one_hot.js + init_define_BUILD_VERSION(); + function oneHot_(indices, depth, onValue = 1, offValue = 0) { + if (depth < 2) { + throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`); + } + const $indices = convertToTensor(indices, "indices", "oneHot", "int32"); + const inputs = { indices: $indices }; + const attrs = { depth, onValue, offValue }; + return ENGINE.runKernel(OneHot, inputs, attrs); + } + var oneHot = op({ oneHot_ }); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/transpose.js + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/globals.js + init_define_BUILD_VERSION(); + function deprecationWarn(msg) { + if (env().getBool("DEPRECATION_WARNINGS_ENABLED")) { + console.warn(msg + " You can disable deprecation warnings with tf.disableDeprecationWarnings()."); + } + } + setDeprecationWarningFn(deprecationWarn); + function engine() { + return ENGINE; + } + function memory() { + return ENGINE.memory(); + } + function tidy(nameOrFn, fn) { + return ENGINE.tidy(nameOrFn, fn); + } + function dispose(container) { + const tensors = getTensorsInContainer(container); + tensors.forEach((tensor3) => tensor3.dispose()); + } + function keep(result) { + return ENGINE.keep(result); + } + function setBackend(backendName) { + return ENGINE.setBackend(backendName); + } + function registerBackend(name, factory, priority = 1) { + return ENGINE.registerBackend(name, factory, priority); + } + function backend() { + return ENGINE.backend; + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/imag.js + init_define_BUILD_VERSION(); + function imag_(input2) { + const $input = convertToTensor(input2, "input", "imag"); + const inputs = { input: $input }; + return ENGINE.runKernel(Imag, inputs); + } + var imag = op({ imag_ }); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/neg.js + init_define_BUILD_VERSION(); + function neg_(x) { + const $x = convertToTensor(x, "x", "neg"); + const inputs = { x: $x }; + return ENGINE.runKernel(Neg, inputs); + } + var neg = op({ neg_ }); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/real.js + init_define_BUILD_VERSION(); + function real_(input2) { + const $input = convertToTensor(input2, "input", "real"); + const inputs = { input: $input }; + return ENGINE.runKernel(Real, inputs); + } + var real = op({ real_ }); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/transpose.js + function transpose_(x, perm, conjugate) { + const $x = convertToTensor(x, "x", "transpose"); + if (perm == null) { + perm = $x.shape.map((s, i) => i).reverse(); + } + assert($x.rank === perm.length, () => `Error in transpose: rank of input ${$x.rank} must match length of perm ${perm}.`); + perm.forEach((axis) => { + assert(axis >= 0 && axis < $x.rank, () => `All entries in 'perm' must be between 0 and ${$x.rank - 1} but got ${perm}`); + }); + if ($x.rank <= 1) { + return $x.clone(); + } + const inputs = { x: $x }; + const attrs = { perm }; + if ($x.dtype === "complex64") { + return tidy(() => { + let $real = real($x); + let $imag = imag($x); + $real = ENGINE.runKernel(Transpose, { x: $real }, attrs); + $imag = ENGINE.runKernel(Transpose, { x: $imag }, attrs); + if (conjugate) { + $imag = neg($imag); + } + return complex($real, $imag); + }); + } + return ENGINE.runKernel(Transpose, inputs, attrs); + } + var transpose = op({ transpose_ }); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/broadcast_util.js + var broadcast_util_exports = {}; + __export(broadcast_util_exports, { + assertAndGetBroadcastShape: () => assertAndGetBroadcastShape, + getBroadcastDims: () => getBroadcastDims, + getReductionAxes: () => getReductionAxes + }); + init_define_BUILD_VERSION(); + function getBroadcastDims(inShape, outShape) { + const inRank = inShape.length; + const dims = []; + for (let i = 0; i < inRank; i++) { + const dim = inRank - 1 - i; + const a = inShape[dim] || 1; + const b = outShape[outShape.length - 1 - i] || 1; + if (b > 1 && a === 1) { + dims.unshift(dim); + } + } + return dims; + } + function getReductionAxes(inShape, outShape) { + const result = []; + for (let i = 0; i < outShape.length; i++) { + const inDim = inShape[inShape.length - i - 1]; + const outAxis = outShape.length - i - 1; + const outDim = outShape[outAxis]; + if (inDim == null || inDim === 1 && outDim > 1) { + result.unshift(outAxis); + } + } + return result; + } + function assertAndGetBroadcastShape(shapeA, shapeB) { + const result = []; + const l = Math.max(shapeA.length, shapeB.length); + for (let i = 0; i < l; i++) { + let a = shapeA[shapeA.length - i - 1]; + if (a == null) { + a = 1; + } + let b = shapeB[shapeB.length - i - 1]; + if (b == null) { + b = 1; + } + if (a === 1) { + result.unshift(b); + } else if (b === 1) { + result.unshift(a); + } else if (a !== b) { + const errMsg = `Operands could not be broadcast together with shapes ${shapeA} and ${shapeB}.`; + throw Error(errMsg); + } else { + result.unshift(a); + } + } + return result; + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/browser.js + var browser_exports = {}; + __export(browser_exports, { + fromPixels: () => fromPixels, + fromPixelsAsync: () => fromPixelsAsync, + toPixels: () => toPixels + }); + init_define_BUILD_VERSION(); + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/tensor3d.js + init_define_BUILD_VERSION(); + function tensor3d(values, shape, dtype) { + assertNonNull(values); + if (shape != null && shape.length !== 3) { + throw new Error("tensor3d() requires shape to have three numbers"); + } + const inferredShape = inferShape(values, dtype); + if (inferredShape.length !== 3 && inferredShape.length !== 1) { + throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray"); + } + if (inferredShape.length === 1 && shape == null) { + throw new Error("tensor3d() requires shape to be provided when `values` are a flat array"); + } + return makeTensor(values, shape, inferredShape, dtype); + } + + // node_modules/.pnpm/@tensorflow+tfjs-core@3.19.0/node_modules/@tensorflow/tfjs-core/dist/ops/browser.js + var fromPixels2DContext; + function fromPixels_(pixels, numChannels = 3) { + if (numChannels > 4) { + throw new Error("Cannot construct Tensor with more than 4 channels from pixels."); + } + if (pixels == null) { + throw new Error("pixels passed to tf.browser.fromPixels() can not be null"); + } + let isPixelData2 = false; + let isImageData = false; + let isVideo = false; + let isImage = false; + let isCanvasLike = false; + let isImageBitmap = false; + if (pixels.data instanceof Uint8Array) { + isPixelData2 = true; + } else if (typeof ImageData !== "undefined" && pixels instanceof ImageData) { + isImageData = true; + } else if (typeof HTMLVideoElement !== "undefined" && pixels instanceof HTMLVideoElement) { + isVideo = true; + } else if (typeof HTMLImageElement !== "undefined" && pixels instanceof HTMLImageElement) { + isImage = true; + } else if (pixels.getContext != null) { + isCanvasLike = true; + } else if (typeof ImageBitmap !== "undefined" && pixels instanceof ImageBitmap) { + isImageBitmap = true; + } else { + throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${pixels.constructor.name}`); + } + if (isVideo) { + const HAVE_CURRENT_DATA_READY_STATE = 2; + if (isVideo && pixels.readyState < HAVE_CURRENT_DATA_READY_STATE) { + throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the