From 6962ccbe0aed12588a87d889cec89dbd48b7d63a Mon Sep 17 00:00:00 2001 From: Juste-Leo Date: Thu, 9 Jul 2026 11:39:31 +0200 Subject: [PATCH 1/4] feat: implement AI integration services with NER-based data anonymization and multi-model support --- .gitignore | 1 + metro.config.js | 10 +- package-lock.json | 795 +++++++++++++++++++++++++++++++++- package.json | 2 + scripts/download_model.js | 68 +++ src/screens/ApiKeysScreen.tsx | 69 +++ src/services/NerService.ts | 66 +++ src/services/ai.ts | 26 +- src/services/anonymizer.ts | 109 +++++ src/types/storage.ts | 1 + test_anonymizer.js | 84 ++++ 11 files changed, 1218 insertions(+), 13 deletions(-) create mode 100644 scripts/download_model.js create mode 100644 src/services/NerService.ts create mode 100644 src/services/anonymizer.ts create mode 100644 test_anonymizer.js diff --git a/.gitignore b/.gitignore index 00d3973..ca1ac94 100644 --- a/.gitignore +++ b/.gitignore @@ -76,3 +76,4 @@ yarn-error.log # Environment variables .env +src/assets/models/albert-wikiner-fr-onnx/ diff --git a/metro.config.js b/metro.config.js index 2a0a21c..670c8bc 100644 --- a/metro.config.js +++ b/metro.config.js @@ -6,6 +6,12 @@ const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); * * @type {import('@react-native/metro-config').MetroConfig} */ -const config = {}; +const defaultConfig = getDefaultConfig(__dirname); -module.exports = mergeConfig(getDefaultConfig(__dirname), config); +const config = { + resolver: { + assetExts: [...defaultConfig.resolver.assetExts, 'bin', 'onnx', 'model'], + }, +}; + +module.exports = mergeConfig(defaultConfig, config); diff --git a/package-lock.json b/package-lock.json index 899d282..2702482 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,12 +9,14 @@ "version": "0.0.1", "dependencies": { "@google/genai": "^1.50.1", + "@huggingface/transformers": "^4.2.0", "@react-native-clipboard/clipboard": "^1.16.3", "@react-native-documents/picker": "^12.0.1", "@react-native/new-app-screen": "0.84.1", "@react-navigation/bottom-tabs": "^7.15.9", "@react-navigation/native": "^7.2.2", "@react-navigation/native-stack": "^7.14.10", + "onnxruntime-react-native": "^1.24.3", "openai": "^6.34.0", "react": "19.2.3", "react-native": "0.84.1", @@ -1993,6 +1995,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@emnapi/runtime": { + "version": "1.11.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.2.tgz", + "integrity": "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.9.1", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", @@ -2150,6 +2162,34 @@ "@hapi/hoek": "^9.0.0" } }, + "node_modules/@huggingface/jinja": { + "version": "0.5.9", + "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.5.9.tgz", + "integrity": "sha512-uWTG+l3VJRsl7EXxYizuL3P+cCPoc3cRqbWWRcQN0FhejRfbdq0RNhCmbY/YDtnTcz9icdLYuLDjsnz4d8JMuw==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@huggingface/tokenizers": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@huggingface/tokenizers/-/tokenizers-0.1.3.tgz", + "integrity": "sha512-8rF/RRT10u+kn7YuUbUg0OF30K8rjTc78aHpxT+qJ1uWSqxT1MHi8+9ltwYfkFYJzT/oS+qw3JVfHtNMGAdqyA==", + "license": "Apache-2.0" + }, + "node_modules/@huggingface/transformers": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@huggingface/transformers/-/transformers-4.2.0.tgz", + "integrity": "sha512-8BRCoBMH0XsWaEIamuR0LrJGAfftgHAfb2Vrffy0VKlSAE/MnUJ5/h/zTfEP3fDIft+nk7TqB8xXEyABGitBjQ==", + "license": "Apache-2.0", + "dependencies": { + "@huggingface/jinja": "^0.5.6", + "@huggingface/tokenizers": "^0.1.3", + "onnxruntime-node": "1.24.3", + "onnxruntime-web": "1.26.0-dev.20260416-b7804b056c", + "sharp": "^0.34.5" + } + }, "node_modules/@humanwhocodes/config-array": { "version": "0.13.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", @@ -2219,6 +2259,471 @@ "dev": true, "license": "BSD-3-Clause" }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz", + "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz", + "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz", + "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz", + "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz", + "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz", + "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz", + "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==", + "cpu": [ + "ppc64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz", + "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==", + "cpu": [ + "riscv64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz", + "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==", + "cpu": [ + "s390x" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz", + "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz", + "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz", + "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz", + "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz", + "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz", + "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==", + "cpu": [ + "ppc64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz", + "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==", + "cpu": [ + "riscv64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz", + "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz", + "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz", + "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz", + "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz", + "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.7.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz", + "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz", + "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz", + "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, "node_modules/@isaacs/ttlcache": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/@isaacs/ttlcache/-/ttlcache-1.4.1.tgz", @@ -4074,6 +4579,15 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, + "node_modules/adm-zip": { + "version": "0.5.18", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.18.tgz", + "integrity": "sha512-ufJnssQGbxzLNS1Ho9bCtX4rQKCCvoVuDLHoJyc3F9dOGDB4BkWs2Ci0kv53lqocAEQ/Cbi+I2XCsNYGqVYqng==", + "license": "MIT", + "engines": { + "node": ">=12.0" + } + }, "node_modules/agent-base": { "version": "7.1.4", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", @@ -4688,6 +5202,13 @@ "devOptional": true, "license": "MIT" }, + "node_modules/boolean": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz", + "integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT" + }, "node_modules/brace-expansion": { "version": "5.0.4", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.4.tgz", @@ -5467,7 +5988,6 @@ "version": "1.1.4", "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", - "dev": true, "license": "MIT", "dependencies": { "es-define-property": "^1.0.0", @@ -5485,7 +6005,6 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", - "dev": true, "license": "MIT", "dependencies": { "define-data-property": "^1.0.1", @@ -5518,6 +6037,15 @@ "npm": "1.2.8000 || >= 1.4.16" } }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, "node_modules/detect-newline": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", @@ -5528,6 +6056,12 @@ "node": ">=8" } }, + "node_modules/detect-node": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz", + "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==", + "license": "MIT" + }, "node_modules/diff-sequences": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", @@ -5761,7 +6295,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "devOptional": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -5771,7 +6304,6 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "devOptional": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -5865,6 +6397,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/es6-error": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz", + "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==", + "license": "MIT" + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -6722,6 +7260,12 @@ "node": "^10.12.0 || >=12.0.0" } }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "license": "Apache-2.0" + }, "node_modules/flatted": { "version": "3.3.4", "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.4.tgz", @@ -7045,6 +7589,62 @@ "node": "*" } }, + "node_modules/global-agent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz", + "integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==", + "license": "BSD-3-Clause", + "dependencies": { + "boolean": "^3.0.1", + "es6-error": "^4.1.1", + "matcher": "^3.0.0", + "roarr": "^2.15.3", + "semver": "^7.3.2", + "serialize-error": "^7.0.1" + }, + "engines": { + "node": ">=10.0" + } + }, + "node_modules/global-agent/node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/global-agent/node_modules/serialize-error": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz", + "integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==", + "license": "MIT", + "dependencies": { + "type-fest": "^0.13.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/global-agent/node_modules/type-fest": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz", + "integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/globals": { "version": "13.24.0", "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", @@ -7065,7 +7665,6 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", - "dev": true, "license": "MIT", "dependencies": { "define-properties": "^1.2.1", @@ -7108,7 +7707,6 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "devOptional": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -7130,6 +7728,12 @@ "dev": true, "license": "MIT" }, + "node_modules/guid-typescript": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", + "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==", + "license": "ISC" + }, "node_modules/has-bigints": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz", @@ -7156,7 +7760,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", - "dev": true, "license": "MIT", "dependencies": { "es-define-property": "^1.0.0" @@ -8725,6 +9328,12 @@ "dev": true, "license": "MIT" }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", + "license": "ISC" + }, "node_modules/json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", @@ -9143,6 +9752,18 @@ "integrity": "sha512-ocnPZQLNpvbedwTy9kNrQEsknEfgvcLMvOtz3sFeWApDq1MXH1TqkCIx58xlpESsfwQOnuBO9beyQuNGzVvuhQ==", "license": "Apache-2.0" }, + "node_modules/matcher": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz", + "integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -9880,7 +10501,6 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -10008,6 +10628,65 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/onnxruntime-common": { + "version": "1.24.3", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.24.3.tgz", + "integrity": "sha512-GeuPZO6U/LBJXvwdaqHbuUmoXiEdeCjWi/EG7Y1HNnDwJYuk6WUbNXpF6luSUY8yASul3cmUlLGrCCL1ZgVXqA==", + "license": "MIT" + }, + "node_modules/onnxruntime-node": { + "version": "1.24.3", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.24.3.tgz", + "integrity": "sha512-JH7+czbc8ALA819vlTgcV+Q214/+VjGeBHDjX81+ZCD0PCVCIFGFNtT0V4sXG/1JXypKPgScQcB3ij/hk3YnTg==", + "hasInstallScript": true, + "license": "MIT", + "os": [ + "win32", + "darwin", + "linux" + ], + "dependencies": { + "adm-zip": "^0.5.16", + "global-agent": "^3.0.0", + "onnxruntime-common": "1.24.3" + } + }, + "node_modules/onnxruntime-react-native": { + "version": "1.24.3", + "resolved": "https://registry.npmjs.org/onnxruntime-react-native/-/onnxruntime-react-native-1.24.3.tgz", + "integrity": "sha512-vMxFcnO1YDtT6auv719Zk0Zj/EXujqeEzSjTe5W7A915qaRrM4pRfXlI4ye/ExOwcTan7NYVZ/wpLX+YBU2aWQ==", + "license": "MIT", + "dependencies": { + "onnxruntime-common": "1.24.3" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "react": "*", + "react-native": "*" + } + }, + "node_modules/onnxruntime-web": { + "version": "1.26.0-dev.20260416-b7804b056c", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.26.0-dev.20260416-b7804b056c.tgz", + "integrity": "sha512-MD6Ss4GSpQBo6zqoJzyT9LRbKYs7x/JVN23FT24EcEvlqF4VuzPOeH6X38orZPKHQDbprn7K+SBpu0/mj2CQiw==", + "license": "MIT", + "dependencies": { + "flatbuffers": "^25.1.24", + "guid-typescript": "^1.0.9", + "long": "^5.2.3", + "onnxruntime-common": "1.24.0-dev.20251116-b39e144322", + "platform": "^1.3.6", + "protobufjs": "^7.2.4" + } + }, + "node_modules/onnxruntime-web/node_modules/onnxruntime-common": { + "version": "1.24.0-dev.20251116-b39e144322", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.24.0-dev.20251116-b39e144322.tgz", + "integrity": "sha512-BOoomdHYmNRL5r4iQ4bMvsl2t0/hzVQ3OM3PHD0gxeXu1PmggqBv3puZicEUVOA3AtHHYmqZtjMj9FOfGrATTw==", + "license": "MIT" + }, "node_modules/open": { "version": "6.4.0", "resolved": "https://registry.npmjs.org/open/-/open-6.4.0.tgz", @@ -10352,6 +11031,12 @@ "node": ">=8" } }, + "node_modules/platform": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", + "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", + "license": "MIT" + }, "node_modules/possible-typed-array-names": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", @@ -11165,6 +11850,29 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/roarr": { + "version": "2.15.4", + "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz", + "integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==", + "license": "BSD-3-Clause", + "dependencies": { + "boolean": "^3.0.1", + "detect-node": "^2.0.4", + "globalthis": "^1.0.1", + "json-stringify-safe": "^5.0.1", + "semver-compare": "^1.0.0", + "sprintf-js": "^1.1.2" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/roarr/node_modules/sprintf-js": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", + "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", + "license": "BSD-3-Clause" + }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", @@ -11286,6 +11994,12 @@ "semver": "bin/semver.js" } }, + "node_modules/semver-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", + "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==", + "license": "MIT" + }, "node_modules/send": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", @@ -11459,6 +12173,62 @@ "node": ">=10" } }, + "node_modules/sharp": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz", + "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.2", + "semver": "^7.7.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.5", + "@img/sharp-darwin-x64": "0.34.5", + "@img/sharp-libvips-darwin-arm64": "1.2.4", + "@img/sharp-libvips-darwin-x64": "1.2.4", + "@img/sharp-libvips-linux-arm": "1.2.4", + "@img/sharp-libvips-linux-arm64": "1.2.4", + "@img/sharp-libvips-linux-ppc64": "1.2.4", + "@img/sharp-libvips-linux-riscv64": "1.2.4", + "@img/sharp-libvips-linux-s390x": "1.2.4", + "@img/sharp-libvips-linux-x64": "1.2.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", + "@img/sharp-libvips-linuxmusl-x64": "1.2.4", + "@img/sharp-linux-arm": "0.34.5", + "@img/sharp-linux-arm64": "0.34.5", + "@img/sharp-linux-ppc64": "0.34.5", + "@img/sharp-linux-riscv64": "0.34.5", + "@img/sharp-linux-s390x": "0.34.5", + "@img/sharp-linux-x64": "0.34.5", + "@img/sharp-linuxmusl-arm64": "0.34.5", + "@img/sharp-linuxmusl-x64": "0.34.5", + "@img/sharp-wasm32": "0.34.5", + "@img/sharp-win32-arm64": "0.34.5", + "@img/sharp-win32-ia32": "0.34.5", + "@img/sharp-win32-x64": "0.34.5" + } + }, + "node_modules/sharp/node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -12174,6 +12944,13 @@ "typescript": ">=4.8.4" } }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD", + "optional": true + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -12305,7 +13082,7 @@ "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "dev": true, + "devOptional": true, "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", diff --git a/package.json b/package.json index 627dec9..9374ab3 100644 --- a/package.json +++ b/package.json @@ -11,12 +11,14 @@ }, "dependencies": { "@google/genai": "^1.50.1", + "@huggingface/transformers": "^4.2.0", "@react-native-clipboard/clipboard": "^1.16.3", "@react-native-documents/picker": "^12.0.1", "@react-native/new-app-screen": "0.84.1", "@react-navigation/bottom-tabs": "^7.15.9", "@react-navigation/native": "^7.2.2", "@react-navigation/native-stack": "^7.14.10", + "onnxruntime-react-native": "^1.24.3", "openai": "^6.34.0", "react": "19.2.3", "react-native": "0.84.1", diff --git a/scripts/download_model.js b/scripts/download_model.js new file mode 100644 index 0000000..a90e1b8 --- /dev/null +++ b/scripts/download_model.js @@ -0,0 +1,68 @@ +const fs = require('fs'); +const path = require('path'); +const https = require('https'); + +const REPO_URL = 'https://huggingface.co/JusteLeo/ALBERT-base-v2-french-ner/resolve/main/onnx'; +const TARGET_DIR = path.join(__dirname, '..', 'src', 'assets', 'models', 'albert-wikiner-fr-onnx'); +const ONNX_DIR = path.join(TARGET_DIR, 'onnx'); + +const FILES_TO_DOWNLOAD = [ + 'config.json', + 'special_tokens_map.json', + 'spiece.model', + 'tokenizer.json', + 'tokenizer_config.json', + 'onnx/model.onnx' +]; + +// Création des dossiers +if (!fs.existsSync(TARGET_DIR)) fs.mkdirSync(TARGET_DIR, { recursive: true }); +if (!fs.existsSync(ONNX_DIR)) fs.mkdirSync(ONNX_DIR, { recursive: true }); + +const downloadFile = (fileUrl, destPath) => { + return new Promise((resolve, reject) => { + console.log(`Téléchargement de ${fileUrl} ...`); + const file = fs.createWriteStream(destPath); + https.get(fileUrl, (response) => { + if (response.statusCode === 302 || response.statusCode === 301) { + // Redirection HuggingFace + downloadFile(response.headers.location, destPath).then(resolve).catch(reject); + return; + } + if (response.statusCode !== 200) { + reject(new Error(`Erreur HTTP ${response.statusCode} pour ${fileUrl}`)); + return; + } + response.pipe(file); + file.on('finish', () => { + file.close(() => resolve()); + }); + }).on('error', (err) => { + fs.unlink(destPath, () => reject(err)); + }); + }); +}; + +const run = async () => { + console.log('Démarrage du téléchargement du modèle NER...'); + try { + for (const file of FILES_TO_DOWNLOAD) { + const fileUrl = `${REPO_URL}/${file}`; + const destPath = path.join(TARGET_DIR, file); + + // Ne retélécharge pas si déjà présent pour gagner du temps + if (!fs.existsSync(destPath)) { + await downloadFile(fileUrl, destPath); + console.log(`✓ ${file} téléchargé avec succès.`); + } else { + console.log(`- ${file} est déjà présent.`); + } + } + console.log('🎉 Téléchargement terminé avec succès !'); + } catch (e) { + console.error('❌ Erreur lors du téléchargement :', e); + process.exit(1); + } +}; + +run(); diff --git a/src/screens/ApiKeysScreen.tsx b/src/screens/ApiKeysScreen.tsx index 470f888..eb4f78f 100644 --- a/src/screens/ApiKeysScreen.tsx +++ b/src/screens/ApiKeysScreen.tsx @@ -11,6 +11,7 @@ import { ActivityIndicator, Animated, Alert, + Switch, } from 'react-native'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import { NativeStackScreenProps } from '@react-navigation/native-stack'; @@ -58,8 +59,16 @@ export default function ApiKeysScreen({ navigation }: Props) { groq: new Animated.Value(0), }).current; + // Anonymization setting state + const [isAnonymizationEnabled, setIsAnonymizationEnabled] = useState(true); + // Load existing keys on mount useEffect(() => { + const prefs = StorageService.getPreferences(); + if (prefs && prefs.isAnonymizationEnabled !== undefined) { + setIsAnonymizationEnabled(prefs.isAnonymizationEnabled); + } + const loadKeys = async () => { for (const p of PROVIDERS) { const saved = StorageService.getApiKey(p.id); @@ -113,6 +122,12 @@ export default function ApiKeysScreen({ navigation }: Props) { } }; + const toggleAnonymization = (value: boolean) => { + setIsAnonymizationEnabled(value); + const prefs = StorageService.getPreferences() || { theme: 'dark' }; + StorageService.savePreferences({ ...prefs, isAnonymizationEnabled: value }); + }; + const handleDelete = (provider: AIProvider) => { Alert.alert( 'Supprimer la clé', @@ -272,6 +287,25 @@ export default function ApiKeysScreen({ navigation }: Props) { contentContainerStyle={[styles.scrollContent, { paddingBottom: insets.bottom + 40 }]} showsVerticalScrollIndicator={false} > + {/* Anonymisation Settings */} + + Confidentialité + + + Anonymisation des données + + Avant d'être envoyées à l'API, les données sensibles (noms, prénoms, lieux) sont supprimées pour protéger votre vie privée. + + + + + + {PROVIDERS.map(renderProviderCard)} @@ -416,4 +450,39 @@ const styles = StyleSheet.create({ fontSize: 13, fontWeight: '600', }, + settingsSection: { + marginBottom: 32, + }, + sectionTitle: { + color: '#F8FAFC', + fontSize: 18, + fontWeight: 'bold', + marginBottom: 16, + marginLeft: 4, + }, + settingRow: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + backgroundColor: '#1E1E38', + borderRadius: 16, + padding: 16, + borderWidth: 1, + borderColor: 'rgba(255,255,255,0.05)', + }, + settingTextContainer: { + flex: 1, + paddingRight: 16, + }, + settingLabel: { + color: '#F8FAFC', + fontSize: 16, + fontWeight: '600', + marginBottom: 4, + }, + settingDescription: { + color: '#94A3B8', + fontSize: 13, + lineHeight: 18, + }, }); diff --git a/src/services/NerService.ts b/src/services/NerService.ts new file mode 100644 index 0000000..e4a73e4 --- /dev/null +++ b/src/services/NerService.ts @@ -0,0 +1,66 @@ +import { pipeline, env } from '@huggingface/transformers'; + +// Configuration pour React Native +// Utiliser le modèle local présent dans ton dossier 'assets/models/albert-wikiner-fr-onnx' +env.allowLocalModels = true; +env.allowRemoteModels = false; // Désactivé pour forcer le local + +// Mettre le chemin vers le dossier contenant le modèle (relatif pour le bundler RN) +// Avec transformers.js et React Native, on peut utiliser des URL ou des chemins d'assets locaux +// selon la configuration du plugin babel / metro. +env.localModelPath = 'assets/models/'; + +/** + * Service pour l'inférence NER avec le modèle ALBERT ONNX + * Utilise Transformers.js pour gérer la tokenisation et l'inférence. + */ +class NERInference { + static instance: any = null; + + static async getInstance() { + if (this.instance === null) { + console.log("Chargement du modèle ONNX..."); + + // Initialisation du pipeline + this.instance = pipeline( + 'token-classification', + 'albert-wikiner-fr-onnx', + { + quantized: false // Utiliser false car le fichier s'appelle model.onnx (pas model_quantized.onnx) + } + ); + } + return this.instance; + } +} + +export interface NerEntity { + entity_group: string; + score: number; + word: string; + start?: number; + end?: number; +} + +/** + * Fonction pour extraire les entités d'un texte + * @param text - Le texte à analyser + * @returns Liste des entités détectées + */ +export const extractEntities = async (text: string): Promise => { + if (!text) return []; + + try { + const classifier = await NERInference.getInstance(); + + // On utilise l'aggregation "simple" (comme en Python) pour regrouper les sous-mots (B-PER, I-PER -> PER) + const results = await classifier(text, { + aggregation_strategy: "simple" + }); + + return results as NerEntity[]; + } catch (error) { + console.error("Erreur d'inférence NER :", error); + return []; + } +}; diff --git a/src/services/ai.ts b/src/services/ai.ts index 80eaad1..e6dd134 100644 --- a/src/services/ai.ts +++ b/src/services/ai.ts @@ -1,6 +1,8 @@ import { GoogleGenAI } from '@google/genai'; import OpenAI from 'openai'; import { MailEntry, MailThread, UserProfile } from '../types/storage'; +import { StorageService } from './storage'; +import { anonymize, deanonymize } from './anonymizer'; export type AIProvider = 'google' | 'groq'; @@ -34,10 +36,30 @@ export async function generateAIResponse( throw new Error('Clé API manquante.'); } + const prefs = StorageService.getPreferences(); + const useAnonymization = prefs?.isAnonymizationEnabled ?? true; + + let finalMessage = message; + let mapping: Record = {}; + + if (useAnonymization) { + const anonResult = await anonymize(message); + finalMessage = anonResult.anonymizedText; + mapping = anonResult.mapping; + } + + let responseText = ''; if (provider === 'google') { - return googleGenerate(apiKey, message); + responseText = await googleGenerate(apiKey, finalMessage); + } else { + responseText = await groqGenerate(apiKey, finalMessage); + } + + if (useAnonymization) { + responseText = deanonymize(responseText, mapping); } - return groqGenerate(apiKey, message); + + return responseText; } async function googleGenerate(apiKey: string, message: string): Promise { diff --git a/src/services/anonymizer.ts b/src/services/anonymizer.ts new file mode 100644 index 0000000..86c8b07 --- /dev/null +++ b/src/services/anonymizer.ts @@ -0,0 +1,109 @@ +import { extractEntities, NerEntity } from './NerService'; + +export interface AnonymizationResult { + anonymizedText: string; + mapping: Record; +} + +// Les civilités à exclure du masquage +const CIVILITIES = ['Monsieur ', 'Madame ', 'M. ', 'Mme ', 'Mr ', 'Mademoiselle ', 'Mlle ']; + +export const anonymize = async (text: string): Promise => { + if (!text) return { anonymizedText: text, mapping: {} }; + + let anonymizedText = text; + const mapping: Record = {}; + + let personCount = 1; + let locCount = 1; + let emailCount = 1; + let phoneCount = 1; + let ineCount = 1; + + // 1. Regex Rapides + // Emails + anonymizedText = anonymizedText.replace(/[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}/g, (match) => { + const key = `[EMAIL${emailCount++}]`; + mapping[key] = match; + return key; + }); + + // Téléphones (français / inter) + anonymizedText = anonymizedText.replace(/(?:(?:\+|00)33|0)\s*[1-9](?:[\s.-]*\d{2}){4}/g, (match) => { + const key = `[TELEPHONE${phoneCount++}]`; + mapping[key] = match; + return key; + }); + + // Numéro INE (11 caractères, alphanumérique ex: 123456789EE) + anonymizedText = anonymizedText.replace(/\b\d{9,10}[A-Z]{1,2}\b/gi, (match) => { + const key = `[INE${ineCount++}]`; + mapping[key] = match; + return key; + }); + + // 2. NER pour Personnes (PER) et Lieux (LOC) + try { + const entities = await extractEntities(anonymizedText); + + // Trier les entités par longueur de mot décroissante pour éviter les remplacements imbriqués partiels + const sortedEntities = [...entities].sort((a, b) => b.word.length - a.word.length); + + for (const entity of sortedEntities) { + if (entity.entity_group === 'PER' || entity.entity_group === 'LOC') { + let originalWord = entity.word.trim(); + + // Nettoyage de la civilité pour ne masquer que le nom propre + if (entity.entity_group === 'PER') { + for (const civ of CIVILITIES) { + if (originalWord.toLowerCase().startsWith(civ.toLowerCase())) { + originalWord = originalWord.substring(civ.length).trim(); + break; + } + } + } + + // Si après nettoyage, il reste un mot valide + if (originalWord.length > 1) { + // On vérifie s'il n'a pas déjà été stocké dans le mapping + let existingKey = Object.keys(mapping).find(key => mapping[key] === originalWord); + let keyToUse = existingKey; + + if (!keyToUse) { + if (entity.entity_group === 'PER') { + keyToUse = `[PERSONNE${personCount++}]`; + } else { + keyToUse = `[LIEU${locCount++}]`; + } + mapping[keyToUse] = originalWord; + } + + // Remplacement global du mot dans le texte + // Échapper le mot original pour la regex + const escapedWord = originalWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const regex = new RegExp(`\\b${escapedWord}\\b`, 'gi'); + + anonymizedText = anonymizedText.replace(regex, keyToUse); + } + } + } + } catch (error) { + console.error("Erreur lors de l'anonymisation NER :", error); + } + + return { anonymizedText, mapping }; +}; + +export const deanonymize = (text: string, mapping: Record): string => { + if (!text || !mapping || Object.keys(mapping).length === 0) return text; + + let deanonymizedText = text; + for (const [key, value] of Object.entries(mapping)) { + // Échapper les crochets pour la regex + const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const regex = new RegExp(escapedKey, 'g'); + deanonymizedText = deanonymizedText.replace(regex, value); + } + + return deanonymizedText; +}; diff --git a/src/types/storage.ts b/src/types/storage.ts index 033c37a..08a44e0 100644 --- a/src/types/storage.ts +++ b/src/types/storage.ts @@ -2,6 +2,7 @@ import { ThemeType } from './theme'; export interface UserPreferences { theme: ThemeType; + isAnonymizationEnabled?: boolean; // D'autres paramètres comme les notifications pourront être ajoutés ici } diff --git a/test_anonymizer.js b/test_anonymizer.js new file mode 100644 index 0000000..24c01c6 --- /dev/null +++ b/test_anonymizer.js @@ -0,0 +1,84 @@ +// test_anonymizer.js +// Petit script de test pour s'assurer que l'anonymisation et la désanonymisation fonctionnent, +// notamment le nettoyage des civilités et le stockage correct des index (PERSONNE1, LIEU1, etc.) +// A lancer avec node test_anonymizer.js après compilation, ou via ts-node, +// mais comme onnxruntime a besoin d'un environnement asynchrone, voici la structure de test : + +// Attention: le service NerService.ts a besoin d'être compilé ou on simule la fonction pour ce test rapide : + +const testLogic = async () => { + // Ceci est un mock du résultat NER pour simuler le comportement + const mockEntities = [ + { entity_group: 'PER', score: 0.99, word: ' Monsieur Jean-Claude Convenant' }, + { entity_group: 'LOC', score: 0.98, word: ' Montpellier' } + ]; + + const CIVILITIES = ['Monsieur ', 'Madame ', 'M. ', 'Mme ', 'Mr ', 'Mademoiselle ', 'Mlle ']; + const mapping = {}; + let personCount = 1; + let locCount = 1; + let emailCount = 1; + + let anonymizedText = "Bonjour, je suis Monsieur Jean-Claude Convenant de Montpellier. Mon email est jc@test.com."; + + // 1. Mocks de Regex + anonymizedText = anonymizedText.replace(/[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}/g, (match) => { + const key = `[EMAIL${emailCount++}]`; + mapping[key] = match; + return key; + }); + + // 2. Mocks de NER + const sortedEntities = [...mockEntities].sort((a, b) => b.word.length - a.word.length); + + for (const entity of sortedEntities) { + if (entity.entity_group === 'PER' || entity.entity_group === 'LOC') { + let originalWord = entity.word.trim(); + + if (entity.entity_group === 'PER') { + for (const civ of CIVILITIES) { + if (originalWord.toLowerCase().startsWith(civ.toLowerCase())) { + originalWord = originalWord.substring(civ.length).trim(); + break; + } + } + } + + if (originalWord.length > 1) { + let existingKey = Object.keys(mapping).find(key => mapping[key] === originalWord); + let keyToUse = existingKey; + + if (!keyToUse) { + if (entity.entity_group === 'PER') { + keyToUse = `[PERSONNE${personCount++}]`; + } else { + keyToUse = `[LIEU${locCount++}]`; + } + mapping[keyToUse] = originalWord; + } + + const escapedWord = originalWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const regex = new RegExp(`\\b${escapedWord}\\b`, 'gi'); + + anonymizedText = anonymizedText.replace(regex, keyToUse); + } + } + } + + console.log("Texte original: Bonjour, je suis Monsieur Jean-Claude Convenant de Montpellier. Mon email est jc@test.com."); + console.log("Texte anonymisé:", anonymizedText); + console.log("Mapping:", mapping); + + // Deanonymize + let deanonymizedText = "Le LLM répond : Ravi de vous rencontrer Monsieur [PERSONNE1]. J'espère qu'il fait beau à [LIEU1]. Je note votre adresse [EMAIL1]."; + for (const [key, value] of Object.entries(mapping)) { + const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const regex = new RegExp(escapedKey, 'g'); + deanonymizedText = deanonymizedText.replace(regex, value); + } + + console.log("\nTexte LLM simulé:", "Le LLM répond : Ravi de vous rencontrer Monsieur [PERSONNE1]. J'espère qu'il fait beau à [LIEU1]. Je note votre adresse [EMAIL1]."); + console.log("Texte désanonymisé:", deanonymizedText); +}; + +testLogic(); From db0e599854a3d902ba404c401a77850b1262d53d Mon Sep 17 00:00:00 2001 From: Juste-Leo Date: Thu, 9 Jul 2026 12:07:59 +0200 Subject: [PATCH 2/4] fix: compile all the way through --- metro.config.js | 12 + package-lock.json | 208 ++++++++++++++++++ package.json | 5 +- patches/onnxruntime-react-native+1.24.3.patch | 19 ++ 4 files changed, 243 insertions(+), 1 deletion(-) create mode 100644 patches/onnxruntime-react-native+1.24.3.patch diff --git a/metro.config.js b/metro.config.js index 670c8bc..59e36d0 100644 --- a/metro.config.js +++ b/metro.config.js @@ -11,6 +11,18 @@ const defaultConfig = getDefaultConfig(__dirname); const config = { resolver: { assetExts: [...defaultConfig.resolver.assetExts, 'bin', 'onnx', 'model'], + resolveRequest: (context, moduleName, platform) => { + // Ignorer les dépendances web/node de transformers.js (car on utilise react-native) + if ( + moduleName.startsWith('onnxruntime-node') || + moduleName.startsWith('onnxruntime-web') + ) { + return { + type: 'empty', + }; + } + return context.resolveRequest(context, moduleName, platform); + }, }, }; diff --git a/package-lock.json b/package-lock.json index 2702482..a6f6aed 100644 --- a/package-lock.json +++ b/package-lock.json @@ -45,6 +45,8 @@ "@types/react-test-renderer": "^19.1.0", "eslint": "^8.19.0", "jest": "^29.6.3", + "patch-package": "^8.0.1", + "postinstall-postinstall": "^2.1.0", "prettier": "2.8.8", "react-native-dotenv": "^3.4.11", "react-test-renderer": "19.2.3", @@ -4521,6 +4523,13 @@ "devOptional": true, "license": "MIT" }, + "node_modules/@yarnpkg/lockfile": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@yarnpkg/lockfile/-/lockfile-1.1.0.tgz", + "integrity": "sha512-GpSwvyXOcOOlV70vbnzjj4fW5xW/FdUF6nQEt1ENy7m4ZCczi1+/buVUPAqmGfqznsORNFzUMjctTIp8a9tuCQ==", + "dev": true, + "license": "BSD-2-Clause" + }, "node_modules/abort-controller": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", @@ -7245,6 +7254,16 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/find-yarn-workspace-root": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/find-yarn-workspace-root/-/find-yarn-workspace-root-2.0.0.tgz", + "integrity": "sha512-1IMnbjt4KzsQfnhnzNd8wUEgXZ44IzZaZmnLYx7D5FZlaHt2gW20Cri8Q+E/t5tIj4+epTBub+2Zxu/vNILzqQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "micromatch": "^4.0.2" + } + }, "node_modules/flat-cache": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", @@ -9321,6 +9340,26 @@ "dev": true, "license": "MIT" }, + "node_modules/json-stable-stringify": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.3.0.tgz", + "integrity": "sha512-qtYiSSFlwot9XHtF9bD9c7rwKjr+RecWT//ZnPvSmEjpV5mmPOCN4j8UjY5hbjNkOwZ/jQv3J6R1/pL7RwgMsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "isarray": "^2.0.5", + "jsonify": "^0.0.1", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", @@ -9356,6 +9395,16 @@ "graceful-fs": "^4.1.6" } }, + "node_modules/jsonify": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.1.tgz", + "integrity": "sha512-2/Ki0GcmuqSrgFyelQq9M05y7PS0mEwuIzrf3f1fPqkVDVRvZrPZtVSMHxdgo8Aq0sxAOb/cr2aqqA3LeWHVPg==", + "dev": true, + "license": "Public Domain", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/jsx-ast-utils": { "version": "3.3.5", "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz", @@ -9403,6 +9452,16 @@ "json-buffer": "3.0.1" } }, + "node_modules/klaw-sync": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/klaw-sync/-/klaw-sync-6.0.0.tgz", + "integrity": "sha512-nIeuVSzdCCs6TDPTqI8w1Yre34sSq7AkZ4B3sfOBbI2CgVSB4Du4aLQijFU2+lhAFCwt9+42Hel6lQNIv6AntQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.1.11" + } + }, "node_modules/kleur": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", @@ -10279,6 +10338,16 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/minipass": { "version": "7.1.3", "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", @@ -10876,6 +10945,127 @@ "node": ">= 0.8" } }, + "node_modules/patch-package": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/patch-package/-/patch-package-8.0.1.tgz", + "integrity": "sha512-VsKRIA8f5uqHQ7NGhwIna6Bx6D9s/1iXlA1hthBVBEbkq+t4kXD0HHt+rJhf/Z+Ci0F/HCB2hvn0qLdLG+Qxlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@yarnpkg/lockfile": "^1.1.0", + "chalk": "^4.1.2", + "ci-info": "^3.7.0", + "cross-spawn": "^7.0.3", + "find-yarn-workspace-root": "^2.0.0", + "fs-extra": "^10.0.0", + "json-stable-stringify": "^1.0.2", + "klaw-sync": "^6.0.0", + "minimist": "^1.2.6", + "open": "^7.4.2", + "semver": "^7.5.3", + "slash": "^2.0.0", + "tmp": "^0.2.4", + "yaml": "^2.2.2" + }, + "bin": { + "patch-package": "index.js" + }, + "engines": { + "node": ">=14", + "npm": ">5" + } + }, + "node_modules/patch-package/node_modules/fs-extra": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", + "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/patch-package/node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/patch-package/node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/patch-package/node_modules/open": { + "version": "7.4.2", + "resolved": "https://registry.npmjs.org/open/-/open-7.4.2.tgz", + "integrity": "sha512-MVHddDVweXZF3awtlAS+6pgKLlm/JgxZ90+/NBurBoQctVOOB/zDdVjcyPzQ+0laDGbsWgrRkflI65sQeOgT9Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0", + "is-wsl": "^2.1.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/patch-package/node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/patch-package/node_modules/slash": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", + "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/patch-package/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -11047,6 +11237,14 @@ "node": ">= 0.4" } }, + "node_modules/postinstall-postinstall": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/postinstall-postinstall/-/postinstall-postinstall-2.1.0.tgz", + "integrity": "sha512-7hQX6ZlZXIoRiWNrbMQaLzUUfH+sSx39u8EJ9HYuDc1kLo9IXKWjM5RSquZN1ad5GnH8CGFM78fsAAQi3OKEEQ==", + "dev": true, + "hasInstallScript": true, + "license": "MIT" + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -12904,6 +13102,16 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/tmp": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", + "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.14" + } + }, "node_modules/tmpl": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", diff --git a/package.json b/package.json index 9374ab3..73923ba 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,8 @@ "ios": "react-native run-ios", "lint": "eslint .", "start": "react-native start", - "test": "jest" + "test": "jest", + "postinstall": "patch-package" }, "dependencies": { "@google/genai": "^1.50.1", @@ -47,6 +48,8 @@ "@types/react-test-renderer": "^19.1.0", "eslint": "^8.19.0", "jest": "^29.6.3", + "patch-package": "^8.0.1", + "postinstall-postinstall": "^2.1.0", "prettier": "2.8.8", "react-native-dotenv": "^3.4.11", "react-test-renderer": "19.2.3", diff --git a/patches/onnxruntime-react-native+1.24.3.patch b/patches/onnxruntime-react-native+1.24.3.patch new file mode 100644 index 0000000..a725c3f --- /dev/null +++ b/patches/onnxruntime-react-native+1.24.3.patch @@ -0,0 +1,19 @@ +diff --git a/node_modules/onnxruntime-react-native/android/build.gradle b/node_modules/onnxruntime-react-native/android/build.gradle +index 41b4359..ad7e49d 100644 +--- a/node_modules/onnxruntime-react-native/android/build.gradle ++++ b/node_modules/onnxruntime-react-native/android/build.gradle +@@ -247,10 +247,10 @@ dependencies { + extractLibs "com.microsoft.onnxruntime:onnxruntime-android:latest.integration@aar" + } + +- if (VersionNumber.parse(REACT_NATIVE_VERSION) < VersionNumber.parse("0.71")) { +- extractLibs "com.facebook.fbjni:fbjni:+:headers" +- extractLibs "com.facebook.fbjni:fbjni:+" +- } ++ // if (VersionNumber.parse(REACT_NATIVE_VERSION) < VersionNumber.parse("0.71")) { ++ // extractLibs "com.facebook.fbjni:fbjni:+:headers" ++ // extractLibs "com.facebook.fbjni:fbjni:+" ++ // } + + // By default it will just include onnxruntime full aar package + if (ortExtensionsEnabled) { From 1e8a8f50389a3f15e05b2a283a40a85def6f8c47 Mon Sep 17 00:00:00 2001 From: Juste-Leo Date: Fri, 10 Jul 2026 15:56:55 +0200 Subject: [PATCH 3/4] feat: implement NER-based text anonymization service with transformers.js and custom model path handling --- index.js | 2 +- metro.config.js | 11 +- package-lock.json | 22 + package.json | 2 + patches/@huggingface+transformers+4.2.0.patch | 414 ++++++++++++++++++ src/services/NerService.ts | 139 +++++- src/services/anonymizer.ts | 6 + 7 files changed, 570 insertions(+), 26 deletions(-) create mode 100644 patches/@huggingface+transformers+4.2.0.patch diff --git a/index.js b/index.js index 9b73932..358927b 100644 --- a/index.js +++ b/index.js @@ -1,7 +1,7 @@ /** * @format */ - +import 'fast-text-encoding'; import { AppRegistry } from 'react-native'; import App from './App'; import { name as appName } from './app.json'; diff --git a/metro.config.js b/metro.config.js index 59e36d0..ec6cfbc 100644 --- a/metro.config.js +++ b/metro.config.js @@ -12,15 +12,16 @@ const config = { resolver: { assetExts: [...defaultConfig.resolver.assetExts, 'bin', 'onnx', 'model'], resolveRequest: (context, moduleName, platform) => { - // Ignorer les dépendances web/node de transformers.js (car on utilise react-native) - if ( - moduleName.startsWith('onnxruntime-node') || - moduleName.startsWith('onnxruntime-web') - ) { + // Ignorer onnxruntime-node + if (moduleName.startsWith('onnxruntime-node')) { return { type: 'empty', }; } + // Rediriger onnxruntime-web vers onnxruntime-react-native + if (moduleName.startsWith('onnxruntime-web')) { + return context.resolveRequest(context, 'onnxruntime-react-native', platform); + } return context.resolveRequest(context, moduleName, platform); }, }, diff --git a/package-lock.json b/package-lock.json index a6f6aed..a4b1c11 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,6 +7,7 @@ "": { "name": "simplifac", "version": "0.0.1", + "hasInstallScript": true, "dependencies": { "@google/genai": "^1.50.1", "@huggingface/transformers": "^4.2.0", @@ -16,6 +17,7 @@ "@react-navigation/bottom-tabs": "^7.15.9", "@react-navigation/native": "^7.2.2", "@react-navigation/native-stack": "^7.14.10", + "fast-text-encoding": "^1.0.6", "onnxruntime-react-native": "^1.24.3", "openai": "^6.34.0", "react": "19.2.3", @@ -43,6 +45,7 @@ "@types/jest": "^29.5.13", "@types/react": "^19.2.0", "@types/react-test-renderer": "^19.1.0", + "babel-plugin-transform-replace-expressions": "^0.2.0", "eslint": "^8.19.0", "jest": "^29.6.3", "patch-package": "^8.0.1", @@ -5060,6 +5063,19 @@ "@babel/plugin-syntax-flow": "^7.12.1" } }, + "node_modules/babel-plugin-transform-replace-expressions": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-replace-expressions/-/babel-plugin-transform-replace-expressions-0.2.0.tgz", + "integrity": "sha512-Eh1rRd9hWEYgkgoA3D0kGp7xJ/wgVshgsqmq60iC4HVWD+Lux+fNHSHBa2v1Hsv+dHflShC71qKhiH40OiPtDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.3.3" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, "node_modules/babel-preset-current-node-syntax": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.2.0.tgz", @@ -7085,6 +7101,12 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-text-encoding": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/fast-text-encoding/-/fast-text-encoding-1.0.6.tgz", + "integrity": "sha512-VhXlQgj9ioXCqGstD37E/HBeqEGV/qOD/kmbVG8h5xKBYvM1L3lR1Zn4555cQ8GkYbJa8aJSipLPndE1k6zK2w==", + "license": "Apache-2.0" + }, "node_modules/fast-xml-parser": { "version": "4.5.4", "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.5.4.tgz", diff --git a/package.json b/package.json index 73923ba..3b43ff2 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "@react-navigation/bottom-tabs": "^7.15.9", "@react-navigation/native": "^7.2.2", "@react-navigation/native-stack": "^7.14.10", + "fast-text-encoding": "^1.0.6", "onnxruntime-react-native": "^1.24.3", "openai": "^6.34.0", "react": "19.2.3", @@ -46,6 +47,7 @@ "@types/jest": "^29.5.13", "@types/react": "^19.2.0", "@types/react-test-renderer": "^19.1.0", + "babel-plugin-transform-replace-expressions": "^0.2.0", "eslint": "^8.19.0", "jest": "^29.6.3", "patch-package": "^8.0.1", diff --git a/patches/@huggingface+transformers+4.2.0.patch b/patches/@huggingface+transformers+4.2.0.patch new file mode 100644 index 0000000..ce06ddc --- /dev/null +++ b/patches/@huggingface+transformers+4.2.0.patch @@ -0,0 +1,414 @@ +diff --git a/node_modules/@huggingface/transformers/dist/ort-wasm-simd-threaded.jsep.mjs b/node_modules/@huggingface/transformers/dist/ort-wasm-simd-threaded.jsep.mjs +index bff0149..52e68f7 100644 +--- a/node_modules/@huggingface/transformers/dist/ort-wasm-simd-threaded.jsep.mjs ++++ b/node_modules/@huggingface/transformers/dist/ort-wasm-simd-threaded.jsep.mjs +@@ -1,9 +1,9 @@ +-async function ortWasmThreaded(moduleArg={}){var moduleRtn;var f=moduleArg,aa=!!globalThis.window,ba=!!globalThis.WorkerGlobalScope,h=globalThis.process?.versions?.node&&"renderer"!=globalThis.process?.type,m=ba&&self.name?.startsWith("em-pthread");if(h){const {createRequire:a}=await import("module");var require=a(import.meta.url),ca=require("worker_threads");global.Worker=ca.Worker;m=(ba=!ca.Xd)&&"em-pthread"==ca.workerData}f.mountExternalData=(a,b)=>{a.startsWith("./")&&(a=a.substring(2));(f.Xc||(f.Xc=new Map)).set(a,b)}; ++async function ortWasmThreaded(moduleArg={}){var moduleRtn;var f=moduleArg,aa=!!globalThis.window,ba=!!globalThis.WorkerGlobalScope,h=globalThis.process?.versions?.node&&"renderer"!=globalThis.process?.type,m=ba&&self.name?.startsWith("em-pthread");if(h){const {createRequire:a}=await import("module");var require=a(import_meta.url),ca=require("worker_threads");global.Worker=ca.Worker;m=(ba=!ca.Xd)&&"em-pthread"==ca.workerData}f.mountExternalData=(a,b)=>{a.startsWith("./")&&(a=a.substring(2));(f.Xc||(f.Xc=new Map)).set(a,b)}; + f.unmountExternalData=()=>{delete f.Xc};var SharedArrayBuffer=globalThis.SharedArrayBuffer??(new WebAssembly.Memory({initial:0,maximum:0,shared:!0})).buffer.constructor;const da=a=>async(...b)=>{try{if(f.Yc)throw Error("Session already started");const d=f.Yc={Kd:b[0],errors:[]},c=await a(...b);if(f.Yc!==d)throw Error("Session mismatch");f.dd?.flush();const e=d.errors;if(0k);if(0{if("webgpu"===a){[f.dd,f.Ad,f.Ed,f.ed,f.Dd,f.$b,f.Fd,f.Hd,f.Bd,f.Cd,f.Gd]=b;const d=f.dd;f.jsepRegisterBuffer=(c,e,g,k)=>d.registerBuffer(c,e,g,k);f.jsepGetBuffer=c=>d.getBuffer(c);f.jsepCreateDownloader=(c,e,g)=>d.createDownloader(c,e,g);f.jsepOnCreateSession=c=>{d.onCreateSession(c)};f.jsepOnReleaseSession=c=>{d.onReleaseSession(c)};f.jsepOnRunStart=c=>d.onRunStart(c);f.Id=(c,e)=>{d.upload(c,e)}}else if("webnn"===a){const d=b[0];[f.Wd,f.sd,f.webnnEnsureTensor,f.td,f.webnnDownloadTensor, + f.Rd,f.webnnEnableTraceEvent]=b.slice(1);f.webnnReleaseTensorId=f.sd;f.webnnUploadTensor=f.td;f.webnnRegisterMLContext=f.Rd;f.webnnOnRunStart=c=>d.onRunStart(c);f.webnnOnRunEnd=d.onRunEnd.bind(d);f.webnnOnReleaseSession=c=>{d.onReleaseSession(c)};f.webnnCreateMLTensorDownloader=(c,e)=>d.createMLTensorDownloader(c,e);f.webnnRegisterMLTensor=(c,e,g,k)=>d.registerMLTensor(c,e,g,k);f.webnnCreateMLContext=c=>d.createMLContext(c);f.webnnRegisterMLConstant=(c,e,g,k,l,n)=>d.registerMLConstant(c,e,g,k,l,f.Xc, + n);f.webnnRegisterGraphInput=d.registerGraphInput.bind(d);f.webnnIsGraphInput=d.isGraphInput.bind(d);f.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d);f.webnnIsGraphOutput=d.isGraphOutput.bind(d);f.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d);f.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)}}; +-let fa=()=>{const a=b=>(...d)=>{const c=q;d=b(...d);return q!=c?ea():d};(b=>{for(const d of b)f[d]=a(f[d])})(["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"]);"undefined"!==typeof da&&(f._OrtRun=da(f._OrtRun),f._OrtRunWithBinding=da(f._OrtRunWithBinding));fa=void 0};f.asyncInit=()=>{fa?.()};var ha="./this.program",ia=(a,b)=>{throw b;},ja=import.meta.url,ka="",la,ma; ++let fa=()=>{const a=b=>(...d)=>{const c=q;d=b(...d);return q!=c?ea():d};(b=>{for(const d of b)f[d]=a(f[d])})(["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"]);"undefined"!==typeof da&&(f._OrtRun=da(f._OrtRun),f._OrtRunWithBinding=da(f._OrtRunWithBinding));fa=void 0};f.asyncInit=()=>{fa?.()};var ha="./this.program",ia=(a,b)=>{throw b;},ja=import_meta.url,ka="",la,ma; + if(h){var fs=require("fs");ja.startsWith("file:")&&(ka=require("path").dirname(require("url").fileURLToPath(ja))+"/");ma=a=>{a=na(a)?new URL(a):a;return fs.readFileSync(a)};la=async a=>{a=na(a)?new URL(a):a;return fs.readFileSync(a,void 0)};1{process.exitCode=a;throw b;}}else if(aa||ba){try{ka=(new URL(".",ja)).href}catch{}h||(ba&&(ma=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer"; + b.send(null);return new Uint8Array(b.response)}),la=async a=>{if(na(a))return new Promise((d,c)=>{var e=new XMLHttpRequest;e.open("GET",a,!0);e.responseType="arraybuffer";e.onload=()=>{200==e.status||0==e.status&&e.response?d(e.response):c(e.status)};e.onerror=c;e.send(null)});var b=await fetch(a,{credentials:"same-origin"});if(b.ok)return b.arrayBuffer();throw Error(b.status+" : "+b.url);})}var oa=console.log.bind(console),pa=console.error.bind(console); + if(h){var qa=require("util"),ra=a=>"object"==typeof a?qa.inspect(a):a;oa=(...a)=>fs.writeSync(1,a.map(ra).join(" ")+"\n");pa=(...a)=>fs.writeSync(2,a.map(ra).join(" ")+"\n")}var sa=oa,r=pa,ta,ua,t=!1,va,na=a=>a.startsWith("file://");function v(){x.buffer!=A.buffer&&wa()}var xa,ya; +@@ -17,12 +17,12 @@ kb:Fc,ma:Gc,lb:Hc,na:Ic,G:Jc,e:Kc,t:Lc,w:Mc,B:Nc,mb:Oc,K:Pc,x:Qc,oa:Rc,X:Sc,aa:T + async function Ca(){function a(c,e){var g=G=c.exports;c={};for(let [k,l]of Object.entries(g))"function"==typeof l?(g=sd(l),c[k]=g):c[k]=l;G=c;G=td();ud.push(G._b);c=G;vd=c.tb;Ia=c.ub;f._OrtInit=c.vb;f._OrtGetLastError=c.wb;f._OrtCreateSessionOptions=c.xb;f._OrtAppendExecutionProvider=c.yb;f._OrtAddFreeDimensionOverride=c.zb;f._OrtAddSessionConfigEntry=c.Ab;f._OrtReleaseSessionOptions=c.Bb;f._OrtCreateSession=c.Cb;f._OrtReleaseSession=c.Db;f._OrtGetInputOutputCount=c.Eb;f._OrtGetInputOutputMetadata= + c.Fb;f._OrtFree=c.Gb;f._OrtCreateTensor=c.Hb;f._OrtGetTensorData=c.Ib;f._OrtReleaseTensor=c.Jb;f._OrtCreateRunOptions=c.Kb;f._OrtAddRunConfigEntry=c.Lb;f._OrtReleaseRunOptions=c.Mb;f._OrtCreateBinding=c.Nb;f._OrtBindInput=c.Ob;f._OrtBindOutput=c.Pb;f._OrtClearBoundOutputs=c.Qb;f._OrtReleaseBinding=c.Rb;f._OrtRunWithBinding=c.Sb;f._OrtRun=c.Tb;f._OrtEndProfiling=c.Ub;f._JsepOutput=c.Vb;f._JsepGetNodeName=c.Wb;wd=c.Xb;I=f._free=c.Yb;xd=f._malloc=c.Zb;Fa=c.ac;La=c.bc;yd=c.cc;zd=c.dc;Ad=c.ec;Bd=c.fc; + Cd=c.gc;J=c.hc;Dd=c.ic;Ed=c.jc;K=c.kc;Fd=c.lc;L=c.mc;Gd=c.nc;Hd=c.oc;Id=c.pc;Jd=c.qc;dynCall_vii=c.rc;Kd=c.sc;dynCall_v=c.tc;Ld=c.uc;Md=c.vc;dynCall_iii=c.wc;Nd=c.xc;Od=c.yc;Pd=c.zc;Qd=c.Ac;dynCall_vi=c.Bc;Rd=c.Cc;Sd=c.Dc;Td=c.Ec;Ud=c.Fc;Vd=c.Gc;Wd=c.Hc;Xd=c.Ic;Yd=c.Jc;Zd=c.Kc;$d=c.Lc;ae=c.Mc;be=c.Nc;ce=c.Pc;de=c.Qc;ee=c.$c;fe=c.ad;ge=c.fd;he=c.jd;ie=c.kd;je=c.ld;ke=c.md;le=c.nd;me=c.od;ne=c.pd;oe=c.qd;pe=c.vd;qe=c.Sd;re=c.Td;se=c.Ud;te=c.Vd;ua=e;return G}var b=Wa();if(f.instantiateWasm)return new Promise(c=> +-{f.instantiateWasm(b,(e,g)=>{c(a(e,g))})});if(m){var d=new WebAssembly.Instance(ua,Wa());return a(d,ua)}Sa??=f.locateFile?f.locateFile?f.locateFile("ort-wasm-simd-threaded.jsep.wasm",ka):ka+"ort-wasm-simd-threaded.jsep.wasm":(new URL("ort-wasm-simd-threaded.jsep.wasm",import.meta.url)).href;return function(c){return a(c.instance,c.module)}(await Va(b))}class ue{name="ExitStatus";constructor(a){this.message=`Program terminated with exit(${a})`;this.status=a}} ++{f.instantiateWasm(b,(e,g)=>{c(a(e,g))})});if(m){var d=new WebAssembly.Instance(ua,Wa());return a(d,ua)}Sa??=f.locateFile?f.locateFile?f.locateFile("ort-wasm-simd-threaded.jsep.wasm",ka):ka+"ort-wasm-simd-threaded.jsep.wasm":(new URL("ort-wasm-simd-threaded.jsep.wasm",import_meta.url)).href;return function(c){return a(c.instance,c.module)}(await Va(b))}class ue{name="ExitStatus";constructor(a){this.message=`Program terminated with exit(${a})`;this.status=a}} + var ve=a=>{a.terminate();a.onmessage=()=>{}},we=[],xe=0,ye=null,Ce=a=>{0==M.length&&(ze(),Ae(M[0]));var b=M.pop();if(!b)return 6;Be.push(b);N[a.Rc]=b;b.Rc=a.Rc;var d={Sc:"run",Md:a.Ld,bd:a.bd,Rc:a.Rc};h&&b.unref();b.postMessage(d,a.rd);return 0},O=0,P=(a,b,...d)=>{var c=16*d.length,e=L(),g=Fd(c),k=g>>>3,l;for(l of d)"bigint"==typeof l?((v(),F)[k++>>>0]=1n,(v(),F)[k++>>>0]=l):((v(),F)[k++>>>0]=0n,(v(),E)[k++>>>0]=l);a=yd(a,0,c,g,b);K(e);return a}; + function rd(a){if(m)return P(0,1,a);va=a;if(!(0{va=a;if(m)throw De(a),"unwind";rd(a)},M=[],Be=[],ud=[],N={};function Ee(){for(var a=f.numThreads-1;a--;)ze();we.push(async()=>{var b=Fe();xe++;await b;xe--;0==xe&&ye&&(b=ye,ye=null,b())})}var Ge=a=>{var b=a.Rc;delete N[b];M.push(a);Be.splice(Be.indexOf(a),1);a.Rc=0;zd(b)};function Ga(){ud.forEach(a=>a())} + var Ae=a=>new Promise(b=>{a.onmessage=g=>{var k=g.data;g=k.Sc;if(k.Zc&&k.Zc!=wd()){var l=N[k.Zc];l?l.postMessage(k,k.rd):r(`Internal error! Worker sent a message "${g}" to target pthread ${k.Zc}, but that thread no longer exists!`)}else if("checkMailbox"===g)Ka();else if("spawnThread"===g)Ce(k);else if("cleanupThread"===g)He(()=>{Ge(N[k.Nd])});else if("loaded"===g)a.loaded=!0,h&&!a.Rc&&a.unref(),b(a);else if("setimmediate"===k.target)a.postMessage(k);else if("uncaughtException"===g)a.onerror(k.error); + else if("callHandler"===g)f[k.wd](...k.args);else g&&r(`worker sent an unknown command ${g}`)};a.onerror=g=>{r(`${"worker sent an error!"} ${g.filename}:${g.lineno}: ${g.message}`);throw g;};h&&(a.on("message",g=>a.onmessage({data:g})),a.on("error",g=>a.onerror(g)));var d=[],c=[],e;for(e of c)f.propertyIsEnumerable(e)&&d.push(e);a.postMessage({Sc:"load",xd:d,Od:x,Pd:ua})});async function Fe(){if(!m)return Promise.all(M.map(Ae))} +-function ze(){var a=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});M.push(a)}function Ea(a){var b=(v(),D)[a+52>>>2>>>0];a=(v(),D)[a+56>>>2>>>0];Ed(b,b-a);K(b)}var Ja=(a,b)=>{O=0;a=Kd(a,b);0>>=0;var b=new Ke(a);0==(v(),A)[b.Tc+12>>>0]&&(Le(b,!0),Je--);Me(b,!1);Ie.push(b);return Jd(a)}var Q=0,ab=()=>{J(0,0);var a=Ie.pop();Gd(a.cd);Q=0}; ++function ze(){var a=new Worker(new URL(import_meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});M.push(a)}function Ea(a){var b=(v(),D)[a+52>>>2>>>0];a=(v(),D)[a+56>>>2>>>0];Ed(b,b-a);K(b)}var Ja=(a,b)=>{O=0;a=Kd(a,b);0>>=0;var b=new Ke(a);0==(v(),A)[b.Tc+12>>>0]&&(Le(b,!0),Je--);Me(b,!1);Ie.push(b);return Jd(a)}var Q=0,ab=()=>{J(0,0);var a=Ie.pop();Gd(a.cd);Q=0}; + function Le(a,b){b=b?1:0;(v(),A)[a.Tc+12>>>0]=b}function Me(a,b){b=b?1:0;(v(),A)[a.Tc+13>>>0]=b}class Ke{constructor(a){this.cd=a;this.Tc=a-24}}var Ne=a=>{var b=Q;if(!b)return Dd(0),0;var d=new Ke(b);(v(),D)[d.Tc+16>>>2>>>0]=b;var c=(v(),D)[d.Tc+4>>>2>>>0];if(!c)return Dd(0),b;for(var e of a){if(0===e||e===c)break;if(Id(e,c,d.Tc+16))return Dd(e),b}Dd(c);return b};function bb(){return Ne([])}function cb(a){return Ne([a>>>0])}function db(a,b,d,c){return Ne([a>>>0,b>>>0,d>>>0,c>>>0])} + var eb=()=>{var a=Ie.pop();a||H("no exception to throw");var b=a.cd;0==(v(),A)[a.Tc+13>>>0]&&(Ie.push(a),Me(a,!0),Le(a,!1),Je++);Hd(b);Q=b;throw Q;};function fb(a,b,d){a>>>=0;var c=new Ke(a);b>>>=0;d>>>=0;(v(),D)[c.Tc+16>>>2>>>0]=0;(v(),D)[c.Tc+4>>>2>>>0]=b;(v(),D)[c.Tc+8>>>2>>>0]=d;Hd(a);Q=a;Je++;throw Q;}var gb=()=>Je;function Oe(a,b,d,c){return m?P(2,1,a,b,d,c):hb(a,b,d,c)} + function hb(a,b,d,c){a>>>=0;b>>>=0;d>>>=0;c>>>=0;if(!globalThis.SharedArrayBuffer)return 6;var e=[];if(m&&0===e.length)return Oe(a,b,d,c);a={Ld:d,Rc:a,bd:c,rd:e};return m?(a.Sc="spawnThread",postMessage(a,e),0):Ce(a)}function ib(a){Q||=a>>>0;throw Q;} +@@ -41,7 +41,7 @@ function Fb(a,b){a>>>=0;b=S(b>>>0);T(a,{name:b,Oc(d){var c=(v(),D)[d>>>2>>>0];c= + var cf=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,df=(a,b,d)=>{a>>>=1;b=Qe((v(),Na),a,b/2,d);if(16>>0];d+=String.fromCharCode(c)}return d},ef=(a,b,d)=>{d??=2147483647;if(2>d)return 0;d-=2;var c=b;d=d<2*a.length?d/2:a.length;for(var e=0;e>>1>>>0]=g;b+=2}(v(),Ma)[b>>>1>>>0]=0;return b-c},ff=a=>2*a.length,gf=(a,b,d)=>{var c="";a>>>=2;for(var e=0;!(e>=b/4);e++){var g= + (v(),D)[a+e>>>0];if(!g&&!d)break;c+=String.fromCodePoint(g)}return c},hf=(a,b,d)=>{b>>>=0;d??=2147483647;if(4>d)return 0;var c=b;d=c+d-4;for(var e=0;e>>2>>>0]=g;b+=4;if(b+4>d)break}(v(),C)[b>>>2>>>0]=0;return b-c},jf=a=>{for(var b=0,d=0;d>>=0;b>>>=0;d>>>=0;d=S(d);if(2===b){var c=df;var e=ef;var g=ff}else c=gf,e=hf,g=jf;T(a,{name:d,Oc:k=>{var l=(v(),D)[k>>>2>>>0];l=c(k+4,l*b,!0);I(k);return l},Vc:(k,l)=>{if("string"!=typeof l)throw new Ve(`Cannot pass non-string to C++ string type ${d}`);var n=g(l),p=xd(4+n+b);(v(),D)[p>>>2>>>0]=n/b;e(l,p+4,n+b);null!==k&&k.push(I,p);return p},Uc:Ze,Wc(k){I(k)}})}function Hb(a,b){a>>>=0;b=S(b>>>0);T(a,{zd:!0,name:b,Oc:()=>{},Vc:()=>{}})} +-function Ib(a){Fa(a>>>0,!ba,1,!aa,131072,!1);Ga()}var He=a=>{if(!t)try{if(a(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ha(a){a>>>=0;kf||(Atomics.waitAsync((v(),C),a>>>2,a).value.then(Ka),a+=128,Atomics.store((v(),C),a>>>2,1))}var Ka=()=>He(()=>{var a=wd();a&&(Ha(a),Cd())}); ++function Ib(a){Fa(a>>>0,!ba,1,!aa,131072,!1);Ga()}var He=a=>{if(!t)try{if(a(),!(0Number(((navigator.userAgent||"").match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ha(a){a>>>=0;kf||(Atomics.waitAsync((v(),C),a>>>2,a).value.then(Ka),a+=128,Atomics.store((v(),C),a>>>2,1))}var Ka=()=>He(()=>{var a=wd();a&&(Ha(a),Cd())}); + function Jb(a,b){a>>>=0;a==b>>>0?setTimeout(Ka):m?postMessage({Zc:a,Sc:"checkMailbox"}):(a=N[a])&&a.postMessage({Sc:"checkMailbox"})}var lf=[];function Kb(a,b,d,c,e){b>>>=0;e>>>=0;lf.length=0;d=e>>>3;for(c=e+c>>>3;d>>0]?g=(v(),F)[d++>>>0]:g=(v(),E)[d++>>>0];lf.push(g)}return(b?mf[b]:nf[a])(...lf)}var Lb=()=>{O=0};function Mb(a){a>>>=0;m?postMessage({Sc:"cleanupThread",Nd:a}):Ge(N[a])}function Nb(a){h&&N[a>>>0].ref()}var of=a=>{try{a()}catch(b){H(b)}}; + function sd(a){var b=(...d)=>{pf.push(a);try{return a(...d)}finally{t||(pf.pop(),q&&1===Z&&0===pf.length&&(Z=0,O+=1,of(re),"undefined"!=typeof Fibers&&Fibers.Zd()))}};qf.set(a,b);return b}var Z=0,q=null,rf=0,pf=[],sf=new Map,tf=new Map,qf=new Map,uf=0,vf=null,wf=[];function ea(){return new Promise((a,b)=>{vf={resolve:a,reject:b}})} + function xf(){var a=xd(65548),b=a+12;(v(),D)[a>>>2>>>0]=b;(v(),D)[a+4>>>2>>>0]=b+65536;b=pf[0];if(!sf.has(b)){var d=uf++;sf.set(b,d);tf.set(d,b)}b=sf.get(b);(v(),C)[a+8>>>2>>>0]=b;return a}function yf(){var a=(v(),C)[q+8>>>2>>>0];a=tf.get(a);a=qf.get(a);--O;return a()} +diff --git a/node_modules/@huggingface/transformers/dist/transformers.js b/node_modules/@huggingface/transformers/dist/transformers.js +index 3274d9c..ad33ea3 100644 +--- a/node_modules/@huggingface/transformers/dist/transformers.js ++++ b/node_modules/@huggingface/transformers/dist/transformers.js +@@ -50,7 +50,7 @@ var isSafari = () => { + if (typeof navigator === "undefined") { + return false; + } +- const userAgent = navigator.userAgent; ++ const userAgent = navigator.userAgent || ""; + const vendor = navigator.vendor || ""; + const isAppleVendor = vendor.indexOf("Apple") > -1; + const notOtherBrowser = !userAgent.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i) && !userAgent.includes("Chrome") && !userAgent.includes("Android"); +@@ -92,7 +92,7 @@ var apis = Object.freeze({ + var RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE; + var dirname__ = "./"; + if (RUNNING_LOCALLY) { +- const _import_meta_url = Object(import.meta).url; ++ const _import_meta_url = Object(import_meta).url; + if (_import_meta_url) { + dirname__ = node_path_default.dirname(node_path_default.dirname(node_url_default.fileURLToPath(_import_meta_url))); + } else if (typeof __dirname !== "undefined") { +@@ -6037,8 +6037,8 @@ function toAbsoluteURL(url) { + let baseURL; + if (typeof location !== "undefined" && location.href) { + baseURL = location.href; +- } else if (typeof import.meta !== "undefined" && import.meta.url) { +- baseURL = import.meta.url; ++ } else if (typeof import_meta !== "undefined" && import_meta.url) { ++ baseURL = import_meta.url; + } else { + return url; + } +@@ -8245,7 +8245,7 @@ async function es(a = {}) { + }; + var l, m, y = (e, t) => { + throw t; +- }, w = import.meta.url, T = ""; ++ }, w = import_meta.url, T = ""; + if (s || f) { + try { + T = new URL(".", w).href; +@@ -8334,7 +8334,7 @@ async function es(a = {}) { + r.instantiateWasm(n, (u, c) => { + o(e(u, c)); + }); +- }) : i ? e(new WebAssembly.Instance(v, Ye()), v) : (we ??= r.locateFile ? r.locateFile ? r.locateFile("ort-wasm-simd-threaded.asyncify.wasm", T) : T + "ort-wasm-simd-threaded.asyncify.wasm" : new URL("ort-wasm-simd-threaded.asyncify.wasm", import.meta.url).href, t = await (async function(o) { ++ }) : i ? e(new WebAssembly.Instance(v, Ye()), v) : (we ??= r.locateFile ? r.locateFile ? r.locateFile("ort-wasm-simd-threaded.asyncify.wasm", T) : T + "ort-wasm-simd-threaded.asyncify.wasm" : new URL("ort-wasm-simd-threaded.asyncify.wasm", import_meta.url).href, t = await (async function(o) { + var u = we; + if (!g && !oe(u)) try { + var c = fetch(u, { credentials: "same-origin" }); +@@ -8427,7 +8427,7 @@ async function es(a = {}) { + function gn() { + var e = new Worker((() => { + let t = URL; +- return import.meta.url > "file:" && import.meta.url < "file;" ? new t("ort.webgpu.bundle.min.mjs", import.meta.url) : new URL(import.meta.url); ++ return import_meta.url > "file:" && import_meta.url < "file;" ? new t("ort.webgpu.bundle.min.mjs", import_meta.url) : new URL(import_meta.url); + })(), { type: "module", workerData: "em-pthread", name: "em-pthread" }); + We.push(e); + } +@@ -9959,13 +9959,13 @@ var fs; + var Yt = k(() => { + "use strict"; + Ht(); +- as = typeof location > "u" ? void 0 : location.origin, tn = import.meta.url > "file:" && import.meta.url < "file;", Zf = () => { ++ as = typeof location > "u" ? void 0 : location.origin, tn = import_meta.url > "file:" && import_meta.url < "file;", Zf = () => { + if (true) { + if (tn) { + let a = URL; +- return new URL(new a("ort.webgpu.bundle.min.mjs", import.meta.url).href, as).href; ++ return new URL(new a("ort.webgpu.bundle.min.mjs", import_meta.url).href, as).href; + } +- return import.meta.url; ++ return import_meta.url; + } + }, ge = Zf(), ss = () => { + if (ge && !ge.startsWith("blob:")) return ge.substring(0, ge.lastIndexOf("/") + 1); +@@ -11270,7 +11270,7 @@ var mn = k(() => { + try { + Ee = f, Ee.onerror = (d) => r(d), Ee.onmessage = wc, ln = [a, r]; + let i = { type: "init-wasm", in: K }; +- !i.in.wasm.wasmPaths && (s || tn) && (i.in.wasm.wasmPaths = { wasm: new URL("ort-wasm-simd-threaded.asyncify.wasm", import.meta.url).href }), Ee.postMessage(i), cr = s; ++ !i.in.wasm.wasmPaths && (s || tn) && (i.in.wasm.wasmPaths = { wasm: new URL("ort-wasm-simd-threaded.asyncify.wasm", import_meta.url).href }), Ee.postMessage(i), cr = s; + } catch (i) { + r(i); + } +diff --git a/node_modules/@huggingface/transformers/dist/transformers.min.js b/node_modules/@huggingface/transformers/dist/transformers.min.js +index 3814ce4..ebe679e 100644 +--- a/node_modules/@huggingface/transformers/dist/transformers.min.js ++++ b/node_modules/@huggingface/transformers/dist/transformers.min.js +@@ -1,4 +1,4 @@ +-var WI=Object.defineProperty;var _s=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var hs=(t,e)=>{for(var r in e)WI(t,r,{get:e[r],enumerable:!0})};var gt={};var Ut={};var gE={};var VI="4.2.0",Of=typeof self<"u",on=!kE(gt),yE=!kE(Ut),oc=Of&&"caches"in self,HI=typeof globalThis.Deno<"u",T3=typeof globalThis.Bun<"u",ic=HI&&oc&&!on,bE=typeof process<"u",vE=bE&&process?.release?.name==="node"&&!ic,If=typeof window<"u"&&typeof window.document<"u",Cf=Of&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),XI=If||Cf||ic,YI=vE||typeof navigator<"u"&&"gpu"in navigator,KI=typeof navigator<"u"&&"ml"in navigator,QI=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",JI=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",ZI=typeof ServiceWorkerGlobalScope<"u"&&Of&&self instanceof ServiceWorkerGlobalScope,eC=()=>{if(typeof navigator>"u")return!1;let t=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,s=!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android");return r&&s},tC=eC(),ie=Object.freeze({IS_BROWSER_ENV:If,IS_WEBWORKER_ENV:Cf,IS_WEB_ENV:XI,IS_SERVICE_WORKER_ENV:ZI,IS_DENO_WEB_RUNTIME:ic,IS_WEB_CACHE_AVAILABLE:oc,IS_WEBGPU_AVAILABLE:YI,IS_WEBNN_AVAILABLE:KI,IS_SAFARI:tC,IS_PROCESS_AVAILABLE:bE,IS_NODE_ENV:vE,IS_FS_AVAILABLE:on,IS_PATH_AVAILABLE:yE,IS_CRYPTO_AVAILABLE:QI,IS_CHROME_AVAILABLE:JI}),Pf=on&&yE,ac="./";if(Pf){let t=Object(import.meta).url;t?ac=Ut.dirname(Ut.dirname(gE.fileURLToPath(t))):typeof __dirname<"u"&&(ac=Ut.dirname(__dirname))}var rC=Pf?Ut.join(ac,"/.cache/"):null,wE="/models/",sC=Pf?Ut.join(ac,wE):wE,nC=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,It=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),xE=It.WARNING,_e={version:VI,backends:{onnx:{}},get logLevel(){return xE},set logLevel(t){xE=t,_e.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(If||Cf||ic),localModelPath:sC,useFS:on,useBrowserCache:oc,useFSCache:on,cacheDir:rC,useCustomCache:!1,customCache:null,useWasmCache:oc||on,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:nC};function kE(t){return Object.keys(t).length===0}var We=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function lr(t,e){t&&t(e)}var gs=class extends We{constructor(e,r){super(),this.callback=e,this.files_loading=r}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let r=Object.values(this.files_loading).reduce((o,a)=>o+a.loaded,0),s=Object.values(this.files_loading).reduce((o,a)=>o+a.total,0),n=s>0?r/s*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:r,total:s,files:structuredClone(this.files_loading)})}this.callback(e)}};function EE(t){return Number.isInteger(t)||typeof t=="bigint"}function Lf(t){return t==null||t===-1}function zf(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function wt(...t){return Array.prototype.concat.apply([],t)}function AE(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function an(t,e){return Math.abs((t+e)%(2*e)-e)}function Ve(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function TE(t,e){let r=0;for(let s of t)s===e&&++r;return r}var ee={error(...t){_e.logLevel<=It.ERROR&&console.error(...t)},warn(...t){_e.logLevel<=It.WARNING&&console.warn(...t)},info(...t){_e.logLevel<=It.INFO&&console.log(...t)},debug(...t){_e.logLevel<=It.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var oC=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let s=e;for(let n=0;ns&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),r=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+r),r+=1);let s=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,s[o]]))})(),lC=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),cC=lC(zE),SE=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",uC=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${SE}])]+`,` ?[^\\s${SE}]+`]]),lc="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Rf=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),cc=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[s,n]of uC)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1,o=r.replace(/(\\[pP])\{([^}=]+)\}/g,(a,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(o,"gu")}catch{throw s}}}else if(t.String!==void 0){let r=pC(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},pC=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),fC=(t,e,r)=>{let s=[],n=0;for(;nt>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,mC=t=>Number.isInteger(t)||typeof t=="bigint",_C=t=>{let e=0;for(let r of t)++e;return e},hC=t=>NE(t.toLowerCase()),Yt=(...t)=>Array.prototype.concat.apply([],t),$f=t=>new Map(Object.entries(t)),gC=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s0&&r.push(o),s=n.index+o.length}return st.replace(/\p{M}/gu,""),OE=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let s of r)if(!(s in t))return`${e} must contain a "${s}" property`;return null},wC=t=>t.match(/\S+/g)||[],xC=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},po=xC,yC=class extends po{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},vr=yC,bC=class extends vr{tokenize_chinese_chars(t){let e=[];for(let r=0;rtypeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var hs=(t,e)=>{for(var r in e)WI(t,r,{get:e[r],enumerable:!0})};var gt={};var Ut={};var gE={};var VI="4.2.0",Of=typeof self<"u",on=!kE(gt),yE=!kE(Ut),oc=Of&&"caches"in self,HI=typeof globalThis.Deno<"u",T3=typeof globalThis.Bun<"u",ic=HI&&oc&&!on,bE=typeof process<"u",vE=bE&&process?.release?.name==="node"&&!ic,If=typeof window<"u"&&typeof window.document<"u",Cf=Of&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),XI=If||Cf||ic,YI=vE||typeof navigator<"u"&&"gpu"in navigator,KI=typeof navigator<"u"&&"ml"in navigator,QI=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",JI=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",ZI=typeof ServiceWorkerGlobalScope<"u"&&Of&&self instanceof ServiceWorkerGlobalScope,eC=()=>{if(typeof navigator>"u")return!1;let t=(navigator.userAgent||""),r=(navigator.vendor||"").indexOf("Apple")>-1,s=!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android");return r&&s},tC=eC(),ie=Object.freeze({IS_BROWSER_ENV:If,IS_WEBWORKER_ENV:Cf,IS_WEB_ENV:XI,IS_SERVICE_WORKER_ENV:ZI,IS_DENO_WEB_RUNTIME:ic,IS_WEB_CACHE_AVAILABLE:oc,IS_WEBGPU_AVAILABLE:YI,IS_WEBNN_AVAILABLE:KI,IS_SAFARI:tC,IS_PROCESS_AVAILABLE:bE,IS_NODE_ENV:vE,IS_FS_AVAILABLE:on,IS_PATH_AVAILABLE:yE,IS_CRYPTO_AVAILABLE:QI,IS_CHROME_AVAILABLE:JI}),Pf=on&&yE,ac="./";if(Pf){let t=Object(import_meta).url;t?ac=Ut.dirname(Ut.dirname(gE.fileURLToPath(t))):typeof __dirname<"u"&&(ac=Ut.dirname(__dirname))}var rC=Pf?Ut.join(ac,"/.cache/"):null,wE="/models/",sC=Pf?Ut.join(ac,wE):wE,nC=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,It=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),xE=It.WARNING,_e={version:VI,backends:{onnx:{}},get logLevel(){return xE},set logLevel(t){xE=t,_e.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(If||Cf||ic),localModelPath:sC,useFS:on,useBrowserCache:oc,useFSCache:on,cacheDir:rC,useCustomCache:!1,customCache:null,useWasmCache:oc||on,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:nC};function kE(t){return Object.keys(t).length===0}var We=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function lr(t,e){t&&t(e)}var gs=class extends We{constructor(e,r){super(),this.callback=e,this.files_loading=r}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let r=Object.values(this.files_loading).reduce((o,a)=>o+a.loaded,0),s=Object.values(this.files_loading).reduce((o,a)=>o+a.total,0),n=s>0?r/s*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:r,total:s,files:structuredClone(this.files_loading)})}this.callback(e)}};function EE(t){return Number.isInteger(t)||typeof t=="bigint"}function Lf(t){return t==null||t===-1}function zf(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function wt(...t){return Array.prototype.concat.apply([],t)}function AE(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function an(t,e){return Math.abs((t+e)%(2*e)-e)}function Ve(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function TE(t,e){let r=0;for(let s of t)s===e&&++r;return r}var ee={error(...t){_e.logLevel<=It.ERROR&&console.error(...t)},warn(...t){_e.logLevel<=It.WARNING&&console.warn(...t)},info(...t){_e.logLevel<=It.INFO&&console.log(...t)},debug(...t){_e.logLevel<=It.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var oC=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let s=e;for(let n=0;ns&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),r=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+r),r+=1);let s=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,s[o]]))})(),lC=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),cC=lC(zE),SE=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",uC=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${SE}])]+`,` ?[^\\s${SE}]+`]]),lc="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Rf=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),cc=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[s,n]of uC)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1,o=r.replace(/(\\[pP])\{([^}=]+)\}/g,(a,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(o,"gu")}catch{throw s}}}else if(t.String!==void 0){let r=pC(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},pC=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),fC=(t,e,r)=>{let s=[],n=0;for(;nt>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,mC=t=>Number.isInteger(t)||typeof t=="bigint",_C=t=>{let e=0;for(let r of t)++e;return e},hC=t=>NE(t.toLowerCase()),Yt=(...t)=>Array.prototype.concat.apply([],t),$f=t=>new Map(Object.entries(t)),gC=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s0&&r.push(o),s=n.index+o.length}return st.replace(/\p{M}/gu,""),OE=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let s of r)if(!(s in t))return`${e} must contain a "${s}" property`;return null},wC=t=>t.match(/\S+/g)||[],xC=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},po=xC,yC=class extends po{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},vr=yC,bC=class extends vr{tokenize_chinese_chars(t){let e=[];for(let r=0;rr.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},EC=kC,AC=class extends vr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>RE(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},TC=AC,MC=class extends vr{normalize(t){let e=cc(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},SC=MC,OC=class extends vr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},uc=OC,IC=class extends uc{constructor(){super(...arguments),this.form="NFC"}},CC=IC,PC=class extends uc{constructor(){super(...arguments),this.form="NFD"}},LC=PC,zC=class extends uc{constructor(){super(...arguments),this.form="NFKC"}},NC=zC,RC=class extends uc{constructor(){super(...arguments),this.form="NFKD"}},$C=RC,DC=class extends vr{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},BC=DC,UC=class extends vr{normalize(t){return NE(t)}},FC=UC,GC=class extends vr{normalize(t){return t.toLowerCase()}},jC=GC,qC=class extends vr{normalize(t){return t=this.config.prepend+t,t}},WC=qC;function VC(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new vC(t);case"Precompiled":return new EC(t);case"Sequence":return new TC(t);case"Replace":return new SC(t);case"NFC":return new CC(t);case"NFD":return new LC(t);case"NFKC":return new NC(t);case"NFKD":return new $C(t);case"Strip":return new BC(t);case"StripAccents":return new FC(t);case"Lowercase":return new jC(t);case"Prepend":return new WC(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var RE=VC,HC=class extends po{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},Kt=HC,XC=class extends Kt{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=zE,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(s=>Array.from(this.text_encoder.encode(s),n=>this.byte_encoder[n]).join(""))}},YC=XC,KC=class extends Kt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},QC=KC,JC=class extends Kt{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},s=t.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},ZC=JC,eP=class extends Kt{constructor(t){super(),this.config=t,this.pattern=cc(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):gC(t,this.pattern)}},tP=eP,rP=class extends Kt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${lc}]+|[${lc}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},sP=rP,nP=class extends Kt{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},oP=nP,aP=class extends Kt{constructor(){super(),this.pattern=new RegExp(`[^\\s${lc}]+|[${lc}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},iP=aP,lP=class extends Kt{constructor(t){super(),this.config=t,this.pattern=cc(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},cP=lP,uP=class extends Kt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>$E(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},pP=uP,fP=class extends Kt{pre_tokenize_text(t){return wC(t)}},dP=fP,mP=class extends Kt{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let r=0;rthis.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,a=[];for(;o0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){n=!0;break}a.push(l),o=i}n?e.push(this.unk_token):e.push(...a)}return e}},IE=wP,CE=class DE{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new DE(!1,new Map)}},xP=class{constructor(){this.root=CE.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let s=e.children.get(r);s===void 0&&(s=CE.default(),e.children.set(r,s)),e=s}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let s of t){if(r+=s,e=e.children.get(s),e===void 0)return;e.is_leaf&&(yield r)}}},yP=xP,Nf=class BE{constructor(e,r,s,n,o){this.token_id=e,this.node_id=r,this.pos=s,this.length=n,this.score=o,this.prev=null,this.backtrace_score=0}clone(){let e=new BE(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},bP=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let s=new Nf(this.bos_token_id??0,0,0,0,0),n=new Nf(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(s)}insert(t,e,r,s){let n=this.nodes.length,o=new Nf(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let c of this.end_nodes[e]){let u=c.backtrace_score+a.score;(l===null||u>i)&&(l=c.clone(),i=u)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},vP=bP;function kP(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=kP(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new yP,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,s=0;for(;sr>s,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},SP=MP,OP=class extends pc{constructor(t){super(t),this.tokens_to_ids=$f(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,s]of this.tokens_to_ids)this.vocab[s]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,s)=>[JSON.stringify(r),s])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new SP(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){let n=new TP((i,l)=>i.score`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);o.every(a=>this.tokens_to_ids.has(a))?e.push(...o):this.unk_token!=null&&e.push(this.unk_token)}else this.unk_token!=null&&e.push(this.unk_token)}return e}},LE=OP,IP=class extends pc{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=$f(e.target_lang?r[e.target_lang]:r),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[s,n]of this.tokens_to_ids)this.vocab[n]=s}encode(t){return t}},CP=IP;function PP(t,e){switch(t.type){case"WordPiece":return new IE(t);case"Unigram":return new PE(t,e.eos_token);case"BPE":return new LE(t);default:if(t.vocab)return Array.isArray(t.vocab)?new PE(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new LE(t):new IE(t):new CP(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var LP=PP,zP=class extends po{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},fo=zP,NP=class extends fo{post_process(t,e=null,r=!0){let s=e===null?this.config.single:this.config.pair,n=[],o=[];for(let a of s)"SpecialToken"in a?r&&(n.push(a.SpecialToken.id),o.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(n=Yt(n,t),o=Yt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Yt(n,e),o=Yt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},RP=NP,$P=class extends fo{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},DP=$P,BP=class extends fo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Yt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=[],o=r?[this.sep[0]]:[];t=Yt(t,n,e,o),s=Yt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},UP=BP,FP=class extends fo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Yt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=r?[this.sep[0]]:[],o=r?[this.sep[0]]:[];t=Yt(t,n,e,o),s=Yt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},GP=FP,jP=class extends fo{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>UE(e))}post_process(t,e=null,r=!0){let s={tokens:t,tokens_pair:e};for(let n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},qP=jP;function WP(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new RP(t);case"ByteLevel":return new DP(t);case"BertProcessing":return new UP(t);case"RobertaProcessing":return new GP(t);case"Sequence":return new qP(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var UE=WP,VP=class extends po{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Ft=VP,HP=class extends Ft{constructor(t){super(t),this.byte_decoder=cC,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),r=new Uint8Array([...e].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let s of t)this.added_tokens.find(n=>n.content===s)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(s)):r.push(s);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},XP=HP,YP=class extends Ft{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let s=this.config.prefix;s&&e.startsWith(s)?e=e.replace(s,""):e=" "+e}return this.cleanup&&(e=Rf(e)),e})}},KP=YP,QP=class extends Ft{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;re.replaceAll(this.suffix,r===t.length-1?"":" "))}},eL=ZP,tL=class extends Ft{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;nn!==this.pad_token).join("");return this.cleanup&&(s=Rf(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},rL=tL,sL=class extends Ft{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>FE(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},nL=sL,oL=class extends Ft{decode_chain(t){let e=cc(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},aL=oL,iL=class extends Ft{decode_chain(t){return[t.join("")]}},lL=iL,cL=class extends Ft{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n")){let o=parseInt(s.slice(3,5),16);isNaN(o)||(n=o)}if(n!==null)r.push(n);else{if(r.length>0){let o=this.text_decoder.decode(Uint8Array.from(r));e.push(o),r=[]}e.push(s)}}if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}return e}},fL=pL;function dL(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new XP(t);case"WordPiece":return new KP(t);case"Metaspace":return new JP(t);case"BPEDecoder":return new eL(t);case"CTC":return new rL(t);case"Sequence":return new nL(t);case"Replace":return new aL(t);case"Fuse":return new lL(t);case"Strip":return new uL(t);case"ByteFallback":return new fL(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var FE=dL,mL=class{constructor(t,e){let r=OE(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=OE(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=RE(this.tokenizer.normalizer),this.pre_tokenizer=$E(this.tokenizer.pre_tokenizer),this.model=LP(this.tokenizer.model,this.config),this.post_processor=UE(this.tokenizer.post_processor),this.decoder=FE(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let n=[],o=[];this.added_tokens_map=new Map;for(let a of this.tokenizer.added_tokens){let i=new iC(a);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){let l=this.normalizer(i.content);o.push(l),this.added_tokens_map.set(l,i)}else n.push(i.content)}(this.config.additional_special_tokens??[]).forEach(a=>{this.special_tokens.includes(a)||this.special_tokens.push(a)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new ME(n),this.splitter_normalized=new ME(o),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){let{tokens:n,token_type_ids:o}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),a=n.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:a,tokens:n,attention_mask:new Array(a.length).fill(1)};return s&&o&&(i.token_type_ids=o),i}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!mC(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=t.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);e.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let s=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(s=s.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=Rf(s)),s}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((r,s)=>{let n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(e[s-1]=e[s-1].trimEnd()),n.rstrip&&s{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=hC(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let n=this.splitter_normalized.split(r);return n.forEach((o,a)=>{let i=this.added_tokens_map.get(o);i&&(i.lstrip&&a>0&&(n[a-1]=n[a-1].trimEnd()),i.rstrip&&a{if(o.length===0)return[];if(this.added_tokens_map.has(o))return[o];let a=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:s}):[o];return this.model(a)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let s=this.encode_text(t),n=this.encode_text(e||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Yt(s??[],n??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let r=0;r=",D.ComparisonBinaryOperator],["==",D.ComparisonBinaryOperator],["!=",D.ComparisonBinaryOperator],["<",D.ComparisonBinaryOperator],[">",D.ComparisonBinaryOperator],["+",D.AdditiveBinaryOperator],["-",D.AdditiveBinaryOperator],["~",D.AdditiveBinaryOperator],["*",D.MultiplicativeBinaryOperator],["/",D.MultiplicativeBinaryOperator],["%",D.MultiplicativeBinaryOperator],["=",D.Equals]],hL=new Map([["n",` + `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function gL(t,e={}){return t.endsWith(` + `)&&(t=t.slice(0,-1)),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%-])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%-]})\n/g,"$1")),t.replace(/{%\s*(end)?generation\s*%}/gs,"")}function wL(t,e={}){let r=[],s=gL(t,e),n=0,o=0,a=c=>{let u="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],m=hL.get(f);if(m===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);u+=m;continue}if(u+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return u},i=()=>{let c=r.at(-1);c&&c.type===D.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n0){r.push(new Gt(f,D.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let f=s[n]==="-";f&&++n;let m="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");m+=s[n++]}let _=m.endsWith("-");_&&(m=m.slice(0,-1)),f&&i(),r.push(new Gt(m,D.Comment)),n+=2,_&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Gt("{%",D.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Gt("{{",D.OpenExpression)),o=0,n+=3;continue}if(a(qE),s.slice(n,n+3)==="-%}"){r.push(new Gt("%}",D.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Gt("}}",D.CloseExpression)),n+=3,l();continue}let u=s[n];if(u==="-"||u==="+"){let f=r.at(-1)?.type;if(f===D.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${u}`);switch(f){case D.Identifier:case D.NumericLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++n;let m=a(mo);r.push(new Gt(`${u}${m}`,m.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(let[f,m]of _L){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new Gt(f,m)),m===D.OpenExpression?o=0:m===D.OpenCurlyBracket?++o:m===D.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(u==="'"||u==='"'){++n;let f=a(m=>m!==u);r.push(new Gt(f,D.StringLiteral)),++n;continue}if(mo(u)){let f=a(mo);if(s[n]==="."&&mo(s[n+1])){++n;let m=a(mo);f=`${f}.${m}`}r.push(new Gt(f,D.NumericLiteral));continue}if(jE(u)){let f=a(jE);r.push(new Gt(f,D.Identifier));continue}throw new SyntaxError(`Unexpected character: ${u}`)}return r}var Jt=class{type="Statement"},xL=class extends Jt{constructor(t){super(),this.body=t}type="Program"},yL=class extends Jt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},bL=class extends Jt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},vL=class extends Jt{type="Break"},kL=class extends Jt{type="Continue"},EL=class extends Jt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},AL=class extends Jt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},TL=class extends Jt{constructor(t){super(),this.value=t}type="Comment"},Lt=class extends Jt{type="Expression"},ML=class extends Lt{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},WE=class extends Lt{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},ln=class extends Lt{constructor(t){super(),this.value=t}type="Identifier"},cn=class extends Lt{constructor(t){super(),this.value=t}type="Literal"},SL=class extends cn{type="IntegerLiteral"},OL=class extends cn{type="FloatLiteral"},VE=class extends cn{type="StringLiteral"},IL=class extends cn{type="ArrayLiteral"},HE=class extends cn{type="TupleLiteral"},CL=class extends cn{type="ObjectLiteral"},_o=class extends Lt{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},PL=class extends Lt{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},LL=class extends Jt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},zL=class extends Lt{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},NL=class extends Lt{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},RL=class extends Lt{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},$L=class extends Lt{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},DL=class extends Lt{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},BL=class extends Lt{constructor(t){super(),this.argument=t}type="SpreadExpression"},UL=class extends Jt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},FL=class extends Lt{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function GL(t){let e=new xL([]),r=0;function s(L,R){let U=t[r++];if(!U||U.type!==L)throw new Error(`Parser Error: ${R}. ${U.type} !== ${L}.`);return U}function n(L){if(!l(L))throw new SyntaxError(`Expected ${L}`);++r}function o(){switch(t[r].type){case D.Comment:return new TL(t[r++].value);case D.Text:return c();case D.OpenStatement:return u();case D.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...L){return r+L.length<=t.length&&L.every((R,U)=>R===t[r+U].type)}function i(...L){return t[r]?.type===D.OpenStatement&&t[r+1]?.type===D.Identifier&&L.includes(t[r+1]?.value)}function l(...L){return r+L.length<=t.length&&L.every((R,U)=>t[r+U].type==="Identifier"&&R===t[r+U].value)}function c(){return new VE(s(D.Text,"Expected text token").value)}function u(){if(s(D.OpenStatement,"Expected opening statement token"),t[r].type!==D.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let L=t[r].value,R;switch(L){case"set":++r,R=m();break;case"if":++r,R=_(),s(D.OpenStatement,"Expected {% token"),n("endif"),s(D.CloseStatement,"Expected %} token");break;case"macro":++r,R=w(),s(D.OpenStatement,"Expected {% token"),n("endmacro"),s(D.CloseStatement,"Expected %} token");break;case"for":++r,R=b(),s(D.OpenStatement,"Expected {% token"),n("endfor"),s(D.CloseStatement,"Expected %} token");break;case"call":{++r;let U=null;a(D.OpenParen)&&(U=F());let Q=K();if(Q.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let le=F();s(D.CloseStatement,"Expected closing statement token");let je=[];for(;!i("endcall");)je.push(o());s(D.OpenStatement,"Expected '{%'"),n("endcall"),s(D.CloseStatement,"Expected closing statement token");let ce=new WE(Q,le);R=new UL(ce,U,je);break}case"break":++r,s(D.CloseStatement,"Expected closing statement token"),R=new vL;break;case"continue":++r,s(D.CloseStatement,"Expected closing statement token"),R=new kL;break;case"filter":{++r;let U=K();U instanceof ln&&a(D.OpenParen)&&(U=G(U)),s(D.CloseStatement,"Expected closing statement token");let Q=[];for(;!i("endfilter");)Q.push(o());s(D.OpenStatement,"Expected '{%'"),n("endfilter"),s(D.CloseStatement,"Expected '%}'"),R=new LL(U,Q);break}default:throw new SyntaxError(`Unknown statement type: ${L}`)}return R}function f(){s(D.OpenExpression,"Expected opening expression token");let L=A();return s(D.CloseExpression,"Expected closing expression token"),L}function m(){let L=x(),R=null,U=[];if(a(D.Equals))++r,R=x();else{for(s(D.CloseStatement,"Expected %} token");!i("endset");)U.push(o());s(D.OpenStatement,"Expected {% token"),n("endset")}return s(D.CloseStatement,"Expected closing statement token"),new EL(L,R,U)}function _(){let L=A();s(D.CloseStatement,"Expected closing statement token");let R=[],U=[];for(;!i("elif","else","endif");)R.push(o());if(i("elif")){++r,++r;let Q=_();U.push(Q)}else if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endif");)U.push(o());return new yL(L,R,U)}function w(){let L=K();if(L.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let R=F();s(D.CloseStatement,"Expected closing statement token");let U=[];for(;!i("endmacro");)U.push(o());return new AL(L,R,U)}function x(L=!1){let R=L?K:A,U=[R()],Q=a(D.Comma);for(;Q&&(++r,U.push(R()),!!a(D.Comma)););return Q?new HE(U):U[0]}function b(){let L=x(!0);if(!(L instanceof ln||L instanceof HE))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${L.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let R=A();s(D.CloseStatement,"Expected closing statement token");let U=[];for(;!i("endfor","else");)U.push(o());let Q=[];if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endfor");)Q.push(o());return new bL(L,R,U,Q)}function A(){return k()}function k(){let L=S();if(l("if")){++r;let R=S();if(l("else")){++r;let U=k();return new FL(R,L,U)}else return new zL(L,R)}return L}function S(){let L=M();for(;l("or");){let R=t[r];++r;let U=M();L=new _o(R,L,U)}return L}function M(){let L=O();for(;l("and");){let R=t[r];++r;let U=O();L=new _o(R,L,U)}return L}function O(){let L;for(;l("not");){let R=t[r];++r;let U=O();L=new RL(R,U)}return L??I()}function I(){let L=v();for(;;){let R;if(l("not","in"))R=new Gt("not in",D.Identifier),r+=2;else if(l("in"))R=t[r++];else if(a(D.ComparisonBinaryOperator))R=t[r++];else break;let U=v();L=new _o(R,L,U)}return L}function v(){let L=$();for(;a(D.AdditiveBinaryOperator);){let R=t[r];++r;let U=$();L=new _o(R,L,U)}return L}function B(){let L=J(K());return a(D.OpenParen)?G(L):L}function G(L){let R=new WE(L,F());return R=J(R),a(D.OpenParen)&&(R=G(R)),R}function F(){s(D.OpenParen,"Expected opening parenthesis for arguments list");let L=X();return s(D.CloseParen,"Expected closing parenthesis for arguments list"),L}function X(){let L=[];for(;!a(D.CloseParen);){let R;if(t[r].type===D.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let U=A();R=new BL(U)}else if(R=A(),a(D.Equals)){if(++r,!(R instanceof ln))throw new SyntaxError("Expected identifier for keyword argument");let U=A();R=new DL(R,U)}L.push(R),a(D.Comma)&&++r}return L}function Y(){let L=[],R=!1;for(;!a(D.CloseSquareBracket);)a(D.Colon)?(L.push(void 0),++r,R=!0):(L.push(A()),a(D.Colon)&&(++r,R=!0));if(L.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(R){if(L.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new $L(...L)}return L[0]}function J(L){for(;a(D.Dot)||a(D.OpenSquareBracket);){let R=t[r];++r;let U,Q=R.type===D.OpenSquareBracket;if(Q)U=Y(),s(D.CloseSquareBracket,"Expected closing square bracket");else if(U=K(),U.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");L=new ML(L,U,Q)}return L}function $(){let L=C();for(;a(D.MultiplicativeBinaryOperator);){let R=t[r++],U=C();L=new _o(R,L,U)}return L}function C(){let L=se();for(;l("is");){++r;let R=l("not");R&&++r;let U=K();if(!(U instanceof ln))throw new SyntaxError("Expected identifier for the test");L=new NL(L,R,U)}return L}function se(){let L=B();for(;a(D.Pipe);){++r;let R=K();if(!(R instanceof ln))throw new SyntaxError("Expected identifier for the filter");a(D.OpenParen)&&(R=G(R)),L=new PL(L,R)}return L}function K(){let L=t[r++];switch(L.type){case D.NumericLiteral:{let R=L.value;return R.includes(".")?new OL(Number(R)):new SL(Number(R))}case D.StringLiteral:{let R=L.value;for(;a(D.StringLiteral);)R+=t[r++].value;return new VE(R)}case D.Identifier:return new ln(L.value);case D.OpenParen:{let R=x();return s(D.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),R}case D.OpenSquareBracket:{let R=[];for(;!a(D.CloseSquareBracket);)R.push(A()),a(D.Comma)&&++r;return++r,new IL(R)}case D.OpenCurlyBracket:{let R=new Map;for(;!a(D.CloseCurlyBracket);){let U=A();s(D.Colon,"Expected colon between key and value in object literal");let Q=A();R.set(U,Q),a(D.Comma)&&++r}return++r,new CL(R)}default:throw new SyntaxError(`Unexpected token: ${L.type}`)}}for(;r0)for(let n=t;ne;n+=r)s.push(n);return s}function XE(t,e,r,s=1){let n=Math.sign(s);n>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));let o=[];for(let a=e;n*ae.toUpperCase())}function WL(t){return VL(new Date,t)}function VL(t,e){let r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),n=o=>o<10?"0"+o:o.toString();return e.replace(/%[YmdbBHM%]/g,o=>{switch(o){case"%Y":return t.getFullYear().toString();case"%m":return n(t.getMonth()+1);case"%d":return n(t.getDate());case"%b":return s.format(t);case"%B":return r.format(t);case"%H":return n(t.getHours());case"%M":return n(t.getMinutes());case"%%":return"%";default:return o}})}function HL(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function XL(t,e,r,s){if(s===0)return t;let n=s==null||s<0?1/0:s,o=e.length===0?new RegExp("(?=)","gu"):new RegExp(HL(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var YE=class extends Error{},KE=class extends Error{},cr=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new de(!!this.value)}toString(){return String(this.value)}},he=class extends cr{type="IntegerValue"},Ze=class extends cr{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},te=class extends cr{type="StringValue";builtins=new Map([["upper",new Xe(()=>new te(this.value.toUpperCase()))],["lower",new Xe(()=>new te(this.value.toLowerCase()))],["strip",new Xe(()=>new te(this.value.trim()))],["title",new Xe(()=>new te(qL(this.value)))],["capitalize",new Xe(()=>new te(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new he(this.value.length)],["rstrip",new Xe(()=>new te(this.value.trimEnd()))],["lstrip",new Xe(()=>new te(this.value.trimStart()))],["startswith",new Xe(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof te)return new de(this.value.startsWith(e.value));if(e instanceof ye){for(let r of e.value){if(!(r instanceof te))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new de(!0)}return new de(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Xe(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof te)return new de(this.value.endsWith(e.value));if(e instanceof ye){for(let r of e.value){if(!(r instanceof te))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new de(!0)}return new de(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Xe(t=>{let e=t[0]??new Ye;if(!(e instanceof te||e instanceof Ye))throw new Error("sep argument must be a string or null");let r=t[1]??new he(-1);if(!(r instanceof he))throw new Error("maxsplit argument must be a number");let s=[];if(e instanceof Ye){let n=this.value.trimStart();for(let{0:o,index:a}of n.matchAll(/\S+/g)){if(r.value!==-1&&s.length>=r.value&&a!==void 0){s.push(o+n.slice(a+o.length));break}s.push(o)}}else{if(e.value==="")throw new Error("empty separator");s=this.value.split(e.value),r.value!==-1&&s.length>r.value&&s.push(s.splice(r.value).join(e.value))}return new ye(s.map(n=>new te(n)))})],["replace",new Xe(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],r=t[1];if(!(e instanceof te&&r instanceof te))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new Ye:s=t[2]:s=new Ye,!(s instanceof he||s instanceof Ye))throw new Error("replace() count argument must be a number or null");return new te(XL(this.value,e.value,r.value,s.value))})]])},de=class extends cr{type="BooleanValue"},YL=/[\x7f-\uffff]/g;function QE(t){return t.replace(YL,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function xs(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,c;switch(a?[l,c]=a:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let u=JSON.stringify(t.value);return o&&(u=QE(u)),u}case"ArrayValue":case"ObjectValue":{let u=n?" ".repeat(n):"",f=` +@@ -7,10 +7,10 @@ var WI=Object.defineProperty;var _s=(t=>typeof require<"u"?require:typeof Proxy< + `));case"join":case"string":return t;case"int":{let n=parseInt(t.value,10);return new he(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new Ze(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof he||t instanceof Ze)switch(s.value){case"abs":return t instanceof he?new he(Math.abs(t.value)):new Ze(Math.abs(t.value));case"int":return new he(Math.floor(t.value));case"float":return new Ze(t.value);case"string":return new te(t.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(t instanceof ft)switch(s.value){case"items":return new ye(Array.from(t.value.entries()).map(([n,o])=>new ye([new te(n),o])));case"length":return new he(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof Xe?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(t instanceof de)switch(s.value){case"bool":return new de(t.value);case"int":return new he(t.value?1:0);case"float":return new Ze(t.value?1:0);case"string":return new te(t.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${t.type}`)}else if(e.type==="CallExpression"){let s=e;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);let n=s.callee.value;if(n==="tojson"){let[,o]=this.evaluateArguments(s.args,r),a=o.get("indent")??new Ye;if(!(a instanceof he||a instanceof Ye))throw new Error("If set, indent must be a number");let i=o.get("ensure_ascii")??new de(!1);if(!(i instanceof de))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new de(!1);if(!(l instanceof de))throw new Error("If set, sort_keys must be a boolean");let c=o.get("separators")??new Ye,u=null;if(c instanceof ye||c instanceof JE){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,m]=c.value;if(!(f instanceof te)||!(m instanceof te))throw new Error("separators must be a tuple of two strings");u=[f.value,m.value]}else if(!(c instanceof Ye))throw new Error("If set, separators must be a tuple of two strings");return new te(xs(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:u}))}else if(n==="join"){let o;if(t instanceof te)o=Array.from(t.value);else if(t instanceof ye)o=t.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[a,i]=this.evaluateArguments(s.args,r),l=a.at(0)??i.get("separator")??new te("");if(!(l instanceof te))throw new Error("separator must be a string");return new te(o.join(l.value))}else if(n==="int"||n==="float"){let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("default")??(n==="int"?new he(0):new Ze(0));if(t instanceof te){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new he(l):new Ze(l)}else{if(t instanceof he||t instanceof Ze)return t;if(t instanceof de)return n==="int"?new he(t.value?1:0):new Ze(t.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}}else if(n==="default"){let[o,a]=this.evaluateArguments(s.args,r),i=o[0]??new te(""),l=o[1]??a.get("boolean")??new de(!1);if(!(l instanceof de))throw new Error("`default` filter flag must be a boolean");return t instanceof He||l.value&&!t.__bool__().value?i:t}if(t instanceof ye){switch(n){case"sort":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("reverse")??new de(!1);if(!(i instanceof de))throw new Error("reverse must be a boolean");let l=o.at(1)??a.get("case_sensitive")??new de(!1);if(!(l instanceof de))throw new Error("case_sensitive must be a boolean");let c=o.at(2)??a.get("attribute")??new Ye;if(!(c instanceof te||c instanceof he||c instanceof Ye))throw new Error("attribute must be a string, integer, or null");let u=f=>{if(c instanceof Ye)return f;let m=c instanceof he?String(c.value):c.value;return ZE(f,m)};return new ye(t.value.slice().sort((f,m)=>{let _=u(f),w=u(m),x=Df(_,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!(f instanceof ft)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[a,i,l]=s.args.map(f=>this.evaluate(f,r)),c;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);c=f}else c=(...f)=>f[0].__bool__().value;let u=t.value.filter(f=>{let m=f.value.get(a.value),_=m?c(m,l):!1;return o?_:!_});return new ye(u)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof te))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(c=>{if(!(c instanceof ft))throw new Error("items in map must be an object");let u=ZE(c,a.value);return u instanceof He?i??new He:u});return new ye(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof te){switch(n){case"indent":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("width")??new he(4);if(!(i instanceof he))throw new Error("width must be a number");let l=o.at(1)??a.get("first")??new de(!1),c=o.at(2)??a.get("blank")??new de(!1),u=t.value.split(` + `),f=" ".repeat(i.value),m=u.map((_,w)=>!l.value&&w===0||!c.value&&_.length===0?_:f+_);return new te(m.join(` + `))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof Xe))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new ho(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof ft){let o=t.builtins.get(n);if(o&&o instanceof Xe){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new ho(i)),o.value(a,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}throw new Error(`Unknown filter: ${e.type}`)}evaluateFilterExpression(t,e){let r=this.evaluate(t.operand,e);return this.applyFilter(r,t.filter,e)}evaluateTestExpression(t,e){let r=this.evaluate(t.operand,e),s=e.tests.get(t.test.value);if(!s)throw new Error(`Unknown test: ${t.test.value}`);let n=s(r);return new de(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new He}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);if(t.operator.value==="not")return new de(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evaluateTernaryExpression(t,e){return this.evaluate(t.condition,e).__bool__().value?this.evaluate(t.trueExpr,e):this.evaluate(t.falseExpr,e)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(let s of t){let n=this.evaluate(s,e);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new te(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){let[r,s]=this.evaluateArguments(t.args,e);s.size>0&&r.push(new ho(s));let n=this.evaluate(t.callee,e);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof ye||t instanceof te))throw new Error("Slice object must be an array or string");let s=this.evaluate(e.start,r),n=this.evaluate(e.stop,r),o=this.evaluate(e.step,r);if(!(s instanceof he||s instanceof He))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof he||n instanceof He))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof he||o instanceof He))throw new Error("Slice step must be numeric or undefined");return t instanceof ye?new ye(XE(t.value,s.value,n.value,o.value)):new te(XE(Array.from(t.value),s.value,n.value,o.value).join(""))}evaluateMemberExpression(t,e){let r=this.evaluate(t.object,e),s;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);s=this.evaluate(t.property,e)}else s=new te(t.property.value);let n;if(r instanceof ft){if(!(s instanceof te))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof ye||r instanceof te)if(s instanceof he)n=r.value.at(s.value),r instanceof te&&(n=new te(r.value.at(s.value)));else if(s instanceof te)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof te))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof cr?n:new He}evaluateSet(t,e){let r=t.value?this.evaluate(t.value,e):this.evaluateBlock(t.body,e);if(t.assignee.type==="Identifier"){let s=t.assignee.value;e.setVariable(s,r)}else if(t.assignee.type==="TupleLiteral"){let s=t.assignee;if(!(r instanceof ye))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let o=0;o_.setVariable(t.loopvar.value,f);else if(t.loopvar.type==="TupleLiteral"){let _=t.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);let w=f;if(_.value.length!==w.value.length)throw new Error(`Too ${_.value.length>w.value.length?"few":"many"} items to unpack`);m=x=>{for(let b=0;b<_.value.length;++b){if(_.value[b].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${_.value[b].type}`);x.setVariable(_.value[b].value,w.value[b])}}}else throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);s&&(m(u),!this.evaluate(s,u).__bool__().value)||(o.push(f),a.push(m))}let i="",l=!0;for(let c=0;c0?o[c-1]:new He],["nextitem",c{let n=new ws(s);r=r.slice();let o;r.at(-1)?.type==="KeywordArgumentsValue"&&(o=r.pop());for(let a=0;a{let c=new ws(l);if(t.callerArgs)for(let u=0;uthis.evaluate(r,e)));case"TupleLiteral":return new JE(t.value.map(r=>this.evaluate(r,e)));case"ObjectLiteral":{let r=new Map;for(let[s,n]of t.value){let o=this.evaluate(s,e);if(!(o instanceof te))throw new Error(`Object keys must be strings: got ${o.type}`);r.set(o.value,this.evaluate(n,e))}return new ft(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"FilterStatement":return this.evaluateFilterStatement(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);case"SelectExpression":return this.evaluateSelectExpression(t,e);case"Ternary":return this.evaluateTernaryExpression(t,e);case"Comment":return new Ye;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function fc(t){switch(typeof t){case"number":return Number.isInteger(t)?new he(t):new Ze(t);case"string":return new te(t);case"boolean":return new de(t);case"undefined":return new He;case"object":return t===null?new Ye:Array.isArray(t)?new ye(t.map(fc)):new ft(new Map(Object.entries(t).map(([e,r])=>[e,fc(r)])));case"function":return new Xe((e,r)=>{let s=t(...e.map(n=>n.value))??null;return fc(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var at=` +-`,JL="{%- ",ZL=" -%}";function ez(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function tz(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Qt(t.body,0,r).replace(/\n$/,"")}function xt(...t){return JL+t.join(" ")+ZL}function Qt(t,e,r){return t.map(s=>rz(s,e,r)).join(at)}function rz(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Qt(t.body,e,r);case"If":return sz(t,e,r);case"For":return nz(t,e,r);case"Set":return oz(t,e,r);case"Macro":return az(t,e,r);case"Break":return s+xt("break");case"Continue":return s+xt("continue");case"CallStatement":return iz(t,e,r);case"FilterStatement":return lz(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function sz(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+xt("if",ke(n[0].test))+at+Qt(n[0].body,e+1,r);for(let i=1;i0&&(a+=at+s+xt("else")+at+Qt(o.alternate,e+1,r)),a+=at+s+xt("endif"),a}function nz(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+xt("for",ke(t.loopvar),"in",n)+at+Qt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=at+s+xt("else")+at+Qt(t.defaultBlock,e+1,r)),o+=at+s+xt("endfor"),o}function oz(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+xt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+at+Qt(t.body,e+1,r)+at+s+xt("endset")}function az(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+xt("macro",`${t.name.value}(${n})`)+at+Qt(t.body,e+1,r)+at+s+xt("endmacro")}function iz(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+xt(`call${n}`,o)+at;return a+=Qt(t.body,e+1,r)+at,a+=s+xt("endcall"),a}function lz(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+xt("filter",n)+at;return o+=Qt(t.body,e+1,r)+at,o+=s+xt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=ez(r),n=ke(r.left,s),o=ke(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var eA=class{parsed;constructor(t){let e=wL(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=GL(e)}render(t){let e=new ws;if(KL(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new QL(e).run(this.parsed).value}format(t){return tz(this.parsed,t?.indent||" ")}};var cz={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"},Pr=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=gt.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=gt.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=gt.createReadStream(e);this.body=new ReadableStream({start(n){s.on("data",o=>n.enqueue(o)),s.on("end",()=>n.close()),s.on("error",o=>n.error(o))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",cz[e]??"application/octet-stream")}clone(){let e=new t(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await gt.promises.readFile(this.filePath)).buffer}async blob(){let e=await gt.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await gt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};var Lr=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(ie.IS_CRYPTO_AVAILABLE){let i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;let r=this._mt,s=(i,l)=>Math.imul(i,l)>>>0,n=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))n.push(i&4294967295);n.length||n.push(0),r[0]=19650218;for(let i=1;i<624;++i)r[i]=s(1812433253,r[i-1]^r[i-1]>>>30)+i>>>0;let o=1,a=0;for(let i=Math.max(624,n.length);i>0;--i,++o,++a)o>=624&&(r[0]=r[623],o=1),a>=n.length&&(a=0),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1664525))+n[a]+a>>>0;for(let i=623;i>0;--i,++o)o>=624&&(r[0]=r[623],o=1),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1566083941))-o>>>0;r[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let s=0;s<624;++s){let n=e[s]&2147483648|e[(s+1)%624]&2147483647;e[s]=(e[(s+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let r=e[this._idx++];return r^=r>>>11,r^=r<<7&2636928640,r^=r<<15&4022730752,r^=r>>>18,r>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,r=1){let s=this._gauss_next;if(this._gauss_next=null,s===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+s*r}shuffle(e){for(let r=e.length-1;r>0;--r){let s=32-Math.clz32(r+1),n=this._int32()>>>32-s;for(;n>r;)n=this._int32()>>>32-s;let o=e[r];e[r]=e[n],e[n]=o}}choices(e,r){return e[tA(this._random_fn,r)]}};function tA(t,e){let r=0;for(let n=0;ntA(ys.random,t);var uz=new Lr,un=class{constructor(e){this.path=e}async match(e){let r=Ut.join(this.path,e),s=new Pr(r);if(s.exists)return s}async put(e,r,s=void 0){let n=Ut.join(this.path,e),o=ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=uz._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),u=0;await gt.promises.mkdir(Ut.dirname(n),{recursive:!0});let f=gt.createWriteStream(i),m=r.body.getReader();for(;;){let{done:_,value:w}=await m.read();if(_)break;await new Promise((b,A)=>{f.write(w,k=>{if(k){A(k);return}b()})}),u+=w.length;let x=c?u/c*100:0;s?.({progress:x,loaded:u,total:c})}await new Promise((_,w)=>{f.close(x=>x?w(x):_())}),await gt.promises.rename(i,n)}catch(l){try{await gt.promises.unlink(i)}catch{}throw l}}async delete(e){let r=Ut.join(this.path,e);try{return await gt.promises.unlink(r),!0}catch{return!1}}};var sA={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"},dc=100,nA=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function go(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function zr(t,e=null,r=null){let s;try{s=new URL(t)}catch{return!1}return!(e&&!e.includes(s.protocol)||r&&!r.includes(s.hostname))}function oA(t){return!(!nA.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function aA(t,e,r){if(!r)return null;let s=sA[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function iA(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&ee.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:u}=await i.read();if(c)return;let f=a+u.length;if(f>n){n=f;let _=new Uint8Array(n);_.set(o),o=_}o.set(u,a),a=f;let m=a/n*100;return e({progress:m,loaded:a,total:n}),l()}return await l(),o}function Bf(t){return zr(t,["blob:"])}function Uf(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof import.meta<"u"&&import.meta.url)e=import.meta.url;else return t;return new URL(t,e).href}var cA="SHA-256",pz="experimental_transformers-hash-cache",lA=t=>({algorithm:cA,value:t}),wo=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(pz),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let r=await this._getFileHash(e);if(r)try{let[s]=await navigator.crossOriginStorage.requestFileHandles([lA(r)]),n=await s.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,r)=>{let s=await this._getFileHash(e);if(s){let n=await r.blob();await this._storeBlobInCOS(n,s)}else this._processAndStore(e,r.body)};_storeBlobInCOS=async(e,r)=>{let[s]=await navigator.crossOriginStorage.requestFileHandles([lA(r)],{create:!0}),n=await s.createWritable();await n.write(e),await n.close()};_processAndStore=async(e,r)=>{try{let s=[];for await(let a of r)s.push(a);let n=new Blob(s),o=await this._getBlobHash(n);await this._storeBlobInCOS(n,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let r=await this._getHashCache(),s=await r.match(e);if(s)return s.text();let n=await this._getLfsFileHash(e);return n?(await r.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let r=e.replace("/resolve/","/raw/");try{let n=(await fetch(r).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{let r=await e.arrayBuffer(),s=await crypto.subtle.digest(cA,r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function Zt(t=null){let e=null;if(_e.useCustomCache){if(!_e.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!_e.customCache.match||!_e.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=_e.customCache}if(!e&&_e.experimental_useCrossOriginStorage&&wo.isAvailable()&&(e=new wo),!e&&_e.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(_e.cacheKey)}catch(r){ee.warn("An error occurred while opening the browser cache:",r)}}if(!e&&_e.useFSCache){if(!ie.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new un(t??_e.cacheDir)}return e}async function uA(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var mc=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let r=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,r),r}put(e,r){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,r),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};var fz=100,Ff=new mc(fz);function _c(t,e){let r=Ff.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(Ff.delete(t),Promise.reject(n)));return Ff.put(t,s),s}async function dz(t){if(!zr(t,["http:","https:"]))return null;let e=Gf(t);return e.set("Range","bytes=0-0"),_e.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function Ct(t,e,r={}){let s=JSON.stringify([t,e,r?.revision,r?.cache_dir,r?.local_files_only]);return _c(s,()=>mz(t,e,r))}async function mz(t,e,r){let s=await Zt(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=Rr(t,e,r,s),l=await $r(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),u=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:u||void 0,fromCache:!0}}if(_e.allowLocalModels&&!zr(n,["http:","https:"]))try{let u=await Nr(n);if(typeof u!="string"&&u.status!==404){let f=u.headers.get("content-length"),m=u.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:m||void 0,fromCache:!1}}}catch{}if(_e.allowRemoteModels&&!r.local_files_only&&i)try{let c=await dz(o);if(c&&c.status>=200&&c.status<300){let u,f=c.headers.get("content-type");if(c.status===206){let m=c.headers.get("content-range");if(m){let _=m.match(/bytes \d+-\d+\/(\d+)/);_&&(u=parseInt(_[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(u===void 0){let m=c.headers.get("content-length");u=m?parseInt(m,10):void 0}return{exists:!0,size:u,contentType:f||void 0,fromCache:!1}}}catch(c){ee.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function Nr(t){return _e.useFS&&!zr(t,["http:","https:","blob:"])?new Pr(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):_e.fetch(t,{headers:Gf(t)})}function Gf(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=_e.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),zr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function Rr(t,e,r={},s=null){let n=r.revision??"main",o=go(t,e),a=oA(t),i=a?go(_e.localModelPath,o):o,l=go(_e.remoteHost,_e.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof un?n==="main"?o:go(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function $r(t,e,r){if(t)return await uA(t,e,r)}async function _z(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o){if(typeof n!="string"){let i=new Headers(n.headers);i.set("content-length",o.byteLength.toString()),await r.put(s,new Response(o,{headers:i})).catch(l=>{ee.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=a.progress_callback?l=>lr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function hz(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:u}=Rr(t,e,s,o),f,m=!1,_;_=await $r(o,i,c);let w=_!==void 0;if(w)f=c;else{if(_e.allowLocalModels)if(zr(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!_e.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{_=await Nr(i),f=i}catch(k){ee.warn(`Unable to load from local path "${i}": "${k}"`)}if(_===void 0||typeof _!="string"&&_.status===404){if(s.local_files_only||!_e.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!u)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(_=await Nr(l),_.status!==200)return aA(_.status,l,r);f=c}m=o&&typeof Response<"u"&&_ instanceof Response&&_.status===200}lr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(ie.IS_NODE_ENV&&n)){let A;if(typeof _!="string")if(!s.progress_callback)A=new Uint8Array(await _.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))A=new Uint8Array(await _.arrayBuffer()),lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A.length,total:A.length});else{let k,S=_.headers.get("content-length");if(S)k=parseInt(S,10);else try{let M=await Ct(t,e,s);M.size&&(k=M.size)}catch{}A=await iA(_,M=>{lr(s.progress_callback,{status:"progress",name:t,file:e,...M})},k)}x=A}if(m&&f&&typeof _!="string"&&await _z(t,e,o,f,_,x,s),ie.IS_NODE_ENV&&n&&s.progress_callback&&typeof _!="string"){let A=parseInt(_.headers.get("content-length"),10)||0;lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A,total:A})}if(lr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!ie.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(_ instanceof Pr)return _.filePath;let b=await o?.match(f);if(b instanceof Pr)return b.filePath;if(b instanceof Response)return new Uint8Array(await b.arrayBuffer());if(typeof b=="string")return b;throw new Error("Unable to get model file path or buffer.")}var hc=new Map;async function xo(t,e,r=!0,s={},n=!1){if(!_e.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!_e.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}lr(s.progress_callback,{status:"initiate",name:t,file:e});let o=`${t}::${e}`,a=hc.get(o);if(!a){let i=await Zt(s?.cache_dir);a=hz(t,e,r,s,n,i).then(l=>(hc.delete(o),l),l=>{throw hc.delete(o),l}),hc.set(o,a)}return await a}async function yo(t,e,r=!0,s={}){let n=await xo(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function nt(t,e,r=!0,s={}){let n=await yo(t,e,r,s);return n===null?{}:JSON.parse(n)}function fA(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,u=new t.constructor(n*o*e),f=r*s,m=n*o;for(let _=0;_=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i=0;--c)l+=u%e[c]*o[c],u=Math.floor(u/e[c]);a[l]=t[i]}return[a,s]}function Re(t){let e=Pe(t)[0],r=t.map(o=>Math.exp(o-e)),s=r.reduce((o,a)=>o+a,0);return r.map(o=>o/s)}function qf(t){let e=Pe(t)[0],r=0;for(let o=0;oo-e-s)}function mA(t,e){let r=0;for(let s=0;se+r*r,0))}function bo(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;se&&(e=t[s],r=s);return[e,r]}function _A(t){return t>0&&(t&t-1)===0}var gc=class{constructor(e){if(this.size=e|0,this.size<=1||!_A(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;ss;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>2;for(l=0;l>>1,a>>>1)}else for(l=0,c=0;l>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>1,w=_>>>1,x=w>>>1;for(l=0;l>>1;for(let _=2;_>1;++u){let f=(u+1-e)**2/2,m=Math.sqrt(l**2+c**2)**f,_=f*Math.atan2(c,l),w=2*u;o[w]=m*Math.cos(_),o[w+1]=m*Math.sin(_),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new gc(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,u=this._a;if(s)for(let f=0;f>1,w=r[_];n[f]=w*c[f],n[m]=w*c[m]}else for(let f=0;f=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function bs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function gA(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function wA(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let u=1;u0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var xA=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l>10,m=l&1023;if(f===31)c=u|2139095040|m<<13;else if(f===0)if(m===0)c=u;else{let _=113;for(;(m&1024)===0;)m<<=1,--_;m&=-1025,c=u|_<<23|m<<13}else c=u|f+112<<23|m<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;owz});var wz={};var Nd={};hs(Nd,{InferenceSession:()=>yd,TRACE:()=>Mc,TRACE_EVENT_BEGIN:()=>Gr,TRACE_EVENT_END:()=>jr,TRACE_FUNC_BEGIN:()=>Ms,TRACE_FUNC_END:()=>Ss,Tensor:()=>er,default:()=>Hz,env:()=>Ke,registerBackend:()=>Ts});var wd=Object.defineProperty,xz=Object.getOwnPropertyDescriptor,yz=Object.getOwnPropertyNames,bz=Object.prototype.hasOwnProperty,vz=(t=>typeof _s<"u"?_s:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof _s<"u"?_s:e)[r]}):t)(function(t){if(typeof _s<"u")return _s.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),be=(t,e)=>()=>(t&&(e=t(t=0)),e),Oo=(t,e)=>{for(var r in e)wd(t,r,{get:e[r],enumerable:!0})},kz=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of yz(e))!bz.call(t,n)&&n!==r&&wd(t,n,{get:()=>e[n],enumerable:!(s=xz(e,n))||s.enumerable});return t},Tc=t=>kz(wd({},"__esModule",{value:!0}),t),vo,Dr,Ts,yA,HA,XA=be(()=>{"use strict";vo=new Map,Dr=[],Ts=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=vo.get(t);if(s===void 0)vo.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=Dr.indexOf(t);n!==-1&&Dr.splice(n,1);for(let o=0;o{let e=vo.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(s){return r||(e.error=`${s}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},HA=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Dr:r,n,o=[],a=new Set;for(let l of s){let c=await yA(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),Ez=be(()=>{"use strict";XA()}),YA,Az=be(()=>{"use strict";YA="1.24.0-dev.20251116-b39e144322"}),Vf,dt,KA=be(()=>{"use strict";Az(),Vf="warning",dt={wasm:{},webgl:{},webgpu:{},versions:{common:YA},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);Vf=t}},get logLevel(){return Vf}},Object.defineProperty(dt,"logLevel",{enumerable:!0})}),Ke,Tz=be(()=>{"use strict";KA(),Ke=dt}),QA,JA,Mz=be(()=>{"use strict";QA=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=o*n,f=0,m=u,_=u*2,w=-1;a==="RGBA"?(f=0,m=u,_=u*2,w=u*3):a==="RGB"?(f=0,m=u,_=u*2):a==="RBG"&&(f=0,_=u,m=u*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,u;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,b=3,A=0,k=f,S=f*2,M=-1;i==="RGBA"?(A=0,k=f,S=f*2,M=f*3):i==="RGB"?(A=0,k=f,S=f*2):i==="RBG"&&(A=0,S=f,k=f*2),s=r.createImageData(n,o);for(let O=0;O{"use strict";xd(),xc=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,b=0,A=c,k=c*2,S=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(b=0,k=c,A=c*2):l==="BGR"&&(k=0,A=c,b=c*2);for(let M=0;M{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,_=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=_}else i.tensorFormat="RGBA",i.height=m,i.width=_;f.drawImage(t,0,0),a=f.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let u,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,f=e.resizedWidth):(u=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=u,i.width=f,e!==void 0){let m=l();m.width=f,m.height=u;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,u).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,xc(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((u,f)=>{let m=l(),_=c(m);if(!t||!_)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,_.drawImage(w,0,0,m.width,m.height);let x=_.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,u(xc(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return xc(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},e2=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Rt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},t2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Rt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},r2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Rt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},s2=(t,e,r)=>new Rt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),Es,Mo,Hf,n2,Oz=be(()=>{"use strict";Es=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Mo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Hf=!1,n2=()=>{if(!Hf){Hf=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Es.set("int64",BigInt64Array),Mo.set(BigInt64Array,"int64")),e&&(Es.set("uint64",BigUint64Array),Mo.set(BigUint64Array,"uint64")),s?(Es.set("float16",r),Mo.set(r,"float16")):Es.set("float16",Uint16Array)}}}),o2,a2,Iz=be(()=>{"use strict";xd(),o2=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new Rt(t.type,t.data,e);case"cpu-pinned":return new Rt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Rt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Rt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Rt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Rt,xd=be(()=>{"use strict";Mz(),Sz(),Oz(),Iz(),Rt=class{constructor(t,e,r){n2();let s,n;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,n=t.dims,t.location){case"cpu-pinned":{let a=Es.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,i;if(typeof t=="string")if(s=t,i=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=Es.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")s="string",a=t;else if(l==="boolean")s="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(t);else{let l=Mo.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=l,a=t}if(i===void 0)i=[a.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=a,this.dataLocation="cpu"}let o=o2(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(t,e){return ZA(t,e)}static fromTexture(t,e){return e2(t,e)}static fromGpuBuffer(t,e){return t2(t,e)}static fromMLTensor(t,e){return r2(t,e)}static fromPinnedBuffer(t,e,r){return s2(t,e,r)}toDataURL(t){return QA(this,t)}toImageData(t){return JA(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return a2(this,t)}}}),er,i2=be(()=>{"use strict";xd(),er=Rt}),Mc,Xf,Ms,Ss,Gr,jr,l2=be(()=>{"use strict";KA(),Mc=(t,e)=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeStamp(`${t}::ORT::${e}`)},Xf=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||Xf("BEGIN",t)},Ss=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||Xf("END",t)},Gr=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.time(`ORT::${t}`)},jr=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeEnd(`ORT::${t}`)}}),c2,Cz=be(()=>{"use strict";XA(),i2(),l2(),c2=class u2{constructor(e){this.handler=e}async run(e,r,s){Ms(),Gr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof er||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof er)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,u=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(u.indexOf(f)!==-1){let m=r[f];(m===null||m instanceof er)&&(c=!0,a=!1,n[f]=m)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let u=i[c];u instanceof er?l[c]=u:l[c]=new er(u.type,u.data,u.dims)}return jr("InferenceSession.run"),Ss(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){Ms(),Gr("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let u=e,f=0,m=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=u.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${u.byteLength}).`);if(m=e.byteLength-f,typeof s=="number"){if(m=s,!Number.isSafeInteger(m))throw new RangeError("'byteLength' must be an integer.");if(m<=0||f+m>u.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${u.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(u,f,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await HA(a),c=await i.createInferenceSessionHandler(o,l);return jr("InferenceSession.create"),Ss(),new u2(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),yd,Pz=be(()=>{"use strict";Cz(),yd=c2}),Lz=be(()=>{"use strict"}),zz=be(()=>{"use strict"}),Nz=be(()=>{"use strict"}),Rz=be(()=>{"use strict"}),p2={};Oo(p2,{InferenceSession:()=>yd,TRACE:()=>Mc,TRACE_EVENT_BEGIN:()=>Gr,TRACE_EVENT_END:()=>jr,TRACE_FUNC_BEGIN:()=>Ms,TRACE_FUNC_END:()=>Ss,Tensor:()=>er,env:()=>Ke,registerBackend:()=>Ts});var Os=be(()=>{"use strict";Ez(),Tz(),Pz(),i2(),Lz(),zz(),l2(),Nz(),Rz()}),bd=be(()=>{"use strict"}),f2={};Oo(f2,{default:()=>d2});var Yf,Kf,d2,$z=be(()=>{"use strict";S2(),Is(),vd(),Yf="ort-wasm-proxy-worker",Kf=globalThis.self?.name===Yf,Kf&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":kd(r.wasm).then(()=>{Sd(r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})})},s=>{postMessage({type:e,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;Od(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=Ic(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;Id(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":Cd(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;Pd(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},zd([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":Ld(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),d2=Kf?null:t=>new Worker(t??zt,{type:"module",name:Yf})}),m2={};Oo(m2,{default:()=>_2});async function bA(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(p,d)=>{p.startsWith("./")&&(p=p.substring(2)),(e.Uc||(e.Uc=new Map)).set(p,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let o=()=>{let p=d=>(...h)=>{let g=ar;return h=d(...h),ar!=g?new Promise((E,T)=>{pf={resolve:E,reject:T}}):h};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=p(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(p,d)=>{throw d},c=import.meta.url,u="";if(r||s){try{u=new URL(".",c).href}catch{}s&&(i=p=>{var d=new XMLHttpRequest;return d.open("GET",p,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async p=>{if(I(p))return new Promise((h,g)=>{var E=new XMLHttpRequest;E.open("GET",p,!0),E.responseType="arraybuffer",E.onload=()=>{E.status==200||E.status==0&&E.response?h(E.response):g(E.status)},E.onerror=g,E.send(null)});var d=await fetch(p,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,m,_,w,x,b,A=console.log.bind(console),k=console.error.bind(console),S=A,M=k,O=!1,I=p=>p.startsWith("file://");function v(){Ir.buffer!=F.buffer&&le()}if(n){let p=function(d){try{var h=d.data,g=h.Oc;if(g==="load"){let E=[];self.onmessage=T=>E.push(T),b=()=>{postMessage({Oc:"loaded"});for(let T of E)p(T);self.onmessage=p};for(let T of h.ce)e[T]&&!e[T].proxy||(e[T]=(...P)=>{postMessage({Oc:"callHandler",be:T,args:P})},T=="print"&&(S=e[T]),T=="printErr"&&(M=e[T]));Ir=h.ie,le(),m=h.je,qe(),nc()}else if(g==="run"){(function(E){var T=(v(),C)[E+52>>>2>>>0];E=(v(),C)[E+56>>>2>>>0],Sk(T,T-E),pe(T)})(h.Nc),kf(h.Nc,0,0,1,0,0),_v(),lf(h.Nc),G||(uk(),G=!0);try{WM(h.ge,h.Wc)}catch(E){if(E!="unwind")throw E}}else h.target!=="setimmediate"&&(g==="checkMailbox"?G&&Kl():g&&(M(`worker: received unknown command ${g}`),M(h)))}catch(E){throw kk(),E}};var B=p,G=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=p}var F,X,Y,J,$,C,se,K,L,R,U,Q=!1;function le(){var p=Ir.buffer;e.HEAP8=F=new Int8Array(p),Y=new Int16Array(p),e.HEAPU8=X=new Uint8Array(p),J=new Uint16Array(p),e.HEAP32=$=new Int32Array(p),e.HEAPU32=C=new Uint32Array(p),se=new Float32Array(p),K=new Float64Array(p),L=new BigInt64Array(p),R=new BigUint64Array(p)}function je(){Q=!0,n?b():br._b()}function ce(p){throw M(p="Aborted("+p+")"),O=!0,p=new WebAssembly.RuntimeError(p+". Build with -sASSERTIONS for more info."),x?.(p),p}function Tt(){return{a:{f:VM,J:HM,k:XM,p:YM,l:KM,sa:QM,b:JM,ca:ZM,Ja:bv,q:eS,da:Av,Za:Tv,Fa:Mv,Ha:Sv,_a:Ov,Xa:Iv,Qa:Cv,Wa:Pv,oa:Lv,Ga:zv,Xb:Nv,Ya:Rv,Yb:$v,db:tS,Da:sS,Sb:nS,Qb:aS,Ca:lS,M:cS,I:uS,Rb:pS,ja:wS,Tb:xS,Ta:yS,Vb:vS,Ka:kS,Ob:ES,ka:AS,Sa:lf,ab:TS,U:IS,n:NS,c:of,rb:RS,w:$S,L:DS,z:BS,j:US,o:Wv,sb:FS,G:GS,T:jS,h:qS,u:WS,m:VS,i:HS,Na:XS,Oa:YS,Pa:KS,La:Yv,Ma:Kv,Pb:Qv,eb:JS,cb:tO,Y:rO,qb:sO,la:nO,bb:ZS,fb:oO,$a:aO,Wb:iO,N:QS,gb:lO,X:cO,Ub:uO,nb:xO,C:yO,ra:bO,qa:vO,pb:kO,W:EO,v:AO,mb:TO,lb:MO,kb:SO,ob:OO,jb:IO,ib:CO,hb:PO,Ua:sk,Va:nk,Ia:Zs,V:ok,na:ak,Ra:ik,ma:lk,Cb:GI,xa:RI,Db:FI,ya:NI,F:EI,e:pI,s:cI,x:lI,B:bI,Fb:PI,ba:CI,D:mI,za:LI,$:$I,ga:II,Gb:OI,Hb:SI,Ba:AI,Aa:MI,Ib:TI,wa:UI,aa:zI,d:uI,A:dI,r:fI,Bb:jI,t:hI,y:vI,H:_I,E:gI,K:kI,R:DI,ia:yI,_:BI,Jb:xI,Kb:wI,g:zO,a:Ir,Nb:Js,Eb:NO,ha:RO,O:$O,pa:DO,Lb:BO,ta:UO,Q:FO,yb:GO,zb:jO,ua:qO,ea:WO,P:VO,Ea:HO,va:XO,Z:YO,wb:KO,Zb:QO,S:JO,Ab:ZO,tb:eI,ub:rI,vb:sI,fa:nI,xb:oI,Mb:aI}}}async function qe(){function p(g,E){var T=br=g.exports;g={};for(let[P,z]of Object.entries(T))typeof z=="function"?(T=MS(z),g[P]=T):g[P]=z;return br=g,br=(function(){var P=br,z=Z=>Ie=>Z(Ie)>>>0,j=Z=>()=>Z()>>>0;return(P=Object.assign({},P)).$b=z(P.$b),P.Cc=j(P.Cc),P.Ec=z(P.Ec),P.rd=(Z=>(Ie,Ne)=>Z(Ie,Ne)>>>0)(P.rd),P.wd=z(P.wd),P.xd=j(P.xd),P.Bd=z(P.Bd),P})(),dv.push(br.id),ck=(g=br).$b,uk=g.ac,e._OrtInit=g.bc,e._OrtGetLastError=g.cc,e._OrtCreateSessionOptions=g.dc,e._OrtAppendExecutionProvider=g.ec,e._OrtAddFreeDimensionOverride=g.fc,e._OrtAddSessionConfigEntry=g.gc,e._OrtReleaseSessionOptions=g.hc,e._OrtCreateSession=g.ic,e._OrtReleaseSession=g.jc,e._OrtGetInputOutputCount=g.kc,e._OrtGetInputOutputMetadata=g.lc,e._OrtFree=g.mc,e._OrtCreateTensor=g.nc,e._OrtGetTensorData=g.oc,e._OrtReleaseTensor=g.pc,e._OrtCreateRunOptions=g.qc,e._OrtAddRunConfigEntry=g.rc,e._OrtReleaseRunOptions=g.sc,e._OrtCreateBinding=g.tc,e._OrtBindInput=g.uc,e._OrtBindOutput=g.vc,e._OrtClearBoundOutputs=g.wc,e._OrtReleaseBinding=g.xc,e._OrtRunWithBinding=g.yc,e._OrtRun=g.zc,e._OrtEndProfiling=g.Ac,gf=e._OrtGetWebGpuDevice=g.Bc,rc=g.Cc,Xt=e._free=g.Dc,nn=e._malloc=g.Ec,pk=e._wgpuBufferRelease=g.Fc,fk=e._wgpuCreateInstance=g.Gc,dk=g.Hc,mk=g.Ic,_k=g.Jc,hk=g.Kc,gk=g.Lc,wk=g.Pc,xk=g.Zc,yk=g._c,bk=g.$c,wf=g.bd,xf=g.cd,yf=g.dd,bf=g.ed,co=g.fd,vf=g.gd,vk=g.hd,kf=g.kd,kk=g.ld,Ek=g.md,Ak=g.nd,Ef=g.od,Tk=g.pd,Mk=g.qd,Af=g.rd,xe=g.sd,uo=g.td,Sk=g.ud,pe=g.vd,sc=g.wd,fe=g.xd,Ok=g.yd,Tf=g.zd,Ik=g.Ad,Ck=g.Bd,Pk=g.Cd,Mf=g.Dd,Lk=g.Ed,zk=g.Fd,Nk=g.Gd,Rk=g.Hd,$k=g.Id,Dk=g.Jd,Bk=g.Kd,Uk=g.Ld,Fk=g.Md,Gk=g.Nd,jk=g.Od,qk=g.Pd,Wk=g.Qd,Vk=g.Rd,Hk=g.Td,Xk=g.Ud,Yk=g.Vd,Kk=g.Wd,Qk=g.Yd,Jk=g.Zd,Zk=g._d,eE=g.$d,tE=g.ae,rE=g.oe,sE=g.pe,nE=g.qe,oE=g.re,aE=g.se,iE=g.te,lE=g.ue,cE=g.ve,uE=g.we,pE=g.xe,fE=g.ye,dE=g.Ye,mE=g.Ze,_E=g._e,hE=g.$e,m=E,br}var d,h=Tt();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(E,T)=>{g(p(E,T))})}):n?p(new WebAssembly.Instance(m,Tt()),m):(U??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",u):u+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,d=await(async function(g){var E=U;if(!f&&!I(E))try{var T=fetch(E,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,g)}catch(P){M(`wasm streaming compile failed: ${P}`),M("falling back to ArrayBuffer instantiation")}return(async function(P,z){try{var j=await(async function(Z){if(!f)try{var Ie=await a(Z);return new Uint8Array(Ie)}catch{}if(Z==U&&f)Z=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";Z=i(Z)}return Z})(P);return await WebAssembly.instantiate(j,z)}catch(Z){M(`failed to asynchronously prepare wasm: ${Z}`),ce(Z)}})(E,g)})(h),p(d.instance,d.module))}class ct{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var Mt=p=>{p.terminate(),p.onmessage=()=>{}},Be=[],Se=0,rt=null,nr=p=>{Or.length==0&&(gv(),hv(Or[0]));var d=Or.pop();if(!d)return 6;ao.push(d),fs[p.Nc]=d,d.Nc=p.Nc;var h={Oc:"run",ge:p.fe,Wc:p.Wc,Nc:p.Nc};return d.postMessage(h,p.Yc),0},Oe=0,Ue=(p,d,...h)=>{var g,E=16*h.length,T=fe(),P=sc(E),z=P>>>3;for(g of h)typeof g=="bigint"?((v(),L)[z++>>>0]=1n,(v(),L)[z++>>>0]=g):((v(),L)[z++>>>0]=0n,(v(),K)[z++>>>0]=g);return p=Ek(p,0,E,P,d),pe(T),p};function Js(p){if(n)return Ue(0,1,p);if(_=p,!(0{if(_=p,n)throw oo(p),"unwind";Js(p)},Or=[],ao=[],dv=[],fs={},mv=p=>{var d=p.Nc;delete fs[d],Or.push(p),ao.splice(ao.indexOf(p),1),p.Nc=0,Ak(d)};function _v(){dv.forEach(p=>p())}var hv=p=>new Promise(d=>{p.onmessage=E=>{var T=E.data;if(E=T.Oc,T.Vc&&T.Vc!=rc()){var P=fs[T.Vc];P?P.postMessage(T,T.Yc):M(`Internal error! Worker sent a message "${E}" to target pthread ${T.Vc}, but that thread no longer exists!`)}else E==="checkMailbox"?Kl():E==="spawnThread"?nr(T):E==="cleanupThread"?St(()=>{mv(fs[T.he])}):E==="loaded"?(p.loaded=!0,d(p)):T.target==="setimmediate"?p.postMessage(T):E==="uncaughtException"?p.onerror(T.error):E==="callHandler"?e[T.be](...T.args):E&&M(`worker sent an unknown command ${E}`)},p.onerror=E=>{throw M(`worker sent an error! ${E.filename}:${E.lineno}: ${E.message}`),E};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);p.postMessage({Oc:"load",ce:g,ie:Ir,je:m})});function gv(){var p=new Worker((()=>{let d=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new d("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Or.push(p)}var Ir,WM=(p,d)=>{Oe=0,p=Mf(p,d),0-9007199254740992>p||9007199254740992>>=0);return(v(),F)[d.Qc+12>>>0]==0&&(wv(d,!0),Yl--),xv(d,!1),Xl.push(d),Ck(p)}var en=0,HM=()=>{xe(0,0);var p=Xl.pop();Ok(p.Xc),en=0};function wv(p,d){d=d?1:0,(v(),F)[p.Qc+12>>>0]=d}function xv(p,d){d=d?1:0,(v(),F)[p.Qc+13>>>0]=d}class tf{constructor(d){this.Xc=d,this.Qc=d-24}}var rf=p=>{var d=en;if(!d)return uo(0),0;var h=new tf(d);(v(),C)[h.Qc+16>>>2>>>0]=d;var g=(v(),C)[h.Qc+4>>>2>>>0];if(!g)return uo(0),d;for(var E of p){if(E===0||E===g)break;if(Ik(E,g,h.Qc+16))return uo(E),d}return uo(g),d};function XM(){return rf([])}function YM(p){return rf([p>>>0])}function KM(p,d,h,g){return rf([p>>>0,d>>>0,h>>>0,g>>>0])}var QM=()=>{var p=Xl.pop();p||ce("no exception to throw");var d=p.Xc;throw(v(),F)[p.Qc+13>>>0]==0&&(Xl.push(p),xv(p,!0),wv(p,!1),Yl++),Tf(d),en=d};function JM(p,d,h){var g=new tf(p>>>=0);throw d>>>=0,h>>>=0,(v(),C)[g.Qc+16>>>2>>>0]=0,(v(),C)[g.Qc+4>>>2>>>0]=d,(v(),C)[g.Qc+8>>>2>>>0]=h,Tf(p),Yl++,en=p}var ZM=()=>Yl;function yv(p,d,h,g){return n?Ue(2,1,p,d,h,g):bv(p,d,h,g)}function bv(p,d,h,g){if(p>>>=0,d>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var E=[];return n&&E.length===0?yv(p,d,h,g):(p={fe:h,Nc:p,Wc:g,Yc:E},n?(p.Oc="spawnThread",postMessage(p,E),0):nr(p))}function eS(p){throw en||=p>>>0,en}var vv=globalThis.TextDecoder&&new TextDecoder,kv=(p,d,h,g)=>{if(h=d+h,g)return h;for(;p[d]&&!(d>=h);)++d;return d},Ev=(p,d=0,h,g)=>{if(16<(h=kv(p,d>>>=0,h,g))-d&&p.buffer&&vv)return vv.decode(p.buffer instanceof ArrayBuffer?p.subarray(d,h):p.slice(d,h));for(g="";d(E=(240&E)==224?(15&E)<<12|T<<6|P:(7&E)<<18|T<<12|P<<6|63&p[d++])?g+=String.fromCharCode(E):(E-=65536,g+=String.fromCharCode(55296|E>>10,56320|1023&E))}}else g+=String.fromCharCode(E)}return g},tn=(p,d,h)=>(p>>>=0)?Ev((v(),X),p,d,h):"";function Av(p,d,h){return n?Ue(3,1,p,d,h):0}function Tv(p,d){if(n)return Ue(4,1,p,d)}function Mv(p,d){if(n)return Ue(5,1,p,d)}function Sv(p,d,h){if(n)return Ue(6,1,p,d,h)}function Ov(p,d,h){return n?Ue(7,1,p,d,h):0}function Iv(p,d){if(n)return Ue(8,1,p,d)}function Cv(p,d,h){if(n)return Ue(9,1,p,d,h)}function Pv(p,d,h,g){if(n)return Ue(10,1,p,d,h,g)}function Lv(p,d,h,g){if(n)return Ue(11,1,p,d,h,g)}function zv(p,d,h,g){if(n)return Ue(12,1,p,d,h,g)}function Nv(p){if(n)return Ue(13,1,p)}function Rv(p,d){if(n)return Ue(14,1,p,d)}function $v(p,d,h){if(n)return Ue(15,1,p,d,h)}var tS=()=>ce(""),or=p=>{p>>>=0;for(var d="";;){var h=(v(),X)[p++>>>0];if(!h)return d;d+=String.fromCharCode(h)}},sf={},nf={},rS={},rn=class extends Error{constructor(p){super(p),this.name="BindingError"}};function hr(p,d,h={}){return(function(g,E,T={}){var P=E.name;if(!g)throw new rn(`type "${P}" must have a positive integer typeid pointer`);if(nf.hasOwnProperty(g)){if(T.de)return;throw new rn(`Cannot register type '${P}' twice`)}nf[g]=E,delete rS[g],sf.hasOwnProperty(g)&&(E=sf[g],delete sf[g],E.forEach(z=>z()))})(p,d,h)}var Dv=(p,d,h)=>{switch(d){case 1:return h?g=>(v(),F)[g>>>0]:g=>(v(),X)[g>>>0];case 2:return h?g=>(v(),Y)[g>>>1>>>0]:g=>(v(),J)[g>>>1>>>0];case 4:return h?g=>(v(),$)[g>>>2>>>0]:g=>(v(),C)[g>>>2>>>0];case 8:return h?g=>(v(),L)[g>>>3>>>0]:g=>(v(),R)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${p}`)}};function sS(p,d,h,g,E){p>>>=0,h>>>=0,d=or(d>>>0);let T=P=>P;if(g=g===0n){let P=8*h;T=z=>BigInt.asUintN(P,z),E=T(E)}hr(p,{name:d,Mc:T,Sc:(P,z)=>(typeof z=="number"&&(z=BigInt(z)),z),Rc:Dv(d,h,!g),Tc:null})}function nS(p,d,h,g){hr(p>>>=0,{name:d=or(d>>>0),Mc:function(E){return!!E},Sc:function(E,T){return T?h:g},Rc:function(E){return this.Mc((v(),X)[E>>>0])},Tc:null})}var Bv=[],ds=[0,1,,1,null,1,!0,1,!1,1];function of(p){9<(p>>>=0)&&--ds[p+1]==0&&(ds[p]=void 0,Bv.push(p))}var Bt=p=>{if(!p)throw new rn(`Cannot use deleted val. handle = ${p}`);return ds[p]},Ht=p=>{switch(p){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=Bv.pop()||ds.length;return ds[d]=p,ds[d+1]=1,d}};function af(p){return this.Mc((v(),C)[p>>>2>>>0])}var oS={name:"emscripten::val",Mc:p=>{var d=Bt(p);return of(p),d},Sc:(p,d)=>Ht(d),Rc:af,Tc:null};function aS(p){return hr(p>>>0,oS)}var iS=(p,d)=>{switch(d){case 4:return function(h){return this.Mc((v(),se)[h>>>2>>>0])};case 8:return function(h){return this.Mc((v(),K)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${p}`)}};function lS(p,d,h){h>>>=0,hr(p>>>=0,{name:d=or(d>>>0),Mc:g=>g,Sc:(g,E)=>E,Rc:iS(d,h),Tc:null})}function cS(p,d,h,g,E){p>>>=0,h>>>=0,d=or(d>>>0);let T=z=>z;if(g===0){var P=32-8*h;T=z=>z<

>>P,E=T(E)}hr(p,{name:d,Mc:T,Sc:(z,j)=>j,Rc:Dv(d,h,g!==0),Tc:null})}function uS(p,d,h){function g(T){var P=(v(),C)[T>>>2>>>0];return T=(v(),C)[T+4>>>2>>>0],new E((v(),F).buffer,T,P)}var E=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];hr(p>>>=0,{name:h=or(h>>>0),Mc:g,Rc:g},{de:!0})}var gr=(p,d,h)=>{var g=(v(),X);if(d>>>=0,0=P){if(d>=h)break;g[d++>>>0]=P}else if(2047>=P){if(d+1>=h)break;g[d++>>>0]=192|P>>6,g[d++>>>0]=128|63&P}else if(65535>=P){if(d+2>=h)break;g[d++>>>0]=224|P>>12,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P}else{if(d+3>=h)break;g[d++>>>0]=240|P>>18,g[d++>>>0]=128|P>>12&63,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P,T++}}g[d>>>0]=0,p=d-E}else p=0;return p},wr=p=>{for(var d=0,h=0;h=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++h):d+=3}return d};function pS(p,d){hr(p>>>=0,{name:d=or(d>>>0),Mc(h){var g=(v(),C)[h>>>2>>>0];return g=tn(h+4,g,!0),Xt(h),g},Sc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var E=typeof g=="string";if(!(E||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new rn("Cannot pass non-string to std::string");var T=E?wr(g):g.length,P=nn(4+T+1),z=P+4;return(v(),C)[P>>>2>>>0]=T,E?gr(g,z,T+1):(v(),X).set(g,z>>>0),h!==null&&h.push(Xt,P),P},Rc:af,Tc(h){Xt(h)}})}var Uv=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,fS=(p,d,h)=>{if(p>>>=1,16<(d=kv((v(),J),p,d/2,h))-p&&Uv)return Uv.decode((v(),J).slice(p,d));for(h="";p>>0];h+=String.fromCharCode(g)}return h},dS=(p,d,h)=>{if(h??=2147483647,2>h)return 0;var g=d;h=(h-=2)<2*p.length?h/2:p.length;for(var E=0;E>>1>>>0]=T,d+=2}return(v(),Y)[d>>>1>>>0]=0,d-g},mS=p=>2*p.length,_S=(p,d,h)=>{var g="";p>>>=2;for(var E=0;!(E>=d/4);E++){var T=(v(),C)[p+E>>>0];if(!T&&!h)break;g+=String.fromCodePoint(T)}return g},hS=(p,d,h)=>{if(d>>>=0,h??=2147483647,4>h)return 0;var g=d;h=g+h-4;for(var E=0;E>>2>>>0]=T,(d+=4)+4>h)break}return(v(),$)[d>>>2>>>0]=0,d-g},gS=p=>{for(var d=0,h=0;h>>=0,d>>>=0,h=or(h>>>=0),d===2)var g=fS,E=dS,T=mS;else g=_S,E=hS,T=gS;hr(p,{name:h,Mc:P=>{var z=(v(),C)[P>>>2>>>0];return z=g(P+4,z*d,!0),Xt(P),z},Sc:(P,z)=>{if(typeof z!="string")throw new rn(`Cannot pass non-string to C++ string type ${h}`);var j=T(z),Z=nn(4+j+d);return(v(),C)[Z>>>2>>>0]=j/d,E(z,Z+4,j+d),P!==null&&P.push(Xt,Z),Z},Rc:af,Tc(P){Xt(P)}})}function xS(p,d){hr(p>>>=0,{ee:!0,name:d=or(d>>>0),Mc:()=>{},Sc:()=>{}})}function yS(p){kf(p>>>0,!s,1,!r,131072,!1),_v()}var St=p=>{if(!O)try{if(p(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function lf(p){p>>>=0,bS||(Atomics.waitAsync((v(),$),p>>>2,p).value.then(Kl),p+=128,Atomics.store((v(),$),p>>>2,1))}var Kl=()=>St(()=>{var p=rc();p&&(lf(p),Mk())});function vS(p,d){(p>>>=0)==d>>>0?setTimeout(Kl):n?postMessage({Vc:p,Oc:"checkMailbox"}):(p=fs[p])&&p.postMessage({Oc:"checkMailbox"})}var cf=[];function kS(p,d,h,g,E){for(d>>>=0,E>>>=0,cf.length=0,h=E>>>3,g=E+g>>>3;h>>0]?(v(),L)[h++>>>0]:(v(),K)[h++>>>0],cf.push(T)}return(d?Sf[d]:iI[p])(...cf)}var ES=()=>{Oe=0};function AS(p){p>>>=0,n?postMessage({Oc:"cleanupThread",he:p}):mv(fs[p])}function TS(p){}var Ql=p=>{try{p()}catch(d){ce(d)}};function MS(p){var d=(...h)=>{Jl.push(p);try{return p(...h)}finally{O||(Jl.pop(),ar&&Cr===1&&Jl.length===0&&(Cr=0,Oe+=1,Ql(mE),typeof Fibers<"u"&&Fibers.Be()))}};return jv.set(p,d),d}var Cr=0,ar=null,Fv=0,Jl=[],uf=new Map,Gv=new Map,jv=new Map,SS=0,pf=null,OS=[],qv=p=>(function(d){if(!O){if(Cr===0){var h=!1,g=!1;d((E=0)=>{if(!O&&(Fv=E,h=!0,g)){Cr=2,Ql(()=>_E(ar)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),E=!1;try{var T=(function(){var j=(v(),$)[ar+8>>>2>>>0];return j=Gv.get(j),j=jv.get(j),--Oe,j()})()}catch(j){T=j,E=!0}var P=!1;if(!ar){var z=pf;z&&(pf=null,(E?z.reject:z.resolve)(T),P=!0)}if(E&&!P)throw T}}),g=!0,h||(Cr=1,ar=(function(){var E=nn(65548),T=E+12;if((v(),C)[E>>>2>>>0]=T,(v(),C)[E+4>>>2>>>0]=T+65536,T=Jl[0],!uf.has(T)){var P=SS++;uf.set(T,P),Gv.set(P,T)}return T=uf.get(T),(v(),$)[E+8>>>2>>>0]=T,E})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Ql(()=>dE(ar)))}else Cr===2?(Cr=0,Ql(hE),Xt(ar),ar=null,OS.forEach(St)):ce(`invalid state: ${Cr}`);return Fv}})(d=>{p().then(d)});function IS(p){return p>>>=0,qv(async()=>{var d=await Bt(p);return Ht(d)})}var ff=[],CS=p=>{var d=ff.length;return ff.push(p),d},PS=(p,d)=>{for(var h=Array(p),g=0;g>>2>>>0],P=nf[T];if(P===void 0)throw p=`parameter ${g}`,T=ck(T),d=or(T),Xt(T),new rn(`${p} has unknown type ${d}`);h[E]=P}return h},LS=(p,d,h)=>{var g=[];return p=p(g,h),g.length&&((v(),C)[d>>>2>>>0]=Ht(g)),p},zS={},Zl=p=>{var d=zS[p];return d===void 0?or(p):d};function NS(p,d,h){var[g,...E]=PS(p,d>>>0);d=g.Sc.bind(g);var T=E.map(j=>j.Rc.bind(j));p--;var P={toValue:Bt};switch(p=T.map((j,Z)=>{var Ie=`argFromPtr${Z}`;return P[Ie]=j,`${Ie}(args${Z?"+"+8*Z:""})`}),h){case 0:var z="toValue(handle)";break;case 2:z="new (toValue(handle))";break;case 3:z="";break;case 1:P.getStringOrSymbol=Zl,z="toValue(handle)[getStringOrSymbol(methodName)]"}return z+=`(${p})`,g.ee||(P.toReturnWire=d,P.emval_returnValue=LS,z=`return emval_returnValue(toReturnWire, destructorsRef, ${z})`),z=`return function (handle, methodName, destructorsRef, args) { ++`,JL="{%- ",ZL=" -%}";function ez(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function tz(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Qt(t.body,0,r).replace(/\n$/,"")}function xt(...t){return JL+t.join(" ")+ZL}function Qt(t,e,r){return t.map(s=>rz(s,e,r)).join(at)}function rz(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Qt(t.body,e,r);case"If":return sz(t,e,r);case"For":return nz(t,e,r);case"Set":return oz(t,e,r);case"Macro":return az(t,e,r);case"Break":return s+xt("break");case"Continue":return s+xt("continue");case"CallStatement":return iz(t,e,r);case"FilterStatement":return lz(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function sz(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+xt("if",ke(n[0].test))+at+Qt(n[0].body,e+1,r);for(let i=1;i0&&(a+=at+s+xt("else")+at+Qt(o.alternate,e+1,r)),a+=at+s+xt("endif"),a}function nz(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+xt("for",ke(t.loopvar),"in",n)+at+Qt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=at+s+xt("else")+at+Qt(t.defaultBlock,e+1,r)),o+=at+s+xt("endfor"),o}function oz(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+xt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+at+Qt(t.body,e+1,r)+at+s+xt("endset")}function az(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+xt("macro",`${t.name.value}(${n})`)+at+Qt(t.body,e+1,r)+at+s+xt("endmacro")}function iz(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+xt(`call${n}`,o)+at;return a+=Qt(t.body,e+1,r)+at,a+=s+xt("endcall"),a}function lz(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+xt("filter",n)+at;return o+=Qt(t.body,e+1,r)+at,o+=s+xt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=ez(r),n=ke(r.left,s),o=ke(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var eA=class{parsed;constructor(t){let e=wL(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=GL(e)}render(t){let e=new ws;if(KL(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new QL(e).run(this.parsed).value}format(t){return tz(this.parsed,t?.indent||" ")}};var cz={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"},Pr=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=gt.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=gt.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=gt.createReadStream(e);this.body=new ReadableStream({start(n){s.on("data",o=>n.enqueue(o)),s.on("end",()=>n.close()),s.on("error",o=>n.error(o))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",cz[e]??"application/octet-stream")}clone(){let e=new t(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await gt.promises.readFile(this.filePath)).buffer}async blob(){let e=await gt.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await gt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};var Lr=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(ie.IS_CRYPTO_AVAILABLE){let i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;let r=this._mt,s=(i,l)=>Math.imul(i,l)>>>0,n=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))n.push(i&4294967295);n.length||n.push(0),r[0]=19650218;for(let i=1;i<624;++i)r[i]=s(1812433253,r[i-1]^r[i-1]>>>30)+i>>>0;let o=1,a=0;for(let i=Math.max(624,n.length);i>0;--i,++o,++a)o>=624&&(r[0]=r[623],o=1),a>=n.length&&(a=0),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1664525))+n[a]+a>>>0;for(let i=623;i>0;--i,++o)o>=624&&(r[0]=r[623],o=1),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1566083941))-o>>>0;r[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let s=0;s<624;++s){let n=e[s]&2147483648|e[(s+1)%624]&2147483647;e[s]=(e[(s+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let r=e[this._idx++];return r^=r>>>11,r^=r<<7&2636928640,r^=r<<15&4022730752,r^=r>>>18,r>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,r=1){let s=this._gauss_next;if(this._gauss_next=null,s===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+s*r}shuffle(e){for(let r=e.length-1;r>0;--r){let s=32-Math.clz32(r+1),n=this._int32()>>>32-s;for(;n>r;)n=this._int32()>>>32-s;let o=e[r];e[r]=e[n],e[n]=o}}choices(e,r){return e[tA(this._random_fn,r)]}};function tA(t,e){let r=0;for(let n=0;ntA(ys.random,t);var uz=new Lr,un=class{constructor(e){this.path=e}async match(e){let r=Ut.join(this.path,e),s=new Pr(r);if(s.exists)return s}async put(e,r,s=void 0){let n=Ut.join(this.path,e),o=ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=uz._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),u=0;await gt.promises.mkdir(Ut.dirname(n),{recursive:!0});let f=gt.createWriteStream(i),m=r.body.getReader();for(;;){let{done:_,value:w}=await m.read();if(_)break;await new Promise((b,A)=>{f.write(w,k=>{if(k){A(k);return}b()})}),u+=w.length;let x=c?u/c*100:0;s?.({progress:x,loaded:u,total:c})}await new Promise((_,w)=>{f.close(x=>x?w(x):_())}),await gt.promises.rename(i,n)}catch(l){try{await gt.promises.unlink(i)}catch{}throw l}}async delete(e){let r=Ut.join(this.path,e);try{return await gt.promises.unlink(r),!0}catch{return!1}}};var sA={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"},dc=100,nA=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function go(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function zr(t,e=null,r=null){let s;try{s=new URL(t)}catch{return!1}return!(e&&!e.includes(s.protocol)||r&&!r.includes(s.hostname))}function oA(t){return!(!nA.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function aA(t,e,r){if(!r)return null;let s=sA[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function iA(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&ee.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:u}=await i.read();if(c)return;let f=a+u.length;if(f>n){n=f;let _=new Uint8Array(n);_.set(o),o=_}o.set(u,a),a=f;let m=a/n*100;return e({progress:m,loaded:a,total:n}),l()}return await l(),o}function Bf(t){return zr(t,["blob:"])}function Uf(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof import_meta<"u"&&import_meta.url)e=import_meta.url;else return t;return new URL(t,e).href}var cA="SHA-256",pz="experimental_transformers-hash-cache",lA=t=>({algorithm:cA,value:t}),wo=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(pz),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let r=await this._getFileHash(e);if(r)try{let[s]=await navigator.crossOriginStorage.requestFileHandles([lA(r)]),n=await s.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,r)=>{let s=await this._getFileHash(e);if(s){let n=await r.blob();await this._storeBlobInCOS(n,s)}else this._processAndStore(e,r.body)};_storeBlobInCOS=async(e,r)=>{let[s]=await navigator.crossOriginStorage.requestFileHandles([lA(r)],{create:!0}),n=await s.createWritable();await n.write(e),await n.close()};_processAndStore=async(e,r)=>{try{let s=[];for await(let a of r)s.push(a);let n=new Blob(s),o=await this._getBlobHash(n);await this._storeBlobInCOS(n,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let r=await this._getHashCache(),s=await r.match(e);if(s)return s.text();let n=await this._getLfsFileHash(e);return n?(await r.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let r=e.replace("/resolve/","/raw/");try{let n=(await fetch(r).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{let r=await e.arrayBuffer(),s=await crypto.subtle.digest(cA,r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function Zt(t=null){let e=null;if(_e.useCustomCache){if(!_e.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!_e.customCache.match||!_e.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=_e.customCache}if(!e&&_e.experimental_useCrossOriginStorage&&wo.isAvailable()&&(e=new wo),!e&&_e.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(_e.cacheKey)}catch(r){ee.warn("An error occurred while opening the browser cache:",r)}}if(!e&&_e.useFSCache){if(!ie.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new un(t??_e.cacheDir)}return e}async function uA(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var mc=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let r=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,r),r}put(e,r){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,r),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};var fz=100,Ff=new mc(fz);function _c(t,e){let r=Ff.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(Ff.delete(t),Promise.reject(n)));return Ff.put(t,s),s}async function dz(t){if(!zr(t,["http:","https:"]))return null;let e=Gf(t);return e.set("Range","bytes=0-0"),_e.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function Ct(t,e,r={}){let s=JSON.stringify([t,e,r?.revision,r?.cache_dir,r?.local_files_only]);return _c(s,()=>mz(t,e,r))}async function mz(t,e,r){let s=await Zt(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=Rr(t,e,r,s),l=await $r(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),u=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:u||void 0,fromCache:!0}}if(_e.allowLocalModels&&!zr(n,["http:","https:"]))try{let u=await Nr(n);if(typeof u!="string"&&u.status!==404){let f=u.headers.get("content-length"),m=u.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:m||void 0,fromCache:!1}}}catch{}if(_e.allowRemoteModels&&!r.local_files_only&&i)try{let c=await dz(o);if(c&&c.status>=200&&c.status<300){let u,f=c.headers.get("content-type");if(c.status===206){let m=c.headers.get("content-range");if(m){let _=m.match(/bytes \d+-\d+\/(\d+)/);_&&(u=parseInt(_[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(u===void 0){let m=c.headers.get("content-length");u=m?parseInt(m,10):void 0}return{exists:!0,size:u,contentType:f||void 0,fromCache:!1}}}catch(c){ee.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function Nr(t){return _e.useFS&&!zr(t,["http:","https:","blob:"])?new Pr(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):_e.fetch(t,{headers:Gf(t)})}function Gf(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=_e.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),zr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function Rr(t,e,r={},s=null){let n=r.revision??"main",o=go(t,e),a=oA(t),i=a?go(_e.localModelPath,o):o,l=go(_e.remoteHost,_e.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof un?n==="main"?o:go(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function $r(t,e,r){if(t)return await uA(t,e,r)}async function _z(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o){if(typeof n!="string"){let i=new Headers(n.headers);i.set("content-length",o.byteLength.toString()),await r.put(s,new Response(o,{headers:i})).catch(l=>{ee.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=a.progress_callback?l=>lr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function hz(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:u}=Rr(t,e,s,o),f,m=!1,_;_=await $r(o,i,c);let w=_!==void 0;if(w)f=c;else{if(_e.allowLocalModels)if(zr(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!_e.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{_=await Nr(i),f=i}catch(k){ee.warn(`Unable to load from local path "${i}": "${k}"`)}if(_===void 0||typeof _!="string"&&_.status===404){if(s.local_files_only||!_e.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!u)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(_=await Nr(l),_.status!==200)return aA(_.status,l,r);f=c}m=o&&typeof Response<"u"&&_ instanceof Response&&_.status===200}lr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(ie.IS_NODE_ENV&&n)){let A;if(typeof _!="string")if(!s.progress_callback)A=new Uint8Array(await _.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test((navigator.userAgent||"")))A=new Uint8Array(await _.arrayBuffer()),lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A.length,total:A.length});else{let k,S=_.headers.get("content-length");if(S)k=parseInt(S,10);else try{let M=await Ct(t,e,s);M.size&&(k=M.size)}catch{}A=await iA(_,M=>{lr(s.progress_callback,{status:"progress",name:t,file:e,...M})},k)}x=A}if(m&&f&&typeof _!="string"&&await _z(t,e,o,f,_,x,s),ie.IS_NODE_ENV&&n&&s.progress_callback&&typeof _!="string"){let A=parseInt(_.headers.get("content-length"),10)||0;lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A,total:A})}if(lr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!ie.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(_ instanceof Pr)return _.filePath;let b=await o?.match(f);if(b instanceof Pr)return b.filePath;if(b instanceof Response)return new Uint8Array(await b.arrayBuffer());if(typeof b=="string")return b;throw new Error("Unable to get model file path or buffer.")}var hc=new Map;async function xo(t,e,r=!0,s={},n=!1){if(!_e.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!_e.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}lr(s.progress_callback,{status:"initiate",name:t,file:e});let o=`${t}::${e}`,a=hc.get(o);if(!a){let i=await Zt(s?.cache_dir);a=hz(t,e,r,s,n,i).then(l=>(hc.delete(o),l),l=>{throw hc.delete(o),l}),hc.set(o,a)}return await a}async function yo(t,e,r=!0,s={}){let n=await xo(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function nt(t,e,r=!0,s={}){let n=await yo(t,e,r,s);return n===null?{}:JSON.parse(n)}function fA(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,u=new t.constructor(n*o*e),f=r*s,m=n*o;for(let _=0;_=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i=0;--c)l+=u%e[c]*o[c],u=Math.floor(u/e[c]);a[l]=t[i]}return[a,s]}function Re(t){let e=Pe(t)[0],r=t.map(o=>Math.exp(o-e)),s=r.reduce((o,a)=>o+a,0);return r.map(o=>o/s)}function qf(t){let e=Pe(t)[0],r=0;for(let o=0;oo-e-s)}function mA(t,e){let r=0;for(let s=0;se+r*r,0))}function bo(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;se&&(e=t[s],r=s);return[e,r]}function _A(t){return t>0&&(t&t-1)===0}var gc=class{constructor(e){if(this.size=e|0,this.size<=1||!_A(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;ss;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>2;for(l=0;l>>1,a>>>1)}else for(l=0,c=0;l>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>1,w=_>>>1,x=w>>>1;for(l=0;l>>1;for(let _=2;_>1;++u){let f=(u+1-e)**2/2,m=Math.sqrt(l**2+c**2)**f,_=f*Math.atan2(c,l),w=2*u;o[w]=m*Math.cos(_),o[w+1]=m*Math.sin(_),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new gc(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,u=this._a;if(s)for(let f=0;f>1,w=r[_];n[f]=w*c[f],n[m]=w*c[m]}else for(let f=0;f=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function bs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function gA(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function wA(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let u=1;u0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var xA=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l>10,m=l&1023;if(f===31)c=u|2139095040|m<<13;else if(f===0)if(m===0)c=u;else{let _=113;for(;(m&1024)===0;)m<<=1,--_;m&=-1025,c=u|_<<23|m<<13}else c=u|f+112<<23|m<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;owz});var wz={};var Nd={};hs(Nd,{InferenceSession:()=>yd,TRACE:()=>Mc,TRACE_EVENT_BEGIN:()=>Gr,TRACE_EVENT_END:()=>jr,TRACE_FUNC_BEGIN:()=>Ms,TRACE_FUNC_END:()=>Ss,Tensor:()=>er,default:()=>Hz,env:()=>Ke,registerBackend:()=>Ts});var wd=Object.defineProperty,xz=Object.getOwnPropertyDescriptor,yz=Object.getOwnPropertyNames,bz=Object.prototype.hasOwnProperty,vz=(t=>typeof _s<"u"?_s:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof _s<"u"?_s:e)[r]}):t)(function(t){if(typeof _s<"u")return _s.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),be=(t,e)=>()=>(t&&(e=t(t=0)),e),Oo=(t,e)=>{for(var r in e)wd(t,r,{get:e[r],enumerable:!0})},kz=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of yz(e))!bz.call(t,n)&&n!==r&&wd(t,n,{get:()=>e[n],enumerable:!(s=xz(e,n))||s.enumerable});return t},Tc=t=>kz(wd({},"__esModule",{value:!0}),t),vo,Dr,Ts,yA,HA,XA=be(()=>{"use strict";vo=new Map,Dr=[],Ts=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=vo.get(t);if(s===void 0)vo.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=Dr.indexOf(t);n!==-1&&Dr.splice(n,1);for(let o=0;o{let e=vo.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(s){return r||(e.error=`${s}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},HA=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Dr:r,n,o=[],a=new Set;for(let l of s){let c=await yA(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),Ez=be(()=>{"use strict";XA()}),YA,Az=be(()=>{"use strict";YA="1.24.0-dev.20251116-b39e144322"}),Vf,dt,KA=be(()=>{"use strict";Az(),Vf="warning",dt={wasm:{},webgl:{},webgpu:{},versions:{common:YA},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);Vf=t}},get logLevel(){return Vf}},Object.defineProperty(dt,"logLevel",{enumerable:!0})}),Ke,Tz=be(()=>{"use strict";KA(),Ke=dt}),QA,JA,Mz=be(()=>{"use strict";QA=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=o*n,f=0,m=u,_=u*2,w=-1;a==="RGBA"?(f=0,m=u,_=u*2,w=u*3):a==="RGB"?(f=0,m=u,_=u*2):a==="RBG"&&(f=0,_=u,m=u*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,u;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,b=3,A=0,k=f,S=f*2,M=-1;i==="RGBA"?(A=0,k=f,S=f*2,M=f*3):i==="RGB"?(A=0,k=f,S=f*2):i==="RBG"&&(A=0,S=f,k=f*2),s=r.createImageData(n,o);for(let O=0;O{"use strict";xd(),xc=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,b=0,A=c,k=c*2,S=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(b=0,k=c,A=c*2):l==="BGR"&&(k=0,A=c,b=c*2);for(let M=0;M{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,_=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=_}else i.tensorFormat="RGBA",i.height=m,i.width=_;f.drawImage(t,0,0),a=f.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let u,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,f=e.resizedWidth):(u=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=u,i.width=f,e!==void 0){let m=l();m.width=f,m.height=u;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,u).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,xc(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((u,f)=>{let m=l(),_=c(m);if(!t||!_)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,_.drawImage(w,0,0,m.width,m.height);let x=_.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,u(xc(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return xc(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},e2=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Rt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},t2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Rt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},r2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Rt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},s2=(t,e,r)=>new Rt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),Es,Mo,Hf,n2,Oz=be(()=>{"use strict";Es=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Mo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Hf=!1,n2=()=>{if(!Hf){Hf=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Es.set("int64",BigInt64Array),Mo.set(BigInt64Array,"int64")),e&&(Es.set("uint64",BigUint64Array),Mo.set(BigUint64Array,"uint64")),s?(Es.set("float16",r),Mo.set(r,"float16")):Es.set("float16",Uint16Array)}}}),o2,a2,Iz=be(()=>{"use strict";xd(),o2=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new Rt(t.type,t.data,e);case"cpu-pinned":return new Rt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Rt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Rt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Rt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Rt,xd=be(()=>{"use strict";Mz(),Sz(),Oz(),Iz(),Rt=class{constructor(t,e,r){n2();let s,n;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,n=t.dims,t.location){case"cpu-pinned":{let a=Es.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,i;if(typeof t=="string")if(s=t,i=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=Es.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")s="string",a=t;else if(l==="boolean")s="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(t);else{let l=Mo.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=l,a=t}if(i===void 0)i=[a.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=a,this.dataLocation="cpu"}let o=o2(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(t,e){return ZA(t,e)}static fromTexture(t,e){return e2(t,e)}static fromGpuBuffer(t,e){return t2(t,e)}static fromMLTensor(t,e){return r2(t,e)}static fromPinnedBuffer(t,e,r){return s2(t,e,r)}toDataURL(t){return QA(this,t)}toImageData(t){return JA(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return a2(this,t)}}}),er,i2=be(()=>{"use strict";xd(),er=Rt}),Mc,Xf,Ms,Ss,Gr,jr,l2=be(()=>{"use strict";KA(),Mc=(t,e)=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeStamp(`${t}::ORT::${e}`)},Xf=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||Xf("BEGIN",t)},Ss=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||Xf("END",t)},Gr=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.time(`ORT::${t}`)},jr=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeEnd(`ORT::${t}`)}}),c2,Cz=be(()=>{"use strict";XA(),i2(),l2(),c2=class u2{constructor(e){this.handler=e}async run(e,r,s){Ms(),Gr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof er||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof er)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,u=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(u.indexOf(f)!==-1){let m=r[f];(m===null||m instanceof er)&&(c=!0,a=!1,n[f]=m)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let u=i[c];u instanceof er?l[c]=u:l[c]=new er(u.type,u.data,u.dims)}return jr("InferenceSession.run"),Ss(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){Ms(),Gr("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let u=e,f=0,m=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=u.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${u.byteLength}).`);if(m=e.byteLength-f,typeof s=="number"){if(m=s,!Number.isSafeInteger(m))throw new RangeError("'byteLength' must be an integer.");if(m<=0||f+m>u.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${u.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(u,f,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await HA(a),c=await i.createInferenceSessionHandler(o,l);return jr("InferenceSession.create"),Ss(),new u2(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),yd,Pz=be(()=>{"use strict";Cz(),yd=c2}),Lz=be(()=>{"use strict"}),zz=be(()=>{"use strict"}),Nz=be(()=>{"use strict"}),Rz=be(()=>{"use strict"}),p2={};Oo(p2,{InferenceSession:()=>yd,TRACE:()=>Mc,TRACE_EVENT_BEGIN:()=>Gr,TRACE_EVENT_END:()=>jr,TRACE_FUNC_BEGIN:()=>Ms,TRACE_FUNC_END:()=>Ss,Tensor:()=>er,env:()=>Ke,registerBackend:()=>Ts});var Os=be(()=>{"use strict";Ez(),Tz(),Pz(),i2(),Lz(),zz(),l2(),Nz(),Rz()}),bd=be(()=>{"use strict"}),f2={};Oo(f2,{default:()=>d2});var Yf,Kf,d2,$z=be(()=>{"use strict";S2(),Is(),vd(),Yf="ort-wasm-proxy-worker",Kf=globalThis.self?.name===Yf,Kf&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":kd(r.wasm).then(()=>{Sd(r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})})},s=>{postMessage({type:e,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;Od(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=Ic(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;Id(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":Cd(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;Pd(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},zd([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":Ld(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),d2=Kf?null:t=>new Worker(t??zt,{type:"module",name:Yf})}),m2={};Oo(m2,{default:()=>_2});async function bA(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(p,d)=>{p.startsWith("./")&&(p=p.substring(2)),(e.Uc||(e.Uc=new Map)).set(p,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let o=()=>{let p=d=>(...h)=>{let g=ar;return h=d(...h),ar!=g?new Promise((E,T)=>{pf={resolve:E,reject:T}}):h};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=p(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(p,d)=>{throw d},c=import_meta.url,u="";if(r||s){try{u=new URL(".",c).href}catch{}s&&(i=p=>{var d=new XMLHttpRequest;return d.open("GET",p,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async p=>{if(I(p))return new Promise((h,g)=>{var E=new XMLHttpRequest;E.open("GET",p,!0),E.responseType="arraybuffer",E.onload=()=>{E.status==200||E.status==0&&E.response?h(E.response):g(E.status)},E.onerror=g,E.send(null)});var d=await fetch(p,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,m,_,w,x,b,A=console.log.bind(console),k=console.error.bind(console),S=A,M=k,O=!1,I=p=>p.startsWith("file://");function v(){Ir.buffer!=F.buffer&&le()}if(n){let p=function(d){try{var h=d.data,g=h.Oc;if(g==="load"){let E=[];self.onmessage=T=>E.push(T),b=()=>{postMessage({Oc:"loaded"});for(let T of E)p(T);self.onmessage=p};for(let T of h.ce)e[T]&&!e[T].proxy||(e[T]=(...P)=>{postMessage({Oc:"callHandler",be:T,args:P})},T=="print"&&(S=e[T]),T=="printErr"&&(M=e[T]));Ir=h.ie,le(),m=h.je,qe(),nc()}else if(g==="run"){(function(E){var T=(v(),C)[E+52>>>2>>>0];E=(v(),C)[E+56>>>2>>>0],Sk(T,T-E),pe(T)})(h.Nc),kf(h.Nc,0,0,1,0,0),_v(),lf(h.Nc),G||(uk(),G=!0);try{WM(h.ge,h.Wc)}catch(E){if(E!="unwind")throw E}}else h.target!=="setimmediate"&&(g==="checkMailbox"?G&&Kl():g&&(M(`worker: received unknown command ${g}`),M(h)))}catch(E){throw kk(),E}};var B=p,G=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=p}var F,X,Y,J,$,C,se,K,L,R,U,Q=!1;function le(){var p=Ir.buffer;e.HEAP8=F=new Int8Array(p),Y=new Int16Array(p),e.HEAPU8=X=new Uint8Array(p),J=new Uint16Array(p),e.HEAP32=$=new Int32Array(p),e.HEAPU32=C=new Uint32Array(p),se=new Float32Array(p),K=new Float64Array(p),L=new BigInt64Array(p),R=new BigUint64Array(p)}function je(){Q=!0,n?b():br._b()}function ce(p){throw M(p="Aborted("+p+")"),O=!0,p=new WebAssembly.RuntimeError(p+". Build with -sASSERTIONS for more info."),x?.(p),p}function Tt(){return{a:{f:VM,J:HM,k:XM,p:YM,l:KM,sa:QM,b:JM,ca:ZM,Ja:bv,q:eS,da:Av,Za:Tv,Fa:Mv,Ha:Sv,_a:Ov,Xa:Iv,Qa:Cv,Wa:Pv,oa:Lv,Ga:zv,Xb:Nv,Ya:Rv,Yb:$v,db:tS,Da:sS,Sb:nS,Qb:aS,Ca:lS,M:cS,I:uS,Rb:pS,ja:wS,Tb:xS,Ta:yS,Vb:vS,Ka:kS,Ob:ES,ka:AS,Sa:lf,ab:TS,U:IS,n:NS,c:of,rb:RS,w:$S,L:DS,z:BS,j:US,o:Wv,sb:FS,G:GS,T:jS,h:qS,u:WS,m:VS,i:HS,Na:XS,Oa:YS,Pa:KS,La:Yv,Ma:Kv,Pb:Qv,eb:JS,cb:tO,Y:rO,qb:sO,la:nO,bb:ZS,fb:oO,$a:aO,Wb:iO,N:QS,gb:lO,X:cO,Ub:uO,nb:xO,C:yO,ra:bO,qa:vO,pb:kO,W:EO,v:AO,mb:TO,lb:MO,kb:SO,ob:OO,jb:IO,ib:CO,hb:PO,Ua:sk,Va:nk,Ia:Zs,V:ok,na:ak,Ra:ik,ma:lk,Cb:GI,xa:RI,Db:FI,ya:NI,F:EI,e:pI,s:cI,x:lI,B:bI,Fb:PI,ba:CI,D:mI,za:LI,$:$I,ga:II,Gb:OI,Hb:SI,Ba:AI,Aa:MI,Ib:TI,wa:UI,aa:zI,d:uI,A:dI,r:fI,Bb:jI,t:hI,y:vI,H:_I,E:gI,K:kI,R:DI,ia:yI,_:BI,Jb:xI,Kb:wI,g:zO,a:Ir,Nb:Js,Eb:NO,ha:RO,O:$O,pa:DO,Lb:BO,ta:UO,Q:FO,yb:GO,zb:jO,ua:qO,ea:WO,P:VO,Ea:HO,va:XO,Z:YO,wb:KO,Zb:QO,S:JO,Ab:ZO,tb:eI,ub:rI,vb:sI,fa:nI,xb:oI,Mb:aI}}}async function qe(){function p(g,E){var T=br=g.exports;g={};for(let[P,z]of Object.entries(T))typeof z=="function"?(T=MS(z),g[P]=T):g[P]=z;return br=g,br=(function(){var P=br,z=Z=>Ie=>Z(Ie)>>>0,j=Z=>()=>Z()>>>0;return(P=Object.assign({},P)).$b=z(P.$b),P.Cc=j(P.Cc),P.Ec=z(P.Ec),P.rd=(Z=>(Ie,Ne)=>Z(Ie,Ne)>>>0)(P.rd),P.wd=z(P.wd),P.xd=j(P.xd),P.Bd=z(P.Bd),P})(),dv.push(br.id),ck=(g=br).$b,uk=g.ac,e._OrtInit=g.bc,e._OrtGetLastError=g.cc,e._OrtCreateSessionOptions=g.dc,e._OrtAppendExecutionProvider=g.ec,e._OrtAddFreeDimensionOverride=g.fc,e._OrtAddSessionConfigEntry=g.gc,e._OrtReleaseSessionOptions=g.hc,e._OrtCreateSession=g.ic,e._OrtReleaseSession=g.jc,e._OrtGetInputOutputCount=g.kc,e._OrtGetInputOutputMetadata=g.lc,e._OrtFree=g.mc,e._OrtCreateTensor=g.nc,e._OrtGetTensorData=g.oc,e._OrtReleaseTensor=g.pc,e._OrtCreateRunOptions=g.qc,e._OrtAddRunConfigEntry=g.rc,e._OrtReleaseRunOptions=g.sc,e._OrtCreateBinding=g.tc,e._OrtBindInput=g.uc,e._OrtBindOutput=g.vc,e._OrtClearBoundOutputs=g.wc,e._OrtReleaseBinding=g.xc,e._OrtRunWithBinding=g.yc,e._OrtRun=g.zc,e._OrtEndProfiling=g.Ac,gf=e._OrtGetWebGpuDevice=g.Bc,rc=g.Cc,Xt=e._free=g.Dc,nn=e._malloc=g.Ec,pk=e._wgpuBufferRelease=g.Fc,fk=e._wgpuCreateInstance=g.Gc,dk=g.Hc,mk=g.Ic,_k=g.Jc,hk=g.Kc,gk=g.Lc,wk=g.Pc,xk=g.Zc,yk=g._c,bk=g.$c,wf=g.bd,xf=g.cd,yf=g.dd,bf=g.ed,co=g.fd,vf=g.gd,vk=g.hd,kf=g.kd,kk=g.ld,Ek=g.md,Ak=g.nd,Ef=g.od,Tk=g.pd,Mk=g.qd,Af=g.rd,xe=g.sd,uo=g.td,Sk=g.ud,pe=g.vd,sc=g.wd,fe=g.xd,Ok=g.yd,Tf=g.zd,Ik=g.Ad,Ck=g.Bd,Pk=g.Cd,Mf=g.Dd,Lk=g.Ed,zk=g.Fd,Nk=g.Gd,Rk=g.Hd,$k=g.Id,Dk=g.Jd,Bk=g.Kd,Uk=g.Ld,Fk=g.Md,Gk=g.Nd,jk=g.Od,qk=g.Pd,Wk=g.Qd,Vk=g.Rd,Hk=g.Td,Xk=g.Ud,Yk=g.Vd,Kk=g.Wd,Qk=g.Yd,Jk=g.Zd,Zk=g._d,eE=g.$d,tE=g.ae,rE=g.oe,sE=g.pe,nE=g.qe,oE=g.re,aE=g.se,iE=g.te,lE=g.ue,cE=g.ve,uE=g.we,pE=g.xe,fE=g.ye,dE=g.Ye,mE=g.Ze,_E=g._e,hE=g.$e,m=E,br}var d,h=Tt();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(E,T)=>{g(p(E,T))})}):n?p(new WebAssembly.Instance(m,Tt()),m):(U??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",u):u+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import_meta.url).href,d=await(async function(g){var E=U;if(!f&&!I(E))try{var T=fetch(E,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,g)}catch(P){M(`wasm streaming compile failed: ${P}`),M("falling back to ArrayBuffer instantiation")}return(async function(P,z){try{var j=await(async function(Z){if(!f)try{var Ie=await a(Z);return new Uint8Array(Ie)}catch{}if(Z==U&&f)Z=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";Z=i(Z)}return Z})(P);return await WebAssembly.instantiate(j,z)}catch(Z){M(`failed to asynchronously prepare wasm: ${Z}`),ce(Z)}})(E,g)})(h),p(d.instance,d.module))}class ct{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var Mt=p=>{p.terminate(),p.onmessage=()=>{}},Be=[],Se=0,rt=null,nr=p=>{Or.length==0&&(gv(),hv(Or[0]));var d=Or.pop();if(!d)return 6;ao.push(d),fs[p.Nc]=d,d.Nc=p.Nc;var h={Oc:"run",ge:p.fe,Wc:p.Wc,Nc:p.Nc};return d.postMessage(h,p.Yc),0},Oe=0,Ue=(p,d,...h)=>{var g,E=16*h.length,T=fe(),P=sc(E),z=P>>>3;for(g of h)typeof g=="bigint"?((v(),L)[z++>>>0]=1n,(v(),L)[z++>>>0]=g):((v(),L)[z++>>>0]=0n,(v(),K)[z++>>>0]=g);return p=Ek(p,0,E,P,d),pe(T),p};function Js(p){if(n)return Ue(0,1,p);if(_=p,!(0{if(_=p,n)throw oo(p),"unwind";Js(p)},Or=[],ao=[],dv=[],fs={},mv=p=>{var d=p.Nc;delete fs[d],Or.push(p),ao.splice(ao.indexOf(p),1),p.Nc=0,Ak(d)};function _v(){dv.forEach(p=>p())}var hv=p=>new Promise(d=>{p.onmessage=E=>{var T=E.data;if(E=T.Oc,T.Vc&&T.Vc!=rc()){var P=fs[T.Vc];P?P.postMessage(T,T.Yc):M(`Internal error! Worker sent a message "${E}" to target pthread ${T.Vc}, but that thread no longer exists!`)}else E==="checkMailbox"?Kl():E==="spawnThread"?nr(T):E==="cleanupThread"?St(()=>{mv(fs[T.he])}):E==="loaded"?(p.loaded=!0,d(p)):T.target==="setimmediate"?p.postMessage(T):E==="uncaughtException"?p.onerror(T.error):E==="callHandler"?e[T.be](...T.args):E&&M(`worker sent an unknown command ${E}`)},p.onerror=E=>{throw M(`worker sent an error! ${E.filename}:${E.lineno}: ${E.message}`),E};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);p.postMessage({Oc:"load",ce:g,ie:Ir,je:m})});function gv(){var p=new Worker((()=>{let d=URL;return import_meta.url>"file:"&&import_meta.url<"file;"?new d("ort.webgpu.bundle.min.mjs",import_meta.url):new URL(import_meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Or.push(p)}var Ir,WM=(p,d)=>{Oe=0,p=Mf(p,d),0-9007199254740992>p||9007199254740992>>=0);return(v(),F)[d.Qc+12>>>0]==0&&(wv(d,!0),Yl--),xv(d,!1),Xl.push(d),Ck(p)}var en=0,HM=()=>{xe(0,0);var p=Xl.pop();Ok(p.Xc),en=0};function wv(p,d){d=d?1:0,(v(),F)[p.Qc+12>>>0]=d}function xv(p,d){d=d?1:0,(v(),F)[p.Qc+13>>>0]=d}class tf{constructor(d){this.Xc=d,this.Qc=d-24}}var rf=p=>{var d=en;if(!d)return uo(0),0;var h=new tf(d);(v(),C)[h.Qc+16>>>2>>>0]=d;var g=(v(),C)[h.Qc+4>>>2>>>0];if(!g)return uo(0),d;for(var E of p){if(E===0||E===g)break;if(Ik(E,g,h.Qc+16))return uo(E),d}return uo(g),d};function XM(){return rf([])}function YM(p){return rf([p>>>0])}function KM(p,d,h,g){return rf([p>>>0,d>>>0,h>>>0,g>>>0])}var QM=()=>{var p=Xl.pop();p||ce("no exception to throw");var d=p.Xc;throw(v(),F)[p.Qc+13>>>0]==0&&(Xl.push(p),xv(p,!0),wv(p,!1),Yl++),Tf(d),en=d};function JM(p,d,h){var g=new tf(p>>>=0);throw d>>>=0,h>>>=0,(v(),C)[g.Qc+16>>>2>>>0]=0,(v(),C)[g.Qc+4>>>2>>>0]=d,(v(),C)[g.Qc+8>>>2>>>0]=h,Tf(p),Yl++,en=p}var ZM=()=>Yl;function yv(p,d,h,g){return n?Ue(2,1,p,d,h,g):bv(p,d,h,g)}function bv(p,d,h,g){if(p>>>=0,d>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var E=[];return n&&E.length===0?yv(p,d,h,g):(p={fe:h,Nc:p,Wc:g,Yc:E},n?(p.Oc="spawnThread",postMessage(p,E),0):nr(p))}function eS(p){throw en||=p>>>0,en}var vv=globalThis.TextDecoder&&new TextDecoder,kv=(p,d,h,g)=>{if(h=d+h,g)return h;for(;p[d]&&!(d>=h);)++d;return d},Ev=(p,d=0,h,g)=>{if(16<(h=kv(p,d>>>=0,h,g))-d&&p.buffer&&vv)return vv.decode(p.buffer instanceof ArrayBuffer?p.subarray(d,h):p.slice(d,h));for(g="";d(E=(240&E)==224?(15&E)<<12|T<<6|P:(7&E)<<18|T<<12|P<<6|63&p[d++])?g+=String.fromCharCode(E):(E-=65536,g+=String.fromCharCode(55296|E>>10,56320|1023&E))}}else g+=String.fromCharCode(E)}return g},tn=(p,d,h)=>(p>>>=0)?Ev((v(),X),p,d,h):"";function Av(p,d,h){return n?Ue(3,1,p,d,h):0}function Tv(p,d){if(n)return Ue(4,1,p,d)}function Mv(p,d){if(n)return Ue(5,1,p,d)}function Sv(p,d,h){if(n)return Ue(6,1,p,d,h)}function Ov(p,d,h){return n?Ue(7,1,p,d,h):0}function Iv(p,d){if(n)return Ue(8,1,p,d)}function Cv(p,d,h){if(n)return Ue(9,1,p,d,h)}function Pv(p,d,h,g){if(n)return Ue(10,1,p,d,h,g)}function Lv(p,d,h,g){if(n)return Ue(11,1,p,d,h,g)}function zv(p,d,h,g){if(n)return Ue(12,1,p,d,h,g)}function Nv(p){if(n)return Ue(13,1,p)}function Rv(p,d){if(n)return Ue(14,1,p,d)}function $v(p,d,h){if(n)return Ue(15,1,p,d,h)}var tS=()=>ce(""),or=p=>{p>>>=0;for(var d="";;){var h=(v(),X)[p++>>>0];if(!h)return d;d+=String.fromCharCode(h)}},sf={},nf={},rS={},rn=class extends Error{constructor(p){super(p),this.name="BindingError"}};function hr(p,d,h={}){return(function(g,E,T={}){var P=E.name;if(!g)throw new rn(`type "${P}" must have a positive integer typeid pointer`);if(nf.hasOwnProperty(g)){if(T.de)return;throw new rn(`Cannot register type '${P}' twice`)}nf[g]=E,delete rS[g],sf.hasOwnProperty(g)&&(E=sf[g],delete sf[g],E.forEach(z=>z()))})(p,d,h)}var Dv=(p,d,h)=>{switch(d){case 1:return h?g=>(v(),F)[g>>>0]:g=>(v(),X)[g>>>0];case 2:return h?g=>(v(),Y)[g>>>1>>>0]:g=>(v(),J)[g>>>1>>>0];case 4:return h?g=>(v(),$)[g>>>2>>>0]:g=>(v(),C)[g>>>2>>>0];case 8:return h?g=>(v(),L)[g>>>3>>>0]:g=>(v(),R)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${p}`)}};function sS(p,d,h,g,E){p>>>=0,h>>>=0,d=or(d>>>0);let T=P=>P;if(g=g===0n){let P=8*h;T=z=>BigInt.asUintN(P,z),E=T(E)}hr(p,{name:d,Mc:T,Sc:(P,z)=>(typeof z=="number"&&(z=BigInt(z)),z),Rc:Dv(d,h,!g),Tc:null})}function nS(p,d,h,g){hr(p>>>=0,{name:d=or(d>>>0),Mc:function(E){return!!E},Sc:function(E,T){return T?h:g},Rc:function(E){return this.Mc((v(),X)[E>>>0])},Tc:null})}var Bv=[],ds=[0,1,,1,null,1,!0,1,!1,1];function of(p){9<(p>>>=0)&&--ds[p+1]==0&&(ds[p]=void 0,Bv.push(p))}var Bt=p=>{if(!p)throw new rn(`Cannot use deleted val. handle = ${p}`);return ds[p]},Ht=p=>{switch(p){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=Bv.pop()||ds.length;return ds[d]=p,ds[d+1]=1,d}};function af(p){return this.Mc((v(),C)[p>>>2>>>0])}var oS={name:"emscripten::val",Mc:p=>{var d=Bt(p);return of(p),d},Sc:(p,d)=>Ht(d),Rc:af,Tc:null};function aS(p){return hr(p>>>0,oS)}var iS=(p,d)=>{switch(d){case 4:return function(h){return this.Mc((v(),se)[h>>>2>>>0])};case 8:return function(h){return this.Mc((v(),K)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${p}`)}};function lS(p,d,h){h>>>=0,hr(p>>>=0,{name:d=or(d>>>0),Mc:g=>g,Sc:(g,E)=>E,Rc:iS(d,h),Tc:null})}function cS(p,d,h,g,E){p>>>=0,h>>>=0,d=or(d>>>0);let T=z=>z;if(g===0){var P=32-8*h;T=z=>z<

>>P,E=T(E)}hr(p,{name:d,Mc:T,Sc:(z,j)=>j,Rc:Dv(d,h,g!==0),Tc:null})}function uS(p,d,h){function g(T){var P=(v(),C)[T>>>2>>>0];return T=(v(),C)[T+4>>>2>>>0],new E((v(),F).buffer,T,P)}var E=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];hr(p>>>=0,{name:h=or(h>>>0),Mc:g,Rc:g},{de:!0})}var gr=(p,d,h)=>{var g=(v(),X);if(d>>>=0,0=P){if(d>=h)break;g[d++>>>0]=P}else if(2047>=P){if(d+1>=h)break;g[d++>>>0]=192|P>>6,g[d++>>>0]=128|63&P}else if(65535>=P){if(d+2>=h)break;g[d++>>>0]=224|P>>12,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P}else{if(d+3>=h)break;g[d++>>>0]=240|P>>18,g[d++>>>0]=128|P>>12&63,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P,T++}}g[d>>>0]=0,p=d-E}else p=0;return p},wr=p=>{for(var d=0,h=0;h=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++h):d+=3}return d};function pS(p,d){hr(p>>>=0,{name:d=or(d>>>0),Mc(h){var g=(v(),C)[h>>>2>>>0];return g=tn(h+4,g,!0),Xt(h),g},Sc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var E=typeof g=="string";if(!(E||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new rn("Cannot pass non-string to std::string");var T=E?wr(g):g.length,P=nn(4+T+1),z=P+4;return(v(),C)[P>>>2>>>0]=T,E?gr(g,z,T+1):(v(),X).set(g,z>>>0),h!==null&&h.push(Xt,P),P},Rc:af,Tc(h){Xt(h)}})}var Uv=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,fS=(p,d,h)=>{if(p>>>=1,16<(d=kv((v(),J),p,d/2,h))-p&&Uv)return Uv.decode((v(),J).slice(p,d));for(h="";p>>0];h+=String.fromCharCode(g)}return h},dS=(p,d,h)=>{if(h??=2147483647,2>h)return 0;var g=d;h=(h-=2)<2*p.length?h/2:p.length;for(var E=0;E>>1>>>0]=T,d+=2}return(v(),Y)[d>>>1>>>0]=0,d-g},mS=p=>2*p.length,_S=(p,d,h)=>{var g="";p>>>=2;for(var E=0;!(E>=d/4);E++){var T=(v(),C)[p+E>>>0];if(!T&&!h)break;g+=String.fromCodePoint(T)}return g},hS=(p,d,h)=>{if(d>>>=0,h??=2147483647,4>h)return 0;var g=d;h=g+h-4;for(var E=0;E>>2>>>0]=T,(d+=4)+4>h)break}return(v(),$)[d>>>2>>>0]=0,d-g},gS=p=>{for(var d=0,h=0;h>>=0,d>>>=0,h=or(h>>>=0),d===2)var g=fS,E=dS,T=mS;else g=_S,E=hS,T=gS;hr(p,{name:h,Mc:P=>{var z=(v(),C)[P>>>2>>>0];return z=g(P+4,z*d,!0),Xt(P),z},Sc:(P,z)=>{if(typeof z!="string")throw new rn(`Cannot pass non-string to C++ string type ${h}`);var j=T(z),Z=nn(4+j+d);return(v(),C)[Z>>>2>>>0]=j/d,E(z,Z+4,j+d),P!==null&&P.push(Xt,Z),Z},Rc:af,Tc(P){Xt(P)}})}function xS(p,d){hr(p>>>=0,{ee:!0,name:d=or(d>>>0),Mc:()=>{},Sc:()=>{}})}function yS(p){kf(p>>>0,!s,1,!r,131072,!1),_v()}var St=p=>{if(!O)try{if(p(),!(0Number(((navigator.userAgent||"").match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function lf(p){p>>>=0,bS||(Atomics.waitAsync((v(),$),p>>>2,p).value.then(Kl),p+=128,Atomics.store((v(),$),p>>>2,1))}var Kl=()=>St(()=>{var p=rc();p&&(lf(p),Mk())});function vS(p,d){(p>>>=0)==d>>>0?setTimeout(Kl):n?postMessage({Vc:p,Oc:"checkMailbox"}):(p=fs[p])&&p.postMessage({Oc:"checkMailbox"})}var cf=[];function kS(p,d,h,g,E){for(d>>>=0,E>>>=0,cf.length=0,h=E>>>3,g=E+g>>>3;h>>0]?(v(),L)[h++>>>0]:(v(),K)[h++>>>0],cf.push(T)}return(d?Sf[d]:iI[p])(...cf)}var ES=()=>{Oe=0};function AS(p){p>>>=0,n?postMessage({Oc:"cleanupThread",he:p}):mv(fs[p])}function TS(p){}var Ql=p=>{try{p()}catch(d){ce(d)}};function MS(p){var d=(...h)=>{Jl.push(p);try{return p(...h)}finally{O||(Jl.pop(),ar&&Cr===1&&Jl.length===0&&(Cr=0,Oe+=1,Ql(mE),typeof Fibers<"u"&&Fibers.Be()))}};return jv.set(p,d),d}var Cr=0,ar=null,Fv=0,Jl=[],uf=new Map,Gv=new Map,jv=new Map,SS=0,pf=null,OS=[],qv=p=>(function(d){if(!O){if(Cr===0){var h=!1,g=!1;d((E=0)=>{if(!O&&(Fv=E,h=!0,g)){Cr=2,Ql(()=>_E(ar)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),E=!1;try{var T=(function(){var j=(v(),$)[ar+8>>>2>>>0];return j=Gv.get(j),j=jv.get(j),--Oe,j()})()}catch(j){T=j,E=!0}var P=!1;if(!ar){var z=pf;z&&(pf=null,(E?z.reject:z.resolve)(T),P=!0)}if(E&&!P)throw T}}),g=!0,h||(Cr=1,ar=(function(){var E=nn(65548),T=E+12;if((v(),C)[E>>>2>>>0]=T,(v(),C)[E+4>>>2>>>0]=T+65536,T=Jl[0],!uf.has(T)){var P=SS++;uf.set(T,P),Gv.set(P,T)}return T=uf.get(T),(v(),$)[E+8>>>2>>>0]=T,E})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Ql(()=>dE(ar)))}else Cr===2?(Cr=0,Ql(hE),Xt(ar),ar=null,OS.forEach(St)):ce(`invalid state: ${Cr}`);return Fv}})(d=>{p().then(d)});function IS(p){return p>>>=0,qv(async()=>{var d=await Bt(p);return Ht(d)})}var ff=[],CS=p=>{var d=ff.length;return ff.push(p),d},PS=(p,d)=>{for(var h=Array(p),g=0;g>>2>>>0],P=nf[T];if(P===void 0)throw p=`parameter ${g}`,T=ck(T),d=or(T),Xt(T),new rn(`${p} has unknown type ${d}`);h[E]=P}return h},LS=(p,d,h)=>{var g=[];return p=p(g,h),g.length&&((v(),C)[d>>>2>>>0]=Ht(g)),p},zS={},Zl=p=>{var d=zS[p];return d===void 0?or(p):d};function NS(p,d,h){var[g,...E]=PS(p,d>>>0);d=g.Sc.bind(g);var T=E.map(j=>j.Rc.bind(j));p--;var P={toValue:Bt};switch(p=T.map((j,Z)=>{var Ie=`argFromPtr${Z}`;return P[Ie]=j,`${Ie}(args${Z?"+"+8*Z:""})`}),h){case 0:var z="toValue(handle)";break;case 2:z="new (toValue(handle))";break;case 3:z="";break;case 1:P.getStringOrSymbol=Zl,z="toValue(handle)[getStringOrSymbol(methodName)]"}return z+=`(${p})`,g.ee||(P.toReturnWire=d,P.emval_returnValue=LS,z=`return emval_returnValue(toReturnWire, destructorsRef, ${z})`),z=`return function (handle, methodName, destructorsRef, args) { + ${z} +- }`,h=new Function(Object.keys(P),z)(...Object.values(P)),z=`methodCaller<(${E.map(j=>j.name)}) => ${g.name}>`,CS(Object.defineProperty(h,"name",{value:z}))}function RS(p,d){return d>>>=0,(p=Bt(p>>>0))==Bt(d)}function $S(p){return(p>>>=0)?(p=Zl(p),Ht(globalThis[p])):Ht(globalThis)}function DS(p){return p=Zl(p>>>0),Ht(e[p])}function BS(p,d){return d>>>=0,p=Bt(p>>>0),d=Bt(d),Ht(p[d])}function US(p){9<(p>>>=0)&&(ds[p+1]+=1)}function Wv(p,d,h,g,E){return ff[p>>>0](d>>>0,h>>>0,g>>>0,E>>>0)}function FS(p,d,h,g,E){return Wv(p>>>0,d>>>0,h>>>0,g>>>0,E>>>0)}function GS(){return Ht([])}function jS(p){p=Bt(p>>>0);for(var d=Array(p.length),h=0;h>>0))}function WS(){return Ht({})}function VS(p){for(var d=Bt(p>>>=0);d.length;){var h=d.pop();d.pop()(h)}of(p)}function HS(p,d,h){d>>>=0,h>>>=0,p=Bt(p>>>0),d=Bt(d),h=Bt(h),p[d]=h}function XS(p,d){p=_t(p),d>>>=0,p=new Date(1e3*p),(v(),$)[d>>>2>>>0]=p.getUTCSeconds(),(v(),$)[d+4>>>2>>>0]=p.getUTCMinutes(),(v(),$)[d+8>>>2>>>0]=p.getUTCHours(),(v(),$)[d+12>>>2>>>0]=p.getUTCDate(),(v(),$)[d+16>>>2>>>0]=p.getUTCMonth(),(v(),$)[d+20>>>2>>>0]=p.getUTCFullYear()-1900,(v(),$)[d+24>>>2>>>0]=p.getUTCDay(),p=(p.getTime()-Date.UTC(p.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(v(),$)[d+28>>>2>>>0]=p}var Vv=p=>p%4==0&&(p%100!=0||p%400==0),Hv=[0,31,60,91,121,152,182,213,244,274,305,335],Xv=[0,31,59,90,120,151,181,212,243,273,304,334];function YS(p,d){p=_t(p),d>>>=0,p=new Date(1e3*p),(v(),$)[d>>>2>>>0]=p.getSeconds(),(v(),$)[d+4>>>2>>>0]=p.getMinutes(),(v(),$)[d+8>>>2>>>0]=p.getHours(),(v(),$)[d+12>>>2>>>0]=p.getDate(),(v(),$)[d+16>>>2>>>0]=p.getMonth(),(v(),$)[d+20>>>2>>>0]=p.getFullYear()-1900,(v(),$)[d+24>>>2>>>0]=p.getDay();var h=(Vv(p.getFullYear())?Hv:Xv)[p.getMonth()]+p.getDate()-1|0;(v(),$)[d+28>>>2>>>0]=h,(v(),$)[d+36>>>2>>>0]=-60*p.getTimezoneOffset(),h=new Date(p.getFullYear(),6,1).getTimezoneOffset();var g=new Date(p.getFullYear(),0,1).getTimezoneOffset();p=0|(h!=g&&p.getTimezoneOffset()==Math.min(g,h)),(v(),$)[d+32>>>2>>>0]=p}function KS(p){p>>>=0;var d=new Date((v(),$)[p+20>>>2>>>0]+1900,(v(),$)[p+16>>>2>>>0],(v(),$)[p+12>>>2>>>0],(v(),$)[p+8>>>2>>>0],(v(),$)[p+4>>>2>>>0],(v(),$)[p>>>2>>>0],0),h=(v(),$)[p+32>>>2>>>0],g=d.getTimezoneOffset(),E=new Date(d.getFullYear(),6,1).getTimezoneOffset(),T=new Date(d.getFullYear(),0,1).getTimezoneOffset(),P=Math.min(T,E);return 0>h?(v(),$)[p+32>>>2>>>0]=+(E!=T&&P==g):0>>2>>>0]=d.getDay(),h=(Vv(d.getFullYear())?Hv:Xv)[d.getMonth()]+d.getDate()-1|0,(v(),$)[p+28>>>2>>>0]=h,(v(),$)[p>>>2>>>0]=d.getSeconds(),(v(),$)[p+4>>>2>>>0]=d.getMinutes(),(v(),$)[p+8>>>2>>>0]=d.getHours(),(v(),$)[p+12>>>2>>>0]=d.getDate(),(v(),$)[p+16>>>2>>>0]=d.getMonth(),(v(),$)[p+20>>>2>>>0]=d.getYear(),p=d.getTime(),BigInt(isNaN(p)?-1:p/1e3)}function Yv(p,d,h,g,E,T,P){return n?Ue(16,1,p,d,h,g,E,T,P):-52}function Kv(p,d,h,g,E,T){if(n)return Ue(17,1,p,d,h,g,E,T)}var io={},QS=()=>performance.timeOrigin+performance.now();function Qv(p,d){if(n)return Ue(18,1,p,d);if(io[p]&&(clearTimeout(io[p].id),delete io[p]),!d)return 0;var h=setTimeout(()=>{delete io[p],St(()=>Tk(p,performance.timeOrigin+performance.now()))},d);return io[p]={id:h,Ae:d},0}function JS(p,d,h,g){p>>>=0,d>>>=0,h>>>=0,g>>>=0;var E=new Date().getFullYear(),T=new Date(E,0,1).getTimezoneOffset();E=new Date(E,6,1).getTimezoneOffset();var P=Math.max(T,E);(v(),C)[p>>>2>>>0]=60*P,(v(),$)[d>>>2>>>0]=+(T!=E),p=(d=z=>{var j=Math.abs(z);return`UTC${0<=z?"-":"+"}${String(Math.floor(j/60)).padStart(2,"0")}${String(j%60).padStart(2,"0")}`})(T),d=d(E),EDate.now(),eO=1;function tO(p,d,h){if(h>>>=0,!(0<=p&&3>=p))return 28;if(p===0)p=Date.now();else{if(!eO)return 52;p=performance.timeOrigin+performance.now()}return p=Math.round(1e6*p),(v(),L)[h>>>3>>>0]=BigInt(p),0}var df=[],Jv=(p,d)=>{df.length=0;for(var h;h=(v(),X)[p++>>>0];){var g=h!=105;d+=(g&=h!=112)&&d%8?4:0,df.push(h==112?(v(),C)[d>>>2>>>0]:h==106?(v(),L)[d>>>3>>>0]:h==105?(v(),$)[d>>>2>>>0]:(v(),K)[d>>>3>>>0]),d+=g?8:4}return df};function rO(p,d,h){return p>>>=0,d=Jv(d>>>0,h>>>0),Sf[p](...d)}function sO(p,d,h){return p>>>=0,d=Jv(d>>>0,h>>>0),Sf[p](...d)}var nO=()=>{};function oO(p,d){return M(tn(p>>>0,d>>>0))}var aO=()=>{throw Oe+=1,"unwind"};function iO(){return 4294901760}var lO=()=>1,cO=()=>navigator.hardwareConcurrency;function uO(p){p>>>=0;var d=(v(),X).length;if(p<=d||4294901760=h;h*=2){var g=d*(1+.2/h);g=Math.min(g,p+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(p,g)/65536))-Ir.buffer.byteLength+65535)/65536|0;try{Ir.grow(g),le();var E=1;break e}catch{}E=void 0}if(E)return!0}return!1}var ir=p=>{var d=wr(p)+1,h=sc(d);return gr(p,h,d),h},mf=(p,d)=>{(v(),C)[p>>>2>>>0]=d;var h=(v(),C)[p>>>2>>>0];(v(),C)[p+4>>>2>>>0]=(d-h)/4294967296},lo=p=>(v(),C)[p>>>2>>>0]+4294967296*(v(),$)[p+4>>>2>>>0],ht=[],pO=(p,d)=>{ht[p>>>0]=d},xr=[],ec=[],sn=(p,d)=>{ec[p]=new Promise(h=>d.finally(()=>h(p)))},oe=p=>{if(p)return ht[p>>>0]},fO=(p,d)=>{for(p=(v(),C)[p>>>2>>>0];p;p=(v(),C)[p>>>2>>>0])d[(v(),$)[p+4>>>2>>>0]](p)},tc=(p,d,h)=>{(v(),C)[p>>>2>>>0]=d,(v(),C)[p+4>>>2>>>0]=h},Zv=p=>{var d=(v(),C)[p>>>2>>>0];return p=(v(),C)[p+4>>>2>>>0],tn(d,p)},yr=p=>{var d=(v(),C)[p>>>2>>>0];return p=(v(),C)[p+4>>>2>>>0],d?tn(d,p):p===0?"":void 0},dO=p=>{var d=yr(p+4),h=(h=(v(),C)[p+12>>>2>>>0])?oe(h):"auto";if(p+=16){var g=oe((v(),C)[p+4>>>2>>>0]),E=(v(),C)[p+16>>>2>>>0],T=(v(),C)[p+20>>>2>>>0];if(E){for(var P={},z=0;z>>3>>>0]}E=P}else E=void 0;p={module:g,constants:E,entryPoint:yr(p+8)}}else p=void 0;return{label:d,layout:h,compute:p}},ek=(p,d)=>{function h(g,E){g=p[g],(v(),C)[d+E>>>2>>>0]=g}h("maxTextureDimension1D",4),h("maxTextureDimension2D",8),h("maxTextureDimension3D",12),h("maxTextureArrayLayers",16),h("maxBindGroups",20),h("maxBindGroupsPlusVertexBuffers",24),h("maxBindingsPerBindGroup",28),h("maxDynamicUniformBuffersPerPipelineLayout",32),h("maxDynamicStorageBuffersPerPipelineLayout",36),h("maxSampledTexturesPerShaderStage",40),h("maxSamplersPerShaderStage",44),h("maxStorageBuffersPerShaderStage",48),h("maxStorageTexturesPerShaderStage",52),h("maxUniformBuffersPerShaderStage",56),h("minUniformBufferOffsetAlignment",80),h("minStorageBufferOffsetAlignment",84),mf(d+64,p.maxUniformBufferBindingSize),mf(d+72,p.maxStorageBufferBindingSize),h("maxVertexBuffers",88),mf(d+96,p.maxBufferSize),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),p.ze!==void 0&&h("maxImmediateSize",148)},mO=[,"validation","out-of-memory","internal"],_O=[,"compatibility","core"],tk={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},hO=[,"low-power","high-performance"],gO=[,"occlusion","timestamp"],wO={undefined:1,unknown:1,destroyed:2};function xO(p,d,h,g,E,T){d=_t(d),h=_t(h),g>>>=0,E>>>=0,T>>>=0;var P=oe(p>>>0);if(p={},T){var z=(v(),C)[T+12>>>2>>>0];if(z){var j=(v(),C)[T+16>>>2>>>0];p.requiredFeatures=Array.from((v(),C).subarray(j>>>2>>>0,j+4*z>>>2>>>0),ae=>tk[ae])}var Z=(v(),C)[T+20>>>2>>>0];if(Z){let ae=function(Ot,pt,ms=!1){pt=Z+pt,(pt=(v(),C)[pt>>>2>>>0])==4294967295||ms&&pt==0||(Fe[Ot]=pt)},ut=function(Ot,pt){pt=Z+pt;var ms=(v(),C)[pt>>>2>>>0],qI=(v(),C)[pt+4>>>2>>>0];ms==4294967295&&qI==4294967295||(Fe[Ot]=lo(pt))};var Ie=ae,Ne=ut,Fe={};ae("maxTextureDimension1D",4),ae("maxTextureDimension2D",8),ae("maxTextureDimension3D",12),ae("maxTextureArrayLayers",16),ae("maxBindGroups",20),ae("maxBindGroupsPlusVertexBuffers",24),ae("maxDynamicUniformBuffersPerPipelineLayout",32),ae("maxDynamicStorageBuffersPerPipelineLayout",36),ae("maxSampledTexturesPerShaderStage",40),ae("maxSamplersPerShaderStage",44),ae("maxStorageBuffersPerShaderStage",48),ae("maxStorageTexturesPerShaderStage",52),ae("maxUniformBuffersPerShaderStage",56),ae("minUniformBufferOffsetAlignment",80),ae("minStorageBufferOffsetAlignment",84),ut("maxUniformBufferBindingSize",64),ut("maxStorageBufferBindingSize",72),ae("maxVertexBuffers",88),ut("maxBufferSize",96),ae("maxVertexAttributes",104),ae("maxVertexBufferArrayStride",108),ae("maxInterStageShaderVariables",112),ae("maxColorAttachments",116),ae("maxColorAttachmentBytesPerSample",120),ae("maxComputeWorkgroupStorageSize",124),ae("maxComputeInvocationsPerWorkgroup",128),ae("maxComputeWorkgroupSizeX",132),ae("maxComputeWorkgroupSizeY",136),ae("maxComputeWorkgroupSizeZ",140),ae("maxComputeWorkgroupsPerDimension",144),ae("maxImmediateSize",148,!0),p.requiredLimits=Fe}(z=(v(),C)[T+24>>>2>>>0])&&(z={label:yr(z+4)},p.defaultQueue=z),p.label=yr(T+4)}Oe+=1,sn(d,P.requestDevice(p).then(ae=>{--Oe,St(()=>{ht[E>>>0]=ae.queue,ht[g>>>0]=ae,Oe+=1,sn(h,ae.lost.then(ut=>{St(()=>{ae.onuncapturederror=()=>{};var Ot=fe(),pt=ir(ut.message);xf(h,wO[ut.reason],pt),pe(Ot)}),--Oe})),ae.onuncapturederror=ut=>{var Ot=5;ut.error instanceof GPUValidationError?Ot=2:ut.error instanceof GPUOutOfMemoryError?Ot=3:ut.error instanceof GPUInternalError&&(Ot=4);var pt=fe();ut=ir(ut.error.message),vk(g,Ot,ut),pe(pt)},"adapterInfo"in ae||(ae.adapterInfo=P.info),vf(d,1,g,0)})},ae=>{--Oe,St(()=>{var ut=fe(),Ot=ir(ae.message);vf(d,3,g,Ot),h&&xf(h,4,Ot),pe(ut)})}))}function yO(p){var d=oe(p>>>=0),h=xr[p];if(h){for(var g=0;g>>=0;var g=oe(p>>>=0);h==4294967295&&(h=void 0);try{var E=g.getMappedRange(d>>>0,h)}catch{return 0}var T=Af(16,E.byteLength);return(v(),X).set(new Uint8Array(E),T>>>0),xr[p].push(()=>Xt(T)),T}function vO(p,d,h){h>>>=0;var g=oe(p>>>=0);h==4294967295&&(h=void 0);try{var E=g.getMappedRange(d>>>0,h)}catch{return 0}var T=Af(16,E.byteLength);return(v(),X).fill(0,T,E.byteLength),xr[p].push(()=>{new Uint8Array(E).set((v(),X).subarray(T>>>0,T+E.byteLength>>>0)),Xt(T)}),T}function kO(p,d,h,g,E){p>>>=0,d=_t(d),h=_t(h),E>>>=0;var T=oe(p);xr[p]=[],E==4294967295&&(E=void 0),Oe+=1,sn(d,T.mapAsync(h,g>>>0,E).then(()=>{--Oe,St(()=>{yf(d,1,0)})},P=>{--Oe,St(()=>{fe();var z=ir(P.message);yf(d,P.name==="AbortError"?4:P.name==="OperationError"?3:0,z),delete xr[p]})}))}function EO(p){var d=oe(p>>>=0),h=xr[p];if(h){for(var g=0;g>>0]}function TO(p,d,h){p>>>=0,d>>>=0,h>>>=0;var g=!!(v(),C)[d+32>>>2>>>0];d={label:yr(d+4),usage:(v(),C)[d+16>>>2>>>0],size:lo(d+24),mappedAtCreation:g},p=oe(p);try{var E=p.createBuffer(d)}catch{return!1}return ht[h>>>0]=E,g&&(xr[h]=[]),!0}function MO(p,d,h,g){p>>>=0,d=_t(d),g>>>=0,h=dO(h>>>0),p=oe(p),Oe+=1,sn(d,p.createComputePipelineAsync(h).then(E=>{--Oe,St(()=>{ht[g>>>0]=E,wf(d,1,g,0)})},E=>{--Oe,St(()=>{var T=fe(),P=ir(E.message);wf(d,E.reason==="validation"?3:E.reason==="internal"?4:0,g,P),pe(T)})}))}function SO(p,d,h){p>>>=0,d>>>=0,h>>>=0;var g=(v(),C)[d>>>2>>>0],E=(v(),$)[g+4>>>2>>>0];d={label:yr(d+4),code:""},E===2&&(d.code=Zv(g+8)),p=oe(p).createShaderModule(d),ht[h>>>0]=p}var OO=p=>{(p=oe(p)).onuncapturederror=null,p.destroy()};function IO(p,d){d=_t(d),p=oe(p>>>0),Oe+=1,sn(d,p.popErrorScope().then(h=>{--Oe,St(()=>{var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var E=fe(),T=h?ir(h.message):0;bf(d,1,g,T),pe(E)})},h=>{--Oe,St(()=>{var g=fe(),E=ir(h.message);bf(d,1,5,E),pe(g)})}))}function CO(p,d,h,g){if(d=_t(d),g>>>=0,h>>>=0){var E={featureLevel:_O[(v(),$)[h+4>>>2>>>0]],powerPreference:hO[(v(),$)[h+8>>>2>>>0]],forceFallbackAdapter:!!(v(),C)[h+12>>>2>>>0]};(p=(v(),C)[h>>>2>>>0])!==0&&(v(),E.De=!!(v(),C)[p+8>>>2>>>0])}"gpu"in navigator?(Oe+=1,sn(d,navigator.gpu.requestAdapter(E).then(T=>{--Oe,St(()=>{if(T)ht[g>>>0]=T,co(d,1,g,0);else{var P=fe(),z=ir("WebGPU not available on this browser (requestAdapter returned null)");co(d,3,g,z),pe(P)}})},T=>{--Oe,St(()=>{var P=fe(),z=ir(T.message);co(d,4,g,z),pe(P)})}))):(E=fe(),p=ir("WebGPU not available on this browser (navigator.gpu is not available)"),co(d,3,g,p),pe(E))}function PO(p,d,h){return p>>>=0,d>>>=0,h>>>=0,qv(async()=>{var g=[];if(h){var E=(v(),$)[h>>>2>>>0];g.length=d+1,g[d]=new Promise(z=>setTimeout(z,E,0))}else g.length=d;for(var T=0;T{if(!_f){var p,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(p in hf)hf[p]===void 0?delete d[p]:d[p]=hf[p];var h=[];for(p in d)h.push(`${p}=${d[p]}`);_f=h}return _f};function sk(p,d){if(n)return Ue(19,1,p,d);p>>>=0,d>>>=0;var h,g=0,E=0;for(h of rk()){var T=d+g;(v(),C)[p+E>>>2>>>0]=T,g+=gr(h,T,1/0)+1,E+=4}return 0}function nk(p,d){if(n)return Ue(20,1,p,d);p>>>=0,d>>>=0;var h=rk();for(var g of((v(),C)[p>>>2>>>0]=h.length,p=0,h))p+=wr(g)+1;return(v(),C)[d>>>2>>>0]=p,0}function ok(p){return n?Ue(21,1,p):52}function ak(p,d,h,g){return n?Ue(22,1,p,d,h,g):52}function ik(p,d,h,g){return n?Ue(23,1,p,d,h,g):70}var LO=[null,[],[]];function lk(p,d,h,g){if(n)return Ue(24,1,p,d,h,g);d>>>=0,h>>>=0,g>>>=0;for(var E=0,T=0;T>>2>>>0],z=(v(),C)[d+4>>>2>>>0];d+=8;for(var j=0;j>>0],Ne=LO[Z];Ie===0||Ie===10?((Z===1?S:M)(Ev(Ne)),Ne.length=0):Ne.push(Ie)}E+=z}return(v(),C)[g>>>2>>>0]=E,0}function zO(p){return p>>>0}function NO(p,d){return ek(oe(p>>>0).limits,d>>>0),1}function RO(p,d){return oe(p>>>0).features.has(tk[d])}function $O(p){return BigInt(oe(p>>>0).size)}function DO(p){return BigInt(oe(p>>>0).usage)}function BO(p,d){if(p>>>=0,d>>>=0){var h=yr(d+4);h={label:h,timestampWrites:d=(d=(v(),C)[d+12>>>2>>>0])!==0?{querySet:oe((v(),C)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(v(),C)[d+8>>>2>>>0],endOfPassWriteIndex:(v(),C)[d+12>>>2>>>0]}:void 0}}return d=oe(p),p=gk(0),h=d.beginComputePass(h),ht[p>>>0]=h,p}function UO(p,d,h,g){h=_t(h),(g=_t(g))==-1&&(g=void 0),(p=oe(p>>>0)).clearBuffer(oe(d>>>0),h,g)}function FO(p,d,h,g,E,T){h=_t(h),E=_t(E),T=_t(T),oe(p>>>0).copyBufferToBuffer(oe(d>>>0),h,oe(g>>>0),E,T)}function GO(p){var d=oe(p>>>0);return p=_k(0),d=d.finish(),ht[p>>>0]=d,p}function jO(p,d,h,g,E,T){T=_t(T),oe(p>>>0).resolveQuerySet(oe(d>>>0),h,g,oe(E>>>0),T)}function qO(p,d,h,g){oe(p>>>0).dispatchWorkgroups(d,h,g)}function WO(p,d,h){h=_t(h),oe(p>>>0).dispatchWorkgroupsIndirect(oe(d>>>0),h)}function VO(p){oe(p>>>0).end()}function HO(p,d,h,g,E){g>>>=0,E>>>=0,p=oe(p>>>0),h=oe(h>>>0),g==0?p.setBindGroup(d,h):p.setBindGroup(d,h,(v(),C),E>>>2,g)}function XO(p,d){oe(p>>>0).setPipeline(oe(d>>>0))}function YO(p,d,h){oe(p>>>0).Ce(oe(d>>>0),h)}function KO(p,d){var h=oe(p>>>0);return p=mk(0),d=h.getBindGroupLayout(d),ht[p>>>0]=d,p}function QO(p,d){function h(E){var T=(v(),C)[E+8>>>2>>>0],P=(v(),C)[E+32>>>2>>>0],z=(v(),C)[E+36>>>2>>>0],j=0;return fO(E,{327681:Z=>{j=(v(),C)[Z+8>>>2>>>0]}}),T?((P=lo(E+24))==-1&&(P=void 0),T={buffer:oe(T),offset:lo(E+16),size:P}):T=oe(P||z||j),{binding:(v(),C)[E+4>>>2>>>0],resource:T}}p>>>=0,d={label:yr(4+(d>>>=0)),layout:oe((v(),C)[d+12>>>2>>>0]),entries:(function(E,T){for(var P=[],z=0;z>>2>>>0],(v(),C)[d+20>>>2>>>0])},p=oe(p);var g=dk(0);return pO(g,p.createBindGroup(d)),g}function JO(p,d){var h;return p>>>=0,(d>>>=0)&&(h={label:yr(d+4)}),d=oe(p),p=hk(0),h=d.createCommandEncoder(h),ht[p>>>0]=h,p}function ZO(p,d){p>>>=0,d>>>=0,d={type:gO[(v(),$)[d+12>>>2>>>0]],count:(v(),C)[d+16>>>2>>>0]};var h=oe(p);return p=wk(0),d=h.createQuerySet(d),ht[p>>>0]=d,p}function eI(p,d){p=oe(p>>>0).adapterInfo,d>>>=0,(v(),C)[d+52>>>2>>>0]=p.subgroupMinSize,(v(),C)[d+56>>>2>>>0]=p.subgroupMaxSize;var h=p.vendor+p.architecture+p.device+p.description,g=wr(h)+1,E=nn(g);return E&&gr(h,E,g),h=E,g=wr(p.vendor),tc(d+4,h,g),h+=g,g=wr(p.architecture),tc(d+12,h,g),h+=g,g=wr(p.device),tc(d+20,h,g),tc(d+28,h+g,wr(p.description)),(v(),$)[d+36>>>2>>>0]=2,p=p.isFallbackAdapter?3:4,(v(),$)[d+40>>>2>>>0]=p,(v(),C)[d+44>>>2>>>0]=0,(v(),C)[d+48>>>2>>>0]=0,1}var tI={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function rI(p,d){d>>>=0;var h=oe(p>>>0);p=nn(4*h.features.size);var g=0,E=0;for(let T of h.features)0<=(h=tI[T])&&((v(),$)[p+g>>>2>>>0]=h,g+=4,E++);(v(),C)[d+4>>>2>>>0]=p,(v(),C)[d>>>2>>>0]=E}function sI(p,d){return ek(oe(p>>>0).limits,d>>>0),1}function nI(p,d){oe(p>>>0).pushErrorScope(mO[d])}function oI(p,d,h){d>>>=0,h>>>=0,p=oe(p>>>0),d=Array.from((v(),$).subarray(h>>>2>>>0,h+4*d>>>2>>>0),g=>oe(g)),p.submit(d)}function aI(p,d,h,g,E){h=_t(h),g>>>=0,E>>>=0,p=oe(p>>>0),d=oe(d>>>0),g=(v(),X).subarray(g>>>0,g+E>>>0),p.writeBuffer(d,h,g,0,E)}n||(function(){for(var p=e.numThreads-1;p--;)gv();Be.push(async()=>{var d=(async function(){if(!n)return Promise.all(Or.map(hv))})();Se++,await d,--Se==0&&rt&&(d=rt,rt=null,d())})})(),n||(Ir=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),le()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>fe(),e.stackRestore=p=>pe(p),e.stackAlloc=p=>sc(p),e.setValue=function(p,d,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(v(),F)[p>>>0]=d;break;case"i16":(v(),Y)[p>>>1>>>0]=d;break;case"i32":(v(),$)[p>>>2>>>0]=d;break;case"i64":(v(),L)[p>>>3>>>0]=BigInt(d);break;case"float":(v(),se)[p>>>2>>>0]=d;break;case"double":(v(),K)[p>>>3>>>0]=d;break;case"*":(v(),C)[p>>>2>>>0]=d;break;default:ce(`invalid type for setValue: ${h}`)}},e.getValue=function(p,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(v(),F)[p>>>0];case"i16":return(v(),Y)[p>>>1>>>0];case"i32":return(v(),$)[p>>>2>>>0];case"i64":return(v(),L)[p>>>3>>>0];case"float":return(v(),se)[p>>>2>>>0];case"double":return(v(),K)[p>>>3>>>0];case"*":return(v(),C)[p>>>2>>>0];default:ce(`invalid type for getValue: ${d}`)}},e.UTF8ToString=tn,e.stringToUTF8=gr,e.lengthBytesUTF8=wr;var ck,uk,gf,rc,Xt,nn,pk,fk,dk,mk,_k,hk,gk,wk,xk,yk,bk,wf,xf,yf,bf,co,vf,vk,kf,kk,Ek,Ak,Ef,Tk,Mk,Af,xe,uo,Sk,pe,sc,fe,Ok,Tf,Ik,Ck,Pk,Mf,Lk,zk,Nk,Rk,$k,Dk,Bk,Uk,Fk,Gk,jk,qk,Wk,Vk,Hk,Xk,Yk,Kk,Qk,Jk,Zk,eE,tE,rE,sE,nE,oE,aE,iE,lE,cE,uE,pE,fE,dE,mE,_E,hE,br,iI=[Js,oo,yv,Av,Tv,Mv,Sv,Ov,Iv,Cv,Pv,Lv,zv,Nv,Rv,$v,Yv,Kv,Qv,sk,nk,ok,ak,ik,lk],Sf={970348:(p,d,h,g,E)=>{if(e===void 0||!e.Uc)return 1;if((p=tn(Number(p>>>0))).startsWith("./")&&(p=p.substring(2)),!(p=e.Uc.get(p)))return 2;if(d=Number(d>>>0),h=Number(h>>>0),g=Number(g>>>0),d+h>p.byteLength)return 3;try{let T=p.subarray(d,d+h);switch(E){case 0:(v(),X).set(T,g>>>0);break;case 1:e.ad?e.ad(g,T):e.ne(g,T);break;default:return 4}return 0}catch{return 4}},971172:(p,d,h)=>{e.Sd(p,(v(),X).subarray(d>>>0,d+h>>>0))},971236:()=>e.le(),971278:p=>{e.jd(p)},971315:()=>typeof wasmOffsetConverter<"u"};function lI(p,d,h,g){var E=fe();try{return Uk(p,d,h,g)}catch(T){if(pe(E),T!==T+0)throw T;xe(1,0)}}function cI(p,d,h){var g=fe();try{return $k(p,d,h)}catch(E){if(pe(g),E!==E+0)throw E;xe(1,0)}}function uI(p){var d=fe();try{Lk(p)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function pI(p,d){var h=fe();try{return Mf(p,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function fI(p,d,h){var g=fe();try{Pk(p,d,h)}catch(E){if(pe(g),E!==E+0)throw E;xe(1,0)}}function dI(p,d){var h=fe();try{Fk(p,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function mI(p,d,h,g,E,T,P){var z=fe();try{return Rk(p,d,h,g,E,T,P)}catch(j){if(pe(z),j!==j+0)throw j;xe(1,0)}}function _I(p,d,h,g,E,T){var P=fe();try{zk(p,d,h,g,E,T)}catch(z){if(pe(P),z!==z+0)throw z;xe(1,0)}}function hI(p,d,h,g){var E=fe();try{Bk(p,d,h,g)}catch(T){if(pe(E),T!==T+0)throw T;xe(1,0)}}function gI(p,d,h,g,E,T,P){var z=fe();try{jk(p,d,h,g,E,T,P)}catch(j){if(pe(z),j!==j+0)throw j;xe(1,0)}}function wI(p,d,h,g,E,T,P){var z=fe();try{qk(p,d,h,g,E,T,P)}catch(j){if(pe(z),j!==j+0)throw j;xe(1,0)}}function xI(p,d,h,g,E,T,P,z){var j=fe();try{Zk(p,d,h,g,E,T,P,z)}catch(Z){if(pe(j),Z!==Z+0)throw Z;xe(1,0)}}function yI(p,d,h,g,E,T,P,z,j,Z,Ie,Ne){var Fe=fe();try{Wk(p,d,h,g,E,T,P,z,j,Z,Ie,Ne)}catch(ae){if(pe(Fe),ae!==ae+0)throw ae;xe(1,0)}}function bI(p,d,h,g,E){var T=fe();try{return Gk(p,d,h,g,E)}catch(P){if(pe(T),P!==P+0)throw P;xe(1,0)}}function vI(p,d,h,g,E){var T=fe();try{Nk(p,d,h,g,E)}catch(P){if(pe(T),P!==P+0)throw P;xe(1,0)}}function kI(p,d,h,g,E,T,P,z){var j=fe();try{Dk(p,d,h,g,E,T,P,z)}catch(Z){if(pe(j),Z!==Z+0)throw Z;xe(1,0)}}function EI(p){var d=fe();try{return eE(p)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function AI(p,d,h){var g=fe();try{return tE(p,d,h)}catch(E){if(pe(g),E!==E+0)throw E;xe(1,0)}}function TI(p,d){var h=fe();try{return fE(p,d)}catch(g){if(pe(h),g!==g+0)throw g;return xe(1,0),0n}}function MI(p){var d=fe();try{return Vk(p)}catch(h){if(pe(d),h!==h+0)throw h;return xe(1,0),0n}}function SI(p,d,h,g){var E=fe();try{return rE(p,d,h,g)}catch(T){if(pe(E),T!==T+0)throw T;xe(1,0)}}function OI(p,d,h,g,E){var T=fe();try{return sE(p,d,h,g,E)}catch(P){if(pe(T),P!==P+0)throw P;xe(1,0)}}function II(p,d,h,g,E,T){var P=fe();try{return nE(p,d,h,g,E,T)}catch(z){if(pe(P),z!==z+0)throw z;xe(1,0)}}function CI(p,d,h,g,E,T){var P=fe();try{return Qk(p,d,h,g,E,T)}catch(z){if(pe(P),z!==z+0)throw z;xe(1,0)}}function PI(p,d,h,g,E,T){var P=fe();try{return oE(p,d,h,g,E,T)}catch(z){if(pe(P),z!==z+0)throw z;xe(1,0)}}function LI(p,d,h,g,E,T,P,z){var j=fe();try{return Jk(p,d,h,g,E,T,P,z)}catch(Z){if(pe(j),Z!==Z+0)throw Z;xe(1,0)}}function zI(p,d,h,g,E){var T=fe();try{return aE(p,d,h,g,E)}catch(P){if(pe(T),P!==P+0)throw P;return xe(1,0),0n}}function NI(p,d,h,g){var E=fe();try{return iE(p,d,h,g)}catch(T){if(pe(E),T!==T+0)throw T;xe(1,0)}}function RI(p,d,h,g){var E=fe();try{return lE(p,d,h,g)}catch(T){if(pe(E),T!==T+0)throw T;xe(1,0)}}function $I(p,d,h,g,E,T,P,z,j,Z,Ie,Ne){var Fe=fe();try{return cE(p,d,h,g,E,T,P,z,j,Z,Ie,Ne)}catch(ae){if(pe(Fe),ae!==ae+0)throw ae;xe(1,0)}}function DI(p,d,h,g,E,T,P,z,j,Z,Ie){var Ne=fe();try{uE(p,d,h,g,E,T,P,z,j,Z,Ie)}catch(Fe){if(pe(Ne),Fe!==Fe+0)throw Fe;xe(1,0)}}function BI(p,d,h,g,E,T,P,z,j,Z,Ie,Ne,Fe,ae,ut,Ot){var pt=fe();try{pE(p,d,h,g,E,T,P,z,j,Z,Ie,Ne,Fe,ae,ut,Ot)}catch(ms){if(pe(pt),ms!==ms+0)throw ms;xe(1,0)}}function UI(p,d,h){var g=fe();try{return Xk(p,d,h)}catch(E){if(pe(g),E!==E+0)throw E;return xe(1,0),0n}}function FI(p,d,h){var g=fe();try{return Hk(p,d,h)}catch(E){if(pe(g),E!==E+0)throw E;xe(1,0)}}function GI(p,d,h){var g=fe();try{return Yk(p,d,h)}catch(E){if(pe(g),E!==E+0)throw E;xe(1,0)}}function jI(p,d,h,g){var E=fe();try{Kk(p,d,h,g)}catch(T){if(pe(E),T!==T+0)throw T;xe(1,0)}}function nc(){if(0{let d=new WeakMap,h,g,E=1;e.webgpuRegisterDevice=z=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(z){var j=d.get(z);if(!j){let Z=((Ie,Ne=0)=>{var Fe=bk(Ne);return Ne=yk(Ne,Fe),ht[Fe>>>0]=Ie.queue,ht[Ne>>>0]=Ie,Ne})(z,j=fk(0));j=[E++,j,Z],d.set(z,j)}return h=z,g=j[0],j}h=void 0,g=0};let T=new Map;e.webgpuOnCreateSession=z=>{if(g!==void 0){var j=g;if(g=void 0,z){let Z=gf(j);T.set(z,Z),j===0&&p(h??oe(Z))}h=void 0}},e.webgpuOnReleaseSession=z=>{T.delete(z)};let P=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(z,j,Z)=>{if(Z)return z[P]=[Z,NaN],Z;if(Z=z[P])return Z[1]++,Z[0];if((j=T.get(j))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return j=((Ie,Ne=0)=>(Ie.mapState==="unmapped"||ce(),Ne=xk(Ne),ht[Ne>>>0]=Ie,Ne))(z,j),z[P]=[j,1],j},e.webgpuUnregisterBuffer=z=>{let j=z[P];if(!j)throw Error("Buffer is not registered");j[1]--,j[1]===0&&(pk(j[0]),delete z[P])},e.webgpuGetBuffer=z=>oe(z),e.webgpuCreateDownloader=(z,j,Z)=>{if((Z=T.get(Z))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Ie=oe(Z),Ne=16*Math.ceil(Number(j)/16);return async()=>{let Fe=Ie.createBuffer({size:Ne,usage:9});try{let ae=Ie.createCommandEncoder();return ae.copyBufferToBuffer(z,0,Fe,0,Ne),Ie.queue.submit([ae.finish()]),await Fe.mapAsync(GPUMapMode.READ),Fe.getMappedRange().slice(0,j)}finally{Fe.destroy()}}},e.ad=(z,j)=>{var Z=j.buffer;let Ie=j.byteOffset,Ne=j.byteLength;if(j=16*Math.ceil(Number(Ne)/16),z=oe(z),!h){var Fe=gf(g);h=oe(Fe)}let ae=(Fe=h.createBuffer({mappedAtCreation:!0,size:j,usage:6})).getMappedRange();new Uint8Array(ae).set(new Uint8Array(Z,Ie,Ne)),Fe.unmap(),(Z=h.createCommandEncoder()).copyBufferToBuffer(Fe,0,z,0,j),h.queue.submit([Z.finish()]),Fe.destroy()}},e.webnnInit=p=>{let d=p[0];[e.le,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.ke,e.webnnEnableTraceEvent]=p.slice(1),e.webnnReleaseTensorId=e.jd,e.webnnUploadTensor=e.Sd,e.webnnRegisterMLContext=e.ke,e.webnnOnRunStart=h=>d.onRunStart(h),e.webnnOnRunEnd=d.onRunEnd.bind(d),e.webnnOnReleaseSession=h=>{d.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>d.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,E,T)=>d.registerMLTensor(h,g,E,T),e.webnnCreateMLContext=h=>d.createMLContext(h),e.webnnRegisterMLConstant=(h,g,E,T,P,z)=>d.registerMLConstant(h,g,E,T,P,e.Uc,z),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},Q?e:new Promise((p,d)=>{w=p,x=d})}var _2,vA,Dz=be(()=>{"use strict";_2=bA,vA=globalThis.self?.name?.startsWith("em-pthread"),vA&&bA()}),Qf,dd,kA,zt,h2,yc,EA,AA,Jf,TA,Zf,g2,ed,w2,vd=be(()=>{"use strict";bd(),Qf=typeof location>"u"?void 0:location.origin,dd=import.meta.url>"file:"&&import.meta.url<"file;",kA=()=>{if(dd){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Qf).href}return import.meta.url},zt=kA(),h2=()=>{if(zt&&!zt.startsWith("blob:"))return zt.substring(0,zt.lastIndexOf("/")+1)},yc=(t,e)=>{try{let r=e??zt;return(r?new URL(t,r):new URL(t)).origin===Qf}catch{return!1}},EA=(t,e)=>{let r=e??zt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},AA=(t,e)=>`${e??"./"}${t}`,Jf=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},TA=async t=>(await import(t)).default,Zf=($z(),Tc(f2)).default,g2=async()=>{if(!zt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(yc(zt))return[void 0,Zf()];let t=await Jf(zt);return[t,Zf(t)]},ed=(Dz(),Tc(m2)).default,w2=async(t,e,r,s)=>{let n=ed&&!(t||e);if(n)if(zt)n=yc(zt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,ed];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??EA(o,e),i=r&&a&&!yc(a,e),l=i?await Jf(a):a??AA(o,e);return[i?l:void 0,await TA(l)]}}}),td,bc,ko,rd,MA,SA,OA,kd,De,Is=be(()=>{"use strict";vd(),bc=!1,ko=!1,rd=!1,MA=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},SA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},OA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},kd=async t=>{if(bc)return Promise.resolve();if(ko)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(rd)throw new Error("previous call to 'initializeWebAssembly()' failed.");ko=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!OA())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!SA())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=MA();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,u=t.wasmBinary,[f,m]=await w2(i,o,r>1,!!u||!!c),_=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{_=!0,x()},e)})),w.push(new Promise((x,b)=>{let A={numThreads:r};if(u)A.wasmBinary=u,A.locateFile=k=>k;else if(c||o)A.locateFile=k=>c??o+k;else if(i&&i.indexOf("blob:")!==0)A.locateFile=k=>new URL(k,i).href;else if(f){let k=h2();k&&(A.locateFile=S=>k+S)}m(A).then(k=>{ko=!1,bc=!0,td=k,x(),f&&URL.revokeObjectURL(f)},k=>{ko=!1,rd=!0,b(k)})})),await Promise.race(w),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},De=()=>{if(bc&&td)return td;throw new Error("WebAssembly is not initialized yet.")}}),Nt,Sc,Le,Ed=be(()=>{"use strict";Is(),Nt=(t,e)=>{let r=De(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},Sc=(t,e,r,s)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([n,o])=>{let a=e?e+n:n;if(typeof o=="object")Sc(o,a+".",r,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Le=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetLastError(n,n+s);let o=Number(e.getValue(n,s===4?"i32":"i64")),a=e.getValue(n+s,"*"),i=a?e.UTF8ToString(a):"";throw new Error(`${t} ERROR_CODE: ${o}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}}),x2,Bz=be(()=>{"use strict";Is(),Ed(),x2=t=>{let e=De(),r=0,s=[],n=t||{};try{if(t?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(n.terminate=!1);let o=0;return t?.tag!==void 0&&(o=Nt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&Le("Can't create run options."),t?.extra!==void 0&&Sc(t.extra,"",new WeakSet,(a,i)=>{let l=Nt(a,s),c=Nt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&Le(`Can't set a run config entry: ${a} - ${i}.`)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),s.forEach(a=>e._free(a)),o}}}),IA,CA,PA,vc,Br,LA,y2,Uz=be(()=>{"use strict";Is(),Ed(),IA=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},CA=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},PA=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},vc=(t,e,r,s)=>{let n=Nt(e,s),o=Nt(r,s);De()._OrtAddSessionConfigEntry(t,n,o)!==0&&Le(`Can't set a session config entry: ${e} - ${r}.`)},Br=(t,e,r,s)=>{let n=Nt(e,s),o=Nt(r,s);t.push([n,o])},LA=async(t,e,r)=>{let s=e.executionProviders;for(let n of s){let o=typeof n=="string"?n:n.name,a=[];switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let f=n?.deviceType;f&&vc(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let _=n;if(_.device)if(typeof GPUDevice<"u"&&_.device instanceof GPUDevice)f=_.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&Br(a,"enableGraphCapture","1",r),typeof _.preferredLayout=="string"&&Br(a,"preferredLayout",_.preferredLayout,r),_.forceCpuNodeNames){let x=Array.isArray(_.forceCpuNodeNames)?_.forceCpuNodeNames:[_.forceCpuNodeNames];Br(a,"forceCpuNodeNames",x.join(` +-`),r)}_.validationMode&&Br(a,"validationMode",_.validationMode,r)}let m=De().webgpuRegisterDevice(f);if(m){let[_,w,x]=m;Br(a,"deviceId",_.toString(),r),Br(a,"webgpuInstance",w.toString(),r),Br(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=Nt(o,r),l=a.length,c=0,u=0;if(l>0){c=De()._malloc(l*De().PTR_SIZE),r.push(c),u=De()._malloc(l*De().PTR_SIZE),r.push(u);for(let f=0;f{let e=De(),r=0,s=[],n=t||{};PA(n);try{let o=IA(n.graphOptimizationLevel??"all"),a=CA(n.executionMode??"sequential"),i=typeof n.logId=="string"?Nt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let u=typeof n.optimizedModelFilePath=="string"?Nt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,u),r===0&&Le("Can't create session options."),n.executionProviders&&await LA(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);vc(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[f,m]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof m!="number"||!Number.isInteger(m)||m<0)throw new Error(`free dimension override value must be a non-negative integer: ${m}`);let _=Nt(f,s);e._OrtAddFreeDimensionOverride(r,_,m)!==0&&Le(`Can't set a free dimension override: ${f} - ${m}.`)}return n.extra!==void 0&&Sc(n.extra,"",new WeakSet,(f,m)=>{vc(r,f,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Le("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),As,Ac,fn,So,Oc,Ad,Td,md,dn=be(()=>{"use strict";As=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},Ac=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},fn=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],s=typeof e=="number"?e:e.reduce((n,o)=>n*o,1);return r>0?Math.ceil(s*r):void 0},So=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Oc=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},Ad=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Td=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",md=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${t}`)}}}),Md,b2=be(()=>{"use strict";bd(),Md=async t=>{if(typeof t=="string"){let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(o,a,c).set(l),a+=c}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),v2,Fz=be(()=>{"use strict";dn(),v2=(t,e)=>new(So(e))(t)}),zA,NA,RA,$A,k2,DA,vt,E2=be(()=>{"use strict";dn(),zA=["V","I","W","E","F"],NA=(t,e)=>{console.log(`[${zA[t]},${new Date().toISOString()}]${e}`)},k2=(t,e)=>{RA=t,$A=e},DA=(t,e)=>{let r=Oc(t),s=Oc(RA);r>=s&&NA(r,typeof e=="function"?e():e)},vt=(...t)=>{$A&&DA(...t)}}),sd,_d,nd,BA,od,UA,ad,id,ld,FA,A2,Gz=be(()=>{"use strict";dn(),E2(),sd=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),_d=(t,e)=>{if(e==="int32")return t;let r=sd.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);let s=r/8;if(t.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=t.byteLength/s,o=new(So(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(l)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&o.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(o,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},nd=(t,e)=>{if(e==="int32")return t;if(t.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=t.byteLength/4,s=new Int32Array(t.buffer,t.byteOffset,r);switch(e){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(o=>o<-128||o>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${e}`)}},BA=1,od=()=>BA++,UA=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),ad=(t,e)=>{let r=sd.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);return e.length>0?Math.ceil(e.reduce((s,n)=>s*n)*r/8):0},id=class{constructor(t){this.isDataConverted=!1;let{sessionId:e,context:r,tensor:s,dataType:n,shape:o,fallbackDataType:a}=t;this.sessionId=e,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.fallbackDataType=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return ad(this.dataType,this.tensorShape)}destroy(){vt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){if(this.fallbackDataType){let e=await this.mlContext.readTensor(this.mlTensor),r=nd(new Uint8Array(e),this.dataType);if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(r);return}else return r.buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,e,r){return this.mlContext===t&&this.dataType===e&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(t){this.isDataConverted=t}},ld=class{constructor(t,e){this.tensorManager=t,this.wrapper=e}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,e,r,s){let n=this.tensorManager.getMLContext(t),o=this.tensorManager.getMLOpSupportLimits(t),a;if(!o?.input.dataTypes.includes(e)){if(a=UA.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);vt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${e} to ${a}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,e,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==ad(e,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,e,r,i,!0,!0,a),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){let e=t;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")e=_d(t,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else vt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(t){if(this.activeUpload){let e=this.wrapper?.isDataConverted?nd(this.activeUpload,this.wrapper?.type):this.activeUpload;if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(e):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(e);return}else return e.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(t):this.wrapper.read()}},FA=class{constructor(t){this.backend=t,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(t){let e=this.backend.getMLContext(t);if(!e)throw new Error("MLContext not found for session.");return e}getMLOpSupportLimits(t){return this.backend.getMLOpSupportLimits(t)}reserveTensorId(){let t=od();return this.tensorTrackersById.set(t,new ld(this)),t}releaseTensorId(t){let e=this.tensorTrackersById.get(t);e&&(this.tensorTrackersById.delete(t),e.tensorWrapper&&this.releaseTensor(e.tensorWrapper))}async ensureTensor(t,e,r,s,n){vt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,s,n)}upload(t,e){let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");r.upload(e)}async download(t,e){vt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${e?.byteLength}}`);let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");return r.download(e)}releaseTensorsForSession(t){for(let e of this.freeTensors)e.sessionId===t&&e.destroy();this.freeTensors=this.freeTensors.filter(e=>e.sessionId!==t)}registerTensor(t,e,r,s){let n=this.getMLContext(t),o=od(),a=new id({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new ld(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,u]of this.freeTensors.entries())if(u.canReuseTensor(i,e,r)){vt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}vt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:a??e,shape:r,dimensions:r,usage:s,writable:n,readable:o});return new id({sessionId:t,context:i,tensor:l,dataType:e,shape:r,fallbackDataType:a})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},A2=(...t)=>new FA(...t)}),T2={};Oo(T2,{WebNNBackend:()=>M2});var Eo,GA,M2,jz=be(()=>{"use strict";dn(),Is(),Fz(),Gz(),E2(),Eo=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),GA=(t,e)=>{if(t===e)return!0;if(t===void 0||e===void 0)return!1;let r=Object.keys(t).sort(),s=Object.keys(e).sort();return r.length===s.length&&r.every((n,o)=>n===s[o]&&t[n]===e[n])},M2=class{constructor(t){this.tensorManager=A2(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,k2(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){vt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){vt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)vt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(t),this.activeSessionId=void 0}}async createMLContext(t){if(t instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===t);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:s}),s}}else if(t===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let e=this.mlContextCache.findIndex(r=>GA(r.options,t));if(e!==-1)return this.mlContextCache[e].mlContext;{let r=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:r}),r}}registerMLContext(t,e){this.mlContextBySessionId.set(t,e);let r=this.sessionIdsByMLContext.get(e);r||(r=new Set,this.sessionIdsByMLContext.set(e,r)),r.add(t),this.mlOpSupportLimitsBySessionId.has(t)||this.mlOpSupportLimitsBySessionId.set(t,e.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(t,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(t,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(t){this.sessionGraphInputs.delete(t),this.sessionGraphOutputs.delete(t);let e=this.mlContextBySessionId.get(t);if(!e)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t),this.mlOpSupportLimitsBySessionId.delete(t);let r=this.sessionIdsByMLContext.get(e);if(r.delete(t),r.size===0){this.sessionIdsByMLContext.delete(e);let s=this.mlContextCache.findIndex(n=>n.mlContext===e);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}getMLOpSupportLimits(t){return this.mlOpSupportLimitsBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){vt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=Eo.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t??this.currentSessionId,e,o,s,n)}async createTemporaryTensor(t,e,r){vt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=Eo.get(e);if(!s)throw new Error(`Unsupported ONNX data type: ${e}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(t,n,s,r,!1);let o=this.temporarySessionTensorIds.get(t);return o?o.push(n):this.temporarySessionTensorIds.set(t,[n]),n}uploadTensor(t,e){if(!De().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");vt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${e.byteLength}}`),this.tensorManager.upload(t,e)}async downloadTensor(t,e){return this.tensorManager.download(t,e)}createMLTensorDownloader(t,e){return async()=>{let r=await this.tensorManager.download(t);return v2(r,e)}}registerMLTensor(t,e,r,s){let n=Eo.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return vt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(e,e+r).buffer,u;switch(n.dataType){case"float32":u=new Float32Array(c);break;case"float16":u=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":u=new Int32Array(c);break;case"uint32":u=new Uint32Array(c);break;case"int64":if(a){let f=_d(new Uint8Array(c),"int64");u=new Int32Array(f.buffer),n.dataType="int32"}else u=new BigInt64Array(c);break;case"uint64":u=new BigUint64Array(c);break;case"int8":u=new Int8Array(c);break;case"int4":case"uint4":case"uint8":u=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return vt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,u)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=Eo.get(As(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),jA,Sd,Od,Ur,qA,cd,Ic,Id,Cd,ud,Pd,Ld,zd,S2=be(()=>{"use strict";Os(),Bz(),Uz(),dn(),Is(),Ed(),b2(),jA=(t,e)=>{De()._OrtInit(t,e)!==0&&Le("Can't initialize onnxruntime.")},Sd=async t=>{jA(t.wasm.numThreads,Oc(t.logLevel))},Od=async(t,e)=>{De().asyncInit?.();let r=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=t.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let n=t.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(e==="webgpu"&&De().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(jz(),Tc(T2)).WebNNBackend(t);De().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,o,a,i,l)=>s.ensureTensor(n,o,a,i,l),(n,o)=>{s.uploadTensor(n,o)},async(n,o)=>s.downloadTensor(n,o),(n,o)=>s.registerMLContext(n,o),!!t.trace])}},Ur=new Map,qA=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetInputOutputCount(t,n,n+s)!==0&&Le("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(e.getValue(n,o)),Number(e.getValue(n+s,o))]}finally{e.stackRestore(r)}},cd=(t,e)=>{let r=De(),s=r.stackSave(),n=0;try{let o=r.PTR_SIZE,a=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(t,e,a,a+o)!==0&&Le("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],u=[];for(let f=0;f{let e=De(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},Id=async(t,e)=>{let r,s,n=De();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=Ic(t);let o=0,a=0,i=0,l=[],c=[],u=[];try{if([a,l]=await y2(e),e?.externalData&&n.mountExternalData){let M=[];for(let O of e.externalData){let I=typeof O=="string"?O:O.path;M.push(Md(typeof O=="string"?O:O.data).then(v=>{n.mountExternalData(I,v)}))}await Promise.all(M)}for(let M of e?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof M!="string"){let O=M,I=O?.context,v=O?.gpuDevice,B=O?.deviceType,G=O?.powerPreference;I?n.currentContext=I:v?n.currentContext=await n.webnnCreateMLContext(v):n.currentContext=await n.webnnCreateMLContext({deviceType:B,powerPreference:G})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Le("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,m]=qA(o),_=!!e?.enableGraphCapture,w=[],x=[],b=[],A=[],k=[];for(let M=0;MM==="gpu-buffer"||M==="ml-tensor"||M==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&Le("Can't create IO binding."),S={handle:i,outputPreferredLocations:k,outputPreferredLocationsEncoded:k.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>md(M))}),Ur.set(o,[o,c,u,S,_,!1]),[o,w,x,b,A]}catch(f){throw c.forEach(m=>n._OrtFree(m)),u.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&Le("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Le("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Le("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},Cd=t=>{let e=De(),r=Ur.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&Le("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Le("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(l=>e._OrtFree(l)),o.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(s)!==0&&Le("Can't release session."),Ur.delete(t)},ud=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=De(),l=i.PTR_SIZE,c=t[0],u=t[1],f=t[3],m=f,_,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let A=t[2].gpuBuffer;w=fn(As(c),u);{let k=i.webgpuRegisterBuffer;if(!k)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=k(A,s)}}else if(f==="ml-tensor"){let A=t[2].mlTensor;w=fn(As(c),u);let k=i.webnnRegisterMLTensor;if(!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=k(s,A,As(c),u)}else{let A=t[2];if(Array.isArray(A)){w=l*A.length,_=i._malloc(w),r.push(_);for(let k=0;ki.setValue(b+S*l,k,l===4?"i32":"i64"));let A=i._OrtCreateTensor(As(c),_,w,b,u.length,md(m));A===0&&Le(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(A)}finally{i.stackRestore(x)}},Pd=async(t,e,r,s,n,o)=>{let a=De(),i=a.PTR_SIZE,l=Ur.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],u=l[1],f=l[2],m=l[3],_=l[4],w=l[5],x=e.length,b=s.length,A=0,k=[],S=[],M=[],O=[],I=[],v=a.stackSave(),B=a.stackAlloc(x*i),G=a.stackAlloc(x*i),F=a.stackAlloc(b*i),X=a.stackAlloc(b*i);try{[A,k]=x2(o),Gr("wasm prepareInputOutputTensor");for(let C=0;CBe*Se,1);U=Ac(je);let Mt=m?.outputPreferredLocations[s[C]];if(U==="string"){if(Mt==="gpu-buffer"||Mt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Be=[];for(let Se=0;Se0){let Be=a.webgpuGetBuffer;if(!Be)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Se=Be(Q),rt=fn(je,ct);if(rt===void 0||!Ad(U))throw new Error(`Unsupported data type: ${U}`);R=!0;{a.webgpuRegisterBuffer(Se,t,Q);let nr=a.webgpuCreateDownloader(Se,rt,t);J.push([U,qe,{gpuBuffer:Se,download:async()=>{let Oe=await nr();return new(So(U))(Oe)},dispose:()=>{a._OrtReleaseTensor(se)!==0&&Le("Can't release tensor.")}},"gpu-buffer"])}}else if(Mt==="ml-tensor"&&ct>0){let Be=a.webnnEnsureTensor,Se=a.webnnIsGraphInputOutputTypeSupported;if(!Be||!Se)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(fn(je,ct)===void 0||!Td(U))throw new Error(`Unsupported data type: ${U}`);if(!Se(t,U,!1))throw new Error(`preferredLocation "ml-tensor" for ${U} output is not supported by current WebNN Context.`);let rt=await Be(t,Q,je,qe,!1);R=!0,J.push([U,qe,{mlTensor:rt,download:a.webnnCreateMLTensorDownloader(Q,U),dispose:()=>{a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(se)}},"ml-tensor"])}else if(Mt==="ml-tensor-cpu-output"&&ct>0){let Be=a.webnnCreateMLTensorDownloader(Q,U)(),Se=J.length;R=!0,$.push((async()=>{let rt=[Se,await Be];return a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(se),rt})()),J.push([U,qe,[],"cpu"])}else{let Be=So(U),Se=new Be(ct);new Uint8Array(Se.buffer,Se.byteOffset,Se.byteLength).set(a.HEAPU8.subarray(Q,Q+Se.byteLength)),J.push([U,qe,Se,"cpu"])}}finally{a.stackRestore(K),U==="string"&&Q&&a._free(Q),R||a._OrtReleaseTensor(se)}}m&&!_&&(a._OrtClearBoundOutputs(m.handle)!==0&&Le("Can't clear bound outputs."),Ur.set(t,[c,u,f,m,_,!1]));for(let[C,se]of await Promise.all($))J[C][2]=se;return jr("wasm ProcessOutputTensor"),J}finally{a.webnnOnRunEnd?.(c),a.stackRestore(v),r.forEach(Y=>{Y&&Y[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(Y[2].gpuBuffer)}),n.forEach(Y=>{Y&&Y[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(Y[2].gpuBuffer)}),S.forEach(Y=>a._OrtReleaseTensor(Y)),M.forEach(Y=>a._OrtReleaseTensor(Y)),O.forEach(Y=>a._free(Y)),A!==0&&a._OrtReleaseRunOptions(A),k.forEach(Y=>a._free(Y))}},Ld=t=>{let e=De(),r=Ur.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Le("Can't get an profile file name."),e._OrtFree(n)},zd=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Fr,jt,pn,Ao,To,kc,pd,Ec,vs,ks,WA,O2,I2,C2,P2,L2,z2,N2,R2=be(()=>{"use strict";Os(),S2(),Is(),vd(),Fr=()=>!!Ke.wasm.proxy&&typeof document<"u",pn=!1,Ao=!1,To=!1,Ec=new Map,vs=(t,e)=>{let r=Ec.get(t);r?r.push(e):Ec.set(t,[e])},ks=()=>{if(pn||!Ao||To||!jt)throw new Error("worker not ready")},WA=t=>{switch(t.data.type){case"init-wasm":pn=!1,t.data.err?(To=!0,pd[1](t.data.err)):(Ao=!0,pd[0]()),kc&&(URL.revokeObjectURL(kc),kc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Ec.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},O2=async()=>{if(!Ao){if(pn)throw new Error("multiple calls to 'initWasm()' detected.");if(To)throw new Error("previous call to 'initWasm()' failed.");if(pn=!0,Fr())return new Promise((t,e)=>{jt?.terminate(),g2().then(([r,s])=>{try{jt=s,jt.onerror=o=>e(o),jt.onmessage=WA,pd=[t,e];let n={type:"init-wasm",in:Ke};!n.in.wasm.wasmPaths&&(r||dd)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),jt.postMessage(n),kc=r}catch(n){e(n)}},e)});try{await kd(Ke.wasm),await Sd(Ke),Ao=!0}catch(t){throw To=!0,t}finally{pn=!1}}},I2=async t=>{if(Fr())return ks(),new Promise((e,r)=>{vs("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Ke}};jt.postMessage(s)});await Od(Ke,t)},C2=async t=>Fr()?(ks(),new Promise((e,r)=>{vs("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};jt.postMessage(s,[t.buffer])})):Ic(t),P2=async(t,e)=>{if(Fr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ks(),new Promise((r,s)=>{vs("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),jt.postMessage(n,o)})}else return Id(t,e)},L2=async t=>{if(Fr())return ks(),new Promise((e,r)=>{vs("release",[e,r]);let s={type:"release",in:t};jt.postMessage(s)});Cd(t)},z2=async(t,e,r,s,n,o)=>{if(Fr()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return ks(),new Promise((a,i)=>{vs("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};jt.postMessage(c,zd(l))})}else return Pd(t,e,r,s,n,o)},N2=async t=>{if(Fr())return ks(),new Promise((e,r)=>{vs("end-profiling",[e,r]);let s={type:"end-profiling",in:t};jt.postMessage(s)});Ld(t)}}),fd,VA,$2,qz=be(()=>{"use strict";Os(),R2(),dn(),bd(),b2(),fd=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},VA=t=>{switch(t[3]){case"cpu":return new er(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Ad(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return er.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!Td(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return er.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},$2=class{async fetchModelAndCopyToWasmMemory(t){return C2(await Md(t))}async loadModel(t,e){Ms();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await P2(r,e),Ss()}async dispose(){return L2(this.sessionId)}async run(t,e,r){Ms();let s=[],n=[];Object.entries(t).forEach(f=>{let m=f[0],_=f[1],w=this.inputNames.indexOf(m);if(w===-1)throw new Error(`invalid input '${m}'`);s.push(_),n.push(w)});let o=[],a=[];Object.entries(e).forEach(f=>{let m=f[0],_=f[1],w=this.outputNames.indexOf(m);if(w===-1)throw new Error(`invalid output '${m}'`);o.push(_),a.push(w)});let i=s.map((f,m)=>fd(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?fd(f,()=>`output "${this.outputNames[a[m]]}"`):null),c=await z2(this.sessionId,n,i,a,l,r),u={};for(let f=0;fgd,initializeFlags:()=>hd,wasmBackend:()=>B2});var hd,gd,B2,Wz=be(()=>{"use strict";Os(),R2(),qz(),hd=()=>{(typeof Ke.wasm.initTimeout!="number"||Ke.wasm.initTimeout<0)&&(Ke.wasm.initTimeout=0);let t=Ke.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),Ke.wasm.simd=!1),typeof Ke.wasm.proxy!="boolean"&&(Ke.wasm.proxy=!1),typeof Ke.wasm.trace!="boolean"&&(Ke.wasm.trace=!1),typeof Ke.wasm.numThreads!="number"||!Number.isInteger(Ke.wasm.numThreads)||Ke.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Ke.wasm.numThreads=1;else{let e=typeof navigator>"u"?vz("node:os").cpus().length:navigator.hardwareConcurrency;Ke.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},gd=class{async init(t){hd(),await O2(),await I2(t)}async createInferenceSessionHandler(t,e){let r=new $2;return await r.loadModel(t,e),r}},B2=new gd});Os();Os();Os();var Vz="1.26.0-dev.20260416-b7804b056c",Hz=p2;{let t=(Wz(),Tc(D2)).wasmBackend;Ts("webgpu",t,5),Ts("webnn",t,5),Ts("cpu",t,10),Ts("wasm",t,10)}Object.defineProperty(Ke.versions,"web",{value:Vz,enumerable:!0});async function U2(t){let e=t.split("/").pop(),r;try{if(r=await Zt(),r){let n=await r.match(t);if(n)return n}}catch(n){ee.warn(`Failed to load ${e} from cache:`,n)}let s=await _e.fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){ee.warn(`Failed to cache ${e}:`,n)}return s}async function F2(t){let e=await U2(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return ee.warn("Failed to read WASM binary:",r),null}}async function G2(t){if(ie.IS_SERVICE_WORKER_ENV||ie.IS_CHROME_AVAILABLE)return t;let e=await U2(t);if(!e||typeof e=="string")return null;try{let r=await e.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return ee.warn("Failed to read WASM factory:",r),null}}var j2="1.24.3";var q2="warning",Rd={wasm:{},webgl:{},webgpu:{},versions:{common:j2},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);q2=t}},get logLevel(){return q2}};Object.defineProperty(Rd,"logLevel",{enumerable:!0});var W2=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=o*n,f=0,m=u,_=u*2,w=-1;a==="RGBA"?(f=0,m=u,_=u*2,w=u*3):a==="RGB"?(f=0,m=u,_=u*2):a==="RBG"&&(f=0,_=u,m=u*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,u;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,b=3,A=0,k=f,S=f*2,M=-1;i==="RGBA"?(A=0,k=f,S=f*2,M=f*3):i==="RGB"?(A=0,k=f,S=f*2):i==="RBG"&&(A=0,S=f,k=f*2),s=r.createImageData(n,o);for(let O=0;O{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,b=0,A=c,k=c*2,S=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(b=0,k=c,A=c*2):l==="BGR"&&(k=0,A=c,b=c*2);for(let O=0;O{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,_=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=_}else i.tensorFormat="RGBA",i.height=m,i.width=_;f.drawImage(t,0,0),a=f.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let u,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,f=e.resizedWidth):(u=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=u,i.width=f,e!==void 0){let m=l();m.width=f,m.height=u;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,u).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,$d(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((u,f)=>{let m=l(),_=c(m);if(!t||!_)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,_.drawImage(w,0,0,m.width,m.height);let x=_.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,u($d(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return $d(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},X2=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new yt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},Y2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new yt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},K2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new yt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},Q2=(t,e,r)=>new yt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]});var Cs=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Io=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),J2=!1,Z2=()=>{if(!J2){J2=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Cs.set("int64",BigInt64Array),Io.set(BigInt64Array,"int64")),e&&(Cs.set("uint64",BigUint64Array),Io.set(BigUint64Array,"uint64")),s?(Cs.set("float16",r),Io.set(r,"float16")):Cs.set("float16",Uint16Array)}};var eT=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new yt(t.type,t.data,e);case"cpu-pinned":return new yt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new yt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new yt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new yt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};var yt=class{constructor(e,r,s){Z2();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=Cs.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof e=="string")if(n=e,l=s,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let c=Cs.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&c===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${c.name} as data.`);e==="uint64"||e==="int64"?i=c.from(r,BigInt):i=c.from(r)}else if(r instanceof c)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&c!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof e[0];if(c==="string")n="string",i=e;else if(c==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let c=Io.get(e.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=c,i=e}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");o=l,this.cpuData=i,this.dataLocation="cpu"}let a=eT(o);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=a}static async fromImage(e,r){return H2(e,r)}static fromTexture(e,r){return X2(e,r)}static fromGpuBuffer(e,r){return Y2(e,r)}static fromMLTensor(e,r){return K2(e,r)}static fromPinnedBuffer(e,r,s){return Q2(e,r,s)}toDataURL(e){return W2(this,e)}toImageData(e){return V2(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return tT(this,e)}};var Cc=yt;var Xz=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function oT(t){return t<=It.DEBUG?0:t<=It.INFO?2:t<=It.WARNING||t<=It.ERROR?3:4}var Yz={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},qt=[],Dd,_n,rT=Symbol.for("onnxruntime");if(rT in globalThis)_n=globalThis[rT];else if(ie.IS_NODE_ENV){switch(_n=Wf,process.platform){case"win32":qt.push("dml");break;case"linux":process.arch==="x64"&&qt.push("cuda");break;case"darwin":qt.push("coreml");break}qt.push("webgpu"),qt.push("cpu"),Dd=["cpu"]}else _n=Nd,ie.IS_WEBNN_AVAILABLE&&qt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ie.IS_WEBGPU_AVAILABLE&&qt.push("webgpu"),qt.push("wasm"),Dd=["wasm"];var Kz=_n.InferenceSession;function aT(t=null){if(!t)return Dd;switch(t){case"auto":return qt;case"gpu":return qt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(qt.includes(t))return[Xz[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${qt.join(", ")}.`)}var sT=Promise.resolve(),mn=null;async function Qz(){if(mn)return mn;if(!(_e.useWasmCache&&typeof it?.wasm?.wasmPaths=="object"&&it?.wasm?.wasmPaths?.wasm&&it?.wasm?.wasmPaths?.mjs)){if(ie.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return mn=Promise.resolve(),mn}return mn=(async()=>{let e=it.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!Bf(e.wasm)?(async()=>{try{let s=await F2(Uf(e.wasm));s&&(it.wasm.wasmBinary=s,r=!0)}catch(s){ee.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!Bf(e.mjs)?(async()=>{try{let s=await G2(Uf(e.mjs));s&&(it.wasm.wasmPaths.mjs=s)}catch(s){ee.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(it.wasm.wasmPaths.mjs=e.mjs)})(),mn}async function Pc(t,e,r){await Qz();let s=oT(_e.logLevel??It.WARNING),n=()=>Kz.create(t,{logSeverityLevel:s,...e}),o=await(ie.IS_WEB_ENV?sT=sT.then(n):n());return o.config=r,o}var nT=Promise.resolve();async function Lc(t,e){let r=()=>t.run(e);return ie.IS_WEB_ENV?nT=nT.then(r):r()}function zc(t){return t instanceof _n.Tensor}var it=_n?.env;function Co(){return it?.wasm?.proxy}if(it){let t=function(e){let r=oT(e);it.logLevel=Yz[r]};if(it.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&it.versions?.web&&!it.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${it.versions.web}/dist/`;it.wasm.wasmPaths=ie.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}it.wasm.proxy=!1}it.webgpu&&(it.webgpu.powerPreference="high-performance"),t(_e.logLevel??It.WARNING),_e.backends.onnx={...it,setLogLevel:t}}var qr=async(t,e,r)=>{let s=await Pc(new Uint8Array(t),e);return(async n=>{let o=Co(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await Lc(s,a);return Array.isArray(r)?r.map(l=>new N(i[l])):new N(i[r])})},pr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=qr([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=qr([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=qr([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=qr([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=qr([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=qr([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=qr([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=qr([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var iT=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),Bd=ie.IS_NODE_ENV?"cpu":"wasm";function Nc(t,e,{warn:r}={}){return t?typeof t=="string"?t:t.hasOwnProperty(e)?t[e]:(r&&r(`device not specified for "${e}". Using the default device (${Bd}).`),Bd):Bd}var uT=(function(){let t;return async function(){if(t===void 0)if(!ie.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),st=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),lT=st.fp32,cT=Object.freeze({[iT.wasm]:st.q8}),Wr=Object.freeze({[st.fp32]:"",[st.fp16]:"_fp16",[st.int8]:"_int8",[st.uint8]:"_uint8",[st.q8]:"_quantized",[st.q4]:"_q4",[st.q2]:"_q2",[st.q1]:"_q1",[st.q4f16]:"_q4f16",[st.q2f16]:"_q2f16",[st.q1f16]:"_q1f16",[st.bnb4]:"_bnb4"});function Rc(t,e,r,{configDtype:s=null,warn:n}={}){let o,a=!1;t&&typeof t!="string"?t.hasOwnProperty(e)?o=t[e]:(o=null,a=!0):o=t;let i;if(o===st.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==st.auto&&st.hasOwnProperty(l))return l}i=cT[r]??lT}else o&&st.hasOwnProperty(o)?i=o:i=cT[r]??lT;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var Vr=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var N=class t{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return zc(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new Cc(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}indexOf(e){let r=this.data;for(let s=0;s_)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(m,0),Math.min(_,this.dims[u])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([u,f])=>f-u),o=n.reduce((u,f)=>u*f),a=this.data,i=new a.constructor(o),l=this.stride(),c=!0;for(let u=1;u=0;--m){let w=n[m];f+=(_%w+s[m][0])*l[m],_=Math.floor(_/w)}i[u]=a[f]}return new t(this.type,i,r)}permute(...e){return Zz(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let a,i;if(o?(a=(f,m)=>f+m,i=0n):(a=(f,m)=>f+m**e,i=0),r===null){let f=n.reduce(a,i);return e!==1&&(f=f**(1/e)),new t(this.type,[f],[])}let[l,c,u]=Po(a,this,r,s);if(e!==1)for(let f=0;f=0;--l){let f=this.dims[l];if(l!==r){let m=c%f;i+=m*u,u*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return Ud(this.dims)}squeeze(e=null){return new t(this.type,this.data,pT(this.dims,e))}squeeze_(e=null){return this.dims=pT(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,fT(this.dims,e))}unsqueeze_(e){return this.dims=fT(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...s,n.reduce((a,i)=>a*i,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;ni!==r?o*a:o,1);e[r]=s.length/n}return new t(this.type,s,e)}neg_(){let e=this.data;for(let r=0;re?1:0;return new t("bool",r,this.dims)}lt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;nMath.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=Pe(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Po((a,i)=>Math.max(a,i),this,e,r,-1/0);return new t(s,n,o)}argmin(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=bo(this.data)[1];return new t("int64",[BigInt(s)],[])}argmax(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Pe(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.lengthu===1)){if(e.length===this.dims.length)return this.clone();let u=e.length-this.dims.length,f=Array(u).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((u,f)=>u*e[f]),o=n.reduce((u,f)=>u*f,1),a=this.data,i=new a.constructor(o),l=Ud(s),c=Ud(n);for(let u=0;uBigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,xA(this.data),this.dims);return new t(e,Vr[e].from(this.data,r),this.dims)}};function Jz(t,e){let r=t.length,s=e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.lengthnew N("int64",t,[t.length]);async function Dc(t,e,r,s,n){return await(await pr.slice)({x:t,s:$c(e),e:$c(r),a:$c(s),t:$c(n??new Array(s.length).fill(1))})}function mT(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let u=0;ur!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function fT(t,e){return e=fr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function fr(t,e,r=null,s=!0){if(t<-e||t>=e){if(s)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function ve(t,e=0){e=fr(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i=0;--m){let x=c[m],b=_%x;m===e&&(b+=a),f+=b*w,w*=r[m],_=Math.floor(_/x)}n[f]=l[u]}a+=c[e]}}return new N(o,n,r)}function bt(t,e=0){return ve(t.map(r=>r.unsqueeze(e)),e)}function Po(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=fr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let c=0;c=0;--f){let w=a[f];if(f!==r){let x=m%w;u+=x*_,_*=i[f]}m=Math.floor(m/w)}l[u]=t(l[u],o[c],c,u)}return s||i.splice(r,1),[e.type,l,i]}function Gd(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let _=n.reduce((A,k)=>A+k,0)/n.length,w=Math.sqrt(n.reduce((A,k)=>A+(k-_)**2,0)/(n.length-r)),x=new N(t.type,[_],[]);return[new N(t.type,[w],[]),x]}e=fr(e,o.length);let a=Bc(t,e,s),i=a.data,[l,c,u]=Po((m,_,w,x)=>m+(_-i[x])**2,t,e,s);for(let m=0;mc+u,0);return new N(t.type,[l/n.length],[])}e=fr(e,s.length);let[o,a,i]=Po((l,c)=>l+c,t,e,r);if(s[e]!==1)for(let l=0;l=0;--r)e[r]=s,s*=t[r];return e}function jd(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new N(r,new s(n).fill(e),t)}function Qe(t,e){let r,s;if(typeof e=="number")r="float32",s=Float32Array;else if(typeof e=="bigint")r="int64",s=BigInt64Array;else if(typeof e=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return jd(t,e,r,s)}function Lo(t,e){return Qe(t.dims,e)}function et(t){return jd(t,1n,"int64",BigInt64Array)}function Uc(t){return et(t.dims)}function qd(t){return jd(t,0n,"int64",BigInt64Array)}function Wd(t){return qd(t.dims)}function VD(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>ys.random()),t)}function _T(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>ys.gauss()),t)}function hT(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i0?1:0,c=Math.floor(i/8),u=i%8;a[c]|=l<<7-u,r&&u===0&&(a[c]-=128)}return new N(s,a,[t.dims[0],t.dims[1]/8])}async function hn(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await Ct(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Vd(t,e){let r=await hn(t);return await Promise.all(r.map(s=>nt(t,s,!0,e)))}function zo(t){let e=t.dims;switch(e.length){case 1:return t.tolist();case 2:if(e[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return t.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${e.length}.`)}}var eN=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function tN(t,e,r,s){for(let n of Object.keys(t)){let o=e-t[n].length,a=r(n),i=new Array(o).fill(a);t[n]=s==="right"?wt(t[n],i):wt(i,t[n])}}function rN(t,e){for(let r of Object.keys(t))t[r].length=e}function Ps(t,...e){for(let r of e){if(!Object.hasOwn(t,r))continue;let s=t[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function sN(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var W=class extends We{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new GE(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Ps(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ps(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ps(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ps(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ps(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ps(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:a}of this.chat_template){if(typeof o!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=a}this.chat_template=n}this._compiled_template_cache=new Map;let s=sN(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let i=await Vd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,r={}){let{text_pair:s=null,add_special_tokens:n=!0,padding:o=!1,return_token_type_ids:a=null}=r,{truncation:i=null,max_length:l=null}=r,c=r.return_tensor??!0,u=Array.isArray(e),f;if(u){if(e.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(e.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");f=e.map((_,w)=>this._encode_plus(_,{text_pair:s[w],add_special_tokens:n,return_token_type_ids:a}))}else f=e.map(_=>this._encode_plus(_,{add_special_tokens:n,return_token_type_ids:a}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(s))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");f=[this._encode_plus(e,{text_pair:s,add_special_tokens:n,return_token_type_ids:a})]}if(l===null?l=this.model_max_length:i===null&&(o===!0?(ee.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):o===!1&&(ee.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),i=!0)),o===!0&&(l=Math.min(Pe(f.map(_=>_.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),o||i)for(let _=0;_l?i&&rN(f[_],l):o&&tN(f[_],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));let m={};if(c){if(!(o&&i)&&f.some(w=>{for(let x of Object.keys(w))if(w[x].length!==f[0][x]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let _=[f.length,f[0].input_ids.length];for(let w of Object.keys(f[0]))m[w]=new N("int64",BigInt64Array.from(f.flatMap(x=>x[w]).map(BigInt)),_)}else{for(let _ of Object.keys(f[0]))m[_]=f.map(w=>w[_]);if(!u)for(let _ of Object.keys(m))m[_]=m[_][0]}return m}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof N&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof N&&(e=zo(e)),!Array.isArray(e)||e.length===0||!EE(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,r={}){let{tools:s=null,documents:n=null,chat_template:o=null,add_generation_prompt:a=!1,tokenize:i=!0,padding:l=!1,truncation:c=!1,max_length:u=null,return_tensor:f=!0,return_dict:m=!0,tokenizer_kwargs:_={},...w}=r;if(o=this.get_chat_template({chat_template:o,tools:s}),typeof o!="string")throw Error(`chat_template must be a string, but got ${typeof o}`);let x=this._compiled_template_cache.get(o);x===void 0&&(x=new eA(o),this._compiled_template_cache.set(o,x));let b=Object.create(null);for(let k of eN){let S=Ps(this.config,k);S&&(b[k]=S)}let A=x.render({messages:e,add_generation_prompt:a,tools:s,documents:n,...b,...w});if(i){let k=this._call(A,{add_special_tokens:!1,padding:l,truncation:c,max_length:u,return_tensor:f,..._});return m?k:k.input_ids}return A}};function gn(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var Dm={};hs(Dm,{AlbertTokenizer:()=>Hd,AutoTokenizer:()=>ne,BartTokenizer:()=>Xd,BertTokenizer:()=>Yd,BlenderbotSmallTokenizer:()=>Kd,BlenderbotTokenizer:()=>Qd,BloomTokenizer:()=>Jd,CLIPTokenizer:()=>em,CamembertTokenizer:()=>Zd,CodeGenTokenizer:()=>rm,CodeLlamaTokenizer:()=>tm,CohereAsrTokenizer:()=>nm,CohereTokenizer:()=>sm,ConvBertTokenizer:()=>om,DebertaTokenizer:()=>im,DebertaV2Tokenizer:()=>am,DistilBertTokenizer:()=>lm,ElectraTokenizer:()=>cm,EsmTokenizer:()=>um,FalconTokenizer:()=>pm,GPT2Tokenizer:()=>mm,GPTNeoXTokenizer:()=>dm,GemmaTokenizer:()=>fm,HerbertTokenizer:()=>_m,LlamaTokenizer:()=>hm,M2M100Tokenizer:()=>gm,MBart50Tokenizer:()=>xm,MBartTokenizer:()=>No,MPNetTokenizer:()=>vm,MarianTokenizer:()=>wm,MgpstrTokenizer:()=>ym,MobileBertTokenizer:()=>bm,NllbTokenizer:()=>km,NougatTokenizer:()=>Em,PreTrainedTokenizer:()=>W,Qwen2Tokenizer:()=>Am,RoFormerTokenizer:()=>Mm,RobertaTokenizer:()=>Tm,SiglipTokenizer:()=>Sm,SpeechT5Tokenizer:()=>Om,SqueezeBertTokenizer:()=>Im,T5Tokenizer:()=>Cm,TokenizersBackend:()=>W,VitsTokenizer:()=>Lm,Wav2Vec2CTCTokenizer:()=>zm,WhisperTokenizer:()=>Nm,XLMRobertaTokenizer:()=>Rm,XLMTokenizer:()=>$m});var Hd=class extends W{return_token_type_ids=!0};var Xd=class extends W{};var Yd=class extends W{return_token_type_ids=!0};var Kd=class extends W{};var Qd=class extends W{};var Jd=class extends W{};var Zd=class extends W{};var em=class extends W{};var tm=class extends W{};var rm=class extends W{};var sm=class extends W{};var nm=class extends W{};var om=class extends W{return_token_type_ids=!0};var am=class extends W{return_token_type_ids=!0};var im=class extends W{return_token_type_ids=!0};var lm=class extends W{};var cm=class extends W{return_token_type_ids=!0};var um=class extends W{};var pm=class extends W{};var fm=class extends W{};var dm=class extends W{};var mm=class extends W{};var _m=class extends W{return_token_type_ids=!0};var hm=class extends W{padding_side="left"};var gm=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return gn(this,e,r,s)}};var wm=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),ee.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[r,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(r);if(s.length===2){let[n,o]=s;return this.supported_language_codes.includes(n)||ee.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),wt([n],super._encode_text(o))}}};var No=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return gn(this,e,r,s)}};var xm=class extends No{};var ym=class extends W{};var bm=class extends W{return_token_type_ids=!0};var vm=class extends W{};var km=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return gn(this,e,r,s)}};var Em=class extends W{};var Am=class extends W{};var Tm=class extends W{};var Mm=class extends W{return_token_type_ids=!0};var Sm=class extends W{};var Om=class extends W{};var Im=class extends W{return_token_type_ids=!0};var Cm=class extends W{};var Pm=class extends Ft{decode_chain(e){let r="";for(let s=1;s[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function wT(t){t=t.toLowerCase();let e=nN.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),Ro.has(t))e=t;else{let n=t.length===2?Ro.keys():Ro.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var oN="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",xT=new RegExp(`^[${oN}]+$`,"gu"),aN=.1,Nm=class extends W{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],u=l(),f=0,m=this.timestamp_begin,w=m+1500,x=[],b=[],A=!1,k=null,S=new Set(this.all_special_ids);for(let I of e){let v=I.tokens,B=i?I.token_timestamps:null,G=null,F=m;if("stride"in I){let[J,$,C]=I.stride;if(f-=$,k=J-C,$&&(F=$/n+m),C)for(let se=v.length-1;se>=0;--se){let K=Number(v[se]);if(K>=m){if(G!==null&&(K-m)*n=m&&$<=w){let C=($-m)*n+f,se=bs(C,2);if(G!==null&&$>=G)A=!0;else if(A||x.length>0&&$0&&u.timestamp[1]!==null))for(let U of u.words)U.timestamp[1]>u.timestamp[1]&&u.timestamp[1]>=U.timestamp[0]&&(U.timestamp[1]=u.timestamp[1]);c.push(u),x=[],X=[],b=[],Y=[],u=l()}}else if(X.push($),i){let C=bs(B[J]+f,2),se;if(J+10?(x.push(X),i&&b.push(Y)):x.every(J=>J.length===0)&&(u=l(),x=[],X=[],b=[],Y=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[I,v]=this.findLongestCommonSequence(x,b),B=this.decode(I);u.text=B,i&&(u.words=this.collateWordTimestamps(I,v,a)),c.push(u)}let M=Object.create(null),O=c.map(I=>I.text).join("");if(r||s){for(let I=0;I0,i=a?[]:null,l=a?r[0]:null;for(let c=1;c$===F[C]&&l[O+C][0]-aN<=r[c][B+C][0]).length:X=v.filter(($,C)=>$===F[C]).length;let Y=M/1e4,J=X/M+Y;X>1&&J>f&&(f=J,m=[O,I,B,G])}let[w,x,b,A]=m,k=Math.floor((x+w)/2),S=Math.floor((A+b)/2);if(a&&f===0&&n>0){let M=l[n-1][0],O=r[c].findIndex(I=>I[0]>=M);S=O===-1?u.length:O}o.push(...s.slice(0,k)),s=u.slice(S),n=s.length,a&&(i.push(...l.slice(0,k)),l=r[c].slice(S))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],c=0;for(let u=0;u=this._tokenizer.token_to_id("<|endoftext|>"),_=c.startsWith(" "),w=c.trim(),x=xT.test(w);if(m||_||x||o.length===0)o.push(c),a.push(u),i.push(f);else{let b=o.length-1;o[b]+=c,a[b].push(...u),i[b].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,u=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[u]=a[c]+a[u],i[u]=wt(i[c],i[u]),l[u]=wt(l[c],l[u]),a[c]="",i[c]=[],l[c]=[]):u=c,--c;for(c=0,u=1;uf),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var Rm=class extends W{};var $m=class extends W{return_token_type_ids=!0;constructor(e,r){super(e,r),ee.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var ne=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await Vd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",u=Dm[c];return u||(ee.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),u=W),new u(i,l)}};var Hr="https://github.com/huggingface/transformers.js/issues/new/choose";var $o="preprocessor_config.json",kr=$o,Fc="processor_config.json",Gc="chat_template.jinja";var re=class extends We{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?nt(e,Fc,!0,r):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{let i=await this[a].from_pretrained(e,r);return[a.replace(/_class$/,""),i]})).then(Object.fromEntries),this.uses_chat_template_file?yo(e,Gc,!0,r):null]);return new this(s,n,o)}};var mu={};hs(mu,{ChatterboxProcessor:()=>e_,CohereAsrProcessor:()=>t_,Florence2Processor:()=>H_,Gemma3Processor:()=>X_,Gemma3nProcessor:()=>Y_,Gemma4Processor:()=>K_,Glm46VProcessor:()=>Q_,GraniteSpeechProcessor:()=>J_,GroundingDinoProcessor:()=>Z_,Idefics3Processor:()=>uu,JinaCLIPProcessor:()=>th,Lfm2VlProcessor:()=>rh,LlavaProcessor:()=>sh,MgpstrProcessor:()=>nh,MoonshineProcessor:()=>oh,OwlViTProcessor:()=>ah,PaliGemmaProcessor:()=>ih,Phi3VProcessor:()=>lh,PixtralProcessor:()=>ch,Processor:()=>re,PyAnnoteProcessor:()=>uh,Qwen2VLProcessor:()=>zs,Qwen2_5_VLProcessor:()=>Yo,Qwen3VLProcessor:()=>ph,Sam2Processor:()=>pu,Sam2VideoProcessor:()=>fh,SamProcessor:()=>Ko,SmolVLMProcessor:()=>uu,SpeechT5Processor:()=>dh,UltravoxProcessor:()=>mh,VLChatProcessor:()=>eh,VoxtralProcessor:()=>_h,VoxtralRealtimeProcessor:()=>gh,Wav2Vec2Processor:()=>wh,Wav2Vec2ProcessorWithLM:()=>xh,WhisperProcessor:()=>yh});var Ee=class extends We{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await nt(e,$o,!0,r);return new this(s)}};function Ae(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var Wo={};hs(Wo,{ASTFeatureExtractor:()=>Fm,ChatterboxFeatureExtractor:()=>Gm,ClapFeatureExtractor:()=>jm,CohereAsrFeatureExtractor:()=>qm,DacFeatureExtractor:()=>Fo,EncodecFeatureExtractor:()=>Bo,FeatureExtractor:()=>Ee,Gemma3nAudioFeatureExtractor:()=>Go,Gemma4AudioFeatureExtractor:()=>jo,GraniteSpeechFeatureExtractor:()=>Wm,MoonshineFeatureExtractor:()=>Vm,ParakeetFeatureExtractor:()=>Uo,PyAnnoteFeatureExtractor:()=>qo,SeamlessM4TFeatureExtractor:()=>Hm,SnacFeatureExtractor:()=>Xm,SpeechT5FeatureExtractor:()=>Ym,VoxtralRealtimeFeatureExtractor:()=>Jm,Wav2Vec2FeatureExtractor:()=>Km,WeSpeakerFeatureExtractor:()=>Qm,WhisperFeatureExtractor:()=>Zm});var iN=()=>{};var yT={fromWeb:iN};var lN=()=>{};var bT=lN;async function jc(t,e){if(ie.IS_BROWSER_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(ie.IS_FS_AVAILABLE){let r=e.stream(),s=yT.fromWeb(r),n=gt.createWriteStream(t);await bT(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function ET(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await Nr(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&ee.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let c=0;c2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function Bm(t,e="htk"){let r=uN[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}var pN={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,r=15,s=Math.log(6.4)/27)=>t>=r?e*Math.exp(s*(t-r)):200*t/3};function fN(t,e="htk"){let r=pN[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}function dN(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;anew Array(t.length));for(let a=0;at+s*o)}function lt(t,e,r,s,n,o=null,a="htk",i=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);let l=Bm(r,a),c=Bm(s,a),u=kT(l,c,e+2),f=fN(u,a),m;if(i){let w=n/((t-1)*2);m=Bm(Float64Array.from({length:t},(x,b)=>b*w),a),f=u}else m=kT(0,Math.floor(n/2),t);let _=dN(m,f);if(o!==null&&o==="slaney")for(let w=0;wn)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(G!==r)throw new Error(`Length of the window (${G}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!u)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a){let Q=Math.floor(r/2);switch(i){case"reflect":{t=mN(t,Q,Q);break}case"constant":{let le=new t.constructor(t.length+2*Q);le.set(t,Q),t=le;break}case"semicausal":{let le=new t.constructor(t.length+Q);le.set(t,Q),t=le;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let F=Math.floor(1+Math.floor((t.length-r)/s));S!==null&&FF?O&&(J=M):J=Y=M);let $=new wc(n),C=new Float64Array(n),se=new Float64Array($.outputBufferSize),K=new Float32Array(X*J);for(let Q=0;Q=1;--ce)C[ce]-=c*C[ce-1];C[0]*=1-c}for(let ce=0;ceMath.pow(c,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null||t===s)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);let i=new Float64Array(s),l=n?Math.floor((s-t)/2):0;return i.set(a,l),i}function gN(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return qc(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),qc(n,8,"WAVE"),qc(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,e,!0),n.setUint32(28,e*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),qc(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function qc(t,e,r){for(let s=0;sn+o.length,0),r=new Float32Array(e),s=0;for(let n of this.audio)r.set(n,s),s+=n.length;return r}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),gN(e,this.sampling_rate)}async save(e){return jc(e,this.toBlob())}};var Fm=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=mt(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){Ae(e,"ASTFeatureExtractor");let r=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let s=this.std*2,n=r.data;for(let o=0;o0)if(s==="rand_trunc"){a=!0;let l=Math.floor(ys.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let c=e.length;c=1;--n)e[n]-=r*e[n-1];return await ot(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){Ae(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f1?s-1:1;for(let f=0;f=u){l.push(e.slice(c,u));break}let f=Math.max(c,c+a-i),m=Math.min(c+a,u),_;m<=f?_=c+a:_=this._find_split_point_energy(e,f,m,n),_=Math.max(c+1,Math.min(_,u)),l.push(e.slice(c,_)),c=_}return l}_find_split_point_energy(e,r,s,n){let o=s-r;if(o<=n)return Math.floor((r+s)/2);let a=1/0,i=r,l=o-n;for(let c=0;c<=l;c+=n){let u=0;for(let f=0;fr&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let a=await this._extract_fbank_features(e,this.config.max_length),i=Qe([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var jo=class extends Go{async _extract_fbank_features(e,r){let{frame_length:s,hop_length:n,fft_length:o}=this.config,a=Math.floor(s/2),i=Math.floor((e.length+a-(s+1))/n)+1;return ot(e,this.window,s,n,{fft_length:o,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:i})}async _call(e,r={}){Ae(e,"Gemma4AudioFeatureExtractor");let s=e.length,n=await super._call(e,r),{input_features:o}=n,[,a,i]=o.dims,{frame_length:l,hop_length:c}=this.config,u=Math.floor(l/2),f=l+1,m=new Uint8Array(s+u+(r.pad_to_multiple_of??128));m.fill(1,u,u+s);let _=new Uint8Array(a);for(let x=0;x({id:l,start:c*s,end:u*s,confidence:f/(u-c)})))}return n}};var Hm=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=mt(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){Ae(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,b=a.data;for(let A=0;A0){let k=new Float32Array(x*(w+A));k.set(b),k.fill(this.config.padding_value,b.length);let S=w+A;a=new N(a.type,k,[S,x]),o&&(i=new N("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,u=this.config.stride;if(l%u!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${u}).`);let m=a.view(1,Math.floor(l/u),c*u),_={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let b=i.data;for(let A=1,k=0;Ao+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){Ae(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));let s=[1,r.length];return{input_values:new N("float32",r,s),attention_mask:new N("int64",new BigInt64Array(r.length).fill(1n),s)}}};var Qm=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=mt(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){Ae(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;ln?(e.length>this.config.n_samples&&ee.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var Ge=class{static async from_pretrained(e,r={}){let s=await nt(e,$o,!0,r),n=s.feature_extractor_type,o=Wo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Hr}.`);return new o(s)}};var e_=class extends re{static tokenizer_class=ne;static feature_extractor_class=Ge;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var xN=new Set(["ja","zh"]),t_=class extends re{static tokenizer_class=ne;static feature_extractor_class=Ge;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let r=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(r)}static join_chunks(e,r="en"){let s=e.filter(a=>a&&a.trim());if(s.length===0)return"";let n=xN.has(r)?"":" ";return[s[0].trimEnd(),...s.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}};var Wc={};var Ls,MT,Xr;if(ie.IS_WEB_ENV)Ls=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},Xr=self.createImageBitmap,MT=self.ImageData;else if(Wc)Xr=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Je(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&o.convert(r),o};else throw new Error("Unable to load image processing library.");var yN={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},bN=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Je=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!ie.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let s=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(s,e.width,e.height,4)}static async fromURL(e){let r=await Nr(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(e){if(ie.IS_WEB_ENV){let r=await Xr(e),s=Ls(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=Wc(await e.arrayBuffer());return await Xr(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r=0?l=s:u=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,u,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await Xr(o)}}async toBlob(e="image/png",r=1){if(!ie.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new N("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!ie.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=Ls(e.width,e.height),s=new MT(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;lnew t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(ie.IS_WEB_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=bN.get(r)??"image/png",n=await this.toBlob(s);return jc(e,n)}else if(ie.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(ie.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return Wc(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},vN=Je.read.bind(Je);function ST(t,e,r=0,s=null){let n=t/e,o=gA(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),oe&&A.push(S)}else{let S=Pe(b.data)[1];if(S===l-1||(k=Re(b.data),k[S]O*f[(I+1)%2])),m.boxes.push(M),m.classes.push(S),m.scores.push(k[S])}}c.push(m)}return c}function Vc(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;of[A]&&(f[A]=b[A],m[A]=x)}let _=new Array(i.dims[0]);for(let x=0;xx!==void 0);n.push({segmentation:u,labels:w})}return n}function kN(t,e,r,s){let n=[],o=[],a=[];for(let i=0;ir&&(n.push(c),o.push(m),a.push(u))}return[n,o,a]}function EN(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let u=0;u=s&&++i;let c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function AN(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new N("int32",new Int32Array(i*l),[i,l]),u=[];if(a!==null)for(let x=0;xm[k]&&(f[k]=x,m[k]=A[k])}let _=0,w=c.data;for(let x=0;x200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let a=Math.round(t/r)*r,i=Math.round(e/r)*r;if(o*a*i>n){let l=Math.sqrt(o*t*e/n);a=Math.max(r,Math.floor(t/l/r)*r),i=Math.max(r,Math.floor(e/l/r)*r)}else if(o*a*io?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=bo(s.data)[0],a=Pe(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=s.height,u=0,f=0,m=s.data;for(let _=0;_this.preprocess(o)));return{pixel_values:bt(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await nt(e,kr,!0,r);return new this(s)}};var kn={};hs(kn,{BeitFeatureExtractor:()=>s_,BitImageProcessor:()=>n_,CHMv2ImageProcessor:()=>a_,CLIPFeatureExtractor:()=>i_,CLIPImageProcessor:()=>Yc,ChineseCLIPFeatureExtractor:()=>o_,ConvNextFeatureExtractor:()=>l_,ConvNextImageProcessor:()=>Kc,DINOv3ViTImageProcessor:()=>p_,DPTFeatureExtractor:()=>d_,DPTImageProcessor:()=>Zc,DeiTFeatureExtractor:()=>c_,DeiTImageProcessor:()=>Qc,DetrFeatureExtractor:()=>u_,DetrImageProcessor:()=>Jc,DonutFeatureExtractor:()=>f_,DonutImageProcessor:()=>xn,EfficientNetImageProcessor:()=>m_,GLPNFeatureExtractor:()=>g_,Gemma3ImageProcessor:()=>__,Gemma4ImageProcessor:()=>Vo,Glm46VImageProcessor:()=>h_,GroundingDinoImageProcessor:()=>w_,Idefics3ImageProcessor:()=>eu,ImageFeatureExtractor:()=>H,ImageProcessor:()=>H,JinaCLIPImageProcessor:()=>y_,Lfm2VlImageProcessor:()=>b_,LlavaOnevisionImageProcessor:()=>v_,Mask2FormerImageProcessor:()=>E_,MaskFormerFeatureExtractor:()=>k_,MaskFormerImageProcessor:()=>yn,MobileNetV1FeatureExtractor:()=>A_,MobileNetV1ImageProcessor:()=>tu,MobileNetV2FeatureExtractor:()=>T_,MobileNetV2ImageProcessor:()=>ru,MobileNetV3FeatureExtractor:()=>M_,MobileNetV3ImageProcessor:()=>su,MobileNetV4FeatureExtractor:()=>S_,MobileNetV4ImageProcessor:()=>nu,MobileViTFeatureExtractor:()=>O_,MobileViTImageProcessor:()=>ou,NougatImageProcessor:()=>I_,OwlViTFeatureExtractor:()=>C_,OwlViTImageProcessor:()=>bn,Owlv2ImageProcessor:()=>P_,Phi3VImageProcessor:()=>N_,PixtralImageProcessor:()=>R_,PvtImageProcessor:()=>$_,Qwen2VLImageProcessor:()=>Ho,RTDetrImageProcessor:()=>D_,Sam2ImageProcessor:()=>Xo,Sam3ImageProcessor:()=>Xo,SamImageProcessor:()=>Xo,SapiensFeatureExtractor:()=>B_,SapiensImageProcessor:()=>au,SegformerFeatureExtractor:()=>U_,SegformerImageProcessor:()=>iu,SiglipImageProcessor:()=>F_,SmolVLMImageProcessor:()=>eu,Swin2SRImageProcessor:()=>G_,VLMImageProcessor:()=>x_,ViTFeatureExtractor:()=>j_,ViTImageProcessor:()=>lu,VitMatteImageProcessor:()=>q_,VitPoseImageProcessor:()=>W_,YolosFeatureExtractor:()=>V_,YolosImageProcessor:()=>cu});var s_=class extends H{};var n_=class extends H{};var o_=class extends H{};var a_=class extends H{};var Yc=class extends H{},i_=class extends Yc{};var Kc=class extends H{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){let s=Math.floor(r/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}},l_=class extends Kc{};var Qc=class extends H{},c_=class extends Qc{};var Jc=class extends H{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Qe(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Yr(...e)}post_process_panoptic_segmentation(...e){return Hc(...e)}post_process_instance_segmentation(...e){return Xc(...e)}},u_=class extends Jc{};var p_=class extends H{};var xn=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let u=l.map((f,m)=>-f/c[m]);return super.pad_image(e,r,s,{center:!0,constant_values:u,...n})}},f_=class extends xn{};var Zc=class extends H{},d_=class extends Zc{};var m_=class extends H{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}};var __=class extends H{};function TN(t,e,r,s,n){let o=s*r**2,a=Math.sqrt(o/(t*e)),i=n*r,l=Math.floor(a*t/i)*i,c=Math.floor(a*e/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);let u=Math.floor(s/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(e/t)*i,u)):c===0&&(c=i,l=Math.min(Math.floor(t/e)*i,u)),[l,c]}function MN(t,e,r,s,n,o,a){let i=Math.floor(e/n),l=Math.floor(r/n),c=i*l,u=n*n*s,f=new Float32Array(o*u),m=0;for(let x=0;xa),0));let u=a.dims[0]/i,f=a.dims[1],m=Math.floor(a.dims[2]/c),_=Math.floor(a.dims[3]/c),w=a.view(u,i,f,Math.floor(m/l),l,c,Math.floor(_/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(u*m*_,f*i*c*c),x=new N("int64",[u,m,_],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var h_=class extends Ho{get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return wn(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}};var g_=class extends H{};var w_=class extends H{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=et([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var eu=class extends H{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],c=[];for(let A of n){let k=await Promise.all(A.map(O=>this.preprocess(O)));l.push(...k.map(O=>O.original_size)),c.push(...k.map(O=>O.reshaped_input_size)),k.forEach(O=>O.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,M;if(r??this.do_image_splitting){let O=new Array(k.length),I=new Array(k.length);M=await Promise.all(k.map(async(v,B)=>{let G=this.get_resize_for_vision_encoder(v.pixel_values,S),F=await kt(v.pixel_values,{size:[G.height,G.width]}),{frames:X,num_splits_h:Y,num_splits_w:J}=await this.split_image(F,this.max_image_size);return O[B]=Y,I[B]=J,ve(X,0)})),a.push(O),i.push(I)}else{let O=[S,S];M=await Promise.all(k.map(I=>kt(I.pixel_values,{size:O}))),a.push(new Array(k.length).fill(0)),i.push(new Array(k.length).fill(0))}o.push(ve(M,0))}let u=o.length,[f,m,_,w]=o[0].dims,x,b;if(u===1)x=o[0].unsqueeze_(0),b=Qe([u,f,_,w],!0);else{let A=Math.max(...o.map(M=>M.dims.at(0)));b=Qe([u,A,_,w],!0);let k=b.data,S=A*_*w;for(let M=0;Ms||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let u=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;wr*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var y_=class extends H{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function IT(t,e){return Math.round(t/e)*e}function SN(t,e,r,s,n){let o=1/0,a=[1,1],i=r*s;for(let l of e){let c=Math.abs(t-l[0]/l[1]);c.5*n*n*l[0]*l[1]&&(a=l)}return a}function ON(t,e){let r=[],s=new Set;for(let n=t;n<=e;++n)for(let o=1;o<=n;++o)for(let a=1;a<=n;++a){let i=o*a;if(i>=t&&i<=e){let l=o<<16|a;s.has(l)||(s.add(l),r.push([o,a]))}}return r.sort((n,o)=>n[0]*n[1]-o[0]*o[1])}function IN(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,u=new Float32Array(r*a*i*l),f=n*o;for(let m=0;mthis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=ON(this.min_tiles,this.max_tiles),[n,o]=SN(r/e,s,r,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:r=null}={}){let s;Array.isArray(e)?Array.isArray(e[0])?s=e:s=[e]:s=[[e]];let n=[],o=[],a=[],i=[],l=[],c=[];for(let f of s){let m=await Promise.all(f.map(_=>this.preprocess(_,{do_pad:!1})));for(let{pixel_values:_}of m){let[,w,x]=_.dims,b=_.unsqueeze_(0),A=this.encoder_patch_size*this.downsample_factor,k=A**2,[S,M]=wn(Math.max(A,w),Math.max(A,x),A,this.min_image_tokens*k,this.max_image_tokens*k).map(F=>Math.max(A,F)),O,I=1,v=1,B=this._is_image_too_large(w,x),G=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(B&&G){let{grid_width:F,grid_height:X,target_width:Y,target_height:J}=this._get_grid_layout(w,x);I=X,v=F;let $=await kt(b,{size:[J,Y]});O=[];for(let C=0;C(u-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||z_(r)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(m=>this.preprocess(m))),o=n.map(m=>m.original_size),a=n.map(m=>m.reshaped_input_size),i=[];for(let{pixel_values:m}of n){m.unsqueeze_(0);let[_,w]=m.dims.slice(-2),x=await kt(m,{size:[$t,$t],mode:"bicubic"});if(r>0){let b=[],A=z_(r),k=vn(w/A),S=vn(_/A);for(let O=0;Om.map(_=>$t*L_(_/$t))),u=new N("int64",c.flat(),[s,2]),f=c.map(([m,_])=>this.calc_num_image_tokens_from_image_size(_,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:u,num_img_tokens:f}}};var R_=class extends H{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:u}=this.config;if(!u)throw new Error("config must contain 'spatial_merge_size'");let f=c*u,m=Math.floor((i-1)/f)+1,_=Math.floor((l-1)/f)+1;return[m*f,_*f]}};var $_=class extends H{};var D_=class extends H{post_process_object_detection(...e){return Yr(...e)}};var Xo=class extends H{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=zf(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;an!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new N("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let c=0;cn&&(w[x]=1);m=new N("bool",w,m.dims)}i.push(m)}return i}generate_crop_boxes(e,r,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:a=1}={}){}};var au=class extends H{post_process_semantic_segmentation(...e){return Vc(...e)}},B_=class extends au{};var iu=class extends H{post_process_semantic_segmentation(...e){return Vc(...e)}},U_=class extends iu{};var F_=class extends H{};var G_=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r;return super.pad_image(e,r,{width:a+(s-a%s)%s,height:o+(s-o%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var lu=class extends H{},j_=class extends lu{};var q_=class extends H{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let s=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(r.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:bt(s.map((a,i)=>ve([a.pixel_values,n[i].pixel_values],0)),0),original_sizes:s.map(a=>a.original_size),reshaped_input_sizes:s.map(a=>a.reshaped_input_size)}}};var W_=class extends H{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let u=0;u/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],c=[];for(let[u,f,...m]of i)l.push(f?f.trim():l.at(-1)??""),c.push(m.map((_,w)=>(Number(_)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:c};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var X_=class extends re{static tokenizer_class=ne;static image_processor_class=Te;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:o,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=o,this.eoi_token=a;let i=o.repeat(this.image_seq_length);this.full_image_sequence=` ++ }`,h=new Function(Object.keys(P),z)(...Object.values(P)),z=`methodCaller<(${E.map(j=>j.name)}) => ${g.name}>`,CS(Object.defineProperty(h,"name",{value:z}))}function RS(p,d){return d>>>=0,(p=Bt(p>>>0))==Bt(d)}function $S(p){return(p>>>=0)?(p=Zl(p),Ht(globalThis[p])):Ht(globalThis)}function DS(p){return p=Zl(p>>>0),Ht(e[p])}function BS(p,d){return d>>>=0,p=Bt(p>>>0),d=Bt(d),Ht(p[d])}function US(p){9<(p>>>=0)&&(ds[p+1]+=1)}function Wv(p,d,h,g,E){return ff[p>>>0](d>>>0,h>>>0,g>>>0,E>>>0)}function FS(p,d,h,g,E){return Wv(p>>>0,d>>>0,h>>>0,g>>>0,E>>>0)}function GS(){return Ht([])}function jS(p){p=Bt(p>>>0);for(var d=Array(p.length),h=0;h>>0))}function WS(){return Ht({})}function VS(p){for(var d=Bt(p>>>=0);d.length;){var h=d.pop();d.pop()(h)}of(p)}function HS(p,d,h){d>>>=0,h>>>=0,p=Bt(p>>>0),d=Bt(d),h=Bt(h),p[d]=h}function XS(p,d){p=_t(p),d>>>=0,p=new Date(1e3*p),(v(),$)[d>>>2>>>0]=p.getUTCSeconds(),(v(),$)[d+4>>>2>>>0]=p.getUTCMinutes(),(v(),$)[d+8>>>2>>>0]=p.getUTCHours(),(v(),$)[d+12>>>2>>>0]=p.getUTCDate(),(v(),$)[d+16>>>2>>>0]=p.getUTCMonth(),(v(),$)[d+20>>>2>>>0]=p.getUTCFullYear()-1900,(v(),$)[d+24>>>2>>>0]=p.getUTCDay(),p=(p.getTime()-Date.UTC(p.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(v(),$)[d+28>>>2>>>0]=p}var Vv=p=>p%4==0&&(p%100!=0||p%400==0),Hv=[0,31,60,91,121,152,182,213,244,274,305,335],Xv=[0,31,59,90,120,151,181,212,243,273,304,334];function YS(p,d){p=_t(p),d>>>=0,p=new Date(1e3*p),(v(),$)[d>>>2>>>0]=p.getSeconds(),(v(),$)[d+4>>>2>>>0]=p.getMinutes(),(v(),$)[d+8>>>2>>>0]=p.getHours(),(v(),$)[d+12>>>2>>>0]=p.getDate(),(v(),$)[d+16>>>2>>>0]=p.getMonth(),(v(),$)[d+20>>>2>>>0]=p.getFullYear()-1900,(v(),$)[d+24>>>2>>>0]=p.getDay();var h=(Vv(p.getFullYear())?Hv:Xv)[p.getMonth()]+p.getDate()-1|0;(v(),$)[d+28>>>2>>>0]=h,(v(),$)[d+36>>>2>>>0]=-60*p.getTimezoneOffset(),h=new Date(p.getFullYear(),6,1).getTimezoneOffset();var g=new Date(p.getFullYear(),0,1).getTimezoneOffset();p=0|(h!=g&&p.getTimezoneOffset()==Math.min(g,h)),(v(),$)[d+32>>>2>>>0]=p}function KS(p){p>>>=0;var d=new Date((v(),$)[p+20>>>2>>>0]+1900,(v(),$)[p+16>>>2>>>0],(v(),$)[p+12>>>2>>>0],(v(),$)[p+8>>>2>>>0],(v(),$)[p+4>>>2>>>0],(v(),$)[p>>>2>>>0],0),h=(v(),$)[p+32>>>2>>>0],g=d.getTimezoneOffset(),E=new Date(d.getFullYear(),6,1).getTimezoneOffset(),T=new Date(d.getFullYear(),0,1).getTimezoneOffset(),P=Math.min(T,E);return 0>h?(v(),$)[p+32>>>2>>>0]=+(E!=T&&P==g):0>>2>>>0]=d.getDay(),h=(Vv(d.getFullYear())?Hv:Xv)[d.getMonth()]+d.getDate()-1|0,(v(),$)[p+28>>>2>>>0]=h,(v(),$)[p>>>2>>>0]=d.getSeconds(),(v(),$)[p+4>>>2>>>0]=d.getMinutes(),(v(),$)[p+8>>>2>>>0]=d.getHours(),(v(),$)[p+12>>>2>>>0]=d.getDate(),(v(),$)[p+16>>>2>>>0]=d.getMonth(),(v(),$)[p+20>>>2>>>0]=d.getYear(),p=d.getTime(),BigInt(isNaN(p)?-1:p/1e3)}function Yv(p,d,h,g,E,T,P){return n?Ue(16,1,p,d,h,g,E,T,P):-52}function Kv(p,d,h,g,E,T){if(n)return Ue(17,1,p,d,h,g,E,T)}var io={},QS=()=>performance.timeOrigin+performance.now();function Qv(p,d){if(n)return Ue(18,1,p,d);if(io[p]&&(clearTimeout(io[p].id),delete io[p]),!d)return 0;var h=setTimeout(()=>{delete io[p],St(()=>Tk(p,performance.timeOrigin+performance.now()))},d);return io[p]={id:h,Ae:d},0}function JS(p,d,h,g){p>>>=0,d>>>=0,h>>>=0,g>>>=0;var E=new Date().getFullYear(),T=new Date(E,0,1).getTimezoneOffset();E=new Date(E,6,1).getTimezoneOffset();var P=Math.max(T,E);(v(),C)[p>>>2>>>0]=60*P,(v(),$)[d>>>2>>>0]=+(T!=E),p=(d=z=>{var j=Math.abs(z);return`UTC${0<=z?"-":"+"}${String(Math.floor(j/60)).padStart(2,"0")}${String(j%60).padStart(2,"0")}`})(T),d=d(E),EDate.now(),eO=1;function tO(p,d,h){if(h>>>=0,!(0<=p&&3>=p))return 28;if(p===0)p=Date.now();else{if(!eO)return 52;p=performance.timeOrigin+performance.now()}return p=Math.round(1e6*p),(v(),L)[h>>>3>>>0]=BigInt(p),0}var df=[],Jv=(p,d)=>{df.length=0;for(var h;h=(v(),X)[p++>>>0];){var g=h!=105;d+=(g&=h!=112)&&d%8?4:0,df.push(h==112?(v(),C)[d>>>2>>>0]:h==106?(v(),L)[d>>>3>>>0]:h==105?(v(),$)[d>>>2>>>0]:(v(),K)[d>>>3>>>0]),d+=g?8:4}return df};function rO(p,d,h){return p>>>=0,d=Jv(d>>>0,h>>>0),Sf[p](...d)}function sO(p,d,h){return p>>>=0,d=Jv(d>>>0,h>>>0),Sf[p](...d)}var nO=()=>{};function oO(p,d){return M(tn(p>>>0,d>>>0))}var aO=()=>{throw Oe+=1,"unwind"};function iO(){return 4294901760}var lO=()=>1,cO=()=>navigator.hardwareConcurrency;function uO(p){p>>>=0;var d=(v(),X).length;if(p<=d||4294901760=h;h*=2){var g=d*(1+.2/h);g=Math.min(g,p+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(p,g)/65536))-Ir.buffer.byteLength+65535)/65536|0;try{Ir.grow(g),le();var E=1;break e}catch{}E=void 0}if(E)return!0}return!1}var ir=p=>{var d=wr(p)+1,h=sc(d);return gr(p,h,d),h},mf=(p,d)=>{(v(),C)[p>>>2>>>0]=d;var h=(v(),C)[p>>>2>>>0];(v(),C)[p+4>>>2>>>0]=(d-h)/4294967296},lo=p=>(v(),C)[p>>>2>>>0]+4294967296*(v(),$)[p+4>>>2>>>0],ht=[],pO=(p,d)=>{ht[p>>>0]=d},xr=[],ec=[],sn=(p,d)=>{ec[p]=new Promise(h=>d.finally(()=>h(p)))},oe=p=>{if(p)return ht[p>>>0]},fO=(p,d)=>{for(p=(v(),C)[p>>>2>>>0];p;p=(v(),C)[p>>>2>>>0])d[(v(),$)[p+4>>>2>>>0]](p)},tc=(p,d,h)=>{(v(),C)[p>>>2>>>0]=d,(v(),C)[p+4>>>2>>>0]=h},Zv=p=>{var d=(v(),C)[p>>>2>>>0];return p=(v(),C)[p+4>>>2>>>0],tn(d,p)},yr=p=>{var d=(v(),C)[p>>>2>>>0];return p=(v(),C)[p+4>>>2>>>0],d?tn(d,p):p===0?"":void 0},dO=p=>{var d=yr(p+4),h=(h=(v(),C)[p+12>>>2>>>0])?oe(h):"auto";if(p+=16){var g=oe((v(),C)[p+4>>>2>>>0]),E=(v(),C)[p+16>>>2>>>0],T=(v(),C)[p+20>>>2>>>0];if(E){for(var P={},z=0;z>>3>>>0]}E=P}else E=void 0;p={module:g,constants:E,entryPoint:yr(p+8)}}else p=void 0;return{label:d,layout:h,compute:p}},ek=(p,d)=>{function h(g,E){g=p[g],(v(),C)[d+E>>>2>>>0]=g}h("maxTextureDimension1D",4),h("maxTextureDimension2D",8),h("maxTextureDimension3D",12),h("maxTextureArrayLayers",16),h("maxBindGroups",20),h("maxBindGroupsPlusVertexBuffers",24),h("maxBindingsPerBindGroup",28),h("maxDynamicUniformBuffersPerPipelineLayout",32),h("maxDynamicStorageBuffersPerPipelineLayout",36),h("maxSampledTexturesPerShaderStage",40),h("maxSamplersPerShaderStage",44),h("maxStorageBuffersPerShaderStage",48),h("maxStorageTexturesPerShaderStage",52),h("maxUniformBuffersPerShaderStage",56),h("minUniformBufferOffsetAlignment",80),h("minStorageBufferOffsetAlignment",84),mf(d+64,p.maxUniformBufferBindingSize),mf(d+72,p.maxStorageBufferBindingSize),h("maxVertexBuffers",88),mf(d+96,p.maxBufferSize),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),p.ze!==void 0&&h("maxImmediateSize",148)},mO=[,"validation","out-of-memory","internal"],_O=[,"compatibility","core"],tk={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},hO=[,"low-power","high-performance"],gO=[,"occlusion","timestamp"],wO={undefined:1,unknown:1,destroyed:2};function xO(p,d,h,g,E,T){d=_t(d),h=_t(h),g>>>=0,E>>>=0,T>>>=0;var P=oe(p>>>0);if(p={},T){var z=(v(),C)[T+12>>>2>>>0];if(z){var j=(v(),C)[T+16>>>2>>>0];p.requiredFeatures=Array.from((v(),C).subarray(j>>>2>>>0,j+4*z>>>2>>>0),ae=>tk[ae])}var Z=(v(),C)[T+20>>>2>>>0];if(Z){let ae=function(Ot,pt,ms=!1){pt=Z+pt,(pt=(v(),C)[pt>>>2>>>0])==4294967295||ms&&pt==0||(Fe[Ot]=pt)},ut=function(Ot,pt){pt=Z+pt;var ms=(v(),C)[pt>>>2>>>0],qI=(v(),C)[pt+4>>>2>>>0];ms==4294967295&&qI==4294967295||(Fe[Ot]=lo(pt))};var Ie=ae,Ne=ut,Fe={};ae("maxTextureDimension1D",4),ae("maxTextureDimension2D",8),ae("maxTextureDimension3D",12),ae("maxTextureArrayLayers",16),ae("maxBindGroups",20),ae("maxBindGroupsPlusVertexBuffers",24),ae("maxDynamicUniformBuffersPerPipelineLayout",32),ae("maxDynamicStorageBuffersPerPipelineLayout",36),ae("maxSampledTexturesPerShaderStage",40),ae("maxSamplersPerShaderStage",44),ae("maxStorageBuffersPerShaderStage",48),ae("maxStorageTexturesPerShaderStage",52),ae("maxUniformBuffersPerShaderStage",56),ae("minUniformBufferOffsetAlignment",80),ae("minStorageBufferOffsetAlignment",84),ut("maxUniformBufferBindingSize",64),ut("maxStorageBufferBindingSize",72),ae("maxVertexBuffers",88),ut("maxBufferSize",96),ae("maxVertexAttributes",104),ae("maxVertexBufferArrayStride",108),ae("maxInterStageShaderVariables",112),ae("maxColorAttachments",116),ae("maxColorAttachmentBytesPerSample",120),ae("maxComputeWorkgroupStorageSize",124),ae("maxComputeInvocationsPerWorkgroup",128),ae("maxComputeWorkgroupSizeX",132),ae("maxComputeWorkgroupSizeY",136),ae("maxComputeWorkgroupSizeZ",140),ae("maxComputeWorkgroupsPerDimension",144),ae("maxImmediateSize",148,!0),p.requiredLimits=Fe}(z=(v(),C)[T+24>>>2>>>0])&&(z={label:yr(z+4)},p.defaultQueue=z),p.label=yr(T+4)}Oe+=1,sn(d,P.requestDevice(p).then(ae=>{--Oe,St(()=>{ht[E>>>0]=ae.queue,ht[g>>>0]=ae,Oe+=1,sn(h,ae.lost.then(ut=>{St(()=>{ae.onuncapturederror=()=>{};var Ot=fe(),pt=ir(ut.message);xf(h,wO[ut.reason],pt),pe(Ot)}),--Oe})),ae.onuncapturederror=ut=>{var Ot=5;ut.error instanceof GPUValidationError?Ot=2:ut.error instanceof GPUOutOfMemoryError?Ot=3:ut.error instanceof GPUInternalError&&(Ot=4);var pt=fe();ut=ir(ut.error.message),vk(g,Ot,ut),pe(pt)},"adapterInfo"in ae||(ae.adapterInfo=P.info),vf(d,1,g,0)})},ae=>{--Oe,St(()=>{var ut=fe(),Ot=ir(ae.message);vf(d,3,g,Ot),h&&xf(h,4,Ot),pe(ut)})}))}function yO(p){var d=oe(p>>>=0),h=xr[p];if(h){for(var g=0;g>>=0;var g=oe(p>>>=0);h==4294967295&&(h=void 0);try{var E=g.getMappedRange(d>>>0,h)}catch{return 0}var T=Af(16,E.byteLength);return(v(),X).set(new Uint8Array(E),T>>>0),xr[p].push(()=>Xt(T)),T}function vO(p,d,h){h>>>=0;var g=oe(p>>>=0);h==4294967295&&(h=void 0);try{var E=g.getMappedRange(d>>>0,h)}catch{return 0}var T=Af(16,E.byteLength);return(v(),X).fill(0,T,E.byteLength),xr[p].push(()=>{new Uint8Array(E).set((v(),X).subarray(T>>>0,T+E.byteLength>>>0)),Xt(T)}),T}function kO(p,d,h,g,E){p>>>=0,d=_t(d),h=_t(h),E>>>=0;var T=oe(p);xr[p]=[],E==4294967295&&(E=void 0),Oe+=1,sn(d,T.mapAsync(h,g>>>0,E).then(()=>{--Oe,St(()=>{yf(d,1,0)})},P=>{--Oe,St(()=>{fe();var z=ir(P.message);yf(d,P.name==="AbortError"?4:P.name==="OperationError"?3:0,z),delete xr[p]})}))}function EO(p){var d=oe(p>>>=0),h=xr[p];if(h){for(var g=0;g>>0]}function TO(p,d,h){p>>>=0,d>>>=0,h>>>=0;var g=!!(v(),C)[d+32>>>2>>>0];d={label:yr(d+4),usage:(v(),C)[d+16>>>2>>>0],size:lo(d+24),mappedAtCreation:g},p=oe(p);try{var E=p.createBuffer(d)}catch{return!1}return ht[h>>>0]=E,g&&(xr[h]=[]),!0}function MO(p,d,h,g){p>>>=0,d=_t(d),g>>>=0,h=dO(h>>>0),p=oe(p),Oe+=1,sn(d,p.createComputePipelineAsync(h).then(E=>{--Oe,St(()=>{ht[g>>>0]=E,wf(d,1,g,0)})},E=>{--Oe,St(()=>{var T=fe(),P=ir(E.message);wf(d,E.reason==="validation"?3:E.reason==="internal"?4:0,g,P),pe(T)})}))}function SO(p,d,h){p>>>=0,d>>>=0,h>>>=0;var g=(v(),C)[d>>>2>>>0],E=(v(),$)[g+4>>>2>>>0];d={label:yr(d+4),code:""},E===2&&(d.code=Zv(g+8)),p=oe(p).createShaderModule(d),ht[h>>>0]=p}var OO=p=>{(p=oe(p)).onuncapturederror=null,p.destroy()};function IO(p,d){d=_t(d),p=oe(p>>>0),Oe+=1,sn(d,p.popErrorScope().then(h=>{--Oe,St(()=>{var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var E=fe(),T=h?ir(h.message):0;bf(d,1,g,T),pe(E)})},h=>{--Oe,St(()=>{var g=fe(),E=ir(h.message);bf(d,1,5,E),pe(g)})}))}function CO(p,d,h,g){if(d=_t(d),g>>>=0,h>>>=0){var E={featureLevel:_O[(v(),$)[h+4>>>2>>>0]],powerPreference:hO[(v(),$)[h+8>>>2>>>0]],forceFallbackAdapter:!!(v(),C)[h+12>>>2>>>0]};(p=(v(),C)[h>>>2>>>0])!==0&&(v(),E.De=!!(v(),C)[p+8>>>2>>>0])}"gpu"in navigator?(Oe+=1,sn(d,navigator.gpu.requestAdapter(E).then(T=>{--Oe,St(()=>{if(T)ht[g>>>0]=T,co(d,1,g,0);else{var P=fe(),z=ir("WebGPU not available on this browser (requestAdapter returned null)");co(d,3,g,z),pe(P)}})},T=>{--Oe,St(()=>{var P=fe(),z=ir(T.message);co(d,4,g,z),pe(P)})}))):(E=fe(),p=ir("WebGPU not available on this browser (navigator.gpu is not available)"),co(d,3,g,p),pe(E))}function PO(p,d,h){return p>>>=0,d>>>=0,h>>>=0,qv(async()=>{var g=[];if(h){var E=(v(),$)[h>>>2>>>0];g.length=d+1,g[d]=new Promise(z=>setTimeout(z,E,0))}else g.length=d;for(var T=0;T{if(!_f){var p,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(p in hf)hf[p]===void 0?delete d[p]:d[p]=hf[p];var h=[];for(p in d)h.push(`${p}=${d[p]}`);_f=h}return _f};function sk(p,d){if(n)return Ue(19,1,p,d);p>>>=0,d>>>=0;var h,g=0,E=0;for(h of rk()){var T=d+g;(v(),C)[p+E>>>2>>>0]=T,g+=gr(h,T,1/0)+1,E+=4}return 0}function nk(p,d){if(n)return Ue(20,1,p,d);p>>>=0,d>>>=0;var h=rk();for(var g of((v(),C)[p>>>2>>>0]=h.length,p=0,h))p+=wr(g)+1;return(v(),C)[d>>>2>>>0]=p,0}function ok(p){return n?Ue(21,1,p):52}function ak(p,d,h,g){return n?Ue(22,1,p,d,h,g):52}function ik(p,d,h,g){return n?Ue(23,1,p,d,h,g):70}var LO=[null,[],[]];function lk(p,d,h,g){if(n)return Ue(24,1,p,d,h,g);d>>>=0,h>>>=0,g>>>=0;for(var E=0,T=0;T>>2>>>0],z=(v(),C)[d+4>>>2>>>0];d+=8;for(var j=0;j>>0],Ne=LO[Z];Ie===0||Ie===10?((Z===1?S:M)(Ev(Ne)),Ne.length=0):Ne.push(Ie)}E+=z}return(v(),C)[g>>>2>>>0]=E,0}function zO(p){return p>>>0}function NO(p,d){return ek(oe(p>>>0).limits,d>>>0),1}function RO(p,d){return oe(p>>>0).features.has(tk[d])}function $O(p){return BigInt(oe(p>>>0).size)}function DO(p){return BigInt(oe(p>>>0).usage)}function BO(p,d){if(p>>>=0,d>>>=0){var h=yr(d+4);h={label:h,timestampWrites:d=(d=(v(),C)[d+12>>>2>>>0])!==0?{querySet:oe((v(),C)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(v(),C)[d+8>>>2>>>0],endOfPassWriteIndex:(v(),C)[d+12>>>2>>>0]}:void 0}}return d=oe(p),p=gk(0),h=d.beginComputePass(h),ht[p>>>0]=h,p}function UO(p,d,h,g){h=_t(h),(g=_t(g))==-1&&(g=void 0),(p=oe(p>>>0)).clearBuffer(oe(d>>>0),h,g)}function FO(p,d,h,g,E,T){h=_t(h),E=_t(E),T=_t(T),oe(p>>>0).copyBufferToBuffer(oe(d>>>0),h,oe(g>>>0),E,T)}function GO(p){var d=oe(p>>>0);return p=_k(0),d=d.finish(),ht[p>>>0]=d,p}function jO(p,d,h,g,E,T){T=_t(T),oe(p>>>0).resolveQuerySet(oe(d>>>0),h,g,oe(E>>>0),T)}function qO(p,d,h,g){oe(p>>>0).dispatchWorkgroups(d,h,g)}function WO(p,d,h){h=_t(h),oe(p>>>0).dispatchWorkgroupsIndirect(oe(d>>>0),h)}function VO(p){oe(p>>>0).end()}function HO(p,d,h,g,E){g>>>=0,E>>>=0,p=oe(p>>>0),h=oe(h>>>0),g==0?p.setBindGroup(d,h):p.setBindGroup(d,h,(v(),C),E>>>2,g)}function XO(p,d){oe(p>>>0).setPipeline(oe(d>>>0))}function YO(p,d,h){oe(p>>>0).Ce(oe(d>>>0),h)}function KO(p,d){var h=oe(p>>>0);return p=mk(0),d=h.getBindGroupLayout(d),ht[p>>>0]=d,p}function QO(p,d){function h(E){var T=(v(),C)[E+8>>>2>>>0],P=(v(),C)[E+32>>>2>>>0],z=(v(),C)[E+36>>>2>>>0],j=0;return fO(E,{327681:Z=>{j=(v(),C)[Z+8>>>2>>>0]}}),T?((P=lo(E+24))==-1&&(P=void 0),T={buffer:oe(T),offset:lo(E+16),size:P}):T=oe(P||z||j),{binding:(v(),C)[E+4>>>2>>>0],resource:T}}p>>>=0,d={label:yr(4+(d>>>=0)),layout:oe((v(),C)[d+12>>>2>>>0]),entries:(function(E,T){for(var P=[],z=0;z>>2>>>0],(v(),C)[d+20>>>2>>>0])},p=oe(p);var g=dk(0);return pO(g,p.createBindGroup(d)),g}function JO(p,d){var h;return p>>>=0,(d>>>=0)&&(h={label:yr(d+4)}),d=oe(p),p=hk(0),h=d.createCommandEncoder(h),ht[p>>>0]=h,p}function ZO(p,d){p>>>=0,d>>>=0,d={type:gO[(v(),$)[d+12>>>2>>>0]],count:(v(),C)[d+16>>>2>>>0]};var h=oe(p);return p=wk(0),d=h.createQuerySet(d),ht[p>>>0]=d,p}function eI(p,d){p=oe(p>>>0).adapterInfo,d>>>=0,(v(),C)[d+52>>>2>>>0]=p.subgroupMinSize,(v(),C)[d+56>>>2>>>0]=p.subgroupMaxSize;var h=p.vendor+p.architecture+p.device+p.description,g=wr(h)+1,E=nn(g);return E&&gr(h,E,g),h=E,g=wr(p.vendor),tc(d+4,h,g),h+=g,g=wr(p.architecture),tc(d+12,h,g),h+=g,g=wr(p.device),tc(d+20,h,g),tc(d+28,h+g,wr(p.description)),(v(),$)[d+36>>>2>>>0]=2,p=p.isFallbackAdapter?3:4,(v(),$)[d+40>>>2>>>0]=p,(v(),C)[d+44>>>2>>>0]=0,(v(),C)[d+48>>>2>>>0]=0,1}var tI={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function rI(p,d){d>>>=0;var h=oe(p>>>0);p=nn(4*h.features.size);var g=0,E=0;for(let T of h.features)0<=(h=tI[T])&&((v(),$)[p+g>>>2>>>0]=h,g+=4,E++);(v(),C)[d+4>>>2>>>0]=p,(v(),C)[d>>>2>>>0]=E}function sI(p,d){return ek(oe(p>>>0).limits,d>>>0),1}function nI(p,d){oe(p>>>0).pushErrorScope(mO[d])}function oI(p,d,h){d>>>=0,h>>>=0,p=oe(p>>>0),d=Array.from((v(),$).subarray(h>>>2>>>0,h+4*d>>>2>>>0),g=>oe(g)),p.submit(d)}function aI(p,d,h,g,E){h=_t(h),g>>>=0,E>>>=0,p=oe(p>>>0),d=oe(d>>>0),g=(v(),X).subarray(g>>>0,g+E>>>0),p.writeBuffer(d,h,g,0,E)}n||(function(){for(var p=e.numThreads-1;p--;)gv();Be.push(async()=>{var d=(async function(){if(!n)return Promise.all(Or.map(hv))})();Se++,await d,--Se==0&&rt&&(d=rt,rt=null,d())})})(),n||(Ir=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),le()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>fe(),e.stackRestore=p=>pe(p),e.stackAlloc=p=>sc(p),e.setValue=function(p,d,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(v(),F)[p>>>0]=d;break;case"i16":(v(),Y)[p>>>1>>>0]=d;break;case"i32":(v(),$)[p>>>2>>>0]=d;break;case"i64":(v(),L)[p>>>3>>>0]=BigInt(d);break;case"float":(v(),se)[p>>>2>>>0]=d;break;case"double":(v(),K)[p>>>3>>>0]=d;break;case"*":(v(),C)[p>>>2>>>0]=d;break;default:ce(`invalid type for setValue: ${h}`)}},e.getValue=function(p,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(v(),F)[p>>>0];case"i16":return(v(),Y)[p>>>1>>>0];case"i32":return(v(),$)[p>>>2>>>0];case"i64":return(v(),L)[p>>>3>>>0];case"float":return(v(),se)[p>>>2>>>0];case"double":return(v(),K)[p>>>3>>>0];case"*":return(v(),C)[p>>>2>>>0];default:ce(`invalid type for getValue: ${d}`)}},e.UTF8ToString=tn,e.stringToUTF8=gr,e.lengthBytesUTF8=wr;var ck,uk,gf,rc,Xt,nn,pk,fk,dk,mk,_k,hk,gk,wk,xk,yk,bk,wf,xf,yf,bf,co,vf,vk,kf,kk,Ek,Ak,Ef,Tk,Mk,Af,xe,uo,Sk,pe,sc,fe,Ok,Tf,Ik,Ck,Pk,Mf,Lk,zk,Nk,Rk,$k,Dk,Bk,Uk,Fk,Gk,jk,qk,Wk,Vk,Hk,Xk,Yk,Kk,Qk,Jk,Zk,eE,tE,rE,sE,nE,oE,aE,iE,lE,cE,uE,pE,fE,dE,mE,_E,hE,br,iI=[Js,oo,yv,Av,Tv,Mv,Sv,Ov,Iv,Cv,Pv,Lv,zv,Nv,Rv,$v,Yv,Kv,Qv,sk,nk,ok,ak,ik,lk],Sf={970348:(p,d,h,g,E)=>{if(e===void 0||!e.Uc)return 1;if((p=tn(Number(p>>>0))).startsWith("./")&&(p=p.substring(2)),!(p=e.Uc.get(p)))return 2;if(d=Number(d>>>0),h=Number(h>>>0),g=Number(g>>>0),d+h>p.byteLength)return 3;try{let T=p.subarray(d,d+h);switch(E){case 0:(v(),X).set(T,g>>>0);break;case 1:e.ad?e.ad(g,T):e.ne(g,T);break;default:return 4}return 0}catch{return 4}},971172:(p,d,h)=>{e.Sd(p,(v(),X).subarray(d>>>0,d+h>>>0))},971236:()=>e.le(),971278:p=>{e.jd(p)},971315:()=>typeof wasmOffsetConverter<"u"};function lI(p,d,h,g){var E=fe();try{return Uk(p,d,h,g)}catch(T){if(pe(E),T!==T+0)throw T;xe(1,0)}}function cI(p,d,h){var g=fe();try{return $k(p,d,h)}catch(E){if(pe(g),E!==E+0)throw E;xe(1,0)}}function uI(p){var d=fe();try{Lk(p)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function pI(p,d){var h=fe();try{return Mf(p,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function fI(p,d,h){var g=fe();try{Pk(p,d,h)}catch(E){if(pe(g),E!==E+0)throw E;xe(1,0)}}function dI(p,d){var h=fe();try{Fk(p,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function mI(p,d,h,g,E,T,P){var z=fe();try{return Rk(p,d,h,g,E,T,P)}catch(j){if(pe(z),j!==j+0)throw j;xe(1,0)}}function _I(p,d,h,g,E,T){var P=fe();try{zk(p,d,h,g,E,T)}catch(z){if(pe(P),z!==z+0)throw z;xe(1,0)}}function hI(p,d,h,g){var E=fe();try{Bk(p,d,h,g)}catch(T){if(pe(E),T!==T+0)throw T;xe(1,0)}}function gI(p,d,h,g,E,T,P){var z=fe();try{jk(p,d,h,g,E,T,P)}catch(j){if(pe(z),j!==j+0)throw j;xe(1,0)}}function wI(p,d,h,g,E,T,P){var z=fe();try{qk(p,d,h,g,E,T,P)}catch(j){if(pe(z),j!==j+0)throw j;xe(1,0)}}function xI(p,d,h,g,E,T,P,z){var j=fe();try{Zk(p,d,h,g,E,T,P,z)}catch(Z){if(pe(j),Z!==Z+0)throw Z;xe(1,0)}}function yI(p,d,h,g,E,T,P,z,j,Z,Ie,Ne){var Fe=fe();try{Wk(p,d,h,g,E,T,P,z,j,Z,Ie,Ne)}catch(ae){if(pe(Fe),ae!==ae+0)throw ae;xe(1,0)}}function bI(p,d,h,g,E){var T=fe();try{return Gk(p,d,h,g,E)}catch(P){if(pe(T),P!==P+0)throw P;xe(1,0)}}function vI(p,d,h,g,E){var T=fe();try{Nk(p,d,h,g,E)}catch(P){if(pe(T),P!==P+0)throw P;xe(1,0)}}function kI(p,d,h,g,E,T,P,z){var j=fe();try{Dk(p,d,h,g,E,T,P,z)}catch(Z){if(pe(j),Z!==Z+0)throw Z;xe(1,0)}}function EI(p){var d=fe();try{return eE(p)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function AI(p,d,h){var g=fe();try{return tE(p,d,h)}catch(E){if(pe(g),E!==E+0)throw E;xe(1,0)}}function TI(p,d){var h=fe();try{return fE(p,d)}catch(g){if(pe(h),g!==g+0)throw g;return xe(1,0),0n}}function MI(p){var d=fe();try{return Vk(p)}catch(h){if(pe(d),h!==h+0)throw h;return xe(1,0),0n}}function SI(p,d,h,g){var E=fe();try{return rE(p,d,h,g)}catch(T){if(pe(E),T!==T+0)throw T;xe(1,0)}}function OI(p,d,h,g,E){var T=fe();try{return sE(p,d,h,g,E)}catch(P){if(pe(T),P!==P+0)throw P;xe(1,0)}}function II(p,d,h,g,E,T){var P=fe();try{return nE(p,d,h,g,E,T)}catch(z){if(pe(P),z!==z+0)throw z;xe(1,0)}}function CI(p,d,h,g,E,T){var P=fe();try{return Qk(p,d,h,g,E,T)}catch(z){if(pe(P),z!==z+0)throw z;xe(1,0)}}function PI(p,d,h,g,E,T){var P=fe();try{return oE(p,d,h,g,E,T)}catch(z){if(pe(P),z!==z+0)throw z;xe(1,0)}}function LI(p,d,h,g,E,T,P,z){var j=fe();try{return Jk(p,d,h,g,E,T,P,z)}catch(Z){if(pe(j),Z!==Z+0)throw Z;xe(1,0)}}function zI(p,d,h,g,E){var T=fe();try{return aE(p,d,h,g,E)}catch(P){if(pe(T),P!==P+0)throw P;return xe(1,0),0n}}function NI(p,d,h,g){var E=fe();try{return iE(p,d,h,g)}catch(T){if(pe(E),T!==T+0)throw T;xe(1,0)}}function RI(p,d,h,g){var E=fe();try{return lE(p,d,h,g)}catch(T){if(pe(E),T!==T+0)throw T;xe(1,0)}}function $I(p,d,h,g,E,T,P,z,j,Z,Ie,Ne){var Fe=fe();try{return cE(p,d,h,g,E,T,P,z,j,Z,Ie,Ne)}catch(ae){if(pe(Fe),ae!==ae+0)throw ae;xe(1,0)}}function DI(p,d,h,g,E,T,P,z,j,Z,Ie){var Ne=fe();try{uE(p,d,h,g,E,T,P,z,j,Z,Ie)}catch(Fe){if(pe(Ne),Fe!==Fe+0)throw Fe;xe(1,0)}}function BI(p,d,h,g,E,T,P,z,j,Z,Ie,Ne,Fe,ae,ut,Ot){var pt=fe();try{pE(p,d,h,g,E,T,P,z,j,Z,Ie,Ne,Fe,ae,ut,Ot)}catch(ms){if(pe(pt),ms!==ms+0)throw ms;xe(1,0)}}function UI(p,d,h){var g=fe();try{return Xk(p,d,h)}catch(E){if(pe(g),E!==E+0)throw E;return xe(1,0),0n}}function FI(p,d,h){var g=fe();try{return Hk(p,d,h)}catch(E){if(pe(g),E!==E+0)throw E;xe(1,0)}}function GI(p,d,h){var g=fe();try{return Yk(p,d,h)}catch(E){if(pe(g),E!==E+0)throw E;xe(1,0)}}function jI(p,d,h,g){var E=fe();try{Kk(p,d,h,g)}catch(T){if(pe(E),T!==T+0)throw T;xe(1,0)}}function nc(){if(0{let d=new WeakMap,h,g,E=1;e.webgpuRegisterDevice=z=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(z){var j=d.get(z);if(!j){let Z=((Ie,Ne=0)=>{var Fe=bk(Ne);return Ne=yk(Ne,Fe),ht[Fe>>>0]=Ie.queue,ht[Ne>>>0]=Ie,Ne})(z,j=fk(0));j=[E++,j,Z],d.set(z,j)}return h=z,g=j[0],j}h=void 0,g=0};let T=new Map;e.webgpuOnCreateSession=z=>{if(g!==void 0){var j=g;if(g=void 0,z){let Z=gf(j);T.set(z,Z),j===0&&p(h??oe(Z))}h=void 0}},e.webgpuOnReleaseSession=z=>{T.delete(z)};let P=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(z,j,Z)=>{if(Z)return z[P]=[Z,NaN],Z;if(Z=z[P])return Z[1]++,Z[0];if((j=T.get(j))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return j=((Ie,Ne=0)=>(Ie.mapState==="unmapped"||ce(),Ne=xk(Ne),ht[Ne>>>0]=Ie,Ne))(z,j),z[P]=[j,1],j},e.webgpuUnregisterBuffer=z=>{let j=z[P];if(!j)throw Error("Buffer is not registered");j[1]--,j[1]===0&&(pk(j[0]),delete z[P])},e.webgpuGetBuffer=z=>oe(z),e.webgpuCreateDownloader=(z,j,Z)=>{if((Z=T.get(Z))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Ie=oe(Z),Ne=16*Math.ceil(Number(j)/16);return async()=>{let Fe=Ie.createBuffer({size:Ne,usage:9});try{let ae=Ie.createCommandEncoder();return ae.copyBufferToBuffer(z,0,Fe,0,Ne),Ie.queue.submit([ae.finish()]),await Fe.mapAsync(GPUMapMode.READ),Fe.getMappedRange().slice(0,j)}finally{Fe.destroy()}}},e.ad=(z,j)=>{var Z=j.buffer;let Ie=j.byteOffset,Ne=j.byteLength;if(j=16*Math.ceil(Number(Ne)/16),z=oe(z),!h){var Fe=gf(g);h=oe(Fe)}let ae=(Fe=h.createBuffer({mappedAtCreation:!0,size:j,usage:6})).getMappedRange();new Uint8Array(ae).set(new Uint8Array(Z,Ie,Ne)),Fe.unmap(),(Z=h.createCommandEncoder()).copyBufferToBuffer(Fe,0,z,0,j),h.queue.submit([Z.finish()]),Fe.destroy()}},e.webnnInit=p=>{let d=p[0];[e.le,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.ke,e.webnnEnableTraceEvent]=p.slice(1),e.webnnReleaseTensorId=e.jd,e.webnnUploadTensor=e.Sd,e.webnnRegisterMLContext=e.ke,e.webnnOnRunStart=h=>d.onRunStart(h),e.webnnOnRunEnd=d.onRunEnd.bind(d),e.webnnOnReleaseSession=h=>{d.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>d.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,E,T)=>d.registerMLTensor(h,g,E,T),e.webnnCreateMLContext=h=>d.createMLContext(h),e.webnnRegisterMLConstant=(h,g,E,T,P,z)=>d.registerMLConstant(h,g,E,T,P,e.Uc,z),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},Q?e:new Promise((p,d)=>{w=p,x=d})}var _2,vA,Dz=be(()=>{"use strict";_2=bA,vA=globalThis.self?.name?.startsWith("em-pthread"),vA&&bA()}),Qf,dd,kA,zt,h2,yc,EA,AA,Jf,TA,Zf,g2,ed,w2,vd=be(()=>{"use strict";bd(),Qf=typeof location>"u"?void 0:location.origin,dd=import_meta.url>"file:"&&import_meta.url<"file;",kA=()=>{if(dd){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import_meta.url).href,Qf).href}return import_meta.url},zt=kA(),h2=()=>{if(zt&&!zt.startsWith("blob:"))return zt.substring(0,zt.lastIndexOf("/")+1)},yc=(t,e)=>{try{let r=e??zt;return(r?new URL(t,r):new URL(t)).origin===Qf}catch{return!1}},EA=(t,e)=>{let r=e??zt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},AA=(t,e)=>`${e??"./"}${t}`,Jf=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},TA=async t=>(await import(t)).default,Zf=($z(),Tc(f2)).default,g2=async()=>{if(!zt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(yc(zt))return[void 0,Zf()];let t=await Jf(zt);return[t,Zf(t)]},ed=(Dz(),Tc(m2)).default,w2=async(t,e,r,s)=>{let n=ed&&!(t||e);if(n)if(zt)n=yc(zt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,ed];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??EA(o,e),i=r&&a&&!yc(a,e),l=i?await Jf(a):a??AA(o,e);return[i?l:void 0,await TA(l)]}}}),td,bc,ko,rd,MA,SA,OA,kd,De,Is=be(()=>{"use strict";vd(),bc=!1,ko=!1,rd=!1,MA=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},SA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},OA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},kd=async t=>{if(bc)return Promise.resolve();if(ko)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(rd)throw new Error("previous call to 'initializeWebAssembly()' failed.");ko=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!OA())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!SA())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=MA();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,u=t.wasmBinary,[f,m]=await w2(i,o,r>1,!!u||!!c),_=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{_=!0,x()},e)})),w.push(new Promise((x,b)=>{let A={numThreads:r};if(u)A.wasmBinary=u,A.locateFile=k=>k;else if(c||o)A.locateFile=k=>c??o+k;else if(i&&i.indexOf("blob:")!==0)A.locateFile=k=>new URL(k,i).href;else if(f){let k=h2();k&&(A.locateFile=S=>k+S)}m(A).then(k=>{ko=!1,bc=!0,td=k,x(),f&&URL.revokeObjectURL(f)},k=>{ko=!1,rd=!0,b(k)})})),await Promise.race(w),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},De=()=>{if(bc&&td)return td;throw new Error("WebAssembly is not initialized yet.")}}),Nt,Sc,Le,Ed=be(()=>{"use strict";Is(),Nt=(t,e)=>{let r=De(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},Sc=(t,e,r,s)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([n,o])=>{let a=e?e+n:n;if(typeof o=="object")Sc(o,a+".",r,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Le=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetLastError(n,n+s);let o=Number(e.getValue(n,s===4?"i32":"i64")),a=e.getValue(n+s,"*"),i=a?e.UTF8ToString(a):"";throw new Error(`${t} ERROR_CODE: ${o}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}}),x2,Bz=be(()=>{"use strict";Is(),Ed(),x2=t=>{let e=De(),r=0,s=[],n=t||{};try{if(t?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(n.terminate=!1);let o=0;return t?.tag!==void 0&&(o=Nt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&Le("Can't create run options."),t?.extra!==void 0&&Sc(t.extra,"",new WeakSet,(a,i)=>{let l=Nt(a,s),c=Nt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&Le(`Can't set a run config entry: ${a} - ${i}.`)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),s.forEach(a=>e._free(a)),o}}}),IA,CA,PA,vc,Br,LA,y2,Uz=be(()=>{"use strict";Is(),Ed(),IA=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},CA=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},PA=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},vc=(t,e,r,s)=>{let n=Nt(e,s),o=Nt(r,s);De()._OrtAddSessionConfigEntry(t,n,o)!==0&&Le(`Can't set a session config entry: ${e} - ${r}.`)},Br=(t,e,r,s)=>{let n=Nt(e,s),o=Nt(r,s);t.push([n,o])},LA=async(t,e,r)=>{let s=e.executionProviders;for(let n of s){let o=typeof n=="string"?n:n.name,a=[];switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let f=n?.deviceType;f&&vc(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let _=n;if(_.device)if(typeof GPUDevice<"u"&&_.device instanceof GPUDevice)f=_.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&Br(a,"enableGraphCapture","1",r),typeof _.preferredLayout=="string"&&Br(a,"preferredLayout",_.preferredLayout,r),_.forceCpuNodeNames){let x=Array.isArray(_.forceCpuNodeNames)?_.forceCpuNodeNames:[_.forceCpuNodeNames];Br(a,"forceCpuNodeNames",x.join(` ++`),r)}_.validationMode&&Br(a,"validationMode",_.validationMode,r)}let m=De().webgpuRegisterDevice(f);if(m){let[_,w,x]=m;Br(a,"deviceId",_.toString(),r),Br(a,"webgpuInstance",w.toString(),r),Br(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=Nt(o,r),l=a.length,c=0,u=0;if(l>0){c=De()._malloc(l*De().PTR_SIZE),r.push(c),u=De()._malloc(l*De().PTR_SIZE),r.push(u);for(let f=0;f{let e=De(),r=0,s=[],n=t||{};PA(n);try{let o=IA(n.graphOptimizationLevel??"all"),a=CA(n.executionMode??"sequential"),i=typeof n.logId=="string"?Nt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let u=typeof n.optimizedModelFilePath=="string"?Nt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,u),r===0&&Le("Can't create session options."),n.executionProviders&&await LA(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);vc(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[f,m]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof m!="number"||!Number.isInteger(m)||m<0)throw new Error(`free dimension override value must be a non-negative integer: ${m}`);let _=Nt(f,s);e._OrtAddFreeDimensionOverride(r,_,m)!==0&&Le(`Can't set a free dimension override: ${f} - ${m}.`)}return n.extra!==void 0&&Sc(n.extra,"",new WeakSet,(f,m)=>{vc(r,f,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Le("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),As,Ac,fn,So,Oc,Ad,Td,md,dn=be(()=>{"use strict";As=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},Ac=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},fn=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],s=typeof e=="number"?e:e.reduce((n,o)=>n*o,1);return r>0?Math.ceil(s*r):void 0},So=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Oc=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},Ad=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Td=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",md=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${t}`)}}}),Md,b2=be(()=>{"use strict";bd(),Md=async t=>{if(typeof t=="string"){let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(o,a,c).set(l),a+=c}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),v2,Fz=be(()=>{"use strict";dn(),v2=(t,e)=>new(So(e))(t)}),zA,NA,RA,$A,k2,DA,vt,E2=be(()=>{"use strict";dn(),zA=["V","I","W","E","F"],NA=(t,e)=>{console.log(`[${zA[t]},${new Date().toISOString()}]${e}`)},k2=(t,e)=>{RA=t,$A=e},DA=(t,e)=>{let r=Oc(t),s=Oc(RA);r>=s&&NA(r,typeof e=="function"?e():e)},vt=(...t)=>{$A&&DA(...t)}}),sd,_d,nd,BA,od,UA,ad,id,ld,FA,A2,Gz=be(()=>{"use strict";dn(),E2(),sd=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),_d=(t,e)=>{if(e==="int32")return t;let r=sd.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);let s=r/8;if(t.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=t.byteLength/s,o=new(So(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(l)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&o.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(o,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},nd=(t,e)=>{if(e==="int32")return t;if(t.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=t.byteLength/4,s=new Int32Array(t.buffer,t.byteOffset,r);switch(e){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(o=>o<-128||o>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${e}`)}},BA=1,od=()=>BA++,UA=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),ad=(t,e)=>{let r=sd.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);return e.length>0?Math.ceil(e.reduce((s,n)=>s*n)*r/8):0},id=class{constructor(t){this.isDataConverted=!1;let{sessionId:e,context:r,tensor:s,dataType:n,shape:o,fallbackDataType:a}=t;this.sessionId=e,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.fallbackDataType=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return ad(this.dataType,this.tensorShape)}destroy(){vt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){if(this.fallbackDataType){let e=await this.mlContext.readTensor(this.mlTensor),r=nd(new Uint8Array(e),this.dataType);if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(r);return}else return r.buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,e,r){return this.mlContext===t&&this.dataType===e&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(t){this.isDataConverted=t}},ld=class{constructor(t,e){this.tensorManager=t,this.wrapper=e}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,e,r,s){let n=this.tensorManager.getMLContext(t),o=this.tensorManager.getMLOpSupportLimits(t),a;if(!o?.input.dataTypes.includes(e)){if(a=UA.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);vt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${e} to ${a}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,e,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==ad(e,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,e,r,i,!0,!0,a),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){let e=t;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")e=_d(t,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else vt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(t){if(this.activeUpload){let e=this.wrapper?.isDataConverted?nd(this.activeUpload,this.wrapper?.type):this.activeUpload;if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(e):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(e);return}else return e.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(t):this.wrapper.read()}},FA=class{constructor(t){this.backend=t,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(t){let e=this.backend.getMLContext(t);if(!e)throw new Error("MLContext not found for session.");return e}getMLOpSupportLimits(t){return this.backend.getMLOpSupportLimits(t)}reserveTensorId(){let t=od();return this.tensorTrackersById.set(t,new ld(this)),t}releaseTensorId(t){let e=this.tensorTrackersById.get(t);e&&(this.tensorTrackersById.delete(t),e.tensorWrapper&&this.releaseTensor(e.tensorWrapper))}async ensureTensor(t,e,r,s,n){vt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,s,n)}upload(t,e){let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");r.upload(e)}async download(t,e){vt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${e?.byteLength}}`);let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");return r.download(e)}releaseTensorsForSession(t){for(let e of this.freeTensors)e.sessionId===t&&e.destroy();this.freeTensors=this.freeTensors.filter(e=>e.sessionId!==t)}registerTensor(t,e,r,s){let n=this.getMLContext(t),o=od(),a=new id({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new ld(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,u]of this.freeTensors.entries())if(u.canReuseTensor(i,e,r)){vt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}vt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:a??e,shape:r,dimensions:r,usage:s,writable:n,readable:o});return new id({sessionId:t,context:i,tensor:l,dataType:e,shape:r,fallbackDataType:a})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},A2=(...t)=>new FA(...t)}),T2={};Oo(T2,{WebNNBackend:()=>M2});var Eo,GA,M2,jz=be(()=>{"use strict";dn(),Is(),Fz(),Gz(),E2(),Eo=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),GA=(t,e)=>{if(t===e)return!0;if(t===void 0||e===void 0)return!1;let r=Object.keys(t).sort(),s=Object.keys(e).sort();return r.length===s.length&&r.every((n,o)=>n===s[o]&&t[n]===e[n])},M2=class{constructor(t){this.tensorManager=A2(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,k2(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){vt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){vt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)vt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(t),this.activeSessionId=void 0}}async createMLContext(t){if(t instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===t);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:s}),s}}else if(t===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let e=this.mlContextCache.findIndex(r=>GA(r.options,t));if(e!==-1)return this.mlContextCache[e].mlContext;{let r=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:r}),r}}registerMLContext(t,e){this.mlContextBySessionId.set(t,e);let r=this.sessionIdsByMLContext.get(e);r||(r=new Set,this.sessionIdsByMLContext.set(e,r)),r.add(t),this.mlOpSupportLimitsBySessionId.has(t)||this.mlOpSupportLimitsBySessionId.set(t,e.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(t,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(t,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(t){this.sessionGraphInputs.delete(t),this.sessionGraphOutputs.delete(t);let e=this.mlContextBySessionId.get(t);if(!e)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t),this.mlOpSupportLimitsBySessionId.delete(t);let r=this.sessionIdsByMLContext.get(e);if(r.delete(t),r.size===0){this.sessionIdsByMLContext.delete(e);let s=this.mlContextCache.findIndex(n=>n.mlContext===e);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}getMLOpSupportLimits(t){return this.mlOpSupportLimitsBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){vt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=Eo.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t??this.currentSessionId,e,o,s,n)}async createTemporaryTensor(t,e,r){vt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=Eo.get(e);if(!s)throw new Error(`Unsupported ONNX data type: ${e}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(t,n,s,r,!1);let o=this.temporarySessionTensorIds.get(t);return o?o.push(n):this.temporarySessionTensorIds.set(t,[n]),n}uploadTensor(t,e){if(!De().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");vt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${e.byteLength}}`),this.tensorManager.upload(t,e)}async downloadTensor(t,e){return this.tensorManager.download(t,e)}createMLTensorDownloader(t,e){return async()=>{let r=await this.tensorManager.download(t);return v2(r,e)}}registerMLTensor(t,e,r,s){let n=Eo.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return vt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(e,e+r).buffer,u;switch(n.dataType){case"float32":u=new Float32Array(c);break;case"float16":u=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":u=new Int32Array(c);break;case"uint32":u=new Uint32Array(c);break;case"int64":if(a){let f=_d(new Uint8Array(c),"int64");u=new Int32Array(f.buffer),n.dataType="int32"}else u=new BigInt64Array(c);break;case"uint64":u=new BigUint64Array(c);break;case"int8":u=new Int8Array(c);break;case"int4":case"uint4":case"uint8":u=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return vt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,u)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=Eo.get(As(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),jA,Sd,Od,Ur,qA,cd,Ic,Id,Cd,ud,Pd,Ld,zd,S2=be(()=>{"use strict";Os(),Bz(),Uz(),dn(),Is(),Ed(),b2(),jA=(t,e)=>{De()._OrtInit(t,e)!==0&&Le("Can't initialize onnxruntime.")},Sd=async t=>{jA(t.wasm.numThreads,Oc(t.logLevel))},Od=async(t,e)=>{De().asyncInit?.();let r=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=t.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let n=t.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(e==="webgpu"&&De().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(jz(),Tc(T2)).WebNNBackend(t);De().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,o,a,i,l)=>s.ensureTensor(n,o,a,i,l),(n,o)=>{s.uploadTensor(n,o)},async(n,o)=>s.downloadTensor(n,o),(n,o)=>s.registerMLContext(n,o),!!t.trace])}},Ur=new Map,qA=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetInputOutputCount(t,n,n+s)!==0&&Le("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(e.getValue(n,o)),Number(e.getValue(n+s,o))]}finally{e.stackRestore(r)}},cd=(t,e)=>{let r=De(),s=r.stackSave(),n=0;try{let o=r.PTR_SIZE,a=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(t,e,a,a+o)!==0&&Le("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],u=[];for(let f=0;f{let e=De(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},Id=async(t,e)=>{let r,s,n=De();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=Ic(t);let o=0,a=0,i=0,l=[],c=[],u=[];try{if([a,l]=await y2(e),e?.externalData&&n.mountExternalData){let M=[];for(let O of e.externalData){let I=typeof O=="string"?O:O.path;M.push(Md(typeof O=="string"?O:O.data).then(v=>{n.mountExternalData(I,v)}))}await Promise.all(M)}for(let M of e?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof M!="string"){let O=M,I=O?.context,v=O?.gpuDevice,B=O?.deviceType,G=O?.powerPreference;I?n.currentContext=I:v?n.currentContext=await n.webnnCreateMLContext(v):n.currentContext=await n.webnnCreateMLContext({deviceType:B,powerPreference:G})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Le("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,m]=qA(o),_=!!e?.enableGraphCapture,w=[],x=[],b=[],A=[],k=[];for(let M=0;MM==="gpu-buffer"||M==="ml-tensor"||M==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&Le("Can't create IO binding."),S={handle:i,outputPreferredLocations:k,outputPreferredLocationsEncoded:k.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>md(M))}),Ur.set(o,[o,c,u,S,_,!1]),[o,w,x,b,A]}catch(f){throw c.forEach(m=>n._OrtFree(m)),u.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&Le("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Le("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Le("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},Cd=t=>{let e=De(),r=Ur.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&Le("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Le("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(l=>e._OrtFree(l)),o.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(s)!==0&&Le("Can't release session."),Ur.delete(t)},ud=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=De(),l=i.PTR_SIZE,c=t[0],u=t[1],f=t[3],m=f,_,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let A=t[2].gpuBuffer;w=fn(As(c),u);{let k=i.webgpuRegisterBuffer;if(!k)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=k(A,s)}}else if(f==="ml-tensor"){let A=t[2].mlTensor;w=fn(As(c),u);let k=i.webnnRegisterMLTensor;if(!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=k(s,A,As(c),u)}else{let A=t[2];if(Array.isArray(A)){w=l*A.length,_=i._malloc(w),r.push(_);for(let k=0;ki.setValue(b+S*l,k,l===4?"i32":"i64"));let A=i._OrtCreateTensor(As(c),_,w,b,u.length,md(m));A===0&&Le(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(A)}finally{i.stackRestore(x)}},Pd=async(t,e,r,s,n,o)=>{let a=De(),i=a.PTR_SIZE,l=Ur.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],u=l[1],f=l[2],m=l[3],_=l[4],w=l[5],x=e.length,b=s.length,A=0,k=[],S=[],M=[],O=[],I=[],v=a.stackSave(),B=a.stackAlloc(x*i),G=a.stackAlloc(x*i),F=a.stackAlloc(b*i),X=a.stackAlloc(b*i);try{[A,k]=x2(o),Gr("wasm prepareInputOutputTensor");for(let C=0;CBe*Se,1);U=Ac(je);let Mt=m?.outputPreferredLocations[s[C]];if(U==="string"){if(Mt==="gpu-buffer"||Mt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Be=[];for(let Se=0;Se0){let Be=a.webgpuGetBuffer;if(!Be)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Se=Be(Q),rt=fn(je,ct);if(rt===void 0||!Ad(U))throw new Error(`Unsupported data type: ${U}`);R=!0;{a.webgpuRegisterBuffer(Se,t,Q);let nr=a.webgpuCreateDownloader(Se,rt,t);J.push([U,qe,{gpuBuffer:Se,download:async()=>{let Oe=await nr();return new(So(U))(Oe)},dispose:()=>{a._OrtReleaseTensor(se)!==0&&Le("Can't release tensor.")}},"gpu-buffer"])}}else if(Mt==="ml-tensor"&&ct>0){let Be=a.webnnEnsureTensor,Se=a.webnnIsGraphInputOutputTypeSupported;if(!Be||!Se)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(fn(je,ct)===void 0||!Td(U))throw new Error(`Unsupported data type: ${U}`);if(!Se(t,U,!1))throw new Error(`preferredLocation "ml-tensor" for ${U} output is not supported by current WebNN Context.`);let rt=await Be(t,Q,je,qe,!1);R=!0,J.push([U,qe,{mlTensor:rt,download:a.webnnCreateMLTensorDownloader(Q,U),dispose:()=>{a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(se)}},"ml-tensor"])}else if(Mt==="ml-tensor-cpu-output"&&ct>0){let Be=a.webnnCreateMLTensorDownloader(Q,U)(),Se=J.length;R=!0,$.push((async()=>{let rt=[Se,await Be];return a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(se),rt})()),J.push([U,qe,[],"cpu"])}else{let Be=So(U),Se=new Be(ct);new Uint8Array(Se.buffer,Se.byteOffset,Se.byteLength).set(a.HEAPU8.subarray(Q,Q+Se.byteLength)),J.push([U,qe,Se,"cpu"])}}finally{a.stackRestore(K),U==="string"&&Q&&a._free(Q),R||a._OrtReleaseTensor(se)}}m&&!_&&(a._OrtClearBoundOutputs(m.handle)!==0&&Le("Can't clear bound outputs."),Ur.set(t,[c,u,f,m,_,!1]));for(let[C,se]of await Promise.all($))J[C][2]=se;return jr("wasm ProcessOutputTensor"),J}finally{a.webnnOnRunEnd?.(c),a.stackRestore(v),r.forEach(Y=>{Y&&Y[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(Y[2].gpuBuffer)}),n.forEach(Y=>{Y&&Y[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(Y[2].gpuBuffer)}),S.forEach(Y=>a._OrtReleaseTensor(Y)),M.forEach(Y=>a._OrtReleaseTensor(Y)),O.forEach(Y=>a._free(Y)),A!==0&&a._OrtReleaseRunOptions(A),k.forEach(Y=>a._free(Y))}},Ld=t=>{let e=De(),r=Ur.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Le("Can't get an profile file name."),e._OrtFree(n)},zd=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Fr,jt,pn,Ao,To,kc,pd,Ec,vs,ks,WA,O2,I2,C2,P2,L2,z2,N2,R2=be(()=>{"use strict";Os(),S2(),Is(),vd(),Fr=()=>!!Ke.wasm.proxy&&typeof document<"u",pn=!1,Ao=!1,To=!1,Ec=new Map,vs=(t,e)=>{let r=Ec.get(t);r?r.push(e):Ec.set(t,[e])},ks=()=>{if(pn||!Ao||To||!jt)throw new Error("worker not ready")},WA=t=>{switch(t.data.type){case"init-wasm":pn=!1,t.data.err?(To=!0,pd[1](t.data.err)):(Ao=!0,pd[0]()),kc&&(URL.revokeObjectURL(kc),kc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Ec.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},O2=async()=>{if(!Ao){if(pn)throw new Error("multiple calls to 'initWasm()' detected.");if(To)throw new Error("previous call to 'initWasm()' failed.");if(pn=!0,Fr())return new Promise((t,e)=>{jt?.terminate(),g2().then(([r,s])=>{try{jt=s,jt.onerror=o=>e(o),jt.onmessage=WA,pd=[t,e];let n={type:"init-wasm",in:Ke};!n.in.wasm.wasmPaths&&(r||dd)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import_meta.url).href}),jt.postMessage(n),kc=r}catch(n){e(n)}},e)});try{await kd(Ke.wasm),await Sd(Ke),Ao=!0}catch(t){throw To=!0,t}finally{pn=!1}}},I2=async t=>{if(Fr())return ks(),new Promise((e,r)=>{vs("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Ke}};jt.postMessage(s)});await Od(Ke,t)},C2=async t=>Fr()?(ks(),new Promise((e,r)=>{vs("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};jt.postMessage(s,[t.buffer])})):Ic(t),P2=async(t,e)=>{if(Fr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ks(),new Promise((r,s)=>{vs("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),jt.postMessage(n,o)})}else return Id(t,e)},L2=async t=>{if(Fr())return ks(),new Promise((e,r)=>{vs("release",[e,r]);let s={type:"release",in:t};jt.postMessage(s)});Cd(t)},z2=async(t,e,r,s,n,o)=>{if(Fr()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return ks(),new Promise((a,i)=>{vs("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};jt.postMessage(c,zd(l))})}else return Pd(t,e,r,s,n,o)},N2=async t=>{if(Fr())return ks(),new Promise((e,r)=>{vs("end-profiling",[e,r]);let s={type:"end-profiling",in:t};jt.postMessage(s)});Ld(t)}}),fd,VA,$2,qz=be(()=>{"use strict";Os(),R2(),dn(),bd(),b2(),fd=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},VA=t=>{switch(t[3]){case"cpu":return new er(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Ad(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return er.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!Td(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return er.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},$2=class{async fetchModelAndCopyToWasmMemory(t){return C2(await Md(t))}async loadModel(t,e){Ms();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await P2(r,e),Ss()}async dispose(){return L2(this.sessionId)}async run(t,e,r){Ms();let s=[],n=[];Object.entries(t).forEach(f=>{let m=f[0],_=f[1],w=this.inputNames.indexOf(m);if(w===-1)throw new Error(`invalid input '${m}'`);s.push(_),n.push(w)});let o=[],a=[];Object.entries(e).forEach(f=>{let m=f[0],_=f[1],w=this.outputNames.indexOf(m);if(w===-1)throw new Error(`invalid output '${m}'`);o.push(_),a.push(w)});let i=s.map((f,m)=>fd(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?fd(f,()=>`output "${this.outputNames[a[m]]}"`):null),c=await z2(this.sessionId,n,i,a,l,r),u={};for(let f=0;fgd,initializeFlags:()=>hd,wasmBackend:()=>B2});var hd,gd,B2,Wz=be(()=>{"use strict";Os(),R2(),qz(),hd=()=>{(typeof Ke.wasm.initTimeout!="number"||Ke.wasm.initTimeout<0)&&(Ke.wasm.initTimeout=0);let t=Ke.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),Ke.wasm.simd=!1),typeof Ke.wasm.proxy!="boolean"&&(Ke.wasm.proxy=!1),typeof Ke.wasm.trace!="boolean"&&(Ke.wasm.trace=!1),typeof Ke.wasm.numThreads!="number"||!Number.isInteger(Ke.wasm.numThreads)||Ke.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Ke.wasm.numThreads=1;else{let e=typeof navigator>"u"?vz("node:os").cpus().length:navigator.hardwareConcurrency;Ke.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},gd=class{async init(t){hd(),await O2(),await I2(t)}async createInferenceSessionHandler(t,e){let r=new $2;return await r.loadModel(t,e),r}},B2=new gd});Os();Os();Os();var Vz="1.26.0-dev.20260416-b7804b056c",Hz=p2;{let t=(Wz(),Tc(D2)).wasmBackend;Ts("webgpu",t,5),Ts("webnn",t,5),Ts("cpu",t,10),Ts("wasm",t,10)}Object.defineProperty(Ke.versions,"web",{value:Vz,enumerable:!0});async function U2(t){let e=t.split("/").pop(),r;try{if(r=await Zt(),r){let n=await r.match(t);if(n)return n}}catch(n){ee.warn(`Failed to load ${e} from cache:`,n)}let s=await _e.fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){ee.warn(`Failed to cache ${e}:`,n)}return s}async function F2(t){let e=await U2(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return ee.warn("Failed to read WASM binary:",r),null}}async function G2(t){if(ie.IS_SERVICE_WORKER_ENV||ie.IS_CHROME_AVAILABLE)return t;let e=await U2(t);if(!e||typeof e=="string")return null;try{let r=await e.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return ee.warn("Failed to read WASM factory:",r),null}}var j2="1.24.3";var q2="warning",Rd={wasm:{},webgl:{},webgpu:{},versions:{common:j2},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);q2=t}},get logLevel(){return q2}};Object.defineProperty(Rd,"logLevel",{enumerable:!0});var W2=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=o*n,f=0,m=u,_=u*2,w=-1;a==="RGBA"?(f=0,m=u,_=u*2,w=u*3):a==="RGB"?(f=0,m=u,_=u*2):a==="RBG"&&(f=0,_=u,m=u*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,u;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,b=3,A=0,k=f,S=f*2,M=-1;i==="RGBA"?(A=0,k=f,S=f*2,M=f*3):i==="RGB"?(A=0,k=f,S=f*2):i==="RBG"&&(A=0,S=f,k=f*2),s=r.createImageData(n,o);for(let O=0;O{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,b=0,A=c,k=c*2,S=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(b=0,k=c,A=c*2):l==="BGR"&&(k=0,A=c,b=c*2);for(let O=0;O{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,_=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=_}else i.tensorFormat="RGBA",i.height=m,i.width=_;f.drawImage(t,0,0),a=f.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let u,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,f=e.resizedWidth):(u=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=u,i.width=f,e!==void 0){let m=l();m.width=f,m.height=u;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,u).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,$d(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((u,f)=>{let m=l(),_=c(m);if(!t||!_)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,_.drawImage(w,0,0,m.width,m.height);let x=_.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,u($d(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return $d(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},X2=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new yt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},Y2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new yt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},K2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new yt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},Q2=(t,e,r)=>new yt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]});var Cs=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Io=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),J2=!1,Z2=()=>{if(!J2){J2=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Cs.set("int64",BigInt64Array),Io.set(BigInt64Array,"int64")),e&&(Cs.set("uint64",BigUint64Array),Io.set(BigUint64Array,"uint64")),s?(Cs.set("float16",r),Io.set(r,"float16")):Cs.set("float16",Uint16Array)}};var eT=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new yt(t.type,t.data,e);case"cpu-pinned":return new yt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new yt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new yt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new yt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};var yt=class{constructor(e,r,s){Z2();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=Cs.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof e=="string")if(n=e,l=s,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let c=Cs.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&c===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${c.name} as data.`);e==="uint64"||e==="int64"?i=c.from(r,BigInt):i=c.from(r)}else if(r instanceof c)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&c!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof e[0];if(c==="string")n="string",i=e;else if(c==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let c=Io.get(e.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=c,i=e}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");o=l,this.cpuData=i,this.dataLocation="cpu"}let a=eT(o);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=a}static async fromImage(e,r){return H2(e,r)}static fromTexture(e,r){return X2(e,r)}static fromGpuBuffer(e,r){return Y2(e,r)}static fromMLTensor(e,r){return K2(e,r)}static fromPinnedBuffer(e,r,s){return Q2(e,r,s)}toDataURL(e){return W2(this,e)}toImageData(e){return V2(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return tT(this,e)}};var Cc=yt;var Xz=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function oT(t){return t<=It.DEBUG?0:t<=It.INFO?2:t<=It.WARNING||t<=It.ERROR?3:4}var Yz={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},qt=[],Dd,_n,rT=Symbol.for("onnxruntime");if(rT in globalThis)_n=globalThis[rT];else if(ie.IS_NODE_ENV){switch(_n=Wf,process.platform){case"win32":qt.push("dml");break;case"linux":process.arch==="x64"&&qt.push("cuda");break;case"darwin":qt.push("coreml");break}qt.push("webgpu"),qt.push("cpu"),Dd=["cpu"]}else _n=Nd,ie.IS_WEBNN_AVAILABLE&&qt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ie.IS_WEBGPU_AVAILABLE&&qt.push("webgpu"),qt.push("wasm"),Dd=["wasm"];var Kz=_n.InferenceSession;function aT(t=null){if(!t)return Dd;switch(t){case"auto":return qt;case"gpu":return qt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(qt.includes(t))return[Xz[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${qt.join(", ")}.`)}var sT=Promise.resolve(),mn=null;async function Qz(){if(mn)return mn;if(!(_e.useWasmCache&&typeof it?.wasm?.wasmPaths=="object"&&it?.wasm?.wasmPaths?.wasm&&it?.wasm?.wasmPaths?.mjs)){if(ie.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return mn=Promise.resolve(),mn}return mn=(async()=>{let e=it.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!Bf(e.wasm)?(async()=>{try{let s=await F2(Uf(e.wasm));s&&(it.wasm.wasmBinary=s,r=!0)}catch(s){ee.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!Bf(e.mjs)?(async()=>{try{let s=await G2(Uf(e.mjs));s&&(it.wasm.wasmPaths.mjs=s)}catch(s){ee.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(it.wasm.wasmPaths.mjs=e.mjs)})(),mn}async function Pc(t,e,r){await Qz();let s=oT(_e.logLevel??It.WARNING),n=()=>Kz.create(t,{logSeverityLevel:s,...e}),o=await(ie.IS_WEB_ENV?sT=sT.then(n):n());return o.config=r,o}var nT=Promise.resolve();async function Lc(t,e){let r=()=>t.run(e);return ie.IS_WEB_ENV?nT=nT.then(r):r()}function zc(t){return t instanceof _n.Tensor}var it=_n?.env;function Co(){return it?.wasm?.proxy}if(it){let t=function(e){let r=oT(e);it.logLevel=Yz[r]};if(it.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&it.versions?.web&&!it.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${it.versions.web}/dist/`;it.wasm.wasmPaths=ie.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}it.wasm.proxy=!1}it.webgpu&&(it.webgpu.powerPreference="high-performance"),t(_e.logLevel??It.WARNING),_e.backends.onnx={...it,setLogLevel:t}}var qr=async(t,e,r)=>{let s=await Pc(new Uint8Array(t),e);return(async n=>{let o=Co(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await Lc(s,a);return Array.isArray(r)?r.map(l=>new N(i[l])):new N(i[r])})},pr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=qr([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=qr([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=qr([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=qr([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=qr([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=qr([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=qr([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=qr([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var iT=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),Bd=ie.IS_NODE_ENV?"cpu":"wasm";function Nc(t,e,{warn:r}={}){return t?typeof t=="string"?t:t.hasOwnProperty(e)?t[e]:(r&&r(`device not specified for "${e}". Using the default device (${Bd}).`),Bd):Bd}var uT=(function(){let t;return async function(){if(t===void 0)if(!ie.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),st=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),lT=st.fp32,cT=Object.freeze({[iT.wasm]:st.q8}),Wr=Object.freeze({[st.fp32]:"",[st.fp16]:"_fp16",[st.int8]:"_int8",[st.uint8]:"_uint8",[st.q8]:"_quantized",[st.q4]:"_q4",[st.q2]:"_q2",[st.q1]:"_q1",[st.q4f16]:"_q4f16",[st.q2f16]:"_q2f16",[st.q1f16]:"_q1f16",[st.bnb4]:"_bnb4"});function Rc(t,e,r,{configDtype:s=null,warn:n}={}){let o,a=!1;t&&typeof t!="string"?t.hasOwnProperty(e)?o=t[e]:(o=null,a=!0):o=t;let i;if(o===st.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==st.auto&&st.hasOwnProperty(l))return l}i=cT[r]??lT}else o&&st.hasOwnProperty(o)?i=o:i=cT[r]??lT;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var Vr=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var N=class t{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return zc(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new Cc(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}indexOf(e){let r=this.data;for(let s=0;s_)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(m,0),Math.min(_,this.dims[u])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([u,f])=>f-u),o=n.reduce((u,f)=>u*f),a=this.data,i=new a.constructor(o),l=this.stride(),c=!0;for(let u=1;u=0;--m){let w=n[m];f+=(_%w+s[m][0])*l[m],_=Math.floor(_/w)}i[u]=a[f]}return new t(this.type,i,r)}permute(...e){return Zz(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let a,i;if(o?(a=(f,m)=>f+m,i=0n):(a=(f,m)=>f+m**e,i=0),r===null){let f=n.reduce(a,i);return e!==1&&(f=f**(1/e)),new t(this.type,[f],[])}let[l,c,u]=Po(a,this,r,s);if(e!==1)for(let f=0;f=0;--l){let f=this.dims[l];if(l!==r){let m=c%f;i+=m*u,u*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return Ud(this.dims)}squeeze(e=null){return new t(this.type,this.data,pT(this.dims,e))}squeeze_(e=null){return this.dims=pT(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,fT(this.dims,e))}unsqueeze_(e){return this.dims=fT(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...s,n.reduce((a,i)=>a*i,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;ni!==r?o*a:o,1);e[r]=s.length/n}return new t(this.type,s,e)}neg_(){let e=this.data;for(let r=0;re?1:0;return new t("bool",r,this.dims)}lt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;nMath.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=Pe(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Po((a,i)=>Math.max(a,i),this,e,r,-1/0);return new t(s,n,o)}argmin(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=bo(this.data)[1];return new t("int64",[BigInt(s)],[])}argmax(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Pe(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.lengthu===1)){if(e.length===this.dims.length)return this.clone();let u=e.length-this.dims.length,f=Array(u).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((u,f)=>u*e[f]),o=n.reduce((u,f)=>u*f,1),a=this.data,i=new a.constructor(o),l=Ud(s),c=Ud(n);for(let u=0;uBigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,xA(this.data),this.dims);return new t(e,Vr[e].from(this.data,r),this.dims)}};function Jz(t,e){let r=t.length,s=e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.lengthnew N("int64",t,[t.length]);async function Dc(t,e,r,s,n){return await(await pr.slice)({x:t,s:$c(e),e:$c(r),a:$c(s),t:$c(n??new Array(s.length).fill(1))})}function mT(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let u=0;ur!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function fT(t,e){return e=fr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function fr(t,e,r=null,s=!0){if(t<-e||t>=e){if(s)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function ve(t,e=0){e=fr(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i=0;--m){let x=c[m],b=_%x;m===e&&(b+=a),f+=b*w,w*=r[m],_=Math.floor(_/x)}n[f]=l[u]}a+=c[e]}}return new N(o,n,r)}function bt(t,e=0){return ve(t.map(r=>r.unsqueeze(e)),e)}function Po(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=fr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let c=0;c=0;--f){let w=a[f];if(f!==r){let x=m%w;u+=x*_,_*=i[f]}m=Math.floor(m/w)}l[u]=t(l[u],o[c],c,u)}return s||i.splice(r,1),[e.type,l,i]}function Gd(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let _=n.reduce((A,k)=>A+k,0)/n.length,w=Math.sqrt(n.reduce((A,k)=>A+(k-_)**2,0)/(n.length-r)),x=new N(t.type,[_],[]);return[new N(t.type,[w],[]),x]}e=fr(e,o.length);let a=Bc(t,e,s),i=a.data,[l,c,u]=Po((m,_,w,x)=>m+(_-i[x])**2,t,e,s);for(let m=0;mc+u,0);return new N(t.type,[l/n.length],[])}e=fr(e,s.length);let[o,a,i]=Po((l,c)=>l+c,t,e,r);if(s[e]!==1)for(let l=0;l=0;--r)e[r]=s,s*=t[r];return e}function jd(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new N(r,new s(n).fill(e),t)}function Qe(t,e){let r,s;if(typeof e=="number")r="float32",s=Float32Array;else if(typeof e=="bigint")r="int64",s=BigInt64Array;else if(typeof e=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return jd(t,e,r,s)}function Lo(t,e){return Qe(t.dims,e)}function et(t){return jd(t,1n,"int64",BigInt64Array)}function Uc(t){return et(t.dims)}function qd(t){return jd(t,0n,"int64",BigInt64Array)}function Wd(t){return qd(t.dims)}function VD(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>ys.random()),t)}function _T(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>ys.gauss()),t)}function hT(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i0?1:0,c=Math.floor(i/8),u=i%8;a[c]|=l<<7-u,r&&u===0&&(a[c]-=128)}return new N(s,a,[t.dims[0],t.dims[1]/8])}async function hn(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await Ct(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Vd(t,e){let r=await hn(t);return await Promise.all(r.map(s=>nt(t,s,!0,e)))}function zo(t){let e=t.dims;switch(e.length){case 1:return t.tolist();case 2:if(e[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return t.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${e.length}.`)}}var eN=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function tN(t,e,r,s){for(let n of Object.keys(t)){let o=e-t[n].length,a=r(n),i=new Array(o).fill(a);t[n]=s==="right"?wt(t[n],i):wt(i,t[n])}}function rN(t,e){for(let r of Object.keys(t))t[r].length=e}function Ps(t,...e){for(let r of e){if(!Object.hasOwn(t,r))continue;let s=t[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function sN(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var W=class extends We{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new GE(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Ps(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ps(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ps(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ps(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ps(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ps(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:a}of this.chat_template){if(typeof o!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=a}this.chat_template=n}this._compiled_template_cache=new Map;let s=sN(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let i=await Vd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,r={}){let{text_pair:s=null,add_special_tokens:n=!0,padding:o=!1,return_token_type_ids:a=null}=r,{truncation:i=null,max_length:l=null}=r,c=r.return_tensor??!0,u=Array.isArray(e),f;if(u){if(e.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(e.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");f=e.map((_,w)=>this._encode_plus(_,{text_pair:s[w],add_special_tokens:n,return_token_type_ids:a}))}else f=e.map(_=>this._encode_plus(_,{add_special_tokens:n,return_token_type_ids:a}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(s))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");f=[this._encode_plus(e,{text_pair:s,add_special_tokens:n,return_token_type_ids:a})]}if(l===null?l=this.model_max_length:i===null&&(o===!0?(ee.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):o===!1&&(ee.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),i=!0)),o===!0&&(l=Math.min(Pe(f.map(_=>_.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),o||i)for(let _=0;_l?i&&rN(f[_],l):o&&tN(f[_],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));let m={};if(c){if(!(o&&i)&&f.some(w=>{for(let x of Object.keys(w))if(w[x].length!==f[0][x]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let _=[f.length,f[0].input_ids.length];for(let w of Object.keys(f[0]))m[w]=new N("int64",BigInt64Array.from(f.flatMap(x=>x[w]).map(BigInt)),_)}else{for(let _ of Object.keys(f[0]))m[_]=f.map(w=>w[_]);if(!u)for(let _ of Object.keys(m))m[_]=m[_][0]}return m}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof N&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof N&&(e=zo(e)),!Array.isArray(e)||e.length===0||!EE(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,r={}){let{tools:s=null,documents:n=null,chat_template:o=null,add_generation_prompt:a=!1,tokenize:i=!0,padding:l=!1,truncation:c=!1,max_length:u=null,return_tensor:f=!0,return_dict:m=!0,tokenizer_kwargs:_={},...w}=r;if(o=this.get_chat_template({chat_template:o,tools:s}),typeof o!="string")throw Error(`chat_template must be a string, but got ${typeof o}`);let x=this._compiled_template_cache.get(o);x===void 0&&(x=new eA(o),this._compiled_template_cache.set(o,x));let b=Object.create(null);for(let k of eN){let S=Ps(this.config,k);S&&(b[k]=S)}let A=x.render({messages:e,add_generation_prompt:a,tools:s,documents:n,...b,...w});if(i){let k=this._call(A,{add_special_tokens:!1,padding:l,truncation:c,max_length:u,return_tensor:f,..._});return m?k:k.input_ids}return A}};function gn(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var Dm={};hs(Dm,{AlbertTokenizer:()=>Hd,AutoTokenizer:()=>ne,BartTokenizer:()=>Xd,BertTokenizer:()=>Yd,BlenderbotSmallTokenizer:()=>Kd,BlenderbotTokenizer:()=>Qd,BloomTokenizer:()=>Jd,CLIPTokenizer:()=>em,CamembertTokenizer:()=>Zd,CodeGenTokenizer:()=>rm,CodeLlamaTokenizer:()=>tm,CohereAsrTokenizer:()=>nm,CohereTokenizer:()=>sm,ConvBertTokenizer:()=>om,DebertaTokenizer:()=>im,DebertaV2Tokenizer:()=>am,DistilBertTokenizer:()=>lm,ElectraTokenizer:()=>cm,EsmTokenizer:()=>um,FalconTokenizer:()=>pm,GPT2Tokenizer:()=>mm,GPTNeoXTokenizer:()=>dm,GemmaTokenizer:()=>fm,HerbertTokenizer:()=>_m,LlamaTokenizer:()=>hm,M2M100Tokenizer:()=>gm,MBart50Tokenizer:()=>xm,MBartTokenizer:()=>No,MPNetTokenizer:()=>vm,MarianTokenizer:()=>wm,MgpstrTokenizer:()=>ym,MobileBertTokenizer:()=>bm,NllbTokenizer:()=>km,NougatTokenizer:()=>Em,PreTrainedTokenizer:()=>W,Qwen2Tokenizer:()=>Am,RoFormerTokenizer:()=>Mm,RobertaTokenizer:()=>Tm,SiglipTokenizer:()=>Sm,SpeechT5Tokenizer:()=>Om,SqueezeBertTokenizer:()=>Im,T5Tokenizer:()=>Cm,TokenizersBackend:()=>W,VitsTokenizer:()=>Lm,Wav2Vec2CTCTokenizer:()=>zm,WhisperTokenizer:()=>Nm,XLMRobertaTokenizer:()=>Rm,XLMTokenizer:()=>$m});var Hd=class extends W{return_token_type_ids=!0};var Xd=class extends W{};var Yd=class extends W{return_token_type_ids=!0};var Kd=class extends W{};var Qd=class extends W{};var Jd=class extends W{};var Zd=class extends W{};var em=class extends W{};var tm=class extends W{};var rm=class extends W{};var sm=class extends W{};var nm=class extends W{};var om=class extends W{return_token_type_ids=!0};var am=class extends W{return_token_type_ids=!0};var im=class extends W{return_token_type_ids=!0};var lm=class extends W{};var cm=class extends W{return_token_type_ids=!0};var um=class extends W{};var pm=class extends W{};var fm=class extends W{};var dm=class extends W{};var mm=class extends W{};var _m=class extends W{return_token_type_ids=!0};var hm=class extends W{padding_side="left"};var gm=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return gn(this,e,r,s)}};var wm=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),ee.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[r,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(r);if(s.length===2){let[n,o]=s;return this.supported_language_codes.includes(n)||ee.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),wt([n],super._encode_text(o))}}};var No=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return gn(this,e,r,s)}};var xm=class extends No{};var ym=class extends W{};var bm=class extends W{return_token_type_ids=!0};var vm=class extends W{};var km=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return gn(this,e,r,s)}};var Em=class extends W{};var Am=class extends W{};var Tm=class extends W{};var Mm=class extends W{return_token_type_ids=!0};var Sm=class extends W{};var Om=class extends W{};var Im=class extends W{return_token_type_ids=!0};var Cm=class extends W{};var Pm=class extends Ft{decode_chain(e){let r="";for(let s=1;s[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function wT(t){t=t.toLowerCase();let e=nN.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),Ro.has(t))e=t;else{let n=t.length===2?Ro.keys():Ro.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var oN="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",xT=new RegExp(`^[${oN}]+$`,"gu"),aN=.1,Nm=class extends W{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],u=l(),f=0,m=this.timestamp_begin,w=m+1500,x=[],b=[],A=!1,k=null,S=new Set(this.all_special_ids);for(let I of e){let v=I.tokens,B=i?I.token_timestamps:null,G=null,F=m;if("stride"in I){let[J,$,C]=I.stride;if(f-=$,k=J-C,$&&(F=$/n+m),C)for(let se=v.length-1;se>=0;--se){let K=Number(v[se]);if(K>=m){if(G!==null&&(K-m)*n=m&&$<=w){let C=($-m)*n+f,se=bs(C,2);if(G!==null&&$>=G)A=!0;else if(A||x.length>0&&$0&&u.timestamp[1]!==null))for(let U of u.words)U.timestamp[1]>u.timestamp[1]&&u.timestamp[1]>=U.timestamp[0]&&(U.timestamp[1]=u.timestamp[1]);c.push(u),x=[],X=[],b=[],Y=[],u=l()}}else if(X.push($),i){let C=bs(B[J]+f,2),se;if(J+10?(x.push(X),i&&b.push(Y)):x.every(J=>J.length===0)&&(u=l(),x=[],X=[],b=[],Y=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[I,v]=this.findLongestCommonSequence(x,b),B=this.decode(I);u.text=B,i&&(u.words=this.collateWordTimestamps(I,v,a)),c.push(u)}let M=Object.create(null),O=c.map(I=>I.text).join("");if(r||s){for(let I=0;I0,i=a?[]:null,l=a?r[0]:null;for(let c=1;c$===F[C]&&l[O+C][0]-aN<=r[c][B+C][0]).length:X=v.filter(($,C)=>$===F[C]).length;let Y=M/1e4,J=X/M+Y;X>1&&J>f&&(f=J,m=[O,I,B,G])}let[w,x,b,A]=m,k=Math.floor((x+w)/2),S=Math.floor((A+b)/2);if(a&&f===0&&n>0){let M=l[n-1][0],O=r[c].findIndex(I=>I[0]>=M);S=O===-1?u.length:O}o.push(...s.slice(0,k)),s=u.slice(S),n=s.length,a&&(i.push(...l.slice(0,k)),l=r[c].slice(S))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],c=0;for(let u=0;u=this._tokenizer.token_to_id("<|endoftext|>"),_=c.startsWith(" "),w=c.trim(),x=xT.test(w);if(m||_||x||o.length===0)o.push(c),a.push(u),i.push(f);else{let b=o.length-1;o[b]+=c,a[b].push(...u),i[b].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,u=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[u]=a[c]+a[u],i[u]=wt(i[c],i[u]),l[u]=wt(l[c],l[u]),a[c]="",i[c]=[],l[c]=[]):u=c,--c;for(c=0,u=1;uf),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var Rm=class extends W{};var $m=class extends W{return_token_type_ids=!0;constructor(e,r){super(e,r),ee.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var ne=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await Vd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",u=Dm[c];return u||(ee.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),u=W),new u(i,l)}};var Hr="https://github.com/huggingface/transformers.js/issues/new/choose";var $o="preprocessor_config.json",kr=$o,Fc="processor_config.json",Gc="chat_template.jinja";var re=class extends We{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?nt(e,Fc,!0,r):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{let i=await this[a].from_pretrained(e,r);return[a.replace(/_class$/,""),i]})).then(Object.fromEntries),this.uses_chat_template_file?yo(e,Gc,!0,r):null]);return new this(s,n,o)}};var mu={};hs(mu,{ChatterboxProcessor:()=>e_,CohereAsrProcessor:()=>t_,Florence2Processor:()=>H_,Gemma3Processor:()=>X_,Gemma3nProcessor:()=>Y_,Gemma4Processor:()=>K_,Glm46VProcessor:()=>Q_,GraniteSpeechProcessor:()=>J_,GroundingDinoProcessor:()=>Z_,Idefics3Processor:()=>uu,JinaCLIPProcessor:()=>th,Lfm2VlProcessor:()=>rh,LlavaProcessor:()=>sh,MgpstrProcessor:()=>nh,MoonshineProcessor:()=>oh,OwlViTProcessor:()=>ah,PaliGemmaProcessor:()=>ih,Phi3VProcessor:()=>lh,PixtralProcessor:()=>ch,Processor:()=>re,PyAnnoteProcessor:()=>uh,Qwen2VLProcessor:()=>zs,Qwen2_5_VLProcessor:()=>Yo,Qwen3VLProcessor:()=>ph,Sam2Processor:()=>pu,Sam2VideoProcessor:()=>fh,SamProcessor:()=>Ko,SmolVLMProcessor:()=>uu,SpeechT5Processor:()=>dh,UltravoxProcessor:()=>mh,VLChatProcessor:()=>eh,VoxtralProcessor:()=>_h,VoxtralRealtimeProcessor:()=>gh,Wav2Vec2Processor:()=>wh,Wav2Vec2ProcessorWithLM:()=>xh,WhisperProcessor:()=>yh});var Ee=class extends We{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await nt(e,$o,!0,r);return new this(s)}};function Ae(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var Wo={};hs(Wo,{ASTFeatureExtractor:()=>Fm,ChatterboxFeatureExtractor:()=>Gm,ClapFeatureExtractor:()=>jm,CohereAsrFeatureExtractor:()=>qm,DacFeatureExtractor:()=>Fo,EncodecFeatureExtractor:()=>Bo,FeatureExtractor:()=>Ee,Gemma3nAudioFeatureExtractor:()=>Go,Gemma4AudioFeatureExtractor:()=>jo,GraniteSpeechFeatureExtractor:()=>Wm,MoonshineFeatureExtractor:()=>Vm,ParakeetFeatureExtractor:()=>Uo,PyAnnoteFeatureExtractor:()=>qo,SeamlessM4TFeatureExtractor:()=>Hm,SnacFeatureExtractor:()=>Xm,SpeechT5FeatureExtractor:()=>Ym,VoxtralRealtimeFeatureExtractor:()=>Jm,Wav2Vec2FeatureExtractor:()=>Km,WeSpeakerFeatureExtractor:()=>Qm,WhisperFeatureExtractor:()=>Zm});var iN=()=>{};var yT={fromWeb:iN};var lN=()=>{};var bT=lN;async function jc(t,e){if(ie.IS_BROWSER_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(ie.IS_FS_AVAILABLE){let r=e.stream(),s=yT.fromWeb(r),n=gt.createWriteStream(t);await bT(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function ET(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await Nr(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&ee.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let c=0;c2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function Bm(t,e="htk"){let r=uN[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}var pN={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,r=15,s=Math.log(6.4)/27)=>t>=r?e*Math.exp(s*(t-r)):200*t/3};function fN(t,e="htk"){let r=pN[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}function dN(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;anew Array(t.length));for(let a=0;at+s*o)}function lt(t,e,r,s,n,o=null,a="htk",i=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);let l=Bm(r,a),c=Bm(s,a),u=kT(l,c,e+2),f=fN(u,a),m;if(i){let w=n/((t-1)*2);m=Bm(Float64Array.from({length:t},(x,b)=>b*w),a),f=u}else m=kT(0,Math.floor(n/2),t);let _=dN(m,f);if(o!==null&&o==="slaney")for(let w=0;wn)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(G!==r)throw new Error(`Length of the window (${G}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!u)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a){let Q=Math.floor(r/2);switch(i){case"reflect":{t=mN(t,Q,Q);break}case"constant":{let le=new t.constructor(t.length+2*Q);le.set(t,Q),t=le;break}case"semicausal":{let le=new t.constructor(t.length+Q);le.set(t,Q),t=le;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let F=Math.floor(1+Math.floor((t.length-r)/s));S!==null&&FF?O&&(J=M):J=Y=M);let $=new wc(n),C=new Float64Array(n),se=new Float64Array($.outputBufferSize),K=new Float32Array(X*J);for(let Q=0;Q=1;--ce)C[ce]-=c*C[ce-1];C[0]*=1-c}for(let ce=0;ceMath.pow(c,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null||t===s)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);let i=new Float64Array(s),l=n?Math.floor((s-t)/2):0;return i.set(a,l),i}function gN(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return qc(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),qc(n,8,"WAVE"),qc(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,e,!0),n.setUint32(28,e*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),qc(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function qc(t,e,r){for(let s=0;sn+o.length,0),r=new Float32Array(e),s=0;for(let n of this.audio)r.set(n,s),s+=n.length;return r}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),gN(e,this.sampling_rate)}async save(e){return jc(e,this.toBlob())}};var Fm=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=mt(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){Ae(e,"ASTFeatureExtractor");let r=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let s=this.std*2,n=r.data;for(let o=0;o0)if(s==="rand_trunc"){a=!0;let l=Math.floor(ys.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let c=e.length;c=1;--n)e[n]-=r*e[n-1];return await ot(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){Ae(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f1?s-1:1;for(let f=0;f=u){l.push(e.slice(c,u));break}let f=Math.max(c,c+a-i),m=Math.min(c+a,u),_;m<=f?_=c+a:_=this._find_split_point_energy(e,f,m,n),_=Math.max(c+1,Math.min(_,u)),l.push(e.slice(c,_)),c=_}return l}_find_split_point_energy(e,r,s,n){let o=s-r;if(o<=n)return Math.floor((r+s)/2);let a=1/0,i=r,l=o-n;for(let c=0;c<=l;c+=n){let u=0;for(let f=0;fr&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let a=await this._extract_fbank_features(e,this.config.max_length),i=Qe([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var jo=class extends Go{async _extract_fbank_features(e,r){let{frame_length:s,hop_length:n,fft_length:o}=this.config,a=Math.floor(s/2),i=Math.floor((e.length+a-(s+1))/n)+1;return ot(e,this.window,s,n,{fft_length:o,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:i})}async _call(e,r={}){Ae(e,"Gemma4AudioFeatureExtractor");let s=e.length,n=await super._call(e,r),{input_features:o}=n,[,a,i]=o.dims,{frame_length:l,hop_length:c}=this.config,u=Math.floor(l/2),f=l+1,m=new Uint8Array(s+u+(r.pad_to_multiple_of??128));m.fill(1,u,u+s);let _=new Uint8Array(a);for(let x=0;x({id:l,start:c*s,end:u*s,confidence:f/(u-c)})))}return n}};var Hm=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=mt(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){Ae(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,b=a.data;for(let A=0;A0){let k=new Float32Array(x*(w+A));k.set(b),k.fill(this.config.padding_value,b.length);let S=w+A;a=new N(a.type,k,[S,x]),o&&(i=new N("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,u=this.config.stride;if(l%u!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${u}).`);let m=a.view(1,Math.floor(l/u),c*u),_={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let b=i.data;for(let A=1,k=0;Ao+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){Ae(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));let s=[1,r.length];return{input_values:new N("float32",r,s),attention_mask:new N("int64",new BigInt64Array(r.length).fill(1n),s)}}};var Qm=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=mt(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){Ae(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;ln?(e.length>this.config.n_samples&&ee.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var Ge=class{static async from_pretrained(e,r={}){let s=await nt(e,$o,!0,r),n=s.feature_extractor_type,o=Wo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Hr}.`);return new o(s)}};var e_=class extends re{static tokenizer_class=ne;static feature_extractor_class=Ge;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var xN=new Set(["ja","zh"]),t_=class extends re{static tokenizer_class=ne;static feature_extractor_class=Ge;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let r=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(r)}static join_chunks(e,r="en"){let s=e.filter(a=>a&&a.trim());if(s.length===0)return"";let n=xN.has(r)?"":" ";return[s[0].trimEnd(),...s.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}};var Wc={};var Ls,MT,Xr;if(ie.IS_WEB_ENV)Ls=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},Xr=self.createImageBitmap,MT=self.ImageData;else if(Wc)Xr=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Je(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&o.convert(r),o};else throw new Error("Unable to load image processing library.");var yN={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},bN=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Je=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!ie.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let s=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(s,e.width,e.height,4)}static async fromURL(e){let r=await Nr(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(e){if(ie.IS_WEB_ENV){let r=await Xr(e),s=Ls(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=Wc(await e.arrayBuffer());return await Xr(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r=0?l=s:u=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,u,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await Xr(o)}}async toBlob(e="image/png",r=1){if(!ie.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new N("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!ie.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=Ls(e.width,e.height),s=new MT(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;lnew t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(ie.IS_WEB_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=bN.get(r)??"image/png",n=await this.toBlob(s);return jc(e,n)}else if(ie.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(ie.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return Wc(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},vN=Je.read.bind(Je);function ST(t,e,r=0,s=null){let n=t/e,o=gA(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),oe&&A.push(S)}else{let S=Pe(b.data)[1];if(S===l-1||(k=Re(b.data),k[S]O*f[(I+1)%2])),m.boxes.push(M),m.classes.push(S),m.scores.push(k[S])}}c.push(m)}return c}function Vc(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;of[A]&&(f[A]=b[A],m[A]=x)}let _=new Array(i.dims[0]);for(let x=0;xx!==void 0);n.push({segmentation:u,labels:w})}return n}function kN(t,e,r,s){let n=[],o=[],a=[];for(let i=0;ir&&(n.push(c),o.push(m),a.push(u))}return[n,o,a]}function EN(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let u=0;u=s&&++i;let c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function AN(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new N("int32",new Int32Array(i*l),[i,l]),u=[];if(a!==null)for(let x=0;xm[k]&&(f[k]=x,m[k]=A[k])}let _=0,w=c.data;for(let x=0;x200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let a=Math.round(t/r)*r,i=Math.round(e/r)*r;if(o*a*i>n){let l=Math.sqrt(o*t*e/n);a=Math.max(r,Math.floor(t/l/r)*r),i=Math.max(r,Math.floor(e/l/r)*r)}else if(o*a*io?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=bo(s.data)[0],a=Pe(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=s.height,u=0,f=0,m=s.data;for(let _=0;_this.preprocess(o)));return{pixel_values:bt(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await nt(e,kr,!0,r);return new this(s)}};var kn={};hs(kn,{BeitFeatureExtractor:()=>s_,BitImageProcessor:()=>n_,CHMv2ImageProcessor:()=>a_,CLIPFeatureExtractor:()=>i_,CLIPImageProcessor:()=>Yc,ChineseCLIPFeatureExtractor:()=>o_,ConvNextFeatureExtractor:()=>l_,ConvNextImageProcessor:()=>Kc,DINOv3ViTImageProcessor:()=>p_,DPTFeatureExtractor:()=>d_,DPTImageProcessor:()=>Zc,DeiTFeatureExtractor:()=>c_,DeiTImageProcessor:()=>Qc,DetrFeatureExtractor:()=>u_,DetrImageProcessor:()=>Jc,DonutFeatureExtractor:()=>f_,DonutImageProcessor:()=>xn,EfficientNetImageProcessor:()=>m_,GLPNFeatureExtractor:()=>g_,Gemma3ImageProcessor:()=>__,Gemma4ImageProcessor:()=>Vo,Glm46VImageProcessor:()=>h_,GroundingDinoImageProcessor:()=>w_,Idefics3ImageProcessor:()=>eu,ImageFeatureExtractor:()=>H,ImageProcessor:()=>H,JinaCLIPImageProcessor:()=>y_,Lfm2VlImageProcessor:()=>b_,LlavaOnevisionImageProcessor:()=>v_,Mask2FormerImageProcessor:()=>E_,MaskFormerFeatureExtractor:()=>k_,MaskFormerImageProcessor:()=>yn,MobileNetV1FeatureExtractor:()=>A_,MobileNetV1ImageProcessor:()=>tu,MobileNetV2FeatureExtractor:()=>T_,MobileNetV2ImageProcessor:()=>ru,MobileNetV3FeatureExtractor:()=>M_,MobileNetV3ImageProcessor:()=>su,MobileNetV4FeatureExtractor:()=>S_,MobileNetV4ImageProcessor:()=>nu,MobileViTFeatureExtractor:()=>O_,MobileViTImageProcessor:()=>ou,NougatImageProcessor:()=>I_,OwlViTFeatureExtractor:()=>C_,OwlViTImageProcessor:()=>bn,Owlv2ImageProcessor:()=>P_,Phi3VImageProcessor:()=>N_,PixtralImageProcessor:()=>R_,PvtImageProcessor:()=>$_,Qwen2VLImageProcessor:()=>Ho,RTDetrImageProcessor:()=>D_,Sam2ImageProcessor:()=>Xo,Sam3ImageProcessor:()=>Xo,SamImageProcessor:()=>Xo,SapiensFeatureExtractor:()=>B_,SapiensImageProcessor:()=>au,SegformerFeatureExtractor:()=>U_,SegformerImageProcessor:()=>iu,SiglipImageProcessor:()=>F_,SmolVLMImageProcessor:()=>eu,Swin2SRImageProcessor:()=>G_,VLMImageProcessor:()=>x_,ViTFeatureExtractor:()=>j_,ViTImageProcessor:()=>lu,VitMatteImageProcessor:()=>q_,VitPoseImageProcessor:()=>W_,YolosFeatureExtractor:()=>V_,YolosImageProcessor:()=>cu});var s_=class extends H{};var n_=class extends H{};var o_=class extends H{};var a_=class extends H{};var Yc=class extends H{},i_=class extends Yc{};var Kc=class extends H{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){let s=Math.floor(r/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}},l_=class extends Kc{};var Qc=class extends H{},c_=class extends Qc{};var Jc=class extends H{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Qe(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Yr(...e)}post_process_panoptic_segmentation(...e){return Hc(...e)}post_process_instance_segmentation(...e){return Xc(...e)}},u_=class extends Jc{};var p_=class extends H{};var xn=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let u=l.map((f,m)=>-f/c[m]);return super.pad_image(e,r,s,{center:!0,constant_values:u,...n})}},f_=class extends xn{};var Zc=class extends H{},d_=class extends Zc{};var m_=class extends H{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}};var __=class extends H{};function TN(t,e,r,s,n){let o=s*r**2,a=Math.sqrt(o/(t*e)),i=n*r,l=Math.floor(a*t/i)*i,c=Math.floor(a*e/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);let u=Math.floor(s/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(e/t)*i,u)):c===0&&(c=i,l=Math.min(Math.floor(t/e)*i,u)),[l,c]}function MN(t,e,r,s,n,o,a){let i=Math.floor(e/n),l=Math.floor(r/n),c=i*l,u=n*n*s,f=new Float32Array(o*u),m=0;for(let x=0;xa),0));let u=a.dims[0]/i,f=a.dims[1],m=Math.floor(a.dims[2]/c),_=Math.floor(a.dims[3]/c),w=a.view(u,i,f,Math.floor(m/l),l,c,Math.floor(_/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(u*m*_,f*i*c*c),x=new N("int64",[u,m,_],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var h_=class extends Ho{get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return wn(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}};var g_=class extends H{};var w_=class extends H{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=et([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var eu=class extends H{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],c=[];for(let A of n){let k=await Promise.all(A.map(O=>this.preprocess(O)));l.push(...k.map(O=>O.original_size)),c.push(...k.map(O=>O.reshaped_input_size)),k.forEach(O=>O.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,M;if(r??this.do_image_splitting){let O=new Array(k.length),I=new Array(k.length);M=await Promise.all(k.map(async(v,B)=>{let G=this.get_resize_for_vision_encoder(v.pixel_values,S),F=await kt(v.pixel_values,{size:[G.height,G.width]}),{frames:X,num_splits_h:Y,num_splits_w:J}=await this.split_image(F,this.max_image_size);return O[B]=Y,I[B]=J,ve(X,0)})),a.push(O),i.push(I)}else{let O=[S,S];M=await Promise.all(k.map(I=>kt(I.pixel_values,{size:O}))),a.push(new Array(k.length).fill(0)),i.push(new Array(k.length).fill(0))}o.push(ve(M,0))}let u=o.length,[f,m,_,w]=o[0].dims,x,b;if(u===1)x=o[0].unsqueeze_(0),b=Qe([u,f,_,w],!0);else{let A=Math.max(...o.map(M=>M.dims.at(0)));b=Qe([u,A,_,w],!0);let k=b.data,S=A*_*w;for(let M=0;Ms||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let u=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;wr*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var y_=class extends H{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function IT(t,e){return Math.round(t/e)*e}function SN(t,e,r,s,n){let o=1/0,a=[1,1],i=r*s;for(let l of e){let c=Math.abs(t-l[0]/l[1]);c.5*n*n*l[0]*l[1]&&(a=l)}return a}function ON(t,e){let r=[],s=new Set;for(let n=t;n<=e;++n)for(let o=1;o<=n;++o)for(let a=1;a<=n;++a){let i=o*a;if(i>=t&&i<=e){let l=o<<16|a;s.has(l)||(s.add(l),r.push([o,a]))}}return r.sort((n,o)=>n[0]*n[1]-o[0]*o[1])}function IN(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,u=new Float32Array(r*a*i*l),f=n*o;for(let m=0;mthis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=ON(this.min_tiles,this.max_tiles),[n,o]=SN(r/e,s,r,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:r=null}={}){let s;Array.isArray(e)?Array.isArray(e[0])?s=e:s=[e]:s=[[e]];let n=[],o=[],a=[],i=[],l=[],c=[];for(let f of s){let m=await Promise.all(f.map(_=>this.preprocess(_,{do_pad:!1})));for(let{pixel_values:_}of m){let[,w,x]=_.dims,b=_.unsqueeze_(0),A=this.encoder_patch_size*this.downsample_factor,k=A**2,[S,M]=wn(Math.max(A,w),Math.max(A,x),A,this.min_image_tokens*k,this.max_image_tokens*k).map(F=>Math.max(A,F)),O,I=1,v=1,B=this._is_image_too_large(w,x),G=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(B&&G){let{grid_width:F,grid_height:X,target_width:Y,target_height:J}=this._get_grid_layout(w,x);I=X,v=F;let $=await kt(b,{size:[J,Y]});O=[];for(let C=0;C(u-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||z_(r)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(m=>this.preprocess(m))),o=n.map(m=>m.original_size),a=n.map(m=>m.reshaped_input_size),i=[];for(let{pixel_values:m}of n){m.unsqueeze_(0);let[_,w]=m.dims.slice(-2),x=await kt(m,{size:[$t,$t],mode:"bicubic"});if(r>0){let b=[],A=z_(r),k=vn(w/A),S=vn(_/A);for(let O=0;Om.map(_=>$t*L_(_/$t))),u=new N("int64",c.flat(),[s,2]),f=c.map(([m,_])=>this.calc_num_image_tokens_from_image_size(_,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:u,num_img_tokens:f}}};var R_=class extends H{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:u}=this.config;if(!u)throw new Error("config must contain 'spatial_merge_size'");let f=c*u,m=Math.floor((i-1)/f)+1,_=Math.floor((l-1)/f)+1;return[m*f,_*f]}};var $_=class extends H{};var D_=class extends H{post_process_object_detection(...e){return Yr(...e)}};var Xo=class extends H{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=zf(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;an!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new N("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let c=0;cn&&(w[x]=1);m=new N("bool",w,m.dims)}i.push(m)}return i}generate_crop_boxes(e,r,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:a=1}={}){}};var au=class extends H{post_process_semantic_segmentation(...e){return Vc(...e)}},B_=class extends au{};var iu=class extends H{post_process_semantic_segmentation(...e){return Vc(...e)}},U_=class extends iu{};var F_=class extends H{};var G_=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r;return super.pad_image(e,r,{width:a+(s-a%s)%s,height:o+(s-o%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var lu=class extends H{},j_=class extends lu{};var q_=class extends H{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let s=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(r.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:bt(s.map((a,i)=>ve([a.pixel_values,n[i].pixel_values],0)),0),original_sizes:s.map(a=>a.original_size),reshaped_input_sizes:s.map(a=>a.reshaped_input_size)}}};var W_=class extends H{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let u=0;u/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],c=[];for(let[u,f,...m]of i)l.push(f?f.trim():l.at(-1)??""),c.push(m.map((_,w)=>(Number(_)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:c};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var X_=class extends re{static tokenizer_class=ne;static image_processor_class=Te;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:o,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=o,this.eoi_token=a;let i=o.repeat(this.image_seq_length);this.full_image_sequence=` + + ${n}${i}${a} + +diff --git a/node_modules/@huggingface/transformers/dist/transformers.node.cjs b/node_modules/@huggingface/transformers/dist/transformers.node.cjs +index 6cb09ae..f94f616 100644 +--- a/node_modules/@huggingface/transformers/dist/transformers.node.cjs ++++ b/node_modules/@huggingface/transformers/dist/transformers.node.cjs +@@ -1002,7 +1002,7 @@ var isSafari = () => { + if (typeof navigator === "undefined") { + return false; + } +- const userAgent = navigator.userAgent; ++ const userAgent = navigator.userAgent || ""; + const vendor = navigator.vendor || ""; + const isAppleVendor = vendor.indexOf("Apple") > -1; + const notOtherBrowser = !userAgent.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i) && !userAgent.includes("Chrome") && !userAgent.includes("Android"); +diff --git a/node_modules/@huggingface/transformers/dist/transformers.node.min.cjs b/node_modules/@huggingface/transformers/dist/transformers.node.min.cjs +index 5a9e5c3..850ec44 100644 +--- a/node_modules/@huggingface/transformers/dist/transformers.node.min.cjs ++++ b/node_modules/@huggingface/transformers/dist/transformers.node.min.cjs +@@ -1,4 +1,4 @@ +-var DI=Object.create;var tp=Object.defineProperty;var FI=Object.getOwnPropertyDescriptor;var BI=Object.getOwnPropertyNames;var UI=Object.getPrototypeOf,jI=Object.prototype.hasOwnProperty;var Os=(t,e)=>{for(var r in e)tp(t,r,{get:e[r],enumerable:!0})},LE=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of BI(e))!jI.call(t,n)&&n!==r&&tp(t,n,{get:()=>e[n],enumerable:!(s=FI(e,n))||s.enumerable});return t};var vr=(t,e,r)=>(r=t!=null?DI(UI(t)):{},LE(e||!t||!t.__esModule?tp(r,"default",{value:t,enumerable:!0}):r,t)),GI=t=>LE(tp({},"__esModule",{value:!0}),t);var h3={};Os(h3,{ASTFeatureExtractor:()=>Nf,ASTForAudioClassification:()=>N_,ASTModel:()=>L_,ASTPreTrainedModel:()=>vo,AfmoeForCausalLM:()=>C_,AfmoeModel:()=>I_,AfmoePreTrainedModel:()=>yo,AlbertForMaskedLM:()=>T_,AlbertForQuestionAnswering:()=>M_,AlbertForSequenceClassification:()=>A_,AlbertModel:()=>E_,AlbertPreTrainedModel:()=>_s,AlbertTokenizer:()=>Fp,ApertusForCausalLM:()=>O_,ApertusModel:()=>S_,ApertusPreTrainedModel:()=>xo,ArceeForCausalLM:()=>z_,ArceeModel:()=>P_,ArceePreTrainedModel:()=>bo,AudioClassificationPipeline:()=>Xi,AutoConfig:()=>Rt,AutoFeatureExtractor:()=>je,AutoImageProcessor:()=>Ae,AutoModel:()=>_r,AutoModelForAudioClassification:()=>Ru,AutoModelForAudioFrameClassification:()=>kv,AutoModelForAudioTextToText:()=>Sv,AutoModelForCTC:()=>$u,AutoModelForCausalLM:()=>Ou,AutoModelForDepthEstimation:()=>Bu,AutoModelForDocumentQuestionAnswering:()=>Du,AutoModelForImageClassification:()=>zu,AutoModelForImageFeatureExtraction:()=>Uu,AutoModelForImageMatting:()=>Ev,AutoModelForImageSegmentation:()=>Ri,AutoModelForImageTextToText:()=>Tv,AutoModelForImageToImage:()=>Fu,AutoModelForMaskGeneration:()=>bv,AutoModelForMaskedLM:()=>Iu,AutoModelForNormalEstimation:()=>Av,AutoModelForObjectDetection:()=>Lu,AutoModelForPoseEstimation:()=>Mv,AutoModelForQuestionAnswering:()=>Cu,AutoModelForSemanticSegmentation:()=>Di,AutoModelForSeq2SeqLM:()=>Mn,AutoModelForSequenceClassification:()=>$i,AutoModelForSpeechSeq2Seq:()=>Mu,AutoModelForTextToSpectrogram:()=>Tu,AutoModelForTextToWaveform:()=>Su,AutoModelForTokenClassification:()=>Au,AutoModelForUniversalSegmentation:()=>Fi,AutoModelForVision2Seq:()=>Pu,AutoModelForXVector:()=>vv,AutoModelForZeroShotObjectDetection:()=>Nu,AutoProcessor:()=>lc,AutoTokenizer:()=>se,AutomaticSpeechRecognitionPipeline:()=>Yi,BackgroundRemovalPipeline:()=>el,BartForConditionalGeneration:()=>R_,BartForSequenceClassification:()=>D_,BartModel:()=>$_,BartPretrainedModel:()=>nn,BartTokenizer:()=>Bp,BaseStreamer:()=>rb,BeitFeatureExtractor:()=>ed,BeitForImageClassification:()=>B_,BeitModel:()=>F_,BeitPreTrainedModel:()=>ko,BertForMaskedLM:()=>j_,BertForQuestionAnswering:()=>W_,BertForSequenceClassification:()=>G_,BertForTokenClassification:()=>q_,BertModel:()=>U_,BertPreTrainedModel:()=>Mr,BertTokenizer:()=>Up,BitImageProcessor:()=>td,BlenderbotForConditionalGeneration:()=>H_,BlenderbotModel:()=>V_,BlenderbotPreTrainedModel:()=>Eo,BlenderbotSmallForConditionalGeneration:()=>K_,BlenderbotSmallModel:()=>X_,BlenderbotSmallPreTrainedModel:()=>Ao,BlenderbotSmallTokenizer:()=>jp,BlenderbotTokenizer:()=>Gp,BloomForCausalLM:()=>Q_,BloomModel:()=>Y_,BloomPreTrainedModel:()=>Mo,BloomTokenizer:()=>qp,CHMv2ForDepthEstimation:()=>nm,CHMv2ImageProcessor:()=>sd,CHMv2PreTrainedModel:()=>Sc,CLIPFeatureExtractor:()=>nd,CLIPImageProcessor:()=>Wl,CLIPModel:()=>am,CLIPPreTrainedModel:()=>rr,CLIPSegForImageSegmentation:()=>pm,CLIPSegModel:()=>um,CLIPSegPreTrainedModel:()=>Co,CLIPTextModel:()=>im,CLIPTextModelWithProjection:()=>Io,CLIPTokenizer:()=>Vp,CLIPVisionModel:()=>lm,CLIPVisionModelWithProjection:()=>cm,CamembertForMaskedLM:()=>Z_,CamembertForQuestionAnswering:()=>rm,CamembertForSequenceClassification:()=>em,CamembertForTokenClassification:()=>tm,CamembertModel:()=>J_,CamembertPreTrainedModel:()=>Tr,CamembertTokenizer:()=>Wp,ChatterboxFeatureExtractor:()=>$f,ChatterboxModel:()=>To,ChatterboxPreTrainedModel:()=>Mc,ChatterboxProcessor:()=>Xf,ChineseCLIPFeatureExtractor:()=>rd,ChineseCLIPModel:()=>sm,ChineseCLIPPreTrainedModel:()=>Tc,ClapAudioModelWithProjection:()=>Oo,ClapFeatureExtractor:()=>Rf,ClapModel:()=>om,ClapPreTrainedModel:()=>on,ClapTextModelWithProjection:()=>So,ClassifierFreeGuidanceLogitsProcessor:()=>wc,CodeGenForCausalLM:()=>dm,CodeGenModel:()=>fm,CodeGenPreTrainedModel:()=>Po,CodeGenTokenizer:()=>Xp,CodeLlamaTokenizer:()=>Hp,Cohere2ForCausalLM:()=>gm,Cohere2Model:()=>hm,Cohere2PreTrainedModel:()=>Lo,CohereAsrFeatureExtractor:()=>Df,CohereAsrForConditionalGeneration:()=>xm,CohereAsrModel:()=>wm,CohereAsrPreTrainedModel:()=>No,CohereAsrProcessor:()=>Kf,CohereAsrTokenizer:()=>Yp,CohereForCausalLM:()=>mm,CohereModel:()=>_m,CoherePreTrainedModel:()=>zo,CohereTokenizer:()=>Kp,ConvBertForMaskedLM:()=>bm,ConvBertForQuestionAnswering:()=>Em,ConvBertForSequenceClassification:()=>vm,ConvBertForTokenClassification:()=>km,ConvBertModel:()=>ym,ConvBertPreTrainedModel:()=>Sr,ConvBertTokenizer:()=>Qp,ConvNextFeatureExtractor:()=>od,ConvNextForImageClassification:()=>Mm,ConvNextImageProcessor:()=>Vl,ConvNextModel:()=>Am,ConvNextPreTrainedModel:()=>$o,ConvNextV2ForImageClassification:()=>Sm,ConvNextV2Model:()=>Tm,ConvNextV2PreTrainedModel:()=>Ro,DFineForObjectDetection:()=>Pm,DFineModel:()=>Cm,DFinePreTrainedModel:()=>Fo,DINOv3ConvNextModel:()=>nh,DINOv3ConvNextPreTrainedModel:()=>Nc,DINOv3ViTImageProcessor:()=>ld,DINOv3ViTModel:()=>oh,DINOv3ViTPreTrainedModel:()=>$c,DPTFeatureExtractor:()=>ud,DPTForDepthEstimation:()=>dh,DPTImageProcessor:()=>Kl,DPTModel:()=>fh,DPTPreTrainedModel:()=>Vo,DacDecoderModel:()=>Uo,DacDecoderOutput:()=>Ic,DacEncoderModel:()=>Bo,DacEncoderOutput:()=>Oc,DacFeatureExtractor:()=>Jn,DacModel:()=>zm,DacPreTrainedModel:()=>an,DebertaForMaskedLM:()=>Nm,DebertaForQuestionAnswering:()=>Dm,DebertaForSequenceClassification:()=>$m,DebertaForTokenClassification:()=>Rm,DebertaModel:()=>Lm,DebertaPreTrainedModel:()=>Or,DebertaTokenizer:()=>Zp,DebertaV2ForMaskedLM:()=>jm,DebertaV2ForQuestionAnswering:()=>Wm,DebertaV2ForSequenceClassification:()=>Gm,DebertaV2ForTokenClassification:()=>qm,DebertaV2Model:()=>Um,DebertaV2PreTrainedModel:()=>Ir,DebertaV2Tokenizer:()=>Jp,DecisionTransformerModel:()=>Vm,DecisionTransformerPreTrainedModel:()=>Cc,DeepseekV3ForCausalLM:()=>Bm,DeepseekV3Model:()=>Fm,DeepseekV3PreTrainedModel:()=>jo,DeiTFeatureExtractor:()=>ad,DeiTForImageClassification:()=>Xm,DeiTImageProcessor:()=>Hl,DeiTModel:()=>Hm,DeiTPreTrainedModel:()=>Go,DepthAnythingForDepthEstimation:()=>Km,DepthAnythingPreTrainedModel:()=>Pc,DepthEstimationPipeline:()=>al,DepthProForDepthEstimation:()=>Ym,DepthProPreTrainedModel:()=>zc,DetrFeatureExtractor:()=>id,DetrForObjectDetection:()=>Jm,DetrForSegmentation:()=>Zm,DetrImageProcessor:()=>Xl,DetrModel:()=>Qm,DetrObjectDetectionOutput:()=>cn,DetrPreTrainedModel:()=>ln,DetrSegmentationOutput:()=>Lc,Dinov2ForImageClassification:()=>th,Dinov2Model:()=>eh,Dinov2PreTrainedModel:()=>qo,Dinov2WithRegistersForImageClassification:()=>sh,Dinov2WithRegistersModel:()=>rh,Dinov2WithRegistersPreTrainedModel:()=>Wo,DistilBertForMaskedLM:()=>uh,DistilBertForQuestionAnswering:()=>ch,DistilBertForSequenceClassification:()=>ih,DistilBertForTokenClassification:()=>lh,DistilBertModel:()=>ah,DistilBertPreTrainedModel:()=>Cr,DistilBertTokenizer:()=>ef,DocumentQuestionAnsweringPipeline:()=>nl,DonutFeatureExtractor:()=>cd,DonutImageProcessor:()=>Hs,DonutSwinModel:()=>ph,DonutSwinPreTrainedModel:()=>Rc,DynamicCache:()=>tn,EdgeTamModel:()=>Ey,EfficientNetForImageClassification:()=>mh,EfficientNetImageProcessor:()=>pd,EfficientNetModel:()=>_h,EfficientNetPreTrainedModel:()=>Ho,ElectraForMaskedLM:()=>gh,ElectraForQuestionAnswering:()=>yh,ElectraForSequenceClassification:()=>wh,ElectraForTokenClassification:()=>xh,ElectraModel:()=>hh,ElectraPreTrainedModel:()=>Pr,ElectraTokenizer:()=>tf,EncodecFeatureExtractor:()=>Yn,EosTokenCriteria:()=>bc,Ernie4_5ForCausalLM:()=>vh,Ernie4_5Model:()=>bh,Ernie4_5PretrainedModel:()=>Xo,EsmForMaskedLM:()=>Eh,EsmForSequenceClassification:()=>Ah,EsmForTokenClassification:()=>Mh,EsmModel:()=>kh,EsmPreTrainedModel:()=>ms,EsmTokenizer:()=>rf,EuroBertForMaskedLM:()=>Sh,EuroBertForSequenceClassification:()=>Oh,EuroBertForTokenClassification:()=>Ih,EuroBertModel:()=>Th,EuroBertPreTrainedModel:()=>hs,ExaoneForCausalLM:()=>Ph,ExaoneModel:()=>Ch,ExaonePreTrainedModel:()=>Ko,FalconForCausalLM:()=>Lh,FalconH1ForCausalLM:()=>$h,FalconH1Model:()=>Nh,FalconH1PreTrainedModel:()=>Qo,FalconModel:()=>zh,FalconPreTrainedModel:()=>Yo,FalconTokenizer:()=>sf,FastViTForImageClassification:()=>Dh,FastViTModel:()=>Rh,FastViTPreTrainedModel:()=>Jo,FeatureExtractionPipeline:()=>il,FeatureExtractor:()=>Ee,FillMaskPipeline:()=>Gi,Florence2ForConditionalGeneration:()=>Fh,Florence2PreTrainedModel:()=>Dc,Florence2Processor:()=>jd,ForcedBOSTokenLogitsProcessor:()=>cc,ForcedEOSTokenLogitsProcessor:()=>uc,GLPNFeatureExtractor:()=>_d,GLPNForDepthEstimation:()=>rg,GLPNModel:()=>tg,GLPNPreTrainedModel:()=>oa,GPT2LMHeadModel:()=>fg,GPT2Model:()=>pg,GPT2PreTrainedModel:()=>ua,GPT2Tokenizer:()=>af,GPTBigCodeForCausalLM:()=>ng,GPTBigCodeModel:()=>sg,GPTBigCodePreTrainedModel:()=>aa,GPTJForCausalLM:()=>_g,GPTJModel:()=>dg,GPTJPreTrainedModel:()=>pa,GPTNeoForCausalLM:()=>ag,GPTNeoModel:()=>og,GPTNeoPreTrainedModel:()=>ia,GPTNeoXForCausalLM:()=>lg,GPTNeoXModel:()=>ig,GPTNeoXPreTrainedModel:()=>la,GPTNeoXTokenizer:()=>of,Gemma2ForCausalLM:()=>Gh,Gemma2Model:()=>jh,Gemma2PreTrainedModel:()=>ea,Gemma3ForCausalLM:()=>Hh,Gemma3ForConditionalGeneration:()=>Uc,Gemma3ImageProcessor:()=>fd,Gemma3Model:()=>Vh,Gemma3PreTrainedModel:()=>Bc,Gemma3Processor:()=>Gd,Gemma3nAudioFeatureExtractor:()=>Zn,Gemma3nForCausalLM:()=>Xh,Gemma3nForConditionalGeneration:()=>zr,Gemma3nPreTrainedModel:()=>jc,Gemma3nProcessor:()=>qd,Gemma4AudioFeatureExtractor:()=>eo,Gemma4ForCausalLM:()=>Kh,Gemma4ForConditionalGeneration:()=>un,Gemma4ImageProcessor:()=>so,Gemma4Processor:()=>Wd,GemmaForCausalLM:()=>Uh,GemmaModel:()=>Bh,GemmaPreTrainedModel:()=>Zo,GemmaTokenizer:()=>nf,Glm46VImageProcessor:()=>dd,Glm46VProcessor:()=>Vd,GlmForCausalLM:()=>Qh,GlmModel:()=>Yh,GlmMoeDsaForCausalLM:()=>Zh,GlmMoeDsaModel:()=>Jh,GlmMoeDsaPreTrainedModel:()=>ra,GlmOcrForConditionalGeneration:()=>eg,GlmPreTrainedModel:()=>ta,GptOssForCausalLM:()=>ug,GptOssModel:()=>cg,GptOssPreTrainedModel:()=>ca,GraniteForCausalLM:()=>hg,GraniteModel:()=>mg,GraniteMoeHybridForCausalLM:()=>wg,GraniteMoeHybridModel:()=>gg,GraniteMoeHybridPreTrainedModel:()=>da,GranitePreTrainedModel:()=>fa,GraniteSpeechFeatureExtractor:()=>Ff,GraniteSpeechForConditionalGeneration:()=>xg,GraniteSpeechProcessor:()=>Hd,GroundingDinoForObjectDetection:()=>yg,GroundingDinoImageProcessor:()=>md,GroundingDinoPreTrainedModel:()=>Wc,GroundingDinoProcessor:()=>Xd,GroupViTModel:()=>bg,GroupViTPreTrainedModel:()=>Vc,HeliumForCausalLM:()=>kg,HeliumModel:()=>vg,HeliumPreTrainedModel:()=>_a,HerbertTokenizer:()=>lf,HieraForImageClassification:()=>Ag,HieraModel:()=>Eg,HieraPreTrainedModel:()=>ma,HubertForCTC:()=>Pg,HubertForSequenceClassification:()=>zg,HubertModel:()=>Cg,HubertPreTrainedModel:()=>Ig,HunYuanDenseV1ForCausalLM:()=>Ng,HunYuanDenseV1Model:()=>Lg,HunYuanDenseV1PreTrainedModel:()=>ha,IJepaForImageClassification:()=>Rg,IJepaModel:()=>$g,IJepaPreTrainedModel:()=>wa,Idefics3ForConditionalGeneration:()=>ga,Idefics3ImageProcessor:()=>Yl,Idefics3Processor:()=>ac,ImageClassificationPipeline:()=>Zi,ImageFeatureExtractionPipeline:()=>ll,ImageFeatureExtractor:()=>H,ImageProcessor:()=>H,ImageSegmentationPipeline:()=>As,ImageToImagePipeline:()=>ol,ImageToTextPipeline:()=>Ji,InterruptableStoppingCriteria:()=>lv,JAISLMHeadModel:()=>Fg,JAISModel:()=>Dg,JAISPreTrainedModel:()=>xa,JinaCLIPImageProcessor:()=>gd,JinaCLIPModel:()=>Bg,JinaCLIPPreTrainedModel:()=>fn,JinaCLIPProcessor:()=>Yd,JinaCLIPTextModel:()=>ya,JinaCLIPVisionModel:()=>Ug,Lfm2ForCausalLM:()=>Gg,Lfm2Model:()=>jg,Lfm2MoeForCausalLM:()=>Vg,Lfm2MoeModel:()=>Wg,Lfm2MoePreTrainedModel:()=>va,Lfm2PreTrainedModel:()=>ba,Lfm2VlForConditionalGeneration:()=>Hg,Lfm2VlImageProcessor:()=>wd,Lfm2VlProcessor:()=>Qd,LightOnOcrForConditionalGeneration:()=>qg,LiteWhisperForConditionalGeneration:()=>F0,Llama4ForCausalLM:()=>Yg,Llama4PreTrainedModel:()=>Hc,LlamaForCausalLM:()=>Kg,LlamaModel:()=>Xg,LlamaPreTrainedModel:()=>ka,LlamaTokenizer:()=>cf,LlavaForConditionalGeneration:()=>bt,LlavaOnevisionForConditionalGeneration:()=>bt,LlavaOnevisionImageProcessor:()=>xd,LlavaPreTrainedModel:()=>Fc,LlavaProcessor:()=>Jd,LlavaQwen2ForCausalLM:()=>Wh,LogLevel:()=>St,LogitsProcessor:()=>It,LogitsProcessorList:()=>ds,LogitsWarper:()=>fo,LongT5ForConditionalGeneration:()=>Jg,LongT5Model:()=>Qg,LongT5PreTrainedModel:()=>Ea,M2M100ForConditionalGeneration:()=>ew,M2M100Model:()=>Zg,M2M100PreTrainedModel:()=>Aa,M2M100Tokenizer:()=>uf,MBart50Tokenizer:()=>ff,MBartForCausalLM:()=>lw,MBartForConditionalGeneration:()=>aw,MBartForSequenceClassification:()=>iw,MBartModel:()=>ow,MBartPreTrainedModel:()=>xs,MBartTokenizer:()=>Xn,MPNetForMaskedLM:()=>Xw,MPNetForQuestionAnswering:()=>Qw,MPNetForSequenceClassification:()=>Kw,MPNetForTokenClassification:()=>Yw,MPNetModel:()=>Hw,MPNetPreTrainedModel:()=>Lr,MPNetTokenizer:()=>mf,MT5ForConditionalGeneration:()=>tx,MT5Model:()=>ex,MT5PreTrainedModel:()=>Da,MarianMTModel:()=>rw,MarianModel:()=>tw,MarianPreTrainedModel:()=>Ma,MarianTokenizer:()=>pf,Mask2FormerImageProcessor:()=>bd,MaskFormerFeatureExtractor:()=>yd,MaskFormerForInstanceSegmentation:()=>nw,MaskFormerImageProcessor:()=>Xs,MaskFormerModel:()=>sw,MaskFormerPreTrainedModel:()=>Ta,MaxLengthCriteria:()=>yc,Metric3DForDepthEstimation:()=>cw,Metric3DPreTrainedModel:()=>Xc,Metric3Dv2ForDepthEstimation:()=>uw,Metric3Dv2PreTrainedModel:()=>Kc,MgpstrForSceneTextRecognition:()=>pw,MgpstrModelOutput:()=>Yc,MgpstrPreTrainedModel:()=>Qc,MgpstrProcessor:()=>Zd,MgpstrTokenizer:()=>df,MimiDecoderModel:()=>Oa,MimiDecoderOutput:()=>Zc,MimiEncoderModel:()=>Sa,MimiEncoderOutput:()=>Jc,MimiModel:()=>fw,MimiPreTrainedModel:()=>dn,MinLengthLogitsProcessor:()=>mc,MinNewTokensLengthLogitsProcessor:()=>hc,Mistral4ForCausalLM:()=>hw,Mistral4Model:()=>mw,Mistral4PreTrainedModel:()=>Ca,MistralForCausalLM:()=>_w,MistralModel:()=>dw,MistralPreTrainedModel:()=>Ia,MobileBertForMaskedLM:()=>ww,MobileBertForQuestionAnswering:()=>yw,MobileBertForSequenceClassification:()=>xw,MobileBertModel:()=>gw,MobileBertPreTrainedModel:()=>ys,MobileBertTokenizer:()=>_f,MobileLLMForCausalLM:()=>vw,MobileLLMModel:()=>bw,MobileLLMPreTrainedModel:()=>Pa,MobileNetV1FeatureExtractor:()=>vd,MobileNetV1ForImageClassification:()=>Ew,MobileNetV1ForSemanticSegmentation:()=>Aw,MobileNetV1ImageProcessor:()=>Ql,MobileNetV1Model:()=>kw,MobileNetV1PreTrainedModel:()=>_n,MobileNetV2FeatureExtractor:()=>kd,MobileNetV2ForImageClassification:()=>Tw,MobileNetV2ForSemanticSegmentation:()=>Sw,MobileNetV2ImageProcessor:()=>Jl,MobileNetV2Model:()=>Mw,MobileNetV2PreTrainedModel:()=>mn,MobileNetV3FeatureExtractor:()=>Ed,MobileNetV3ForImageClassification:()=>Iw,MobileNetV3ForSemanticSegmentation:()=>Cw,MobileNetV3ImageProcessor:()=>Zl,MobileNetV3Model:()=>Ow,MobileNetV3PreTrainedModel:()=>hn,MobileNetV4FeatureExtractor:()=>Ad,MobileNetV4ForImageClassification:()=>zw,MobileNetV4ForSemanticSegmentation:()=>Lw,MobileNetV4ImageProcessor:()=>ec,MobileNetV4Model:()=>Pw,MobileNetV4PreTrainedModel:()=>gn,MobileViTFeatureExtractor:()=>Md,MobileViTForImageClassification:()=>$w,MobileViTImageProcessor:()=>tc,MobileViTModel:()=>Nw,MobileViTPreTrainedModel:()=>za,MobileViTV2ForImageClassification:()=>Dw,MobileViTV2Model:()=>Rw,MobileViTV2PreTrainedModel:()=>La,ModelRegistry:()=>ob,ModernBertDecoderForCausalLM:()=>qw,ModernBertDecoderModel:()=>Gw,ModernBertDecoderPreTrainedModel:()=>Na,ModernBertForMaskedLM:()=>Bw,ModernBertForSequenceClassification:()=>Uw,ModernBertForTokenClassification:()=>jw,ModernBertModel:()=>Fw,ModernBertPreTrainedModel:()=>bs,Moondream1ForConditionalGeneration:()=>qh,MoonshineFeatureExtractor:()=>Bf,MoonshineForConditionalGeneration:()=>Vw,MoonshineModel:()=>Ww,MoonshinePreTrainedModel:()=>$a,MoonshineProcessor:()=>e_,MptForCausalLM:()=>Zw,MptModel:()=>Jw,MptPreTrainedModel:()=>Ra,MultiModalityCausalLM:()=>rx,MultiModalityPreTrainedModel:()=>eu,MusicgenForCausalLM:()=>nx,MusicgenForConditionalGeneration:()=>Ba,MusicgenModel:()=>sx,MusicgenPreTrainedModel:()=>Fa,NanoChatForCausalLM:()=>ax,NanoChatModel:()=>ox,NanoChatPreTrainedModel:()=>Ua,NemotronHForCausalLM:()=>lx,NemotronHModel:()=>ix,NemotronHPreTrainedModel:()=>ja,NeoBertForMaskedLM:()=>ux,NeoBertForQuestionAnswering:()=>dx,NeoBertForSequenceClassification:()=>px,NeoBertForTokenClassification:()=>fx,NeoBertModel:()=>cx,NeoBertPreTrainedModel:()=>Nr,NllbTokenizer:()=>hf,NoBadWordsLogitsProcessor:()=>gc,NoRepeatNGramLogitsProcessor:()=>dc,NomicBertModel:()=>_x,NomicBertPreTrainedModel:()=>tu,NougatImageProcessor:()=>Td,NougatTokenizer:()=>gf,OPTForCausalLM:()=>Sx,OPTModel:()=>Tx,OPTPreTrainedModel:()=>Ka,ObjectDetectionPipeline:()=>rl,Olmo2ForCausalLM:()=>wx,Olmo2Model:()=>gx,Olmo2PreTrainedModel:()=>qa,Olmo3ForCausalLM:()=>yx,Olmo3Model:()=>xx,Olmo3PreTrainedModel:()=>Wa,OlmoForCausalLM:()=>hx,OlmoHybridForCausalLM:()=>vx,OlmoHybridModel:()=>bx,OlmoHybridPreTrainedModel:()=>Va,OlmoModel:()=>mx,OlmoPreTrainedModel:()=>Ga,OpenAIPrivacyFilterForTokenClassification:()=>Ex,OpenAIPrivacyFilterModel:()=>kx,OpenAIPrivacyFilterPreTrainedModel:()=>Ha,OpenELMForCausalLM:()=>Mx,OpenELMModel:()=>Ax,OpenELMPreTrainedModel:()=>Xa,OwlViTFeatureExtractor:()=>Sd,OwlViTForObjectDetection:()=>Px,OwlViTImageProcessor:()=>Ks,OwlViTModel:()=>Cx,OwlViTPreTrainedModel:()=>Qa,OwlViTProcessor:()=>t_,Owlv2ForObjectDetection:()=>Ix,Owlv2ImageProcessor:()=>Od,Owlv2Model:()=>Ox,Owlv2PreTrainedModel:()=>Ya,PaliGemmaForConditionalGeneration:()=>zx,PaliGemmaProcessor:()=>r_,ParakeetFeatureExtractor:()=>Qn,ParakeetForCTC:()=>Lx,ParakeetPreTrainedModel:()=>ru,PatchTSMixerForPrediction:()=>$x,PatchTSMixerModel:()=>Nx,PatchTSMixerPreTrainedModel:()=>Ja,PatchTSTForPrediction:()=>Dx,PatchTSTModel:()=>Rx,PatchTSTPreTrainedModel:()=>Za,Phi3ForCausalLM:()=>jx,Phi3Model:()=>Ux,Phi3PreTrainedModel:()=>ti,Phi3VForCausalLM:()=>ri,Phi3VImageProcessor:()=>Id,Phi3VPreTrainedModel:()=>su,Phi3VProcessor:()=>s_,PhiForCausalLM:()=>Bx,PhiModel:()=>Fx,PhiPreTrainedModel:()=>ei,PixtralImageProcessor:()=>Cd,PixtralProcessor:()=>n_,PreTrainedModel:()=>y,PreTrainedTokenizer:()=>W,PretrainedConfig:()=>Ys,Processor:()=>re,PvtForImageClassification:()=>qx,PvtImageProcessor:()=>Pd,PvtModel:()=>Gx,PvtPreTrainedModel:()=>si,PyAnnoteFeatureExtractor:()=>to,PyAnnoteForAudioFrameClassification:()=>Vx,PyAnnoteModel:()=>Wx,PyAnnotePreTrainedModel:()=>ni,PyAnnoteProcessor:()=>o_,QuestionAnsweringPipeline:()=>ji,Qwen2ForCausalLM:()=>Xx,Qwen2Model:()=>Hx,Qwen2MoeForCausalLM:()=>Yx,Qwen2MoeModel:()=>Kx,Qwen2MoePreTrainedModel:()=>ai,Qwen2PreTrainedModel:()=>oi,Qwen2Tokenizer:()=>wf,Qwen2VLForCausalLM:()=>sa,Qwen2VLForConditionalGeneration:()=>pn,Qwen2VLImageProcessor:()=>no,Qwen2VLPreTrainedModel:()=>Gc,Qwen2VLProcessor:()=>fs,Qwen2_5_VLForCausalLM:()=>na,Qwen2_5_VLForConditionalGeneration:()=>gs,Qwen2_5_VLProcessor:()=>co,Qwen3ForCausalLM:()=>Jx,Qwen3Model:()=>Qx,Qwen3MoeForCausalLM:()=>ey,Qwen3MoeModel:()=>Zx,Qwen3MoePreTrainedModel:()=>li,Qwen3NextForCausalLM:()=>ry,Qwen3NextModel:()=>ty,Qwen3NextPreTrainedModel:()=>ci,Qwen3PreTrainedModel:()=>ii,Qwen3VLForCausalLM:()=>ui,Qwen3VLForConditionalGeneration:()=>vs,Qwen3VLMoeForCausalLM:()=>ny,Qwen3VLMoeForConditionalGeneration:()=>sy,Qwen3VLProcessor:()=>a_,Qwen3_5ForCausalLM:()=>pi,Qwen3_5ForConditionalGeneration:()=>wn,Qwen3_5MoeForCausalLM:()=>ay,Qwen3_5MoeForConditionalGeneration:()=>oy,RFDetrForObjectDetection:()=>uy,RFDetrModel:()=>cy,RFDetrObjectDetectionOutput:()=>nu,RFDetrPreTrainedModel:()=>di,RTDetrForObjectDetection:()=>Im,RTDetrImageProcessor:()=>zd,RTDetrModel:()=>Om,RTDetrObjectDetectionOutput:()=>sr,RTDetrPreTrainedModel:()=>Do,RTDetrV2ForObjectDetection:()=>vy,RTDetrV2Model:()=>by,RTDetrV2ObjectDetectionOutput:()=>ou,RTDetrV2PreTrainedModel:()=>_i,RawAudio:()=>Kn,RawImage:()=>Je,RawVideo:()=>Gu,RawVideoFrame:()=>ul,RepetitionPenaltyLogitsProcessor:()=>_c,ResNetForImageClassification:()=>ly,ResNetModel:()=>iy,ResNetPreTrainedModel:()=>fi,RoFormerForMaskedLM:()=>gy,RoFormerForQuestionAnswering:()=>yy,RoFormerForSequenceClassification:()=>wy,RoFormerForTokenClassification:()=>xy,RoFormerModel:()=>hy,RoFormerPreTrainedModel:()=>Rr,RoFormerTokenizer:()=>yf,RobertaForMaskedLM:()=>fy,RobertaForQuestionAnswering:()=>my,RobertaForSequenceClassification:()=>dy,RobertaForTokenClassification:()=>_y,RobertaModel:()=>py,RobertaPreTrainedModel:()=>$r,RobertaTokenizer:()=>xf,Sam2ImageProcessor:()=>ao,Sam2ImageSegmentationOutput:()=>lu,Sam2Model:()=>mi,Sam2PreTrainedModel:()=>cu,Sam2Processor:()=>ic,Sam2VideoProcessor:()=>i_,Sam3ImageProcessor:()=>ao,Sam3TrackerModel:()=>Ay,SamImageProcessor:()=>ao,SamImageSegmentationOutput:()=>au,SamModel:()=>ky,SamPreTrainedModel:()=>iu,SamProcessor:()=>uo,SapiensFeatureExtractor:()=>Ld,SapiensForDepthEstimation:()=>Ty,SapiensForNormalEstimation:()=>Sy,SapiensForSemanticSegmentation:()=>My,SapiensImageProcessor:()=>rc,SapiensPreTrainedModel:()=>xn,SeamlessM4TFeatureExtractor:()=>Uf,SegformerFeatureExtractor:()=>Nd,SegformerForImageClassification:()=>Iy,SegformerForSemanticSegmentation:()=>Cy,SegformerImageProcessor:()=>sc,SegformerModel:()=>Oy,SegformerPreTrainedModel:()=>yn,SiglipImageProcessor:()=>$d,SiglipModel:()=>Py,SiglipPreTrainedModel:()=>hi,SiglipTextModel:()=>gi,SiglipTokenizer:()=>bf,SiglipVisionModel:()=>zy,SmolLM3ForCausalLM:()=>Ny,SmolLM3Model:()=>Ly,SmolLM3PreTrainedModel:()=>wi,SmolVLMForConditionalGeneration:()=>$y,SmolVLMImageProcessor:()=>Yl,SmolVLMProcessor:()=>ac,SnacDecoderModel:()=>yi,SnacEncoderModel:()=>xi,SnacFeatureExtractor:()=>jf,SnacModel:()=>Ry,SnacPreTrainedModel:()=>bn,SolarOpenForCausalLM:()=>Fy,SolarOpenModel:()=>Dy,SolarOpenPreTrainedModel:()=>bi,SpeechT5FeatureExtractor:()=>Gf,SpeechT5ForSpeechToText:()=>Uy,SpeechT5ForTextToSpeech:()=>jy,SpeechT5HifiGan:()=>Gy,SpeechT5Model:()=>By,SpeechT5PreTrainedModel:()=>vn,SpeechT5Processor:()=>l_,SpeechT5Tokenizer:()=>vf,SqueezeBertForMaskedLM:()=>Wy,SqueezeBertForQuestionAnswering:()=>Hy,SqueezeBertForSequenceClassification:()=>Vy,SqueezeBertModel:()=>qy,SqueezeBertPreTrainedModel:()=>ks,SqueezeBertTokenizer:()=>kf,StableLmForCausalLM:()=>Ky,StableLmModel:()=>Xy,StableLmPreTrainedModel:()=>vi,Starcoder2ForCausalLM:()=>Qy,Starcoder2Model:()=>Yy,Starcoder2PreTrainedModel:()=>ki,StoppingCriteria:()=>Ar,StoppingCriteriaList:()=>Zs,StyleTextToSpeech2Model:()=>Jy,StyleTextToSpeech2PreTrainedModel:()=>uu,SummarizationPipeline:()=>qi,SupertonicForConditionalGeneration:()=>Ei,SupertonicPreTrainedModel:()=>pu,SuppressTokensAtBeginLogitsProcessor:()=>Js,SuppressTokensLogitsProcessor:()=>pc,Swin2SRForImageSuperResolution:()=>s0,Swin2SRImageProcessor:()=>Rd,Swin2SRModel:()=>r0,Swin2SRPreTrainedModel:()=>Ai,SwinForImageClassification:()=>e0,SwinForSemanticSegmentation:()=>t0,SwinModel:()=>Zy,SwinPreTrainedModel:()=>kn,T5ForConditionalGeneration:()=>o0,T5Model:()=>n0,T5PreTrainedModel:()=>Mi,T5Tokenizer:()=>Ef,TableTransformerForObjectDetection:()=>i0,TableTransformerModel:()=>a0,TableTransformerObjectDetectionOutput:()=>fu,TableTransformerPreTrainedModel:()=>Ti,TemperatureLogitsWarper:()=>xc,Tensor:()=>N,Text2TextGenerationPipeline:()=>mr,TextClassificationPipeline:()=>Bi,TextGenerationPipeline:()=>Vi,TextStreamer:()=>sb,TextToAudioPipeline:()=>Qi,TokenClassificationPipeline:()=>Ui,TokenizersBackend:()=>W,TopKLogitsWarper:()=>iv,TopPLogitsWarper:()=>av,TrOCRForCausalLM:()=>l0,TrOCRPreTrainedModel:()=>du,TranslationPipeline:()=>Wi,UltravoxModel:()=>ws,UltravoxPreTrainedModel:()=>qc,UltravoxProcessor:()=>c_,UniSpeechForCTC:()=>u0,UniSpeechForSequenceClassification:()=>p0,UniSpeechModel:()=>c0,UniSpeechPreTrainedModel:()=>En,UniSpeechSatForAudioFrameClassification:()=>m0,UniSpeechSatForCTC:()=>d0,UniSpeechSatForSequenceClassification:()=>_0,UniSpeechSatModel:()=>f0,UniSpeechSatPreTrainedModel:()=>Es,VLChatProcessor:()=>Kd,VLMImageProcessor:()=>hd,VaultGemmaForCausalLM:()=>g0,VaultGemmaModel:()=>h0,VaultGemmaPreTrainedModel:()=>Si,ViTFeatureExtractor:()=>Dd,ViTForImageClassification:()=>y0,ViTImageProcessor:()=>nc,ViTMAEModel:()=>b0,ViTMAEPreTrainedModel:()=>_u,ViTMSNForImageClassification:()=>k0,ViTMSNModel:()=>v0,ViTMSNPreTrainedModel:()=>Ii,ViTModel:()=>x0,ViTPreTrainedModel:()=>Oi,VisionEncoderDecoderModel:()=>w0,VitMatteForImageMatting:()=>E0,VitMatteImageProcessor:()=>Fd,VitMattePreTrainedModel:()=>mu,VitPoseForPoseEstimation:()=>A0,VitPoseImageProcessor:()=>Bd,VitPosePreTrainedModel:()=>hu,VitsModel:()=>M0,VitsModelOutput:()=>gu,VitsPreTrainedModel:()=>wu,VitsTokenizer:()=>Af,VoxtralForConditionalGeneration:()=>T0,VoxtralProcessor:()=>p_,VoxtralRealtimeFeatureExtractor:()=>Vf,VoxtralRealtimeForConditionalGeneration:()=>Ci,VoxtralRealtimePreTrainedModel:()=>xu,VoxtralRealtimeProcessor:()=>d_,Wav2Vec2BertForCTC:()=>O0,Wav2Vec2BertForSequenceClassification:()=>I0,Wav2Vec2BertModel:()=>S0,Wav2Vec2BertPreTrainedModel:()=>An,Wav2Vec2CTCTokenizer:()=>Mf,Wav2Vec2FeatureExtractor:()=>qf,Wav2Vec2ForAudioFrameClassification:()=>Og,Wav2Vec2ForCTC:()=>Tg,Wav2Vec2ForSequenceClassification:()=>Sg,Wav2Vec2Model:()=>Mg,Wav2Vec2PreTrainedModel:()=>Wt,Wav2Vec2Processor:()=>__,Wav2Vec2ProcessorWithLM:()=>m_,WavLMForAudioFrameClassification:()=>N0,WavLMForCTC:()=>P0,WavLMForSequenceClassification:()=>z0,WavLMForXVector:()=>L0,WavLMModel:()=>C0,WavLMPreTrainedModel:()=>Dr,WeSpeakerFeatureExtractor:()=>Wf,WeSpeakerResNetModel:()=>$0,WeSpeakerResNetPreTrainedModel:()=>bu,WhisperFeatureExtractor:()=>Hf,WhisperForConditionalGeneration:()=>vu,WhisperModel:()=>D0,WhisperPreTrainedModel:()=>Pi,WhisperProcessor:()=>h_,WhisperTextStreamer:()=>Ov,WhisperTimeStampLogitsProcessor:()=>fc,WhisperTokenizer:()=>Tf,XLMForQuestionAnswering:()=>q0,XLMForSequenceClassification:()=>j0,XLMForTokenClassification:()=>G0,XLMModel:()=>B0,XLMPreTrainedModel:()=>Fr,XLMRobertaForMaskedLM:()=>V0,XLMRobertaForQuestionAnswering:()=>K0,XLMRobertaForSequenceClassification:()=>H0,XLMRobertaForTokenClassification:()=>X0,XLMRobertaModel:()=>W0,XLMRobertaPreTrainedModel:()=>Br,XLMRobertaTokenizer:()=>Sf,XLMTokenizer:()=>Of,XLMWithLMHeadModel:()=>U0,XVectorOutput:()=>yu,YolosFeatureExtractor:()=>Ud,YolosForObjectDetection:()=>Q0,YolosImageProcessor:()=>oc,YolosModel:()=>Y0,YolosObjectDetectionOutput:()=>ku,YolosPreTrainedModel:()=>zi,YoutuForCausalLM:()=>Z0,YoutuModel:()=>J0,YoutuPreTrainedModel:()=>Li,ZeroShotAudioClassificationPipeline:()=>Ki,ZeroShotClassificationPipeline:()=>Hi,ZeroShotImageClassificationPipeline:()=>tl,ZeroShotObjectDetectionPipeline:()=>sl,cat:()=>ye,cos_sim:()=>zA,dot:()=>Kb,env:()=>_e,full:()=>Ke,full_like:()=>Wn,interpolate:()=>Np,interpolate_4d:()=>yt,layer_norm:()=>JL,load_audio:()=>Z1,load_image:()=>CM,load_video:()=>ST,log_softmax:()=>hp,matmul:()=>q1,mean:()=>Fl,mean_pooling:()=>W1,ones:()=>Ze,ones_like:()=>Bl,permute:()=>xM,pipeline:()=>d3,quantize_embeddings:()=>X1,rand:()=>ZL,randn:()=>H1,random:()=>Kr,read_audio:()=>Lf,rfft:()=>QL,slice:()=>Dl,softmax:()=>Pe,stack:()=>_t,std_mean:()=>$p,topk:()=>Gt,zeros:()=>Rp,zeros_like:()=>Dp});module.exports=GI(h3);var RE=vr(require("fs"),1),Is=vr(require("path"),1),DE=vr(require("url"),1),sC={},qI="4.2.0",zb=typeof self<"u",Ln=!jE(RE.default),FE=!jE(Is.default),rp=zb&&"caches"in self,WI=typeof globalThis.Deno<"u",w3=typeof globalThis.Bun<"u",np=WI&&rp&&!Ln,BE=typeof process<"u",UE=BE&&process?.release?.name==="node"&&!np,Lb=typeof window<"u"&&typeof window.document<"u",Nb=zb&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),VI=Lb||Nb||np,HI=UE||typeof navigator<"u"&&"gpu"in navigator,XI=typeof navigator<"u"&&"ml"in navigator,KI=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",YI=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",QI=typeof ServiceWorkerGlobalScope<"u"&&zb&&self instanceof ServiceWorkerGlobalScope,JI=()=>{if(typeof navigator>"u")return!1;let t=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,s=!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android");return r&&s},ZI=JI(),ie=Object.freeze({IS_BROWSER_ENV:Lb,IS_WEBWORKER_ENV:Nb,IS_WEB_ENV:VI,IS_SERVICE_WORKER_ENV:QI,IS_DENO_WEB_RUNTIME:np,IS_WEB_CACHE_AVAILABLE:rp,IS_WEBGPU_AVAILABLE:HI,IS_WEBNN_AVAILABLE:XI,IS_SAFARI:ZI,IS_PROCESS_AVAILABLE:BE,IS_NODE_ENV:UE,IS_FS_AVAILABLE:Ln,IS_PATH_AVAILABLE:FE,IS_CRYPTO_AVAILABLE:KI,IS_CHROME_AVAILABLE:YI}),$b=Ln&&FE,sp="./";if($b){let t=Object(sC).url;t?sp=Is.default.dirname(Is.default.dirname(DE.default.fileURLToPath(t))):typeof __dirname<"u"&&(sp=Is.default.dirname(__dirname))}var eC=$b?Is.default.join(sp,"/.cache/"):null,NE="/models/",tC=$b?Is.default.join(sp,NE):NE,rC=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,St=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),$E=St.WARNING,_e={version:qI,backends:{onnx:{}},get logLevel(){return $E},set logLevel(t){$E=t,_e.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Lb||Nb||np),localModelPath:tC,useFS:Ln,useBrowserCache:rp,useFSCache:Ln,cacheDir:eC,useCustomCache:!1,customCache:null,useWasmCache:rp||Ln,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:rC};function jE(t){return Object.keys(t).length===0}var We=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function lr(t,e){t&&t(e)}var Cs=class extends We{constructor(e,r){super(),this.callback=e,this.files_loading=r}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let r=Object.values(this.files_loading).reduce((o,a)=>o+a.loaded,0),s=Object.values(this.files_loading).reduce((o,a)=>o+a.total,0),n=s>0?r/s*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:r,total:s,files:structuredClone(this.files_loading)})}this.callback(e)}};function GE(t){return Number.isInteger(t)||typeof t=="bigint"}function Rb(t){return t==null||t===-1}function Db(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function wt(...t){return Array.prototype.concat.apply([],t)}function qE(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function Nn(t,e){return Math.abs((t+e)%(2*e)-e)}function Ve(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function WE(t,e){let r=0;for(let s of t)s===e&&++r;return r}var ee={error(...t){_e.logLevel<=St.ERROR&&console.error(...t)},warn(...t){_e.logLevel<=St.WARNING&&console.warn(...t)},info(...t){_e.logLevel<=St.INFO&&console.log(...t)},debug(...t){_e.logLevel<=St.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var nC=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let s=e;for(let n=0;ns&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),r=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+r),r+=1);let s=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,s[o]]))})(),iC=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),lC=iC(ZE),HE=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",cC=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${HE}])]+`,` ?[^\\s${HE}]+`]]),op="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Bb=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),ap=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[s,n]of cC)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1,o=r.replace(/(\\[pP])\{([^}=]+)\}/g,(a,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(o,"gu")}catch{throw s}}}else if(t.String!==void 0){let r=uC(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},uC=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),pC=(t,e,r)=>{let s=[],n=0;for(;nt>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,dC=t=>Number.isInteger(t)||typeof t=="bigint",_C=t=>{let e=0;for(let r of t)++e;return e},mC=t=>eA(t.toLowerCase()),Xt=(...t)=>Array.prototype.concat.apply([],t),Ub=t=>new Map(Object.entries(t)),hC=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s0&&r.push(o),s=n.index+o.length}return st.replace(/\p{M}/gu,""),XE=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let s of r)if(!(s in t))return`${e} must contain a "${s}" property`;return null},gC=t=>t.match(/\S+/g)||[],wC=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},gl=wC,xC=class extends gl{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},kr=xC,yC=class extends kr{tokenize_chinese_chars(t){let e=[];for(let r=0;r{for(var r in e)tp(t,r,{get:e[r],enumerable:!0})},LE=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of BI(e))!jI.call(t,n)&&n!==r&&tp(t,n,{get:()=>e[n],enumerable:!(s=FI(e,n))||s.enumerable});return t};var vr=(t,e,r)=>(r=t!=null?DI(UI(t)):{},LE(e||!t||!t.__esModule?tp(r,"default",{value:t,enumerable:!0}):r,t)),GI=t=>LE(tp({},"__esModule",{value:!0}),t);var h3={};Os(h3,{ASTFeatureExtractor:()=>Nf,ASTForAudioClassification:()=>N_,ASTModel:()=>L_,ASTPreTrainedModel:()=>vo,AfmoeForCausalLM:()=>C_,AfmoeModel:()=>I_,AfmoePreTrainedModel:()=>yo,AlbertForMaskedLM:()=>T_,AlbertForQuestionAnswering:()=>M_,AlbertForSequenceClassification:()=>A_,AlbertModel:()=>E_,AlbertPreTrainedModel:()=>_s,AlbertTokenizer:()=>Fp,ApertusForCausalLM:()=>O_,ApertusModel:()=>S_,ApertusPreTrainedModel:()=>xo,ArceeForCausalLM:()=>z_,ArceeModel:()=>P_,ArceePreTrainedModel:()=>bo,AudioClassificationPipeline:()=>Xi,AutoConfig:()=>Rt,AutoFeatureExtractor:()=>je,AutoImageProcessor:()=>Ae,AutoModel:()=>_r,AutoModelForAudioClassification:()=>Ru,AutoModelForAudioFrameClassification:()=>kv,AutoModelForAudioTextToText:()=>Sv,AutoModelForCTC:()=>$u,AutoModelForCausalLM:()=>Ou,AutoModelForDepthEstimation:()=>Bu,AutoModelForDocumentQuestionAnswering:()=>Du,AutoModelForImageClassification:()=>zu,AutoModelForImageFeatureExtraction:()=>Uu,AutoModelForImageMatting:()=>Ev,AutoModelForImageSegmentation:()=>Ri,AutoModelForImageTextToText:()=>Tv,AutoModelForImageToImage:()=>Fu,AutoModelForMaskGeneration:()=>bv,AutoModelForMaskedLM:()=>Iu,AutoModelForNormalEstimation:()=>Av,AutoModelForObjectDetection:()=>Lu,AutoModelForPoseEstimation:()=>Mv,AutoModelForQuestionAnswering:()=>Cu,AutoModelForSemanticSegmentation:()=>Di,AutoModelForSeq2SeqLM:()=>Mn,AutoModelForSequenceClassification:()=>$i,AutoModelForSpeechSeq2Seq:()=>Mu,AutoModelForTextToSpectrogram:()=>Tu,AutoModelForTextToWaveform:()=>Su,AutoModelForTokenClassification:()=>Au,AutoModelForUniversalSegmentation:()=>Fi,AutoModelForVision2Seq:()=>Pu,AutoModelForXVector:()=>vv,AutoModelForZeroShotObjectDetection:()=>Nu,AutoProcessor:()=>lc,AutoTokenizer:()=>se,AutomaticSpeechRecognitionPipeline:()=>Yi,BackgroundRemovalPipeline:()=>el,BartForConditionalGeneration:()=>R_,BartForSequenceClassification:()=>D_,BartModel:()=>$_,BartPretrainedModel:()=>nn,BartTokenizer:()=>Bp,BaseStreamer:()=>rb,BeitFeatureExtractor:()=>ed,BeitForImageClassification:()=>B_,BeitModel:()=>F_,BeitPreTrainedModel:()=>ko,BertForMaskedLM:()=>j_,BertForQuestionAnswering:()=>W_,BertForSequenceClassification:()=>G_,BertForTokenClassification:()=>q_,BertModel:()=>U_,BertPreTrainedModel:()=>Mr,BertTokenizer:()=>Up,BitImageProcessor:()=>td,BlenderbotForConditionalGeneration:()=>H_,BlenderbotModel:()=>V_,BlenderbotPreTrainedModel:()=>Eo,BlenderbotSmallForConditionalGeneration:()=>K_,BlenderbotSmallModel:()=>X_,BlenderbotSmallPreTrainedModel:()=>Ao,BlenderbotSmallTokenizer:()=>jp,BlenderbotTokenizer:()=>Gp,BloomForCausalLM:()=>Q_,BloomModel:()=>Y_,BloomPreTrainedModel:()=>Mo,BloomTokenizer:()=>qp,CHMv2ForDepthEstimation:()=>nm,CHMv2ImageProcessor:()=>sd,CHMv2PreTrainedModel:()=>Sc,CLIPFeatureExtractor:()=>nd,CLIPImageProcessor:()=>Wl,CLIPModel:()=>am,CLIPPreTrainedModel:()=>rr,CLIPSegForImageSegmentation:()=>pm,CLIPSegModel:()=>um,CLIPSegPreTrainedModel:()=>Co,CLIPTextModel:()=>im,CLIPTextModelWithProjection:()=>Io,CLIPTokenizer:()=>Vp,CLIPVisionModel:()=>lm,CLIPVisionModelWithProjection:()=>cm,CamembertForMaskedLM:()=>Z_,CamembertForQuestionAnswering:()=>rm,CamembertForSequenceClassification:()=>em,CamembertForTokenClassification:()=>tm,CamembertModel:()=>J_,CamembertPreTrainedModel:()=>Tr,CamembertTokenizer:()=>Wp,ChatterboxFeatureExtractor:()=>$f,ChatterboxModel:()=>To,ChatterboxPreTrainedModel:()=>Mc,ChatterboxProcessor:()=>Xf,ChineseCLIPFeatureExtractor:()=>rd,ChineseCLIPModel:()=>sm,ChineseCLIPPreTrainedModel:()=>Tc,ClapAudioModelWithProjection:()=>Oo,ClapFeatureExtractor:()=>Rf,ClapModel:()=>om,ClapPreTrainedModel:()=>on,ClapTextModelWithProjection:()=>So,ClassifierFreeGuidanceLogitsProcessor:()=>wc,CodeGenForCausalLM:()=>dm,CodeGenModel:()=>fm,CodeGenPreTrainedModel:()=>Po,CodeGenTokenizer:()=>Xp,CodeLlamaTokenizer:()=>Hp,Cohere2ForCausalLM:()=>gm,Cohere2Model:()=>hm,Cohere2PreTrainedModel:()=>Lo,CohereAsrFeatureExtractor:()=>Df,CohereAsrForConditionalGeneration:()=>xm,CohereAsrModel:()=>wm,CohereAsrPreTrainedModel:()=>No,CohereAsrProcessor:()=>Kf,CohereAsrTokenizer:()=>Yp,CohereForCausalLM:()=>mm,CohereModel:()=>_m,CoherePreTrainedModel:()=>zo,CohereTokenizer:()=>Kp,ConvBertForMaskedLM:()=>bm,ConvBertForQuestionAnswering:()=>Em,ConvBertForSequenceClassification:()=>vm,ConvBertForTokenClassification:()=>km,ConvBertModel:()=>ym,ConvBertPreTrainedModel:()=>Sr,ConvBertTokenizer:()=>Qp,ConvNextFeatureExtractor:()=>od,ConvNextForImageClassification:()=>Mm,ConvNextImageProcessor:()=>Vl,ConvNextModel:()=>Am,ConvNextPreTrainedModel:()=>$o,ConvNextV2ForImageClassification:()=>Sm,ConvNextV2Model:()=>Tm,ConvNextV2PreTrainedModel:()=>Ro,DFineForObjectDetection:()=>Pm,DFineModel:()=>Cm,DFinePreTrainedModel:()=>Fo,DINOv3ConvNextModel:()=>nh,DINOv3ConvNextPreTrainedModel:()=>Nc,DINOv3ViTImageProcessor:()=>ld,DINOv3ViTModel:()=>oh,DINOv3ViTPreTrainedModel:()=>$c,DPTFeatureExtractor:()=>ud,DPTForDepthEstimation:()=>dh,DPTImageProcessor:()=>Kl,DPTModel:()=>fh,DPTPreTrainedModel:()=>Vo,DacDecoderModel:()=>Uo,DacDecoderOutput:()=>Ic,DacEncoderModel:()=>Bo,DacEncoderOutput:()=>Oc,DacFeatureExtractor:()=>Jn,DacModel:()=>zm,DacPreTrainedModel:()=>an,DebertaForMaskedLM:()=>Nm,DebertaForQuestionAnswering:()=>Dm,DebertaForSequenceClassification:()=>$m,DebertaForTokenClassification:()=>Rm,DebertaModel:()=>Lm,DebertaPreTrainedModel:()=>Or,DebertaTokenizer:()=>Zp,DebertaV2ForMaskedLM:()=>jm,DebertaV2ForQuestionAnswering:()=>Wm,DebertaV2ForSequenceClassification:()=>Gm,DebertaV2ForTokenClassification:()=>qm,DebertaV2Model:()=>Um,DebertaV2PreTrainedModel:()=>Ir,DebertaV2Tokenizer:()=>Jp,DecisionTransformerModel:()=>Vm,DecisionTransformerPreTrainedModel:()=>Cc,DeepseekV3ForCausalLM:()=>Bm,DeepseekV3Model:()=>Fm,DeepseekV3PreTrainedModel:()=>jo,DeiTFeatureExtractor:()=>ad,DeiTForImageClassification:()=>Xm,DeiTImageProcessor:()=>Hl,DeiTModel:()=>Hm,DeiTPreTrainedModel:()=>Go,DepthAnythingForDepthEstimation:()=>Km,DepthAnythingPreTrainedModel:()=>Pc,DepthEstimationPipeline:()=>al,DepthProForDepthEstimation:()=>Ym,DepthProPreTrainedModel:()=>zc,DetrFeatureExtractor:()=>id,DetrForObjectDetection:()=>Jm,DetrForSegmentation:()=>Zm,DetrImageProcessor:()=>Xl,DetrModel:()=>Qm,DetrObjectDetectionOutput:()=>cn,DetrPreTrainedModel:()=>ln,DetrSegmentationOutput:()=>Lc,Dinov2ForImageClassification:()=>th,Dinov2Model:()=>eh,Dinov2PreTrainedModel:()=>qo,Dinov2WithRegistersForImageClassification:()=>sh,Dinov2WithRegistersModel:()=>rh,Dinov2WithRegistersPreTrainedModel:()=>Wo,DistilBertForMaskedLM:()=>uh,DistilBertForQuestionAnswering:()=>ch,DistilBertForSequenceClassification:()=>ih,DistilBertForTokenClassification:()=>lh,DistilBertModel:()=>ah,DistilBertPreTrainedModel:()=>Cr,DistilBertTokenizer:()=>ef,DocumentQuestionAnsweringPipeline:()=>nl,DonutFeatureExtractor:()=>cd,DonutImageProcessor:()=>Hs,DonutSwinModel:()=>ph,DonutSwinPreTrainedModel:()=>Rc,DynamicCache:()=>tn,EdgeTamModel:()=>Ey,EfficientNetForImageClassification:()=>mh,EfficientNetImageProcessor:()=>pd,EfficientNetModel:()=>_h,EfficientNetPreTrainedModel:()=>Ho,ElectraForMaskedLM:()=>gh,ElectraForQuestionAnswering:()=>yh,ElectraForSequenceClassification:()=>wh,ElectraForTokenClassification:()=>xh,ElectraModel:()=>hh,ElectraPreTrainedModel:()=>Pr,ElectraTokenizer:()=>tf,EncodecFeatureExtractor:()=>Yn,EosTokenCriteria:()=>bc,Ernie4_5ForCausalLM:()=>vh,Ernie4_5Model:()=>bh,Ernie4_5PretrainedModel:()=>Xo,EsmForMaskedLM:()=>Eh,EsmForSequenceClassification:()=>Ah,EsmForTokenClassification:()=>Mh,EsmModel:()=>kh,EsmPreTrainedModel:()=>ms,EsmTokenizer:()=>rf,EuroBertForMaskedLM:()=>Sh,EuroBertForSequenceClassification:()=>Oh,EuroBertForTokenClassification:()=>Ih,EuroBertModel:()=>Th,EuroBertPreTrainedModel:()=>hs,ExaoneForCausalLM:()=>Ph,ExaoneModel:()=>Ch,ExaonePreTrainedModel:()=>Ko,FalconForCausalLM:()=>Lh,FalconH1ForCausalLM:()=>$h,FalconH1Model:()=>Nh,FalconH1PreTrainedModel:()=>Qo,FalconModel:()=>zh,FalconPreTrainedModel:()=>Yo,FalconTokenizer:()=>sf,FastViTForImageClassification:()=>Dh,FastViTModel:()=>Rh,FastViTPreTrainedModel:()=>Jo,FeatureExtractionPipeline:()=>il,FeatureExtractor:()=>Ee,FillMaskPipeline:()=>Gi,Florence2ForConditionalGeneration:()=>Fh,Florence2PreTrainedModel:()=>Dc,Florence2Processor:()=>jd,ForcedBOSTokenLogitsProcessor:()=>cc,ForcedEOSTokenLogitsProcessor:()=>uc,GLPNFeatureExtractor:()=>_d,GLPNForDepthEstimation:()=>rg,GLPNModel:()=>tg,GLPNPreTrainedModel:()=>oa,GPT2LMHeadModel:()=>fg,GPT2Model:()=>pg,GPT2PreTrainedModel:()=>ua,GPT2Tokenizer:()=>af,GPTBigCodeForCausalLM:()=>ng,GPTBigCodeModel:()=>sg,GPTBigCodePreTrainedModel:()=>aa,GPTJForCausalLM:()=>_g,GPTJModel:()=>dg,GPTJPreTrainedModel:()=>pa,GPTNeoForCausalLM:()=>ag,GPTNeoModel:()=>og,GPTNeoPreTrainedModel:()=>ia,GPTNeoXForCausalLM:()=>lg,GPTNeoXModel:()=>ig,GPTNeoXPreTrainedModel:()=>la,GPTNeoXTokenizer:()=>of,Gemma2ForCausalLM:()=>Gh,Gemma2Model:()=>jh,Gemma2PreTrainedModel:()=>ea,Gemma3ForCausalLM:()=>Hh,Gemma3ForConditionalGeneration:()=>Uc,Gemma3ImageProcessor:()=>fd,Gemma3Model:()=>Vh,Gemma3PreTrainedModel:()=>Bc,Gemma3Processor:()=>Gd,Gemma3nAudioFeatureExtractor:()=>Zn,Gemma3nForCausalLM:()=>Xh,Gemma3nForConditionalGeneration:()=>zr,Gemma3nPreTrainedModel:()=>jc,Gemma3nProcessor:()=>qd,Gemma4AudioFeatureExtractor:()=>eo,Gemma4ForCausalLM:()=>Kh,Gemma4ForConditionalGeneration:()=>un,Gemma4ImageProcessor:()=>so,Gemma4Processor:()=>Wd,GemmaForCausalLM:()=>Uh,GemmaModel:()=>Bh,GemmaPreTrainedModel:()=>Zo,GemmaTokenizer:()=>nf,Glm46VImageProcessor:()=>dd,Glm46VProcessor:()=>Vd,GlmForCausalLM:()=>Qh,GlmModel:()=>Yh,GlmMoeDsaForCausalLM:()=>Zh,GlmMoeDsaModel:()=>Jh,GlmMoeDsaPreTrainedModel:()=>ra,GlmOcrForConditionalGeneration:()=>eg,GlmPreTrainedModel:()=>ta,GptOssForCausalLM:()=>ug,GptOssModel:()=>cg,GptOssPreTrainedModel:()=>ca,GraniteForCausalLM:()=>hg,GraniteModel:()=>mg,GraniteMoeHybridForCausalLM:()=>wg,GraniteMoeHybridModel:()=>gg,GraniteMoeHybridPreTrainedModel:()=>da,GranitePreTrainedModel:()=>fa,GraniteSpeechFeatureExtractor:()=>Ff,GraniteSpeechForConditionalGeneration:()=>xg,GraniteSpeechProcessor:()=>Hd,GroundingDinoForObjectDetection:()=>yg,GroundingDinoImageProcessor:()=>md,GroundingDinoPreTrainedModel:()=>Wc,GroundingDinoProcessor:()=>Xd,GroupViTModel:()=>bg,GroupViTPreTrainedModel:()=>Vc,HeliumForCausalLM:()=>kg,HeliumModel:()=>vg,HeliumPreTrainedModel:()=>_a,HerbertTokenizer:()=>lf,HieraForImageClassification:()=>Ag,HieraModel:()=>Eg,HieraPreTrainedModel:()=>ma,HubertForCTC:()=>Pg,HubertForSequenceClassification:()=>zg,HubertModel:()=>Cg,HubertPreTrainedModel:()=>Ig,HunYuanDenseV1ForCausalLM:()=>Ng,HunYuanDenseV1Model:()=>Lg,HunYuanDenseV1PreTrainedModel:()=>ha,IJepaForImageClassification:()=>Rg,IJepaModel:()=>$g,IJepaPreTrainedModel:()=>wa,Idefics3ForConditionalGeneration:()=>ga,Idefics3ImageProcessor:()=>Yl,Idefics3Processor:()=>ac,ImageClassificationPipeline:()=>Zi,ImageFeatureExtractionPipeline:()=>ll,ImageFeatureExtractor:()=>H,ImageProcessor:()=>H,ImageSegmentationPipeline:()=>As,ImageToImagePipeline:()=>ol,ImageToTextPipeline:()=>Ji,InterruptableStoppingCriteria:()=>lv,JAISLMHeadModel:()=>Fg,JAISModel:()=>Dg,JAISPreTrainedModel:()=>xa,JinaCLIPImageProcessor:()=>gd,JinaCLIPModel:()=>Bg,JinaCLIPPreTrainedModel:()=>fn,JinaCLIPProcessor:()=>Yd,JinaCLIPTextModel:()=>ya,JinaCLIPVisionModel:()=>Ug,Lfm2ForCausalLM:()=>Gg,Lfm2Model:()=>jg,Lfm2MoeForCausalLM:()=>Vg,Lfm2MoeModel:()=>Wg,Lfm2MoePreTrainedModel:()=>va,Lfm2PreTrainedModel:()=>ba,Lfm2VlForConditionalGeneration:()=>Hg,Lfm2VlImageProcessor:()=>wd,Lfm2VlProcessor:()=>Qd,LightOnOcrForConditionalGeneration:()=>qg,LiteWhisperForConditionalGeneration:()=>F0,Llama4ForCausalLM:()=>Yg,Llama4PreTrainedModel:()=>Hc,LlamaForCausalLM:()=>Kg,LlamaModel:()=>Xg,LlamaPreTrainedModel:()=>ka,LlamaTokenizer:()=>cf,LlavaForConditionalGeneration:()=>bt,LlavaOnevisionForConditionalGeneration:()=>bt,LlavaOnevisionImageProcessor:()=>xd,LlavaPreTrainedModel:()=>Fc,LlavaProcessor:()=>Jd,LlavaQwen2ForCausalLM:()=>Wh,LogLevel:()=>St,LogitsProcessor:()=>It,LogitsProcessorList:()=>ds,LogitsWarper:()=>fo,LongT5ForConditionalGeneration:()=>Jg,LongT5Model:()=>Qg,LongT5PreTrainedModel:()=>Ea,M2M100ForConditionalGeneration:()=>ew,M2M100Model:()=>Zg,M2M100PreTrainedModel:()=>Aa,M2M100Tokenizer:()=>uf,MBart50Tokenizer:()=>ff,MBartForCausalLM:()=>lw,MBartForConditionalGeneration:()=>aw,MBartForSequenceClassification:()=>iw,MBartModel:()=>ow,MBartPreTrainedModel:()=>xs,MBartTokenizer:()=>Xn,MPNetForMaskedLM:()=>Xw,MPNetForQuestionAnswering:()=>Qw,MPNetForSequenceClassification:()=>Kw,MPNetForTokenClassification:()=>Yw,MPNetModel:()=>Hw,MPNetPreTrainedModel:()=>Lr,MPNetTokenizer:()=>mf,MT5ForConditionalGeneration:()=>tx,MT5Model:()=>ex,MT5PreTrainedModel:()=>Da,MarianMTModel:()=>rw,MarianModel:()=>tw,MarianPreTrainedModel:()=>Ma,MarianTokenizer:()=>pf,Mask2FormerImageProcessor:()=>bd,MaskFormerFeatureExtractor:()=>yd,MaskFormerForInstanceSegmentation:()=>nw,MaskFormerImageProcessor:()=>Xs,MaskFormerModel:()=>sw,MaskFormerPreTrainedModel:()=>Ta,MaxLengthCriteria:()=>yc,Metric3DForDepthEstimation:()=>cw,Metric3DPreTrainedModel:()=>Xc,Metric3Dv2ForDepthEstimation:()=>uw,Metric3Dv2PreTrainedModel:()=>Kc,MgpstrForSceneTextRecognition:()=>pw,MgpstrModelOutput:()=>Yc,MgpstrPreTrainedModel:()=>Qc,MgpstrProcessor:()=>Zd,MgpstrTokenizer:()=>df,MimiDecoderModel:()=>Oa,MimiDecoderOutput:()=>Zc,MimiEncoderModel:()=>Sa,MimiEncoderOutput:()=>Jc,MimiModel:()=>fw,MimiPreTrainedModel:()=>dn,MinLengthLogitsProcessor:()=>mc,MinNewTokensLengthLogitsProcessor:()=>hc,Mistral4ForCausalLM:()=>hw,Mistral4Model:()=>mw,Mistral4PreTrainedModel:()=>Ca,MistralForCausalLM:()=>_w,MistralModel:()=>dw,MistralPreTrainedModel:()=>Ia,MobileBertForMaskedLM:()=>ww,MobileBertForQuestionAnswering:()=>yw,MobileBertForSequenceClassification:()=>xw,MobileBertModel:()=>gw,MobileBertPreTrainedModel:()=>ys,MobileBertTokenizer:()=>_f,MobileLLMForCausalLM:()=>vw,MobileLLMModel:()=>bw,MobileLLMPreTrainedModel:()=>Pa,MobileNetV1FeatureExtractor:()=>vd,MobileNetV1ForImageClassification:()=>Ew,MobileNetV1ForSemanticSegmentation:()=>Aw,MobileNetV1ImageProcessor:()=>Ql,MobileNetV1Model:()=>kw,MobileNetV1PreTrainedModel:()=>_n,MobileNetV2FeatureExtractor:()=>kd,MobileNetV2ForImageClassification:()=>Tw,MobileNetV2ForSemanticSegmentation:()=>Sw,MobileNetV2ImageProcessor:()=>Jl,MobileNetV2Model:()=>Mw,MobileNetV2PreTrainedModel:()=>mn,MobileNetV3FeatureExtractor:()=>Ed,MobileNetV3ForImageClassification:()=>Iw,MobileNetV3ForSemanticSegmentation:()=>Cw,MobileNetV3ImageProcessor:()=>Zl,MobileNetV3Model:()=>Ow,MobileNetV3PreTrainedModel:()=>hn,MobileNetV4FeatureExtractor:()=>Ad,MobileNetV4ForImageClassification:()=>zw,MobileNetV4ForSemanticSegmentation:()=>Lw,MobileNetV4ImageProcessor:()=>ec,MobileNetV4Model:()=>Pw,MobileNetV4PreTrainedModel:()=>gn,MobileViTFeatureExtractor:()=>Md,MobileViTForImageClassification:()=>$w,MobileViTImageProcessor:()=>tc,MobileViTModel:()=>Nw,MobileViTPreTrainedModel:()=>za,MobileViTV2ForImageClassification:()=>Dw,MobileViTV2Model:()=>Rw,MobileViTV2PreTrainedModel:()=>La,ModelRegistry:()=>ob,ModernBertDecoderForCausalLM:()=>qw,ModernBertDecoderModel:()=>Gw,ModernBertDecoderPreTrainedModel:()=>Na,ModernBertForMaskedLM:()=>Bw,ModernBertForSequenceClassification:()=>Uw,ModernBertForTokenClassification:()=>jw,ModernBertModel:()=>Fw,ModernBertPreTrainedModel:()=>bs,Moondream1ForConditionalGeneration:()=>qh,MoonshineFeatureExtractor:()=>Bf,MoonshineForConditionalGeneration:()=>Vw,MoonshineModel:()=>Ww,MoonshinePreTrainedModel:()=>$a,MoonshineProcessor:()=>e_,MptForCausalLM:()=>Zw,MptModel:()=>Jw,MptPreTrainedModel:()=>Ra,MultiModalityCausalLM:()=>rx,MultiModalityPreTrainedModel:()=>eu,MusicgenForCausalLM:()=>nx,MusicgenForConditionalGeneration:()=>Ba,MusicgenModel:()=>sx,MusicgenPreTrainedModel:()=>Fa,NanoChatForCausalLM:()=>ax,NanoChatModel:()=>ox,NanoChatPreTrainedModel:()=>Ua,NemotronHForCausalLM:()=>lx,NemotronHModel:()=>ix,NemotronHPreTrainedModel:()=>ja,NeoBertForMaskedLM:()=>ux,NeoBertForQuestionAnswering:()=>dx,NeoBertForSequenceClassification:()=>px,NeoBertForTokenClassification:()=>fx,NeoBertModel:()=>cx,NeoBertPreTrainedModel:()=>Nr,NllbTokenizer:()=>hf,NoBadWordsLogitsProcessor:()=>gc,NoRepeatNGramLogitsProcessor:()=>dc,NomicBertModel:()=>_x,NomicBertPreTrainedModel:()=>tu,NougatImageProcessor:()=>Td,NougatTokenizer:()=>gf,OPTForCausalLM:()=>Sx,OPTModel:()=>Tx,OPTPreTrainedModel:()=>Ka,ObjectDetectionPipeline:()=>rl,Olmo2ForCausalLM:()=>wx,Olmo2Model:()=>gx,Olmo2PreTrainedModel:()=>qa,Olmo3ForCausalLM:()=>yx,Olmo3Model:()=>xx,Olmo3PreTrainedModel:()=>Wa,OlmoForCausalLM:()=>hx,OlmoHybridForCausalLM:()=>vx,OlmoHybridModel:()=>bx,OlmoHybridPreTrainedModel:()=>Va,OlmoModel:()=>mx,OlmoPreTrainedModel:()=>Ga,OpenAIPrivacyFilterForTokenClassification:()=>Ex,OpenAIPrivacyFilterModel:()=>kx,OpenAIPrivacyFilterPreTrainedModel:()=>Ha,OpenELMForCausalLM:()=>Mx,OpenELMModel:()=>Ax,OpenELMPreTrainedModel:()=>Xa,OwlViTFeatureExtractor:()=>Sd,OwlViTForObjectDetection:()=>Px,OwlViTImageProcessor:()=>Ks,OwlViTModel:()=>Cx,OwlViTPreTrainedModel:()=>Qa,OwlViTProcessor:()=>t_,Owlv2ForObjectDetection:()=>Ix,Owlv2ImageProcessor:()=>Od,Owlv2Model:()=>Ox,Owlv2PreTrainedModel:()=>Ya,PaliGemmaForConditionalGeneration:()=>zx,PaliGemmaProcessor:()=>r_,ParakeetFeatureExtractor:()=>Qn,ParakeetForCTC:()=>Lx,ParakeetPreTrainedModel:()=>ru,PatchTSMixerForPrediction:()=>$x,PatchTSMixerModel:()=>Nx,PatchTSMixerPreTrainedModel:()=>Ja,PatchTSTForPrediction:()=>Dx,PatchTSTModel:()=>Rx,PatchTSTPreTrainedModel:()=>Za,Phi3ForCausalLM:()=>jx,Phi3Model:()=>Ux,Phi3PreTrainedModel:()=>ti,Phi3VForCausalLM:()=>ri,Phi3VImageProcessor:()=>Id,Phi3VPreTrainedModel:()=>su,Phi3VProcessor:()=>s_,PhiForCausalLM:()=>Bx,PhiModel:()=>Fx,PhiPreTrainedModel:()=>ei,PixtralImageProcessor:()=>Cd,PixtralProcessor:()=>n_,PreTrainedModel:()=>y,PreTrainedTokenizer:()=>W,PretrainedConfig:()=>Ys,Processor:()=>re,PvtForImageClassification:()=>qx,PvtImageProcessor:()=>Pd,PvtModel:()=>Gx,PvtPreTrainedModel:()=>si,PyAnnoteFeatureExtractor:()=>to,PyAnnoteForAudioFrameClassification:()=>Vx,PyAnnoteModel:()=>Wx,PyAnnotePreTrainedModel:()=>ni,PyAnnoteProcessor:()=>o_,QuestionAnsweringPipeline:()=>ji,Qwen2ForCausalLM:()=>Xx,Qwen2Model:()=>Hx,Qwen2MoeForCausalLM:()=>Yx,Qwen2MoeModel:()=>Kx,Qwen2MoePreTrainedModel:()=>ai,Qwen2PreTrainedModel:()=>oi,Qwen2Tokenizer:()=>wf,Qwen2VLForCausalLM:()=>sa,Qwen2VLForConditionalGeneration:()=>pn,Qwen2VLImageProcessor:()=>no,Qwen2VLPreTrainedModel:()=>Gc,Qwen2VLProcessor:()=>fs,Qwen2_5_VLForCausalLM:()=>na,Qwen2_5_VLForConditionalGeneration:()=>gs,Qwen2_5_VLProcessor:()=>co,Qwen3ForCausalLM:()=>Jx,Qwen3Model:()=>Qx,Qwen3MoeForCausalLM:()=>ey,Qwen3MoeModel:()=>Zx,Qwen3MoePreTrainedModel:()=>li,Qwen3NextForCausalLM:()=>ry,Qwen3NextModel:()=>ty,Qwen3NextPreTrainedModel:()=>ci,Qwen3PreTrainedModel:()=>ii,Qwen3VLForCausalLM:()=>ui,Qwen3VLForConditionalGeneration:()=>vs,Qwen3VLMoeForCausalLM:()=>ny,Qwen3VLMoeForConditionalGeneration:()=>sy,Qwen3VLProcessor:()=>a_,Qwen3_5ForCausalLM:()=>pi,Qwen3_5ForConditionalGeneration:()=>wn,Qwen3_5MoeForCausalLM:()=>ay,Qwen3_5MoeForConditionalGeneration:()=>oy,RFDetrForObjectDetection:()=>uy,RFDetrModel:()=>cy,RFDetrObjectDetectionOutput:()=>nu,RFDetrPreTrainedModel:()=>di,RTDetrForObjectDetection:()=>Im,RTDetrImageProcessor:()=>zd,RTDetrModel:()=>Om,RTDetrObjectDetectionOutput:()=>sr,RTDetrPreTrainedModel:()=>Do,RTDetrV2ForObjectDetection:()=>vy,RTDetrV2Model:()=>by,RTDetrV2ObjectDetectionOutput:()=>ou,RTDetrV2PreTrainedModel:()=>_i,RawAudio:()=>Kn,RawImage:()=>Je,RawVideo:()=>Gu,RawVideoFrame:()=>ul,RepetitionPenaltyLogitsProcessor:()=>_c,ResNetForImageClassification:()=>ly,ResNetModel:()=>iy,ResNetPreTrainedModel:()=>fi,RoFormerForMaskedLM:()=>gy,RoFormerForQuestionAnswering:()=>yy,RoFormerForSequenceClassification:()=>wy,RoFormerForTokenClassification:()=>xy,RoFormerModel:()=>hy,RoFormerPreTrainedModel:()=>Rr,RoFormerTokenizer:()=>yf,RobertaForMaskedLM:()=>fy,RobertaForQuestionAnswering:()=>my,RobertaForSequenceClassification:()=>dy,RobertaForTokenClassification:()=>_y,RobertaModel:()=>py,RobertaPreTrainedModel:()=>$r,RobertaTokenizer:()=>xf,Sam2ImageProcessor:()=>ao,Sam2ImageSegmentationOutput:()=>lu,Sam2Model:()=>mi,Sam2PreTrainedModel:()=>cu,Sam2Processor:()=>ic,Sam2VideoProcessor:()=>i_,Sam3ImageProcessor:()=>ao,Sam3TrackerModel:()=>Ay,SamImageProcessor:()=>ao,SamImageSegmentationOutput:()=>au,SamModel:()=>ky,SamPreTrainedModel:()=>iu,SamProcessor:()=>uo,SapiensFeatureExtractor:()=>Ld,SapiensForDepthEstimation:()=>Ty,SapiensForNormalEstimation:()=>Sy,SapiensForSemanticSegmentation:()=>My,SapiensImageProcessor:()=>rc,SapiensPreTrainedModel:()=>xn,SeamlessM4TFeatureExtractor:()=>Uf,SegformerFeatureExtractor:()=>Nd,SegformerForImageClassification:()=>Iy,SegformerForSemanticSegmentation:()=>Cy,SegformerImageProcessor:()=>sc,SegformerModel:()=>Oy,SegformerPreTrainedModel:()=>yn,SiglipImageProcessor:()=>$d,SiglipModel:()=>Py,SiglipPreTrainedModel:()=>hi,SiglipTextModel:()=>gi,SiglipTokenizer:()=>bf,SiglipVisionModel:()=>zy,SmolLM3ForCausalLM:()=>Ny,SmolLM3Model:()=>Ly,SmolLM3PreTrainedModel:()=>wi,SmolVLMForConditionalGeneration:()=>$y,SmolVLMImageProcessor:()=>Yl,SmolVLMProcessor:()=>ac,SnacDecoderModel:()=>yi,SnacEncoderModel:()=>xi,SnacFeatureExtractor:()=>jf,SnacModel:()=>Ry,SnacPreTrainedModel:()=>bn,SolarOpenForCausalLM:()=>Fy,SolarOpenModel:()=>Dy,SolarOpenPreTrainedModel:()=>bi,SpeechT5FeatureExtractor:()=>Gf,SpeechT5ForSpeechToText:()=>Uy,SpeechT5ForTextToSpeech:()=>jy,SpeechT5HifiGan:()=>Gy,SpeechT5Model:()=>By,SpeechT5PreTrainedModel:()=>vn,SpeechT5Processor:()=>l_,SpeechT5Tokenizer:()=>vf,SqueezeBertForMaskedLM:()=>Wy,SqueezeBertForQuestionAnswering:()=>Hy,SqueezeBertForSequenceClassification:()=>Vy,SqueezeBertModel:()=>qy,SqueezeBertPreTrainedModel:()=>ks,SqueezeBertTokenizer:()=>kf,StableLmForCausalLM:()=>Ky,StableLmModel:()=>Xy,StableLmPreTrainedModel:()=>vi,Starcoder2ForCausalLM:()=>Qy,Starcoder2Model:()=>Yy,Starcoder2PreTrainedModel:()=>ki,StoppingCriteria:()=>Ar,StoppingCriteriaList:()=>Zs,StyleTextToSpeech2Model:()=>Jy,StyleTextToSpeech2PreTrainedModel:()=>uu,SummarizationPipeline:()=>qi,SupertonicForConditionalGeneration:()=>Ei,SupertonicPreTrainedModel:()=>pu,SuppressTokensAtBeginLogitsProcessor:()=>Js,SuppressTokensLogitsProcessor:()=>pc,Swin2SRForImageSuperResolution:()=>s0,Swin2SRImageProcessor:()=>Rd,Swin2SRModel:()=>r0,Swin2SRPreTrainedModel:()=>Ai,SwinForImageClassification:()=>e0,SwinForSemanticSegmentation:()=>t0,SwinModel:()=>Zy,SwinPreTrainedModel:()=>kn,T5ForConditionalGeneration:()=>o0,T5Model:()=>n0,T5PreTrainedModel:()=>Mi,T5Tokenizer:()=>Ef,TableTransformerForObjectDetection:()=>i0,TableTransformerModel:()=>a0,TableTransformerObjectDetectionOutput:()=>fu,TableTransformerPreTrainedModel:()=>Ti,TemperatureLogitsWarper:()=>xc,Tensor:()=>N,Text2TextGenerationPipeline:()=>mr,TextClassificationPipeline:()=>Bi,TextGenerationPipeline:()=>Vi,TextStreamer:()=>sb,TextToAudioPipeline:()=>Qi,TokenClassificationPipeline:()=>Ui,TokenizersBackend:()=>W,TopKLogitsWarper:()=>iv,TopPLogitsWarper:()=>av,TrOCRForCausalLM:()=>l0,TrOCRPreTrainedModel:()=>du,TranslationPipeline:()=>Wi,UltravoxModel:()=>ws,UltravoxPreTrainedModel:()=>qc,UltravoxProcessor:()=>c_,UniSpeechForCTC:()=>u0,UniSpeechForSequenceClassification:()=>p0,UniSpeechModel:()=>c0,UniSpeechPreTrainedModel:()=>En,UniSpeechSatForAudioFrameClassification:()=>m0,UniSpeechSatForCTC:()=>d0,UniSpeechSatForSequenceClassification:()=>_0,UniSpeechSatModel:()=>f0,UniSpeechSatPreTrainedModel:()=>Es,VLChatProcessor:()=>Kd,VLMImageProcessor:()=>hd,VaultGemmaForCausalLM:()=>g0,VaultGemmaModel:()=>h0,VaultGemmaPreTrainedModel:()=>Si,ViTFeatureExtractor:()=>Dd,ViTForImageClassification:()=>y0,ViTImageProcessor:()=>nc,ViTMAEModel:()=>b0,ViTMAEPreTrainedModel:()=>_u,ViTMSNForImageClassification:()=>k0,ViTMSNModel:()=>v0,ViTMSNPreTrainedModel:()=>Ii,ViTModel:()=>x0,ViTPreTrainedModel:()=>Oi,VisionEncoderDecoderModel:()=>w0,VitMatteForImageMatting:()=>E0,VitMatteImageProcessor:()=>Fd,VitMattePreTrainedModel:()=>mu,VitPoseForPoseEstimation:()=>A0,VitPoseImageProcessor:()=>Bd,VitPosePreTrainedModel:()=>hu,VitsModel:()=>M0,VitsModelOutput:()=>gu,VitsPreTrainedModel:()=>wu,VitsTokenizer:()=>Af,VoxtralForConditionalGeneration:()=>T0,VoxtralProcessor:()=>p_,VoxtralRealtimeFeatureExtractor:()=>Vf,VoxtralRealtimeForConditionalGeneration:()=>Ci,VoxtralRealtimePreTrainedModel:()=>xu,VoxtralRealtimeProcessor:()=>d_,Wav2Vec2BertForCTC:()=>O0,Wav2Vec2BertForSequenceClassification:()=>I0,Wav2Vec2BertModel:()=>S0,Wav2Vec2BertPreTrainedModel:()=>An,Wav2Vec2CTCTokenizer:()=>Mf,Wav2Vec2FeatureExtractor:()=>qf,Wav2Vec2ForAudioFrameClassification:()=>Og,Wav2Vec2ForCTC:()=>Tg,Wav2Vec2ForSequenceClassification:()=>Sg,Wav2Vec2Model:()=>Mg,Wav2Vec2PreTrainedModel:()=>Wt,Wav2Vec2Processor:()=>__,Wav2Vec2ProcessorWithLM:()=>m_,WavLMForAudioFrameClassification:()=>N0,WavLMForCTC:()=>P0,WavLMForSequenceClassification:()=>z0,WavLMForXVector:()=>L0,WavLMModel:()=>C0,WavLMPreTrainedModel:()=>Dr,WeSpeakerFeatureExtractor:()=>Wf,WeSpeakerResNetModel:()=>$0,WeSpeakerResNetPreTrainedModel:()=>bu,WhisperFeatureExtractor:()=>Hf,WhisperForConditionalGeneration:()=>vu,WhisperModel:()=>D0,WhisperPreTrainedModel:()=>Pi,WhisperProcessor:()=>h_,WhisperTextStreamer:()=>Ov,WhisperTimeStampLogitsProcessor:()=>fc,WhisperTokenizer:()=>Tf,XLMForQuestionAnswering:()=>q0,XLMForSequenceClassification:()=>j0,XLMForTokenClassification:()=>G0,XLMModel:()=>B0,XLMPreTrainedModel:()=>Fr,XLMRobertaForMaskedLM:()=>V0,XLMRobertaForQuestionAnswering:()=>K0,XLMRobertaForSequenceClassification:()=>H0,XLMRobertaForTokenClassification:()=>X0,XLMRobertaModel:()=>W0,XLMRobertaPreTrainedModel:()=>Br,XLMRobertaTokenizer:()=>Sf,XLMTokenizer:()=>Of,XLMWithLMHeadModel:()=>U0,XVectorOutput:()=>yu,YolosFeatureExtractor:()=>Ud,YolosForObjectDetection:()=>Q0,YolosImageProcessor:()=>oc,YolosModel:()=>Y0,YolosObjectDetectionOutput:()=>ku,YolosPreTrainedModel:()=>zi,YoutuForCausalLM:()=>Z0,YoutuModel:()=>J0,YoutuPreTrainedModel:()=>Li,ZeroShotAudioClassificationPipeline:()=>Ki,ZeroShotClassificationPipeline:()=>Hi,ZeroShotImageClassificationPipeline:()=>tl,ZeroShotObjectDetectionPipeline:()=>sl,cat:()=>ye,cos_sim:()=>zA,dot:()=>Kb,env:()=>_e,full:()=>Ke,full_like:()=>Wn,interpolate:()=>Np,interpolate_4d:()=>yt,layer_norm:()=>JL,load_audio:()=>Z1,load_image:()=>CM,load_video:()=>ST,log_softmax:()=>hp,matmul:()=>q1,mean:()=>Fl,mean_pooling:()=>W1,ones:()=>Ze,ones_like:()=>Bl,permute:()=>xM,pipeline:()=>d3,quantize_embeddings:()=>X1,rand:()=>ZL,randn:()=>H1,random:()=>Kr,read_audio:()=>Lf,rfft:()=>QL,slice:()=>Dl,softmax:()=>Pe,stack:()=>_t,std_mean:()=>$p,topk:()=>Gt,zeros:()=>Rp,zeros_like:()=>Dp});module.exports=GI(h3);var RE=vr(require("fs"),1),Is=vr(require("path"),1),DE=vr(require("url"),1),sC={},qI="4.2.0",zb=typeof self<"u",Ln=!jE(RE.default),FE=!jE(Is.default),rp=zb&&"caches"in self,WI=typeof globalThis.Deno<"u",w3=typeof globalThis.Bun<"u",np=WI&&rp&&!Ln,BE=typeof process<"u",UE=BE&&process?.release?.name==="node"&&!np,Lb=typeof window<"u"&&typeof window.document<"u",Nb=zb&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),VI=Lb||Nb||np,HI=UE||typeof navigator<"u"&&"gpu"in navigator,XI=typeof navigator<"u"&&"ml"in navigator,KI=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",YI=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",QI=typeof ServiceWorkerGlobalScope<"u"&&zb&&self instanceof ServiceWorkerGlobalScope,JI=()=>{if(typeof navigator>"u")return!1;let t=(navigator.userAgent||""),r=(navigator.vendor||"").indexOf("Apple")>-1,s=!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android");return r&&s},ZI=JI(),ie=Object.freeze({IS_BROWSER_ENV:Lb,IS_WEBWORKER_ENV:Nb,IS_WEB_ENV:VI,IS_SERVICE_WORKER_ENV:QI,IS_DENO_WEB_RUNTIME:np,IS_WEB_CACHE_AVAILABLE:rp,IS_WEBGPU_AVAILABLE:HI,IS_WEBNN_AVAILABLE:XI,IS_SAFARI:ZI,IS_PROCESS_AVAILABLE:BE,IS_NODE_ENV:UE,IS_FS_AVAILABLE:Ln,IS_PATH_AVAILABLE:FE,IS_CRYPTO_AVAILABLE:KI,IS_CHROME_AVAILABLE:YI}),$b=Ln&&FE,sp="./";if($b){let t=Object(sC).url;t?sp=Is.default.dirname(Is.default.dirname(DE.default.fileURLToPath(t))):typeof __dirname<"u"&&(sp=Is.default.dirname(__dirname))}var eC=$b?Is.default.join(sp,"/.cache/"):null,NE="/models/",tC=$b?Is.default.join(sp,NE):NE,rC=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,St=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),$E=St.WARNING,_e={version:qI,backends:{onnx:{}},get logLevel(){return $E},set logLevel(t){$E=t,_e.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Lb||Nb||np),localModelPath:tC,useFS:Ln,useBrowserCache:rp,useFSCache:Ln,cacheDir:eC,useCustomCache:!1,customCache:null,useWasmCache:rp||Ln,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:rC};function jE(t){return Object.keys(t).length===0}var We=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function lr(t,e){t&&t(e)}var Cs=class extends We{constructor(e,r){super(),this.callback=e,this.files_loading=r}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let r=Object.values(this.files_loading).reduce((o,a)=>o+a.loaded,0),s=Object.values(this.files_loading).reduce((o,a)=>o+a.total,0),n=s>0?r/s*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:r,total:s,files:structuredClone(this.files_loading)})}this.callback(e)}};function GE(t){return Number.isInteger(t)||typeof t=="bigint"}function Rb(t){return t==null||t===-1}function Db(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function wt(...t){return Array.prototype.concat.apply([],t)}function qE(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function Nn(t,e){return Math.abs((t+e)%(2*e)-e)}function Ve(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function WE(t,e){let r=0;for(let s of t)s===e&&++r;return r}var ee={error(...t){_e.logLevel<=St.ERROR&&console.error(...t)},warn(...t){_e.logLevel<=St.WARNING&&console.warn(...t)},info(...t){_e.logLevel<=St.INFO&&console.log(...t)},debug(...t){_e.logLevel<=St.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var nC=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let s=e;for(let n=0;ns&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),r=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+r),r+=1);let s=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,s[o]]))})(),iC=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),lC=iC(ZE),HE=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",cC=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${HE}])]+`,` ?[^\\s${HE}]+`]]),op="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Bb=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),ap=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[s,n]of cC)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1,o=r.replace(/(\\[pP])\{([^}=]+)\}/g,(a,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(o,"gu")}catch{throw s}}}else if(t.String!==void 0){let r=uC(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},uC=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),pC=(t,e,r)=>{let s=[],n=0;for(;nt>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,dC=t=>Number.isInteger(t)||typeof t=="bigint",_C=t=>{let e=0;for(let r of t)++e;return e},mC=t=>eA(t.toLowerCase()),Xt=(...t)=>Array.prototype.concat.apply([],t),Ub=t=>new Map(Object.entries(t)),hC=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s0&&r.push(o),s=n.index+o.length}return st.replace(/\p{M}/gu,""),XE=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let s of r)if(!(s in t))return`${e} must contain a "${s}" property`;return null},gC=t=>t.match(/\S+/g)||[],wC=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},gl=wC,xC=class extends gl{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},kr=xC,yC=class extends kr{tokenize_chinese_chars(t){let e=[];for(let r=0;rr.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},kC=vC,EC=class extends kr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>tA(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},AC=EC,MC=class extends kr{normalize(t){let e=ap(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},TC=MC,SC=class extends kr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},ip=SC,OC=class extends ip{constructor(){super(...arguments),this.form="NFC"}},IC=OC,CC=class extends ip{constructor(){super(...arguments),this.form="NFD"}},PC=CC,zC=class extends ip{constructor(){super(...arguments),this.form="NFKC"}},LC=zC,NC=class extends ip{constructor(){super(...arguments),this.form="NFKD"}},$C=NC,RC=class extends kr{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},DC=RC,FC=class extends kr{normalize(t){return eA(t)}},BC=FC,UC=class extends kr{normalize(t){return t.toLowerCase()}},jC=UC,GC=class extends kr{normalize(t){return t=this.config.prepend+t,t}},qC=GC;function WC(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new bC(t);case"Precompiled":return new kC(t);case"Sequence":return new AC(t);case"Replace":return new TC(t);case"NFC":return new IC(t);case"NFD":return new PC(t);case"NFKC":return new LC(t);case"NFKD":return new $C(t);case"Strip":return new DC(t);case"StripAccents":return new BC(t);case"Lowercase":return new jC(t);case"Prepend":return new qC(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var tA=WC,VC=class extends gl{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},Kt=VC,HC=class extends Kt{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=ZE,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(s=>Array.from(this.text_encoder.encode(s),n=>this.byte_encoder[n]).join(""))}},XC=HC,KC=class extends Kt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},YC=KC,QC=class extends Kt{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},s=t.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},JC=QC,ZC=class extends Kt{constructor(t){super(),this.config=t,this.pattern=ap(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):hC(t,this.pattern)}},eP=ZC,tP=class extends Kt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${op}]+|[${op}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},rP=tP,sP=class extends Kt{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},nP=sP,oP=class extends Kt{constructor(){super(),this.pattern=new RegExp(`[^\\s${op}]+|[${op}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},aP=oP,iP=class extends Kt{constructor(t){super(),this.config=t,this.pattern=ap(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},lP=iP,cP=class extends Kt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>rA(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},uP=cP,pP=class extends Kt{pre_tokenize_text(t){return gC(t)}},fP=pP,dP=class extends Kt{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let r=0;rthis.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,a=[];for(;o0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){n=!0;break}a.push(l),o=i}n?e.push(this.unk_token):e.push(...a)}return e}},KE=gP,YE=class sA{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new sA(!1,new Map)}},wP=class{constructor(){this.root=YE.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let s=e.children.get(r);s===void 0&&(s=YE.default(),e.children.set(r,s)),e=s}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let s of t){if(r+=s,e=e.children.get(s),e===void 0)return;e.is_leaf&&(yield r)}}},xP=wP,Fb=class nA{constructor(e,r,s,n,o){this.token_id=e,this.node_id=r,this.pos=s,this.length=n,this.score=o,this.prev=null,this.backtrace_score=0}clone(){let e=new nA(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},yP=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let s=new Fb(this.bos_token_id??0,0,0,0,0),n=new Fb(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(s)}insert(t,e,r,s){let n=this.nodes.length,o=new Fb(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let c of this.end_nodes[e]){let p=c.backtrace_score+a.score;(l===null||p>i)&&(l=c.clone(),i=p)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},bP=yP;function vP(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=vP(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new xP,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,s=0;for(;sr>s,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},TP=MP,SP=class extends lp{constructor(t){super(t),this.tokens_to_ids=Ub(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,s]of this.tokens_to_ids)this.vocab[s]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,s)=>[JSON.stringify(r),s])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new TP(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){let n=new AP((i,l)=>i.score`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);o.every(a=>this.tokens_to_ids.has(a))?e.push(...o):this.unk_token!=null&&e.push(this.unk_token)}else this.unk_token!=null&&e.push(this.unk_token)}return e}},JE=SP,OP=class extends lp{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=Ub(e.target_lang?r[e.target_lang]:r),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[s,n]of this.tokens_to_ids)this.vocab[n]=s}encode(t){return t}},IP=OP;function CP(t,e){switch(t.type){case"WordPiece":return new KE(t);case"Unigram":return new QE(t,e.eos_token);case"BPE":return new JE(t);default:if(t.vocab)return Array.isArray(t.vocab)?new QE(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new JE(t):new KE(t):new IP(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var PP=CP,zP=class extends gl{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},wl=zP,LP=class extends wl{post_process(t,e=null,r=!0){let s=e===null?this.config.single:this.config.pair,n=[],o=[];for(let a of s)"SpecialToken"in a?r&&(n.push(a.SpecialToken.id),o.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(n=Xt(n,t),o=Xt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Xt(n,e),o=Xt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},NP=LP,$P=class extends wl{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},RP=$P,DP=class extends wl{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Xt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=[],o=r?[this.sep[0]]:[];t=Xt(t,n,e,o),s=Xt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},FP=DP,BP=class extends wl{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Xt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=r?[this.sep[0]]:[],o=r?[this.sep[0]]:[];t=Xt(t,n,e,o),s=Xt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},UP=BP,jP=class extends wl{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>oA(e))}post_process(t,e=null,r=!0){let s={tokens:t,tokens_pair:e};for(let n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},GP=jP;function qP(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new NP(t);case"ByteLevel":return new RP(t);case"BertProcessing":return new FP(t);case"RobertaProcessing":return new UP(t);case"Sequence":return new GP(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var oA=qP,WP=class extends gl{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Ft=WP,VP=class extends Ft{constructor(t){super(t),this.byte_decoder=lC,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),r=new Uint8Array([...e].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let s of t)this.added_tokens.find(n=>n.content===s)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(s)):r.push(s);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},HP=VP,XP=class extends Ft{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let s=this.config.prefix;s&&e.startsWith(s)?e=e.replace(s,""):e=" "+e}return this.cleanup&&(e=Bb(e)),e})}},KP=XP,YP=class extends Ft{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;re.replaceAll(this.suffix,r===t.length-1?"":" "))}},ZP=JP,ez=class extends Ft{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;nn!==this.pad_token).join("");return this.cleanup&&(s=Bb(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},tz=ez,rz=class extends Ft{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>aA(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},sz=rz,nz=class extends Ft{decode_chain(t){let e=ap(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},oz=nz,az=class extends Ft{decode_chain(t){return[t.join("")]}},iz=az,lz=class extends Ft{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n")){let o=parseInt(s.slice(3,5),16);isNaN(o)||(n=o)}if(n!==null)r.push(n);else{if(r.length>0){let o=this.text_decoder.decode(Uint8Array.from(r));e.push(o),r=[]}e.push(s)}}if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}return e}},pz=uz;function fz(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new HP(t);case"WordPiece":return new KP(t);case"Metaspace":return new QP(t);case"BPEDecoder":return new ZP(t);case"CTC":return new tz(t);case"Sequence":return new sz(t);case"Replace":return new oz(t);case"Fuse":return new iz(t);case"Strip":return new cz(t);case"ByteFallback":return new pz(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var aA=fz,dz=class{constructor(t,e){let r=XE(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=XE(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=tA(this.tokenizer.normalizer),this.pre_tokenizer=rA(this.tokenizer.pre_tokenizer),this.model=PP(this.tokenizer.model,this.config),this.post_processor=oA(this.tokenizer.post_processor),this.decoder=aA(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let n=[],o=[];this.added_tokens_map=new Map;for(let a of this.tokenizer.added_tokens){let i=new aC(a);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){let l=this.normalizer(i.content);o.push(l),this.added_tokens_map.set(l,i)}else n.push(i.content)}(this.config.additional_special_tokens??[]).forEach(a=>{this.special_tokens.includes(a)||this.special_tokens.push(a)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new VE(n),this.splitter_normalized=new VE(o),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){let{tokens:n,token_type_ids:o}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),a=n.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:a,tokens:n,attention_mask:new Array(a.length).fill(1)};return s&&o&&(i.token_type_ids=o),i}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!dC(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=t.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);e.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let s=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(s=s.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=Bb(s)),s}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((r,s)=>{let n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(e[s-1]=e[s-1].trimEnd()),n.rstrip&&s{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=mC(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let n=this.splitter_normalized.split(r);return n.forEach((o,a)=>{let i=this.added_tokens_map.get(o);i&&(i.lstrip&&a>0&&(n[a-1]=n[a-1].trimEnd()),i.rstrip&&a{if(o.length===0)return[];if(this.added_tokens_map.has(o))return[o];let a=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:s}):[o];return this.model(a)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let s=this.encode_text(t),n=this.encode_text(e||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Xt(s??[],n??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let r=0;r=",D.ComparisonBinaryOperator],["==",D.ComparisonBinaryOperator],["!=",D.ComparisonBinaryOperator],["<",D.ComparisonBinaryOperator],[">",D.ComparisonBinaryOperator],["+",D.AdditiveBinaryOperator],["-",D.AdditiveBinaryOperator],["~",D.AdditiveBinaryOperator],["*",D.MultiplicativeBinaryOperator],["/",D.MultiplicativeBinaryOperator],["%",D.MultiplicativeBinaryOperator],["=",D.Equals]],mz=new Map([["n",` + `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function hz(t,e={}){return t.endsWith(` + `)&&(t=t.slice(0,-1)),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%-])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%-]})\n/g,"$1")),t.replace(/{%\s*(end)?generation\s*%}/gs,"")}function gz(t,e={}){let r=[],s=hz(t,e),n=0,o=0,a=c=>{let p="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],_=mz.get(f);if(_===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);p+=_;continue}if(p+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return p},i=()=>{let c=r.at(-1);c&&c.type===D.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n0){r.push(new Bt(f,D.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let f=s[n]==="-";f&&++n;let _="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");_+=s[n++]}let m=_.endsWith("-");m&&(_=_.slice(0,-1)),f&&i(),r.push(new Bt(_,D.Comment)),n+=2,m&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Bt("{%",D.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Bt("{{",D.OpenExpression)),o=0,n+=3;continue}if(a(cA),s.slice(n,n+3)==="-%}"){r.push(new Bt("%}",D.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Bt("}}",D.CloseExpression)),n+=3,l();continue}let p=s[n];if(p==="-"||p==="+"){let f=r.at(-1)?.type;if(f===D.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(f){case D.Identifier:case D.NumericLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++n;let _=a(xl);r.push(new Bt(`${p}${_}`,_.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(let[f,_]of _z){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new Bt(f,_)),_===D.OpenExpression?o=0:_===D.OpenCurlyBracket?++o:_===D.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(p==="'"||p==='"'){++n;let f=a(_=>_!==p);r.push(new Bt(f,D.StringLiteral)),++n;continue}if(xl(p)){let f=a(xl);if(s[n]==="."&&xl(s[n+1])){++n;let _=a(xl);f=`${f}.${_}`}r.push(new Bt(f,D.NumericLiteral));continue}if(lA(p)){let f=a(lA);r.push(new Bt(f,D.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return r}var Qt=class{type="Statement"},wz=class extends Qt{constructor(t){super(),this.body=t}type="Program"},xz=class extends Qt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},yz=class extends Qt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},bz=class extends Qt{type="Break"},vz=class extends Qt{type="Continue"},kz=class extends Qt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},Ez=class extends Qt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},Az=class extends Qt{constructor(t){super(),this.value=t}type="Comment"},Pt=class extends Qt{type="Expression"},Mz=class extends Pt{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},uA=class extends Pt{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},$n=class extends Pt{constructor(t){super(),this.value=t}type="Identifier"},Rn=class extends Pt{constructor(t){super(),this.value=t}type="Literal"},Tz=class extends Rn{type="IntegerLiteral"},Sz=class extends Rn{type="FloatLiteral"},pA=class extends Rn{type="StringLiteral"},Oz=class extends Rn{type="ArrayLiteral"},fA=class extends Rn{type="TupleLiteral"},Iz=class extends Rn{type="ObjectLiteral"},yl=class extends Pt{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},Cz=class extends Pt{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},Pz=class extends Qt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},zz=class extends Pt{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},Lz=class extends Pt{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},Nz=class extends Pt{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},$z=class extends Pt{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},Rz=class extends Pt{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},Dz=class extends Pt{constructor(t){super(),this.argument=t}type="SpreadExpression"},Fz=class extends Qt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},Bz=class extends Pt{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function Uz(t){let e=new wz([]),r=0;function s(z,$){let B=t[r++];if(!B||B.type!==z)throw new Error(`Parser Error: ${$}. ${B.type} !== ${z}.`);return B}function n(z){if(!l(z))throw new SyntaxError(`Expected ${z}`);++r}function o(){switch(t[r].type){case D.Comment:return new Az(t[r++].value);case D.Text:return c();case D.OpenStatement:return p();case D.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...z){return r+z.length<=t.length&&z.every(($,B)=>$===t[r+B].type)}function i(...z){return t[r]?.type===D.OpenStatement&&t[r+1]?.type===D.Identifier&&z.includes(t[r+1]?.value)}function l(...z){return r+z.length<=t.length&&z.every(($,B)=>t[r+B].type==="Identifier"&&$===t[r+B].value)}function c(){return new pA(s(D.Text,"Expected text token").value)}function p(){if(s(D.OpenStatement,"Expected opening statement token"),t[r].type!==D.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let z=t[r].value,$;switch(z){case"set":++r,$=_();break;case"if":++r,$=m(),s(D.OpenStatement,"Expected {% token"),n("endif"),s(D.CloseStatement,"Expected %} token");break;case"macro":++r,$=w(),s(D.OpenStatement,"Expected {% token"),n("endmacro"),s(D.CloseStatement,"Expected %} token");break;case"for":++r,$=k(),s(D.OpenStatement,"Expected {% token"),n("endfor"),s(D.CloseStatement,"Expected %} token");break;case"call":{++r;let B=null;a(D.OpenParen)&&(B=U());let Q=Y();if(Q.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let le=U();s(D.CloseStatement,"Expected closing statement token");let Ge=[];for(;!i("endcall");)Ge.push(o());s(D.OpenStatement,"Expected '{%'"),n("endcall"),s(D.CloseStatement,"Expected closing statement token");let ce=new uA(Q,le);$=new Fz(ce,B,Ge);break}case"break":++r,s(D.CloseStatement,"Expected closing statement token"),$=new bz;break;case"continue":++r,s(D.CloseStatement,"Expected closing statement token"),$=new vz;break;case"filter":{++r;let B=Y();B instanceof $n&&a(D.OpenParen)&&(B=j(B)),s(D.CloseStatement,"Expected closing statement token");let Q=[];for(;!i("endfilter");)Q.push(o());s(D.OpenStatement,"Expected '{%'"),n("endfilter"),s(D.CloseStatement,"Expected '%}'"),$=new Pz(B,Q);break}default:throw new SyntaxError(`Unknown statement type: ${z}`)}return $}function f(){s(D.OpenExpression,"Expected opening expression token");let z=A();return s(D.CloseExpression,"Expected closing expression token"),z}function _(){let z=x(),$=null,B=[];if(a(D.Equals))++r,$=x();else{for(s(D.CloseStatement,"Expected %} token");!i("endset");)B.push(o());s(D.OpenStatement,"Expected {% token"),n("endset")}return s(D.CloseStatement,"Expected closing statement token"),new kz(z,$,B)}function m(){let z=A();s(D.CloseStatement,"Expected closing statement token");let $=[],B=[];for(;!i("elif","else","endif");)$.push(o());if(i("elif")){++r,++r;let Q=m();B.push(Q)}else if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endif");)B.push(o());return new xz(z,$,B)}function w(){let z=Y();if(z.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let $=U();s(D.CloseStatement,"Expected closing statement token");let B=[];for(;!i("endmacro");)B.push(o());return new Ez(z,$,B)}function x(z=!1){let $=z?Y:A,B=[$()],Q=a(D.Comma);for(;Q&&(++r,B.push($()),!!a(D.Comma)););return Q?new fA(B):B[0]}function k(){let z=x(!0);if(!(z instanceof $n||z instanceof fA))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${z.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let $=A();s(D.CloseStatement,"Expected closing statement token");let B=[];for(;!i("endfor","else");)B.push(o());let Q=[];if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endfor");)Q.push(o());return new yz(z,$,B,Q)}function A(){return E()}function E(){let z=S();if(l("if")){++r;let $=S();if(l("else")){++r;let B=E();return new Bz($,z,B)}else return new zz(z,$)}return z}function S(){let z=T();for(;l("or");){let $=t[r];++r;let B=T();z=new yl($,z,B)}return z}function T(){let z=I();for(;l("and");){let $=t[r];++r;let B=I();z=new yl($,z,B)}return z}function I(){let z;for(;l("not");){let $=t[r];++r;let B=I();z=new Nz($,B)}return z??O()}function O(){let z=b();for(;;){let $;if(l("not","in"))$=new Bt("not in",D.Identifier),r+=2;else if(l("in"))$=t[r++];else if(a(D.ComparisonBinaryOperator))$=t[r++];else break;let B=b();z=new yl($,z,B)}return z}function b(){let z=R();for(;a(D.AdditiveBinaryOperator);){let $=t[r];++r;let B=R();z=new yl($,z,B)}return z}function F(){let z=J(Y());return a(D.OpenParen)?j(z):z}function j(z){let $=new uA(z,U());return $=J($),a(D.OpenParen)&&($=j($)),$}function U(){s(D.OpenParen,"Expected opening parenthesis for arguments list");let z=X();return s(D.CloseParen,"Expected closing parenthesis for arguments list"),z}function X(){let z=[];for(;!a(D.CloseParen);){let $;if(t[r].type===D.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let B=A();$=new Dz(B)}else if($=A(),a(D.Equals)){if(++r,!($ instanceof $n))throw new SyntaxError("Expected identifier for keyword argument");let B=A();$=new Rz($,B)}z.push($),a(D.Comma)&&++r}return z}function K(){let z=[],$=!1;for(;!a(D.CloseSquareBracket);)a(D.Colon)?(z.push(void 0),++r,$=!0):(z.push(A()),a(D.Colon)&&(++r,$=!0));if(z.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if($){if(z.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new $z(...z)}return z[0]}function J(z){for(;a(D.Dot)||a(D.OpenSquareBracket);){let $=t[r];++r;let B,Q=$.type===D.OpenSquareBracket;if(Q)B=K(),s(D.CloseSquareBracket,"Expected closing square bracket");else if(B=Y(),B.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");z=new Mz(z,B,Q)}return z}function R(){let z=C();for(;a(D.MultiplicativeBinaryOperator);){let $=t[r++],B=C();z=new yl($,z,B)}return z}function C(){let z=ne();for(;l("is");){++r;let $=l("not");$&&++r;let B=Y();if(!(B instanceof $n))throw new SyntaxError("Expected identifier for the test");z=new Lz(z,$,B)}return z}function ne(){let z=F();for(;a(D.Pipe);){++r;let $=Y();if(!($ instanceof $n))throw new SyntaxError("Expected identifier for the filter");a(D.OpenParen)&&($=j($)),z=new Cz(z,$)}return z}function Y(){let z=t[r++];switch(z.type){case D.NumericLiteral:{let $=z.value;return $.includes(".")?new Sz(Number($)):new Tz(Number($))}case D.StringLiteral:{let $=z.value;for(;a(D.StringLiteral);)$+=t[r++].value;return new pA($)}case D.Identifier:return new $n(z.value);case D.OpenParen:{let $=x();return s(D.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),$}case D.OpenSquareBracket:{let $=[];for(;!a(D.CloseSquareBracket);)$.push(A()),a(D.Comma)&&++r;return++r,new Oz($)}case D.OpenCurlyBracket:{let $=new Map;for(;!a(D.CloseCurlyBracket);){let B=A();s(D.Colon,"Expected colon between key and value in object literal");let Q=A();$.set(B,Q),a(D.Comma)&&++r}return++r,new Iz($)}default:throw new SyntaxError(`Unexpected token: ${z.type}`)}}for(;r0)for(let n=t;ne;n+=r)s.push(n);return s}function dA(t,e,r,s=1){let n=Math.sign(s);n>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));let o=[];for(let a=e;n*ae.toUpperCase())}function qz(t){return Wz(new Date,t)}function Wz(t,e){let r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),n=o=>o<10?"0"+o:o.toString();return e.replace(/%[YmdbBHM%]/g,o=>{switch(o){case"%Y":return t.getFullYear().toString();case"%m":return n(t.getMonth()+1);case"%d":return n(t.getDate());case"%b":return s.format(t);case"%B":return r.format(t);case"%H":return n(t.getHours());case"%M":return n(t.getMinutes());case"%%":return"%";default:return o}})}function Vz(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hz(t,e,r,s){if(s===0)return t;let n=s==null||s<0?1/0:s,o=e.length===0?new RegExp("(?=)","gu"):new RegExp(Vz(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var _A=class extends Error{},mA=class extends Error{},cr=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new de(!!this.value)}toString(){return String(this.value)}},he=class extends cr{type="IntegerValue"},et=class extends cr{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},te=class extends cr{type="StringValue";builtins=new Map([["upper",new Xe(()=>new te(this.value.toUpperCase()))],["lower",new Xe(()=>new te(this.value.toLowerCase()))],["strip",new Xe(()=>new te(this.value.trim()))],["title",new Xe(()=>new te(Gz(this.value)))],["capitalize",new Xe(()=>new te(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new he(this.value.length)],["rstrip",new Xe(()=>new te(this.value.trimEnd()))],["lstrip",new Xe(()=>new te(this.value.trimStart()))],["startswith",new Xe(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof te)return new de(this.value.startsWith(e.value));if(e instanceof be){for(let r of e.value){if(!(r instanceof te))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new de(!0)}return new de(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Xe(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof te)return new de(this.value.endsWith(e.value));if(e instanceof be){for(let r of e.value){if(!(r instanceof te))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new de(!0)}return new de(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Xe(t=>{let e=t[0]??new Ye;if(!(e instanceof te||e instanceof Ye))throw new Error("sep argument must be a string or null");let r=t[1]??new he(-1);if(!(r instanceof he))throw new Error("maxsplit argument must be a number");let s=[];if(e instanceof Ye){let n=this.value.trimStart();for(let{0:o,index:a}of n.matchAll(/\S+/g)){if(r.value!==-1&&s.length>=r.value&&a!==void 0){s.push(o+n.slice(a+o.length));break}s.push(o)}}else{if(e.value==="")throw new Error("empty separator");s=this.value.split(e.value),r.value!==-1&&s.length>r.value&&s.push(s.splice(r.value).join(e.value))}return new be(s.map(n=>new te(n)))})],["replace",new Xe(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],r=t[1];if(!(e instanceof te&&r instanceof te))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new Ye:s=t[2]:s=new Ye,!(s instanceof he||s instanceof Ye))throw new Error("replace() count argument must be a number or null");return new te(Hz(this.value,e.value,r.value,s.value))})]])},de=class extends cr{type="BooleanValue"},Xz=/[\x7f-\uffff]/g;function hA(t){return t.replace(Xz,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function zs(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,c;switch(a?[l,c]=a:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let p=JSON.stringify(t.value);return o&&(p=hA(p)),p}case"ArrayValue":case"ObjectValue":{let p=n?" ".repeat(n):"",f=` +@@ -7,7 +7,7 @@ var DI=Object.create;var tp=Object.defineProperty;var FI=Object.getOwnPropertyDe + `));case"join":case"string":return t;case"int":{let n=parseInt(t.value,10);return new he(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new et(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof he||t instanceof et)switch(s.value){case"abs":return t instanceof he?new he(Math.abs(t.value)):new et(Math.abs(t.value));case"int":return new he(Math.floor(t.value));case"float":return new et(t.value);case"string":return new te(t.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(t instanceof ft)switch(s.value){case"items":return new be(Array.from(t.value.entries()).map(([n,o])=>new be([new te(n),o])));case"length":return new he(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof Xe?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(t instanceof de)switch(s.value){case"bool":return new de(t.value);case"int":return new he(t.value?1:0);case"float":return new et(t.value?1:0);case"string":return new te(t.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${t.type}`)}else if(e.type==="CallExpression"){let s=e;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);let n=s.callee.value;if(n==="tojson"){let[,o]=this.evaluateArguments(s.args,r),a=o.get("indent")??new Ye;if(!(a instanceof he||a instanceof Ye))throw new Error("If set, indent must be a number");let i=o.get("ensure_ascii")??new de(!1);if(!(i instanceof de))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new de(!1);if(!(l instanceof de))throw new Error("If set, sort_keys must be a boolean");let c=o.get("separators")??new Ye,p=null;if(c instanceof be||c instanceof gA){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,_]=c.value;if(!(f instanceof te)||!(_ instanceof te))throw new Error("separators must be a tuple of two strings");p=[f.value,_.value]}else if(!(c instanceof Ye))throw new Error("If set, separators must be a tuple of two strings");return new te(zs(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:p}))}else if(n==="join"){let o;if(t instanceof te)o=Array.from(t.value);else if(t instanceof be)o=t.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[a,i]=this.evaluateArguments(s.args,r),l=a.at(0)??i.get("separator")??new te("");if(!(l instanceof te))throw new Error("separator must be a string");return new te(o.join(l.value))}else if(n==="int"||n==="float"){let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("default")??(n==="int"?new he(0):new et(0));if(t instanceof te){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new he(l):new et(l)}else{if(t instanceof he||t instanceof et)return t;if(t instanceof de)return n==="int"?new he(t.value?1:0):new et(t.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}}else if(n==="default"){let[o,a]=this.evaluateArguments(s.args,r),i=o[0]??new te(""),l=o[1]??a.get("boolean")??new de(!1);if(!(l instanceof de))throw new Error("`default` filter flag must be a boolean");return t instanceof He||l.value&&!t.__bool__().value?i:t}if(t instanceof be){switch(n){case"sort":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("reverse")??new de(!1);if(!(i instanceof de))throw new Error("reverse must be a boolean");let l=o.at(1)??a.get("case_sensitive")??new de(!1);if(!(l instanceof de))throw new Error("case_sensitive must be a boolean");let c=o.at(2)??a.get("attribute")??new Ye;if(!(c instanceof te||c instanceof he||c instanceof Ye))throw new Error("attribute must be a string, integer, or null");let p=f=>{if(c instanceof Ye)return f;let _=c instanceof he?String(c.value):c.value;return wA(f,_)};return new be(t.value.slice().sort((f,_)=>{let m=p(f),w=p(_),x=jb(m,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!(f instanceof ft)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[a,i,l]=s.args.map(f=>this.evaluate(f,r)),c;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);c=f}else c=(...f)=>f[0].__bool__().value;let p=t.value.filter(f=>{let _=f.value.get(a.value),m=_?c(_,l):!1;return o?m:!m});return new be(p)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof te))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(c=>{if(!(c instanceof ft))throw new Error("items in map must be an object");let p=wA(c,a.value);return p instanceof He?i??new He:p});return new be(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof te){switch(n){case"indent":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("width")??new he(4);if(!(i instanceof he))throw new Error("width must be a number");let l=o.at(1)??a.get("first")??new de(!1),c=o.at(2)??a.get("blank")??new de(!1),p=t.value.split(` + `),f=" ".repeat(i.value),_=p.map((m,w)=>!l.value&&w===0||!c.value&&m.length===0?m:f+m);return new te(_.join(` + `))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof Xe))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new bl(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof ft){let o=t.builtins.get(n);if(o&&o instanceof Xe){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new bl(i)),o.value(a,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}throw new Error(`Unknown filter: ${e.type}`)}evaluateFilterExpression(t,e){let r=this.evaluate(t.operand,e);return this.applyFilter(r,t.filter,e)}evaluateTestExpression(t,e){let r=this.evaluate(t.operand,e),s=e.tests.get(t.test.value);if(!s)throw new Error(`Unknown test: ${t.test.value}`);let n=s(r);return new de(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new He}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);if(t.operator.value==="not")return new de(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evaluateTernaryExpression(t,e){return this.evaluate(t.condition,e).__bool__().value?this.evaluate(t.trueExpr,e):this.evaluate(t.falseExpr,e)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(let s of t){let n=this.evaluate(s,e);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new te(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){let[r,s]=this.evaluateArguments(t.args,e);s.size>0&&r.push(new bl(s));let n=this.evaluate(t.callee,e);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof be||t instanceof te))throw new Error("Slice object must be an array or string");let s=this.evaluate(e.start,r),n=this.evaluate(e.stop,r),o=this.evaluate(e.step,r);if(!(s instanceof he||s instanceof He))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof he||n instanceof He))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof he||o instanceof He))throw new Error("Slice step must be numeric or undefined");return t instanceof be?new be(dA(t.value,s.value,n.value,o.value)):new te(dA(Array.from(t.value),s.value,n.value,o.value).join(""))}evaluateMemberExpression(t,e){let r=this.evaluate(t.object,e),s;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);s=this.evaluate(t.property,e)}else s=new te(t.property.value);let n;if(r instanceof ft){if(!(s instanceof te))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof be||r instanceof te)if(s instanceof he)n=r.value.at(s.value),r instanceof te&&(n=new te(r.value.at(s.value)));else if(s instanceof te)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof te))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof cr?n:new He}evaluateSet(t,e){let r=t.value?this.evaluate(t.value,e):this.evaluateBlock(t.body,e);if(t.assignee.type==="Identifier"){let s=t.assignee.value;e.setVariable(s,r)}else if(t.assignee.type==="TupleLiteral"){let s=t.assignee;if(!(r instanceof be))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let o=0;om.setVariable(t.loopvar.value,f);else if(t.loopvar.type==="TupleLiteral"){let m=t.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);let w=f;if(m.value.length!==w.value.length)throw new Error(`Too ${m.value.length>w.value.length?"few":"many"} items to unpack`);_=x=>{for(let k=0;k0?o[c-1]:new He],["nextitem",c{let n=new Ps(s);r=r.slice();let o;r.at(-1)?.type==="KeywordArgumentsValue"&&(o=r.pop());for(let a=0;a{let c=new Ps(l);if(t.callerArgs)for(let p=0;pthis.evaluate(r,e)));case"TupleLiteral":return new gA(t.value.map(r=>this.evaluate(r,e)));case"ObjectLiteral":{let r=new Map;for(let[s,n]of t.value){let o=this.evaluate(s,e);if(!(o instanceof te))throw new Error(`Object keys must be strings: got ${o.type}`);r.set(o.value,this.evaluate(n,e))}return new ft(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"FilterStatement":return this.evaluateFilterStatement(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);case"SelectExpression":return this.evaluateSelectExpression(t,e);case"Ternary":return this.evaluateTernaryExpression(t,e);case"Comment":return new Ye;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function cp(t){switch(typeof t){case"number":return Number.isInteger(t)?new he(t):new et(t);case"string":return new te(t);case"boolean":return new de(t);case"undefined":return new He;case"object":return t===null?new Ye:Array.isArray(t)?new be(t.map(cp)):new ft(new Map(Object.entries(t).map(([e,r])=>[e,cp(r)])));case"function":return new Xe((e,r)=>{let s=t(...e.map(n=>n.value))??null;return cp(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var at=` +-`,Qz="{%- ",Jz=" -%}";function Zz(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function eL(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Yt(t.body,0,r).replace(/\n$/,"")}function xt(...t){return Qz+t.join(" ")+Jz}function Yt(t,e,r){return t.map(s=>tL(s,e,r)).join(at)}function tL(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Yt(t.body,e,r);case"If":return rL(t,e,r);case"For":return sL(t,e,r);case"Set":return nL(t,e,r);case"Macro":return oL(t,e,r);case"Break":return s+xt("break");case"Continue":return s+xt("continue");case"CallStatement":return aL(t,e,r);case"FilterStatement":return iL(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function rL(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+xt("if",ke(n[0].test))+at+Yt(n[0].body,e+1,r);for(let i=1;i0&&(a+=at+s+xt("else")+at+Yt(o.alternate,e+1,r)),a+=at+s+xt("endif"),a}function sL(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+xt("for",ke(t.loopvar),"in",n)+at+Yt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=at+s+xt("else")+at+Yt(t.defaultBlock,e+1,r)),o+=at+s+xt("endfor"),o}function nL(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+xt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+at+Yt(t.body,e+1,r)+at+s+xt("endset")}function oL(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+xt("macro",`${t.name.value}(${n})`)+at+Yt(t.body,e+1,r)+at+s+xt("endmacro")}function aL(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+xt(`call${n}`,o)+at;return a+=Yt(t.body,e+1,r)+at,a+=s+xt("endcall"),a}function iL(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+xt("filter",n)+at;return o+=Yt(t.body,e+1,r)+at,o+=s+xt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=Zz(r),n=ke(r.left,s),o=ke(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var xA=class{parsed;constructor(t){let e=gz(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Uz(e)}render(t){let e=new Ps;if(Kz(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new Yz(e).run(this.parsed).value}format(t){return eL(this.parsed,t?.indent||" ")}};var Ls=vr(require("fs"),1),lL={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"},Hr=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=Ls.default.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=Ls.default.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=Ls.default.createReadStream(e);this.body=new ReadableStream({start(n){s.on("data",o=>n.enqueue(o)),s.on("end",()=>n.close()),s.on("error",o=>n.error(o))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",lL[e]??"application/octet-stream")}clone(){let e=new t(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await Ls.default.promises.readFile(this.filePath)).buffer}async blob(){let e=await Ls.default.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await Ls.default.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};var Dn=vr(require("fs"),1),vl=vr(require("path"),1);var Xr=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(ie.IS_CRYPTO_AVAILABLE){let i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;let r=this._mt,s=(i,l)=>Math.imul(i,l)>>>0,n=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))n.push(i&4294967295);n.length||n.push(0),r[0]=19650218;for(let i=1;i<624;++i)r[i]=s(1812433253,r[i-1]^r[i-1]>>>30)+i>>>0;let o=1,a=0;for(let i=Math.max(624,n.length);i>0;--i,++o,++a)o>=624&&(r[0]=r[623],o=1),a>=n.length&&(a=0),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1664525))+n[a]+a>>>0;for(let i=623;i>0;--i,++o)o>=624&&(r[0]=r[623],o=1),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1566083941))-o>>>0;r[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let s=0;s<624;++s){let n=e[s]&2147483648|e[(s+1)%624]&2147483647;e[s]=(e[(s+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let r=e[this._idx++];return r^=r>>>11,r^=r<<7&2636928640,r^=r<<15&4022730752,r^=r>>>18,r>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,r=1){let s=this._gauss_next;if(this._gauss_next=null,s===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+s*r}shuffle(e){for(let r=e.length-1;r>0;--r){let s=32-Math.clz32(r+1),n=this._int32()>>>32-s;for(;n>r;)n=this._int32()>>>32-s;let o=e[r];e[r]=e[n],e[n]=o}}choices(e,r){return e[yA(this._random_fn,r)]}};function yA(t,e){let r=0;for(let n=0;nyA(Kr.random,t);var cL=new Xr,Fn=class{constructor(e){this.path=e}async match(e){let r=vl.default.join(this.path,e),s=new Hr(r);if(s.exists)return s}async put(e,r,s=void 0){let n=vl.default.join(this.path,e),o=ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=cL._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),p=0;await Dn.default.promises.mkdir(vl.default.dirname(n),{recursive:!0});let f=Dn.default.createWriteStream(i),_=r.body.getReader();for(;;){let{done:m,value:w}=await _.read();if(m)break;await new Promise((k,A)=>{f.write(w,E=>{if(E){A(E);return}k()})}),p+=w.length;let x=c?p/c*100:0;s?.({progress:x,loaded:p,total:c})}await new Promise((m,w)=>{f.close(x=>x?w(x):m())}),await Dn.default.promises.rename(i,n)}catch(l){try{await Dn.default.promises.unlink(i)}catch{}throw l}}async delete(e){let r=vl.default.join(this.path,e);try{return await Dn.default.promises.unlink(r),!0}catch{return!1}}};var vA={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"},up=100,kA=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;var Gb={};function kl(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function Yr(t,e=null,r=null){let s;try{s=new URL(t)}catch{return!1}return!(e&&!e.includes(s.protocol)||r&&!r.includes(s.hostname))}function EA(t){return!(!kA.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function AA(t,e,r){if(!r)return null;let s=vA[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function MA(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&ee.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:p}=await i.read();if(c)return;let f=a+p.length;if(f>n){n=f;let m=new Uint8Array(n);m.set(o),o=m}o.set(p,a),a=f;let _=a/n*100;return e({progress:_,loaded:a,total:n}),l()}return await l(),o}function qb(t){return Yr(t,["blob:"])}function Wb(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof Gb<"u"&&Gb.url)e=Gb.url;else return t;return new URL(t,e).href}var SA="SHA-256",uL="experimental_transformers-hash-cache",TA=t=>({algorithm:SA,value:t}),El=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(uL),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let r=await this._getFileHash(e);if(r)try{let[s]=await navigator.crossOriginStorage.requestFileHandles([TA(r)]),n=await s.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,r)=>{let s=await this._getFileHash(e);if(s){let n=await r.blob();await this._storeBlobInCOS(n,s)}else this._processAndStore(e,r.body)};_storeBlobInCOS=async(e,r)=>{let[s]=await navigator.crossOriginStorage.requestFileHandles([TA(r)],{create:!0}),n=await s.createWritable();await n.write(e),await n.close()};_processAndStore=async(e,r)=>{try{let s=[];for await(let a of r)s.push(a);let n=new Blob(s),o=await this._getBlobHash(n);await this._storeBlobInCOS(n,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let r=await this._getHashCache(),s=await r.match(e);if(s)return s.text();let n=await this._getLfsFileHash(e);return n?(await r.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let r=e.replace("/resolve/","/raw/");try{let n=(await fetch(r).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{let r=await e.arrayBuffer(),s=await crypto.subtle.digest(SA,r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function Jt(t=null){let e=null;if(_e.useCustomCache){if(!_e.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!_e.customCache.match||!_e.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=_e.customCache}if(!e&&_e.experimental_useCrossOriginStorage&&El.isAvailable()&&(e=new El),!e&&_e.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(_e.cacheKey)}catch(r){ee.warn("An error occurred while opening the browser cache:",r)}}if(!e&&_e.useFSCache){if(!ie.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new Fn(t??_e.cacheDir)}return e}async function OA(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var pp=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let r=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,r),r}put(e,r){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,r),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};var pL=100,Vb=new pp(pL);function fp(t,e){let r=Vb.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(Vb.delete(t),Promise.reject(n)));return Vb.put(t,s),s}async function fL(t){if(!Yr(t,["http:","https:"]))return null;let e=Hb(t);return e.set("Range","bytes=0-0"),_e.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function Ot(t,e,r={}){let s=JSON.stringify([t,e,r?.revision,r?.cache_dir,r?.local_files_only]);return fp(s,()=>dL(t,e,r))}async function dL(t,e,r){let s=await Jt(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=Jr(t,e,r,s),l=await Zr(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),p=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:p||void 0,fromCache:!0}}if(_e.allowLocalModels&&!Yr(n,["http:","https:"]))try{let p=await Qr(n);if(typeof p!="string"&&p.status!==404){let f=p.headers.get("content-length"),_=p.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:_||void 0,fromCache:!1}}}catch{}if(_e.allowRemoteModels&&!r.local_files_only&&i)try{let c=await fL(o);if(c&&c.status>=200&&c.status<300){let p,f=c.headers.get("content-type");if(c.status===206){let _=c.headers.get("content-range");if(_){let m=_.match(/bytes \d+-\d+\/(\d+)/);m&&(p=parseInt(m[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(p===void 0){let _=c.headers.get("content-length");p=_?parseInt(_,10):void 0}return{exists:!0,size:p,contentType:f||void 0,fromCache:!1}}}catch(c){ee.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function Qr(t){return _e.useFS&&!Yr(t,["http:","https:","blob:"])?new Hr(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):_e.fetch(t,{headers:Hb(t)})}function Hb(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=_e.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),Yr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function Jr(t,e,r={},s=null){let n=r.revision??"main",o=kl(t,e),a=EA(t),i=a?kl(_e.localModelPath,o):o,l=kl(_e.remoteHost,_e.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof Fn?n==="main"?o:kl(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function Zr(t,e,r){if(t)return await OA(t,e,r)}async function _L(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o){if(typeof n!="string"){let i=new Headers(n.headers);i.set("content-length",o.byteLength.toString()),await r.put(s,new Response(o,{headers:i})).catch(l=>{ee.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=a.progress_callback?l=>lr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function mL(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:p}=Jr(t,e,s,o),f,_=!1,m;m=await Zr(o,i,c);let w=m!==void 0;if(w)f=c;else{if(_e.allowLocalModels)if(Yr(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!_e.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{m=await Qr(i),f=i}catch(E){ee.warn(`Unable to load from local path "${i}": "${E}"`)}if(m===void 0||typeof m!="string"&&m.status===404){if(s.local_files_only||!_e.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!p)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(m=await Qr(l),m.status!==200)return AA(m.status,l,r);f=c}_=o&&typeof Response<"u"&&m instanceof Response&&m.status===200}lr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(ie.IS_NODE_ENV&&n)){let A;if(typeof m!="string")if(!s.progress_callback)A=new Uint8Array(await m.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))A=new Uint8Array(await m.arrayBuffer()),lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A.length,total:A.length});else{let E,S=m.headers.get("content-length");if(S)E=parseInt(S,10);else try{let T=await Ot(t,e,s);T.size&&(E=T.size)}catch{}A=await MA(m,T=>{lr(s.progress_callback,{status:"progress",name:t,file:e,...T})},E)}x=A}if(_&&f&&typeof m!="string"&&await _L(t,e,o,f,m,x,s),ie.IS_NODE_ENV&&n&&s.progress_callback&&typeof m!="string"){let A=parseInt(m.headers.get("content-length"),10)||0;lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A,total:A})}if(lr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!ie.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(m instanceof Hr)return m.filePath;let k=await o?.match(f);if(k instanceof Hr)return k.filePath;if(k instanceof Response)return new Uint8Array(await k.arrayBuffer());if(typeof k=="string")return k;throw new Error("Unable to get model file path or buffer.")}var dp=new Map;async function Al(t,e,r=!0,s={},n=!1){if(!_e.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!_e.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}lr(s.progress_callback,{status:"initiate",name:t,file:e});let o=`${t}::${e}`,a=dp.get(o);if(!a){let i=await Jt(s?.cache_dir);a=mL(t,e,r,s,n,i).then(l=>(dp.delete(o),l),l=>{throw dp.delete(o),l}),dp.set(o,a)}return await a}async function Ml(t,e,r=!0,s={}){let n=await Al(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function nt(t,e,r=!0,s={}){let n=await Ml(t,e,r,s);return n===null?{}:JSON.parse(n)}function CA(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,p=new t.constructor(n*o*e),f=r*s,_=n*o;for(let m=0;m=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i=0;--c)l+=p%e[c]*o[c],p=Math.floor(p/e[c]);a[l]=t[i]}return[a,s]}function Pe(t){let e=ze(t)[0],r=t.map(o=>Math.exp(o-e)),s=r.reduce((o,a)=>o+a,0);return r.map(o=>o/s)}function hp(t){let e=ze(t)[0],r=0;for(let o=0;oo-e-s)}function Kb(t,e){let r=0;for(let s=0;se+r*r,0))}function Tl(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;se&&(e=t[s],r=s);return[e,r]}function LA(t){return t>0&&(t&t-1)===0}var _p=class{constructor(e){if(this.size=e|0,this.size<=1||!LA(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;ss;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>2;for(l=0;l>>1,a>>>1)}else for(l=0,c=0;l>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>1,w=m>>>1,x=w>>>1;for(l=0;l>>1;for(let m=2;m<_;m+=2)e[n-m]=e[m],e[n-m+1]=-e[m+1]}_singleRealTransform2(e,r,s,n,o){let a=e[n],i=e[n+o];r[s]=a+i,r[s+1]=0,r[s+2]=a-i,r[s+3]=0}_singleRealTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,c=e[n],p=e[n+o],f=e[n+i],_=e[n+l],m=c+f,w=c-f,x=p+_,k=a*(p-_);r[s]=m+x,r[s+1]=0,r[s+2]=w,r[s+3]=-k,r[s+4]=m-x,r[s+5]=0,r[s+6]=w,r[s+7]=k}},Xb=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let i=-2*Math.PI/e,l=Math.cos(i),c=Math.sin(i);for(let p=0;p>1;++p){let f=(p+1-e)**2/2,_=Math.sqrt(l**2+c**2)**f,m=f*Math.atan2(c,l),w=2*p;o[w]=_*Math.cos(m),o[w+1]=_*Math.sin(m),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new _p(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,p=this._a;if(s)for(let f=0;f>1,w=r[m];n[f]=w*c[f],n[_]=w*c[_]}else for(let f=0;f=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function Ns(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function $A(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function RA(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let p=1;p0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var DA=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l>10,_=l&1023;if(f===31)c=p|2139095040|_<<13;else if(f===0)if(_===0)c=p;else{let m=113;for(;(_&1024)===0;)_<<=1,--m;_&=-1025,c=p|m<<23|_<<13}else c=p|f+112<<23|_<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;oE1,TRACE:()=>Ap,TRACE_EVENT_BEGIN:()=>ns,TRACE_EVENT_END:()=>os,TRACE_FUNC_BEGIN:()=>Us,TRACE_FUNC_END:()=>js,Tensor:()=>er,default:()=>qL,env:()=>Qe,registerBackend:()=>Bs});var Zt={};var v1=Object.defineProperty,hL=Object.getOwnPropertyDescriptor,gL=Object.getOwnPropertyNames,wL=Object.prototype.hasOwnProperty,xL=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),ve=(t,e)=>()=>(t&&(e=t(t=0)),e),Nl=(t,e)=>{for(var r in e)v1(t,r,{get:e[r],enumerable:!0})},yL=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of gL(e))!wL.call(t,n)&&n!==r&&v1(t,n,{get:()=>e[n],enumerable:!(s=hL(e,n))||s.enumerable});return t},Ep=t=>yL(v1({},"__esModule",{value:!0}),t),Sl,es,Bs,FA,f2,d2=ve(()=>{"use strict";Sl=new Map,es=[],Bs=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=Sl.get(t);if(s===void 0)Sl.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=es.indexOf(t);n!==-1&&es.splice(n,1);for(let o=0;o{let e=Sl.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(s){return r||(e.error=`${s}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},f2=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?es:r,n,o=[],a=new Set;for(let l of s){let c=await FA(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),bL=ve(()=>{"use strict";d2()}),_2,vL=ve(()=>{"use strict";_2="1.24.0-dev.20251116-b39e144322"}),Yb,dt,m2=ve(()=>{"use strict";vL(),Yb="warning",dt={wasm:{},webgl:{},webgpu:{},versions:{common:_2},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);Yb=t}},get logLevel(){return Yb}},Object.defineProperty(dt,"logLevel",{enumerable:!0})}),Qe,kL=ve(()=>{"use strict";m2(),Qe=dt}),h2,g2,EL=ve(()=>{"use strict";h2=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let p=o*n,f=0,_=p,m=p*2,w=-1;a==="RGBA"?(f=0,_=p,m=p*2,w=p*3):a==="RGB"?(f=0,_=p,m=p*2):a==="RBG"&&(f=0,m=p,_=p*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let _=4,m=0,w=1,x=2,k=3,A=0,E=f,S=f*2,T=-1;i==="RGBA"?(A=0,E=f,S=f*2,T=f*3):i==="RGB"?(A=0,E=f,S=f*2):i==="RBG"&&(A=0,S=f,E=f*2),s=r.createImageData(n,o);for(let I=0;I{"use strict";k1(),gp=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,_=0,m=1,w=2,x=3,k=0,A=c,E=c*2,S=-1;i==="RGB"&&(f=3,_=0,m=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(k=0,E=c,A=c*2):l==="BGR"&&(E=0,A=c,k=c*2);for(let T=0;T{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let _=t.height,m=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(_=e.resizedHeight,m=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=m}else i.tensorFormat="RGBA",i.height=_,i.width=m;f.drawImage(t,0,0),a=f.getImageData(0,0,m,_).data}else throw new Error("Can not access image data")}else if(s){let p,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(p=e.resizedHeight,f=e.resizedWidth):(p=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=p,i.width=f,e!==void 0){let _=l();_.width=f,_.height=p;let m=c(_);if(m!=null)m.putImageData(t,0,0),a=m.getImageData(0,0,f,p).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let _=t.height,m=t.width;return f.drawImage(t,0,0,m,_),a=f.getImageData(0,0,m,_).data,i.height=_,i.width=m,gp(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,f)=>{let _=l(),m=c(_);if(!t||!m)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{_.width=w.width,_.height=w.height,m.drawImage(w,0,0,_.width,_.height);let x=m.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,p(gp(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return gp(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},x2=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Nt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},y2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Nt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},b2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Nt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},v2=(t,e,r)=>new Nt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),Ds,zl,Qb,k2,ML=ve(()=>{"use strict";Ds=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),zl=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Qb=!1,k2=()=>{if(!Qb){Qb=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Ds.set("int64",BigInt64Array),zl.set(BigInt64Array,"int64")),e&&(Ds.set("uint64",BigUint64Array),zl.set(BigUint64Array,"uint64")),s?(Ds.set("float16",r),zl.set(r,"float16")):Ds.set("float16",Uint16Array)}}}),E2,A2,TL=ve(()=>{"use strict";k1(),E2=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new Nt(t.type,t.data,e);case"cpu-pinned":return new Nt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Nt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Nt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Nt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Nt,k1=ve(()=>{"use strict";EL(),AL(),ML(),TL(),Nt=class{constructor(t,e,r){k2();let s,n;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,n=t.dims,t.location){case"cpu-pinned":{let a=Ds.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,i;if(typeof t=="string")if(s=t,i=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=Ds.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")s="string",a=t;else if(l==="boolean")s="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(t);else{let l=zl.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=l,a=t}if(i===void 0)i=[a.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=a,this.dataLocation="cpu"}let o=E2(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(t,e){return w2(t,e)}static fromTexture(t,e){return x2(t,e)}static fromGpuBuffer(t,e){return y2(t,e)}static fromMLTensor(t,e){return b2(t,e)}static fromPinnedBuffer(t,e,r){return v2(t,e,r)}toDataURL(t){return h2(this,t)}toImageData(t){return g2(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return A2(this,t)}}}),er,M2=ve(()=>{"use strict";k1(),er=Nt}),Ap,Jb,Us,js,ns,os,T2=ve(()=>{"use strict";m2(),Ap=(t,e)=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeStamp(`${t}::ORT::${e}`)},Jb=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||Jb("BEGIN",t)},js=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||Jb("END",t)},ns=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.time(`ORT::${t}`)},os=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeEnd(`ORT::${t}`)}}),S2,SL=ve(()=>{"use strict";d2(),M2(),T2(),S2=class O2{constructor(e){this.handler=e}async run(e,r,s){Us(),ns("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof er||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof er)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(p.indexOf(f)!==-1){let _=r[f];(_===null||_ instanceof er)&&(c=!0,a=!1,n[f]=_)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let p=i[c];p instanceof er?l[c]=p:l[c]=new er(p.type,p.data,p.dims)}return os("InferenceSession.run"),js(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){Us(),ns("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let p=e,f=0,_=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(_=e.byteLength-f,typeof s=="number"){if(_=s,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||f+_>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,f,_)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await f2(a),c=await i.createInferenceSessionHandler(o,l);return os("InferenceSession.create"),js(),new O2(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),E1,OL=ve(()=>{"use strict";SL(),E1=S2}),IL=ve(()=>{"use strict"}),CL=ve(()=>{"use strict"}),PL=ve(()=>{"use strict"}),zL=ve(()=>{"use strict"}),I2={};Nl(I2,{InferenceSession:()=>E1,TRACE:()=>Ap,TRACE_EVENT_BEGIN:()=>ns,TRACE_EVENT_END:()=>os,TRACE_FUNC_BEGIN:()=>Us,TRACE_FUNC_END:()=>js,Tensor:()=>er,env:()=>Qe,registerBackend:()=>Bs});var Gs=ve(()=>{"use strict";bL(),kL(),OL(),M2(),IL(),CL(),T2(),PL(),zL()}),A1=ve(()=>{"use strict"}),C2={};Nl(C2,{default:()=>P2});var Zb,e1,P2,LL=ve(()=>{"use strict";H2(),qs(),M1(),Zb="ort-wasm-proxy-worker",e1=globalThis.self?.name===Zb,e1&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":T1(r.wasm).then(()=>{P1(r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})})},s=>{postMessage({type:e,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;z1(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=Sp(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;L1(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":N1(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;$1(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},D1([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":R1(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),P2=e1?null:t=>new Worker(t??zt,{type:"module",name:Zb})}),z2={};Nl(z2,{default:()=>L2});async function BA(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(u,d)=>{u.startsWith("./")&&(u=u.substring(2)),(e.Uc||(e.Uc=new Map)).set(u,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let o=()=>{let u=d=>(...h)=>{let g=ar;return h=d(...h),ar!=g?new Promise((v,M)=>{mb={resolve:v,reject:M}}):h};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=u(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(u,d)=>{throw d},c=Zt.url,p="";if(r||s){try{p=new URL(".",c).href}catch{}s&&(i=u=>{var d=new XMLHttpRequest;return d.open("GET",u,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async u=>{if(O(u))return new Promise((h,g)=>{var v=new XMLHttpRequest;v.open("GET",u,!0),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?h(v.response):g(v.status)},v.onerror=g,v.send(null)});var d=await fetch(u,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,_,m,w,x,k,A=console.log.bind(console),E=console.error.bind(console),S=A,T=E,I=!1,O=u=>u.startsWith("file://");function b(){Wr.buffer!=U.buffer&&le()}if(n){let u=function(d){try{var h=d.data,g=h.Oc;if(g==="load"){let v=[];self.onmessage=M=>v.push(M),k=()=>{postMessage({Oc:"loaded"});for(let M of v)u(M);self.onmessage=u};for(let M of h.ce)e[M]&&!e[M].proxy||(e[M]=(...P)=>{postMessage({Oc:"callHandler",be:M,args:P})},M=="print"&&(S=e[M]),M=="printErr"&&(T=e[M]));Wr=h.ie,le(),_=h.je,qe(),ep()}else if(g==="run"){(function(v){var M=(b(),C)[v+52>>>2>>>0];v=(b(),C)[v+56>>>2>>>0],Wk(M,M-v),pe(M)})(h.Nc),Tb(h.Nc,0,0,1,0,0),Pv(),fb(h.Nc),j||(Tk(),j=!0);try{DT(h.ge,h.Wc)}catch(v){if(v!="unwind")throw v}}else h.target!=="setimmediate"&&(g==="checkMailbox"?j&&Vu():g&&(T(`worker: received unknown command ${g}`),T(h)))}catch(v){throw Bk(),v}};var F=u,j=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=u}var U,X,K,J,R,C,ne,Y,z,$,B,Q=!1;function le(){var u=Wr.buffer;e.HEAP8=U=new Int8Array(u),K=new Int16Array(u),e.HEAPU8=X=new Uint8Array(u),J=new Uint16Array(u),e.HEAP32=R=new Int32Array(u),e.HEAPU32=C=new Uint32Array(u),ne=new Float32Array(u),Y=new Float64Array(u),z=new BigInt64Array(u),$=new BigUint64Array(u)}function Ge(){Q=!0,n?k():br._b()}function ce(u){throw T(u="Aborted("+u+")"),I=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),x?.(u),u}function Et(){return{a:{f:FT,J:BT,k:UT,p:jT,l:GT,sa:qT,b:WT,ca:VT,Ja:Dv,q:HT,da:jv,Za:Gv,Fa:qv,Ha:Wv,_a:Vv,Xa:Hv,Qa:Xv,Wa:Kv,oa:Yv,Ga:Qv,Xb:Jv,Ya:Zv,Yb:ek,db:XT,Da:YT,Sb:QT,Qb:ZT,Ca:tS,M:rS,I:sS,Rb:nS,ja:pS,Tb:fS,Ta:dS,Vb:mS,Ka:hS,Ob:gS,ka:wS,Sa:fb,ab:xS,U:kS,n:SS,c:ub,rb:OS,w:IS,L:CS,z:PS,j:zS,o:lk,sb:LS,G:NS,T:$S,h:RS,u:DS,m:FS,i:BS,Na:US,Oa:jS,Pa:GS,La:fk,Ma:dk,Pb:_k,eb:WS,cb:XS,Y:KS,qb:YS,la:QS,bb:VS,fb:JS,$a:ZS,Wb:eO,N:qS,gb:tO,X:rO,Ub:sO,nb:fO,C:dO,ra:_O,qa:mO,pb:hO,W:gO,v:wO,mb:xO,lb:yO,kb:bO,ob:vO,jb:kO,ib:EO,hb:AO,Ua:yk,Va:bk,Ia:Sn,V:vk,na:kk,Ra:Ek,ma:Ak,Cb:NI,xa:OI,Db:LI,ya:SI,F:gI,e:nI,s:rI,x:tI,B:_I,Fb:AI,ba:EI,D:iI,za:MI,$:II,ga:kI,Gb:vI,Hb:bI,Ba:wI,Aa:yI,Ib:xI,wa:zI,aa:TI,d:sI,A:aI,r:oI,Bb:$I,t:cI,y:mI,H:lI,E:uI,K:hI,R:CI,ia:dI,_:PI,Jb:fI,Kb:pI,g:TO,a:Wr,Nb:Tn,Eb:SO,ha:OO,O:IO,pa:CO,Lb:PO,ta:zO,Q:LO,yb:NO,zb:$O,ua:RO,ea:DO,P:FO,Ea:BO,va:UO,Z:jO,wb:GO,Zb:qO,S:WO,Ab:VO,tb:HO,ub:KO,vb:YO,fa:QO,xb:JO,Mb:ZO}}}async function qe(){function u(g,v){var M=br=g.exports;g={};for(let[P,L]of Object.entries(M))typeof L=="function"?(M=yS(L),g[P]=M):g[P]=L;return br=g,br=(function(){var P=br,L=Z=>Ie=>Z(Ie)>>>0,G=Z=>()=>Z()>>>0;return(P=Object.assign({},P)).$b=L(P.$b),P.Cc=G(P.Cc),P.Ec=L(P.Ec),P.rd=(Z=>(Ie,$e)=>Z(Ie,$e)>>>0)(P.rd),P.wd=L(P.wd),P.xd=G(P.xd),P.Bd=L(P.Bd),P})(),Iv.push(br.id),Mk=(g=br).$b,Tk=g.ac,e._OrtInit=g.bc,e._OrtGetLastError=g.cc,e._OrtCreateSessionOptions=g.dc,e._OrtAppendExecutionProvider=g.ec,e._OrtAddFreeDimensionOverride=g.fc,e._OrtAddSessionConfigEntry=g.gc,e._OrtReleaseSessionOptions=g.hc,e._OrtCreateSession=g.ic,e._OrtReleaseSession=g.jc,e._OrtGetInputOutputCount=g.kc,e._OrtGetInputOutputMetadata=g.lc,e._OrtFree=g.mc,e._OrtCreateTensor=g.nc,e._OrtGetTensorData=g.oc,e._OrtReleaseTensor=g.pc,e._OrtCreateRunOptions=g.qc,e._OrtAddRunConfigEntry=g.rc,e._OrtReleaseRunOptions=g.sc,e._OrtCreateBinding=g.tc,e._OrtBindInput=g.uc,e._OrtBindOutput=g.vc,e._OrtClearBoundOutputs=g.wc,e._OrtReleaseBinding=g.xc,e._OrtRunWithBinding=g.yc,e._OrtRun=g.zc,e._OrtEndProfiling=g.Ac,bb=e._OrtGetWebGpuDevice=g.Bc,Ju=g.Cc,Ht=e._free=g.Dc,zn=e._malloc=g.Ec,Sk=e._wgpuBufferRelease=g.Fc,Ok=e._wgpuCreateInstance=g.Gc,Ik=g.Hc,Ck=g.Ic,Pk=g.Jc,zk=g.Kc,Lk=g.Lc,Nk=g.Pc,$k=g.Zc,Rk=g._c,Dk=g.$c,vb=g.bd,kb=g.cd,Eb=g.dd,Ab=g.ed,ml=g.fd,Mb=g.gd,Fk=g.hd,Tb=g.kd,Bk=g.ld,Uk=g.md,jk=g.nd,Sb=g.od,Gk=g.pd,qk=g.qd,Ob=g.rd,xe=g.sd,hl=g.td,Wk=g.ud,pe=g.vd,Zu=g.wd,fe=g.xd,Vk=g.yd,Ib=g.zd,Hk=g.Ad,Xk=g.Bd,Kk=g.Cd,Cb=g.Dd,Yk=g.Ed,Qk=g.Fd,Jk=g.Gd,Zk=g.Hd,eE=g.Id,tE=g.Jd,rE=g.Kd,sE=g.Ld,nE=g.Md,oE=g.Nd,aE=g.Od,iE=g.Pd,lE=g.Qd,cE=g.Rd,uE=g.Td,pE=g.Ud,fE=g.Vd,dE=g.Wd,_E=g.Yd,mE=g.Zd,hE=g._d,gE=g.$d,wE=g.ae,xE=g.oe,yE=g.pe,bE=g.qe,vE=g.re,kE=g.se,EE=g.te,AE=g.ue,ME=g.ve,TE=g.we,SE=g.xe,OE=g.ye,IE=g.Ye,CE=g.Ze,PE=g._e,zE=g.$e,_=v,br}var d,h=Et();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(v,M)=>{g(u(v,M))})}):n?u(new WebAssembly.Instance(_,Et()),_):(B??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",p):p+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",Zt.url).href,d=await(async function(g){var v=B;if(!f&&!O(v))try{var M=fetch(v,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(M,g)}catch(P){T(`wasm streaming compile failed: ${P}`),T("falling back to ArrayBuffer instantiation")}return(async function(P,L){try{var G=await(async function(Z){if(!f)try{var Ie=await a(Z);return new Uint8Array(Ie)}catch{}if(Z==B&&f)Z=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";Z=i(Z)}return Z})(P);return await WebAssembly.instantiate(G,L)}catch(Z){T(`failed to asynchronously prepare wasm: ${Z}`),ce(Z)}})(v,g)})(h),u(d.instance,d.module))}class ct{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var At=u=>{u.terminate(),u.onmessage=()=>{}},Fe=[],Se=0,rt=null,nr=u=>{qr.length==0&&(Lv(),zv(qr[0]));var d=qr.pop();if(!d)return 6;fl.push(d),Ms[u.Nc]=d,d.Nc=u.Nc;var h={Oc:"run",ge:u.fe,Wc:u.Wc,Nc:u.Nc};return d.postMessage(h,u.Yc),0},Oe=0,Be=(u,d,...h)=>{var g,v=16*h.length,M=fe(),P=Zu(v),L=P>>>3;for(g of h)typeof g=="bigint"?((b(),z)[L++>>>0]=1n,(b(),z)[L++>>>0]=g):((b(),z)[L++>>>0]=0n,(b(),Y)[L++>>>0]=g);return u=Uk(u,0,v,P,d),pe(M),u};function Tn(u){if(n)return Be(0,1,u);if(m=u,!(0{if(m=u,n)throw pl(u),"unwind";Tn(u)},qr=[],fl=[],Iv=[],Ms={},Cv=u=>{var d=u.Nc;delete Ms[d],qr.push(u),fl.splice(fl.indexOf(u),1),u.Nc=0,jk(d)};function Pv(){Iv.forEach(u=>u())}var zv=u=>new Promise(d=>{u.onmessage=v=>{var M=v.data;if(v=M.Oc,M.Vc&&M.Vc!=Ju()){var P=Ms[M.Vc];P?P.postMessage(M,M.Yc):T(`Internal error! Worker sent a message "${v}" to target pthread ${M.Vc}, but that thread no longer exists!`)}else v==="checkMailbox"?Vu():v==="spawnThread"?nr(M):v==="cleanupThread"?Mt(()=>{Cv(Ms[M.he])}):v==="loaded"?(u.loaded=!0,d(u)):M.target==="setimmediate"?u.postMessage(M):v==="uncaughtException"?u.onerror(M.error):v==="callHandler"?e[M.be](...M.args):v&&T(`worker sent an unknown command ${v}`)},u.onerror=v=>{throw T(`worker sent an error! ${v.filename}:${v.lineno}: ${v.message}`),v};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);u.postMessage({Oc:"load",ce:g,ie:Wr,je:_})});function Lv(){var u=new Worker((()=>{let d=URL;return Zt.url>"file:"&&Zt.url<"file;"?new d("ort.webgpu.bundle.min.mjs",Zt.url):new URL(Zt.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});qr.push(u)}var Wr,DT=(u,d)=>{Oe=0,u=Cb(u,d),0-9007199254740992>u||9007199254740992>>=0);return(b(),U)[d.Qc+12>>>0]==0&&(Nv(d,!0),Wu--),$v(d,!1),qu.push(d),Xk(u)}var On=0,BT=()=>{xe(0,0);var u=qu.pop();Vk(u.Xc),On=0};function Nv(u,d){d=d?1:0,(b(),U)[u.Qc+12>>>0]=d}function $v(u,d){d=d?1:0,(b(),U)[u.Qc+13>>>0]=d}class ab{constructor(d){this.Xc=d,this.Qc=d-24}}var ib=u=>{var d=On;if(!d)return hl(0),0;var h=new ab(d);(b(),C)[h.Qc+16>>>2>>>0]=d;var g=(b(),C)[h.Qc+4>>>2>>>0];if(!g)return hl(0),d;for(var v of u){if(v===0||v===g)break;if(Hk(v,g,h.Qc+16))return hl(v),d}return hl(g),d};function UT(){return ib([])}function jT(u){return ib([u>>>0])}function GT(u,d,h,g){return ib([u>>>0,d>>>0,h>>>0,g>>>0])}var qT=()=>{var u=qu.pop();u||ce("no exception to throw");var d=u.Xc;throw(b(),U)[u.Qc+13>>>0]==0&&(qu.push(u),$v(u,!0),Nv(u,!1),Wu++),Ib(d),On=d};function WT(u,d,h){var g=new ab(u>>>=0);throw d>>>=0,h>>>=0,(b(),C)[g.Qc+16>>>2>>>0]=0,(b(),C)[g.Qc+4>>>2>>>0]=d,(b(),C)[g.Qc+8>>>2>>>0]=h,Ib(u),Wu++,On=u}var VT=()=>Wu;function Rv(u,d,h,g){return n?Be(2,1,u,d,h,g):Dv(u,d,h,g)}function Dv(u,d,h,g){if(u>>>=0,d>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var v=[];return n&&v.length===0?Rv(u,d,h,g):(u={fe:h,Nc:u,Wc:g,Yc:v},n?(u.Oc="spawnThread",postMessage(u,v),0):nr(u))}function HT(u){throw On||=u>>>0,On}var Fv=globalThis.TextDecoder&&new TextDecoder,Bv=(u,d,h,g)=>{if(h=d+h,g)return h;for(;u[d]&&!(d>=h);)++d;return d},Uv=(u,d=0,h,g)=>{if(16<(h=Bv(u,d>>>=0,h,g))-d&&u.buffer&&Fv)return Fv.decode(u.buffer instanceof ArrayBuffer?u.subarray(d,h):u.slice(d,h));for(g="";d(v=(240&v)==224?(15&v)<<12|M<<6|P:(7&v)<<18|M<<12|P<<6|63&u[d++])?g+=String.fromCharCode(v):(v-=65536,g+=String.fromCharCode(55296|v>>10,56320|1023&v))}}else g+=String.fromCharCode(v)}return g},In=(u,d,h)=>(u>>>=0)?Uv((b(),X),u,d,h):"";function jv(u,d,h){return n?Be(3,1,u,d,h):0}function Gv(u,d){if(n)return Be(4,1,u,d)}function qv(u,d){if(n)return Be(5,1,u,d)}function Wv(u,d,h){if(n)return Be(6,1,u,d,h)}function Vv(u,d,h){return n?Be(7,1,u,d,h):0}function Hv(u,d){if(n)return Be(8,1,u,d)}function Xv(u,d,h){if(n)return Be(9,1,u,d,h)}function Kv(u,d,h,g){if(n)return Be(10,1,u,d,h,g)}function Yv(u,d,h,g){if(n)return Be(11,1,u,d,h,g)}function Qv(u,d,h,g){if(n)return Be(12,1,u,d,h,g)}function Jv(u){if(n)return Be(13,1,u)}function Zv(u,d){if(n)return Be(14,1,u,d)}function ek(u,d,h){if(n)return Be(15,1,u,d,h)}var XT=()=>ce(""),or=u=>{u>>>=0;for(var d="";;){var h=(b(),X)[u++>>>0];if(!h)return d;d+=String.fromCharCode(h)}},lb={},cb={},KT={},Cn=class extends Error{constructor(u){super(u),this.name="BindingError"}};function hr(u,d,h={}){return(function(g,v,M={}){var P=v.name;if(!g)throw new Cn(`type "${P}" must have a positive integer typeid pointer`);if(cb.hasOwnProperty(g)){if(M.de)return;throw new Cn(`Cannot register type '${P}' twice`)}cb[g]=v,delete KT[g],lb.hasOwnProperty(g)&&(v=lb[g],delete lb[g],v.forEach(L=>L()))})(u,d,h)}var tk=(u,d,h)=>{switch(d){case 1:return h?g=>(b(),U)[g>>>0]:g=>(b(),X)[g>>>0];case 2:return h?g=>(b(),K)[g>>>1>>>0]:g=>(b(),J)[g>>>1>>>0];case 4:return h?g=>(b(),R)[g>>>2>>>0]:g=>(b(),C)[g>>>2>>>0];case 8:return h?g=>(b(),z)[g>>>3>>>0]:g=>(b(),$)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${u}`)}};function YT(u,d,h,g,v){u>>>=0,h>>>=0,d=or(d>>>0);let M=P=>P;if(g=g===0n){let P=8*h;M=L=>BigInt.asUintN(P,L),v=M(v)}hr(u,{name:d,Mc:M,Sc:(P,L)=>(typeof L=="number"&&(L=BigInt(L)),L),Rc:tk(d,h,!g),Tc:null})}function QT(u,d,h,g){hr(u>>>=0,{name:d=or(d>>>0),Mc:function(v){return!!v},Sc:function(v,M){return M?h:g},Rc:function(v){return this.Mc((b(),X)[v>>>0])},Tc:null})}var rk=[],Ts=[0,1,,1,null,1,!0,1,!1,1];function ub(u){9<(u>>>=0)&&--Ts[u+1]==0&&(Ts[u]=void 0,rk.push(u))}var Dt=u=>{if(!u)throw new Cn(`Cannot use deleted val. handle = ${u}`);return Ts[u]},Vt=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=rk.pop()||Ts.length;return Ts[d]=u,Ts[d+1]=1,d}};function pb(u){return this.Mc((b(),C)[u>>>2>>>0])}var JT={name:"emscripten::val",Mc:u=>{var d=Dt(u);return ub(u),d},Sc:(u,d)=>Vt(d),Rc:pb,Tc:null};function ZT(u){return hr(u>>>0,JT)}var eS=(u,d)=>{switch(d){case 4:return function(h){return this.Mc((b(),ne)[h>>>2>>>0])};case 8:return function(h){return this.Mc((b(),Y)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${u}`)}};function tS(u,d,h){h>>>=0,hr(u>>>=0,{name:d=or(d>>>0),Mc:g=>g,Sc:(g,v)=>v,Rc:eS(d,h),Tc:null})}function rS(u,d,h,g,v){u>>>=0,h>>>=0,d=or(d>>>0);let M=L=>L;if(g===0){var P=32-8*h;M=L=>L<

>>P,v=M(v)}hr(u,{name:d,Mc:M,Sc:(L,G)=>G,Rc:tk(d,h,g!==0),Tc:null})}function sS(u,d,h){function g(M){var P=(b(),C)[M>>>2>>>0];return M=(b(),C)[M+4>>>2>>>0],new v((b(),U).buffer,M,P)}var v=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];hr(u>>>=0,{name:h=or(h>>>0),Mc:g,Rc:g},{de:!0})}var gr=(u,d,h)=>{var g=(b(),X);if(d>>>=0,0=P){if(d>=h)break;g[d++>>>0]=P}else if(2047>=P){if(d+1>=h)break;g[d++>>>0]=192|P>>6,g[d++>>>0]=128|63&P}else if(65535>=P){if(d+2>=h)break;g[d++>>>0]=224|P>>12,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P}else{if(d+3>=h)break;g[d++>>>0]=240|P>>18,g[d++>>>0]=128|P>>12&63,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P,M++}}g[d>>>0]=0,u=d-v}else u=0;return u},wr=u=>{for(var d=0,h=0;h=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++h):d+=3}return d};function nS(u,d){hr(u>>>=0,{name:d=or(d>>>0),Mc(h){var g=(b(),C)[h>>>2>>>0];return g=In(h+4,g,!0),Ht(h),g},Sc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var v=typeof g=="string";if(!(v||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Cn("Cannot pass non-string to std::string");var M=v?wr(g):g.length,P=zn(4+M+1),L=P+4;return(b(),C)[P>>>2>>>0]=M,v?gr(g,L,M+1):(b(),X).set(g,L>>>0),h!==null&&h.push(Ht,P),P},Rc:pb,Tc(h){Ht(h)}})}var sk=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,oS=(u,d,h)=>{if(u>>>=1,16<(d=Bv((b(),J),u,d/2,h))-u&&sk)return sk.decode((b(),J).slice(u,d));for(h="";u>>0];h+=String.fromCharCode(g)}return h},aS=(u,d,h)=>{if(h??=2147483647,2>h)return 0;var g=d;h=(h-=2)<2*u.length?h/2:u.length;for(var v=0;v>>1>>>0]=M,d+=2}return(b(),K)[d>>>1>>>0]=0,d-g},iS=u=>2*u.length,lS=(u,d,h)=>{var g="";u>>>=2;for(var v=0;!(v>=d/4);v++){var M=(b(),C)[u+v>>>0];if(!M&&!h)break;g+=String.fromCodePoint(M)}return g},cS=(u,d,h)=>{if(d>>>=0,h??=2147483647,4>h)return 0;var g=d;h=g+h-4;for(var v=0;v>>2>>>0]=M,(d+=4)+4>h)break}return(b(),R)[d>>>2>>>0]=0,d-g},uS=u=>{for(var d=0,h=0;h>>=0,d>>>=0,h=or(h>>>=0),d===2)var g=oS,v=aS,M=iS;else g=lS,v=cS,M=uS;hr(u,{name:h,Mc:P=>{var L=(b(),C)[P>>>2>>>0];return L=g(P+4,L*d,!0),Ht(P),L},Sc:(P,L)=>{if(typeof L!="string")throw new Cn(`Cannot pass non-string to C++ string type ${h}`);var G=M(L),Z=zn(4+G+d);return(b(),C)[Z>>>2>>>0]=G/d,v(L,Z+4,G+d),P!==null&&P.push(Ht,Z),Z},Rc:pb,Tc(P){Ht(P)}})}function fS(u,d){hr(u>>>=0,{ee:!0,name:d=or(d>>>0),Mc:()=>{},Sc:()=>{}})}function dS(u){Tb(u>>>0,!s,1,!r,131072,!1),Pv()}var Mt=u=>{if(!I)try{if(u(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function fb(u){u>>>=0,_S||(Atomics.waitAsync((b(),R),u>>>2,u).value.then(Vu),u+=128,Atomics.store((b(),R),u>>>2,1))}var Vu=()=>Mt(()=>{var u=Ju();u&&(fb(u),qk())});function mS(u,d){(u>>>=0)==d>>>0?setTimeout(Vu):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=Ms[u])&&u.postMessage({Oc:"checkMailbox"})}var db=[];function hS(u,d,h,g,v){for(d>>>=0,v>>>=0,db.length=0,h=v>>>3,g=v+g>>>3;h>>0]?(b(),z)[h++>>>0]:(b(),Y)[h++>>>0],db.push(M)}return(d?Pb[d]:eI[u])(...db)}var gS=()=>{Oe=0};function wS(u){u>>>=0,n?postMessage({Oc:"cleanupThread",he:u}):Cv(Ms[u])}function xS(u){}var Hu=u=>{try{u()}catch(d){ce(d)}};function yS(u){var d=(...h)=>{Xu.push(u);try{return u(...h)}finally{I||(Xu.pop(),ar&&Vr===1&&Xu.length===0&&(Vr=0,Oe+=1,Hu(CE),typeof Fibers<"u"&&Fibers.Be()))}};return ak.set(u,d),d}var Vr=0,ar=null,nk=0,Xu=[],_b=new Map,ok=new Map,ak=new Map,bS=0,mb=null,vS=[],ik=u=>(function(d){if(!I){if(Vr===0){var h=!1,g=!1;d((v=0)=>{if(!I&&(nk=v,h=!0,g)){Vr=2,Hu(()=>PE(ar)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),v=!1;try{var M=(function(){var G=(b(),R)[ar+8>>>2>>>0];return G=ok.get(G),G=ak.get(G),--Oe,G()})()}catch(G){M=G,v=!0}var P=!1;if(!ar){var L=mb;L&&(mb=null,(v?L.reject:L.resolve)(M),P=!0)}if(v&&!P)throw M}}),g=!0,h||(Vr=1,ar=(function(){var v=zn(65548),M=v+12;if((b(),C)[v>>>2>>>0]=M,(b(),C)[v+4>>>2>>>0]=M+65536,M=Xu[0],!_b.has(M)){var P=bS++;_b.set(M,P),ok.set(P,M)}return M=_b.get(M),(b(),R)[v+8>>>2>>>0]=M,v})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Hu(()=>IE(ar)))}else Vr===2?(Vr=0,Hu(zE),Ht(ar),ar=null,vS.forEach(Mt)):ce(`invalid state: ${Vr}`);return nk}})(d=>{u().then(d)});function kS(u){return u>>>=0,ik(async()=>{var d=await Dt(u);return Vt(d)})}var hb=[],ES=u=>{var d=hb.length;return hb.push(u),d},AS=(u,d)=>{for(var h=Array(u),g=0;g>>2>>>0],P=cb[M];if(P===void 0)throw u=`parameter ${g}`,M=Mk(M),d=or(M),Ht(M),new Cn(`${u} has unknown type ${d}`);h[v]=P}return h},MS=(u,d,h)=>{var g=[];return u=u(g,h),g.length&&((b(),C)[d>>>2>>>0]=Vt(g)),u},TS={},Ku=u=>{var d=TS[u];return d===void 0?or(u):d};function SS(u,d,h){var[g,...v]=AS(u,d>>>0);d=g.Sc.bind(g);var M=v.map(G=>G.Rc.bind(G));u--;var P={toValue:Dt};switch(u=M.map((G,Z)=>{var Ie=`argFromPtr${Z}`;return P[Ie]=G,`${Ie}(args${Z?"+"+8*Z:""})`}),h){case 0:var L="toValue(handle)";break;case 2:L="new (toValue(handle))";break;case 3:L="";break;case 1:P.getStringOrSymbol=Ku,L="toValue(handle)[getStringOrSymbol(methodName)]"}return L+=`(${u})`,g.ee||(P.toReturnWire=d,P.emval_returnValue=MS,L=`return emval_returnValue(toReturnWire, destructorsRef, ${L})`),L=`return function (handle, methodName, destructorsRef, args) { ++`,Qz="{%- ",Jz=" -%}";function Zz(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function eL(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Yt(t.body,0,r).replace(/\n$/,"")}function xt(...t){return Qz+t.join(" ")+Jz}function Yt(t,e,r){return t.map(s=>tL(s,e,r)).join(at)}function tL(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Yt(t.body,e,r);case"If":return rL(t,e,r);case"For":return sL(t,e,r);case"Set":return nL(t,e,r);case"Macro":return oL(t,e,r);case"Break":return s+xt("break");case"Continue":return s+xt("continue");case"CallStatement":return aL(t,e,r);case"FilterStatement":return iL(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function rL(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+xt("if",ke(n[0].test))+at+Yt(n[0].body,e+1,r);for(let i=1;i0&&(a+=at+s+xt("else")+at+Yt(o.alternate,e+1,r)),a+=at+s+xt("endif"),a}function sL(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+xt("for",ke(t.loopvar),"in",n)+at+Yt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=at+s+xt("else")+at+Yt(t.defaultBlock,e+1,r)),o+=at+s+xt("endfor"),o}function nL(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+xt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+at+Yt(t.body,e+1,r)+at+s+xt("endset")}function oL(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+xt("macro",`${t.name.value}(${n})`)+at+Yt(t.body,e+1,r)+at+s+xt("endmacro")}function aL(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+xt(`call${n}`,o)+at;return a+=Yt(t.body,e+1,r)+at,a+=s+xt("endcall"),a}function iL(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+xt("filter",n)+at;return o+=Yt(t.body,e+1,r)+at,o+=s+xt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=Zz(r),n=ke(r.left,s),o=ke(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var xA=class{parsed;constructor(t){let e=gz(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Uz(e)}render(t){let e=new Ps;if(Kz(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new Yz(e).run(this.parsed).value}format(t){return eL(this.parsed,t?.indent||" ")}};var Ls=vr(require("fs"),1),lL={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"},Hr=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=Ls.default.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=Ls.default.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=Ls.default.createReadStream(e);this.body=new ReadableStream({start(n){s.on("data",o=>n.enqueue(o)),s.on("end",()=>n.close()),s.on("error",o=>n.error(o))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",lL[e]??"application/octet-stream")}clone(){let e=new t(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await Ls.default.promises.readFile(this.filePath)).buffer}async blob(){let e=await Ls.default.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await Ls.default.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};var Dn=vr(require("fs"),1),vl=vr(require("path"),1);var Xr=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(ie.IS_CRYPTO_AVAILABLE){let i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;let r=this._mt,s=(i,l)=>Math.imul(i,l)>>>0,n=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))n.push(i&4294967295);n.length||n.push(0),r[0]=19650218;for(let i=1;i<624;++i)r[i]=s(1812433253,r[i-1]^r[i-1]>>>30)+i>>>0;let o=1,a=0;for(let i=Math.max(624,n.length);i>0;--i,++o,++a)o>=624&&(r[0]=r[623],o=1),a>=n.length&&(a=0),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1664525))+n[a]+a>>>0;for(let i=623;i>0;--i,++o)o>=624&&(r[0]=r[623],o=1),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1566083941))-o>>>0;r[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let s=0;s<624;++s){let n=e[s]&2147483648|e[(s+1)%624]&2147483647;e[s]=(e[(s+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let r=e[this._idx++];return r^=r>>>11,r^=r<<7&2636928640,r^=r<<15&4022730752,r^=r>>>18,r>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,r=1){let s=this._gauss_next;if(this._gauss_next=null,s===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+s*r}shuffle(e){for(let r=e.length-1;r>0;--r){let s=32-Math.clz32(r+1),n=this._int32()>>>32-s;for(;n>r;)n=this._int32()>>>32-s;let o=e[r];e[r]=e[n],e[n]=o}}choices(e,r){return e[yA(this._random_fn,r)]}};function yA(t,e){let r=0;for(let n=0;nyA(Kr.random,t);var cL=new Xr,Fn=class{constructor(e){this.path=e}async match(e){let r=vl.default.join(this.path,e),s=new Hr(r);if(s.exists)return s}async put(e,r,s=void 0){let n=vl.default.join(this.path,e),o=ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=cL._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),p=0;await Dn.default.promises.mkdir(vl.default.dirname(n),{recursive:!0});let f=Dn.default.createWriteStream(i),_=r.body.getReader();for(;;){let{done:m,value:w}=await _.read();if(m)break;await new Promise((k,A)=>{f.write(w,E=>{if(E){A(E);return}k()})}),p+=w.length;let x=c?p/c*100:0;s?.({progress:x,loaded:p,total:c})}await new Promise((m,w)=>{f.close(x=>x?w(x):m())}),await Dn.default.promises.rename(i,n)}catch(l){try{await Dn.default.promises.unlink(i)}catch{}throw l}}async delete(e){let r=vl.default.join(this.path,e);try{return await Dn.default.promises.unlink(r),!0}catch{return!1}}};var vA={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"},up=100,kA=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;var Gb={};function kl(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function Yr(t,e=null,r=null){let s;try{s=new URL(t)}catch{return!1}return!(e&&!e.includes(s.protocol)||r&&!r.includes(s.hostname))}function EA(t){return!(!kA.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function AA(t,e,r){if(!r)return null;let s=vA[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function MA(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&ee.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:p}=await i.read();if(c)return;let f=a+p.length;if(f>n){n=f;let m=new Uint8Array(n);m.set(o),o=m}o.set(p,a),a=f;let _=a/n*100;return e({progress:_,loaded:a,total:n}),l()}return await l(),o}function qb(t){return Yr(t,["blob:"])}function Wb(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof Gb<"u"&&Gb.url)e=Gb.url;else return t;return new URL(t,e).href}var SA="SHA-256",uL="experimental_transformers-hash-cache",TA=t=>({algorithm:SA,value:t}),El=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(uL),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let r=await this._getFileHash(e);if(r)try{let[s]=await navigator.crossOriginStorage.requestFileHandles([TA(r)]),n=await s.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,r)=>{let s=await this._getFileHash(e);if(s){let n=await r.blob();await this._storeBlobInCOS(n,s)}else this._processAndStore(e,r.body)};_storeBlobInCOS=async(e,r)=>{let[s]=await navigator.crossOriginStorage.requestFileHandles([TA(r)],{create:!0}),n=await s.createWritable();await n.write(e),await n.close()};_processAndStore=async(e,r)=>{try{let s=[];for await(let a of r)s.push(a);let n=new Blob(s),o=await this._getBlobHash(n);await this._storeBlobInCOS(n,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let r=await this._getHashCache(),s=await r.match(e);if(s)return s.text();let n=await this._getLfsFileHash(e);return n?(await r.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let r=e.replace("/resolve/","/raw/");try{let n=(await fetch(r).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{let r=await e.arrayBuffer(),s=await crypto.subtle.digest(SA,r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function Jt(t=null){let e=null;if(_e.useCustomCache){if(!_e.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!_e.customCache.match||!_e.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=_e.customCache}if(!e&&_e.experimental_useCrossOriginStorage&&El.isAvailable()&&(e=new El),!e&&_e.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(_e.cacheKey)}catch(r){ee.warn("An error occurred while opening the browser cache:",r)}}if(!e&&_e.useFSCache){if(!ie.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new Fn(t??_e.cacheDir)}return e}async function OA(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var pp=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let r=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,r),r}put(e,r){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,r),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};var pL=100,Vb=new pp(pL);function fp(t,e){let r=Vb.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(Vb.delete(t),Promise.reject(n)));return Vb.put(t,s),s}async function fL(t){if(!Yr(t,["http:","https:"]))return null;let e=Hb(t);return e.set("Range","bytes=0-0"),_e.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function Ot(t,e,r={}){let s=JSON.stringify([t,e,r?.revision,r?.cache_dir,r?.local_files_only]);return fp(s,()=>dL(t,e,r))}async function dL(t,e,r){let s=await Jt(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=Jr(t,e,r,s),l=await Zr(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),p=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:p||void 0,fromCache:!0}}if(_e.allowLocalModels&&!Yr(n,["http:","https:"]))try{let p=await Qr(n);if(typeof p!="string"&&p.status!==404){let f=p.headers.get("content-length"),_=p.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:_||void 0,fromCache:!1}}}catch{}if(_e.allowRemoteModels&&!r.local_files_only&&i)try{let c=await fL(o);if(c&&c.status>=200&&c.status<300){let p,f=c.headers.get("content-type");if(c.status===206){let _=c.headers.get("content-range");if(_){let m=_.match(/bytes \d+-\d+\/(\d+)/);m&&(p=parseInt(m[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(p===void 0){let _=c.headers.get("content-length");p=_?parseInt(_,10):void 0}return{exists:!0,size:p,contentType:f||void 0,fromCache:!1}}}catch(c){ee.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function Qr(t){return _e.useFS&&!Yr(t,["http:","https:","blob:"])?new Hr(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):_e.fetch(t,{headers:Hb(t)})}function Hb(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=_e.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),Yr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function Jr(t,e,r={},s=null){let n=r.revision??"main",o=kl(t,e),a=EA(t),i=a?kl(_e.localModelPath,o):o,l=kl(_e.remoteHost,_e.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof Fn?n==="main"?o:kl(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function Zr(t,e,r){if(t)return await OA(t,e,r)}async function _L(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o){if(typeof n!="string"){let i=new Headers(n.headers);i.set("content-length",o.byteLength.toString()),await r.put(s,new Response(o,{headers:i})).catch(l=>{ee.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=a.progress_callback?l=>lr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function mL(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:p}=Jr(t,e,s,o),f,_=!1,m;m=await Zr(o,i,c);let w=m!==void 0;if(w)f=c;else{if(_e.allowLocalModels)if(Yr(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!_e.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{m=await Qr(i),f=i}catch(E){ee.warn(`Unable to load from local path "${i}": "${E}"`)}if(m===void 0||typeof m!="string"&&m.status===404){if(s.local_files_only||!_e.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!p)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(m=await Qr(l),m.status!==200)return AA(m.status,l,r);f=c}_=o&&typeof Response<"u"&&m instanceof Response&&m.status===200}lr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(ie.IS_NODE_ENV&&n)){let A;if(typeof m!="string")if(!s.progress_callback)A=new Uint8Array(await m.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test((navigator.userAgent||"")))A=new Uint8Array(await m.arrayBuffer()),lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A.length,total:A.length});else{let E,S=m.headers.get("content-length");if(S)E=parseInt(S,10);else try{let T=await Ot(t,e,s);T.size&&(E=T.size)}catch{}A=await MA(m,T=>{lr(s.progress_callback,{status:"progress",name:t,file:e,...T})},E)}x=A}if(_&&f&&typeof m!="string"&&await _L(t,e,o,f,m,x,s),ie.IS_NODE_ENV&&n&&s.progress_callback&&typeof m!="string"){let A=parseInt(m.headers.get("content-length"),10)||0;lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A,total:A})}if(lr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!ie.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(m instanceof Hr)return m.filePath;let k=await o?.match(f);if(k instanceof Hr)return k.filePath;if(k instanceof Response)return new Uint8Array(await k.arrayBuffer());if(typeof k=="string")return k;throw new Error("Unable to get model file path or buffer.")}var dp=new Map;async function Al(t,e,r=!0,s={},n=!1){if(!_e.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!_e.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}lr(s.progress_callback,{status:"initiate",name:t,file:e});let o=`${t}::${e}`,a=dp.get(o);if(!a){let i=await Jt(s?.cache_dir);a=mL(t,e,r,s,n,i).then(l=>(dp.delete(o),l),l=>{throw dp.delete(o),l}),dp.set(o,a)}return await a}async function Ml(t,e,r=!0,s={}){let n=await Al(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function nt(t,e,r=!0,s={}){let n=await Ml(t,e,r,s);return n===null?{}:JSON.parse(n)}function CA(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,p=new t.constructor(n*o*e),f=r*s,_=n*o;for(let m=0;m=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i=0;--c)l+=p%e[c]*o[c],p=Math.floor(p/e[c]);a[l]=t[i]}return[a,s]}function Pe(t){let e=ze(t)[0],r=t.map(o=>Math.exp(o-e)),s=r.reduce((o,a)=>o+a,0);return r.map(o=>o/s)}function hp(t){let e=ze(t)[0],r=0;for(let o=0;oo-e-s)}function Kb(t,e){let r=0;for(let s=0;se+r*r,0))}function Tl(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;se&&(e=t[s],r=s);return[e,r]}function LA(t){return t>0&&(t&t-1)===0}var _p=class{constructor(e){if(this.size=e|0,this.size<=1||!LA(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;ss;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>2;for(l=0;l>>1,a>>>1)}else for(l=0,c=0;l>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>1,w=m>>>1,x=w>>>1;for(l=0;l>>1;for(let m=2;m<_;m+=2)e[n-m]=e[m],e[n-m+1]=-e[m+1]}_singleRealTransform2(e,r,s,n,o){let a=e[n],i=e[n+o];r[s]=a+i,r[s+1]=0,r[s+2]=a-i,r[s+3]=0}_singleRealTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,c=e[n],p=e[n+o],f=e[n+i],_=e[n+l],m=c+f,w=c-f,x=p+_,k=a*(p-_);r[s]=m+x,r[s+1]=0,r[s+2]=w,r[s+3]=-k,r[s+4]=m-x,r[s+5]=0,r[s+6]=w,r[s+7]=k}},Xb=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let i=-2*Math.PI/e,l=Math.cos(i),c=Math.sin(i);for(let p=0;p>1;++p){let f=(p+1-e)**2/2,_=Math.sqrt(l**2+c**2)**f,m=f*Math.atan2(c,l),w=2*p;o[w]=_*Math.cos(m),o[w+1]=_*Math.sin(m),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new _p(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,p=this._a;if(s)for(let f=0;f>1,w=r[m];n[f]=w*c[f],n[_]=w*c[_]}else for(let f=0;f=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function Ns(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function $A(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function RA(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let p=1;p0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var DA=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l>10,_=l&1023;if(f===31)c=p|2139095040|_<<13;else if(f===0)if(_===0)c=p;else{let m=113;for(;(_&1024)===0;)_<<=1,--m;_&=-1025,c=p|m<<23|_<<13}else c=p|f+112<<23|_<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;oE1,TRACE:()=>Ap,TRACE_EVENT_BEGIN:()=>ns,TRACE_EVENT_END:()=>os,TRACE_FUNC_BEGIN:()=>Us,TRACE_FUNC_END:()=>js,Tensor:()=>er,default:()=>qL,env:()=>Qe,registerBackend:()=>Bs});var Zt={};var v1=Object.defineProperty,hL=Object.getOwnPropertyDescriptor,gL=Object.getOwnPropertyNames,wL=Object.prototype.hasOwnProperty,xL=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),ve=(t,e)=>()=>(t&&(e=t(t=0)),e),Nl=(t,e)=>{for(var r in e)v1(t,r,{get:e[r],enumerable:!0})},yL=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of gL(e))!wL.call(t,n)&&n!==r&&v1(t,n,{get:()=>e[n],enumerable:!(s=hL(e,n))||s.enumerable});return t},Ep=t=>yL(v1({},"__esModule",{value:!0}),t),Sl,es,Bs,FA,f2,d2=ve(()=>{"use strict";Sl=new Map,es=[],Bs=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=Sl.get(t);if(s===void 0)Sl.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=es.indexOf(t);n!==-1&&es.splice(n,1);for(let o=0;o{let e=Sl.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(s){return r||(e.error=`${s}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},f2=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?es:r,n,o=[],a=new Set;for(let l of s){let c=await FA(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),bL=ve(()=>{"use strict";d2()}),_2,vL=ve(()=>{"use strict";_2="1.24.0-dev.20251116-b39e144322"}),Yb,dt,m2=ve(()=>{"use strict";vL(),Yb="warning",dt={wasm:{},webgl:{},webgpu:{},versions:{common:_2},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);Yb=t}},get logLevel(){return Yb}},Object.defineProperty(dt,"logLevel",{enumerable:!0})}),Qe,kL=ve(()=>{"use strict";m2(),Qe=dt}),h2,g2,EL=ve(()=>{"use strict";h2=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let p=o*n,f=0,_=p,m=p*2,w=-1;a==="RGBA"?(f=0,_=p,m=p*2,w=p*3):a==="RGB"?(f=0,_=p,m=p*2):a==="RBG"&&(f=0,m=p,_=p*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let _=4,m=0,w=1,x=2,k=3,A=0,E=f,S=f*2,T=-1;i==="RGBA"?(A=0,E=f,S=f*2,T=f*3):i==="RGB"?(A=0,E=f,S=f*2):i==="RBG"&&(A=0,S=f,E=f*2),s=r.createImageData(n,o);for(let I=0;I{"use strict";k1(),gp=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,_=0,m=1,w=2,x=3,k=0,A=c,E=c*2,S=-1;i==="RGB"&&(f=3,_=0,m=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(k=0,E=c,A=c*2):l==="BGR"&&(E=0,A=c,k=c*2);for(let T=0;T{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let _=t.height,m=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(_=e.resizedHeight,m=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=m}else i.tensorFormat="RGBA",i.height=_,i.width=m;f.drawImage(t,0,0),a=f.getImageData(0,0,m,_).data}else throw new Error("Can not access image data")}else if(s){let p,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(p=e.resizedHeight,f=e.resizedWidth):(p=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=p,i.width=f,e!==void 0){let _=l();_.width=f,_.height=p;let m=c(_);if(m!=null)m.putImageData(t,0,0),a=m.getImageData(0,0,f,p).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let _=t.height,m=t.width;return f.drawImage(t,0,0,m,_),a=f.getImageData(0,0,m,_).data,i.height=_,i.width=m,gp(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,f)=>{let _=l(),m=c(_);if(!t||!m)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{_.width=w.width,_.height=w.height,m.drawImage(w,0,0,_.width,_.height);let x=m.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,p(gp(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return gp(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},x2=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Nt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},y2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Nt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},b2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Nt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},v2=(t,e,r)=>new Nt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),Ds,zl,Qb,k2,ML=ve(()=>{"use strict";Ds=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),zl=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Qb=!1,k2=()=>{if(!Qb){Qb=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Ds.set("int64",BigInt64Array),zl.set(BigInt64Array,"int64")),e&&(Ds.set("uint64",BigUint64Array),zl.set(BigUint64Array,"uint64")),s?(Ds.set("float16",r),zl.set(r,"float16")):Ds.set("float16",Uint16Array)}}}),E2,A2,TL=ve(()=>{"use strict";k1(),E2=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new Nt(t.type,t.data,e);case"cpu-pinned":return new Nt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Nt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Nt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Nt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Nt,k1=ve(()=>{"use strict";EL(),AL(),ML(),TL(),Nt=class{constructor(t,e,r){k2();let s,n;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,n=t.dims,t.location){case"cpu-pinned":{let a=Ds.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,i;if(typeof t=="string")if(s=t,i=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=Ds.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")s="string",a=t;else if(l==="boolean")s="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(t);else{let l=zl.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=l,a=t}if(i===void 0)i=[a.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=a,this.dataLocation="cpu"}let o=E2(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(t,e){return w2(t,e)}static fromTexture(t,e){return x2(t,e)}static fromGpuBuffer(t,e){return y2(t,e)}static fromMLTensor(t,e){return b2(t,e)}static fromPinnedBuffer(t,e,r){return v2(t,e,r)}toDataURL(t){return h2(this,t)}toImageData(t){return g2(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return A2(this,t)}}}),er,M2=ve(()=>{"use strict";k1(),er=Nt}),Ap,Jb,Us,js,ns,os,T2=ve(()=>{"use strict";m2(),Ap=(t,e)=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeStamp(`${t}::ORT::${e}`)},Jb=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||Jb("BEGIN",t)},js=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||Jb("END",t)},ns=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.time(`ORT::${t}`)},os=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeEnd(`ORT::${t}`)}}),S2,SL=ve(()=>{"use strict";d2(),M2(),T2(),S2=class O2{constructor(e){this.handler=e}async run(e,r,s){Us(),ns("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof er||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof er)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(p.indexOf(f)!==-1){let _=r[f];(_===null||_ instanceof er)&&(c=!0,a=!1,n[f]=_)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let p=i[c];p instanceof er?l[c]=p:l[c]=new er(p.type,p.data,p.dims)}return os("InferenceSession.run"),js(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){Us(),ns("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let p=e,f=0,_=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(_=e.byteLength-f,typeof s=="number"){if(_=s,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||f+_>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,f,_)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await f2(a),c=await i.createInferenceSessionHandler(o,l);return os("InferenceSession.create"),js(),new O2(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),E1,OL=ve(()=>{"use strict";SL(),E1=S2}),IL=ve(()=>{"use strict"}),CL=ve(()=>{"use strict"}),PL=ve(()=>{"use strict"}),zL=ve(()=>{"use strict"}),I2={};Nl(I2,{InferenceSession:()=>E1,TRACE:()=>Ap,TRACE_EVENT_BEGIN:()=>ns,TRACE_EVENT_END:()=>os,TRACE_FUNC_BEGIN:()=>Us,TRACE_FUNC_END:()=>js,Tensor:()=>er,env:()=>Qe,registerBackend:()=>Bs});var Gs=ve(()=>{"use strict";bL(),kL(),OL(),M2(),IL(),CL(),T2(),PL(),zL()}),A1=ve(()=>{"use strict"}),C2={};Nl(C2,{default:()=>P2});var Zb,e1,P2,LL=ve(()=>{"use strict";H2(),qs(),M1(),Zb="ort-wasm-proxy-worker",e1=globalThis.self?.name===Zb,e1&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":T1(r.wasm).then(()=>{P1(r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})})},s=>{postMessage({type:e,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;z1(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=Sp(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;L1(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":N1(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;$1(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},D1([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":R1(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),P2=e1?null:t=>new Worker(t??zt,{type:"module",name:Zb})}),z2={};Nl(z2,{default:()=>L2});async function BA(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(u,d)=>{u.startsWith("./")&&(u=u.substring(2)),(e.Uc||(e.Uc=new Map)).set(u,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let o=()=>{let u=d=>(...h)=>{let g=ar;return h=d(...h),ar!=g?new Promise((v,M)=>{mb={resolve:v,reject:M}}):h};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=u(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(u,d)=>{throw d},c=Zt.url,p="";if(r||s){try{p=new URL(".",c).href}catch{}s&&(i=u=>{var d=new XMLHttpRequest;return d.open("GET",u,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async u=>{if(O(u))return new Promise((h,g)=>{var v=new XMLHttpRequest;v.open("GET",u,!0),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?h(v.response):g(v.status)},v.onerror=g,v.send(null)});var d=await fetch(u,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,_,m,w,x,k,A=console.log.bind(console),E=console.error.bind(console),S=A,T=E,I=!1,O=u=>u.startsWith("file://");function b(){Wr.buffer!=U.buffer&&le()}if(n){let u=function(d){try{var h=d.data,g=h.Oc;if(g==="load"){let v=[];self.onmessage=M=>v.push(M),k=()=>{postMessage({Oc:"loaded"});for(let M of v)u(M);self.onmessage=u};for(let M of h.ce)e[M]&&!e[M].proxy||(e[M]=(...P)=>{postMessage({Oc:"callHandler",be:M,args:P})},M=="print"&&(S=e[M]),M=="printErr"&&(T=e[M]));Wr=h.ie,le(),_=h.je,qe(),ep()}else if(g==="run"){(function(v){var M=(b(),C)[v+52>>>2>>>0];v=(b(),C)[v+56>>>2>>>0],Wk(M,M-v),pe(M)})(h.Nc),Tb(h.Nc,0,0,1,0,0),Pv(),fb(h.Nc),j||(Tk(),j=!0);try{DT(h.ge,h.Wc)}catch(v){if(v!="unwind")throw v}}else h.target!=="setimmediate"&&(g==="checkMailbox"?j&&Vu():g&&(T(`worker: received unknown command ${g}`),T(h)))}catch(v){throw Bk(),v}};var F=u,j=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=u}var U,X,K,J,R,C,ne,Y,z,$,B,Q=!1;function le(){var u=Wr.buffer;e.HEAP8=U=new Int8Array(u),K=new Int16Array(u),e.HEAPU8=X=new Uint8Array(u),J=new Uint16Array(u),e.HEAP32=R=new Int32Array(u),e.HEAPU32=C=new Uint32Array(u),ne=new Float32Array(u),Y=new Float64Array(u),z=new BigInt64Array(u),$=new BigUint64Array(u)}function Ge(){Q=!0,n?k():br._b()}function ce(u){throw T(u="Aborted("+u+")"),I=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),x?.(u),u}function Et(){return{a:{f:FT,J:BT,k:UT,p:jT,l:GT,sa:qT,b:WT,ca:VT,Ja:Dv,q:HT,da:jv,Za:Gv,Fa:qv,Ha:Wv,_a:Vv,Xa:Hv,Qa:Xv,Wa:Kv,oa:Yv,Ga:Qv,Xb:Jv,Ya:Zv,Yb:ek,db:XT,Da:YT,Sb:QT,Qb:ZT,Ca:tS,M:rS,I:sS,Rb:nS,ja:pS,Tb:fS,Ta:dS,Vb:mS,Ka:hS,Ob:gS,ka:wS,Sa:fb,ab:xS,U:kS,n:SS,c:ub,rb:OS,w:IS,L:CS,z:PS,j:zS,o:lk,sb:LS,G:NS,T:$S,h:RS,u:DS,m:FS,i:BS,Na:US,Oa:jS,Pa:GS,La:fk,Ma:dk,Pb:_k,eb:WS,cb:XS,Y:KS,qb:YS,la:QS,bb:VS,fb:JS,$a:ZS,Wb:eO,N:qS,gb:tO,X:rO,Ub:sO,nb:fO,C:dO,ra:_O,qa:mO,pb:hO,W:gO,v:wO,mb:xO,lb:yO,kb:bO,ob:vO,jb:kO,ib:EO,hb:AO,Ua:yk,Va:bk,Ia:Sn,V:vk,na:kk,Ra:Ek,ma:Ak,Cb:NI,xa:OI,Db:LI,ya:SI,F:gI,e:nI,s:rI,x:tI,B:_I,Fb:AI,ba:EI,D:iI,za:MI,$:II,ga:kI,Gb:vI,Hb:bI,Ba:wI,Aa:yI,Ib:xI,wa:zI,aa:TI,d:sI,A:aI,r:oI,Bb:$I,t:cI,y:mI,H:lI,E:uI,K:hI,R:CI,ia:dI,_:PI,Jb:fI,Kb:pI,g:TO,a:Wr,Nb:Tn,Eb:SO,ha:OO,O:IO,pa:CO,Lb:PO,ta:zO,Q:LO,yb:NO,zb:$O,ua:RO,ea:DO,P:FO,Ea:BO,va:UO,Z:jO,wb:GO,Zb:qO,S:WO,Ab:VO,tb:HO,ub:KO,vb:YO,fa:QO,xb:JO,Mb:ZO}}}async function qe(){function u(g,v){var M=br=g.exports;g={};for(let[P,L]of Object.entries(M))typeof L=="function"?(M=yS(L),g[P]=M):g[P]=L;return br=g,br=(function(){var P=br,L=Z=>Ie=>Z(Ie)>>>0,G=Z=>()=>Z()>>>0;return(P=Object.assign({},P)).$b=L(P.$b),P.Cc=G(P.Cc),P.Ec=L(P.Ec),P.rd=(Z=>(Ie,$e)=>Z(Ie,$e)>>>0)(P.rd),P.wd=L(P.wd),P.xd=G(P.xd),P.Bd=L(P.Bd),P})(),Iv.push(br.id),Mk=(g=br).$b,Tk=g.ac,e._OrtInit=g.bc,e._OrtGetLastError=g.cc,e._OrtCreateSessionOptions=g.dc,e._OrtAppendExecutionProvider=g.ec,e._OrtAddFreeDimensionOverride=g.fc,e._OrtAddSessionConfigEntry=g.gc,e._OrtReleaseSessionOptions=g.hc,e._OrtCreateSession=g.ic,e._OrtReleaseSession=g.jc,e._OrtGetInputOutputCount=g.kc,e._OrtGetInputOutputMetadata=g.lc,e._OrtFree=g.mc,e._OrtCreateTensor=g.nc,e._OrtGetTensorData=g.oc,e._OrtReleaseTensor=g.pc,e._OrtCreateRunOptions=g.qc,e._OrtAddRunConfigEntry=g.rc,e._OrtReleaseRunOptions=g.sc,e._OrtCreateBinding=g.tc,e._OrtBindInput=g.uc,e._OrtBindOutput=g.vc,e._OrtClearBoundOutputs=g.wc,e._OrtReleaseBinding=g.xc,e._OrtRunWithBinding=g.yc,e._OrtRun=g.zc,e._OrtEndProfiling=g.Ac,bb=e._OrtGetWebGpuDevice=g.Bc,Ju=g.Cc,Ht=e._free=g.Dc,zn=e._malloc=g.Ec,Sk=e._wgpuBufferRelease=g.Fc,Ok=e._wgpuCreateInstance=g.Gc,Ik=g.Hc,Ck=g.Ic,Pk=g.Jc,zk=g.Kc,Lk=g.Lc,Nk=g.Pc,$k=g.Zc,Rk=g._c,Dk=g.$c,vb=g.bd,kb=g.cd,Eb=g.dd,Ab=g.ed,ml=g.fd,Mb=g.gd,Fk=g.hd,Tb=g.kd,Bk=g.ld,Uk=g.md,jk=g.nd,Sb=g.od,Gk=g.pd,qk=g.qd,Ob=g.rd,xe=g.sd,hl=g.td,Wk=g.ud,pe=g.vd,Zu=g.wd,fe=g.xd,Vk=g.yd,Ib=g.zd,Hk=g.Ad,Xk=g.Bd,Kk=g.Cd,Cb=g.Dd,Yk=g.Ed,Qk=g.Fd,Jk=g.Gd,Zk=g.Hd,eE=g.Id,tE=g.Jd,rE=g.Kd,sE=g.Ld,nE=g.Md,oE=g.Nd,aE=g.Od,iE=g.Pd,lE=g.Qd,cE=g.Rd,uE=g.Td,pE=g.Ud,fE=g.Vd,dE=g.Wd,_E=g.Yd,mE=g.Zd,hE=g._d,gE=g.$d,wE=g.ae,xE=g.oe,yE=g.pe,bE=g.qe,vE=g.re,kE=g.se,EE=g.te,AE=g.ue,ME=g.ve,TE=g.we,SE=g.xe,OE=g.ye,IE=g.Ye,CE=g.Ze,PE=g._e,zE=g.$e,_=v,br}var d,h=Et();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(v,M)=>{g(u(v,M))})}):n?u(new WebAssembly.Instance(_,Et()),_):(B??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",p):p+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",Zt.url).href,d=await(async function(g){var v=B;if(!f&&!O(v))try{var M=fetch(v,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(M,g)}catch(P){T(`wasm streaming compile failed: ${P}`),T("falling back to ArrayBuffer instantiation")}return(async function(P,L){try{var G=await(async function(Z){if(!f)try{var Ie=await a(Z);return new Uint8Array(Ie)}catch{}if(Z==B&&f)Z=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";Z=i(Z)}return Z})(P);return await WebAssembly.instantiate(G,L)}catch(Z){T(`failed to asynchronously prepare wasm: ${Z}`),ce(Z)}})(v,g)})(h),u(d.instance,d.module))}class ct{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var At=u=>{u.terminate(),u.onmessage=()=>{}},Fe=[],Se=0,rt=null,nr=u=>{qr.length==0&&(Lv(),zv(qr[0]));var d=qr.pop();if(!d)return 6;fl.push(d),Ms[u.Nc]=d,d.Nc=u.Nc;var h={Oc:"run",ge:u.fe,Wc:u.Wc,Nc:u.Nc};return d.postMessage(h,u.Yc),0},Oe=0,Be=(u,d,...h)=>{var g,v=16*h.length,M=fe(),P=Zu(v),L=P>>>3;for(g of h)typeof g=="bigint"?((b(),z)[L++>>>0]=1n,(b(),z)[L++>>>0]=g):((b(),z)[L++>>>0]=0n,(b(),Y)[L++>>>0]=g);return u=Uk(u,0,v,P,d),pe(M),u};function Tn(u){if(n)return Be(0,1,u);if(m=u,!(0{if(m=u,n)throw pl(u),"unwind";Tn(u)},qr=[],fl=[],Iv=[],Ms={},Cv=u=>{var d=u.Nc;delete Ms[d],qr.push(u),fl.splice(fl.indexOf(u),1),u.Nc=0,jk(d)};function Pv(){Iv.forEach(u=>u())}var zv=u=>new Promise(d=>{u.onmessage=v=>{var M=v.data;if(v=M.Oc,M.Vc&&M.Vc!=Ju()){var P=Ms[M.Vc];P?P.postMessage(M,M.Yc):T(`Internal error! Worker sent a message "${v}" to target pthread ${M.Vc}, but that thread no longer exists!`)}else v==="checkMailbox"?Vu():v==="spawnThread"?nr(M):v==="cleanupThread"?Mt(()=>{Cv(Ms[M.he])}):v==="loaded"?(u.loaded=!0,d(u)):M.target==="setimmediate"?u.postMessage(M):v==="uncaughtException"?u.onerror(M.error):v==="callHandler"?e[M.be](...M.args):v&&T(`worker sent an unknown command ${v}`)},u.onerror=v=>{throw T(`worker sent an error! ${v.filename}:${v.lineno}: ${v.message}`),v};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);u.postMessage({Oc:"load",ce:g,ie:Wr,je:_})});function Lv(){var u=new Worker((()=>{let d=URL;return Zt.url>"file:"&&Zt.url<"file;"?new d("ort.webgpu.bundle.min.mjs",Zt.url):new URL(Zt.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});qr.push(u)}var Wr,DT=(u,d)=>{Oe=0,u=Cb(u,d),0-9007199254740992>u||9007199254740992>>=0);return(b(),U)[d.Qc+12>>>0]==0&&(Nv(d,!0),Wu--),$v(d,!1),qu.push(d),Xk(u)}var On=0,BT=()=>{xe(0,0);var u=qu.pop();Vk(u.Xc),On=0};function Nv(u,d){d=d?1:0,(b(),U)[u.Qc+12>>>0]=d}function $v(u,d){d=d?1:0,(b(),U)[u.Qc+13>>>0]=d}class ab{constructor(d){this.Xc=d,this.Qc=d-24}}var ib=u=>{var d=On;if(!d)return hl(0),0;var h=new ab(d);(b(),C)[h.Qc+16>>>2>>>0]=d;var g=(b(),C)[h.Qc+4>>>2>>>0];if(!g)return hl(0),d;for(var v of u){if(v===0||v===g)break;if(Hk(v,g,h.Qc+16))return hl(v),d}return hl(g),d};function UT(){return ib([])}function jT(u){return ib([u>>>0])}function GT(u,d,h,g){return ib([u>>>0,d>>>0,h>>>0,g>>>0])}var qT=()=>{var u=qu.pop();u||ce("no exception to throw");var d=u.Xc;throw(b(),U)[u.Qc+13>>>0]==0&&(qu.push(u),$v(u,!0),Nv(u,!1),Wu++),Ib(d),On=d};function WT(u,d,h){var g=new ab(u>>>=0);throw d>>>=0,h>>>=0,(b(),C)[g.Qc+16>>>2>>>0]=0,(b(),C)[g.Qc+4>>>2>>>0]=d,(b(),C)[g.Qc+8>>>2>>>0]=h,Ib(u),Wu++,On=u}var VT=()=>Wu;function Rv(u,d,h,g){return n?Be(2,1,u,d,h,g):Dv(u,d,h,g)}function Dv(u,d,h,g){if(u>>>=0,d>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var v=[];return n&&v.length===0?Rv(u,d,h,g):(u={fe:h,Nc:u,Wc:g,Yc:v},n?(u.Oc="spawnThread",postMessage(u,v),0):nr(u))}function HT(u){throw On||=u>>>0,On}var Fv=globalThis.TextDecoder&&new TextDecoder,Bv=(u,d,h,g)=>{if(h=d+h,g)return h;for(;u[d]&&!(d>=h);)++d;return d},Uv=(u,d=0,h,g)=>{if(16<(h=Bv(u,d>>>=0,h,g))-d&&u.buffer&&Fv)return Fv.decode(u.buffer instanceof ArrayBuffer?u.subarray(d,h):u.slice(d,h));for(g="";d(v=(240&v)==224?(15&v)<<12|M<<6|P:(7&v)<<18|M<<12|P<<6|63&u[d++])?g+=String.fromCharCode(v):(v-=65536,g+=String.fromCharCode(55296|v>>10,56320|1023&v))}}else g+=String.fromCharCode(v)}return g},In=(u,d,h)=>(u>>>=0)?Uv((b(),X),u,d,h):"";function jv(u,d,h){return n?Be(3,1,u,d,h):0}function Gv(u,d){if(n)return Be(4,1,u,d)}function qv(u,d){if(n)return Be(5,1,u,d)}function Wv(u,d,h){if(n)return Be(6,1,u,d,h)}function Vv(u,d,h){return n?Be(7,1,u,d,h):0}function Hv(u,d){if(n)return Be(8,1,u,d)}function Xv(u,d,h){if(n)return Be(9,1,u,d,h)}function Kv(u,d,h,g){if(n)return Be(10,1,u,d,h,g)}function Yv(u,d,h,g){if(n)return Be(11,1,u,d,h,g)}function Qv(u,d,h,g){if(n)return Be(12,1,u,d,h,g)}function Jv(u){if(n)return Be(13,1,u)}function Zv(u,d){if(n)return Be(14,1,u,d)}function ek(u,d,h){if(n)return Be(15,1,u,d,h)}var XT=()=>ce(""),or=u=>{u>>>=0;for(var d="";;){var h=(b(),X)[u++>>>0];if(!h)return d;d+=String.fromCharCode(h)}},lb={},cb={},KT={},Cn=class extends Error{constructor(u){super(u),this.name="BindingError"}};function hr(u,d,h={}){return(function(g,v,M={}){var P=v.name;if(!g)throw new Cn(`type "${P}" must have a positive integer typeid pointer`);if(cb.hasOwnProperty(g)){if(M.de)return;throw new Cn(`Cannot register type '${P}' twice`)}cb[g]=v,delete KT[g],lb.hasOwnProperty(g)&&(v=lb[g],delete lb[g],v.forEach(L=>L()))})(u,d,h)}var tk=(u,d,h)=>{switch(d){case 1:return h?g=>(b(),U)[g>>>0]:g=>(b(),X)[g>>>0];case 2:return h?g=>(b(),K)[g>>>1>>>0]:g=>(b(),J)[g>>>1>>>0];case 4:return h?g=>(b(),R)[g>>>2>>>0]:g=>(b(),C)[g>>>2>>>0];case 8:return h?g=>(b(),z)[g>>>3>>>0]:g=>(b(),$)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${u}`)}};function YT(u,d,h,g,v){u>>>=0,h>>>=0,d=or(d>>>0);let M=P=>P;if(g=g===0n){let P=8*h;M=L=>BigInt.asUintN(P,L),v=M(v)}hr(u,{name:d,Mc:M,Sc:(P,L)=>(typeof L=="number"&&(L=BigInt(L)),L),Rc:tk(d,h,!g),Tc:null})}function QT(u,d,h,g){hr(u>>>=0,{name:d=or(d>>>0),Mc:function(v){return!!v},Sc:function(v,M){return M?h:g},Rc:function(v){return this.Mc((b(),X)[v>>>0])},Tc:null})}var rk=[],Ts=[0,1,,1,null,1,!0,1,!1,1];function ub(u){9<(u>>>=0)&&--Ts[u+1]==0&&(Ts[u]=void 0,rk.push(u))}var Dt=u=>{if(!u)throw new Cn(`Cannot use deleted val. handle = ${u}`);return Ts[u]},Vt=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=rk.pop()||Ts.length;return Ts[d]=u,Ts[d+1]=1,d}};function pb(u){return this.Mc((b(),C)[u>>>2>>>0])}var JT={name:"emscripten::val",Mc:u=>{var d=Dt(u);return ub(u),d},Sc:(u,d)=>Vt(d),Rc:pb,Tc:null};function ZT(u){return hr(u>>>0,JT)}var eS=(u,d)=>{switch(d){case 4:return function(h){return this.Mc((b(),ne)[h>>>2>>>0])};case 8:return function(h){return this.Mc((b(),Y)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${u}`)}};function tS(u,d,h){h>>>=0,hr(u>>>=0,{name:d=or(d>>>0),Mc:g=>g,Sc:(g,v)=>v,Rc:eS(d,h),Tc:null})}function rS(u,d,h,g,v){u>>>=0,h>>>=0,d=or(d>>>0);let M=L=>L;if(g===0){var P=32-8*h;M=L=>L<

>>P,v=M(v)}hr(u,{name:d,Mc:M,Sc:(L,G)=>G,Rc:tk(d,h,g!==0),Tc:null})}function sS(u,d,h){function g(M){var P=(b(),C)[M>>>2>>>0];return M=(b(),C)[M+4>>>2>>>0],new v((b(),U).buffer,M,P)}var v=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];hr(u>>>=0,{name:h=or(h>>>0),Mc:g,Rc:g},{de:!0})}var gr=(u,d,h)=>{var g=(b(),X);if(d>>>=0,0=P){if(d>=h)break;g[d++>>>0]=P}else if(2047>=P){if(d+1>=h)break;g[d++>>>0]=192|P>>6,g[d++>>>0]=128|63&P}else if(65535>=P){if(d+2>=h)break;g[d++>>>0]=224|P>>12,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P}else{if(d+3>=h)break;g[d++>>>0]=240|P>>18,g[d++>>>0]=128|P>>12&63,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P,M++}}g[d>>>0]=0,u=d-v}else u=0;return u},wr=u=>{for(var d=0,h=0;h=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++h):d+=3}return d};function nS(u,d){hr(u>>>=0,{name:d=or(d>>>0),Mc(h){var g=(b(),C)[h>>>2>>>0];return g=In(h+4,g,!0),Ht(h),g},Sc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var v=typeof g=="string";if(!(v||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Cn("Cannot pass non-string to std::string");var M=v?wr(g):g.length,P=zn(4+M+1),L=P+4;return(b(),C)[P>>>2>>>0]=M,v?gr(g,L,M+1):(b(),X).set(g,L>>>0),h!==null&&h.push(Ht,P),P},Rc:pb,Tc(h){Ht(h)}})}var sk=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,oS=(u,d,h)=>{if(u>>>=1,16<(d=Bv((b(),J),u,d/2,h))-u&&sk)return sk.decode((b(),J).slice(u,d));for(h="";u>>0];h+=String.fromCharCode(g)}return h},aS=(u,d,h)=>{if(h??=2147483647,2>h)return 0;var g=d;h=(h-=2)<2*u.length?h/2:u.length;for(var v=0;v>>1>>>0]=M,d+=2}return(b(),K)[d>>>1>>>0]=0,d-g},iS=u=>2*u.length,lS=(u,d,h)=>{var g="";u>>>=2;for(var v=0;!(v>=d/4);v++){var M=(b(),C)[u+v>>>0];if(!M&&!h)break;g+=String.fromCodePoint(M)}return g},cS=(u,d,h)=>{if(d>>>=0,h??=2147483647,4>h)return 0;var g=d;h=g+h-4;for(var v=0;v>>2>>>0]=M,(d+=4)+4>h)break}return(b(),R)[d>>>2>>>0]=0,d-g},uS=u=>{for(var d=0,h=0;h>>=0,d>>>=0,h=or(h>>>=0),d===2)var g=oS,v=aS,M=iS;else g=lS,v=cS,M=uS;hr(u,{name:h,Mc:P=>{var L=(b(),C)[P>>>2>>>0];return L=g(P+4,L*d,!0),Ht(P),L},Sc:(P,L)=>{if(typeof L!="string")throw new Cn(`Cannot pass non-string to C++ string type ${h}`);var G=M(L),Z=zn(4+G+d);return(b(),C)[Z>>>2>>>0]=G/d,v(L,Z+4,G+d),P!==null&&P.push(Ht,Z),Z},Rc:pb,Tc(P){Ht(P)}})}function fS(u,d){hr(u>>>=0,{ee:!0,name:d=or(d>>>0),Mc:()=>{},Sc:()=>{}})}function dS(u){Tb(u>>>0,!s,1,!r,131072,!1),Pv()}var Mt=u=>{if(!I)try{if(u(),!(0Number(((navigator.userAgent||"").match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function fb(u){u>>>=0,_S||(Atomics.waitAsync((b(),R),u>>>2,u).value.then(Vu),u+=128,Atomics.store((b(),R),u>>>2,1))}var Vu=()=>Mt(()=>{var u=Ju();u&&(fb(u),qk())});function mS(u,d){(u>>>=0)==d>>>0?setTimeout(Vu):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=Ms[u])&&u.postMessage({Oc:"checkMailbox"})}var db=[];function hS(u,d,h,g,v){for(d>>>=0,v>>>=0,db.length=0,h=v>>>3,g=v+g>>>3;h>>0]?(b(),z)[h++>>>0]:(b(),Y)[h++>>>0],db.push(M)}return(d?Pb[d]:eI[u])(...db)}var gS=()=>{Oe=0};function wS(u){u>>>=0,n?postMessage({Oc:"cleanupThread",he:u}):Cv(Ms[u])}function xS(u){}var Hu=u=>{try{u()}catch(d){ce(d)}};function yS(u){var d=(...h)=>{Xu.push(u);try{return u(...h)}finally{I||(Xu.pop(),ar&&Vr===1&&Xu.length===0&&(Vr=0,Oe+=1,Hu(CE),typeof Fibers<"u"&&Fibers.Be()))}};return ak.set(u,d),d}var Vr=0,ar=null,nk=0,Xu=[],_b=new Map,ok=new Map,ak=new Map,bS=0,mb=null,vS=[],ik=u=>(function(d){if(!I){if(Vr===0){var h=!1,g=!1;d((v=0)=>{if(!I&&(nk=v,h=!0,g)){Vr=2,Hu(()=>PE(ar)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),v=!1;try{var M=(function(){var G=(b(),R)[ar+8>>>2>>>0];return G=ok.get(G),G=ak.get(G),--Oe,G()})()}catch(G){M=G,v=!0}var P=!1;if(!ar){var L=mb;L&&(mb=null,(v?L.reject:L.resolve)(M),P=!0)}if(v&&!P)throw M}}),g=!0,h||(Vr=1,ar=(function(){var v=zn(65548),M=v+12;if((b(),C)[v>>>2>>>0]=M,(b(),C)[v+4>>>2>>>0]=M+65536,M=Xu[0],!_b.has(M)){var P=bS++;_b.set(M,P),ok.set(P,M)}return M=_b.get(M),(b(),R)[v+8>>>2>>>0]=M,v})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Hu(()=>IE(ar)))}else Vr===2?(Vr=0,Hu(zE),Ht(ar),ar=null,vS.forEach(Mt)):ce(`invalid state: ${Vr}`);return nk}})(d=>{u().then(d)});function kS(u){return u>>>=0,ik(async()=>{var d=await Dt(u);return Vt(d)})}var hb=[],ES=u=>{var d=hb.length;return hb.push(u),d},AS=(u,d)=>{for(var h=Array(u),g=0;g>>2>>>0],P=cb[M];if(P===void 0)throw u=`parameter ${g}`,M=Mk(M),d=or(M),Ht(M),new Cn(`${u} has unknown type ${d}`);h[v]=P}return h},MS=(u,d,h)=>{var g=[];return u=u(g,h),g.length&&((b(),C)[d>>>2>>>0]=Vt(g)),u},TS={},Ku=u=>{var d=TS[u];return d===void 0?or(u):d};function SS(u,d,h){var[g,...v]=AS(u,d>>>0);d=g.Sc.bind(g);var M=v.map(G=>G.Rc.bind(G));u--;var P={toValue:Dt};switch(u=M.map((G,Z)=>{var Ie=`argFromPtr${Z}`;return P[Ie]=G,`${Ie}(args${Z?"+"+8*Z:""})`}),h){case 0:var L="toValue(handle)";break;case 2:L="new (toValue(handle))";break;case 3:L="";break;case 1:P.getStringOrSymbol=Ku,L="toValue(handle)[getStringOrSymbol(methodName)]"}return L+=`(${u})`,g.ee||(P.toReturnWire=d,P.emval_returnValue=MS,L=`return emval_returnValue(toReturnWire, destructorsRef, ${L})`),L=`return function (handle, methodName, destructorsRef, args) { + ${L} + }`,h=new Function(Object.keys(P),L)(...Object.values(P)),L=`methodCaller<(${v.map(G=>G.name)}) => ${g.name}>`,ES(Object.defineProperty(h,"name",{value:L}))}function OS(u,d){return d>>>=0,(u=Dt(u>>>0))==Dt(d)}function IS(u){return(u>>>=0)?(u=Ku(u),Vt(globalThis[u])):Vt(globalThis)}function CS(u){return u=Ku(u>>>0),Vt(e[u])}function PS(u,d){return d>>>=0,u=Dt(u>>>0),d=Dt(d),Vt(u[d])}function zS(u){9<(u>>>=0)&&(Ts[u+1]+=1)}function lk(u,d,h,g,v){return hb[u>>>0](d>>>0,h>>>0,g>>>0,v>>>0)}function LS(u,d,h,g,v){return lk(u>>>0,d>>>0,h>>>0,g>>>0,v>>>0)}function NS(){return Vt([])}function $S(u){u=Dt(u>>>0);for(var d=Array(u.length),h=0;h>>0))}function DS(){return Vt({})}function FS(u){for(var d=Dt(u>>>=0);d.length;){var h=d.pop();d.pop()(h)}ub(u)}function BS(u,d,h){d>>>=0,h>>>=0,u=Dt(u>>>0),d=Dt(d),h=Dt(h),u[d]=h}function US(u,d){u=ht(u),d>>>=0,u=new Date(1e3*u),(b(),R)[d>>>2>>>0]=u.getUTCSeconds(),(b(),R)[d+4>>>2>>>0]=u.getUTCMinutes(),(b(),R)[d+8>>>2>>>0]=u.getUTCHours(),(b(),R)[d+12>>>2>>>0]=u.getUTCDate(),(b(),R)[d+16>>>2>>>0]=u.getUTCMonth(),(b(),R)[d+20>>>2>>>0]=u.getUTCFullYear()-1900,(b(),R)[d+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(b(),R)[d+28>>>2>>>0]=u}var ck=u=>u%4==0&&(u%100!=0||u%400==0),uk=[0,31,60,91,121,152,182,213,244,274,305,335],pk=[0,31,59,90,120,151,181,212,243,273,304,334];function jS(u,d){u=ht(u),d>>>=0,u=new Date(1e3*u),(b(),R)[d>>>2>>>0]=u.getSeconds(),(b(),R)[d+4>>>2>>>0]=u.getMinutes(),(b(),R)[d+8>>>2>>>0]=u.getHours(),(b(),R)[d+12>>>2>>>0]=u.getDate(),(b(),R)[d+16>>>2>>>0]=u.getMonth(),(b(),R)[d+20>>>2>>>0]=u.getFullYear()-1900,(b(),R)[d+24>>>2>>>0]=u.getDay();var h=(ck(u.getFullYear())?uk:pk)[u.getMonth()]+u.getDate()-1|0;(b(),R)[d+28>>>2>>>0]=h,(b(),R)[d+36>>>2>>>0]=-60*u.getTimezoneOffset(),h=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(h!=g&&u.getTimezoneOffset()==Math.min(g,h)),(b(),R)[d+32>>>2>>>0]=u}function GS(u){u>>>=0;var d=new Date((b(),R)[u+20>>>2>>>0]+1900,(b(),R)[u+16>>>2>>>0],(b(),R)[u+12>>>2>>>0],(b(),R)[u+8>>>2>>>0],(b(),R)[u+4>>>2>>>0],(b(),R)[u>>>2>>>0],0),h=(b(),R)[u+32>>>2>>>0],g=d.getTimezoneOffset(),v=new Date(d.getFullYear(),6,1).getTimezoneOffset(),M=new Date(d.getFullYear(),0,1).getTimezoneOffset(),P=Math.min(M,v);return 0>h?(b(),R)[u+32>>>2>>>0]=+(v!=M&&P==g):0>>2>>>0]=d.getDay(),h=(ck(d.getFullYear())?uk:pk)[d.getMonth()]+d.getDate()-1|0,(b(),R)[u+28>>>2>>>0]=h,(b(),R)[u>>>2>>>0]=d.getSeconds(),(b(),R)[u+4>>>2>>>0]=d.getMinutes(),(b(),R)[u+8>>>2>>>0]=d.getHours(),(b(),R)[u+12>>>2>>>0]=d.getDate(),(b(),R)[u+16>>>2>>>0]=d.getMonth(),(b(),R)[u+20>>>2>>>0]=d.getYear(),u=d.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function fk(u,d,h,g,v,M,P){return n?Be(16,1,u,d,h,g,v,M,P):-52}function dk(u,d,h,g,v,M){if(n)return Be(17,1,u,d,h,g,v,M)}var dl={},qS=()=>performance.timeOrigin+performance.now();function _k(u,d){if(n)return Be(18,1,u,d);if(dl[u]&&(clearTimeout(dl[u].id),delete dl[u]),!d)return 0;var h=setTimeout(()=>{delete dl[u],Mt(()=>Gk(u,performance.timeOrigin+performance.now()))},d);return dl[u]={id:h,Ae:d},0}function WS(u,d,h,g){u>>>=0,d>>>=0,h>>>=0,g>>>=0;var v=new Date().getFullYear(),M=new Date(v,0,1).getTimezoneOffset();v=new Date(v,6,1).getTimezoneOffset();var P=Math.max(M,v);(b(),C)[u>>>2>>>0]=60*P,(b(),R)[d>>>2>>>0]=+(M!=v),u=(d=L=>{var G=Math.abs(L);return`UTC${0<=L?"-":"+"}${String(Math.floor(G/60)).padStart(2,"0")}${String(G%60).padStart(2,"0")}`})(M),d=d(v),vDate.now(),HS=1;function XS(u,d,h){if(h>>>=0,!(0<=u&&3>=u))return 28;if(u===0)u=Date.now();else{if(!HS)return 52;u=performance.timeOrigin+performance.now()}return u=Math.round(1e6*u),(b(),z)[h>>>3>>>0]=BigInt(u),0}var gb=[],mk=(u,d)=>{gb.length=0;for(var h;h=(b(),X)[u++>>>0];){var g=h!=105;d+=(g&=h!=112)&&d%8?4:0,gb.push(h==112?(b(),C)[d>>>2>>>0]:h==106?(b(),z)[d>>>3>>>0]:h==105?(b(),R)[d>>>2>>>0]:(b(),Y)[d>>>3>>>0]),d+=g?8:4}return gb};function KS(u,d,h){return u>>>=0,d=mk(d>>>0,h>>>0),Pb[u](...d)}function YS(u,d,h){return u>>>=0,d=mk(d>>>0,h>>>0),Pb[u](...d)}var QS=()=>{};function JS(u,d){return T(In(u>>>0,d>>>0))}var ZS=()=>{throw Oe+=1,"unwind"};function eO(){return 4294901760}var tO=()=>1,rO=()=>navigator.hardwareConcurrency;function sO(u){u>>>=0;var d=(b(),X).length;if(u<=d||4294901760=h;h*=2){var g=d*(1+.2/h);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-Wr.buffer.byteLength+65535)/65536|0;try{Wr.grow(g),le();var v=1;break e}catch{}v=void 0}if(v)return!0}return!1}var ir=u=>{var d=wr(u)+1,h=Zu(d);return gr(u,h,d),h},wb=(u,d)=>{(b(),C)[u>>>2>>>0]=d;var h=(b(),C)[u>>>2>>>0];(b(),C)[u+4>>>2>>>0]=(d-h)/4294967296},_l=u=>(b(),C)[u>>>2>>>0]+4294967296*(b(),R)[u+4>>>2>>>0],gt=[],nO=(u,d)=>{gt[u>>>0]=d},xr=[],Yu=[],Pn=(u,d)=>{Yu[u]=new Promise(h=>d.finally(()=>h(u)))},oe=u=>{if(u)return gt[u>>>0]},oO=(u,d)=>{for(u=(b(),C)[u>>>2>>>0];u;u=(b(),C)[u>>>2>>>0])d[(b(),R)[u+4>>>2>>>0]](u)},Qu=(u,d,h)=>{(b(),C)[u>>>2>>>0]=d,(b(),C)[u+4>>>2>>>0]=h},hk=u=>{var d=(b(),C)[u>>>2>>>0];return u=(b(),C)[u+4>>>2>>>0],In(d,u)},yr=u=>{var d=(b(),C)[u>>>2>>>0];return u=(b(),C)[u+4>>>2>>>0],d?In(d,u):u===0?"":void 0},aO=u=>{var d=yr(u+4),h=(h=(b(),C)[u+12>>>2>>>0])?oe(h):"auto";if(u+=16){var g=oe((b(),C)[u+4>>>2>>>0]),v=(b(),C)[u+16>>>2>>>0],M=(b(),C)[u+20>>>2>>>0];if(v){for(var P={},L=0;L>>3>>>0]}v=P}else v=void 0;u={module:g,constants:v,entryPoint:yr(u+8)}}else u=void 0;return{label:d,layout:h,compute:u}},gk=(u,d)=>{function h(g,v){g=u[g],(b(),C)[d+v>>>2>>>0]=g}h("maxTextureDimension1D",4),h("maxTextureDimension2D",8),h("maxTextureDimension3D",12),h("maxTextureArrayLayers",16),h("maxBindGroups",20),h("maxBindGroupsPlusVertexBuffers",24),h("maxBindingsPerBindGroup",28),h("maxDynamicUniformBuffersPerPipelineLayout",32),h("maxDynamicStorageBuffersPerPipelineLayout",36),h("maxSampledTexturesPerShaderStage",40),h("maxSamplersPerShaderStage",44),h("maxStorageBuffersPerShaderStage",48),h("maxStorageTexturesPerShaderStage",52),h("maxUniformBuffersPerShaderStage",56),h("minUniformBufferOffsetAlignment",80),h("minStorageBufferOffsetAlignment",84),wb(d+64,u.maxUniformBufferBindingSize),wb(d+72,u.maxStorageBufferBindingSize),h("maxVertexBuffers",88),wb(d+96,u.maxBufferSize),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),u.ze!==void 0&&h("maxImmediateSize",148)},iO=[,"validation","out-of-memory","internal"],lO=[,"compatibility","core"],wk={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},cO=[,"low-power","high-performance"],uO=[,"occlusion","timestamp"],pO={undefined:1,unknown:1,destroyed:2};function fO(u,d,h,g,v,M){d=ht(d),h=ht(h),g>>>=0,v>>>=0,M>>>=0;var P=oe(u>>>0);if(u={},M){var L=(b(),C)[M+12>>>2>>>0];if(L){var G=(b(),C)[M+16>>>2>>>0];u.requiredFeatures=Array.from((b(),C).subarray(G>>>2>>>0,G+4*L>>>2>>>0),ae=>wk[ae])}var Z=(b(),C)[M+20>>>2>>>0];if(Z){let ae=function(Tt,pt,Ss=!1){pt=Z+pt,(pt=(b(),C)[pt>>>2>>>0])==4294967295||Ss&&pt==0||(Ue[Tt]=pt)},ut=function(Tt,pt){pt=Z+pt;var Ss=(b(),C)[pt>>>2>>>0],RI=(b(),C)[pt+4>>>2>>>0];Ss==4294967295&&RI==4294967295||(Ue[Tt]=_l(pt))};var Ie=ae,$e=ut,Ue={};ae("maxTextureDimension1D",4),ae("maxTextureDimension2D",8),ae("maxTextureDimension3D",12),ae("maxTextureArrayLayers",16),ae("maxBindGroups",20),ae("maxBindGroupsPlusVertexBuffers",24),ae("maxDynamicUniformBuffersPerPipelineLayout",32),ae("maxDynamicStorageBuffersPerPipelineLayout",36),ae("maxSampledTexturesPerShaderStage",40),ae("maxSamplersPerShaderStage",44),ae("maxStorageBuffersPerShaderStage",48),ae("maxStorageTexturesPerShaderStage",52),ae("maxUniformBuffersPerShaderStage",56),ae("minUniformBufferOffsetAlignment",80),ae("minStorageBufferOffsetAlignment",84),ut("maxUniformBufferBindingSize",64),ut("maxStorageBufferBindingSize",72),ae("maxVertexBuffers",88),ut("maxBufferSize",96),ae("maxVertexAttributes",104),ae("maxVertexBufferArrayStride",108),ae("maxInterStageShaderVariables",112),ae("maxColorAttachments",116),ae("maxColorAttachmentBytesPerSample",120),ae("maxComputeWorkgroupStorageSize",124),ae("maxComputeInvocationsPerWorkgroup",128),ae("maxComputeWorkgroupSizeX",132),ae("maxComputeWorkgroupSizeY",136),ae("maxComputeWorkgroupSizeZ",140),ae("maxComputeWorkgroupsPerDimension",144),ae("maxImmediateSize",148,!0),u.requiredLimits=Ue}(L=(b(),C)[M+24>>>2>>>0])&&(L={label:yr(L+4)},u.defaultQueue=L),u.label=yr(M+4)}Oe+=1,Pn(d,P.requestDevice(u).then(ae=>{--Oe,Mt(()=>{gt[v>>>0]=ae.queue,gt[g>>>0]=ae,Oe+=1,Pn(h,ae.lost.then(ut=>{Mt(()=>{ae.onuncapturederror=()=>{};var Tt=fe(),pt=ir(ut.message);kb(h,pO[ut.reason],pt),pe(Tt)}),--Oe})),ae.onuncapturederror=ut=>{var Tt=5;ut.error instanceof GPUValidationError?Tt=2:ut.error instanceof GPUOutOfMemoryError?Tt=3:ut.error instanceof GPUInternalError&&(Tt=4);var pt=fe();ut=ir(ut.error.message),Fk(g,Tt,ut),pe(pt)},"adapterInfo"in ae||(ae.adapterInfo=P.info),Mb(d,1,g,0)})},ae=>{--Oe,Mt(()=>{var ut=fe(),Tt=ir(ae.message);Mb(d,3,g,Tt),h&&kb(h,4,Tt),pe(ut)})}))}function dO(u){var d=oe(u>>>=0),h=xr[u];if(h){for(var g=0;g>>=0;var g=oe(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(d>>>0,h)}catch{return 0}var M=Ob(16,v.byteLength);return(b(),X).set(new Uint8Array(v),M>>>0),xr[u].push(()=>Ht(M)),M}function mO(u,d,h){h>>>=0;var g=oe(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(d>>>0,h)}catch{return 0}var M=Ob(16,v.byteLength);return(b(),X).fill(0,M,v.byteLength),xr[u].push(()=>{new Uint8Array(v).set((b(),X).subarray(M>>>0,M+v.byteLength>>>0)),Ht(M)}),M}function hO(u,d,h,g,v){u>>>=0,d=ht(d),h=ht(h),v>>>=0;var M=oe(u);xr[u]=[],v==4294967295&&(v=void 0),Oe+=1,Pn(d,M.mapAsync(h,g>>>0,v).then(()=>{--Oe,Mt(()=>{Eb(d,1,0)})},P=>{--Oe,Mt(()=>{fe();var L=ir(P.message);Eb(d,P.name==="AbortError"?4:P.name==="OperationError"?3:0,L),delete xr[u]})}))}function gO(u){var d=oe(u>>>=0),h=xr[u];if(h){for(var g=0;g>>0]}function xO(u,d,h){u>>>=0,d>>>=0,h>>>=0;var g=!!(b(),C)[d+32>>>2>>>0];d={label:yr(d+4),usage:(b(),C)[d+16>>>2>>>0],size:_l(d+24),mappedAtCreation:g},u=oe(u);try{var v=u.createBuffer(d)}catch{return!1}return gt[h>>>0]=v,g&&(xr[h]=[]),!0}function yO(u,d,h,g){u>>>=0,d=ht(d),g>>>=0,h=aO(h>>>0),u=oe(u),Oe+=1,Pn(d,u.createComputePipelineAsync(h).then(v=>{--Oe,Mt(()=>{gt[g>>>0]=v,vb(d,1,g,0)})},v=>{--Oe,Mt(()=>{var M=fe(),P=ir(v.message);vb(d,v.reason==="validation"?3:v.reason==="internal"?4:0,g,P),pe(M)})}))}function bO(u,d,h){u>>>=0,d>>>=0,h>>>=0;var g=(b(),C)[d>>>2>>>0],v=(b(),R)[g+4>>>2>>>0];d={label:yr(d+4),code:""},v===2&&(d.code=hk(g+8)),u=oe(u).createShaderModule(d),gt[h>>>0]=u}var vO=u=>{(u=oe(u)).onuncapturederror=null,u.destroy()};function kO(u,d){d=ht(d),u=oe(u>>>0),Oe+=1,Pn(d,u.popErrorScope().then(h=>{--Oe,Mt(()=>{var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var v=fe(),M=h?ir(h.message):0;Ab(d,1,g,M),pe(v)})},h=>{--Oe,Mt(()=>{var g=fe(),v=ir(h.message);Ab(d,1,5,v),pe(g)})}))}function EO(u,d,h,g){if(d=ht(d),g>>>=0,h>>>=0){var v={featureLevel:lO[(b(),R)[h+4>>>2>>>0]],powerPreference:cO[(b(),R)[h+8>>>2>>>0]],forceFallbackAdapter:!!(b(),C)[h+12>>>2>>>0]};(u=(b(),C)[h>>>2>>>0])!==0&&(b(),v.De=!!(b(),C)[u+8>>>2>>>0])}"gpu"in navigator?(Oe+=1,Pn(d,navigator.gpu.requestAdapter(v).then(M=>{--Oe,Mt(()=>{if(M)gt[g>>>0]=M,ml(d,1,g,0);else{var P=fe(),L=ir("WebGPU not available on this browser (requestAdapter returned null)");ml(d,3,g,L),pe(P)}})},M=>{--Oe,Mt(()=>{var P=fe(),L=ir(M.message);ml(d,4,g,L),pe(P)})}))):(v=fe(),u=ir("WebGPU not available on this browser (navigator.gpu is not available)"),ml(d,3,g,u),pe(v))}function AO(u,d,h){return u>>>=0,d>>>=0,h>>>=0,ik(async()=>{var g=[];if(h){var v=(b(),R)[h>>>2>>>0];g.length=d+1,g[d]=new Promise(L=>setTimeout(L,v,0))}else g.length=d;for(var M=0;M{if(!xb){var u,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in yb)yb[u]===void 0?delete d[u]:d[u]=yb[u];var h=[];for(u in d)h.push(`${u}=${d[u]}`);xb=h}return xb};function yk(u,d){if(n)return Be(19,1,u,d);u>>>=0,d>>>=0;var h,g=0,v=0;for(h of xk()){var M=d+g;(b(),C)[u+v>>>2>>>0]=M,g+=gr(h,M,1/0)+1,v+=4}return 0}function bk(u,d){if(n)return Be(20,1,u,d);u>>>=0,d>>>=0;var h=xk();for(var g of((b(),C)[u>>>2>>>0]=h.length,u=0,h))u+=wr(g)+1;return(b(),C)[d>>>2>>>0]=u,0}function vk(u){return n?Be(21,1,u):52}function kk(u,d,h,g){return n?Be(22,1,u,d,h,g):52}function Ek(u,d,h,g){return n?Be(23,1,u,d,h,g):70}var MO=[null,[],[]];function Ak(u,d,h,g){if(n)return Be(24,1,u,d,h,g);d>>>=0,h>>>=0,g>>>=0;for(var v=0,M=0;M>>2>>>0],L=(b(),C)[d+4>>>2>>>0];d+=8;for(var G=0;G>>0],$e=MO[Z];Ie===0||Ie===10?((Z===1?S:T)(Uv($e)),$e.length=0):$e.push(Ie)}v+=L}return(b(),C)[g>>>2>>>0]=v,0}function TO(u){return u>>>0}function SO(u,d){return gk(oe(u>>>0).limits,d>>>0),1}function OO(u,d){return oe(u>>>0).features.has(wk[d])}function IO(u){return BigInt(oe(u>>>0).size)}function CO(u){return BigInt(oe(u>>>0).usage)}function PO(u,d){if(u>>>=0,d>>>=0){var h=yr(d+4);h={label:h,timestampWrites:d=(d=(b(),C)[d+12>>>2>>>0])!==0?{querySet:oe((b(),C)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(b(),C)[d+8>>>2>>>0],endOfPassWriteIndex:(b(),C)[d+12>>>2>>>0]}:void 0}}return d=oe(u),u=Lk(0),h=d.beginComputePass(h),gt[u>>>0]=h,u}function zO(u,d,h,g){h=ht(h),(g=ht(g))==-1&&(g=void 0),(u=oe(u>>>0)).clearBuffer(oe(d>>>0),h,g)}function LO(u,d,h,g,v,M){h=ht(h),v=ht(v),M=ht(M),oe(u>>>0).copyBufferToBuffer(oe(d>>>0),h,oe(g>>>0),v,M)}function NO(u){var d=oe(u>>>0);return u=Pk(0),d=d.finish(),gt[u>>>0]=d,u}function $O(u,d,h,g,v,M){M=ht(M),oe(u>>>0).resolveQuerySet(oe(d>>>0),h,g,oe(v>>>0),M)}function RO(u,d,h,g){oe(u>>>0).dispatchWorkgroups(d,h,g)}function DO(u,d,h){h=ht(h),oe(u>>>0).dispatchWorkgroupsIndirect(oe(d>>>0),h)}function FO(u){oe(u>>>0).end()}function BO(u,d,h,g,v){g>>>=0,v>>>=0,u=oe(u>>>0),h=oe(h>>>0),g==0?u.setBindGroup(d,h):u.setBindGroup(d,h,(b(),C),v>>>2,g)}function UO(u,d){oe(u>>>0).setPipeline(oe(d>>>0))}function jO(u,d,h){oe(u>>>0).Ce(oe(d>>>0),h)}function GO(u,d){var h=oe(u>>>0);return u=Ck(0),d=h.getBindGroupLayout(d),gt[u>>>0]=d,u}function qO(u,d){function h(v){var M=(b(),C)[v+8>>>2>>>0],P=(b(),C)[v+32>>>2>>>0],L=(b(),C)[v+36>>>2>>>0],G=0;return oO(v,{327681:Z=>{G=(b(),C)[Z+8>>>2>>>0]}}),M?((P=_l(v+24))==-1&&(P=void 0),M={buffer:oe(M),offset:_l(v+16),size:P}):M=oe(P||L||G),{binding:(b(),C)[v+4>>>2>>>0],resource:M}}u>>>=0,d={label:yr(4+(d>>>=0)),layout:oe((b(),C)[d+12>>>2>>>0]),entries:(function(v,M){for(var P=[],L=0;L>>2>>>0],(b(),C)[d+20>>>2>>>0])},u=oe(u);var g=Ik(0);return nO(g,u.createBindGroup(d)),g}function WO(u,d){var h;return u>>>=0,(d>>>=0)&&(h={label:yr(d+4)}),d=oe(u),u=zk(0),h=d.createCommandEncoder(h),gt[u>>>0]=h,u}function VO(u,d){u>>>=0,d>>>=0,d={type:uO[(b(),R)[d+12>>>2>>>0]],count:(b(),C)[d+16>>>2>>>0]};var h=oe(u);return u=Nk(0),d=h.createQuerySet(d),gt[u>>>0]=d,u}function HO(u,d){u=oe(u>>>0).adapterInfo,d>>>=0,(b(),C)[d+52>>>2>>>0]=u.subgroupMinSize,(b(),C)[d+56>>>2>>>0]=u.subgroupMaxSize;var h=u.vendor+u.architecture+u.device+u.description,g=wr(h)+1,v=zn(g);return v&&gr(h,v,g),h=v,g=wr(u.vendor),Qu(d+4,h,g),h+=g,g=wr(u.architecture),Qu(d+12,h,g),h+=g,g=wr(u.device),Qu(d+20,h,g),Qu(d+28,h+g,wr(u.description)),(b(),R)[d+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(b(),R)[d+40>>>2>>>0]=u,(b(),C)[d+44>>>2>>>0]=0,(b(),C)[d+48>>>2>>>0]=0,1}var XO={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function KO(u,d){d>>>=0;var h=oe(u>>>0);u=zn(4*h.features.size);var g=0,v=0;for(let M of h.features)0<=(h=XO[M])&&((b(),R)[u+g>>>2>>>0]=h,g+=4,v++);(b(),C)[d+4>>>2>>>0]=u,(b(),C)[d>>>2>>>0]=v}function YO(u,d){return gk(oe(u>>>0).limits,d>>>0),1}function QO(u,d){oe(u>>>0).pushErrorScope(iO[d])}function JO(u,d,h){d>>>=0,h>>>=0,u=oe(u>>>0),d=Array.from((b(),R).subarray(h>>>2>>>0,h+4*d>>>2>>>0),g=>oe(g)),u.submit(d)}function ZO(u,d,h,g,v){h=ht(h),g>>>=0,v>>>=0,u=oe(u>>>0),d=oe(d>>>0),g=(b(),X).subarray(g>>>0,g+v>>>0),u.writeBuffer(d,h,g,0,v)}n||(function(){for(var u=e.numThreads-1;u--;)Lv();Fe.push(async()=>{var d=(async function(){if(!n)return Promise.all(qr.map(zv))})();Se++,await d,--Se==0&&rt&&(d=rt,rt=null,d())})})(),n||(Wr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),le()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>fe(),e.stackRestore=u=>pe(u),e.stackAlloc=u=>Zu(u),e.setValue=function(u,d,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(b(),U)[u>>>0]=d;break;case"i16":(b(),K)[u>>>1>>>0]=d;break;case"i32":(b(),R)[u>>>2>>>0]=d;break;case"i64":(b(),z)[u>>>3>>>0]=BigInt(d);break;case"float":(b(),ne)[u>>>2>>>0]=d;break;case"double":(b(),Y)[u>>>3>>>0]=d;break;case"*":(b(),C)[u>>>2>>>0]=d;break;default:ce(`invalid type for setValue: ${h}`)}},e.getValue=function(u,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(b(),U)[u>>>0];case"i16":return(b(),K)[u>>>1>>>0];case"i32":return(b(),R)[u>>>2>>>0];case"i64":return(b(),z)[u>>>3>>>0];case"float":return(b(),ne)[u>>>2>>>0];case"double":return(b(),Y)[u>>>3>>>0];case"*":return(b(),C)[u>>>2>>>0];default:ce(`invalid type for getValue: ${d}`)}},e.UTF8ToString=In,e.stringToUTF8=gr,e.lengthBytesUTF8=wr;var Mk,Tk,bb,Ju,Ht,zn,Sk,Ok,Ik,Ck,Pk,zk,Lk,Nk,$k,Rk,Dk,vb,kb,Eb,Ab,ml,Mb,Fk,Tb,Bk,Uk,jk,Sb,Gk,qk,Ob,xe,hl,Wk,pe,Zu,fe,Vk,Ib,Hk,Xk,Kk,Cb,Yk,Qk,Jk,Zk,eE,tE,rE,sE,nE,oE,aE,iE,lE,cE,uE,pE,fE,dE,_E,mE,hE,gE,wE,xE,yE,bE,vE,kE,EE,AE,ME,TE,SE,OE,IE,CE,PE,zE,br,eI=[Tn,pl,Rv,jv,Gv,qv,Wv,Vv,Hv,Xv,Kv,Yv,Qv,Jv,Zv,ek,fk,dk,_k,yk,bk,vk,kk,Ek,Ak],Pb={970348:(u,d,h,g,v)=>{if(e===void 0||!e.Uc)return 1;if((u=In(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=e.Uc.get(u)))return 2;if(d=Number(d>>>0),h=Number(h>>>0),g=Number(g>>>0),d+h>u.byteLength)return 3;try{let M=u.subarray(d,d+h);switch(v){case 0:(b(),X).set(M,g>>>0);break;case 1:e.ad?e.ad(g,M):e.ne(g,M);break;default:return 4}return 0}catch{return 4}},971172:(u,d,h)=>{e.Sd(u,(b(),X).subarray(d>>>0,d+h>>>0))},971236:()=>e.le(),971278:u=>{e.jd(u)},971315:()=>typeof wasmOffsetConverter<"u"};function tI(u,d,h,g){var v=fe();try{return sE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function rI(u,d,h){var g=fe();try{return eE(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function sI(u){var d=fe();try{Yk(u)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function nI(u,d){var h=fe();try{return Cb(u,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function oI(u,d,h){var g=fe();try{Kk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function aI(u,d){var h=fe();try{nE(u,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function iI(u,d,h,g,v,M,P){var L=fe();try{return Zk(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function lI(u,d,h,g,v,M){var P=fe();try{Qk(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function cI(u,d,h,g){var v=fe();try{rE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function uI(u,d,h,g,v,M,P){var L=fe();try{aE(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function pI(u,d,h,g,v,M,P){var L=fe();try{iE(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function fI(u,d,h,g,v,M,P,L){var G=fe();try{hE(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function dI(u,d,h,g,v,M,P,L,G,Z,Ie,$e){var Ue=fe();try{lE(u,d,h,g,v,M,P,L,G,Z,Ie,$e)}catch(ae){if(pe(Ue),ae!==ae+0)throw ae;xe(1,0)}}function _I(u,d,h,g,v){var M=fe();try{return oE(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function mI(u,d,h,g,v){var M=fe();try{Jk(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function hI(u,d,h,g,v,M,P,L){var G=fe();try{tE(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function gI(u){var d=fe();try{return gE(u)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function wI(u,d,h){var g=fe();try{return wE(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function xI(u,d){var h=fe();try{return OE(u,d)}catch(g){if(pe(h),g!==g+0)throw g;return xe(1,0),0n}}function yI(u){var d=fe();try{return cE(u)}catch(h){if(pe(d),h!==h+0)throw h;return xe(1,0),0n}}function bI(u,d,h,g){var v=fe();try{return xE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function vI(u,d,h,g,v){var M=fe();try{return yE(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function kI(u,d,h,g,v,M){var P=fe();try{return bE(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function EI(u,d,h,g,v,M){var P=fe();try{return _E(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function AI(u,d,h,g,v,M){var P=fe();try{return vE(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function MI(u,d,h,g,v,M,P,L){var G=fe();try{return mE(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function TI(u,d,h,g,v){var M=fe();try{return kE(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;return xe(1,0),0n}}function SI(u,d,h,g){var v=fe();try{return EE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function OI(u,d,h,g){var v=fe();try{return AE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function II(u,d,h,g,v,M,P,L,G,Z,Ie,$e){var Ue=fe();try{return ME(u,d,h,g,v,M,P,L,G,Z,Ie,$e)}catch(ae){if(pe(Ue),ae!==ae+0)throw ae;xe(1,0)}}function CI(u,d,h,g,v,M,P,L,G,Z,Ie){var $e=fe();try{TE(u,d,h,g,v,M,P,L,G,Z,Ie)}catch(Ue){if(pe($e),Ue!==Ue+0)throw Ue;xe(1,0)}}function PI(u,d,h,g,v,M,P,L,G,Z,Ie,$e,Ue,ae,ut,Tt){var pt=fe();try{SE(u,d,h,g,v,M,P,L,G,Z,Ie,$e,Ue,ae,ut,Tt)}catch(Ss){if(pe(pt),Ss!==Ss+0)throw Ss;xe(1,0)}}function zI(u,d,h){var g=fe();try{return pE(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;return xe(1,0),0n}}function LI(u,d,h){var g=fe();try{return uE(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function NI(u,d,h){var g=fe();try{return fE(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function $I(u,d,h,g){var v=fe();try{dE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function ep(){if(0{let d=new WeakMap,h,g,v=1;e.webgpuRegisterDevice=L=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(L){var G=d.get(L);if(!G){let Z=((Ie,$e=0)=>{var Ue=Dk($e);return $e=Rk($e,Ue),gt[Ue>>>0]=Ie.queue,gt[$e>>>0]=Ie,$e})(L,G=Ok(0));G=[v++,G,Z],d.set(L,G)}return h=L,g=G[0],G}h=void 0,g=0};let M=new Map;e.webgpuOnCreateSession=L=>{if(g!==void 0){var G=g;if(g=void 0,L){let Z=bb(G);M.set(L,Z),G===0&&u(h??oe(Z))}h=void 0}},e.webgpuOnReleaseSession=L=>{M.delete(L)};let P=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(L,G,Z)=>{if(Z)return L[P]=[Z,NaN],Z;if(Z=L[P])return Z[1]++,Z[0];if((G=M.get(G))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return G=((Ie,$e=0)=>(Ie.mapState==="unmapped"||ce(),$e=$k($e),gt[$e>>>0]=Ie,$e))(L,G),L[P]=[G,1],G},e.webgpuUnregisterBuffer=L=>{let G=L[P];if(!G)throw Error("Buffer is not registered");G[1]--,G[1]===0&&(Sk(G[0]),delete L[P])},e.webgpuGetBuffer=L=>oe(L),e.webgpuCreateDownloader=(L,G,Z)=>{if((Z=M.get(Z))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Ie=oe(Z),$e=16*Math.ceil(Number(G)/16);return async()=>{let Ue=Ie.createBuffer({size:$e,usage:9});try{let ae=Ie.createCommandEncoder();return ae.copyBufferToBuffer(L,0,Ue,0,$e),Ie.queue.submit([ae.finish()]),await Ue.mapAsync(GPUMapMode.READ),Ue.getMappedRange().slice(0,G)}finally{Ue.destroy()}}},e.ad=(L,G)=>{var Z=G.buffer;let Ie=G.byteOffset,$e=G.byteLength;if(G=16*Math.ceil(Number($e)/16),L=oe(L),!h){var Ue=bb(g);h=oe(Ue)}let ae=(Ue=h.createBuffer({mappedAtCreation:!0,size:G,usage:6})).getMappedRange();new Uint8Array(ae).set(new Uint8Array(Z,Ie,$e)),Ue.unmap(),(Z=h.createCommandEncoder()).copyBufferToBuffer(Ue,0,L,0,G),h.queue.submit([Z.finish()]),Ue.destroy()}},e.webnnInit=u=>{let d=u[0];[e.le,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.ke,e.webnnEnableTraceEvent]=u.slice(1),e.webnnReleaseTensorId=e.jd,e.webnnUploadTensor=e.Sd,e.webnnRegisterMLContext=e.ke,e.webnnOnRunStart=h=>d.onRunStart(h),e.webnnOnRunEnd=d.onRunEnd.bind(d),e.webnnOnReleaseSession=h=>{d.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>d.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,v,M)=>d.registerMLTensor(h,g,v,M),e.webnnCreateMLContext=h=>d.createMLContext(h),e.webnnRegisterMLConstant=(h,g,v,M,P,L)=>d.registerMLConstant(h,g,v,M,P,e.Uc,L),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},Q?e:new Promise((u,d)=>{w=u,x=d})}var L2,UA,NL=ve(()=>{"use strict";L2=BA,UA=globalThis.self?.name?.startsWith("em-pthread"),UA&&BA()}),t1,g1,jA,zt,N2,wp,GA,qA,r1,WA,s1,$2,n1,R2,M1=ve(()=>{"use strict";A1(),t1=typeof location>"u"?void 0:location.origin,g1=Zt.url>"file:"&&Zt.url<"file;",jA=()=>{if(g1){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",Zt.url).href,t1).href}return Zt.url},zt=jA(),N2=()=>{if(zt&&!zt.startsWith("blob:"))return zt.substring(0,zt.lastIndexOf("/")+1)},wp=(t,e)=>{try{let r=e??zt;return(r?new URL(t,r):new URL(t)).origin===t1}catch{return!1}},GA=(t,e)=>{let r=e??zt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},qA=(t,e)=>`${e??"./"}${t}`,r1=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},WA=async t=>(await import(t)).default,s1=(LL(),Ep(C2)).default,$2=async()=>{if(!zt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(wp(zt))return[void 0,s1()];let t=await r1(zt);return[t,s1(t)]},n1=(NL(),Ep(z2)).default,R2=async(t,e,r,s)=>{let n=n1&&!(t||e);if(n)if(zt)n=wp(zt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,n1];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??GA(o,e),i=r&&a&&!wp(a,e),l=i?await r1(a):a??qA(o,e);return[i?l:void 0,await WA(l)]}}}),o1,xp,Ol,a1,VA,HA,XA,T1,De,qs=ve(()=>{"use strict";M1(),xp=!1,Ol=!1,a1=!1,VA=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},HA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},XA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},T1=async t=>{if(xp)return Promise.resolve();if(Ol)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(a1)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ol=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!XA())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!HA())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=VA();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,p=t.wasmBinary,[f,_]=await R2(i,o,r>1,!!p||!!c),m=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{m=!0,x()},e)})),w.push(new Promise((x,k)=>{let A={numThreads:r};if(p)A.wasmBinary=p,A.locateFile=E=>E;else if(c||o)A.locateFile=E=>c??o+E;else if(i&&i.indexOf("blob:")!==0)A.locateFile=E=>new URL(E,i).href;else if(f){let E=N2();E&&(A.locateFile=S=>E+S)}_(A).then(E=>{Ol=!1,xp=!0,o1=E,x(),f&&URL.revokeObjectURL(f)},E=>{Ol=!1,a1=!0,k(E)})})),await Promise.race(w),m)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},De=()=>{if(xp&&o1)return o1;throw new Error("WebAssembly is not initialized yet.")}}),Lt,Mp,Le,S1=ve(()=>{"use strict";qs(),Lt=(t,e)=>{let r=De(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},Mp=(t,e,r,s)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([n,o])=>{let a=e?e+n:n;if(typeof o=="object")Mp(o,a+".",r,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Le=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetLastError(n,n+s);let o=Number(e.getValue(n,s===4?"i32":"i64")),a=e.getValue(n+s,"*"),i=a?e.UTF8ToString(a):"";throw new Error(`${t} ERROR_CODE: ${o}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}}),D2,$L=ve(()=>{"use strict";qs(),S1(),D2=t=>{let e=De(),r=0,s=[],n=t||{};try{if(t?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(n.terminate=!1);let o=0;return t?.tag!==void 0&&(o=Lt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&Le("Can't create run options."),t?.extra!==void 0&&Mp(t.extra,"",new WeakSet,(a,i)=>{let l=Lt(a,s),c=Lt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&Le(`Can't set a run config entry: ${a} - ${i}.`)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),s.forEach(a=>e._free(a)),o}}}),KA,YA,QA,yp,ts,JA,F2,RL=ve(()=>{"use strict";qs(),S1(),KA=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},YA=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},QA=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},yp=(t,e,r,s)=>{let n=Lt(e,s),o=Lt(r,s);De()._OrtAddSessionConfigEntry(t,n,o)!==0&&Le(`Can't set a session config entry: ${e} - ${r}.`)},ts=(t,e,r,s)=>{let n=Lt(e,s),o=Lt(r,s);t.push([n,o])},JA=async(t,e,r)=>{let s=e.executionProviders;for(let n of s){let o=typeof n=="string"?n:n.name,a=[];switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let f=n?.deviceType;f&&yp(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let m=n;if(m.device)if(typeof GPUDevice<"u"&&m.device instanceof GPUDevice)f=m.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&ts(a,"enableGraphCapture","1",r),typeof m.preferredLayout=="string"&&ts(a,"preferredLayout",m.preferredLayout,r),m.forceCpuNodeNames){let x=Array.isArray(m.forceCpuNodeNames)?m.forceCpuNodeNames:[m.forceCpuNodeNames];ts(a,"forceCpuNodeNames",x.join(` + `),r)}m.validationMode&&ts(a,"validationMode",m.validationMode,r)}let _=De().webgpuRegisterDevice(f);if(_){let[m,w,x]=_;ts(a,"deviceId",m.toString(),r),ts(a,"webgpuInstance",w.toString(),r),ts(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=Lt(o,r),l=a.length,c=0,p=0;if(l>0){c=De()._malloc(l*De().PTR_SIZE),r.push(c),p=De()._malloc(l*De().PTR_SIZE),r.push(p);for(let f=0;f{let e=De(),r=0,s=[],n=t||{};QA(n);try{let o=KA(n.graphOptimizationLevel??"all"),a=YA(n.executionMode??"sequential"),i=typeof n.logId=="string"?Lt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?Lt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,p),r===0&&Le("Can't create session options."),n.executionProviders&&await JA(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);yp(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[f,_]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw new Error(`free dimension override value must be a non-negative integer: ${_}`);let m=Lt(f,s);e._OrtAddFreeDimensionOverride(r,m,_)!==0&&Le(`Can't set a free dimension override: ${f} - ${_}.`)}return n.extra!==void 0&&Mp(n.extra,"",new WeakSet,(f,_)=>{yp(r,f,_,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Le("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),Fs,kp,Un,Ll,Tp,O1,I1,w1,jn=ve(()=>{"use strict";Fs=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},kp=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},Un=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],s=typeof e=="number"?e:e.reduce((n,o)=>n*o,1);return r>0?Math.ceil(s*r):void 0},Ll=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Tp=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},O1=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",I1=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",w1=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${t}`)}}}),C1,B2=ve(()=>{"use strict";A1(),C1=async t=>{if(typeof t=="string"){let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(o,a,c).set(l),a+=c}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),U2,DL=ve(()=>{"use strict";jn(),U2=(t,e)=>new(Ll(e))(t)}),ZA,e2,t2,r2,j2,s2,vt,G2=ve(()=>{"use strict";jn(),ZA=["V","I","W","E","F"],e2=(t,e)=>{console.log(`[${ZA[t]},${new Date().toISOString()}]${e}`)},j2=(t,e)=>{t2=t,r2=e},s2=(t,e)=>{let r=Tp(t),s=Tp(t2);r>=s&&e2(r,typeof e=="function"?e():e)},vt=(...t)=>{r2&&s2(...t)}}),i1,x1,l1,n2,c1,o2,u1,p1,f1,a2,q2,FL=ve(()=>{"use strict";jn(),G2(),i1=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),x1=(t,e)=>{if(e==="int32")return t;let r=i1.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);let s=r/8;if(t.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=t.byteLength/s,o=new(Ll(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(l)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&o.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(o,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},l1=(t,e)=>{if(e==="int32")return t;if(t.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=t.byteLength/4,s=new Int32Array(t.buffer,t.byteOffset,r);switch(e){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(o=>o<-128||o>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${e}`)}},n2=1,c1=()=>n2++,o2=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),u1=(t,e)=>{let r=i1.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);return e.length>0?Math.ceil(e.reduce((s,n)=>s*n)*r/8):0},p1=class{constructor(t){this.isDataConverted=!1;let{sessionId:e,context:r,tensor:s,dataType:n,shape:o,fallbackDataType:a}=t;this.sessionId=e,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.fallbackDataType=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return u1(this.dataType,this.tensorShape)}destroy(){vt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){if(this.fallbackDataType){let e=await this.mlContext.readTensor(this.mlTensor),r=l1(new Uint8Array(e),this.dataType);if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(r);return}else return r.buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,e,r){return this.mlContext===t&&this.dataType===e&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(t){this.isDataConverted=t}},f1=class{constructor(t,e){this.tensorManager=t,this.wrapper=e}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,e,r,s){let n=this.tensorManager.getMLContext(t),o=this.tensorManager.getMLOpSupportLimits(t),a;if(!o?.input.dataTypes.includes(e)){if(a=o2.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);vt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${e} to ${a}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,e,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==u1(e,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,e,r,i,!0,!0,a),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){let e=t;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")e=x1(t,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else vt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(t){if(this.activeUpload){let e=this.wrapper?.isDataConverted?l1(this.activeUpload,this.wrapper?.type):this.activeUpload;if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(e):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(e);return}else return e.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(t):this.wrapper.read()}},a2=class{constructor(t){this.backend=t,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(t){let e=this.backend.getMLContext(t);if(!e)throw new Error("MLContext not found for session.");return e}getMLOpSupportLimits(t){return this.backend.getMLOpSupportLimits(t)}reserveTensorId(){let t=c1();return this.tensorTrackersById.set(t,new f1(this)),t}releaseTensorId(t){let e=this.tensorTrackersById.get(t);e&&(this.tensorTrackersById.delete(t),e.tensorWrapper&&this.releaseTensor(e.tensorWrapper))}async ensureTensor(t,e,r,s,n){vt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,s,n)}upload(t,e){let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");r.upload(e)}async download(t,e){vt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${e?.byteLength}}`);let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");return r.download(e)}releaseTensorsForSession(t){for(let e of this.freeTensors)e.sessionId===t&&e.destroy();this.freeTensors=this.freeTensors.filter(e=>e.sessionId!==t)}registerTensor(t,e,r,s){let n=this.getMLContext(t),o=c1(),a=new p1({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new f1(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(i,e,r)){vt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}vt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:a??e,shape:r,dimensions:r,usage:s,writable:n,readable:o});return new p1({sessionId:t,context:i,tensor:l,dataType:e,shape:r,fallbackDataType:a})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},q2=(...t)=>new a2(...t)}),W2={};Nl(W2,{WebNNBackend:()=>V2});var Il,i2,V2,BL=ve(()=>{"use strict";jn(),qs(),DL(),FL(),G2(),Il=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),i2=(t,e)=>{if(t===e)return!0;if(t===void 0||e===void 0)return!1;let r=Object.keys(t).sort(),s=Object.keys(e).sort();return r.length===s.length&&r.every((n,o)=>n===s[o]&&t[n]===e[n])},V2=class{constructor(t){this.tensorManager=q2(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,j2(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){vt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){vt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)vt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(t),this.activeSessionId=void 0}}async createMLContext(t){if(t instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===t);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:s}),s}}else if(t===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let e=this.mlContextCache.findIndex(r=>i2(r.options,t));if(e!==-1)return this.mlContextCache[e].mlContext;{let r=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:r}),r}}registerMLContext(t,e){this.mlContextBySessionId.set(t,e);let r=this.sessionIdsByMLContext.get(e);r||(r=new Set,this.sessionIdsByMLContext.set(e,r)),r.add(t),this.mlOpSupportLimitsBySessionId.has(t)||this.mlOpSupportLimitsBySessionId.set(t,e.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(t,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(t,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(t){this.sessionGraphInputs.delete(t),this.sessionGraphOutputs.delete(t);let e=this.mlContextBySessionId.get(t);if(!e)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t),this.mlOpSupportLimitsBySessionId.delete(t);let r=this.sessionIdsByMLContext.get(e);if(r.delete(t),r.size===0){this.sessionIdsByMLContext.delete(e);let s=this.mlContextCache.findIndex(n=>n.mlContext===e);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}getMLOpSupportLimits(t){return this.mlOpSupportLimitsBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){vt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=Il.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t??this.currentSessionId,e,o,s,n)}async createTemporaryTensor(t,e,r){vt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=Il.get(e);if(!s)throw new Error(`Unsupported ONNX data type: ${e}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(t,n,s,r,!1);let o=this.temporarySessionTensorIds.get(t);return o?o.push(n):this.temporarySessionTensorIds.set(t,[n]),n}uploadTensor(t,e){if(!De().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");vt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${e.byteLength}}`),this.tensorManager.upload(t,e)}async downloadTensor(t,e){return this.tensorManager.download(t,e)}createMLTensorDownloader(t,e){return async()=>{let r=await this.tensorManager.download(t);return U2(r,e)}}registerMLTensor(t,e,r,s){let n=Il.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return vt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(e,e+r).buffer,p;switch(n.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":if(a){let f=x1(new Uint8Array(c),"int64");p=new Int32Array(f.buffer),n.dataType="int32"}else p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return vt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,p)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=Il.get(Fs(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),l2,P1,z1,rs,c2,d1,Sp,L1,N1,_1,$1,R1,D1,H2=ve(()=>{"use strict";Gs(),$L(),RL(),jn(),qs(),S1(),B2(),l2=(t,e)=>{De()._OrtInit(t,e)!==0&&Le("Can't initialize onnxruntime.")},P1=async t=>{l2(t.wasm.numThreads,Tp(t.logLevel))},z1=async(t,e)=>{De().asyncInit?.();let r=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=t.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let n=t.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(e==="webgpu"&&De().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(BL(),Ep(W2)).WebNNBackend(t);De().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,o,a,i,l)=>s.ensureTensor(n,o,a,i,l),(n,o)=>{s.uploadTensor(n,o)},async(n,o)=>s.downloadTensor(n,o),(n,o)=>s.registerMLContext(n,o),!!t.trace])}},rs=new Map,c2=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetInputOutputCount(t,n,n+s)!==0&&Le("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(e.getValue(n,o)),Number(e.getValue(n+s,o))]}finally{e.stackRestore(r)}},d1=(t,e)=>{let r=De(),s=r.stackSave(),n=0;try{let o=r.PTR_SIZE,a=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(t,e,a,a+o)!==0&&Le("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],p=[];for(let f=0;f{let e=De(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},L1=async(t,e)=>{let r,s,n=De();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=Sp(t);let o=0,a=0,i=0,l=[],c=[],p=[];try{if([a,l]=await F2(e),e?.externalData&&n.mountExternalData){let T=[];for(let I of e.externalData){let O=typeof I=="string"?I:I.path;T.push(C1(typeof I=="string"?I:I.data).then(b=>{n.mountExternalData(O,b)}))}await Promise.all(T)}for(let T of e?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof T!="string"){let I=T,O=I?.context,b=I?.gpuDevice,F=I?.deviceType,j=I?.powerPreference;O?n.currentContext=O:b?n.currentContext=await n.webnnCreateMLContext(b):n.currentContext=await n.webnnCreateMLContext({deviceType:F,powerPreference:j})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Le("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,_]=c2(o),m=!!e?.enableGraphCapture,w=[],x=[],k=[],A=[],E=[];for(let T=0;TT==="gpu-buffer"||T==="ml-tensor"||T==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&Le("Can't create IO binding."),S={handle:i,outputPreferredLocations:E,outputPreferredLocationsEncoded:E.map(T=>T==="ml-tensor-cpu-output"?"ml-tensor":T).map(T=>w1(T))}),rs.set(o,[o,c,p,S,m,!1]),[o,w,x,k,A]}catch(f){throw c.forEach(_=>n._OrtFree(_)),p.forEach(_=>n._OrtFree(_)),i!==0&&n._OrtReleaseBinding(i)!==0&&Le("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Le("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Le("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},N1=t=>{let e=De(),r=rs.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&Le("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Le("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(l=>e._OrtFree(l)),o.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(s)!==0&&Le("Can't release session."),rs.delete(t)},_1=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=De(),l=i.PTR_SIZE,c=t[0],p=t[1],f=t[3],_=f,m,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let A=t[2].gpuBuffer;w=Un(Fs(c),p);{let E=i.webgpuRegisterBuffer;if(!E)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');m=E(A,s)}}else if(f==="ml-tensor"){let A=t[2].mlTensor;w=Un(Fs(c),p);let E=i.webnnRegisterMLTensor;if(!E)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');m=E(s,A,Fs(c),p)}else{let A=t[2];if(Array.isArray(A)){w=l*A.length,m=i._malloc(w),r.push(m);for(let E=0;Ei.setValue(k+S*l,E,l===4?"i32":"i64"));let A=i._OrtCreateTensor(Fs(c),m,w,k,p.length,w1(_));A===0&&Le(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(A)}finally{i.stackRestore(x)}},$1=async(t,e,r,s,n,o)=>{let a=De(),i=a.PTR_SIZE,l=rs.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],p=l[1],f=l[2],_=l[3],m=l[4],w=l[5],x=e.length,k=s.length,A=0,E=[],S=[],T=[],I=[],O=[],b=a.stackSave(),F=a.stackAlloc(x*i),j=a.stackAlloc(x*i),U=a.stackAlloc(k*i),X=a.stackAlloc(k*i);try{[A,E]=D2(o),ns("wasm prepareInputOutputTensor");for(let C=0;CFe*Se,1);B=kp(Ge);let At=_?.outputPreferredLocations[s[C]];if(B==="string"){if(At==="gpu-buffer"||At==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Fe=[];for(let Se=0;Se0){let Fe=a.webgpuGetBuffer;if(!Fe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Se=Fe(Q),rt=Un(Ge,ct);if(rt===void 0||!O1(B))throw new Error(`Unsupported data type: ${B}`);$=!0;{a.webgpuRegisterBuffer(Se,t,Q);let nr=a.webgpuCreateDownloader(Se,rt,t);J.push([B,qe,{gpuBuffer:Se,download:async()=>{let Oe=await nr();return new(Ll(B))(Oe)},dispose:()=>{a._OrtReleaseTensor(ne)!==0&&Le("Can't release tensor.")}},"gpu-buffer"])}}else if(At==="ml-tensor"&&ct>0){let Fe=a.webnnEnsureTensor,Se=a.webnnIsGraphInputOutputTypeSupported;if(!Fe||!Se)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Un(Ge,ct)===void 0||!I1(B))throw new Error(`Unsupported data type: ${B}`);if(!Se(t,B,!1))throw new Error(`preferredLocation "ml-tensor" for ${B} output is not supported by current WebNN Context.`);let rt=await Fe(t,Q,Ge,qe,!1);$=!0,J.push([B,qe,{mlTensor:rt,download:a.webnnCreateMLTensorDownloader(Q,B),dispose:()=>{a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(ne)}},"ml-tensor"])}else if(At==="ml-tensor-cpu-output"&&ct>0){let Fe=a.webnnCreateMLTensorDownloader(Q,B)(),Se=J.length;$=!0,R.push((async()=>{let rt=[Se,await Fe];return a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(ne),rt})()),J.push([B,qe,[],"cpu"])}else{let Fe=Ll(B),Se=new Fe(ct);new Uint8Array(Se.buffer,Se.byteOffset,Se.byteLength).set(a.HEAPU8.subarray(Q,Q+Se.byteLength)),J.push([B,qe,Se,"cpu"])}}finally{a.stackRestore(Y),B==="string"&&Q&&a._free(Q),$||a._OrtReleaseTensor(ne)}}_&&!m&&(a._OrtClearBoundOutputs(_.handle)!==0&&Le("Can't clear bound outputs."),rs.set(t,[c,p,f,_,m,!1]));for(let[C,ne]of await Promise.all(R))J[C][2]=ne;return os("wasm ProcessOutputTensor"),J}finally{a.webnnOnRunEnd?.(c),a.stackRestore(b),r.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),n.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),S.forEach(K=>a._OrtReleaseTensor(K)),T.forEach(K=>a._OrtReleaseTensor(K)),I.forEach(K=>a._free(K)),A!==0&&a._OrtReleaseRunOptions(A),E.forEach(K=>a._free(K))}},R1=t=>{let e=De(),r=rs.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Le("Can't get an profile file name."),e._OrtFree(n)},D1=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),ss,Ut,Bn,Cl,Pl,bp,m1,vp,$s,Rs,u2,X2,K2,Y2,Q2,J2,Z2,eM,tM=ve(()=>{"use strict";Gs(),H2(),qs(),M1(),ss=()=>!!Qe.wasm.proxy&&typeof document<"u",Bn=!1,Cl=!1,Pl=!1,vp=new Map,$s=(t,e)=>{let r=vp.get(t);r?r.push(e):vp.set(t,[e])},Rs=()=>{if(Bn||!Cl||Pl||!Ut)throw new Error("worker not ready")},u2=t=>{switch(t.data.type){case"init-wasm":Bn=!1,t.data.err?(Pl=!0,m1[1](t.data.err)):(Cl=!0,m1[0]()),bp&&(URL.revokeObjectURL(bp),bp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=vp.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},X2=async()=>{if(!Cl){if(Bn)throw new Error("multiple calls to 'initWasm()' detected.");if(Pl)throw new Error("previous call to 'initWasm()' failed.");if(Bn=!0,ss())return new Promise((t,e)=>{Ut?.terminate(),$2().then(([r,s])=>{try{Ut=s,Ut.onerror=o=>e(o),Ut.onmessage=u2,m1=[t,e];let n={type:"init-wasm",in:Qe};!n.in.wasm.wasmPaths&&(r||g1)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",Zt.url).href}),Ut.postMessage(n),bp=r}catch(n){e(n)}},e)});try{await T1(Qe.wasm),await P1(Qe),Cl=!0}catch(t){throw Pl=!0,t}finally{Bn=!1}}},K2=async t=>{if(ss())return Rs(),new Promise((e,r)=>{$s("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Qe}};Ut.postMessage(s)});await z1(Qe,t)},Y2=async t=>ss()?(Rs(),new Promise((e,r)=>{$s("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Ut.postMessage(s,[t.buffer])})):Sp(t),Q2=async(t,e)=>{if(ss()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Rs(),new Promise((r,s)=>{$s("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Ut.postMessage(n,o)})}else return L1(t,e)},J2=async t=>{if(ss())return Rs(),new Promise((e,r)=>{$s("release",[e,r]);let s={type:"release",in:t};Ut.postMessage(s)});N1(t)},Z2=async(t,e,r,s,n,o)=>{if(ss()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Rs(),new Promise((a,i)=>{$s("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Ut.postMessage(c,D1(l))})}else return $1(t,e,r,s,n,o)},eM=async t=>{if(ss())return Rs(),new Promise((e,r)=>{$s("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Ut.postMessage(s)});R1(t)}}),h1,p2,rM,UL=ve(()=>{"use strict";Gs(),tM(),jn(),A1(),B2(),h1=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},p2=t=>{switch(t[3]){case"cpu":return new er(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!O1(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return er.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!I1(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return er.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},rM=class{async fetchModelAndCopyToWasmMemory(t){return Y2(await C1(t))}async loadModel(t,e){Us();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Q2(r,e),js()}async dispose(){return J2(this.sessionId)}async run(t,e,r){Us();let s=[],n=[];Object.entries(t).forEach(f=>{let _=f[0],m=f[1],w=this.inputNames.indexOf(_);if(w===-1)throw new Error(`invalid input '${_}'`);s.push(m),n.push(w)});let o=[],a=[];Object.entries(e).forEach(f=>{let _=f[0],m=f[1],w=this.outputNames.indexOf(_);if(w===-1)throw new Error(`invalid output '${_}'`);o.push(m),a.push(w)});let i=s.map((f,_)=>h1(f,()=>`input "${this.inputNames[n[_]]}"`)),l=o.map((f,_)=>f?h1(f,()=>`output "${this.outputNames[a[_]]}"`):null),c=await Z2(this.sessionId,n,i,a,l,r),p={};for(let f=0;fb1,initializeFlags:()=>y1,wasmBackend:()=>nM});var y1,b1,nM,jL=ve(()=>{"use strict";Gs(),tM(),UL(),y1=()=>{(typeof Qe.wasm.initTimeout!="number"||Qe.wasm.initTimeout<0)&&(Qe.wasm.initTimeout=0);let t=Qe.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),Qe.wasm.simd=!1),typeof Qe.wasm.proxy!="boolean"&&(Qe.wasm.proxy=!1),typeof Qe.wasm.trace!="boolean"&&(Qe.wasm.trace=!1),typeof Qe.wasm.numThreads!="number"||!Number.isInteger(Qe.wasm.numThreads)||Qe.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Qe.wasm.numThreads=1;else{let e=typeof navigator>"u"?xL("node:os").cpus().length:navigator.hardwareConcurrency;Qe.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},b1=class{async init(t){y1(),await X2(),await K2(t)}async createInferenceSessionHandler(t,e){let r=new rM;return await r.loadModel(t,e),r}},nM=new b1});Gs();Gs();Gs();var GL="1.26.0-dev.20260416-b7804b056c",qL=I2;{let t=(jL(),Ep(sM)).wasmBackend;Bs("webgpu",t,5),Bs("webnn",t,5),Bs("cpu",t,10),Bs("wasm",t,10)}Object.defineProperty(Qe.versions,"web",{value:GL,enumerable:!0});async function oM(t){let e=t.split("/").pop(),r;try{if(r=await Jt(),r){let n=await r.match(t);if(n)return n}}catch(n){ee.warn(`Failed to load ${e} from cache:`,n)}let s=await _e.fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){ee.warn(`Failed to cache ${e}:`,n)}return s}async function aM(t){let e=await oM(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return ee.warn("Failed to read WASM binary:",r),null}}async function iM(t){if(ie.IS_SERVICE_WORKER_ENV||ie.IS_CHROME_AVAILABLE)return t;let e=await oM(t);if(!e||typeof e=="string")return null;try{let r=await e.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return ee.warn("Failed to read WASM factory:",r),null}}var U1=require("onnxruntime-common"),VL=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function pM(t){return t<=St.DEBUG?0:t<=St.INFO?2:t<=St.WARNING||t<=St.ERROR?3:4}var HL={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},jt=[],B1,qn,lM=Symbol.for("onnxruntime");if(lM in globalThis)qn=globalThis[lM];else if(ie.IS_NODE_ENV){switch(qn=WL,process.platform){case"win32":jt.push("dml");break;case"linux":process.arch==="x64"&&jt.push("cuda");break;case"darwin":jt.push("coreml");break}jt.push("webgpu"),jt.push("cpu"),B1=["cpu"]}else qn=F1,ie.IS_WEBNN_AVAILABLE&&jt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ie.IS_WEBGPU_AVAILABLE&&jt.push("webgpu"),jt.push("wasm"),B1=["wasm"];var XL=qn.InferenceSession;function fM(t=null){if(!t)return B1;switch(t){case"auto":return jt;case"gpu":return jt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(jt.includes(t))return[VL[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${jt.join(", ")}.`)}var cM=Promise.resolve(),Gn=null;async function KL(){if(Gn)return Gn;if(!(_e.useWasmCache&&typeof it?.wasm?.wasmPaths=="object"&&it?.wasm?.wasmPaths?.wasm&&it?.wasm?.wasmPaths?.mjs)){if(ie.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return Gn=Promise.resolve(),Gn}return Gn=(async()=>{let e=it.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!qb(e.wasm)?(async()=>{try{let s=await aM(Wb(e.wasm));s&&(it.wasm.wasmBinary=s,r=!0)}catch(s){ee.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!qb(e.mjs)?(async()=>{try{let s=await iM(Wb(e.mjs));s&&(it.wasm.wasmPaths.mjs=s)}catch(s){ee.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(it.wasm.wasmPaths.mjs=e.mjs)})(),Gn}async function Op(t,e,r){await KL();let s=pM(_e.logLevel??St.WARNING),n=()=>XL.create(t,{logSeverityLevel:s,...e}),o=await(ie.IS_WEB_ENV?cM=cM.then(n):n());return o.config=r,o}var uM=Promise.resolve();async function Ip(t,e){let r=()=>t.run(e);return ie.IS_WEB_ENV?uM=uM.then(r):r()}function Cp(t){return t instanceof qn.Tensor}var it=qn?.env;function $l(){return it?.wasm?.proxy}if(it){let t=function(e){let r=pM(e);it.logLevel=HL[r]};if(it.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&it.versions?.web&&!it.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${it.versions.web}/dist/`;it.wasm.wasmPaths=ie.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}it.wasm.proxy=!1}it.webgpu&&(it.webgpu.powerPreference="high-performance"),t(_e.logLevel??St.WARNING),_e.backends.onnx={...it,setLogLevel:t}}var as=async(t,e,r)=>{let s=await Op(new Uint8Array(t),e);return(async n=>{let o=$l(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await Ip(s,a);return Array.isArray(r)?r.map(l=>new N(i[l])):new N(i[r])})},pr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=as([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=as([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=as([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=as([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=as([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=as([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=as([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=as([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var dM=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),j1=ie.IS_NODE_ENV?"cpu":"wasm";function Pp(t,e,{warn:r}={}){return t?typeof t=="string"?t:t.hasOwnProperty(e)?t[e]:(r&&r(`device not specified for "${e}". Using the default device (${j1}).`),j1):j1}var hM=(function(){let t;return async function(){if(t===void 0)if(!ie.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),st=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),_M=st.fp32,mM=Object.freeze({[dM.wasm]:st.q8}),is=Object.freeze({[st.fp32]:"",[st.fp16]:"_fp16",[st.int8]:"_int8",[st.uint8]:"_uint8",[st.q8]:"_quantized",[st.q4]:"_q4",[st.q2]:"_q2",[st.q1]:"_q1",[st.q4f16]:"_q4f16",[st.q2f16]:"_q2f16",[st.q1f16]:"_q1f16",[st.bnb4]:"_bnb4"});function zp(t,e,r,{configDtype:s=null,warn:n}={}){let o,a=!1;t&&typeof t!="string"?t.hasOwnProperty(e)?o=t[e]:(o=null,a=!0):o=t;let i;if(o===st.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==st.auto&&st.hasOwnProperty(l))return l}i=mM[r]??_M}else o&&st.hasOwnProperty(o)?i=o:i=mM[r]??_M;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var ls=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var N=class t{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return Cp(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new U1.Tensor(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}indexOf(e){let r=this.data;for(let s=0;sm)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(_,0),Math.min(m,this.dims[p])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([p,f])=>f-p),o=n.reduce((p,f)=>p*f),a=this.data,i=new a.constructor(o),l=this.stride(),c=!0;for(let p=1;p=0;--_){let w=n[_];f+=(m%w+s[_][0])*l[_],m=Math.floor(m/w)}i[p]=a[f]}return new t(this.type,i,r)}permute(...e){return xM(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let a,i;if(o?(a=(f,_)=>f+_,i=0n):(a=(f,_)=>f+_**e,i=0),r===null){let f=n.reduce(a,i);return e!==1&&(f=f**(1/e)),new t(this.type,[f],[])}let[l,c,p]=Rl(a,this,r,s);if(e!==1)for(let f=0;f=0;--l){let f=this.dims[l];if(l!==r){let _=c%f;i+=_*p,p*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return G1(this.dims)}squeeze(e=null){return new t(this.type,this.data,gM(this.dims,e))}squeeze_(e=null){return this.dims=gM(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,wM(this.dims,e))}unsqueeze_(e){return this.dims=wM(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...s,n.reduce((a,i)=>a*i,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;ni!==r?o*a:o,1);e[r]=s.length/n}return new t(this.type,s,e)}neg_(){let e=this.data;for(let r=0;re?1:0;return new t("bool",r,this.dims)}lt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;nMath.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=ze(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Rl((a,i)=>Math.max(a,i),this,e,r,-1/0);return new t(s,n,o)}argmin(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Tl(this.data)[1];return new t("int64",[BigInt(s)],[])}argmax(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=ze(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.lengthp===1)){if(e.length===this.dims.length)return this.clone();let p=e.length-this.dims.length,f=Array(p).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((p,f)=>p*e[f]),o=n.reduce((p,f)=>p*f,1),a=this.data,i=new a.constructor(o),l=G1(s),c=G1(n);for(let p=0;pBigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,DA(this.data),this.dims);return new t(e,ls[e].from(this.data,r),this.dims)}};function YL(t,e){let r=t.length,s=e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.lengthnew N("int64",t,[t.length]);async function Dl(t,e,r,s,n){return await(await pr.slice)({x:t,s:Lp(e),e:Lp(r),a:Lp(s),t:Lp(n??new Array(s.length).fill(1))})}function W1(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let p=0;pr!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function wM(t,e){return e=fr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function fr(t,e,r=null,s=!0){if(t<-e||t>=e){if(s)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function ye(t,e=0){e=fr(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i=0;--_){let x=c[_],k=m%x;_===e&&(k+=a),f+=k*w,w*=r[_],m=Math.floor(m/x)}n[f]=l[p]}a+=c[e]}}return new N(o,n,r)}function _t(t,e=0){return ye(t.map(r=>r.unsqueeze(e)),e)}function Rl(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=fr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let c=0;c=0;--f){let w=a[f];if(f!==r){let x=_%w;p+=x*m,m*=i[f]}_=Math.floor(_/w)}l[p]=t(l[p],o[c],c,p)}return s||i.splice(r,1),[e.type,l,i]}function $p(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let m=n.reduce((A,E)=>A+E,0)/n.length,w=Math.sqrt(n.reduce((A,E)=>A+(E-m)**2,0)/(n.length-r)),x=new N(t.type,[m],[]);return[new N(t.type,[w],[]),x]}e=fr(e,o.length);let a=Fl(t,e,s),i=a.data,[l,c,p]=Rl((_,m,w,x)=>_+(m-i[x])**2,t,e,s);for(let _=0;_c+p,0);return new N(t.type,[l/n.length],[])}e=fr(e,s.length);let[o,a,i]=Rl((l,c)=>l+c,t,e,r);if(s[e]!==1)for(let l=0;l=0;--r)e[r]=s,s*=t[r];return e}function V1(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new N(r,new s(n).fill(e),t)}function Ke(t,e){let r,s;if(typeof e=="number")r="float32",s=Float32Array;else if(typeof e=="bigint")r="int64",s=BigInt64Array;else if(typeof e=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return V1(t,e,r,s)}function Wn(t,e){return Ke(t.dims,e)}function Ze(t){return V1(t,1n,"int64",BigInt64Array)}function Bl(t){return Ze(t.dims)}function Rp(t){return V1(t,0n,"int64",BigInt64Array)}function Dp(t){return Rp(t.dims)}function ZL(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>Kr.random()),t)}function H1(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>Kr.gauss()),t)}function X1(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i0?1:0,c=Math.floor(i/8),p=i%8;a[c]|=l<<7-p,r&&p===0&&(a[c]-=128)}return new N(s,a,[t.dims[0],t.dims[1]/8])}async function Vn(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await Ot(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function K1(t,e){let r=await Vn(t);return await Promise.all(r.map(s=>nt(t,s,!0,e)))}function Ul(t){let e=t.dims;switch(e.length){case 1:return t.tolist();case 2:if(e[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return t.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${e.length}.`)}}var eN=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function tN(t,e,r,s){for(let n of Object.keys(t)){let o=e-t[n].length,a=r(n),i=new Array(o).fill(a);t[n]=s==="right"?wt(t[n],i):wt(i,t[n])}}function rN(t,e){for(let r of Object.keys(t))t[r].length=e}function Ws(t,...e){for(let r of e){if(!Object.hasOwn(t,r))continue;let s=t[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function sN(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var W=class extends We{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new iA(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Ws(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ws(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ws(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ws(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ws(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ws(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:a}of this.chat_template){if(typeof o!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=a}this.chat_template=n}this._compiled_template_cache=new Map;let s=sN(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let i=await K1(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,r={}){let{text_pair:s=null,add_special_tokens:n=!0,padding:o=!1,return_token_type_ids:a=null}=r,{truncation:i=null,max_length:l=null}=r,c=r.return_tensor??!0,p=Array.isArray(e),f;if(p){if(e.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(e.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");f=e.map((m,w)=>this._encode_plus(m,{text_pair:s[w],add_special_tokens:n,return_token_type_ids:a}))}else f=e.map(m=>this._encode_plus(m,{add_special_tokens:n,return_token_type_ids:a}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(s))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");f=[this._encode_plus(e,{text_pair:s,add_special_tokens:n,return_token_type_ids:a})]}if(l===null?l=this.model_max_length:i===null&&(o===!0?(ee.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):o===!1&&(ee.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),i=!0)),o===!0&&(l=Math.min(ze(f.map(m=>m.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),o||i)for(let m=0;ml?i&&rN(f[m],l):o&&tN(f[m],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));let _={};if(c){if(!(o&&i)&&f.some(w=>{for(let x of Object.keys(w))if(w[x].length!==f[0][x]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let m=[f.length,f[0].input_ids.length];for(let w of Object.keys(f[0]))_[w]=new N("int64",BigInt64Array.from(f.flatMap(x=>x[w]).map(BigInt)),m)}else{for(let m of Object.keys(f[0]))_[m]=f.map(w=>w[m]);if(!p)for(let m of Object.keys(_))_[m]=_[m][0]}return _}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof N&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof N&&(e=Ul(e)),!Array.isArray(e)||e.length===0||!GE(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,r={}){let{tools:s=null,documents:n=null,chat_template:o=null,add_generation_prompt:a=!1,tokenize:i=!0,padding:l=!1,truncation:c=!1,max_length:p=null,return_tensor:f=!0,return_dict:_=!0,tokenizer_kwargs:m={},...w}=r;if(o=this.get_chat_template({chat_template:o,tools:s}),typeof o!="string")throw Error(`chat_template must be a string, but got ${typeof o}`);let x=this._compiled_template_cache.get(o);x===void 0&&(x=new xA(o),this._compiled_template_cache.set(o,x));let k=Object.create(null);for(let E of eN){let S=Ws(this.config,E);S&&(k[E]=S)}let A=x.render({messages:e,add_generation_prompt:a,tools:s,documents:n,...k,...w});if(i){let E=this._call(A,{add_special_tokens:!1,padding:l,truncation:c,max_length:p,return_tensor:f,...m});return _?E:E.input_ids}return A}};function Hn(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var Q1={};Os(Q1,{AlbertTokenizer:()=>Fp,AutoTokenizer:()=>se,BartTokenizer:()=>Bp,BertTokenizer:()=>Up,BlenderbotSmallTokenizer:()=>jp,BlenderbotTokenizer:()=>Gp,BloomTokenizer:()=>qp,CLIPTokenizer:()=>Vp,CamembertTokenizer:()=>Wp,CodeGenTokenizer:()=>Xp,CodeLlamaTokenizer:()=>Hp,CohereAsrTokenizer:()=>Yp,CohereTokenizer:()=>Kp,ConvBertTokenizer:()=>Qp,DebertaTokenizer:()=>Zp,DebertaV2Tokenizer:()=>Jp,DistilBertTokenizer:()=>ef,ElectraTokenizer:()=>tf,EsmTokenizer:()=>rf,FalconTokenizer:()=>sf,GPT2Tokenizer:()=>af,GPTNeoXTokenizer:()=>of,GemmaTokenizer:()=>nf,HerbertTokenizer:()=>lf,LlamaTokenizer:()=>cf,M2M100Tokenizer:()=>uf,MBart50Tokenizer:()=>ff,MBartTokenizer:()=>Xn,MPNetTokenizer:()=>mf,MarianTokenizer:()=>pf,MgpstrTokenizer:()=>df,MobileBertTokenizer:()=>_f,NllbTokenizer:()=>hf,NougatTokenizer:()=>gf,PreTrainedTokenizer:()=>W,Qwen2Tokenizer:()=>wf,RoFormerTokenizer:()=>yf,RobertaTokenizer:()=>xf,SiglipTokenizer:()=>bf,SpeechT5Tokenizer:()=>vf,SqueezeBertTokenizer:()=>kf,T5Tokenizer:()=>Ef,TokenizersBackend:()=>W,VitsTokenizer:()=>Af,Wav2Vec2CTCTokenizer:()=>Mf,WhisperTokenizer:()=>Tf,XLMRobertaTokenizer:()=>Sf,XLMTokenizer:()=>Of});var Fp=class extends W{return_token_type_ids=!0};var Bp=class extends W{};var Up=class extends W{return_token_type_ids=!0};var jp=class extends W{};var Gp=class extends W{};var qp=class extends W{};var Wp=class extends W{};var Vp=class extends W{};var Hp=class extends W{};var Xp=class extends W{};var Kp=class extends W{};var Yp=class extends W{};var Qp=class extends W{return_token_type_ids=!0};var Jp=class extends W{return_token_type_ids=!0};var Zp=class extends W{return_token_type_ids=!0};var ef=class extends W{};var tf=class extends W{return_token_type_ids=!0};var rf=class extends W{};var sf=class extends W{};var nf=class extends W{};var of=class extends W{};var af=class extends W{};var lf=class extends W{return_token_type_ids=!0};var cf=class extends W{padding_side="left"};var uf=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return Hn(this,e,r,s)}};var pf=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),ee.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[r,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(r);if(s.length===2){let[n,o]=s;return this.supported_language_codes.includes(n)||ee.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),wt([n],super._encode_text(o))}}};var Xn=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return Hn(this,e,r,s)}};var ff=class extends Xn{};var df=class extends W{};var _f=class extends W{return_token_type_ids=!0};var mf=class extends W{};var hf=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return Hn(this,e,r,s)}};var gf=class extends W{};var wf=class extends W{};var xf=class extends W{};var yf=class extends W{return_token_type_ids=!0};var bf=class extends W{};var vf=class extends W{};var kf=class extends W{return_token_type_ids=!0};var Ef=class extends W{};var Y1=class extends Ft{decode_chain(e){let r="";for(let s=1;s[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function bM(t){t=t.toLowerCase();let e=nN.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),jl.has(t))e=t;else{let n=t.length===2?jl.keys():jl.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var oN="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",vM=new RegExp(`^[${oN}]+$`,"gu"),aN=.1,Tf=class extends W{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],p=l(),f=0,_=this.timestamp_begin,w=_+1500,x=[],k=[],A=!1,E=null,S=new Set(this.all_special_ids);for(let O of e){let b=O.tokens,F=i?O.token_timestamps:null,j=null,U=_;if("stride"in O){let[J,R,C]=O.stride;if(f-=R,E=J-C,R&&(U=R/n+_),C)for(let ne=b.length-1;ne>=0;--ne){let Y=Number(b[ne]);if(Y>=_){if(j!==null&&(Y-_)*n=_&&R<=w){let C=(R-_)*n+f,ne=Ns(C,2);if(j!==null&&R>=j)A=!0;else if(A||x.length>0&&R0&&p.timestamp[1]!==null))for(let B of p.words)B.timestamp[1]>p.timestamp[1]&&p.timestamp[1]>=B.timestamp[0]&&(B.timestamp[1]=p.timestamp[1]);c.push(p),x=[],X=[],k=[],K=[],p=l()}}else if(X.push(R),i){let C=Ns(F[J]+f,2),ne;if(J+10?(x.push(X),i&&k.push(K)):x.every(J=>J.length===0)&&(p=l(),x=[],X=[],k=[],K=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[O,b]=this.findLongestCommonSequence(x,k),F=this.decode(O);p.text=F,i&&(p.words=this.collateWordTimestamps(O,b,a)),c.push(p)}let T=Object.create(null),I=c.map(O=>O.text).join("");if(r||s){for(let O=0;O0,i=a?[]:null,l=a?r[0]:null;for(let c=1;cR===U[C]&&l[I+C][0]-aN<=r[c][F+C][0]).length:X=b.filter((R,C)=>R===U[C]).length;let K=T/1e4,J=X/T+K;X>1&&J>f&&(f=J,_=[I,O,F,j])}let[w,x,k,A]=_,E=Math.floor((x+w)/2),S=Math.floor((A+k)/2);if(a&&f===0&&n>0){let T=l[n-1][0],I=r[c].findIndex(O=>O[0]>=T);S=I===-1?p.length:I}o.push(...s.slice(0,E)),s=p.slice(S),n=s.length,a&&(i.push(...l.slice(0,E)),l=r[c].slice(S))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],c=0;for(let p=0;p=this._tokenizer.token_to_id("<|endoftext|>"),m=c.startsWith(" "),w=c.trim(),x=vM.test(w);if(_||m||x||o.length===0)o.push(c),a.push(p),i.push(f);else{let k=o.length-1;o[k]+=c,a[k].push(...p),i[k].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,p=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[p]=a[c]+a[p],i[p]=wt(i[c],i[p]),l[p]=wt(l[c],l[p]),a[c]="",i[c]=[],l[c]=[]):p=c,--c;for(c=0,p=1;pf),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var Sf=class extends W{};var Of=class extends W{return_token_type_ids=!0;constructor(e,r){super(e,r),ee.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var se=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await K1(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=Q1[c];return p||(ee.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=W),new p(i,l)}};var cs="https://github.com/huggingface/transformers.js/issues/new/choose";var Gl="preprocessor_config.json",Er=Gl,If="processor_config.json",Cf="chat_template.jinja";var re=class extends We{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?nt(e,If,!0,r):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{let i=await this[a].from_pretrained(e,r);return[a.replace(/_class$/,""),i]})).then(Object.fromEntries),this.uses_chat_template_file?Ml(e,Cf,!0,r):null]);return new this(s,n,o)}};var g_={};Os(g_,{ChatterboxProcessor:()=>Xf,CohereAsrProcessor:()=>Kf,Florence2Processor:()=>jd,Gemma3Processor:()=>Gd,Gemma3nProcessor:()=>qd,Gemma4Processor:()=>Wd,Glm46VProcessor:()=>Vd,GraniteSpeechProcessor:()=>Hd,GroundingDinoProcessor:()=>Xd,Idefics3Processor:()=>ac,JinaCLIPProcessor:()=>Yd,Lfm2VlProcessor:()=>Qd,LlavaProcessor:()=>Jd,MgpstrProcessor:()=>Zd,MoonshineProcessor:()=>e_,OwlViTProcessor:()=>t_,PaliGemmaProcessor:()=>r_,Phi3VProcessor:()=>s_,PixtralProcessor:()=>n_,Processor:()=>re,PyAnnoteProcessor:()=>o_,Qwen2VLProcessor:()=>fs,Qwen2_5_VLProcessor:()=>co,Qwen3VLProcessor:()=>a_,Sam2Processor:()=>ic,Sam2VideoProcessor:()=>i_,SamProcessor:()=>uo,SmolVLMProcessor:()=>ac,SpeechT5Processor:()=>l_,UltravoxProcessor:()=>c_,VLChatProcessor:()=>Kd,VoxtralProcessor:()=>p_,VoxtralRealtimeProcessor:()=>d_,Wav2Vec2Processor:()=>__,Wav2Vec2ProcessorWithLM:()=>m_,WhisperProcessor:()=>h_});var Ee=class extends We{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await nt(e,Gl,!0,r);return new this(s)}};function Me(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var ql={};Os(ql,{ASTFeatureExtractor:()=>Nf,ChatterboxFeatureExtractor:()=>$f,ClapFeatureExtractor:()=>Rf,CohereAsrFeatureExtractor:()=>Df,DacFeatureExtractor:()=>Jn,EncodecFeatureExtractor:()=>Yn,FeatureExtractor:()=>Ee,Gemma3nAudioFeatureExtractor:()=>Zn,Gemma4AudioFeatureExtractor:()=>eo,GraniteSpeechFeatureExtractor:()=>Ff,MoonshineFeatureExtractor:()=>Bf,ParakeetFeatureExtractor:()=>Qn,PyAnnoteFeatureExtractor:()=>to,SeamlessM4TFeatureExtractor:()=>Uf,SnacFeatureExtractor:()=>jf,SpeechT5FeatureExtractor:()=>Gf,VoxtralRealtimeFeatureExtractor:()=>Vf,Wav2Vec2FeatureExtractor:()=>qf,WeSpeakerFeatureExtractor:()=>Wf,WhisperFeatureExtractor:()=>Hf});var kM=vr(require("fs"),1),EM=require("stream"),AM=require("stream/promises");async function Pf(t,e){if(ie.IS_BROWSER_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(ie.IS_FS_AVAILABLE){let r=e.stream(),s=EM.Readable.fromWeb(r),n=kM.default.createWriteStream(t);await(0,AM.pipeline)(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function Z1(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await Qr(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&ee.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let c=0;c2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function J1(t,e="htk"){let r=lN[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}var cN={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,r=15,s=Math.log(6.4)/27)=>t>=r?e*Math.exp(s*(t-r)):200*t/3};function uN(t,e="htk"){let r=cN[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}function pN(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;anew Array(t.length));for(let a=0;at+s*o)}function lt(t,e,r,s,n,o=null,a="htk",i=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);let l=J1(r,a),c=J1(s,a),p=TM(l,c,e+2),f=uN(p,a),_;if(i){let w=n/((t-1)*2);_=J1(Float64Array.from({length:t},(x,k)=>k*w),a),f=p}else _=TM(0,Math.floor(n/2),t);let m=pN(_,f);if(o!==null&&o==="slaney")for(let w=0;wn)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(j!==r)throw new Error(`Length of the window (${j}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!p)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a){let Q=Math.floor(r/2);switch(i){case"reflect":{t=fN(t,Q,Q);break}case"constant":{let le=new t.constructor(t.length+2*Q);le.set(t,Q),t=le;break}case"semicausal":{let le=new t.constructor(t.length+Q);le.set(t,Q),t=le;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let U=Math.floor(1+Math.floor((t.length-r)/s));S!==null&&UU?I&&(J=T):J=K=T);let R=new mp(n),C=new Float64Array(n),ne=new Float64Array(R.outputBufferSize),Y=new Float32Array(X*J);for(let Q=0;Q=1;--ce)C[ce]-=c*C[ce-1];C[0]*=1-c}for(let ce=0;ceMath.pow(c,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null||t===s)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);let i=new Float64Array(s),l=n?Math.floor((s-t)/2):0;return i.set(a,l),i}function mN(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return zf(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),zf(n,8,"WAVE"),zf(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,e,!0),n.setUint32(28,e*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),zf(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function zf(t,e,r){for(let s=0;sn+o.length,0),r=new Float32Array(e),s=0;for(let n of this.audio)r.set(n,s),s+=n.length;return r}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),mN(e,this.sampling_rate)}async save(e){return Pf(e,this.toBlob())}};var Nf=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=mt(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){Me(e,"ASTFeatureExtractor");let r=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let s=this.std*2,n=r.data;for(let o=0;o0)if(s==="rand_trunc"){a=!0;let l=Math.floor(Kr.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let c=e.length;c=1;--n)e[n]-=r*e[n-1];return await ot(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){Me(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f1?s-1:1;for(let f=0;f=p){l.push(e.slice(c,p));break}let f=Math.max(c,c+a-i),_=Math.min(c+a,p),m;_<=f?m=c+a:m=this._find_split_point_energy(e,f,_,n),m=Math.max(c+1,Math.min(m,p)),l.push(e.slice(c,m)),c=m}return l}_find_split_point_energy(e,r,s,n){let o=s-r;if(o<=n)return Math.floor((r+s)/2);let a=1/0,i=r,l=o-n;for(let c=0;c<=l;c+=n){let p=0;for(let f=0;fr&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let a=await this._extract_fbank_features(e,this.config.max_length),i=Ke([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var eo=class extends Zn{async _extract_fbank_features(e,r){let{frame_length:s,hop_length:n,fft_length:o}=this.config,a=Math.floor(s/2),i=Math.floor((e.length+a-(s+1))/n)+1;return ot(e,this.window,s,n,{fft_length:o,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:i})}async _call(e,r={}){Me(e,"Gemma4AudioFeatureExtractor");let s=e.length,n=await super._call(e,r),{input_features:o}=n,[,a,i]=o.dims,{frame_length:l,hop_length:c}=this.config,p=Math.floor(l/2),f=l+1,_=new Uint8Array(s+p+(r.pad_to_multiple_of??128));_.fill(1,p,p+s);let m=new Uint8Array(a);for(let x=0;x({id:l,start:c*s,end:p*s,confidence:f/(p-c)})))}return n}};var Uf=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=mt(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){Me(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,k=a.data;for(let A=0;A0){let E=new Float32Array(x*(w+A));E.set(k),E.fill(this.config.padding_value,k.length);let S=w+A;a=new N(a.type,E,[S,x]),o&&(i=new N("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,p=this.config.stride;if(l%p!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${p}).`);let _=a.view(1,Math.floor(l/p),c*p),m={input_features:_};if(o){let w=_.dims[1],x=new BigInt64Array(w);if(i){let k=i.data;for(let A=1,E=0;Ao+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){Me(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));let s=[1,r.length];return{input_values:new N("float32",r,s),attention_mask:new N("int64",new BigInt64Array(r.length).fill(1n),s)}}};var Wf=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=mt(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){Me(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;ln?(e.length>this.config.n_samples&&ee.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var je=class{static async from_pretrained(e,r={}){let s=await nt(e,Gl,!0,r),n=s.feature_extractor_type,o=ql[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${cs}.`);return new o(s)}};var Xf=class extends re{static tokenizer_class=se;static feature_extractor_class=je;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var gN=new Set(["ja","zh"]),Kf=class extends re{static tokenizer_class=se;static feature_extractor_class=je;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let r=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(r)}static join_chunks(e,r="en"){let s=e.filter(a=>a&&a.trim());if(s.length===0)return"";let n=gN.has(r)?"":" ";return[s[0].trimEnd(),...s.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}};var Yf=vr(require("sharp"),1);var Vs,IM,us;if(ie.IS_WEB_ENV)Vs=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},us=self.createImageBitmap,IM=self.ImageData;else if(Yf.default)us=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Je(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&o.convert(r),o};else throw new Error("Unable to load image processing library.");var wN={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},xN=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Je=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!ie.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let s=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(s,e.width,e.height,4)}static async fromURL(e){let r=await Qr(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(e){if(ie.IS_WEB_ENV){let r=await us(e),s=Vs(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=(0,Yf.default)(await e.arrayBuffer());return await us(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r=0?l=s:p=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,p,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await us(o)}}async toBlob(e="image/png",r=1){if(!ie.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new N("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!ie.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=Vs(e.width,e.height),s=new IM(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;lnew t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(ie.IS_WEB_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=xN.get(r)??"image/png",n=await this.toBlob(s);return Pf(e,n)}else if(ie.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(ie.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return(0,Yf.default)(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},CM=Je.read.bind(Je);function PM(t,e,r=0,s=null){let n=t/e,o=$A(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),oe&&A.push(S)}else{let S=ze(k.data)[1];if(S===l-1||(E=Pe(k.data),E[S]I*f[(O+1)%2])),_.boxes.push(T),_.classes.push(S),_.scores.push(E[S])}}c.push(_)}return c}function Qf(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;of[A]&&(f[A]=k[A],_[A]=x)}let m=new Array(i.dims[0]);for(let x=0;x<_.length;++x){let k=_[x];m[k]=k}let w=m.filter(x=>x!==void 0);n.push({segmentation:p,labels:w})}return n}function yN(t,e,r,s){let n=[],o=[],a=[];for(let i=0;ir&&(n.push(c),o.push(_),a.push(p))}return[n,o,a]}function bN(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let p=0;p=s&&++i;let c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function vN(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new N("int32",new Int32Array(i*l),[i,l]),p=[];if(a!==null)for(let x=0;x_[E]&&(f[E]=x,_[E]=A[E])}let m=0,w=c.data;for(let x=0;x200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let a=Math.round(t/r)*r,i=Math.round(e/r)*r;if(o*a*i>n){let l=Math.sqrt(o*t*e/n);a=Math.max(r,Math.floor(t/l/r)*r),i=Math.max(r,Math.floor(e/l/r)*r)}else if(o*a*io?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=Tl(s.data)[0],a=ze(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=s.height,p=0,f=0,_=s.data;for(let m=0;mthis.preprocess(o)));return{pixel_values:_t(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await nt(e,Er,!0,r);return new this(s)}};var io={};Os(io,{BeitFeatureExtractor:()=>ed,BitImageProcessor:()=>td,CHMv2ImageProcessor:()=>sd,CLIPFeatureExtractor:()=>nd,CLIPImageProcessor:()=>Wl,ChineseCLIPFeatureExtractor:()=>rd,ConvNextFeatureExtractor:()=>od,ConvNextImageProcessor:()=>Vl,DINOv3ViTImageProcessor:()=>ld,DPTFeatureExtractor:()=>ud,DPTImageProcessor:()=>Kl,DeiTFeatureExtractor:()=>ad,DeiTImageProcessor:()=>Hl,DetrFeatureExtractor:()=>id,DetrImageProcessor:()=>Xl,DonutFeatureExtractor:()=>cd,DonutImageProcessor:()=>Hs,EfficientNetImageProcessor:()=>pd,GLPNFeatureExtractor:()=>_d,Gemma3ImageProcessor:()=>fd,Gemma4ImageProcessor:()=>so,Glm46VImageProcessor:()=>dd,GroundingDinoImageProcessor:()=>md,Idefics3ImageProcessor:()=>Yl,ImageFeatureExtractor:()=>H,ImageProcessor:()=>H,JinaCLIPImageProcessor:()=>gd,Lfm2VlImageProcessor:()=>wd,LlavaOnevisionImageProcessor:()=>xd,Mask2FormerImageProcessor:()=>bd,MaskFormerFeatureExtractor:()=>yd,MaskFormerImageProcessor:()=>Xs,MobileNetV1FeatureExtractor:()=>vd,MobileNetV1ImageProcessor:()=>Ql,MobileNetV2FeatureExtractor:()=>kd,MobileNetV2ImageProcessor:()=>Jl,MobileNetV3FeatureExtractor:()=>Ed,MobileNetV3ImageProcessor:()=>Zl,MobileNetV4FeatureExtractor:()=>Ad,MobileNetV4ImageProcessor:()=>ec,MobileViTFeatureExtractor:()=>Md,MobileViTImageProcessor:()=>tc,NougatImageProcessor:()=>Td,OwlViTFeatureExtractor:()=>Sd,OwlViTImageProcessor:()=>Ks,Owlv2ImageProcessor:()=>Od,Phi3VImageProcessor:()=>Id,PixtralImageProcessor:()=>Cd,PvtImageProcessor:()=>Pd,Qwen2VLImageProcessor:()=>no,RTDetrImageProcessor:()=>zd,Sam2ImageProcessor:()=>ao,Sam3ImageProcessor:()=>ao,SamImageProcessor:()=>ao,SapiensFeatureExtractor:()=>Ld,SapiensImageProcessor:()=>rc,SegformerFeatureExtractor:()=>Nd,SegformerImageProcessor:()=>sc,SiglipImageProcessor:()=>$d,SmolVLMImageProcessor:()=>Yl,Swin2SRImageProcessor:()=>Rd,VLMImageProcessor:()=>hd,ViTFeatureExtractor:()=>Dd,ViTImageProcessor:()=>nc,VitMatteImageProcessor:()=>Fd,VitPoseImageProcessor:()=>Bd,YolosFeatureExtractor:()=>Ud,YolosImageProcessor:()=>oc});var ed=class extends H{};var td=class extends H{};var rd=class extends H{};var sd=class extends H{};var Wl=class extends H{},nd=class extends Wl{};var Vl=class extends H{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){let s=Math.floor(r/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}},od=class extends Vl{};var Hl=class extends H{},ad=class extends Hl{};var Xl=class extends H{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Ke(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return ps(...e)}post_process_panoptic_segmentation(...e){return Jf(...e)}post_process_instance_segmentation(...e){return Zf(...e)}},id=class extends Xl{};var ld=class extends H{};var Hs=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let p=l.map((f,_)=>-f/c[_]);return super.pad_image(e,r,s,{center:!0,constant_values:p,...n})}},cd=class extends Hs{};var Kl=class extends H{},ud=class extends Kl{};var pd=class extends H{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}};var fd=class extends H{};function kN(t,e,r,s,n){let o=s*r**2,a=Math.sqrt(o/(t*e)),i=n*r,l=Math.floor(a*t/i)*i,c=Math.floor(a*e/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);let p=Math.floor(s/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(e/t)*i,p)):c===0&&(c=i,l=Math.min(Math.floor(t/e)*i,p)),[l,c]}function EN(t,e,r,s,n,o,a){let i=Math.floor(e/n),l=Math.floor(r/n),c=i*l,p=n*n*s,f=new Float32Array(o*p),_=0;for(let x=0;xa),0));let p=a.dims[0]/i,f=a.dims[1],_=Math.floor(a.dims[2]/c),m=Math.floor(a.dims[3]/c),w=a.view(p,i,f,Math.floor(_/l),l,c,Math.floor(m/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(p*_*m,f*i*c*c),x=new N("int64",[p,_,m],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var dd=class extends no{get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return ro(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}};var _d=class extends H{};var md=class extends H{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=Ze([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var Yl=class extends H{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],c=[];for(let A of n){let E=await Promise.all(A.map(I=>this.preprocess(I)));l.push(...E.map(I=>I.original_size)),c.push(...E.map(I=>I.reshaped_input_size)),E.forEach(I=>I.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,T;if(r??this.do_image_splitting){let I=new Array(E.length),O=new Array(E.length);T=await Promise.all(E.map(async(b,F)=>{let j=this.get_resize_for_vision_encoder(b.pixel_values,S),U=await yt(b.pixel_values,{size:[j.height,j.width]}),{frames:X,num_splits_h:K,num_splits_w:J}=await this.split_image(U,this.max_image_size);return I[F]=K,O[F]=J,ye(X,0)})),a.push(I),i.push(O)}else{let I=[S,S];T=await Promise.all(E.map(O=>yt(O.pixel_values,{size:I}))),a.push(new Array(E.length).fill(0)),i.push(new Array(E.length).fill(0))}o.push(ye(T,0))}let p=o.length,[f,_,m,w]=o[0].dims,x,k;if(p===1)x=o[0].unsqueeze_(0),k=Ke([p,f,m,w],!0);else{let A=Math.max(...o.map(T=>T.dims.at(0)));k=Ke([p,A,m,w],!0);let E=k.data,S=A*m*w;for(let T=0;Ts||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let p=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;wr*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var gd=class extends H{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function LM(t,e){return Math.round(t/e)*e}function AN(t,e,r,s,n){let o=1/0,a=[1,1],i=r*s;for(let l of e){let c=Math.abs(t-l[0]/l[1]);c.5*n*n*l[0]*l[1]&&(a=l)}return a}function MN(t,e){let r=[],s=new Set;for(let n=t;n<=e;++n)for(let o=1;o<=n;++o)for(let a=1;a<=n;++a){let i=o*a;if(i>=t&&i<=e){let l=o<<16|a;s.has(l)||(s.add(l),r.push([o,a]))}}return r.sort((n,o)=>n[0]*n[1]-o[0]*o[1])}function TN(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,p=new Float32Array(r*a*i*l),f=n*o;for(let _=0;_this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=MN(this.min_tiles,this.max_tiles),[n,o]=AN(r/e,s,r,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:r=null}={}){let s;Array.isArray(e)?Array.isArray(e[0])?s=e:s=[e]:s=[[e]];let n=[],o=[],a=[],i=[],l=[],c=[];for(let f of s){let _=await Promise.all(f.map(m=>this.preprocess(m,{do_pad:!1})));for(let{pixel_values:m}of _){let[,w,x]=m.dims,k=m.unsqueeze_(0),A=this.encoder_patch_size*this.downsample_factor,E=A**2,[S,T]=ro(Math.max(A,w),Math.max(A,x),A,this.min_image_tokens*E,this.max_image_tokens*E).map(U=>Math.max(A,U)),I,O=1,b=1,F=this._is_image_too_large(w,x),j=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(F&&j){let{grid_width:U,grid_height:X,target_width:K,target_height:J}=this._get_grid_layout(w,x);O=X,b=U;let R=await yt(k,{size:[J,K]});I=[];for(let C=0;C(p-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||rv(r)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(_=>this.preprocess(_))),o=n.map(_=>_.original_size),a=n.map(_=>_.reshaped_input_size),i=[];for(let{pixel_values:_}of n){_.unsqueeze_(0);let[m,w]=_.dims.slice(-2),x=await yt(_,{size:[$t,$t],mode:"bicubic"});if(r>0){let k=[],A=rv(r),E=oo(w/A),S=oo(m/A);for(let I=0;I_.map(m=>$t*tv(m/$t))),p=new N("int64",c.flat(),[s,2]),f=c.map(([_,m])=>this.calc_num_image_tokens_from_image_size(m,_));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:p,num_img_tokens:f}}};var Cd=class extends H{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");let f=c*p,_=Math.floor((i-1)/f)+1,m=Math.floor((l-1)/f)+1;return[_*f,m*f]}};var Pd=class extends H{};var zd=class extends H{post_process_object_detection(...e){return ps(...e)}};var ao=class extends H{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=Db(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;an!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new N("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let c=0;cn&&(w[x]=1);_=new N("bool",w,_.dims)}i.push(_)}return i}generate_crop_boxes(e,r,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:a=1}={}){}};var rc=class extends H{post_process_semantic_segmentation(...e){return Qf(...e)}},Ld=class extends rc{};var sc=class extends H{post_process_semantic_segmentation(...e){return Qf(...e)}},Nd=class extends sc{};var $d=class extends H{};var Rd=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r;return super.pad_image(e,r,{width:a+(s-a%s)%s,height:o+(s-o%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var nc=class extends H{},Dd=class extends nc{};var Fd=class extends H{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let s=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(r.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:_t(s.map((a,i)=>ye([a.pixel_values,n[i].pixel_values],0)),0),original_sizes:s.map(a=>a.original_size),reshaped_input_sizes:s.map(a=>a.reshaped_input_size)}}};var Bd=class extends H{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let p=0;p/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],c=[];for(let[p,f,..._]of i)l.push(f?f.trim():l.at(-1)??""),c.push(_.map((m,w)=>(Number(m)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:c};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var Gd=class extends re{static tokenizer_class=se;static image_processor_class=Ae;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:o,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=o,this.eoi_token=a;let i=o.repeat(this.image_seq_length);this.full_image_sequence=` +diff --git a/node_modules/@huggingface/transformers/dist/transformers.node.min.mjs b/node_modules/@huggingface/transformers/dist/transformers.node.min.mjs +index 125c9eb..af00cc8 100644 +--- a/node_modules/@huggingface/transformers/dist/transformers.node.min.mjs ++++ b/node_modules/@huggingface/transformers/dist/transformers.node.min.mjs +@@ -1,4 +1,4 @@ +-var AI=Object.defineProperty;var fs=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var en=(t,e)=>{for(var r in e)AI(t,r,{get:e[r],enumerable:!0})};import MI from"fs";import tn from"path";import TI from"url";var SI="4.2.0",Mf=typeof self<"u",rn=!gE(MI),_E=!gE(tn),sc=Mf&&"caches"in self,OI=typeof globalThis.Deno<"u",a3=typeof globalThis.Bun<"u",oc=OI&&sc&&!rn,mE=typeof process<"u",hE=mE&&process?.release?.name==="node"&&!oc,Tf=typeof window<"u"&&typeof window.document<"u",Sf=Mf&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),II=Tf||Sf||oc,CI=hE||typeof navigator<"u"&&"gpu"in navigator,PI=typeof navigator<"u"&&"ml"in navigator,zI=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",LI=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",NI=typeof ServiceWorkerGlobalScope<"u"&&Mf&&self instanceof ServiceWorkerGlobalScope,$I=()=>{if(typeof navigator>"u")return!1;let t=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,s=!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android");return r&&s},RI=$I(),ie=Object.freeze({IS_BROWSER_ENV:Tf,IS_WEBWORKER_ENV:Sf,IS_WEB_ENV:II,IS_SERVICE_WORKER_ENV:NI,IS_DENO_WEB_RUNTIME:oc,IS_WEB_CACHE_AVAILABLE:sc,IS_WEBGPU_AVAILABLE:CI,IS_WEBNN_AVAILABLE:PI,IS_SAFARI:RI,IS_PROCESS_AVAILABLE:mE,IS_NODE_ENV:hE,IS_FS_AVAILABLE:rn,IS_PATH_AVAILABLE:_E,IS_CRYPTO_AVAILABLE:zI,IS_CHROME_AVAILABLE:LI}),Of=rn&&_E,nc="./";if(Of){let t=Object(import.meta).url;t?nc=tn.dirname(tn.dirname(TI.fileURLToPath(t))):typeof __dirname<"u"&&(nc=tn.dirname(__dirname))}var DI=Of?tn.join(nc,"/.cache/"):null,fE="/models/",FI=Of?tn.join(nc,fE):fE,BI=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,St=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),dE=St.WARNING,me={version:SI,backends:{onnx:{}},get logLevel(){return dE},set logLevel(t){dE=t,me.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Tf||Sf||oc),localModelPath:FI,useFS:rn,useBrowserCache:sc,useFSCache:rn,cacheDir:DI,useCustomCache:!1,customCache:null,useWasmCache:sc||rn,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:BI};function gE(t){return Object.keys(t).length===0}var We=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function or(t,e){t&&t(e)}var ds=class extends We{constructor(e,r){super(),this.callback=e,this.files_loading=r}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let r=Object.values(this.files_loading).reduce((o,a)=>o+a.loaded,0),s=Object.values(this.files_loading).reduce((o,a)=>o+a.total,0),n=s>0?r/s*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:r,total:s,files:structuredClone(this.files_loading)})}this.callback(e)}};function wE(t){return Number.isInteger(t)||typeof t=="bigint"}function If(t){return t==null||t===-1}function Cf(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function gt(...t){return Array.prototype.concat.apply([],t)}function xE(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function sn(t,e){return Math.abs((t+e)%(2*e)-e)}function Ve(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function yE(t,e){let r=0;for(let s of t)s===e&&++r;return r}var ee={error(...t){me.logLevel<=St.ERROR&&console.error(...t)},warn(...t){me.logLevel<=St.WARNING&&console.warn(...t)},info(...t){me.logLevel<=St.INFO&&console.log(...t)},debug(...t){me.logLevel<=St.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var UI=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let s=e;for(let n=0;ns&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),r=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+r),r+=1);let s=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,s[o]]))})(),qI=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),WI=qI(SE),vE=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",VI=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${vE}])]+`,` ?[^\\s${vE}]+`]]),ac="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",zf=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),ic=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[s,n]of VI)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1,o=r.replace(/(\\[pP])\{([^}=]+)\}/g,(a,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(o,"gu")}catch{throw s}}}else if(t.String!==void 0){let r=HI(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},HI=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),XI=(t,e,r)=>{let s=[],n=0;for(;nt>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,YI=t=>Number.isInteger(t)||typeof t=="bigint",QI=t=>{let e=0;for(let r of t)++e;return e},JI=t=>OE(t.toLowerCase()),Vt=(...t)=>Array.prototype.concat.apply([],t),Lf=t=>new Map(Object.entries(t)),ZI=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s0&&r.push(o),s=n.index+o.length}return st.replace(/\p{M}/gu,""),kE=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let s of r)if(!(s in t))return`${e} must contain a "${s}" property`;return null},eC=t=>t.match(/\S+/g)||[],tC=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},co=tC,rC=class extends co{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},xr=rC,sC=class extends xr{tokenize_chinese_chars(t){let e=[];for(let r=0;rtypeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var en=(t,e)=>{for(var r in e)AI(t,r,{get:e[r],enumerable:!0})};import MI from"fs";import tn from"path";import TI from"url";var SI="4.2.0",Mf=typeof self<"u",rn=!gE(MI),_E=!gE(tn),sc=Mf&&"caches"in self,OI=typeof globalThis.Deno<"u",a3=typeof globalThis.Bun<"u",oc=OI&&sc&&!rn,mE=typeof process<"u",hE=mE&&process?.release?.name==="node"&&!oc,Tf=typeof window<"u"&&typeof window.document<"u",Sf=Mf&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),II=Tf||Sf||oc,CI=hE||typeof navigator<"u"&&"gpu"in navigator,PI=typeof navigator<"u"&&"ml"in navigator,zI=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",LI=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",NI=typeof ServiceWorkerGlobalScope<"u"&&Mf&&self instanceof ServiceWorkerGlobalScope,$I=()=>{if(typeof navigator>"u")return!1;let t=(navigator.userAgent||""),r=(navigator.vendor||"").indexOf("Apple")>-1,s=!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android");return r&&s},RI=$I(),ie=Object.freeze({IS_BROWSER_ENV:Tf,IS_WEBWORKER_ENV:Sf,IS_WEB_ENV:II,IS_SERVICE_WORKER_ENV:NI,IS_DENO_WEB_RUNTIME:oc,IS_WEB_CACHE_AVAILABLE:sc,IS_WEBGPU_AVAILABLE:CI,IS_WEBNN_AVAILABLE:PI,IS_SAFARI:RI,IS_PROCESS_AVAILABLE:mE,IS_NODE_ENV:hE,IS_FS_AVAILABLE:rn,IS_PATH_AVAILABLE:_E,IS_CRYPTO_AVAILABLE:zI,IS_CHROME_AVAILABLE:LI}),Of=rn&&_E,nc="./";if(Of){let t=Object(import_meta).url;t?nc=tn.dirname(tn.dirname(TI.fileURLToPath(t))):typeof __dirname<"u"&&(nc=tn.dirname(__dirname))}var DI=Of?tn.join(nc,"/.cache/"):null,fE="/models/",FI=Of?tn.join(nc,fE):fE,BI=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,St=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),dE=St.WARNING,me={version:SI,backends:{onnx:{}},get logLevel(){return dE},set logLevel(t){dE=t,me.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Tf||Sf||oc),localModelPath:FI,useFS:rn,useBrowserCache:sc,useFSCache:rn,cacheDir:DI,useCustomCache:!1,customCache:null,useWasmCache:sc||rn,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:BI};function gE(t){return Object.keys(t).length===0}var We=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function or(t,e){t&&t(e)}var ds=class extends We{constructor(e,r){super(),this.callback=e,this.files_loading=r}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let r=Object.values(this.files_loading).reduce((o,a)=>o+a.loaded,0),s=Object.values(this.files_loading).reduce((o,a)=>o+a.total,0),n=s>0?r/s*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:r,total:s,files:structuredClone(this.files_loading)})}this.callback(e)}};function wE(t){return Number.isInteger(t)||typeof t=="bigint"}function If(t){return t==null||t===-1}function Cf(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function gt(...t){return Array.prototype.concat.apply([],t)}function xE(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function sn(t,e){return Math.abs((t+e)%(2*e)-e)}function Ve(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function yE(t,e){let r=0;for(let s of t)s===e&&++r;return r}var ee={error(...t){me.logLevel<=St.ERROR&&console.error(...t)},warn(...t){me.logLevel<=St.WARNING&&console.warn(...t)},info(...t){me.logLevel<=St.INFO&&console.log(...t)},debug(...t){me.logLevel<=St.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var UI=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let s=e;for(let n=0;ns&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),r=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+r),r+=1);let s=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,s[o]]))})(),qI=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),WI=qI(SE),vE=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",VI=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${vE}])]+`,` ?[^\\s${vE}]+`]]),ac="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",zf=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),ic=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[s,n]of VI)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1,o=r.replace(/(\\[pP])\{([^}=]+)\}/g,(a,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(o,"gu")}catch{throw s}}}else if(t.String!==void 0){let r=HI(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},HI=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),XI=(t,e,r)=>{let s=[],n=0;for(;nt>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,YI=t=>Number.isInteger(t)||typeof t=="bigint",QI=t=>{let e=0;for(let r of t)++e;return e},JI=t=>OE(t.toLowerCase()),Vt=(...t)=>Array.prototype.concat.apply([],t),Lf=t=>new Map(Object.entries(t)),ZI=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s0&&r.push(o),s=n.index+o.length}return st.replace(/\p{M}/gu,""),kE=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let s of r)if(!(s in t))return`${e} must contain a "${s}" property`;return null},eC=t=>t.match(/\S+/g)||[],tC=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},co=tC,rC=class extends co{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},xr=rC,sC=class extends xr{tokenize_chinese_chars(t){let e=[];for(let r=0;rr.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},aC=oC,iC=class extends xr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>IE(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},lC=iC,cC=class extends xr{normalize(t){let e=ic(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},uC=cC,pC=class extends xr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},lc=pC,fC=class extends lc{constructor(){super(...arguments),this.form="NFC"}},dC=fC,_C=class extends lc{constructor(){super(...arguments),this.form="NFD"}},mC=_C,hC=class extends lc{constructor(){super(...arguments),this.form="NFKC"}},gC=hC,wC=class extends lc{constructor(){super(...arguments),this.form="NFKD"}},xC=wC,yC=class extends xr{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},bC=yC,vC=class extends xr{normalize(t){return OE(t)}},kC=vC,EC=class extends xr{normalize(t){return t.toLowerCase()}},AC=EC,MC=class extends xr{normalize(t){return t=this.config.prepend+t,t}},TC=MC;function SC(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new nC(t);case"Precompiled":return new aC(t);case"Sequence":return new lC(t);case"Replace":return new uC(t);case"NFC":return new dC(t);case"NFD":return new mC(t);case"NFKC":return new gC(t);case"NFKD":return new xC(t);case"Strip":return new bC(t);case"StripAccents":return new kC(t);case"Lowercase":return new AC(t);case"Prepend":return new TC(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var IE=SC,OC=class extends co{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},Ht=OC,IC=class extends Ht{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=SE,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(s=>Array.from(this.text_encoder.encode(s),n=>this.byte_encoder[n]).join(""))}},CC=IC,PC=class extends Ht{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},zC=PC,LC=class extends Ht{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},s=t.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},NC=LC,$C=class extends Ht{constructor(t){super(),this.config=t,this.pattern=ic(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):ZI(t,this.pattern)}},RC=$C,DC=class extends Ht{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${ac}]+|[${ac}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},FC=DC,BC=class extends Ht{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},UC=BC,jC=class extends Ht{constructor(){super(),this.pattern=new RegExp(`[^\\s${ac}]+|[${ac}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},GC=jC,qC=class extends Ht{constructor(t){super(),this.config=t,this.pattern=ic(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},WC=qC,VC=class extends Ht{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>CE(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},HC=VC,XC=class extends Ht{pre_tokenize_text(t){return eC(t)}},KC=XC,YC=class extends Ht{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let r=0;rthis.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,a=[];for(;o0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){n=!0;break}a.push(l),o=i}n?e.push(this.unk_token):e.push(...a)}return e}},EE=eP,AE=class PE{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new PE(!1,new Map)}},tP=class{constructor(){this.root=AE.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let s=e.children.get(r);s===void 0&&(s=AE.default(),e.children.set(r,s)),e=s}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let s of t){if(r+=s,e=e.children.get(s),e===void 0)return;e.is_leaf&&(yield r)}}},rP=tP,Pf=class zE{constructor(e,r,s,n,o){this.token_id=e,this.node_id=r,this.pos=s,this.length=n,this.score=o,this.prev=null,this.backtrace_score=0}clone(){let e=new zE(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},sP=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let s=new Pf(this.bos_token_id??0,0,0,0,0),n=new Pf(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(s)}insert(t,e,r,s){let n=this.nodes.length,o=new Pf(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let c of this.end_nodes[e]){let p=c.backtrace_score+a.score;(l===null||p>i)&&(l=c.clone(),i=p)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},nP=sP;function oP(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=oP(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new rP,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,s=0;for(;sr>s,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},uP=cP,pP=class extends cc{constructor(t){super(t),this.tokens_to_ids=Lf(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,s]of this.tokens_to_ids)this.vocab[s]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,s)=>[JSON.stringify(r),s])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new uP(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){let n=new lP((i,l)=>i.score`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);o.every(a=>this.tokens_to_ids.has(a))?e.push(...o):this.unk_token!=null&&e.push(this.unk_token)}else this.unk_token!=null&&e.push(this.unk_token)}return e}},TE=pP,fP=class extends cc{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=Lf(e.target_lang?r[e.target_lang]:r),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[s,n]of this.tokens_to_ids)this.vocab[n]=s}encode(t){return t}},dP=fP;function _P(t,e){switch(t.type){case"WordPiece":return new EE(t);case"Unigram":return new ME(t,e.eos_token);case"BPE":return new TE(t);default:if(t.vocab)return Array.isArray(t.vocab)?new ME(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new TE(t):new EE(t):new dP(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var mP=_P,hP=class extends co{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},uo=hP,gP=class extends uo{post_process(t,e=null,r=!0){let s=e===null?this.config.single:this.config.pair,n=[],o=[];for(let a of s)"SpecialToken"in a?r&&(n.push(a.SpecialToken.id),o.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(n=Vt(n,t),o=Vt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Vt(n,e),o=Vt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},wP=gP,xP=class extends uo{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},yP=xP,bP=class extends uo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Vt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=[],o=r?[this.sep[0]]:[];t=Vt(t,n,e,o),s=Vt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},vP=bP,kP=class extends uo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Vt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=r?[this.sep[0]]:[],o=r?[this.sep[0]]:[];t=Vt(t,n,e,o),s=Vt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},EP=kP,AP=class extends uo{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>LE(e))}post_process(t,e=null,r=!0){let s={tokens:t,tokens_pair:e};for(let n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},MP=AP;function TP(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new wP(t);case"ByteLevel":return new yP(t);case"BertProcessing":return new vP(t);case"RobertaProcessing":return new EP(t);case"Sequence":return new MP(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var LE=TP,SP=class extends co{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Dt=SP,OP=class extends Dt{constructor(t){super(t),this.byte_decoder=WI,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),r=new Uint8Array([...e].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let s of t)this.added_tokens.find(n=>n.content===s)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(s)):r.push(s);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},IP=OP,CP=class extends Dt{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let s=this.config.prefix;s&&e.startsWith(s)?e=e.replace(s,""):e=" "+e}return this.cleanup&&(e=zf(e)),e})}},PP=CP,zP=class extends Dt{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;re.replaceAll(this.suffix,r===t.length-1?"":" "))}},$P=NP,RP=class extends Dt{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;nn!==this.pad_token).join("");return this.cleanup&&(s=zf(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},DP=RP,FP=class extends Dt{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>NE(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},BP=FP,UP=class extends Dt{decode_chain(t){let e=ic(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},jP=UP,GP=class extends Dt{decode_chain(t){return[t.join("")]}},qP=GP,WP=class extends Dt{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n")){let o=parseInt(s.slice(3,5),16);isNaN(o)||(n=o)}if(n!==null)r.push(n);else{if(r.length>0){let o=this.text_decoder.decode(Uint8Array.from(r));e.push(o),r=[]}e.push(s)}}if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}return e}},XP=HP;function KP(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new IP(t);case"WordPiece":return new PP(t);case"Metaspace":return new LP(t);case"BPEDecoder":return new $P(t);case"CTC":return new DP(t);case"Sequence":return new BP(t);case"Replace":return new jP(t);case"Fuse":return new qP(t);case"Strip":return new VP(t);case"ByteFallback":return new XP(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var NE=KP,YP=class{constructor(t,e){let r=kE(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=kE(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=IE(this.tokenizer.normalizer),this.pre_tokenizer=CE(this.tokenizer.pre_tokenizer),this.model=mP(this.tokenizer.model,this.config),this.post_processor=LE(this.tokenizer.post_processor),this.decoder=NE(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let n=[],o=[];this.added_tokens_map=new Map;for(let a of this.tokenizer.added_tokens){let i=new GI(a);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){let l=this.normalizer(i.content);o.push(l),this.added_tokens_map.set(l,i)}else n.push(i.content)}(this.config.additional_special_tokens??[]).forEach(a=>{this.special_tokens.includes(a)||this.special_tokens.push(a)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new bE(n),this.splitter_normalized=new bE(o),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){let{tokens:n,token_type_ids:o}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),a=n.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:a,tokens:n,attention_mask:new Array(a.length).fill(1)};return s&&o&&(i.token_type_ids=o),i}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!YI(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=t.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);e.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let s=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(s=s.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=zf(s)),s}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((r,s)=>{let n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(e[s-1]=e[s-1].trimEnd()),n.rstrip&&s{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=JI(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let n=this.splitter_normalized.split(r);return n.forEach((o,a)=>{let i=this.added_tokens_map.get(o);i&&(i.lstrip&&a>0&&(n[a-1]=n[a-1].trimEnd()),i.rstrip&&a{if(o.length===0)return[];if(this.added_tokens_map.has(o))return[o];let a=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:s}):[o];return this.model(a)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let s=this.encode_text(t),n=this.encode_text(e||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Vt(s??[],n??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let r=0;r=",D.ComparisonBinaryOperator],["==",D.ComparisonBinaryOperator],["!=",D.ComparisonBinaryOperator],["<",D.ComparisonBinaryOperator],[">",D.ComparisonBinaryOperator],["+",D.AdditiveBinaryOperator],["-",D.AdditiveBinaryOperator],["~",D.AdditiveBinaryOperator],["*",D.MultiplicativeBinaryOperator],["/",D.MultiplicativeBinaryOperator],["%",D.MultiplicativeBinaryOperator],["=",D.Equals]],JP=new Map([["n",` + `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function ZP(t,e={}){return t.endsWith(` + `)&&(t=t.slice(0,-1)),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%-])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%-]})\n/g,"$1")),t.replace(/{%\s*(end)?generation\s*%}/gs,"")}function ez(t,e={}){let r=[],s=ZP(t,e),n=0,o=0,a=c=>{let p="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],_=JP.get(f);if(_===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);p+=_;continue}if(p+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return p},i=()=>{let c=r.at(-1);c&&c.type===D.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n0){r.push(new Ft(f,D.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let f=s[n]==="-";f&&++n;let _="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");_+=s[n++]}let m=_.endsWith("-");m&&(_=_.slice(0,-1)),f&&i(),r.push(new Ft(_,D.Comment)),n+=2,m&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Ft("{%",D.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Ft("{{",D.OpenExpression)),o=0,n+=3;continue}if(a(DE),s.slice(n,n+3)==="-%}"){r.push(new Ft("%}",D.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Ft("}}",D.CloseExpression)),n+=3,l();continue}let p=s[n];if(p==="-"||p==="+"){let f=r.at(-1)?.type;if(f===D.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(f){case D.Identifier:case D.NumericLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++n;let _=a(po);r.push(new Ft(`${p}${_}`,_.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(let[f,_]of QP){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new Ft(f,_)),_===D.OpenExpression?o=0:_===D.OpenCurlyBracket?++o:_===D.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(p==="'"||p==='"'){++n;let f=a(_=>_!==p);r.push(new Ft(f,D.StringLiteral)),++n;continue}if(po(p)){let f=a(po);if(s[n]==="."&&po(s[n+1])){++n;let _=a(po);f=`${f}.${_}`}r.push(new Ft(f,D.NumericLiteral));continue}if(RE(p)){let f=a(RE);r.push(new Ft(f,D.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return r}var Kt=class{type="Statement"},tz=class extends Kt{constructor(t){super(),this.body=t}type="Program"},rz=class extends Kt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},sz=class extends Kt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},nz=class extends Kt{type="Break"},oz=class extends Kt{type="Continue"},az=class extends Kt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},iz=class extends Kt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},lz=class extends Kt{constructor(t){super(),this.value=t}type="Comment"},Ct=class extends Kt{type="Expression"},cz=class extends Ct{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},FE=class extends Ct{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},nn=class extends Ct{constructor(t){super(),this.value=t}type="Identifier"},on=class extends Ct{constructor(t){super(),this.value=t}type="Literal"},uz=class extends on{type="IntegerLiteral"},pz=class extends on{type="FloatLiteral"},BE=class extends on{type="StringLiteral"},fz=class extends on{type="ArrayLiteral"},UE=class extends on{type="TupleLiteral"},dz=class extends on{type="ObjectLiteral"},fo=class extends Ct{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},_z=class extends Ct{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},mz=class extends Kt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},hz=class extends Ct{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},gz=class extends Ct{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},wz=class extends Ct{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},xz=class extends Ct{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},yz=class extends Ct{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},bz=class extends Ct{constructor(t){super(),this.argument=t}type="SpreadExpression"},vz=class extends Kt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},kz=class extends Ct{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function Ez(t){let e=new tz([]),r=0;function s(z,$){let B=t[r++];if(!B||B.type!==z)throw new Error(`Parser Error: ${$}. ${B.type} !== ${z}.`);return B}function n(z){if(!l(z))throw new SyntaxError(`Expected ${z}`);++r}function o(){switch(t[r].type){case D.Comment:return new lz(t[r++].value);case D.Text:return c();case D.OpenStatement:return p();case D.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...z){return r+z.length<=t.length&&z.every(($,B)=>$===t[r+B].type)}function i(...z){return t[r]?.type===D.OpenStatement&&t[r+1]?.type===D.Identifier&&z.includes(t[r+1]?.value)}function l(...z){return r+z.length<=t.length&&z.every(($,B)=>t[r+B].type==="Identifier"&&$===t[r+B].value)}function c(){return new BE(s(D.Text,"Expected text token").value)}function p(){if(s(D.OpenStatement,"Expected opening statement token"),t[r].type!==D.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let z=t[r].value,$;switch(z){case"set":++r,$=_();break;case"if":++r,$=m(),s(D.OpenStatement,"Expected {% token"),n("endif"),s(D.CloseStatement,"Expected %} token");break;case"macro":++r,$=w(),s(D.OpenStatement,"Expected {% token"),n("endmacro"),s(D.CloseStatement,"Expected %} token");break;case"for":++r,$=k(),s(D.OpenStatement,"Expected {% token"),n("endfor"),s(D.CloseStatement,"Expected %} token");break;case"call":{++r;let B=null;a(D.OpenParen)&&(B=U());let Q=Y();if(Q.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let le=U();s(D.CloseStatement,"Expected closing statement token");let Ge=[];for(;!i("endcall");)Ge.push(o());s(D.OpenStatement,"Expected '{%'"),n("endcall"),s(D.CloseStatement,"Expected closing statement token");let ce=new FE(Q,le);$=new vz(ce,B,Ge);break}case"break":++r,s(D.CloseStatement,"Expected closing statement token"),$=new nz;break;case"continue":++r,s(D.CloseStatement,"Expected closing statement token"),$=new oz;break;case"filter":{++r;let B=Y();B instanceof nn&&a(D.OpenParen)&&(B=j(B)),s(D.CloseStatement,"Expected closing statement token");let Q=[];for(;!i("endfilter");)Q.push(o());s(D.OpenStatement,"Expected '{%'"),n("endfilter"),s(D.CloseStatement,"Expected '%}'"),$=new mz(B,Q);break}default:throw new SyntaxError(`Unknown statement type: ${z}`)}return $}function f(){s(D.OpenExpression,"Expected opening expression token");let z=A();return s(D.CloseExpression,"Expected closing expression token"),z}function _(){let z=x(),$=null,B=[];if(a(D.Equals))++r,$=x();else{for(s(D.CloseStatement,"Expected %} token");!i("endset");)B.push(o());s(D.OpenStatement,"Expected {% token"),n("endset")}return s(D.CloseStatement,"Expected closing statement token"),new az(z,$,B)}function m(){let z=A();s(D.CloseStatement,"Expected closing statement token");let $=[],B=[];for(;!i("elif","else","endif");)$.push(o());if(i("elif")){++r,++r;let Q=m();B.push(Q)}else if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endif");)B.push(o());return new rz(z,$,B)}function w(){let z=Y();if(z.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let $=U();s(D.CloseStatement,"Expected closing statement token");let B=[];for(;!i("endmacro");)B.push(o());return new iz(z,$,B)}function x(z=!1){let $=z?Y:A,B=[$()],Q=a(D.Comma);for(;Q&&(++r,B.push($()),!!a(D.Comma)););return Q?new UE(B):B[0]}function k(){let z=x(!0);if(!(z instanceof nn||z instanceof UE))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${z.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let $=A();s(D.CloseStatement,"Expected closing statement token");let B=[];for(;!i("endfor","else");)B.push(o());let Q=[];if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endfor");)Q.push(o());return new sz(z,$,B,Q)}function A(){return E()}function E(){let z=S();if(l("if")){++r;let $=S();if(l("else")){++r;let B=E();return new kz($,z,B)}else return new hz(z,$)}return z}function S(){let z=T();for(;l("or");){let $=t[r];++r;let B=T();z=new fo($,z,B)}return z}function T(){let z=I();for(;l("and");){let $=t[r];++r;let B=I();z=new fo($,z,B)}return z}function I(){let z;for(;l("not");){let $=t[r];++r;let B=I();z=new wz($,B)}return z??O()}function O(){let z=b();for(;;){let $;if(l("not","in"))$=new Ft("not in",D.Identifier),r+=2;else if(l("in"))$=t[r++];else if(a(D.ComparisonBinaryOperator))$=t[r++];else break;let B=b();z=new fo($,z,B)}return z}function b(){let z=R();for(;a(D.AdditiveBinaryOperator);){let $=t[r];++r;let B=R();z=new fo($,z,B)}return z}function F(){let z=J(Y());return a(D.OpenParen)?j(z):z}function j(z){let $=new FE(z,U());return $=J($),a(D.OpenParen)&&($=j($)),$}function U(){s(D.OpenParen,"Expected opening parenthesis for arguments list");let z=X();return s(D.CloseParen,"Expected closing parenthesis for arguments list"),z}function X(){let z=[];for(;!a(D.CloseParen);){let $;if(t[r].type===D.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let B=A();$=new bz(B)}else if($=A(),a(D.Equals)){if(++r,!($ instanceof nn))throw new SyntaxError("Expected identifier for keyword argument");let B=A();$=new yz($,B)}z.push($),a(D.Comma)&&++r}return z}function K(){let z=[],$=!1;for(;!a(D.CloseSquareBracket);)a(D.Colon)?(z.push(void 0),++r,$=!0):(z.push(A()),a(D.Colon)&&(++r,$=!0));if(z.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if($){if(z.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new xz(...z)}return z[0]}function J(z){for(;a(D.Dot)||a(D.OpenSquareBracket);){let $=t[r];++r;let B,Q=$.type===D.OpenSquareBracket;if(Q)B=K(),s(D.CloseSquareBracket,"Expected closing square bracket");else if(B=Y(),B.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");z=new cz(z,B,Q)}return z}function R(){let z=C();for(;a(D.MultiplicativeBinaryOperator);){let $=t[r++],B=C();z=new fo($,z,B)}return z}function C(){let z=se();for(;l("is");){++r;let $=l("not");$&&++r;let B=Y();if(!(B instanceof nn))throw new SyntaxError("Expected identifier for the test");z=new gz(z,$,B)}return z}function se(){let z=F();for(;a(D.Pipe);){++r;let $=Y();if(!($ instanceof nn))throw new SyntaxError("Expected identifier for the filter");a(D.OpenParen)&&($=j($)),z=new _z(z,$)}return z}function Y(){let z=t[r++];switch(z.type){case D.NumericLiteral:{let $=z.value;return $.includes(".")?new pz(Number($)):new uz(Number($))}case D.StringLiteral:{let $=z.value;for(;a(D.StringLiteral);)$+=t[r++].value;return new BE($)}case D.Identifier:return new nn(z.value);case D.OpenParen:{let $=x();return s(D.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),$}case D.OpenSquareBracket:{let $=[];for(;!a(D.CloseSquareBracket);)$.push(A()),a(D.Comma)&&++r;return++r,new fz($)}case D.OpenCurlyBracket:{let $=new Map;for(;!a(D.CloseCurlyBracket);){let B=A();s(D.Colon,"Expected colon between key and value in object literal");let Q=A();$.set(B,Q),a(D.Comma)&&++r}return++r,new dz($)}default:throw new SyntaxError(`Unexpected token: ${z.type}`)}}for(;r0)for(let n=t;ne;n+=r)s.push(n);return s}function jE(t,e,r,s=1){let n=Math.sign(s);n>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));let o=[];for(let a=e;n*ae.toUpperCase())}function Tz(t){return Sz(new Date,t)}function Sz(t,e){let r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),n=o=>o<10?"0"+o:o.toString();return e.replace(/%[YmdbBHM%]/g,o=>{switch(o){case"%Y":return t.getFullYear().toString();case"%m":return n(t.getMonth()+1);case"%d":return n(t.getDate());case"%b":return s.format(t);case"%B":return r.format(t);case"%H":return n(t.getHours());case"%M":return n(t.getMinutes());case"%%":return"%";default:return o}})}function Oz(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Iz(t,e,r,s){if(s===0)return t;let n=s==null||s<0?1/0:s,o=e.length===0?new RegExp("(?=)","gu"):new RegExp(Oz(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var GE=class extends Error{},qE=class extends Error{},ar=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new de(!!this.value)}toString(){return String(this.value)}},he=class extends ar{type="IntegerValue"},Ze=class extends ar{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},te=class extends ar{type="StringValue";builtins=new Map([["upper",new Xe(()=>new te(this.value.toUpperCase()))],["lower",new Xe(()=>new te(this.value.toLowerCase()))],["strip",new Xe(()=>new te(this.value.trim()))],["title",new Xe(()=>new te(Mz(this.value)))],["capitalize",new Xe(()=>new te(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new he(this.value.length)],["rstrip",new Xe(()=>new te(this.value.trimEnd()))],["lstrip",new Xe(()=>new te(this.value.trimStart()))],["startswith",new Xe(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof te)return new de(this.value.startsWith(e.value));if(e instanceof ye){for(let r of e.value){if(!(r instanceof te))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new de(!0)}return new de(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Xe(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof te)return new de(this.value.endsWith(e.value));if(e instanceof ye){for(let r of e.value){if(!(r instanceof te))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new de(!0)}return new de(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Xe(t=>{let e=t[0]??new Ke;if(!(e instanceof te||e instanceof Ke))throw new Error("sep argument must be a string or null");let r=t[1]??new he(-1);if(!(r instanceof he))throw new Error("maxsplit argument must be a number");let s=[];if(e instanceof Ke){let n=this.value.trimStart();for(let{0:o,index:a}of n.matchAll(/\S+/g)){if(r.value!==-1&&s.length>=r.value&&a!==void 0){s.push(o+n.slice(a+o.length));break}s.push(o)}}else{if(e.value==="")throw new Error("empty separator");s=this.value.split(e.value),r.value!==-1&&s.length>r.value&&s.push(s.splice(r.value).join(e.value))}return new ye(s.map(n=>new te(n)))})],["replace",new Xe(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],r=t[1];if(!(e instanceof te&&r instanceof te))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new Ke:s=t[2]:s=new Ke,!(s instanceof he||s instanceof Ke))throw new Error("replace() count argument must be a number or null");return new te(Iz(this.value,e.value,r.value,s.value))})]])},de=class extends ar{type="BooleanValue"},Cz=/[\x7f-\uffff]/g;function WE(t){return t.replace(Cz,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function ms(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,c;switch(a?[l,c]=a:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let p=JSON.stringify(t.value);return o&&(p=WE(p)),p}case"ArrayValue":case"ObjectValue":{let p=n?" ".repeat(n):"",f=` +@@ -7,10 +7,10 @@ var AI=Object.defineProperty;var fs=(t=>typeof require<"u"?require:typeof Proxy< + `));case"join":case"string":return t;case"int":{let n=parseInt(t.value,10);return new he(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new Ze(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof he||t instanceof Ze)switch(s.value){case"abs":return t instanceof he?new he(Math.abs(t.value)):new Ze(Math.abs(t.value));case"int":return new he(Math.floor(t.value));case"float":return new Ze(t.value);case"string":return new te(t.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(t instanceof ft)switch(s.value){case"items":return new ye(Array.from(t.value.entries()).map(([n,o])=>new ye([new te(n),o])));case"length":return new he(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof Xe?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(t instanceof de)switch(s.value){case"bool":return new de(t.value);case"int":return new he(t.value?1:0);case"float":return new Ze(t.value?1:0);case"string":return new te(t.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${t.type}`)}else if(e.type==="CallExpression"){let s=e;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);let n=s.callee.value;if(n==="tojson"){let[,o]=this.evaluateArguments(s.args,r),a=o.get("indent")??new Ke;if(!(a instanceof he||a instanceof Ke))throw new Error("If set, indent must be a number");let i=o.get("ensure_ascii")??new de(!1);if(!(i instanceof de))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new de(!1);if(!(l instanceof de))throw new Error("If set, sort_keys must be a boolean");let c=o.get("separators")??new Ke,p=null;if(c instanceof ye||c instanceof VE){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,_]=c.value;if(!(f instanceof te)||!(_ instanceof te))throw new Error("separators must be a tuple of two strings");p=[f.value,_.value]}else if(!(c instanceof Ke))throw new Error("If set, separators must be a tuple of two strings");return new te(ms(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:p}))}else if(n==="join"){let o;if(t instanceof te)o=Array.from(t.value);else if(t instanceof ye)o=t.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[a,i]=this.evaluateArguments(s.args,r),l=a.at(0)??i.get("separator")??new te("");if(!(l instanceof te))throw new Error("separator must be a string");return new te(o.join(l.value))}else if(n==="int"||n==="float"){let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("default")??(n==="int"?new he(0):new Ze(0));if(t instanceof te){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new he(l):new Ze(l)}else{if(t instanceof he||t instanceof Ze)return t;if(t instanceof de)return n==="int"?new he(t.value?1:0):new Ze(t.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}}else if(n==="default"){let[o,a]=this.evaluateArguments(s.args,r),i=o[0]??new te(""),l=o[1]??a.get("boolean")??new de(!1);if(!(l instanceof de))throw new Error("`default` filter flag must be a boolean");return t instanceof He||l.value&&!t.__bool__().value?i:t}if(t instanceof ye){switch(n){case"sort":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("reverse")??new de(!1);if(!(i instanceof de))throw new Error("reverse must be a boolean");let l=o.at(1)??a.get("case_sensitive")??new de(!1);if(!(l instanceof de))throw new Error("case_sensitive must be a boolean");let c=o.at(2)??a.get("attribute")??new Ke;if(!(c instanceof te||c instanceof he||c instanceof Ke))throw new Error("attribute must be a string, integer, or null");let p=f=>{if(c instanceof Ke)return f;let _=c instanceof he?String(c.value):c.value;return HE(f,_)};return new ye(t.value.slice().sort((f,_)=>{let m=p(f),w=p(_),x=Nf(m,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!(f instanceof ft)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[a,i,l]=s.args.map(f=>this.evaluate(f,r)),c;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);c=f}else c=(...f)=>f[0].__bool__().value;let p=t.value.filter(f=>{let _=f.value.get(a.value),m=_?c(_,l):!1;return o?m:!m});return new ye(p)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof te))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(c=>{if(!(c instanceof ft))throw new Error("items in map must be an object");let p=HE(c,a.value);return p instanceof He?i??new He:p});return new ye(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof te){switch(n){case"indent":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("width")??new he(4);if(!(i instanceof he))throw new Error("width must be a number");let l=o.at(1)??a.get("first")??new de(!1),c=o.at(2)??a.get("blank")??new de(!1),p=t.value.split(` + `),f=" ".repeat(i.value),_=p.map((m,w)=>!l.value&&w===0||!c.value&&m.length===0?m:f+m);return new te(_.join(` + `))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof Xe))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new _o(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof ft){let o=t.builtins.get(n);if(o&&o instanceof Xe){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new _o(i)),o.value(a,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}throw new Error(`Unknown filter: ${e.type}`)}evaluateFilterExpression(t,e){let r=this.evaluate(t.operand,e);return this.applyFilter(r,t.filter,e)}evaluateTestExpression(t,e){let r=this.evaluate(t.operand,e),s=e.tests.get(t.test.value);if(!s)throw new Error(`Unknown test: ${t.test.value}`);let n=s(r);return new de(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new He}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);if(t.operator.value==="not")return new de(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evaluateTernaryExpression(t,e){return this.evaluate(t.condition,e).__bool__().value?this.evaluate(t.trueExpr,e):this.evaluate(t.falseExpr,e)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(let s of t){let n=this.evaluate(s,e);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new te(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){let[r,s]=this.evaluateArguments(t.args,e);s.size>0&&r.push(new _o(s));let n=this.evaluate(t.callee,e);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof ye||t instanceof te))throw new Error("Slice object must be an array or string");let s=this.evaluate(e.start,r),n=this.evaluate(e.stop,r),o=this.evaluate(e.step,r);if(!(s instanceof he||s instanceof He))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof he||n instanceof He))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof he||o instanceof He))throw new Error("Slice step must be numeric or undefined");return t instanceof ye?new ye(jE(t.value,s.value,n.value,o.value)):new te(jE(Array.from(t.value),s.value,n.value,o.value).join(""))}evaluateMemberExpression(t,e){let r=this.evaluate(t.object,e),s;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);s=this.evaluate(t.property,e)}else s=new te(t.property.value);let n;if(r instanceof ft){if(!(s instanceof te))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof ye||r instanceof te)if(s instanceof he)n=r.value.at(s.value),r instanceof te&&(n=new te(r.value.at(s.value)));else if(s instanceof te)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof te))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof ar?n:new He}evaluateSet(t,e){let r=t.value?this.evaluate(t.value,e):this.evaluateBlock(t.body,e);if(t.assignee.type==="Identifier"){let s=t.assignee.value;e.setVariable(s,r)}else if(t.assignee.type==="TupleLiteral"){let s=t.assignee;if(!(r instanceof ye))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let o=0;om.setVariable(t.loopvar.value,f);else if(t.loopvar.type==="TupleLiteral"){let m=t.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);let w=f;if(m.value.length!==w.value.length)throw new Error(`Too ${m.value.length>w.value.length?"few":"many"} items to unpack`);_=x=>{for(let k=0;k0?o[c-1]:new He],["nextitem",c{let n=new _s(s);r=r.slice();let o;r.at(-1)?.type==="KeywordArgumentsValue"&&(o=r.pop());for(let a=0;a{let c=new _s(l);if(t.callerArgs)for(let p=0;pthis.evaluate(r,e)));case"TupleLiteral":return new VE(t.value.map(r=>this.evaluate(r,e)));case"ObjectLiteral":{let r=new Map;for(let[s,n]of t.value){let o=this.evaluate(s,e);if(!(o instanceof te))throw new Error(`Object keys must be strings: got ${o.type}`);r.set(o.value,this.evaluate(n,e))}return new ft(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"FilterStatement":return this.evaluateFilterStatement(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);case"SelectExpression":return this.evaluateSelectExpression(t,e);case"Ternary":return this.evaluateTernaryExpression(t,e);case"Comment":return new Ke;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function uc(t){switch(typeof t){case"number":return Number.isInteger(t)?new he(t):new Ze(t);case"string":return new te(t);case"boolean":return new de(t);case"undefined":return new He;case"object":return t===null?new Ke:Array.isArray(t)?new ye(t.map(uc)):new ft(new Map(Object.entries(t).map(([e,r])=>[e,uc(r)])));case"function":return new Xe((e,r)=>{let s=t(...e.map(n=>n.value))??null;return uc(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var at=` +-`,Lz="{%- ",Nz=" -%}";function $z(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function Rz(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Xt(t.body,0,r).replace(/\n$/,"")}function wt(...t){return Lz+t.join(" ")+Nz}function Xt(t,e,r){return t.map(s=>Dz(s,e,r)).join(at)}function Dz(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Xt(t.body,e,r);case"If":return Fz(t,e,r);case"For":return Bz(t,e,r);case"Set":return Uz(t,e,r);case"Macro":return jz(t,e,r);case"Break":return s+wt("break");case"Continue":return s+wt("continue");case"CallStatement":return Gz(t,e,r);case"FilterStatement":return qz(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function Fz(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+wt("if",ke(n[0].test))+at+Xt(n[0].body,e+1,r);for(let i=1;i0&&(a+=at+s+wt("else")+at+Xt(o.alternate,e+1,r)),a+=at+s+wt("endif"),a}function Bz(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+wt("for",ke(t.loopvar),"in",n)+at+Xt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=at+s+wt("else")+at+Xt(t.defaultBlock,e+1,r)),o+=at+s+wt("endfor"),o}function Uz(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+wt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+at+Xt(t.body,e+1,r)+at+s+wt("endset")}function jz(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+wt("macro",`${t.name.value}(${n})`)+at+Xt(t.body,e+1,r)+at+s+wt("endmacro")}function Gz(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+wt(`call${n}`,o)+at;return a+=Xt(t.body,e+1,r)+at,a+=s+wt("endcall"),a}function qz(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+wt("filter",n)+at;return o+=Xt(t.body,e+1,r)+at,o+=s+wt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=$z(r),n=ke(r.left,s),o=ke(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var XE=class{parsed;constructor(t){let e=ez(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Ez(e)}render(t){let e=new _s;if(Pz(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new zz(e).run(this.parsed).value}format(t){return Rz(this.parsed,t?.indent||" ")}};import an from"fs";var Wz={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"},Or=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=an.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=an.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=an.createReadStream(e);this.body=new ReadableStream({start(n){s.on("data",o=>n.enqueue(o)),s.on("end",()=>n.close()),s.on("error",o=>n.error(o))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",Wz[e]??"application/octet-stream")}clone(){let e=new t(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await an.promises.readFile(this.filePath)).buffer}async blob(){let e=await an.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await an.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};import mo from"fs";import pc from"path";var Ir=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(ie.IS_CRYPTO_AVAILABLE){let i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;let r=this._mt,s=(i,l)=>Math.imul(i,l)>>>0,n=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))n.push(i&4294967295);n.length||n.push(0),r[0]=19650218;for(let i=1;i<624;++i)r[i]=s(1812433253,r[i-1]^r[i-1]>>>30)+i>>>0;let o=1,a=0;for(let i=Math.max(624,n.length);i>0;--i,++o,++a)o>=624&&(r[0]=r[623],o=1),a>=n.length&&(a=0),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1664525))+n[a]+a>>>0;for(let i=623;i>0;--i,++o)o>=624&&(r[0]=r[623],o=1),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1566083941))-o>>>0;r[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let s=0;s<624;++s){let n=e[s]&2147483648|e[(s+1)%624]&2147483647;e[s]=(e[(s+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let r=e[this._idx++];return r^=r>>>11,r^=r<<7&2636928640,r^=r<<15&4022730752,r^=r>>>18,r>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,r=1){let s=this._gauss_next;if(this._gauss_next=null,s===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+s*r}shuffle(e){for(let r=e.length-1;r>0;--r){let s=32-Math.clz32(r+1),n=this._int32()>>>32-s;for(;n>r;)n=this._int32()>>>32-s;let o=e[r];e[r]=e[n],e[n]=o}}choices(e,r){return e[KE(this._random_fn,r)]}};function KE(t,e){let r=0;for(let n=0;nKE(hs.random,t);var Vz=new Ir,ln=class{constructor(e){this.path=e}async match(e){let r=pc.join(this.path,e),s=new Or(r);if(s.exists)return s}async put(e,r,s=void 0){let n=pc.join(this.path,e),o=ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=Vz._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),p=0;await mo.promises.mkdir(pc.dirname(n),{recursive:!0});let f=mo.createWriteStream(i),_=r.body.getReader();for(;;){let{done:m,value:w}=await _.read();if(m)break;await new Promise((k,A)=>{f.write(w,E=>{if(E){A(E);return}k()})}),p+=w.length;let x=c?p/c*100:0;s?.({progress:x,loaded:p,total:c})}await new Promise((m,w)=>{f.close(x=>x?w(x):m())}),await mo.promises.rename(i,n)}catch(l){try{await mo.promises.unlink(i)}catch{}throw l}}async delete(e){let r=pc.join(this.path,e);try{return await mo.promises.unlink(r),!0}catch{return!1}}};var QE={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"},fc=100,JE=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function ho(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function Cr(t,e=null,r=null){let s;try{s=new URL(t)}catch{return!1}return!(e&&!e.includes(s.protocol)||r&&!r.includes(s.hostname))}function ZE(t){return!(!JE.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function eA(t,e,r){if(!r)return null;let s=QE[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function tA(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&ee.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:p}=await i.read();if(c)return;let f=a+p.length;if(f>n){n=f;let m=new Uint8Array(n);m.set(o),o=m}o.set(p,a),a=f;let _=a/n*100;return e({progress:_,loaded:a,total:n}),l()}return await l(),o}function $f(t){return Cr(t,["blob:"])}function Rf(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof import.meta<"u"&&import.meta.url)e=import.meta.url;else return t;return new URL(t,e).href}var sA="SHA-256",Hz="experimental_transformers-hash-cache",rA=t=>({algorithm:sA,value:t}),go=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(Hz),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let r=await this._getFileHash(e);if(r)try{let[s]=await navigator.crossOriginStorage.requestFileHandles([rA(r)]),n=await s.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,r)=>{let s=await this._getFileHash(e);if(s){let n=await r.blob();await this._storeBlobInCOS(n,s)}else this._processAndStore(e,r.body)};_storeBlobInCOS=async(e,r)=>{let[s]=await navigator.crossOriginStorage.requestFileHandles([rA(r)],{create:!0}),n=await s.createWritable();await n.write(e),await n.close()};_processAndStore=async(e,r)=>{try{let s=[];for await(let a of r)s.push(a);let n=new Blob(s),o=await this._getBlobHash(n);await this._storeBlobInCOS(n,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let r=await this._getHashCache(),s=await r.match(e);if(s)return s.text();let n=await this._getLfsFileHash(e);return n?(await r.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let r=e.replace("/resolve/","/raw/");try{let n=(await fetch(r).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{let r=await e.arrayBuffer(),s=await crypto.subtle.digest(sA,r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function Yt(t=null){let e=null;if(me.useCustomCache){if(!me.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!me.customCache.match||!me.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=me.customCache}if(!e&&me.experimental_useCrossOriginStorage&&go.isAvailable()&&(e=new go),!e&&me.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(me.cacheKey)}catch(r){ee.warn("An error occurred while opening the browser cache:",r)}}if(!e&&me.useFSCache){if(!ie.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new ln(t??me.cacheDir)}return e}async function nA(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var dc=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let r=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,r),r}put(e,r){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,r),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};var Xz=100,Df=new dc(Xz);function _c(t,e){let r=Df.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(Df.delete(t),Promise.reject(n)));return Df.put(t,s),s}async function Kz(t){if(!Cr(t,["http:","https:"]))return null;let e=Ff(t);return e.set("Range","bytes=0-0"),me.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function Ot(t,e,r={}){let s=JSON.stringify([t,e,r?.revision,r?.cache_dir,r?.local_files_only]);return _c(s,()=>Yz(t,e,r))}async function Yz(t,e,r){let s=await Yt(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=zr(t,e,r,s),l=await Lr(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),p=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:p||void 0,fromCache:!0}}if(me.allowLocalModels&&!Cr(n,["http:","https:"]))try{let p=await Pr(n);if(typeof p!="string"&&p.status!==404){let f=p.headers.get("content-length"),_=p.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:_||void 0,fromCache:!1}}}catch{}if(me.allowRemoteModels&&!r.local_files_only&&i)try{let c=await Kz(o);if(c&&c.status>=200&&c.status<300){let p,f=c.headers.get("content-type");if(c.status===206){let _=c.headers.get("content-range");if(_){let m=_.match(/bytes \d+-\d+\/(\d+)/);m&&(p=parseInt(m[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(p===void 0){let _=c.headers.get("content-length");p=_?parseInt(_,10):void 0}return{exists:!0,size:p,contentType:f||void 0,fromCache:!1}}}catch(c){ee.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function Pr(t){return me.useFS&&!Cr(t,["http:","https:","blob:"])?new Or(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):me.fetch(t,{headers:Ff(t)})}function Ff(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=me.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),Cr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function zr(t,e,r={},s=null){let n=r.revision??"main",o=ho(t,e),a=ZE(t),i=a?ho(me.localModelPath,o):o,l=ho(me.remoteHost,me.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof ln?n==="main"?o:ho(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function Lr(t,e,r){if(t)return await nA(t,e,r)}async function Qz(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o){if(typeof n!="string"){let i=new Headers(n.headers);i.set("content-length",o.byteLength.toString()),await r.put(s,new Response(o,{headers:i})).catch(l=>{ee.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=a.progress_callback?l=>or(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function Jz(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:p}=zr(t,e,s,o),f,_=!1,m;m=await Lr(o,i,c);let w=m!==void 0;if(w)f=c;else{if(me.allowLocalModels)if(Cr(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!me.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{m=await Pr(i),f=i}catch(E){ee.warn(`Unable to load from local path "${i}": "${E}"`)}if(m===void 0||typeof m!="string"&&m.status===404){if(s.local_files_only||!me.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!p)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(m=await Pr(l),m.status!==200)return eA(m.status,l,r);f=c}_=o&&typeof Response<"u"&&m instanceof Response&&m.status===200}or(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(ie.IS_NODE_ENV&&n)){let A;if(typeof m!="string")if(!s.progress_callback)A=new Uint8Array(await m.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))A=new Uint8Array(await m.arrayBuffer()),or(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A.length,total:A.length});else{let E,S=m.headers.get("content-length");if(S)E=parseInt(S,10);else try{let T=await Ot(t,e,s);T.size&&(E=T.size)}catch{}A=await tA(m,T=>{or(s.progress_callback,{status:"progress",name:t,file:e,...T})},E)}x=A}if(_&&f&&typeof m!="string"&&await Qz(t,e,o,f,m,x,s),ie.IS_NODE_ENV&&n&&s.progress_callback&&typeof m!="string"){let A=parseInt(m.headers.get("content-length"),10)||0;or(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A,total:A})}if(or(s.progress_callback,{status:"done",name:t,file:e}),x){if(!ie.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(m instanceof Or)return m.filePath;let k=await o?.match(f);if(k instanceof Or)return k.filePath;if(k instanceof Response)return new Uint8Array(await k.arrayBuffer());if(typeof k=="string")return k;throw new Error("Unable to get model file path or buffer.")}var mc=new Map;async function wo(t,e,r=!0,s={},n=!1){if(!me.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!me.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}or(s.progress_callback,{status:"initiate",name:t,file:e});let o=`${t}::${e}`,a=mc.get(o);if(!a){let i=await Yt(s?.cache_dir);a=Jz(t,e,r,s,n,i).then(l=>(mc.delete(o),l),l=>{throw mc.delete(o),l}),mc.set(o,a)}return await a}async function xo(t,e,r=!0,s={}){let n=await wo(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function nt(t,e,r=!0,s={}){let n=await xo(t,e,r,s);return n===null?{}:JSON.parse(n)}function aA(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,p=new t.constructor(n*o*e),f=r*s,_=n*o;for(let m=0;m=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i=0;--c)l+=p%e[c]*o[c],p=Math.floor(p/e[c]);a[l]=t[i]}return[a,s]}function $e(t){let e=Pe(t)[0],r=t.map(o=>Math.exp(o-e)),s=r.reduce((o,a)=>o+a,0);return r.map(o=>o/s)}function Uf(t){let e=Pe(t)[0],r=0;for(let o=0;oo-e-s)}function lA(t,e){let r=0;for(let s=0;se+r*r,0))}function yo(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;se&&(e=t[s],r=s);return[e,r]}function cA(t){return t>0&&(t&t-1)===0}var hc=class{constructor(e){if(this.size=e|0,this.size<=1||!cA(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;ss;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>2;for(l=0;l>>1,a>>>1)}else for(l=0,c=0;l>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>1,w=m>>>1,x=w>>>1;for(l=0;l>>1;for(let m=2;m<_;m+=2)e[n-m]=e[m],e[n-m+1]=-e[m+1]}_singleRealTransform2(e,r,s,n,o){let a=e[n],i=e[n+o];r[s]=a+i,r[s+1]=0,r[s+2]=a-i,r[s+3]=0}_singleRealTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,c=e[n],p=e[n+o],f=e[n+i],_=e[n+l],m=c+f,w=c-f,x=p+_,k=a*(p-_);r[s]=m+x,r[s+1]=0,r[s+2]=w,r[s+3]=-k,r[s+4]=m-x,r[s+5]=0,r[s+6]=w,r[s+7]=k}},Bf=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let i=-2*Math.PI/e,l=Math.cos(i),c=Math.sin(i);for(let p=0;p>1;++p){let f=(p+1-e)**2/2,_=Math.sqrt(l**2+c**2)**f,m=f*Math.atan2(c,l),w=2*p;o[w]=_*Math.cos(m),o[w+1]=_*Math.sin(m),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new hc(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,p=this._a;if(s)for(let f=0;f>1,w=r[m];n[f]=w*c[f],n[_]=w*c[_]}else for(let f=0;f=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function gs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function pA(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function fA(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let p=1;p0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var dA=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l>10,_=l&1023;if(f===31)c=p|2139095040|_<<13;else if(f===0)if(_===0)c=p;else{let m=113;for(;(_&1024)===0;)_<<=1,--m;_&=-1025,c=p|m<<23|_<<13}else c=p|f+112<<23|_<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;ohd,TRACE:()=>Mc,TRACE_EVENT_BEGIN:()=>Fr,TRACE_EVENT_END:()=>Br,TRACE_FUNC_BEGIN:()=>ks,TRACE_FUNC_END:()=>Es,Tensor:()=>Qt,default:()=>SL,env:()=>Ye,registerBackend:()=>vs});var _d=Object.defineProperty,eL=Object.getOwnPropertyDescriptor,tL=Object.getOwnPropertyNames,rL=Object.prototype.hasOwnProperty,sL=(t=>typeof fs<"u"?fs:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof fs<"u"?fs:e)[r]}):t)(function(t){if(typeof fs<"u")return fs.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),be=(t,e)=>()=>(t&&(e=t(t=0)),e),So=(t,e)=>{for(var r in e)_d(t,r,{get:e[r],enumerable:!0})},nL=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of tL(e))!rL.call(t,n)&&n!==r&&_d(t,n,{get:()=>e[n],enumerable:!(s=eL(e,n))||s.enumerable});return t},Ac=t=>nL(_d({},"__esModule",{value:!0}),t),bo,Nr,vs,_A,UA,jA=be(()=>{"use strict";bo=new Map,Nr=[],vs=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=bo.get(t);if(s===void 0)bo.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=Nr.indexOf(t);n!==-1&&Nr.splice(n,1);for(let o=0;o{let e=bo.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(s){return r||(e.error=`${s}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},UA=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Nr:r,n,o=[],a=new Set;for(let l of s){let c=await _A(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),oL=be(()=>{"use strict";jA()}),GA,aL=be(()=>{"use strict";GA="1.24.0-dev.20251116-b39e144322"}),jf,dt,qA=be(()=>{"use strict";aL(),jf="warning",dt={wasm:{},webgl:{},webgpu:{},versions:{common:GA},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);jf=t}},get logLevel(){return jf}},Object.defineProperty(dt,"logLevel",{enumerable:!0})}),Ye,iL=be(()=>{"use strict";qA(),Ye=dt}),WA,VA,lL=be(()=>{"use strict";WA=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let p=o*n,f=0,_=p,m=p*2,w=-1;a==="RGBA"?(f=0,_=p,m=p*2,w=p*3):a==="RGB"?(f=0,_=p,m=p*2):a==="RBG"&&(f=0,m=p,_=p*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let _=4,m=0,w=1,x=2,k=3,A=0,E=f,S=f*2,T=-1;i==="RGBA"?(A=0,E=f,S=f*2,T=f*3):i==="RGB"?(A=0,E=f,S=f*2):i==="RBG"&&(A=0,S=f,E=f*2),s=r.createImageData(n,o);for(let I=0;I{"use strict";md(),wc=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,_=0,m=1,w=2,x=3,k=0,A=c,E=c*2,S=-1;i==="RGB"&&(f=3,_=0,m=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(k=0,E=c,A=c*2):l==="BGR"&&(E=0,A=c,k=c*2);for(let T=0;T{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let _=t.height,m=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(_=e.resizedHeight,m=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=m}else i.tensorFormat="RGBA",i.height=_,i.width=m;f.drawImage(t,0,0),a=f.getImageData(0,0,m,_).data}else throw new Error("Can not access image data")}else if(s){let p,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(p=e.resizedHeight,f=e.resizedWidth):(p=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=p,i.width=f,e!==void 0){let _=l();_.width=f,_.height=p;let m=c(_);if(m!=null)m.putImageData(t,0,0),a=m.getImageData(0,0,f,p).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let _=t.height,m=t.width;return f.drawImage(t,0,0,m,_),a=f.getImageData(0,0,m,_).data,i.height=_,i.width=m,wc(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,f)=>{let _=l(),m=c(_);if(!t||!m)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{_.width=w.width,_.height=w.height,m.drawImage(w,0,0,_.width,_.height);let x=m.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,p(wc(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return wc(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},XA=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Lt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},KA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Lt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},YA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Lt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},QA=(t,e,r)=>new Lt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),ys,Mo,Gf,JA,uL=be(()=>{"use strict";ys=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Mo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Gf=!1,JA=()=>{if(!Gf){Gf=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(ys.set("int64",BigInt64Array),Mo.set(BigInt64Array,"int64")),e&&(ys.set("uint64",BigUint64Array),Mo.set(BigUint64Array,"uint64")),s?(ys.set("float16",r),Mo.set(r,"float16")):ys.set("float16",Uint16Array)}}}),ZA,e2,pL=be(()=>{"use strict";md(),ZA=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new Lt(t.type,t.data,e);case"cpu-pinned":return new Lt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Lt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Lt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Lt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Lt,md=be(()=>{"use strict";lL(),cL(),uL(),pL(),Lt=class{constructor(t,e,r){JA();let s,n;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,n=t.dims,t.location){case"cpu-pinned":{let a=ys.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,i;if(typeof t=="string")if(s=t,i=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=ys.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")s="string",a=t;else if(l==="boolean")s="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(t);else{let l=Mo.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=l,a=t}if(i===void 0)i=[a.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=a,this.dataLocation="cpu"}let o=ZA(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(t,e){return HA(t,e)}static fromTexture(t,e){return XA(t,e)}static fromGpuBuffer(t,e){return KA(t,e)}static fromMLTensor(t,e){return YA(t,e)}static fromPinnedBuffer(t,e,r){return QA(t,e,r)}toDataURL(t){return WA(this,t)}toImageData(t){return VA(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return e2(this,t)}}}),Qt,t2=be(()=>{"use strict";md(),Qt=Lt}),Mc,qf,ks,Es,Fr,Br,r2=be(()=>{"use strict";qA(),Mc=(t,e)=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeStamp(`${t}::ORT::${e}`)},qf=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||qf("BEGIN",t)},Es=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||qf("END",t)},Fr=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.time(`ORT::${t}`)},Br=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeEnd(`ORT::${t}`)}}),s2,fL=be(()=>{"use strict";jA(),t2(),r2(),s2=class n2{constructor(e){this.handler=e}async run(e,r,s){ks(),Fr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof Qt||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Qt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(p.indexOf(f)!==-1){let _=r[f];(_===null||_ instanceof Qt)&&(c=!0,a=!1,n[f]=_)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let p=i[c];p instanceof Qt?l[c]=p:l[c]=new Qt(p.type,p.data,p.dims)}return Br("InferenceSession.run"),Es(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){ks(),Fr("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let p=e,f=0,_=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(_=e.byteLength-f,typeof s=="number"){if(_=s,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||f+_>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,f,_)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await UA(a),c=await i.createInferenceSessionHandler(o,l);return Br("InferenceSession.create"),Es(),new n2(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),hd,dL=be(()=>{"use strict";fL(),hd=s2}),_L=be(()=>{"use strict"}),mL=be(()=>{"use strict"}),hL=be(()=>{"use strict"}),gL=be(()=>{"use strict"}),o2={};So(o2,{InferenceSession:()=>hd,TRACE:()=>Mc,TRACE_EVENT_BEGIN:()=>Fr,TRACE_EVENT_END:()=>Br,TRACE_FUNC_BEGIN:()=>ks,TRACE_FUNC_END:()=>Es,Tensor:()=>Qt,env:()=>Ye,registerBackend:()=>vs});var As=be(()=>{"use strict";oL(),iL(),dL(),t2(),_L(),mL(),r2(),hL(),gL()}),gd=be(()=>{"use strict"}),a2={};So(a2,{default:()=>i2});var Wf,Vf,i2,wL=be(()=>{"use strict";v2(),Ms(),wd(),Wf="ort-wasm-proxy-worker",Vf=globalThis.self?.name===Wf,Vf&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":xd(r.wasm).then(()=>{Ed(r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})})},s=>{postMessage({type:e,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;Ad(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=Oc(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;Md(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":Td(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;Sd(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},Id([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":Od(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),i2=Vf?null:t=>new Worker(t??Pt,{type:"module",name:Wf})}),l2={};So(l2,{default:()=>c2});async function mA(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(u,d)=>{u.startsWith("./")&&(u=u.substring(2)),(e.Uc||(e.Uc=new Map)).set(u,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let o=()=>{let u=d=>(...h)=>{let g=sr;return h=d(...h),sr!=g?new Promise((v,M)=>{lf={resolve:v,reject:M}}):h};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=u(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(u,d)=>{throw d},c=import.meta.url,p="";if(r||s){try{p=new URL(".",c).href}catch{}s&&(i=u=>{var d=new XMLHttpRequest;return d.open("GET",u,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async u=>{if(O(u))return new Promise((h,g)=>{var v=new XMLHttpRequest;v.open("GET",u,!0),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?h(v.response):g(v.status)},v.onerror=g,v.send(null)});var d=await fetch(u,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,_,m,w,x,k,A=console.log.bind(console),E=console.error.bind(console),S=A,T=E,I=!1,O=u=>u.startsWith("file://");function b(){Tr.buffer!=U.buffer&&le()}if(n){let u=function(d){try{var h=d.data,g=h.Oc;if(g==="load"){let v=[];self.onmessage=M=>v.push(M),k=()=>{postMessage({Oc:"loaded"});for(let M of v)u(M);self.onmessage=u};for(let M of h.ce)e[M]&&!e[M].proxy||(e[M]=(...P)=>{postMessage({Oc:"callHandler",be:M,args:P})},M=="print"&&(S=e[M]),M=="printErr"&&(T=e[M]));Tr=h.ie,le(),_=h.je,qe(),rc()}else if(g==="run"){(function(v){var M=(b(),C)[v+52>>>2>>>0];v=(b(),C)[v+56>>>2>>>0],kk(M,M-v),pe(M)})(h.Nc),yf(h.Nc,0,0,1,0,0),uv(),nf(h.Nc),j||(ok(),j=!0);try{AT(h.ge,h.Wc)}catch(v){if(v!="unwind")throw v}}else h.target!=="setimmediate"&&(g==="checkMailbox"?j&&Xl():g&&(T(`worker: received unknown command ${g}`),T(h)))}catch(v){throw wk(),v}};var F=u,j=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=u}var U,X,K,J,R,C,se,Y,z,$,B,Q=!1;function le(){var u=Tr.buffer;e.HEAP8=U=new Int8Array(u),K=new Int16Array(u),e.HEAPU8=X=new Uint8Array(u),J=new Uint16Array(u),e.HEAP32=R=new Int32Array(u),e.HEAPU32=C=new Uint32Array(u),se=new Float32Array(u),Y=new Float64Array(u),z=new BigInt64Array(u),$=new BigUint64Array(u)}function Ge(){Q=!0,n?k():wr._b()}function ce(u){throw T(u="Aborted("+u+")"),I=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),x?.(u),u}function Et(){return{a:{f:MT,J:TT,k:ST,p:OT,l:IT,sa:CT,b:PT,ca:zT,Ja:hv,q:LT,da:yv,Za:bv,Fa:vv,Ha:kv,_a:Ev,Xa:Av,Qa:Mv,Wa:Tv,oa:Sv,Ga:Ov,Xb:Iv,Ya:Cv,Yb:Pv,db:NT,Da:RT,Sb:DT,Qb:BT,Ca:jT,M:GT,I:qT,Rb:WT,ja:JT,Tb:ZT,Ta:eS,Vb:rS,Ka:sS,Ob:nS,ka:oS,Sa:nf,ab:aS,U:uS,n:mS,c:rf,rb:hS,w:gS,L:wS,z:xS,j:yS,o:Bv,sb:bS,G:vS,T:kS,h:ES,u:AS,m:MS,i:TS,Na:SS,Oa:OS,Pa:IS,La:qv,Ma:Wv,Pb:Vv,eb:PS,cb:NS,Y:$S,qb:RS,la:DS,bb:zS,fb:FS,$a:BS,Wb:US,N:CS,gb:jS,X:GS,Ub:qS,nb:ZS,C:eO,ra:tO,qa:rO,pb:sO,W:nO,v:oO,mb:aO,lb:iO,kb:lO,ob:cO,jb:uO,ib:pO,hb:fO,Ua:Jv,Va:Zv,Ia:Xs,V:ek,na:tk,Ra:rk,ma:sk,Cb:vI,xa:hI,Db:bI,ya:mI,F:nI,e:WO,s:GO,x:jO,B:tI,Fb:fI,ba:pI,D:XO,za:dI,$:gI,ga:uI,Gb:cI,Hb:lI,Ba:oI,Aa:iI,Ib:aI,wa:yI,aa:_I,d:qO,A:HO,r:VO,Bb:kI,t:YO,y:rI,H:KO,E:QO,K:sI,R:wI,ia:eI,_:xI,Jb:ZO,Kb:JO,g:_O,a:Tr,Nb:Hs,Eb:mO,ha:hO,O:gO,pa:wO,Lb:xO,ta:yO,Q:bO,yb:vO,zb:kO,ua:EO,ea:AO,P:MO,Ea:TO,va:SO,Z:OO,wb:IO,Zb:CO,S:PO,Ab:zO,tb:LO,ub:$O,vb:RO,fa:DO,xb:FO,Mb:BO}}}async function qe(){function u(g,v){var M=wr=g.exports;g={};for(let[P,L]of Object.entries(M))typeof L=="function"?(M=iS(L),g[P]=M):g[P]=L;return wr=g,wr=(function(){var P=wr,L=Z=>Ie=>Z(Ie)>>>0,G=Z=>()=>Z()>>>0;return(P=Object.assign({},P)).$b=L(P.$b),P.Cc=G(P.Cc),P.Ec=L(P.Ec),P.rd=(Z=>(Ie,Ne)=>Z(Ie,Ne)>>>0)(P.rd),P.wd=L(P.wd),P.xd=G(P.xd),P.Bd=L(P.Bd),P})(),lv.push(wr.id),nk=(g=wr).$b,ok=g.ac,e._OrtInit=g.bc,e._OrtGetLastError=g.cc,e._OrtCreateSessionOptions=g.dc,e._OrtAppendExecutionProvider=g.ec,e._OrtAddFreeDimensionOverride=g.fc,e._OrtAddSessionConfigEntry=g.gc,e._OrtReleaseSessionOptions=g.hc,e._OrtCreateSession=g.ic,e._OrtReleaseSession=g.jc,e._OrtGetInputOutputCount=g.kc,e._OrtGetInputOutputMetadata=g.lc,e._OrtFree=g.mc,e._OrtCreateTensor=g.nc,e._OrtGetTensorData=g.oc,e._OrtReleaseTensor=g.pc,e._OrtCreateRunOptions=g.qc,e._OrtAddRunConfigEntry=g.rc,e._OrtReleaseRunOptions=g.sc,e._OrtCreateBinding=g.tc,e._OrtBindInput=g.uc,e._OrtBindOutput=g.vc,e._OrtClearBoundOutputs=g.wc,e._OrtReleaseBinding=g.xc,e._OrtRunWithBinding=g.yc,e._OrtRun=g.zc,e._OrtEndProfiling=g.Ac,_f=e._OrtGetWebGpuDevice=g.Bc,ec=g.Cc,Wt=e._free=g.Dc,Zs=e._malloc=g.Ec,ak=e._wgpuBufferRelease=g.Fc,ik=e._wgpuCreateInstance=g.Gc,lk=g.Hc,ck=g.Ic,uk=g.Jc,pk=g.Kc,fk=g.Lc,dk=g.Pc,_k=g.Zc,mk=g._c,hk=g.$c,mf=g.bd,hf=g.cd,gf=g.dd,wf=g.ed,io=g.fd,xf=g.gd,gk=g.hd,yf=g.kd,wk=g.ld,xk=g.md,yk=g.nd,bf=g.od,bk=g.pd,vk=g.qd,vf=g.rd,xe=g.sd,lo=g.td,kk=g.ud,pe=g.vd,tc=g.wd,fe=g.xd,Ek=g.yd,kf=g.zd,Ak=g.Ad,Mk=g.Bd,Tk=g.Cd,Ef=g.Dd,Sk=g.Ed,Ok=g.Fd,Ik=g.Gd,Ck=g.Hd,Pk=g.Id,zk=g.Jd,Lk=g.Kd,Nk=g.Ld,$k=g.Md,Rk=g.Nd,Dk=g.Od,Fk=g.Pd,Bk=g.Qd,Uk=g.Rd,jk=g.Td,Gk=g.Ud,qk=g.Vd,Wk=g.Wd,Vk=g.Yd,Hk=g.Zd,Xk=g._d,Kk=g.$d,Yk=g.ae,Qk=g.oe,Jk=g.pe,Zk=g.qe,eE=g.re,tE=g.se,rE=g.te,sE=g.ue,nE=g.ve,oE=g.we,aE=g.xe,iE=g.ye,lE=g.Ye,cE=g.Ze,uE=g._e,pE=g.$e,_=v,wr}var d,h=Et();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(v,M)=>{g(u(v,M))})}):n?u(new WebAssembly.Instance(_,Et()),_):(B??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",p):p+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,d=await(async function(g){var v=B;if(!f&&!O(v))try{var M=fetch(v,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(M,g)}catch(P){T(`wasm streaming compile failed: ${P}`),T("falling back to ArrayBuffer instantiation")}return(async function(P,L){try{var G=await(async function(Z){if(!f)try{var Ie=await a(Z);return new Uint8Array(Ie)}catch{}if(Z==B&&f)Z=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";Z=i(Z)}return Z})(P);return await WebAssembly.instantiate(G,L)}catch(Z){T(`failed to asynchronously prepare wasm: ${Z}`),ce(Z)}})(v,g)})(h),u(d.instance,d.module))}class ct{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var At=u=>{u.terminate(),u.onmessage=()=>{}},Fe=[],Se=0,rt=null,tr=u=>{Mr.length==0&&(fv(),pv(Mr[0]));var d=Mr.pop();if(!d)return 6;no.push(d),cs[u.Nc]=d,d.Nc=u.Nc;var h={Oc:"run",ge:u.fe,Wc:u.Wc,Nc:u.Nc};return d.postMessage(h,u.Yc),0},Oe=0,Be=(u,d,...h)=>{var g,v=16*h.length,M=fe(),P=tc(v),L=P>>>3;for(g of h)typeof g=="bigint"?((b(),z)[L++>>>0]=1n,(b(),z)[L++>>>0]=g):((b(),z)[L++>>>0]=0n,(b(),Y)[L++>>>0]=g);return u=xk(u,0,v,P,d),pe(M),u};function Hs(u){if(n)return Be(0,1,u);if(m=u,!(0{if(m=u,n)throw so(u),"unwind";Hs(u)},Mr=[],no=[],lv=[],cs={},cv=u=>{var d=u.Nc;delete cs[d],Mr.push(u),no.splice(no.indexOf(u),1),u.Nc=0,yk(d)};function uv(){lv.forEach(u=>u())}var pv=u=>new Promise(d=>{u.onmessage=v=>{var M=v.data;if(v=M.Oc,M.Vc&&M.Vc!=ec()){var P=cs[M.Vc];P?P.postMessage(M,M.Yc):T(`Internal error! Worker sent a message "${v}" to target pthread ${M.Vc}, but that thread no longer exists!`)}else v==="checkMailbox"?Xl():v==="spawnThread"?tr(M):v==="cleanupThread"?Mt(()=>{cv(cs[M.he])}):v==="loaded"?(u.loaded=!0,d(u)):M.target==="setimmediate"?u.postMessage(M):v==="uncaughtException"?u.onerror(M.error):v==="callHandler"?e[M.be](...M.args):v&&T(`worker sent an unknown command ${v}`)},u.onerror=v=>{throw T(`worker sent an error! ${v.filename}:${v.lineno}: ${v.message}`),v};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);u.postMessage({Oc:"load",ce:g,ie:Tr,je:_})});function fv(){var u=new Worker((()=>{let d=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new d("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Mr.push(u)}var Tr,AT=(u,d)=>{Oe=0,u=Ef(u,d),0-9007199254740992>u||9007199254740992>>=0);return(b(),U)[d.Qc+12>>>0]==0&&(dv(d,!0),Hl--),_v(d,!1),Vl.push(d),Mk(u)}var Ks=0,TT=()=>{xe(0,0);var u=Vl.pop();Ek(u.Xc),Ks=0};function dv(u,d){d=d?1:0,(b(),U)[u.Qc+12>>>0]=d}function _v(u,d){d=d?1:0,(b(),U)[u.Qc+13>>>0]=d}class Jp{constructor(d){this.Xc=d,this.Qc=d-24}}var Zp=u=>{var d=Ks;if(!d)return lo(0),0;var h=new Jp(d);(b(),C)[h.Qc+16>>>2>>>0]=d;var g=(b(),C)[h.Qc+4>>>2>>>0];if(!g)return lo(0),d;for(var v of u){if(v===0||v===g)break;if(Ak(v,g,h.Qc+16))return lo(v),d}return lo(g),d};function ST(){return Zp([])}function OT(u){return Zp([u>>>0])}function IT(u,d,h,g){return Zp([u>>>0,d>>>0,h>>>0,g>>>0])}var CT=()=>{var u=Vl.pop();u||ce("no exception to throw");var d=u.Xc;throw(b(),U)[u.Qc+13>>>0]==0&&(Vl.push(u),_v(u,!0),dv(u,!1),Hl++),kf(d),Ks=d};function PT(u,d,h){var g=new Jp(u>>>=0);throw d>>>=0,h>>>=0,(b(),C)[g.Qc+16>>>2>>>0]=0,(b(),C)[g.Qc+4>>>2>>>0]=d,(b(),C)[g.Qc+8>>>2>>>0]=h,kf(u),Hl++,Ks=u}var zT=()=>Hl;function mv(u,d,h,g){return n?Be(2,1,u,d,h,g):hv(u,d,h,g)}function hv(u,d,h,g){if(u>>>=0,d>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var v=[];return n&&v.length===0?mv(u,d,h,g):(u={fe:h,Nc:u,Wc:g,Yc:v},n?(u.Oc="spawnThread",postMessage(u,v),0):tr(u))}function LT(u){throw Ks||=u>>>0,Ks}var gv=globalThis.TextDecoder&&new TextDecoder,wv=(u,d,h,g)=>{if(h=d+h,g)return h;for(;u[d]&&!(d>=h);)++d;return d},xv=(u,d=0,h,g)=>{if(16<(h=wv(u,d>>>=0,h,g))-d&&u.buffer&&gv)return gv.decode(u.buffer instanceof ArrayBuffer?u.subarray(d,h):u.slice(d,h));for(g="";d(v=(240&v)==224?(15&v)<<12|M<<6|P:(7&v)<<18|M<<12|P<<6|63&u[d++])?g+=String.fromCharCode(v):(v-=65536,g+=String.fromCharCode(55296|v>>10,56320|1023&v))}}else g+=String.fromCharCode(v)}return g},Ys=(u,d,h)=>(u>>>=0)?xv((b(),X),u,d,h):"";function yv(u,d,h){return n?Be(3,1,u,d,h):0}function bv(u,d){if(n)return Be(4,1,u,d)}function vv(u,d){if(n)return Be(5,1,u,d)}function kv(u,d,h){if(n)return Be(6,1,u,d,h)}function Ev(u,d,h){return n?Be(7,1,u,d,h):0}function Av(u,d){if(n)return Be(8,1,u,d)}function Mv(u,d,h){if(n)return Be(9,1,u,d,h)}function Tv(u,d,h,g){if(n)return Be(10,1,u,d,h,g)}function Sv(u,d,h,g){if(n)return Be(11,1,u,d,h,g)}function Ov(u,d,h,g){if(n)return Be(12,1,u,d,h,g)}function Iv(u){if(n)return Be(13,1,u)}function Cv(u,d){if(n)return Be(14,1,u,d)}function Pv(u,d,h){if(n)return Be(15,1,u,d,h)}var NT=()=>ce(""),rr=u=>{u>>>=0;for(var d="";;){var h=(b(),X)[u++>>>0];if(!h)return d;d+=String.fromCharCode(h)}},ef={},tf={},$T={},Qs=class extends Error{constructor(u){super(u),this.name="BindingError"}};function dr(u,d,h={}){return(function(g,v,M={}){var P=v.name;if(!g)throw new Qs(`type "${P}" must have a positive integer typeid pointer`);if(tf.hasOwnProperty(g)){if(M.de)return;throw new Qs(`Cannot register type '${P}' twice`)}tf[g]=v,delete $T[g],ef.hasOwnProperty(g)&&(v=ef[g],delete ef[g],v.forEach(L=>L()))})(u,d,h)}var zv=(u,d,h)=>{switch(d){case 1:return h?g=>(b(),U)[g>>>0]:g=>(b(),X)[g>>>0];case 2:return h?g=>(b(),K)[g>>>1>>>0]:g=>(b(),J)[g>>>1>>>0];case 4:return h?g=>(b(),R)[g>>>2>>>0]:g=>(b(),C)[g>>>2>>>0];case 8:return h?g=>(b(),z)[g>>>3>>>0]:g=>(b(),$)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${u}`)}};function RT(u,d,h,g,v){u>>>=0,h>>>=0,d=rr(d>>>0);let M=P=>P;if(g=g===0n){let P=8*h;M=L=>BigInt.asUintN(P,L),v=M(v)}dr(u,{name:d,Mc:M,Sc:(P,L)=>(typeof L=="number"&&(L=BigInt(L)),L),Rc:zv(d,h,!g),Tc:null})}function DT(u,d,h,g){dr(u>>>=0,{name:d=rr(d>>>0),Mc:function(v){return!!v},Sc:function(v,M){return M?h:g},Rc:function(v){return this.Mc((b(),X)[v>>>0])},Tc:null})}var Lv=[],us=[0,1,,1,null,1,!0,1,!1,1];function rf(u){9<(u>>>=0)&&--us[u+1]==0&&(us[u]=void 0,Lv.push(u))}var Rt=u=>{if(!u)throw new Qs(`Cannot use deleted val. handle = ${u}`);return us[u]},qt=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=Lv.pop()||us.length;return us[d]=u,us[d+1]=1,d}};function sf(u){return this.Mc((b(),C)[u>>>2>>>0])}var FT={name:"emscripten::val",Mc:u=>{var d=Rt(u);return rf(u),d},Sc:(u,d)=>qt(d),Rc:sf,Tc:null};function BT(u){return dr(u>>>0,FT)}var UT=(u,d)=>{switch(d){case 4:return function(h){return this.Mc((b(),se)[h>>>2>>>0])};case 8:return function(h){return this.Mc((b(),Y)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${u}`)}};function jT(u,d,h){h>>>=0,dr(u>>>=0,{name:d=rr(d>>>0),Mc:g=>g,Sc:(g,v)=>v,Rc:UT(d,h),Tc:null})}function GT(u,d,h,g,v){u>>>=0,h>>>=0,d=rr(d>>>0);let M=L=>L;if(g===0){var P=32-8*h;M=L=>L<

>>P,v=M(v)}dr(u,{name:d,Mc:M,Sc:(L,G)=>G,Rc:zv(d,h,g!==0),Tc:null})}function qT(u,d,h){function g(M){var P=(b(),C)[M>>>2>>>0];return M=(b(),C)[M+4>>>2>>>0],new v((b(),U).buffer,M,P)}var v=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];dr(u>>>=0,{name:h=rr(h>>>0),Mc:g,Rc:g},{de:!0})}var _r=(u,d,h)=>{var g=(b(),X);if(d>>>=0,0=P){if(d>=h)break;g[d++>>>0]=P}else if(2047>=P){if(d+1>=h)break;g[d++>>>0]=192|P>>6,g[d++>>>0]=128|63&P}else if(65535>=P){if(d+2>=h)break;g[d++>>>0]=224|P>>12,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P}else{if(d+3>=h)break;g[d++>>>0]=240|P>>18,g[d++>>>0]=128|P>>12&63,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P,M++}}g[d>>>0]=0,u=d-v}else u=0;return u},mr=u=>{for(var d=0,h=0;h=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++h):d+=3}return d};function WT(u,d){dr(u>>>=0,{name:d=rr(d>>>0),Mc(h){var g=(b(),C)[h>>>2>>>0];return g=Ys(h+4,g,!0),Wt(h),g},Sc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var v=typeof g=="string";if(!(v||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Qs("Cannot pass non-string to std::string");var M=v?mr(g):g.length,P=Zs(4+M+1),L=P+4;return(b(),C)[P>>>2>>>0]=M,v?_r(g,L,M+1):(b(),X).set(g,L>>>0),h!==null&&h.push(Wt,P),P},Rc:sf,Tc(h){Wt(h)}})}var Nv=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,VT=(u,d,h)=>{if(u>>>=1,16<(d=wv((b(),J),u,d/2,h))-u&&Nv)return Nv.decode((b(),J).slice(u,d));for(h="";u>>0];h+=String.fromCharCode(g)}return h},HT=(u,d,h)=>{if(h??=2147483647,2>h)return 0;var g=d;h=(h-=2)<2*u.length?h/2:u.length;for(var v=0;v>>1>>>0]=M,d+=2}return(b(),K)[d>>>1>>>0]=0,d-g},XT=u=>2*u.length,KT=(u,d,h)=>{var g="";u>>>=2;for(var v=0;!(v>=d/4);v++){var M=(b(),C)[u+v>>>0];if(!M&&!h)break;g+=String.fromCodePoint(M)}return g},YT=(u,d,h)=>{if(d>>>=0,h??=2147483647,4>h)return 0;var g=d;h=g+h-4;for(var v=0;v>>2>>>0]=M,(d+=4)+4>h)break}return(b(),R)[d>>>2>>>0]=0,d-g},QT=u=>{for(var d=0,h=0;h>>=0,d>>>=0,h=rr(h>>>=0),d===2)var g=VT,v=HT,M=XT;else g=KT,v=YT,M=QT;dr(u,{name:h,Mc:P=>{var L=(b(),C)[P>>>2>>>0];return L=g(P+4,L*d,!0),Wt(P),L},Sc:(P,L)=>{if(typeof L!="string")throw new Qs(`Cannot pass non-string to C++ string type ${h}`);var G=M(L),Z=Zs(4+G+d);return(b(),C)[Z>>>2>>>0]=G/d,v(L,Z+4,G+d),P!==null&&P.push(Wt,Z),Z},Rc:sf,Tc(P){Wt(P)}})}function ZT(u,d){dr(u>>>=0,{ee:!0,name:d=rr(d>>>0),Mc:()=>{},Sc:()=>{}})}function eS(u){yf(u>>>0,!s,1,!r,131072,!1),uv()}var Mt=u=>{if(!I)try{if(u(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function nf(u){u>>>=0,tS||(Atomics.waitAsync((b(),R),u>>>2,u).value.then(Xl),u+=128,Atomics.store((b(),R),u>>>2,1))}var Xl=()=>Mt(()=>{var u=ec();u&&(nf(u),vk())});function rS(u,d){(u>>>=0)==d>>>0?setTimeout(Xl):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=cs[u])&&u.postMessage({Oc:"checkMailbox"})}var of=[];function sS(u,d,h,g,v){for(d>>>=0,v>>>=0,of.length=0,h=v>>>3,g=v+g>>>3;h>>0]?(b(),z)[h++>>>0]:(b(),Y)[h++>>>0],of.push(M)}return(d?Af[d]:UO[u])(...of)}var nS=()=>{Oe=0};function oS(u){u>>>=0,n?postMessage({Oc:"cleanupThread",he:u}):cv(cs[u])}function aS(u){}var Kl=u=>{try{u()}catch(d){ce(d)}};function iS(u){var d=(...h)=>{Yl.push(u);try{return u(...h)}finally{I||(Yl.pop(),sr&&Sr===1&&Yl.length===0&&(Sr=0,Oe+=1,Kl(cE),typeof Fibers<"u"&&Fibers.Be()))}};return Dv.set(u,d),d}var Sr=0,sr=null,$v=0,Yl=[],af=new Map,Rv=new Map,Dv=new Map,lS=0,lf=null,cS=[],Fv=u=>(function(d){if(!I){if(Sr===0){var h=!1,g=!1;d((v=0)=>{if(!I&&($v=v,h=!0,g)){Sr=2,Kl(()=>uE(sr)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),v=!1;try{var M=(function(){var G=(b(),R)[sr+8>>>2>>>0];return G=Rv.get(G),G=Dv.get(G),--Oe,G()})()}catch(G){M=G,v=!0}var P=!1;if(!sr){var L=lf;L&&(lf=null,(v?L.reject:L.resolve)(M),P=!0)}if(v&&!P)throw M}}),g=!0,h||(Sr=1,sr=(function(){var v=Zs(65548),M=v+12;if((b(),C)[v>>>2>>>0]=M,(b(),C)[v+4>>>2>>>0]=M+65536,M=Yl[0],!af.has(M)){var P=lS++;af.set(M,P),Rv.set(P,M)}return M=af.get(M),(b(),R)[v+8>>>2>>>0]=M,v})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Kl(()=>lE(sr)))}else Sr===2?(Sr=0,Kl(pE),Wt(sr),sr=null,cS.forEach(Mt)):ce(`invalid state: ${Sr}`);return $v}})(d=>{u().then(d)});function uS(u){return u>>>=0,Fv(async()=>{var d=await Rt(u);return qt(d)})}var cf=[],pS=u=>{var d=cf.length;return cf.push(u),d},fS=(u,d)=>{for(var h=Array(u),g=0;g>>2>>>0],P=tf[M];if(P===void 0)throw u=`parameter ${g}`,M=nk(M),d=rr(M),Wt(M),new Qs(`${u} has unknown type ${d}`);h[v]=P}return h},dS=(u,d,h)=>{var g=[];return u=u(g,h),g.length&&((b(),C)[d>>>2>>>0]=qt(g)),u},_S={},Ql=u=>{var d=_S[u];return d===void 0?rr(u):d};function mS(u,d,h){var[g,...v]=fS(u,d>>>0);d=g.Sc.bind(g);var M=v.map(G=>G.Rc.bind(G));u--;var P={toValue:Rt};switch(u=M.map((G,Z)=>{var Ie=`argFromPtr${Z}`;return P[Ie]=G,`${Ie}(args${Z?"+"+8*Z:""})`}),h){case 0:var L="toValue(handle)";break;case 2:L="new (toValue(handle))";break;case 3:L="";break;case 1:P.getStringOrSymbol=Ql,L="toValue(handle)[getStringOrSymbol(methodName)]"}return L+=`(${u})`,g.ee||(P.toReturnWire=d,P.emval_returnValue=dS,L=`return emval_returnValue(toReturnWire, destructorsRef, ${L})`),L=`return function (handle, methodName, destructorsRef, args) { ++`,Lz="{%- ",Nz=" -%}";function $z(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function Rz(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Xt(t.body,0,r).replace(/\n$/,"")}function wt(...t){return Lz+t.join(" ")+Nz}function Xt(t,e,r){return t.map(s=>Dz(s,e,r)).join(at)}function Dz(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Xt(t.body,e,r);case"If":return Fz(t,e,r);case"For":return Bz(t,e,r);case"Set":return Uz(t,e,r);case"Macro":return jz(t,e,r);case"Break":return s+wt("break");case"Continue":return s+wt("continue");case"CallStatement":return Gz(t,e,r);case"FilterStatement":return qz(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function Fz(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+wt("if",ke(n[0].test))+at+Xt(n[0].body,e+1,r);for(let i=1;i0&&(a+=at+s+wt("else")+at+Xt(o.alternate,e+1,r)),a+=at+s+wt("endif"),a}function Bz(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+wt("for",ke(t.loopvar),"in",n)+at+Xt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=at+s+wt("else")+at+Xt(t.defaultBlock,e+1,r)),o+=at+s+wt("endfor"),o}function Uz(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+wt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+at+Xt(t.body,e+1,r)+at+s+wt("endset")}function jz(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+wt("macro",`${t.name.value}(${n})`)+at+Xt(t.body,e+1,r)+at+s+wt("endmacro")}function Gz(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+wt(`call${n}`,o)+at;return a+=Xt(t.body,e+1,r)+at,a+=s+wt("endcall"),a}function qz(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+wt("filter",n)+at;return o+=Xt(t.body,e+1,r)+at,o+=s+wt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=$z(r),n=ke(r.left,s),o=ke(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var XE=class{parsed;constructor(t){let e=ez(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Ez(e)}render(t){let e=new _s;if(Pz(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new zz(e).run(this.parsed).value}format(t){return Rz(this.parsed,t?.indent||" ")}};import an from"fs";var Wz={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"},Or=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=an.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=an.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=an.createReadStream(e);this.body=new ReadableStream({start(n){s.on("data",o=>n.enqueue(o)),s.on("end",()=>n.close()),s.on("error",o=>n.error(o))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",Wz[e]??"application/octet-stream")}clone(){let e=new t(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await an.promises.readFile(this.filePath)).buffer}async blob(){let e=await an.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await an.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};import mo from"fs";import pc from"path";var Ir=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(ie.IS_CRYPTO_AVAILABLE){let i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;let r=this._mt,s=(i,l)=>Math.imul(i,l)>>>0,n=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))n.push(i&4294967295);n.length||n.push(0),r[0]=19650218;for(let i=1;i<624;++i)r[i]=s(1812433253,r[i-1]^r[i-1]>>>30)+i>>>0;let o=1,a=0;for(let i=Math.max(624,n.length);i>0;--i,++o,++a)o>=624&&(r[0]=r[623],o=1),a>=n.length&&(a=0),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1664525))+n[a]+a>>>0;for(let i=623;i>0;--i,++o)o>=624&&(r[0]=r[623],o=1),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1566083941))-o>>>0;r[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let s=0;s<624;++s){let n=e[s]&2147483648|e[(s+1)%624]&2147483647;e[s]=(e[(s+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let r=e[this._idx++];return r^=r>>>11,r^=r<<7&2636928640,r^=r<<15&4022730752,r^=r>>>18,r>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,r=1){let s=this._gauss_next;if(this._gauss_next=null,s===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+s*r}shuffle(e){for(let r=e.length-1;r>0;--r){let s=32-Math.clz32(r+1),n=this._int32()>>>32-s;for(;n>r;)n=this._int32()>>>32-s;let o=e[r];e[r]=e[n],e[n]=o}}choices(e,r){return e[KE(this._random_fn,r)]}};function KE(t,e){let r=0;for(let n=0;nKE(hs.random,t);var Vz=new Ir,ln=class{constructor(e){this.path=e}async match(e){let r=pc.join(this.path,e),s=new Or(r);if(s.exists)return s}async put(e,r,s=void 0){let n=pc.join(this.path,e),o=ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=Vz._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),p=0;await mo.promises.mkdir(pc.dirname(n),{recursive:!0});let f=mo.createWriteStream(i),_=r.body.getReader();for(;;){let{done:m,value:w}=await _.read();if(m)break;await new Promise((k,A)=>{f.write(w,E=>{if(E){A(E);return}k()})}),p+=w.length;let x=c?p/c*100:0;s?.({progress:x,loaded:p,total:c})}await new Promise((m,w)=>{f.close(x=>x?w(x):m())}),await mo.promises.rename(i,n)}catch(l){try{await mo.promises.unlink(i)}catch{}throw l}}async delete(e){let r=pc.join(this.path,e);try{return await mo.promises.unlink(r),!0}catch{return!1}}};var QE={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"},fc=100,JE=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function ho(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function Cr(t,e=null,r=null){let s;try{s=new URL(t)}catch{return!1}return!(e&&!e.includes(s.protocol)||r&&!r.includes(s.hostname))}function ZE(t){return!(!JE.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function eA(t,e,r){if(!r)return null;let s=QE[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function tA(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&ee.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:p}=await i.read();if(c)return;let f=a+p.length;if(f>n){n=f;let m=new Uint8Array(n);m.set(o),o=m}o.set(p,a),a=f;let _=a/n*100;return e({progress:_,loaded:a,total:n}),l()}return await l(),o}function $f(t){return Cr(t,["blob:"])}function Rf(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof import_meta<"u"&&import_meta.url)e=import_meta.url;else return t;return new URL(t,e).href}var sA="SHA-256",Hz="experimental_transformers-hash-cache",rA=t=>({algorithm:sA,value:t}),go=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(Hz),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let r=await this._getFileHash(e);if(r)try{let[s]=await navigator.crossOriginStorage.requestFileHandles([rA(r)]),n=await s.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,r)=>{let s=await this._getFileHash(e);if(s){let n=await r.blob();await this._storeBlobInCOS(n,s)}else this._processAndStore(e,r.body)};_storeBlobInCOS=async(e,r)=>{let[s]=await navigator.crossOriginStorage.requestFileHandles([rA(r)],{create:!0}),n=await s.createWritable();await n.write(e),await n.close()};_processAndStore=async(e,r)=>{try{let s=[];for await(let a of r)s.push(a);let n=new Blob(s),o=await this._getBlobHash(n);await this._storeBlobInCOS(n,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let r=await this._getHashCache(),s=await r.match(e);if(s)return s.text();let n=await this._getLfsFileHash(e);return n?(await r.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let r=e.replace("/resolve/","/raw/");try{let n=(await fetch(r).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{let r=await e.arrayBuffer(),s=await crypto.subtle.digest(sA,r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function Yt(t=null){let e=null;if(me.useCustomCache){if(!me.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!me.customCache.match||!me.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=me.customCache}if(!e&&me.experimental_useCrossOriginStorage&&go.isAvailable()&&(e=new go),!e&&me.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(me.cacheKey)}catch(r){ee.warn("An error occurred while opening the browser cache:",r)}}if(!e&&me.useFSCache){if(!ie.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new ln(t??me.cacheDir)}return e}async function nA(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var dc=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let r=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,r),r}put(e,r){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,r),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};var Xz=100,Df=new dc(Xz);function _c(t,e){let r=Df.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(Df.delete(t),Promise.reject(n)));return Df.put(t,s),s}async function Kz(t){if(!Cr(t,["http:","https:"]))return null;let e=Ff(t);return e.set("Range","bytes=0-0"),me.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function Ot(t,e,r={}){let s=JSON.stringify([t,e,r?.revision,r?.cache_dir,r?.local_files_only]);return _c(s,()=>Yz(t,e,r))}async function Yz(t,e,r){let s=await Yt(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=zr(t,e,r,s),l=await Lr(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),p=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:p||void 0,fromCache:!0}}if(me.allowLocalModels&&!Cr(n,["http:","https:"]))try{let p=await Pr(n);if(typeof p!="string"&&p.status!==404){let f=p.headers.get("content-length"),_=p.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:_||void 0,fromCache:!1}}}catch{}if(me.allowRemoteModels&&!r.local_files_only&&i)try{let c=await Kz(o);if(c&&c.status>=200&&c.status<300){let p,f=c.headers.get("content-type");if(c.status===206){let _=c.headers.get("content-range");if(_){let m=_.match(/bytes \d+-\d+\/(\d+)/);m&&(p=parseInt(m[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(p===void 0){let _=c.headers.get("content-length");p=_?parseInt(_,10):void 0}return{exists:!0,size:p,contentType:f||void 0,fromCache:!1}}}catch(c){ee.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function Pr(t){return me.useFS&&!Cr(t,["http:","https:","blob:"])?new Or(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):me.fetch(t,{headers:Ff(t)})}function Ff(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=me.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),Cr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function zr(t,e,r={},s=null){let n=r.revision??"main",o=ho(t,e),a=ZE(t),i=a?ho(me.localModelPath,o):o,l=ho(me.remoteHost,me.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof ln?n==="main"?o:ho(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function Lr(t,e,r){if(t)return await nA(t,e,r)}async function Qz(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o){if(typeof n!="string"){let i=new Headers(n.headers);i.set("content-length",o.byteLength.toString()),await r.put(s,new Response(o,{headers:i})).catch(l=>{ee.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=a.progress_callback?l=>or(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function Jz(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:p}=zr(t,e,s,o),f,_=!1,m;m=await Lr(o,i,c);let w=m!==void 0;if(w)f=c;else{if(me.allowLocalModels)if(Cr(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!me.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{m=await Pr(i),f=i}catch(E){ee.warn(`Unable to load from local path "${i}": "${E}"`)}if(m===void 0||typeof m!="string"&&m.status===404){if(s.local_files_only||!me.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!p)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(m=await Pr(l),m.status!==200)return eA(m.status,l,r);f=c}_=o&&typeof Response<"u"&&m instanceof Response&&m.status===200}or(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(ie.IS_NODE_ENV&&n)){let A;if(typeof m!="string")if(!s.progress_callback)A=new Uint8Array(await m.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test((navigator.userAgent||"")))A=new Uint8Array(await m.arrayBuffer()),or(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A.length,total:A.length});else{let E,S=m.headers.get("content-length");if(S)E=parseInt(S,10);else try{let T=await Ot(t,e,s);T.size&&(E=T.size)}catch{}A=await tA(m,T=>{or(s.progress_callback,{status:"progress",name:t,file:e,...T})},E)}x=A}if(_&&f&&typeof m!="string"&&await Qz(t,e,o,f,m,x,s),ie.IS_NODE_ENV&&n&&s.progress_callback&&typeof m!="string"){let A=parseInt(m.headers.get("content-length"),10)||0;or(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A,total:A})}if(or(s.progress_callback,{status:"done",name:t,file:e}),x){if(!ie.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(m instanceof Or)return m.filePath;let k=await o?.match(f);if(k instanceof Or)return k.filePath;if(k instanceof Response)return new Uint8Array(await k.arrayBuffer());if(typeof k=="string")return k;throw new Error("Unable to get model file path or buffer.")}var mc=new Map;async function wo(t,e,r=!0,s={},n=!1){if(!me.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!me.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}or(s.progress_callback,{status:"initiate",name:t,file:e});let o=`${t}::${e}`,a=mc.get(o);if(!a){let i=await Yt(s?.cache_dir);a=Jz(t,e,r,s,n,i).then(l=>(mc.delete(o),l),l=>{throw mc.delete(o),l}),mc.set(o,a)}return await a}async function xo(t,e,r=!0,s={}){let n=await wo(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function nt(t,e,r=!0,s={}){let n=await xo(t,e,r,s);return n===null?{}:JSON.parse(n)}function aA(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,p=new t.constructor(n*o*e),f=r*s,_=n*o;for(let m=0;m=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i=0;--c)l+=p%e[c]*o[c],p=Math.floor(p/e[c]);a[l]=t[i]}return[a,s]}function $e(t){let e=Pe(t)[0],r=t.map(o=>Math.exp(o-e)),s=r.reduce((o,a)=>o+a,0);return r.map(o=>o/s)}function Uf(t){let e=Pe(t)[0],r=0;for(let o=0;oo-e-s)}function lA(t,e){let r=0;for(let s=0;se+r*r,0))}function yo(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;se&&(e=t[s],r=s);return[e,r]}function cA(t){return t>0&&(t&t-1)===0}var hc=class{constructor(e){if(this.size=e|0,this.size<=1||!cA(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;ss;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>2;for(l=0;l>>1,a>>>1)}else for(l=0,c=0;l>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>1,w=m>>>1,x=w>>>1;for(l=0;l>>1;for(let m=2;m<_;m+=2)e[n-m]=e[m],e[n-m+1]=-e[m+1]}_singleRealTransform2(e,r,s,n,o){let a=e[n],i=e[n+o];r[s]=a+i,r[s+1]=0,r[s+2]=a-i,r[s+3]=0}_singleRealTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,c=e[n],p=e[n+o],f=e[n+i],_=e[n+l],m=c+f,w=c-f,x=p+_,k=a*(p-_);r[s]=m+x,r[s+1]=0,r[s+2]=w,r[s+3]=-k,r[s+4]=m-x,r[s+5]=0,r[s+6]=w,r[s+7]=k}},Bf=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let i=-2*Math.PI/e,l=Math.cos(i),c=Math.sin(i);for(let p=0;p>1;++p){let f=(p+1-e)**2/2,_=Math.sqrt(l**2+c**2)**f,m=f*Math.atan2(c,l),w=2*p;o[w]=_*Math.cos(m),o[w+1]=_*Math.sin(m),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new hc(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,p=this._a;if(s)for(let f=0;f>1,w=r[m];n[f]=w*c[f],n[_]=w*c[_]}else for(let f=0;f=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function gs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function pA(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function fA(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let p=1;p0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var dA=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l>10,_=l&1023;if(f===31)c=p|2139095040|_<<13;else if(f===0)if(_===0)c=p;else{let m=113;for(;(_&1024)===0;)_<<=1,--m;_&=-1025,c=p|m<<23|_<<13}else c=p|f+112<<23|_<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;ohd,TRACE:()=>Mc,TRACE_EVENT_BEGIN:()=>Fr,TRACE_EVENT_END:()=>Br,TRACE_FUNC_BEGIN:()=>ks,TRACE_FUNC_END:()=>Es,Tensor:()=>Qt,default:()=>SL,env:()=>Ye,registerBackend:()=>vs});var _d=Object.defineProperty,eL=Object.getOwnPropertyDescriptor,tL=Object.getOwnPropertyNames,rL=Object.prototype.hasOwnProperty,sL=(t=>typeof fs<"u"?fs:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof fs<"u"?fs:e)[r]}):t)(function(t){if(typeof fs<"u")return fs.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),be=(t,e)=>()=>(t&&(e=t(t=0)),e),So=(t,e)=>{for(var r in e)_d(t,r,{get:e[r],enumerable:!0})},nL=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of tL(e))!rL.call(t,n)&&n!==r&&_d(t,n,{get:()=>e[n],enumerable:!(s=eL(e,n))||s.enumerable});return t},Ac=t=>nL(_d({},"__esModule",{value:!0}),t),bo,Nr,vs,_A,UA,jA=be(()=>{"use strict";bo=new Map,Nr=[],vs=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=bo.get(t);if(s===void 0)bo.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=Nr.indexOf(t);n!==-1&&Nr.splice(n,1);for(let o=0;o{let e=bo.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(s){return r||(e.error=`${s}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},UA=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Nr:r,n,o=[],a=new Set;for(let l of s){let c=await _A(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),oL=be(()=>{"use strict";jA()}),GA,aL=be(()=>{"use strict";GA="1.24.0-dev.20251116-b39e144322"}),jf,dt,qA=be(()=>{"use strict";aL(),jf="warning",dt={wasm:{},webgl:{},webgpu:{},versions:{common:GA},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);jf=t}},get logLevel(){return jf}},Object.defineProperty(dt,"logLevel",{enumerable:!0})}),Ye,iL=be(()=>{"use strict";qA(),Ye=dt}),WA,VA,lL=be(()=>{"use strict";WA=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let p=o*n,f=0,_=p,m=p*2,w=-1;a==="RGBA"?(f=0,_=p,m=p*2,w=p*3):a==="RGB"?(f=0,_=p,m=p*2):a==="RBG"&&(f=0,m=p,_=p*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let _=4,m=0,w=1,x=2,k=3,A=0,E=f,S=f*2,T=-1;i==="RGBA"?(A=0,E=f,S=f*2,T=f*3):i==="RGB"?(A=0,E=f,S=f*2):i==="RBG"&&(A=0,S=f,E=f*2),s=r.createImageData(n,o);for(let I=0;I{"use strict";md(),wc=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,_=0,m=1,w=2,x=3,k=0,A=c,E=c*2,S=-1;i==="RGB"&&(f=3,_=0,m=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(k=0,E=c,A=c*2):l==="BGR"&&(E=0,A=c,k=c*2);for(let T=0;T{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let _=t.height,m=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(_=e.resizedHeight,m=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=m}else i.tensorFormat="RGBA",i.height=_,i.width=m;f.drawImage(t,0,0),a=f.getImageData(0,0,m,_).data}else throw new Error("Can not access image data")}else if(s){let p,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(p=e.resizedHeight,f=e.resizedWidth):(p=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=p,i.width=f,e!==void 0){let _=l();_.width=f,_.height=p;let m=c(_);if(m!=null)m.putImageData(t,0,0),a=m.getImageData(0,0,f,p).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let _=t.height,m=t.width;return f.drawImage(t,0,0,m,_),a=f.getImageData(0,0,m,_).data,i.height=_,i.width=m,wc(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,f)=>{let _=l(),m=c(_);if(!t||!m)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{_.width=w.width,_.height=w.height,m.drawImage(w,0,0,_.width,_.height);let x=m.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,p(wc(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return wc(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},XA=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Lt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},KA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Lt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},YA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Lt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},QA=(t,e,r)=>new Lt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),ys,Mo,Gf,JA,uL=be(()=>{"use strict";ys=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Mo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Gf=!1,JA=()=>{if(!Gf){Gf=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(ys.set("int64",BigInt64Array),Mo.set(BigInt64Array,"int64")),e&&(ys.set("uint64",BigUint64Array),Mo.set(BigUint64Array,"uint64")),s?(ys.set("float16",r),Mo.set(r,"float16")):ys.set("float16",Uint16Array)}}}),ZA,e2,pL=be(()=>{"use strict";md(),ZA=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new Lt(t.type,t.data,e);case"cpu-pinned":return new Lt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Lt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Lt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Lt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Lt,md=be(()=>{"use strict";lL(),cL(),uL(),pL(),Lt=class{constructor(t,e,r){JA();let s,n;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,n=t.dims,t.location){case"cpu-pinned":{let a=ys.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,i;if(typeof t=="string")if(s=t,i=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=ys.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")s="string",a=t;else if(l==="boolean")s="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(t);else{let l=Mo.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=l,a=t}if(i===void 0)i=[a.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=a,this.dataLocation="cpu"}let o=ZA(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(t,e){return HA(t,e)}static fromTexture(t,e){return XA(t,e)}static fromGpuBuffer(t,e){return KA(t,e)}static fromMLTensor(t,e){return YA(t,e)}static fromPinnedBuffer(t,e,r){return QA(t,e,r)}toDataURL(t){return WA(this,t)}toImageData(t){return VA(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return e2(this,t)}}}),Qt,t2=be(()=>{"use strict";md(),Qt=Lt}),Mc,qf,ks,Es,Fr,Br,r2=be(()=>{"use strict";qA(),Mc=(t,e)=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeStamp(`${t}::ORT::${e}`)},qf=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||qf("BEGIN",t)},Es=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||qf("END",t)},Fr=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.time(`ORT::${t}`)},Br=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeEnd(`ORT::${t}`)}}),s2,fL=be(()=>{"use strict";jA(),t2(),r2(),s2=class n2{constructor(e){this.handler=e}async run(e,r,s){ks(),Fr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof Qt||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Qt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(p.indexOf(f)!==-1){let _=r[f];(_===null||_ instanceof Qt)&&(c=!0,a=!1,n[f]=_)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let p=i[c];p instanceof Qt?l[c]=p:l[c]=new Qt(p.type,p.data,p.dims)}return Br("InferenceSession.run"),Es(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){ks(),Fr("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let p=e,f=0,_=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(_=e.byteLength-f,typeof s=="number"){if(_=s,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||f+_>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,f,_)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await UA(a),c=await i.createInferenceSessionHandler(o,l);return Br("InferenceSession.create"),Es(),new n2(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),hd,dL=be(()=>{"use strict";fL(),hd=s2}),_L=be(()=>{"use strict"}),mL=be(()=>{"use strict"}),hL=be(()=>{"use strict"}),gL=be(()=>{"use strict"}),o2={};So(o2,{InferenceSession:()=>hd,TRACE:()=>Mc,TRACE_EVENT_BEGIN:()=>Fr,TRACE_EVENT_END:()=>Br,TRACE_FUNC_BEGIN:()=>ks,TRACE_FUNC_END:()=>Es,Tensor:()=>Qt,env:()=>Ye,registerBackend:()=>vs});var As=be(()=>{"use strict";oL(),iL(),dL(),t2(),_L(),mL(),r2(),hL(),gL()}),gd=be(()=>{"use strict"}),a2={};So(a2,{default:()=>i2});var Wf,Vf,i2,wL=be(()=>{"use strict";v2(),Ms(),wd(),Wf="ort-wasm-proxy-worker",Vf=globalThis.self?.name===Wf,Vf&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":xd(r.wasm).then(()=>{Ed(r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})})},s=>{postMessage({type:e,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;Ad(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=Oc(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;Md(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":Td(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;Sd(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},Id([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":Od(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),i2=Vf?null:t=>new Worker(t??Pt,{type:"module",name:Wf})}),l2={};So(l2,{default:()=>c2});async function mA(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(u,d)=>{u.startsWith("./")&&(u=u.substring(2)),(e.Uc||(e.Uc=new Map)).set(u,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let o=()=>{let u=d=>(...h)=>{let g=sr;return h=d(...h),sr!=g?new Promise((v,M)=>{lf={resolve:v,reject:M}}):h};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=u(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(u,d)=>{throw d},c=import_meta.url,p="";if(r||s){try{p=new URL(".",c).href}catch{}s&&(i=u=>{var d=new XMLHttpRequest;return d.open("GET",u,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async u=>{if(O(u))return new Promise((h,g)=>{var v=new XMLHttpRequest;v.open("GET",u,!0),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?h(v.response):g(v.status)},v.onerror=g,v.send(null)});var d=await fetch(u,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,_,m,w,x,k,A=console.log.bind(console),E=console.error.bind(console),S=A,T=E,I=!1,O=u=>u.startsWith("file://");function b(){Tr.buffer!=U.buffer&&le()}if(n){let u=function(d){try{var h=d.data,g=h.Oc;if(g==="load"){let v=[];self.onmessage=M=>v.push(M),k=()=>{postMessage({Oc:"loaded"});for(let M of v)u(M);self.onmessage=u};for(let M of h.ce)e[M]&&!e[M].proxy||(e[M]=(...P)=>{postMessage({Oc:"callHandler",be:M,args:P})},M=="print"&&(S=e[M]),M=="printErr"&&(T=e[M]));Tr=h.ie,le(),_=h.je,qe(),rc()}else if(g==="run"){(function(v){var M=(b(),C)[v+52>>>2>>>0];v=(b(),C)[v+56>>>2>>>0],kk(M,M-v),pe(M)})(h.Nc),yf(h.Nc,0,0,1,0,0),uv(),nf(h.Nc),j||(ok(),j=!0);try{AT(h.ge,h.Wc)}catch(v){if(v!="unwind")throw v}}else h.target!=="setimmediate"&&(g==="checkMailbox"?j&&Xl():g&&(T(`worker: received unknown command ${g}`),T(h)))}catch(v){throw wk(),v}};var F=u,j=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=u}var U,X,K,J,R,C,se,Y,z,$,B,Q=!1;function le(){var u=Tr.buffer;e.HEAP8=U=new Int8Array(u),K=new Int16Array(u),e.HEAPU8=X=new Uint8Array(u),J=new Uint16Array(u),e.HEAP32=R=new Int32Array(u),e.HEAPU32=C=new Uint32Array(u),se=new Float32Array(u),Y=new Float64Array(u),z=new BigInt64Array(u),$=new BigUint64Array(u)}function Ge(){Q=!0,n?k():wr._b()}function ce(u){throw T(u="Aborted("+u+")"),I=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),x?.(u),u}function Et(){return{a:{f:MT,J:TT,k:ST,p:OT,l:IT,sa:CT,b:PT,ca:zT,Ja:hv,q:LT,da:yv,Za:bv,Fa:vv,Ha:kv,_a:Ev,Xa:Av,Qa:Mv,Wa:Tv,oa:Sv,Ga:Ov,Xb:Iv,Ya:Cv,Yb:Pv,db:NT,Da:RT,Sb:DT,Qb:BT,Ca:jT,M:GT,I:qT,Rb:WT,ja:JT,Tb:ZT,Ta:eS,Vb:rS,Ka:sS,Ob:nS,ka:oS,Sa:nf,ab:aS,U:uS,n:mS,c:rf,rb:hS,w:gS,L:wS,z:xS,j:yS,o:Bv,sb:bS,G:vS,T:kS,h:ES,u:AS,m:MS,i:TS,Na:SS,Oa:OS,Pa:IS,La:qv,Ma:Wv,Pb:Vv,eb:PS,cb:NS,Y:$S,qb:RS,la:DS,bb:zS,fb:FS,$a:BS,Wb:US,N:CS,gb:jS,X:GS,Ub:qS,nb:ZS,C:eO,ra:tO,qa:rO,pb:sO,W:nO,v:oO,mb:aO,lb:iO,kb:lO,ob:cO,jb:uO,ib:pO,hb:fO,Ua:Jv,Va:Zv,Ia:Xs,V:ek,na:tk,Ra:rk,ma:sk,Cb:vI,xa:hI,Db:bI,ya:mI,F:nI,e:WO,s:GO,x:jO,B:tI,Fb:fI,ba:pI,D:XO,za:dI,$:gI,ga:uI,Gb:cI,Hb:lI,Ba:oI,Aa:iI,Ib:aI,wa:yI,aa:_I,d:qO,A:HO,r:VO,Bb:kI,t:YO,y:rI,H:KO,E:QO,K:sI,R:wI,ia:eI,_:xI,Jb:ZO,Kb:JO,g:_O,a:Tr,Nb:Hs,Eb:mO,ha:hO,O:gO,pa:wO,Lb:xO,ta:yO,Q:bO,yb:vO,zb:kO,ua:EO,ea:AO,P:MO,Ea:TO,va:SO,Z:OO,wb:IO,Zb:CO,S:PO,Ab:zO,tb:LO,ub:$O,vb:RO,fa:DO,xb:FO,Mb:BO}}}async function qe(){function u(g,v){var M=wr=g.exports;g={};for(let[P,L]of Object.entries(M))typeof L=="function"?(M=iS(L),g[P]=M):g[P]=L;return wr=g,wr=(function(){var P=wr,L=Z=>Ie=>Z(Ie)>>>0,G=Z=>()=>Z()>>>0;return(P=Object.assign({},P)).$b=L(P.$b),P.Cc=G(P.Cc),P.Ec=L(P.Ec),P.rd=(Z=>(Ie,Ne)=>Z(Ie,Ne)>>>0)(P.rd),P.wd=L(P.wd),P.xd=G(P.xd),P.Bd=L(P.Bd),P})(),lv.push(wr.id),nk=(g=wr).$b,ok=g.ac,e._OrtInit=g.bc,e._OrtGetLastError=g.cc,e._OrtCreateSessionOptions=g.dc,e._OrtAppendExecutionProvider=g.ec,e._OrtAddFreeDimensionOverride=g.fc,e._OrtAddSessionConfigEntry=g.gc,e._OrtReleaseSessionOptions=g.hc,e._OrtCreateSession=g.ic,e._OrtReleaseSession=g.jc,e._OrtGetInputOutputCount=g.kc,e._OrtGetInputOutputMetadata=g.lc,e._OrtFree=g.mc,e._OrtCreateTensor=g.nc,e._OrtGetTensorData=g.oc,e._OrtReleaseTensor=g.pc,e._OrtCreateRunOptions=g.qc,e._OrtAddRunConfigEntry=g.rc,e._OrtReleaseRunOptions=g.sc,e._OrtCreateBinding=g.tc,e._OrtBindInput=g.uc,e._OrtBindOutput=g.vc,e._OrtClearBoundOutputs=g.wc,e._OrtReleaseBinding=g.xc,e._OrtRunWithBinding=g.yc,e._OrtRun=g.zc,e._OrtEndProfiling=g.Ac,_f=e._OrtGetWebGpuDevice=g.Bc,ec=g.Cc,Wt=e._free=g.Dc,Zs=e._malloc=g.Ec,ak=e._wgpuBufferRelease=g.Fc,ik=e._wgpuCreateInstance=g.Gc,lk=g.Hc,ck=g.Ic,uk=g.Jc,pk=g.Kc,fk=g.Lc,dk=g.Pc,_k=g.Zc,mk=g._c,hk=g.$c,mf=g.bd,hf=g.cd,gf=g.dd,wf=g.ed,io=g.fd,xf=g.gd,gk=g.hd,yf=g.kd,wk=g.ld,xk=g.md,yk=g.nd,bf=g.od,bk=g.pd,vk=g.qd,vf=g.rd,xe=g.sd,lo=g.td,kk=g.ud,pe=g.vd,tc=g.wd,fe=g.xd,Ek=g.yd,kf=g.zd,Ak=g.Ad,Mk=g.Bd,Tk=g.Cd,Ef=g.Dd,Sk=g.Ed,Ok=g.Fd,Ik=g.Gd,Ck=g.Hd,Pk=g.Id,zk=g.Jd,Lk=g.Kd,Nk=g.Ld,$k=g.Md,Rk=g.Nd,Dk=g.Od,Fk=g.Pd,Bk=g.Qd,Uk=g.Rd,jk=g.Td,Gk=g.Ud,qk=g.Vd,Wk=g.Wd,Vk=g.Yd,Hk=g.Zd,Xk=g._d,Kk=g.$d,Yk=g.ae,Qk=g.oe,Jk=g.pe,Zk=g.qe,eE=g.re,tE=g.se,rE=g.te,sE=g.ue,nE=g.ve,oE=g.we,aE=g.xe,iE=g.ye,lE=g.Ye,cE=g.Ze,uE=g._e,pE=g.$e,_=v,wr}var d,h=Et();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(v,M)=>{g(u(v,M))})}):n?u(new WebAssembly.Instance(_,Et()),_):(B??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",p):p+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import_meta.url).href,d=await(async function(g){var v=B;if(!f&&!O(v))try{var M=fetch(v,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(M,g)}catch(P){T(`wasm streaming compile failed: ${P}`),T("falling back to ArrayBuffer instantiation")}return(async function(P,L){try{var G=await(async function(Z){if(!f)try{var Ie=await a(Z);return new Uint8Array(Ie)}catch{}if(Z==B&&f)Z=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";Z=i(Z)}return Z})(P);return await WebAssembly.instantiate(G,L)}catch(Z){T(`failed to asynchronously prepare wasm: ${Z}`),ce(Z)}})(v,g)})(h),u(d.instance,d.module))}class ct{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var At=u=>{u.terminate(),u.onmessage=()=>{}},Fe=[],Se=0,rt=null,tr=u=>{Mr.length==0&&(fv(),pv(Mr[0]));var d=Mr.pop();if(!d)return 6;no.push(d),cs[u.Nc]=d,d.Nc=u.Nc;var h={Oc:"run",ge:u.fe,Wc:u.Wc,Nc:u.Nc};return d.postMessage(h,u.Yc),0},Oe=0,Be=(u,d,...h)=>{var g,v=16*h.length,M=fe(),P=tc(v),L=P>>>3;for(g of h)typeof g=="bigint"?((b(),z)[L++>>>0]=1n,(b(),z)[L++>>>0]=g):((b(),z)[L++>>>0]=0n,(b(),Y)[L++>>>0]=g);return u=xk(u,0,v,P,d),pe(M),u};function Hs(u){if(n)return Be(0,1,u);if(m=u,!(0{if(m=u,n)throw so(u),"unwind";Hs(u)},Mr=[],no=[],lv=[],cs={},cv=u=>{var d=u.Nc;delete cs[d],Mr.push(u),no.splice(no.indexOf(u),1),u.Nc=0,yk(d)};function uv(){lv.forEach(u=>u())}var pv=u=>new Promise(d=>{u.onmessage=v=>{var M=v.data;if(v=M.Oc,M.Vc&&M.Vc!=ec()){var P=cs[M.Vc];P?P.postMessage(M,M.Yc):T(`Internal error! Worker sent a message "${v}" to target pthread ${M.Vc}, but that thread no longer exists!`)}else v==="checkMailbox"?Xl():v==="spawnThread"?tr(M):v==="cleanupThread"?Mt(()=>{cv(cs[M.he])}):v==="loaded"?(u.loaded=!0,d(u)):M.target==="setimmediate"?u.postMessage(M):v==="uncaughtException"?u.onerror(M.error):v==="callHandler"?e[M.be](...M.args):v&&T(`worker sent an unknown command ${v}`)},u.onerror=v=>{throw T(`worker sent an error! ${v.filename}:${v.lineno}: ${v.message}`),v};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);u.postMessage({Oc:"load",ce:g,ie:Tr,je:_})});function fv(){var u=new Worker((()=>{let d=URL;return import_meta.url>"file:"&&import_meta.url<"file;"?new d("ort.webgpu.bundle.min.mjs",import_meta.url):new URL(import_meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Mr.push(u)}var Tr,AT=(u,d)=>{Oe=0,u=Ef(u,d),0-9007199254740992>u||9007199254740992>>=0);return(b(),U)[d.Qc+12>>>0]==0&&(dv(d,!0),Hl--),_v(d,!1),Vl.push(d),Mk(u)}var Ks=0,TT=()=>{xe(0,0);var u=Vl.pop();Ek(u.Xc),Ks=0};function dv(u,d){d=d?1:0,(b(),U)[u.Qc+12>>>0]=d}function _v(u,d){d=d?1:0,(b(),U)[u.Qc+13>>>0]=d}class Jp{constructor(d){this.Xc=d,this.Qc=d-24}}var Zp=u=>{var d=Ks;if(!d)return lo(0),0;var h=new Jp(d);(b(),C)[h.Qc+16>>>2>>>0]=d;var g=(b(),C)[h.Qc+4>>>2>>>0];if(!g)return lo(0),d;for(var v of u){if(v===0||v===g)break;if(Ak(v,g,h.Qc+16))return lo(v),d}return lo(g),d};function ST(){return Zp([])}function OT(u){return Zp([u>>>0])}function IT(u,d,h,g){return Zp([u>>>0,d>>>0,h>>>0,g>>>0])}var CT=()=>{var u=Vl.pop();u||ce("no exception to throw");var d=u.Xc;throw(b(),U)[u.Qc+13>>>0]==0&&(Vl.push(u),_v(u,!0),dv(u,!1),Hl++),kf(d),Ks=d};function PT(u,d,h){var g=new Jp(u>>>=0);throw d>>>=0,h>>>=0,(b(),C)[g.Qc+16>>>2>>>0]=0,(b(),C)[g.Qc+4>>>2>>>0]=d,(b(),C)[g.Qc+8>>>2>>>0]=h,kf(u),Hl++,Ks=u}var zT=()=>Hl;function mv(u,d,h,g){return n?Be(2,1,u,d,h,g):hv(u,d,h,g)}function hv(u,d,h,g){if(u>>>=0,d>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var v=[];return n&&v.length===0?mv(u,d,h,g):(u={fe:h,Nc:u,Wc:g,Yc:v},n?(u.Oc="spawnThread",postMessage(u,v),0):tr(u))}function LT(u){throw Ks||=u>>>0,Ks}var gv=globalThis.TextDecoder&&new TextDecoder,wv=(u,d,h,g)=>{if(h=d+h,g)return h;for(;u[d]&&!(d>=h);)++d;return d},xv=(u,d=0,h,g)=>{if(16<(h=wv(u,d>>>=0,h,g))-d&&u.buffer&&gv)return gv.decode(u.buffer instanceof ArrayBuffer?u.subarray(d,h):u.slice(d,h));for(g="";d(v=(240&v)==224?(15&v)<<12|M<<6|P:(7&v)<<18|M<<12|P<<6|63&u[d++])?g+=String.fromCharCode(v):(v-=65536,g+=String.fromCharCode(55296|v>>10,56320|1023&v))}}else g+=String.fromCharCode(v)}return g},Ys=(u,d,h)=>(u>>>=0)?xv((b(),X),u,d,h):"";function yv(u,d,h){return n?Be(3,1,u,d,h):0}function bv(u,d){if(n)return Be(4,1,u,d)}function vv(u,d){if(n)return Be(5,1,u,d)}function kv(u,d,h){if(n)return Be(6,1,u,d,h)}function Ev(u,d,h){return n?Be(7,1,u,d,h):0}function Av(u,d){if(n)return Be(8,1,u,d)}function Mv(u,d,h){if(n)return Be(9,1,u,d,h)}function Tv(u,d,h,g){if(n)return Be(10,1,u,d,h,g)}function Sv(u,d,h,g){if(n)return Be(11,1,u,d,h,g)}function Ov(u,d,h,g){if(n)return Be(12,1,u,d,h,g)}function Iv(u){if(n)return Be(13,1,u)}function Cv(u,d){if(n)return Be(14,1,u,d)}function Pv(u,d,h){if(n)return Be(15,1,u,d,h)}var NT=()=>ce(""),rr=u=>{u>>>=0;for(var d="";;){var h=(b(),X)[u++>>>0];if(!h)return d;d+=String.fromCharCode(h)}},ef={},tf={},$T={},Qs=class extends Error{constructor(u){super(u),this.name="BindingError"}};function dr(u,d,h={}){return(function(g,v,M={}){var P=v.name;if(!g)throw new Qs(`type "${P}" must have a positive integer typeid pointer`);if(tf.hasOwnProperty(g)){if(M.de)return;throw new Qs(`Cannot register type '${P}' twice`)}tf[g]=v,delete $T[g],ef.hasOwnProperty(g)&&(v=ef[g],delete ef[g],v.forEach(L=>L()))})(u,d,h)}var zv=(u,d,h)=>{switch(d){case 1:return h?g=>(b(),U)[g>>>0]:g=>(b(),X)[g>>>0];case 2:return h?g=>(b(),K)[g>>>1>>>0]:g=>(b(),J)[g>>>1>>>0];case 4:return h?g=>(b(),R)[g>>>2>>>0]:g=>(b(),C)[g>>>2>>>0];case 8:return h?g=>(b(),z)[g>>>3>>>0]:g=>(b(),$)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${u}`)}};function RT(u,d,h,g,v){u>>>=0,h>>>=0,d=rr(d>>>0);let M=P=>P;if(g=g===0n){let P=8*h;M=L=>BigInt.asUintN(P,L),v=M(v)}dr(u,{name:d,Mc:M,Sc:(P,L)=>(typeof L=="number"&&(L=BigInt(L)),L),Rc:zv(d,h,!g),Tc:null})}function DT(u,d,h,g){dr(u>>>=0,{name:d=rr(d>>>0),Mc:function(v){return!!v},Sc:function(v,M){return M?h:g},Rc:function(v){return this.Mc((b(),X)[v>>>0])},Tc:null})}var Lv=[],us=[0,1,,1,null,1,!0,1,!1,1];function rf(u){9<(u>>>=0)&&--us[u+1]==0&&(us[u]=void 0,Lv.push(u))}var Rt=u=>{if(!u)throw new Qs(`Cannot use deleted val. handle = ${u}`);return us[u]},qt=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=Lv.pop()||us.length;return us[d]=u,us[d+1]=1,d}};function sf(u){return this.Mc((b(),C)[u>>>2>>>0])}var FT={name:"emscripten::val",Mc:u=>{var d=Rt(u);return rf(u),d},Sc:(u,d)=>qt(d),Rc:sf,Tc:null};function BT(u){return dr(u>>>0,FT)}var UT=(u,d)=>{switch(d){case 4:return function(h){return this.Mc((b(),se)[h>>>2>>>0])};case 8:return function(h){return this.Mc((b(),Y)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${u}`)}};function jT(u,d,h){h>>>=0,dr(u>>>=0,{name:d=rr(d>>>0),Mc:g=>g,Sc:(g,v)=>v,Rc:UT(d,h),Tc:null})}function GT(u,d,h,g,v){u>>>=0,h>>>=0,d=rr(d>>>0);let M=L=>L;if(g===0){var P=32-8*h;M=L=>L<

>>P,v=M(v)}dr(u,{name:d,Mc:M,Sc:(L,G)=>G,Rc:zv(d,h,g!==0),Tc:null})}function qT(u,d,h){function g(M){var P=(b(),C)[M>>>2>>>0];return M=(b(),C)[M+4>>>2>>>0],new v((b(),U).buffer,M,P)}var v=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];dr(u>>>=0,{name:h=rr(h>>>0),Mc:g,Rc:g},{de:!0})}var _r=(u,d,h)=>{var g=(b(),X);if(d>>>=0,0=P){if(d>=h)break;g[d++>>>0]=P}else if(2047>=P){if(d+1>=h)break;g[d++>>>0]=192|P>>6,g[d++>>>0]=128|63&P}else if(65535>=P){if(d+2>=h)break;g[d++>>>0]=224|P>>12,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P}else{if(d+3>=h)break;g[d++>>>0]=240|P>>18,g[d++>>>0]=128|P>>12&63,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P,M++}}g[d>>>0]=0,u=d-v}else u=0;return u},mr=u=>{for(var d=0,h=0;h=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++h):d+=3}return d};function WT(u,d){dr(u>>>=0,{name:d=rr(d>>>0),Mc(h){var g=(b(),C)[h>>>2>>>0];return g=Ys(h+4,g,!0),Wt(h),g},Sc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var v=typeof g=="string";if(!(v||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Qs("Cannot pass non-string to std::string");var M=v?mr(g):g.length,P=Zs(4+M+1),L=P+4;return(b(),C)[P>>>2>>>0]=M,v?_r(g,L,M+1):(b(),X).set(g,L>>>0),h!==null&&h.push(Wt,P),P},Rc:sf,Tc(h){Wt(h)}})}var Nv=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,VT=(u,d,h)=>{if(u>>>=1,16<(d=wv((b(),J),u,d/2,h))-u&&Nv)return Nv.decode((b(),J).slice(u,d));for(h="";u>>0];h+=String.fromCharCode(g)}return h},HT=(u,d,h)=>{if(h??=2147483647,2>h)return 0;var g=d;h=(h-=2)<2*u.length?h/2:u.length;for(var v=0;v>>1>>>0]=M,d+=2}return(b(),K)[d>>>1>>>0]=0,d-g},XT=u=>2*u.length,KT=(u,d,h)=>{var g="";u>>>=2;for(var v=0;!(v>=d/4);v++){var M=(b(),C)[u+v>>>0];if(!M&&!h)break;g+=String.fromCodePoint(M)}return g},YT=(u,d,h)=>{if(d>>>=0,h??=2147483647,4>h)return 0;var g=d;h=g+h-4;for(var v=0;v>>2>>>0]=M,(d+=4)+4>h)break}return(b(),R)[d>>>2>>>0]=0,d-g},QT=u=>{for(var d=0,h=0;h>>=0,d>>>=0,h=rr(h>>>=0),d===2)var g=VT,v=HT,M=XT;else g=KT,v=YT,M=QT;dr(u,{name:h,Mc:P=>{var L=(b(),C)[P>>>2>>>0];return L=g(P+4,L*d,!0),Wt(P),L},Sc:(P,L)=>{if(typeof L!="string")throw new Qs(`Cannot pass non-string to C++ string type ${h}`);var G=M(L),Z=Zs(4+G+d);return(b(),C)[Z>>>2>>>0]=G/d,v(L,Z+4,G+d),P!==null&&P.push(Wt,Z),Z},Rc:sf,Tc(P){Wt(P)}})}function ZT(u,d){dr(u>>>=0,{ee:!0,name:d=rr(d>>>0),Mc:()=>{},Sc:()=>{}})}function eS(u){yf(u>>>0,!s,1,!r,131072,!1),uv()}var Mt=u=>{if(!I)try{if(u(),!(0Number(((navigator.userAgent||"").match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function nf(u){u>>>=0,tS||(Atomics.waitAsync((b(),R),u>>>2,u).value.then(Xl),u+=128,Atomics.store((b(),R),u>>>2,1))}var Xl=()=>Mt(()=>{var u=ec();u&&(nf(u),vk())});function rS(u,d){(u>>>=0)==d>>>0?setTimeout(Xl):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=cs[u])&&u.postMessage({Oc:"checkMailbox"})}var of=[];function sS(u,d,h,g,v){for(d>>>=0,v>>>=0,of.length=0,h=v>>>3,g=v+g>>>3;h>>0]?(b(),z)[h++>>>0]:(b(),Y)[h++>>>0],of.push(M)}return(d?Af[d]:UO[u])(...of)}var nS=()=>{Oe=0};function oS(u){u>>>=0,n?postMessage({Oc:"cleanupThread",he:u}):cv(cs[u])}function aS(u){}var Kl=u=>{try{u()}catch(d){ce(d)}};function iS(u){var d=(...h)=>{Yl.push(u);try{return u(...h)}finally{I||(Yl.pop(),sr&&Sr===1&&Yl.length===0&&(Sr=0,Oe+=1,Kl(cE),typeof Fibers<"u"&&Fibers.Be()))}};return Dv.set(u,d),d}var Sr=0,sr=null,$v=0,Yl=[],af=new Map,Rv=new Map,Dv=new Map,lS=0,lf=null,cS=[],Fv=u=>(function(d){if(!I){if(Sr===0){var h=!1,g=!1;d((v=0)=>{if(!I&&($v=v,h=!0,g)){Sr=2,Kl(()=>uE(sr)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),v=!1;try{var M=(function(){var G=(b(),R)[sr+8>>>2>>>0];return G=Rv.get(G),G=Dv.get(G),--Oe,G()})()}catch(G){M=G,v=!0}var P=!1;if(!sr){var L=lf;L&&(lf=null,(v?L.reject:L.resolve)(M),P=!0)}if(v&&!P)throw M}}),g=!0,h||(Sr=1,sr=(function(){var v=Zs(65548),M=v+12;if((b(),C)[v>>>2>>>0]=M,(b(),C)[v+4>>>2>>>0]=M+65536,M=Yl[0],!af.has(M)){var P=lS++;af.set(M,P),Rv.set(P,M)}return M=af.get(M),(b(),R)[v+8>>>2>>>0]=M,v})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Kl(()=>lE(sr)))}else Sr===2?(Sr=0,Kl(pE),Wt(sr),sr=null,cS.forEach(Mt)):ce(`invalid state: ${Sr}`);return $v}})(d=>{u().then(d)});function uS(u){return u>>>=0,Fv(async()=>{var d=await Rt(u);return qt(d)})}var cf=[],pS=u=>{var d=cf.length;return cf.push(u),d},fS=(u,d)=>{for(var h=Array(u),g=0;g>>2>>>0],P=tf[M];if(P===void 0)throw u=`parameter ${g}`,M=nk(M),d=rr(M),Wt(M),new Qs(`${u} has unknown type ${d}`);h[v]=P}return h},dS=(u,d,h)=>{var g=[];return u=u(g,h),g.length&&((b(),C)[d>>>2>>>0]=qt(g)),u},_S={},Ql=u=>{var d=_S[u];return d===void 0?rr(u):d};function mS(u,d,h){var[g,...v]=fS(u,d>>>0);d=g.Sc.bind(g);var M=v.map(G=>G.Rc.bind(G));u--;var P={toValue:Rt};switch(u=M.map((G,Z)=>{var Ie=`argFromPtr${Z}`;return P[Ie]=G,`${Ie}(args${Z?"+"+8*Z:""})`}),h){case 0:var L="toValue(handle)";break;case 2:L="new (toValue(handle))";break;case 3:L="";break;case 1:P.getStringOrSymbol=Ql,L="toValue(handle)[getStringOrSymbol(methodName)]"}return L+=`(${u})`,g.ee||(P.toReturnWire=d,P.emval_returnValue=dS,L=`return emval_returnValue(toReturnWire, destructorsRef, ${L})`),L=`return function (handle, methodName, destructorsRef, args) { + ${L} +- }`,h=new Function(Object.keys(P),L)(...Object.values(P)),L=`methodCaller<(${v.map(G=>G.name)}) => ${g.name}>`,pS(Object.defineProperty(h,"name",{value:L}))}function hS(u,d){return d>>>=0,(u=Rt(u>>>0))==Rt(d)}function gS(u){return(u>>>=0)?(u=Ql(u),qt(globalThis[u])):qt(globalThis)}function wS(u){return u=Ql(u>>>0),qt(e[u])}function xS(u,d){return d>>>=0,u=Rt(u>>>0),d=Rt(d),qt(u[d])}function yS(u){9<(u>>>=0)&&(us[u+1]+=1)}function Bv(u,d,h,g,v){return cf[u>>>0](d>>>0,h>>>0,g>>>0,v>>>0)}function bS(u,d,h,g,v){return Bv(u>>>0,d>>>0,h>>>0,g>>>0,v>>>0)}function vS(){return qt([])}function kS(u){u=Rt(u>>>0);for(var d=Array(u.length),h=0;h>>0))}function AS(){return qt({})}function MS(u){for(var d=Rt(u>>>=0);d.length;){var h=d.pop();d.pop()(h)}rf(u)}function TS(u,d,h){d>>>=0,h>>>=0,u=Rt(u>>>0),d=Rt(d),h=Rt(h),u[d]=h}function SS(u,d){u=mt(u),d>>>=0,u=new Date(1e3*u),(b(),R)[d>>>2>>>0]=u.getUTCSeconds(),(b(),R)[d+4>>>2>>>0]=u.getUTCMinutes(),(b(),R)[d+8>>>2>>>0]=u.getUTCHours(),(b(),R)[d+12>>>2>>>0]=u.getUTCDate(),(b(),R)[d+16>>>2>>>0]=u.getUTCMonth(),(b(),R)[d+20>>>2>>>0]=u.getUTCFullYear()-1900,(b(),R)[d+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(b(),R)[d+28>>>2>>>0]=u}var Uv=u=>u%4==0&&(u%100!=0||u%400==0),jv=[0,31,60,91,121,152,182,213,244,274,305,335],Gv=[0,31,59,90,120,151,181,212,243,273,304,334];function OS(u,d){u=mt(u),d>>>=0,u=new Date(1e3*u),(b(),R)[d>>>2>>>0]=u.getSeconds(),(b(),R)[d+4>>>2>>>0]=u.getMinutes(),(b(),R)[d+8>>>2>>>0]=u.getHours(),(b(),R)[d+12>>>2>>>0]=u.getDate(),(b(),R)[d+16>>>2>>>0]=u.getMonth(),(b(),R)[d+20>>>2>>>0]=u.getFullYear()-1900,(b(),R)[d+24>>>2>>>0]=u.getDay();var h=(Uv(u.getFullYear())?jv:Gv)[u.getMonth()]+u.getDate()-1|0;(b(),R)[d+28>>>2>>>0]=h,(b(),R)[d+36>>>2>>>0]=-60*u.getTimezoneOffset(),h=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(h!=g&&u.getTimezoneOffset()==Math.min(g,h)),(b(),R)[d+32>>>2>>>0]=u}function IS(u){u>>>=0;var d=new Date((b(),R)[u+20>>>2>>>0]+1900,(b(),R)[u+16>>>2>>>0],(b(),R)[u+12>>>2>>>0],(b(),R)[u+8>>>2>>>0],(b(),R)[u+4>>>2>>>0],(b(),R)[u>>>2>>>0],0),h=(b(),R)[u+32>>>2>>>0],g=d.getTimezoneOffset(),v=new Date(d.getFullYear(),6,1).getTimezoneOffset(),M=new Date(d.getFullYear(),0,1).getTimezoneOffset(),P=Math.min(M,v);return 0>h?(b(),R)[u+32>>>2>>>0]=+(v!=M&&P==g):0>>2>>>0]=d.getDay(),h=(Uv(d.getFullYear())?jv:Gv)[d.getMonth()]+d.getDate()-1|0,(b(),R)[u+28>>>2>>>0]=h,(b(),R)[u>>>2>>>0]=d.getSeconds(),(b(),R)[u+4>>>2>>>0]=d.getMinutes(),(b(),R)[u+8>>>2>>>0]=d.getHours(),(b(),R)[u+12>>>2>>>0]=d.getDate(),(b(),R)[u+16>>>2>>>0]=d.getMonth(),(b(),R)[u+20>>>2>>>0]=d.getYear(),u=d.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function qv(u,d,h,g,v,M,P){return n?Be(16,1,u,d,h,g,v,M,P):-52}function Wv(u,d,h,g,v,M){if(n)return Be(17,1,u,d,h,g,v,M)}var oo={},CS=()=>performance.timeOrigin+performance.now();function Vv(u,d){if(n)return Be(18,1,u,d);if(oo[u]&&(clearTimeout(oo[u].id),delete oo[u]),!d)return 0;var h=setTimeout(()=>{delete oo[u],Mt(()=>bk(u,performance.timeOrigin+performance.now()))},d);return oo[u]={id:h,Ae:d},0}function PS(u,d,h,g){u>>>=0,d>>>=0,h>>>=0,g>>>=0;var v=new Date().getFullYear(),M=new Date(v,0,1).getTimezoneOffset();v=new Date(v,6,1).getTimezoneOffset();var P=Math.max(M,v);(b(),C)[u>>>2>>>0]=60*P,(b(),R)[d>>>2>>>0]=+(M!=v),u=(d=L=>{var G=Math.abs(L);return`UTC${0<=L?"-":"+"}${String(Math.floor(G/60)).padStart(2,"0")}${String(G%60).padStart(2,"0")}`})(M),d=d(v),vDate.now(),LS=1;function NS(u,d,h){if(h>>>=0,!(0<=u&&3>=u))return 28;if(u===0)u=Date.now();else{if(!LS)return 52;u=performance.timeOrigin+performance.now()}return u=Math.round(1e6*u),(b(),z)[h>>>3>>>0]=BigInt(u),0}var uf=[],Hv=(u,d)=>{uf.length=0;for(var h;h=(b(),X)[u++>>>0];){var g=h!=105;d+=(g&=h!=112)&&d%8?4:0,uf.push(h==112?(b(),C)[d>>>2>>>0]:h==106?(b(),z)[d>>>3>>>0]:h==105?(b(),R)[d>>>2>>>0]:(b(),Y)[d>>>3>>>0]),d+=g?8:4}return uf};function $S(u,d,h){return u>>>=0,d=Hv(d>>>0,h>>>0),Af[u](...d)}function RS(u,d,h){return u>>>=0,d=Hv(d>>>0,h>>>0),Af[u](...d)}var DS=()=>{};function FS(u,d){return T(Ys(u>>>0,d>>>0))}var BS=()=>{throw Oe+=1,"unwind"};function US(){return 4294901760}var jS=()=>1,GS=()=>navigator.hardwareConcurrency;function qS(u){u>>>=0;var d=(b(),X).length;if(u<=d||4294901760=h;h*=2){var g=d*(1+.2/h);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-Tr.buffer.byteLength+65535)/65536|0;try{Tr.grow(g),le();var v=1;break e}catch{}v=void 0}if(v)return!0}return!1}var nr=u=>{var d=mr(u)+1,h=tc(d);return _r(u,h,d),h},pf=(u,d)=>{(b(),C)[u>>>2>>>0]=d;var h=(b(),C)[u>>>2>>>0];(b(),C)[u+4>>>2>>>0]=(d-h)/4294967296},ao=u=>(b(),C)[u>>>2>>>0]+4294967296*(b(),R)[u+4>>>2>>>0],ht=[],WS=(u,d)=>{ht[u>>>0]=d},hr=[],Jl=[],Js=(u,d)=>{Jl[u]=new Promise(h=>d.finally(()=>h(u)))},oe=u=>{if(u)return ht[u>>>0]},VS=(u,d)=>{for(u=(b(),C)[u>>>2>>>0];u;u=(b(),C)[u>>>2>>>0])d[(b(),R)[u+4>>>2>>>0]](u)},Zl=(u,d,h)=>{(b(),C)[u>>>2>>>0]=d,(b(),C)[u+4>>>2>>>0]=h},Xv=u=>{var d=(b(),C)[u>>>2>>>0];return u=(b(),C)[u+4>>>2>>>0],Ys(d,u)},gr=u=>{var d=(b(),C)[u>>>2>>>0];return u=(b(),C)[u+4>>>2>>>0],d?Ys(d,u):u===0?"":void 0},HS=u=>{var d=gr(u+4),h=(h=(b(),C)[u+12>>>2>>>0])?oe(h):"auto";if(u+=16){var g=oe((b(),C)[u+4>>>2>>>0]),v=(b(),C)[u+16>>>2>>>0],M=(b(),C)[u+20>>>2>>>0];if(v){for(var P={},L=0;L>>3>>>0]}v=P}else v=void 0;u={module:g,constants:v,entryPoint:gr(u+8)}}else u=void 0;return{label:d,layout:h,compute:u}},Kv=(u,d)=>{function h(g,v){g=u[g],(b(),C)[d+v>>>2>>>0]=g}h("maxTextureDimension1D",4),h("maxTextureDimension2D",8),h("maxTextureDimension3D",12),h("maxTextureArrayLayers",16),h("maxBindGroups",20),h("maxBindGroupsPlusVertexBuffers",24),h("maxBindingsPerBindGroup",28),h("maxDynamicUniformBuffersPerPipelineLayout",32),h("maxDynamicStorageBuffersPerPipelineLayout",36),h("maxSampledTexturesPerShaderStage",40),h("maxSamplersPerShaderStage",44),h("maxStorageBuffersPerShaderStage",48),h("maxStorageTexturesPerShaderStage",52),h("maxUniformBuffersPerShaderStage",56),h("minUniformBufferOffsetAlignment",80),h("minStorageBufferOffsetAlignment",84),pf(d+64,u.maxUniformBufferBindingSize),pf(d+72,u.maxStorageBufferBindingSize),h("maxVertexBuffers",88),pf(d+96,u.maxBufferSize),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),u.ze!==void 0&&h("maxImmediateSize",148)},XS=[,"validation","out-of-memory","internal"],KS=[,"compatibility","core"],Yv={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},YS=[,"low-power","high-performance"],QS=[,"occlusion","timestamp"],JS={undefined:1,unknown:1,destroyed:2};function ZS(u,d,h,g,v,M){d=mt(d),h=mt(h),g>>>=0,v>>>=0,M>>>=0;var P=oe(u>>>0);if(u={},M){var L=(b(),C)[M+12>>>2>>>0];if(L){var G=(b(),C)[M+16>>>2>>>0];u.requiredFeatures=Array.from((b(),C).subarray(G>>>2>>>0,G+4*L>>>2>>>0),ae=>Yv[ae])}var Z=(b(),C)[M+20>>>2>>>0];if(Z){let ae=function(Tt,pt,ps=!1){pt=Z+pt,(pt=(b(),C)[pt>>>2>>>0])==4294967295||ps&&pt==0||(Ue[Tt]=pt)},ut=function(Tt,pt){pt=Z+pt;var ps=(b(),C)[pt>>>2>>>0],EI=(b(),C)[pt+4>>>2>>>0];ps==4294967295&&EI==4294967295||(Ue[Tt]=ao(pt))};var Ie=ae,Ne=ut,Ue={};ae("maxTextureDimension1D",4),ae("maxTextureDimension2D",8),ae("maxTextureDimension3D",12),ae("maxTextureArrayLayers",16),ae("maxBindGroups",20),ae("maxBindGroupsPlusVertexBuffers",24),ae("maxDynamicUniformBuffersPerPipelineLayout",32),ae("maxDynamicStorageBuffersPerPipelineLayout",36),ae("maxSampledTexturesPerShaderStage",40),ae("maxSamplersPerShaderStage",44),ae("maxStorageBuffersPerShaderStage",48),ae("maxStorageTexturesPerShaderStage",52),ae("maxUniformBuffersPerShaderStage",56),ae("minUniformBufferOffsetAlignment",80),ae("minStorageBufferOffsetAlignment",84),ut("maxUniformBufferBindingSize",64),ut("maxStorageBufferBindingSize",72),ae("maxVertexBuffers",88),ut("maxBufferSize",96),ae("maxVertexAttributes",104),ae("maxVertexBufferArrayStride",108),ae("maxInterStageShaderVariables",112),ae("maxColorAttachments",116),ae("maxColorAttachmentBytesPerSample",120),ae("maxComputeWorkgroupStorageSize",124),ae("maxComputeInvocationsPerWorkgroup",128),ae("maxComputeWorkgroupSizeX",132),ae("maxComputeWorkgroupSizeY",136),ae("maxComputeWorkgroupSizeZ",140),ae("maxComputeWorkgroupsPerDimension",144),ae("maxImmediateSize",148,!0),u.requiredLimits=Ue}(L=(b(),C)[M+24>>>2>>>0])&&(L={label:gr(L+4)},u.defaultQueue=L),u.label=gr(M+4)}Oe+=1,Js(d,P.requestDevice(u).then(ae=>{--Oe,Mt(()=>{ht[v>>>0]=ae.queue,ht[g>>>0]=ae,Oe+=1,Js(h,ae.lost.then(ut=>{Mt(()=>{ae.onuncapturederror=()=>{};var Tt=fe(),pt=nr(ut.message);hf(h,JS[ut.reason],pt),pe(Tt)}),--Oe})),ae.onuncapturederror=ut=>{var Tt=5;ut.error instanceof GPUValidationError?Tt=2:ut.error instanceof GPUOutOfMemoryError?Tt=3:ut.error instanceof GPUInternalError&&(Tt=4);var pt=fe();ut=nr(ut.error.message),gk(g,Tt,ut),pe(pt)},"adapterInfo"in ae||(ae.adapterInfo=P.info),xf(d,1,g,0)})},ae=>{--Oe,Mt(()=>{var ut=fe(),Tt=nr(ae.message);xf(d,3,g,Tt),h&&hf(h,4,Tt),pe(ut)})}))}function eO(u){var d=oe(u>>>=0),h=hr[u];if(h){for(var g=0;g>>=0;var g=oe(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(d>>>0,h)}catch{return 0}var M=vf(16,v.byteLength);return(b(),X).set(new Uint8Array(v),M>>>0),hr[u].push(()=>Wt(M)),M}function rO(u,d,h){h>>>=0;var g=oe(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(d>>>0,h)}catch{return 0}var M=vf(16,v.byteLength);return(b(),X).fill(0,M,v.byteLength),hr[u].push(()=>{new Uint8Array(v).set((b(),X).subarray(M>>>0,M+v.byteLength>>>0)),Wt(M)}),M}function sO(u,d,h,g,v){u>>>=0,d=mt(d),h=mt(h),v>>>=0;var M=oe(u);hr[u]=[],v==4294967295&&(v=void 0),Oe+=1,Js(d,M.mapAsync(h,g>>>0,v).then(()=>{--Oe,Mt(()=>{gf(d,1,0)})},P=>{--Oe,Mt(()=>{fe();var L=nr(P.message);gf(d,P.name==="AbortError"?4:P.name==="OperationError"?3:0,L),delete hr[u]})}))}function nO(u){var d=oe(u>>>=0),h=hr[u];if(h){for(var g=0;g>>0]}function aO(u,d,h){u>>>=0,d>>>=0,h>>>=0;var g=!!(b(),C)[d+32>>>2>>>0];d={label:gr(d+4),usage:(b(),C)[d+16>>>2>>>0],size:ao(d+24),mappedAtCreation:g},u=oe(u);try{var v=u.createBuffer(d)}catch{return!1}return ht[h>>>0]=v,g&&(hr[h]=[]),!0}function iO(u,d,h,g){u>>>=0,d=mt(d),g>>>=0,h=HS(h>>>0),u=oe(u),Oe+=1,Js(d,u.createComputePipelineAsync(h).then(v=>{--Oe,Mt(()=>{ht[g>>>0]=v,mf(d,1,g,0)})},v=>{--Oe,Mt(()=>{var M=fe(),P=nr(v.message);mf(d,v.reason==="validation"?3:v.reason==="internal"?4:0,g,P),pe(M)})}))}function lO(u,d,h){u>>>=0,d>>>=0,h>>>=0;var g=(b(),C)[d>>>2>>>0],v=(b(),R)[g+4>>>2>>>0];d={label:gr(d+4),code:""},v===2&&(d.code=Xv(g+8)),u=oe(u).createShaderModule(d),ht[h>>>0]=u}var cO=u=>{(u=oe(u)).onuncapturederror=null,u.destroy()};function uO(u,d){d=mt(d),u=oe(u>>>0),Oe+=1,Js(d,u.popErrorScope().then(h=>{--Oe,Mt(()=>{var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var v=fe(),M=h?nr(h.message):0;wf(d,1,g,M),pe(v)})},h=>{--Oe,Mt(()=>{var g=fe(),v=nr(h.message);wf(d,1,5,v),pe(g)})}))}function pO(u,d,h,g){if(d=mt(d),g>>>=0,h>>>=0){var v={featureLevel:KS[(b(),R)[h+4>>>2>>>0]],powerPreference:YS[(b(),R)[h+8>>>2>>>0]],forceFallbackAdapter:!!(b(),C)[h+12>>>2>>>0]};(u=(b(),C)[h>>>2>>>0])!==0&&(b(),v.De=!!(b(),C)[u+8>>>2>>>0])}"gpu"in navigator?(Oe+=1,Js(d,navigator.gpu.requestAdapter(v).then(M=>{--Oe,Mt(()=>{if(M)ht[g>>>0]=M,io(d,1,g,0);else{var P=fe(),L=nr("WebGPU not available on this browser (requestAdapter returned null)");io(d,3,g,L),pe(P)}})},M=>{--Oe,Mt(()=>{var P=fe(),L=nr(M.message);io(d,4,g,L),pe(P)})}))):(v=fe(),u=nr("WebGPU not available on this browser (navigator.gpu is not available)"),io(d,3,g,u),pe(v))}function fO(u,d,h){return u>>>=0,d>>>=0,h>>>=0,Fv(async()=>{var g=[];if(h){var v=(b(),R)[h>>>2>>>0];g.length=d+1,g[d]=new Promise(L=>setTimeout(L,v,0))}else g.length=d;for(var M=0;M{if(!ff){var u,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in df)df[u]===void 0?delete d[u]:d[u]=df[u];var h=[];for(u in d)h.push(`${u}=${d[u]}`);ff=h}return ff};function Jv(u,d){if(n)return Be(19,1,u,d);u>>>=0,d>>>=0;var h,g=0,v=0;for(h of Qv()){var M=d+g;(b(),C)[u+v>>>2>>>0]=M,g+=_r(h,M,1/0)+1,v+=4}return 0}function Zv(u,d){if(n)return Be(20,1,u,d);u>>>=0,d>>>=0;var h=Qv();for(var g of((b(),C)[u>>>2>>>0]=h.length,u=0,h))u+=mr(g)+1;return(b(),C)[d>>>2>>>0]=u,0}function ek(u){return n?Be(21,1,u):52}function tk(u,d,h,g){return n?Be(22,1,u,d,h,g):52}function rk(u,d,h,g){return n?Be(23,1,u,d,h,g):70}var dO=[null,[],[]];function sk(u,d,h,g){if(n)return Be(24,1,u,d,h,g);d>>>=0,h>>>=0,g>>>=0;for(var v=0,M=0;M>>2>>>0],L=(b(),C)[d+4>>>2>>>0];d+=8;for(var G=0;G>>0],Ne=dO[Z];Ie===0||Ie===10?((Z===1?S:T)(xv(Ne)),Ne.length=0):Ne.push(Ie)}v+=L}return(b(),C)[g>>>2>>>0]=v,0}function _O(u){return u>>>0}function mO(u,d){return Kv(oe(u>>>0).limits,d>>>0),1}function hO(u,d){return oe(u>>>0).features.has(Yv[d])}function gO(u){return BigInt(oe(u>>>0).size)}function wO(u){return BigInt(oe(u>>>0).usage)}function xO(u,d){if(u>>>=0,d>>>=0){var h=gr(d+4);h={label:h,timestampWrites:d=(d=(b(),C)[d+12>>>2>>>0])!==0?{querySet:oe((b(),C)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(b(),C)[d+8>>>2>>>0],endOfPassWriteIndex:(b(),C)[d+12>>>2>>>0]}:void 0}}return d=oe(u),u=fk(0),h=d.beginComputePass(h),ht[u>>>0]=h,u}function yO(u,d,h,g){h=mt(h),(g=mt(g))==-1&&(g=void 0),(u=oe(u>>>0)).clearBuffer(oe(d>>>0),h,g)}function bO(u,d,h,g,v,M){h=mt(h),v=mt(v),M=mt(M),oe(u>>>0).copyBufferToBuffer(oe(d>>>0),h,oe(g>>>0),v,M)}function vO(u){var d=oe(u>>>0);return u=uk(0),d=d.finish(),ht[u>>>0]=d,u}function kO(u,d,h,g,v,M){M=mt(M),oe(u>>>0).resolveQuerySet(oe(d>>>0),h,g,oe(v>>>0),M)}function EO(u,d,h,g){oe(u>>>0).dispatchWorkgroups(d,h,g)}function AO(u,d,h){h=mt(h),oe(u>>>0).dispatchWorkgroupsIndirect(oe(d>>>0),h)}function MO(u){oe(u>>>0).end()}function TO(u,d,h,g,v){g>>>=0,v>>>=0,u=oe(u>>>0),h=oe(h>>>0),g==0?u.setBindGroup(d,h):u.setBindGroup(d,h,(b(),C),v>>>2,g)}function SO(u,d){oe(u>>>0).setPipeline(oe(d>>>0))}function OO(u,d,h){oe(u>>>0).Ce(oe(d>>>0),h)}function IO(u,d){var h=oe(u>>>0);return u=ck(0),d=h.getBindGroupLayout(d),ht[u>>>0]=d,u}function CO(u,d){function h(v){var M=(b(),C)[v+8>>>2>>>0],P=(b(),C)[v+32>>>2>>>0],L=(b(),C)[v+36>>>2>>>0],G=0;return VS(v,{327681:Z=>{G=(b(),C)[Z+8>>>2>>>0]}}),M?((P=ao(v+24))==-1&&(P=void 0),M={buffer:oe(M),offset:ao(v+16),size:P}):M=oe(P||L||G),{binding:(b(),C)[v+4>>>2>>>0],resource:M}}u>>>=0,d={label:gr(4+(d>>>=0)),layout:oe((b(),C)[d+12>>>2>>>0]),entries:(function(v,M){for(var P=[],L=0;L>>2>>>0],(b(),C)[d+20>>>2>>>0])},u=oe(u);var g=lk(0);return WS(g,u.createBindGroup(d)),g}function PO(u,d){var h;return u>>>=0,(d>>>=0)&&(h={label:gr(d+4)}),d=oe(u),u=pk(0),h=d.createCommandEncoder(h),ht[u>>>0]=h,u}function zO(u,d){u>>>=0,d>>>=0,d={type:QS[(b(),R)[d+12>>>2>>>0]],count:(b(),C)[d+16>>>2>>>0]};var h=oe(u);return u=dk(0),d=h.createQuerySet(d),ht[u>>>0]=d,u}function LO(u,d){u=oe(u>>>0).adapterInfo,d>>>=0,(b(),C)[d+52>>>2>>>0]=u.subgroupMinSize,(b(),C)[d+56>>>2>>>0]=u.subgroupMaxSize;var h=u.vendor+u.architecture+u.device+u.description,g=mr(h)+1,v=Zs(g);return v&&_r(h,v,g),h=v,g=mr(u.vendor),Zl(d+4,h,g),h+=g,g=mr(u.architecture),Zl(d+12,h,g),h+=g,g=mr(u.device),Zl(d+20,h,g),Zl(d+28,h+g,mr(u.description)),(b(),R)[d+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(b(),R)[d+40>>>2>>>0]=u,(b(),C)[d+44>>>2>>>0]=0,(b(),C)[d+48>>>2>>>0]=0,1}var NO={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function $O(u,d){d>>>=0;var h=oe(u>>>0);u=Zs(4*h.features.size);var g=0,v=0;for(let M of h.features)0<=(h=NO[M])&&((b(),R)[u+g>>>2>>>0]=h,g+=4,v++);(b(),C)[d+4>>>2>>>0]=u,(b(),C)[d>>>2>>>0]=v}function RO(u,d){return Kv(oe(u>>>0).limits,d>>>0),1}function DO(u,d){oe(u>>>0).pushErrorScope(XS[d])}function FO(u,d,h){d>>>=0,h>>>=0,u=oe(u>>>0),d=Array.from((b(),R).subarray(h>>>2>>>0,h+4*d>>>2>>>0),g=>oe(g)),u.submit(d)}function BO(u,d,h,g,v){h=mt(h),g>>>=0,v>>>=0,u=oe(u>>>0),d=oe(d>>>0),g=(b(),X).subarray(g>>>0,g+v>>>0),u.writeBuffer(d,h,g,0,v)}n||(function(){for(var u=e.numThreads-1;u--;)fv();Fe.push(async()=>{var d=(async function(){if(!n)return Promise.all(Mr.map(pv))})();Se++,await d,--Se==0&&rt&&(d=rt,rt=null,d())})})(),n||(Tr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),le()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>fe(),e.stackRestore=u=>pe(u),e.stackAlloc=u=>tc(u),e.setValue=function(u,d,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(b(),U)[u>>>0]=d;break;case"i16":(b(),K)[u>>>1>>>0]=d;break;case"i32":(b(),R)[u>>>2>>>0]=d;break;case"i64":(b(),z)[u>>>3>>>0]=BigInt(d);break;case"float":(b(),se)[u>>>2>>>0]=d;break;case"double":(b(),Y)[u>>>3>>>0]=d;break;case"*":(b(),C)[u>>>2>>>0]=d;break;default:ce(`invalid type for setValue: ${h}`)}},e.getValue=function(u,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(b(),U)[u>>>0];case"i16":return(b(),K)[u>>>1>>>0];case"i32":return(b(),R)[u>>>2>>>0];case"i64":return(b(),z)[u>>>3>>>0];case"float":return(b(),se)[u>>>2>>>0];case"double":return(b(),Y)[u>>>3>>>0];case"*":return(b(),C)[u>>>2>>>0];default:ce(`invalid type for getValue: ${d}`)}},e.UTF8ToString=Ys,e.stringToUTF8=_r,e.lengthBytesUTF8=mr;var nk,ok,_f,ec,Wt,Zs,ak,ik,lk,ck,uk,pk,fk,dk,_k,mk,hk,mf,hf,gf,wf,io,xf,gk,yf,wk,xk,yk,bf,bk,vk,vf,xe,lo,kk,pe,tc,fe,Ek,kf,Ak,Mk,Tk,Ef,Sk,Ok,Ik,Ck,Pk,zk,Lk,Nk,$k,Rk,Dk,Fk,Bk,Uk,jk,Gk,qk,Wk,Vk,Hk,Xk,Kk,Yk,Qk,Jk,Zk,eE,tE,rE,sE,nE,oE,aE,iE,lE,cE,uE,pE,wr,UO=[Hs,so,mv,yv,bv,vv,kv,Ev,Av,Mv,Tv,Sv,Ov,Iv,Cv,Pv,qv,Wv,Vv,Jv,Zv,ek,tk,rk,sk],Af={970348:(u,d,h,g,v)=>{if(e===void 0||!e.Uc)return 1;if((u=Ys(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=e.Uc.get(u)))return 2;if(d=Number(d>>>0),h=Number(h>>>0),g=Number(g>>>0),d+h>u.byteLength)return 3;try{let M=u.subarray(d,d+h);switch(v){case 0:(b(),X).set(M,g>>>0);break;case 1:e.ad?e.ad(g,M):e.ne(g,M);break;default:return 4}return 0}catch{return 4}},971172:(u,d,h)=>{e.Sd(u,(b(),X).subarray(d>>>0,d+h>>>0))},971236:()=>e.le(),971278:u=>{e.jd(u)},971315:()=>typeof wasmOffsetConverter<"u"};function jO(u,d,h,g){var v=fe();try{return Nk(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function GO(u,d,h){var g=fe();try{return Pk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function qO(u){var d=fe();try{Sk(u)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function WO(u,d){var h=fe();try{return Ef(u,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function VO(u,d,h){var g=fe();try{Tk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function HO(u,d){var h=fe();try{$k(u,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function XO(u,d,h,g,v,M,P){var L=fe();try{return Ck(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function KO(u,d,h,g,v,M){var P=fe();try{Ok(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function YO(u,d,h,g){var v=fe();try{Lk(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function QO(u,d,h,g,v,M,P){var L=fe();try{Dk(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function JO(u,d,h,g,v,M,P){var L=fe();try{Fk(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function ZO(u,d,h,g,v,M,P,L){var G=fe();try{Xk(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function eI(u,d,h,g,v,M,P,L,G,Z,Ie,Ne){var Ue=fe();try{Bk(u,d,h,g,v,M,P,L,G,Z,Ie,Ne)}catch(ae){if(pe(Ue),ae!==ae+0)throw ae;xe(1,0)}}function tI(u,d,h,g,v){var M=fe();try{return Rk(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function rI(u,d,h,g,v){var M=fe();try{Ik(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function sI(u,d,h,g,v,M,P,L){var G=fe();try{zk(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function nI(u){var d=fe();try{return Kk(u)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function oI(u,d,h){var g=fe();try{return Yk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function aI(u,d){var h=fe();try{return iE(u,d)}catch(g){if(pe(h),g!==g+0)throw g;return xe(1,0),0n}}function iI(u){var d=fe();try{return Uk(u)}catch(h){if(pe(d),h!==h+0)throw h;return xe(1,0),0n}}function lI(u,d,h,g){var v=fe();try{return Qk(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function cI(u,d,h,g,v){var M=fe();try{return Jk(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function uI(u,d,h,g,v,M){var P=fe();try{return Zk(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function pI(u,d,h,g,v,M){var P=fe();try{return Vk(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function fI(u,d,h,g,v,M){var P=fe();try{return eE(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function dI(u,d,h,g,v,M,P,L){var G=fe();try{return Hk(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function _I(u,d,h,g,v){var M=fe();try{return tE(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;return xe(1,0),0n}}function mI(u,d,h,g){var v=fe();try{return rE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function hI(u,d,h,g){var v=fe();try{return sE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function gI(u,d,h,g,v,M,P,L,G,Z,Ie,Ne){var Ue=fe();try{return nE(u,d,h,g,v,M,P,L,G,Z,Ie,Ne)}catch(ae){if(pe(Ue),ae!==ae+0)throw ae;xe(1,0)}}function wI(u,d,h,g,v,M,P,L,G,Z,Ie){var Ne=fe();try{oE(u,d,h,g,v,M,P,L,G,Z,Ie)}catch(Ue){if(pe(Ne),Ue!==Ue+0)throw Ue;xe(1,0)}}function xI(u,d,h,g,v,M,P,L,G,Z,Ie,Ne,Ue,ae,ut,Tt){var pt=fe();try{aE(u,d,h,g,v,M,P,L,G,Z,Ie,Ne,Ue,ae,ut,Tt)}catch(ps){if(pe(pt),ps!==ps+0)throw ps;xe(1,0)}}function yI(u,d,h){var g=fe();try{return Gk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;return xe(1,0),0n}}function bI(u,d,h){var g=fe();try{return jk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function vI(u,d,h){var g=fe();try{return qk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function kI(u,d,h,g){var v=fe();try{Wk(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function rc(){if(0{let d=new WeakMap,h,g,v=1;e.webgpuRegisterDevice=L=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(L){var G=d.get(L);if(!G){let Z=((Ie,Ne=0)=>{var Ue=hk(Ne);return Ne=mk(Ne,Ue),ht[Ue>>>0]=Ie.queue,ht[Ne>>>0]=Ie,Ne})(L,G=ik(0));G=[v++,G,Z],d.set(L,G)}return h=L,g=G[0],G}h=void 0,g=0};let M=new Map;e.webgpuOnCreateSession=L=>{if(g!==void 0){var G=g;if(g=void 0,L){let Z=_f(G);M.set(L,Z),G===0&&u(h??oe(Z))}h=void 0}},e.webgpuOnReleaseSession=L=>{M.delete(L)};let P=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(L,G,Z)=>{if(Z)return L[P]=[Z,NaN],Z;if(Z=L[P])return Z[1]++,Z[0];if((G=M.get(G))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return G=((Ie,Ne=0)=>(Ie.mapState==="unmapped"||ce(),Ne=_k(Ne),ht[Ne>>>0]=Ie,Ne))(L,G),L[P]=[G,1],G},e.webgpuUnregisterBuffer=L=>{let G=L[P];if(!G)throw Error("Buffer is not registered");G[1]--,G[1]===0&&(ak(G[0]),delete L[P])},e.webgpuGetBuffer=L=>oe(L),e.webgpuCreateDownloader=(L,G,Z)=>{if((Z=M.get(Z))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Ie=oe(Z),Ne=16*Math.ceil(Number(G)/16);return async()=>{let Ue=Ie.createBuffer({size:Ne,usage:9});try{let ae=Ie.createCommandEncoder();return ae.copyBufferToBuffer(L,0,Ue,0,Ne),Ie.queue.submit([ae.finish()]),await Ue.mapAsync(GPUMapMode.READ),Ue.getMappedRange().slice(0,G)}finally{Ue.destroy()}}},e.ad=(L,G)=>{var Z=G.buffer;let Ie=G.byteOffset,Ne=G.byteLength;if(G=16*Math.ceil(Number(Ne)/16),L=oe(L),!h){var Ue=_f(g);h=oe(Ue)}let ae=(Ue=h.createBuffer({mappedAtCreation:!0,size:G,usage:6})).getMappedRange();new Uint8Array(ae).set(new Uint8Array(Z,Ie,Ne)),Ue.unmap(),(Z=h.createCommandEncoder()).copyBufferToBuffer(Ue,0,L,0,G),h.queue.submit([Z.finish()]),Ue.destroy()}},e.webnnInit=u=>{let d=u[0];[e.le,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.ke,e.webnnEnableTraceEvent]=u.slice(1),e.webnnReleaseTensorId=e.jd,e.webnnUploadTensor=e.Sd,e.webnnRegisterMLContext=e.ke,e.webnnOnRunStart=h=>d.onRunStart(h),e.webnnOnRunEnd=d.onRunEnd.bind(d),e.webnnOnReleaseSession=h=>{d.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>d.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,v,M)=>d.registerMLTensor(h,g,v,M),e.webnnCreateMLContext=h=>d.createMLContext(h),e.webnnRegisterMLConstant=(h,g,v,M,P,L)=>d.registerMLConstant(h,g,v,M,P,e.Uc,L),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},Q?e:new Promise((u,d)=>{w=u,x=d})}var c2,hA,xL=be(()=>{"use strict";c2=mA,hA=globalThis.self?.name?.startsWith("em-pthread"),hA&&mA()}),Hf,cd,gA,Pt,u2,xc,wA,xA,Xf,yA,Kf,p2,Yf,f2,wd=be(()=>{"use strict";gd(),Hf=typeof location>"u"?void 0:location.origin,cd=import.meta.url>"file:"&&import.meta.url<"file;",gA=()=>{if(cd){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Hf).href}return import.meta.url},Pt=gA(),u2=()=>{if(Pt&&!Pt.startsWith("blob:"))return Pt.substring(0,Pt.lastIndexOf("/")+1)},xc=(t,e)=>{try{let r=e??Pt;return(r?new URL(t,r):new URL(t)).origin===Hf}catch{return!1}},wA=(t,e)=>{let r=e??Pt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},xA=(t,e)=>`${e??"./"}${t}`,Xf=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},yA=async t=>(await import(t)).default,Kf=(wL(),Ac(a2)).default,p2=async()=>{if(!Pt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(xc(Pt))return[void 0,Kf()];let t=await Xf(Pt);return[t,Kf(t)]},Yf=(xL(),Ac(l2)).default,f2=async(t,e,r,s)=>{let n=Yf&&!(t||e);if(n)if(Pt)n=xc(Pt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,Yf];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??wA(o,e),i=r&&a&&!xc(a,e),l=i?await Xf(a):a??xA(o,e);return[i?l:void 0,await yA(l)]}}}),Qf,yc,vo,Jf,bA,vA,kA,xd,De,Ms=be(()=>{"use strict";wd(),yc=!1,vo=!1,Jf=!1,bA=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},vA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},kA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},xd=async t=>{if(yc)return Promise.resolve();if(vo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Jf)throw new Error("previous call to 'initializeWebAssembly()' failed.");vo=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!kA())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!vA())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=bA();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,p=t.wasmBinary,[f,_]=await f2(i,o,r>1,!!p||!!c),m=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{m=!0,x()},e)})),w.push(new Promise((x,k)=>{let A={numThreads:r};if(p)A.wasmBinary=p,A.locateFile=E=>E;else if(c||o)A.locateFile=E=>c??o+E;else if(i&&i.indexOf("blob:")!==0)A.locateFile=E=>new URL(E,i).href;else if(f){let E=u2();E&&(A.locateFile=S=>E+S)}_(A).then(E=>{vo=!1,yc=!0,Qf=E,x(),f&&URL.revokeObjectURL(f)},E=>{vo=!1,Jf=!0,k(E)})})),await Promise.race(w),m)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},De=()=>{if(yc&&Qf)return Qf;throw new Error("WebAssembly is not initialized yet.")}}),zt,Tc,ze,yd=be(()=>{"use strict";Ms(),zt=(t,e)=>{let r=De(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},Tc=(t,e,r,s)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([n,o])=>{let a=e?e+n:n;if(typeof o=="object")Tc(o,a+".",r,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},ze=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetLastError(n,n+s);let o=Number(e.getValue(n,s===4?"i32":"i64")),a=e.getValue(n+s,"*"),i=a?e.UTF8ToString(a):"";throw new Error(`${t} ERROR_CODE: ${o}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}}),d2,yL=be(()=>{"use strict";Ms(),yd(),d2=t=>{let e=De(),r=0,s=[],n=t||{};try{if(t?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(n.terminate=!1);let o=0;return t?.tag!==void 0&&(o=zt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&ze("Can't create run options."),t?.extra!==void 0&&Tc(t.extra,"",new WeakSet,(a,i)=>{let l=zt(a,s),c=zt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&ze(`Can't set a run config entry: ${a} - ${i}.`)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),s.forEach(a=>e._free(a)),o}}}),EA,AA,MA,bc,$r,TA,_2,bL=be(()=>{"use strict";Ms(),yd(),EA=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},AA=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},MA=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},bc=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);De()._OrtAddSessionConfigEntry(t,n,o)!==0&&ze(`Can't set a session config entry: ${e} - ${r}.`)},$r=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);t.push([n,o])},TA=async(t,e,r)=>{let s=e.executionProviders;for(let n of s){let o=typeof n=="string"?n:n.name,a=[];switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let f=n?.deviceType;f&&bc(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let m=n;if(m.device)if(typeof GPUDevice<"u"&&m.device instanceof GPUDevice)f=m.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&$r(a,"enableGraphCapture","1",r),typeof m.preferredLayout=="string"&&$r(a,"preferredLayout",m.preferredLayout,r),m.forceCpuNodeNames){let x=Array.isArray(m.forceCpuNodeNames)?m.forceCpuNodeNames:[m.forceCpuNodeNames];$r(a,"forceCpuNodeNames",x.join(` +-`),r)}m.validationMode&&$r(a,"validationMode",m.validationMode,r)}let _=De().webgpuRegisterDevice(f);if(_){let[m,w,x]=_;$r(a,"deviceId",m.toString(),r),$r(a,"webgpuInstance",w.toString(),r),$r(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=zt(o,r),l=a.length,c=0,p=0;if(l>0){c=De()._malloc(l*De().PTR_SIZE),r.push(c),p=De()._malloc(l*De().PTR_SIZE),r.push(p);for(let f=0;f{let e=De(),r=0,s=[],n=t||{};MA(n);try{let o=EA(n.graphOptimizationLevel??"all"),a=AA(n.executionMode??"sequential"),i=typeof n.logId=="string"?zt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?zt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,p),r===0&&ze("Can't create session options."),n.executionProviders&&await TA(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);bc(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[f,_]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw new Error(`free dimension override value must be a non-negative integer: ${_}`);let m=zt(f,s);e._OrtAddFreeDimensionOverride(r,m,_)!==0&&ze(`Can't set a free dimension override: ${f} - ${_}.`)}return n.extra!==void 0&&Tc(n.extra,"",new WeakSet,(f,_)=>{bc(r,f,_,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&ze("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),bs,Ec,un,To,Sc,bd,vd,ud,pn=be(()=>{"use strict";bs=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},Ec=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},un=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],s=typeof e=="number"?e:e.reduce((n,o)=>n*o,1);return r>0?Math.ceil(s*r):void 0},To=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Sc=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},bd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",vd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",ud=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${t}`)}}}),kd,m2=be(()=>{"use strict";gd(),kd=async t=>{if(typeof t=="string"){let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(o,a,c).set(l),a+=c}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),h2,vL=be(()=>{"use strict";pn(),h2=(t,e)=>new(To(e))(t)}),SA,OA,IA,CA,g2,PA,yt,w2=be(()=>{"use strict";pn(),SA=["V","I","W","E","F"],OA=(t,e)=>{console.log(`[${SA[t]},${new Date().toISOString()}]${e}`)},g2=(t,e)=>{IA=t,CA=e},PA=(t,e)=>{let r=Sc(t),s=Sc(IA);r>=s&&OA(r,typeof e=="function"?e():e)},yt=(...t)=>{CA&&PA(...t)}}),Zf,pd,ed,zA,td,LA,rd,sd,nd,NA,x2,kL=be(()=>{"use strict";pn(),w2(),Zf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),pd=(t,e)=>{if(e==="int32")return t;let r=Zf.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);let s=r/8;if(t.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=t.byteLength/s,o=new(To(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(l)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&o.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(o,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},ed=(t,e)=>{if(e==="int32")return t;if(t.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=t.byteLength/4,s=new Int32Array(t.buffer,t.byteOffset,r);switch(e){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(o=>o<-128||o>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${e}`)}},zA=1,td=()=>zA++,LA=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),rd=(t,e)=>{let r=Zf.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);return e.length>0?Math.ceil(e.reduce((s,n)=>s*n)*r/8):0},sd=class{constructor(t){this.isDataConverted=!1;let{sessionId:e,context:r,tensor:s,dataType:n,shape:o,fallbackDataType:a}=t;this.sessionId=e,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.fallbackDataType=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return rd(this.dataType,this.tensorShape)}destroy(){yt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){if(this.fallbackDataType){let e=await this.mlContext.readTensor(this.mlTensor),r=ed(new Uint8Array(e),this.dataType);if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(r);return}else return r.buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,e,r){return this.mlContext===t&&this.dataType===e&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(t){this.isDataConverted=t}},nd=class{constructor(t,e){this.tensorManager=t,this.wrapper=e}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,e,r,s){let n=this.tensorManager.getMLContext(t),o=this.tensorManager.getMLOpSupportLimits(t),a;if(!o?.input.dataTypes.includes(e)){if(a=LA.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);yt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${e} to ${a}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,e,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==rd(e,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,e,r,i,!0,!0,a),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){let e=t;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")e=pd(t,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else yt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(t){if(this.activeUpload){let e=this.wrapper?.isDataConverted?ed(this.activeUpload,this.wrapper?.type):this.activeUpload;if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(e):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(e);return}else return e.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(t):this.wrapper.read()}},NA=class{constructor(t){this.backend=t,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(t){let e=this.backend.getMLContext(t);if(!e)throw new Error("MLContext not found for session.");return e}getMLOpSupportLimits(t){return this.backend.getMLOpSupportLimits(t)}reserveTensorId(){let t=td();return this.tensorTrackersById.set(t,new nd(this)),t}releaseTensorId(t){let e=this.tensorTrackersById.get(t);e&&(this.tensorTrackersById.delete(t),e.tensorWrapper&&this.releaseTensor(e.tensorWrapper))}async ensureTensor(t,e,r,s,n){yt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,s,n)}upload(t,e){let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");r.upload(e)}async download(t,e){yt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${e?.byteLength}}`);let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");return r.download(e)}releaseTensorsForSession(t){for(let e of this.freeTensors)e.sessionId===t&&e.destroy();this.freeTensors=this.freeTensors.filter(e=>e.sessionId!==t)}registerTensor(t,e,r,s){let n=this.getMLContext(t),o=td(),a=new sd({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new nd(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(i,e,r)){yt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}yt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:a??e,shape:r,dimensions:r,usage:s,writable:n,readable:o});return new sd({sessionId:t,context:i,tensor:l,dataType:e,shape:r,fallbackDataType:a})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},x2=(...t)=>new NA(...t)}),y2={};So(y2,{WebNNBackend:()=>b2});var ko,$A,b2,EL=be(()=>{"use strict";pn(),Ms(),vL(),kL(),w2(),ko=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),$A=(t,e)=>{if(t===e)return!0;if(t===void 0||e===void 0)return!1;let r=Object.keys(t).sort(),s=Object.keys(e).sort();return r.length===s.length&&r.every((n,o)=>n===s[o]&&t[n]===e[n])},b2=class{constructor(t){this.tensorManager=x2(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,g2(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){yt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){yt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)yt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(t),this.activeSessionId=void 0}}async createMLContext(t){if(t instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===t);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:s}),s}}else if(t===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let e=this.mlContextCache.findIndex(r=>$A(r.options,t));if(e!==-1)return this.mlContextCache[e].mlContext;{let r=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:r}),r}}registerMLContext(t,e){this.mlContextBySessionId.set(t,e);let r=this.sessionIdsByMLContext.get(e);r||(r=new Set,this.sessionIdsByMLContext.set(e,r)),r.add(t),this.mlOpSupportLimitsBySessionId.has(t)||this.mlOpSupportLimitsBySessionId.set(t,e.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(t,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(t,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(t){this.sessionGraphInputs.delete(t),this.sessionGraphOutputs.delete(t);let e=this.mlContextBySessionId.get(t);if(!e)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t),this.mlOpSupportLimitsBySessionId.delete(t);let r=this.sessionIdsByMLContext.get(e);if(r.delete(t),r.size===0){this.sessionIdsByMLContext.delete(e);let s=this.mlContextCache.findIndex(n=>n.mlContext===e);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}getMLOpSupportLimits(t){return this.mlOpSupportLimitsBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){yt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=ko.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t??this.currentSessionId,e,o,s,n)}async createTemporaryTensor(t,e,r){yt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=ko.get(e);if(!s)throw new Error(`Unsupported ONNX data type: ${e}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(t,n,s,r,!1);let o=this.temporarySessionTensorIds.get(t);return o?o.push(n):this.temporarySessionTensorIds.set(t,[n]),n}uploadTensor(t,e){if(!De().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");yt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${e.byteLength}}`),this.tensorManager.upload(t,e)}async downloadTensor(t,e){return this.tensorManager.download(t,e)}createMLTensorDownloader(t,e){return async()=>{let r=await this.tensorManager.download(t);return h2(r,e)}}registerMLTensor(t,e,r,s){let n=ko.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return yt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(e,e+r).buffer,p;switch(n.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":if(a){let f=pd(new Uint8Array(c),"int64");p=new Int32Array(f.buffer),n.dataType="int32"}else p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return yt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,p)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=ko.get(bs(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),RA,Ed,Ad,Rr,DA,od,Oc,Md,Td,ad,Sd,Od,Id,v2=be(()=>{"use strict";As(),yL(),bL(),pn(),Ms(),yd(),m2(),RA=(t,e)=>{De()._OrtInit(t,e)!==0&&ze("Can't initialize onnxruntime.")},Ed=async t=>{RA(t.wasm.numThreads,Sc(t.logLevel))},Ad=async(t,e)=>{De().asyncInit?.();let r=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=t.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let n=t.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(e==="webgpu"&&De().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(EL(),Ac(y2)).WebNNBackend(t);De().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,o,a,i,l)=>s.ensureTensor(n,o,a,i,l),(n,o)=>{s.uploadTensor(n,o)},async(n,o)=>s.downloadTensor(n,o),(n,o)=>s.registerMLContext(n,o),!!t.trace])}},Rr=new Map,DA=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetInputOutputCount(t,n,n+s)!==0&&ze("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(e.getValue(n,o)),Number(e.getValue(n+s,o))]}finally{e.stackRestore(r)}},od=(t,e)=>{let r=De(),s=r.stackSave(),n=0;try{let o=r.PTR_SIZE,a=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(t,e,a,a+o)!==0&&ze("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],p=[];for(let f=0;f{let e=De(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},Md=async(t,e)=>{let r,s,n=De();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=Oc(t);let o=0,a=0,i=0,l=[],c=[],p=[];try{if([a,l]=await _2(e),e?.externalData&&n.mountExternalData){let T=[];for(let I of e.externalData){let O=typeof I=="string"?I:I.path;T.push(kd(typeof I=="string"?I:I.data).then(b=>{n.mountExternalData(O,b)}))}await Promise.all(T)}for(let T of e?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof T!="string"){let I=T,O=I?.context,b=I?.gpuDevice,F=I?.deviceType,j=I?.powerPreference;O?n.currentContext=O:b?n.currentContext=await n.webnnCreateMLContext(b):n.currentContext=await n.webnnCreateMLContext({deviceType:F,powerPreference:j})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&ze("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,_]=DA(o),m=!!e?.enableGraphCapture,w=[],x=[],k=[],A=[],E=[];for(let T=0;TT==="gpu-buffer"||T==="ml-tensor"||T==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&ze("Can't create IO binding."),S={handle:i,outputPreferredLocations:E,outputPreferredLocationsEncoded:E.map(T=>T==="ml-tensor-cpu-output"?"ml-tensor":T).map(T=>ud(T))}),Rr.set(o,[o,c,p,S,m,!1]),[o,w,x,k,A]}catch(f){throw c.forEach(_=>n._OrtFree(_)),p.forEach(_=>n._OrtFree(_)),i!==0&&n._OrtReleaseBinding(i)!==0&&ze("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&ze("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&ze("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},Td=t=>{let e=De(),r=Rr.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&ze("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&ze("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(l=>e._OrtFree(l)),o.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(s)!==0&&ze("Can't release session."),Rr.delete(t)},ad=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=De(),l=i.PTR_SIZE,c=t[0],p=t[1],f=t[3],_=f,m,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let A=t[2].gpuBuffer;w=un(bs(c),p);{let E=i.webgpuRegisterBuffer;if(!E)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');m=E(A,s)}}else if(f==="ml-tensor"){let A=t[2].mlTensor;w=un(bs(c),p);let E=i.webnnRegisterMLTensor;if(!E)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');m=E(s,A,bs(c),p)}else{let A=t[2];if(Array.isArray(A)){w=l*A.length,m=i._malloc(w),r.push(m);for(let E=0;Ei.setValue(k+S*l,E,l===4?"i32":"i64"));let A=i._OrtCreateTensor(bs(c),m,w,k,p.length,ud(_));A===0&&ze(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(A)}finally{i.stackRestore(x)}},Sd=async(t,e,r,s,n,o)=>{let a=De(),i=a.PTR_SIZE,l=Rr.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],p=l[1],f=l[2],_=l[3],m=l[4],w=l[5],x=e.length,k=s.length,A=0,E=[],S=[],T=[],I=[],O=[],b=a.stackSave(),F=a.stackAlloc(x*i),j=a.stackAlloc(x*i),U=a.stackAlloc(k*i),X=a.stackAlloc(k*i);try{[A,E]=d2(o),Fr("wasm prepareInputOutputTensor");for(let C=0;CFe*Se,1);B=Ec(Ge);let At=_?.outputPreferredLocations[s[C]];if(B==="string"){if(At==="gpu-buffer"||At==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Fe=[];for(let Se=0;Se0){let Fe=a.webgpuGetBuffer;if(!Fe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Se=Fe(Q),rt=un(Ge,ct);if(rt===void 0||!bd(B))throw new Error(`Unsupported data type: ${B}`);$=!0;{a.webgpuRegisterBuffer(Se,t,Q);let tr=a.webgpuCreateDownloader(Se,rt,t);J.push([B,qe,{gpuBuffer:Se,download:async()=>{let Oe=await tr();return new(To(B))(Oe)},dispose:()=>{a._OrtReleaseTensor(se)!==0&&ze("Can't release tensor.")}},"gpu-buffer"])}}else if(At==="ml-tensor"&&ct>0){let Fe=a.webnnEnsureTensor,Se=a.webnnIsGraphInputOutputTypeSupported;if(!Fe||!Se)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(un(Ge,ct)===void 0||!vd(B))throw new Error(`Unsupported data type: ${B}`);if(!Se(t,B,!1))throw new Error(`preferredLocation "ml-tensor" for ${B} output is not supported by current WebNN Context.`);let rt=await Fe(t,Q,Ge,qe,!1);$=!0,J.push([B,qe,{mlTensor:rt,download:a.webnnCreateMLTensorDownloader(Q,B),dispose:()=>{a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(se)}},"ml-tensor"])}else if(At==="ml-tensor-cpu-output"&&ct>0){let Fe=a.webnnCreateMLTensorDownloader(Q,B)(),Se=J.length;$=!0,R.push((async()=>{let rt=[Se,await Fe];return a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(se),rt})()),J.push([B,qe,[],"cpu"])}else{let Fe=To(B),Se=new Fe(ct);new Uint8Array(Se.buffer,Se.byteOffset,Se.byteLength).set(a.HEAPU8.subarray(Q,Q+Se.byteLength)),J.push([B,qe,Se,"cpu"])}}finally{a.stackRestore(Y),B==="string"&&Q&&a._free(Q),$||a._OrtReleaseTensor(se)}}_&&!m&&(a._OrtClearBoundOutputs(_.handle)!==0&&ze("Can't clear bound outputs."),Rr.set(t,[c,p,f,_,m,!1]));for(let[C,se]of await Promise.all(R))J[C][2]=se;return Br("wasm ProcessOutputTensor"),J}finally{a.webnnOnRunEnd?.(c),a.stackRestore(b),r.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),n.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),S.forEach(K=>a._OrtReleaseTensor(K)),T.forEach(K=>a._OrtReleaseTensor(K)),I.forEach(K=>a._free(K)),A!==0&&a._OrtReleaseRunOptions(A),E.forEach(K=>a._free(K))}},Od=t=>{let e=De(),r=Rr.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&ze("Can't get an profile file name."),e._OrtFree(n)},Id=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Dr,Bt,cn,Eo,Ao,vc,id,kc,ws,xs,FA,k2,E2,A2,M2,T2,S2,O2,I2=be(()=>{"use strict";As(),v2(),Ms(),wd(),Dr=()=>!!Ye.wasm.proxy&&typeof document<"u",cn=!1,Eo=!1,Ao=!1,kc=new Map,ws=(t,e)=>{let r=kc.get(t);r?r.push(e):kc.set(t,[e])},xs=()=>{if(cn||!Eo||Ao||!Bt)throw new Error("worker not ready")},FA=t=>{switch(t.data.type){case"init-wasm":cn=!1,t.data.err?(Ao=!0,id[1](t.data.err)):(Eo=!0,id[0]()),vc&&(URL.revokeObjectURL(vc),vc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=kc.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},k2=async()=>{if(!Eo){if(cn)throw new Error("multiple calls to 'initWasm()' detected.");if(Ao)throw new Error("previous call to 'initWasm()' failed.");if(cn=!0,Dr())return new Promise((t,e)=>{Bt?.terminate(),p2().then(([r,s])=>{try{Bt=s,Bt.onerror=o=>e(o),Bt.onmessage=FA,id=[t,e];let n={type:"init-wasm",in:Ye};!n.in.wasm.wasmPaths&&(r||cd)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Bt.postMessage(n),vc=r}catch(n){e(n)}},e)});try{await xd(Ye.wasm),await Ed(Ye),Eo=!0}catch(t){throw Ao=!0,t}finally{cn=!1}}},E2=async t=>{if(Dr())return xs(),new Promise((e,r)=>{ws("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Ye}};Bt.postMessage(s)});await Ad(Ye,t)},A2=async t=>Dr()?(xs(),new Promise((e,r)=>{ws("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Bt.postMessage(s,[t.buffer])})):Oc(t),M2=async(t,e)=>{if(Dr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return xs(),new Promise((r,s)=>{ws("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Bt.postMessage(n,o)})}else return Md(t,e)},T2=async t=>{if(Dr())return xs(),new Promise((e,r)=>{ws("release",[e,r]);let s={type:"release",in:t};Bt.postMessage(s)});Td(t)},S2=async(t,e,r,s,n,o)=>{if(Dr()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return xs(),new Promise((a,i)=>{ws("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Bt.postMessage(c,Id(l))})}else return Sd(t,e,r,s,n,o)},O2=async t=>{if(Dr())return xs(),new Promise((e,r)=>{ws("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Bt.postMessage(s)});Od(t)}}),ld,BA,C2,AL=be(()=>{"use strict";As(),I2(),pn(),gd(),m2(),ld=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},BA=t=>{switch(t[3]){case"cpu":return new Qt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!bd(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return Qt.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!vd(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return Qt.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},C2=class{async fetchModelAndCopyToWasmMemory(t){return A2(await kd(t))}async loadModel(t,e){ks();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await M2(r,e),Es()}async dispose(){return T2(this.sessionId)}async run(t,e,r){ks();let s=[],n=[];Object.entries(t).forEach(f=>{let _=f[0],m=f[1],w=this.inputNames.indexOf(_);if(w===-1)throw new Error(`invalid input '${_}'`);s.push(m),n.push(w)});let o=[],a=[];Object.entries(e).forEach(f=>{let _=f[0],m=f[1],w=this.outputNames.indexOf(_);if(w===-1)throw new Error(`invalid output '${_}'`);o.push(m),a.push(w)});let i=s.map((f,_)=>ld(f,()=>`input "${this.inputNames[n[_]]}"`)),l=o.map((f,_)=>f?ld(f,()=>`output "${this.outputNames[a[_]]}"`):null),c=await S2(this.sessionId,n,i,a,l,r),p={};for(let f=0;fdd,initializeFlags:()=>fd,wasmBackend:()=>z2});var fd,dd,z2,ML=be(()=>{"use strict";As(),I2(),AL(),fd=()=>{(typeof Ye.wasm.initTimeout!="number"||Ye.wasm.initTimeout<0)&&(Ye.wasm.initTimeout=0);let t=Ye.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),Ye.wasm.simd=!1),typeof Ye.wasm.proxy!="boolean"&&(Ye.wasm.proxy=!1),typeof Ye.wasm.trace!="boolean"&&(Ye.wasm.trace=!1),typeof Ye.wasm.numThreads!="number"||!Number.isInteger(Ye.wasm.numThreads)||Ye.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Ye.wasm.numThreads=1;else{let e=typeof navigator>"u"?sL("node:os").cpus().length:navigator.hardwareConcurrency;Ye.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},dd=class{async init(t){fd(),await k2(),await E2(t)}async createInferenceSessionHandler(t,e){let r=new C2;return await r.loadModel(t,e),r}},z2=new dd});As();As();As();var TL="1.26.0-dev.20260416-b7804b056c",SL=o2;{let t=(ML(),Ac(P2)).wasmBackend;vs("webgpu",t,5),vs("webnn",t,5),vs("cpu",t,10),vs("wasm",t,10)}Object.defineProperty(Ye.versions,"web",{value:TL,enumerable:!0});async function L2(t){let e=t.split("/").pop(),r;try{if(r=await Yt(),r){let n=await r.match(t);if(n)return n}}catch(n){ee.warn(`Failed to load ${e} from cache:`,n)}let s=await me.fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){ee.warn(`Failed to cache ${e}:`,n)}return s}async function N2(t){let e=await L2(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return ee.warn("Failed to read WASM binary:",r),null}}async function $2(t){if(ie.IS_SERVICE_WORKER_ENV||ie.IS_CHROME_AVAILABLE)return t;let e=await L2(t);if(!e||typeof e=="string")return null;try{let r=await e.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return ee.warn("Failed to read WASM factory:",r),null}}import{Tensor as j2}from"onnxruntime-common";var IL=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function B2(t){return t<=St.DEBUG?0:t<=St.INFO?2:t<=St.WARNING||t<=St.ERROR?3:4}var CL={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},Ut=[],Pd,dn,R2=Symbol.for("onnxruntime");if(R2 in globalThis)dn=globalThis[R2];else if(ie.IS_NODE_ENV){switch(dn=OL,process.platform){case"win32":Ut.push("dml");break;case"linux":process.arch==="x64"&&Ut.push("cuda");break;case"darwin":Ut.push("coreml");break}Ut.push("webgpu"),Ut.push("cpu"),Pd=["cpu"]}else dn=Cd,ie.IS_WEBNN_AVAILABLE&&Ut.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ie.IS_WEBGPU_AVAILABLE&&Ut.push("webgpu"),Ut.push("wasm"),Pd=["wasm"];var PL=dn.InferenceSession;function U2(t=null){if(!t)return Pd;switch(t){case"auto":return Ut;case"gpu":return Ut.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Ut.includes(t))return[IL[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Ut.join(", ")}.`)}var D2=Promise.resolve(),fn=null;async function zL(){if(fn)return fn;if(!(me.useWasmCache&&typeof it?.wasm?.wasmPaths=="object"&&it?.wasm?.wasmPaths?.wasm&&it?.wasm?.wasmPaths?.mjs)){if(ie.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return fn=Promise.resolve(),fn}return fn=(async()=>{let e=it.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!$f(e.wasm)?(async()=>{try{let s=await N2(Rf(e.wasm));s&&(it.wasm.wasmBinary=s,r=!0)}catch(s){ee.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!$f(e.mjs)?(async()=>{try{let s=await $2(Rf(e.mjs));s&&(it.wasm.wasmPaths.mjs=s)}catch(s){ee.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(it.wasm.wasmPaths.mjs=e.mjs)})(),fn}async function Ic(t,e,r){await zL();let s=B2(me.logLevel??St.WARNING),n=()=>PL.create(t,{logSeverityLevel:s,...e}),o=await(ie.IS_WEB_ENV?D2=D2.then(n):n());return o.config=r,o}var F2=Promise.resolve();async function Cc(t,e){let r=()=>t.run(e);return ie.IS_WEB_ENV?F2=F2.then(r):r()}function Pc(t){return t instanceof dn.Tensor}var it=dn?.env;function Oo(){return it?.wasm?.proxy}if(it){let t=function(e){let r=B2(e);it.logLevel=CL[r]};if(it.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&it.versions?.web&&!it.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${it.versions.web}/dist/`;it.wasm.wasmPaths=ie.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}it.wasm.proxy=!1}it.webgpu&&(it.webgpu.powerPreference="high-performance"),t(me.logLevel??St.WARNING),me.backends.onnx={...it,setLogLevel:t}}var Ur=async(t,e,r)=>{let s=await Ic(new Uint8Array(t),e);return(async n=>{let o=Oo(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await Cc(s,a);return Array.isArray(r)?r.map(l=>new N(i[l])):new N(i[r])})},lr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Ur([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Ur([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Ur([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Ur([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Ur([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Ur([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Ur([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=Ur([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var G2=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),zd=ie.IS_NODE_ENV?"cpu":"wasm";function zc(t,e,{warn:r}={}){return t?typeof t=="string"?t:t.hasOwnProperty(e)?t[e]:(r&&r(`device not specified for "${e}". Using the default device (${zd}).`),zd):zd}var V2=(function(){let t;return async function(){if(t===void 0)if(!ie.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),st=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),q2=st.fp32,W2=Object.freeze({[G2.wasm]:st.q8}),jr=Object.freeze({[st.fp32]:"",[st.fp16]:"_fp16",[st.int8]:"_int8",[st.uint8]:"_uint8",[st.q8]:"_quantized",[st.q4]:"_q4",[st.q2]:"_q2",[st.q1]:"_q1",[st.q4f16]:"_q4f16",[st.q2f16]:"_q2f16",[st.q1f16]:"_q1f16",[st.bnb4]:"_bnb4"});function Lc(t,e,r,{configDtype:s=null,warn:n}={}){let o,a=!1;t&&typeof t!="string"?t.hasOwnProperty(e)?o=t[e]:(o=null,a=!0):o=t;let i;if(o===st.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==st.auto&&st.hasOwnProperty(l))return l}i=W2[r]??q2}else o&&st.hasOwnProperty(o)?i=o:i=W2[r]??q2;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var Gr=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var N=class t{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return Pc(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new j2(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}indexOf(e){let r=this.data;for(let s=0;sm)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(_,0),Math.min(m,this.dims[p])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([p,f])=>f-p),o=n.reduce((p,f)=>p*f),a=this.data,i=new a.constructor(o),l=this.stride(),c=!0;for(let p=1;p=0;--_){let w=n[_];f+=(m%w+s[_][0])*l[_],m=Math.floor(m/w)}i[p]=a[f]}return new t(this.type,i,r)}permute(...e){return NL(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let a,i;if(o?(a=(f,_)=>f+_,i=0n):(a=(f,_)=>f+_**e,i=0),r===null){let f=n.reduce(a,i);return e!==1&&(f=f**(1/e)),new t(this.type,[f],[])}let[l,c,p]=Io(a,this,r,s);if(e!==1)for(let f=0;f=0;--l){let f=this.dims[l];if(l!==r){let _=c%f;i+=_*p,p*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return Ld(this.dims)}squeeze(e=null){return new t(this.type,this.data,H2(this.dims,e))}squeeze_(e=null){return this.dims=H2(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,X2(this.dims,e))}unsqueeze_(e){return this.dims=X2(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...s,n.reduce((a,i)=>a*i,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;ni!==r?o*a:o,1);e[r]=s.length/n}return new t(this.type,s,e)}neg_(){let e=this.data;for(let r=0;re?1:0;return new t("bool",r,this.dims)}lt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;nMath.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=Pe(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Io((a,i)=>Math.max(a,i),this,e,r,-1/0);return new t(s,n,o)}argmin(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=yo(this.data)[1];return new t("int64",[BigInt(s)],[])}argmax(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Pe(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.lengthp===1)){if(e.length===this.dims.length)return this.clone();let p=e.length-this.dims.length,f=Array(p).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((p,f)=>p*e[f]),o=n.reduce((p,f)=>p*f,1),a=this.data,i=new a.constructor(o),l=Ld(s),c=Ld(n);for(let p=0;pBigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,dA(this.data),this.dims);return new t(e,Gr[e].from(this.data,r),this.dims)}};function LL(t,e){let r=t.length,s=e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.lengthnew N("int64",t,[t.length]);async function $c(t,e,r,s,n){return await(await lr.slice)({x:t,s:Nc(e),e:Nc(r),a:Nc(s),t:Nc(n??new Array(s.length).fill(1))})}function Y2(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let p=0;pr!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function X2(t,e){return e=cr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function cr(t,e,r=null,s=!0){if(t<-e||t>=e){if(s)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function ve(t,e=0){e=cr(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i=0;--_){let x=c[_],k=m%x;_===e&&(k+=a),f+=k*w,w*=r[_],m=Math.floor(m/x)}n[f]=l[p]}a+=c[e]}}return new N(o,n,r)}function xt(t,e=0){return ve(t.map(r=>r.unsqueeze(e)),e)}function Io(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=cr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let c=0;c=0;--f){let w=a[f];if(f!==r){let x=_%w;p+=x*m,m*=i[f]}_=Math.floor(_/w)}l[p]=t(l[p],o[c],c,p)}return s||i.splice(r,1),[e.type,l,i]}function $d(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let m=n.reduce((A,E)=>A+E,0)/n.length,w=Math.sqrt(n.reduce((A,E)=>A+(E-m)**2,0)/(n.length-r)),x=new N(t.type,[m],[]);return[new N(t.type,[w],[]),x]}e=cr(e,o.length);let a=Rc(t,e,s),i=a.data,[l,c,p]=Io((_,m,w,x)=>_+(m-i[x])**2,t,e,s);for(let _=0;_c+p,0);return new N(t.type,[l/n.length],[])}e=cr(e,s.length);let[o,a,i]=Io((l,c)=>l+c,t,e,r);if(s[e]!==1)for(let l=0;l=0;--r)e[r]=s,s*=t[r];return e}function Rd(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new N(r,new s(n).fill(e),t)}function Qe(t,e){let r,s;if(typeof e=="number")r="float32",s=Float32Array;else if(typeof e=="bigint")r="int64",s=BigInt64Array;else if(typeof e=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return Rd(t,e,r,s)}function Co(t,e){return Qe(t.dims,e)}function et(t){return Rd(t,1n,"int64",BigInt64Array)}function Dc(t){return et(t.dims)}function Dd(t){return Rd(t,0n,"int64",BigInt64Array)}function Fd(t){return Dd(t.dims)}function L4(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>hs.random()),t)}function Q2(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>hs.gauss()),t)}function J2(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i0?1:0,c=Math.floor(i/8),p=i%8;a[c]|=l<<7-p,r&&p===0&&(a[c]-=128)}return new N(s,a,[t.dims[0],t.dims[1]/8])}async function _n(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await Ot(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Bd(t,e){let r=await _n(t);return await Promise.all(r.map(s=>nt(t,s,!0,e)))}function Po(t){let e=t.dims;switch(e.length){case 1:return t.tolist();case 2:if(e[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return t.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${e.length}.`)}}var $L=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function RL(t,e,r,s){for(let n of Object.keys(t)){let o=e-t[n].length,a=r(n),i=new Array(o).fill(a);t[n]=s==="right"?gt(t[n],i):gt(i,t[n])}}function DL(t,e){for(let r of Object.keys(t))t[r].length=e}function Ts(t,...e){for(let r of e){if(!Object.hasOwn(t,r))continue;let s=t[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function FL(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var W=class extends We{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new $E(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Ts(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ts(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ts(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ts(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ts(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ts(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:a}of this.chat_template){if(typeof o!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=a}this.chat_template=n}this._compiled_template_cache=new Map;let s=FL(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let i=await Bd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,r={}){let{text_pair:s=null,add_special_tokens:n=!0,padding:o=!1,return_token_type_ids:a=null}=r,{truncation:i=null,max_length:l=null}=r,c=r.return_tensor??!0,p=Array.isArray(e),f;if(p){if(e.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(e.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");f=e.map((m,w)=>this._encode_plus(m,{text_pair:s[w],add_special_tokens:n,return_token_type_ids:a}))}else f=e.map(m=>this._encode_plus(m,{add_special_tokens:n,return_token_type_ids:a}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(s))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");f=[this._encode_plus(e,{text_pair:s,add_special_tokens:n,return_token_type_ids:a})]}if(l===null?l=this.model_max_length:i===null&&(o===!0?(ee.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):o===!1&&(ee.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),i=!0)),o===!0&&(l=Math.min(Pe(f.map(m=>m.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),o||i)for(let m=0;ml?i&&DL(f[m],l):o&&RL(f[m],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));let _={};if(c){if(!(o&&i)&&f.some(w=>{for(let x of Object.keys(w))if(w[x].length!==f[0][x]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let m=[f.length,f[0].input_ids.length];for(let w of Object.keys(f[0]))_[w]=new N("int64",BigInt64Array.from(f.flatMap(x=>x[w]).map(BigInt)),m)}else{for(let m of Object.keys(f[0]))_[m]=f.map(w=>w[m]);if(!p)for(let m of Object.keys(_))_[m]=_[m][0]}return _}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof N&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof N&&(e=Po(e)),!Array.isArray(e)||e.length===0||!wE(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,r={}){let{tools:s=null,documents:n=null,chat_template:o=null,add_generation_prompt:a=!1,tokenize:i=!0,padding:l=!1,truncation:c=!1,max_length:p=null,return_tensor:f=!0,return_dict:_=!0,tokenizer_kwargs:m={},...w}=r;if(o=this.get_chat_template({chat_template:o,tools:s}),typeof o!="string")throw Error(`chat_template must be a string, but got ${typeof o}`);let x=this._compiled_template_cache.get(o);x===void 0&&(x=new XE(o),this._compiled_template_cache.set(o,x));let k=Object.create(null);for(let E of $L){let S=Ts(this.config,E);S&&(k[E]=S)}let A=x.render({messages:e,add_generation_prompt:a,tools:s,documents:n,...k,...w});if(i){let E=this._call(A,{add_special_tokens:!1,padding:l,truncation:c,max_length:p,return_tensor:f,...m});return _?E:E.input_ids}return A}};function mn(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var P_={};en(P_,{AlbertTokenizer:()=>Ud,AutoTokenizer:()=>ne,BartTokenizer:()=>jd,BertTokenizer:()=>Gd,BlenderbotSmallTokenizer:()=>qd,BlenderbotTokenizer:()=>Wd,BloomTokenizer:()=>Vd,CLIPTokenizer:()=>Xd,CamembertTokenizer:()=>Hd,CodeGenTokenizer:()=>Yd,CodeLlamaTokenizer:()=>Kd,CohereAsrTokenizer:()=>Jd,CohereTokenizer:()=>Qd,ConvBertTokenizer:()=>Zd,DebertaTokenizer:()=>t_,DebertaV2Tokenizer:()=>e_,DistilBertTokenizer:()=>r_,ElectraTokenizer:()=>s_,EsmTokenizer:()=>n_,FalconTokenizer:()=>o_,GPT2Tokenizer:()=>l_,GPTNeoXTokenizer:()=>i_,GemmaTokenizer:()=>a_,HerbertTokenizer:()=>c_,LlamaTokenizer:()=>u_,M2M100Tokenizer:()=>p_,MBart50Tokenizer:()=>d_,MBartTokenizer:()=>zo,MPNetTokenizer:()=>h_,MarianTokenizer:()=>f_,MgpstrTokenizer:()=>__,MobileBertTokenizer:()=>m_,NllbTokenizer:()=>g_,NougatTokenizer:()=>w_,PreTrainedTokenizer:()=>W,Qwen2Tokenizer:()=>x_,RoFormerTokenizer:()=>b_,RobertaTokenizer:()=>y_,SiglipTokenizer:()=>v_,SpeechT5Tokenizer:()=>k_,SqueezeBertTokenizer:()=>E_,T5Tokenizer:()=>A_,TokenizersBackend:()=>W,VitsTokenizer:()=>T_,Wav2Vec2CTCTokenizer:()=>S_,WhisperTokenizer:()=>O_,XLMRobertaTokenizer:()=>I_,XLMTokenizer:()=>C_});var Ud=class extends W{return_token_type_ids=!0};var jd=class extends W{};var Gd=class extends W{return_token_type_ids=!0};var qd=class extends W{};var Wd=class extends W{};var Vd=class extends W{};var Hd=class extends W{};var Xd=class extends W{};var Kd=class extends W{};var Yd=class extends W{};var Qd=class extends W{};var Jd=class extends W{};var Zd=class extends W{return_token_type_ids=!0};var e_=class extends W{return_token_type_ids=!0};var t_=class extends W{return_token_type_ids=!0};var r_=class extends W{};var s_=class extends W{return_token_type_ids=!0};var n_=class extends W{};var o_=class extends W{};var a_=class extends W{};var i_=class extends W{};var l_=class extends W{};var c_=class extends W{return_token_type_ids=!0};var u_=class extends W{padding_side="left"};var p_=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return mn(this,e,r,s)}};var f_=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),ee.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[r,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(r);if(s.length===2){let[n,o]=s;return this.supported_language_codes.includes(n)||ee.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),gt([n],super._encode_text(o))}}};var zo=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return mn(this,e,r,s)}};var d_=class extends zo{};var __=class extends W{};var m_=class extends W{return_token_type_ids=!0};var h_=class extends W{};var g_=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return mn(this,e,r,s)}};var w_=class extends W{};var x_=class extends W{};var y_=class extends W{};var b_=class extends W{return_token_type_ids=!0};var v_=class extends W{};var k_=class extends W{};var E_=class extends W{return_token_type_ids=!0};var A_=class extends W{};var M_=class extends Dt{decode_chain(e){let r="";for(let s=1;s[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function eM(t){t=t.toLowerCase();let e=BL.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),Lo.has(t))e=t;else{let n=t.length===2?Lo.keys():Lo.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var UL="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",tM=new RegExp(`^[${UL}]+$`,"gu"),jL=.1,O_=class extends W{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],p=l(),f=0,_=this.timestamp_begin,w=_+1500,x=[],k=[],A=!1,E=null,S=new Set(this.all_special_ids);for(let O of e){let b=O.tokens,F=i?O.token_timestamps:null,j=null,U=_;if("stride"in O){let[J,R,C]=O.stride;if(f-=R,E=J-C,R&&(U=R/n+_),C)for(let se=b.length-1;se>=0;--se){let Y=Number(b[se]);if(Y>=_){if(j!==null&&(Y-_)*n=_&&R<=w){let C=(R-_)*n+f,se=gs(C,2);if(j!==null&&R>=j)A=!0;else if(A||x.length>0&&R0&&p.timestamp[1]!==null))for(let B of p.words)B.timestamp[1]>p.timestamp[1]&&p.timestamp[1]>=B.timestamp[0]&&(B.timestamp[1]=p.timestamp[1]);c.push(p),x=[],X=[],k=[],K=[],p=l()}}else if(X.push(R),i){let C=gs(F[J]+f,2),se;if(J+10?(x.push(X),i&&k.push(K)):x.every(J=>J.length===0)&&(p=l(),x=[],X=[],k=[],K=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[O,b]=this.findLongestCommonSequence(x,k),F=this.decode(O);p.text=F,i&&(p.words=this.collateWordTimestamps(O,b,a)),c.push(p)}let T=Object.create(null),I=c.map(O=>O.text).join("");if(r||s){for(let O=0;O0,i=a?[]:null,l=a?r[0]:null;for(let c=1;cR===U[C]&&l[I+C][0]-jL<=r[c][F+C][0]).length:X=b.filter((R,C)=>R===U[C]).length;let K=T/1e4,J=X/T+K;X>1&&J>f&&(f=J,_=[I,O,F,j])}let[w,x,k,A]=_,E=Math.floor((x+w)/2),S=Math.floor((A+k)/2);if(a&&f===0&&n>0){let T=l[n-1][0],I=r[c].findIndex(O=>O[0]>=T);S=I===-1?p.length:I}o.push(...s.slice(0,E)),s=p.slice(S),n=s.length,a&&(i.push(...l.slice(0,E)),l=r[c].slice(S))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],c=0;for(let p=0;p=this._tokenizer.token_to_id("<|endoftext|>"),m=c.startsWith(" "),w=c.trim(),x=tM.test(w);if(_||m||x||o.length===0)o.push(c),a.push(p),i.push(f);else{let k=o.length-1;o[k]+=c,a[k].push(...p),i[k].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,p=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[p]=a[c]+a[p],i[p]=gt(i[c],i[p]),l[p]=gt(l[c],l[p]),a[c]="",i[c]=[],l[c]=[]):p=c,--c;for(c=0,p=1;pf),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var I_=class extends W{};var C_=class extends W{return_token_type_ids=!0;constructor(e,r){super(e,r),ee.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var ne=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await Bd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=P_[c];return p||(ee.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=W),new p(i,l)}};var qr="https://github.com/huggingface/transformers.js/issues/new/choose";var No="preprocessor_config.json",yr=No,Fc="processor_config.json",Bc="chat_template.jinja";var re=class extends We{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?nt(e,Fc,!0,r):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{let i=await this[a].from_pretrained(e,r);return[a.replace(/_class$/,""),i]})).then(Object.fromEntries),this.uses_chat_template_file?xo(e,Bc,!0,r):null]);return new this(s,n,o)}};var pu={};en(pu,{ChatterboxProcessor:()=>X_,CohereAsrProcessor:()=>K_,Florence2Processor:()=>jm,Gemma3Processor:()=>Gm,Gemma3nProcessor:()=>qm,Gemma4Processor:()=>Wm,Glm46VProcessor:()=>Vm,GraniteSpeechProcessor:()=>Hm,GroundingDinoProcessor:()=>Xm,Idefics3Processor:()=>iu,JinaCLIPProcessor:()=>Ym,Lfm2VlProcessor:()=>Qm,LlavaProcessor:()=>Jm,MgpstrProcessor:()=>Zm,MoonshineProcessor:()=>eh,OwlViTProcessor:()=>th,PaliGemmaProcessor:()=>rh,Phi3VProcessor:()=>sh,PixtralProcessor:()=>nh,Processor:()=>re,PyAnnoteProcessor:()=>oh,Qwen2VLProcessor:()=>Os,Qwen2_5_VLProcessor:()=>Ho,Qwen3VLProcessor:()=>ah,Sam2Processor:()=>lu,Sam2VideoProcessor:()=>ih,SamProcessor:()=>Xo,SmolVLMProcessor:()=>iu,SpeechT5Processor:()=>lh,UltravoxProcessor:()=>ch,VLChatProcessor:()=>Km,VoxtralProcessor:()=>uh,VoxtralRealtimeProcessor:()=>fh,Wav2Vec2Processor:()=>dh,Wav2Vec2ProcessorWithLM:()=>_h,WhisperProcessor:()=>mh});var Ee=class extends We{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await nt(e,No,!0,r);return new this(s)}};function Ae(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var Go={};en(Go,{ASTFeatureExtractor:()=>N_,ChatterboxFeatureExtractor:()=>$_,ClapFeatureExtractor:()=>R_,CohereAsrFeatureExtractor:()=>D_,DacFeatureExtractor:()=>Fo,EncodecFeatureExtractor:()=>Ro,FeatureExtractor:()=>Ee,Gemma3nAudioFeatureExtractor:()=>Bo,Gemma4AudioFeatureExtractor:()=>Uo,GraniteSpeechFeatureExtractor:()=>F_,MoonshineFeatureExtractor:()=>B_,ParakeetFeatureExtractor:()=>Do,PyAnnoteFeatureExtractor:()=>jo,SeamlessM4TFeatureExtractor:()=>U_,SnacFeatureExtractor:()=>j_,SpeechT5FeatureExtractor:()=>G_,VoxtralRealtimeFeatureExtractor:()=>V_,Wav2Vec2FeatureExtractor:()=>q_,WeSpeakerFeatureExtractor:()=>W_,WhisperFeatureExtractor:()=>H_});import GL from"fs";import{Readable as qL}from"stream";import{pipeline as WL}from"stream/promises";async function Uc(t,e){if(ie.IS_BROWSER_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(ie.IS_FS_AVAILABLE){let r=e.stream(),s=qL.fromWeb(r),n=GL.createWriteStream(t);await WL(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function nM(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await Pr(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&ee.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let c=0;c2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function z_(t,e="htk"){let r=HL[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}var XL={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,r=15,s=Math.log(6.4)/27)=>t>=r?e*Math.exp(s*(t-r)):200*t/3};function KL(t,e="htk"){let r=XL[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}function YL(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;anew Array(t.length));for(let a=0;at+s*o)}function lt(t,e,r,s,n,o=null,a="htk",i=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);let l=z_(r,a),c=z_(s,a),p=sM(l,c,e+2),f=KL(p,a),_;if(i){let w=n/((t-1)*2);_=z_(Float64Array.from({length:t},(x,k)=>k*w),a),f=p}else _=sM(0,Math.floor(n/2),t);let m=YL(_,f);if(o!==null&&o==="slaney")for(let w=0;wn)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(j!==r)throw new Error(`Length of the window (${j}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!p)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a){let Q=Math.floor(r/2);switch(i){case"reflect":{t=QL(t,Q,Q);break}case"constant":{let le=new t.constructor(t.length+2*Q);le.set(t,Q),t=le;break}case"semicausal":{let le=new t.constructor(t.length+Q);le.set(t,Q),t=le;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let U=Math.floor(1+Math.floor((t.length-r)/s));S!==null&&UU?I&&(J=T):J=K=T);let R=new gc(n),C=new Float64Array(n),se=new Float64Array(R.outputBufferSize),Y=new Float32Array(X*J);for(let Q=0;Q=1;--ce)C[ce]-=c*C[ce-1];C[0]*=1-c}for(let ce=0;ceMath.pow(c,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null||t===s)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);let i=new Float64Array(s),l=n?Math.floor((s-t)/2):0;return i.set(a,l),i}function eN(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return jc(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),jc(n,8,"WAVE"),jc(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,e,!0),n.setUint32(28,e*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),jc(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function jc(t,e,r){for(let s=0;sn+o.length,0),r=new Float32Array(e),s=0;for(let n of this.audio)r.set(n,s),s+=n.length;return r}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),eN(e,this.sampling_rate)}async save(e){return Uc(e,this.toBlob())}};var N_=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){Ae(e,"ASTFeatureExtractor");let r=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let s=this.std*2,n=r.data;for(let o=0;o0)if(s==="rand_trunc"){a=!0;let l=Math.floor(hs.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let c=e.length;c=1;--n)e[n]-=r*e[n-1];return await ot(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){Ae(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f1?s-1:1;for(let f=0;f=p){l.push(e.slice(c,p));break}let f=Math.max(c,c+a-i),_=Math.min(c+a,p),m;_<=f?m=c+a:m=this._find_split_point_energy(e,f,_,n),m=Math.max(c+1,Math.min(m,p)),l.push(e.slice(c,m)),c=m}return l}_find_split_point_energy(e,r,s,n){let o=s-r;if(o<=n)return Math.floor((r+s)/2);let a=1/0,i=r,l=o-n;for(let c=0;c<=l;c+=n){let p=0;for(let f=0;fr&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let a=await this._extract_fbank_features(e,this.config.max_length),i=Qe([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var Uo=class extends Bo{async _extract_fbank_features(e,r){let{frame_length:s,hop_length:n,fft_length:o}=this.config,a=Math.floor(s/2),i=Math.floor((e.length+a-(s+1))/n)+1;return ot(e,this.window,s,n,{fft_length:o,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:i})}async _call(e,r={}){Ae(e,"Gemma4AudioFeatureExtractor");let s=e.length,n=await super._call(e,r),{input_features:o}=n,[,a,i]=o.dims,{frame_length:l,hop_length:c}=this.config,p=Math.floor(l/2),f=l+1,_=new Uint8Array(s+p+(r.pad_to_multiple_of??128));_.fill(1,p,p+s);let m=new Uint8Array(a);for(let x=0;x({id:l,start:c*s,end:p*s,confidence:f/(p-c)})))}return n}};var U_=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){Ae(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,k=a.data;for(let A=0;A0){let E=new Float32Array(x*(w+A));E.set(k),E.fill(this.config.padding_value,k.length);let S=w+A;a=new N(a.type,E,[S,x]),o&&(i=new N("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,p=this.config.stride;if(l%p!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${p}).`);let _=a.view(1,Math.floor(l/p),c*p),m={input_features:_};if(o){let w=_.dims[1],x=new BigInt64Array(w);if(i){let k=i.data;for(let A=1,E=0;Ao+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){Ae(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));let s=[1,r.length];return{input_values:new N("float32",r,s),attention_mask:new N("int64",new BigInt64Array(r.length).fill(1n),s)}}};var W_=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){Ae(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;ln?(e.length>this.config.n_samples&&ee.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var je=class{static async from_pretrained(e,r={}){let s=await nt(e,No,!0,r),n=s.feature_extractor_type,o=Go[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${qr}.`);return new o(s)}};var X_=class extends re{static tokenizer_class=ne;static feature_extractor_class=je;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var rN=new Set(["ja","zh"]),K_=class extends re{static tokenizer_class=ne;static feature_extractor_class=je;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let r=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(r)}static join_chunks(e,r="en"){let s=e.filter(a=>a&&a.trim());if(s.length===0)return"";let n=rN.has(r)?"":" ";return[s[0].trimEnd(),...s.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}};import Y_ from"sharp";var Ss,iM,Wr;if(ie.IS_WEB_ENV)Ss=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},Wr=self.createImageBitmap,iM=self.ImageData;else if(Y_)Wr=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Je(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&o.convert(r),o};else throw new Error("Unable to load image processing library.");var sN={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},nN=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Je=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!ie.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let s=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(s,e.width,e.height,4)}static async fromURL(e){let r=await Pr(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(e){if(ie.IS_WEB_ENV){let r=await Wr(e),s=Ss(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=Y_(await e.arrayBuffer());return await Wr(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r=0?l=s:p=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,p,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await Wr(o)}}async toBlob(e="image/png",r=1){if(!ie.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new N("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!ie.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=Ss(e.width,e.height),s=new iM(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;lnew t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(ie.IS_WEB_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=nN.get(r)??"image/png",n=await this.toBlob(s);return Uc(e,n)}else if(ie.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(ie.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return Y_(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},oN=Je.read.bind(Je);function lM(t,e,r=0,s=null){let n=t/e,o=pA(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),oe&&A.push(S)}else{let S=Pe(k.data)[1];if(S===l-1||(E=$e(k.data),E[S]I*f[(O+1)%2])),_.boxes.push(T),_.classes.push(S),_.scores.push(E[S])}}c.push(_)}return c}function Gc(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;of[A]&&(f[A]=k[A],_[A]=x)}let m=new Array(i.dims[0]);for(let x=0;x<_.length;++x){let k=_[x];m[k]=k}let w=m.filter(x=>x!==void 0);n.push({segmentation:p,labels:w})}return n}function aN(t,e,r,s){let n=[],o=[],a=[];for(let i=0;ir&&(n.push(c),o.push(_),a.push(p))}return[n,o,a]}function iN(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let p=0;p=s&&++i;let c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function lN(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new N("int32",new Int32Array(i*l),[i,l]),p=[];if(a!==null)for(let x=0;x_[E]&&(f[E]=x,_[E]=A[E])}let m=0,w=c.data;for(let x=0;x200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let a=Math.round(t/r)*r,i=Math.round(e/r)*r;if(o*a*i>n){let l=Math.sqrt(o*t*e/n);a=Math.max(r,Math.floor(t/l/r)*r),i=Math.max(r,Math.floor(e/l/r)*r)}else if(o*a*io?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=yo(s.data)[0],a=Pe(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=s.height,p=0,f=0,_=s.data;for(let m=0;mthis.preprocess(o)));return{pixel_values:xt(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await nt(e,yr,!0,r);return new this(s)}};var bn={};en(bn,{BeitFeatureExtractor:()=>J_,BitImageProcessor:()=>Z_,CHMv2ImageProcessor:()=>tm,CLIPFeatureExtractor:()=>rm,CLIPImageProcessor:()=>Vc,ChineseCLIPFeatureExtractor:()=>em,ConvNextFeatureExtractor:()=>sm,ConvNextImageProcessor:()=>Hc,DINOv3ViTImageProcessor:()=>am,DPTFeatureExtractor:()=>lm,DPTImageProcessor:()=>Yc,DeiTFeatureExtractor:()=>nm,DeiTImageProcessor:()=>Xc,DetrFeatureExtractor:()=>om,DetrImageProcessor:()=>Kc,DonutFeatureExtractor:()=>im,DonutImageProcessor:()=>gn,EfficientNetImageProcessor:()=>cm,GLPNFeatureExtractor:()=>fm,Gemma3ImageProcessor:()=>um,Gemma4ImageProcessor:()=>qo,Glm46VImageProcessor:()=>pm,GroundingDinoImageProcessor:()=>dm,Idefics3ImageProcessor:()=>Qc,ImageFeatureExtractor:()=>H,ImageProcessor:()=>H,JinaCLIPImageProcessor:()=>mm,Lfm2VlImageProcessor:()=>hm,LlavaOnevisionImageProcessor:()=>gm,Mask2FormerImageProcessor:()=>xm,MaskFormerFeatureExtractor:()=>wm,MaskFormerImageProcessor:()=>wn,MobileNetV1FeatureExtractor:()=>ym,MobileNetV1ImageProcessor:()=>Jc,MobileNetV2FeatureExtractor:()=>bm,MobileNetV2ImageProcessor:()=>Zc,MobileNetV3FeatureExtractor:()=>vm,MobileNetV3ImageProcessor:()=>eu,MobileNetV4FeatureExtractor:()=>km,MobileNetV4ImageProcessor:()=>tu,MobileViTFeatureExtractor:()=>Em,MobileViTImageProcessor:()=>ru,NougatImageProcessor:()=>Am,OwlViTFeatureExtractor:()=>Mm,OwlViTImageProcessor:()=>xn,Owlv2ImageProcessor:()=>Tm,Phi3VImageProcessor:()=>Im,PixtralImageProcessor:()=>Cm,PvtImageProcessor:()=>Pm,Qwen2VLImageProcessor:()=>Wo,RTDetrImageProcessor:()=>zm,Sam2ImageProcessor:()=>Vo,Sam3ImageProcessor:()=>Vo,SamImageProcessor:()=>Vo,SapiensFeatureExtractor:()=>Lm,SapiensImageProcessor:()=>su,SegformerFeatureExtractor:()=>Nm,SegformerImageProcessor:()=>nu,SiglipImageProcessor:()=>$m,SmolVLMImageProcessor:()=>Qc,Swin2SRImageProcessor:()=>Rm,VLMImageProcessor:()=>_m,ViTFeatureExtractor:()=>Dm,ViTImageProcessor:()=>ou,VitMatteImageProcessor:()=>Fm,VitPoseImageProcessor:()=>Bm,YolosFeatureExtractor:()=>Um,YolosImageProcessor:()=>au});var J_=class extends H{};var Z_=class extends H{};var em=class extends H{};var tm=class extends H{};var Vc=class extends H{},rm=class extends Vc{};var Hc=class extends H{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){let s=Math.floor(r/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}},sm=class extends Hc{};var Xc=class extends H{},nm=class extends Xc{};var Kc=class extends H{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Qe(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Vr(...e)}post_process_panoptic_segmentation(...e){return qc(...e)}post_process_instance_segmentation(...e){return Wc(...e)}},om=class extends Kc{};var am=class extends H{};var gn=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let p=l.map((f,_)=>-f/c[_]);return super.pad_image(e,r,s,{center:!0,constant_values:p,...n})}},im=class extends gn{};var Yc=class extends H{},lm=class extends Yc{};var cm=class extends H{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}};var um=class extends H{};function cN(t,e,r,s,n){let o=s*r**2,a=Math.sqrt(o/(t*e)),i=n*r,l=Math.floor(a*t/i)*i,c=Math.floor(a*e/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);let p=Math.floor(s/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(e/t)*i,p)):c===0&&(c=i,l=Math.min(Math.floor(t/e)*i,p)),[l,c]}function uN(t,e,r,s,n,o,a){let i=Math.floor(e/n),l=Math.floor(r/n),c=i*l,p=n*n*s,f=new Float32Array(o*p),_=0;for(let x=0;xa),0));let p=a.dims[0]/i,f=a.dims[1],_=Math.floor(a.dims[2]/c),m=Math.floor(a.dims[3]/c),w=a.view(p,i,f,Math.floor(_/l),l,c,Math.floor(m/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(p*_*m,f*i*c*c),x=new N("int64",[p,_,m],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var pm=class extends Wo{get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return hn(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}};var fm=class extends H{};var dm=class extends H{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=et([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var Qc=class extends H{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],c=[];for(let A of n){let E=await Promise.all(A.map(I=>this.preprocess(I)));l.push(...E.map(I=>I.original_size)),c.push(...E.map(I=>I.reshaped_input_size)),E.forEach(I=>I.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,T;if(r??this.do_image_splitting){let I=new Array(E.length),O=new Array(E.length);T=await Promise.all(E.map(async(b,F)=>{let j=this.get_resize_for_vision_encoder(b.pixel_values,S),U=await bt(b.pixel_values,{size:[j.height,j.width]}),{frames:X,num_splits_h:K,num_splits_w:J}=await this.split_image(U,this.max_image_size);return I[F]=K,O[F]=J,ve(X,0)})),a.push(I),i.push(O)}else{let I=[S,S];T=await Promise.all(E.map(O=>bt(O.pixel_values,{size:I}))),a.push(new Array(E.length).fill(0)),i.push(new Array(E.length).fill(0))}o.push(ve(T,0))}let p=o.length,[f,_,m,w]=o[0].dims,x,k;if(p===1)x=o[0].unsqueeze_(0),k=Qe([p,f,m,w],!0);else{let A=Math.max(...o.map(T=>T.dims.at(0)));k=Qe([p,A,m,w],!0);let E=k.data,S=A*m*w;for(let T=0;Ts||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let p=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;wr*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var mm=class extends H{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function uM(t,e){return Math.round(t/e)*e}function pN(t,e,r,s,n){let o=1/0,a=[1,1],i=r*s;for(let l of e){let c=Math.abs(t-l[0]/l[1]);c.5*n*n*l[0]*l[1]&&(a=l)}return a}function fN(t,e){let r=[],s=new Set;for(let n=t;n<=e;++n)for(let o=1;o<=n;++o)for(let a=1;a<=n;++a){let i=o*a;if(i>=t&&i<=e){let l=o<<16|a;s.has(l)||(s.add(l),r.push([o,a]))}}return r.sort((n,o)=>n[0]*n[1]-o[0]*o[1])}function dN(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,p=new Float32Array(r*a*i*l),f=n*o;for(let _=0;_this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=fN(this.min_tiles,this.max_tiles),[n,o]=pN(r/e,s,r,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:r=null}={}){let s;Array.isArray(e)?Array.isArray(e[0])?s=e:s=[e]:s=[[e]];let n=[],o=[],a=[],i=[],l=[],c=[];for(let f of s){let _=await Promise.all(f.map(m=>this.preprocess(m,{do_pad:!1})));for(let{pixel_values:m}of _){let[,w,x]=m.dims,k=m.unsqueeze_(0),A=this.encoder_patch_size*this.downsample_factor,E=A**2,[S,T]=hn(Math.max(A,w),Math.max(A,x),A,this.min_image_tokens*E,this.max_image_tokens*E).map(U=>Math.max(A,U)),I,O=1,b=1,F=this._is_image_too_large(w,x),j=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(F&&j){let{grid_width:U,grid_height:X,target_width:K,target_height:J}=this._get_grid_layout(w,x);O=X,b=U;let R=await bt(k,{size:[J,K]});I=[];for(let C=0;C(p-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||Om(r)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(_=>this.preprocess(_))),o=n.map(_=>_.original_size),a=n.map(_=>_.reshaped_input_size),i=[];for(let{pixel_values:_}of n){_.unsqueeze_(0);let[m,w]=_.dims.slice(-2),x=await bt(_,{size:[Nt,Nt],mode:"bicubic"});if(r>0){let k=[],A=Om(r),E=yn(w/A),S=yn(m/A);for(let I=0;I_.map(m=>Nt*Sm(m/Nt))),p=new N("int64",c.flat(),[s,2]),f=c.map(([_,m])=>this.calc_num_image_tokens_from_image_size(m,_));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:p,num_img_tokens:f}}};var Cm=class extends H{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");let f=c*p,_=Math.floor((i-1)/f)+1,m=Math.floor((l-1)/f)+1;return[_*f,m*f]}};var Pm=class extends H{};var zm=class extends H{post_process_object_detection(...e){return Vr(...e)}};var Vo=class extends H{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=Cf(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;an!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new N("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let c=0;cn&&(w[x]=1);_=new N("bool",w,_.dims)}i.push(_)}return i}generate_crop_boxes(e,r,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:a=1}={}){}};var su=class extends H{post_process_semantic_segmentation(...e){return Gc(...e)}},Lm=class extends su{};var nu=class extends H{post_process_semantic_segmentation(...e){return Gc(...e)}},Nm=class extends nu{};var $m=class extends H{};var Rm=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r;return super.pad_image(e,r,{width:a+(s-a%s)%s,height:o+(s-o%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var ou=class extends H{},Dm=class extends ou{};var Fm=class extends H{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let s=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(r.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:xt(s.map((a,i)=>ve([a.pixel_values,n[i].pixel_values],0)),0),original_sizes:s.map(a=>a.original_size),reshaped_input_sizes:s.map(a=>a.reshaped_input_size)}}};var Bm=class extends H{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let p=0;p/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],c=[];for(let[p,f,..._]of i)l.push(f?f.trim():l.at(-1)??""),c.push(_.map((m,w)=>(Number(m)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:c};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var Gm=class extends re{static tokenizer_class=ne;static image_processor_class=Me;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:o,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=o,this.eoi_token=a;let i=o.repeat(this.image_seq_length);this.full_image_sequence=` ++ }`,h=new Function(Object.keys(P),L)(...Object.values(P)),L=`methodCaller<(${v.map(G=>G.name)}) => ${g.name}>`,pS(Object.defineProperty(h,"name",{value:L}))}function hS(u,d){return d>>>=0,(u=Rt(u>>>0))==Rt(d)}function gS(u){return(u>>>=0)?(u=Ql(u),qt(globalThis[u])):qt(globalThis)}function wS(u){return u=Ql(u>>>0),qt(e[u])}function xS(u,d){return d>>>=0,u=Rt(u>>>0),d=Rt(d),qt(u[d])}function yS(u){9<(u>>>=0)&&(us[u+1]+=1)}function Bv(u,d,h,g,v){return cf[u>>>0](d>>>0,h>>>0,g>>>0,v>>>0)}function bS(u,d,h,g,v){return Bv(u>>>0,d>>>0,h>>>0,g>>>0,v>>>0)}function vS(){return qt([])}function kS(u){u=Rt(u>>>0);for(var d=Array(u.length),h=0;h>>0))}function AS(){return qt({})}function MS(u){for(var d=Rt(u>>>=0);d.length;){var h=d.pop();d.pop()(h)}rf(u)}function TS(u,d,h){d>>>=0,h>>>=0,u=Rt(u>>>0),d=Rt(d),h=Rt(h),u[d]=h}function SS(u,d){u=mt(u),d>>>=0,u=new Date(1e3*u),(b(),R)[d>>>2>>>0]=u.getUTCSeconds(),(b(),R)[d+4>>>2>>>0]=u.getUTCMinutes(),(b(),R)[d+8>>>2>>>0]=u.getUTCHours(),(b(),R)[d+12>>>2>>>0]=u.getUTCDate(),(b(),R)[d+16>>>2>>>0]=u.getUTCMonth(),(b(),R)[d+20>>>2>>>0]=u.getUTCFullYear()-1900,(b(),R)[d+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(b(),R)[d+28>>>2>>>0]=u}var Uv=u=>u%4==0&&(u%100!=0||u%400==0),jv=[0,31,60,91,121,152,182,213,244,274,305,335],Gv=[0,31,59,90,120,151,181,212,243,273,304,334];function OS(u,d){u=mt(u),d>>>=0,u=new Date(1e3*u),(b(),R)[d>>>2>>>0]=u.getSeconds(),(b(),R)[d+4>>>2>>>0]=u.getMinutes(),(b(),R)[d+8>>>2>>>0]=u.getHours(),(b(),R)[d+12>>>2>>>0]=u.getDate(),(b(),R)[d+16>>>2>>>0]=u.getMonth(),(b(),R)[d+20>>>2>>>0]=u.getFullYear()-1900,(b(),R)[d+24>>>2>>>0]=u.getDay();var h=(Uv(u.getFullYear())?jv:Gv)[u.getMonth()]+u.getDate()-1|0;(b(),R)[d+28>>>2>>>0]=h,(b(),R)[d+36>>>2>>>0]=-60*u.getTimezoneOffset(),h=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(h!=g&&u.getTimezoneOffset()==Math.min(g,h)),(b(),R)[d+32>>>2>>>0]=u}function IS(u){u>>>=0;var d=new Date((b(),R)[u+20>>>2>>>0]+1900,(b(),R)[u+16>>>2>>>0],(b(),R)[u+12>>>2>>>0],(b(),R)[u+8>>>2>>>0],(b(),R)[u+4>>>2>>>0],(b(),R)[u>>>2>>>0],0),h=(b(),R)[u+32>>>2>>>0],g=d.getTimezoneOffset(),v=new Date(d.getFullYear(),6,1).getTimezoneOffset(),M=new Date(d.getFullYear(),0,1).getTimezoneOffset(),P=Math.min(M,v);return 0>h?(b(),R)[u+32>>>2>>>0]=+(v!=M&&P==g):0>>2>>>0]=d.getDay(),h=(Uv(d.getFullYear())?jv:Gv)[d.getMonth()]+d.getDate()-1|0,(b(),R)[u+28>>>2>>>0]=h,(b(),R)[u>>>2>>>0]=d.getSeconds(),(b(),R)[u+4>>>2>>>0]=d.getMinutes(),(b(),R)[u+8>>>2>>>0]=d.getHours(),(b(),R)[u+12>>>2>>>0]=d.getDate(),(b(),R)[u+16>>>2>>>0]=d.getMonth(),(b(),R)[u+20>>>2>>>0]=d.getYear(),u=d.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function qv(u,d,h,g,v,M,P){return n?Be(16,1,u,d,h,g,v,M,P):-52}function Wv(u,d,h,g,v,M){if(n)return Be(17,1,u,d,h,g,v,M)}var oo={},CS=()=>performance.timeOrigin+performance.now();function Vv(u,d){if(n)return Be(18,1,u,d);if(oo[u]&&(clearTimeout(oo[u].id),delete oo[u]),!d)return 0;var h=setTimeout(()=>{delete oo[u],Mt(()=>bk(u,performance.timeOrigin+performance.now()))},d);return oo[u]={id:h,Ae:d},0}function PS(u,d,h,g){u>>>=0,d>>>=0,h>>>=0,g>>>=0;var v=new Date().getFullYear(),M=new Date(v,0,1).getTimezoneOffset();v=new Date(v,6,1).getTimezoneOffset();var P=Math.max(M,v);(b(),C)[u>>>2>>>0]=60*P,(b(),R)[d>>>2>>>0]=+(M!=v),u=(d=L=>{var G=Math.abs(L);return`UTC${0<=L?"-":"+"}${String(Math.floor(G/60)).padStart(2,"0")}${String(G%60).padStart(2,"0")}`})(M),d=d(v),vDate.now(),LS=1;function NS(u,d,h){if(h>>>=0,!(0<=u&&3>=u))return 28;if(u===0)u=Date.now();else{if(!LS)return 52;u=performance.timeOrigin+performance.now()}return u=Math.round(1e6*u),(b(),z)[h>>>3>>>0]=BigInt(u),0}var uf=[],Hv=(u,d)=>{uf.length=0;for(var h;h=(b(),X)[u++>>>0];){var g=h!=105;d+=(g&=h!=112)&&d%8?4:0,uf.push(h==112?(b(),C)[d>>>2>>>0]:h==106?(b(),z)[d>>>3>>>0]:h==105?(b(),R)[d>>>2>>>0]:(b(),Y)[d>>>3>>>0]),d+=g?8:4}return uf};function $S(u,d,h){return u>>>=0,d=Hv(d>>>0,h>>>0),Af[u](...d)}function RS(u,d,h){return u>>>=0,d=Hv(d>>>0,h>>>0),Af[u](...d)}var DS=()=>{};function FS(u,d){return T(Ys(u>>>0,d>>>0))}var BS=()=>{throw Oe+=1,"unwind"};function US(){return 4294901760}var jS=()=>1,GS=()=>navigator.hardwareConcurrency;function qS(u){u>>>=0;var d=(b(),X).length;if(u<=d||4294901760=h;h*=2){var g=d*(1+.2/h);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-Tr.buffer.byteLength+65535)/65536|0;try{Tr.grow(g),le();var v=1;break e}catch{}v=void 0}if(v)return!0}return!1}var nr=u=>{var d=mr(u)+1,h=tc(d);return _r(u,h,d),h},pf=(u,d)=>{(b(),C)[u>>>2>>>0]=d;var h=(b(),C)[u>>>2>>>0];(b(),C)[u+4>>>2>>>0]=(d-h)/4294967296},ao=u=>(b(),C)[u>>>2>>>0]+4294967296*(b(),R)[u+4>>>2>>>0],ht=[],WS=(u,d)=>{ht[u>>>0]=d},hr=[],Jl=[],Js=(u,d)=>{Jl[u]=new Promise(h=>d.finally(()=>h(u)))},oe=u=>{if(u)return ht[u>>>0]},VS=(u,d)=>{for(u=(b(),C)[u>>>2>>>0];u;u=(b(),C)[u>>>2>>>0])d[(b(),R)[u+4>>>2>>>0]](u)},Zl=(u,d,h)=>{(b(),C)[u>>>2>>>0]=d,(b(),C)[u+4>>>2>>>0]=h},Xv=u=>{var d=(b(),C)[u>>>2>>>0];return u=(b(),C)[u+4>>>2>>>0],Ys(d,u)},gr=u=>{var d=(b(),C)[u>>>2>>>0];return u=(b(),C)[u+4>>>2>>>0],d?Ys(d,u):u===0?"":void 0},HS=u=>{var d=gr(u+4),h=(h=(b(),C)[u+12>>>2>>>0])?oe(h):"auto";if(u+=16){var g=oe((b(),C)[u+4>>>2>>>0]),v=(b(),C)[u+16>>>2>>>0],M=(b(),C)[u+20>>>2>>>0];if(v){for(var P={},L=0;L>>3>>>0]}v=P}else v=void 0;u={module:g,constants:v,entryPoint:gr(u+8)}}else u=void 0;return{label:d,layout:h,compute:u}},Kv=(u,d)=>{function h(g,v){g=u[g],(b(),C)[d+v>>>2>>>0]=g}h("maxTextureDimension1D",4),h("maxTextureDimension2D",8),h("maxTextureDimension3D",12),h("maxTextureArrayLayers",16),h("maxBindGroups",20),h("maxBindGroupsPlusVertexBuffers",24),h("maxBindingsPerBindGroup",28),h("maxDynamicUniformBuffersPerPipelineLayout",32),h("maxDynamicStorageBuffersPerPipelineLayout",36),h("maxSampledTexturesPerShaderStage",40),h("maxSamplersPerShaderStage",44),h("maxStorageBuffersPerShaderStage",48),h("maxStorageTexturesPerShaderStage",52),h("maxUniformBuffersPerShaderStage",56),h("minUniformBufferOffsetAlignment",80),h("minStorageBufferOffsetAlignment",84),pf(d+64,u.maxUniformBufferBindingSize),pf(d+72,u.maxStorageBufferBindingSize),h("maxVertexBuffers",88),pf(d+96,u.maxBufferSize),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),u.ze!==void 0&&h("maxImmediateSize",148)},XS=[,"validation","out-of-memory","internal"],KS=[,"compatibility","core"],Yv={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},YS=[,"low-power","high-performance"],QS=[,"occlusion","timestamp"],JS={undefined:1,unknown:1,destroyed:2};function ZS(u,d,h,g,v,M){d=mt(d),h=mt(h),g>>>=0,v>>>=0,M>>>=0;var P=oe(u>>>0);if(u={},M){var L=(b(),C)[M+12>>>2>>>0];if(L){var G=(b(),C)[M+16>>>2>>>0];u.requiredFeatures=Array.from((b(),C).subarray(G>>>2>>>0,G+4*L>>>2>>>0),ae=>Yv[ae])}var Z=(b(),C)[M+20>>>2>>>0];if(Z){let ae=function(Tt,pt,ps=!1){pt=Z+pt,(pt=(b(),C)[pt>>>2>>>0])==4294967295||ps&&pt==0||(Ue[Tt]=pt)},ut=function(Tt,pt){pt=Z+pt;var ps=(b(),C)[pt>>>2>>>0],EI=(b(),C)[pt+4>>>2>>>0];ps==4294967295&&EI==4294967295||(Ue[Tt]=ao(pt))};var Ie=ae,Ne=ut,Ue={};ae("maxTextureDimension1D",4),ae("maxTextureDimension2D",8),ae("maxTextureDimension3D",12),ae("maxTextureArrayLayers",16),ae("maxBindGroups",20),ae("maxBindGroupsPlusVertexBuffers",24),ae("maxDynamicUniformBuffersPerPipelineLayout",32),ae("maxDynamicStorageBuffersPerPipelineLayout",36),ae("maxSampledTexturesPerShaderStage",40),ae("maxSamplersPerShaderStage",44),ae("maxStorageBuffersPerShaderStage",48),ae("maxStorageTexturesPerShaderStage",52),ae("maxUniformBuffersPerShaderStage",56),ae("minUniformBufferOffsetAlignment",80),ae("minStorageBufferOffsetAlignment",84),ut("maxUniformBufferBindingSize",64),ut("maxStorageBufferBindingSize",72),ae("maxVertexBuffers",88),ut("maxBufferSize",96),ae("maxVertexAttributes",104),ae("maxVertexBufferArrayStride",108),ae("maxInterStageShaderVariables",112),ae("maxColorAttachments",116),ae("maxColorAttachmentBytesPerSample",120),ae("maxComputeWorkgroupStorageSize",124),ae("maxComputeInvocationsPerWorkgroup",128),ae("maxComputeWorkgroupSizeX",132),ae("maxComputeWorkgroupSizeY",136),ae("maxComputeWorkgroupSizeZ",140),ae("maxComputeWorkgroupsPerDimension",144),ae("maxImmediateSize",148,!0),u.requiredLimits=Ue}(L=(b(),C)[M+24>>>2>>>0])&&(L={label:gr(L+4)},u.defaultQueue=L),u.label=gr(M+4)}Oe+=1,Js(d,P.requestDevice(u).then(ae=>{--Oe,Mt(()=>{ht[v>>>0]=ae.queue,ht[g>>>0]=ae,Oe+=1,Js(h,ae.lost.then(ut=>{Mt(()=>{ae.onuncapturederror=()=>{};var Tt=fe(),pt=nr(ut.message);hf(h,JS[ut.reason],pt),pe(Tt)}),--Oe})),ae.onuncapturederror=ut=>{var Tt=5;ut.error instanceof GPUValidationError?Tt=2:ut.error instanceof GPUOutOfMemoryError?Tt=3:ut.error instanceof GPUInternalError&&(Tt=4);var pt=fe();ut=nr(ut.error.message),gk(g,Tt,ut),pe(pt)},"adapterInfo"in ae||(ae.adapterInfo=P.info),xf(d,1,g,0)})},ae=>{--Oe,Mt(()=>{var ut=fe(),Tt=nr(ae.message);xf(d,3,g,Tt),h&&hf(h,4,Tt),pe(ut)})}))}function eO(u){var d=oe(u>>>=0),h=hr[u];if(h){for(var g=0;g>>=0;var g=oe(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(d>>>0,h)}catch{return 0}var M=vf(16,v.byteLength);return(b(),X).set(new Uint8Array(v),M>>>0),hr[u].push(()=>Wt(M)),M}function rO(u,d,h){h>>>=0;var g=oe(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(d>>>0,h)}catch{return 0}var M=vf(16,v.byteLength);return(b(),X).fill(0,M,v.byteLength),hr[u].push(()=>{new Uint8Array(v).set((b(),X).subarray(M>>>0,M+v.byteLength>>>0)),Wt(M)}),M}function sO(u,d,h,g,v){u>>>=0,d=mt(d),h=mt(h),v>>>=0;var M=oe(u);hr[u]=[],v==4294967295&&(v=void 0),Oe+=1,Js(d,M.mapAsync(h,g>>>0,v).then(()=>{--Oe,Mt(()=>{gf(d,1,0)})},P=>{--Oe,Mt(()=>{fe();var L=nr(P.message);gf(d,P.name==="AbortError"?4:P.name==="OperationError"?3:0,L),delete hr[u]})}))}function nO(u){var d=oe(u>>>=0),h=hr[u];if(h){for(var g=0;g>>0]}function aO(u,d,h){u>>>=0,d>>>=0,h>>>=0;var g=!!(b(),C)[d+32>>>2>>>0];d={label:gr(d+4),usage:(b(),C)[d+16>>>2>>>0],size:ao(d+24),mappedAtCreation:g},u=oe(u);try{var v=u.createBuffer(d)}catch{return!1}return ht[h>>>0]=v,g&&(hr[h]=[]),!0}function iO(u,d,h,g){u>>>=0,d=mt(d),g>>>=0,h=HS(h>>>0),u=oe(u),Oe+=1,Js(d,u.createComputePipelineAsync(h).then(v=>{--Oe,Mt(()=>{ht[g>>>0]=v,mf(d,1,g,0)})},v=>{--Oe,Mt(()=>{var M=fe(),P=nr(v.message);mf(d,v.reason==="validation"?3:v.reason==="internal"?4:0,g,P),pe(M)})}))}function lO(u,d,h){u>>>=0,d>>>=0,h>>>=0;var g=(b(),C)[d>>>2>>>0],v=(b(),R)[g+4>>>2>>>0];d={label:gr(d+4),code:""},v===2&&(d.code=Xv(g+8)),u=oe(u).createShaderModule(d),ht[h>>>0]=u}var cO=u=>{(u=oe(u)).onuncapturederror=null,u.destroy()};function uO(u,d){d=mt(d),u=oe(u>>>0),Oe+=1,Js(d,u.popErrorScope().then(h=>{--Oe,Mt(()=>{var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var v=fe(),M=h?nr(h.message):0;wf(d,1,g,M),pe(v)})},h=>{--Oe,Mt(()=>{var g=fe(),v=nr(h.message);wf(d,1,5,v),pe(g)})}))}function pO(u,d,h,g){if(d=mt(d),g>>>=0,h>>>=0){var v={featureLevel:KS[(b(),R)[h+4>>>2>>>0]],powerPreference:YS[(b(),R)[h+8>>>2>>>0]],forceFallbackAdapter:!!(b(),C)[h+12>>>2>>>0]};(u=(b(),C)[h>>>2>>>0])!==0&&(b(),v.De=!!(b(),C)[u+8>>>2>>>0])}"gpu"in navigator?(Oe+=1,Js(d,navigator.gpu.requestAdapter(v).then(M=>{--Oe,Mt(()=>{if(M)ht[g>>>0]=M,io(d,1,g,0);else{var P=fe(),L=nr("WebGPU not available on this browser (requestAdapter returned null)");io(d,3,g,L),pe(P)}})},M=>{--Oe,Mt(()=>{var P=fe(),L=nr(M.message);io(d,4,g,L),pe(P)})}))):(v=fe(),u=nr("WebGPU not available on this browser (navigator.gpu is not available)"),io(d,3,g,u),pe(v))}function fO(u,d,h){return u>>>=0,d>>>=0,h>>>=0,Fv(async()=>{var g=[];if(h){var v=(b(),R)[h>>>2>>>0];g.length=d+1,g[d]=new Promise(L=>setTimeout(L,v,0))}else g.length=d;for(var M=0;M{if(!ff){var u,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in df)df[u]===void 0?delete d[u]:d[u]=df[u];var h=[];for(u in d)h.push(`${u}=${d[u]}`);ff=h}return ff};function Jv(u,d){if(n)return Be(19,1,u,d);u>>>=0,d>>>=0;var h,g=0,v=0;for(h of Qv()){var M=d+g;(b(),C)[u+v>>>2>>>0]=M,g+=_r(h,M,1/0)+1,v+=4}return 0}function Zv(u,d){if(n)return Be(20,1,u,d);u>>>=0,d>>>=0;var h=Qv();for(var g of((b(),C)[u>>>2>>>0]=h.length,u=0,h))u+=mr(g)+1;return(b(),C)[d>>>2>>>0]=u,0}function ek(u){return n?Be(21,1,u):52}function tk(u,d,h,g){return n?Be(22,1,u,d,h,g):52}function rk(u,d,h,g){return n?Be(23,1,u,d,h,g):70}var dO=[null,[],[]];function sk(u,d,h,g){if(n)return Be(24,1,u,d,h,g);d>>>=0,h>>>=0,g>>>=0;for(var v=0,M=0;M>>2>>>0],L=(b(),C)[d+4>>>2>>>0];d+=8;for(var G=0;G>>0],Ne=dO[Z];Ie===0||Ie===10?((Z===1?S:T)(xv(Ne)),Ne.length=0):Ne.push(Ie)}v+=L}return(b(),C)[g>>>2>>>0]=v,0}function _O(u){return u>>>0}function mO(u,d){return Kv(oe(u>>>0).limits,d>>>0),1}function hO(u,d){return oe(u>>>0).features.has(Yv[d])}function gO(u){return BigInt(oe(u>>>0).size)}function wO(u){return BigInt(oe(u>>>0).usage)}function xO(u,d){if(u>>>=0,d>>>=0){var h=gr(d+4);h={label:h,timestampWrites:d=(d=(b(),C)[d+12>>>2>>>0])!==0?{querySet:oe((b(),C)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(b(),C)[d+8>>>2>>>0],endOfPassWriteIndex:(b(),C)[d+12>>>2>>>0]}:void 0}}return d=oe(u),u=fk(0),h=d.beginComputePass(h),ht[u>>>0]=h,u}function yO(u,d,h,g){h=mt(h),(g=mt(g))==-1&&(g=void 0),(u=oe(u>>>0)).clearBuffer(oe(d>>>0),h,g)}function bO(u,d,h,g,v,M){h=mt(h),v=mt(v),M=mt(M),oe(u>>>0).copyBufferToBuffer(oe(d>>>0),h,oe(g>>>0),v,M)}function vO(u){var d=oe(u>>>0);return u=uk(0),d=d.finish(),ht[u>>>0]=d,u}function kO(u,d,h,g,v,M){M=mt(M),oe(u>>>0).resolveQuerySet(oe(d>>>0),h,g,oe(v>>>0),M)}function EO(u,d,h,g){oe(u>>>0).dispatchWorkgroups(d,h,g)}function AO(u,d,h){h=mt(h),oe(u>>>0).dispatchWorkgroupsIndirect(oe(d>>>0),h)}function MO(u){oe(u>>>0).end()}function TO(u,d,h,g,v){g>>>=0,v>>>=0,u=oe(u>>>0),h=oe(h>>>0),g==0?u.setBindGroup(d,h):u.setBindGroup(d,h,(b(),C),v>>>2,g)}function SO(u,d){oe(u>>>0).setPipeline(oe(d>>>0))}function OO(u,d,h){oe(u>>>0).Ce(oe(d>>>0),h)}function IO(u,d){var h=oe(u>>>0);return u=ck(0),d=h.getBindGroupLayout(d),ht[u>>>0]=d,u}function CO(u,d){function h(v){var M=(b(),C)[v+8>>>2>>>0],P=(b(),C)[v+32>>>2>>>0],L=(b(),C)[v+36>>>2>>>0],G=0;return VS(v,{327681:Z=>{G=(b(),C)[Z+8>>>2>>>0]}}),M?((P=ao(v+24))==-1&&(P=void 0),M={buffer:oe(M),offset:ao(v+16),size:P}):M=oe(P||L||G),{binding:(b(),C)[v+4>>>2>>>0],resource:M}}u>>>=0,d={label:gr(4+(d>>>=0)),layout:oe((b(),C)[d+12>>>2>>>0]),entries:(function(v,M){for(var P=[],L=0;L>>2>>>0],(b(),C)[d+20>>>2>>>0])},u=oe(u);var g=lk(0);return WS(g,u.createBindGroup(d)),g}function PO(u,d){var h;return u>>>=0,(d>>>=0)&&(h={label:gr(d+4)}),d=oe(u),u=pk(0),h=d.createCommandEncoder(h),ht[u>>>0]=h,u}function zO(u,d){u>>>=0,d>>>=0,d={type:QS[(b(),R)[d+12>>>2>>>0]],count:(b(),C)[d+16>>>2>>>0]};var h=oe(u);return u=dk(0),d=h.createQuerySet(d),ht[u>>>0]=d,u}function LO(u,d){u=oe(u>>>0).adapterInfo,d>>>=0,(b(),C)[d+52>>>2>>>0]=u.subgroupMinSize,(b(),C)[d+56>>>2>>>0]=u.subgroupMaxSize;var h=u.vendor+u.architecture+u.device+u.description,g=mr(h)+1,v=Zs(g);return v&&_r(h,v,g),h=v,g=mr(u.vendor),Zl(d+4,h,g),h+=g,g=mr(u.architecture),Zl(d+12,h,g),h+=g,g=mr(u.device),Zl(d+20,h,g),Zl(d+28,h+g,mr(u.description)),(b(),R)[d+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(b(),R)[d+40>>>2>>>0]=u,(b(),C)[d+44>>>2>>>0]=0,(b(),C)[d+48>>>2>>>0]=0,1}var NO={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function $O(u,d){d>>>=0;var h=oe(u>>>0);u=Zs(4*h.features.size);var g=0,v=0;for(let M of h.features)0<=(h=NO[M])&&((b(),R)[u+g>>>2>>>0]=h,g+=4,v++);(b(),C)[d+4>>>2>>>0]=u,(b(),C)[d>>>2>>>0]=v}function RO(u,d){return Kv(oe(u>>>0).limits,d>>>0),1}function DO(u,d){oe(u>>>0).pushErrorScope(XS[d])}function FO(u,d,h){d>>>=0,h>>>=0,u=oe(u>>>0),d=Array.from((b(),R).subarray(h>>>2>>>0,h+4*d>>>2>>>0),g=>oe(g)),u.submit(d)}function BO(u,d,h,g,v){h=mt(h),g>>>=0,v>>>=0,u=oe(u>>>0),d=oe(d>>>0),g=(b(),X).subarray(g>>>0,g+v>>>0),u.writeBuffer(d,h,g,0,v)}n||(function(){for(var u=e.numThreads-1;u--;)fv();Fe.push(async()=>{var d=(async function(){if(!n)return Promise.all(Mr.map(pv))})();Se++,await d,--Se==0&&rt&&(d=rt,rt=null,d())})})(),n||(Tr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),le()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>fe(),e.stackRestore=u=>pe(u),e.stackAlloc=u=>tc(u),e.setValue=function(u,d,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(b(),U)[u>>>0]=d;break;case"i16":(b(),K)[u>>>1>>>0]=d;break;case"i32":(b(),R)[u>>>2>>>0]=d;break;case"i64":(b(),z)[u>>>3>>>0]=BigInt(d);break;case"float":(b(),se)[u>>>2>>>0]=d;break;case"double":(b(),Y)[u>>>3>>>0]=d;break;case"*":(b(),C)[u>>>2>>>0]=d;break;default:ce(`invalid type for setValue: ${h}`)}},e.getValue=function(u,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(b(),U)[u>>>0];case"i16":return(b(),K)[u>>>1>>>0];case"i32":return(b(),R)[u>>>2>>>0];case"i64":return(b(),z)[u>>>3>>>0];case"float":return(b(),se)[u>>>2>>>0];case"double":return(b(),Y)[u>>>3>>>0];case"*":return(b(),C)[u>>>2>>>0];default:ce(`invalid type for getValue: ${d}`)}},e.UTF8ToString=Ys,e.stringToUTF8=_r,e.lengthBytesUTF8=mr;var nk,ok,_f,ec,Wt,Zs,ak,ik,lk,ck,uk,pk,fk,dk,_k,mk,hk,mf,hf,gf,wf,io,xf,gk,yf,wk,xk,yk,bf,bk,vk,vf,xe,lo,kk,pe,tc,fe,Ek,kf,Ak,Mk,Tk,Ef,Sk,Ok,Ik,Ck,Pk,zk,Lk,Nk,$k,Rk,Dk,Fk,Bk,Uk,jk,Gk,qk,Wk,Vk,Hk,Xk,Kk,Yk,Qk,Jk,Zk,eE,tE,rE,sE,nE,oE,aE,iE,lE,cE,uE,pE,wr,UO=[Hs,so,mv,yv,bv,vv,kv,Ev,Av,Mv,Tv,Sv,Ov,Iv,Cv,Pv,qv,Wv,Vv,Jv,Zv,ek,tk,rk,sk],Af={970348:(u,d,h,g,v)=>{if(e===void 0||!e.Uc)return 1;if((u=Ys(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=e.Uc.get(u)))return 2;if(d=Number(d>>>0),h=Number(h>>>0),g=Number(g>>>0),d+h>u.byteLength)return 3;try{let M=u.subarray(d,d+h);switch(v){case 0:(b(),X).set(M,g>>>0);break;case 1:e.ad?e.ad(g,M):e.ne(g,M);break;default:return 4}return 0}catch{return 4}},971172:(u,d,h)=>{e.Sd(u,(b(),X).subarray(d>>>0,d+h>>>0))},971236:()=>e.le(),971278:u=>{e.jd(u)},971315:()=>typeof wasmOffsetConverter<"u"};function jO(u,d,h,g){var v=fe();try{return Nk(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function GO(u,d,h){var g=fe();try{return Pk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function qO(u){var d=fe();try{Sk(u)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function WO(u,d){var h=fe();try{return Ef(u,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function VO(u,d,h){var g=fe();try{Tk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function HO(u,d){var h=fe();try{$k(u,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function XO(u,d,h,g,v,M,P){var L=fe();try{return Ck(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function KO(u,d,h,g,v,M){var P=fe();try{Ok(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function YO(u,d,h,g){var v=fe();try{Lk(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function QO(u,d,h,g,v,M,P){var L=fe();try{Dk(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function JO(u,d,h,g,v,M,P){var L=fe();try{Fk(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function ZO(u,d,h,g,v,M,P,L){var G=fe();try{Xk(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function eI(u,d,h,g,v,M,P,L,G,Z,Ie,Ne){var Ue=fe();try{Bk(u,d,h,g,v,M,P,L,G,Z,Ie,Ne)}catch(ae){if(pe(Ue),ae!==ae+0)throw ae;xe(1,0)}}function tI(u,d,h,g,v){var M=fe();try{return Rk(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function rI(u,d,h,g,v){var M=fe();try{Ik(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function sI(u,d,h,g,v,M,P,L){var G=fe();try{zk(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function nI(u){var d=fe();try{return Kk(u)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function oI(u,d,h){var g=fe();try{return Yk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function aI(u,d){var h=fe();try{return iE(u,d)}catch(g){if(pe(h),g!==g+0)throw g;return xe(1,0),0n}}function iI(u){var d=fe();try{return Uk(u)}catch(h){if(pe(d),h!==h+0)throw h;return xe(1,0),0n}}function lI(u,d,h,g){var v=fe();try{return Qk(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function cI(u,d,h,g,v){var M=fe();try{return Jk(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function uI(u,d,h,g,v,M){var P=fe();try{return Zk(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function pI(u,d,h,g,v,M){var P=fe();try{return Vk(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function fI(u,d,h,g,v,M){var P=fe();try{return eE(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function dI(u,d,h,g,v,M,P,L){var G=fe();try{return Hk(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function _I(u,d,h,g,v){var M=fe();try{return tE(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;return xe(1,0),0n}}function mI(u,d,h,g){var v=fe();try{return rE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function hI(u,d,h,g){var v=fe();try{return sE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function gI(u,d,h,g,v,M,P,L,G,Z,Ie,Ne){var Ue=fe();try{return nE(u,d,h,g,v,M,P,L,G,Z,Ie,Ne)}catch(ae){if(pe(Ue),ae!==ae+0)throw ae;xe(1,0)}}function wI(u,d,h,g,v,M,P,L,G,Z,Ie){var Ne=fe();try{oE(u,d,h,g,v,M,P,L,G,Z,Ie)}catch(Ue){if(pe(Ne),Ue!==Ue+0)throw Ue;xe(1,0)}}function xI(u,d,h,g,v,M,P,L,G,Z,Ie,Ne,Ue,ae,ut,Tt){var pt=fe();try{aE(u,d,h,g,v,M,P,L,G,Z,Ie,Ne,Ue,ae,ut,Tt)}catch(ps){if(pe(pt),ps!==ps+0)throw ps;xe(1,0)}}function yI(u,d,h){var g=fe();try{return Gk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;return xe(1,0),0n}}function bI(u,d,h){var g=fe();try{return jk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function vI(u,d,h){var g=fe();try{return qk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function kI(u,d,h,g){var v=fe();try{Wk(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function rc(){if(0{let d=new WeakMap,h,g,v=1;e.webgpuRegisterDevice=L=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(L){var G=d.get(L);if(!G){let Z=((Ie,Ne=0)=>{var Ue=hk(Ne);return Ne=mk(Ne,Ue),ht[Ue>>>0]=Ie.queue,ht[Ne>>>0]=Ie,Ne})(L,G=ik(0));G=[v++,G,Z],d.set(L,G)}return h=L,g=G[0],G}h=void 0,g=0};let M=new Map;e.webgpuOnCreateSession=L=>{if(g!==void 0){var G=g;if(g=void 0,L){let Z=_f(G);M.set(L,Z),G===0&&u(h??oe(Z))}h=void 0}},e.webgpuOnReleaseSession=L=>{M.delete(L)};let P=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(L,G,Z)=>{if(Z)return L[P]=[Z,NaN],Z;if(Z=L[P])return Z[1]++,Z[0];if((G=M.get(G))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return G=((Ie,Ne=0)=>(Ie.mapState==="unmapped"||ce(),Ne=_k(Ne),ht[Ne>>>0]=Ie,Ne))(L,G),L[P]=[G,1],G},e.webgpuUnregisterBuffer=L=>{let G=L[P];if(!G)throw Error("Buffer is not registered");G[1]--,G[1]===0&&(ak(G[0]),delete L[P])},e.webgpuGetBuffer=L=>oe(L),e.webgpuCreateDownloader=(L,G,Z)=>{if((Z=M.get(Z))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Ie=oe(Z),Ne=16*Math.ceil(Number(G)/16);return async()=>{let Ue=Ie.createBuffer({size:Ne,usage:9});try{let ae=Ie.createCommandEncoder();return ae.copyBufferToBuffer(L,0,Ue,0,Ne),Ie.queue.submit([ae.finish()]),await Ue.mapAsync(GPUMapMode.READ),Ue.getMappedRange().slice(0,G)}finally{Ue.destroy()}}},e.ad=(L,G)=>{var Z=G.buffer;let Ie=G.byteOffset,Ne=G.byteLength;if(G=16*Math.ceil(Number(Ne)/16),L=oe(L),!h){var Ue=_f(g);h=oe(Ue)}let ae=(Ue=h.createBuffer({mappedAtCreation:!0,size:G,usage:6})).getMappedRange();new Uint8Array(ae).set(new Uint8Array(Z,Ie,Ne)),Ue.unmap(),(Z=h.createCommandEncoder()).copyBufferToBuffer(Ue,0,L,0,G),h.queue.submit([Z.finish()]),Ue.destroy()}},e.webnnInit=u=>{let d=u[0];[e.le,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.ke,e.webnnEnableTraceEvent]=u.slice(1),e.webnnReleaseTensorId=e.jd,e.webnnUploadTensor=e.Sd,e.webnnRegisterMLContext=e.ke,e.webnnOnRunStart=h=>d.onRunStart(h),e.webnnOnRunEnd=d.onRunEnd.bind(d),e.webnnOnReleaseSession=h=>{d.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>d.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,v,M)=>d.registerMLTensor(h,g,v,M),e.webnnCreateMLContext=h=>d.createMLContext(h),e.webnnRegisterMLConstant=(h,g,v,M,P,L)=>d.registerMLConstant(h,g,v,M,P,e.Uc,L),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},Q?e:new Promise((u,d)=>{w=u,x=d})}var c2,hA,xL=be(()=>{"use strict";c2=mA,hA=globalThis.self?.name?.startsWith("em-pthread"),hA&&mA()}),Hf,cd,gA,Pt,u2,xc,wA,xA,Xf,yA,Kf,p2,Yf,f2,wd=be(()=>{"use strict";gd(),Hf=typeof location>"u"?void 0:location.origin,cd=import_meta.url>"file:"&&import_meta.url<"file;",gA=()=>{if(cd){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import_meta.url).href,Hf).href}return import_meta.url},Pt=gA(),u2=()=>{if(Pt&&!Pt.startsWith("blob:"))return Pt.substring(0,Pt.lastIndexOf("/")+1)},xc=(t,e)=>{try{let r=e??Pt;return(r?new URL(t,r):new URL(t)).origin===Hf}catch{return!1}},wA=(t,e)=>{let r=e??Pt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},xA=(t,e)=>`${e??"./"}${t}`,Xf=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},yA=async t=>(await import(t)).default,Kf=(wL(),Ac(a2)).default,p2=async()=>{if(!Pt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(xc(Pt))return[void 0,Kf()];let t=await Xf(Pt);return[t,Kf(t)]},Yf=(xL(),Ac(l2)).default,f2=async(t,e,r,s)=>{let n=Yf&&!(t||e);if(n)if(Pt)n=xc(Pt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,Yf];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??wA(o,e),i=r&&a&&!xc(a,e),l=i?await Xf(a):a??xA(o,e);return[i?l:void 0,await yA(l)]}}}),Qf,yc,vo,Jf,bA,vA,kA,xd,De,Ms=be(()=>{"use strict";wd(),yc=!1,vo=!1,Jf=!1,bA=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},vA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},kA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},xd=async t=>{if(yc)return Promise.resolve();if(vo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Jf)throw new Error("previous call to 'initializeWebAssembly()' failed.");vo=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!kA())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!vA())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=bA();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,p=t.wasmBinary,[f,_]=await f2(i,o,r>1,!!p||!!c),m=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{m=!0,x()},e)})),w.push(new Promise((x,k)=>{let A={numThreads:r};if(p)A.wasmBinary=p,A.locateFile=E=>E;else if(c||o)A.locateFile=E=>c??o+E;else if(i&&i.indexOf("blob:")!==0)A.locateFile=E=>new URL(E,i).href;else if(f){let E=u2();E&&(A.locateFile=S=>E+S)}_(A).then(E=>{vo=!1,yc=!0,Qf=E,x(),f&&URL.revokeObjectURL(f)},E=>{vo=!1,Jf=!0,k(E)})})),await Promise.race(w),m)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},De=()=>{if(yc&&Qf)return Qf;throw new Error("WebAssembly is not initialized yet.")}}),zt,Tc,ze,yd=be(()=>{"use strict";Ms(),zt=(t,e)=>{let r=De(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},Tc=(t,e,r,s)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([n,o])=>{let a=e?e+n:n;if(typeof o=="object")Tc(o,a+".",r,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},ze=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetLastError(n,n+s);let o=Number(e.getValue(n,s===4?"i32":"i64")),a=e.getValue(n+s,"*"),i=a?e.UTF8ToString(a):"";throw new Error(`${t} ERROR_CODE: ${o}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}}),d2,yL=be(()=>{"use strict";Ms(),yd(),d2=t=>{let e=De(),r=0,s=[],n=t||{};try{if(t?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(n.terminate=!1);let o=0;return t?.tag!==void 0&&(o=zt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&ze("Can't create run options."),t?.extra!==void 0&&Tc(t.extra,"",new WeakSet,(a,i)=>{let l=zt(a,s),c=zt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&ze(`Can't set a run config entry: ${a} - ${i}.`)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),s.forEach(a=>e._free(a)),o}}}),EA,AA,MA,bc,$r,TA,_2,bL=be(()=>{"use strict";Ms(),yd(),EA=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},AA=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},MA=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},bc=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);De()._OrtAddSessionConfigEntry(t,n,o)!==0&&ze(`Can't set a session config entry: ${e} - ${r}.`)},$r=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);t.push([n,o])},TA=async(t,e,r)=>{let s=e.executionProviders;for(let n of s){let o=typeof n=="string"?n:n.name,a=[];switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let f=n?.deviceType;f&&bc(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let m=n;if(m.device)if(typeof GPUDevice<"u"&&m.device instanceof GPUDevice)f=m.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&$r(a,"enableGraphCapture","1",r),typeof m.preferredLayout=="string"&&$r(a,"preferredLayout",m.preferredLayout,r),m.forceCpuNodeNames){let x=Array.isArray(m.forceCpuNodeNames)?m.forceCpuNodeNames:[m.forceCpuNodeNames];$r(a,"forceCpuNodeNames",x.join(` ++`),r)}m.validationMode&&$r(a,"validationMode",m.validationMode,r)}let _=De().webgpuRegisterDevice(f);if(_){let[m,w,x]=_;$r(a,"deviceId",m.toString(),r),$r(a,"webgpuInstance",w.toString(),r),$r(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=zt(o,r),l=a.length,c=0,p=0;if(l>0){c=De()._malloc(l*De().PTR_SIZE),r.push(c),p=De()._malloc(l*De().PTR_SIZE),r.push(p);for(let f=0;f{let e=De(),r=0,s=[],n=t||{};MA(n);try{let o=EA(n.graphOptimizationLevel??"all"),a=AA(n.executionMode??"sequential"),i=typeof n.logId=="string"?zt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?zt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,p),r===0&&ze("Can't create session options."),n.executionProviders&&await TA(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);bc(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[f,_]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw new Error(`free dimension override value must be a non-negative integer: ${_}`);let m=zt(f,s);e._OrtAddFreeDimensionOverride(r,m,_)!==0&&ze(`Can't set a free dimension override: ${f} - ${_}.`)}return n.extra!==void 0&&Tc(n.extra,"",new WeakSet,(f,_)=>{bc(r,f,_,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&ze("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),bs,Ec,un,To,Sc,bd,vd,ud,pn=be(()=>{"use strict";bs=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},Ec=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},un=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],s=typeof e=="number"?e:e.reduce((n,o)=>n*o,1);return r>0?Math.ceil(s*r):void 0},To=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Sc=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},bd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",vd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",ud=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${t}`)}}}),kd,m2=be(()=>{"use strict";gd(),kd=async t=>{if(typeof t=="string"){let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(o,a,c).set(l),a+=c}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),h2,vL=be(()=>{"use strict";pn(),h2=(t,e)=>new(To(e))(t)}),SA,OA,IA,CA,g2,PA,yt,w2=be(()=>{"use strict";pn(),SA=["V","I","W","E","F"],OA=(t,e)=>{console.log(`[${SA[t]},${new Date().toISOString()}]${e}`)},g2=(t,e)=>{IA=t,CA=e},PA=(t,e)=>{let r=Sc(t),s=Sc(IA);r>=s&&OA(r,typeof e=="function"?e():e)},yt=(...t)=>{CA&&PA(...t)}}),Zf,pd,ed,zA,td,LA,rd,sd,nd,NA,x2,kL=be(()=>{"use strict";pn(),w2(),Zf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),pd=(t,e)=>{if(e==="int32")return t;let r=Zf.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);let s=r/8;if(t.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=t.byteLength/s,o=new(To(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(l)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&o.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(o,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},ed=(t,e)=>{if(e==="int32")return t;if(t.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=t.byteLength/4,s=new Int32Array(t.buffer,t.byteOffset,r);switch(e){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(o=>o<-128||o>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${e}`)}},zA=1,td=()=>zA++,LA=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),rd=(t,e)=>{let r=Zf.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);return e.length>0?Math.ceil(e.reduce((s,n)=>s*n)*r/8):0},sd=class{constructor(t){this.isDataConverted=!1;let{sessionId:e,context:r,tensor:s,dataType:n,shape:o,fallbackDataType:a}=t;this.sessionId=e,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.fallbackDataType=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return rd(this.dataType,this.tensorShape)}destroy(){yt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){if(this.fallbackDataType){let e=await this.mlContext.readTensor(this.mlTensor),r=ed(new Uint8Array(e),this.dataType);if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(r);return}else return r.buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,e,r){return this.mlContext===t&&this.dataType===e&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(t){this.isDataConverted=t}},nd=class{constructor(t,e){this.tensorManager=t,this.wrapper=e}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,e,r,s){let n=this.tensorManager.getMLContext(t),o=this.tensorManager.getMLOpSupportLimits(t),a;if(!o?.input.dataTypes.includes(e)){if(a=LA.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);yt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${e} to ${a}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,e,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==rd(e,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,e,r,i,!0,!0,a),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){let e=t;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")e=pd(t,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else yt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(t){if(this.activeUpload){let e=this.wrapper?.isDataConverted?ed(this.activeUpload,this.wrapper?.type):this.activeUpload;if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(e):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(e);return}else return e.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(t):this.wrapper.read()}},NA=class{constructor(t){this.backend=t,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(t){let e=this.backend.getMLContext(t);if(!e)throw new Error("MLContext not found for session.");return e}getMLOpSupportLimits(t){return this.backend.getMLOpSupportLimits(t)}reserveTensorId(){let t=td();return this.tensorTrackersById.set(t,new nd(this)),t}releaseTensorId(t){let e=this.tensorTrackersById.get(t);e&&(this.tensorTrackersById.delete(t),e.tensorWrapper&&this.releaseTensor(e.tensorWrapper))}async ensureTensor(t,e,r,s,n){yt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,s,n)}upload(t,e){let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");r.upload(e)}async download(t,e){yt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${e?.byteLength}}`);let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");return r.download(e)}releaseTensorsForSession(t){for(let e of this.freeTensors)e.sessionId===t&&e.destroy();this.freeTensors=this.freeTensors.filter(e=>e.sessionId!==t)}registerTensor(t,e,r,s){let n=this.getMLContext(t),o=td(),a=new sd({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new nd(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(i,e,r)){yt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}yt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:a??e,shape:r,dimensions:r,usage:s,writable:n,readable:o});return new sd({sessionId:t,context:i,tensor:l,dataType:e,shape:r,fallbackDataType:a})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},x2=(...t)=>new NA(...t)}),y2={};So(y2,{WebNNBackend:()=>b2});var ko,$A,b2,EL=be(()=>{"use strict";pn(),Ms(),vL(),kL(),w2(),ko=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),$A=(t,e)=>{if(t===e)return!0;if(t===void 0||e===void 0)return!1;let r=Object.keys(t).sort(),s=Object.keys(e).sort();return r.length===s.length&&r.every((n,o)=>n===s[o]&&t[n]===e[n])},b2=class{constructor(t){this.tensorManager=x2(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,g2(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){yt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){yt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)yt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(t),this.activeSessionId=void 0}}async createMLContext(t){if(t instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===t);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:s}),s}}else if(t===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let e=this.mlContextCache.findIndex(r=>$A(r.options,t));if(e!==-1)return this.mlContextCache[e].mlContext;{let r=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:r}),r}}registerMLContext(t,e){this.mlContextBySessionId.set(t,e);let r=this.sessionIdsByMLContext.get(e);r||(r=new Set,this.sessionIdsByMLContext.set(e,r)),r.add(t),this.mlOpSupportLimitsBySessionId.has(t)||this.mlOpSupportLimitsBySessionId.set(t,e.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(t,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(t,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(t){this.sessionGraphInputs.delete(t),this.sessionGraphOutputs.delete(t);let e=this.mlContextBySessionId.get(t);if(!e)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t),this.mlOpSupportLimitsBySessionId.delete(t);let r=this.sessionIdsByMLContext.get(e);if(r.delete(t),r.size===0){this.sessionIdsByMLContext.delete(e);let s=this.mlContextCache.findIndex(n=>n.mlContext===e);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}getMLOpSupportLimits(t){return this.mlOpSupportLimitsBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){yt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=ko.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t??this.currentSessionId,e,o,s,n)}async createTemporaryTensor(t,e,r){yt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=ko.get(e);if(!s)throw new Error(`Unsupported ONNX data type: ${e}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(t,n,s,r,!1);let o=this.temporarySessionTensorIds.get(t);return o?o.push(n):this.temporarySessionTensorIds.set(t,[n]),n}uploadTensor(t,e){if(!De().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");yt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${e.byteLength}}`),this.tensorManager.upload(t,e)}async downloadTensor(t,e){return this.tensorManager.download(t,e)}createMLTensorDownloader(t,e){return async()=>{let r=await this.tensorManager.download(t);return h2(r,e)}}registerMLTensor(t,e,r,s){let n=ko.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return yt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(e,e+r).buffer,p;switch(n.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":if(a){let f=pd(new Uint8Array(c),"int64");p=new Int32Array(f.buffer),n.dataType="int32"}else p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return yt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,p)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=ko.get(bs(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),RA,Ed,Ad,Rr,DA,od,Oc,Md,Td,ad,Sd,Od,Id,v2=be(()=>{"use strict";As(),yL(),bL(),pn(),Ms(),yd(),m2(),RA=(t,e)=>{De()._OrtInit(t,e)!==0&&ze("Can't initialize onnxruntime.")},Ed=async t=>{RA(t.wasm.numThreads,Sc(t.logLevel))},Ad=async(t,e)=>{De().asyncInit?.();let r=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=t.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let n=t.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(e==="webgpu"&&De().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(EL(),Ac(y2)).WebNNBackend(t);De().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,o,a,i,l)=>s.ensureTensor(n,o,a,i,l),(n,o)=>{s.uploadTensor(n,o)},async(n,o)=>s.downloadTensor(n,o),(n,o)=>s.registerMLContext(n,o),!!t.trace])}},Rr=new Map,DA=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetInputOutputCount(t,n,n+s)!==0&&ze("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(e.getValue(n,o)),Number(e.getValue(n+s,o))]}finally{e.stackRestore(r)}},od=(t,e)=>{let r=De(),s=r.stackSave(),n=0;try{let o=r.PTR_SIZE,a=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(t,e,a,a+o)!==0&&ze("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],p=[];for(let f=0;f{let e=De(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},Md=async(t,e)=>{let r,s,n=De();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=Oc(t);let o=0,a=0,i=0,l=[],c=[],p=[];try{if([a,l]=await _2(e),e?.externalData&&n.mountExternalData){let T=[];for(let I of e.externalData){let O=typeof I=="string"?I:I.path;T.push(kd(typeof I=="string"?I:I.data).then(b=>{n.mountExternalData(O,b)}))}await Promise.all(T)}for(let T of e?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof T!="string"){let I=T,O=I?.context,b=I?.gpuDevice,F=I?.deviceType,j=I?.powerPreference;O?n.currentContext=O:b?n.currentContext=await n.webnnCreateMLContext(b):n.currentContext=await n.webnnCreateMLContext({deviceType:F,powerPreference:j})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&ze("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,_]=DA(o),m=!!e?.enableGraphCapture,w=[],x=[],k=[],A=[],E=[];for(let T=0;TT==="gpu-buffer"||T==="ml-tensor"||T==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&ze("Can't create IO binding."),S={handle:i,outputPreferredLocations:E,outputPreferredLocationsEncoded:E.map(T=>T==="ml-tensor-cpu-output"?"ml-tensor":T).map(T=>ud(T))}),Rr.set(o,[o,c,p,S,m,!1]),[o,w,x,k,A]}catch(f){throw c.forEach(_=>n._OrtFree(_)),p.forEach(_=>n._OrtFree(_)),i!==0&&n._OrtReleaseBinding(i)!==0&&ze("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&ze("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&ze("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},Td=t=>{let e=De(),r=Rr.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&ze("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&ze("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(l=>e._OrtFree(l)),o.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(s)!==0&&ze("Can't release session."),Rr.delete(t)},ad=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=De(),l=i.PTR_SIZE,c=t[0],p=t[1],f=t[3],_=f,m,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let A=t[2].gpuBuffer;w=un(bs(c),p);{let E=i.webgpuRegisterBuffer;if(!E)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');m=E(A,s)}}else if(f==="ml-tensor"){let A=t[2].mlTensor;w=un(bs(c),p);let E=i.webnnRegisterMLTensor;if(!E)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');m=E(s,A,bs(c),p)}else{let A=t[2];if(Array.isArray(A)){w=l*A.length,m=i._malloc(w),r.push(m);for(let E=0;Ei.setValue(k+S*l,E,l===4?"i32":"i64"));let A=i._OrtCreateTensor(bs(c),m,w,k,p.length,ud(_));A===0&&ze(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(A)}finally{i.stackRestore(x)}},Sd=async(t,e,r,s,n,o)=>{let a=De(),i=a.PTR_SIZE,l=Rr.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],p=l[1],f=l[2],_=l[3],m=l[4],w=l[5],x=e.length,k=s.length,A=0,E=[],S=[],T=[],I=[],O=[],b=a.stackSave(),F=a.stackAlloc(x*i),j=a.stackAlloc(x*i),U=a.stackAlloc(k*i),X=a.stackAlloc(k*i);try{[A,E]=d2(o),Fr("wasm prepareInputOutputTensor");for(let C=0;CFe*Se,1);B=Ec(Ge);let At=_?.outputPreferredLocations[s[C]];if(B==="string"){if(At==="gpu-buffer"||At==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Fe=[];for(let Se=0;Se0){let Fe=a.webgpuGetBuffer;if(!Fe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Se=Fe(Q),rt=un(Ge,ct);if(rt===void 0||!bd(B))throw new Error(`Unsupported data type: ${B}`);$=!0;{a.webgpuRegisterBuffer(Se,t,Q);let tr=a.webgpuCreateDownloader(Se,rt,t);J.push([B,qe,{gpuBuffer:Se,download:async()=>{let Oe=await tr();return new(To(B))(Oe)},dispose:()=>{a._OrtReleaseTensor(se)!==0&&ze("Can't release tensor.")}},"gpu-buffer"])}}else if(At==="ml-tensor"&&ct>0){let Fe=a.webnnEnsureTensor,Se=a.webnnIsGraphInputOutputTypeSupported;if(!Fe||!Se)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(un(Ge,ct)===void 0||!vd(B))throw new Error(`Unsupported data type: ${B}`);if(!Se(t,B,!1))throw new Error(`preferredLocation "ml-tensor" for ${B} output is not supported by current WebNN Context.`);let rt=await Fe(t,Q,Ge,qe,!1);$=!0,J.push([B,qe,{mlTensor:rt,download:a.webnnCreateMLTensorDownloader(Q,B),dispose:()=>{a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(se)}},"ml-tensor"])}else if(At==="ml-tensor-cpu-output"&&ct>0){let Fe=a.webnnCreateMLTensorDownloader(Q,B)(),Se=J.length;$=!0,R.push((async()=>{let rt=[Se,await Fe];return a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(se),rt})()),J.push([B,qe,[],"cpu"])}else{let Fe=To(B),Se=new Fe(ct);new Uint8Array(Se.buffer,Se.byteOffset,Se.byteLength).set(a.HEAPU8.subarray(Q,Q+Se.byteLength)),J.push([B,qe,Se,"cpu"])}}finally{a.stackRestore(Y),B==="string"&&Q&&a._free(Q),$||a._OrtReleaseTensor(se)}}_&&!m&&(a._OrtClearBoundOutputs(_.handle)!==0&&ze("Can't clear bound outputs."),Rr.set(t,[c,p,f,_,m,!1]));for(let[C,se]of await Promise.all(R))J[C][2]=se;return Br("wasm ProcessOutputTensor"),J}finally{a.webnnOnRunEnd?.(c),a.stackRestore(b),r.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),n.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),S.forEach(K=>a._OrtReleaseTensor(K)),T.forEach(K=>a._OrtReleaseTensor(K)),I.forEach(K=>a._free(K)),A!==0&&a._OrtReleaseRunOptions(A),E.forEach(K=>a._free(K))}},Od=t=>{let e=De(),r=Rr.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&ze("Can't get an profile file name."),e._OrtFree(n)},Id=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Dr,Bt,cn,Eo,Ao,vc,id,kc,ws,xs,FA,k2,E2,A2,M2,T2,S2,O2,I2=be(()=>{"use strict";As(),v2(),Ms(),wd(),Dr=()=>!!Ye.wasm.proxy&&typeof document<"u",cn=!1,Eo=!1,Ao=!1,kc=new Map,ws=(t,e)=>{let r=kc.get(t);r?r.push(e):kc.set(t,[e])},xs=()=>{if(cn||!Eo||Ao||!Bt)throw new Error("worker not ready")},FA=t=>{switch(t.data.type){case"init-wasm":cn=!1,t.data.err?(Ao=!0,id[1](t.data.err)):(Eo=!0,id[0]()),vc&&(URL.revokeObjectURL(vc),vc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=kc.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},k2=async()=>{if(!Eo){if(cn)throw new Error("multiple calls to 'initWasm()' detected.");if(Ao)throw new Error("previous call to 'initWasm()' failed.");if(cn=!0,Dr())return new Promise((t,e)=>{Bt?.terminate(),p2().then(([r,s])=>{try{Bt=s,Bt.onerror=o=>e(o),Bt.onmessage=FA,id=[t,e];let n={type:"init-wasm",in:Ye};!n.in.wasm.wasmPaths&&(r||cd)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import_meta.url).href}),Bt.postMessage(n),vc=r}catch(n){e(n)}},e)});try{await xd(Ye.wasm),await Ed(Ye),Eo=!0}catch(t){throw Ao=!0,t}finally{cn=!1}}},E2=async t=>{if(Dr())return xs(),new Promise((e,r)=>{ws("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Ye}};Bt.postMessage(s)});await Ad(Ye,t)},A2=async t=>Dr()?(xs(),new Promise((e,r)=>{ws("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Bt.postMessage(s,[t.buffer])})):Oc(t),M2=async(t,e)=>{if(Dr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return xs(),new Promise((r,s)=>{ws("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Bt.postMessage(n,o)})}else return Md(t,e)},T2=async t=>{if(Dr())return xs(),new Promise((e,r)=>{ws("release",[e,r]);let s={type:"release",in:t};Bt.postMessage(s)});Td(t)},S2=async(t,e,r,s,n,o)=>{if(Dr()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return xs(),new Promise((a,i)=>{ws("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Bt.postMessage(c,Id(l))})}else return Sd(t,e,r,s,n,o)},O2=async t=>{if(Dr())return xs(),new Promise((e,r)=>{ws("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Bt.postMessage(s)});Od(t)}}),ld,BA,C2,AL=be(()=>{"use strict";As(),I2(),pn(),gd(),m2(),ld=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},BA=t=>{switch(t[3]){case"cpu":return new Qt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!bd(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return Qt.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!vd(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return Qt.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},C2=class{async fetchModelAndCopyToWasmMemory(t){return A2(await kd(t))}async loadModel(t,e){ks();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await M2(r,e),Es()}async dispose(){return T2(this.sessionId)}async run(t,e,r){ks();let s=[],n=[];Object.entries(t).forEach(f=>{let _=f[0],m=f[1],w=this.inputNames.indexOf(_);if(w===-1)throw new Error(`invalid input '${_}'`);s.push(m),n.push(w)});let o=[],a=[];Object.entries(e).forEach(f=>{let _=f[0],m=f[1],w=this.outputNames.indexOf(_);if(w===-1)throw new Error(`invalid output '${_}'`);o.push(m),a.push(w)});let i=s.map((f,_)=>ld(f,()=>`input "${this.inputNames[n[_]]}"`)),l=o.map((f,_)=>f?ld(f,()=>`output "${this.outputNames[a[_]]}"`):null),c=await S2(this.sessionId,n,i,a,l,r),p={};for(let f=0;fdd,initializeFlags:()=>fd,wasmBackend:()=>z2});var fd,dd,z2,ML=be(()=>{"use strict";As(),I2(),AL(),fd=()=>{(typeof Ye.wasm.initTimeout!="number"||Ye.wasm.initTimeout<0)&&(Ye.wasm.initTimeout=0);let t=Ye.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),Ye.wasm.simd=!1),typeof Ye.wasm.proxy!="boolean"&&(Ye.wasm.proxy=!1),typeof Ye.wasm.trace!="boolean"&&(Ye.wasm.trace=!1),typeof Ye.wasm.numThreads!="number"||!Number.isInteger(Ye.wasm.numThreads)||Ye.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Ye.wasm.numThreads=1;else{let e=typeof navigator>"u"?sL("node:os").cpus().length:navigator.hardwareConcurrency;Ye.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},dd=class{async init(t){fd(),await k2(),await E2(t)}async createInferenceSessionHandler(t,e){let r=new C2;return await r.loadModel(t,e),r}},z2=new dd});As();As();As();var TL="1.26.0-dev.20260416-b7804b056c",SL=o2;{let t=(ML(),Ac(P2)).wasmBackend;vs("webgpu",t,5),vs("webnn",t,5),vs("cpu",t,10),vs("wasm",t,10)}Object.defineProperty(Ye.versions,"web",{value:TL,enumerable:!0});async function L2(t){let e=t.split("/").pop(),r;try{if(r=await Yt(),r){let n=await r.match(t);if(n)return n}}catch(n){ee.warn(`Failed to load ${e} from cache:`,n)}let s=await me.fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){ee.warn(`Failed to cache ${e}:`,n)}return s}async function N2(t){let e=await L2(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return ee.warn("Failed to read WASM binary:",r),null}}async function $2(t){if(ie.IS_SERVICE_WORKER_ENV||ie.IS_CHROME_AVAILABLE)return t;let e=await L2(t);if(!e||typeof e=="string")return null;try{let r=await e.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return ee.warn("Failed to read WASM factory:",r),null}}import{Tensor as j2}from"onnxruntime-common";var IL=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function B2(t){return t<=St.DEBUG?0:t<=St.INFO?2:t<=St.WARNING||t<=St.ERROR?3:4}var CL={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},Ut=[],Pd,dn,R2=Symbol.for("onnxruntime");if(R2 in globalThis)dn=globalThis[R2];else if(ie.IS_NODE_ENV){switch(dn=OL,process.platform){case"win32":Ut.push("dml");break;case"linux":process.arch==="x64"&&Ut.push("cuda");break;case"darwin":Ut.push("coreml");break}Ut.push("webgpu"),Ut.push("cpu"),Pd=["cpu"]}else dn=Cd,ie.IS_WEBNN_AVAILABLE&&Ut.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ie.IS_WEBGPU_AVAILABLE&&Ut.push("webgpu"),Ut.push("wasm"),Pd=["wasm"];var PL=dn.InferenceSession;function U2(t=null){if(!t)return Pd;switch(t){case"auto":return Ut;case"gpu":return Ut.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Ut.includes(t))return[IL[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Ut.join(", ")}.`)}var D2=Promise.resolve(),fn=null;async function zL(){if(fn)return fn;if(!(me.useWasmCache&&typeof it?.wasm?.wasmPaths=="object"&&it?.wasm?.wasmPaths?.wasm&&it?.wasm?.wasmPaths?.mjs)){if(ie.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return fn=Promise.resolve(),fn}return fn=(async()=>{let e=it.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!$f(e.wasm)?(async()=>{try{let s=await N2(Rf(e.wasm));s&&(it.wasm.wasmBinary=s,r=!0)}catch(s){ee.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!$f(e.mjs)?(async()=>{try{let s=await $2(Rf(e.mjs));s&&(it.wasm.wasmPaths.mjs=s)}catch(s){ee.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(it.wasm.wasmPaths.mjs=e.mjs)})(),fn}async function Ic(t,e,r){await zL();let s=B2(me.logLevel??St.WARNING),n=()=>PL.create(t,{logSeverityLevel:s,...e}),o=await(ie.IS_WEB_ENV?D2=D2.then(n):n());return o.config=r,o}var F2=Promise.resolve();async function Cc(t,e){let r=()=>t.run(e);return ie.IS_WEB_ENV?F2=F2.then(r):r()}function Pc(t){return t instanceof dn.Tensor}var it=dn?.env;function Oo(){return it?.wasm?.proxy}if(it){let t=function(e){let r=B2(e);it.logLevel=CL[r]};if(it.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&it.versions?.web&&!it.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${it.versions.web}/dist/`;it.wasm.wasmPaths=ie.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}it.wasm.proxy=!1}it.webgpu&&(it.webgpu.powerPreference="high-performance"),t(me.logLevel??St.WARNING),me.backends.onnx={...it,setLogLevel:t}}var Ur=async(t,e,r)=>{let s=await Ic(new Uint8Array(t),e);return(async n=>{let o=Oo(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await Cc(s,a);return Array.isArray(r)?r.map(l=>new N(i[l])):new N(i[r])})},lr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Ur([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Ur([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Ur([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Ur([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Ur([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Ur([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Ur([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=Ur([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var G2=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),zd=ie.IS_NODE_ENV?"cpu":"wasm";function zc(t,e,{warn:r}={}){return t?typeof t=="string"?t:t.hasOwnProperty(e)?t[e]:(r&&r(`device not specified for "${e}". Using the default device (${zd}).`),zd):zd}var V2=(function(){let t;return async function(){if(t===void 0)if(!ie.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),st=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),q2=st.fp32,W2=Object.freeze({[G2.wasm]:st.q8}),jr=Object.freeze({[st.fp32]:"",[st.fp16]:"_fp16",[st.int8]:"_int8",[st.uint8]:"_uint8",[st.q8]:"_quantized",[st.q4]:"_q4",[st.q2]:"_q2",[st.q1]:"_q1",[st.q4f16]:"_q4f16",[st.q2f16]:"_q2f16",[st.q1f16]:"_q1f16",[st.bnb4]:"_bnb4"});function Lc(t,e,r,{configDtype:s=null,warn:n}={}){let o,a=!1;t&&typeof t!="string"?t.hasOwnProperty(e)?o=t[e]:(o=null,a=!0):o=t;let i;if(o===st.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==st.auto&&st.hasOwnProperty(l))return l}i=W2[r]??q2}else o&&st.hasOwnProperty(o)?i=o:i=W2[r]??q2;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var Gr=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var N=class t{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return Pc(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new j2(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}indexOf(e){let r=this.data;for(let s=0;sm)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(_,0),Math.min(m,this.dims[p])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([p,f])=>f-p),o=n.reduce((p,f)=>p*f),a=this.data,i=new a.constructor(o),l=this.stride(),c=!0;for(let p=1;p=0;--_){let w=n[_];f+=(m%w+s[_][0])*l[_],m=Math.floor(m/w)}i[p]=a[f]}return new t(this.type,i,r)}permute(...e){return NL(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let a,i;if(o?(a=(f,_)=>f+_,i=0n):(a=(f,_)=>f+_**e,i=0),r===null){let f=n.reduce(a,i);return e!==1&&(f=f**(1/e)),new t(this.type,[f],[])}let[l,c,p]=Io(a,this,r,s);if(e!==1)for(let f=0;f=0;--l){let f=this.dims[l];if(l!==r){let _=c%f;i+=_*p,p*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return Ld(this.dims)}squeeze(e=null){return new t(this.type,this.data,H2(this.dims,e))}squeeze_(e=null){return this.dims=H2(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,X2(this.dims,e))}unsqueeze_(e){return this.dims=X2(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...s,n.reduce((a,i)=>a*i,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;ni!==r?o*a:o,1);e[r]=s.length/n}return new t(this.type,s,e)}neg_(){let e=this.data;for(let r=0;re?1:0;return new t("bool",r,this.dims)}lt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;nMath.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=Pe(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Io((a,i)=>Math.max(a,i),this,e,r,-1/0);return new t(s,n,o)}argmin(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=yo(this.data)[1];return new t("int64",[BigInt(s)],[])}argmax(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Pe(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.lengthp===1)){if(e.length===this.dims.length)return this.clone();let p=e.length-this.dims.length,f=Array(p).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((p,f)=>p*e[f]),o=n.reduce((p,f)=>p*f,1),a=this.data,i=new a.constructor(o),l=Ld(s),c=Ld(n);for(let p=0;pBigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,dA(this.data),this.dims);return new t(e,Gr[e].from(this.data,r),this.dims)}};function LL(t,e){let r=t.length,s=e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.lengthnew N("int64",t,[t.length]);async function $c(t,e,r,s,n){return await(await lr.slice)({x:t,s:Nc(e),e:Nc(r),a:Nc(s),t:Nc(n??new Array(s.length).fill(1))})}function Y2(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let p=0;pr!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function X2(t,e){return e=cr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function cr(t,e,r=null,s=!0){if(t<-e||t>=e){if(s)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function ve(t,e=0){e=cr(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i=0;--_){let x=c[_],k=m%x;_===e&&(k+=a),f+=k*w,w*=r[_],m=Math.floor(m/x)}n[f]=l[p]}a+=c[e]}}return new N(o,n,r)}function xt(t,e=0){return ve(t.map(r=>r.unsqueeze(e)),e)}function Io(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=cr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let c=0;c=0;--f){let w=a[f];if(f!==r){let x=_%w;p+=x*m,m*=i[f]}_=Math.floor(_/w)}l[p]=t(l[p],o[c],c,p)}return s||i.splice(r,1),[e.type,l,i]}function $d(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let m=n.reduce((A,E)=>A+E,0)/n.length,w=Math.sqrt(n.reduce((A,E)=>A+(E-m)**2,0)/(n.length-r)),x=new N(t.type,[m],[]);return[new N(t.type,[w],[]),x]}e=cr(e,o.length);let a=Rc(t,e,s),i=a.data,[l,c,p]=Io((_,m,w,x)=>_+(m-i[x])**2,t,e,s);for(let _=0;_c+p,0);return new N(t.type,[l/n.length],[])}e=cr(e,s.length);let[o,a,i]=Io((l,c)=>l+c,t,e,r);if(s[e]!==1)for(let l=0;l=0;--r)e[r]=s,s*=t[r];return e}function Rd(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new N(r,new s(n).fill(e),t)}function Qe(t,e){let r,s;if(typeof e=="number")r="float32",s=Float32Array;else if(typeof e=="bigint")r="int64",s=BigInt64Array;else if(typeof e=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return Rd(t,e,r,s)}function Co(t,e){return Qe(t.dims,e)}function et(t){return Rd(t,1n,"int64",BigInt64Array)}function Dc(t){return et(t.dims)}function Dd(t){return Rd(t,0n,"int64",BigInt64Array)}function Fd(t){return Dd(t.dims)}function L4(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>hs.random()),t)}function Q2(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>hs.gauss()),t)}function J2(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i0?1:0,c=Math.floor(i/8),p=i%8;a[c]|=l<<7-p,r&&p===0&&(a[c]-=128)}return new N(s,a,[t.dims[0],t.dims[1]/8])}async function _n(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await Ot(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Bd(t,e){let r=await _n(t);return await Promise.all(r.map(s=>nt(t,s,!0,e)))}function Po(t){let e=t.dims;switch(e.length){case 1:return t.tolist();case 2:if(e[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return t.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${e.length}.`)}}var $L=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function RL(t,e,r,s){for(let n of Object.keys(t)){let o=e-t[n].length,a=r(n),i=new Array(o).fill(a);t[n]=s==="right"?gt(t[n],i):gt(i,t[n])}}function DL(t,e){for(let r of Object.keys(t))t[r].length=e}function Ts(t,...e){for(let r of e){if(!Object.hasOwn(t,r))continue;let s=t[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function FL(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var W=class extends We{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new $E(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Ts(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ts(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ts(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ts(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ts(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ts(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:a}of this.chat_template){if(typeof o!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=a}this.chat_template=n}this._compiled_template_cache=new Map;let s=FL(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let i=await Bd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,r={}){let{text_pair:s=null,add_special_tokens:n=!0,padding:o=!1,return_token_type_ids:a=null}=r,{truncation:i=null,max_length:l=null}=r,c=r.return_tensor??!0,p=Array.isArray(e),f;if(p){if(e.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(e.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");f=e.map((m,w)=>this._encode_plus(m,{text_pair:s[w],add_special_tokens:n,return_token_type_ids:a}))}else f=e.map(m=>this._encode_plus(m,{add_special_tokens:n,return_token_type_ids:a}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(s))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");f=[this._encode_plus(e,{text_pair:s,add_special_tokens:n,return_token_type_ids:a})]}if(l===null?l=this.model_max_length:i===null&&(o===!0?(ee.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):o===!1&&(ee.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),i=!0)),o===!0&&(l=Math.min(Pe(f.map(m=>m.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),o||i)for(let m=0;ml?i&&DL(f[m],l):o&&RL(f[m],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));let _={};if(c){if(!(o&&i)&&f.some(w=>{for(let x of Object.keys(w))if(w[x].length!==f[0][x]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let m=[f.length,f[0].input_ids.length];for(let w of Object.keys(f[0]))_[w]=new N("int64",BigInt64Array.from(f.flatMap(x=>x[w]).map(BigInt)),m)}else{for(let m of Object.keys(f[0]))_[m]=f.map(w=>w[m]);if(!p)for(let m of Object.keys(_))_[m]=_[m][0]}return _}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof N&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof N&&(e=Po(e)),!Array.isArray(e)||e.length===0||!wE(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,r={}){let{tools:s=null,documents:n=null,chat_template:o=null,add_generation_prompt:a=!1,tokenize:i=!0,padding:l=!1,truncation:c=!1,max_length:p=null,return_tensor:f=!0,return_dict:_=!0,tokenizer_kwargs:m={},...w}=r;if(o=this.get_chat_template({chat_template:o,tools:s}),typeof o!="string")throw Error(`chat_template must be a string, but got ${typeof o}`);let x=this._compiled_template_cache.get(o);x===void 0&&(x=new XE(o),this._compiled_template_cache.set(o,x));let k=Object.create(null);for(let E of $L){let S=Ts(this.config,E);S&&(k[E]=S)}let A=x.render({messages:e,add_generation_prompt:a,tools:s,documents:n,...k,...w});if(i){let E=this._call(A,{add_special_tokens:!1,padding:l,truncation:c,max_length:p,return_tensor:f,...m});return _?E:E.input_ids}return A}};function mn(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var P_={};en(P_,{AlbertTokenizer:()=>Ud,AutoTokenizer:()=>ne,BartTokenizer:()=>jd,BertTokenizer:()=>Gd,BlenderbotSmallTokenizer:()=>qd,BlenderbotTokenizer:()=>Wd,BloomTokenizer:()=>Vd,CLIPTokenizer:()=>Xd,CamembertTokenizer:()=>Hd,CodeGenTokenizer:()=>Yd,CodeLlamaTokenizer:()=>Kd,CohereAsrTokenizer:()=>Jd,CohereTokenizer:()=>Qd,ConvBertTokenizer:()=>Zd,DebertaTokenizer:()=>t_,DebertaV2Tokenizer:()=>e_,DistilBertTokenizer:()=>r_,ElectraTokenizer:()=>s_,EsmTokenizer:()=>n_,FalconTokenizer:()=>o_,GPT2Tokenizer:()=>l_,GPTNeoXTokenizer:()=>i_,GemmaTokenizer:()=>a_,HerbertTokenizer:()=>c_,LlamaTokenizer:()=>u_,M2M100Tokenizer:()=>p_,MBart50Tokenizer:()=>d_,MBartTokenizer:()=>zo,MPNetTokenizer:()=>h_,MarianTokenizer:()=>f_,MgpstrTokenizer:()=>__,MobileBertTokenizer:()=>m_,NllbTokenizer:()=>g_,NougatTokenizer:()=>w_,PreTrainedTokenizer:()=>W,Qwen2Tokenizer:()=>x_,RoFormerTokenizer:()=>b_,RobertaTokenizer:()=>y_,SiglipTokenizer:()=>v_,SpeechT5Tokenizer:()=>k_,SqueezeBertTokenizer:()=>E_,T5Tokenizer:()=>A_,TokenizersBackend:()=>W,VitsTokenizer:()=>T_,Wav2Vec2CTCTokenizer:()=>S_,WhisperTokenizer:()=>O_,XLMRobertaTokenizer:()=>I_,XLMTokenizer:()=>C_});var Ud=class extends W{return_token_type_ids=!0};var jd=class extends W{};var Gd=class extends W{return_token_type_ids=!0};var qd=class extends W{};var Wd=class extends W{};var Vd=class extends W{};var Hd=class extends W{};var Xd=class extends W{};var Kd=class extends W{};var Yd=class extends W{};var Qd=class extends W{};var Jd=class extends W{};var Zd=class extends W{return_token_type_ids=!0};var e_=class extends W{return_token_type_ids=!0};var t_=class extends W{return_token_type_ids=!0};var r_=class extends W{};var s_=class extends W{return_token_type_ids=!0};var n_=class extends W{};var o_=class extends W{};var a_=class extends W{};var i_=class extends W{};var l_=class extends W{};var c_=class extends W{return_token_type_ids=!0};var u_=class extends W{padding_side="left"};var p_=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return mn(this,e,r,s)}};var f_=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),ee.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[r,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(r);if(s.length===2){let[n,o]=s;return this.supported_language_codes.includes(n)||ee.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),gt([n],super._encode_text(o))}}};var zo=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return mn(this,e,r,s)}};var d_=class extends zo{};var __=class extends W{};var m_=class extends W{return_token_type_ids=!0};var h_=class extends W{};var g_=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return mn(this,e,r,s)}};var w_=class extends W{};var x_=class extends W{};var y_=class extends W{};var b_=class extends W{return_token_type_ids=!0};var v_=class extends W{};var k_=class extends W{};var E_=class extends W{return_token_type_ids=!0};var A_=class extends W{};var M_=class extends Dt{decode_chain(e){let r="";for(let s=1;s[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function eM(t){t=t.toLowerCase();let e=BL.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),Lo.has(t))e=t;else{let n=t.length===2?Lo.keys():Lo.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var UL="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",tM=new RegExp(`^[${UL}]+$`,"gu"),jL=.1,O_=class extends W{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],p=l(),f=0,_=this.timestamp_begin,w=_+1500,x=[],k=[],A=!1,E=null,S=new Set(this.all_special_ids);for(let O of e){let b=O.tokens,F=i?O.token_timestamps:null,j=null,U=_;if("stride"in O){let[J,R,C]=O.stride;if(f-=R,E=J-C,R&&(U=R/n+_),C)for(let se=b.length-1;se>=0;--se){let Y=Number(b[se]);if(Y>=_){if(j!==null&&(Y-_)*n=_&&R<=w){let C=(R-_)*n+f,se=gs(C,2);if(j!==null&&R>=j)A=!0;else if(A||x.length>0&&R0&&p.timestamp[1]!==null))for(let B of p.words)B.timestamp[1]>p.timestamp[1]&&p.timestamp[1]>=B.timestamp[0]&&(B.timestamp[1]=p.timestamp[1]);c.push(p),x=[],X=[],k=[],K=[],p=l()}}else if(X.push(R),i){let C=gs(F[J]+f,2),se;if(J+10?(x.push(X),i&&k.push(K)):x.every(J=>J.length===0)&&(p=l(),x=[],X=[],k=[],K=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[O,b]=this.findLongestCommonSequence(x,k),F=this.decode(O);p.text=F,i&&(p.words=this.collateWordTimestamps(O,b,a)),c.push(p)}let T=Object.create(null),I=c.map(O=>O.text).join("");if(r||s){for(let O=0;O0,i=a?[]:null,l=a?r[0]:null;for(let c=1;cR===U[C]&&l[I+C][0]-jL<=r[c][F+C][0]).length:X=b.filter((R,C)=>R===U[C]).length;let K=T/1e4,J=X/T+K;X>1&&J>f&&(f=J,_=[I,O,F,j])}let[w,x,k,A]=_,E=Math.floor((x+w)/2),S=Math.floor((A+k)/2);if(a&&f===0&&n>0){let T=l[n-1][0],I=r[c].findIndex(O=>O[0]>=T);S=I===-1?p.length:I}o.push(...s.slice(0,E)),s=p.slice(S),n=s.length,a&&(i.push(...l.slice(0,E)),l=r[c].slice(S))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],c=0;for(let p=0;p=this._tokenizer.token_to_id("<|endoftext|>"),m=c.startsWith(" "),w=c.trim(),x=tM.test(w);if(_||m||x||o.length===0)o.push(c),a.push(p),i.push(f);else{let k=o.length-1;o[k]+=c,a[k].push(...p),i[k].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,p=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[p]=a[c]+a[p],i[p]=gt(i[c],i[p]),l[p]=gt(l[c],l[p]),a[c]="",i[c]=[],l[c]=[]):p=c,--c;for(c=0,p=1;pf),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var I_=class extends W{};var C_=class extends W{return_token_type_ids=!0;constructor(e,r){super(e,r),ee.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var ne=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await Bd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=P_[c];return p||(ee.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=W),new p(i,l)}};var qr="https://github.com/huggingface/transformers.js/issues/new/choose";var No="preprocessor_config.json",yr=No,Fc="processor_config.json",Bc="chat_template.jinja";var re=class extends We{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?nt(e,Fc,!0,r):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{let i=await this[a].from_pretrained(e,r);return[a.replace(/_class$/,""),i]})).then(Object.fromEntries),this.uses_chat_template_file?xo(e,Bc,!0,r):null]);return new this(s,n,o)}};var pu={};en(pu,{ChatterboxProcessor:()=>X_,CohereAsrProcessor:()=>K_,Florence2Processor:()=>jm,Gemma3Processor:()=>Gm,Gemma3nProcessor:()=>qm,Gemma4Processor:()=>Wm,Glm46VProcessor:()=>Vm,GraniteSpeechProcessor:()=>Hm,GroundingDinoProcessor:()=>Xm,Idefics3Processor:()=>iu,JinaCLIPProcessor:()=>Ym,Lfm2VlProcessor:()=>Qm,LlavaProcessor:()=>Jm,MgpstrProcessor:()=>Zm,MoonshineProcessor:()=>eh,OwlViTProcessor:()=>th,PaliGemmaProcessor:()=>rh,Phi3VProcessor:()=>sh,PixtralProcessor:()=>nh,Processor:()=>re,PyAnnoteProcessor:()=>oh,Qwen2VLProcessor:()=>Os,Qwen2_5_VLProcessor:()=>Ho,Qwen3VLProcessor:()=>ah,Sam2Processor:()=>lu,Sam2VideoProcessor:()=>ih,SamProcessor:()=>Xo,SmolVLMProcessor:()=>iu,SpeechT5Processor:()=>lh,UltravoxProcessor:()=>ch,VLChatProcessor:()=>Km,VoxtralProcessor:()=>uh,VoxtralRealtimeProcessor:()=>fh,Wav2Vec2Processor:()=>dh,Wav2Vec2ProcessorWithLM:()=>_h,WhisperProcessor:()=>mh});var Ee=class extends We{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await nt(e,No,!0,r);return new this(s)}};function Ae(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var Go={};en(Go,{ASTFeatureExtractor:()=>N_,ChatterboxFeatureExtractor:()=>$_,ClapFeatureExtractor:()=>R_,CohereAsrFeatureExtractor:()=>D_,DacFeatureExtractor:()=>Fo,EncodecFeatureExtractor:()=>Ro,FeatureExtractor:()=>Ee,Gemma3nAudioFeatureExtractor:()=>Bo,Gemma4AudioFeatureExtractor:()=>Uo,GraniteSpeechFeatureExtractor:()=>F_,MoonshineFeatureExtractor:()=>B_,ParakeetFeatureExtractor:()=>Do,PyAnnoteFeatureExtractor:()=>jo,SeamlessM4TFeatureExtractor:()=>U_,SnacFeatureExtractor:()=>j_,SpeechT5FeatureExtractor:()=>G_,VoxtralRealtimeFeatureExtractor:()=>V_,Wav2Vec2FeatureExtractor:()=>q_,WeSpeakerFeatureExtractor:()=>W_,WhisperFeatureExtractor:()=>H_});import GL from"fs";import{Readable as qL}from"stream";import{pipeline as WL}from"stream/promises";async function Uc(t,e){if(ie.IS_BROWSER_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(ie.IS_FS_AVAILABLE){let r=e.stream(),s=qL.fromWeb(r),n=GL.createWriteStream(t);await WL(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function nM(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await Pr(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&ee.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let c=0;c2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function z_(t,e="htk"){let r=HL[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}var XL={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,r=15,s=Math.log(6.4)/27)=>t>=r?e*Math.exp(s*(t-r)):200*t/3};function KL(t,e="htk"){let r=XL[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}function YL(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;anew Array(t.length));for(let a=0;at+s*o)}function lt(t,e,r,s,n,o=null,a="htk",i=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);let l=z_(r,a),c=z_(s,a),p=sM(l,c,e+2),f=KL(p,a),_;if(i){let w=n/((t-1)*2);_=z_(Float64Array.from({length:t},(x,k)=>k*w),a),f=p}else _=sM(0,Math.floor(n/2),t);let m=YL(_,f);if(o!==null&&o==="slaney")for(let w=0;wn)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(j!==r)throw new Error(`Length of the window (${j}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!p)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a){let Q=Math.floor(r/2);switch(i){case"reflect":{t=QL(t,Q,Q);break}case"constant":{let le=new t.constructor(t.length+2*Q);le.set(t,Q),t=le;break}case"semicausal":{let le=new t.constructor(t.length+Q);le.set(t,Q),t=le;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let U=Math.floor(1+Math.floor((t.length-r)/s));S!==null&&UU?I&&(J=T):J=K=T);let R=new gc(n),C=new Float64Array(n),se=new Float64Array(R.outputBufferSize),Y=new Float32Array(X*J);for(let Q=0;Q=1;--ce)C[ce]-=c*C[ce-1];C[0]*=1-c}for(let ce=0;ceMath.pow(c,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null||t===s)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);let i=new Float64Array(s),l=n?Math.floor((s-t)/2):0;return i.set(a,l),i}function eN(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return jc(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),jc(n,8,"WAVE"),jc(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,e,!0),n.setUint32(28,e*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),jc(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function jc(t,e,r){for(let s=0;sn+o.length,0),r=new Float32Array(e),s=0;for(let n of this.audio)r.set(n,s),s+=n.length;return r}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),eN(e,this.sampling_rate)}async save(e){return Uc(e,this.toBlob())}};var N_=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){Ae(e,"ASTFeatureExtractor");let r=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let s=this.std*2,n=r.data;for(let o=0;o0)if(s==="rand_trunc"){a=!0;let l=Math.floor(hs.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let c=e.length;c=1;--n)e[n]-=r*e[n-1];return await ot(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){Ae(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f1?s-1:1;for(let f=0;f=p){l.push(e.slice(c,p));break}let f=Math.max(c,c+a-i),_=Math.min(c+a,p),m;_<=f?m=c+a:m=this._find_split_point_energy(e,f,_,n),m=Math.max(c+1,Math.min(m,p)),l.push(e.slice(c,m)),c=m}return l}_find_split_point_energy(e,r,s,n){let o=s-r;if(o<=n)return Math.floor((r+s)/2);let a=1/0,i=r,l=o-n;for(let c=0;c<=l;c+=n){let p=0;for(let f=0;fr&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let a=await this._extract_fbank_features(e,this.config.max_length),i=Qe([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var Uo=class extends Bo{async _extract_fbank_features(e,r){let{frame_length:s,hop_length:n,fft_length:o}=this.config,a=Math.floor(s/2),i=Math.floor((e.length+a-(s+1))/n)+1;return ot(e,this.window,s,n,{fft_length:o,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:i})}async _call(e,r={}){Ae(e,"Gemma4AudioFeatureExtractor");let s=e.length,n=await super._call(e,r),{input_features:o}=n,[,a,i]=o.dims,{frame_length:l,hop_length:c}=this.config,p=Math.floor(l/2),f=l+1,_=new Uint8Array(s+p+(r.pad_to_multiple_of??128));_.fill(1,p,p+s);let m=new Uint8Array(a);for(let x=0;x({id:l,start:c*s,end:p*s,confidence:f/(p-c)})))}return n}};var U_=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){Ae(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,k=a.data;for(let A=0;A0){let E=new Float32Array(x*(w+A));E.set(k),E.fill(this.config.padding_value,k.length);let S=w+A;a=new N(a.type,E,[S,x]),o&&(i=new N("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,p=this.config.stride;if(l%p!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${p}).`);let _=a.view(1,Math.floor(l/p),c*p),m={input_features:_};if(o){let w=_.dims[1],x=new BigInt64Array(w);if(i){let k=i.data;for(let A=1,E=0;Ao+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){Ae(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));let s=[1,r.length];return{input_values:new N("float32",r,s),attention_mask:new N("int64",new BigInt64Array(r.length).fill(1n),s)}}};var W_=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){Ae(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;ln?(e.length>this.config.n_samples&&ee.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var je=class{static async from_pretrained(e,r={}){let s=await nt(e,No,!0,r),n=s.feature_extractor_type,o=Go[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${qr}.`);return new o(s)}};var X_=class extends re{static tokenizer_class=ne;static feature_extractor_class=je;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var rN=new Set(["ja","zh"]),K_=class extends re{static tokenizer_class=ne;static feature_extractor_class=je;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let r=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(r)}static join_chunks(e,r="en"){let s=e.filter(a=>a&&a.trim());if(s.length===0)return"";let n=rN.has(r)?"":" ";return[s[0].trimEnd(),...s.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}};import Y_ from"sharp";var Ss,iM,Wr;if(ie.IS_WEB_ENV)Ss=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},Wr=self.createImageBitmap,iM=self.ImageData;else if(Y_)Wr=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Je(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&o.convert(r),o};else throw new Error("Unable to load image processing library.");var sN={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},nN=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Je=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!ie.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let s=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(s,e.width,e.height,4)}static async fromURL(e){let r=await Pr(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(e){if(ie.IS_WEB_ENV){let r=await Wr(e),s=Ss(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=Y_(await e.arrayBuffer());return await Wr(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r=0?l=s:p=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,p,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await Wr(o)}}async toBlob(e="image/png",r=1){if(!ie.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new N("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!ie.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=Ss(e.width,e.height),s=new iM(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;lnew t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(ie.IS_WEB_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=nN.get(r)??"image/png",n=await this.toBlob(s);return Uc(e,n)}else if(ie.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(ie.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return Y_(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},oN=Je.read.bind(Je);function lM(t,e,r=0,s=null){let n=t/e,o=pA(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),oe&&A.push(S)}else{let S=Pe(k.data)[1];if(S===l-1||(E=$e(k.data),E[S]I*f[(O+1)%2])),_.boxes.push(T),_.classes.push(S),_.scores.push(E[S])}}c.push(_)}return c}function Gc(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;of[A]&&(f[A]=k[A],_[A]=x)}let m=new Array(i.dims[0]);for(let x=0;x<_.length;++x){let k=_[x];m[k]=k}let w=m.filter(x=>x!==void 0);n.push({segmentation:p,labels:w})}return n}function aN(t,e,r,s){let n=[],o=[],a=[];for(let i=0;ir&&(n.push(c),o.push(_),a.push(p))}return[n,o,a]}function iN(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let p=0;p=s&&++i;let c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function lN(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new N("int32",new Int32Array(i*l),[i,l]),p=[];if(a!==null)for(let x=0;x_[E]&&(f[E]=x,_[E]=A[E])}let m=0,w=c.data;for(let x=0;x200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let a=Math.round(t/r)*r,i=Math.round(e/r)*r;if(o*a*i>n){let l=Math.sqrt(o*t*e/n);a=Math.max(r,Math.floor(t/l/r)*r),i=Math.max(r,Math.floor(e/l/r)*r)}else if(o*a*io?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=yo(s.data)[0],a=Pe(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=s.height,p=0,f=0,_=s.data;for(let m=0;mthis.preprocess(o)));return{pixel_values:xt(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await nt(e,yr,!0,r);return new this(s)}};var bn={};en(bn,{BeitFeatureExtractor:()=>J_,BitImageProcessor:()=>Z_,CHMv2ImageProcessor:()=>tm,CLIPFeatureExtractor:()=>rm,CLIPImageProcessor:()=>Vc,ChineseCLIPFeatureExtractor:()=>em,ConvNextFeatureExtractor:()=>sm,ConvNextImageProcessor:()=>Hc,DINOv3ViTImageProcessor:()=>am,DPTFeatureExtractor:()=>lm,DPTImageProcessor:()=>Yc,DeiTFeatureExtractor:()=>nm,DeiTImageProcessor:()=>Xc,DetrFeatureExtractor:()=>om,DetrImageProcessor:()=>Kc,DonutFeatureExtractor:()=>im,DonutImageProcessor:()=>gn,EfficientNetImageProcessor:()=>cm,GLPNFeatureExtractor:()=>fm,Gemma3ImageProcessor:()=>um,Gemma4ImageProcessor:()=>qo,Glm46VImageProcessor:()=>pm,GroundingDinoImageProcessor:()=>dm,Idefics3ImageProcessor:()=>Qc,ImageFeatureExtractor:()=>H,ImageProcessor:()=>H,JinaCLIPImageProcessor:()=>mm,Lfm2VlImageProcessor:()=>hm,LlavaOnevisionImageProcessor:()=>gm,Mask2FormerImageProcessor:()=>xm,MaskFormerFeatureExtractor:()=>wm,MaskFormerImageProcessor:()=>wn,MobileNetV1FeatureExtractor:()=>ym,MobileNetV1ImageProcessor:()=>Jc,MobileNetV2FeatureExtractor:()=>bm,MobileNetV2ImageProcessor:()=>Zc,MobileNetV3FeatureExtractor:()=>vm,MobileNetV3ImageProcessor:()=>eu,MobileNetV4FeatureExtractor:()=>km,MobileNetV4ImageProcessor:()=>tu,MobileViTFeatureExtractor:()=>Em,MobileViTImageProcessor:()=>ru,NougatImageProcessor:()=>Am,OwlViTFeatureExtractor:()=>Mm,OwlViTImageProcessor:()=>xn,Owlv2ImageProcessor:()=>Tm,Phi3VImageProcessor:()=>Im,PixtralImageProcessor:()=>Cm,PvtImageProcessor:()=>Pm,Qwen2VLImageProcessor:()=>Wo,RTDetrImageProcessor:()=>zm,Sam2ImageProcessor:()=>Vo,Sam3ImageProcessor:()=>Vo,SamImageProcessor:()=>Vo,SapiensFeatureExtractor:()=>Lm,SapiensImageProcessor:()=>su,SegformerFeatureExtractor:()=>Nm,SegformerImageProcessor:()=>nu,SiglipImageProcessor:()=>$m,SmolVLMImageProcessor:()=>Qc,Swin2SRImageProcessor:()=>Rm,VLMImageProcessor:()=>_m,ViTFeatureExtractor:()=>Dm,ViTImageProcessor:()=>ou,VitMatteImageProcessor:()=>Fm,VitPoseImageProcessor:()=>Bm,YolosFeatureExtractor:()=>Um,YolosImageProcessor:()=>au});var J_=class extends H{};var Z_=class extends H{};var em=class extends H{};var tm=class extends H{};var Vc=class extends H{},rm=class extends Vc{};var Hc=class extends H{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){let s=Math.floor(r/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}},sm=class extends Hc{};var Xc=class extends H{},nm=class extends Xc{};var Kc=class extends H{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Qe(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Vr(...e)}post_process_panoptic_segmentation(...e){return qc(...e)}post_process_instance_segmentation(...e){return Wc(...e)}},om=class extends Kc{};var am=class extends H{};var gn=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let p=l.map((f,_)=>-f/c[_]);return super.pad_image(e,r,s,{center:!0,constant_values:p,...n})}},im=class extends gn{};var Yc=class extends H{},lm=class extends Yc{};var cm=class extends H{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}};var um=class extends H{};function cN(t,e,r,s,n){let o=s*r**2,a=Math.sqrt(o/(t*e)),i=n*r,l=Math.floor(a*t/i)*i,c=Math.floor(a*e/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);let p=Math.floor(s/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(e/t)*i,p)):c===0&&(c=i,l=Math.min(Math.floor(t/e)*i,p)),[l,c]}function uN(t,e,r,s,n,o,a){let i=Math.floor(e/n),l=Math.floor(r/n),c=i*l,p=n*n*s,f=new Float32Array(o*p),_=0;for(let x=0;xa),0));let p=a.dims[0]/i,f=a.dims[1],_=Math.floor(a.dims[2]/c),m=Math.floor(a.dims[3]/c),w=a.view(p,i,f,Math.floor(_/l),l,c,Math.floor(m/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(p*_*m,f*i*c*c),x=new N("int64",[p,_,m],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var pm=class extends Wo{get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return hn(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}};var fm=class extends H{};var dm=class extends H{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=et([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var Qc=class extends H{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],c=[];for(let A of n){let E=await Promise.all(A.map(I=>this.preprocess(I)));l.push(...E.map(I=>I.original_size)),c.push(...E.map(I=>I.reshaped_input_size)),E.forEach(I=>I.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,T;if(r??this.do_image_splitting){let I=new Array(E.length),O=new Array(E.length);T=await Promise.all(E.map(async(b,F)=>{let j=this.get_resize_for_vision_encoder(b.pixel_values,S),U=await bt(b.pixel_values,{size:[j.height,j.width]}),{frames:X,num_splits_h:K,num_splits_w:J}=await this.split_image(U,this.max_image_size);return I[F]=K,O[F]=J,ve(X,0)})),a.push(I),i.push(O)}else{let I=[S,S];T=await Promise.all(E.map(O=>bt(O.pixel_values,{size:I}))),a.push(new Array(E.length).fill(0)),i.push(new Array(E.length).fill(0))}o.push(ve(T,0))}let p=o.length,[f,_,m,w]=o[0].dims,x,k;if(p===1)x=o[0].unsqueeze_(0),k=Qe([p,f,m,w],!0);else{let A=Math.max(...o.map(T=>T.dims.at(0)));k=Qe([p,A,m,w],!0);let E=k.data,S=A*m*w;for(let T=0;Ts||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let p=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;wr*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var mm=class extends H{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function uM(t,e){return Math.round(t/e)*e}function pN(t,e,r,s,n){let o=1/0,a=[1,1],i=r*s;for(let l of e){let c=Math.abs(t-l[0]/l[1]);c.5*n*n*l[0]*l[1]&&(a=l)}return a}function fN(t,e){let r=[],s=new Set;for(let n=t;n<=e;++n)for(let o=1;o<=n;++o)for(let a=1;a<=n;++a){let i=o*a;if(i>=t&&i<=e){let l=o<<16|a;s.has(l)||(s.add(l),r.push([o,a]))}}return r.sort((n,o)=>n[0]*n[1]-o[0]*o[1])}function dN(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,p=new Float32Array(r*a*i*l),f=n*o;for(let _=0;_this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=fN(this.min_tiles,this.max_tiles),[n,o]=pN(r/e,s,r,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:r=null}={}){let s;Array.isArray(e)?Array.isArray(e[0])?s=e:s=[e]:s=[[e]];let n=[],o=[],a=[],i=[],l=[],c=[];for(let f of s){let _=await Promise.all(f.map(m=>this.preprocess(m,{do_pad:!1})));for(let{pixel_values:m}of _){let[,w,x]=m.dims,k=m.unsqueeze_(0),A=this.encoder_patch_size*this.downsample_factor,E=A**2,[S,T]=hn(Math.max(A,w),Math.max(A,x),A,this.min_image_tokens*E,this.max_image_tokens*E).map(U=>Math.max(A,U)),I,O=1,b=1,F=this._is_image_too_large(w,x),j=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(F&&j){let{grid_width:U,grid_height:X,target_width:K,target_height:J}=this._get_grid_layout(w,x);O=X,b=U;let R=await bt(k,{size:[J,K]});I=[];for(let C=0;C(p-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||Om(r)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(_=>this.preprocess(_))),o=n.map(_=>_.original_size),a=n.map(_=>_.reshaped_input_size),i=[];for(let{pixel_values:_}of n){_.unsqueeze_(0);let[m,w]=_.dims.slice(-2),x=await bt(_,{size:[Nt,Nt],mode:"bicubic"});if(r>0){let k=[],A=Om(r),E=yn(w/A),S=yn(m/A);for(let I=0;I_.map(m=>Nt*Sm(m/Nt))),p=new N("int64",c.flat(),[s,2]),f=c.map(([_,m])=>this.calc_num_image_tokens_from_image_size(m,_));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:p,num_img_tokens:f}}};var Cm=class extends H{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");let f=c*p,_=Math.floor((i-1)/f)+1,m=Math.floor((l-1)/f)+1;return[_*f,m*f]}};var Pm=class extends H{};var zm=class extends H{post_process_object_detection(...e){return Vr(...e)}};var Vo=class extends H{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=Cf(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;an!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new N("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let c=0;cn&&(w[x]=1);_=new N("bool",w,_.dims)}i.push(_)}return i}generate_crop_boxes(e,r,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:a=1}={}){}};var su=class extends H{post_process_semantic_segmentation(...e){return Gc(...e)}},Lm=class extends su{};var nu=class extends H{post_process_semantic_segmentation(...e){return Gc(...e)}},Nm=class extends nu{};var $m=class extends H{};var Rm=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r;return super.pad_image(e,r,{width:a+(s-a%s)%s,height:o+(s-o%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var ou=class extends H{},Dm=class extends ou{};var Fm=class extends H{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let s=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(r.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:xt(s.map((a,i)=>ve([a.pixel_values,n[i].pixel_values],0)),0),original_sizes:s.map(a=>a.original_size),reshaped_input_sizes:s.map(a=>a.reshaped_input_size)}}};var Bm=class extends H{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let p=0;p/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],c=[];for(let[p,f,..._]of i)l.push(f?f.trim():l.at(-1)??""),c.push(_.map((m,w)=>(Number(m)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:c};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var Gm=class extends re{static tokenizer_class=ne;static image_processor_class=Me;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:o,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=o,this.eoi_token=a;let i=o.repeat(this.image_seq_length);this.full_image_sequence=` + + ${n}${i}${a} + +diff --git a/node_modules/@huggingface/transformers/dist/transformers.node.mjs b/node_modules/@huggingface/transformers/dist/transformers.node.mjs +index bacb354..e4cb585 100644 +--- a/node_modules/@huggingface/transformers/dist/transformers.node.mjs ++++ b/node_modules/@huggingface/transformers/dist/transformers.node.mjs +@@ -44,7 +44,7 @@ var isSafari = () => { + if (typeof navigator === "undefined") { + return false; + } +- const userAgent = navigator.userAgent; ++ const userAgent = navigator.userAgent || ""; + const vendor = navigator.vendor || ""; + const isAppleVendor = vendor.indexOf("Apple") > -1; + const notOtherBrowser = !userAgent.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i) && !userAgent.includes("Chrome") && !userAgent.includes("Android"); +@@ -86,7 +86,7 @@ var apis = Object.freeze({ + var RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE; + var dirname__ = "./"; + if (RUNNING_LOCALLY) { +- const _import_meta_url = Object(import.meta).url; ++ const _import_meta_url = Object(import_meta).url; + if (_import_meta_url) { + dirname__ = path.dirname(path.dirname(url.fileURLToPath(_import_meta_url))); + } else if (typeof __dirname !== "undefined") { +@@ -6036,8 +6036,8 @@ function toAbsoluteURL(url2) { + let baseURL; + if (typeof location !== "undefined" && location.href) { + baseURL = location.href; +- } else if (typeof import.meta !== "undefined" && import.meta.url) { +- baseURL = import.meta.url; ++ } else if (typeof import_meta !== "undefined" && import_meta.url) { ++ baseURL = import_meta.url; + } else { + return url2; + } +@@ -8240,7 +8240,7 @@ async function es(a = {}) { + }; + var l, m, y = (e, t) => { + throw t; +- }, w = import.meta.url, T = ""; ++ }, w = import_meta.url, T = ""; + if (s || f) { + try { + T = new URL(".", w).href; +@@ -8329,7 +8329,7 @@ async function es(a = {}) { + r.instantiateWasm(n, (u, c) => { + o(e(u, c)); + }); +- }) : i ? e(new WebAssembly.Instance(v, Ye()), v) : (we ??= r.locateFile ? r.locateFile ? r.locateFile("ort-wasm-simd-threaded.asyncify.wasm", T) : T + "ort-wasm-simd-threaded.asyncify.wasm" : new URL("ort-wasm-simd-threaded.asyncify.wasm", import.meta.url).href, t = await (async function(o) { ++ }) : i ? e(new WebAssembly.Instance(v, Ye()), v) : (we ??= r.locateFile ? r.locateFile ? r.locateFile("ort-wasm-simd-threaded.asyncify.wasm", T) : T + "ort-wasm-simd-threaded.asyncify.wasm" : new URL("ort-wasm-simd-threaded.asyncify.wasm", import_meta.url).href, t = await (async function(o) { + var u = we; + if (!g && !oe(u)) try { + var c = fetch(u, { credentials: "same-origin" }); +@@ -8422,7 +8422,7 @@ async function es(a = {}) { + function gn() { + var e = new Worker((() => { + let t = URL; +- return import.meta.url > "file:" && import.meta.url < "file;" ? new t("ort.webgpu.bundle.min.mjs", import.meta.url) : new URL(import.meta.url); ++ return import_meta.url > "file:" && import_meta.url < "file;" ? new t("ort.webgpu.bundle.min.mjs", import_meta.url) : new URL(import_meta.url); + })(), { type: "module", workerData: "em-pthread", name: "em-pthread" }); + We.push(e); + } +@@ -9954,13 +9954,13 @@ var fs4; + var Yt = k(() => { + "use strict"; + Ht(); +- as = typeof location > "u" ? void 0 : location.origin, tn = import.meta.url > "file:" && import.meta.url < "file;", Zf = () => { ++ as = typeof location > "u" ? void 0 : location.origin, tn = import_meta.url > "file:" && import_meta.url < "file;", Zf = () => { + if (true) { + if (tn) { + let a = URL; +- return new URL(new a("ort.webgpu.bundle.min.mjs", import.meta.url).href, as).href; ++ return new URL(new a("ort.webgpu.bundle.min.mjs", import_meta.url).href, as).href; + } +- return import.meta.url; ++ return import_meta.url; + } + }, ge = Zf(), ss = () => { + if (ge && !ge.startsWith("blob:")) return ge.substring(0, ge.lastIndexOf("/") + 1); +@@ -11265,7 +11265,7 @@ var mn = k(() => { + try { + Ee = f, Ee.onerror = (d) => r(d), Ee.onmessage = wc, ln = [a, r]; + let i = { type: "init-wasm", in: K }; +- !i.in.wasm.wasmPaths && (s || tn) && (i.in.wasm.wasmPaths = { wasm: new URL("ort-wasm-simd-threaded.asyncify.wasm", import.meta.url).href }), Ee.postMessage(i), cr = s; ++ !i.in.wasm.wasmPaths && (s || tn) && (i.in.wasm.wasmPaths = { wasm: new URL("ort-wasm-simd-threaded.asyncify.wasm", import_meta.url).href }), Ee.postMessage(i), cr = s; + } catch (i) { + r(i); + } +diff --git a/node_modules/@huggingface/transformers/dist/transformers.web.js b/node_modules/@huggingface/transformers/dist/transformers.web.js +index bb7b327..805ba0f 100644 +--- a/node_modules/@huggingface/transformers/dist/transformers.web.js ++++ b/node_modules/@huggingface/transformers/dist/transformers.web.js +@@ -44,7 +44,7 @@ var isSafari = () => { + if (typeof navigator === "undefined") { + return false; + } +- const userAgent = navigator.userAgent; ++ const userAgent = navigator.userAgent || ""; + const vendor = navigator.vendor || ""; + const isAppleVendor = vendor.indexOf("Apple") > -1; + const notOtherBrowser = !userAgent.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i) && !userAgent.includes("Chrome") && !userAgent.includes("Android"); +@@ -86,7 +86,7 @@ var apis = Object.freeze({ + var RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE; + var dirname__ = "./"; + if (RUNNING_LOCALLY) { +- const _import_meta_url = Object(import.meta).url; ++ const _import_meta_url = Object(import_meta).url; + if (_import_meta_url) { + dirname__ = node_path_default.dirname(node_path_default.dirname(node_url_default.fileURLToPath(_import_meta_url))); + } else if (typeof __dirname !== "undefined") { +@@ -6031,8 +6031,8 @@ function toAbsoluteURL(url) { + let baseURL; + if (typeof location !== "undefined" && location.href) { + baseURL = location.href; +- } else if (typeof import.meta !== "undefined" && import.meta.url) { +- baseURL = import.meta.url; ++ } else if (typeof import_meta !== "undefined" && "") { ++ baseURL = ""; + } else { + return url; + } +diff --git a/node_modules/@huggingface/transformers/dist/transformers.web.min.js b/node_modules/@huggingface/transformers/dist/transformers.web.min.js +index 4e99aec..b0250ba 100644 +--- a/node_modules/@huggingface/transformers/dist/transformers.web.min.js ++++ b/node_modules/@huggingface/transformers/dist/transformers.web.min.js +@@ -1,4 +1,4 @@ +-var Lk=Object.defineProperty;var Os=(t,e)=>{for(var s in e)Lk(t,s,{get:e[s],enumerable:!0})};var Fe={};var Ye={};var Dy={};var $k="4.2.0",Bc=typeof self<"u",Is=!Wy(Fe),By=!Wy(Ye),ra=Bc&&"caches"in self,Fk=typeof globalThis.Deno<"u",BM=typeof globalThis.Bun<"u",oa=Fk&&ra&&!Is,Uy=typeof process<"u",Gy=Uy&&process?.release?.name==="node"&&!oa,Uc=typeof window<"u"&&typeof window.document<"u",Gc=Bc&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),Rk=Uc||Gc||oa,Dk=Gy||typeof navigator<"u"&&"gpu"in navigator,qk=typeof navigator<"u"&&"ml"in navigator,jk=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",Bk=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",Uk=typeof ServiceWorkerGlobalScope<"u"&&Bc&&self instanceof ServiceWorkerGlobalScope,Gk=()=>{if(typeof navigator>"u")return!1;let t=navigator.userAgent,s=(navigator.vendor||"").indexOf("Apple")>-1,r=!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android");return s&&r},Wk=Gk(),K=Object.freeze({IS_BROWSER_ENV:Uc,IS_WEBWORKER_ENV:Gc,IS_WEB_ENV:Rk,IS_SERVICE_WORKER_ENV:Uk,IS_DENO_WEB_RUNTIME:oa,IS_WEB_CACHE_AVAILABLE:ra,IS_WEBGPU_AVAILABLE:Dk,IS_WEBNN_AVAILABLE:qk,IS_SAFARI:Wk,IS_PROCESS_AVAILABLE:Uy,IS_NODE_ENV:Gy,IS_FS_AVAILABLE:Is,IS_PATH_AVAILABLE:By,IS_CRYPTO_AVAILABLE:jk,IS_CHROME_AVAILABLE:Bk}),Wc=Is&&By,na="./";if(Wc){let t=Object(import.meta).url;t?na=Ye.dirname(Ye.dirname(Dy.fileURLToPath(t))):typeof __dirname<"u"&&(na=Ye.dirname(__dirname))}var Vk=Wc?Ye.join(na,"/.cache/"):null,qy="/models/",Hk=Wc?Ye.join(na,qy):qy,Kk=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Ge=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),jy=Ge.WARNING,J={version:$k,backends:{onnx:{}},get logLevel(){return jy},set logLevel(t){jy=t,J.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Uc||Gc||oa),localModelPath:Hk,useFS:Is,useBrowserCache:ra,useFSCache:Is,cacheDir:Vk,useCustomCache:!1,customCache:null,useWasmCache:ra||Is,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:Kk};function Wy(t){return Object.keys(t).length===0}var xe=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function _t(t,e){t&&t(e)}var ts=class extends xe{constructor(e,s){super(),this.callback=e,this.files_loading=s}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let s=Object.values(this.files_loading).reduce((o,i)=>o+i.loaded,0),r=Object.values(this.files_loading).reduce((o,i)=>o+i.total,0),n=r>0?s/r*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:s,total:r,files:structuredClone(this.files_loading)})}this.callback(e)}};function Vy(t){return Number.isInteger(t)||typeof t=="bigint"}function Vc(t){return t==null||t===-1}function Hc(t){let e=[],s=t;for(;Array.isArray(s);)e.push(s.length),s=s[0];return e}function Re(...t){return Array.prototype.concat.apply([],t)}function Hy(...t){return t.reduce((e,s)=>e.flatMap(r=>s.map(n=>[r,n])))}function zs(t,e){return Math.abs((t+e)%(2*e)-e)}function we(t,e){return Object.assign({},...e.map(s=>{if(t[s]!==void 0)return{[s]:t[s]}}))}function Ky(t,e){let s=0;for(let r of t)r===e&&++s;return s}var F={error(...t){J.logLevel<=Ge.ERROR&&console.error(...t)},warn(...t){J.logLevel<=Ge.WARNING&&console.warn(...t)},info(...t){J.logLevel<=Ge.INFO&&console.log(...t)},debug(...t){J.logLevel<=Ge.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var Xk=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let s of t){let r=e;for(let n=0;nr&&e.push(t.slice(r,n)),e.push(i),n+=i.length,r=n):++n}return r{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),s=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+s),s+=1);let r=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,r[o]]))})(),Jk=t=>Object.fromEntries(Object.entries(t).map(([e,s])=>[s,e])),Zk=Jk(s0),Qy=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",e1=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${Qy}])]+`,` ?[^\\s${Qy}]+`]]),ia="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Xc=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),aa=(t,e=!0)=>{if(t.Regex!==void 0){let s=t.Regex.replace(/\\([#&~])/g,"$1");s=s.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[r,n]of e1)s=s.replaceAll(r,n);try{return new RegExp(s,"gu")}catch(r){if(!(r instanceof SyntaxError)||!r.message.toLowerCase().includes("invalid property name"))throw r;let n=!1,o=s.replace(/(\\[pP])\{([^}=]+)\}/g,(i,a,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${a}{${l}}`}catch{return n=!0,`${a}{Script=${l}}`}});if(!n)throw r;try{return new RegExp(o,"gu")}catch{throw r}}}else if(t.String!==void 0){let s=t1(t.String);return new RegExp(e?s:`(${s})`,"gu")}else return console.warn("Unknown pattern type:",t),null},t1=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s1=(t,e,s)=>{let r=[],n=0;for(;nt>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,n1=t=>Number.isInteger(t)||typeof t=="bigint",o1=t=>{let e=0;for(let s of t)++e;return e},i1=t=>r0(t.toLowerCase()),rt=(...t)=>Array.prototype.concat.apply([],t),Qc=t=>new Map(Object.entries(t)),a1=(t,e)=>{let s=[],r=0;for(let n of t.matchAll(e)){let o=n[0];r0&&s.push(o),r=n.index+o.length}return rt.replace(/\p{M}/gu,""),Yy=(t,e,s=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let r of s)if(!(r in t))return`${e} must contain a "${r}" property`;return null},l1=t=>t.match(/\S+/g)||[],c1=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},Or=c1,p1=class extends Or{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},yt=p1,u1=class extends yt{tokenize_chinese_chars(t){let e=[];for(let s=0;s{for(var s in e)Lk(t,s,{get:e[s],enumerable:!0})};var Fe={};var Ye={};var Dy={};var $k="4.2.0",Bc=typeof self<"u",Is=!Wy(Fe),By=!Wy(Ye),ra=Bc&&"caches"in self,Fk=typeof globalThis.Deno<"u",BM=typeof globalThis.Bun<"u",oa=Fk&&ra&&!Is,Uy=typeof process<"u",Gy=Uy&&process?.release?.name==="node"&&!oa,Uc=typeof window<"u"&&typeof window.document<"u",Gc=Bc&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),Rk=Uc||Gc||oa,Dk=Gy||typeof navigator<"u"&&"gpu"in navigator,qk=typeof navigator<"u"&&"ml"in navigator,jk=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",Bk=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",Uk=typeof ServiceWorkerGlobalScope<"u"&&Bc&&self instanceof ServiceWorkerGlobalScope,Gk=()=>{if(typeof navigator>"u")return!1;let t=(navigator.userAgent||""),s=(navigator.vendor||"").indexOf("Apple")>-1,r=!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android");return s&&r},Wk=Gk(),K=Object.freeze({IS_BROWSER_ENV:Uc,IS_WEBWORKER_ENV:Gc,IS_WEB_ENV:Rk,IS_SERVICE_WORKER_ENV:Uk,IS_DENO_WEB_RUNTIME:oa,IS_WEB_CACHE_AVAILABLE:ra,IS_WEBGPU_AVAILABLE:Dk,IS_WEBNN_AVAILABLE:qk,IS_SAFARI:Wk,IS_PROCESS_AVAILABLE:Uy,IS_NODE_ENV:Gy,IS_FS_AVAILABLE:Is,IS_PATH_AVAILABLE:By,IS_CRYPTO_AVAILABLE:jk,IS_CHROME_AVAILABLE:Bk}),Wc=Is&&By,na="./";if(Wc){let t=Object(import_meta).url;t?na=Ye.dirname(Ye.dirname(Dy.fileURLToPath(t))):typeof __dirname<"u"&&(na=Ye.dirname(__dirname))}var Vk=Wc?Ye.join(na,"/.cache/"):null,qy="/models/",Hk=Wc?Ye.join(na,qy):qy,Kk=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Ge=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),jy=Ge.WARNING,J={version:$k,backends:{onnx:{}},get logLevel(){return jy},set logLevel(t){jy=t,J.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Uc||Gc||oa),localModelPath:Hk,useFS:Is,useBrowserCache:ra,useFSCache:Is,cacheDir:Vk,useCustomCache:!1,customCache:null,useWasmCache:ra||Is,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:Kk};function Wy(t){return Object.keys(t).length===0}var xe=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function _t(t,e){t&&t(e)}var ts=class extends xe{constructor(e,s){super(),this.callback=e,this.files_loading=s}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let s=Object.values(this.files_loading).reduce((o,i)=>o+i.loaded,0),r=Object.values(this.files_loading).reduce((o,i)=>o+i.total,0),n=r>0?s/r*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:s,total:r,files:structuredClone(this.files_loading)})}this.callback(e)}};function Vy(t){return Number.isInteger(t)||typeof t=="bigint"}function Vc(t){return t==null||t===-1}function Hc(t){let e=[],s=t;for(;Array.isArray(s);)e.push(s.length),s=s[0];return e}function Re(...t){return Array.prototype.concat.apply([],t)}function Hy(...t){return t.reduce((e,s)=>e.flatMap(r=>s.map(n=>[r,n])))}function zs(t,e){return Math.abs((t+e)%(2*e)-e)}function we(t,e){return Object.assign({},...e.map(s=>{if(t[s]!==void 0)return{[s]:t[s]}}))}function Ky(t,e){let s=0;for(let r of t)r===e&&++s;return s}var F={error(...t){J.logLevel<=Ge.ERROR&&console.error(...t)},warn(...t){J.logLevel<=Ge.WARNING&&console.warn(...t)},info(...t){J.logLevel<=Ge.INFO&&console.log(...t)},debug(...t){J.logLevel<=Ge.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var Xk=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let s of t){let r=e;for(let n=0;nr&&e.push(t.slice(r,n)),e.push(i),n+=i.length,r=n):++n}return r{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),s=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+s),s+=1);let r=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,r[o]]))})(),Jk=t=>Object.fromEntries(Object.entries(t).map(([e,s])=>[s,e])),Zk=Jk(s0),Qy=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",e1=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${Qy}])]+`,` ?[^\\s${Qy}]+`]]),ia="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Xc=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),aa=(t,e=!0)=>{if(t.Regex!==void 0){let s=t.Regex.replace(/\\([#&~])/g,"$1");s=s.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[r,n]of e1)s=s.replaceAll(r,n);try{return new RegExp(s,"gu")}catch(r){if(!(r instanceof SyntaxError)||!r.message.toLowerCase().includes("invalid property name"))throw r;let n=!1,o=s.replace(/(\\[pP])\{([^}=]+)\}/g,(i,a,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${a}{${l}}`}catch{return n=!0,`${a}{Script=${l}}`}});if(!n)throw r;try{return new RegExp(o,"gu")}catch{throw r}}}else if(t.String!==void 0){let s=t1(t.String);return new RegExp(e?s:`(${s})`,"gu")}else return console.warn("Unknown pattern type:",t),null},t1=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s1=(t,e,s)=>{let r=[],n=0;for(;nt>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,n1=t=>Number.isInteger(t)||typeof t=="bigint",o1=t=>{let e=0;for(let s of t)++e;return e},i1=t=>r0(t.toLowerCase()),rt=(...t)=>Array.prototype.concat.apply([],t),Qc=t=>new Map(Object.entries(t)),a1=(t,e)=>{let s=[],r=0;for(let n of t.matchAll(e)){let o=n[0];r0&&s.push(o),r=n.index+o.length}return rt.replace(/\p{M}/gu,""),Yy=(t,e,s=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let r of s)if(!(r in t))return`${e} must contain a "${r}" property`;return null},l1=t=>t.match(/\S+/g)||[],c1=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},Or=c1,p1=class extends Or{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},yt=p1,u1=class extends yt{tokenize_chinese_chars(t){let e=[];for(let s=0;ss.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},f1=d1,m1=class extends yt{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>n0(e))}normalize(t){return this.normalizers.reduce((e,s)=>s?s.normalize(e):e,t)}},h1=m1,g1=class extends yt{normalize(t){let e=aa(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},x1=g1,w1=class extends yt{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},la=w1,y1=class extends la{constructor(){super(...arguments),this.form="NFC"}},b1=y1,k1=class extends la{constructor(){super(...arguments),this.form="NFD"}},v1=k1,E1=class extends la{constructor(){super(...arguments),this.form="NFKC"}},A1=E1,M1=class extends la{constructor(){super(...arguments),this.form="NFKD"}},S1=M1,O1=class extends yt{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},I1=O1,z1=class extends yt{normalize(t){return r0(t)}},T1=z1,C1=class extends yt{normalize(t){return t.toLowerCase()}},P1=C1,N1=class extends yt{normalize(t){return t=this.config.prepend+t,t}},L1=N1;function $1(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new _1(t);case"Precompiled":return new f1(t);case"Sequence":return new h1(t);case"Replace":return new x1(t);case"NFC":return new b1(t);case"NFD":return new v1(t);case"NFKC":return new A1(t);case"NFKD":return new S1(t);case"Strip":return new I1(t);case"StripAccents":return new T1(t);case"Lowercase":return new P1(t);case"Prepend":return new L1(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var n0=$1,F1=class extends Or{pre_tokenize(t,e){return(Array.isArray(t)?t.map(s=>this.pre_tokenize_text(s,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},nt=F1,R1=class extends nt{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=s0,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(r=>Array.from(this.text_encoder.encode(r),n=>this.byte_encoder[n]).join(""))}},D1=R1,q1=class extends nt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},j1=q1,B1=class extends nt{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:s=void 0}=e??{},r=t.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&s===0)&&(r=this.str_rep+r),[r]}},U1=B1,G1=class extends nt{constructor(t){super(),this.config=t,this.pattern=aa(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):a1(t,this.pattern)}},W1=G1,V1=class extends nt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${ia}]+|[${ia}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},H1=V1,K1=class extends nt{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},X1=K1,Q1=class extends nt{constructor(){super(),this.pattern=new RegExp(`[^\\s${ia}]+|[${ia}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},Y1=Q1,J1=class extends nt{constructor(t){super(),this.config=t,this.pattern=aa(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Z1=J1,ev=class extends nt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>o0(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((s,r)=>r?r.pre_tokenize(s,e):s,[t])}},tv=ev,sv=class extends nt{pre_tokenize_text(t){return l1(t)}},rv=sv,nv=class extends nt{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let s=0;sthis.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,i=[];for(;o0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--a}if(l===null){n=!0;break}i.push(l),o=a}n?e.push(this.unk_token):e.push(...i)}return e}},Jy=lv,Zy=class i0{constructor(e,s){this.is_leaf=e,this.children=s}static default(){return new i0(!1,new Map)}},cv=class{constructor(){this.root=Zy.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let s of t){let r=e.children.get(s);r===void 0&&(r=Zy.default(),e.children.set(s,r)),e=r}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let s="";for(let r of t){if(s+=r,e=e.children.get(r),e===void 0)return;e.is_leaf&&(yield s)}}},pv=cv,Kc=class a0{constructor(e,s,r,n,o){this.token_id=e,this.node_id=s,this.pos=r,this.length=n,this.score=o,this.prev=null,this.backtrace_score=0}clone(){let e=new a0(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},uv=class{constructor(t,e,s){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=s,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new Kc(this.bos_token_id??0,0,0,0,0),n=new Kc(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(r)}insert(t,e,s,r){let n=this.nodes.length,o=new Kc(r,n,t,e,s);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let i of this.begin_nodes[e]){i.prev=null;let a=0,l=null;for(let c of this.end_nodes[e]){let p=c.backtrace_score+i.score;(l===null||p>a)&&(l=c.clone(),a=p)}if(l!==null)i.prev=l,i.backtrace_score=a;else return[]}++e}let s=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)s.push(o.clone()),o=o.clone().prev.clone();return s.reverse(),s}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},_v=uv;function dv(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],s=0;for(let r=1;r[r,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=dv(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new pv,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,s=1,r=0;for(;rs>r,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let s=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=s}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},xv=gv,wv=class extends ca{constructor(t){super(t),this.tokens_to_ids=Qc(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[s,r]of this.tokens_to_ids)this.vocab[r]=s;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(s=>s.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((s,r)=>[JSON.stringify(s),r])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new xv(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let s=Array.from(t);this.end_of_word_suffix&&(s[s.length-1]+=this.end_of_word_suffix);let r=[];if(s.length>1){let n=new hv((a,l)=>a.score`<0x${i.toString(16).toUpperCase().padStart(2,"0")}>`);o.every(i=>this.tokens_to_ids.has(i))?e.push(...o):this.unk_token!=null&&e.push(this.unk_token)}else this.unk_token!=null&&e.push(this.unk_token)}return e}},t0=wv,yv=class extends ca{constructor(t,e){super(t);let s=t.vocab;this.tokens_to_ids=Qc(e.target_lang?s[e.target_lang]:s),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[r,n]of this.tokens_to_ids)this.vocab[n]=r}encode(t){return t}},bv=yv;function kv(t,e){switch(t.type){case"WordPiece":return new Jy(t);case"Unigram":return new e0(t,e.eos_token);case"BPE":return new t0(t);default:if(t.vocab)return Array.isArray(t.vocab)?new e0(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new t0(t):new Jy(t):new bv(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var vv=kv,Ev=class extends Or{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Ir=Ev,Av=class extends Ir{post_process(t,e=null,s=!0){let r=e===null?this.config.single:this.config.pair,n=[],o=[];for(let i of r)"SpecialToken"in i?s&&(n.push(i.SpecialToken.id),o.push(i.SpecialToken.type_id)):"Sequence"in i&&(i.Sequence.id==="A"?(n=rt(n,t),o=rt(o,new Array(t.length).fill(i.Sequence.type_id))):i.Sequence.id==="B"&&(n=rt(n,e),o=rt(o,new Array(e.length).fill(i.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},Mv=Av,Sv=class extends Ir{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},Ov=Sv,Iv=class extends Ir{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,s=!0){s&&(t=rt([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let n=[],o=s?[this.sep[0]]:[];t=rt(t,n,e,o),r=rt(r,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:r}}},zv=Iv,Tv=class extends Ir{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,s=!0){s&&(t=rt([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let n=s?[this.sep[0]]:[],o=s?[this.sep[0]]:[];t=rt(t,n,e,o),r=rt(r,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:r}}},Cv=Tv,Pv=class extends Ir{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>l0(e))}post_process(t,e=null,s=!0){let r={tokens:t,tokens_pair:e};for(let n of this.processors)r=n.post_process(r.tokens,r.tokens_pair,s);return r}},Nv=Pv;function Lv(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new Mv(t);case"ByteLevel":return new Ov(t);case"BertProcessing":return new zv(t);case"RobertaProcessing":return new Cv(t);case"Sequence":return new Nv(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var l0=Lv,$v=class extends Or{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Je=$v,Fv=class extends Je{constructor(t){super(t),this.byte_decoder=Zk,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),s=new Uint8Array([...e].map(r=>this.byte_decoder[r]));return this.text_decoder.decode(s)}decode_chain(t){let e=[],s=[];for(let r of t)this.added_tokens.find(n=>n.content===r)!==void 0?(s.length>0&&(e.push(this.convert_tokens_to_string(s)),s=[]),e.push(r)):s.push(r);return s.length>0&&e.push(this.convert_tokens_to_string(s)),e}},Rv=Fv,Dv=class extends Je{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,s)=>{if(s!==0){let r=this.config.prefix;r&&e.startsWith(r)?e=e.replace(r,""):e=" "+e}return this.cleanup&&(e=Xc(e)),e})}},qv=Dv,jv=class extends Je{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let s=0;se.replaceAll(this.suffix,s===t.length-1?"":" "))}},Gv=Uv,Wv=class extends Je{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;nn!==this.pad_token).join("");return this.cleanup&&(r=Xc(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},Vv=Wv,Hv=class extends Je{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>c0(e))}decode_chain(t){return this.decoders.reduce((e,s)=>s.decode_chain(e),t)}},Kv=Hv,Xv=class extends Je{decode_chain(t){let e=aa(this.config.pattern),s=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,s))}},Qv=Xv,Yv=class extends Je{decode_chain(t){return[t.join("")]}},Jv=Yv,Zv=class extends Je{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let s=0;for(let n=0;n")){let o=parseInt(r.slice(3,5),16);isNaN(o)||(n=o)}if(n!==null)s.push(n);else{if(s.length>0){let o=this.text_decoder.decode(Uint8Array.from(s));e.push(o),s=[]}e.push(r)}}if(s.length>0){let r=this.text_decoder.decode(Uint8Array.from(s));e.push(r),s=[]}return e}},sE=tE;function rE(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new Rv(t);case"WordPiece":return new qv(t);case"Metaspace":return new Bv(t);case"BPEDecoder":return new Gv(t);case"CTC":return new Vv(t);case"Sequence":return new Kv(t);case"Replace":return new Qv(t);case"Fuse":return new Jv(t);case"Strip":return new eE(t);case"ByteFallback":return new sE(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var c0=rE,nE=class{constructor(t,e){let s=Yy(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(s)throw new Error(s);let r=Yy(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=n0(this.tokenizer.normalizer),this.pre_tokenizer=o0(this.tokenizer.pre_tokenizer),this.model=vv(this.tokenizer.model,this.config),this.post_processor=l0(this.tokenizer.post_processor),this.decoder=c0(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let n=[],o=[];this.added_tokens_map=new Map;for(let i of this.tokenizer.added_tokens){let a=new Yk(i);if(this.added_tokens.push(a),this.model.tokens_to_ids.set(a.content,a.id),this.model.vocab[a.id]=a.content,a.special&&(this.special_tokens.push(a.content),this.all_special_ids.push(a.id)),this.added_tokens_map.set(a.content,a),a.normalized&&this.normalizer!==null){let l=this.normalizer(a.content);o.push(l),this.added_tokens_map.set(l,a)}else n.push(a.content)}(this.config.additional_special_tokens??[]).forEach(i=>{this.special_tokens.includes(i)||this.special_tokens.push(i)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new Xy(n),this.splitter_normalized=new Xy(o),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:s=!0,return_token_type_ids:r=null}={}){let{tokens:n,token_type_ids:o}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:s}),i=n.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),a={ids:i,tokens:n,attention_mask:new Array(i.length).fill(1)};return r&&o&&(a.token_type_ids=o),a}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!n1(t[0]))throw Error("token_ids must be a non-empty array of integers.");let s=t.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);e.skip_special_tokens&&(s=s.filter(n=>!this.special_tokens.includes(n)));let r=this.decoder?this.decoder(s):s.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(r=r.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=Xc(r)),r}tokenize(t,{text_pair:e=null,add_special_tokens:s=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:s}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((s,r)=>{let n=this.added_tokens_map.get(s);n&&(n.lstrip&&r>0&&(e[r-1]=e[r-1].trimEnd()),n.rstrip&&r{if(s.length===0)return[];if(this.added_tokens_map.has(s))return[s];if(this.remove_space===!0&&(s=s.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(s=i1(s)),this.normalizer!==null&&(s=this.normalizer(s)),s.length===0)return[];let n=this.splitter_normalized.split(s);return n.forEach((o,i)=>{let a=this.added_tokens_map.get(o);a&&(a.lstrip&&i>0&&(n[i-1]=n[i-1].trimEnd()),a.rstrip&&i{if(o.length===0)return[];if(this.added_tokens_map.has(o))return[o];let i=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:r}):[o];return this.model(i)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:s=!0}){let r=this.encode_text(t),n=this.encode_text(e||null);return this.post_processor?this.post_processor(r,n,s):{tokens:rt(r??[],n??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let s=0;s=",M.ComparisonBinaryOperator],["==",M.ComparisonBinaryOperator],["!=",M.ComparisonBinaryOperator],["<",M.ComparisonBinaryOperator],[">",M.ComparisonBinaryOperator],["+",M.AdditiveBinaryOperator],["-",M.AdditiveBinaryOperator],["~",M.AdditiveBinaryOperator],["*",M.MultiplicativeBinaryOperator],["/",M.MultiplicativeBinaryOperator],["%",M.MultiplicativeBinaryOperator],["=",M.Equals]],iE=new Map([["n",` + `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function aE(t,e={}){return t.endsWith(` + `)&&(t=t.slice(0,-1)),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%-])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%-]})\n/g,"$1")),t.replace(/{%\s*(end)?generation\s*%}/gs,"")}function lE(t,e={}){let s=[],r=aE(t,e),n=0,o=0,i=c=>{let p="";for(;c(r[n]);){if(r[n]==="\\"){if(++n,n>=r.length)throw new SyntaxError("Unexpected end of input");let u=r[n++],_=iE.get(u);if(_===void 0)throw new SyntaxError(`Unexpected escaped character: ${u}`);p+=_;continue}if(p+=r[n++],n>=r.length)throw new SyntaxError("Unexpected end of input")}return p},a=()=>{let c=s.at(-1);c&&c.type===M.Text&&(c.value=c.value.trimEnd(),c.value===""&&s.pop())},l=()=>{for(;n0){s.push(new Ze(u,M.Text));continue}}if(r[n]==="{"&&r[n+1]==="#"){n+=2;let u=r[n]==="-";u&&++n;let _="";for(;r[n]!=="#"||r[n+1]!=="}";){if(n+2>=r.length)throw new SyntaxError("Missing end of comment tag");_+=r[n++]}let d=_.endsWith("-");d&&(_=_.slice(0,-1)),u&&a(),s.push(new Ze(_,M.Comment)),n+=2,d&&l();continue}if(r.slice(n,n+3)==="{%-"){a(),s.push(new Ze("{%",M.OpenStatement)),n+=3;continue}if(r.slice(n,n+3)==="{{-"){a(),s.push(new Ze("{{",M.OpenExpression)),o=0,n+=3;continue}if(i(_0),r.slice(n,n+3)==="-%}"){s.push(new Ze("%}",M.CloseStatement)),n+=3,l();continue}if(r.slice(n,n+3)==="-}}"){s.push(new Ze("}}",M.CloseExpression)),n+=3,l();continue}let p=r[n];if(p==="-"||p==="+"){let u=s.at(-1)?.type;if(u===M.Text||u===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(u){case M.Identifier:case M.NumericLiteral:case M.StringLiteral:case M.CloseParen:case M.CloseSquareBracket:break;default:{++n;let _=i(zr);s.push(new Ze(`${p}${_}`,_.length>0?M.NumericLiteral:M.UnaryOperator));continue}}}for(let[u,_]of oE){if(u==="}}"&&o>0)continue;if(r.slice(n,n+u.length)===u){s.push(new Ze(u,_)),_===M.OpenExpression?o=0:_===M.OpenCurlyBracket?++o:_===M.CloseCurlyBracket&&--o,n+=u.length;continue e}}if(p==="'"||p==='"'){++n;let u=i(_=>_!==p);s.push(new Ze(u,M.StringLiteral)),++n;continue}if(zr(p)){let u=i(zr);if(r[n]==="."&&zr(r[n+1])){++n;let _=i(zr);u=`${u}.${_}`}s.push(new Ze(u,M.NumericLiteral));continue}if(u0(p)){let u=i(u0);s.push(new Ze(u,M.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return s}var it=class{type="Statement"},cE=class extends it{constructor(t){super(),this.body=t}type="Program"},pE=class extends it{constructor(t,e,s){super(),this.test=t,this.body=e,this.alternate=s}type="If"},uE=class extends it{constructor(t,e,s,r){super(),this.loopvar=t,this.iterable=e,this.body=s,this.defaultBlock=r}type="For"},_E=class extends it{type="Break"},dE=class extends it{type="Continue"},fE=class extends it{constructor(t,e,s){super(),this.assignee=t,this.value=e,this.body=s}type="Set"},mE=class extends it{constructor(t,e,s){super(),this.name=t,this.args=e,this.body=s}type="Macro"},hE=class extends it{constructor(t){super(),this.value=t}type="Comment"},Ke=class extends it{type="Expression"},gE=class extends Ke{constructor(t,e,s){super(),this.object=t,this.property=e,this.computed=s}type="MemberExpression"},d0=class extends Ke{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},Ts=class extends Ke{constructor(t){super(),this.value=t}type="Identifier"},Cs=class extends Ke{constructor(t){super(),this.value=t}type="Literal"},xE=class extends Cs{type="IntegerLiteral"},wE=class extends Cs{type="FloatLiteral"},f0=class extends Cs{type="StringLiteral"},yE=class extends Cs{type="ArrayLiteral"},m0=class extends Cs{type="TupleLiteral"},bE=class extends Cs{type="ObjectLiteral"},Tr=class extends Ke{constructor(t,e,s){super(),this.operator=t,this.left=e,this.right=s}type="BinaryExpression"},kE=class extends Ke{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},vE=class extends it{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},EE=class extends Ke{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},AE=class extends Ke{constructor(t,e,s){super(),this.operand=t,this.negate=e,this.test=s}type="TestExpression"},ME=class extends Ke{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},SE=class extends Ke{constructor(t=void 0,e=void 0,s=void 0){super(),this.start=t,this.stop=e,this.step=s}type="SliceExpression"},OE=class extends Ke{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},IE=class extends Ke{constructor(t){super(),this.argument=t}type="SpreadExpression"},zE=class extends it{constructor(t,e,s){super(),this.call=t,this.callerArgs=e,this.body=s}type="CallStatement"},TE=class extends Ke{constructor(t,e,s){super(),this.condition=t,this.trueExpr=e,this.falseExpr=s}type="Ternary"};function CE(t){let e=new cE([]),s=0;function r(A,O){let T=t[s++];if(!T||T.type!==A)throw new Error(`Parser Error: ${O}. ${T.type} !== ${A}.`);return T}function n(A){if(!l(A))throw new SyntaxError(`Expected ${A}`);++s}function o(){switch(t[s].type){case M.Comment:return new hE(t[s++].value);case M.Text:return c();case M.OpenStatement:return p();case M.OpenExpression:return u();default:throw new SyntaxError(`Unexpected token type: ${t[s].type}`)}}function i(...A){return s+A.length<=t.length&&A.every((O,T)=>O===t[s+T].type)}function a(...A){return t[s]?.type===M.OpenStatement&&t[s+1]?.type===M.Identifier&&A.includes(t[s+1]?.value)}function l(...A){return s+A.length<=t.length&&A.every((O,T)=>t[s+T].type==="Identifier"&&O===t[s+T].value)}function c(){return new f0(r(M.Text,"Expected text token").value)}function p(){if(r(M.OpenStatement,"Expected opening statement token"),t[s].type!==M.Identifier)throw new SyntaxError(`Unknown statement, got ${t[s].type}`);let A=t[s].value,O;switch(A){case"set":++s,O=_();break;case"if":++s,O=d(),r(M.OpenStatement,"Expected {% token"),n("endif"),r(M.CloseStatement,"Expected %} token");break;case"macro":++s,O=m(),r(M.OpenStatement,"Expected {% token"),n("endmacro"),r(M.CloseStatement,"Expected %} token");break;case"for":++s,O=g(),r(M.OpenStatement,"Expected {% token"),n("endfor"),r(M.CloseStatement,"Expected %} token");break;case"call":{++s;let T=null;i(M.OpenParen)&&(T=C());let G=D();if(G.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let ee=C();r(M.CloseStatement,"Expected closing statement token");let $e=[];for(;!a("endcall");)$e.push(o());r(M.OpenStatement,"Expected '{%'"),n("endcall"),r(M.CloseStatement,"Expected closing statement token");let re=new d0(G,ee);O=new zE(re,T,$e);break}case"break":++s,r(M.CloseStatement,"Expected closing statement token"),O=new _E;break;case"continue":++s,r(M.CloseStatement,"Expected closing statement token"),O=new dE;break;case"filter":{++s;let T=D();T instanceof Ts&&i(M.OpenParen)&&(T=$(T)),r(M.CloseStatement,"Expected closing statement token");let G=[];for(;!a("endfilter");)G.push(o());r(M.OpenStatement,"Expected '{%'"),n("endfilter"),r(M.CloseStatement,"Expected '%}'"),O=new vE(T,G);break}default:throw new SyntaxError(`Unknown statement type: ${A}`)}return O}function u(){r(M.OpenExpression,"Expected opening expression token");let A=w();return r(M.CloseExpression,"Expected closing expression token"),A}function _(){let A=f(),O=null,T=[];if(i(M.Equals))++s,O=f();else{for(r(M.CloseStatement,"Expected %} token");!a("endset");)T.push(o());r(M.OpenStatement,"Expected {% token"),n("endset")}return r(M.CloseStatement,"Expected closing statement token"),new fE(A,O,T)}function d(){let A=w();r(M.CloseStatement,"Expected closing statement token");let O=[],T=[];for(;!a("elif","else","endif");)O.push(o());if(a("elif")){++s,++s;let G=d();T.push(G)}else if(a("else"))for(++s,++s,r(M.CloseStatement,"Expected closing statement token");!a("endif");)T.push(o());return new pE(A,O,T)}function m(){let A=D();if(A.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let O=C();r(M.CloseStatement,"Expected closing statement token");let T=[];for(;!a("endmacro");)T.push(o());return new mE(A,O,T)}function f(A=!1){let O=A?D:w,T=[O()],G=i(M.Comma);for(;G&&(++s,T.push(O()),!!i(M.Comma)););return G?new m0(T):T[0]}function g(){let A=f(!0);if(!(A instanceof Ts||A instanceof m0))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${A.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++s;let O=w();r(M.CloseStatement,"Expected closing statement token");let T=[];for(;!a("endfor","else");)T.push(o());let G=[];if(a("else"))for(++s,++s,r(M.CloseStatement,"Expected closing statement token");!a("endfor");)G.push(o());return new uE(A,O,T,G)}function w(){return x()}function x(){let A=y();if(l("if")){++s;let O=y();if(l("else")){++s;let T=x();return new TE(O,A,T)}else return new EE(A,O)}return A}function y(){let A=b();for(;l("or");){let O=t[s];++s;let T=b();A=new Tr(O,A,T)}return A}function b(){let A=v();for(;l("and");){let O=t[s];++s;let T=v();A=new Tr(O,A,T)}return A}function v(){let A;for(;l("not");){let O=t[s];++s;let T=v();A=new ME(O,T)}return A??k()}function k(){let A=S();for(;;){let O;if(l("not","in"))O=new Ze("not in",M.Identifier),s+=2;else if(l("in"))O=t[s++];else if(i(M.ComparisonBinaryOperator))O=t[s++];else break;let T=S();A=new Tr(O,A,T)}return A}function S(){let A=j();for(;i(M.AdditiveBinaryOperator);){let O=t[s];++s;let T=j();A=new Tr(O,A,T)}return A}function I(){let A=H(D());return i(M.OpenParen)?$(A):A}function $(A){let O=new d0(A,C());return O=H(O),i(M.OpenParen)&&(O=$(O)),O}function C(){r(M.OpenParen,"Expected opening parenthesis for arguments list");let A=R();return r(M.CloseParen,"Expected closing parenthesis for arguments list"),A}function R(){let A=[];for(;!i(M.CloseParen);){let O;if(t[s].type===M.MultiplicativeBinaryOperator&&t[s].value==="*"){++s;let T=w();O=new IE(T)}else if(O=w(),i(M.Equals)){if(++s,!(O instanceof Ts))throw new SyntaxError("Expected identifier for keyword argument");let T=w();O=new OE(O,T)}A.push(O),i(M.Comma)&&++s}return A}function V(){let A=[],O=!1;for(;!i(M.CloseSquareBracket);)i(M.Colon)?(A.push(void 0),++s,O=!0):(A.push(w()),i(M.Colon)&&(++s,O=!0));if(A.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(O){if(A.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new SE(...A)}return A[0]}function H(A){for(;i(M.Dot)||i(M.OpenSquareBracket);){let O=t[s];++s;let T,G=O.type===M.OpenSquareBracket;if(G)T=V(),r(M.CloseSquareBracket,"Expected closing square bracket");else if(T=D(),T.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");A=new gE(A,T,G)}return A}function j(){let A=B();for(;i(M.MultiplicativeBinaryOperator);){let O=t[s++],T=B();A=new Tr(O,A,T)}return A}function B(){let A=Z();for(;l("is");){++s;let O=l("not");O&&++s;let T=D();if(!(T instanceof Ts))throw new SyntaxError("Expected identifier for the test");A=new AE(A,O,T)}return A}function Z(){let A=I();for(;i(M.Pipe);){++s;let O=D();if(!(O instanceof Ts))throw new SyntaxError("Expected identifier for the filter");i(M.OpenParen)&&(O=$(O)),A=new kE(A,O)}return A}function D(){let A=t[s++];switch(A.type){case M.NumericLiteral:{let O=A.value;return O.includes(".")?new wE(Number(O)):new xE(Number(O))}case M.StringLiteral:{let O=A.value;for(;i(M.StringLiteral);)O+=t[s++].value;return new f0(O)}case M.Identifier:return new Ts(A.value);case M.OpenParen:{let O=f();return r(M.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),O}case M.OpenSquareBracket:{let O=[];for(;!i(M.CloseSquareBracket);)O.push(w()),i(M.Comma)&&++s;return++s,new yE(O)}case M.OpenCurlyBracket:{let O=new Map;for(;!i(M.CloseCurlyBracket);){let T=w();r(M.Colon,"Expected colon between key and value in object literal");let G=w();O.set(T,G),i(M.Comma)&&++s}return++s,new bE(O)}default:throw new SyntaxError(`Unexpected token: ${A.type}`)}}for(;s0)for(let n=t;ne;n+=s)r.push(n);return r}function h0(t,e,s,r=1){let n=Math.sign(r);n>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),s=(s??=t.length)<0?Math.max(t.length+s,0):Math.min(s,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),s=(s??=-1)<-1?Math.max(t.length+s,-1):Math.min(s,t.length-1));let o=[];for(let i=e;n*ie.toUpperCase())}function LE(t){return $E(new Date,t)}function $E(t,e){let s=new Intl.DateTimeFormat(void 0,{month:"long"}),r=new Intl.DateTimeFormat(void 0,{month:"short"}),n=o=>o<10?"0"+o:o.toString();return e.replace(/%[YmdbBHM%]/g,o=>{switch(o){case"%Y":return t.getFullYear().toString();case"%m":return n(t.getMonth()+1);case"%d":return n(t.getDate());case"%b":return r.format(t);case"%B":return s.format(t);case"%H":return n(t.getHours());case"%M":return n(t.getMinutes());case"%%":return"%";default:return o}})}function FE(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function RE(t,e,s,r){if(r===0)return t;let n=r==null||r<0?1/0:r,o=e.length===0?new RegExp("(?=)","gu"):new RegExp(FE(e),"gu");return t.replaceAll(o,i=>n>0?(--n,s):i)}var g0=class extends Error{},x0=class extends Error{},dt=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new Q(!!this.value)}toString(){return String(this.value)}},te=class extends dt{type="IntegerValue"},Ae=class extends dt{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},q=class extends dt{type="StringValue";builtins=new Map([["upper",new be(()=>new q(this.value.toUpperCase()))],["lower",new be(()=>new q(this.value.toLowerCase()))],["strip",new be(()=>new q(this.value.trim()))],["title",new be(()=>new q(NE(this.value)))],["capitalize",new be(()=>new q(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new te(this.value.length)],["rstrip",new be(()=>new q(this.value.trimEnd()))],["lstrip",new be(()=>new q(this.value.trimStart()))],["startswith",new be(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof q)return new Q(this.value.startsWith(e.value));if(e instanceof oe){for(let s of e.value){if(!(s instanceof q))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(s.value))return new Q(!0)}return new Q(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new be(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof q)return new Q(this.value.endsWith(e.value));if(e instanceof oe){for(let s of e.value){if(!(s instanceof q))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(s.value))return new Q(!0)}return new Q(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new be(t=>{let e=t[0]??new ke;if(!(e instanceof q||e instanceof ke))throw new Error("sep argument must be a string or null");let s=t[1]??new te(-1);if(!(s instanceof te))throw new Error("maxsplit argument must be a number");let r=[];if(e instanceof ke){let n=this.value.trimStart();for(let{0:o,index:i}of n.matchAll(/\S+/g)){if(s.value!==-1&&r.length>=s.value&&i!==void 0){r.push(o+n.slice(i+o.length));break}r.push(o)}}else{if(e.value==="")throw new Error("empty separator");r=this.value.split(e.value),s.value!==-1&&r.length>s.value&&r.push(r.splice(s.value).join(e.value))}return new oe(r.map(n=>new q(n)))})],["replace",new be(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],s=t[1];if(!(e instanceof q&&s instanceof q))throw new Error("replace() arguments must be strings");let r;if(t.length>2?t[2].type==="KeywordArgumentsValue"?r=t[2].value.get("count")??new ke:r=t[2]:r=new ke,!(r instanceof te||r instanceof ke))throw new Error("replace() count argument must be a number or null");return new q(RE(this.value,e.value,s.value,r.value))})]])},Q=class extends dt{type="BooleanValue"},DE=/[\x7f-\uffff]/g;function w0(t){return t.replace(DE,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function rs(t,e={},s=0,r=!0){let{indent:n=null,ensureAscii:o=!1,separators:i=null,sortKeys:a=!1}=e,l,c;switch(i?[l,c]=i:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return r?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let p=JSON.stringify(t.value);return o&&(p=w0(p)),p}case"ArrayValue":case"ObjectValue":{let p=n?" ".repeat(n):"",u=` +@@ -7,7 +7,7 @@ var Lk=Object.defineProperty;var Os=(t,e)=>{for(var s in e)Lk(t,s,{get:e[s],enum + `));case"join":case"string":return t;case"int":{let n=parseInt(t.value,10);return new te(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new Ae(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${r.value}`)}else if(t instanceof te||t instanceof Ae)switch(r.value){case"abs":return t instanceof te?new te(Math.abs(t.value)):new Ae(Math.abs(t.value));case"int":return new te(Math.floor(t.value));case"float":return new Ae(t.value);case"string":return new q(t.toString());default:throw new Error(`Unknown NumericValue filter: ${r.value}`)}else if(t instanceof Ne)switch(r.value){case"items":return new oe(Array.from(t.value.entries()).map(([n,o])=>new oe([new q(n),o])));case"length":return new te(t.value.size);default:{let n=t.builtins.get(r.value);if(n)return n instanceof be?n.value([],s):n;throw new Error(`Unknown ObjectValue filter: ${r.value}`)}}else if(t instanceof Q)switch(r.value){case"bool":return new Q(t.value);case"int":return new te(t.value?1:0);case"float":return new Ae(t.value?1:0);case"string":return new q(t.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${r.value}`)}throw new Error(`Cannot apply filter "${r.value}" to type: ${t.type}`)}else if(e.type==="CallExpression"){let r=e;if(r.callee.type!=="Identifier")throw new Error(`Unknown filter: ${r.callee.type}`);let n=r.callee.value;if(n==="tojson"){let[,o]=this.evaluateArguments(r.args,s),i=o.get("indent")??new ke;if(!(i instanceof te||i instanceof ke))throw new Error("If set, indent must be a number");let a=o.get("ensure_ascii")??new Q(!1);if(!(a instanceof Q))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new Q(!1);if(!(l instanceof Q))throw new Error("If set, sort_keys must be a boolean");let c=o.get("separators")??new ke,p=null;if(c instanceof oe||c instanceof y0){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[u,_]=c.value;if(!(u instanceof q)||!(_ instanceof q))throw new Error("separators must be a tuple of two strings");p=[u.value,_.value]}else if(!(c instanceof ke))throw new Error("If set, separators must be a tuple of two strings");return new q(rs(t,{indent:i.value,ensureAscii:a.value,sortKeys:l.value,separators:p}))}else if(n==="join"){let o;if(t instanceof q)o=Array.from(t.value);else if(t instanceof oe)o=t.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[i,a]=this.evaluateArguments(r.args,s),l=i.at(0)??a.get("separator")??new q("");if(!(l instanceof q))throw new Error("separator must be a string");return new q(o.join(l.value))}else if(n==="int"||n==="float"){let[o,i]=this.evaluateArguments(r.args,s),a=o.at(0)??i.get("default")??(n==="int"?new te(0):new Ae(0));if(t instanceof q){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?a:n==="int"?new te(l):new Ae(l)}else{if(t instanceof te||t instanceof Ae)return t;if(t instanceof Q)return n==="int"?new te(t.value?1:0):new Ae(t.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}}else if(n==="default"){let[o,i]=this.evaluateArguments(r.args,s),a=o[0]??new q(""),l=o[1]??i.get("boolean")??new Q(!1);if(!(l instanceof Q))throw new Error("`default` filter flag must be a boolean");return t instanceof ye||l.value&&!t.__bool__().value?a:t}if(t instanceof oe){switch(n){case"sort":{let[o,i]=this.evaluateArguments(r.args,s),a=o.at(0)??i.get("reverse")??new Q(!1);if(!(a instanceof Q))throw new Error("reverse must be a boolean");let l=o.at(1)??i.get("case_sensitive")??new Q(!1);if(!(l instanceof Q))throw new Error("case_sensitive must be a boolean");let c=o.at(2)??i.get("attribute")??new ke;if(!(c instanceof q||c instanceof te||c instanceof ke))throw new Error("attribute must be a string, integer, or null");let p=u=>{if(c instanceof ke)return u;let _=c instanceof te?String(c.value):c.value;return b0(u,_)};return new oe(t.value.slice().sort((u,_)=>{let d=p(u),m=p(_),f=Yc(d,m,l.value);return a.value?-f:f}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(u=>!(u instanceof Ne)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(r.args.some(u=>u.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[i,a,l]=r.args.map(u=>this.evaluate(u,s)),c;if(a){let u=s.tests.get(a.value);if(!u)throw new Error(`Unknown test: ${a.value}`);c=u}else c=(...u)=>u[0].__bool__().value;let p=t.value.filter(u=>{let _=u.value.get(i.value),d=_?c(_,l):!1;return o?d:!d});return new oe(p)}case"map":{let[,o]=this.evaluateArguments(r.args,s);if(o.has("attribute")){let i=o.get("attribute");if(!(i instanceof q))throw new Error("attribute must be a string");let a=o.get("default"),l=t.value.map(c=>{if(!(c instanceof Ne))throw new Error("items in map must be an object");let p=b0(c,i.value);return p instanceof ye?a??new ye:p});return new oe(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof q){switch(n){case"indent":{let[o,i]=this.evaluateArguments(r.args,s),a=o.at(0)??i.get("width")??new te(4);if(!(a instanceof te))throw new Error("width must be a number");let l=o.at(1)??i.get("first")??new Q(!1),c=o.at(2)??i.get("blank")??new Q(!1),p=t.value.split(` + `),u=" ".repeat(a.value),_=p.map((d,m)=>!l.value&&m===0||!c.value&&d.length===0?d:u+d);return new q(_.join(` + `))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof be))throw new Error("replace filter not available");let[i,a]=this.evaluateArguments(r.args,s);return o.value([...i,new Cr(a)],s)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof Ne){let o=t.builtins.get(n);if(o&&o instanceof be){let[i,a]=this.evaluateArguments(r.args,s);return a.size>0&&i.push(new Cr(a)),o.value(i,s)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}throw new Error(`Unknown filter: ${e.type}`)}evaluateFilterExpression(t,e){let s=this.evaluate(t.operand,e);return this.applyFilter(s,t.filter,e)}evaluateTestExpression(t,e){let s=this.evaluate(t.operand,e),r=e.tests.get(t.test.value);if(!r)throw new Error(`Unknown test: ${t.test.value}`);let n=r(s);return new Q(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new ye}evaluateUnaryExpression(t,e){let s=this.evaluate(t.argument,e);if(t.operator.value==="not")return new Q(!s.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evaluateTernaryExpression(t,e){return this.evaluate(t.condition,e).__bool__().value?this.evaluate(t.trueExpr,e):this.evaluate(t.falseExpr,e)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let s="";for(let r of t){let n=this.evaluate(r,e);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(s+=n.toString())}return new q(s)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){let[s,r]=this.evaluateArguments(t.args,e);r.size>0&&s.push(new Cr(r));let n=this.evaluate(t.callee,e);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(s,e)}evaluateSliceExpression(t,e,s){if(!(t instanceof oe||t instanceof q))throw new Error("Slice object must be an array or string");let r=this.evaluate(e.start,s),n=this.evaluate(e.stop,s),o=this.evaluate(e.step,s);if(!(r instanceof te||r instanceof ye))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof te||n instanceof ye))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof te||o instanceof ye))throw new Error("Slice step must be numeric or undefined");return t instanceof oe?new oe(h0(t.value,r.value,n.value,o.value)):new q(h0(Array.from(t.value),r.value,n.value,o.value).join(""))}evaluateMemberExpression(t,e){let s=this.evaluate(t.object,e),r;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(s,t.property,e);r=this.evaluate(t.property,e)}else r=new q(t.property.value);let n;if(s instanceof Ne){if(!(r instanceof q))throw new Error(`Cannot access property with non-string: got ${r.type}`);n=s.value.get(r.value)??s.builtins.get(r.value)}else if(s instanceof oe||s instanceof q)if(r instanceof te)n=s.value.at(r.value),s instanceof q&&(n=new q(s.value.at(r.value)));else if(r instanceof q)n=s.builtins.get(r.value);else throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);else{if(!(r instanceof q))throw new Error(`Cannot access property with non-string: got ${r.type}`);n=s.builtins.get(r.value)}return n instanceof dt?n:new ye}evaluateSet(t,e){let s=t.value?this.evaluate(t.value,e):this.evaluateBlock(t.body,e);if(t.assignee.type==="Identifier"){let r=t.assignee.value;e.setVariable(r,s)}else if(t.assignee.type==="TupleLiteral"){let r=t.assignee;if(!(s instanceof oe))throw new Error(`Cannot unpack non-iterable type in set: ${s.type}`);let n=s.value;if(n.length!==r.value.length)throw new Error(`Too ${r.value.length>n.length?"few":"many"} items to unpack in set`);for(let o=0;od.setVariable(t.loopvar.value,u);else if(t.loopvar.type==="TupleLiteral"){let d=t.loopvar;if(u.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${u.type}`);let m=u;if(d.value.length!==m.value.length)throw new Error(`Too ${d.value.length>m.value.length?"few":"many"} items to unpack`);_=f=>{for(let g=0;g0?o[c-1]:new ye],["nextitem",c{let n=new ss(r);s=s.slice();let o;s.at(-1)?.type==="KeywordArgumentsValue"&&(o=s.pop());for(let i=0;i{let c=new ss(l);if(t.callerArgs)for(let p=0;pthis.evaluate(s,e)));case"TupleLiteral":return new y0(t.value.map(s=>this.evaluate(s,e)));case"ObjectLiteral":{let s=new Map;for(let[r,n]of t.value){let o=this.evaluate(r,e);if(!(o instanceof q))throw new Error(`Object keys must be strings: got ${o.type}`);s.set(o.value,this.evaluate(n,e))}return new Ne(s)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"FilterStatement":return this.evaluateFilterStatement(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);case"SelectExpression":return this.evaluateSelectExpression(t,e);case"Ternary":return this.evaluateTernaryExpression(t,e);case"Comment":return new ke;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function pa(t){switch(typeof t){case"number":return Number.isInteger(t)?new te(t):new Ae(t);case"string":return new q(t);case"boolean":return new Q(t);case"undefined":return new ye;case"object":return t===null?new ke:Array.isArray(t)?new oe(t.map(pa)):new Ne(new Map(Object.entries(t).map(([e,s])=>[e,pa(s)])));case"function":return new be((e,s)=>{let r=t(...e.map(n=>n.value))??null;return pa(r)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var Te=` +-`,BE="{%- ",UE=" -%}";function GE(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function WE(t,e=" "){let s=typeof e=="number"?" ".repeat(e):e;return ot(t.body,0,s).replace(/\n$/,"")}function De(...t){return BE+t.join(" ")+UE}function ot(t,e,s){return t.map(r=>VE(r,e,s)).join(Te)}function VE(t,e,s){let r=s.repeat(e);switch(t.type){case"Program":return ot(t.body,e,s);case"If":return HE(t,e,s);case"For":return KE(t,e,s);case"Set":return XE(t,e,s);case"Macro":return QE(t,e,s);case"Break":return r+De("break");case"Continue":return r+De("continue");case"CallStatement":return YE(t,e,s);case"FilterStatement":return JE(t,e,s);case"Comment":return r+"{# "+t.value+" #}";default:return r+"{{- "+ae(t)+" -}}"}}function HE(t,e,s){let r=s.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let i=r+De("if",ae(n[0].test))+Te+ot(n[0].body,e+1,s);for(let a=1;a0&&(i+=Te+r+De("else")+Te+ot(o.alternate,e+1,s)),i+=Te+r+De("endif"),i}function KE(t,e,s){let r=s.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let i=t.iterable;n=`${ae(i.lhs)} if ${ae(i.test)}`}else n=ae(t.iterable);let o=r+De("for",ae(t.loopvar),"in",n)+Te+ot(t.body,e+1,s);return t.defaultBlock.length>0&&(o+=Te+r+De("else")+Te+ot(t.defaultBlock,e+1,s)),o+=Te+r+De("endfor"),o}function XE(t,e,s){let r=s.repeat(e),n=ae(t.assignee),o=t.value?ae(t.value):"",i=r+De("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?i:i+Te+ot(t.body,e+1,s)+Te+r+De("endset")}function QE(t,e,s){let r=s.repeat(e),n=t.args.map(ae).join(", ");return r+De("macro",`${t.name.value}(${n})`)+Te+ot(t.body,e+1,s)+Te+r+De("endmacro")}function YE(t,e,s){let r=s.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ae).join(", ")})`:"",o=ae(t.call),i=r+De(`call${n}`,o)+Te;return i+=ot(t.body,e+1,s)+Te,i+=r+De("endcall"),i}function JE(t,e,s){let r=s.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ae(t.filter),o=r+De("filter",n)+Te;return o+=ot(t.body,e+1,s)+Te,o+=r+De("endfilter"),o}function ae(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ae(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let s=t,r=GE(s),n=ae(s.left,r),o=ae(s.right,r+1),i=`${n} ${s.operator.value} ${o}`;return r`${ae(r)}: ${ae(n)}`).join(", ")}}`;case"SliceExpression":{let s=t,r=s.start?ae(s.start):"",n=s.stop?ae(s.stop):"",o=s.step?`:${ae(s.step)}`:"";return`${r}:${n}${o}`}case"KeywordArgumentExpression":{let s=t;return`${s.key.value}=${ae(s.value)}`}case"Ternary":{let s=t,r=`${ae(s.trueExpr)} if ${ae(s.condition,0)} else ${ae(s.falseExpr)}`;return e>-1?`(${r})`:r}default:throw new Error(`Unknown expression type: ${t.type}`)}}var k0=class{parsed;constructor(t){let e=lE(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=CE(e)}render(t){let e=new ss;if(qE(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new jE(e).run(this.parsed).value}format(t){return WE(this.parsed,t?.indent||" ")}};var ZE={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"},St=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=Fe.existsSync(e),this.exists){this.status=200,this.statusText="OK";let s=Fe.statSync(e);this.headers.set("content-length",s.size.toString()),this.updateContentType();let r=Fe.createReadStream(e);this.body=new ReadableStream({start(n){r.on("data",o=>n.enqueue(o)),r.on("end",()=>n.close()),r.on("error",o=>n.error(o))},cancel(){r.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",ZE[e]??"application/octet-stream")}clone(){let e=new t(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await Fe.promises.readFile(this.filePath)).buffer}async blob(){let e=await Fe.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await Fe.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};var Ot=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(K.IS_CRYPTO_AVAILABLE){let a=new Uint32Array(1);crypto.getRandomValues(a),e=a[0]}else e=Date.now()>>>0;let s=this._mt,r=(a,l)=>Math.imul(a,l)>>>0,n=[];for(let a=e||0;a>0;a=Math.floor(a/4294967296))n.push(a&4294967295);n.length||n.push(0),s[0]=19650218;for(let a=1;a<624;++a)s[a]=r(1812433253,s[a-1]^s[a-1]>>>30)+a>>>0;let o=1,i=0;for(let a=Math.max(624,n.length);a>0;--a,++o,++i)o>=624&&(s[0]=s[623],o=1),i>=n.length&&(i=0),s[o]=(s[o]^r(s[o-1]^s[o-1]>>>30,1664525))+n[i]+i>>>0;for(let a=623;a>0;--a,++o)o>=624&&(s[0]=s[623],o=1),s[o]=(s[o]^r(s[o-1]^s[o-1]>>>30,1566083941))-o>>>0;s[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let r=0;r<624;++r){let n=e[r]&2147483648|e[(r+1)%624]&2147483647;e[r]=(e[(r+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let s=e[this._idx++];return s^=s>>>11,s^=s<<7&2636928640,s^=s<<15&4022730752,s^=s>>>18,s>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,s=1){let r=this._gauss_next;if(this._gauss_next=null,r===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));r=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+r*s}shuffle(e){for(let s=e.length-1;s>0;--s){let r=32-Math.clz32(s+1),n=this._int32()>>>32-r;for(;n>s;)n=this._int32()>>>32-r;let o=e[s];e[s]=e[n],e[n]=o}}choices(e,s){return e[v0(this._random_fn,s)]}};function v0(t,e){let s=0;for(let n=0;nv0(ns.random,t);var eA=new Ot,Ps=class{constructor(e){this.path=e}async match(e){let s=Ye.join(this.path,e),r=new St(s);if(r.exists)return r}async put(e,s,r=void 0){let n=Ye.join(this.path,e),o=K.IS_PROCESS_AVAILABLE?process.pid:Date.now(),i=eA._int32().toString(36),a=n+`.tmp.${o}.${i}`;try{let l=s.headers.get("Content-Length"),c=parseInt(l??"0"),p=0;await Fe.promises.mkdir(Ye.dirname(n),{recursive:!0});let u=Fe.createWriteStream(a),_=s.body.getReader();for(;;){let{done:d,value:m}=await _.read();if(d)break;await new Promise((g,w)=>{u.write(m,x=>{if(x){w(x);return}g()})}),p+=m.length;let f=c?p/c*100:0;r?.({progress:f,loaded:p,total:c})}await new Promise((d,m)=>{u.close(f=>f?m(f):d())}),await Fe.promises.rename(a,n)}catch(l){try{await Fe.promises.unlink(a)}catch{}throw l}}async delete(e){let s=Ye.join(this.path,e);try{return await Fe.promises.unlink(s),!0}catch{return!1}}};var A0={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"},ua=100,M0=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Pr(...t){return t=t.map((e,s)=>(s&&(e=e.replace(new RegExp("^/"),"")),s!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function It(t,e=null,s=null){let r;try{r=new URL(t)}catch{return!1}return!(e&&!e.includes(r.protocol)||s&&!s.includes(r.hostname))}function S0(t){return!(!M0.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function O0(t,e,s){if(!s)return null;let r=A0[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${r}: "${e}".`)}async function I0(t,e,s){let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):s??0;r===null&&!s&&F.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),i=0,a=t.body.getReader();async function l(){let{done:c,value:p}=await a.read();if(c)return;let u=i+p.length;if(u>n){n=u;let d=new Uint8Array(n);d.set(o),o=d}o.set(p,i),i=u;let _=i/n*100;return e({progress:_,loaded:i,total:n}),l()}return await l(),o}function Jc(t){return It(t,["blob:"])}function Zc(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof import.meta<"u"&&import.meta.url)e=import.meta.url;else return t;return new URL(t,e).href}var T0="SHA-256",tA="experimental_transformers-hash-cache",z0=t=>({algorithm:T0,value:t}),Nr=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(tA),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let s=await this._getFileHash(e);if(s)try{let[r]=await navigator.crossOriginStorage.requestFileHandles([z0(s)]),n=await r.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,s)=>{let r=await this._getFileHash(e);if(r){let n=await s.blob();await this._storeBlobInCOS(n,r)}else this._processAndStore(e,s.body)};_storeBlobInCOS=async(e,s)=>{let[r]=await navigator.crossOriginStorage.requestFileHandles([z0(s)],{create:!0}),n=await r.createWritable();await n.write(e),await n.close()};_processAndStore=async(e,s)=>{try{let r=[];for await(let i of s)r.push(i);let n=new Blob(r),o=await this._getBlobHash(n);await this._storeBlobInCOS(n,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let s=await this._getHashCache(),r=await s.match(e);if(r)return r.text();let n=await this._getLfsFileHash(e);return n?(await s.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let s=e.replace("/resolve/","/raw/");try{let n=(await fetch(s).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{let s=await e.arrayBuffer(),r=await crypto.subtle.digest(T0,s);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function at(t=null){let e=null;if(J.useCustomCache){if(!J.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!J.customCache.match||!J.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=J.customCache}if(!e&&J.experimental_useCrossOriginStorage&&Nr.isAvailable()&&(e=new Nr),!e&&J.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(J.cacheKey)}catch(s){F.warn("An error occurred while opening the browser cache:",s)}}if(!e&&J.useFSCache){if(!K.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new Ps(t??J.cacheDir)}return e}async function C0(t,...e){for(let s of e)try{let r=await t.match(s);if(r)return r}catch{continue}}var _a=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let s=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,s),s}put(e,s){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,s),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};var sA=100,ep=new _a(sA);function da(t,e){let s=ep.get(t);if(s!==void 0)return s;let r=e().then(n=>n,n=>(ep.delete(t),Promise.reject(n)));return ep.put(t,r),r}async function rA(t){if(!It(t,["http:","https:"]))return null;let e=tp(t);return e.set("Range","bytes=0-0"),J.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function We(t,e,s={}){let r=JSON.stringify([t,e,s?.revision,s?.cache_dir,s?.local_files_only]);return da(r,()=>nA(t,e,s))}async function nA(t,e,s){let r=await at(s?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:i,validModelId:a}=Tt(t,e,s,r),l=await Ct(r,n,i);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),p=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:p||void 0,fromCache:!0}}if(J.allowLocalModels&&!It(n,["http:","https:"]))try{let p=await zt(n);if(typeof p!="string"&&p.status!==404){let u=p.headers.get("content-length"),_=p.headers.get("content-type");return{exists:!0,size:u?parseInt(u,10):void 0,contentType:_||void 0,fromCache:!1}}}catch{}if(J.allowRemoteModels&&!s.local_files_only&&a)try{let c=await rA(o);if(c&&c.status>=200&&c.status<300){let p,u=c.headers.get("content-type");if(c.status===206){let _=c.headers.get("content-range");if(_){let d=_.match(/bytes \d+-\d+\/(\d+)/);d&&(p=parseInt(d[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(p===void 0){let _=c.headers.get("content-length");p=_?parseInt(_,10):void 0}return{exists:!0,size:p,contentType:u||void 0,fromCache:!1}}}catch(c){F.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function zt(t){return J.useFS&&!It(t,["http:","https:","blob:"])?new St(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):J.fetch(t,{headers:tp(t)})}function tp(t){let e=typeof process<"u"&&process?.release?.name==="node",s=new Headers;if(e){let r=!!process.env?.TESTING_REMOTELY,n=J.version;if(s.set("User-Agent",`transformers.js/${n}; is_ci/${r};`),It(t,["http:","https:"],["huggingface.co","hf.co"])){let i=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;i&&s.set("Authorization",`Bearer ${i}`)}}return s}function Tt(t,e,s={},r=null){let n=s.revision??"main",o=Pr(t,e),i=S0(t),a=i?Pr(J.localModelPath,o):o,l=Pr(J.remoteHost,J.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=r instanceof Ps?n==="main"?o:Pr(t,n,e):l;return{requestURL:o,localPath:a,remoteURL:l,proposedCacheKey:c,validModelId:i}}async function Ct(t,e,s){if(t)return await C0(t,e,s)}async function oA(t,e,s,r,n,o,i={}){if(await s.match(r)===void 0)if(o){if(typeof n!="string"){let a=new Headers(n.headers);a.set("content-length",o.byteLength.toString()),await s.put(r,new Response(o,{headers:a})).catch(l=>{F.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let a=i.progress_callback?l=>_t(i.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await s.put(r,n,a)}}async function iA(t,e,s=!0,r={},n=!1,o=null){let{requestURL:i,localPath:a,remoteURL:l,proposedCacheKey:c,validModelId:p}=Tt(t,e,r,o),u,_=!1,d;d=await Ct(o,a,c);let m=d!==void 0;if(m)u=c;else{if(J.allowLocalModels)if(It(i,["http:","https:"])){if(r.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${i}.`);if(!J.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${i}.`)}else try{d=await zt(a),u=a}catch(x){F.warn(`Unable to load from local path "${a}": "${x}"`)}if(d===void 0||typeof d!="string"&&d.status===404){if(r.local_files_only||!J.allowRemoteModels){if(s)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${a}".`);return null}if(!p)throw Error(`Local file missing at "${a}" and download aborted due to invalid model ID "${t}".`);if(d=await zt(l),d.status!==200)return O0(d.status,l,s);u=c}_=o&&typeof Response<"u"&&d instanceof Response&&d.status===200}_t(r.progress_callback,{status:"download",name:t,file:e});let f;if(!(K.IS_NODE_ENV&&n)){let w;if(typeof d!="string")if(!r.progress_callback)w=new Uint8Array(await d.arrayBuffer());else if(m&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))w=new Uint8Array(await d.arrayBuffer()),_t(r.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:w.length,total:w.length});else{let x,y=d.headers.get("content-length");if(y)x=parseInt(y,10);else try{let b=await We(t,e,r);b.size&&(x=b.size)}catch{}w=await I0(d,b=>{_t(r.progress_callback,{status:"progress",name:t,file:e,...b})},x)}f=w}if(_&&u&&typeof d!="string"&&await oA(t,e,o,u,d,f,r),K.IS_NODE_ENV&&n&&r.progress_callback&&typeof d!="string"){let w=parseInt(d.headers.get("content-length"),10)||0;_t(r.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:w,total:w})}if(_t(r.progress_callback,{status:"done",name:t,file:e}),f){if(!K.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return f}if(d instanceof St)return d.filePath;let g=await o?.match(u);if(g instanceof St)return g.filePath;if(g instanceof Response)return new Uint8Array(await g.arrayBuffer());if(typeof g=="string")return g;throw new Error("Unable to get model file path or buffer.")}var fa=new Map;async function Lr(t,e,s=!0,r={},n=!1){if(!J.allowLocalModels){if(r.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!J.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}_t(r.progress_callback,{status:"initiate",name:t,file:e});let o=`${t}::${e}`,i=fa.get(o);if(!i){let a=await at(r?.cache_dir);i=iA(t,e,s,r,n,a).then(l=>(fa.delete(o),l),l=>{throw fa.delete(o),l}),fa.set(o,i)}return await i}async function $r(t,e,s=!0,r={}){let n=await Lr(t,e,s,r,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function Ie(t,e,s=!0,r={}){let n=await $r(t,e,s,r);return n===null?{}:JSON.parse(n)}function N0(t,[e,s,r],[n,o],i="bilinear",a=!1){let l=o/r,c=n/s,p=new t.constructor(n*o*e),u=s*r,_=n*o;for(let d=0;d=0;--a)n[a]=l,r[a]=e[s[a]],l*=r[a];let o=s.map((a,l)=>n[s.indexOf(l)]),i=new t.constructor(t.length);for(let a=0;a=0;--c)l+=p%e[c]*o[c],p=Math.floor(p/e[c]);i[l]=t[a]}return[i,r]}function me(t){let e=de(t)[0],s=t.map(o=>Math.exp(o-e)),r=s.reduce((o,i)=>o+i,0);return s.map(o=>o/r)}function rp(t){let e=de(t)[0],s=0;for(let o=0;oo-e-r)}function $0(t,e){let s=0;for(let r=0;re+s*s,0))}function Fr(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],s=0;for(let r=1;re&&(e=t[r],s=r);return[e,s]}function F0(t){return t>0&&(t&t-1)===0}var ma=class{constructor(e){if(this.size=e|0,this.size<=1||!F0(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let r=0;rr;r<<=1)++s;this._width=s%2===0?s-1:s,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return r}toComplexArray(e,s){let r=s||this.createComplexArray();for(let n=0;n>>1],r[n+1]=0;return r}transform(e,s){if(e===s)throw new Error("Input and output buffers must be different");this._transform4(e,s,1)}realTransform(e,s){if(e===s)throw new Error("Input and output buffers must be different");this._realTransform4(e,s,1)}inverseTransform(e,s){if(e===s)throw new Error("Input and output buffers must be different");this._transform4(e,s,-1);for(let r=0;r>=2;i>=2;i>>=2){a=n/i<<1;let _=a>>>2;for(l=0;l>>1,i>>>1)}else for(l=0,c=0;l>>1,i>>>1,r)}let u=this.table;for(i>>=2;i>=2;i>>=2){a=n/i<<1;let d=a>>>1,m=d>>>1,f=m>>>1;for(l=0;l>>1;for(let d=2;d<_;d+=2)e[n-d]=e[d],e[n-d+1]=-e[d+1]}_singleRealTransform2(e,s,r,n,o){let i=e[n],a=e[n+o];s[r]=i+a,s[r+1]=0,s[r+2]=i-a,s[r+3]=0}_singleRealTransform4(e,s,r,n,o,i){let a=o*2,l=o*3,c=e[n],p=e[n+o],u=e[n+a],_=e[n+l],d=c+u,m=c-u,f=p+_,g=i*(p-_);s[r]=d+f,s[r+1]=0,s[r+2]=m,s[r+3]=-g,s[r+4]=d-f,s[r+5]=0,s[r+6]=m,s[r+7]=g}},sp=class{constructor(e){let s=2*(e-1),r=2*(2*e-1),n=2**Math.ceil(Math.log2(r));this.bufferSize=n,this._a=s;let o=new Float64Array(r),i=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let a=-2*Math.PI/e,l=Math.cos(a),c=Math.sin(a);for(let p=0;p>1;++p){let u=(p+1-e)**2/2,_=Math.sqrt(l**2+c**2)**u,d=u*Math.atan2(c,l),m=2*p;o[m]=_*Math.cos(d),o[m+1]=_*Math.sin(d),i[m]=o[m],i[m+1]=-o[m+1]}this._slicedChirpBuffer=o.subarray(s,r),this._f=new ma(n>>1),this._f.transform(this._chirpBuffer,i)}_transform(e,s,r){let n=this._buffer1,o=this._buffer2,i=this._outBuffer1,a=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,p=this._a;if(r)for(let u=0;u>1,m=s[d];n[u]=m*c[u],n[_]=m*c[_]}else for(let u=0;u=t.length&&(l=2*(t.length-1)-l),r[i++]=t[l]}r.sort(),s[o]=r[n]}return s}function os(t,e){let s=Math.pow(10,e);return Math.round(t*s)/s}function D0(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function q0(t){let e=t.length,s=t[0].length,r=[e+1,s+1],n=Array.from({length:r[0]},()=>Array(r[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:r[0]},()=>Array(r[1]).fill(-1));for(let p=1;p0||a>0;)switch(l.push(i-1),c.push(a-1),o[i][a]){case 0:--i,--a;break;case 1:--i;break;case 2:--a;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${i}, ${a}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var j0=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),i=new Uint32Array(o),a=new Float32Array(o);for(let l=0;l>10,_=l&1023;if(u===31)c=p|2139095040|_<<13;else if(u===0)if(_===0)c=p;else{let d=113;for(;(_&1024)===0;)_<<=1,--d;_&=-1025,c=p|d<<23|_<<13}else c=p|u+112<<23|_<<13;i[0]=c,t[l]=a[0]}}let s=e.length,r=t,n=new Float32Array(s);for(let o=0;olA});var lA={};import*as cA from"onnxruntime-web/webgpu";async function B0(t){let e=t.split("/").pop(),s;try{if(s=await at(),s){let n=await s.match(t);if(n)return n}}catch(n){F.warn(`Failed to load ${e} from cache:`,n)}let r=await J.fetch(t);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);if(s)try{await s.put(t,r.clone())}catch(n){F.warn(`Failed to cache ${e}:`,n)}return r}async function U0(t){let e=await B0(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(s){return F.warn("Failed to read WASM binary:",s),null}}async function G0(t){if(K.IS_SERVICE_WORKER_ENV||K.IS_CHROME_AVAILABLE)return t;let e=await B0(t);if(!e||typeof e=="string")return null;try{let s=await e.text();s=s.replaceAll("globalThis.process?.versions?.node","false");let r=new Blob([s],{type:"text/javascript"});return URL.createObjectURL(r)}catch(s){return F.warn("Failed to read WASM factory:",s),null}}import{Tensor as Q0}from"onnxruntime-common";var pA=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function K0(t){return t<=Ge.DEBUG?0:t<=Ge.INFO?2:t<=Ge.WARNING||t<=Ge.ERROR?3:4}var uA={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},et=[],op,Ls,W0=Symbol.for("onnxruntime");if(W0 in globalThis)Ls=globalThis[W0];else if(K.IS_NODE_ENV){switch(Ls=np,process.platform){case"win32":et.push("dml");break;case"linux":process.arch==="x64"&&et.push("cuda");break;case"darwin":et.push("coreml");break}et.push("webgpu"),et.push("cpu"),op=["cpu"]}else Ls=cA,K.IS_WEBNN_AVAILABLE&&et.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),K.IS_WEBGPU_AVAILABLE&&et.push("webgpu"),et.push("wasm"),op=["wasm"];var _A=Ls.InferenceSession;function X0(t=null){if(!t)return op;switch(t){case"auto":return et;case"gpu":return et.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(et.includes(t))return[pA[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${et.join(", ")}.`)}var V0=Promise.resolve(),Ns=null;async function dA(){if(Ns)return Ns;if(!(J.useWasmCache&&typeof Ce?.wasm?.wasmPaths=="object"&&Ce?.wasm?.wasmPaths?.wasm&&Ce?.wasm?.wasmPaths?.mjs)){if(K.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return Ns=Promise.resolve(),Ns}return Ns=(async()=>{let e=Ce.wasm.wasmPaths,s=!1;await Promise.all([e.wasm&&!Jc(e.wasm)?(async()=>{try{let r=await U0(Zc(e.wasm));r&&(Ce.wasm.wasmBinary=r,s=!0)}catch(r){F.warn("Failed to pre-load WASM binary:",r)}})():Promise.resolve(),e.mjs&&!Jc(e.mjs)?(async()=>{try{let r=await G0(Zc(e.mjs));r&&(Ce.wasm.wasmPaths.mjs=r)}catch(r){F.warn("Failed to pre-load WASM factory:",r)}})():Promise.resolve()]),s||(Ce.wasm.wasmPaths.mjs=e.mjs)})(),Ns}async function ga(t,e,s){await dA();let r=K0(J.logLevel??Ge.WARNING),n=()=>_A.create(t,{logSeverityLevel:r,...e}),o=await(K.IS_WEB_ENV?V0=V0.then(n):n());return o.config=s,o}var H0=Promise.resolve();async function xa(t,e){let s=()=>t.run(e);return K.IS_WEB_ENV?H0=H0.then(s):s()}function wa(t){return t instanceof Ls.Tensor}var Ce=Ls?.env;function Rr(){return Ce?.wasm?.proxy}if(Ce){let t=function(e){let s=K0(e);Ce.logLevel=uA[s]};if(Ce.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&Ce.versions?.web&&!Ce.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Ce.versions.web}/dist/`;Ce.wasm.wasmPaths=K.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}Ce.wasm.proxy=!1}Ce.webgpu&&(Ce.webgpu.powerPreference="high-performance"),t(J.logLevel??Ge.WARNING),J.backends.onnx={...Ce,setLogLevel:t}}var Pt=async(t,e,s)=>{let r=await ga(new Uint8Array(t),e);return(async n=>{let o=Rr(),i=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),a=await xa(r,i);return Array.isArray(s)?s.map(l=>new E(a[l])):new E(a[s])})},mt=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Pt([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Pt([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Pt([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Pt([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Pt([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Pt([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Pt([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=Pt([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var Y0=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),ip=K.IS_NODE_ENV?"cpu":"wasm";function ya(t,e,{warn:s}={}){return t?typeof t=="string"?t:t.hasOwnProperty(e)?t[e]:(s&&s(`device not specified for "${e}". Using the default device (${ip}).`),ip):ip}var eb=(function(){let t;return async function(){if(t===void 0)if(!K.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),Oe=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),J0=Oe.fp32,Z0=Object.freeze({[Y0.wasm]:Oe.q8}),Nt=Object.freeze({[Oe.fp32]:"",[Oe.fp16]:"_fp16",[Oe.int8]:"_int8",[Oe.uint8]:"_uint8",[Oe.q8]:"_quantized",[Oe.q4]:"_q4",[Oe.q2]:"_q2",[Oe.q1]:"_q1",[Oe.q4f16]:"_q4f16",[Oe.q2f16]:"_q2f16",[Oe.q1f16]:"_q1f16",[Oe.bnb4]:"_bnb4"});function ba(t,e,s,{configDtype:r=null,warn:n}={}){let o,i=!1;t&&typeof t!="string"?t.hasOwnProperty(e)?o=t[e]:(o=null,i=!0):o=t;let a;if(o===Oe.auto){if(r){let l=typeof r=="string"?r:r?.[e];if(l&&l!==Oe.auto&&Oe.hasOwnProperty(l))return l}a=Z0[s]??J0}else o&&Oe.hasOwnProperty(o)?a=o:a=Z0[s]??J0;return i&&n&&n(`dtype not specified for "${e}". Using the default dtype (${a}) for this device (${s}).`),a}var Lt=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var E=class t{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return wa(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new Q0(e[0],e[1],e[2]),new Proxy(this,{get:(s,r)=>{if(typeof r=="string"){let n=Number(r);if(Number.isInteger(n))return s._getitem(n)}return s[r]},set:(s,r,n)=>s[r]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...s]=this.dims;if(s.length>0){let r=s.reduce((n,o)=>n*o);for(let n=0;n0){let n=r.reduce((o,i)=>o*i);return this._subarray(e,n,r)}else return new t(this.type,[this.data[e]],r)}indexOf(e){let s=this.data;for(let r=0;rd)throw new Error(`Invalid slice: ${u}`);let m=[Math.max(_,0),Math.min(d,this.dims[p])];r.push(m),s.push(m[1]-m[0])}else throw new Error(`Invalid slice: ${u}`)}let n=r.map(([p,u])=>u-p),o=n.reduce((p,u)=>p*u),i=this.data,a=new i.constructor(o),l=this.stride(),c=!0;for(let p=1;p=0;--_){let m=n[_];u+=(d%m+r[_][0])*l[_],d=Math.floor(d/m)}a[p]=i[u]}return new t(this.type,a,s)}permute(...e){return mA(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,s=!1){return this.norm(1,e,s)}norm(e="fro",s=null,r=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let i,a;if(o?(i=(u,_)=>u+_,a=0n):(i=(u,_)=>u+_**e,a=0),s===null){let u=n.reduce(i,a);return e!==1&&(u=u**(1/e)),new t(this.type,[u],[])}let[l,c,p]=Dr(i,this,s,r);if(e!==1)for(let u=0;u=0;--l){let u=this.dims[l];if(l!==s){let _=c%u;a+=_*p,p*=this.dims[l]}c=Math.floor(c/u)}n[i]/=o[a]}return this}normalize(e=2,s=1){return this.clone().normalize_(e,s)}stride(){return ap(this.dims)}squeeze(e=null){return new t(this.type,this.data,tb(this.dims,e))}squeeze_(e=null){return this.dims=tb(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,sb(this.dims,e))}unsqueeze_(e){return this.dims=sb(this.dims,e),this}flatten_(e=0,s=-1){s=(s+this.dims.length)%this.dims.length;let r=this.dims.slice(0,e),n=this.dims.slice(e,s+1),o=this.dims.slice(s+1);return this.dims=[...r,n.reduce((i,a)=>i*a,1),...o],this}flatten(e=0,s=-1){return this.clone().flatten_(e,s)}view(...e){let s=-1;for(let n=0;na!==s?o*i:o,1);e[s]=r.length/n}return new t(this.type,r,e)}neg_(){let e=this.data;for(let s=0;se?1:0;return new t("bool",s,this.dims)}lt(e){let s=new Uint8Array(this.data.length),r=this.data;for(let n=0;nMath.min(i,a),this,e,s,1/0);return new t(r,n,o)}max(e=null,s=!1){if(e===null){let i=de(this.data)[0];return new t(this.type,[i],[])}let[r,n,o]=Dr((i,a)=>Math.max(i,a),this,e,s,-1/0);return new t(r,n,o)}argmin(e=null,s=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let r=Fr(this.data)[1];return new t("int64",[BigInt(r)],[])}argmax(e=null,s=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let r=de(this.data)[1];return new t("int64",[BigInt(r)],[])}repeat(...e){if(e.lengthp===1)){if(e.length===this.dims.length)return this.clone();let p=e.length-this.dims.length,u=Array(p).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),u)}let s=e.length-this.dims.length,r=Array(s).fill(1).concat(this.dims),n=r.map((p,u)=>p*e[u]),o=n.reduce((p,u)=>p*u,1),i=this.data,a=new i.constructor(o),l=ap(r),c=ap(n);for(let p=0;pBigInt(Math.floor(o)):s=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,j0(this.data),this.dims);return new t(e,Lt[e].from(this.data,s),this.dims)}};function fA(t,e){let s=t.length,r=e.reduce((o,i)=>o*i);if(s!==r)throw Error(`cannot reshape array of size ${s} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((i,a)=>{let l=i[i.length-1];return l.lengthnew E("int64",t,[t.length]);async function va(t,e,s,r,n){return await(await mt.slice)({x:t,s:ka(e),e:ka(s),a:ka(r),t:ka(n??new Array(r.length).fill(1))})}function nb(t,e){let s=t.data,r=e.data,n=[t.dims[0],t.dims[2]],o=new s.constructor(n[0]*n[1]),[i,a,l]=t.dims,c=0;for(let p=0;ps!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((s,r)=>s!==1||!e.includes(r))),t}function sb(t,e){return e=ht(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function ht(t,e,s=null,r=!0){if(t<-e||t>=e){if(r)throw new Error(`IndexError: index ${t} is out of bounds for dimension${s===null?"":" "+s} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function ie(t,e=0){e=ht(e,t[0].dims.length);let s=t[0].dims.slice();s[e]=t.reduce((i,a)=>i+a.dims[e],0);let r=s.reduce((i,a)=>i*a,1),n=new t[0].data.constructor(r),o=t[0].type;if(e===0){let i=0;for(let a of t){let l=a.data;n.set(l,i),i+=l.length}}else{let i=0;for(let a=0;a=0;--_){let f=c[_],g=d%f;_===e&&(g+=i),u+=g*m,m*=s[_],d=Math.floor(d/f)}n[u]=l[p]}i+=c[e]}}return new E(o,n,s)}function qe(t,e=0){return ie(t.map(s=>s.unsqueeze(e)),e)}function Dr(t,e,s,r=!1,n=null){let o=e.data,i=e.dims;s=ht(s,i.length);let a=i.slice();a[s]=1;let l=new o.constructor(o.length/i[s]);n!==null&&l.fill(n);for(let c=0;c=0;--u){let m=i[u];if(u!==s){let f=_%m;p+=f*d,d*=a[u]}_=Math.floor(_/m)}l[p]=t(l[p],o[c],c,p)}return r||a.splice(s,1),[e.type,l,a]}function cp(t,e=null,s=1,r=!1){let n=t.data,o=t.dims;if(e===null){let d=n.reduce((w,x)=>w+x,0)/n.length,m=Math.sqrt(n.reduce((w,x)=>w+(x-d)**2,0)/(n.length-s)),f=new E(t.type,[d],[]);return[new E(t.type,[m],[]),f]}e=ht(e,o.length);let i=Ea(t,e,r),a=i.data,[l,c,p]=Dr((_,d,m,f)=>_+(d-a[f])**2,t,e,r);for(let _=0;_c+p,0);return new E(t.type,[l/n.length],[])}e=ht(e,r.length);let[o,i,a]=Dr((l,c)=>l+c,t,e,s);if(r[e]!==1)for(let l=0;l=0;--s)e[s]=r,r*=t[s];return e}function pp(t,e,s,r){let n=t.reduce((o,i)=>o*i,1);return new E(s,new r(n).fill(e),t)}function ve(t,e){let s,r;if(typeof e=="number")s="float32",r=Float32Array;else if(typeof e=="bigint")s="int64",r=BigInt64Array;else if(typeof e=="boolean")s="bool",r=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return pp(t,e,s,r)}function qr(t,e){return ve(t.dims,e)}function Me(t){return pp(t,1n,"int64",BigInt64Array)}function Aa(t){return Me(t.dims)}function up(t){return pp(t,0n,"int64",BigInt64Array)}function _p(t){return up(t.dims)}function aI(t){let e=t.reduce((s,r)=>s*r,1);return new E("float32",Float32Array.from({length:e},()=>ns.random()),t)}function ob(t){let e=t.reduce((s,r)=>s*r,1);return new E("float32",Float32Array.from({length:e},()=>ns.gauss()),t)}function ib(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let s=e==="binary",r=s?"int8":"uint8",n=s?Int8Array:Uint8Array,o=t.data,i=new n(o.length/8);for(let a=0;a0?1:0,c=Math.floor(a/8),p=a%8;i[c]|=l<<7-p,s&&p===0&&(i[c]-=128)}return new E(r,i,[t.dims[0],t.dims[1]/8])}async function $s(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await We(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function dp(t,e){let s=await $s(t);return await Promise.all(s.map(r=>Ie(t,r,!0,e)))}function jr(t){let e=t.dims;switch(e.length){case 1:return t.tolist();case 2:if(e[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return t.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${e.length}.`)}}var hA=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function gA(t,e,s,r){for(let n of Object.keys(t)){let o=e-t[n].length,i=s(n),a=new Array(o).fill(i);t[n]=r==="right"?Re(t[n],a):Re(a,t[n])}}function xA(t,e){for(let s of Object.keys(t))t[s].length=e}function is(t,...e){for(let s of e){if(!Object.hasOwn(t,s))continue;let r=t[s];if(r)if(typeof r=="object"){if(r.__type==="AddedToken")return r.content;throw Error(`Unknown token: ${r}`)}else return r}return null}function wA(t){let e=[];for(let s of t.get_added_tokens_decoder().values())s.special&&e.push(s);return e}var P=class extends xe{return_token_type_ids=!1;padding_side="right";constructor(e,s){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=s,this._tokenizer=new p0(e,s),this.config=s,this.padding_side=s.padding_side??this.padding_side,this.mask_token=is(s,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=is(s,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=is(s,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=is(s,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=is(s,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=is(s,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=s.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:i}of this.chat_template){if(typeof o!="string"||typeof i!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=i}this.chat_template=n}this._compiled_template_cache=new Map;let r=wA(this._tokenizer);this.all_special_ids=r.map(n=>n.id),this.all_special_tokens=r.map(n=>n.content)}static async from_pretrained(e,{progress_callback:s=null,config:r=null,cache_dir:n=null,local_files_only:o=!1,revision:i="main"}={}){let a=await dp(e,{progress_callback:s,config:r,cache_dir:n,local_files_only:o,revision:i});return new this(...a)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(s=>this._tokenizer.token_to_id(s))}_call(e,s={}){let{text_pair:r=null,add_special_tokens:n=!0,padding:o=!1,return_token_type_ids:i=null}=s,{truncation:a=null,max_length:l=null}=s,c=s.return_tensor??!0,p=Array.isArray(e),u;if(p){if(e.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(e.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");u=e.map((d,m)=>this._encode_plus(d,{text_pair:r[m],add_special_tokens:n,return_token_type_ids:i}))}else u=e.map(d=>this._encode_plus(d,{add_special_tokens:n,return_token_type_ids:i}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");u=[this._encode_plus(e,{text_pair:r,add_special_tokens:n,return_token_type_ids:i})]}if(l===null?l=this.model_max_length:a===null&&(o===!0?(F.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):o===!1&&(F.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),a=!0)),o===!0&&(l=Math.min(de(u.map(d=>d.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),o||a)for(let d=0;dl?a&&xA(u[d],l):o&&gA(u[d],l,m=>m==="input_ids"?this.pad_token_id:0,this.padding_side));let _={};if(c){if(!(o&&a)&&u.some(m=>{for(let f of Object.keys(m))if(m[f].length!==u[0][f]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let d=[u.length,u[0].input_ids.length];for(let m of Object.keys(u[0]))_[m]=new E("int64",BigInt64Array.from(u.flatMap(f=>f[m]).map(BigInt)),d)}else{for(let d of Object.keys(u[0]))_[d]=u.map(m=>m[d]);if(!p)for(let d of Object.keys(_))_[d]=_[d][0]}return _}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:s=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:i,token_type_ids:a}=this._tokenizer.encode(e,{text_pair:s,add_special_tokens:r,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:i,...a?{token_type_ids:a}:{}}}tokenize(e,{pair:s=null,add_special_tokens:r=!1}={}){return this._tokenizer.tokenize(e,{text_pair:s,add_special_tokens:r})}encode(e,{text_pair:s=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:s,add_special_tokens:r,return_token_type_ids:n}).ids}batch_decode(e,s={}){return e instanceof E&&(e=e.tolist()),e.map(r=>this.decode(r,s))}decode(e,s={}){if(e instanceof E&&(e=jr(e)),!Array.isArray(e)||e.length===0||!Vy(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,s)}decode_single(e,{skip_special_tokens:s=!1,clean_up_tokenization_spaces:r=null}){return this._tokenizer.decode(e,{skip_special_tokens:s,clean_up_tokenization_spaces:r})}get_chat_template({chat_template:e=null,tools:s=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let r=this.chat_template;if(e!==null&&Object.hasOwn(r,e))e=r[e];else if(e===null)if(s!==null&&"tool_use"in r)e=r.tool_use;else if("default"in r)e=r.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(r).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,s={}){let{tools:r=null,documents:n=null,chat_template:o=null,add_generation_prompt:i=!1,tokenize:a=!0,padding:l=!1,truncation:c=!1,max_length:p=null,return_tensor:u=!0,return_dict:_=!0,tokenizer_kwargs:d={},...m}=s;if(o=this.get_chat_template({chat_template:o,tools:r}),typeof o!="string")throw Error(`chat_template must be a string, but got ${typeof o}`);let f=this._compiled_template_cache.get(o);f===void 0&&(f=new k0(o),this._compiled_template_cache.set(o,f));let g=Object.create(null);for(let x of hA){let y=is(this.config,x);y&&(g[x]=y)}let w=f.render({messages:e,add_generation_prompt:i,tools:r,documents:n,...g,...m});if(a){let x=this._call(w,{add_special_tokens:!1,padding:l,truncation:c,max_length:p,return_tensor:u,...d});return _?x:x.input_ids}return w}};function Fs(t,e,s,r){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=r.src_lang,o=r.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let i of t._tokenizer.post_processor.config.single)if("SpecialToken"in i&&t.languageRegex.test(i.SpecialToken.id)){i.SpecialToken.id=t.lang_to_token(n);break}}return r.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,s)}var ou={};Os(ou,{AlbertTokenizer:()=>fp,AutoTokenizer:()=>W,BartTokenizer:()=>mp,BertTokenizer:()=>hp,BlenderbotSmallTokenizer:()=>gp,BlenderbotTokenizer:()=>xp,BloomTokenizer:()=>wp,CLIPTokenizer:()=>bp,CamembertTokenizer:()=>yp,CodeGenTokenizer:()=>vp,CodeLlamaTokenizer:()=>kp,CohereAsrTokenizer:()=>Ap,CohereTokenizer:()=>Ep,ConvBertTokenizer:()=>Mp,DebertaTokenizer:()=>Op,DebertaV2Tokenizer:()=>Sp,DistilBertTokenizer:()=>Ip,ElectraTokenizer:()=>zp,EsmTokenizer:()=>Tp,FalconTokenizer:()=>Cp,GPT2Tokenizer:()=>Lp,GPTNeoXTokenizer:()=>Np,GemmaTokenizer:()=>Pp,HerbertTokenizer:()=>$p,LlamaTokenizer:()=>Fp,M2M100Tokenizer:()=>Rp,MBart50Tokenizer:()=>qp,MBartTokenizer:()=>Br,MPNetTokenizer:()=>Up,MarianTokenizer:()=>Dp,MgpstrTokenizer:()=>jp,MobileBertTokenizer:()=>Bp,NllbTokenizer:()=>Gp,NougatTokenizer:()=>Wp,PreTrainedTokenizer:()=>P,Qwen2Tokenizer:()=>Vp,RoFormerTokenizer:()=>Kp,RobertaTokenizer:()=>Hp,SiglipTokenizer:()=>Xp,SpeechT5Tokenizer:()=>Qp,SqueezeBertTokenizer:()=>Yp,T5Tokenizer:()=>Jp,TokenizersBackend:()=>P,VitsTokenizer:()=>eu,Wav2Vec2CTCTokenizer:()=>tu,WhisperTokenizer:()=>su,XLMRobertaTokenizer:()=>ru,XLMTokenizer:()=>nu});var fp=class extends P{return_token_type_ids=!0};var mp=class extends P{};var hp=class extends P{return_token_type_ids=!0};var gp=class extends P{};var xp=class extends P{};var wp=class extends P{};var yp=class extends P{};var bp=class extends P{};var kp=class extends P{};var vp=class extends P{};var Ep=class extends P{};var Ap=class extends P{};var Mp=class extends P{return_token_type_ids=!0};var Sp=class extends P{return_token_type_ids=!0};var Op=class extends P{return_token_type_ids=!0};var Ip=class extends P{};var zp=class extends P{return_token_type_ids=!0};var Tp=class extends P{};var Cp=class extends P{};var Pp=class extends P{};var Np=class extends P{};var Lp=class extends P{};var $p=class extends P{return_token_type_ids=!0};var Fp=class extends P{padding_side="left"};var Rp=class extends P{constructor(e,s){super(e,s),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`}_build_translation_inputs(e,s,r){return Fs(this,e,s,r)}};var Dp=class extends P{constructor(e,s){super(e,s),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(r=>this.languageRegex.test(r)),F.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[s,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(s);if(r.length===2){let[n,o]=r;return this.supported_language_codes.includes(n)||F.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Re([n],super._encode_text(o))}}};var Br=class extends P{constructor(e,s){super(e,s),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r),this.lang_to_token=r=>r}_build_translation_inputs(e,s,r){return Fs(this,e,s,r)}};var qp=class extends Br{};var jp=class extends P{};var Bp=class extends P{return_token_type_ids=!0};var Up=class extends P{};var Gp=class extends P{constructor(e,s){super(e,s),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,s,r){return Fs(this,e,s,r)}};var Wp=class extends P{};var Vp=class extends P{};var Hp=class extends P{};var Kp=class extends P{return_token_type_ids=!0};var Xp=class extends P{};var Qp=class extends P{};var Yp=class extends P{return_token_type_ids=!0};var Jp=class extends P{};var Zp=class extends Je{decode_chain(e){let s="";for(let r=1;r[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function lb(t){t=t.toLowerCase();let e=yA.get(t);if(e===void 0){let s=t.match(/^<\|([a-z]{2})\|>$/);if(s&&(t=s[1]),Ur.has(t))e=t;else{let n=t.length===2?Ur.keys():Ur.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var bA="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",cb=new RegExp(`^[${bA}]+$`,"gu"),kA=.1,su=class extends P{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:s=!1,return_language:r=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let i=null,a=s==="word";function l(){return{language:i,timestamp:[null,null],text:""}}let c=[],p=l(),u=0,_=this.timestamp_begin,m=_+1500,f=[],g=[],w=!1,x=null,y=new Set(this.all_special_ids);for(let k of e){let S=k.tokens,I=a?k.token_timestamps:null,$=null,C=_;if("stride"in k){let[H,j,B]=k.stride;if(u-=j,x=H-B,j&&(C=j/n+_),B)for(let Z=S.length-1;Z>=0;--Z){let D=Number(S[Z]);if(D>=_){if($!==null&&(D-_)*n=_&&j<=m){let B=(j-_)*n+u,Z=os(B,2);if($!==null&&j>=$)w=!0;else if(w||f.length>0&&j0&&p.timestamp[1]!==null))for(let T of p.words)T.timestamp[1]>p.timestamp[1]&&p.timestamp[1]>=T.timestamp[0]&&(T.timestamp[1]=p.timestamp[1]);c.push(p),f=[],R=[],g=[],V=[],p=l()}}else if(R.push(j),a){let B=os(I[H]+u,2),Z;if(H+10?(f.push(R),a&&g.push(V)):f.every(H=>H.length===0)&&(p=l(),f=[],R=[],g=[],V=[])}if(f.length>0){if(o&&s)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[k,S]=this.findLongestCommonSequence(f,g),I=this.decode(k);p.text=I,a&&(p.words=this.collateWordTimestamps(k,S,i)),c.push(p)}let b=Object.create(null),v=c.map(k=>k.text).join("");if(s||r){for(let k=0;k0,a=i?[]:null,l=i?s[0]:null;for(let c=1;cj===C[B]&&l[v+B][0]-kA<=s[c][I+B][0]).length:R=S.filter((j,B)=>j===C[B]).length;let V=b/1e4,H=R/b+V;R>1&&H>u&&(u=H,_=[v,k,I,$])}let[m,f,g,w]=_,x=Math.floor((f+m)/2),y=Math.floor((w+g)/2);if(i&&u===0&&n>0){let b=l[n-1][0],v=s[c].findIndex(k=>k[0]>=b);y=v===-1?p.length:v}o.push(...r.slice(0,x)),r=p.slice(y),n=r.length,i&&(a.push(...l.slice(0,x)),l=s[c].slice(y))}return o.push(...r),i?(a.push(...l),[o,a]):[o,[]]}collateWordTimestamps(e,s,r){let[n,o,i]=this.combineTokensIntoWords(e,r),a=[];for(let l=0;l=n){let a=((i-n)*r).toFixed(2);o.push(`<|${a}|>`),o.push([])}else o[o.length-1].push(i);return o=o.map(i=>typeof i=="string"?i:super.decode(i,s)),o.join("")}splitTokensOnUnicode(e){let s=this.decode(e,{decode_with_timestamps:!0}),r="\uFFFD",n=[],o=[],i=[],a=[],l=[],c=0;for(let p=0;p=this._tokenizer.token_to_id("<|endoftext|>"),d=c.startsWith(" "),m=c.trim(),f=cb.test(m);if(_||d||f||o.length===0)o.push(c),i.push(p),a.push(u);else{let g=o.length-1;o[g]+=c,i[g].push(...p),a[g].push(...u)}}return[o,i,a]}mergePunctuations(e,s,r,n,o){let i=structuredClone(e),a=structuredClone(s),l=structuredClone(r),c=i.length-2,p=i.length-1;for(;c>=0;)i[c].startsWith(" ")&&n.includes(i[c].trim())?(i[p]=i[c]+i[p],a[p]=Re(a[c],a[p]),l[p]=Re(l[c],l[p]),i[c]="",a[c]=[],l[c]=[]):p=c,--c;for(c=0,p=1;pu),a.filter(u=>u.length>0),l.filter(u=>u.length>0)]}};var ru=class extends P{};var nu=class extends P{return_token_type_ids=!0;constructor(e,s){super(e,s),F.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var W=class{static async from_pretrained(e,{progress_callback:s=null,config:r=null,cache_dir:n=null,local_files_only:o=!1,revision:i="main"}={}){let[a,l]=await dp(e,{progress_callback:s,config:r,cache_dir:n,local_files_only:o,revision:i}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=ou[c];return p||(F.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=P),new p(a,l)}};var $t="https://github.com/huggingface/transformers.js/issues/new/choose";var Gr="preprocessor_config.json",bt=Gr,Ma="processor_config.json",Sa="chat_template.jinja";var U=class extends xe{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,s,r){super(),this.config=e,this.components=s,this.chat_template=r}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,s={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...s})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...s){for(let r of[this.image_processor,this.feature_extractor,this.tokenizer])if(r)return r(e,...s);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,s={}){let[r,n,o]=await Promise.all([this.uses_processor_config?Ie(e,Ma,!0,s):{},Promise.all(this.classes.filter(i=>i in this).map(async i=>{let a=await this[i].from_pretrained(e,s);return[i.replace(/_class$/,""),a]})).then(Object.fromEntries),this.uses_chat_template_file?$r(e,Sa,!0,s):null]);return new this(r,n,o)}};var Za={};Os(Za,{ChatterboxProcessor:()=>bu,CohereAsrProcessor:()=>ku,Florence2Processor:()=>f_,Gemma3Processor:()=>m_,Gemma3nProcessor:()=>h_,Gemma4Processor:()=>g_,Glm46VProcessor:()=>x_,GraniteSpeechProcessor:()=>w_,GroundingDinoProcessor:()=>y_,Idefics3Processor:()=>Xa,JinaCLIPProcessor:()=>k_,Lfm2VlProcessor:()=>v_,LlavaProcessor:()=>E_,MgpstrProcessor:()=>A_,MoonshineProcessor:()=>M_,OwlViTProcessor:()=>S_,PaliGemmaProcessor:()=>O_,Phi3VProcessor:()=>I_,PixtralProcessor:()=>z_,Processor:()=>U,PyAnnoteProcessor:()=>T_,Qwen2VLProcessor:()=>ls,Qwen2_5_VLProcessor:()=>sn,Qwen3VLProcessor:()=>C_,Sam2Processor:()=>Qa,Sam2VideoProcessor:()=>P_,SamProcessor:()=>rn,SmolVLMProcessor:()=>Xa,SpeechT5Processor:()=>N_,UltravoxProcessor:()=>L_,VLChatProcessor:()=>b_,VoxtralProcessor:()=>$_,VoxtralRealtimeProcessor:()=>R_,Wav2Vec2Processor:()=>D_,Wav2Vec2ProcessorWithLM:()=>q_,WhisperProcessor:()=>j_});var le=class extends xe{constructor(e){super(),this.config=e}static async from_pretrained(e,s={}){let r=await Ie(e,Gr,!0,s);return new this(r)}};function ce(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var Jr={};Os(Jr,{ASTFeatureExtractor:()=>lu,ChatterboxFeatureExtractor:()=>cu,ClapFeatureExtractor:()=>pu,CohereAsrFeatureExtractor:()=>uu,DacFeatureExtractor:()=>Kr,EncodecFeatureExtractor:()=>Vr,FeatureExtractor:()=>le,Gemma3nAudioFeatureExtractor:()=>Xr,Gemma4AudioFeatureExtractor:()=>Qr,GraniteSpeechFeatureExtractor:()=>_u,MoonshineFeatureExtractor:()=>du,ParakeetFeatureExtractor:()=>Hr,PyAnnoteFeatureExtractor:()=>Yr,SeamlessM4TFeatureExtractor:()=>fu,SnacFeatureExtractor:()=>mu,SpeechT5FeatureExtractor:()=>hu,VoxtralRealtimeFeatureExtractor:()=>wu,Wav2Vec2FeatureExtractor:()=>gu,WeSpeakerFeatureExtractor:()=>xu,WhisperFeatureExtractor:()=>yu});var vA=()=>{};var pb={fromWeb:vA};var EA=()=>{};var ub=EA;async function Oa(t,e){if(K.IS_BROWSER_ENV){if(K.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let s=URL.createObjectURL(e),r=document.createElement("a");r.href=s,r.download=t,r.click(),r.remove(),URL.revokeObjectURL(s)}else if(K.IS_FS_AVAILABLE){let s=e.stream(),r=pb.fromWeb(s),n=Fe.createWriteStream(t);await ub(r,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function fb(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let s=await(await zt(t)).arrayBuffer(),r=new AudioContext({sampleRate:e});typeof e>"u"&&F.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);let n=await r.decodeAudioData(s),o;if(n.numberOfChannels===2){let i=Math.sqrt(2),a=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(a.length);for(let c=0;c2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,s=15,r=27/Math.log(6.4))=>t>=e?s+Math.log(t/e)*r:3*t/200};function iu(t,e="htk"){let s=MA[e];if(!s)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?s(t):t.map(r=>s(r))}var SA={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,s=15,r=Math.log(6.4)/27)=>t>=s?e*Math.exp(r*(t-s)):200*t/3};function OA(t,e="htk"){let s=SA[e];if(!s)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?s(t):t.map(r=>s(r))}function IA(t,e){let s=Float64Array.from({length:e.length-1},(i,a)=>e[a+1]-e[a]),r=Array.from({length:t.length},()=>new Array(e.length));for(let i=0;inew Array(t.length));for(let i=0;it+r*o)}function Pe(t,e,s,r,n,o=null,i="htk",a=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(s>r)throw new Error(`Require min_frequency: ${s} <= max_frequency: ${r}`);let l=iu(s,i),c=iu(r,i),p=db(l,c,e+2),u=OA(p,i),_;if(a){let m=n/((t-1)*2);_=iu(Float64Array.from({length:t},(f,g)=>g*m),i),u=p}else _=db(0,Math.floor(n/2),t);let d=IA(_,u);if(o!==null&&o==="slaney")for(let m=0;mn)throw Error(`frame_length (${s}) may not be larger than fft_length (${n})`);if($!==s)throw new Error(`Length of the window (${$}) must equal frame_length (${s})`);if(r<=0)throw new Error("hop_length must be greater than zero");if(o===null&&u!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!p)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(i){let G=Math.floor(s/2);switch(a){case"reflect":{t=zA(t,G,G);break}case"constant":{let ee=new t.constructor(t.length+2*G);ee.set(t,G),t=ee;break}case"semicausal":{let ee=new t.constructor(t.length+G);ee.set(t,G),t=ee;break}default:throw new Error(`pad_mode="${a}" not implemented yet.`)}}let C=Math.floor(1+Math.floor((t.length-s)/r));y!==null&&CC?v&&(H=b):H=V=b);let j=new ha(n),B=new Float64Array(n),Z=new Float64Array(j.outputBufferSize),D=new Float32Array(R*H);for(let G=0;G=1;--re)B[re]-=c*B[re-1];B[0]*=1-c}for(let re=0;reMath.pow(c,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(s&&(i=i.subarray(0,t)),r===null||t===r)return i;if(t>r)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${r})`);let a=new Float64Array(r),l=n?Math.floor((r-t)/2):0;return a.set(i,l),a}function PA(t,e){let s=t.reduce((o,i)=>o+i.length,0),r=new ArrayBuffer(44),n=new DataView(r);return Ia(n,0,"RIFF"),n.setUint32(4,36+s*4,!0),Ia(n,8,"WAVE"),Ia(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,e,!0),n.setUint32(28,e*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),Ia(n,36,"data"),n.setUint32(40,s*4,!0),new Blob([r,...t.map(o=>o.buffer)],{type:"audio/wav"})}function Ia(t,e,s){for(let r=0;rn+o.length,0),s=new Float32Array(e),r=0;for(let n of this.audio)s.set(n,r),r+=n.length;return s}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),PA(e,this.sampling_rate)}async save(e){return Oa(e,this.toBlob())}};var lu=class extends le{constructor(e){super(e);let s=this.config.sampling_rate,r=Pe(257,this.config.num_mel_bins,20,Math.floor(s/2),s,null,"kaldi",!0);this.mel_filters=r,this.window=Le(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,s){return ze(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:s,transpose:!0})}async _call(e){ce(e,"ASTFeatureExtractor");let s=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let r=this.std*2,n=s.data;for(let o=0;o0)if(r==="rand_trunc"){i=!0;let l=Math.floor(ns.random()*(a+1));e=e.subarray(l,l+s),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${r}" not implemented`);else{if(a<0){let l=new Float64Array(s);if(l.set(e),n==="repeat")for(let c=e.length;c=1;--n)e[n]-=s*e[n-1];return await ze(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){ce(e,"ParakeetFeatureExtractor");let s=await this._extract_fbank_features(e),r=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=s.data;n.fill(0,r*s.dims[1]);let[o,i]=s.dims,a=new Float64Array(i),l=new Float64Array(i);for(let u=0;u1?r-1:1;for(let u=0;u=p){l.push(e.slice(c,p));break}let u=Math.max(c,c+i-a),_=Math.min(c+i,p),d;_<=u?d=c+i:d=this._find_split_point_energy(e,u,_,n),d=Math.max(c+1,Math.min(d,p)),l.push(e.slice(c,d)),c=d}return l}_find_split_point_energy(e,s,r,n){let o=r-s;if(o<=n)return Math.floor((s+r)/2);let i=1/0,a=s,l=o-n;for(let c=0;c<=l;c+=n){let p=0;for(let u=0;us&&(e=e.slice(0,s)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let i=await this._extract_fbank_features(e,this.config.max_length),a=ve([1,i.dims[0]],!0);return{input_features:i.unsqueeze_(0),input_features_mask:a}}};var Qr=class extends Xr{async _extract_fbank_features(e,s){let{frame_length:r,hop_length:n,fft_length:o}=this.config,i=Math.floor(r/2),a=Math.floor((e.length+i-(r+1))/n)+1;return ze(e,this.window,r,n,{fft_length:o,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:a})}async _call(e,s={}){ce(e,"Gemma4AudioFeatureExtractor");let r=e.length,n=await super._call(e,s),{input_features:o}=n,[,i,a]=o.dims,{frame_length:l,hop_length:c}=this.config,p=Math.floor(l/2),u=l+1,_=new Uint8Array(r+p+(s.pad_to_multiple_of??128));_.fill(1,p,p+r);let d=new Uint8Array(i);for(let f=0;f({id:l,start:c*r,end:p*r,confidence:u/(p-c)})))}return n}};var fu=class extends le{constructor(e){super(e);let s=this.config.sampling_rate,r=Pe(257,this.config.num_mel_bins,20,Math.floor(s/2),s,null,"kaldi",!0);this.mel_filters=r,this.window=Le(400,"povey",{periodic:!1})}async _extract_fbank_features(e,s){return e=e.map(r=>r*32768),ze(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:s,transpose:!0})}async _call(e,{padding:s=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){ce(e,"SeamlessM4TFeatureExtractor");let i=await this._extract_fbank_features(e,this.config.max_length);if(n){let[m,f]=i.dims,g=i.data;for(let w=0;w0){let x=new Float32Array(f*(m+w));x.set(g),x.fill(this.config.padding_value,g.length);let y=m+w;i=new E(i.type,x,[y,f]),o&&(a=new E("int64",new BigInt64Array(y),[1,y]),a.data.fill(1n,0,m))}}let[l,c]=i.dims,p=this.config.stride;if(l%p!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${p}).`);let _=i.view(1,Math.floor(l/p),c*p),d={input_features:_};if(o){let m=_.dims[1],f=new BigInt64Array(m);if(a){let g=a.data;for(let w=1,x=0;wo+i,0)/e.length,n=e.reduce((o,i)=>o+(i-r)**2,0)/e.length;return e.map(o=>(o-r)/Math.sqrt(n+1e-7))}async _call(e){ce(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let s=e;this.config.do_normalize&&(s=this._zero_mean_unit_var_norm(s));let r=[1,s.length];return{input_values:new E("float32",s,r),attention_mask:new E("int64",new BigInt64Array(s.length).fill(1n),r)}}};var xu=class extends le{constructor(e){super(e);let s=this.config.sampling_rate,r=Pe(257,this.config.num_mel_bins,20,Math.floor(s/2),s,null,"kaldi",!0);this.mel_filters=r,this.window=Le(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(s=>s*32768),ze(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){ce(e,"WeSpeakerFeatureExtractor");let s=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let r=s.mean(1).data,n=s.data,[o,i,a]=s.dims;for(let l=0;ln?(e.length>this.config.n_samples&&F.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),r=e.slice(0,n)):(r=new Float32Array(n),r.set(e)),{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}};var ge=class{static async from_pretrained(e,s={}){let r=await Ie(e,Gr,!0,s),n=r.feature_extractor_type,o=Jr[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${$t}.`);return new o(r)}};var bu=class extends U{static tokenizer_class=W;static feature_extractor_class=ge;async _call(e,s=null){let r=this.tokenizer(e),n=s?await this.feature_extractor(s):{};return{...r,...n}}};var LA=new Set(["ja","zh"]),ku=class extends U{static tokenizer_class=W;static feature_extractor_class=ge;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let s=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(s)}static join_chunks(e,s="en"){let r=e.filter(i=>i&&i.trim());if(r.length===0)return"";let n=LA.has(s)?"":" ";return[r[0].trimEnd(),...r.slice(1).map(i=>i.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}};var za={};var as,gb,Ft;if(K.IS_WEB_ENV)as=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},Ft=self.createImageBitmap,gb=self.ImageData;else if(za)Ft=async t=>{let s=(await t.metadata()).channels,{data:r,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Ee(new Uint8ClampedArray(r),n.width,n.height,n.channels);return s!==void 0&&s!==n.channels&&o.convert(s),o};else throw new Error("Unable to load image processing library.");var $A={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},FA=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Ee=class t{constructor(e,s,r,n){this.data=e,this.width=s,this.height=r,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!K.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let r=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(r,e.width,e.height,4)}static async fromURL(e){let s=await zt(e);if(s.status!==200)throw new Error(`Unable to read image from "${e}" (${s.status} ${s.statusText})`);let r=await s.blob();return this.fromBlob(r)}static async fromBlob(e){if(K.IS_WEB_ENV){let s=await Ft(e),r=as(s.width,s.height).getContext("2d");return r.drawImage(s,0,0),new this(r.getImageData(0,0,s.width,s.height).data,s.width,s.height,4)}else{let s=za(await e.arrayBuffer());return await Ft(s)}}static fromTensor(e,s="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(s==="CHW")e=e.transpose(1,2,0);else if(s!=="HWC")throw new Error(`Unsupported channel format: ${s}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let s=0,r=0;s=0?l=r:p=-r,n>=0?c=n:u=-n,a.drawImage(i,l,c,e,s,p,u,e,s),new t(a.getImageData(0,0,e,s).data,e,s,4).convert(o)}else{let o=this.toSharp();if(r>=0&&n>=0)o=o.extract({left:Math.floor(r),top:Math.floor(n),width:e,height:s});else if(r<=0&&n<=0){let i=Math.floor(-n),a=Math.floor(-r);o=o.extend({top:i,left:a,right:e-this.width-a,bottom:s-this.height-i})}else{let i=[0,0],a=0;n<0?(i[0]=Math.floor(-n),i[1]=s-this.height-i[0]):a=Math.floor(n);let l=[0,0],c=0;r<0?(l[0]=Math.floor(-r),l[1]=e-this.width-l[0]):c=Math.floor(r),o=o.extend({top:i[0],bottom:i[1],left:l[0],right:l[1]}).extract({left:c,top:a,width:e,height:s})}return await Ft(o)}}async toBlob(e="image/png",s=1){if(!K.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:s})}toTensor(e="CHW"){let s=new E("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")s=s.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return s}toCanvas(){if(!K.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),s=as(e.width,e.height),r=new gb(e.data,e.width,e.height);return s.getContext("2d").putImageData(r,0,0),s}split(){let{data:e,width:s,height:r,channels:n}=this,o=e.constructor,i=e.length/n,a=Array.from({length:n},()=>new o(i));for(let l=0;lnew t(l,s,r,1))}_update(e,s,r,n=null){return this.data=e,this.width=s,this.height=r,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(K.IS_WEB_ENV){if(K.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let s=e.split(".").pop().toLowerCase(),r=FA.get(s)??"image/png",n=await this.toBlob(r);return Oa(e,n)}else if(K.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(K.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return za(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},RA=Ee.read.bind(Ee);function xb(t,e,s=0,r=null){let n=t/e,o=D0(n)*e;return r!==null&&o>r&&(o=Math.floor(n)*e),oe&&w.push(y)}else{let y=de(g.data)[1];if(y===l-1||(x=me(g.data),x[y]v*u[(k+1)%2])),_.boxes.push(b),_.classes.push(y),_.scores.push(x[y])}}c.push(_)}return c}function Ta(t,e=null){let s=t.logits,r=s.dims[0];if(e!==null&&e.length!==r)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;ou[w]&&(u[w]=g[w],_[w]=f)}let d=new Array(a.dims[0]);for(let f=0;f<_.length;++f){let g=_[f];d[g]=g}let m=d.filter(f=>f!==void 0);n.push({segmentation:p,labels:m})}return n}function DA(t,e,s,r){let n=[],o=[],i=[];for(let a=0;as&&(n.push(c),o.push(_),i.push(p))}return[n,o,i]}function qA(t,e,s,r=.5,n=.8){let o=[],i=0,a=0,l=e[s].data;for(let p=0;p=r&&++a;let c=i>0&&a>0;return c&&(c=i/a>n),[c,o]}function jA(t,e,s,r,n,o=null,i=null){let[a,l]=i??t[0].dims,c=new E("int32",new Int32Array(a*l),[a,l]),p=[];if(i!==null)for(let f=0;f_[x]&&(u[x]=f,_[x]=w[x])}let d=0,m=c.data;for(let f=0;f200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let i=Math.round(t/s)*s,a=Math.round(e/s)*s;if(o*i*a>n){let l=Math.sqrt(o*t*e/n);i=Math.max(s,Math.floor(t/l/s)*s),a=Math.max(s,Math.floor(e/l/s)*s)}else if(o*i*ao?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:r}))}async crop_margin(e,s=200){let r=e.clone().grayscale(),n=Fr(r.data)[0],i=de(r.data)[0]-n;if(i===0)return e;let a=s/255,l=r.width,c=r.height,p=0,u=0,_=r.data;for(let d=0;dthis.preprocess(o)));return{pixel_values:qe(r.map(o=>o.pixel_values),0),original_sizes:r.map(o=>o.original_size),reshaped_input_sizes:r.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,s={}){let r=await Ie(e,bt,!0,s);return new this(r)}};var Us={};Os(Us,{BeitFeatureExtractor:()=>Eu,BitImageProcessor:()=>Au,CHMv2ImageProcessor:()=>Su,CLIPFeatureExtractor:()=>Ou,CLIPImageProcessor:()=>Na,ChineseCLIPFeatureExtractor:()=>Mu,ConvNextFeatureExtractor:()=>Iu,ConvNextImageProcessor:()=>La,DINOv3ViTImageProcessor:()=>Cu,DPTFeatureExtractor:()=>Nu,DPTImageProcessor:()=>Ra,DeiTFeatureExtractor:()=>zu,DeiTImageProcessor:()=>$a,DetrFeatureExtractor:()=>Tu,DetrImageProcessor:()=>Fa,DonutFeatureExtractor:()=>Pu,DonutImageProcessor:()=>Ds,EfficientNetImageProcessor:()=>Lu,GLPNFeatureExtractor:()=>Ru,Gemma3ImageProcessor:()=>$u,Gemma4ImageProcessor:()=>Zr,Glm46VImageProcessor:()=>Fu,GroundingDinoImageProcessor:()=>Du,Idefics3ImageProcessor:()=>Da,ImageFeatureExtractor:()=>L,ImageProcessor:()=>L,JinaCLIPImageProcessor:()=>ju,Lfm2VlImageProcessor:()=>Bu,LlavaOnevisionImageProcessor:()=>Uu,Mask2FormerImageProcessor:()=>Wu,MaskFormerFeatureExtractor:()=>Gu,MaskFormerImageProcessor:()=>qs,MobileNetV1FeatureExtractor:()=>Vu,MobileNetV1ImageProcessor:()=>qa,MobileNetV2FeatureExtractor:()=>Hu,MobileNetV2ImageProcessor:()=>ja,MobileNetV3FeatureExtractor:()=>Ku,MobileNetV3ImageProcessor:()=>Ba,MobileNetV4FeatureExtractor:()=>Xu,MobileNetV4ImageProcessor:()=>Ua,MobileViTFeatureExtractor:()=>Qu,MobileViTImageProcessor:()=>Ga,NougatImageProcessor:()=>Yu,OwlViTFeatureExtractor:()=>Ju,OwlViTImageProcessor:()=>js,Owlv2ImageProcessor:()=>Zu,Phi3VImageProcessor:()=>s_,PixtralImageProcessor:()=>r_,PvtImageProcessor:()=>n_,Qwen2VLImageProcessor:()=>en,RTDetrImageProcessor:()=>o_,Sam2ImageProcessor:()=>tn,Sam3ImageProcessor:()=>tn,SamImageProcessor:()=>tn,SapiensFeatureExtractor:()=>i_,SapiensImageProcessor:()=>Wa,SegformerFeatureExtractor:()=>a_,SegformerImageProcessor:()=>Va,SiglipImageProcessor:()=>l_,SmolVLMImageProcessor:()=>Da,Swin2SRImageProcessor:()=>c_,VLMImageProcessor:()=>qu,ViTFeatureExtractor:()=>p_,ViTImageProcessor:()=>Ha,VitMatteImageProcessor:()=>u_,VitPoseImageProcessor:()=>__,YolosFeatureExtractor:()=>d_,YolosImageProcessor:()=>Ka});var Eu=class extends L{};var Au=class extends L{};var Mu=class extends L{};var Su=class extends L{};var Na=class extends L{},Ou=class extends Na{};var La=class extends L{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let s=this.size?.shortest_edge;if(s===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(s<384){let r=Math.floor(s/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:r});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(s,s)}else e=await e.resize(s,s,{resample:this.resample});return e}},Iu=class extends La{};var $a=class extends L{},zu=class extends $a{};var Fa=class extends L{async _call(e){let s=await super._call(e),r=[s.pixel_values.dims[0],64,64],n=ve(r,1n);return{...s,pixel_mask:n}}post_process_object_detection(...e){return Rt(...e)}post_process_panoptic_segmentation(...e){return Ca(...e)}post_process_instance_segmentation(...e){return Pa(...e)}},Tu=class extends Fa{};var Cu=class extends L{};var Ds=class extends L{pad_image(e,s,r,n={}){let[o,i,a]=s,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(a).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(a).fill(l));let p=l.map((u,_)=>-u/c[_]);return super.pad_image(e,s,r,{center:!0,constant_values:p,...n})}},Pu=class extends Ds{};var Ra=class extends L{},Nu=class extends Ra{};var Lu=class extends L{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(s=>s*s))}};var $u=class extends L{};function BA(t,e,s,r,n){let o=r*s**2,i=Math.sqrt(o/(t*e)),a=n*s,l=Math.floor(i*t/a)*a,c=Math.floor(i*e/a)*a;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${a}.`);let p=Math.floor(r/n**2)*a;return l===0?(l=a,c=Math.min(Math.floor(e/t)*a,p)):c===0&&(c=a,l=Math.min(Math.floor(t/e)*a,p)),[l,c]}function UA(t,e,s,r,n,o,i){let a=Math.floor(e/n),l=Math.floor(s/n),c=a*l,p=n*n*r,u=new Float32Array(o*p),_=0;for(let f=0;fi),0));let p=i.dims[0]/a,u=i.dims[1],_=Math.floor(i.dims[2]/c),d=Math.floor(i.dims[3]/c),m=i.view(p,a,u,Math.floor(_/l),l,c,Math.floor(d/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(p*_*d,u*a*c*c),f=new E("int64",[p,_,d],[1,3]);return{pixel_values:m,image_grid_thw:f,original_sizes:n,reshaped_input_sizes:o}}};var Fu=class extends en{get_resize_output_image_size(e,s){let r=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return Rs(e.height,e.width,r,this.min_pixels,this.max_pixels,n)}};var Ru=class extends L{};var Du=class extends L{async _call(e){let s=await super._call(e),r=s.pixel_values.dims,n=Me([r[0],r[2],r[3]]);return{...s,pixel_mask:n}}};var Da=class extends L{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,s){let[r,n]=e.dims.slice(-2),o=n/r;return n>=r?(n=Math.ceil(n/s)*s,r=Math.floor(n/o),r=Math.ceil(r/s)*s):(r=Math.ceil(r/s)*s,n=Math.floor(r*o),n=Math.ceil(n/s)*s),{height:r,width:n}}async _call(e,{do_image_splitting:s=null,return_row_col_info:r=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],i=[],a=[],l=[],c=[];for(let w of n){let x=await Promise.all(w.map(v=>this.preprocess(v)));l.push(...x.map(v=>v.original_size)),c.push(...x.map(v=>v.reshaped_input_size)),x.forEach(v=>v.pixel_values.unsqueeze_(0));let{longest_edge:y}=this.max_image_size,b;if(s??this.do_image_splitting){let v=new Array(x.length),k=new Array(x.length);b=await Promise.all(x.map(async(S,I)=>{let $=this.get_resize_for_vision_encoder(S.pixel_values,y),C=await je(S.pixel_values,{size:[$.height,$.width]}),{frames:R,num_splits_h:V,num_splits_w:H}=await this.split_image(C,this.max_image_size);return v[I]=V,k[I]=H,ie(R,0)})),i.push(v),a.push(k)}else{let v=[y,y];b=await Promise.all(x.map(k=>je(k.pixel_values,{size:v}))),i.push(new Array(x.length).fill(0)),a.push(new Array(x.length).fill(0))}o.push(ie(b,0))}let p=o.length,[u,_,d,m]=o[0].dims,f,g;if(p===1)f=o[0].unsqueeze_(0),g=ve([p,u,d,m],!0);else{let w=Math.max(...o.map(b=>b.dims.at(0)));g=ve([p,w,d,m],!0);let x=g.data,y=w*d*m;for(let b=0;br||a>n){l=Math.ceil(i/r),c=Math.ceil(a/n);let p=Math.ceil(i/l),u=Math.ceil(a/c);for(let m=0;ms*this.rescale_factor)}pad_image(e,s,r,n){return super.pad_image(e,s,r,{constant_values:this.constant_values,center:!0,...n})}};var ju=class extends L{constructor(e){let{resize_mode:s,fill_color:r,interpolation:n,size:o,...i}=e,a=s==="squash"?{width:o,height:o}:s==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...i,size:a,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function yb(t,e){return Math.round(t/e)*e}function GA(t,e,s,r,n){let o=1/0,i=[1,1],a=s*r;for(let l of e){let c=Math.abs(t-l[0]/l[1]);c.5*n*n*l[0]*l[1]&&(i=l)}return i}function WA(t,e){let s=[],r=new Set;for(let n=t;n<=e;++n)for(let o=1;o<=n;++o)for(let i=1;i<=n;++i){let a=o*i;if(a>=t&&a<=e){let l=o<<16|i;r.has(l)||(r.add(l),s.push([o,i]))}}return s.sort((n,o)=>n[0]*n[1]-o[0]*o[1])}function VA(t,e){let[s,r,n,o]=t.dims,i=Math.floor(n/e),a=Math.floor(o/e),l=e*e*r,c=t.data,p=new Float32Array(s*i*a*l),u=n*o;for(let _=0;_this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,s){let r=WA(this.min_tiles,this.max_tiles),[n,o]=GA(s/e,r,s,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:s=null}={}){let r;Array.isArray(e)?Array.isArray(e[0])?r=e:r=[e]:r=[[e]];let n=[],o=[],i=[],a=[],l=[],c=[];for(let u of r){let _=await Promise.all(u.map(d=>this.preprocess(d,{do_pad:!1})));for(let{pixel_values:d}of _){let[,m,f]=d.dims,g=d.unsqueeze_(0),w=this.encoder_patch_size*this.downsample_factor,x=w**2,[y,b]=Rs(Math.max(w,m),Math.max(w,f),w,this.min_image_tokens*x,this.max_image_tokens*x).map(C=>Math.max(w,C)),v,k=1,S=1,I=this._is_image_too_large(m,f),$=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(I&&$){let{grid_width:C,grid_height:R,target_width:V,target_height:H}=this._get_grid_layout(m,f);k=R,S=C;let j=await je(g,{size:[H,V]});v=[];for(let B=0;B(p-this.image_mean[u])/this.image_std[u]);return super.pad_image(e,s,{width:l,height:a},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:s=null}={}){if(this._num_crops=s??=this.config.num_crops,s<4||t_(s)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let r=e.length,n=await Promise.all(e.map(_=>this.preprocess(_))),o=n.map(_=>_.original_size),i=n.map(_=>_.reshaped_input_size),a=[];for(let{pixel_values:_}of n){_.unsqueeze_(0);let[d,m]=_.dims.slice(-2),f=await je(_,{size:[Xe,Xe],mode:"bicubic"});if(s>0){let g=[],w=t_(s),x=Bs(m/w),y=Bs(d/w);for(let v=0;v_.map(d=>Xe*e_(d/Xe))),p=new E("int64",c.flat(),[r,2]),u=c.map(([_,d])=>this.calc_num_image_tokens_from_image_size(d,_));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:i,image_sizes:p,num_img_tokens:u}}};var r_=class extends L{get_resize_output_image_size(e,s){let{longest_edge:r}=s;if(r===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,i=Math.max(n,o)/r,a=n,l=o;i>1&&(a=Math.floor(n/i),l=Math.floor(o/i));let{patch_size:c,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");let u=c*p,_=Math.floor((a-1)/u)+1,d=Math.floor((l-1)/u)+1;return[_*u,d*u]}};var n_=class extends L{};var o_=class extends L{post_process_object_detection(...e){return Rt(...e)}};var tn=class extends L{reshape_input_points(e,s,r,n=!1){e=structuredClone(e);let o=Hc(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let i=0;in!==s.dims[o]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new E("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:s=null,input_labels:r=null,input_boxes:n=null}={}){let o=await super._call(e);if(s&&(o.input_points=this.reshape_input_points(s,o.original_sizes,o.reshaped_input_sizes)),r){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(r,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,s,r,{mask_threshold:n=0,binarize:o=!0,pad_size:i=null}={}){let a=[];i=i??this.pad_size??this.size;let l=[i.height,i.width];for(let c=0;cn&&(m[f]=1);_=new E("bool",m,_.dims)}a.push(_)}return a}generate_crop_boxes(e,s,{crop_n_layers:r=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:i=1}={}){}};var Wa=class extends L{post_process_semantic_segmentation(...e){return Ta(...e)}},i_=class extends Wa{};var Va=class extends L{post_process_semantic_segmentation(...e){return Ta(...e)}},a_=class extends Va{};var l_=class extends L{};var c_=class extends L{pad_image(e,s,r,n={}){let[o,i,a]=s;return super.pad_image(e,s,{width:i+(r-i%r)%r,height:o+(r-o%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var Ha=class extends L{},p_=class extends Ha{};var u_=class extends L{async _call(e,s){Array.isArray(e)||(e=[e]),Array.isArray(s)||(s=[s]);let r=await Promise.all(e.map(i=>this.preprocess(i))),n=await Promise.all(s.map(i=>this.preprocess(i,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:qe(r.map((i,a)=>ie([i.pixel_values,n[a].pixel_values],0)),0),original_sizes:r.map(i=>i.original_size),reshaped_input_sizes:r.map(i=>i.reshaped_input_size)}}};var __=class extends L{post_process_pose_estimation(e,s,{threshold:r=null}={}){let n=e.tolist(),[o,i,a,l]=e.dims,c=[];for(let p=0;p/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let s=[];for(let r of e)if(this.task_prompts_without_inputs.has(r))s.push(this.task_prompts_without_inputs.get(r));else{for(let[n,o]of this.task_prompts_with_input)if(r.includes(n)){s.push(o.replaceAll("{input}",r).replaceAll(n,""));break}s.length!==e.length&&s.push(r)}return s}post_process_generation(e,s,r){let n=this.tasks_answer_post_processing_type.get(s)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let i=n==="ocr"?"quad_boxes":"bboxes",a=e.matchAll(this.regexes[i]),l=[],c=[];for(let[p,u,..._]of a)l.push(u?u.trim():l.at(-1)??""),c.push(_.map((d,m)=>(Number(d)+.5)/this.size_per_bin*r[m%2]));o={labels:l,[i]:c};break;default:throw new Error(`Task "${s}" (of type "${n}") not yet implemented.`)}return{[s]:o}}async _call(e,s=null,r={}){if(!e&&!s)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,r),o=s?this.tokenizer(this.construct_prompts(s),r):{};return{...n,...o}}};var m_=class extends U{static tokenizer_class=W;static image_processor_class=pe;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,s,r){super(e,s,r),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:o,eoi_token:i}=this.tokenizer.config;this.boi_token=n,this.image_token=o,this.eoi_token=i;let a=o.repeat(this.image_seq_length);this.full_image_sequence=` ++`,BE="{%- ",UE=" -%}";function GE(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function WE(t,e=" "){let s=typeof e=="number"?" ".repeat(e):e;return ot(t.body,0,s).replace(/\n$/,"")}function De(...t){return BE+t.join(" ")+UE}function ot(t,e,s){return t.map(r=>VE(r,e,s)).join(Te)}function VE(t,e,s){let r=s.repeat(e);switch(t.type){case"Program":return ot(t.body,e,s);case"If":return HE(t,e,s);case"For":return KE(t,e,s);case"Set":return XE(t,e,s);case"Macro":return QE(t,e,s);case"Break":return r+De("break");case"Continue":return r+De("continue");case"CallStatement":return YE(t,e,s);case"FilterStatement":return JE(t,e,s);case"Comment":return r+"{# "+t.value+" #}";default:return r+"{{- "+ae(t)+" -}}"}}function HE(t,e,s){let r=s.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let i=r+De("if",ae(n[0].test))+Te+ot(n[0].body,e+1,s);for(let a=1;a0&&(i+=Te+r+De("else")+Te+ot(o.alternate,e+1,s)),i+=Te+r+De("endif"),i}function KE(t,e,s){let r=s.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let i=t.iterable;n=`${ae(i.lhs)} if ${ae(i.test)}`}else n=ae(t.iterable);let o=r+De("for",ae(t.loopvar),"in",n)+Te+ot(t.body,e+1,s);return t.defaultBlock.length>0&&(o+=Te+r+De("else")+Te+ot(t.defaultBlock,e+1,s)),o+=Te+r+De("endfor"),o}function XE(t,e,s){let r=s.repeat(e),n=ae(t.assignee),o=t.value?ae(t.value):"",i=r+De("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?i:i+Te+ot(t.body,e+1,s)+Te+r+De("endset")}function QE(t,e,s){let r=s.repeat(e),n=t.args.map(ae).join(", ");return r+De("macro",`${t.name.value}(${n})`)+Te+ot(t.body,e+1,s)+Te+r+De("endmacro")}function YE(t,e,s){let r=s.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ae).join(", ")})`:"",o=ae(t.call),i=r+De(`call${n}`,o)+Te;return i+=ot(t.body,e+1,s)+Te,i+=r+De("endcall"),i}function JE(t,e,s){let r=s.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ae(t.filter),o=r+De("filter",n)+Te;return o+=ot(t.body,e+1,s)+Te,o+=r+De("endfilter"),o}function ae(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ae(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let s=t,r=GE(s),n=ae(s.left,r),o=ae(s.right,r+1),i=`${n} ${s.operator.value} ${o}`;return r`${ae(r)}: ${ae(n)}`).join(", ")}}`;case"SliceExpression":{let s=t,r=s.start?ae(s.start):"",n=s.stop?ae(s.stop):"",o=s.step?`:${ae(s.step)}`:"";return`${r}:${n}${o}`}case"KeywordArgumentExpression":{let s=t;return`${s.key.value}=${ae(s.value)}`}case"Ternary":{let s=t,r=`${ae(s.trueExpr)} if ${ae(s.condition,0)} else ${ae(s.falseExpr)}`;return e>-1?`(${r})`:r}default:throw new Error(`Unknown expression type: ${t.type}`)}}var k0=class{parsed;constructor(t){let e=lE(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=CE(e)}render(t){let e=new ss;if(qE(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new jE(e).run(this.parsed).value}format(t){return WE(this.parsed,t?.indent||" ")}};var ZE={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"},St=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=Fe.existsSync(e),this.exists){this.status=200,this.statusText="OK";let s=Fe.statSync(e);this.headers.set("content-length",s.size.toString()),this.updateContentType();let r=Fe.createReadStream(e);this.body=new ReadableStream({start(n){r.on("data",o=>n.enqueue(o)),r.on("end",()=>n.close()),r.on("error",o=>n.error(o))},cancel(){r.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",ZE[e]??"application/octet-stream")}clone(){let e=new t(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await Fe.promises.readFile(this.filePath)).buffer}async blob(){let e=await Fe.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await Fe.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};var Ot=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(K.IS_CRYPTO_AVAILABLE){let a=new Uint32Array(1);crypto.getRandomValues(a),e=a[0]}else e=Date.now()>>>0;let s=this._mt,r=(a,l)=>Math.imul(a,l)>>>0,n=[];for(let a=e||0;a>0;a=Math.floor(a/4294967296))n.push(a&4294967295);n.length||n.push(0),s[0]=19650218;for(let a=1;a<624;++a)s[a]=r(1812433253,s[a-1]^s[a-1]>>>30)+a>>>0;let o=1,i=0;for(let a=Math.max(624,n.length);a>0;--a,++o,++i)o>=624&&(s[0]=s[623],o=1),i>=n.length&&(i=0),s[o]=(s[o]^r(s[o-1]^s[o-1]>>>30,1664525))+n[i]+i>>>0;for(let a=623;a>0;--a,++o)o>=624&&(s[0]=s[623],o=1),s[o]=(s[o]^r(s[o-1]^s[o-1]>>>30,1566083941))-o>>>0;s[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let r=0;r<624;++r){let n=e[r]&2147483648|e[(r+1)%624]&2147483647;e[r]=(e[(r+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let s=e[this._idx++];return s^=s>>>11,s^=s<<7&2636928640,s^=s<<15&4022730752,s^=s>>>18,s>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,s=1){let r=this._gauss_next;if(this._gauss_next=null,r===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));r=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+r*s}shuffle(e){for(let s=e.length-1;s>0;--s){let r=32-Math.clz32(s+1),n=this._int32()>>>32-r;for(;n>s;)n=this._int32()>>>32-r;let o=e[s];e[s]=e[n],e[n]=o}}choices(e,s){return e[v0(this._random_fn,s)]}};function v0(t,e){let s=0;for(let n=0;nv0(ns.random,t);var eA=new Ot,Ps=class{constructor(e){this.path=e}async match(e){let s=Ye.join(this.path,e),r=new St(s);if(r.exists)return r}async put(e,s,r=void 0){let n=Ye.join(this.path,e),o=K.IS_PROCESS_AVAILABLE?process.pid:Date.now(),i=eA._int32().toString(36),a=n+`.tmp.${o}.${i}`;try{let l=s.headers.get("Content-Length"),c=parseInt(l??"0"),p=0;await Fe.promises.mkdir(Ye.dirname(n),{recursive:!0});let u=Fe.createWriteStream(a),_=s.body.getReader();for(;;){let{done:d,value:m}=await _.read();if(d)break;await new Promise((g,w)=>{u.write(m,x=>{if(x){w(x);return}g()})}),p+=m.length;let f=c?p/c*100:0;r?.({progress:f,loaded:p,total:c})}await new Promise((d,m)=>{u.close(f=>f?m(f):d())}),await Fe.promises.rename(a,n)}catch(l){try{await Fe.promises.unlink(a)}catch{}throw l}}async delete(e){let s=Ye.join(this.path,e);try{return await Fe.promises.unlink(s),!0}catch{return!1}}};var A0={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"},ua=100,M0=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Pr(...t){return t=t.map((e,s)=>(s&&(e=e.replace(new RegExp("^/"),"")),s!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function It(t,e=null,s=null){let r;try{r=new URL(t)}catch{return!1}return!(e&&!e.includes(r.protocol)||s&&!s.includes(r.hostname))}function S0(t){return!(!M0.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function O0(t,e,s){if(!s)return null;let r=A0[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${r}: "${e}".`)}async function I0(t,e,s){let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):s??0;r===null&&!s&&F.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),i=0,a=t.body.getReader();async function l(){let{done:c,value:p}=await a.read();if(c)return;let u=i+p.length;if(u>n){n=u;let d=new Uint8Array(n);d.set(o),o=d}o.set(p,i),i=u;let _=i/n*100;return e({progress:_,loaded:i,total:n}),l()}return await l(),o}function Jc(t){return It(t,["blob:"])}function Zc(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof import_meta<"u"&&import_meta.url)e=import_meta.url;else return t;return new URL(t,e).href}var T0="SHA-256",tA="experimental_transformers-hash-cache",z0=t=>({algorithm:T0,value:t}),Nr=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(tA),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let s=await this._getFileHash(e);if(s)try{let[r]=await navigator.crossOriginStorage.requestFileHandles([z0(s)]),n=await r.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,s)=>{let r=await this._getFileHash(e);if(r){let n=await s.blob();await this._storeBlobInCOS(n,r)}else this._processAndStore(e,s.body)};_storeBlobInCOS=async(e,s)=>{let[r]=await navigator.crossOriginStorage.requestFileHandles([z0(s)],{create:!0}),n=await r.createWritable();await n.write(e),await n.close()};_processAndStore=async(e,s)=>{try{let r=[];for await(let i of s)r.push(i);let n=new Blob(r),o=await this._getBlobHash(n);await this._storeBlobInCOS(n,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let s=await this._getHashCache(),r=await s.match(e);if(r)return r.text();let n=await this._getLfsFileHash(e);return n?(await s.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let s=e.replace("/resolve/","/raw/");try{let n=(await fetch(s).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{let s=await e.arrayBuffer(),r=await crypto.subtle.digest(T0,s);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function at(t=null){let e=null;if(J.useCustomCache){if(!J.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!J.customCache.match||!J.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=J.customCache}if(!e&&J.experimental_useCrossOriginStorage&&Nr.isAvailable()&&(e=new Nr),!e&&J.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(J.cacheKey)}catch(s){F.warn("An error occurred while opening the browser cache:",s)}}if(!e&&J.useFSCache){if(!K.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new Ps(t??J.cacheDir)}return e}async function C0(t,...e){for(let s of e)try{let r=await t.match(s);if(r)return r}catch{continue}}var _a=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let s=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,s),s}put(e,s){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,s),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};var sA=100,ep=new _a(sA);function da(t,e){let s=ep.get(t);if(s!==void 0)return s;let r=e().then(n=>n,n=>(ep.delete(t),Promise.reject(n)));return ep.put(t,r),r}async function rA(t){if(!It(t,["http:","https:"]))return null;let e=tp(t);return e.set("Range","bytes=0-0"),J.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function We(t,e,s={}){let r=JSON.stringify([t,e,s?.revision,s?.cache_dir,s?.local_files_only]);return da(r,()=>nA(t,e,s))}async function nA(t,e,s){let r=await at(s?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:i,validModelId:a}=Tt(t,e,s,r),l=await Ct(r,n,i);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),p=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:p||void 0,fromCache:!0}}if(J.allowLocalModels&&!It(n,["http:","https:"]))try{let p=await zt(n);if(typeof p!="string"&&p.status!==404){let u=p.headers.get("content-length"),_=p.headers.get("content-type");return{exists:!0,size:u?parseInt(u,10):void 0,contentType:_||void 0,fromCache:!1}}}catch{}if(J.allowRemoteModels&&!s.local_files_only&&a)try{let c=await rA(o);if(c&&c.status>=200&&c.status<300){let p,u=c.headers.get("content-type");if(c.status===206){let _=c.headers.get("content-range");if(_){let d=_.match(/bytes \d+-\d+\/(\d+)/);d&&(p=parseInt(d[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(p===void 0){let _=c.headers.get("content-length");p=_?parseInt(_,10):void 0}return{exists:!0,size:p,contentType:u||void 0,fromCache:!1}}}catch(c){F.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function zt(t){return J.useFS&&!It(t,["http:","https:","blob:"])?new St(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):J.fetch(t,{headers:tp(t)})}function tp(t){let e=typeof process<"u"&&process?.release?.name==="node",s=new Headers;if(e){let r=!!process.env?.TESTING_REMOTELY,n=J.version;if(s.set("User-Agent",`transformers.js/${n}; is_ci/${r};`),It(t,["http:","https:"],["huggingface.co","hf.co"])){let i=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;i&&s.set("Authorization",`Bearer ${i}`)}}return s}function Tt(t,e,s={},r=null){let n=s.revision??"main",o=Pr(t,e),i=S0(t),a=i?Pr(J.localModelPath,o):o,l=Pr(J.remoteHost,J.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=r instanceof Ps?n==="main"?o:Pr(t,n,e):l;return{requestURL:o,localPath:a,remoteURL:l,proposedCacheKey:c,validModelId:i}}async function Ct(t,e,s){if(t)return await C0(t,e,s)}async function oA(t,e,s,r,n,o,i={}){if(await s.match(r)===void 0)if(o){if(typeof n!="string"){let a=new Headers(n.headers);a.set("content-length",o.byteLength.toString()),await s.put(r,new Response(o,{headers:a})).catch(l=>{F.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let a=i.progress_callback?l=>_t(i.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await s.put(r,n,a)}}async function iA(t,e,s=!0,r={},n=!1,o=null){let{requestURL:i,localPath:a,remoteURL:l,proposedCacheKey:c,validModelId:p}=Tt(t,e,r,o),u,_=!1,d;d=await Ct(o,a,c);let m=d!==void 0;if(m)u=c;else{if(J.allowLocalModels)if(It(i,["http:","https:"])){if(r.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${i}.`);if(!J.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${i}.`)}else try{d=await zt(a),u=a}catch(x){F.warn(`Unable to load from local path "${a}": "${x}"`)}if(d===void 0||typeof d!="string"&&d.status===404){if(r.local_files_only||!J.allowRemoteModels){if(s)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${a}".`);return null}if(!p)throw Error(`Local file missing at "${a}" and download aborted due to invalid model ID "${t}".`);if(d=await zt(l),d.status!==200)return O0(d.status,l,s);u=c}_=o&&typeof Response<"u"&&d instanceof Response&&d.status===200}_t(r.progress_callback,{status:"download",name:t,file:e});let f;if(!(K.IS_NODE_ENV&&n)){let w;if(typeof d!="string")if(!r.progress_callback)w=new Uint8Array(await d.arrayBuffer());else if(m&&typeof navigator<"u"&&/firefox/i.test((navigator.userAgent||"")))w=new Uint8Array(await d.arrayBuffer()),_t(r.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:w.length,total:w.length});else{let x,y=d.headers.get("content-length");if(y)x=parseInt(y,10);else try{let b=await We(t,e,r);b.size&&(x=b.size)}catch{}w=await I0(d,b=>{_t(r.progress_callback,{status:"progress",name:t,file:e,...b})},x)}f=w}if(_&&u&&typeof d!="string"&&await oA(t,e,o,u,d,f,r),K.IS_NODE_ENV&&n&&r.progress_callback&&typeof d!="string"){let w=parseInt(d.headers.get("content-length"),10)||0;_t(r.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:w,total:w})}if(_t(r.progress_callback,{status:"done",name:t,file:e}),f){if(!K.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return f}if(d instanceof St)return d.filePath;let g=await o?.match(u);if(g instanceof St)return g.filePath;if(g instanceof Response)return new Uint8Array(await g.arrayBuffer());if(typeof g=="string")return g;throw new Error("Unable to get model file path or buffer.")}var fa=new Map;async function Lr(t,e,s=!0,r={},n=!1){if(!J.allowLocalModels){if(r.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!J.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}_t(r.progress_callback,{status:"initiate",name:t,file:e});let o=`${t}::${e}`,i=fa.get(o);if(!i){let a=await at(r?.cache_dir);i=iA(t,e,s,r,n,a).then(l=>(fa.delete(o),l),l=>{throw fa.delete(o),l}),fa.set(o,i)}return await i}async function $r(t,e,s=!0,r={}){let n=await Lr(t,e,s,r,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function Ie(t,e,s=!0,r={}){let n=await $r(t,e,s,r);return n===null?{}:JSON.parse(n)}function N0(t,[e,s,r],[n,o],i="bilinear",a=!1){let l=o/r,c=n/s,p=new t.constructor(n*o*e),u=s*r,_=n*o;for(let d=0;d=0;--a)n[a]=l,r[a]=e[s[a]],l*=r[a];let o=s.map((a,l)=>n[s.indexOf(l)]),i=new t.constructor(t.length);for(let a=0;a=0;--c)l+=p%e[c]*o[c],p=Math.floor(p/e[c]);i[l]=t[a]}return[i,r]}function me(t){let e=de(t)[0],s=t.map(o=>Math.exp(o-e)),r=s.reduce((o,i)=>o+i,0);return s.map(o=>o/r)}function rp(t){let e=de(t)[0],s=0;for(let o=0;oo-e-r)}function $0(t,e){let s=0;for(let r=0;re+s*s,0))}function Fr(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],s=0;for(let r=1;re&&(e=t[r],s=r);return[e,s]}function F0(t){return t>0&&(t&t-1)===0}var ma=class{constructor(e){if(this.size=e|0,this.size<=1||!F0(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let r=0;rr;r<<=1)++s;this._width=s%2===0?s-1:s,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return r}toComplexArray(e,s){let r=s||this.createComplexArray();for(let n=0;n>>1],r[n+1]=0;return r}transform(e,s){if(e===s)throw new Error("Input and output buffers must be different");this._transform4(e,s,1)}realTransform(e,s){if(e===s)throw new Error("Input and output buffers must be different");this._realTransform4(e,s,1)}inverseTransform(e,s){if(e===s)throw new Error("Input and output buffers must be different");this._transform4(e,s,-1);for(let r=0;r>=2;i>=2;i>>=2){a=n/i<<1;let _=a>>>2;for(l=0;l>>1,i>>>1)}else for(l=0,c=0;l>>1,i>>>1,r)}let u=this.table;for(i>>=2;i>=2;i>>=2){a=n/i<<1;let d=a>>>1,m=d>>>1,f=m>>>1;for(l=0;l>>1;for(let d=2;d<_;d+=2)e[n-d]=e[d],e[n-d+1]=-e[d+1]}_singleRealTransform2(e,s,r,n,o){let i=e[n],a=e[n+o];s[r]=i+a,s[r+1]=0,s[r+2]=i-a,s[r+3]=0}_singleRealTransform4(e,s,r,n,o,i){let a=o*2,l=o*3,c=e[n],p=e[n+o],u=e[n+a],_=e[n+l],d=c+u,m=c-u,f=p+_,g=i*(p-_);s[r]=d+f,s[r+1]=0,s[r+2]=m,s[r+3]=-g,s[r+4]=d-f,s[r+5]=0,s[r+6]=m,s[r+7]=g}},sp=class{constructor(e){let s=2*(e-1),r=2*(2*e-1),n=2**Math.ceil(Math.log2(r));this.bufferSize=n,this._a=s;let o=new Float64Array(r),i=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let a=-2*Math.PI/e,l=Math.cos(a),c=Math.sin(a);for(let p=0;p>1;++p){let u=(p+1-e)**2/2,_=Math.sqrt(l**2+c**2)**u,d=u*Math.atan2(c,l),m=2*p;o[m]=_*Math.cos(d),o[m+1]=_*Math.sin(d),i[m]=o[m],i[m+1]=-o[m+1]}this._slicedChirpBuffer=o.subarray(s,r),this._f=new ma(n>>1),this._f.transform(this._chirpBuffer,i)}_transform(e,s,r){let n=this._buffer1,o=this._buffer2,i=this._outBuffer1,a=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,p=this._a;if(r)for(let u=0;u>1,m=s[d];n[u]=m*c[u],n[_]=m*c[_]}else for(let u=0;u=t.length&&(l=2*(t.length-1)-l),r[i++]=t[l]}r.sort(),s[o]=r[n]}return s}function os(t,e){let s=Math.pow(10,e);return Math.round(t*s)/s}function D0(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function q0(t){let e=t.length,s=t[0].length,r=[e+1,s+1],n=Array.from({length:r[0]},()=>Array(r[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:r[0]},()=>Array(r[1]).fill(-1));for(let p=1;p0||a>0;)switch(l.push(i-1),c.push(a-1),o[i][a]){case 0:--i,--a;break;case 1:--i;break;case 2:--a;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${i}, ${a}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var j0=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),i=new Uint32Array(o),a=new Float32Array(o);for(let l=0;l>10,_=l&1023;if(u===31)c=p|2139095040|_<<13;else if(u===0)if(_===0)c=p;else{let d=113;for(;(_&1024)===0;)_<<=1,--d;_&=-1025,c=p|d<<23|_<<13}else c=p|u+112<<23|_<<13;i[0]=c,t[l]=a[0]}}let s=e.length,r=t,n=new Float32Array(s);for(let o=0;olA});var lA={};import*as cA from"onnxruntime-web/webgpu";async function B0(t){let e=t.split("/").pop(),s;try{if(s=await at(),s){let n=await s.match(t);if(n)return n}}catch(n){F.warn(`Failed to load ${e} from cache:`,n)}let r=await J.fetch(t);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);if(s)try{await s.put(t,r.clone())}catch(n){F.warn(`Failed to cache ${e}:`,n)}return r}async function U0(t){let e=await B0(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(s){return F.warn("Failed to read WASM binary:",s),null}}async function G0(t){if(K.IS_SERVICE_WORKER_ENV||K.IS_CHROME_AVAILABLE)return t;let e=await B0(t);if(!e||typeof e=="string")return null;try{let s=await e.text();s=s.replaceAll("globalThis.process?.versions?.node","false");let r=new Blob([s],{type:"text/javascript"});return URL.createObjectURL(r)}catch(s){return F.warn("Failed to read WASM factory:",s),null}}import{Tensor as Q0}from"onnxruntime-common";var pA=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function K0(t){return t<=Ge.DEBUG?0:t<=Ge.INFO?2:t<=Ge.WARNING||t<=Ge.ERROR?3:4}var uA={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},et=[],op,Ls,W0=Symbol.for("onnxruntime");if(W0 in globalThis)Ls=globalThis[W0];else if(K.IS_NODE_ENV){switch(Ls=np,process.platform){case"win32":et.push("dml");break;case"linux":process.arch==="x64"&&et.push("cuda");break;case"darwin":et.push("coreml");break}et.push("webgpu"),et.push("cpu"),op=["cpu"]}else Ls=cA,K.IS_WEBNN_AVAILABLE&&et.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),K.IS_WEBGPU_AVAILABLE&&et.push("webgpu"),et.push("wasm"),op=["wasm"];var _A=Ls.InferenceSession;function X0(t=null){if(!t)return op;switch(t){case"auto":return et;case"gpu":return et.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(et.includes(t))return[pA[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${et.join(", ")}.`)}var V0=Promise.resolve(),Ns=null;async function dA(){if(Ns)return Ns;if(!(J.useWasmCache&&typeof Ce?.wasm?.wasmPaths=="object"&&Ce?.wasm?.wasmPaths?.wasm&&Ce?.wasm?.wasmPaths?.mjs)){if(K.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return Ns=Promise.resolve(),Ns}return Ns=(async()=>{let e=Ce.wasm.wasmPaths,s=!1;await Promise.all([e.wasm&&!Jc(e.wasm)?(async()=>{try{let r=await U0(Zc(e.wasm));r&&(Ce.wasm.wasmBinary=r,s=!0)}catch(r){F.warn("Failed to pre-load WASM binary:",r)}})():Promise.resolve(),e.mjs&&!Jc(e.mjs)?(async()=>{try{let r=await G0(Zc(e.mjs));r&&(Ce.wasm.wasmPaths.mjs=r)}catch(r){F.warn("Failed to pre-load WASM factory:",r)}})():Promise.resolve()]),s||(Ce.wasm.wasmPaths.mjs=e.mjs)})(),Ns}async function ga(t,e,s){await dA();let r=K0(J.logLevel??Ge.WARNING),n=()=>_A.create(t,{logSeverityLevel:r,...e}),o=await(K.IS_WEB_ENV?V0=V0.then(n):n());return o.config=s,o}var H0=Promise.resolve();async function xa(t,e){let s=()=>t.run(e);return K.IS_WEB_ENV?H0=H0.then(s):s()}function wa(t){return t instanceof Ls.Tensor}var Ce=Ls?.env;function Rr(){return Ce?.wasm?.proxy}if(Ce){let t=function(e){let s=K0(e);Ce.logLevel=uA[s]};if(Ce.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&Ce.versions?.web&&!Ce.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Ce.versions.web}/dist/`;Ce.wasm.wasmPaths=K.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}Ce.wasm.proxy=!1}Ce.webgpu&&(Ce.webgpu.powerPreference="high-performance"),t(J.logLevel??Ge.WARNING),J.backends.onnx={...Ce,setLogLevel:t}}var Pt=async(t,e,s)=>{let r=await ga(new Uint8Array(t),e);return(async n=>{let o=Rr(),i=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),a=await xa(r,i);return Array.isArray(s)?s.map(l=>new E(a[l])):new E(a[s])})},mt=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Pt([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Pt([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Pt([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Pt([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Pt([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Pt([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Pt([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=Pt([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var Y0=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),ip=K.IS_NODE_ENV?"cpu":"wasm";function ya(t,e,{warn:s}={}){return t?typeof t=="string"?t:t.hasOwnProperty(e)?t[e]:(s&&s(`device not specified for "${e}". Using the default device (${ip}).`),ip):ip}var eb=(function(){let t;return async function(){if(t===void 0)if(!K.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),Oe=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),J0=Oe.fp32,Z0=Object.freeze({[Y0.wasm]:Oe.q8}),Nt=Object.freeze({[Oe.fp32]:"",[Oe.fp16]:"_fp16",[Oe.int8]:"_int8",[Oe.uint8]:"_uint8",[Oe.q8]:"_quantized",[Oe.q4]:"_q4",[Oe.q2]:"_q2",[Oe.q1]:"_q1",[Oe.q4f16]:"_q4f16",[Oe.q2f16]:"_q2f16",[Oe.q1f16]:"_q1f16",[Oe.bnb4]:"_bnb4"});function ba(t,e,s,{configDtype:r=null,warn:n}={}){let o,i=!1;t&&typeof t!="string"?t.hasOwnProperty(e)?o=t[e]:(o=null,i=!0):o=t;let a;if(o===Oe.auto){if(r){let l=typeof r=="string"?r:r?.[e];if(l&&l!==Oe.auto&&Oe.hasOwnProperty(l))return l}a=Z0[s]??J0}else o&&Oe.hasOwnProperty(o)?a=o:a=Z0[s]??J0;return i&&n&&n(`dtype not specified for "${e}". Using the default dtype (${a}) for this device (${s}).`),a}var Lt=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var E=class t{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return wa(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new Q0(e[0],e[1],e[2]),new Proxy(this,{get:(s,r)=>{if(typeof r=="string"){let n=Number(r);if(Number.isInteger(n))return s._getitem(n)}return s[r]},set:(s,r,n)=>s[r]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...s]=this.dims;if(s.length>0){let r=s.reduce((n,o)=>n*o);for(let n=0;n0){let n=r.reduce((o,i)=>o*i);return this._subarray(e,n,r)}else return new t(this.type,[this.data[e]],r)}indexOf(e){let s=this.data;for(let r=0;rd)throw new Error(`Invalid slice: ${u}`);let m=[Math.max(_,0),Math.min(d,this.dims[p])];r.push(m),s.push(m[1]-m[0])}else throw new Error(`Invalid slice: ${u}`)}let n=r.map(([p,u])=>u-p),o=n.reduce((p,u)=>p*u),i=this.data,a=new i.constructor(o),l=this.stride(),c=!0;for(let p=1;p=0;--_){let m=n[_];u+=(d%m+r[_][0])*l[_],d=Math.floor(d/m)}a[p]=i[u]}return new t(this.type,a,s)}permute(...e){return mA(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,s=!1){return this.norm(1,e,s)}norm(e="fro",s=null,r=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let i,a;if(o?(i=(u,_)=>u+_,a=0n):(i=(u,_)=>u+_**e,a=0),s===null){let u=n.reduce(i,a);return e!==1&&(u=u**(1/e)),new t(this.type,[u],[])}let[l,c,p]=Dr(i,this,s,r);if(e!==1)for(let u=0;u=0;--l){let u=this.dims[l];if(l!==s){let _=c%u;a+=_*p,p*=this.dims[l]}c=Math.floor(c/u)}n[i]/=o[a]}return this}normalize(e=2,s=1){return this.clone().normalize_(e,s)}stride(){return ap(this.dims)}squeeze(e=null){return new t(this.type,this.data,tb(this.dims,e))}squeeze_(e=null){return this.dims=tb(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,sb(this.dims,e))}unsqueeze_(e){return this.dims=sb(this.dims,e),this}flatten_(e=0,s=-1){s=(s+this.dims.length)%this.dims.length;let r=this.dims.slice(0,e),n=this.dims.slice(e,s+1),o=this.dims.slice(s+1);return this.dims=[...r,n.reduce((i,a)=>i*a,1),...o],this}flatten(e=0,s=-1){return this.clone().flatten_(e,s)}view(...e){let s=-1;for(let n=0;na!==s?o*i:o,1);e[s]=r.length/n}return new t(this.type,r,e)}neg_(){let e=this.data;for(let s=0;se?1:0;return new t("bool",s,this.dims)}lt(e){let s=new Uint8Array(this.data.length),r=this.data;for(let n=0;nMath.min(i,a),this,e,s,1/0);return new t(r,n,o)}max(e=null,s=!1){if(e===null){let i=de(this.data)[0];return new t(this.type,[i],[])}let[r,n,o]=Dr((i,a)=>Math.max(i,a),this,e,s,-1/0);return new t(r,n,o)}argmin(e=null,s=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let r=Fr(this.data)[1];return new t("int64",[BigInt(r)],[])}argmax(e=null,s=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let r=de(this.data)[1];return new t("int64",[BigInt(r)],[])}repeat(...e){if(e.lengthp===1)){if(e.length===this.dims.length)return this.clone();let p=e.length-this.dims.length,u=Array(p).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),u)}let s=e.length-this.dims.length,r=Array(s).fill(1).concat(this.dims),n=r.map((p,u)=>p*e[u]),o=n.reduce((p,u)=>p*u,1),i=this.data,a=new i.constructor(o),l=ap(r),c=ap(n);for(let p=0;pBigInt(Math.floor(o)):s=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,j0(this.data),this.dims);return new t(e,Lt[e].from(this.data,s),this.dims)}};function fA(t,e){let s=t.length,r=e.reduce((o,i)=>o*i);if(s!==r)throw Error(`cannot reshape array of size ${s} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((i,a)=>{let l=i[i.length-1];return l.lengthnew E("int64",t,[t.length]);async function va(t,e,s,r,n){return await(await mt.slice)({x:t,s:ka(e),e:ka(s),a:ka(r),t:ka(n??new Array(r.length).fill(1))})}function nb(t,e){let s=t.data,r=e.data,n=[t.dims[0],t.dims[2]],o=new s.constructor(n[0]*n[1]),[i,a,l]=t.dims,c=0;for(let p=0;ps!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((s,r)=>s!==1||!e.includes(r))),t}function sb(t,e){return e=ht(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function ht(t,e,s=null,r=!0){if(t<-e||t>=e){if(r)throw new Error(`IndexError: index ${t} is out of bounds for dimension${s===null?"":" "+s} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function ie(t,e=0){e=ht(e,t[0].dims.length);let s=t[0].dims.slice();s[e]=t.reduce((i,a)=>i+a.dims[e],0);let r=s.reduce((i,a)=>i*a,1),n=new t[0].data.constructor(r),o=t[0].type;if(e===0){let i=0;for(let a of t){let l=a.data;n.set(l,i),i+=l.length}}else{let i=0;for(let a=0;a=0;--_){let f=c[_],g=d%f;_===e&&(g+=i),u+=g*m,m*=s[_],d=Math.floor(d/f)}n[u]=l[p]}i+=c[e]}}return new E(o,n,s)}function qe(t,e=0){return ie(t.map(s=>s.unsqueeze(e)),e)}function Dr(t,e,s,r=!1,n=null){let o=e.data,i=e.dims;s=ht(s,i.length);let a=i.slice();a[s]=1;let l=new o.constructor(o.length/i[s]);n!==null&&l.fill(n);for(let c=0;c=0;--u){let m=i[u];if(u!==s){let f=_%m;p+=f*d,d*=a[u]}_=Math.floor(_/m)}l[p]=t(l[p],o[c],c,p)}return r||a.splice(s,1),[e.type,l,a]}function cp(t,e=null,s=1,r=!1){let n=t.data,o=t.dims;if(e===null){let d=n.reduce((w,x)=>w+x,0)/n.length,m=Math.sqrt(n.reduce((w,x)=>w+(x-d)**2,0)/(n.length-s)),f=new E(t.type,[d],[]);return[new E(t.type,[m],[]),f]}e=ht(e,o.length);let i=Ea(t,e,r),a=i.data,[l,c,p]=Dr((_,d,m,f)=>_+(d-a[f])**2,t,e,r);for(let _=0;_c+p,0);return new E(t.type,[l/n.length],[])}e=ht(e,r.length);let[o,i,a]=Dr((l,c)=>l+c,t,e,s);if(r[e]!==1)for(let l=0;l=0;--s)e[s]=r,r*=t[s];return e}function pp(t,e,s,r){let n=t.reduce((o,i)=>o*i,1);return new E(s,new r(n).fill(e),t)}function ve(t,e){let s,r;if(typeof e=="number")s="float32",r=Float32Array;else if(typeof e=="bigint")s="int64",r=BigInt64Array;else if(typeof e=="boolean")s="bool",r=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return pp(t,e,s,r)}function qr(t,e){return ve(t.dims,e)}function Me(t){return pp(t,1n,"int64",BigInt64Array)}function Aa(t){return Me(t.dims)}function up(t){return pp(t,0n,"int64",BigInt64Array)}function _p(t){return up(t.dims)}function aI(t){let e=t.reduce((s,r)=>s*r,1);return new E("float32",Float32Array.from({length:e},()=>ns.random()),t)}function ob(t){let e=t.reduce((s,r)=>s*r,1);return new E("float32",Float32Array.from({length:e},()=>ns.gauss()),t)}function ib(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let s=e==="binary",r=s?"int8":"uint8",n=s?Int8Array:Uint8Array,o=t.data,i=new n(o.length/8);for(let a=0;a0?1:0,c=Math.floor(a/8),p=a%8;i[c]|=l<<7-p,s&&p===0&&(i[c]-=128)}return new E(r,i,[t.dims[0],t.dims[1]/8])}async function $s(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await We(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function dp(t,e){let s=await $s(t);return await Promise.all(s.map(r=>Ie(t,r,!0,e)))}function jr(t){let e=t.dims;switch(e.length){case 1:return t.tolist();case 2:if(e[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return t.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${e.length}.`)}}var hA=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function gA(t,e,s,r){for(let n of Object.keys(t)){let o=e-t[n].length,i=s(n),a=new Array(o).fill(i);t[n]=r==="right"?Re(t[n],a):Re(a,t[n])}}function xA(t,e){for(let s of Object.keys(t))t[s].length=e}function is(t,...e){for(let s of e){if(!Object.hasOwn(t,s))continue;let r=t[s];if(r)if(typeof r=="object"){if(r.__type==="AddedToken")return r.content;throw Error(`Unknown token: ${r}`)}else return r}return null}function wA(t){let e=[];for(let s of t.get_added_tokens_decoder().values())s.special&&e.push(s);return e}var P=class extends xe{return_token_type_ids=!1;padding_side="right";constructor(e,s){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=s,this._tokenizer=new p0(e,s),this.config=s,this.padding_side=s.padding_side??this.padding_side,this.mask_token=is(s,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=is(s,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=is(s,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=is(s,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=is(s,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=is(s,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=s.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:i}of this.chat_template){if(typeof o!="string"||typeof i!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=i}this.chat_template=n}this._compiled_template_cache=new Map;let r=wA(this._tokenizer);this.all_special_ids=r.map(n=>n.id),this.all_special_tokens=r.map(n=>n.content)}static async from_pretrained(e,{progress_callback:s=null,config:r=null,cache_dir:n=null,local_files_only:o=!1,revision:i="main"}={}){let a=await dp(e,{progress_callback:s,config:r,cache_dir:n,local_files_only:o,revision:i});return new this(...a)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(s=>this._tokenizer.token_to_id(s))}_call(e,s={}){let{text_pair:r=null,add_special_tokens:n=!0,padding:o=!1,return_token_type_ids:i=null}=s,{truncation:a=null,max_length:l=null}=s,c=s.return_tensor??!0,p=Array.isArray(e),u;if(p){if(e.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(e.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");u=e.map((d,m)=>this._encode_plus(d,{text_pair:r[m],add_special_tokens:n,return_token_type_ids:i}))}else u=e.map(d=>this._encode_plus(d,{add_special_tokens:n,return_token_type_ids:i}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");u=[this._encode_plus(e,{text_pair:r,add_special_tokens:n,return_token_type_ids:i})]}if(l===null?l=this.model_max_length:a===null&&(o===!0?(F.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):o===!1&&(F.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),a=!0)),o===!0&&(l=Math.min(de(u.map(d=>d.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),o||a)for(let d=0;dl?a&&xA(u[d],l):o&&gA(u[d],l,m=>m==="input_ids"?this.pad_token_id:0,this.padding_side));let _={};if(c){if(!(o&&a)&&u.some(m=>{for(let f of Object.keys(m))if(m[f].length!==u[0][f]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let d=[u.length,u[0].input_ids.length];for(let m of Object.keys(u[0]))_[m]=new E("int64",BigInt64Array.from(u.flatMap(f=>f[m]).map(BigInt)),d)}else{for(let d of Object.keys(u[0]))_[d]=u.map(m=>m[d]);if(!p)for(let d of Object.keys(_))_[d]=_[d][0]}return _}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:s=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:i,token_type_ids:a}=this._tokenizer.encode(e,{text_pair:s,add_special_tokens:r,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:i,...a?{token_type_ids:a}:{}}}tokenize(e,{pair:s=null,add_special_tokens:r=!1}={}){return this._tokenizer.tokenize(e,{text_pair:s,add_special_tokens:r})}encode(e,{text_pair:s=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:s,add_special_tokens:r,return_token_type_ids:n}).ids}batch_decode(e,s={}){return e instanceof E&&(e=e.tolist()),e.map(r=>this.decode(r,s))}decode(e,s={}){if(e instanceof E&&(e=jr(e)),!Array.isArray(e)||e.length===0||!Vy(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,s)}decode_single(e,{skip_special_tokens:s=!1,clean_up_tokenization_spaces:r=null}){return this._tokenizer.decode(e,{skip_special_tokens:s,clean_up_tokenization_spaces:r})}get_chat_template({chat_template:e=null,tools:s=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let r=this.chat_template;if(e!==null&&Object.hasOwn(r,e))e=r[e];else if(e===null)if(s!==null&&"tool_use"in r)e=r.tool_use;else if("default"in r)e=r.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(r).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,s={}){let{tools:r=null,documents:n=null,chat_template:o=null,add_generation_prompt:i=!1,tokenize:a=!0,padding:l=!1,truncation:c=!1,max_length:p=null,return_tensor:u=!0,return_dict:_=!0,tokenizer_kwargs:d={},...m}=s;if(o=this.get_chat_template({chat_template:o,tools:r}),typeof o!="string")throw Error(`chat_template must be a string, but got ${typeof o}`);let f=this._compiled_template_cache.get(o);f===void 0&&(f=new k0(o),this._compiled_template_cache.set(o,f));let g=Object.create(null);for(let x of hA){let y=is(this.config,x);y&&(g[x]=y)}let w=f.render({messages:e,add_generation_prompt:i,tools:r,documents:n,...g,...m});if(a){let x=this._call(w,{add_special_tokens:!1,padding:l,truncation:c,max_length:p,return_tensor:u,...d});return _?x:x.input_ids}return w}};function Fs(t,e,s,r){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=r.src_lang,o=r.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let i of t._tokenizer.post_processor.config.single)if("SpecialToken"in i&&t.languageRegex.test(i.SpecialToken.id)){i.SpecialToken.id=t.lang_to_token(n);break}}return r.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,s)}var ou={};Os(ou,{AlbertTokenizer:()=>fp,AutoTokenizer:()=>W,BartTokenizer:()=>mp,BertTokenizer:()=>hp,BlenderbotSmallTokenizer:()=>gp,BlenderbotTokenizer:()=>xp,BloomTokenizer:()=>wp,CLIPTokenizer:()=>bp,CamembertTokenizer:()=>yp,CodeGenTokenizer:()=>vp,CodeLlamaTokenizer:()=>kp,CohereAsrTokenizer:()=>Ap,CohereTokenizer:()=>Ep,ConvBertTokenizer:()=>Mp,DebertaTokenizer:()=>Op,DebertaV2Tokenizer:()=>Sp,DistilBertTokenizer:()=>Ip,ElectraTokenizer:()=>zp,EsmTokenizer:()=>Tp,FalconTokenizer:()=>Cp,GPT2Tokenizer:()=>Lp,GPTNeoXTokenizer:()=>Np,GemmaTokenizer:()=>Pp,HerbertTokenizer:()=>$p,LlamaTokenizer:()=>Fp,M2M100Tokenizer:()=>Rp,MBart50Tokenizer:()=>qp,MBartTokenizer:()=>Br,MPNetTokenizer:()=>Up,MarianTokenizer:()=>Dp,MgpstrTokenizer:()=>jp,MobileBertTokenizer:()=>Bp,NllbTokenizer:()=>Gp,NougatTokenizer:()=>Wp,PreTrainedTokenizer:()=>P,Qwen2Tokenizer:()=>Vp,RoFormerTokenizer:()=>Kp,RobertaTokenizer:()=>Hp,SiglipTokenizer:()=>Xp,SpeechT5Tokenizer:()=>Qp,SqueezeBertTokenizer:()=>Yp,T5Tokenizer:()=>Jp,TokenizersBackend:()=>P,VitsTokenizer:()=>eu,Wav2Vec2CTCTokenizer:()=>tu,WhisperTokenizer:()=>su,XLMRobertaTokenizer:()=>ru,XLMTokenizer:()=>nu});var fp=class extends P{return_token_type_ids=!0};var mp=class extends P{};var hp=class extends P{return_token_type_ids=!0};var gp=class extends P{};var xp=class extends P{};var wp=class extends P{};var yp=class extends P{};var bp=class extends P{};var kp=class extends P{};var vp=class extends P{};var Ep=class extends P{};var Ap=class extends P{};var Mp=class extends P{return_token_type_ids=!0};var Sp=class extends P{return_token_type_ids=!0};var Op=class extends P{return_token_type_ids=!0};var Ip=class extends P{};var zp=class extends P{return_token_type_ids=!0};var Tp=class extends P{};var Cp=class extends P{};var Pp=class extends P{};var Np=class extends P{};var Lp=class extends P{};var $p=class extends P{return_token_type_ids=!0};var Fp=class extends P{padding_side="left"};var Rp=class extends P{constructor(e,s){super(e,s),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`}_build_translation_inputs(e,s,r){return Fs(this,e,s,r)}};var Dp=class extends P{constructor(e,s){super(e,s),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(r=>this.languageRegex.test(r)),F.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[s,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(s);if(r.length===2){let[n,o]=r;return this.supported_language_codes.includes(n)||F.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Re([n],super._encode_text(o))}}};var Br=class extends P{constructor(e,s){super(e,s),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r),this.lang_to_token=r=>r}_build_translation_inputs(e,s,r){return Fs(this,e,s,r)}};var qp=class extends Br{};var jp=class extends P{};var Bp=class extends P{return_token_type_ids=!0};var Up=class extends P{};var Gp=class extends P{constructor(e,s){super(e,s),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,s,r){return Fs(this,e,s,r)}};var Wp=class extends P{};var Vp=class extends P{};var Hp=class extends P{};var Kp=class extends P{return_token_type_ids=!0};var Xp=class extends P{};var Qp=class extends P{};var Yp=class extends P{return_token_type_ids=!0};var Jp=class extends P{};var Zp=class extends Je{decode_chain(e){let s="";for(let r=1;r[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function lb(t){t=t.toLowerCase();let e=yA.get(t);if(e===void 0){let s=t.match(/^<\|([a-z]{2})\|>$/);if(s&&(t=s[1]),Ur.has(t))e=t;else{let n=t.length===2?Ur.keys():Ur.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var bA="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",cb=new RegExp(`^[${bA}]+$`,"gu"),kA=.1,su=class extends P{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:s=!1,return_language:r=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let i=null,a=s==="word";function l(){return{language:i,timestamp:[null,null],text:""}}let c=[],p=l(),u=0,_=this.timestamp_begin,m=_+1500,f=[],g=[],w=!1,x=null,y=new Set(this.all_special_ids);for(let k of e){let S=k.tokens,I=a?k.token_timestamps:null,$=null,C=_;if("stride"in k){let[H,j,B]=k.stride;if(u-=j,x=H-B,j&&(C=j/n+_),B)for(let Z=S.length-1;Z>=0;--Z){let D=Number(S[Z]);if(D>=_){if($!==null&&(D-_)*n=_&&j<=m){let B=(j-_)*n+u,Z=os(B,2);if($!==null&&j>=$)w=!0;else if(w||f.length>0&&j0&&p.timestamp[1]!==null))for(let T of p.words)T.timestamp[1]>p.timestamp[1]&&p.timestamp[1]>=T.timestamp[0]&&(T.timestamp[1]=p.timestamp[1]);c.push(p),f=[],R=[],g=[],V=[],p=l()}}else if(R.push(j),a){let B=os(I[H]+u,2),Z;if(H+10?(f.push(R),a&&g.push(V)):f.every(H=>H.length===0)&&(p=l(),f=[],R=[],g=[],V=[])}if(f.length>0){if(o&&s)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[k,S]=this.findLongestCommonSequence(f,g),I=this.decode(k);p.text=I,a&&(p.words=this.collateWordTimestamps(k,S,i)),c.push(p)}let b=Object.create(null),v=c.map(k=>k.text).join("");if(s||r){for(let k=0;k0,a=i?[]:null,l=i?s[0]:null;for(let c=1;cj===C[B]&&l[v+B][0]-kA<=s[c][I+B][0]).length:R=S.filter((j,B)=>j===C[B]).length;let V=b/1e4,H=R/b+V;R>1&&H>u&&(u=H,_=[v,k,I,$])}let[m,f,g,w]=_,x=Math.floor((f+m)/2),y=Math.floor((w+g)/2);if(i&&u===0&&n>0){let b=l[n-1][0],v=s[c].findIndex(k=>k[0]>=b);y=v===-1?p.length:v}o.push(...r.slice(0,x)),r=p.slice(y),n=r.length,i&&(a.push(...l.slice(0,x)),l=s[c].slice(y))}return o.push(...r),i?(a.push(...l),[o,a]):[o,[]]}collateWordTimestamps(e,s,r){let[n,o,i]=this.combineTokensIntoWords(e,r),a=[];for(let l=0;l=n){let a=((i-n)*r).toFixed(2);o.push(`<|${a}|>`),o.push([])}else o[o.length-1].push(i);return o=o.map(i=>typeof i=="string"?i:super.decode(i,s)),o.join("")}splitTokensOnUnicode(e){let s=this.decode(e,{decode_with_timestamps:!0}),r="\uFFFD",n=[],o=[],i=[],a=[],l=[],c=0;for(let p=0;p=this._tokenizer.token_to_id("<|endoftext|>"),d=c.startsWith(" "),m=c.trim(),f=cb.test(m);if(_||d||f||o.length===0)o.push(c),i.push(p),a.push(u);else{let g=o.length-1;o[g]+=c,i[g].push(...p),a[g].push(...u)}}return[o,i,a]}mergePunctuations(e,s,r,n,o){let i=structuredClone(e),a=structuredClone(s),l=structuredClone(r),c=i.length-2,p=i.length-1;for(;c>=0;)i[c].startsWith(" ")&&n.includes(i[c].trim())?(i[p]=i[c]+i[p],a[p]=Re(a[c],a[p]),l[p]=Re(l[c],l[p]),i[c]="",a[c]=[],l[c]=[]):p=c,--c;for(c=0,p=1;pu),a.filter(u=>u.length>0),l.filter(u=>u.length>0)]}};var ru=class extends P{};var nu=class extends P{return_token_type_ids=!0;constructor(e,s){super(e,s),F.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var W=class{static async from_pretrained(e,{progress_callback:s=null,config:r=null,cache_dir:n=null,local_files_only:o=!1,revision:i="main"}={}){let[a,l]=await dp(e,{progress_callback:s,config:r,cache_dir:n,local_files_only:o,revision:i}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=ou[c];return p||(F.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=P),new p(a,l)}};var $t="https://github.com/huggingface/transformers.js/issues/new/choose";var Gr="preprocessor_config.json",bt=Gr,Ma="processor_config.json",Sa="chat_template.jinja";var U=class extends xe{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,s,r){super(),this.config=e,this.components=s,this.chat_template=r}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,s={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...s})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...s){for(let r of[this.image_processor,this.feature_extractor,this.tokenizer])if(r)return r(e,...s);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,s={}){let[r,n,o]=await Promise.all([this.uses_processor_config?Ie(e,Ma,!0,s):{},Promise.all(this.classes.filter(i=>i in this).map(async i=>{let a=await this[i].from_pretrained(e,s);return[i.replace(/_class$/,""),a]})).then(Object.fromEntries),this.uses_chat_template_file?$r(e,Sa,!0,s):null]);return new this(r,n,o)}};var Za={};Os(Za,{ChatterboxProcessor:()=>bu,CohereAsrProcessor:()=>ku,Florence2Processor:()=>f_,Gemma3Processor:()=>m_,Gemma3nProcessor:()=>h_,Gemma4Processor:()=>g_,Glm46VProcessor:()=>x_,GraniteSpeechProcessor:()=>w_,GroundingDinoProcessor:()=>y_,Idefics3Processor:()=>Xa,JinaCLIPProcessor:()=>k_,Lfm2VlProcessor:()=>v_,LlavaProcessor:()=>E_,MgpstrProcessor:()=>A_,MoonshineProcessor:()=>M_,OwlViTProcessor:()=>S_,PaliGemmaProcessor:()=>O_,Phi3VProcessor:()=>I_,PixtralProcessor:()=>z_,Processor:()=>U,PyAnnoteProcessor:()=>T_,Qwen2VLProcessor:()=>ls,Qwen2_5_VLProcessor:()=>sn,Qwen3VLProcessor:()=>C_,Sam2Processor:()=>Qa,Sam2VideoProcessor:()=>P_,SamProcessor:()=>rn,SmolVLMProcessor:()=>Xa,SpeechT5Processor:()=>N_,UltravoxProcessor:()=>L_,VLChatProcessor:()=>b_,VoxtralProcessor:()=>$_,VoxtralRealtimeProcessor:()=>R_,Wav2Vec2Processor:()=>D_,Wav2Vec2ProcessorWithLM:()=>q_,WhisperProcessor:()=>j_});var le=class extends xe{constructor(e){super(),this.config=e}static async from_pretrained(e,s={}){let r=await Ie(e,Gr,!0,s);return new this(r)}};function ce(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var Jr={};Os(Jr,{ASTFeatureExtractor:()=>lu,ChatterboxFeatureExtractor:()=>cu,ClapFeatureExtractor:()=>pu,CohereAsrFeatureExtractor:()=>uu,DacFeatureExtractor:()=>Kr,EncodecFeatureExtractor:()=>Vr,FeatureExtractor:()=>le,Gemma3nAudioFeatureExtractor:()=>Xr,Gemma4AudioFeatureExtractor:()=>Qr,GraniteSpeechFeatureExtractor:()=>_u,MoonshineFeatureExtractor:()=>du,ParakeetFeatureExtractor:()=>Hr,PyAnnoteFeatureExtractor:()=>Yr,SeamlessM4TFeatureExtractor:()=>fu,SnacFeatureExtractor:()=>mu,SpeechT5FeatureExtractor:()=>hu,VoxtralRealtimeFeatureExtractor:()=>wu,Wav2Vec2FeatureExtractor:()=>gu,WeSpeakerFeatureExtractor:()=>xu,WhisperFeatureExtractor:()=>yu});var vA=()=>{};var pb={fromWeb:vA};var EA=()=>{};var ub=EA;async function Oa(t,e){if(K.IS_BROWSER_ENV){if(K.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let s=URL.createObjectURL(e),r=document.createElement("a");r.href=s,r.download=t,r.click(),r.remove(),URL.revokeObjectURL(s)}else if(K.IS_FS_AVAILABLE){let s=e.stream(),r=pb.fromWeb(s),n=Fe.createWriteStream(t);await ub(r,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function fb(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let s=await(await zt(t)).arrayBuffer(),r=new AudioContext({sampleRate:e});typeof e>"u"&&F.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);let n=await r.decodeAudioData(s),o;if(n.numberOfChannels===2){let i=Math.sqrt(2),a=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(a.length);for(let c=0;c2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,s=15,r=27/Math.log(6.4))=>t>=e?s+Math.log(t/e)*r:3*t/200};function iu(t,e="htk"){let s=MA[e];if(!s)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?s(t):t.map(r=>s(r))}var SA={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,s=15,r=Math.log(6.4)/27)=>t>=s?e*Math.exp(r*(t-s)):200*t/3};function OA(t,e="htk"){let s=SA[e];if(!s)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?s(t):t.map(r=>s(r))}function IA(t,e){let s=Float64Array.from({length:e.length-1},(i,a)=>e[a+1]-e[a]),r=Array.from({length:t.length},()=>new Array(e.length));for(let i=0;inew Array(t.length));for(let i=0;it+r*o)}function Pe(t,e,s,r,n,o=null,i="htk",a=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(s>r)throw new Error(`Require min_frequency: ${s} <= max_frequency: ${r}`);let l=iu(s,i),c=iu(r,i),p=db(l,c,e+2),u=OA(p,i),_;if(a){let m=n/((t-1)*2);_=iu(Float64Array.from({length:t},(f,g)=>g*m),i),u=p}else _=db(0,Math.floor(n/2),t);let d=IA(_,u);if(o!==null&&o==="slaney")for(let m=0;mn)throw Error(`frame_length (${s}) may not be larger than fft_length (${n})`);if($!==s)throw new Error(`Length of the window (${$}) must equal frame_length (${s})`);if(r<=0)throw new Error("hop_length must be greater than zero");if(o===null&&u!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!p)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(i){let G=Math.floor(s/2);switch(a){case"reflect":{t=zA(t,G,G);break}case"constant":{let ee=new t.constructor(t.length+2*G);ee.set(t,G),t=ee;break}case"semicausal":{let ee=new t.constructor(t.length+G);ee.set(t,G),t=ee;break}default:throw new Error(`pad_mode="${a}" not implemented yet.`)}}let C=Math.floor(1+Math.floor((t.length-s)/r));y!==null&&CC?v&&(H=b):H=V=b);let j=new ha(n),B=new Float64Array(n),Z=new Float64Array(j.outputBufferSize),D=new Float32Array(R*H);for(let G=0;G=1;--re)B[re]-=c*B[re-1];B[0]*=1-c}for(let re=0;reMath.pow(c,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(s&&(i=i.subarray(0,t)),r===null||t===r)return i;if(t>r)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${r})`);let a=new Float64Array(r),l=n?Math.floor((r-t)/2):0;return a.set(i,l),a}function PA(t,e){let s=t.reduce((o,i)=>o+i.length,0),r=new ArrayBuffer(44),n=new DataView(r);return Ia(n,0,"RIFF"),n.setUint32(4,36+s*4,!0),Ia(n,8,"WAVE"),Ia(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,e,!0),n.setUint32(28,e*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),Ia(n,36,"data"),n.setUint32(40,s*4,!0),new Blob([r,...t.map(o=>o.buffer)],{type:"audio/wav"})}function Ia(t,e,s){for(let r=0;rn+o.length,0),s=new Float32Array(e),r=0;for(let n of this.audio)s.set(n,r),r+=n.length;return s}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),PA(e,this.sampling_rate)}async save(e){return Oa(e,this.toBlob())}};var lu=class extends le{constructor(e){super(e);let s=this.config.sampling_rate,r=Pe(257,this.config.num_mel_bins,20,Math.floor(s/2),s,null,"kaldi",!0);this.mel_filters=r,this.window=Le(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,s){return ze(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:s,transpose:!0})}async _call(e){ce(e,"ASTFeatureExtractor");let s=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let r=this.std*2,n=s.data;for(let o=0;o0)if(r==="rand_trunc"){i=!0;let l=Math.floor(ns.random()*(a+1));e=e.subarray(l,l+s),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${r}" not implemented`);else{if(a<0){let l=new Float64Array(s);if(l.set(e),n==="repeat")for(let c=e.length;c=1;--n)e[n]-=s*e[n-1];return await ze(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){ce(e,"ParakeetFeatureExtractor");let s=await this._extract_fbank_features(e),r=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=s.data;n.fill(0,r*s.dims[1]);let[o,i]=s.dims,a=new Float64Array(i),l=new Float64Array(i);for(let u=0;u1?r-1:1;for(let u=0;u=p){l.push(e.slice(c,p));break}let u=Math.max(c,c+i-a),_=Math.min(c+i,p),d;_<=u?d=c+i:d=this._find_split_point_energy(e,u,_,n),d=Math.max(c+1,Math.min(d,p)),l.push(e.slice(c,d)),c=d}return l}_find_split_point_energy(e,s,r,n){let o=r-s;if(o<=n)return Math.floor((s+r)/2);let i=1/0,a=s,l=o-n;for(let c=0;c<=l;c+=n){let p=0;for(let u=0;us&&(e=e.slice(0,s)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let i=await this._extract_fbank_features(e,this.config.max_length),a=ve([1,i.dims[0]],!0);return{input_features:i.unsqueeze_(0),input_features_mask:a}}};var Qr=class extends Xr{async _extract_fbank_features(e,s){let{frame_length:r,hop_length:n,fft_length:o}=this.config,i=Math.floor(r/2),a=Math.floor((e.length+i-(r+1))/n)+1;return ze(e,this.window,r,n,{fft_length:o,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:a})}async _call(e,s={}){ce(e,"Gemma4AudioFeatureExtractor");let r=e.length,n=await super._call(e,s),{input_features:o}=n,[,i,a]=o.dims,{frame_length:l,hop_length:c}=this.config,p=Math.floor(l/2),u=l+1,_=new Uint8Array(r+p+(s.pad_to_multiple_of??128));_.fill(1,p,p+r);let d=new Uint8Array(i);for(let f=0;f({id:l,start:c*r,end:p*r,confidence:u/(p-c)})))}return n}};var fu=class extends le{constructor(e){super(e);let s=this.config.sampling_rate,r=Pe(257,this.config.num_mel_bins,20,Math.floor(s/2),s,null,"kaldi",!0);this.mel_filters=r,this.window=Le(400,"povey",{periodic:!1})}async _extract_fbank_features(e,s){return e=e.map(r=>r*32768),ze(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:s,transpose:!0})}async _call(e,{padding:s=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){ce(e,"SeamlessM4TFeatureExtractor");let i=await this._extract_fbank_features(e,this.config.max_length);if(n){let[m,f]=i.dims,g=i.data;for(let w=0;w0){let x=new Float32Array(f*(m+w));x.set(g),x.fill(this.config.padding_value,g.length);let y=m+w;i=new E(i.type,x,[y,f]),o&&(a=new E("int64",new BigInt64Array(y),[1,y]),a.data.fill(1n,0,m))}}let[l,c]=i.dims,p=this.config.stride;if(l%p!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${p}).`);let _=i.view(1,Math.floor(l/p),c*p),d={input_features:_};if(o){let m=_.dims[1],f=new BigInt64Array(m);if(a){let g=a.data;for(let w=1,x=0;wo+i,0)/e.length,n=e.reduce((o,i)=>o+(i-r)**2,0)/e.length;return e.map(o=>(o-r)/Math.sqrt(n+1e-7))}async _call(e){ce(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let s=e;this.config.do_normalize&&(s=this._zero_mean_unit_var_norm(s));let r=[1,s.length];return{input_values:new E("float32",s,r),attention_mask:new E("int64",new BigInt64Array(s.length).fill(1n),r)}}};var xu=class extends le{constructor(e){super(e);let s=this.config.sampling_rate,r=Pe(257,this.config.num_mel_bins,20,Math.floor(s/2),s,null,"kaldi",!0);this.mel_filters=r,this.window=Le(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(s=>s*32768),ze(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){ce(e,"WeSpeakerFeatureExtractor");let s=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let r=s.mean(1).data,n=s.data,[o,i,a]=s.dims;for(let l=0;ln?(e.length>this.config.n_samples&&F.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),r=e.slice(0,n)):(r=new Float32Array(n),r.set(e)),{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}};var ge=class{static async from_pretrained(e,s={}){let r=await Ie(e,Gr,!0,s),n=r.feature_extractor_type,o=Jr[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${$t}.`);return new o(r)}};var bu=class extends U{static tokenizer_class=W;static feature_extractor_class=ge;async _call(e,s=null){let r=this.tokenizer(e),n=s?await this.feature_extractor(s):{};return{...r,...n}}};var LA=new Set(["ja","zh"]),ku=class extends U{static tokenizer_class=W;static feature_extractor_class=ge;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let s=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(s)}static join_chunks(e,s="en"){let r=e.filter(i=>i&&i.trim());if(r.length===0)return"";let n=LA.has(s)?"":" ";return[r[0].trimEnd(),...r.slice(1).map(i=>i.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}};var za={};var as,gb,Ft;if(K.IS_WEB_ENV)as=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},Ft=self.createImageBitmap,gb=self.ImageData;else if(za)Ft=async t=>{let s=(await t.metadata()).channels,{data:r,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Ee(new Uint8ClampedArray(r),n.width,n.height,n.channels);return s!==void 0&&s!==n.channels&&o.convert(s),o};else throw new Error("Unable to load image processing library.");var $A={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},FA=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Ee=class t{constructor(e,s,r,n){this.data=e,this.width=s,this.height=r,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!K.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let r=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(r,e.width,e.height,4)}static async fromURL(e){let s=await zt(e);if(s.status!==200)throw new Error(`Unable to read image from "${e}" (${s.status} ${s.statusText})`);let r=await s.blob();return this.fromBlob(r)}static async fromBlob(e){if(K.IS_WEB_ENV){let s=await Ft(e),r=as(s.width,s.height).getContext("2d");return r.drawImage(s,0,0),new this(r.getImageData(0,0,s.width,s.height).data,s.width,s.height,4)}else{let s=za(await e.arrayBuffer());return await Ft(s)}}static fromTensor(e,s="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(s==="CHW")e=e.transpose(1,2,0);else if(s!=="HWC")throw new Error(`Unsupported channel format: ${s}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let s=0,r=0;s=0?l=r:p=-r,n>=0?c=n:u=-n,a.drawImage(i,l,c,e,s,p,u,e,s),new t(a.getImageData(0,0,e,s).data,e,s,4).convert(o)}else{let o=this.toSharp();if(r>=0&&n>=0)o=o.extract({left:Math.floor(r),top:Math.floor(n),width:e,height:s});else if(r<=0&&n<=0){let i=Math.floor(-n),a=Math.floor(-r);o=o.extend({top:i,left:a,right:e-this.width-a,bottom:s-this.height-i})}else{let i=[0,0],a=0;n<0?(i[0]=Math.floor(-n),i[1]=s-this.height-i[0]):a=Math.floor(n);let l=[0,0],c=0;r<0?(l[0]=Math.floor(-r),l[1]=e-this.width-l[0]):c=Math.floor(r),o=o.extend({top:i[0],bottom:i[1],left:l[0],right:l[1]}).extract({left:c,top:a,width:e,height:s})}return await Ft(o)}}async toBlob(e="image/png",s=1){if(!K.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:s})}toTensor(e="CHW"){let s=new E("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")s=s.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return s}toCanvas(){if(!K.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),s=as(e.width,e.height),r=new gb(e.data,e.width,e.height);return s.getContext("2d").putImageData(r,0,0),s}split(){let{data:e,width:s,height:r,channels:n}=this,o=e.constructor,i=e.length/n,a=Array.from({length:n},()=>new o(i));for(let l=0;lnew t(l,s,r,1))}_update(e,s,r,n=null){return this.data=e,this.width=s,this.height=r,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(K.IS_WEB_ENV){if(K.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let s=e.split(".").pop().toLowerCase(),r=FA.get(s)??"image/png",n=await this.toBlob(r);return Oa(e,n)}else if(K.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(K.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return za(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},RA=Ee.read.bind(Ee);function xb(t,e,s=0,r=null){let n=t/e,o=D0(n)*e;return r!==null&&o>r&&(o=Math.floor(n)*e),oe&&w.push(y)}else{let y=de(g.data)[1];if(y===l-1||(x=me(g.data),x[y]v*u[(k+1)%2])),_.boxes.push(b),_.classes.push(y),_.scores.push(x[y])}}c.push(_)}return c}function Ta(t,e=null){let s=t.logits,r=s.dims[0];if(e!==null&&e.length!==r)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;ou[w]&&(u[w]=g[w],_[w]=f)}let d=new Array(a.dims[0]);for(let f=0;f<_.length;++f){let g=_[f];d[g]=g}let m=d.filter(f=>f!==void 0);n.push({segmentation:p,labels:m})}return n}function DA(t,e,s,r){let n=[],o=[],i=[];for(let a=0;as&&(n.push(c),o.push(_),i.push(p))}return[n,o,i]}function qA(t,e,s,r=.5,n=.8){let o=[],i=0,a=0,l=e[s].data;for(let p=0;p=r&&++a;let c=i>0&&a>0;return c&&(c=i/a>n),[c,o]}function jA(t,e,s,r,n,o=null,i=null){let[a,l]=i??t[0].dims,c=new E("int32",new Int32Array(a*l),[a,l]),p=[];if(i!==null)for(let f=0;f_[x]&&(u[x]=f,_[x]=w[x])}let d=0,m=c.data;for(let f=0;f200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let i=Math.round(t/s)*s,a=Math.round(e/s)*s;if(o*i*a>n){let l=Math.sqrt(o*t*e/n);i=Math.max(s,Math.floor(t/l/s)*s),a=Math.max(s,Math.floor(e/l/s)*s)}else if(o*i*ao?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:r}))}async crop_margin(e,s=200){let r=e.clone().grayscale(),n=Fr(r.data)[0],i=de(r.data)[0]-n;if(i===0)return e;let a=s/255,l=r.width,c=r.height,p=0,u=0,_=r.data;for(let d=0;dthis.preprocess(o)));return{pixel_values:qe(r.map(o=>o.pixel_values),0),original_sizes:r.map(o=>o.original_size),reshaped_input_sizes:r.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,s={}){let r=await Ie(e,bt,!0,s);return new this(r)}};var Us={};Os(Us,{BeitFeatureExtractor:()=>Eu,BitImageProcessor:()=>Au,CHMv2ImageProcessor:()=>Su,CLIPFeatureExtractor:()=>Ou,CLIPImageProcessor:()=>Na,ChineseCLIPFeatureExtractor:()=>Mu,ConvNextFeatureExtractor:()=>Iu,ConvNextImageProcessor:()=>La,DINOv3ViTImageProcessor:()=>Cu,DPTFeatureExtractor:()=>Nu,DPTImageProcessor:()=>Ra,DeiTFeatureExtractor:()=>zu,DeiTImageProcessor:()=>$a,DetrFeatureExtractor:()=>Tu,DetrImageProcessor:()=>Fa,DonutFeatureExtractor:()=>Pu,DonutImageProcessor:()=>Ds,EfficientNetImageProcessor:()=>Lu,GLPNFeatureExtractor:()=>Ru,Gemma3ImageProcessor:()=>$u,Gemma4ImageProcessor:()=>Zr,Glm46VImageProcessor:()=>Fu,GroundingDinoImageProcessor:()=>Du,Idefics3ImageProcessor:()=>Da,ImageFeatureExtractor:()=>L,ImageProcessor:()=>L,JinaCLIPImageProcessor:()=>ju,Lfm2VlImageProcessor:()=>Bu,LlavaOnevisionImageProcessor:()=>Uu,Mask2FormerImageProcessor:()=>Wu,MaskFormerFeatureExtractor:()=>Gu,MaskFormerImageProcessor:()=>qs,MobileNetV1FeatureExtractor:()=>Vu,MobileNetV1ImageProcessor:()=>qa,MobileNetV2FeatureExtractor:()=>Hu,MobileNetV2ImageProcessor:()=>ja,MobileNetV3FeatureExtractor:()=>Ku,MobileNetV3ImageProcessor:()=>Ba,MobileNetV4FeatureExtractor:()=>Xu,MobileNetV4ImageProcessor:()=>Ua,MobileViTFeatureExtractor:()=>Qu,MobileViTImageProcessor:()=>Ga,NougatImageProcessor:()=>Yu,OwlViTFeatureExtractor:()=>Ju,OwlViTImageProcessor:()=>js,Owlv2ImageProcessor:()=>Zu,Phi3VImageProcessor:()=>s_,PixtralImageProcessor:()=>r_,PvtImageProcessor:()=>n_,Qwen2VLImageProcessor:()=>en,RTDetrImageProcessor:()=>o_,Sam2ImageProcessor:()=>tn,Sam3ImageProcessor:()=>tn,SamImageProcessor:()=>tn,SapiensFeatureExtractor:()=>i_,SapiensImageProcessor:()=>Wa,SegformerFeatureExtractor:()=>a_,SegformerImageProcessor:()=>Va,SiglipImageProcessor:()=>l_,SmolVLMImageProcessor:()=>Da,Swin2SRImageProcessor:()=>c_,VLMImageProcessor:()=>qu,ViTFeatureExtractor:()=>p_,ViTImageProcessor:()=>Ha,VitMatteImageProcessor:()=>u_,VitPoseImageProcessor:()=>__,YolosFeatureExtractor:()=>d_,YolosImageProcessor:()=>Ka});var Eu=class extends L{};var Au=class extends L{};var Mu=class extends L{};var Su=class extends L{};var Na=class extends L{},Ou=class extends Na{};var La=class extends L{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let s=this.size?.shortest_edge;if(s===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(s<384){let r=Math.floor(s/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:r});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(s,s)}else e=await e.resize(s,s,{resample:this.resample});return e}},Iu=class extends La{};var $a=class extends L{},zu=class extends $a{};var Fa=class extends L{async _call(e){let s=await super._call(e),r=[s.pixel_values.dims[0],64,64],n=ve(r,1n);return{...s,pixel_mask:n}}post_process_object_detection(...e){return Rt(...e)}post_process_panoptic_segmentation(...e){return Ca(...e)}post_process_instance_segmentation(...e){return Pa(...e)}},Tu=class extends Fa{};var Cu=class extends L{};var Ds=class extends L{pad_image(e,s,r,n={}){let[o,i,a]=s,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(a).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(a).fill(l));let p=l.map((u,_)=>-u/c[_]);return super.pad_image(e,s,r,{center:!0,constant_values:p,...n})}},Pu=class extends Ds{};var Ra=class extends L{},Nu=class extends Ra{};var Lu=class extends L{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(s=>s*s))}};var $u=class extends L{};function BA(t,e,s,r,n){let o=r*s**2,i=Math.sqrt(o/(t*e)),a=n*s,l=Math.floor(i*t/a)*a,c=Math.floor(i*e/a)*a;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${a}.`);let p=Math.floor(r/n**2)*a;return l===0?(l=a,c=Math.min(Math.floor(e/t)*a,p)):c===0&&(c=a,l=Math.min(Math.floor(t/e)*a,p)),[l,c]}function UA(t,e,s,r,n,o,i){let a=Math.floor(e/n),l=Math.floor(s/n),c=a*l,p=n*n*r,u=new Float32Array(o*p),_=0;for(let f=0;fi),0));let p=i.dims[0]/a,u=i.dims[1],_=Math.floor(i.dims[2]/c),d=Math.floor(i.dims[3]/c),m=i.view(p,a,u,Math.floor(_/l),l,c,Math.floor(d/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(p*_*d,u*a*c*c),f=new E("int64",[p,_,d],[1,3]);return{pixel_values:m,image_grid_thw:f,original_sizes:n,reshaped_input_sizes:o}}};var Fu=class extends en{get_resize_output_image_size(e,s){let r=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return Rs(e.height,e.width,r,this.min_pixels,this.max_pixels,n)}};var Ru=class extends L{};var Du=class extends L{async _call(e){let s=await super._call(e),r=s.pixel_values.dims,n=Me([r[0],r[2],r[3]]);return{...s,pixel_mask:n}}};var Da=class extends L{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,s){let[r,n]=e.dims.slice(-2),o=n/r;return n>=r?(n=Math.ceil(n/s)*s,r=Math.floor(n/o),r=Math.ceil(r/s)*s):(r=Math.ceil(r/s)*s,n=Math.floor(r*o),n=Math.ceil(n/s)*s),{height:r,width:n}}async _call(e,{do_image_splitting:s=null,return_row_col_info:r=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],i=[],a=[],l=[],c=[];for(let w of n){let x=await Promise.all(w.map(v=>this.preprocess(v)));l.push(...x.map(v=>v.original_size)),c.push(...x.map(v=>v.reshaped_input_size)),x.forEach(v=>v.pixel_values.unsqueeze_(0));let{longest_edge:y}=this.max_image_size,b;if(s??this.do_image_splitting){let v=new Array(x.length),k=new Array(x.length);b=await Promise.all(x.map(async(S,I)=>{let $=this.get_resize_for_vision_encoder(S.pixel_values,y),C=await je(S.pixel_values,{size:[$.height,$.width]}),{frames:R,num_splits_h:V,num_splits_w:H}=await this.split_image(C,this.max_image_size);return v[I]=V,k[I]=H,ie(R,0)})),i.push(v),a.push(k)}else{let v=[y,y];b=await Promise.all(x.map(k=>je(k.pixel_values,{size:v}))),i.push(new Array(x.length).fill(0)),a.push(new Array(x.length).fill(0))}o.push(ie(b,0))}let p=o.length,[u,_,d,m]=o[0].dims,f,g;if(p===1)f=o[0].unsqueeze_(0),g=ve([p,u,d,m],!0);else{let w=Math.max(...o.map(b=>b.dims.at(0)));g=ve([p,w,d,m],!0);let x=g.data,y=w*d*m;for(let b=0;br||a>n){l=Math.ceil(i/r),c=Math.ceil(a/n);let p=Math.ceil(i/l),u=Math.ceil(a/c);for(let m=0;ms*this.rescale_factor)}pad_image(e,s,r,n){return super.pad_image(e,s,r,{constant_values:this.constant_values,center:!0,...n})}};var ju=class extends L{constructor(e){let{resize_mode:s,fill_color:r,interpolation:n,size:o,...i}=e,a=s==="squash"?{width:o,height:o}:s==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...i,size:a,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function yb(t,e){return Math.round(t/e)*e}function GA(t,e,s,r,n){let o=1/0,i=[1,1],a=s*r;for(let l of e){let c=Math.abs(t-l[0]/l[1]);c.5*n*n*l[0]*l[1]&&(i=l)}return i}function WA(t,e){let s=[],r=new Set;for(let n=t;n<=e;++n)for(let o=1;o<=n;++o)for(let i=1;i<=n;++i){let a=o*i;if(a>=t&&a<=e){let l=o<<16|i;r.has(l)||(r.add(l),s.push([o,i]))}}return s.sort((n,o)=>n[0]*n[1]-o[0]*o[1])}function VA(t,e){let[s,r,n,o]=t.dims,i=Math.floor(n/e),a=Math.floor(o/e),l=e*e*r,c=t.data,p=new Float32Array(s*i*a*l),u=n*o;for(let _=0;_this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,s){let r=WA(this.min_tiles,this.max_tiles),[n,o]=GA(s/e,r,s,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:s=null}={}){let r;Array.isArray(e)?Array.isArray(e[0])?r=e:r=[e]:r=[[e]];let n=[],o=[],i=[],a=[],l=[],c=[];for(let u of r){let _=await Promise.all(u.map(d=>this.preprocess(d,{do_pad:!1})));for(let{pixel_values:d}of _){let[,m,f]=d.dims,g=d.unsqueeze_(0),w=this.encoder_patch_size*this.downsample_factor,x=w**2,[y,b]=Rs(Math.max(w,m),Math.max(w,f),w,this.min_image_tokens*x,this.max_image_tokens*x).map(C=>Math.max(w,C)),v,k=1,S=1,I=this._is_image_too_large(m,f),$=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(I&&$){let{grid_width:C,grid_height:R,target_width:V,target_height:H}=this._get_grid_layout(m,f);k=R,S=C;let j=await je(g,{size:[H,V]});v=[];for(let B=0;B(p-this.image_mean[u])/this.image_std[u]);return super.pad_image(e,s,{width:l,height:a},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:s=null}={}){if(this._num_crops=s??=this.config.num_crops,s<4||t_(s)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let r=e.length,n=await Promise.all(e.map(_=>this.preprocess(_))),o=n.map(_=>_.original_size),i=n.map(_=>_.reshaped_input_size),a=[];for(let{pixel_values:_}of n){_.unsqueeze_(0);let[d,m]=_.dims.slice(-2),f=await je(_,{size:[Xe,Xe],mode:"bicubic"});if(s>0){let g=[],w=t_(s),x=Bs(m/w),y=Bs(d/w);for(let v=0;v_.map(d=>Xe*e_(d/Xe))),p=new E("int64",c.flat(),[r,2]),u=c.map(([_,d])=>this.calc_num_image_tokens_from_image_size(d,_));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:i,image_sizes:p,num_img_tokens:u}}};var r_=class extends L{get_resize_output_image_size(e,s){let{longest_edge:r}=s;if(r===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,i=Math.max(n,o)/r,a=n,l=o;i>1&&(a=Math.floor(n/i),l=Math.floor(o/i));let{patch_size:c,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");let u=c*p,_=Math.floor((a-1)/u)+1,d=Math.floor((l-1)/u)+1;return[_*u,d*u]}};var n_=class extends L{};var o_=class extends L{post_process_object_detection(...e){return Rt(...e)}};var tn=class extends L{reshape_input_points(e,s,r,n=!1){e=structuredClone(e);let o=Hc(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let i=0;in!==s.dims[o]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new E("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:s=null,input_labels:r=null,input_boxes:n=null}={}){let o=await super._call(e);if(s&&(o.input_points=this.reshape_input_points(s,o.original_sizes,o.reshaped_input_sizes)),r){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(r,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,s,r,{mask_threshold:n=0,binarize:o=!0,pad_size:i=null}={}){let a=[];i=i??this.pad_size??this.size;let l=[i.height,i.width];for(let c=0;cn&&(m[f]=1);_=new E("bool",m,_.dims)}a.push(_)}return a}generate_crop_boxes(e,s,{crop_n_layers:r=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:i=1}={}){}};var Wa=class extends L{post_process_semantic_segmentation(...e){return Ta(...e)}},i_=class extends Wa{};var Va=class extends L{post_process_semantic_segmentation(...e){return Ta(...e)}},a_=class extends Va{};var l_=class extends L{};var c_=class extends L{pad_image(e,s,r,n={}){let[o,i,a]=s;return super.pad_image(e,s,{width:i+(r-i%r)%r,height:o+(r-o%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var Ha=class extends L{},p_=class extends Ha{};var u_=class extends L{async _call(e,s){Array.isArray(e)||(e=[e]),Array.isArray(s)||(s=[s]);let r=await Promise.all(e.map(i=>this.preprocess(i))),n=await Promise.all(s.map(i=>this.preprocess(i,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:qe(r.map((i,a)=>ie([i.pixel_values,n[a].pixel_values],0)),0),original_sizes:r.map(i=>i.original_size),reshaped_input_sizes:r.map(i=>i.reshaped_input_size)}}};var __=class extends L{post_process_pose_estimation(e,s,{threshold:r=null}={}){let n=e.tolist(),[o,i,a,l]=e.dims,c=[];for(let p=0;p/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let s=[];for(let r of e)if(this.task_prompts_without_inputs.has(r))s.push(this.task_prompts_without_inputs.get(r));else{for(let[n,o]of this.task_prompts_with_input)if(r.includes(n)){s.push(o.replaceAll("{input}",r).replaceAll(n,""));break}s.length!==e.length&&s.push(r)}return s}post_process_generation(e,s,r){let n=this.tasks_answer_post_processing_type.get(s)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let i=n==="ocr"?"quad_boxes":"bboxes",a=e.matchAll(this.regexes[i]),l=[],c=[];for(let[p,u,..._]of a)l.push(u?u.trim():l.at(-1)??""),c.push(_.map((d,m)=>(Number(d)+.5)/this.size_per_bin*r[m%2]));o={labels:l,[i]:c};break;default:throw new Error(`Task "${s}" (of type "${n}") not yet implemented.`)}return{[s]:o}}async _call(e,s=null,r={}){if(!e&&!s)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,r),o=s?this.tokenizer(this.construct_prompts(s),r):{};return{...n,...o}}};var m_=class extends U{static tokenizer_class=W;static image_processor_class=pe;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,s,r){super(e,s,r),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:o,eoi_token:i}=this.tokenizer.config;this.boi_token=n,this.image_token=o,this.eoi_token=i;let a=o.repeat(this.image_seq_length);this.full_image_sequence=` + + ${n}${a}${i} + +diff --git a/node_modules/@huggingface/transformers/src/backends/onnx.js b/node_modules/@huggingface/transformers/src/backends/onnx.js +index 13b1a74..0e21e24 100644 +--- a/node_modules/@huggingface/transformers/src/backends/onnx.js ++++ b/node_modules/@huggingface/transformers/src/backends/onnx.js +@@ -232,7 +232,7 @@ async function ensureWasmLoaded() { + + // Load both in parallel; the .mjs blob URL is only kept if wasmBinary succeeded. + // ORT only sets locateFile when wasmBinary is provided (onnxruntime PR https://github.com/microsoft/onnxruntime/pull/27411), which +- // prevents new URL(fileName, import.meta.url) from failing inside a blob URL factory. ++ // prevents new URL(fileName, import_meta.url) from failing inside a blob URL factory. + let wasmBinaryLoaded = false; + await Promise.all([ + // Load and cache the WASM binary +diff --git a/node_modules/@huggingface/transformers/src/env.js b/node_modules/@huggingface/transformers/src/env.js +index 25b3cf3..5aab692 100644 +--- a/node_modules/@huggingface/transformers/src/env.js ++++ b/node_modules/@huggingface/transformers/src/env.js +@@ -75,7 +75,7 @@ const isSafari = () => { + return false; + } + +- const userAgent = navigator.userAgent; ++ const userAgent = navigator.userAgent || ""; + const vendor = navigator.vendor || ''; + + // Safari has "Apple" in vendor string +@@ -146,10 +146,10 @@ const RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE; + + let dirname__ = './'; + if (RUNNING_LOCALLY) { +- // NOTE: We wrap `import.meta` in a call to `Object` to prevent Webpack from trying to bundle it in CommonJS. +- // Although we get the warning: "Accessing import.meta directly is unsupported (only property access or destructuring is supported)", ++ // NOTE: We wrap `import_meta` in a call to `Object` to prevent Webpack from trying to bundle it in CommonJS. ++ // Although we get the warning: "Accessing import_meta directly is unsupported (only property access or destructuring is supported)", + // it is safe to ignore since the bundled value (`{}`) isn't used for CommonJS environments (we use __dirname instead). +- const _import_meta_url = Object(import.meta).url; ++ const _import_meta_url = Object(import_meta).url; + + if (_import_meta_url) { + dirname__ = path.dirname(path.dirname(url.fileURLToPath(_import_meta_url))); // ESM +diff --git a/node_modules/@huggingface/transformers/src/utils/hub.js b/node_modules/@huggingface/transformers/src/utils/hub.js +index 6cd7e40..f6b7f9e 100644 +--- a/node_modules/@huggingface/transformers/src/utils/hub.js ++++ b/node_modules/@huggingface/transformers/src/utils/hub.js +@@ -366,7 +366,7 @@ export async function loadResourceFile( + } else if ( + cacheHit && // The item is being read from the cache + typeof navigator !== 'undefined' && +- /firefox/i.test(navigator.userAgent) // We are in Firefox ++ /firefox/i.test((navigator.userAgent||"")) // We are in Firefox + ) { + // Due to bug in Firefox, we cannot display progress when loading from cache. + // Fortunately, since this should be instantaneous, this should not impact users too much. +diff --git a/node_modules/@huggingface/transformers/src/utils/hub/utils.js b/node_modules/@huggingface/transformers/src/utils/hub/utils.js +index e05ee27..afbf089 100644 +--- a/node_modules/@huggingface/transformers/src/utils/hub/utils.js ++++ b/node_modules/@huggingface/transformers/src/utils/hub/utils.js +@@ -156,9 +156,9 @@ export function toAbsoluteURL(url) { + if (typeof location !== 'undefined' && location.href) { + // Browser environment: use location.href + baseURL = location.href; +- } else if (typeof import.meta !== 'undefined' && import.meta.url) { +- // Node.js/Bun/Deno module environment: use import.meta.url +- baseURL = import.meta.url; ++ } else if (typeof import_meta !== 'undefined' && import_meta.url) { ++ // Node.js/Bun/Deno module environment: use import_meta.url ++ baseURL = import_meta.url; + } else { + // Fallback: if no base is available, return the URL unchanged + return url; diff --git a/src/services/NerService.ts b/src/services/NerService.ts index e4a73e4..d7f6e53 100644 --- a/src/services/NerService.ts +++ b/src/services/NerService.ts @@ -1,19 +1,118 @@ import { pipeline, env } from '@huggingface/transformers'; +import { Image } from 'react-native'; +import ReactNativeBlobUtil from 'react-native-blob-util'; +import { InferenceSession } from 'onnxruntime-react-native'; -// Configuration pour React Native -// Utiliser le modèle local présent dans ton dossier 'assets/models/albert-wikiner-fr-onnx' -env.allowLocalModels = true; -env.allowRemoteModels = false; // Désactivé pour forcer le local +// Monkey patch InferenceSession.create pour contourner la conversion Uint8Array de transformers.js +// Transformers.js force la conversion du buffer en Uint8Array, ce qui détruit notre string de chemin. +// On intercepte la création de session pour lui redonner le vrai chemin du fichier local ! +const originalCreate = InferenceSession.create; +(InferenceSession as any).create = async function(arg0: any, arg1?: any, arg2?: any, arg3?: any) { + if (arg0 instanceof Uint8Array && arg0.length === 0 && (global as any).latestModelPath) { + console.log("Intercepted InferenceSession.create, using local path:", (global as any).latestModelPath); + return originalCreate.call(InferenceSession, (global as any).latestModelPath, arg1); + } + return originalCreate.call(InferenceSession, arg0, arg1, arg2, arg3); +}; -// Mettre le chemin vers le dossier contenant le modèle (relatif pour le bundler RN) -// Avec transformers.js et React Native, on peut utiliser des URL ou des chemins d'assets locaux -// selon la configuration du plugin babel / metro. -env.localModelPath = 'assets/models/'; +// Désactivation des requêtes distantes et du FS Node +env.allowLocalModels = true; +env.allowRemoteModels = false; +env.useFS = false; +env.localModelPath = 'assets/models/'; + +// Pre-load all assets via Metro bundler +const modelAssets: Record = { + 'config.json': require('../assets/models/albert-wikiner-fr-onnx/config.json'), + 'tokenizer.json': require('../assets/models/albert-wikiner-fr-onnx/tokenizer.json'), + 'tokenizer_config.json': require('../assets/models/albert-wikiner-fr-onnx/tokenizer_config.json'), + 'special_tokens_map.json': require('../assets/models/albert-wikiner-fr-onnx/special_tokens_map.json'), + 'spiece.model': require('../assets/models/albert-wikiner-fr-onnx/spiece.model'), + 'model.onnx': require('../assets/models/albert-wikiner-fr-onnx/onnx/model.onnx'), + 'model_quantized.onnx': require('../assets/models/albert-wikiner-fr-onnx/onnx/model.onnx'), +}; + +// Surcharge de la méthode fetch pour intercepter les appels de transformers.js +env.fetch = async (url: string, init?: any) => { + console.log("Intercepted fetch:", url); + + const parts = url.split('/'); + const filename = parts.pop()!; + + // Récupérer l'asset correspondant + const asset = modelAssets[filename]; + + if (asset) { + if (filename.endsWith('.json')) { + return new Response(JSON.stringify(asset), { + headers: { 'Content-Type': 'application/json' } + }); + } + + if (filename.endsWith('.model') || filename.endsWith('.onnx')) { + const uri = Image.resolveAssetSource(asset).uri; + + if (filename.endsWith('.onnx')) { + let modelPath = uri; + + if (uri.startsWith('http')) { + const destPath = `${ReactNativeBlobUtil.fs.dirs.CacheDir}/${filename}`; + // Toujours vérifier si le fichier est valide. Dans le doute, on peut le retélécharger, + // mais on va assumer qu'il est bon s'il existe pour éviter de télécharger 41Mo à chaque fois. + const exists = await ReactNativeBlobUtil.fs.exists(destPath); + + if (!exists) { + console.log("Downloading ONNX model to cache in DEV mode..."); + await ReactNativeBlobUtil.config({ path: destPath }).fetch('GET', uri); + } + modelPath = destPath; + } else if (uri.startsWith('raw/')) { + // En production Android, l'URI des assets ressemble à "raw/model_onnx" + // react-native-blob-util peut générer un chemin absolu pour les assets + // ou onnxruntime peut le charger avec 'asset://' + modelPath = `asset://${filename}`; // 'asset://model.onnx' si on le met à la racine des assets + // Mais attention, metro bundler met les assets ailleurs. + // Le plus sûr pour onnxruntime-react-native avec les assets packagés est de donner l'URI brute. + } + + // On sauvegarde le vrai chemin local dans une variable globale + (global as any).latestModelPath = modelPath; + + // On retourne un ArrayBuffer vide (0 bytes). + // transformers.js va le cast en Uint8Array(0), puis appeler InferenceSession.create. + // Notre monkey patch attrapera cet appel et utilisera latestModelPath ! + return { + arrayBuffer: async () => new ArrayBuffer(0) + } as any; + } + + if (uri.startsWith('http')) { + // Mode développement pour spiece.model (petit fichier, fetch classique OK) + return fetch(uri, init); + } else { + // Mode production pour spiece.model (raw assets) + try { + const base64Str = await ReactNativeBlobUtil.fs.readFile(uri, 'base64'); + const binaryString = global.atob ? global.atob(base64Str) : ReactNativeBlobUtil.base64.decode(base64Str); + const len = binaryString.length; + const bytes = new Uint8Array(len); + for (let i = 0; i < len; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return new Response(bytes.buffer, { + headers: { 'Content-Type': 'application/octet-stream' } + }); + } catch (e) { + console.error("Error loading asset:", filename, e); + throw e; + } + } + } + } + + return fetch(url, init); +}; -/** - * Service pour l'inférence NER avec le modèle ALBERT ONNX - * Utilise Transformers.js pour gérer la tokenisation et l'inférence. - */ class NERInference { static instance: any = null; @@ -21,12 +120,15 @@ class NERInference { if (this.instance === null) { console.log("Chargement du modèle ONNX..."); - // Initialisation du pipeline + // Initialisation du pipeline (nous passons juste un nom bidon puisque fetch est intercepté) this.instance = pipeline( 'token-classification', 'albert-wikiner-fr-onnx', { - quantized: false // Utiliser false car le fichier s'appelle model.onnx (pas model_quantized.onnx) + quantized: false, + session_options: { + executionProviders: ['cpu'] // onnxruntime-react-native doesn't support 'wasm' + } } ); } @@ -42,22 +144,19 @@ export interface NerEntity { end?: number; } -/** - * Fonction pour extraire les entités d'un texte - * @param text - Le texte à analyser - * @returns Liste des entités détectées - */ export const extractEntities = async (text: string): Promise => { + console.log("=== DÉMARRAGE DE L'EXTRACTION NER ==="); if (!text) return []; try { const classifier = await NERInference.getInstance(); - // On utilise l'aggregation "simple" (comme en Python) pour regrouper les sous-mots (B-PER, I-PER -> PER) const results = await classifier(text, { aggregation_strategy: "simple" }); + console.log("NER EXTRACTED ENTITIES:", JSON.stringify(results, null, 2)); + return results as NerEntity[]; } catch (error) { console.error("Erreur d'inférence NER :", error); diff --git a/src/services/anonymizer.ts b/src/services/anonymizer.ts index 86c8b07..fc18ee3 100644 --- a/src/services/anonymizer.ts +++ b/src/services/anonymizer.ts @@ -91,6 +91,12 @@ export const anonymize = async (text: string): Promise => { console.error("Erreur lors de l'anonymisation NER :", error); } + console.log("=== RÉSULTAT DE L'ANONYMISATION ==="); + console.log("Texte original:", text); + console.log("Texte anonymisé:", anonymizedText); + console.log("Dictionnaire (Mapping):", JSON.stringify(mapping, null, 2)); + console.log("==================================="); + return { anonymizedText, mapping }; }; From 7bf028f183a376adf15a8438e94f2d07a303565a Mon Sep 17 00:00:00 2001 From: Juste-Leo Date: Fri, 10 Jul 2026 16:12:22 +0200 Subject: [PATCH 4/4] finally up and running --- src/services/NerService.ts | 78 ++++++++++++++++++++++++++++++++--- src/services/anonymizer.ts | 84 +++++++++++++++++++++++++------------- 2 files changed, 128 insertions(+), 34 deletions(-) diff --git a/src/services/NerService.ts b/src/services/NerService.ts index d7f6e53..2a176ce 100644 --- a/src/services/NerService.ts +++ b/src/services/NerService.ts @@ -144,20 +144,88 @@ export interface NerEntity { end?: number; } +// Découpage du texte pour éviter de dépasser la limite de tokens d'ALBERT (généralement 512) +function chunkText(text: string, maxLength: number = 200): string[] { + const chunks: string[] = []; + let currentChunk = ""; + + // Séparer par sauts de lignes et points pour garder un sens contextuel + const sentences = text.split(/([.\n])/); + + for (let i = 0; i < sentences.length; i++) { + const part = sentences[i]; + if (currentChunk.length + part.length > maxLength) { + if (currentChunk.trim()) chunks.push(currentChunk.trim()); + currentChunk = part; + } else { + currentChunk += part; + } + } + if (currentChunk.trim()) chunks.push(currentChunk.trim()); + + return chunks; +} + export const extractEntities = async (text: string): Promise => { console.log("=== DÉMARRAGE DE L'EXTRACTION NER ==="); if (!text) return []; try { const classifier = await NERInference.getInstance(); + const chunks = chunkText(text); + let allEntities: NerEntity[] = []; - const results = await classifier(text, { - aggregation_strategy: "simple" - }); + for (const chunk of chunks) { + if (chunk.length < 2) continue; + + // On retire l'aggregation_strategy "simple" car il fusionne mal les mots sous React Native + // On va faire l'agrégation manuellement. + const results = await classifier(chunk) as Array<{entity: string, score: number, word: string, index: number}>; + + console.log(`Raw ALBERT tokens for chunk:`, JSON.stringify(results)); + + let currentEntity: NerEntity | null = null; + let lastTokenIndex = -1; + + if (Array.isArray(results)) { + for (const token of results) { + if (token.entity === 'O') { + if (currentEntity) { allEntities.push(currentEntity); currentEntity = null; } + continue; + } + + const group = token.entity.replace('B-', '').replace('I-', ''); + const cleanPiece = token.word.replace(/ /g, '').replace(/\u2581/g, '').trim(); + + if (cleanPiece.length === 0) continue; + + // Le modèle ne renvoie pas toujours B- ou les espaces de séparation. + // La seule façon fiable de savoir si deux sous-mots appartiennent à la même entité, + // c'est de vérifier s'ils ont été générés à la suite (index consécutifs). + const isSameGroup = currentEntity && currentEntity.entity_group === group; + const isConsecutive = lastTokenIndex !== -1 && (token.index === lastTokenIndex + 1); + + if (currentEntity && isSameGroup && isConsecutive) { + // Concaténer le sous-mot qui appartient au MÊME mot consécutif (ex: "eco" + "ute") + currentEntity.word += cleanPiece; + } else { + // C'est un nouveau mot ou une nouvelle entité ! + if (currentEntity) allEntities.push(currentEntity); + currentEntity = { entity_group: group, word: cleanPiece, score: token.score } as NerEntity; + } + + lastTokenIndex = token.index; + } + if (currentEntity) { + allEntities.push(currentEntity); + currentEntity = null; + } + } + } - console.log("NER EXTRACTED ENTITIES:", JSON.stringify(results, null, 2)); + console.log("NER EXTRACTED ENTITIES:", JSON.stringify(allEntities, null, 2)); - return results as NerEntity[]; + return allEntities; } catch (error) { console.error("Erreur d'inférence NER :", error); return []; diff --git a/src/services/anonymizer.ts b/src/services/anonymizer.ts index fc18ee3..12cab89 100644 --- a/src/services/anonymizer.ts +++ b/src/services/anonymizer.ts @@ -8,6 +8,8 @@ export interface AnonymizationResult { // Les civilités à exclure du masquage const CIVILITIES = ['Monsieur ', 'Madame ', 'M. ', 'Mme ', 'Mr ', 'Mademoiselle ', 'Mlle ']; +const removeAccents = (str: string) => str.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase(); + export const anonymize = async (text: string): Promise => { if (!text) return { anonymizedText: text, mapping: {} }; @@ -35,7 +37,7 @@ export const anonymize = async (text: string): Promise => { return key; }); - // Numéro INE (11 caractères, alphanumérique ex: 123456789EE) + // Numéro INE anonymizedText = anonymizedText.replace(/\b\d{9,10}[A-Z]{1,2}\b/gi, (match) => { const key = `[INE${ineCount++}]`; mapping[key] = match; @@ -48,42 +50,66 @@ export const anonymize = async (text: string): Promise => { // Trier les entités par longueur de mot décroissante pour éviter les remplacements imbriqués partiels const sortedEntities = [...entities].sort((a, b) => b.word.length - a.word.length); + const normalizedText = removeAccents(anonymizedText); for (const entity of sortedEntities) { if (entity.entity_group === 'PER' || entity.entity_group === 'LOC') { - let originalWord = entity.word.trim(); - - // Nettoyage de la civilité pour ne masquer que le nom propre - if (entity.entity_group === 'PER') { - for (const civ of CIVILITIES) { - if (originalWord.toLowerCase().startsWith(civ.toLowerCase())) { - originalWord = originalWord.substring(civ.length).trim(); - break; + let cleanWord = entity.word.trim(); + + // Ignorer les mots très courts qui pourraient être des erreurs de tokenisation + if (cleanWord.length <= 2) continue; + + // Trouver toutes les occurrences de cleanWord dans le texte normalisé + let startIndex = 0; + let index = normalizedText.indexOf(cleanWord, startIndex); + + while (index !== -1) { + // Extraire le mot exact avec sa casse et ses accents d'origine ! + // La normalisation NFD préserve la longueur exacte de la chaîne en JavaScript après notre regex. + let originalWord = anonymizedText.substring(index, index + cleanWord.length); + + // Vérifier les frontières du mot (pour ne pas remplacer "Stras" dans "Strasbourgeoise") + const beforeChar = index > 0 ? anonymizedText[index - 1] : ' '; + const afterChar = index + cleanWord.length < anonymizedText.length ? anonymizedText[index + cleanWord.length] : ' '; + const isWordBoundary = (char: string) => /[\s.,!?;:'"()\[\]{}\\]/.test(char); + + if ((index === 0 || isWordBoundary(beforeChar)) && + (index + cleanWord.length === anonymizedText.length || isWordBoundary(afterChar))) { + + // Nettoyage de la civilité pour ne masquer que le nom propre + let wordToMask = originalWord; + if (entity.entity_group === 'PER') { + for (const civ of CIVILITIES) { + if (wordToMask.toLowerCase().startsWith(civ.toLowerCase())) { + wordToMask = wordToMask.substring(civ.length).trim(); + break; + } + } } - } - } - - // Si après nettoyage, il reste un mot valide - if (originalWord.length > 1) { - // On vérifie s'il n'a pas déjà été stocké dans le mapping - let existingKey = Object.keys(mapping).find(key => mapping[key] === originalWord); - let keyToUse = existingKey; - if (!keyToUse) { - if (entity.entity_group === 'PER') { - keyToUse = `[PERSONNE${personCount++}]`; - } else { - keyToUse = `[LIEU${locCount++}]`; + if (wordToMask.length > 1) { + let existingKey = Object.keys(mapping).find(key => mapping[key] === wordToMask); + let keyToUse = existingKey; + + if (!keyToUse) { + if (entity.entity_group === 'PER') { + keyToUse = `[PERSONNE${personCount++}]`; + } else { + keyToUse = `[LIEU${locCount++}]`; + } + mapping[keyToUse] = wordToMask; + } + + // Remplacement sécurisé via regex sur le mot exact + const escapedWord = wordToMask.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const regex = new RegExp(`\\b${escapedWord}\\b`, 'g'); + anonymizedText = anonymizedText.replace(regex, keyToUse); } - mapping[keyToUse] = originalWord; } - - // Remplacement global du mot dans le texte - // Échapper le mot original pour la regex - const escapedWord = originalWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - const regex = new RegExp(`\\b${escapedWord}\\b`, 'gi'); - anonymizedText = anonymizedText.replace(regex, keyToUse); + // Chercher l'occurrence suivante + startIndex = index + cleanWord.length; + index = normalizedText.indexOf(cleanWord, startIndex); } } }