Spaces:
Running
Running
Antalia-2 Mini 1.0.0 in the browser (ONNX Runtime Web)
Browse files- README.md +51 -5
- app.webmanifest +9 -0
- assets/frontend-data.json.gz +3 -0
- css/style.css +213 -0
- icon.svg +1 -0
- index.html +93 -17
- js/app.js +322 -0
- js/frontend.js +1126 -0
- js/strings.js +45 -0
- js/tts.js +413 -0
- js/worker.js +108 -0
- models/cond.fp16.onnx +3 -0
- models/cond.int8.onnx +3 -0
- models/cond.onnx +3 -0
- models/flow.fp16.onnx +3 -0
- models/flow.int8.onnx +3 -0
- models/flow.onnx +3 -0
- models/manifest.json +141 -0
- models/text.fp16.onnx +3 -0
- models/text.int8.onnx +3 -0
- models/text.onnx +3 -0
- models/vocoder.fp16.onnx +3 -0
- models/vocoder.int8.onnx +3 -0
- models/vocoder.onnx +3 -0
- sw.js +53 -0
- vendor/ort/LICENSE +21 -0
- vendor/ort/VERSION +1 -0
- vendor/ort/ort-wasm-simd-threaded.asyncify.mjs +124 -0
- vendor/ort/ort-wasm-simd-threaded.asyncify.wasm +3 -0
- vendor/ort/ort-wasm-simd-threaded.mjs +59 -0
- vendor/ort/ort-wasm-simd-threaded.wasm +3 -0
- vendor/ort/ort.wasm.min.mjs +7 -0
- vendor/ort/ort.webgpu.min.mjs +8 -0
README.md
CHANGED
|
@@ -1,10 +1,56 @@
|
|
| 1 |
---
|
| 2 |
-
title: Antalia Mini
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
colorTo: gray
|
| 6 |
sdk: static
|
|
|
|
|
|
|
| 7 |
pinned: false
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Antalia-2 Mini
|
| 3 |
+
colorFrom: blue
|
| 4 |
+
colorTo: indigo
|
|
|
|
| 5 |
sdk: static
|
| 6 |
+
app_file: index.html
|
| 7 |
+
license: apache-2.0
|
| 8 |
pinned: false
|
| 9 |
+
models:
|
| 10 |
+
- cloud0day3/antalia-mini
|
| 11 |
+
short_description: Turkish text-to-speech running entirely in your browser
|
| 12 |
+
custom_headers:
|
| 13 |
+
cross-origin-embedder-policy: require-corp
|
| 14 |
+
cross-origin-opener-policy: same-origin
|
| 15 |
+
cross-origin-resource-policy: cross-origin
|
| 16 |
---
|
| 17 |
|
| 18 |
+
# Antalia-2 Mini in the browser
|
| 19 |
+
|
| 20 |
+
A static page that runs Antalia-2 Mini 1.0.0 (7.62M parameters, Turkish text to speech, 48 kHz) entirely on the
|
| 21 |
+
visitor's device with ONNX Runtime Web: no server, and the text never leaves the browser. It synthesises the way
|
| 22 |
+
the released Python package does: the same text and seed give the same audio as
|
| 23 |
+
`from antalia_mini import Antalia; Antalia().say(text, seed=0)` (`tests/release_parity/REPORT.md`). This folder is
|
| 24 |
+
deployable as a Hugging Face static Space as it is (index.html at the root, every path relative).
|
| 25 |
+
|
| 26 |
+
## Layout
|
| 27 |
+
|
| 28 |
+
| Path | What |
|
| 29 |
+
|---|---|
|
| 30 |
+
| `index.html`, `css/`, `js/app.js`, `js/strings.js` | the page (Turkish UI, English toggle, light and dark) |
|
| 31 |
+
| `js/worker.js` | runs the frontend and the model in a Web Worker |
|
| 32 |
+
| `js/tts.js` | the inference glue, as `antalia_mini.api`: durations (with the release's double-sound stretch), torch-identical noise, guided flow steps, iSTFT, the spoken prefix / suffix cut away, chunking, pauses, tone EQ and limiter |
|
| 33 |
+
| `js/frontend.js`, `assets/frontend-data.json.gz` | the Turkish normaliser ported to JS (`normalize_for_cased_model` + `respell_foreign`), with a compact lexicon, CMU respellings and Turkish vocabulary subset |
|
| 34 |
+
| `models/` | `text`, `cond`, `flow`, `vocoder` graphs in fp32, fp16 storage (from the release's fp16 weights) and int8; `manifest.json` names the release, its defaults and synthesis options. The page loads "mixed" by default: fp32 acoustic graphs + fp16 vocoder, 22.8 MB |
|
| 35 |
+
| `vendor/ort/` | ONNX Runtime Web (MIT), WASM build |
|
| 36 |
+
| `sw.js` | offline cache, and COOP/COEP headers so the page is cross-origin isolated and ORT can use threads |
|
| 37 |
+
| `tools/`, `tests/` | export, verification, precision comparison, parity tests (not needed by the page) |
|
| 38 |
+
|
| 39 |
+
## Commands (run from the repo root)
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
web/update_weights.sh ../antalia-mini-release/dist/hf # a release directory (or two runs / .pt files) -> export -> verify -> swap
|
| 43 |
+
web/tools/fetch_ort.sh # vendor ONNX Runtime Web (WEBGPU=1 adds the WebGPU build)
|
| 44 |
+
python3 web/tools/serve.py --port 8840 # local static server (add --coi to send COOP/COEP itself)
|
| 45 |
+
.venv/bin/python web/tools/verify_onnx.py --release DIR --precision mixed --strict # vs the package's Antalia().say
|
| 46 |
+
node web/tests/release_parity/run_js.mjs OUT --precision mixed # the page's own JS in Node (then verify_onnx.py --js OUT)
|
| 47 |
+
node web/tests/glue/run_glue.mjs # glue units vs torch and the package
|
| 48 |
+
node web/tests/parity/run_parity.mjs # normaliser parity, Python vs JS (see the file header)
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
URL options for measuring: `?threads=N`, `?precision=mixed|fp32|fp16|int8`, `?backend=webgpu` (needs the WebGPU
|
| 52 |
+
build), `?noreload` (skip the one-time reload that turns on cross-origin isolation). In the console,
|
| 53 |
+
`await amBench({runs: 3})` times every example sentence without playing it.
|
| 54 |
+
|
| 55 |
+
Model and voice: Antalia-2 Mini, Apache-2.0, PatientDesk AI. The voice is synthetic; no real person's voice was
|
| 56 |
+
used in training.
|
app.webmanifest
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "Antalia-2 Mini",
|
| 3 |
+
"short_name": "Antalia-2 Mini",
|
| 4 |
+
"start_url": "./",
|
| 5 |
+
"display": "standalone",
|
| 6 |
+
"background_color": "#f4f1ea",
|
| 7 |
+
"theme_color": "#1f42b0",
|
| 8 |
+
"icons": [{ "src": "icon.svg", "sizes": "any", "type": "image/svg+xml" }]
|
| 9 |
+
}
|
assets/frontend-data.json.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9f25ae01718643d5572deb11b586fb5ee2d443176990f8a39e2c073617a01453
|
| 3 |
+
size 560861
|
css/style.css
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Antalia Mini demo. Tokens follow speech.patientdesk.ai's İznik look: glazed cream and cobalt in light,
|
| 2 |
+
ink navy and cream in dark; Instrument Serif for display, Karla for text, JetBrains Mono for numbers.
|
| 3 |
+
Corners nearly square (tiles, not pills). */
|
| 4 |
+
:root {
|
| 5 |
+
--bg: #f4f1ea;
|
| 6 |
+
--bg-elev: #fbfaf6;
|
| 7 |
+
--bg-sunk: #ece8de;
|
| 8 |
+
--fg: #13235a;
|
| 9 |
+
--fg-2: #4a5478;
|
| 10 |
+
--fg-3: #6f7896;
|
| 11 |
+
--line: #dad8cf;
|
| 12 |
+
--line-2: #c5c3b8;
|
| 13 |
+
--brand: #1f42b0;
|
| 14 |
+
--brand-strong: #17348f;
|
| 15 |
+
--brand-fg: #f7f5ef;
|
| 16 |
+
--brand-soft: #e3e8f6;
|
| 17 |
+
--warm: #8a6420;
|
| 18 |
+
--warm-soft: #f3e8cf;
|
| 19 |
+
--err: #b83a32;
|
| 20 |
+
--radius: 4px;
|
| 21 |
+
--serif: "Instrument Serif", ui-serif, Georgia, serif;
|
| 22 |
+
--sans: "Karla", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
|
| 23 |
+
--mono: "JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace;
|
| 24 |
+
color-scheme: light;
|
| 25 |
+
}
|
| 26 |
+
:root[data-theme="dark"] {
|
| 27 |
+
--bg: #0a0f1e;
|
| 28 |
+
--bg-elev: #0f1528;
|
| 29 |
+
--bg-sunk: #141b33;
|
| 30 |
+
--fg: #f1ece2;
|
| 31 |
+
--fg-2: #b8bed1;
|
| 32 |
+
--fg-3: #8d95b2;
|
| 33 |
+
--line: #1f2744;
|
| 34 |
+
--line-2: #2c3659;
|
| 35 |
+
--brand: #7d9bff;
|
| 36 |
+
--brand-strong: #9db3ff;
|
| 37 |
+
--brand-fg: #0a0f1e;
|
| 38 |
+
--brand-soft: #172150;
|
| 39 |
+
--warm: #e3b26a;
|
| 40 |
+
--warm-soft: #2e2512;
|
| 41 |
+
--err: #e8776e;
|
| 42 |
+
color-scheme: dark;
|
| 43 |
+
}
|
| 44 |
+
@media (prefers-color-scheme: dark) {
|
| 45 |
+
:root:not([data-theme="light"]) {
|
| 46 |
+
--bg: #0a0f1e;
|
| 47 |
+
--bg-elev: #0f1528;
|
| 48 |
+
--bg-sunk: #141b33;
|
| 49 |
+
--fg: #f1ece2;
|
| 50 |
+
--fg-2: #b8bed1;
|
| 51 |
+
--fg-3: #8d95b2;
|
| 52 |
+
--line: #1f2744;
|
| 53 |
+
--line-2: #2c3659;
|
| 54 |
+
--brand: #7d9bff;
|
| 55 |
+
--brand-strong: #9db3ff;
|
| 56 |
+
--brand-fg: #0a0f1e;
|
| 57 |
+
--brand-soft: #172150;
|
| 58 |
+
--warm: #e3b26a;
|
| 59 |
+
--warm-soft: #2e2512;
|
| 60 |
+
--err: #e8776e;
|
| 61 |
+
color-scheme: dark;
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
*, *::before, *::after { box-sizing: border-box; }
|
| 66 |
+
html { -webkit-text-size-adjust: 100%; }
|
| 67 |
+
body {
|
| 68 |
+
margin: 0;
|
| 69 |
+
background: var(--bg);
|
| 70 |
+
color: var(--fg);
|
| 71 |
+
font: 400 17px/1.55 var(--sans);
|
| 72 |
+
-webkit-font-smoothing: antialiased;
|
| 73 |
+
}
|
| 74 |
+
.page {
|
| 75 |
+
max-width: 760px;
|
| 76 |
+
margin: 0 auto;
|
| 77 |
+
padding: 0 16px;
|
| 78 |
+
min-height: 100vh;
|
| 79 |
+
display: flex;
|
| 80 |
+
flex-direction: column;
|
| 81 |
+
}
|
| 82 |
+
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
| 83 |
+
:focus-visible { outline: 2px solid var(--brand); outline-offset: 2px; }
|
| 84 |
+
button { font: inherit; color: inherit; }
|
| 85 |
+
|
| 86 |
+
/* ------------------------------------------------------------------ top */
|
| 87 |
+
.top {
|
| 88 |
+
display: flex;
|
| 89 |
+
align-items: center;
|
| 90 |
+
justify-content: space-between;
|
| 91 |
+
padding: 20px 0 0;
|
| 92 |
+
border-top: 3px solid var(--brand);
|
| 93 |
+
margin-top: 0;
|
| 94 |
+
}
|
| 95 |
+
.wordmark { font-family: var(--mono); font-size: 14px; letter-spacing: 0.02em; color: var(--fg-2); }
|
| 96 |
+
.toggles { display: flex; gap: 4px; }
|
| 97 |
+
.toggles button {
|
| 98 |
+
min-width: 40px; height: 40px; padding: 0 10px;
|
| 99 |
+
background: transparent; border: 1px solid transparent; border-radius: var(--radius);
|
| 100 |
+
color: var(--fg-2); cursor: pointer; display: inline-flex; align-items: center; justify-content: center;
|
| 101 |
+
font-family: var(--mono); font-size: 13px; letter-spacing: 0.06em;
|
| 102 |
+
}
|
| 103 |
+
.toggles button:hover { border-color: var(--line); color: var(--fg); }
|
| 104 |
+
.theme .i-sun { display: none; }
|
| 105 |
+
:root[data-theme="dark"] .theme .i-sun { display: block; }
|
| 106 |
+
:root[data-theme="dark"] .theme .i-moon { display: none; }
|
| 107 |
+
@media (prefers-color-scheme: dark) {
|
| 108 |
+
:root:not([data-theme="light"]) .theme .i-sun { display: block; }
|
| 109 |
+
:root:not([data-theme="light"]) .theme .i-moon { display: none; }
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
/* ------------------------------------------------------------------ intro */
|
| 113 |
+
.intro { padding: 36px 0 22px; }
|
| 114 |
+
h1 {
|
| 115 |
+
font: 400 clamp(38px, 7vw, 60px)/1.04 var(--serif);
|
| 116 |
+
letter-spacing: -0.01em;
|
| 117 |
+
margin: 0 0 16px;
|
| 118 |
+
text-wrap: balance;
|
| 119 |
+
}
|
| 120 |
+
.lead { margin: 0; max-width: 60ch; color: var(--fg-2); text-wrap: pretty; }
|
| 121 |
+
|
| 122 |
+
/* ------------------------------------------------------------------ studio */
|
| 123 |
+
.studio {
|
| 124 |
+
background: var(--bg-elev);
|
| 125 |
+
border: 1px solid var(--line);
|
| 126 |
+
border-radius: var(--radius);
|
| 127 |
+
padding: 20px;
|
| 128 |
+
}
|
| 129 |
+
.label { display: block; font-size: 13px; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase; color: var(--fg-2); margin-bottom: 8px; }
|
| 130 |
+
textarea {
|
| 131 |
+
display: block; width: 100%; resize: vertical; min-height: 92px;
|
| 132 |
+
font: 400 19px/1.5 var(--sans); color: var(--fg);
|
| 133 |
+
background: var(--bg); border: 1px solid var(--line-2); border-radius: var(--radius);
|
| 134 |
+
padding: 12px 14px;
|
| 135 |
+
}
|
| 136 |
+
textarea:focus-visible { outline: 2px solid var(--brand); outline-offset: 0; border-color: var(--brand); }
|
| 137 |
+
.examples { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0 0; }
|
| 138 |
+
.chip {
|
| 139 |
+
border: 1px solid var(--line-2); background: transparent; border-radius: var(--radius);
|
| 140 |
+
padding: 6px 12px; font-size: 15px; color: var(--fg-2); cursor: pointer; min-height: 36px;
|
| 141 |
+
}
|
| 142 |
+
.chip:hover { color: var(--fg); border-color: var(--fg-3); }
|
| 143 |
+
.chip[aria-pressed="true"] { color: var(--brand); border-color: var(--brand); background: var(--brand-soft); }
|
| 144 |
+
|
| 145 |
+
.controls { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 24px; margin-top: 16px; }
|
| 146 |
+
.play {
|
| 147 |
+
display: inline-flex; align-items: center; gap: 10px;
|
| 148 |
+
min-height: 48px; padding: 0 22px; min-width: 10.5em; justify-content: center;
|
| 149 |
+
background: var(--brand); color: var(--brand-fg);
|
| 150 |
+
border: 0; border-radius: var(--radius); cursor: pointer;
|
| 151 |
+
font-size: 17px; font-weight: 700; letter-spacing: 0.01em;
|
| 152 |
+
font-variant-numeric: tabular-nums;
|
| 153 |
+
}
|
| 154 |
+
.play:hover:not(:disabled) { background: var(--brand-strong); }
|
| 155 |
+
.play:disabled { cursor: progress; opacity: 0.75; }
|
| 156 |
+
.play .i-stop { display: none; }
|
| 157 |
+
.play[data-state="playing"] .i-stop { display: block; }
|
| 158 |
+
.play[data-state="playing"] .i-play { display: none; }
|
| 159 |
+
|
| 160 |
+
.setting { display: inline-flex; align-items: center; gap: 10px; font-size: 15px; color: var(--fg-2); }
|
| 161 |
+
.setting output { font-family: var(--mono); font-size: 14px; color: var(--fg); min-width: 4.5ch; font-variant-numeric: tabular-nums; }
|
| 162 |
+
input[type="range"] { width: 130px; accent-color: var(--brand); }
|
| 163 |
+
.steps label { position: relative; cursor: pointer; }
|
| 164 |
+
.steps input { position: absolute; opacity: 0; inset: 0; margin: 0; cursor: pointer; }
|
| 165 |
+
.steps label span {
|
| 166 |
+
display: inline-flex; align-items: center; justify-content: center; min-width: 36px; height: 32px;
|
| 167 |
+
border: 1px solid var(--line-2); font-family: var(--mono); font-size: 14px; color: var(--fg-2);
|
| 168 |
+
}
|
| 169 |
+
.steps label:first-of-type span { border-radius: var(--radius) 0 0 var(--radius); }
|
| 170 |
+
.steps label:last-of-type span { border-radius: 0 var(--radius) var(--radius) 0; margin-left: -1px; }
|
| 171 |
+
.steps input:checked + span { background: var(--brand-soft); color: var(--brand); border-color: var(--brand); position: relative; }
|
| 172 |
+
.steps input:focus-visible + span { outline: 2px solid var(--brand); outline-offset: 2px; }
|
| 173 |
+
|
| 174 |
+
.progress { height: 2px; background: var(--line); margin-top: 16px; overflow: hidden; border-radius: 1px; }
|
| 175 |
+
.progress span { display: block; height: 100%; width: 0; background: var(--brand); transition: width 120ms linear; }
|
| 176 |
+
.progress[data-done] { visibility: hidden; }
|
| 177 |
+
|
| 178 |
+
.ai-label { display: flex; align-items: center; gap: 8px; margin: 12px 0 0; font-size: 14px; color: var(--warm); font-weight: 500; }
|
| 179 |
+
.ai-label .dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; flex: none; }
|
| 180 |
+
|
| 181 |
+
/* ------------------------------------------------------------------ readout */
|
| 182 |
+
.readout { padding: 20px 0 8px; }
|
| 183 |
+
.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0; margin: 0; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
|
| 184 |
+
.stats > div { padding: 14px 12px 16px; border-left: 1px solid var(--line); min-width: 0; }
|
| 185 |
+
.stats > div:first-child { border-left: 0; padding-left: 0; }
|
| 186 |
+
.stats dt { font-size: 13px; color: var(--fg-2); margin-bottom: 6px; }
|
| 187 |
+
.stats dd { margin: 0; font-family: var(--mono); font-size: 26px; font-weight: 500; line-height: 1.1; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
| 188 |
+
.stats dd small { font-size: 14px; color: var(--fg-3); margin-left: 4px; font-weight: 400; }
|
| 189 |
+
.stats .hero-stat dd { color: var(--brand); }
|
| 190 |
+
.status { font-family: var(--mono); font-size: 13px; color: var(--fg-3); margin: 12px 0 0; min-height: 1.5em; overflow-wrap: anywhere; }
|
| 191 |
+
.status.err { color: var(--err); }
|
| 192 |
+
.reading { margin-top: 14px; font-size: 15px; color: var(--fg-2); }
|
| 193 |
+
.reading summary { cursor: pointer; width: fit-content; }
|
| 194 |
+
.reading summary:hover { color: var(--fg); }
|
| 195 |
+
.mono { font-family: var(--mono); font-size: 14px; color: var(--fg); background: var(--bg-sunk); padding: 10px 12px; border-radius: var(--radius); margin: 8px 0 0; overflow-wrap: anywhere; min-height: 2.5em; }
|
| 196 |
+
.download { margin: 12px 0 0; font-size: 15px; }
|
| 197 |
+
a { color: var(--brand); text-underline-offset: 3px; }
|
| 198 |
+
|
| 199 |
+
.foot { margin-top: auto; padding: 40px 0 28px; font-size: 14px; color: var(--fg-3); display: flex; flex-wrap: wrap; justify-content: space-between; gap: 8px; }
|
| 200 |
+
.foot p { margin: 0; }
|
| 201 |
+
|
| 202 |
+
@media (max-width: 620px) {
|
| 203 |
+
body { font-size: 16px; }
|
| 204 |
+
.intro { padding: 32px 0 20px; }
|
| 205 |
+
.studio { padding: 16px; }
|
| 206 |
+
.stats { grid-template-columns: repeat(2, 1fr); }
|
| 207 |
+
.stats > div:nth-child(3) { border-left: 0; padding-left: 0; }
|
| 208 |
+
.stats > div:nth-child(n + 3) { border-top: 1px solid var(--line); }
|
| 209 |
+
.stats dd { font-size: 22px; }
|
| 210 |
+
.controls { gap: 14px 18px; }
|
| 211 |
+
.play { width: 100%; justify-content: center; }
|
| 212 |
+
}
|
| 213 |
+
@media (prefers-reduced-motion: reduce) { .progress span { transition: none; } }
|
icon.svg
ADDED
|
|
index.html
CHANGED
|
@@ -1,19 +1,95 @@
|
|
| 1 |
<!doctype html>
|
| 2 |
-
<html>
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
</html>
|
|
|
|
| 1 |
<!doctype html>
|
| 2 |
+
<html lang="tr">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<title>Antalia-2 Mini</title>
|
| 7 |
+
<meta name="description" content="Antalia-2 Mini: tarayıcıda, cihazınızda çalışan küçük, açık kaynak Türkçe metinden konuşma modeli.">
|
| 8 |
+
<meta name="color-scheme" content="light dark">
|
| 9 |
+
<link rel="icon" href="icon.svg" type="image/svg+xml">
|
| 10 |
+
<link rel="manifest" href="app.webmanifest">
|
| 11 |
+
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
|
| 12 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
| 13 |
+
<link rel="stylesheet" crossorigin href="https://fonts.googleapis.com/css2?family=Instrument+Serif&family=JetBrains+Mono:wght@400;500&family=Karla:wght@400;500;700&display=swap">
|
| 14 |
+
<link rel="stylesheet" href="css/style.css">
|
| 15 |
+
<script>
|
| 16 |
+
// theme before first paint: a stored choice wins, else the system preference
|
| 17 |
+
try { const t = localStorage.getItem("am-theme"); if (t === "light" || t === "dark") document.documentElement.dataset.theme = t; } catch (e) {}
|
| 18 |
+
</script>
|
| 19 |
+
<script type="module" src="js/app.js"></script>
|
| 20 |
+
</head>
|
| 21 |
+
<body>
|
| 22 |
+
<div class="page">
|
| 23 |
+
<header class="top">
|
| 24 |
+
<span class="wordmark">Antalia-2 Mini</span>
|
| 25 |
+
<nav class="toggles" aria-label="Görünüm">
|
| 26 |
+
<button type="button" class="lang" id="lang" aria-label="Switch to English">EN</button>
|
| 27 |
+
<button type="button" class="theme" id="theme" aria-label="Koyu tema">
|
| 28 |
+
<svg class="i-moon" viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5Z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/></svg>
|
| 29 |
+
<svg class="i-sun" viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><circle cx="12" cy="12" r="4" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M12 2.5v2.5M12 19v2.5M2.5 12H5M19 12h2.5M5.3 5.3l1.8 1.8M16.9 16.9l1.8 1.8M5.3 18.7l1.8-1.8M16.9 7.1l1.8-1.8" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>
|
| 30 |
+
</button>
|
| 31 |
+
</nav>
|
| 32 |
+
</header>
|
| 33 |
+
|
| 34 |
+
<main>
|
| 35 |
+
<section class="intro">
|
| 36 |
+
<h1 data-i18n="title">Tarayıcınızda çalışan Türkçe ses</h1>
|
| 37 |
+
<p class="lead" data-i18n="lead">Antalia-2 Mini, 7,62 milyon parametrelik açık kaynak bir Türkçe metinden konuşma modeli. Bu sayfada tamamen sizin cihazınızda çalışıyor: sunucu yok, yazdığınız metin hiçbir yere gönderilmiyor.</p>
|
| 38 |
+
</section>
|
| 39 |
+
|
| 40 |
+
<section class="studio" aria-labelledby="text-label">
|
| 41 |
+
<label id="text-label" for="text" class="label" data-i18n="textLabel">Metin</label>
|
| 42 |
+
<textarea id="text" rows="3" spellcheck="false" maxlength="2000">15 Ekim'de PatientDesk üzerinden WhatsApp ile 1.250.000 TL ödendi.</textarea>
|
| 43 |
+
<div class="examples" role="group" aria-label="Örnek cümleler" data-i18n-aria="examples">
|
| 44 |
+
<button type="button" class="chip" data-example="0" data-i18n="ex0">Ödeme</button>
|
| 45 |
+
<button type="button" class="chip" data-example="1" data-i18n="ex1">Randevu</button>
|
| 46 |
+
<button type="button" class="chip" data-example="2" data-i18n="ex2">Hava durumu</button>
|
| 47 |
+
<button type="button" class="chip" data-example="3" data-i18n="ex3">Iğdır'dan İstanbul'a</button>
|
| 48 |
+
</div>
|
| 49 |
+
|
| 50 |
+
<div class="controls">
|
| 51 |
+
<button type="button" id="play" class="play" disabled>
|
| 52 |
+
<svg class="i-play" viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path d="M7 4.5v15l12-7.5z" fill="currentColor"/></svg>
|
| 53 |
+
<svg class="i-stop" viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><rect x="6" y="6" width="12" height="12" fill="currentColor"/></svg>
|
| 54 |
+
<span id="play-label" data-i18n="loading">Model yükleniyor</span>
|
| 55 |
+
</button>
|
| 56 |
+
<div class="setting">
|
| 57 |
+
<label for="speed" data-i18n="speed">Hız</label>
|
| 58 |
+
<input type="range" id="speed" min="0.75" max="1.35" step="0.05" value="0.95">
|
| 59 |
+
<output id="speed-out" for="speed">0,95×</output>
|
| 60 |
+
</div>
|
| 61 |
+
<div class="setting steps" role="radiogroup" aria-label="Adım sayısı" data-i18n-aria="steps">
|
| 62 |
+
<span class="setting-name" data-i18n="stepsShort">Adım</span>
|
| 63 |
+
<label><input type="radio" name="steps" value="4"><span>4</span></label>
|
| 64 |
+
<label><input type="radio" name="steps" value="8" checked><span>8</span></label>
|
| 65 |
+
</div>
|
| 66 |
+
</div>
|
| 67 |
+
<div class="progress" id="progress" aria-hidden="true"><span></span></div>
|
| 68 |
+
|
| 69 |
+
<p class="ai-label"><span class="dot" aria-hidden="true"></span><span data-i18n="aiLabel">Yapay zekâ ile üretilmiş ses</span></p>
|
| 70 |
+
</section>
|
| 71 |
+
|
| 72 |
+
<section class="readout" aria-live="polite" aria-labelledby="readout-title">
|
| 73 |
+
<h2 id="readout-title" class="sr-only" data-i18n="readoutTitle">Ölçümler</h2>
|
| 74 |
+
<dl class="stats">
|
| 75 |
+
<div><dt data-i18n="ttfa">İlk ses</dt><dd><span id="r-ttfa">–</span><small>ms</small></dd></div>
|
| 76 |
+
<div><dt data-i18n="gen">Üretim süresi</dt><dd><span id="r-gen">–</span><small>ms</small></dd></div>
|
| 77 |
+
<div><dt data-i18n="len">Ses uzunluğu</dt><dd><span id="r-len">–</span><small>s</small></dd></div>
|
| 78 |
+
<div class="hero-stat"><dt data-i18n="rtf">Gerçek zamandan hızlı</dt><dd><span id="r-rtf">–</span><small>×</small></dd></div>
|
| 79 |
+
</dl>
|
| 80 |
+
<p class="status" id="status"></p>
|
| 81 |
+
<details class="reading">
|
| 82 |
+
<summary data-i18n="reading">Modelin okuduğu metin</summary>
|
| 83 |
+
<p id="model-text" class="mono"></p>
|
| 84 |
+
</details>
|
| 85 |
+
<p class="download" hidden id="download-row"><a id="download" download="antalia-mini.wav" data-i18n="download">WAV olarak indir</a></p>
|
| 86 |
+
</section>
|
| 87 |
+
</main>
|
| 88 |
+
|
| 89 |
+
<footer class="foot">
|
| 90 |
+
<p data-i18n="foot">Apache-2.0 · Model, tarayıcınızda ONNX Runtime Web ile çalışır.</p>
|
| 91 |
+
<p><a href="https://speech.patientdesk.ai" rel="noopener">PatientDesk AI</a></p>
|
| 92 |
+
</footer>
|
| 93 |
+
</div>
|
| 94 |
+
</body>
|
| 95 |
</html>
|
js/app.js
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Page logic: UI, language and theme, playback, and the live readout. The model runs in js/worker.js.
|
| 2 |
+
// URL options for measuring: ?backend=webgpu|wasm &threads=N &precision=mixed|fp32|fp16|int8
|
| 3 |
+
import { STRINGS, EXAMPLES } from "./strings.js";
|
| 4 |
+
|
| 5 |
+
const $ = (s) => document.querySelector(s);
|
| 6 |
+
const params = new URLSearchParams(location.search);
|
| 7 |
+
const OPTS = {
|
| 8 |
+
backend: params.get("backend") || "wasm",
|
| 9 |
+
threads: Number(params.get("threads") || 0),
|
| 10 |
+
precision: params.get("precision") || "mixed",
|
| 11 |
+
};
|
| 12 |
+
const SAMPLE_RATE = 48000;
|
| 13 |
+
|
| 14 |
+
// ------------------------------------------------------------------ language
|
| 15 |
+
let lang = "tr";
|
| 16 |
+
try { if (localStorage.getItem("am-lang") === "en") lang = "en"; } catch (e) {}
|
| 17 |
+
const t = (k) => STRINGS[lang][k] ?? STRINGS.tr[k] ?? k;
|
| 18 |
+
function applyLang() {
|
| 19 |
+
document.documentElement.lang = lang;
|
| 20 |
+
for (const el of document.querySelectorAll("[data-i18n]")) el.textContent = t(el.dataset.i18n);
|
| 21 |
+
for (const el of document.querySelectorAll("[data-i18n-aria]")) el.setAttribute("aria-label", t(el.dataset.i18nAria));
|
| 22 |
+
$("#lang").textContent = lang === "tr" ? "EN" : "TR";
|
| 23 |
+
$("#lang").setAttribute("aria-label", lang === "tr" ? "Switch to English" : "Türkçeye geç");
|
| 24 |
+
document.title = "Antalia-2 Mini";
|
| 25 |
+
renderPlay();
|
| 26 |
+
renderStatus();
|
| 27 |
+
renderSpeed();
|
| 28 |
+
renderTheme();
|
| 29 |
+
}
|
| 30 |
+
$("#lang").addEventListener("click", () => {
|
| 31 |
+
lang = lang === "tr" ? "en" : "tr";
|
| 32 |
+
try { localStorage.setItem("am-lang", lang); } catch (e) {}
|
| 33 |
+
applyLang();
|
| 34 |
+
});
|
| 35 |
+
|
| 36 |
+
// ------------------------------------------------------------------ theme
|
| 37 |
+
function isDark() {
|
| 38 |
+
const d = document.documentElement.dataset.theme;
|
| 39 |
+
return d ? d === "dark" : matchMedia("(prefers-color-scheme: dark)").matches;
|
| 40 |
+
}
|
| 41 |
+
function renderTheme() { $("#theme").setAttribute("aria-label", t(isDark() ? "themeLight" : "themeDark")); }
|
| 42 |
+
matchMedia("(prefers-color-scheme: dark)").addEventListener?.("change", () => renderTheme());
|
| 43 |
+
$("#theme").addEventListener("click", () => {
|
| 44 |
+
const next = isDark() ? "light" : "dark";
|
| 45 |
+
document.documentElement.dataset.theme = next;
|
| 46 |
+
try { localStorage.setItem("am-theme", next); } catch (e) {}
|
| 47 |
+
renderTheme();
|
| 48 |
+
});
|
| 49 |
+
|
| 50 |
+
// ------------------------------------------------------------------ number formatting
|
| 51 |
+
const fmt = (x, d = 0) => new Intl.NumberFormat(lang === "tr" ? "tr-TR" : "en-US", { minimumFractionDigits: d, maximumFractionDigits: d }).format(x);
|
| 52 |
+
const mb = (b) => fmt(b / 1e6, 1);
|
| 53 |
+
|
| 54 |
+
// ------------------------------------------------------------------ worker
|
| 55 |
+
const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
|
| 56 |
+
let ready = false, info = null, loadState = { loaded: 0, total: 0 }, errorMsg = "";
|
| 57 |
+
let current = null; // the utterance being generated / played
|
| 58 |
+
let pending = null; // a request made before the model was ready
|
| 59 |
+
let lastStats = null;
|
| 60 |
+
|
| 61 |
+
worker.onmessage = (ev) => {
|
| 62 |
+
const m = ev.data;
|
| 63 |
+
if (m.type === "progress") {
|
| 64 |
+
loadState = m;
|
| 65 |
+
$("#progress span").style.width = m.total ? `${Math.min(100, (100 * m.loaded) / m.total)}%` : "0";
|
| 66 |
+
renderPlay();
|
| 67 |
+
} else if (m.type === "ready") {
|
| 68 |
+
ready = true; info = m.info;
|
| 69 |
+
$("#progress").dataset.done = "";
|
| 70 |
+
window.amInfo = info;
|
| 71 |
+
applyDefaults(info.defaults);
|
| 72 |
+
console.info("[antalia-mini] ready", info);
|
| 73 |
+
renderPlay(); renderStatus();
|
| 74 |
+
if (pending) { const p = pending; pending = null; speak({ ...p, t0: performance.now() }); }
|
| 75 |
+
} else if (m.type === "error") {
|
| 76 |
+
errorMsg = m.message;
|
| 77 |
+
console.error("[antalia-mini]", m.message);
|
| 78 |
+
if (current && m.id === current.id) finish();
|
| 79 |
+
renderStatus(); renderPlay();
|
| 80 |
+
} else if (current && m.id === current.id) {
|
| 81 |
+
if (m.type === "text") $("#model-text").textContent = m.modelText;
|
| 82 |
+
else if (m.type === "chunk") onChunk(m);
|
| 83 |
+
else if (m.type === "done") onDone(m.stats);
|
| 84 |
+
}
|
| 85 |
+
};
|
| 86 |
+
|
| 87 |
+
function startLoading() {
|
| 88 |
+
if (startLoading.started) return;
|
| 89 |
+
startLoading.started = true;
|
| 90 |
+
worker.postMessage({ type: "init", ...OPTS });
|
| 91 |
+
renderPlay();
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
// ------------------------------------------------------------------ playback
|
| 95 |
+
let ctx = null, sources = [], nextTime = 0;
|
| 96 |
+
function audioContext() {
|
| 97 |
+
if (!ctx) {
|
| 98 |
+
try { ctx = new AudioContext({ sampleRate: SAMPLE_RATE, latencyHint: "interactive" }); }
|
| 99 |
+
catch (e) { ctx = new AudioContext(); }
|
| 100 |
+
}
|
| 101 |
+
if (ctx.state === "suspended") ctx.resume();
|
| 102 |
+
return ctx;
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
let nextId = 1;
|
| 106 |
+
function speak(req) {
|
| 107 |
+
if (!ready) { pending = req; renderPlay(); return; }
|
| 108 |
+
stop();
|
| 109 |
+
errorMsg = "";
|
| 110 |
+
current = { id: nextId++, t0: req.t0, chunks: [], firstMs: null, playing: true };
|
| 111 |
+
for (const k of ["#r-ttfa", "#r-gen", "#r-len", "#r-rtf"]) $(k).textContent = "–";
|
| 112 |
+
renderPlay();
|
| 113 |
+
worker.postMessage({ type: "synth", id: current.id, text: req.text, steps: req.steps, speed: req.speed, seed: 0 });
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
function onChunk(m) {
|
| 117 |
+
const c = audioContext();
|
| 118 |
+
const audio = m.audio;
|
| 119 |
+
current.chunks.push(audio);
|
| 120 |
+
if (current.firstMs === null) {
|
| 121 |
+
current.firstMs = performance.now() - current.t0;
|
| 122 |
+
nextTime = c.currentTime + 0.01;
|
| 123 |
+
$("#r-ttfa").textContent = fmt(current.firstMs);
|
| 124 |
+
}
|
| 125 |
+
const buf = c.createBuffer(1, audio.length, SAMPLE_RATE);
|
| 126 |
+
buf.copyToChannel(audio, 0);
|
| 127 |
+
const src = c.createBufferSource();
|
| 128 |
+
src.buffer = buf;
|
| 129 |
+
src.connect(c.destination);
|
| 130 |
+
const at = Math.max(nextTime, c.currentTime + 0.005);
|
| 131 |
+
src.start(at);
|
| 132 |
+
nextTime = at + buf.duration; // each chunk already ends with the pause before the next (as Antalia.stream)
|
| 133 |
+
sources.push(src);
|
| 134 |
+
const u = current;
|
| 135 |
+
src.onended = () => {
|
| 136 |
+
u.ended = (u.ended || 0) + 1;
|
| 137 |
+
if (current === u && u.done && u.ended === u.chunks.length) finish();
|
| 138 |
+
};
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
function onDone(stats) {
|
| 142 |
+
current.done = true;
|
| 143 |
+
current.stats = stats;
|
| 144 |
+
lastStats = { ...stats, firstMs: current.firstMs };
|
| 145 |
+
window.amLast = lastStats;
|
| 146 |
+
$("#r-gen").textContent = fmt(stats.computeMs);
|
| 147 |
+
$("#r-len").textContent = fmt(stats.seconds, 2);
|
| 148 |
+
$("#r-rtf").textContent = fmt((stats.seconds * 1000) / stats.computeMs);
|
| 149 |
+
makeDownload(current.chunks);
|
| 150 |
+
renderStatus();
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
function finish() {
|
| 154 |
+
if (current) current.playing = false;
|
| 155 |
+
current = null;
|
| 156 |
+
renderPlay();
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
function stop() {
|
| 160 |
+
for (const s of sources) { try { s.stop(); } catch (e) {} }
|
| 161 |
+
sources = [];
|
| 162 |
+
if (current) { current.playing = false; current = null; }
|
| 163 |
+
renderPlay();
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
function makeDownload(chunks) {
|
| 167 |
+
// the chunks joined are Antalia().say's audio; 16-bit PCM as Speech.save writes .wav
|
| 168 |
+
const n = chunks.reduce((a, c) => a + c.length, 0);
|
| 169 |
+
if (!n) return;
|
| 170 |
+
const pcm = new Int16Array(n);
|
| 171 |
+
let o = 0;
|
| 172 |
+
for (const c of chunks) {
|
| 173 |
+
for (let j = 0; j < c.length; j++) pcm[o + j] = Math.max(-32768, Math.min(32767, Math.round(c[j] * 32767)));
|
| 174 |
+
o += c.length;
|
| 175 |
+
}
|
| 176 |
+
const header = new DataView(new ArrayBuffer(44));
|
| 177 |
+
const w = (off, s) => [...s].forEach((ch, i) => header.setUint8(off + i, ch.charCodeAt(0)));
|
| 178 |
+
w(0, "RIFF"); header.setUint32(4, 36 + pcm.byteLength, true); w(8, "WAVE"); w(12, "fmt ");
|
| 179 |
+
header.setUint32(16, 16, true); header.setUint16(20, 1, true); header.setUint16(22, 1, true);
|
| 180 |
+
header.setUint32(24, SAMPLE_RATE, true); header.setUint32(28, SAMPLE_RATE * 2, true);
|
| 181 |
+
header.setUint16(32, 2, true); header.setUint16(34, 16, true); w(36, "data"); header.setUint32(40, pcm.byteLength, true);
|
| 182 |
+
const a = $("#download");
|
| 183 |
+
if (a.href) URL.revokeObjectURL(a.href);
|
| 184 |
+
a.href = URL.createObjectURL(new Blob([header, pcm], { type: "audio/wav" }));
|
| 185 |
+
$("#download-row").hidden = false;
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
// ------------------------------------------------------------------ controls
|
| 189 |
+
function steps() { return Number(document.querySelector('input[name="steps"]:checked').value); }
|
| 190 |
+
function speed() { return Number($("#speed").value); }
|
| 191 |
+
function renderSpeed() { $("#speed-out").textContent = `${fmt(speed(), 2)}×`; }
|
| 192 |
+
let touched = false; // the visitor changed speed or steps: keep their choice
|
| 193 |
+
$("#speed").addEventListener("input", () => { touched = true; renderSpeed(); });
|
| 194 |
+
for (const r of document.querySelectorAll('input[name="steps"]')) r.addEventListener("change", () => { touched = true; });
|
| 195 |
+
/** The controls start at the release's defaults (models/manifest.json), as Antalia().say uses them. */
|
| 196 |
+
function applyDefaults(d) {
|
| 197 |
+
if (!d || touched) return;
|
| 198 |
+
$("#speed").value = String(d.speed);
|
| 199 |
+
const r = document.querySelector(`input[name="steps"][value="${d.steps}"]`);
|
| 200 |
+
if (r) r.checked = true;
|
| 201 |
+
renderSpeed();
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
function renderPlay() {
|
| 205 |
+
const b = $("#play"), label = $("#play-label");
|
| 206 |
+
const playing = !!(current && current.playing);
|
| 207 |
+
b.dataset.state = playing ? "playing" : "idle";
|
| 208 |
+
if (ready) {
|
| 209 |
+
b.disabled = false;
|
| 210 |
+
label.textContent = playing ? t("stop") : t("play");
|
| 211 |
+
} else if (!startLoading.started) {
|
| 212 |
+
b.disabled = false;
|
| 213 |
+
label.textContent = t("loadModel");
|
| 214 |
+
} else {
|
| 215 |
+
const pct = loadState.total ? Math.round((100 * loadState.loaded) / loadState.total) : 0;
|
| 216 |
+
b.disabled = true;
|
| 217 |
+
label.textContent = errorMsg ? t("failed") : `${t("loading")} ${fmt(pct)}%`;
|
| 218 |
+
}
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
function renderStatus() {
|
| 222 |
+
const el = $("#status");
|
| 223 |
+
el.classList.toggle("err", !!errorMsg);
|
| 224 |
+
if (errorMsg) { el.textContent = `${t("error")}: ${errorMsg}`; return; }
|
| 225 |
+
if (!info) {
|
| 226 |
+
el.textContent = loadState.total ? `${t("downloading")} ${mb(loadState.loaded)} / ${mb(loadState.total)} MB` : "";
|
| 227 |
+
return;
|
| 228 |
+
}
|
| 229 |
+
const be = info.backend === "webgpu" ? "WebGPU" : `WASM SIMD · ${info.threads} ${t(info.threads === 1 ? "thread" : "threads")}`;
|
| 230 |
+
const parts = [be, info.precision, `${mb(info.bytes)} MB`];
|
| 231 |
+
if (lastStats) parts.push(`${t("chunks")} ${lastStats.chunks}`);
|
| 232 |
+
el.textContent = parts.join(" · ");
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
$("#play").addEventListener("click", () => {
|
| 236 |
+
if (current && current.playing) { stop(); return; }
|
| 237 |
+
const text = $("#text").value.trim();
|
| 238 |
+
if (!text) return;
|
| 239 |
+
audioContext(); // unlock audio inside the click
|
| 240 |
+
const req = { text, steps: steps(), speed: speed(), t0: performance.now() };
|
| 241 |
+
if (!startLoading.started) { pending = req; startLoading(); renderPlay(); return; }
|
| 242 |
+
speak(req);
|
| 243 |
+
});
|
| 244 |
+
$("#text").addEventListener("keydown", (e) => {
|
| 245 |
+
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); $("#play").click(); }
|
| 246 |
+
});
|
| 247 |
+
$("#text").addEventListener("input", () => {
|
| 248 |
+
for (const c of document.querySelectorAll(".chip")) c.setAttribute("aria-pressed", "false");
|
| 249 |
+
});
|
| 250 |
+
for (const c of document.querySelectorAll(".chip")) {
|
| 251 |
+
c.setAttribute("aria-pressed", c.dataset.example === "0" ? "true" : "false");
|
| 252 |
+
c.addEventListener("click", () => {
|
| 253 |
+
$("#text").value = EXAMPLES[Number(c.dataset.example)];
|
| 254 |
+
for (const o of document.querySelectorAll(".chip")) o.setAttribute("aria-pressed", o === c ? "true" : "false");
|
| 255 |
+
if (ready) $("#play").click();
|
| 256 |
+
});
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
// ------------------------------------------------------------------ measurement hook (console / automation)
|
| 260 |
+
// await amBench({runs: 3}) synthesises every example `runs` times without playing and returns the timings
|
| 261 |
+
// (steps and speed default to the release's, as the page's controls do).
|
| 262 |
+
window.amBench = async ({ runs = 3, steps: st, speed: sp } = {}) => {
|
| 263 |
+
while (!ready) await new Promise((r) => setTimeout(r, 100));
|
| 264 |
+
const out = [];
|
| 265 |
+
for (let r = 0; r < runs; r++) {
|
| 266 |
+
for (const text of EXAMPLES) {
|
| 267 |
+
const res = await new Promise((resolve) => {
|
| 268 |
+
const id = nextId++;
|
| 269 |
+
const t0 = performance.now();
|
| 270 |
+
let first = null;
|
| 271 |
+
const h = (ev) => {
|
| 272 |
+
const m = ev.data;
|
| 273 |
+
if (m.id !== id) return;
|
| 274 |
+
if (m.type === "chunk" && first === null) first = performance.now() - t0;
|
| 275 |
+
if (m.type === "done") { worker.removeEventListener("message", h); resolve({ text, firstMs: first, ...m.stats }); }
|
| 276 |
+
if (m.type === "error") { worker.removeEventListener("message", h); resolve({ text, error: m.message }); }
|
| 277 |
+
};
|
| 278 |
+
worker.addEventListener("message", h);
|
| 279 |
+
worker.postMessage({ type: "synth", id, text, steps: st, speed: sp, seed: 0 });
|
| 280 |
+
});
|
| 281 |
+
out.push({ ...res, xRealtime: (res.seconds * 1000) / res.computeMs });
|
| 282 |
+
}
|
| 283 |
+
}
|
| 284 |
+
return { info, runs: out };
|
| 285 |
+
};
|
| 286 |
+
|
| 287 |
+
// ------------------------------------------------------------------ start
|
| 288 |
+
applyLang();
|
| 289 |
+
renderTheme();
|
| 290 |
+
|
| 291 |
+
// The service worker caches everything for offline use and adds the COOP/COEP headers that make the page
|
| 292 |
+
// cross-origin isolated, which ONNX Runtime needs for threads (about 2x faster here). Static hosts do not
|
| 293 |
+
// send those headers, so the first visit reloads once, as soon as the worker controls the page, before the
|
| 294 |
+
// model is downloaded. If isolation still fails (e.g. inside an iframe), the model runs on one thread.
|
| 295 |
+
async function prepare() {
|
| 296 |
+
if (!("serviceWorker" in navigator) || !window.isSecureContext) return;
|
| 297 |
+
try {
|
| 298 |
+
await navigator.serviceWorker.register("sw.js");
|
| 299 |
+
} catch (e) {
|
| 300 |
+
console.warn("service worker", e);
|
| 301 |
+
return;
|
| 302 |
+
}
|
| 303 |
+
let tried = false;
|
| 304 |
+
try { tried = sessionStorage.getItem("am-coi") === "1"; } catch (e) { tried = true; }
|
| 305 |
+
if (window.crossOriginIsolated || tried || params.has("noreload")) return;
|
| 306 |
+
try { sessionStorage.setItem("am-coi", "1"); } catch (e) { return; }
|
| 307 |
+
if (!navigator.serviceWorker.controller) {
|
| 308 |
+
await new Promise((r) => {
|
| 309 |
+
navigator.serviceWorker.addEventListener("controllerchange", r, { once: true });
|
| 310 |
+
setTimeout(r, 3000);
|
| 311 |
+
});
|
| 312 |
+
}
|
| 313 |
+
if (navigator.serviceWorker.controller) { location.reload(); await new Promise(() => {}); }
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
const saveData = navigator.connection && navigator.connection.saveData;
|
| 317 |
+
prepare().then(() => {
|
| 318 |
+
// on a data-saver connection the model (about 23 MB, plus the runtime) waits for the first press
|
| 319 |
+
if (!saveData) startLoading();
|
| 320 |
+
renderPlay();
|
| 321 |
+
});
|
| 322 |
+
renderPlay();
|
js/frontend.js
ADDED
|
@@ -0,0 +1,1126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Antalia Mini text frontend, ported from antalia_mini/text (__init__.py, normalize.py, foreign.py)
|
| 2 |
+
// to a dependency-free ES module for browsers (Chrome, Safari 16.4+) and Node.
|
| 3 |
+
//
|
| 4 |
+
// const fe = await loadFrontend("assets/frontend-data.json.gz");
|
| 5 |
+
// fe.toModelText("15 Ekim'de 1.250.000 TL ödendi.") // == antalia_mini.text.to_model_text
|
| 6 |
+
// fe.encode(fe.toModelText(raw)) // == antalia_mini.text.encode
|
| 7 |
+
//
|
| 8 |
+
// The Python is the source of truth; every function below mirrors one there, in the same order, and
|
| 9 |
+
// web/tests/parity/run_parity.mjs checks exact output equality. Python regular expressions are
|
| 10 |
+
// written here in Python syntax and translated by `py()` (Unicode \w \d \s \b, Python $, and the
|
| 11 |
+
// IGNORECASE rule that i, I, ı and İ all match each other). Where Python raises (a KeyError in
|
| 12 |
+
// `_respell_span` for a lexicon term matched with a dotless ı, e.g. "ınstagram"), this port throws an
|
| 13 |
+
// Error whose name is the Python exception's.
|
| 14 |
+
//
|
| 15 |
+
// Data (CMU respellings, Turkish vocabulary sets, reviewed lexicon) comes from the asset built by
|
| 16 |
+
// web/tools/build_frontend_data.py.
|
| 17 |
+
//
|
| 18 |
+
// Known residual difference: the Unicode version. Python 3.12's unicodedata is Unicode 15.0; JS
|
| 19 |
+
// engines use their own (Node 24: 17.0). For characters assigned after 15.0 (new emoji, scripts),
|
| 20 |
+
// \p{L}/\p{N}/\p{So}, NFKC and case mappings can disagree with Python (e.g. a new emoji is dropped
|
| 21 |
+
// as So here but kept by Python, which sees it as unassigned). Everything else is exact as far as
|
| 22 |
+
// the parity test reaches (web/tests/parity: 1167 sentences, 100%). Python int() is unbounded, so
|
| 23 |
+
// numbers are BigInt here; \d is Unicode Nd as in Python (Arabic-Indic digits are read too).
|
| 24 |
+
|
| 25 |
+
// ---------------------------------------------------------------- Python regex translation
|
| 26 |
+
|
| 27 |
+
const W = "\\p{L}\\p{N}_"; // Python 3 str \w: str.isalnum() or "_"
|
| 28 |
+
const S = "\\t-\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000"; // str.isspace()
|
| 29 |
+
const BOUNDARY = `(?:(?<=[${W}])(?![${W}])|(?<![${W}])(?=[${W}]))`; // Unicode \b
|
| 30 |
+
const I4 = "iIıİ"; // re.IGNORECASE: each of these matches all four
|
| 31 |
+
const JS_SYNTAX = "^$\\.*+?()[]{}|/";
|
| 32 |
+
const CLASS_SPECIAL = {
|
| 33 |
+
"^\\W\\d_": "[\\p{L}\\p{Nl}\\p{No}]", // letters (and non-decimal numerics), as Python's [^\W\d_]
|
| 34 |
+
"^\\W_": "[\\p{L}\\p{N}]",
|
| 35 |
+
};
|
| 36 |
+
const reCache = new Map();
|
| 37 |
+
|
| 38 |
+
/** Translate a Python `re` pattern (str, Unicode) to an equivalent JS RegExp ("u" is always on;
|
| 39 |
+
* "i" means re.IGNORECASE). */
|
| 40 |
+
function py(src, flags = "") {
|
| 41 |
+
const cacheKey = flags + "\u0000" + src;
|
| 42 |
+
const hit = reCache.get(cacheKey);
|
| 43 |
+
if (hit) return hit;
|
| 44 |
+
const ic = flags.includes("i");
|
| 45 |
+
let out = "";
|
| 46 |
+
let i = 0;
|
| 47 |
+
while (i < src.length) {
|
| 48 |
+
const c = src[i];
|
| 49 |
+
if (c === "\\") {
|
| 50 |
+
const d = src[i + 1];
|
| 51 |
+
i += 2;
|
| 52 |
+
if (d === "w") out += `[${W}]`;
|
| 53 |
+
else if (d === "W") out += `[^${W}]`;
|
| 54 |
+
else if (d === "d") out += "\\p{Nd}";
|
| 55 |
+
else if (d === "D") out += "\\P{Nd}";
|
| 56 |
+
else if (d === "s") out += `[${S}]`;
|
| 57 |
+
else if (d === "S") out += `[^${S}]`;
|
| 58 |
+
else if (d === "b") out += BOUNDARY;
|
| 59 |
+
else if (/[1-9]/.test(d)) out += "\\" + d;
|
| 60 |
+
else if (/[A-Za-z0]/.test(d)) throw new Error(`py(): unsupported escape \\${d} in ${src}`);
|
| 61 |
+
else out += literal(d, ic);
|
| 62 |
+
continue;
|
| 63 |
+
}
|
| 64 |
+
if (c === "[") {
|
| 65 |
+
const [cls, next] = translateClass(src, i, ic);
|
| 66 |
+
out += cls;
|
| 67 |
+
i = next;
|
| 68 |
+
continue;
|
| 69 |
+
}
|
| 70 |
+
if (c === ".") out += "[^\\n]";
|
| 71 |
+
else if (c === "$") out += "(?=\\n?(?![\\s\\S]))"; // Python $: the end, or before a final newline
|
| 72 |
+
else if (c === "(" && src[i + 1] === "?" && src[i + 2] === "P") throw new Error("py(): named groups unsupported");
|
| 73 |
+
else if (ic && I4.includes(c)) out += "[iIıİ]";
|
| 74 |
+
else out += c;
|
| 75 |
+
i++;
|
| 76 |
+
}
|
| 77 |
+
const re = new RegExp(out, "u" + flags);
|
| 78 |
+
reCache.set(cacheKey, re);
|
| 79 |
+
return re;
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
function literal(ch, ic) {
|
| 83 |
+
if (JS_SYNTAX.includes(ch)) return "\\" + ch;
|
| 84 |
+
if (ic && I4.includes(ch)) return "[iIıİ]";
|
| 85 |
+
return ch;
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
function translateClass(src, start, ic) {
|
| 89 |
+
let j = start + 1;
|
| 90 |
+
if (src[j] === "^") j++;
|
| 91 |
+
if (src[j] === "]") j++; // a "]" first in the class is literal in Python
|
| 92 |
+
while (src[j] !== "]") {
|
| 93 |
+
if (src[j] === "\\") j++;
|
| 94 |
+
j++;
|
| 95 |
+
if (j >= src.length) throw new Error("py(): unterminated class in " + src);
|
| 96 |
+
}
|
| 97 |
+
const raw = src.slice(start + 1, j);
|
| 98 |
+
if (CLASS_SPECIAL[raw]) return [CLASS_SPECIAL[raw], j + 1];
|
| 99 |
+
let k = 0;
|
| 100 |
+
let neg = "";
|
| 101 |
+
if (raw[0] === "^") {
|
| 102 |
+
neg = "^";
|
| 103 |
+
k = 1;
|
| 104 |
+
}
|
| 105 |
+
let body = "";
|
| 106 |
+
for (; k < raw.length; k++) {
|
| 107 |
+
const c = raw[k];
|
| 108 |
+
if (c === "\\") {
|
| 109 |
+
const d = raw[++k];
|
| 110 |
+
if (d === "w") body += W;
|
| 111 |
+
else if (d === "d") body += "\\p{Nd}";
|
| 112 |
+
else if (d === "s") body += S;
|
| 113 |
+
else if (/[A-Za-z0-9]/.test(d)) throw new Error(`py(): unsupported class escape \\${d} in ${src}`);
|
| 114 |
+
else body += "-]\\^[".includes(d) ? "\\" + d : d;
|
| 115 |
+
} else if (c === "[") body += "\\[";
|
| 116 |
+
else if (c === "]") body += "\\]";
|
| 117 |
+
else body += c;
|
| 118 |
+
}
|
| 119 |
+
if (ic) {
|
| 120 |
+
const probe = new RegExp(`[${body}]`, "iu");
|
| 121 |
+
if ([...I4].some((ch) => probe.test(ch))) body += I4;
|
| 122 |
+
}
|
| 123 |
+
return [`[${neg}${body}]`, j + 1];
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
/** Python re.escape (3.7+): escapes ()[]{}?*+-|^$\.&~# and whitespace controls. */
|
| 127 |
+
function pyEscape(s) {
|
| 128 |
+
return s.replace(/[()[\]{}?*+\-|^$\\.&~# \t\n\r\v\f]/g, "\\$&");
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
const g = (src, flags = "") => py(src, "g" + flags);
|
| 132 |
+
|
| 133 |
+
/** re.sub with a function: the callback gets a match-like array (m[0], m[1]..., m.index, m.input);
|
| 134 |
+
* unmatched groups are undefined (Python None). */
|
| 135 |
+
function sub(re, text, fn) {
|
| 136 |
+
return text.replace(re, (...args) => {
|
| 137 |
+
let n = args.length;
|
| 138 |
+
if (typeof args[n - 1] === "object" && args[n - 1] !== null) n--; // named groups object
|
| 139 |
+
const input = args[n - 1];
|
| 140 |
+
const index = args[n - 2];
|
| 141 |
+
const m = args.slice(0, n - 2);
|
| 142 |
+
m.index = index;
|
| 143 |
+
m.input = input;
|
| 144 |
+
return fn(m);
|
| 145 |
+
});
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
const endCache = new Map();
|
| 149 |
+
function endAnchored(src, flags) {
|
| 150 |
+
const key = flags + "\u0000" + src;
|
| 151 |
+
let re = endCache.get(key);
|
| 152 |
+
if (!re) {
|
| 153 |
+
re = new RegExp("^(?:" + py(src, flags).source + ")(?![\\s\\S])", "u" + flags);
|
| 154 |
+
endCache.set(key, re);
|
| 155 |
+
}
|
| 156 |
+
return re;
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
// ---------------------------------------------------------------- Python str helpers
|
| 160 |
+
|
| 161 |
+
class PyError extends Error {
|
| 162 |
+
constructor(name, message) {
|
| 163 |
+
super(message);
|
| 164 |
+
this.name = name;
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
/** Strict dict lookup: a missing key raises KeyError, as Python's d[k]. */
|
| 169 |
+
function getKey(map, key) {
|
| 170 |
+
const v = map.get(key);
|
| 171 |
+
if (v === undefined) throw new PyError("KeyError", JSON.stringify(key));
|
| 172 |
+
return v;
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
const cps = (s) => Array.from(s); // Python indexes strings by code point
|
| 176 |
+
const cpLen = (s) => {
|
| 177 |
+
let n = 0;
|
| 178 |
+
for (const _ of s) n++;
|
| 179 |
+
return n;
|
| 180 |
+
};
|
| 181 |
+
const lastChar = (s) => {
|
| 182 |
+
const a = cps(s);
|
| 183 |
+
return a[a.length - 1];
|
| 184 |
+
};
|
| 185 |
+
const firstChar = (s) => (s === "" ? "" : String.fromCodePoint(s.codePointAt(0)));
|
| 186 |
+
const RE_UPPER = /[\p{Uppercase}]/u;
|
| 187 |
+
const RE_LOWER = /[\p{Lowercase}]/u;
|
| 188 |
+
const RE_TITLE = /\p{Lt}/u;
|
| 189 |
+
const RE_ALPHA = /^\p{L}+$/u;
|
| 190 |
+
const RE_ASCII = /^[\x00-\x7f]*$/;
|
| 191 |
+
const RE_ND = /^\p{Nd}$/u;
|
| 192 |
+
const RE_SPACE_RUN = new RegExp(`[${S}]+`, "gu");
|
| 193 |
+
const RE_STRIP = new RegExp(`^[${S}]+|[${S}]+$`, "gu");
|
| 194 |
+
|
| 195 |
+
function isUpper(s) {
|
| 196 |
+
let cased = false;
|
| 197 |
+
for (const c of s) {
|
| 198 |
+
if (RE_LOWER.test(c) || RE_TITLE.test(c)) return false;
|
| 199 |
+
if (RE_UPPER.test(c)) cased = true;
|
| 200 |
+
}
|
| 201 |
+
return cased;
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
function isLower(s) {
|
| 205 |
+
let cased = false;
|
| 206 |
+
for (const c of s) {
|
| 207 |
+
if (RE_UPPER.test(c) || RE_TITLE.test(c)) return false;
|
| 208 |
+
if (RE_LOWER.test(c)) cased = true;
|
| 209 |
+
}
|
| 210 |
+
return cased;
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
const isAlpha = (s) => RE_ALPHA.test(s);
|
| 214 |
+
const isAscii = (s) => RE_ASCII.test(s);
|
| 215 |
+
const isDigitStr = (s) => s.length > 0 && cps(s).every((c) => RE_ND.test(c));
|
| 216 |
+
const pyStrip = (s) => s.replace(RE_STRIP, "");
|
| 217 |
+
const pySplit = (s) => s.split(RE_SPACE_RUN).filter((x) => x !== "");
|
| 218 |
+
const pyLower = (s) => s.toLowerCase();
|
| 219 |
+
const pyUpper = (s) => s.toUpperCase();
|
| 220 |
+
const capitalize = (s) => (s === "" ? "" : pyUpper(firstChar(s)) + pyLower(s.slice(firstChar(s).length)));
|
| 221 |
+
|
| 222 |
+
/** Value of a Unicode decimal digit (Nd comes in contiguous runs of 0..9). */
|
| 223 |
+
function digitValue(ch) {
|
| 224 |
+
const cp = ch.codePointAt(0);
|
| 225 |
+
if (cp >= 48 && cp <= 57) return cp - 48;
|
| 226 |
+
let start = cp;
|
| 227 |
+
while (RE_ND.test(String.fromCodePoint(start - 1))) start--;
|
| 228 |
+
return (cp - start) % 10;
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
/** Python int() of a string of decimal digits, as a BigInt (Python ints are unbounded). */
|
| 232 |
+
function pyInt(s) {
|
| 233 |
+
if (/^[0-9]+$/.test(s)) return BigInt(s);
|
| 234 |
+
let n = 0n;
|
| 235 |
+
for (const c of s) {
|
| 236 |
+
if (!RE_ND.test(c)) throw new PyError("ValueError", `invalid literal for int(): ${s}`);
|
| 237 |
+
n = n * 10n + BigInt(digitValue(c));
|
| 238 |
+
}
|
| 239 |
+
return n;
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
const ljust = (s, width, fill) => s + fill.repeat(Math.max(0, width - cpLen(s)));
|
| 243 |
+
const map = (obj) => new Map(Object.entries(obj));
|
| 244 |
+
const translate = (s, table) => {
|
| 245 |
+
let out = "";
|
| 246 |
+
for (const c of s) {
|
| 247 |
+
const r = table.get(c);
|
| 248 |
+
out += r === undefined ? c : r;
|
| 249 |
+
}
|
| 250 |
+
return out;
|
| 251 |
+
};
|
| 252 |
+
|
| 253 |
+
// ---------------------------------------------------------------- normalize.py
|
| 254 |
+
|
| 255 |
+
const _WHITESPACE = g("\\s+");
|
| 256 |
+
const _LETTER_THEN_DIGIT = g("(?<=[^\\W\\d_])(?=\\d)");
|
| 257 |
+
const _DIGIT_THEN_LETTER = g("(?<=\\d)(?=[^\\W\\d_])");
|
| 258 |
+
const _LONE_LETTER_BY_DIGIT = g("\\b([A-ZÇĞİÖŞÜQWX])(?= \\d)|(?<=\\d )([A-ZÇĞİÖŞÜQWX])\\b");
|
| 259 |
+
const _APOSTROPHES = map({ "’": "'", "‘": "'", "`": "'", "´": "'" });
|
| 260 |
+
const _QUOTES = new Set('"“”„«»');
|
| 261 |
+
const _TURKISH_CASE = map({ I: "ı", İ: "i" });
|
| 262 |
+
const _EMAIL = g("\\b[\\w.+-]+@[\\w-]+(?:\\.[\\w-]+)+\\b");
|
| 263 |
+
const _URL = g(
|
| 264 |
+
"\\b(?:https?://)?(?:www\\.)?[a-z0-9-]+(?:\\.[a-z0-9-]+)*\\.(?:com|net|org|gov|edu|info|io|ai|tr)\\b(?:/[\\w./-]*)?",
|
| 265 |
+
"i",
|
| 266 |
+
);
|
| 267 |
+
const _ADDRESS_WORDS = map({
|
| 268 |
+
www: "dabılyu dabılyu dabılyu",
|
| 269 |
+
com: "kom",
|
| 270 |
+
net: "net",
|
| 271 |
+
org: "org",
|
| 272 |
+
gov: "gov",
|
| 273 |
+
info: "info",
|
| 274 |
+
gmail: "cimeyl",
|
| 275 |
+
hotmail: "hotmeyl",
|
| 276 |
+
outlook: "autluk",
|
| 277 |
+
yahoo: "yahu",
|
| 278 |
+
icloud: "ayklaud",
|
| 279 |
+
});
|
| 280 |
+
const _RANGE = g("(?<![\\d\\-–])(\\d[\\d.:,]*)\\s*[-–]\\s*(\\d[\\d.:,]*)(?![\\d\\-–])");
|
| 281 |
+
const _PHONE = g("(?<!\\d)(\\+90[\\s-]?)?(0?)\\(?(\\d{3})\\)?[\\s-]?(\\d{3})[\\s-]?(\\d{2})[\\s-]?(\\d{2})(?!\\d)");
|
| 282 |
+
const _VOWELS = new Set("aeıioöuüAEIİOÖUÜ");
|
| 283 |
+
const _PER_UNIT = map({ sn: "saniye", sa: "saat", dk: "dakika" });
|
| 284 |
+
const _CAPS_LEXICON = map({
|
| 285 |
+
MR: "emar", SMS: "esemes", NTV: "entivi", YÖK: "yök", BİM: "bim", ŞOK: "şok", COVID: "kovid",
|
| 286 |
+
MEB: "meb", İTÜ: "itü", IBAN: "iban", İETT: "ietete", ALO: "alo", MİT: "mit", OK: "okey",
|
| 287 |
+
TSH: "teseha", MHRS: "meharese", HES: "hes",
|
| 288 |
+
CEO: "siio", PR: "piar", DJ: "dijey", TV: "tivi", FBI: "efbiay", CNN: "sienen", VIP: "viaypi",
|
| 289 |
+
HD: "heyçdi",
|
| 290 |
+
});
|
| 291 |
+
const _CAPS_WORD_SRC = "\\b[A-ZÇĞİÖŞÜQWX]{2,}\\b";
|
| 292 |
+
const _CAPS_WORD = g(_CAPS_WORD_SRC);
|
| 293 |
+
const _WORD = g("\\b[^\\W\\d_]{2,}\\b");
|
| 294 |
+
const _ONES = ["sıfır", "bir", "iki", "üç", "dört", "beş", "altı", "yedi", "sekiz", "dokuz"];
|
| 295 |
+
const _TENS = ["", "on", "yirmi", "otuz", "kırk", "elli", "altmış", "yetmiş", "seksen", "doksan"];
|
| 296 |
+
const _MONTHS = new Map([
|
| 297 |
+
[1, "ocak"], [2, "şubat"], [3, "mart"], [4, "nisan"], [5, "mayıs"], [6, "haziran"],
|
| 298 |
+
[7, "temmuz"], [8, "ağustos"], [9, "eylül"], [10, "ekim"], [11, "kasım"], [12, "aralık"],
|
| 299 |
+
]);
|
| 300 |
+
const _ABBREVIATIONS = [
|
| 301 |
+
["dr.", "doktor"], ["prof.", "profesör"], ["vb.", "ve benzeri"], ["vs.", "vesaire"], ["örn.", "örneğin"],
|
| 302 |
+
["no.", "numara"], ["mg", "miligram"], ["kg", "kilogram"], ["gr", "gram"], ["km", "kilometre"],
|
| 303 |
+
["cm", "santimetre"], ["mm", "milimetre"], ["lt", "litre"], ["ml", "mililitre"], ["kb", "kilobayt"],
|
| 304 |
+
["mb", "megabayt"], ["gb", "gigabayt"], ["tb", "terabayt"], ["tl", "lira"],
|
| 305 |
+
["doç.", "doçent"], ["uzm.", "uzman"], ["op.", "operatör"], ["yrd.", "yardımcı"],
|
| 306 |
+
["öğr. üyesi", "öğretim üyesi"], ["öğr. gör.", "öğretim görevlisi"], ["dt.", "diş hekimi"],
|
| 307 |
+
["dyt.", "diyetisyen"], ["psk.", "psikolog"], ["fzt.", "fizyoterapist"], ["hemş.", "hemşire"],
|
| 308 |
+
["ecz.", "eczacı"], ["av.", "avukat"], ["müh.", "mühendis"], ["hz.", "hazreti"], ["bkz.", "bakınız"],
|
| 309 |
+
["vd.", "ve diğerleri"],
|
| 310 |
+
["mah.", "mahallesi"], ["cad.", "caddesi"], ["cd.", "caddesi"], ["sok.", "sokak"], ["sk.", "sokak"],
|
| 311 |
+
["bul.", "bulvarı"], ["blv.", "bulvarı"], ["apt.", "apartmanı"], ["ltd. şti.", "limited şirketi"],
|
| 312 |
+
["şti.", "şirketi"],
|
| 313 |
+
];
|
| 314 |
+
const _BEFORE_A_WORD = new Set([
|
| 315 |
+
"doç.", "uzm.", "op.", "yrd.", "dt.", "dyt.", "psk.", "fzt.", "hemş.", "ecz.", "av.", "müh.", "hz.", "mah.",
|
| 316 |
+
"cad.", "cd.", "sok.", "sk.", "bul.", "blv.", "apt.",
|
| 317 |
+
]);
|
| 318 |
+
const _NUMBER_UNITS_LIST = [
|
| 319 |
+
["m", "metre"], ["g", "gram"], ["cc", "sisi"], ["mcg", "mikrogram"], ["μg", "mikrogram"], ["IU", "ünite"],
|
| 320 |
+
["kcal", "kilokalori"], ["mmHg", "milimetre cıva"], ["dk", "dakika"], ["sn", "saniye"], ["sa", "saat"],
|
| 321 |
+
["ms", "milisaniye"], ["dl", "desilitre"],
|
| 322 |
+
];
|
| 323 |
+
const _NUMBER_UNITS = new Map(_NUMBER_UNITS_LIST);
|
| 324 |
+
const _AREA_UNITS = map({ m: "metre", km: "kilometre", cm: "santimetre" });
|
| 325 |
+
const _ORDINAL_HEADS =
|
| 326 |
+
"Dünya|Lig|Ordu|Kolordu|Tümen|Dönem|Meclis|Kurultay|Kongre|Uluslararası|Ulusal|Olağan|Olağanüstü|Geleneksel" +
|
| 327 |
+
"|Yıl|Yüzyıl|Sınıf|Kat|Blok|Etap|Bölge|Asliye|Ağır|Sulh|İcra|Aile|Selim|Murat|Murad|Mehmet|Mehmed|Mahmut" +
|
| 328 |
+
"|Mahmud|Ahmet|Ahmed|Osman|Bayezid|Beyazıt|Süleyman|Mustafa|Abdülhamid|Abdülmecid|Louis|Henry|Napolyon";
|
| 329 |
+
const _WEEKDAYS = new Map([
|
| 330 |
+
["Pzt", "pazartesi"], ["Sal", "salı"], ["Çar", "çarşamba"], ["Per", "perşembe"], ["Cum", "cuma"],
|
| 331 |
+
["Cmt", "cumartesi"], ["Paz", "pazar"],
|
| 332 |
+
]);
|
| 333 |
+
const _LETTER_NAMES = map({
|
| 334 |
+
A: "a", B: "be", C: "ce", Ç: "çe", D: "de", E: "e", F: "fe", G: "ge", Ğ: "yumuşak ge", H: "he", I: "ı",
|
| 335 |
+
İ: "i", J: "je", K: "ke", L: "le", M: "me", N: "ne", O: "o", Ö: "ö", P: "pe", R: "re", S: "se", Ş: "şe",
|
| 336 |
+
T: "te", U: "u", Ü: "ü", V: "ve", Y: "ye", Z: "ze", Q: "kü", W: "dabılyu", X: "iks",
|
| 337 |
+
});
|
| 338 |
+
const _INITIALISM_LETTERS = new Map([..._LETTER_NAMES, ["K", "ka"], ["I", "i"]]);
|
| 339 |
+
const _ROMAN = "(?:XX|XIX|XVIII|XVII|XVI|XV|XIV|XIII|XII|XI|IX|VIII|VII|VI|IV|III|II)";
|
| 340 |
+
const _ROMAN_VALUES = map({ I: 1, V: 5, X: 10 });
|
| 341 |
+
const _ORDINAL_EXCEPTIONS = map({
|
| 342 |
+
bir: "birinci", iki: "ikinci", üç: "üçüncü", dört: "dördüncü", beş: "beşinci", altı: "altıncı",
|
| 343 |
+
yedi: "yedinci", sekiz: "sekizinci", dokuz: "dokuzuncu", on: "onuncu", yirmi: "yirminci", otuz: "otuzuncu",
|
| 344 |
+
kırk: "kırkıncı", elli: "ellinci", altmış: "altmışıncı", yetmiş: "yetmişinci", seksen: "sekseninci",
|
| 345 |
+
doksan: "doksanıncı", yüz: "yüzüncü", bin: "bininci", milyon: "milyonuncu", milyar: "milyarıncı",
|
| 346 |
+
});
|
| 347 |
+
// Python sorts a set by length (its order among equal lengths varies with the hash seed); two different
|
| 348 |
+
// stems of equal length never match at the same place, so any order among them gives the same result.
|
| 349 |
+
const _SPOKEN_STEMS = [
|
| 350 |
+
...new Set([
|
| 351 |
+
..._ONES, ..._TENS.filter(Boolean), "yüz", "bin", "milyon", "milyar", "trilyon", "lira", "kuruş", "dolar",
|
| 352 |
+
"avro", "sent", "sterlin", "peni", "saniye", "dakika", "saat", "buçuk", "metrekare", "metreküp",
|
| 353 |
+
"kilometrekare", "santimetrekare", "kilometreküp", "santimetreküp",
|
| 354 |
+
..._ABBREVIATIONS.map(([, v]) => v.split(" ").at(-1)),
|
| 355 |
+
..._NUMBER_UNITS_LIST.map(([, v]) => v.split(" ").at(-1)),
|
| 356 |
+
..._ORDINAL_EXCEPTIONS.values(),
|
| 357 |
+
]),
|
| 358 |
+
].sort((a, b) => cpLen(b) - cpLen(a));
|
| 359 |
+
const _SPOKEN_STEM_SUFFIX = g(
|
| 360 |
+
"\\b(" + _SPOKEN_STEMS.map(pyEscape).join("|") + "|\\w+(?:inci|ıncı|üncü|uncu|nci|ncı|ncü|ncu))'([a-zçğıöşü]+)\\b",
|
| 361 |
+
);
|
| 362 |
+
|
| 363 |
+
export function turkishLower(text) {
|
| 364 |
+
return pyLower(translate(text, _TURKISH_CASE)).replaceAll("\u0307", "");
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
function normalizeOrthography(text) {
|
| 368 |
+
let n = translate(text.normalize("NFKC"), _APOSTROPHES);
|
| 369 |
+
n = Array.from(n).filter((c) => !_QUOTES.has(c)).join("");
|
| 370 |
+
n = n.replaceAll("''", "");
|
| 371 |
+
return pyStrip(n.replace(_WHITESPACE, " "));
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
const _ABBREVIATION_RULES = [..._ABBREVIATIONS]
|
| 375 |
+
.sort((a, b) => cpLen(b[0]) - cpLen(a[0]))
|
| 376 |
+
.map(([abbreviation, expansion]) => {
|
| 377 |
+
const rules = [];
|
| 378 |
+
let pattern;
|
| 379 |
+
if (abbreviation.endsWith(".")) {
|
| 380 |
+
rules.push([g(`(?<!\\w)${pyEscape(abbreviation)}\\s*(?=\\w)`, "i"), `${expansion} `]);
|
| 381 |
+
if (_BEFORE_A_WORD.has(abbreviation)) return rules;
|
| 382 |
+
pattern = `(?<!\\w)${pyEscape(abbreviation)}`;
|
| 383 |
+
} else {
|
| 384 |
+
pattern = `(?<!\\w)${pyEscape(abbreviation)}(?!\\w)`;
|
| 385 |
+
}
|
| 386 |
+
rules.push([g(pattern, "i"), expansion]);
|
| 387 |
+
return rules;
|
| 388 |
+
})
|
| 389 |
+
.flat();
|
| 390 |
+
|
| 391 |
+
const R = {
|
| 392 |
+
quoteCaps: g("'([A-ZÇĞİÖŞÜ]+)\\b"),
|
| 393 |
+
noName: g(
|
| 394 |
+
"(?<!\\bsokak )(?<!\\bsokağı )(?<!\\bcadde )(?<!\\bcaddesi )(?<!\\bbulvarı )(?<!\\bmahallesi )(?<!\\bapartmanı )" +
|
| 395 |
+
"(?<=[^\\W\\d_] )no\\b\\.?:?(?=\\s)",
|
| 396 |
+
"i",
|
| 397 |
+
),
|
| 398 |
+
noNumber: g("\\bno\\s*[:.]\\s*(?=\\d)", "i"),
|
| 399 |
+
daire: g("\\bD\\s*:\\s*(?=\\d)"),
|
| 400 |
+
tel: g("\\bTel\\s*:"),
|
| 401 |
+
sayfa: g("\\bs\\.\\s*(?=\\d)"),
|
| 402 |
+
iban: g("\\bTR(\\d{2})((?:\\s?\\d{4}){5})\\s?(\\d{2})\\b"),
|
| 403 |
+
dotted: g("\\b(?:[A-ZÇĞİÖŞÜ]\\.){2,}"),
|
| 404 |
+
pH: g("\\bpH\\b"),
|
| 405 |
+
h2o: g("\\bH2O\\b"),
|
| 406 |
+
pylori: g("\\bH\\.\\s*pylori\\b", "i"),
|
| 407 |
+
xray: g("\\bX-?ray\\b", "i"),
|
| 408 |
+
hane: g("\\b(hane(?:si|leri)?)\\s+(\\d{2,6})\\b"),
|
| 409 |
+
hba1c: g("\\bHbA1c\\b"),
|
| 410 |
+
blood: g("\\b(AB|A|B|0)\\s?Rh\\s?\\(?([+-])\\)?"),
|
| 411 |
+
pressure: g("\\b(\\d{2,3})/(\\d{2,3})\\s*mmHg\\b"),
|
| 412 |
+
times: g("(\\bgünde\\s+)?\\b(\\d+)\\s?[xX×]\\s?(\\d+)\\b"),
|
| 413 |
+
kmh: g("(?<![\\d.,])(\\d+(?:,\\d+)?)\\s?km/(?:sa|s|h)\\b"),
|
| 414 |
+
dose: g("(?<![\\d.,])(\\d+(?:,\\d+)?)\\s?(mg|mcg|g|ml)/kg\\b"),
|
| 415 |
+
area: g("(?<=\\d) ?(km|cm|m)([23])(?!\\w)"),
|
| 416 |
+
units: g("(?<=\\d) ?(" + _NUMBER_UNITS_LIST.map(([k]) => pyEscape(k)).join("|") + ")(?![\\w/])"),
|
| 417 |
+
litre: g("(?<=\\d) L\\b(?![/'’])(?!\\s*\\d)"),
|
| 418 |
+
weekday: g("\\b(" + [..._WEEKDAYS.keys()].join("|") + ")\\b\\.?(?=\\s*(?:[-–,/]|\\d|$))"),
|
| 419 |
+
weekdayRange: g(
|
| 420 |
+
"\\b(pazartesi|salı|çarşamba|perşembe|cuma|cumartesi|pazar)\\s*[-–]\\s*" +
|
| 421 |
+
"(pazartesi|salı|çarşamba|perşembe|cuma|cumartesi|pazar)\\b",
|
| 422 |
+
"i",
|
| 423 |
+
),
|
| 424 |
+
currencySymbol: g("([₺$€£])\\s*((?:\\d{1,3}(?:\\.\\d{3})+)|\\d+)(?:[,.](\\d{1,2}))?"),
|
| 425 |
+
currencyAfter: g("(?<![\\d.,])((?:\\d{1,3}(?:\\.\\d{3})+)|\\d+)(?:,(\\d{1,2}))?\\s?(?:([₺$€£])|(TL|USD|EUR|GBP)\\b)"),
|
| 426 |
+
code: g(
|
| 427 |
+
"(?<=\\d)[A-ZÇĞİÖŞÜQWX]{1,6}(?=\\d|\\b)|\\b[A-ZÇĞİÖŞÜQWX]{1,6}(?=\\d)|(?<=\\d )[A-ZÇĞİÖŞÜQWX]{2,6}(?= \\d)",
|
| 428 |
+
),
|
| 429 |
+
letterDash: g("(?<=[^\\W\\d_])-(?=\\d)"),
|
| 430 |
+
date: g("\\b(\\d{1,2})[./-](\\d{1,2})[./-](\\d{4})\\b"),
|
| 431 |
+
isoDate: g("\\b(\\d{4})-(\\d{1,2})-(\\d{1,2})\\b"),
|
| 432 |
+
percentBefore: g("%\\s*(\\d+(?:[,.]\\d+)?)"),
|
| 433 |
+
percentAfter: g("(?<![\\d.,])(\\d+(?:,\\d+)?)\\s?%"),
|
| 434 |
+
minus: g("(?<![\\w.,:)\\]])-(?=\\d)"),
|
| 435 |
+
duration: g("\\b(\\d{1,2}):([0-5]\\d):([0-5]\\d)\\b"),
|
| 436 |
+
time: g("\\b([01]?\\d|2[0-3])[:.]([0-5]\\d)\\b"),
|
| 437 |
+
slashPair: g("\\b(\\d{1,2})/(\\d{1,2})\\b"),
|
| 438 |
+
slash: g("\\b(\\d+)/(\\d+)\\b"),
|
| 439 |
+
thousands: g("\\b\\d{1,3}(?:\\.\\d{3})+(?:,\\d+)?\\b"),
|
| 440 |
+
decimal: g("\\b(\\d+)[,.](\\d+)\\b"),
|
| 441 |
+
ordinalSuffix: g("\\b(\\d+)'?(?:inci|ıncı|üncü|uncu|nci|ncı|ncü|ncu)\\b"),
|
| 442 |
+
ordinalDotWord: g("\\b(\\d+)\\.(?=[a-zçğıöşü])"),
|
| 443 |
+
ordinalDot: g("\\b([1-9]\\d*)\\.(?=\\s+(?:[a-zçğıöşü]|(?:" + _ORDINAL_HEADS + ")\\b))"),
|
| 444 |
+
longDigits: g("\\b\\d{5,}\\b"),
|
| 445 |
+
zeroDigits: g("\\b0\\d+\\b"),
|
| 446 |
+
digits: g("\\b\\d+\\b"),
|
| 447 |
+
noSu: g("\\bno\\.'?s[ıu]\\b", "i"),
|
| 448 |
+
perUnit: g("(?<=\\w)/(sn|sa|dk)\\b", "i"),
|
| 449 |
+
unitPer: g("\\b(mg|kg|g|km|m|cm|ml)/(kg|g|m|l|lt|ml|saat|gün)\\b"),
|
| 450 |
+
sayin: g("\\bSn\\.\\s*(?=[A-ZÇĞİÖŞÜ])"),
|
| 451 |
+
initialism: g("\\b[A-ZÇĞİÖŞÜQWX]{2,6}\\b"),
|
| 452 |
+
loneLetter: g("(?<![\\w.'-])([A-ZÇĞİÖŞÜQWX])(\\.(?=\\s+[a-zçğıöşü]))?(?![\\w-])"),
|
| 453 |
+
spacedSlash: g("\\s+/\\s+"),
|
| 454 |
+
wordSlash: g("(?<=[^\\W\\d_])/(?=[^\\W\\d_])"),
|
| 455 |
+
spaceBeforePunct: g("\\s+([,.;:!?])"),
|
| 456 |
+
leading: g("^[\\s,]+|(?<=[,.;:!?])\\s*,"),
|
| 457 |
+
// _replace_symbols
|
| 458 |
+
degree: g("(?<=\\d)\\s?°\\s?C?(?![^\\W\\d_])"),
|
| 459 |
+
plus: g("(?<=\\d)\\s?\\+\\s?(?=\\d)|(?<=\\s)\\+(?=\\s)"),
|
| 460 |
+
equals: g("(?<=[\\d\\s])=(?=[\\d\\s])"),
|
| 461 |
+
hashtag: g("(?<![\\w&])#(?=[^\\W\\d_])"),
|
| 462 |
+
emphasis: g("\\*+|_{2,}"),
|
| 463 |
+
// helpers
|
| 464 |
+
scheme: py("^https?://", "i"),
|
| 465 |
+
addressSplit: py("([.@/_-])", "g"),
|
| 466 |
+
vitaminBefore: py("vitamin\\w*\\s+(?:\\w+\\s+ve\\s+)?$", "i"),
|
| 467 |
+
vitaminAfter: py("\\s+vitamin", "iy"),
|
| 468 |
+
doseWord: py("\\s*(?:tablet|kapsül|şurup|ölçek|damla|doz|puf|kaşık|ampul|draje|saşe|fitil|iğne)", "iy"),
|
| 469 |
+
romanOrdinal: g("\\b(" + _ROMAN + "|I(?=\\.\\s+Dünya))\\.\\s+(?=[A-ZÇĞİÖŞÜ])"),
|
| 470 |
+
romanAfterTitle: g("\\b([A-ZÇĞİÖŞÜ][^\\W\\d_]*\\s+)(" + _ROMAN + ")\\b(?![.'’]?[^\\W\\d_])"),
|
| 471 |
+
threeConsonants: py("[^AEIİOÖUÜ]{3}"),
|
| 472 |
+
sepComma: py("[,.]"),
|
| 473 |
+
};
|
| 474 |
+
|
| 475 |
+
/** re.match at the start of `s` (sticky regex from position 0). */
|
| 476 |
+
function matchAtStart(re, s) {
|
| 477 |
+
re.lastIndex = 0;
|
| 478 |
+
return re.test(s);
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
function normalizeForModel(text) {
|
| 482 |
+
// The typographic minus sign (U+2212) is read like "-": "−5 derece" -> "eksi beş derece".
|
| 483 |
+
let n = normalizeOrthography(text.replaceAll("\u2212", "-"));
|
| 484 |
+
n = lowerIfShouted(n);
|
| 485 |
+
n = replaceRoman(n);
|
| 486 |
+
n = sub(R.quoteCaps, n, (m) => "'" + turkishLower(m[1]));
|
| 487 |
+
n = n.replace(R.noName, "numarası");
|
| 488 |
+
n = n.replace(R.noNumber, "numara ");
|
| 489 |
+
n = n.replace(R.daire, "daire ");
|
| 490 |
+
n = n.replace(R.tel, "telefon:");
|
| 491 |
+
n = n.replace(R.sayfa, "sayfa ");
|
| 492 |
+
n = sub(_EMAIL, n, replaceAddress);
|
| 493 |
+
n = sub(_URL, n, replaceAddress);
|
| 494 |
+
n = replaceSymbols(n);
|
| 495 |
+
n = sub(R.iban, n, replaceIban);
|
| 496 |
+
n = sub(R.dotted, n, (m) => cps(m[0]).filter((c) => c !== ".").map((c) => getKey(_INITIALISM_LETTERS, c)).join(""));
|
| 497 |
+
n = n.replace(R.pH, "pe ha");
|
| 498 |
+
n = n.replace(R.h2o, "haş iki o");
|
| 499 |
+
n = n.replace(R.pylori, "ha pilori");
|
| 500 |
+
n = n.replace(R.xray, "iksrey");
|
| 501 |
+
n = sub(R.hane, n, (m) => `${m[1]} ${digitSequenceToWords(m[2])}`);
|
| 502 |
+
n = n.replace(R.hba1c, "ha be a bir ce");
|
| 503 |
+
n = sub(R.blood, n, replaceBloodGroup);
|
| 504 |
+
n = sub(R.pressure, n, (m) =>
|
| 505 |
+
`${withDative(numberToWords(pyInt(m[1])))} ${numberToWords(pyInt(m[2]))} milimetre cıva`);
|
| 506 |
+
n = sub(R.times, n, replaceTimes);
|
| 507 |
+
n = sub(R.kmh, n, (m) => `saatte ${numericToWords(m[1])} kilometre`);
|
| 508 |
+
n = sub(R.dose, n, (m) => `kilogram başına ${numericToWords(m[1])} ${getKey(_DOSE_UNITS, m[2])}`);
|
| 509 |
+
n = sub(R.area, n, (m) => " " + getKey(_AREA_UNITS, m[1]) + (m[2] === "2" ? "kare" : "küp"));
|
| 510 |
+
n = sub(R.units, n, (m) => " " + getKey(_NUMBER_UNITS, m[1]));
|
| 511 |
+
n = n.replace(R.litre, " litre");
|
| 512 |
+
n = sub(R.weekday, n, (m) => getKey(_WEEKDAYS, m[1]));
|
| 513 |
+
n = n.replace(R.weekdayRange, "$1 ile $2");
|
| 514 |
+
n = sub(R.currencySymbol, n, (m) => currencyWords(m[1], m[2], m[3]));
|
| 515 |
+
n = sub(R.currencyAfter, n, (m) => currencyWords(m[3] || getKey(_CURRENCY_CODES, m[4]), m[1], m[2]));
|
| 516 |
+
n = sub(R.code, n, (m) =>
|
| 517 |
+
_CAPS_LEXICON.has(m[0]) || isPronounceable(m[0])
|
| 518 |
+
? m[0]
|
| 519 |
+
: " " + cps(m[0]).map((c) => getKey(_INITIALISM_LETTERS, c)).join(" ") + " ");
|
| 520 |
+
n = n.replace(_LETTER_THEN_DIGIT, " ").replace(_DIGIT_THEN_LETTER, " ");
|
| 521 |
+
n = n.replace(R.letterDash, " ");
|
| 522 |
+
n = sub(_LONE_LETTER_BY_DIGIT, n, (m) => getKey(_LETTER_NAMES, m[1] || m[2]));
|
| 523 |
+
n = sub(R.date, n, (m) => replaceDateParts(m[1], m[2], m[3], m[0]));
|
| 524 |
+
n = sub(R.isoDate, n, (m) => replaceDateParts(m[3], m[2], m[1]));
|
| 525 |
+
n = sub(R.percentBefore, n, (m) => `yüzde ${numericToWords(m[1])}`);
|
| 526 |
+
n = sub(R.percentAfter, n, (m) => `yüzde ${numericToWords(m[1])}`);
|
| 527 |
+
n = sub(_PHONE, n, replacePhone);
|
| 528 |
+
n = sub(_RANGE, n, replaceRange);
|
| 529 |
+
n = n.replace(R.minus, "eksi ");
|
| 530 |
+
n = sub(R.duration, n, replaceDuration);
|
| 531 |
+
n = sub(R.time, n, replaceTime);
|
| 532 |
+
n = sub(R.slashPair, n, replaceSlashPair);
|
| 533 |
+
n = n.replace(R.slash, "$1 bölü $2");
|
| 534 |
+
n = sub(R.thousands, n, (m) => numericToWords(m[0]));
|
| 535 |
+
n = sub(R.decimal, n, (m) => decimalToWords(m[0]));
|
| 536 |
+
n = sub(R.ordinalSuffix, n, (m) => ordinalToWords(pyInt(m[1])));
|
| 537 |
+
n = sub(R.ordinalDotWord, n, (m) => ordinalToWords(pyInt(m[1])));
|
| 538 |
+
n = sub(R.ordinalDot, n, (m) => ordinalToWords(pyInt(m[1])));
|
| 539 |
+
n = sub(R.longDigits, n, (m) => digitSequenceToWords(m[0]));
|
| 540 |
+
n = sub(R.zeroDigits, n, (m) => digitGroupToWords(m[0]));
|
| 541 |
+
n = sub(R.digits, n, (m) => numberToWords(pyInt(m[0])));
|
| 542 |
+
n = n.replace(R.noSu, "numarası");
|
| 543 |
+
n = sub(R.perUnit, n, (m) => " bölü " + getKey(_PER_UNIT, pyLower(m[1])));
|
| 544 |
+
n = n.replace(R.unitPer, "$1 bölü $2");
|
| 545 |
+
n = n.replace(R.sayin, "sayın ");
|
| 546 |
+
for (const [re, expansion] of _ABBREVIATION_RULES) n = sub(re, n, () => expansion);
|
| 547 |
+
n = sub(R.initialism, n, replaceInitialism);
|
| 548 |
+
n = sub(R.loneLetter, n, replaceLoneLetter);
|
| 549 |
+
n = sub(_SPOKEN_STEM_SUFFIX, n, attachSuffix);
|
| 550 |
+
n = n.replace(R.spacedSlash, ", ");
|
| 551 |
+
n = n.replace(R.wordSlash, " ");
|
| 552 |
+
n = n.replace(R.spaceBeforePunct, "$1");
|
| 553 |
+
n = n.replace(R.leading, "");
|
| 554 |
+
return pyStrip(n.replace(_WHITESPACE, " "));
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
/** number_to_words for a BigInt (or a safe integer Number). */
|
| 558 |
+
export function numberToWords(number) {
|
| 559 |
+
number = BigInt(number);
|
| 560 |
+
if (number < 0n) return `eksi ${numberToWords(-number)}`;
|
| 561 |
+
if (number < 10n) return _ONES[Number(number)];
|
| 562 |
+
if (number < 100n) {
|
| 563 |
+
const tens = Number(number / 10n);
|
| 564 |
+
const ones = Number(number % 10n);
|
| 565 |
+
return !ones ? _TENS[tens] : `${_TENS[tens]} ${_ONES[ones]}`;
|
| 566 |
+
}
|
| 567 |
+
if (number < 1000n) {
|
| 568 |
+
const hundreds = Number(number / 100n);
|
| 569 |
+
const remainder = number % 100n;
|
| 570 |
+
const prefix = hundreds === 1 ? "yüz" : `${_ONES[hundreds]} yüz`;
|
| 571 |
+
return !remainder ? prefix : `${prefix} ${numberToWords(remainder)}`;
|
| 572 |
+
}
|
| 573 |
+
const scales = [[1000000000000n, "trilyon"], [1000000000n, "milyar"], [1000000n, "milyon"], [1000n, "bin"]];
|
| 574 |
+
for (const [scale, label] of scales) {
|
| 575 |
+
if (number >= scale) {
|
| 576 |
+
const count = number / scale;
|
| 577 |
+
const remainder = number % scale;
|
| 578 |
+
const prefix = scale === 1000n && count === 1n ? label : `${numberToWords(count)} ${label}`;
|
| 579 |
+
return !remainder ? prefix : `${prefix} ${numberToWords(remainder)}`;
|
| 580 |
+
}
|
| 581 |
+
}
|
| 582 |
+
throw new PyError("ValueError", `number is too large to normalize: ${number}`);
|
| 583 |
+
}
|
| 584 |
+
|
| 585 |
+
function replaceDateParts(dayText, monthText, yearText, original) {
|
| 586 |
+
const day = pyInt(dayText);
|
| 587 |
+
const month = pyInt(monthText);
|
| 588 |
+
const year = pyInt(yearText);
|
| 589 |
+
if (!(1n <= day && day <= 31n) || !(month >= 1n && month <= 12n)) {
|
| 590 |
+
return original !== undefined ? original : `${yearText}-${monthText}-${dayText}`;
|
| 591 |
+
}
|
| 592 |
+
return `${numberToWords(day)} ${_MONTHS.get(Number(month))} ${numberToWords(year)}`;
|
| 593 |
+
}
|
| 594 |
+
|
| 595 |
+
const _CURRENCY_CODES = map({ TL: "₺", USD: "$", EUR: "€", GBP: "£" });
|
| 596 |
+
const _SYMBOLS = map({ "&": " ve ", "•": " , ", "▪": " , ", "►": " , ", "→": " , ", "⇒": " , " });
|
| 597 |
+
const RE_DROP_CATEGORY = /^[\p{So}\p{Cs}\p{Co}]$/u;
|
| 598 |
+
|
| 599 |
+
function replaceSymbols(text) {
|
| 600 |
+
text = text.replace(R.degree, " derece");
|
| 601 |
+
text = text.replace(R.plus, " artı ");
|
| 602 |
+
text = text.replace(R.equals, " eşittir ");
|
| 603 |
+
text = text.replace(R.hashtag, "heşteg ");
|
| 604 |
+
text = text.replace(R.emphasis, "");
|
| 605 |
+
text = translate(text, _SYMBOLS);
|
| 606 |
+
let out = "";
|
| 607 |
+
for (const c of text) if (!RE_DROP_CATEGORY.test(c)) out += c;
|
| 608 |
+
return out.replaceAll("\ufe0f", "").replaceAll("\u200d", "");
|
| 609 |
+
}
|
| 610 |
+
|
| 611 |
+
function replaceIban(m) {
|
| 612 |
+
const groups = m[2].includes(" ") ? [m[1], ...pySplit(m[2]), m[3]] : [m[1], m[2], m[3]];
|
| 613 |
+
return "te re, " + groups.map(digitSequenceToWords).join(", ");
|
| 614 |
+
}
|
| 615 |
+
|
| 616 |
+
function replaceBloodGroup(m) {
|
| 617 |
+
const group = m[1] === "0" ? "sıfır" : cps(m[1]).map((c) => getKey(_INITIALISM_LETTERS, c)).join("");
|
| 618 |
+
return `${group} eraj ${m[2] === "+" ? "pozitif" : "negatif"}`;
|
| 619 |
+
}
|
| 620 |
+
|
| 621 |
+
function replaceRange(m) {
|
| 622 |
+
const start = m[1];
|
| 623 |
+
const end = m[2];
|
| 624 |
+
if (fullmatchRe("\\d{4}", start) && fullmatchRe("\\d{2}", end) && pyInt(end) === (pyInt(start) + 1n) % 100n) {
|
| 625 |
+
return `${start} ${pyInt(end)}`;
|
| 626 |
+
}
|
| 627 |
+
if (isDigitStr(start) && isDigitStr(end) && pyInt(start) > pyInt(end)) return `${start} ${end}`;
|
| 628 |
+
return `${start} ile ${end}`;
|
| 629 |
+
}
|
| 630 |
+
|
| 631 |
+
function replaceLoneLetter(m) {
|
| 632 |
+
const letter = firstChar(m[0]);
|
| 633 |
+
const text = m.input;
|
| 634 |
+
const start = m.index;
|
| 635 |
+
const end = m.index + m[0].length;
|
| 636 |
+
const following = firstChar(text.slice(end));
|
| 637 |
+
if ("OI".includes(letter) || ("AE".includes(letter) && [",", "!", "?"].includes(following))) return m[0];
|
| 638 |
+
const initial = m[2] || following === ".";
|
| 639 |
+
const vitamin = R.vitaminBefore.test(text.slice(0, start)) || matchAtStart(R.vitaminAfter, text.slice(end));
|
| 640 |
+
return getKey(initial || vitamin ? _INITIALISM_LETTERS : _LETTER_NAMES, letter);
|
| 641 |
+
}
|
| 642 |
+
|
| 643 |
+
const _DOSE_UNITS = map({ mg: "miligram", mcg: "mikrogram", g: "gram", ml: "mililitre" });
|
| 644 |
+
|
| 645 |
+
function replaceTimes(m) {
|
| 646 |
+
const daily = m[1];
|
| 647 |
+
const first = numberToWords(pyInt(m[2]));
|
| 648 |
+
const second = numberToWords(pyInt(m[3]));
|
| 649 |
+
if (daily || matchAtStart(R.doseWord, m.input.slice(m.index + m[0].length))) {
|
| 650 |
+
return `${daily || ""}${first} defa ${second}`;
|
| 651 |
+
}
|
| 652 |
+
return `${withDative(first)} ${second}`;
|
| 653 |
+
}
|
| 654 |
+
|
| 655 |
+
function lastVowel(words) {
|
| 656 |
+
const a = cps(words);
|
| 657 |
+
for (let k = a.length - 1; k >= 0; k--) if (_VOWELS.has(a[k])) return a[k];
|
| 658 |
+
return "e";
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
function withDative(words) {
|
| 662 |
+
if (words.endsWith("dört")) return words.slice(0, -1) + "de";
|
| 663 |
+
const vowel = "aıou".includes(lastVowel(words)) ? "a" : "e";
|
| 664 |
+
return `${words}${_VOWELS.has(lastChar(words)) ? "y" : ""}${vowel}`;
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
function currencyWords(symbol, whole, fraction) {
|
| 668 |
+
const [unit, subunit] = getKey(
|
| 669 |
+
new Map([["₺", ["lira", "kuruş"]], ["$", ["dolar", "sent"]], ["€", ["avro", "sent"]], ["£", ["sterlin", "peni"]]]),
|
| 670 |
+
symbol,
|
| 671 |
+
);
|
| 672 |
+
let value = `${numberToWords(pyInt(whole.replaceAll(".", "")))} ${unit}`;
|
| 673 |
+
if (fraction && pyInt(ljust(fraction, 2, "0")) !== 0n) {
|
| 674 |
+
value += ` ${numberToWords(pyInt(ljust(fraction, 2, "0")))} ${subunit}`;
|
| 675 |
+
}
|
| 676 |
+
return value;
|
| 677 |
+
}
|
| 678 |
+
|
| 679 |
+
function replacePhone(m) {
|
| 680 |
+
const [country, trunk, ...groups] = m.slice(1);
|
| 681 |
+
const spoken = country ? ["artı doksan"] : [];
|
| 682 |
+
spoken.push(trunk ? `sıfır ${digitGroupToWords(groups[0])}` : digitGroupToWords(groups[0]));
|
| 683 |
+
for (const group of groups.slice(1)) spoken.push(digitGroupToWords(group));
|
| 684 |
+
return spoken.join(", ");
|
| 685 |
+
}
|
| 686 |
+
|
| 687 |
+
function digitGroupToWords(value) {
|
| 688 |
+
let k = 0;
|
| 689 |
+
while (value[k] === "0") k++;
|
| 690 |
+
const stripped = value.slice(k);
|
| 691 |
+
const zeros = Array(k).fill("sıfır");
|
| 692 |
+
return (stripped ? [...zeros, numberToWords(pyInt(stripped))] : zeros).join(" ");
|
| 693 |
+
}
|
| 694 |
+
|
| 695 |
+
function turkishUpper(c) {
|
| 696 |
+
return c === "i" ? "İ" : c === "ı" ? "I" : pyUpper(c);
|
| 697 |
+
}
|
| 698 |
+
|
| 699 |
+
function replaceSlashPair(m) {
|
| 700 |
+
const numerator = pyInt(m[1]);
|
| 701 |
+
const denominator = pyInt(m[2]);
|
| 702 |
+
if (0n < numerator && numerator < denominator && denominator <= 10n) {
|
| 703 |
+
return `${withLocative(numberToWords(denominator))} ${numberToWords(numerator)}`;
|
| 704 |
+
}
|
| 705 |
+
if ((numerator === 7n && denominator === 24n) || (numerator === 24n && denominator === 7n)) {
|
| 706 |
+
return `${numberToWords(numerator)} ${numberToWords(denominator)}`;
|
| 707 |
+
}
|
| 708 |
+
return `${numberToWords(numerator)} bölü ${numberToWords(denominator)}`;
|
| 709 |
+
}
|
| 710 |
+
|
| 711 |
+
function withLocative(words) {
|
| 712 |
+
const vowel = "aıou".includes(lastVowel(words)) ? "a" : "e";
|
| 713 |
+
const consonant = "çfhkpsşt".includes(lastChar(words)) ? "t" : "d";
|
| 714 |
+
return `${words}${consonant}${vowel}`;
|
| 715 |
+
}
|
| 716 |
+
|
| 717 |
+
const _ADDRESS_PIECES = map({ ".": "nokta", "@": "et", "/": "bölü", _: "alt tire", "-": "tire" });
|
| 718 |
+
|
| 719 |
+
function replaceAddress(m) {
|
| 720 |
+
let address = m[0].replace(R.scheme, "");
|
| 721 |
+
address = address.replace(/\/+$/u, "");
|
| 722 |
+
const spoken = [];
|
| 723 |
+
for (const piece of address.split(R.addressSplit)) {
|
| 724 |
+
if (_ADDRESS_PIECES.has(piece)) spoken.push(_ADDRESS_PIECES.get(piece));
|
| 725 |
+
else if (piece) {
|
| 726 |
+
const lower = pyLower(piece);
|
| 727 |
+
if (_ADDRESS_WORDS.has(lower)) spoken.push(_ADDRESS_WORDS.get(lower));
|
| 728 |
+
else if (cpLen(lower) <= 2 && isAlpha(lower)) {
|
| 729 |
+
spoken.push(cps(turkishLower(lower)).map((c) => _LETTER_NAMES.get(turkishUpper(c)) ?? c).join(" "));
|
| 730 |
+
} else spoken.push(piece);
|
| 731 |
+
}
|
| 732 |
+
}
|
| 733 |
+
return spoken.join(" ");
|
| 734 |
+
}
|
| 735 |
+
|
| 736 |
+
function replaceDuration(m) {
|
| 737 |
+
const [hours, minutes, seconds] = [m[1], m[2], m[3]].map(pyInt);
|
| 738 |
+
const parts = [];
|
| 739 |
+
if (hours) parts.push(`${numberToWords(hours)} saat`);
|
| 740 |
+
if (minutes) parts.push(`${numberToWords(minutes)} dakika`);
|
| 741 |
+
if (seconds || !parts.length) parts.push(`${numberToWords(seconds)} saniye`);
|
| 742 |
+
return parts.join(" ");
|
| 743 |
+
}
|
| 744 |
+
|
| 745 |
+
function attachSuffix(m) {
|
| 746 |
+
let stem = m[1];
|
| 747 |
+
let suffix = m[2];
|
| 748 |
+
let sfx = cps(suffix);
|
| 749 |
+
if (!_VOWELS.has(lastChar(stem)) && sfx.length > 1 && "yns".includes(sfx[0]) && _VOWELS.has(sfx[1])) {
|
| 750 |
+
sfx = sfx.slice(1);
|
| 751 |
+
}
|
| 752 |
+
if (_VOWELS.has(sfx[0])) stem = stem.replace(/buçuk$/u, "buçuğ").replace(/dört$/u, "dörd");
|
| 753 |
+
let vowel = lastVowel(stem);
|
| 754 |
+
const out = [];
|
| 755 |
+
sfx.forEach((ch, index) => {
|
| 756 |
+
let c = ch;
|
| 757 |
+
if ("ae".includes(c)) c = "aıou".includes(vowel) ? "a" : "e";
|
| 758 |
+
else if ("ıiuü".includes(c)) {
|
| 759 |
+
const back = "aıou".includes(vowel);
|
| 760 |
+
const round = "ouöü".includes(vowel);
|
| 761 |
+
c = back ? (round ? "u" : "ı") : round ? "ü" : "i";
|
| 762 |
+
} else if (index === 0 && "dt".includes(c)) c = "çfhkpsşt".includes(lastChar(stem)) ? "t" : "d";
|
| 763 |
+
if (_VOWELS.has(c)) vowel = c;
|
| 764 |
+
out.push(c);
|
| 765 |
+
});
|
| 766 |
+
return stem + out.join("");
|
| 767 |
+
}
|
| 768 |
+
|
| 769 |
+
function replaceTime(m) {
|
| 770 |
+
const hour = m[1];
|
| 771 |
+
const minute = m[2];
|
| 772 |
+
const hourWords = numberToWords(pyInt(hour));
|
| 773 |
+
if (pyInt(minute) === 0n) return hourWords;
|
| 774 |
+
const minuteWords = minute.startsWith("0") ? digitSequenceToWords(minute) : numberToWords(pyInt(minute));
|
| 775 |
+
return `${hourWords} ${minuteWords}`;
|
| 776 |
+
}
|
| 777 |
+
|
| 778 |
+
function fullmatchRe(src, s) {
|
| 779 |
+
return endAnchored(src, "").test(s);
|
| 780 |
+
}
|
| 781 |
+
|
| 782 |
+
function numericToWords(value) {
|
| 783 |
+
if (fullmatchRe("\\d{1,3}(?:\\.\\d{3})+(?:,\\d+)?", value)) {
|
| 784 |
+
const plain = value.replaceAll(".", "");
|
| 785 |
+
const comma = plain.indexOf(",");
|
| 786 |
+
const whole = comma < 0 ? plain : plain.slice(0, comma);
|
| 787 |
+
const fraction = comma < 0 ? "" : plain.slice(comma + 1);
|
| 788 |
+
return fraction ? decimalToWords(`${whole},${fraction}`) : numberToWords(pyInt(whole));
|
| 789 |
+
}
|
| 790 |
+
return R.sepComma.test(value) ? decimalToWords(value) : numberToWords(pyInt(value));
|
| 791 |
+
}
|
| 792 |
+
|
| 793 |
+
function decimalToWords(value) {
|
| 794 |
+
const at = value.search(R.sepComma);
|
| 795 |
+
if (at < 0) throw new PyError("ValueError", "not enough values to unpack");
|
| 796 |
+
const whole = value.slice(0, at);
|
| 797 |
+
const fraction = value.slice(at + 1);
|
| 798 |
+
const wholeWords = numberToWords(pyInt(whole));
|
| 799 |
+
if (fraction === "5" && pyInt(whole) !== 0n) return `${wholeWords} buçuk`;
|
| 800 |
+
const fractionWords = cpLen(fraction) <= 2 ? digitGroupToWords(fraction) : digitSequenceToWords(fraction);
|
| 801 |
+
return `${wholeWords} virgül ${fractionWords}`;
|
| 802 |
+
}
|
| 803 |
+
|
| 804 |
+
function digitSequenceToWords(value) {
|
| 805 |
+
return cps(value).map((d) => _ONES[digitValue(d)]).join(" ");
|
| 806 |
+
}
|
| 807 |
+
|
| 808 |
+
function ordinalToWords(number) {
|
| 809 |
+
const words = numberToWords(number).split(" ");
|
| 810 |
+
const last = words[words.length - 1];
|
| 811 |
+
words[words.length - 1] = _ORDINAL_EXCEPTIONS.get(last) ?? `${last}inci`;
|
| 812 |
+
return words.join(" ");
|
| 813 |
+
}
|
| 814 |
+
|
| 815 |
+
function romanToInt(numeral) {
|
| 816 |
+
let total = 0;
|
| 817 |
+
for (let i = 0; i < numeral.length; i++) {
|
| 818 |
+
const value = getKey(_ROMAN_VALUES, numeral[i]);
|
| 819 |
+
total += i + 1 < numeral.length && getKey(_ROMAN_VALUES, numeral[i + 1]) > value ? -value : value;
|
| 820 |
+
}
|
| 821 |
+
return BigInt(total);
|
| 822 |
+
}
|
| 823 |
+
|
| 824 |
+
function replaceRoman(text) {
|
| 825 |
+
text = sub(R.romanOrdinal, text, (m) => ordinalToWords(romanToInt(m[1])) + " ");
|
| 826 |
+
return sub(R.romanAfterTitle, text, (m) => m[1] + numberToWords(romanToInt(m[2])));
|
| 827 |
+
}
|
| 828 |
+
|
| 829 |
+
function lowerIfShouted(text) {
|
| 830 |
+
const words = Array.from(text.matchAll(_WORD), (m) => m[0]);
|
| 831 |
+
const capitals = words.filter((w) => fullmatchRe(_CAPS_WORD_SRC, w));
|
| 832 |
+
const spokenWords = capitals.filter(isPronounceable).length;
|
| 833 |
+
return spokenWords >= 3 && capitals.length >= 0.7 * words.length ? turkishLower(text) : text;
|
| 834 |
+
}
|
| 835 |
+
|
| 836 |
+
function replaceInitialism(m) {
|
| 837 |
+
const word = m[0];
|
| 838 |
+
if (_CAPS_LEXICON.has(word)) return _CAPS_LEXICON.get(word);
|
| 839 |
+
if (isPronounceable(word)) return word;
|
| 840 |
+
return cps(word).map((c) => getKey(_INITIALISM_LETTERS, c)).join("");
|
| 841 |
+
}
|
| 842 |
+
|
| 843 |
+
function isPronounceable(word) {
|
| 844 |
+
const chars = cps(word);
|
| 845 |
+
if (chars.length < 4) return false;
|
| 846 |
+
const vowels = chars.filter((c) => _VOWELS.has(c)).length;
|
| 847 |
+
return vowels / chars.length >= 0.3 && !R.threeConsonants.test(word);
|
| 848 |
+
}
|
| 849 |
+
|
| 850 |
+
// ---------------------------------------------------------------- foreign.py
|
| 851 |
+
|
| 852 |
+
const LETTERS = map({
|
| 853 |
+
A: "ey", B: "bi", C: "si", D: "di", E: "i", F: "ef", G: "ci", H: "eyç", I: "ay", J: "cey",
|
| 854 |
+
K: "key", L: "el", M: "em", N: "en", O: "o", P: "pi", Q: "kyu", R: "ar", S: "es", T: "ti",
|
| 855 |
+
U: "yu", V: "vi", W: "dabılyu", X: "eks", Y: "vay", Z: "zi",
|
| 856 |
+
});
|
| 857 |
+
const _TR_LETTERS = new Set("çğıöşüÇĞİÖŞÜ");
|
| 858 |
+
const _TOKEN = g("(?<![\\w@./])([A-Za-z][A-Za-z0-9]*)(['’][a-zçğıöşü]+)?(?![\\w@])");
|
| 859 |
+
const _CAMEL = g("[A-Z]{2,}(?=[A-Z][a-z]|\\b|[0-9]|$)|[A-Z]?[a-z]+|[A-Z]+|[0-9]+");
|
| 860 |
+
const _PROTECTED = g(
|
| 861 |
+
"[\\w.+-]+@[\\w-]+(?:\\.[\\w-]+)+" +
|
| 862 |
+
"|(?:https?://|www\\.)\\S+" +
|
| 863 |
+
"|\\b[\\w-]+(?:\\.[\\w-]+)*\\.(?:com|net|org|ai|io|co|app|dev|gov|edu|tr|me|info)(?:\\.[a-z]{2})?\\b",
|
| 864 |
+
"i",
|
| 865 |
+
);
|
| 866 |
+
|
| 867 |
+
const trLower = (w) => pyLower(w.replaceAll("I", "ı").replaceAll("İ", "i"));
|
| 868 |
+
const RE_ASCII_ALPHA = /^[A-Za-z]+$/;
|
| 869 |
+
|
| 870 |
+
function decodeData(data) {
|
| 871 |
+
if (data.format !== 1) throw new Error("frontend data: unsupported format " + data.format);
|
| 872 |
+
const cmu = new Map();
|
| 873 |
+
const turkish = new Set(data.trBlockExtra || []);
|
| 874 |
+
let prevK = "";
|
| 875 |
+
let prevV = "";
|
| 876 |
+
for (const line of data.cmu.split("\n")) {
|
| 877 |
+
let sep = line.indexOf("\t");
|
| 878 |
+
const blocked = sep < 0;
|
| 879 |
+
if (blocked) sep = line.indexOf("|");
|
| 880 |
+
const k = prevK.slice(0, line.charCodeAt(0) - 48) + line.slice(1, sep);
|
| 881 |
+
const v = prevV.slice(0, line.charCodeAt(sep + 1) - 48) + line.slice(sep + 2);
|
| 882 |
+
cmu.set(k, v);
|
| 883 |
+
if (blocked) turkish.add(k);
|
| 884 |
+
prevK = k;
|
| 885 |
+
prevV = v;
|
| 886 |
+
}
|
| 887 |
+
const known = new Set(data.known ? data.known.split("\n") : []);
|
| 888 |
+
return { cmu, turkish, known, lexicon: data.lexicon.map(([k, v]) => [k, v]) };
|
| 889 |
+
}
|
| 890 |
+
|
| 891 |
+
/** Build the frontend from the parsed asset object (see web/tools/build_frontend_data.py). */
|
| 892 |
+
export function createFrontend(data) {
|
| 893 |
+
const { cmu, turkish, known, lexicon: builtinLexicon } = decodeData(data);
|
| 894 |
+
|
| 895 |
+
function isEnglish(word) {
|
| 896 |
+
if (!isAscii(word) || !isAlpha(word) || cps(word).some((c) => _TR_LETTERS.has(c))) return false;
|
| 897 |
+
if (!cmu.has(pyLower(word))) return false;
|
| 898 |
+
return !turkish.has(trLower(word)) && !turkish.has(pyLower(word));
|
| 899 |
+
}
|
| 900 |
+
|
| 901 |
+
function looksEnglish(word) {
|
| 902 |
+
return RE_ASCII_ALPHA.test(word) && cmu.has(pyLower(word));
|
| 903 |
+
}
|
| 904 |
+
|
| 905 |
+
const knownInTurkish = (word) => known.has(pyLower(word));
|
| 906 |
+
|
| 907 |
+
function hasInnerCapital(word) {
|
| 908 |
+
const chars = cps(word);
|
| 909 |
+
return chars.slice(1).some(isUpper) && chars.some(isLower);
|
| 910 |
+
}
|
| 911 |
+
|
| 912 |
+
const splitCamel = (word) => Array.from(word.matchAll(_CAMEL), (m) => m[0]);
|
| 913 |
+
|
| 914 |
+
function respellPart(part) {
|
| 915 |
+
if (isDigitStr(part)) return part;
|
| 916 |
+
if (isUpper(part) && cpLen(part) <= 5) {
|
| 917 |
+
const many = cpLen(part) > 1;
|
| 918 |
+
return cps(part).map((c) => (many ? capitalize(getKey(LETTERS, c)) : getKey(LETTERS, c))).join(" ");
|
| 919 |
+
}
|
| 920 |
+
if (part === "i" || part === "e") return getKey(LETTERS, pyUpper(part));
|
| 921 |
+
const r = cmu.get(pyLower(part));
|
| 922 |
+
return r === undefined ? null : r;
|
| 923 |
+
}
|
| 924 |
+
|
| 925 |
+
const up = (t) => (firstChar(t) === "i" ? "İ" + t.slice(1) : pyUpper(firstChar(t)) + t.slice(firstChar(t).length));
|
| 926 |
+
|
| 927 |
+
function respell(word) {
|
| 928 |
+
const parts = hasInnerCapital(word) ? splitCamel(word) : [word];
|
| 929 |
+
let spoken = [];
|
| 930 |
+
for (const part of parts) {
|
| 931 |
+
const r = respellPart(part);
|
| 932 |
+
if (r === null) return null;
|
| 933 |
+
spoken.push(r);
|
| 934 |
+
}
|
| 935 |
+
spoken = spoken.map((sp, k) =>
|
| 936 |
+
isUpper(firstChar(parts[k])) || (k === 0 && isUpper(firstChar(word))) ? up(sp) : sp);
|
| 937 |
+
const merged = [];
|
| 938 |
+
parts.forEach((p, k) => {
|
| 939 |
+
const sp = spoken[k];
|
| 940 |
+
if (merged.length && ((cpLen(p) <= 2 && !isUpper(p)) || (k === 1 && (parts[0] === "i" || parts[0] === "e")))) {
|
| 941 |
+
merged[merged.length - 1] = merged[merged.length - 1] + trLower(sp);
|
| 942 |
+
} else merged.push(sp);
|
| 943 |
+
});
|
| 944 |
+
const text = merged.join(" ");
|
| 945 |
+
return hasInnerCapital(word) || isUpper(firstChar(word)) ? up(text) : text;
|
| 946 |
+
}
|
| 947 |
+
|
| 948 |
+
function addressTerms(text, lex) {
|
| 949 |
+
const spans = Array.from(text.matchAll(_PROTECTED), (m) => m[0]);
|
| 950 |
+
if (!spans.length) return [];
|
| 951 |
+
return lex.filter(([term]) => {
|
| 952 |
+
const re = py(`(?<![^\\W_])${pyEscape(term)}(?![^\\W_])`, "i");
|
| 953 |
+
return spans.some((span) => re.test(span));
|
| 954 |
+
});
|
| 955 |
+
}
|
| 956 |
+
|
| 957 |
+
function respellForeign(text, lex, auto = true) {
|
| 958 |
+
const out = [];
|
| 959 |
+
let last = 0;
|
| 960 |
+
for (const m of text.matchAll(_PROTECTED)) {
|
| 961 |
+
out.push(respellSpan(text.slice(last, m.index), lex, auto));
|
| 962 |
+
const span = m[0];
|
| 963 |
+
out.push(span.includes("@") ? pyLower(span) : span);
|
| 964 |
+
last = m.index + span.length;
|
| 965 |
+
}
|
| 966 |
+
out.push(respellSpan(text.slice(last), lex, auto));
|
| 967 |
+
return out.join("");
|
| 968 |
+
}
|
| 969 |
+
|
| 970 |
+
const lexCache = new WeakMap();
|
| 971 |
+
// The pattern matches ignoring case, which also pairs the dotted and dotless i of both cases
|
| 972 |
+
// ("İnstagram", "ınstagram", "Nıke"), so the lookup key folds them the same way.
|
| 973 |
+
const key = (t) => pyLower(t.replaceAll("İ", "i").replaceAll("I", "i").replaceAll("ı", "i"));
|
| 974 |
+
|
| 975 |
+
function compileLexicon(lex) {
|
| 976 |
+
let c = lexCache.get(lex);
|
| 977 |
+
if (c) return c;
|
| 978 |
+
const terms = lex.map(([t]) => t).sort((a, b) => cpLen(b) - cpLen(a)); // stable, like sorted()
|
| 979 |
+
const says = new Map(lex);
|
| 980 |
+
const pattern = py("(?<!\\w)(" + terms.map(pyEscape).join("|") + ")(?=['’]|[^\\w]|$)", "gi");
|
| 981 |
+
const byLower = new Map();
|
| 982 |
+
for (const t of terms) byLower.set(key(t), says.get(t));
|
| 983 |
+
c = { pattern, byLower };
|
| 984 |
+
lexCache.set(lex, c);
|
| 985 |
+
return c;
|
| 986 |
+
}
|
| 987 |
+
|
| 988 |
+
function respellSpan(text, lex, auto) {
|
| 989 |
+
if (!lex || !lex.length) return auto ? autoRespell(text) : text;
|
| 990 |
+
const { pattern, byLower } = compileLexicon(lex);
|
| 991 |
+
const out = [];
|
| 992 |
+
let last = 0;
|
| 993 |
+
for (const m of text.matchAll(pattern)) {
|
| 994 |
+
out.push(auto ? autoRespell(text.slice(last, m.index)) : text.slice(last, m.index));
|
| 995 |
+
const term = m[1];
|
| 996 |
+
const say = byLower.get(key(term));
|
| 997 |
+
if (say === undefined) { // a case pairing the key does not fold: leave the words alone
|
| 998 |
+
out.push(term);
|
| 999 |
+
last = m.index + m[0].length;
|
| 1000 |
+
continue;
|
| 1001 |
+
}
|
| 1002 |
+
const kept = key(say) === key(term);
|
| 1003 |
+
out.push(kept && auto ? englishI(term) : kept ? term : say);
|
| 1004 |
+
last = m.index + m[0].length;
|
| 1005 |
+
}
|
| 1006 |
+
out.push(auto ? autoRespell(text.slice(last)) : text.slice(last));
|
| 1007 |
+
return out.join("");
|
| 1008 |
+
}
|
| 1009 |
+
|
| 1010 |
+
function englishI(word) {
|
| 1011 |
+
if (isUpper(word) && cpLen(word) <= 5) return word;
|
| 1012 |
+
return word.includes("I") && looksEnglish(word) ? word.replaceAll("I", "İ") : word;
|
| 1013 |
+
}
|
| 1014 |
+
|
| 1015 |
+
function autoRespell(text) {
|
| 1016 |
+
return sub(_TOKEN, text, (m) => {
|
| 1017 |
+
const word = m[1];
|
| 1018 |
+
const suffix = m[2] || "";
|
| 1019 |
+
if (isUpper(word) && cpLen(word) <= 5) return m[0];
|
| 1020 |
+
if (knownInTurkish(word) || !(hasInnerCapital(word) || isEnglish(word))) return englishI(word) + suffix;
|
| 1021 |
+
const r = respell(word);
|
| 1022 |
+
return (r !== null ? r : englishI(word)) + suffix;
|
| 1023 |
+
});
|
| 1024 |
+
}
|
| 1025 |
+
|
| 1026 |
+
function normalizeForCasedModel(text) {
|
| 1027 |
+
const merged = builtinLexicon;
|
| 1028 |
+
const inAddresses = addressTerms(text, merged);
|
| 1029 |
+
text = respellForeign(text, merged, true);
|
| 1030 |
+
let normalized = normalizeForModel(text);
|
| 1031 |
+
if (inAddresses.length) normalized = respellForeign(normalized, inAddresses, false);
|
| 1032 |
+
normalized = sub(_CAPS_WORD, normalized, (m) => turkishLower(m[0]));
|
| 1033 |
+
return translate(normalized, _TURKISH_CASE);
|
| 1034 |
+
}
|
| 1035 |
+
|
| 1036 |
+
function toModelText(raw) {
|
| 1037 |
+
return cleanModelText(turkishLower(normalizeForCasedModel(raw.normalize("NFC"))));
|
| 1038 |
+
}
|
| 1039 |
+
|
| 1040 |
+
/** antalia_mini.api.model_text: if the normaliser fails on some input, read the text as written
|
| 1041 |
+
* (lowercased), so synthesis never fails on text. */
|
| 1042 |
+
function modelText(raw) {
|
| 1043 |
+
try {
|
| 1044 |
+
return toModelText(raw);
|
| 1045 |
+
} catch (err) {
|
| 1046 |
+
console.warn("[antalia-mini] text normaliser failed; reading the text as written:", err);
|
| 1047 |
+
return cleanModelText(turkishLower(raw.normalize("NFC")));
|
| 1048 |
+
}
|
| 1049 |
+
}
|
| 1050 |
+
|
| 1051 |
+
/** The first call compiles ~90 Unicode regexes (about 50-150 ms); later calls take well under 1 ms.
|
| 1052 |
+
* loadFrontend() runs this once so the first real sentence is fast. */
|
| 1053 |
+
function warmup() {
|
| 1054 |
+
toModelText(
|
| 1055 |
+
"Dr. Ayşe 15.10.2026'da 14:30'da ₺1.250,50 ödedi; PatientDesk'e www.patientdesk.ai, " +
|
| 1056 |
+
"ILKER.SAHIN85@gmail.com, 0532 123 45 67, %3, 3-5 gün, 2x1 tablet, 5 mg/kg, II. Selim, SGK, D vitamini.",
|
| 1057 |
+
);
|
| 1058 |
+
}
|
| 1059 |
+
|
| 1060 |
+
return {
|
| 1061 |
+
warmup,
|
| 1062 |
+
SYMBOLS,
|
| 1063 |
+
SYMBOL_TO_ID,
|
| 1064 |
+
PAD, BOS, EOS,
|
| 1065 |
+
normalizeForCasedModel,
|
| 1066 |
+
normalizeForModel,
|
| 1067 |
+
toModelText,
|
| 1068 |
+
modelText,
|
| 1069 |
+
cleanModelText,
|
| 1070 |
+
encode,
|
| 1071 |
+
turkishLower,
|
| 1072 |
+
// foreign.py pieces, for tests and debugging
|
| 1073 |
+
isEnglish, looksEnglish, respell, respellForeign: (t, lex = builtinLexicon, auto = true) => respellForeign(t, lex, auto),
|
| 1074 |
+
};
|
| 1075 |
+
}
|
| 1076 |
+
|
| 1077 |
+
// ---------------------------------------------------------------- __init__.py
|
| 1078 |
+
|
| 1079 |
+
export const PAD = 0;
|
| 1080 |
+
export const BOS = 1;
|
| 1081 |
+
export const EOS = 2;
|
| 1082 |
+
const LETTERS_TR = "abcçdefgğhıijklmnoöpqrsştuüvwxyz";
|
| 1083 |
+
const PUNCT = " .,?!'-:;";
|
| 1084 |
+
export const SYMBOLS = ["<pad>", "<bos>", "<eos>", ...PUNCT, ...LETTERS_TR, ..."âîû"];
|
| 1085 |
+
export const SYMBOL_TO_ID = new Map(SYMBOLS.map((s, i) => [s, i]));
|
| 1086 |
+
const _FOLD = map({ "’": "'", "‘": "'", "`": "'", "´": "'", "–": "-", "—": "-", "…": ".", "\u00a0": " ", "\t": " ", "\n": " " });
|
| 1087 |
+
const _DROP = g("[^abcçdefgğhıijklmnoöpqrsştuüvwxyzâîû .,?!'\\-:;]");
|
| 1088 |
+
const _SPACE_PUNCT = g("\\s+([.,?!:;])");
|
| 1089 |
+
|
| 1090 |
+
export function cleanModelText(t) {
|
| 1091 |
+
t = translate(t, _FOLD);
|
| 1092 |
+
t = t.replace(_DROP, " ");
|
| 1093 |
+
t = t.replace(_SPACE_PUNCT, "$1");
|
| 1094 |
+
return pyStrip(t.replace(_WHITESPACE, " "));
|
| 1095 |
+
}
|
| 1096 |
+
|
| 1097 |
+
export function encode(modelText) {
|
| 1098 |
+
const ids = [BOS];
|
| 1099 |
+
for (const c of modelText) {
|
| 1100 |
+
const id = SYMBOL_TO_ID.get(c);
|
| 1101 |
+
if (id !== undefined) ids.push(id);
|
| 1102 |
+
}
|
| 1103 |
+
ids.push(EOS);
|
| 1104 |
+
return ids;
|
| 1105 |
+
}
|
| 1106 |
+
|
| 1107 |
+
// ---------------------------------------------------------------- loading
|
| 1108 |
+
|
| 1109 |
+
/** Bytes of the asset (gzipped or not: the server may already have decoded it) -> parsed object. */
|
| 1110 |
+
export async function decodeAsset(bytes) {
|
| 1111 |
+
let u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
| 1112 |
+
if (u8.length >= 2 && u8[0] === 0x1f && u8[1] === 0x8b) {
|
| 1113 |
+
const stream = new Blob([u8]).stream().pipeThrough(new DecompressionStream("gzip"));
|
| 1114 |
+
u8 = new Uint8Array(await new Response(stream).arrayBuffer());
|
| 1115 |
+
}
|
| 1116 |
+
return JSON.parse(new TextDecoder("utf-8").decode(u8));
|
| 1117 |
+
}
|
| 1118 |
+
|
| 1119 |
+
/** Fetch the asset and build the frontend. */
|
| 1120 |
+
export async function loadFrontend(url) {
|
| 1121 |
+
const res = await fetch(url);
|
| 1122 |
+
if (!res.ok) throw new Error(`frontend data: HTTP ${res.status} for ${url}`);
|
| 1123 |
+
const fe = createFrontend(await decodeAsset(await res.arrayBuffer()));
|
| 1124 |
+
fe.warmup();
|
| 1125 |
+
return fe;
|
| 1126 |
+
}
|
js/strings.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// UI strings (Turkish first) and the example sentences. The examples stay Turkish in both languages:
|
| 2 |
+
// the model speaks Turkish.
|
| 3 |
+
export const EXAMPLES = [
|
| 4 |
+
"15 Ekim'de PatientDesk üzerinden WhatsApp ile 1.250.000 TL ödendi.",
|
| 5 |
+
"Randevunuz 21 Ekim Salı günü saat 14:30'da, Dr. Ayşe Yılmaz ile. Lütfen 10 dakika önce gelin.",
|
| 6 |
+
"Yarın İzmir'de hava parçalı bulutlu olacak; sıcaklık 18 ile 24 derece arasında.",
|
| 7 |
+
"Iğdır'dan İstanbul'a giden uçak 2 saat 15 dakika rötar yaptı.",
|
| 8 |
+
];
|
| 9 |
+
|
| 10 |
+
export const STRINGS = {
|
| 11 |
+
tr: {
|
| 12 |
+
title: "Tarayıcınızda çalışan Türkçe ses",
|
| 13 |
+
lead: "Antalia-2 Mini, 7,62 milyon parametrelik açık kaynak bir Türkçe metinden konuşma modeli. Bu sayfada tamamen sizin cihazınızda çalışıyor: sunucu yok, yazdığınız metin hiçbir yere gönderilmiyor.",
|
| 14 |
+
textLabel: "Metin",
|
| 15 |
+
examples: "Örnek cümleler",
|
| 16 |
+
ex0: "Ödeme", ex1: "Randevu", ex2: "Hava durumu", ex3: "Iğdır'dan İstanbul'a",
|
| 17 |
+
play: "Seslendir", stop: "Durdur", loading: "Model yükleniyor", loadModel: "Modeli yükle ve seslendir", failed: "Yüklenemedi",
|
| 18 |
+
speed: "Hız", steps: "Örnekleme adımı", stepsShort: "Adım",
|
| 19 |
+
aiLabel: "Yapay zekâ ile üretilmiş ses",
|
| 20 |
+
readoutTitle: "Ölçümler",
|
| 21 |
+
ttfa: "İlk ses", gen: "Üretim süresi", len: "Ses uzunluğu", rtf: "Gerçek zamandan hızlı",
|
| 22 |
+
reading: "Modelin okuduğu metin",
|
| 23 |
+
download: "WAV olarak indir",
|
| 24 |
+
foot: "Apache-2.0 · Model, tarayıcınızda ONNX Runtime Web ile çalışır.",
|
| 25 |
+
downloading: "İndiriliyor", thread: "iş parçacığı", threads: "iş parçacığı", chunks: "parça",
|
| 26 |
+
error: "Hata", themeDark: "Koyu tema", themeLight: "Açık tema",
|
| 27 |
+
},
|
| 28 |
+
en: {
|
| 29 |
+
title: "Turkish speech, running in your browser",
|
| 30 |
+
lead: "Antalia-2 Mini is an open-source Turkish text-to-speech model with 7.62 million parameters. On this page it runs entirely on your device: no server, and the text you type is not sent anywhere.",
|
| 31 |
+
textLabel: "Text",
|
| 32 |
+
examples: "Example sentences",
|
| 33 |
+
ex0: "Payment", ex1: "Appointment", ex2: "Weather", ex3: "Iğdır to İstanbul",
|
| 34 |
+
play: "Speak", stop: "Stop", loading: "Loading model", loadModel: "Load model and speak", failed: "Could not load",
|
| 35 |
+
speed: "Speed", steps: "Sampling steps", stepsShort: "Steps",
|
| 36 |
+
aiLabel: "AI-generated voice",
|
| 37 |
+
readoutTitle: "Measurements",
|
| 38 |
+
ttfa: "First audio", gen: "Generation time", len: "Audio length", rtf: "Faster than real time",
|
| 39 |
+
reading: "Text as the model reads it",
|
| 40 |
+
download: "Download WAV",
|
| 41 |
+
foot: "Apache-2.0 · The model runs in your browser with ONNX Runtime Web.",
|
| 42 |
+
downloading: "Downloading", thread: "thread", threads: "threads", chunks: "chunks",
|
| 43 |
+
error: "Error", themeDark: "Dark theme", themeLight: "Light theme",
|
| 44 |
+
},
|
| 45 |
+
};
|
js/tts.js
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Antalia-2 Mini inference in the browser: four ONNX graphs and the glue between them, reproducing
|
| 2 |
+
// antalia_mini.api.Antalia.say of the release (same defaults, options and noise: the same text and seed give
|
| 3 |
+
// the same audio). Every glue step mirrors web/tools/pipeline.py line for line (that file is what
|
| 4 |
+
// verify_onnx.py checks against the released package); keep the two in step.
|
| 5 |
+
//
|
| 6 |
+
// text.onnx ids (1, L) int64 -> h (1, L, 192), logd (1, L)
|
| 7 |
+
// durations logd -> frames per symbol: double-sound stretch, / speed, round half to even, clamp 1..60
|
| 8 |
+
// frameIndex durations -> frame-to-symbol index (1, T), T rounded up to a multiple of 2
|
| 9 |
+
// cond.onnx h, idx -> ctok, cnull (1, T/2, 192)
|
| 10 |
+
// TorchRandn x0 = torch.randn(T/2, 256) * temperature, one generator per utterance
|
| 11 |
+
// flow.onnx x, ctok, cnull, t, dt, cfg -> x + (vc + (cfg-1)(vc-vu)) * dt (run `steps` times)
|
| 12 |
+
// vocoder.onnx z (1, T/2, 256) -> mel (1, 128, T), re / im (1, 1025, T)
|
| 13 |
+
// istft n_fft 2048, hop 512, Hann, centred -> 48 kHz audio, T * 512 samples
|
| 14 |
+
// edges cut the spoken prefix / suffix away (5 ms fades)
|
| 15 |
+
// pause, OutputChain silence between chunks, tone EQ (shelves at 210 Hz and 4 kHz), soft limiter
|
| 16 |
+
|
| 17 |
+
export const SAMPLE_RATE = 48000;
|
| 18 |
+
const N_FFT = 2048, HOP = 512, STACK = 2, N_MELS = 128, BINS = N_FFT / 2 + 1, MAX_DUR = 60;
|
| 19 |
+
const SPACE_ID = 3; // " " in the symbol table
|
| 20 |
+
const GRAPHS = ["text", "cond", "flow", "vocoder"];
|
| 21 |
+
|
| 22 |
+
// Which file of each graph a precision loads ("" = fp32, ".fp16" = the release's fp16 weights stored as float16,
|
| 23 |
+
// ".int8" = dynamic int8 MatMuls). Every variant computes in fp32. "mixed", the default: the acoustic graphs in
|
| 24 |
+
// fp32, so durations and mel are exactly Antalia().say's, and the vocoder (half the bytes) from the fp16 weights,
|
| 25 |
+
// which moves the audio by ~0.03 dB log-spectral distance (web/tests/onnx_verify). All-fp16 is 7 MB smaller but
|
| 26 |
+
// flips a rounded duration on ~1 sentence in 20, as Antalia(variant="fp16") does.
|
| 27 |
+
export const PRECISIONS = {
|
| 28 |
+
mixed: { text: "", cond: "", flow: "", vocoder: ".fp16" },
|
| 29 |
+
fp32: { text: "", cond: "", flow: "", vocoder: "" },
|
| 30 |
+
fp16: { text: ".fp16", cond: ".fp16", flow: ".fp16", vocoder: ".fp16" },
|
| 31 |
+
int8: { text: ".int8", cond: ".int8", flow: ".int8", vocoder: ".int8" },
|
| 32 |
+
};
|
| 33 |
+
const f32 = Math.fround;
|
| 34 |
+
|
| 35 |
+
// ----------------------------------------------------------------------------------- noise: torch.randn
|
| 36 |
+
/** torch.Generator().manual_seed(seed) and then torch.randn(n, 256, generator=g) calls, as on the CPU:
|
| 37 |
+
* mt19937, a float in [0, 1) from the low 24 bits of each draw, Box-Muller over blocks of 16 (the first 8
|
| 38 |
+
* values pair with the next 8) in float32. Equal to torch up to the last bit of log / cos / sin. */
|
| 39 |
+
export class TorchRandn {
|
| 40 |
+
constructor(seed) {
|
| 41 |
+
const s = new Uint32Array(624);
|
| 42 |
+
s[0] = seed >>> 0;
|
| 43 |
+
for (let i = 1; i < 624; i++) s[i] = (Math.imul(1812433253, s[i - 1] ^ (s[i - 1] >>> 30)) + i) >>> 0;
|
| 44 |
+
this.s = s;
|
| 45 |
+
this.i = 624;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
u32() {
|
| 49 |
+
const s = this.s;
|
| 50 |
+
if (this.i >= 624) {
|
| 51 |
+
for (let k = 0; k < 624; k++) {
|
| 52 |
+
const y = (s[k] & 0x80000000) | (s[(k + 1) % 624] & 0x7fffffff);
|
| 53 |
+
s[k] = s[(k + 397) % 624] ^ (y >>> 1) ^ (y & 1 ? 0x9908b0df : 0);
|
| 54 |
+
}
|
| 55 |
+
this.i = 0;
|
| 56 |
+
}
|
| 57 |
+
let y = s[this.i++];
|
| 58 |
+
y ^= y >>> 11;
|
| 59 |
+
y ^= (y << 7) & 0x9d2c5680;
|
| 60 |
+
y ^= (y << 15) & 0xefc60000;
|
| 61 |
+
y ^= y >>> 18;
|
| 62 |
+
return y >>> 0;
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
/** n standard normal floats (n a multiple of 16), times `scale` in float32 */
|
| 66 |
+
randn(n, scale = 1) {
|
| 67 |
+
const out = new Float32Array(n), u = new Float32Array(16), sc = f32(scale);
|
| 68 |
+
for (let b = 0; b < n; b += 16) {
|
| 69 |
+
for (let j = 0; j < 16; j++) u[j] = (this.u32() & 0xffffff) * 5.9604644775390625e-8; // 2^-24, exact
|
| 70 |
+
for (let j = 0; j < 8; j++) {
|
| 71 |
+
const r = f32(Math.sqrt(f32(-2 * f32(Math.log(f32(1 - u[j]))))));
|
| 72 |
+
const th = f32(2 * Math.PI * u[j + 8]);
|
| 73 |
+
out[b + j] = f32(f32(r * f32(Math.cos(th))) * sc);
|
| 74 |
+
out[b + j + 8] = f32(f32(r * f32(Math.sin(th))) * sc);
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
return out;
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
// ----------------------------------------------------------------------------------- glue
|
| 82 |
+
const roundHalfEven = (x) => {
|
| 83 |
+
const f = Math.floor(x), d = x - f;
|
| 84 |
+
return d > 0.5 ? f + 1 : d < 0.5 ? f : f % 2 === 0 ? f : f + 1;
|
| 85 |
+
};
|
| 86 |
+
|
| 87 |
+
/** log durations (float32, per symbol) -> frames per symbol, as Antalia._acoustic computes them. */
|
| 88 |
+
export function durations(logd, ids, speed, gemStretch = 1) {
|
| 89 |
+
const L = ids.length, ld = Float32Array.from(logd);
|
| 90 |
+
if (gemStretch !== 1) {
|
| 91 |
+
// double sounds are long in Turkish: the second of a pair inside a word ("berraktı"), the gap between a
|
| 92 |
+
// pair across a word boundary ("alerjim mahvediyor")
|
| 93 |
+
const g = f32(Math.log(gemStretch));
|
| 94 |
+
for (let j = 2; j < L - 1; j++) {
|
| 95 |
+
if (ids[j] === ids[j - 1] && ids[j] !== SPACE_ID) ld[j] = f32(ld[j] + g);
|
| 96 |
+
else if (ids[j - 1] === SPACE_ID && ids[j] === ids[j - 2]) ld[j - 1] = f32(ld[j - 1] + g);
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
const sp = f32(speed), dur = new Array(L);
|
| 100 |
+
for (let j = 0; j < L; j++) dur[j] = Math.min(MAX_DUR, Math.max(1, roundHalfEven(f32(f32(Math.exp(ld[j])) / sp))));
|
| 101 |
+
return dur;
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
export function frameIndex(dur) {
|
| 105 |
+
const L = dur.length;
|
| 106 |
+
const cum = new Array(L);
|
| 107 |
+
let s = 0;
|
| 108 |
+
for (let i = 0; i < L; i++) { s += dur[i]; cum[i] = s; }
|
| 109 |
+
const T = Math.ceil(s / STACK) * STACK;
|
| 110 |
+
const idx = new BigInt64Array(T);
|
| 111 |
+
let j = 0;
|
| 112 |
+
for (let f = 0; f < T; f++) {
|
| 113 |
+
while (j < L && cum[j] <= f) j++; // searchsorted(cum, f, side="right")
|
| 114 |
+
idx[f] = BigInt(Math.min(j, L - 1));
|
| 115 |
+
}
|
| 116 |
+
return idx;
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
// iSTFT: per frame a real inverse FFT, Hann window, overlap-add, divided by the summed squared window,
|
| 120 |
+
// trimmed by n_fft / 2 on both sides (torch.istft with center=True). The real inverse FFT of size 2048 runs
|
| 121 |
+
// as one complex inverse FFT of size 1024 over the even/odd samples packed as real/imaginary parts.
|
| 122 |
+
const M = N_FFT / 2;
|
| 123 |
+
const WINDOW = new Float64Array(N_FFT);
|
| 124 |
+
for (let i = 0; i < N_FFT; i++) WINDOW[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N_FFT);
|
| 125 |
+
const BITREV = new Uint32Array(M);
|
| 126 |
+
{
|
| 127 |
+
const bits = Math.log2(M);
|
| 128 |
+
for (let i = 0; i < M; i++) {
|
| 129 |
+
let r = 0;
|
| 130 |
+
for (let b = 0; b < bits; b++) r |= ((i >> b) & 1) << (bits - 1 - b);
|
| 131 |
+
BITREV[i] = r;
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
const COS_M = new Float64Array(M / 2), SIN_M = new Float64Array(M / 2); // twiddles of the size-M transform
|
| 135 |
+
for (let i = 0; i < M / 2; i++) { COS_M[i] = Math.cos((2 * Math.PI * i) / M); SIN_M[i] = Math.sin((2 * Math.PI * i) / M); }
|
| 136 |
+
const COS_N = new Float64Array(M), SIN_N = new Float64Array(M); // e^{+2 pi i k / N} for the odd half
|
| 137 |
+
for (let i = 0; i < M; i++) { COS_N[i] = Math.cos((2 * Math.PI * i) / N_FFT); SIN_N[i] = Math.sin((2 * Math.PI * i) / N_FFT); }
|
| 138 |
+
|
| 139 |
+
function inverseFFT(xr, xi) {
|
| 140 |
+
// in place, size M, unnormalised inverse transform (e^{+i...})
|
| 141 |
+
for (let i = 0; i < M; i++) {
|
| 142 |
+
const j = BITREV[i];
|
| 143 |
+
if (j > i) { let t = xr[i]; xr[i] = xr[j]; xr[j] = t; t = xi[i]; xi[i] = xi[j]; xi[j] = t; }
|
| 144 |
+
}
|
| 145 |
+
for (let size = 2; size <= M; size <<= 1) {
|
| 146 |
+
const half = size >> 1, step = M / size;
|
| 147 |
+
for (let start = 0; start < M; start += size) {
|
| 148 |
+
for (let k = 0; k < half; k++) {
|
| 149 |
+
const wr = COS_M[k * step], wi = SIN_M[k * step];
|
| 150 |
+
const a = start + k, b = a + half;
|
| 151 |
+
const tr = xr[b] * wr - xi[b] * wi, ti = xr[b] * wi + xi[b] * wr;
|
| 152 |
+
xr[b] = xr[a] - tr; xi[b] = xi[a] - ti;
|
| 153 |
+
xr[a] += tr; xi[a] += ti;
|
| 154 |
+
}
|
| 155 |
+
}
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
/** re, im: (1025 x T) row-major -> Float32Array of T * HOP samples (the last HOP are zeros, as the vocoder pads). */
|
| 160 |
+
export function istft(re, im, T) {
|
| 161 |
+
const n = N_FFT + HOP * (T - 1);
|
| 162 |
+
const y = new Float64Array(n), env = new Float64Array(n);
|
| 163 |
+
const zr = new Float64Array(M), zi = new Float64Array(M);
|
| 164 |
+
// frame-major copies: reading a frame's 1025 bins with stride T thrashes the cache
|
| 165 |
+
const fr = new Float32Array(BINS * T), fi = new Float32Array(BINS * T);
|
| 166 |
+
for (let k = 0; k < BINS; k++) {
|
| 167 |
+
const row = k * T;
|
| 168 |
+
for (let t = 0; t < T; t++) { fr[t * BINS + k] = re[row + t]; fi[t * BINS + k] = im[row + t]; }
|
| 169 |
+
}
|
| 170 |
+
for (let t = 0; t < T; t++) {
|
| 171 |
+
const base = t * BINS;
|
| 172 |
+
// x[2m] + i x[2m+1] = IDFT_M(E + i O) / N, with E[k] = X[k] + X[k+M], O[k] = (X[k] - X[k+M]) e^{2 pi i k/N},
|
| 173 |
+
// X[k+M] = conj(X[M-k]); the imaginary parts of the DC and Nyquist bins are ignored, as irfft does
|
| 174 |
+
for (let k = 0; k < M; k++) {
|
| 175 |
+
const ar = fr[base + k], ai = k === 0 ? 0 : fi[base + k];
|
| 176 |
+
const br = fr[base + M - k], bi = k === 0 ? 0 : -fi[base + M - k];
|
| 177 |
+
const er = ar + br, ei = ai + bi, dr = ar - br, di = ai - bi;
|
| 178 |
+
const or = dr * COS_N[k] - di * SIN_N[k], oi = dr * SIN_N[k] + di * COS_N[k];
|
| 179 |
+
zr[k] = er - oi; zi[k] = ei + or;
|
| 180 |
+
}
|
| 181 |
+
inverseFFT(zr, zi);
|
| 182 |
+
const off = t * HOP;
|
| 183 |
+
for (let m = 0; m < M; m++) {
|
| 184 |
+
const i = 2 * m, w0 = WINDOW[i], w1 = WINDOW[i + 1];
|
| 185 |
+
y[off + i] += (zr[m] / N_FFT) * w0;
|
| 186 |
+
y[off + i + 1] += (zi[m] / N_FFT) * w1;
|
| 187 |
+
env[off + i] += w0 * w0;
|
| 188 |
+
env[off + i + 1] += w1 * w1;
|
| 189 |
+
}
|
| 190 |
+
}
|
| 191 |
+
const a = N_FFT / 2, len = n - N_FFT;
|
| 192 |
+
const out = new Float32Array(T * HOP);
|
| 193 |
+
for (let i = 0; i < len; i++) {
|
| 194 |
+
const e = env[a + i];
|
| 195 |
+
out[i] = y[a + i] / (e > 1e-11 ? e : 1);
|
| 196 |
+
}
|
| 197 |
+
return out;
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
// ----------------------------------------------------------------------------------- engine
|
| 201 |
+
export class Engine {
|
| 202 |
+
/** ort: the onnxruntime-web module; buffers: {text, cond, flow, vocoder} -> ArrayBuffer;
|
| 203 |
+
* manifest: models/manifest.json (symbols, the release's defaults and options) */
|
| 204 |
+
static async create(ort, buffers, manifest, providers = ["wasm"]) {
|
| 205 |
+
const e = new Engine();
|
| 206 |
+
e.ort = ort;
|
| 207 |
+
e.sessions = {};
|
| 208 |
+
e.defaults = { steps: 4, cfg: 1, speed: 1, temperature: 1, ...(manifest.defaults || {}) };
|
| 209 |
+
e.options = { prefix: "", suffix: "", prefix_initials: null, gem_stretch: 1, tone: null, fade_ms: 5, ...(manifest.options || {}) };
|
| 210 |
+
e.symbolId = new Map(manifest.symbols.map((c, i) => [c, i]));
|
| 211 |
+
const opts = { executionProviders: providers, graphOptimizationLevel: "all" };
|
| 212 |
+
for (const k of GRAPHS) e.sessions[k] = await ort.InferenceSession.create(new Uint8Array(buffers[k]), opts);
|
| 213 |
+
return e;
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
/** model text -> ids with BOS / EOS, characters outside the symbol table dropped (== antalia_mini.text.encode) */
|
| 217 |
+
encode(text) {
|
| 218 |
+
const ids = [1];
|
| 219 |
+
for (const c of text) {
|
| 220 |
+
const id = this.symbolId.get(c);
|
| 221 |
+
if (id !== undefined && id > 2) ids.push(id);
|
| 222 |
+
}
|
| 223 |
+
ids.push(2);
|
| 224 |
+
return ids;
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
/** One chunk of model text -> 48 kHz audio with the spoken prefix / suffix cut away (before the output
|
| 228 |
+
* chain). rng: the utterance's TorchRandn. Returns {audio, timings, frames}. */
|
| 229 |
+
async synthChunk(text, rng, { steps, cfg, speed, temperature } = {}) {
|
| 230 |
+
const { ort, sessions: s, options: o, defaults: d } = this;
|
| 231 |
+
steps = Math.max(1, Math.trunc(steps || d.steps));
|
| 232 |
+
cfg = cfg ?? d.cfg;
|
| 233 |
+
speed = speed > 0 ? speed : d.speed;
|
| 234 |
+
temperature = temperature ?? d.temperature;
|
| 235 |
+
const now = () => performance.now();
|
| 236 |
+
const tm = {};
|
| 237 |
+
let t0 = now();
|
| 238 |
+
const pre = o.prefix && (o.prefix_initials == null || o.prefix_initials.includes(text.slice(0, 1))) ? o.prefix : "";
|
| 239 |
+
const suf = o.suffix || "";
|
| 240 |
+
const nPre = pre ? this.encode(pre).length - 2 : 0, nSuf = suf ? this.encode(suf).length - 2 : 0;
|
| 241 |
+
const ids = this.encode(pre + text + suf);
|
| 242 |
+
const L = ids.length;
|
| 243 |
+
const r1 = await s.text.run({ ids: new ort.Tensor("int64", BigInt64Array.from(ids.map(BigInt)), [1, L]) });
|
| 244 |
+
const dur = durations(r1.logd.data, ids, speed, o.gem_stretch);
|
| 245 |
+
tm.text = now() - t0; t0 = now();
|
| 246 |
+
|
| 247 |
+
const idx = frameIndex(dur);
|
| 248 |
+
const T = idx.length, N = T / STACK;
|
| 249 |
+
const r2 = await s.cond.run({ h: r1.h, idx: new ort.Tensor("int64", idx, [1, T]) });
|
| 250 |
+
tm.cond = now() - t0; t0 = now();
|
| 251 |
+
|
| 252 |
+
let x = new ort.Tensor("float32", rng.randn(N * N_MELS * STACK, temperature), [1, N, N_MELS * STACK]);
|
| 253 |
+
const dtv = 1 / steps;
|
| 254 |
+
const dt = new ort.Tensor("float32", new Float32Array([dtv]), [1]);
|
| 255 |
+
const cfgT = new ort.Tensor("float32", new Float32Array([cfg]), [1]);
|
| 256 |
+
for (let i = 0; i < steps; i++) {
|
| 257 |
+
const r = await s.flow.run({ x, ctok: r2.ctok, cnull: r2.cnull, t: new ort.Tensor("float32", new Float32Array([i * dtv]), [1]), dt, cfg: cfgT });
|
| 258 |
+
if (i) x.dispose?.();
|
| 259 |
+
x = r.x_next;
|
| 260 |
+
}
|
| 261 |
+
tm.flow = now() - t0; t0 = now();
|
| 262 |
+
|
| 263 |
+
const r4 = await s.vocoder.run({ z: x });
|
| 264 |
+
tm.vocoder = now() - t0; t0 = now();
|
| 265 |
+
let audio = istft(r4.re.data, r4.im.data, T);
|
| 266 |
+
tm.istft = now() - t0;
|
| 267 |
+
for (const k of [r1.h, r1.logd, r2.ctok, r2.cnull, x, r4.mel, r4.re, r4.im]) k.dispose?.();
|
| 268 |
+
|
| 269 |
+
if (pre || suf) {
|
| 270 |
+
// api._edges: keep the frame span of the chunk's own text (after BOS + prefix, before suffix + EOS)
|
| 271 |
+
let cum = 0, a = 0, b = 0;
|
| 272 |
+
for (let j = 0; j < L; j++) {
|
| 273 |
+
cum += dur[j];
|
| 274 |
+
if (j === nPre) a = cum;
|
| 275 |
+
if (j === L - 2 - nSuf) b = cum;
|
| 276 |
+
}
|
| 277 |
+
audio = audio.slice(pre ? a * HOP : 0, suf ? b * HOP : audio.length);
|
| 278 |
+
const fade = Math.floor((o.fade_ms * SAMPLE_RATE) / 1000);
|
| 279 |
+
if (pre && fade && audio.length > 2 * fade) for (let i = 0; i < fade; i++) audio[i] = f32(audio[i] * fadeIn(i, fade));
|
| 280 |
+
if (suf && fade && audio.length > 2 * fade) {
|
| 281 |
+
const off = audio.length - fade;
|
| 282 |
+
for (let i = 0; i < fade; i++) audio[off + i] = f32(audio[off + i] * fadeOut(i, fade));
|
| 283 |
+
}
|
| 284 |
+
}
|
| 285 |
+
return { audio, timings: tm, frames: T };
|
| 286 |
+
}
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
// np.linspace(0, 1, n, dtype=float32) and np.linspace(1, 0, n, dtype=float32), element i
|
| 290 |
+
const fadeIn = (i, n) => (i === n - 1 ? 1 : f32(i * (1 / (n - 1))));
|
| 291 |
+
const fadeOut = (i, n) => (i === n - 1 ? 0 : f32(i * (-1 / (n - 1)) + 1));
|
| 292 |
+
|
| 293 |
+
/** Silence after a chunk that is not the last: 0.12 s after a sentence, 0.06 s after a clause. */
|
| 294 |
+
export function pauseAfter(chunk) {
|
| 295 |
+
return new Float32Array(Math.floor((/[.?!]$/.test(chunk.trimEnd()) ? 0.12 : 0.06) * SAMPLE_RATE));
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
// ----------------------------------------------------------------------------------- output chain
|
| 299 |
+
const LIMIT_THRESHOLD = 10 ** (-1 / 20), LIMIT_CEILING = 10 ** (-0.1 / 20);
|
| 300 |
+
|
| 301 |
+
function shelf(f0, gainDb, high, q = 0.707) {
|
| 302 |
+
// RBJ cookbook low / high shelf, normalised [b0, b1, b2, a1, a2]
|
| 303 |
+
const A = 10 ** (gainDb / 40), w0 = (2 * Math.PI * f0) / SAMPLE_RATE;
|
| 304 |
+
const alpha = Math.sin(w0) / (2 * q), c = Math.cos(w0), s = 2 * Math.sqrt(A) * alpha;
|
| 305 |
+
const b = high
|
| 306 |
+
? [A * (A + 1 + (A - 1) * c + s), -2 * A * (A - 1 + (A + 1) * c), A * (A + 1 + (A - 1) * c - s)]
|
| 307 |
+
: [A * (A + 1 - (A - 1) * c + s), 2 * A * (A - 1 - (A + 1) * c), A * (A + 1 - (A - 1) * c - s)];
|
| 308 |
+
const a = high
|
| 309 |
+
? [A + 1 - (A - 1) * c + s, 2 * (A - 1 - (A + 1) * c), A + 1 - (A - 1) * c - s]
|
| 310 |
+
: [A + 1 + (A - 1) * c + s, -2 * (A - 1 + (A + 1) * c), A + 1 + (A - 1) * c - s];
|
| 311 |
+
return [b[0] / a[0], b[1] / a[0], b[2] / a[0], a[1] / a[0], a[2] / a[0]];
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
/** post.OutputChain at 48 kHz: with tone [low dB, high dB], a low shelf at 210 Hz and a high shelf at 4 kHz
|
| 315 |
+
* (replacing the default EQ, no make-up gain), then the soft limiter (knee from -1 dBFS, ceiling -0.1 dBFS).
|
| 316 |
+
* The release applies the shelves as an FIR of their impulse response; the same biquads run recursively here.
|
| 317 |
+
* State carries across chunks, so chunk by chunk equals the whole utterance at once. */
|
| 318 |
+
export class OutputChain {
|
| 319 |
+
constructor(tone) {
|
| 320 |
+
this.sections = tone ? [shelf(210, tone[0], false), shelf(4000, tone[1], true)] : [];
|
| 321 |
+
this.state = this.sections.map(() => [0, 0, 0, 0]);
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
process(x) {
|
| 325 |
+
const n = x.length, out = new Float32Array(n);
|
| 326 |
+
if (!this.sections.length) {
|
| 327 |
+
for (let i = 0; i < n; i++) out[i] = Math.max(-1, Math.min(1, x[i]));
|
| 328 |
+
return out;
|
| 329 |
+
}
|
| 330 |
+
const y = Float64Array.from(x);
|
| 331 |
+
this.sections.forEach(([b0, b1, b2, a1, a2], k) => {
|
| 332 |
+
let [x1, x2, y1, y2] = this.state[k];
|
| 333 |
+
for (let i = 0; i < n; i++) {
|
| 334 |
+
const v = y[i], o = b0 * v + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;
|
| 335 |
+
x2 = x1; x1 = v; y2 = y1; y1 = o;
|
| 336 |
+
y[i] = o;
|
| 337 |
+
}
|
| 338 |
+
this.state[k] = [x1, x2, y1, y2];
|
| 339 |
+
});
|
| 340 |
+
const room = LIMIT_CEILING - LIMIT_THRESHOLD;
|
| 341 |
+
for (let i = 0; i < n; i++) {
|
| 342 |
+
const v = y[i], a = Math.abs(v);
|
| 343 |
+
out[i] = a > LIMIT_THRESHOLD ? Math.sign(v) * (LIMIT_THRESHOLD + room * Math.tanh((a - LIMIT_THRESHOLD) / room)) : v;
|
| 344 |
+
}
|
| 345 |
+
return out;
|
| 346 |
+
}
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
// ----------------------------------------------------------------------------------- one utterance
|
| 350 |
+
/** Antalia.stream: model text -> audio chunks (first sentence first) through one noise generator and one
|
| 351 |
+
* output chain; joined, the chunks equal Antalia.say(text, seed) of the release.
|
| 352 |
+
* Yields {audio, index, count, timings}. */
|
| 353 |
+
export async function* speak(engine, modelText, { seed = 0, steps, cfg, speed, temperature } = {}) {
|
| 354 |
+
const chunks = splitModelText(modelText);
|
| 355 |
+
const rng = new TorchRandn(seed), chain = new OutputChain(engine.options.tone);
|
| 356 |
+
for (let k = 0; k < chunks.length; k++) {
|
| 357 |
+
const { audio, timings } = await engine.synthChunk(chunks[k], rng, { steps, cfg, speed, temperature });
|
| 358 |
+
const t0 = performance.now();
|
| 359 |
+
let w = audio;
|
| 360 |
+
if (k < chunks.length - 1) {
|
| 361 |
+
const p = pauseAfter(chunks[k]);
|
| 362 |
+
w = new Float32Array(audio.length + p.length);
|
| 363 |
+
w.set(audio);
|
| 364 |
+
}
|
| 365 |
+
w = chain.process(w);
|
| 366 |
+
timings.post = performance.now() - t0;
|
| 367 |
+
yield { audio: w, index: k, count: chunks.length, timings };
|
| 368 |
+
}
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
// ----------------------------------------------------------------------------------- text chunks
|
| 372 |
+
// api.split_model_text: sentences packed up to 300 characters (~18 s), a longer sentence cut at commas, then
|
| 373 |
+
// at spaces; the first chunk packs only up to 80 characters (but always holds the whole first sentence), so
|
| 374 |
+
// playback starts after the first sentence.
|
| 375 |
+
const pyLen = (s) => Array.from(s).length;
|
| 376 |
+
|
| 377 |
+
function pack(pieces, maxChars, sep = " ") {
|
| 378 |
+
const out = [];
|
| 379 |
+
let cur = "";
|
| 380 |
+
for (const p of pieces) {
|
| 381 |
+
if (pyLen(p) > maxChars) {
|
| 382 |
+
if (cur) { out.push(cur); cur = ""; }
|
| 383 |
+
if (sep === " " && p.includes(" ")) out.push(...pack(p.split(" "), maxChars));
|
| 384 |
+
else { const cp = Array.from(p); for (let i = 0; i < cp.length; i += maxChars) out.push(cp.slice(i, i + maxChars).join("")); }
|
| 385 |
+
continue;
|
| 386 |
+
}
|
| 387 |
+
if (cur && pyLen(cur) + 1 + pyLen(p) > maxChars) { out.push(cur); cur = p; }
|
| 388 |
+
else cur = cur ? `${cur} ${p}` : p;
|
| 389 |
+
}
|
| 390 |
+
if (cur) out.push(cur);
|
| 391 |
+
return out;
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
export function splitModelText(text, maxChars = 300, firstChars = 80) {
|
| 395 |
+
const sentences = text.trim().split(/(?<=[.?!])\s+/u).map((s) => s.trim()).filter(Boolean);
|
| 396 |
+
const pieces = [];
|
| 397 |
+
for (const s of sentences) {
|
| 398 |
+
if (pyLen(s) > maxChars) pieces.push(...pack(s.split(/(?<=[,;:])\s+/u).filter(Boolean), maxChars));
|
| 399 |
+
else pieces.push(s);
|
| 400 |
+
}
|
| 401 |
+
if (!pieces.length) return [];
|
| 402 |
+
let chunks;
|
| 403 |
+
if (firstChars) {
|
| 404 |
+
let head = "", used = 0;
|
| 405 |
+
for (const p of pieces) {
|
| 406 |
+
if (head && pyLen(head) + 1 + pyLen(p) > firstChars) break;
|
| 407 |
+
head = head ? `${head} ${p}` : p;
|
| 408 |
+
used++;
|
| 409 |
+
}
|
| 410 |
+
chunks = [head, ...pack(pieces.slice(used), maxChars)];
|
| 411 |
+
} else chunks = pack(pieces, maxChars);
|
| 412 |
+
return chunks.filter((c) => /\p{L}/u.test(c));
|
| 413 |
+
}
|
js/worker.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Runs the text frontend and the model off the main thread.
|
| 2 |
+
// -> {type: "init", backend: "wasm" | "webgpu", threads, precision: "mixed" | "fp32" | "fp16" | "int8"}
|
| 3 |
+
// <- {type: "progress", loaded, total} ... {type: "ready", info}
|
| 4 |
+
// -> {type: "synth", id, text, steps?, speed?, seed} (steps / speed default to the release's)
|
| 5 |
+
// <- {type: "text", id, modelText} {type: "chunk", id, index, count, audio, timings} ... {type: "done", id, stats}
|
| 6 |
+
// <- {type: "error", id?, message}
|
| 7 |
+
import { Engine, PRECISIONS, SAMPLE_RATE, speak } from "./tts.js";
|
| 8 |
+
import { loadFrontend } from "./frontend.js";
|
| 9 |
+
|
| 10 |
+
const BASE = new URL("../", import.meta.url);
|
| 11 |
+
let engine = null, frontend = null, manifest = null;
|
| 12 |
+
|
| 13 |
+
async function fetchWithProgress(urls, onProgress) {
|
| 14 |
+
// Content-Length per file when the server sends it, else the sizes recorded in the manifest
|
| 15 |
+
const sizes = urls.map((u) => manifest?.files?.[u.split("/").pop().split("?")[0]]?.bytes || 0);
|
| 16 |
+
const loaded = urls.map(() => 0);
|
| 17 |
+
const report = () => onProgress(loaded.reduce((a, b) => a + b, 0), sizes.reduce((a, b) => a + b, 0));
|
| 18 |
+
return Promise.all(urls.map(async (u, i) => {
|
| 19 |
+
const res = await fetch(new URL(u, BASE));
|
| 20 |
+
if (!res.ok) throw new Error(`${u}: HTTP ${res.status}`);
|
| 21 |
+
const len = Number(res.headers.get("Content-Length")) || 0;
|
| 22 |
+
if (len && !res.headers.get("Content-Encoding")) sizes[i] = len;
|
| 23 |
+
if (!res.body) { const b = await res.arrayBuffer(); loaded[i] = b.byteLength; report(); return b; }
|
| 24 |
+
const reader = res.body.getReader();
|
| 25 |
+
const parts = [];
|
| 26 |
+
for (;;) {
|
| 27 |
+
const { done, value } = await reader.read();
|
| 28 |
+
if (done) break;
|
| 29 |
+
parts.push(value);
|
| 30 |
+
loaded[i] += value.byteLength;
|
| 31 |
+
report();
|
| 32 |
+
}
|
| 33 |
+
const out = new Uint8Array(loaded[i]);
|
| 34 |
+
let o = 0;
|
| 35 |
+
for (const p of parts) { out.set(p, o); o += p.byteLength; }
|
| 36 |
+
return out.buffer;
|
| 37 |
+
}));
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
async function init({ backend = "wasm", threads = 0, precision = "mixed" }) {
|
| 41 |
+
const t0 = performance.now();
|
| 42 |
+
manifest = await (await fetch(new URL("models/manifest.json", BASE), { cache: "no-cache" })).json();
|
| 43 |
+
const useGpu = backend === "webgpu";
|
| 44 |
+
const ort = await import(useGpu ? "../vendor/ort/ort.webgpu.min.mjs" : "../vendor/ort/ort.wasm.min.mjs");
|
| 45 |
+
ort.env.wasm.wasmPaths = new URL("vendor/ort/", BASE).href;
|
| 46 |
+
// threads need SharedArrayBuffer, i.e. a cross-origin isolated page. Half the cores, at most 4: on a
|
| 47 |
+
// 10-core M5, 1/2/4/6/8 threads gave 27/41/46/50/41x real time, and phones mix fast and slow cores.
|
| 48 |
+
const cores = self.crossOriginIsolated ? navigator.hardwareConcurrency || 1 : 1;
|
| 49 |
+
ort.env.wasm.numThreads = threads ? Math.min(threads, cores) : Math.max(1, Math.min(4, Math.floor(cores / 2)));
|
| 50 |
+
if (!PRECISIONS[precision]) precision = "mixed";
|
| 51 |
+
// ?v=<sha256 prefix>: new weights get new URLs, so the service worker's cache-first copy is never stale
|
| 52 |
+
const files = ["text", "cond", "flow", "vocoder"].map((k) => {
|
| 53 |
+
const name = `${k}${PRECISIONS[precision][k]}.onnx`;
|
| 54 |
+
return `models/${name}?v=${manifest.files[name]?.sha256 || "0"}`;
|
| 55 |
+
});
|
| 56 |
+
const [buffers, fe] = await Promise.all([
|
| 57 |
+
fetchWithProgress(files, (loaded, total) => postMessage({ type: "progress", loaded, total })),
|
| 58 |
+
loadFrontend(new URL("assets/frontend-data.json.gz", BASE)),
|
| 59 |
+
]);
|
| 60 |
+
frontend = fe;
|
| 61 |
+
const tLoaded = performance.now();
|
| 62 |
+
engine = await Engine.create(ort, { text: buffers[0], cond: buffers[1], flow: buffers[2], vocoder: buffers[3] },
|
| 63 |
+
manifest, useGpu ? ["webgpu", "wasm"] : ["wasm"]);
|
| 64 |
+
// warm-up: the first run of each graph allocates and picks kernels; the frontend compiles its patterns
|
| 65 |
+
for await (const _ of speak(engine, fe.modelText("Merhaba, 15 Ekim'de 1.250 TL."), { steps: 1 }));
|
| 66 |
+
const tReady = performance.now();
|
| 67 |
+
postMessage({
|
| 68 |
+
type: "ready",
|
| 69 |
+
info: {
|
| 70 |
+
backend: useGpu ? "webgpu" : "wasm", threads: ort.env.wasm.numThreads, crossOriginIsolated: self.crossOriginIsolated,
|
| 71 |
+
precision, bytes: buffers.reduce((a, b) => a + b.byteLength, 0), downloadMs: tLoaded - t0,
|
| 72 |
+
initMs: tReady - tLoaded, weights: manifest.weights, params: manifest.params_inference, ortVersion: ort.env.versions?.web,
|
| 73 |
+
model: manifest.model, version: manifest.version, defaults: engine.defaults,
|
| 74 |
+
},
|
| 75 |
+
});
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
async function synth({ id, text, steps, speed, seed = 0 }) {
|
| 79 |
+
const t0 = performance.now();
|
| 80 |
+
const modelText = frontend.modelText(text);
|
| 81 |
+
const tNorm = performance.now() - t0;
|
| 82 |
+
postMessage({ type: "text", id, modelText });
|
| 83 |
+
let samples = 0, compute = tNorm, count = 0;
|
| 84 |
+
const timings = { normalize: tNorm, text: 0, cond: 0, flow: 0, vocoder: 0, istft: 0, post: 0 };
|
| 85 |
+
let c0 = performance.now();
|
| 86 |
+
for await (const { audio, index, count: n, timings: tm } of speak(engine, modelText, { seed, steps, speed })) {
|
| 87 |
+
compute += performance.now() - c0;
|
| 88 |
+
for (const k in tm) timings[k] += tm[k];
|
| 89 |
+
samples += audio.length;
|
| 90 |
+
count = n;
|
| 91 |
+
postMessage({ type: "chunk", id, index, count: n, audio, sinceStart: performance.now() - t0 }, [audio.buffer]);
|
| 92 |
+
c0 = performance.now();
|
| 93 |
+
}
|
| 94 |
+
postMessage({ type: "done", id, stats: { computeMs: compute, wallMs: performance.now() - t0, seconds: samples / SAMPLE_RATE, chunks: count, timings } });
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
let queue = Promise.resolve();
|
| 98 |
+
onmessage = (ev) => {
|
| 99 |
+
const msg = ev.data;
|
| 100 |
+
queue = queue.then(async () => {
|
| 101 |
+
try {
|
| 102 |
+
if (msg.type === "init") await init(msg);
|
| 103 |
+
else if (msg.type === "synth") await synth(msg);
|
| 104 |
+
} catch (err) {
|
| 105 |
+
postMessage({ type: "error", id: msg.id, message: String(err?.message || err) });
|
| 106 |
+
}
|
| 107 |
+
});
|
| 108 |
+
};
|
models/cond.fp16.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:664a0704b2594a6b7726ad71a314b97b050d31120eafc6bdcae1c20c055d03f1
|
| 3 |
+
size 315081
|
models/cond.int8.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b361bf461341955192db7be1fa33f1580c656bd9bf91c2804e79bf9aeea44afe
|
| 3 |
+
size 771040
|
models/cond.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:55aa32749a8a6f8180f06694e9b36a10b2c632d8ecd250e04be6823bfc2b15ec
|
| 3 |
+
size 613058
|
models/flow.fp16.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e3b79aecb85765c7bc6dc1aa24dd3a0059b9a9c85801ed9077f7df64879400a9
|
| 3 |
+
size 5221397
|
models/flow.int8.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0d7490885d4ce2d4f88377bde70c489374d5b8087391735d6914cadda64963f8
|
| 3 |
+
size 2851323
|
models/flow.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0ec1fca11bad905e8fba85c2855ae08042a0787e244d7cbc525059349ffc16a5
|
| 3 |
+
size 10288080
|
models/manifest.json
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": "Antalia-2 Mini",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"params_inference": 7620931,
|
| 5 |
+
"sample_rate": 48000,
|
| 6 |
+
"symbols": [
|
| 7 |
+
"<pad>",
|
| 8 |
+
"<bos>",
|
| 9 |
+
"<eos>",
|
| 10 |
+
" ",
|
| 11 |
+
".",
|
| 12 |
+
",",
|
| 13 |
+
"?",
|
| 14 |
+
"!",
|
| 15 |
+
"'",
|
| 16 |
+
"-",
|
| 17 |
+
":",
|
| 18 |
+
";",
|
| 19 |
+
"a",
|
| 20 |
+
"b",
|
| 21 |
+
"c",
|
| 22 |
+
"ç",
|
| 23 |
+
"d",
|
| 24 |
+
"e",
|
| 25 |
+
"f",
|
| 26 |
+
"g",
|
| 27 |
+
"ğ",
|
| 28 |
+
"h",
|
| 29 |
+
"ı",
|
| 30 |
+
"i",
|
| 31 |
+
"j",
|
| 32 |
+
"k",
|
| 33 |
+
"l",
|
| 34 |
+
"m",
|
| 35 |
+
"n",
|
| 36 |
+
"o",
|
| 37 |
+
"ö",
|
| 38 |
+
"p",
|
| 39 |
+
"q",
|
| 40 |
+
"r",
|
| 41 |
+
"s",
|
| 42 |
+
"ş",
|
| 43 |
+
"t",
|
| 44 |
+
"u",
|
| 45 |
+
"ü",
|
| 46 |
+
"v",
|
| 47 |
+
"w",
|
| 48 |
+
"x",
|
| 49 |
+
"y",
|
| 50 |
+
"z",
|
| 51 |
+
"â",
|
| 52 |
+
"î",
|
| 53 |
+
"û"
|
| 54 |
+
],
|
| 55 |
+
"opset": 17,
|
| 56 |
+
"weights": {
|
| 57 |
+
"version": "1.0.0",
|
| 58 |
+
"acoustic": {
|
| 59 |
+
"file": "ac-main-short.pt",
|
| 60 |
+
"step": 51880,
|
| 61 |
+
"weights": "ema"
|
| 62 |
+
},
|
| 63 |
+
"vocoder": {
|
| 64 |
+
"file": "voc-gta3-76860.pt",
|
| 65 |
+
"step": 76860
|
| 66 |
+
},
|
| 67 |
+
"sha256": {
|
| 68 |
+
"acoustic.safetensors": "72c36a6855ce95dc",
|
| 69 |
+
"vocoder.safetensors": "89ca374cc55864b3",
|
| 70 |
+
"acoustic.fp16.safetensors": "c94d5cbe11df77db",
|
| 71 |
+
"vocoder.fp16.safetensors": "a5ba4b559daccf93"
|
| 72 |
+
},
|
| 73 |
+
"fp16_graphs_from": "acoustic.fp16.safetensors + vocoder.fp16.safetensors"
|
| 74 |
+
},
|
| 75 |
+
"defaults": {
|
| 76 |
+
"steps": 8,
|
| 77 |
+
"cfg": 2.0,
|
| 78 |
+
"speed": 0.95,
|
| 79 |
+
"temperature": 0.6
|
| 80 |
+
},
|
| 81 |
+
"options": {
|
| 82 |
+
"suffix": " ee.",
|
| 83 |
+
"prefix": "ee, ",
|
| 84 |
+
"prefix_initials": "öı",
|
| 85 |
+
"gem_stretch": 1.3,
|
| 86 |
+
"tone": [
|
| 87 |
+
6.0,
|
| 88 |
+
-9.0
|
| 89 |
+
]
|
| 90 |
+
},
|
| 91 |
+
"files": {
|
| 92 |
+
"text.onnx": {
|
| 93 |
+
"bytes": 4048328,
|
| 94 |
+
"sha256": "6b74570a31734f9a"
|
| 95 |
+
},
|
| 96 |
+
"text.fp16.onnx": {
|
| 97 |
+
"bytes": 2058376,
|
| 98 |
+
"sha256": "cfeb9fe582926b9e"
|
| 99 |
+
},
|
| 100 |
+
"text.int8.onnx": {
|
| 101 |
+
"bytes": 1662683,
|
| 102 |
+
"sha256": "159f387268579038"
|
| 103 |
+
},
|
| 104 |
+
"cond.onnx": {
|
| 105 |
+
"bytes": 613058,
|
| 106 |
+
"sha256": "55aa32749a8a6f81"
|
| 107 |
+
},
|
| 108 |
+
"cond.fp16.onnx": {
|
| 109 |
+
"bytes": 315081,
|
| 110 |
+
"sha256": "664a0704b2594a6b"
|
| 111 |
+
},
|
| 112 |
+
"cond.int8.onnx": {
|
| 113 |
+
"bytes": 771040,
|
| 114 |
+
"sha256": "b361bf4613419551"
|
| 115 |
+
},
|
| 116 |
+
"flow.onnx": {
|
| 117 |
+
"bytes": 10288080,
|
| 118 |
+
"sha256": "0ec1fca11bad905e"
|
| 119 |
+
},
|
| 120 |
+
"flow.fp16.onnx": {
|
| 121 |
+
"bytes": 5221397,
|
| 122 |
+
"sha256": "e3b79aecb85765c7"
|
| 123 |
+
},
|
| 124 |
+
"flow.int8.onnx": {
|
| 125 |
+
"bytes": 2851323,
|
| 126 |
+
"sha256": "0d7490885d4ce2d4"
|
| 127 |
+
},
|
| 128 |
+
"vocoder.onnx": {
|
| 129 |
+
"bytes": 15758929,
|
| 130 |
+
"sha256": "4deec2f68e03e59b"
|
| 131 |
+
},
|
| 132 |
+
"vocoder.fp16.onnx": {
|
| 133 |
+
"bytes": 7898746,
|
| 134 |
+
"sha256": "c82c830e4fc83446"
|
| 135 |
+
},
|
| 136 |
+
"vocoder.int8.onnx": {
|
| 137 |
+
"bytes": 4827420,
|
| 138 |
+
"sha256": "dc2b795e854f536a"
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
}
|
models/text.fp16.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cfeb9fe582926b9e7052ad6d048e2473f1612c171e20f338780adacc6d0ede5e
|
| 3 |
+
size 2058376
|
models/text.int8.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:159f3872685790383fb920a1714e39040b96ce61eade7b45c1c43b92e1b0c975
|
| 3 |
+
size 1662683
|
models/text.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6b74570a31734f9aebb121dce04a44f09c2aa0fbe0d299147c4506b4546b2ce8
|
| 3 |
+
size 4048328
|
models/vocoder.fp16.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c82c830e4fc83446918af9f4f35711e4b3c361eab3a25288d117b7ff4cb24417
|
| 3 |
+
size 7898746
|
models/vocoder.int8.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dc2b795e854f536aea7ffe28dbe8a1b521067c1d7fa54d84e700db2f71fad2ef
|
| 3 |
+
size 4827420
|
models/vocoder.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4deec2f68e03e59b949a27c5bc4e775879625e836980cfe00d81408520dd3cfa
|
| 3 |
+
size 15758929
|
sw.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Offline support: after the first visit the page, the runtime and the model come from this cache.
|
| 2 |
+
// Model files are requested with ?v=<sha256 prefix> from models/manifest.json, so new weights get new
|
| 3 |
+
// cache keys (cache-first is safe for them); everything else is network-first with the cache as fallback.
|
| 4 |
+
// COI = true also adds COOP/COEP headers, which makes the page cross-origin isolated on hosts that do not
|
| 5 |
+
// send them (static Spaces), so ONNX Runtime Web may use threads; it costs one reload on the first visit.
|
| 6 |
+
const CACHE = "antalia-mini-v1";
|
| 7 |
+
const COI = true;
|
| 8 |
+
|
| 9 |
+
self.addEventListener("install", () => self.skipWaiting());
|
| 10 |
+
self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim()));
|
| 11 |
+
|
| 12 |
+
function withCoi(res) {
|
| 13 |
+
if (!COI || res.status === 0 || res.type === "opaque") return res;
|
| 14 |
+
const h = new Headers(res.headers);
|
| 15 |
+
h.set("Cross-Origin-Opener-Policy", "same-origin");
|
| 16 |
+
h.set("Cross-Origin-Embedder-Policy", "require-corp");
|
| 17 |
+
h.set("Cross-Origin-Resource-Policy", "same-origin");
|
| 18 |
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers: h });
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
async function cacheFirst(req) {
|
| 22 |
+
const cache = await caches.open(CACHE);
|
| 23 |
+
const hit = await cache.match(req);
|
| 24 |
+
if (hit) return hit;
|
| 25 |
+
const res = await fetch(req);
|
| 26 |
+
if (res.ok) cache.put(req, res.clone());
|
| 27 |
+
return res;
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
async function networkFirst(req) {
|
| 31 |
+
const cache = await caches.open(CACHE);
|
| 32 |
+
try {
|
| 33 |
+
const res = await fetch(req);
|
| 34 |
+
if (res.ok) cache.put(req, res.clone());
|
| 35 |
+
return res;
|
| 36 |
+
} catch (err) {
|
| 37 |
+
const hit = await cache.match(req, { ignoreSearch: req.mode === "navigate" });
|
| 38 |
+
if (hit) return hit;
|
| 39 |
+
throw err;
|
| 40 |
+
}
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
self.addEventListener("fetch", (e) => {
|
| 44 |
+
const req = e.request;
|
| 45 |
+
if (req.method !== "GET") return;
|
| 46 |
+
const url = new URL(req.url);
|
| 47 |
+
const sameOrigin = url.origin === self.location.origin;
|
| 48 |
+
const immutable = (sameOrigin && (/\/models\/.+\.onnx$/.test(url.pathname) && url.searchParams.has("v")))
|
| 49 |
+
|| (sameOrigin && url.pathname.includes("/vendor/"))
|
| 50 |
+
|| url.hostname === "fonts.gstatic.com";
|
| 51 |
+
const p = immutable ? cacheFirst(req) : networkFirst(req);
|
| 52 |
+
e.respondWith(sameOrigin ? p.then(withCoi) : p);
|
| 53 |
+
});
|
vendor/ort/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) Microsoft Corporation
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
vendor/ort/VERSION
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
1.30.0
|
vendor/ort/ort-wasm-simd-threaded.asyncify.mjs
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
async function ortWasmThreaded(moduleArg={}){var moduleRtn;var g=moduleArg,aa=!!globalThis.window,ba=!!globalThis.WorkerGlobalScope,m=globalThis.process?.versions?.node&&"renderer"!=globalThis.process?.type,n=ba&&self.name?.startsWith("em-pthread");if(m){const {createRequire:a}=await import("module");var require=a(import.meta.url),ca=require("worker_threads");global.Worker=ca.Worker;n=(ba=!ca.Qe)&&"em-pthread"==ca.workerData}g.mountExternalData=(a,b)=>{a.startsWith("./")&&(a=a.substring(2));(g.ed||(g.ed=new Map)).set(a,b)};
|
| 2 |
+
g.unmountExternalData=()=>{delete g.ed;delete g.Te;delete g.Se;delete g.Ue};var SharedArrayBuffer=globalThis.SharedArrayBuffer??(new WebAssembly.Memory({initial:0,maximum:0,shared:!0})).buffer.constructor;
|
| 3 |
+
let ea=()=>{const a=b=>(...c)=>{const d=r;c=b(...c);return r!=d?da():c};(b=>{for(const c of b)g[c]=a(g[c])})(["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"]);"undefined"!==typeof jsepRunAsync&&(g._OrtRun=jsepRunAsync(g._OrtRun),g._OrtRunWithBinding=jsepRunAsync(g._OrtRunWithBinding));ea=void 0};g.asyncInit=()=>{ea?.()};var fa="./this.program",ha=(a,b)=>{throw b;},ia=import.meta.url,ka="",la,ma;
|
| 4 |
+
if(m){var fs=require("fs");ia.startsWith("file:")&&(ka=require("path").dirname(require("url").fileURLToPath(ia))+"/");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.argv.length&&(fa=process.argv[1].replace(/\\/g,"/"));process.argv.slice(2);ha=(a,b)=>{process.exitCode=a;throw b;}}else if(aa||ba){try{ka=(new URL(".",ia)).href}catch{}m||(ba&&(ma=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";
|
| 5 |
+
b.send(null);return new Uint8Array(b.response)}),la=async a=>{if(na(a))return new Promise((c,d)=>{var e=new XMLHttpRequest;e.open("GET",a,!0);e.responseType="arraybuffer";e.onload=()=>{200==e.status||0==e.status&&e.response?c(e.response):d(e.status)};e.onerror=d;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);
|
| 6 |
+
if(m){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,t=pa,ta,ua,va=!1,wa,na=a=>a.startsWith("file://");function u(){v.buffer!=w.buffer&&xa()}var ya,za;
|
| 7 |
+
if(m&&n){var Ba=ca.parentPort;Ba.on("message",a=>global.onmessage?.({data:a}));Object.assign(globalThis,{self:global,postMessage:a=>Ba.postMessage(a)});process.on("uncaughtException",a=>{postMessage({$c:"uncaughtException",error:a});process.exit(1)})}var Ca;
|
| 8 |
+
if(n){var Da=!1;self.onunhandledrejection=b=>{throw b.reason||b;};function a(b){try{var c=b.data,d=c.$c;if("load"===d){let e=[];self.onmessage=f=>e.push(f);Ca=()=>{postMessage({$c:"loaded"});for(let f of e)a(f);self.onmessage=a};for(const f of c.ue)if(!g[f]||g[f].proxy)g[f]=(...k)=>{postMessage({$c:"callHandler",te:f,args:k})},"print"==f&&(sa=g[f]),"printErr"==f&&(t=g[f]);v=c.Me;xa();ua=c.Ne;Ea();Fa()}else if("run"===d){Ga(c.Xc);Ha(c.Xc,0,0,1,0,0);Ia();Ja(c.Xc);Da||(Ka(),Da=!0);try{La(c.ze,c.kd)}catch(e){if("unwind"!=
|
| 9 |
+
e)throw e;}}else"setimmediate"!==c.target&&("checkMailbox"===d?Da&&Ma():d&&(t(`worker: received unknown command ${d}`),t(c)))}catch(e){throw Na(),e;}}self.onmessage=a}var w,x,Oa,Pa,B,C,Qa,D,E,Ra,Sa=!1;function xa(){var a=v.buffer;g.HEAP8=w=new Int8Array(a);Oa=new Int16Array(a);g.HEAPU8=x=new Uint8Array(a);Pa=new Uint16Array(a);g.HEAP32=B=new Int32Array(a);g.HEAPU32=C=new Uint32Array(a);Qa=new Float32Array(a);D=new Float64Array(a);E=new BigInt64Array(a);Ra=new BigUint64Array(a)}
|
| 10 |
+
function Ta(){Sa=!0;n?Ca():F.hc()}function G(a){a="Aborted("+a+")";t(a);va=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");za?.(a);throw a;}var Ua;async function Va(a){if(!ta)try{var b=await la(a);return new Uint8Array(b)}catch{}if(a==Ua&&ta)a=new Uint8Array(ta);else if(ma)a=ma(a);else throw"both async and sync fetching of the wasm failed";return a}
|
| 11 |
+
async function Wa(a,b){try{var c=await Va(a);return await WebAssembly.instantiate(c,b)}catch(d){t(`failed to asynchronously prepare wasm: ${d}`),G(d)}}async function Xa(a){var b=Ua;if(!ta&&!na(b)&&!m)try{var c=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(c,a)}catch(d){t(`wasm streaming compile failed: ${d}`),t("falling back to ArrayBuffer instantiation")}return Wa(b,a)}
|
| 12 |
+
function Ya(){Za={qa:$a,f:ab,K:bb,k:cb,p:db,l:eb,fa:fb,b:gb,da:hb,gc:ib,q:jb,ea:kb,Ua:lb,cc:mb,ec:nb,Va:ob,Sa:pb,La:qb,Ra:rb,oa:sb,dc:tb,ac:ub,Ta:vb,bc:wb,_a:xb,Ba:yb,Xb:zb,Vb:Ab,Aa:Bb,O:Cb,J:Eb,Wb:Fb,ka:Gb,Yb:Hb,Oa:Ib,_b:Jb,Ea:Kb,Tb:Lb,Ca:Mb,Na:Ja,Xa:Nb,U:Ob,n:Pb,c:Qb,qb:Rb,w:Sb,N:Tb,A:Ub,j:Vb,o:Wb,rb:Xb,H:Yb,T:Zb,g:$b,u:ac,m:bc,i:cc,Ia:dc,Ja:ec,Ka:fc,Ga:gc,Ha:hc,Ub:ic,ab:jc,Za:kc,Z:lc,pb:mc,Da:nc,Ya:oc,X:pc,Wa:qc,$b:rc,G:sc,db:tc,_:uc,pa:vc,Zb:wc,cb:xc,bb:yc,lb:zc,z:Ac,sa:Bc,ra:Cc,nb:Dc,Y:Ec,v:Fc,
|
| 13 |
+
kb:Gc,jb:Hc,ib:Ic,mb:Jc,gb:Kc,fb:Lc,eb:Mc,Pa:Nc,Qa:Oc,fc:Pc,W:Qc,Fa:Rc,ma:Sc,Ma:Tc,la:Uc,Fb:Vc,va:Wc,Gb:Xc,wa:Yc,E:Zc,e:$c,r:ad,x:bd,C:cd,Ib:dd,ca:ed,D:fd,xa:gd,aa:hd,ha:jd,Jb:kd,Kb:ld,za:md,Lb:nd,ya:od,Mb:pd,ua:qd,ba:rd,d:sd,B:td,s:ud,Eb:vd,t:wd,y:xd,F:yd,I:zd,L:Ad,Nb:Bd,R:Cd,ia:Dd,$:Ed,Pb:Fd,Rb:Gd,Ob:Hd,h:Id,a:v,$a:Jd,Hb:Kd,V:Ld,M:Md,na:Nd,Db:Od,ja:Pd,S:Qd,Ab:Rd,Bb:Sd,vb:Td,wb:Ud,P:Vd,xb:Wd,yb:Xd,ta:Yd,Sb:Zd,ob:$d,Q:ae,hb:be,Cb:ce,sb:de,tb:ee,ub:fe,ga:ge,zb:he,Qb:ie};return{a:Za}}
|
| 14 |
+
async function Ea(){function a(d,e){var f=F=d.exports;d={};for(let [k,h]of Object.entries(f))"function"==typeof h?(f=je(h),d[k]=f):d[k]=h;F=d;F=ke();le.push(F.sd);d=F;me=d.ic;Ka=d.jc;g._OrtInit=d.kc;g._OrtGetLastError=d.lc;g._OrtCreateSessionOptions=d.mc;g._OrtAppendExecutionProvider=d.nc;g._OrtAddFreeDimensionOverride=d.oc;g._OrtAddSessionConfigEntry=d.pc;g._OrtReleaseSessionOptions=d.qc;g._OrtCreateSession=d.rc;g._OrtReleaseSession=d.sc;g._OrtGetInputOutputCount=d.tc;g._OrtGetInputOutputMetadata=
|
| 15 |
+
d.uc;g._OrtFree=d.vc;g._OrtCreateTensor=d.wc;g._OrtGetTensorData=d.xc;g._OrtReleaseTensor=d.yc;g._OrtCreateRunOptions=d.zc;g._OrtAddRunConfigEntry=d.Ac;g._OrtReleaseRunOptions=d.Bc;g._OrtCreateBinding=d.Cc;g._OrtBindInput=d.Dc;g._OrtBindOutput=d.Ec;g._OrtClearBoundOutputs=d.Fc;g._OrtReleaseBinding=d.Gc;g._OrtRunWithBinding=d.Hc;g._OrtRun=d.Ic;g._OrtEndProfiling=d.Jc;ne=g._OrtCreateWebGpuInstance=d.Kc;g._wgpuCreateInstance=d.Lc;oe=g._OrtGetWebGpuDevice=d.Mc;pe=d.Nc;H=g._free=d.Oc;qe=g._malloc=d.Pc;
|
| 16 |
+
re=g._wgpuBufferRelease=d.Qc;se=d.Rc;te=d.Sc;ue=d.Tc;ve=d.Uc;we=d.Vc;xe=d.Yc;ye=d.Zc;ze=d.hd;Ae=d.id;Be=d.jd;Ce=d.ld;De=d.md;Ee=d.nd;Fe=d.od;Ge=d.pd;He=d.qd;Ie=d.rd;Ha=d.ud;Na=d.vd;Je=d.wd;Ke=d.xd;Le=d.yd;Me=d.zd;Ne=d.Ad;Oe=d.Bd;I=d.Cd;Pe=d.Dd;Qe=d.Ed;J=d.Fd;Re=d.Gd;K=d.Hd;Se=d.Id;Te=d.Jd;Ue=d.Kd;Ve=d.Ld;dynCall_vii=d.Md;We=d.Nd;dynCall_v=d.Od;Xe=d.Pd;Ye=d.Qd;Ze=d.Rd;dynCall_iii=d.Sd;$e=d.Td;af=d.Ud;bf=d.Vd;dynCall_vi=d.Wd;cf=d.Xd;df=d.Yd;ef=d.Zd;ff=d._d;gf=d.$d;hf=d.ae;jf=d.be;kf=d.ce;lf=d.de;mf=
|
| 17 |
+
d.fe;nf=d.ge;of=d.he;pf=d.ie;qf=d.je;rf=d.ke;sf=d.le;tf=d.me;uf=d.Ae;vf=d.Be;wf=d.Ce;xf=d.De;yf=d.Ee;zf=d.Fe;Af=d.Ge;Bf=d.He;Cf=d.Ie;Df=d.Je;Ef=d.Ke;Ff=d.nf;Gf=d.of;Hf=d.pf;If=d.qf;ua=e;return F}var b=Ya();if(g.instantiateWasm)return new Promise(d=>{g.instantiateWasm(b,(e,f)=>{d(a(e,f))})});if(n){var c=new WebAssembly.Instance(ua,Ya());return a(c,ua)}Ua??=g.locateFile?g.locateFile?g.locateFile("ort-wasm-simd-threaded.asyncify.wasm",ka):ka+"ort-wasm-simd-threaded.asyncify.wasm":(new URL("ort-wasm-simd-threaded.asyncify.wasm",
|
| 18 |
+
import.meta.url)).href;return function(d){return a(d.instance,d.module)}(await Xa(b))}class Jf{name="ExitStatus";constructor(a){this.message=`Program terminated with exit(${a})`;this.status=a}}
|
| 19 |
+
var Kf=a=>{a.terminate();a.onmessage=()=>{}},Lf=[],Mf=0,Nf=null,Tf=a=>{0==Of.length&&(Pf(),Qf(Of[0]));var b=Of.pop();if(!b)return 6;Rf.push(b);Sf[a.Xc]=b;b.Xc=a.Xc;var c={$c:"run",ze:a.ye,kd:a.kd,Xc:a.Xc};m&&b.unref();b.postMessage(c,a.oe);return 0},L=0,M=(a,b,...c)=>{var d=16*c.length,e=K(),f=Re(d),k=f>>>3,h;for(h of c)"bigint"==typeof h?((u(),E)[k++>>>0]=1n,(u(),E)[k++>>>0]=h):((u(),E)[k++>>>0]=0n,(u(),D)[k++>>>0]=h);a=Je(a,0,d,f,b);J(e);return a};
|
| 20 |
+
function Jd(a){if(n)return M(0,1,a);wa=a;if(!(0<L)){for(var b of Rf)Kf(b);for(b of Of)Kf(b);Of=[];Rf=[];Sf={};va=!0}ha(a,new Jf(a))}function Uf(a){if(n)return M(1,0,a);Pc(a)}var Pc=a=>{wa=a;if(n)throw Uf(a),"unwind";Jd(a)},Of=[],Rf=[],le=[],Sf={};function Vf(){for(var a=g.numThreads-1;a--;)Pf();Lf.push(async()=>{var b=Wf();Mf++;await b;Mf--;0==Mf&&Nf&&(b=Nf,Nf=null,b())})}var Xf=a=>{var b=a.Xc;delete Sf[b];Of.push(a);Rf.splice(Rf.indexOf(a),1);a.Xc=0;Ke(b)};function Ia(){le.forEach(a=>a())}
|
| 21 |
+
var Qf=a=>new Promise(b=>{a.onmessage=f=>{var k=f.data;f=k.$c;if(k.gd&&k.gd!=pe()){var h=Sf[k.gd];h?h.postMessage(k,k.oe):t(`Internal error! Worker sent a message "${f}" to target pthread ${k.gd}, but that thread no longer exists!`)}else if("checkMailbox"===f)Ma();else if("spawnThread"===f)Tf(k);else if("cleanupThread"===f)N(()=>{Xf(Sf[k.Le])});else if("loaded"===f)a.loaded=!0,m&&!a.Xc&&a.unref(),b(a);else if("setimmediate"===k.target)a.postMessage(k);else if("uncaughtException"===f)a.onerror(k.error);
|
| 22 |
+
else if("callHandler"===f)g[k.te](...k.args);else f&&t(`worker sent an unknown command ${f}`)};a.onerror=f=>{t(`${"worker sent an error!"} ${f.filename}:${f.lineno}: ${f.message}`);throw f;};m&&(a.on("message",f=>a.onmessage({data:f})),a.on("error",f=>a.onerror(f)));var c=[],d=[],e;for(e of d)g.propertyIsEnumerable(e)&&c.push(e);a.postMessage({$c:"load",ue:c,Me:v,Ne:ua})});async function Wf(){if(!n)return Promise.all(Of.map(Qf))}
|
| 23 |
+
function Pf(){var a=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});Of.push(a)}function Ga(a){var b=(u(),C)[a+52>>>2>>>0];a=(u(),C)[a+56>>>2>>>0];Qe(b,b-a);J(b)}var La=(a,b)=>{L=0;a=We(a,b);0<L?wa=a:Le(a)},v,Yf=[],Zf=0,O=a=>-9007199254740992>a||9007199254740992<a?NaN:Number(a);function ab(a){a>>>=0;var b=new $f(a);0==(u(),w)[b.ad+12>>>0]&&(ag(b,!0),Zf--);bg(b,!1);Yf.push(b);return Ve(a)}
|
| 24 |
+
var cg=0,bb=()=>{I(0,0);var a=Yf.pop();Se(a.td);cg=0};function ag(a,b){b=b?1:0;(u(),w)[a.ad+12>>>0]=b}function bg(a,b){b=b?1:0;(u(),w)[a.ad+13>>>0]=b}class $f{constructor(a){this.td=a;this.ad=a-24}}var dg=a=>{var b=cg;if(!b)return Pe(0),0;var c=new $f(b);(u(),C)[c.ad+16>>>2>>>0]=b;var d=(u(),C)[c.ad+4>>>2>>>0];if(!d)return Pe(0),b;for(var e of a){if(0===e||e===d)break;if(Ue(e,d,c.ad+16))return Pe(e),b}Pe(d);return b};function cb(){return dg([])}function db(a){return dg([a>>>0])}
|
| 25 |
+
function eb(a,b,c,d){return dg([a>>>0,b>>>0,c>>>0,d>>>0])}var fb=()=>{var a=Yf.pop();a||G("no exception to throw");var b=a.td;0==(u(),w)[a.ad+13>>>0]&&(Yf.push(a),bg(a,!0),ag(a,!1),Zf++);Te(b);cg=b;throw cg;};function gb(a,b,c){a>>>=0;var d=new $f(a);b>>>=0;c>>>=0;(u(),C)[d.ad+16>>>2>>>0]=0;(u(),C)[d.ad+4>>>2>>>0]=b;(u(),C)[d.ad+8>>>2>>>0]=c;Te(a);cg=a;Zf++;throw cg;}var hb=()=>Zf;function eg(a,b,c,d){return n?M(2,1,a,b,c,d):ib(a,b,c,d)}
|
| 26 |
+
function ib(a,b,c,d){a>>>=0;b>>>=0;c>>>=0;d>>>=0;if(!globalThis.SharedArrayBuffer)return 6;var e=[];if(n&&0===e.length)return eg(a,b,c,d);a={ye:c,Xc:a,kd:d,oe:e};return n?(a.$c="spawnThread",postMessage(a,e),0):Tf(a)}function jb(a){cg||=a>>>0;throw cg;}
|
| 27 |
+
var fg=globalThis.TextDecoder&&new TextDecoder,gg=(a,b,c,d)=>{c=b+c;if(d)return c;for(;a[b]&&!(b>=c);)++b;return b},hg=(a,b=0,c,d)=>{b>>>=0;c=gg(a,b,c,d);if(16<c-b&&a.buffer&&fg)return fg.decode(a.buffer instanceof ArrayBuffer?a.subarray(b,c):a.slice(b,c));for(d="";b<c;){var e=a[b++];if(e&128){var f=a[b++]&63;if(192==(e&224))d+=String.fromCharCode((e&31)<<6|f);else{var k=a[b++]&63;e=224==(e&240)?(e&15)<<12|f<<6|k:(e&7)<<18|f<<12|k<<6|a[b++]&63;65536>e?d+=String.fromCharCode(e):(e-=65536,d+=String.fromCharCode(55296|
|
| 28 |
+
e>>10,56320|e&1023))}}else d+=String.fromCharCode(e)}return d},ig=(a,b,c)=>(a>>>=0)?hg((u(),x),a,b,c):"";function kb(a,b,c){return n?M(3,1,a,b,c):0}function lb(a,b){if(n)return M(4,1,a,b)}function mb(a,b){if(n)return M(5,1,a,b)}function nb(a,b,c){if(n)return M(6,1,a,b,c)}function ob(a,b,c){return n?M(7,1,a,b,c):0}function pb(a,b){if(n)return M(8,1,a,b)}function qb(a,b,c){if(n)return M(9,1,a,b,c)}function rb(a,b,c,d){if(n)return M(10,1,a,b,c,d)}function sb(a,b,c,d){if(n)return M(11,1,a,b,c,d)}
|
| 29 |
+
function tb(a,b,c,d){if(n)return M(12,1,a,b,c,d)}function ub(a){if(n)return M(13,1,a)}function vb(a,b){if(n)return M(14,1,a,b)}function wb(a,b,c){if(n)return M(15,1,a,b,c)}var xb=()=>G(""),P=a=>{a>>>=0;for(var b="";;){var c=(u(),x)[a++>>>0];if(!c)return b;b+=String.fromCharCode(c)}},jg={},kg={},lg={},mg=class extends Error{constructor(a){super(a);this.name="BindingError"}};
|
| 30 |
+
function ng(a,b,c={}){var d=b.name;if(!a)throw new mg(`type "${d}" must have a positive integer typeid pointer`);if(kg.hasOwnProperty(a)){if(c.ve)return;throw new mg(`Cannot register type '${d}' twice`);}kg[a]=b;delete lg[a];jg.hasOwnProperty(a)&&(b=jg[a],delete jg[a],b.forEach(e=>e()))}function Q(a,b,c={}){return ng(a,b,c)}
|
| 31 |
+
var og=(a,b,c)=>{switch(b){case 1:return c?d=>(u(),w)[d>>>0]:d=>(u(),x)[d>>>0];case 2:return c?d=>(u(),Oa)[d>>>1>>>0]:d=>(u(),Pa)[d>>>1>>>0];case 4:return c?d=>(u(),B)[d>>>2>>>0]:d=>(u(),C)[d>>>2>>>0];case 8:return c?d=>(u(),E)[d>>>3>>>0]:d=>(u(),Ra)[d>>>3>>>0];default:throw new TypeError(`invalid integer width (${b}): ${a}`);}};
|
| 32 |
+
function yb(a,b,c,d,e){a>>>=0;c>>>=0;b=P(b>>>0);d=0n===d;let f=k=>k;if(d){const k=8*c;f=h=>BigInt.asUintN(k,h);e=f(e)}Q(a,{name:b,Wc:f,cd:(k,h)=>{"number"==typeof h&&(h=BigInt(h));return h},bd:og(b,c,!d),dd:null})}function zb(a,b,c,d){a>>>=0;b=P(b>>>0);Q(a,{name:b,Wc:function(e){return!!e},cd:function(e,f){return f?c:d},bd:function(e){return this.Wc((u(),x)[e>>>0])},dd:null})}var pg=[],qg=[0,1,,1,null,1,!0,1,!1,1];function Qb(a){a>>>=0;9<a&&0===--qg[a+1]&&(qg[a]=void 0,pg.push(a))}
|
| 33 |
+
var R=a=>{if(!a)throw new mg(`Cannot use deleted val. handle = ${a}`);return qg[a]},S=a=>{switch(a){case void 0:return 2;case null:return 4;case !0:return 6;case !1:return 8;default:const b=pg.pop()||qg.length;qg[b]=a;qg[b+1]=1;return b}};function rg(a){return this.Wc((u(),C)[a>>>2>>>0])}var sg={name:"emscripten::val",Wc:a=>{var b=R(a);Qb(a);return b},cd:(a,b)=>S(b),bd:rg,dd:null};function Ab(a){return Q(a>>>0,sg)}
|
| 34 |
+
var tg=(a,b)=>{switch(b){case 4:return function(c){return this.Wc((u(),Qa)[c>>>2>>>0])};case 8:return function(c){return this.Wc((u(),D)[c>>>3>>>0])};default:throw new TypeError(`invalid float width (${b}): ${a}`);}};function Bb(a,b,c){a>>>=0;c>>>=0;b=P(b>>>0);Q(a,{name:b,Wc:d=>d,cd:(d,e)=>e,bd:tg(b,c),dd:null})}function Cb(a,b,c,d,e){a>>>=0;c>>>=0;b=P(b>>>0);let f=h=>h;if(0===d){var k=32-8*c;f=h=>h<<k>>>k;e=f(e)}Q(a,{name:b,Wc:f,cd:(h,l)=>l,bd:og(b,c,0!==d),dd:null})}
|
| 35 |
+
function Eb(a,b,c){function d(f){var k=(u(),C)[f>>>2>>>0];f=(u(),C)[f+4>>>2>>>0];return new e((u(),w).buffer,f,k)}a>>>=0;var e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][b];c=P(c>>>0);Q(a,{name:c,Wc:d,bd:d},{ve:!0})}
|
| 36 |
+
var T=(a,b,c)=>{var d=(u(),x);b>>>=0;if(0<c){var e=b;c=b+c-1;for(var f=0;f<a.length;++f){var k=a.codePointAt(f);if(127>=k){if(b>=c)break;d[b++>>>0]=k}else if(2047>=k){if(b+1>=c)break;d[b++>>>0]=192|k>>6;d[b++>>>0]=128|k&63}else if(65535>=k){if(b+2>=c)break;d[b++>>>0]=224|k>>12;d[b++>>>0]=128|k>>6&63;d[b++>>>0]=128|k&63}else{if(b+3>=c)break;d[b++>>>0]=240|k>>18;d[b++>>>0]=128|k>>12&63;d[b++>>>0]=128|k>>6&63;d[b++>>>0]=128|k&63;f++}}d[b>>>0]=0;a=b-e}else a=0;return a},U=a=>{for(var b=0,c=0;c<a.length;++c){var d=
|
| 37 |
+
a.charCodeAt(c);127>=d?b++:2047>=d?b+=2:55296<=d&&57343>=d?(b+=4,++c):b+=3}return b};
|
| 38 |
+
function Fb(a,b){a>>>=0;b=P(b>>>0);Q(a,{name:b,Wc(c){var d=(u(),C)[c>>>2>>>0];d=ig(c+4,d,!0);H(c);return d},cd(c,d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));var e="string"==typeof d;if(!(e||ArrayBuffer.isView(d)&&1==d.BYTES_PER_ELEMENT))throw new mg("Cannot pass non-string to std::string");var f=e?U(d):d.length;var k=qe(4+f+1),h=k+4;(u(),C)[k>>>2>>>0]=f;e?T(d,h,f+1):(u(),x).set(d,h>>>0);null!==c&&c.push(H,k);return k},bd:rg,dd(c){H(c)}})}
|
| 39 |
+
var ug=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,vg=(a,b,c)=>{a>>>=1;b=gg((u(),Pa),a,b/2,c);if(16<b-a&&ug)return ug.decode((u(),Pa).slice(a,b));for(c="";a<b;++a){var d=(u(),Pa)[a>>>0];c+=String.fromCharCode(d)}return c},wg=(a,b,c)=>{c??=2147483647;if(2>c)return 0;c-=2;var d=b;c=c<2*a.length?c/2:a.length;for(var e=0;e<c;++e){var f=a.charCodeAt(e);(u(),Oa)[b>>>1>>>0]=f;b+=2}(u(),Oa)[b>>>1>>>0]=0;return b-d},xg=a=>2*a.length,yg=(a,b,c)=>{var d="";a>>>=2;for(var e=0;!(e>=b/4);e++){var f=
|
| 40 |
+
(u(),C)[a+e>>>0];if(!f&&!c)break;d+=String.fromCodePoint(f)}return d},zg=(a,b,c)=>{b>>>=0;c??=2147483647;if(4>c)return 0;var d=b;c=d+c-4;for(var e=0;e<a.length;++e){var f=a.codePointAt(e);65535<f&&e++;(u(),B)[b>>>2>>>0]=f;b+=4;if(b+4>c)break}(u(),B)[b>>>2>>>0]=0;return b-d},Ag=a=>{for(var b=0,c=0;c<a.length;++c)65535<a.codePointAt(c)&&c++,b+=4;return b};
|
| 41 |
+
function Gb(a,b,c){a>>>=0;b>>>=0;c>>>=0;c=P(c);if(2===b){var d=vg;var e=wg;var f=xg}else d=yg,e=zg,f=Ag;Q(a,{name:c,Wc:k=>{var h=(u(),C)[k>>>2>>>0];h=d(k+4,h*b,!0);H(k);return h},cd:(k,h)=>{if("string"!=typeof h)throw new mg(`Cannot pass non-string to C++ string type ${c}`);var l=f(h),p=qe(4+l+b);(u(),C)[p>>>2>>>0]=l/b;e(h,p+4,l+b);null!==k&&k.push(H,p);return p},bd:rg,dd(k){H(k)}})}function Hb(a,b){a>>>=0;b=P(b>>>0);Q(a,{we:!0,name:b,Wc:()=>{},cd:()=>{}})}
|
| 42 |
+
function Ib(a){Ha(a>>>0,!ba,1,!aa,131072,!1);Ia()}var N=a=>{if(!va)try{if(a(),!(0<L))try{n?pe()&&Le(wa):Pc(wa)}catch(b){b instanceof Jf||"unwind"==b||ha(1,b)}}catch(b){b instanceof Jf||"unwind"==b||ha(1,b)}},Bg=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ja(a){a>>>=0;Bg||(Atomics.waitAsync((u(),B),a>>>2,a).value.then(Ma),a+=128,Atomics.store((u(),B),a>>>2,1))}var Ma=()=>N(()=>{var a=pe();a&&(Ja(a),Ne())});
|
| 43 |
+
function Jb(a,b){a>>>=0;a==b>>>0?setTimeout(Ma):n?postMessage({gd:a,$c:"checkMailbox"}):(a=Sf[a])&&a.postMessage({$c:"checkMailbox"})}var Cg=[];function Kb(a,b,c,d,e){b>>>=0;e>>>=0;Cg.length=0;c=e>>>3;for(d=e+d>>>3;c<d;){var f;(u(),E)[c++>>>0]?f=(u(),E)[c++>>>0]:f=(u(),D)[c++>>>0];Cg.push(f)}return(b?Dg[b]:Eg[a])(...Cg)}var Lb=()=>{L=0};function Mb(a){a>>>=0;n?postMessage({$c:"cleanupThread",Le:a}):Xf(Sf[a])}function Nb(a){m&&Sf[a>>>0].ref()}var Fg=a=>{try{a()}catch(b){G(b)}};
|
| 44 |
+
function je(a){var b=(...c)=>{Gg.push(a);try{return a(...c)}finally{va||(Gg.pop(),r&&1===Hg&&0===Gg.length&&(Hg=0,L+=1,Fg(Gf),"undefined"!=typeof Fibers&&Fibers.We()))}};Ig.set(a,b);return b}var Hg=0,r=null,Jg=0,Gg=[],Kg=new Map,Lg=new Map,Ig=new Map,Mg=0,Ng=null,Og=[];function da(){return new Promise((a,b)=>{Ng={resolve:a,reject:b}})}
|
| 45 |
+
function Pg(){var a=qe(65548),b=a+12;(u(),C)[a>>>2>>>0]=b;(u(),C)[a+4>>>2>>>0]=b+65536;b=Gg[0];if(!Kg.has(b)){var c=Mg++;Kg.set(b,c);Lg.set(c,b)}b=Kg.get(b);(u(),B)[a+8>>>2>>>0]=b;return a}function Qg(){var a=(u(),B)[r+8>>>2>>>0];a=Lg.get(a);a=Ig.get(a);--L;return a()}
|
| 46 |
+
function Rg(a){if(!va){if(0===Hg){var b=!1,c=!1;a((d=0)=>{if(!va&&(Jg=d,b=!0,c)){Hg=2;Fg(()=>Hf(r));"undefined"!=typeof MainLoop&&MainLoop.se&&MainLoop.resume();d=!1;try{var e=Qg()}catch(h){e=h,d=!0}var f=!1;if(!r){var k=Ng;k&&(Ng=null,(d?k.reject:k.resolve)(e),f=!0)}if(d&&!f)throw e;}});c=!0;b||(Hg=1,r=Pg(),"undefined"!=typeof MainLoop&&MainLoop.se&&MainLoop.pause(),Fg(()=>Ff(r)))}else 2===Hg?(Hg=0,Fg(If),H(r),r=null,Og.forEach(N)):G(`invalid state: ${Hg}`);return Jg}}var Sg=a=>Rg(b=>{a().then(b)});
|
| 47 |
+
function Ob(a){a>>>=0;return Sg(async()=>{var b=await R(a);return S(b)})}var Tg=[],Ug=a=>{var b=Tg.length;Tg.push(a);return b},Vg=(a,b)=>{for(var c=Array(a),d=0;d<a;++d){var e=d,f=(u(),C)[b+4*d>>>2>>>0],k=kg[f];if(void 0===k)throw a=`parameter ${d}`,f=me(f),b=P(f),H(f),new mg(`${a} has unknown type ${b}`);c[e]=k}return c},Wg=(a,b,c)=>{var d=[];a=a(d,c);d.length&&((u(),C)[b>>>2>>>0]=S(d));return a},Xg={},Yg=a=>{var b=Xg[a];return void 0===b?P(a):b};
|
| 48 |
+
function Pb(a,b,c){var [d,...e]=Vg(a,b>>>0);b=d.cd.bind(d);var f=e.map(l=>l.bd.bind(l));a--;var k={toValue:R};a=f.map((l,p)=>{var q=`argFromPtr${p}`;k[q]=l;return`${q}(args${p?"+"+8*p:""})`});switch(c){case 0:var h="toValue(handle)";break;case 2:h="new (toValue(handle))";break;case 3:h="";break;case 1:k.getStringOrSymbol=Yg,h="toValue(handle)[getStringOrSymbol(methodName)]"}h+=`(${a})`;d.we||(k.toReturnWire=b,k.emval_returnValue=Wg,h=`return emval_returnValue(toReturnWire, destructorsRef, ${h})`);
|
| 49 |
+
h=`return function (handle, methodName, destructorsRef, args) {\n ${h}\n }`;c=(new Function(Object.keys(k),h))(...Object.values(k));h=`methodCaller<(${e.map(l=>l.name)}) => ${d.name}>`;return Ug(Object.defineProperty(c,"name",{value:h}))}function Rb(a,b){b>>>=0;a=R(a>>>0);b=R(b);return a==b}function Sb(a){a>>>=0;if(!a)return S(globalThis);a=Yg(a);return S(globalThis[a])}function Tb(a){a=Yg(a>>>0);return S(g[a])}function Ub(a,b){b>>>=0;a=R(a>>>0);b=R(b);return S(a[b])}
|
| 50 |
+
function Vb(a){a>>>=0;9<a&&(qg[a+1]+=1)}function Wb(a,b,c,d,e){return Tg[a>>>0](b>>>0,c>>>0,d>>>0,e>>>0)}function Xb(a,b,c,d,e){return Wb(a>>>0,b>>>0,c>>>0,d>>>0,e>>>0)}function Yb(){return S([])}function Zb(a){a=R(a>>>0);for(var b=Array(a.length),c=0;c<a.length;c++)b[c]=a[c];return S(b)}function $b(a){return S(Yg(a>>>0))}function ac(){return S({})}function bc(a){a>>>=0;for(var b=R(a);b.length;){var c=b.pop();b.pop()(c)}Qb(a)}function cc(a,b,c){b>>>=0;c>>>=0;a=R(a>>>0);b=R(b);c=R(c);a[b]=c}
|
| 51 |
+
function dc(a,b){a=O(a);b>>>=0;a=new Date(1E3*a);(u(),B)[b>>>2>>>0]=a.getUTCSeconds();(u(),B)[b+4>>>2>>>0]=a.getUTCMinutes();(u(),B)[b+8>>>2>>>0]=a.getUTCHours();(u(),B)[b+12>>>2>>>0]=a.getUTCDate();(u(),B)[b+16>>>2>>>0]=a.getUTCMonth();(u(),B)[b+20>>>2>>>0]=a.getUTCFullYear()-1900;(u(),B)[b+24>>>2>>>0]=a.getUTCDay();a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0;(u(),B)[b+28>>>2>>>0]=a}
|
| 52 |
+
var Zg=a=>0===a%4&&(0!==a%100||0===a%400),$g=[0,31,60,91,121,152,182,213,244,274,305,335],ah=[0,31,59,90,120,151,181,212,243,273,304,334];
|
| 53 |
+
function ec(a,b){a=O(a);b>>>=0;a=new Date(1E3*a);(u(),B)[b>>>2>>>0]=a.getSeconds();(u(),B)[b+4>>>2>>>0]=a.getMinutes();(u(),B)[b+8>>>2>>>0]=a.getHours();(u(),B)[b+12>>>2>>>0]=a.getDate();(u(),B)[b+16>>>2>>>0]=a.getMonth();(u(),B)[b+20>>>2>>>0]=a.getFullYear()-1900;(u(),B)[b+24>>>2>>>0]=a.getDay();var c=(Zg(a.getFullYear())?$g:ah)[a.getMonth()]+a.getDate()-1|0;(u(),B)[b+28>>>2>>>0]=c;(u(),B)[b+36>>>2>>>0]=-(60*a.getTimezoneOffset());c=(new Date(a.getFullYear(),6,1)).getTimezoneOffset();var d=(new Date(a.getFullYear(),
|
| 54 |
+
0,1)).getTimezoneOffset();a=(c!=d&&a.getTimezoneOffset()==Math.min(d,c))|0;(u(),B)[b+32>>>2>>>0]=a}
|
| 55 |
+
function fc(a){a>>>=0;var b=new Date((u(),B)[a+20>>>2>>>0]+1900,(u(),B)[a+16>>>2>>>0],(u(),B)[a+12>>>2>>>0],(u(),B)[a+8>>>2>>>0],(u(),B)[a+4>>>2>>>0],(u(),B)[a>>>2>>>0],0),c=(u(),B)[a+32>>>2>>>0],d=b.getTimezoneOffset(),e=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),f=(new Date(b.getFullYear(),0,1)).getTimezoneOffset(),k=Math.min(f,e);0>c?(u(),B)[a+32>>>2>>>0]=Number(e!=f&&k==d):0<c!=(k==d)&&(e=Math.max(f,e),b.setTime(b.getTime()+6E4*((0<c?k:e)-d)));(u(),B)[a+24>>>2>>>0]=b.getDay();c=(Zg(b.getFullYear())?
|
| 56 |
+
$g:ah)[b.getMonth()]+b.getDate()-1|0;(u(),B)[a+28>>>2>>>0]=c;(u(),B)[a>>>2>>>0]=b.getSeconds();(u(),B)[a+4>>>2>>>0]=b.getMinutes();(u(),B)[a+8>>>2>>>0]=b.getHours();(u(),B)[a+12>>>2>>>0]=b.getDate();(u(),B)[a+16>>>2>>>0]=b.getMonth();(u(),B)[a+20>>>2>>>0]=b.getYear();a=b.getTime();return BigInt(isNaN(a)?-1:a/1E3)}function gc(a,b,c,d,e,f,k){return n?M(16,1,a,b,c,d,e,f,k):-52}function hc(a,b,c,d,e,f){if(n)return M(17,1,a,b,c,d,e,f)}var bh={},sc=()=>performance.timeOrigin+performance.now();
|
| 57 |
+
function ic(a,b){if(n)return M(18,1,a,b);bh[a]&&(clearTimeout(bh[a].id),delete bh[a]);if(!b)return 0;var c=setTimeout(()=>{delete bh[a];N(()=>Me(a,performance.timeOrigin+performance.now()))},b);bh[a]={id:c,Ve:b};return 0}
|
| 58 |
+
function jc(a,b,c,d){a>>>=0;b>>>=0;c>>>=0;d>>>=0;var e=(new Date).getFullYear(),f=(new Date(e,0,1)).getTimezoneOffset();e=(new Date(e,6,1)).getTimezoneOffset();var k=Math.max(f,e);(u(),C)[a>>>2>>>0]=60*k;(u(),B)[b>>>2>>>0]=Number(f!=e);b=h=>{var l=Math.abs(h);return`UTC${0<=h?"-":"+"}${String(Math.floor(l/60)).padStart(2,"0")}${String(l%60).padStart(2,"0")}`};a=b(f);b=b(e);e<f?(T(a,c,17),T(b,d,17)):(T(a,d,17),T(b,c,17))}var oc=()=>Date.now(),ch=1;
|
| 59 |
+
function kc(a,b,c){c>>>=0;if(!(0<=a&&3>=a))return 28;if(0===a)a=Date.now();else if(ch)a=performance.timeOrigin+performance.now();else return 52;a=Math.round(1E6*a);(u(),E)[c>>>3>>>0]=BigInt(a);return 0}var dh=[],eh=(a,b)=>{dh.length=0;for(var c;c=(u(),x)[a++>>>0];){var d=105!=c;d&=112!=c;b+=d&&b%8?4:0;dh.push(112==c?(u(),C)[b>>>2>>>0]:106==c?(u(),E)[b>>>3>>>0]:105==c?(u(),B)[b>>>2>>>0]:(u(),D)[b>>>3>>>0]);b+=d?8:4}return dh};function lc(a,b,c){a>>>=0;b=eh(b>>>0,c>>>0);return Dg[a](...b)}
|
| 60 |
+
function mc(a,b,c){a>>>=0;b=eh(b>>>0,c>>>0);return Dg[a](...b)}var nc=()=>{};function pc(a,b){return t(ig(a>>>0,b>>>0))}var qc=()=>{L+=1;throw"unwind";};function rc(){return 4294901760}var tc=()=>1,uc=()=>m?require("os").cpus().length:navigator.hardwareConcurrency,fh={},gh=a=>{var b=U(a)+1,c=qe(b);c&&T(a,c,b);return c},hh=a=>{var b;return(b=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(a))?+b[1]:(b=/:(\d+):\d+(?:\)|$)/.exec(a))?2147483648|+b[1]:0},ih=a=>{for(var b of a)(a=hh(b))&&(fh[a]=b)};
|
| 61 |
+
function xc(){var a=Error().stack.toString().split("\n");"Error"==a[0]&&a.shift();ih(a);fh.ee=hh(a[3]);fh.xe=a;return fh.ee}function vc(a){a=fh[a>>>0];if(!a)return 0;var b;if(b=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(a))a=b[1];else if(b=/^\s+at (.*) \(.*\)$/.exec(a))a=b[1];else if(b=/^(.+?)@/.exec(a))a=b[1];else return 0;H(vc.ne??0);vc.ne=gh(a);return vc.ne}
|
| 62 |
+
function wc(a){a>>>=0;var b=(u(),x).length;if(a<=b||4294901760<a)return!1;for(var c=1;4>=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);a:{d=(Math.min(4294901760,65536*Math.ceil(Math.max(a,d)/65536))-v.buffer.byteLength+65535)/65536|0;try{v.grow(d);xa();var e=1;break a}catch(f){}e=void 0}if(e)return!0}return!1}
|
| 63 |
+
function yc(a,b,c){a>>>=0;b>>>=0;if(fh.ee==a)var d=fh.xe;else d=Error().stack.toString().split("\n"),"Error"==d[0]&&d.shift(),ih(d);for(var e=3;d[e]&&hh(d[e])!=a;)++e;for(a=0;a<c&&d[a+e];++a)(u(),B)[b+4*a>>>2>>>0]=hh(d[a+e]);return a}
|
| 64 |
+
var V=a=>{var b=U(a)+1,c=Re(b);T(a,c,b);return c},jh=a=>(u(),C)[a>>>2>>>0]+4294967296*(u(),B)[a+4>>>2>>>0],W=[],kh=(a,b)=>{W[a>>>0]=b},X=[],lh=[],mh=(a,b)=>{lh[a]=new Promise(c=>b.finally(()=>c(a)))},Y=a=>{if(a)return W[a>>>0]},nh=(a,b=0)=>{"unmapped"===a.mapState||G();b=ze(b);W[b>>>0]=a;return b},oh=(a,b=0)=>{var c=Be(b);b=Ae(b,c);W[c>>>0]=a.queue;W[b>>>0]=a;return b},ph=(a,b)=>{for(a=(u(),C)[a>>>2>>>0];a;a=(u(),C)[a>>>2>>>0]){var c=(u(),B)[a+4>>>2>>>0];b[c](a)}},qh=(a,b,c)=>{(u(),C)[a>>>2>>>0]=
|
| 65 |
+
b;(u(),C)[a+4>>>2>>>0]=c},rh=a=>{var b=(u(),C)[a>>>2>>>0];a=(u(),C)[a+4>>>2>>>0];return ig(b,a)},Z=a=>{var b=(u(),C)[a>>>2>>>0];a=(u(),C)[a+4>>>2>>>0];if(b)return ig(b,a);if(0===a)return""},sh=a=>{var b=Z(a+4);var c=(c=(u(),C)[a+12>>>2>>>0])?Y(c):"auto";if(a+=16){var d=Y((u(),C)[a+4>>>2>>>0]);var e=(u(),C)[a+16>>>2>>>0];var f=(u(),C)[a+20>>>2>>>0];if(e){for(var k={},h=0;h<e;++h){var l=f+24*h,p=rh(l+4);k[p]=(u(),D)[l+16>>>3>>>0]}e=k}else e=void 0;a={module:d,constants:e,entryPoint:Z(a+8)}}else a=void 0;
|
| 66 |
+
return{label:b,layout:c,compute:a}},th=(a,b)=>{function c(f,k,h,l=0){f=a[f]??l;(u(),C)[k+h>>>2>>>0]=f}function d(f,k,h,l=0){k+=h;f=a[f]??l;(u(),C)[k>>>2>>>0]=f;l=(u(),C)[k>>>2>>>0];(u(),C)[k+4>>>2>>>0]=(f-l)/4294967296}var e=(u(),C)[b>>>2>>>0];c("maxTextureDimension1D",b,4);c("maxTextureDimension2D",b,8);c("maxTextureDimension3D",b,12);c("maxTextureArrayLayers",b,16);c("maxBindGroups",b,20);c("maxBindGroupsPlusVertexBuffers",b,24);c("maxBindingsPerBindGroup",b,28);c("maxDynamicUniformBuffersPerPipelineLayout",
|
| 67 |
+
b,32);c("maxDynamicStorageBuffersPerPipelineLayout",b,36);c("maxSampledTexturesPerShaderStage",b,40);c("maxSamplersPerShaderStage",b,44);c("maxStorageBuffersPerShaderStage",b,48);c("maxStorageTexturesPerShaderStage",b,52);c("maxUniformBuffersPerShaderStage",b,56);c("minUniformBufferOffsetAlignment",b,80);c("minStorageBufferOffsetAlignment",b,84);d("maxUniformBufferBindingSize",b,64);d("maxStorageBufferBindingSize",b,72);c("maxVertexBuffers",b,88);d("maxBufferSize",b,96);c("maxVertexAttributes",b,
|
| 68 |
+
104);c("maxVertexBufferArrayStride",b,108);c("maxInterStageShaderVariables",b,112);c("maxColorAttachments",b,116);c("maxColorAttachmentBytesPerSample",b,120);c("maxComputeWorkgroupStorageSize",b,124);c("maxComputeInvocationsPerWorkgroup",b,128);c("maxComputeWorkgroupSizeX",b,132);c("maxComputeWorkgroupSizeY",b,136);c("maxComputeWorkgroupSizeZ",b,140);c("maxComputeWorkgroupsPerDimension",b,144);c("maxImmediateSize",b,148);0!==e&&(u(),c("maxStorageBuffersInVertexStage",e,8,a.maxStorageBuffersPerShaderStage),
|
| 69 |
+
c("maxStorageBuffersInFragmentStage",e,16,a.maxStorageBuffersPerShaderStage),c("maxStorageTexturesInVertexStage",e,12,a.maxStorageTexturesPerShaderStage),c("maxStorageTexturesInFragmentStage",e,20,a.maxStorageTexturesPerShaderStage))},vh=(a,b)=>{(u(),C)[b+52>>>2>>>0]=a.subgroupMinSize;(u(),C)[b+56>>>2>>>0]=a.subgroupMaxSize;var c=gh(a.vendor+a.architecture+a.device+a.description),d=U(a.vendor);qh(b+4,c,d);c+=d;d=U(a.architecture);qh(b+12,c,d);c+=d;d=U(a.device);qh(b+20,c,d);c+=d;d=U(a.description);
|
| 70 |
+
qh(b+28,c,d);c+=d;(u(),B)[b+36>>>2>>>0]=2;c=a.isFallbackAdapter?3:4;(u(),B)[b+40>>>2>>>0]=c;(u(),C)[b+44>>>2>>>0]=0;(u(),C)[b+48>>>2>>>0]=0;ph(b,{327739:e=>{let f=0,k=0;if(a.subgroupMatrixConfigs){f=a.subgroupMatrixConfigs.length;k=qe(20*f);for(const [h,l]of a.subgroupMatrixConfigs.entries()){const p=k+20*h,q=uh.indexOf(l.componentType),y=uh.indexOf(l.resultComponentType);(u(),B)[p>>>2>>>0]=q;(u(),B)[p+4>>>2>>>0]=y;(u(),C)[p+8>>>2>>>0]=l.M;(u(),C)[p+12>>>2>>>0]=l.N;(u(),C)[p+16>>>2>>>0]=l.K}}(u(),
|
| 71 |
+
C)[e+12>>>2>>>0]=k;(u(),C)[e+8>>>2>>>0]=f}})},wh=[,,"uniform","storage","read-only-storage"],xh=[,"validation","out-of-memory","internal"],yh=[,"compatibility","core"],zh={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",
|
| 72 |
+
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",23:"subgroup-size-control",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect",327732:"chromium-experimental-subgroup-matrix"},Ah=[,"low-power","high-performance"],Bh=[,"occlusion","timestamp"],Ch=[,,"filtering",
|
| 73 |
+
"non-filtering","comparison"],Dh=[,,"write-only","read-only","read-write"],uh=[,"f32","f16","u32","i32","u8","i8"],Eh=[,"r8unorm","r8snorm","r8uint","r8sint","r16unorm","r16snorm","r16uint","r16sint","r16float","rg8unorm","rg8snorm","rg8uint","rg8sint","r32float","r32uint","r32sint","rg16unorm","rg16snorm","rg16uint","rg16sint","rg16float","rgba8unorm","rgba8unorm-srgb","rgba8snorm","rgba8uint","rgba8sint","bgra8unorm","bgra8unorm-srgb","rgb10a2uint","rgb10a2unorm","rg11b10ufloat","rgb9e5ufloat",
|
| 74 |
+
"rg32float","rg32uint","rg32sint","rgba16unorm","rgba16snorm","rgba16uint","rgba16sint","rgba16float","rgba32float","rgba32uint","rgba32sint","stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8","bc1-rgba-unorm","bc1-rgba-unorm-srgb","bc2-rgba-unorm","bc2-rgba-unorm-srgb","bc3-rgba-unorm","bc3-rgba-unorm-srgb","bc4-r-unorm","bc4-r-snorm","bc5-rg-unorm","bc5-rg-snorm","bc6h-rgb-ufloat","bc6h-rgb-float","bc7-rgba-unorm","bc7-rgba-unorm-srgb","etc2-rgb8unorm",
|
| 75 |
+
"etc2-rgb8unorm-srgb","etc2-rgb8a1unorm","etc2-rgb8a1unorm-srgb","etc2-rgba8unorm","etc2-rgba8unorm-srgb","eac-r11unorm","eac-r11snorm","eac-rg11unorm","eac-rg11snorm","astc-4x4-unorm","astc-4x4-unorm-srgb","astc-5x4-unorm","astc-5x4-unorm-srgb","astc-5x5-unorm","astc-5x5-unorm-srgb","astc-6x5-unorm","astc-6x5-unorm-srgb","astc-6x6-unorm","astc-6x6-unorm-srgb","astc-8x5-unorm","astc-8x5-unorm-srgb","astc-8x6-unorm","astc-8x6-unorm-srgb","astc-8x8-unorm","astc-8x8-unorm-srgb","astc-10x5-unorm","astc-10x5-unorm-srgb",
|
| 76 |
+
"astc-10x6-unorm","astc-10x6-unorm-srgb","astc-10x8-unorm","astc-10x8-unorm-srgb","astc-10x10-unorm","astc-10x10-unorm-srgb","astc-12x10-unorm","astc-12x10-unorm-srgb","astc-12x12-unorm","astc-12x12-unorm-srgb"],Fh=[,,"float","unfilterable-float","depth","sint","uint"],Gh=[,"1d","2d","2d-array","cube","cube-array","3d"],Hh={undefined:1,unknown:1,destroyed:2};
|
| 77 |
+
function zc(a,b,c,d,e,f){b=O(b);c=O(c);d>>>=0;e>>>=0;f>>>=0;var k=Y(a>>>0);a={};if(f){var h=(u(),C)[f+12>>>2>>>0];if(h){var l=(u(),C)[f+16>>>2>>>0];a.requiredFeatures=Array.from((u(),C).subarray(l>>>2>>>0,l+4*h>>>2>>>0),q=>zh[q])}if(h=(u(),C)[f+20>>>2>>>0]){l=(u(),C)[h>>>2>>>0];var p={};function q(z,A,ja,Aa=!1){A+=ja;A=(u(),C)[A>>>2>>>0];4294967295==A||Aa&&0==A||(p[z]=A)}function y(z,A,ja){A+=ja;ja=(u(),C)[A>>>2>>>0];var Aa=(u(),C)[A+4>>>2>>>0];if(4294967295!=ja||4294967295!=Aa)p[z]=jh(A)}q("maxTextureDimension1D",
|
| 78 |
+
h,4);q("maxTextureDimension2D",h,8);q("maxTextureDimension3D",h,12);q("maxTextureArrayLayers",h,16);q("maxBindGroups",h,20);q("maxBindGroupsPlusVertexBuffers",h,24);q("maxBindingsPerBindGroup",h,28);q("maxDynamicUniformBuffersPerPipelineLayout",h,32);q("maxDynamicStorageBuffersPerPipelineLayout",h,36);q("maxSampledTexturesPerShaderStage",h,40);q("maxSamplersPerShaderStage",h,44);q("maxStorageBuffersPerShaderStage",h,48);q("maxStorageTexturesPerShaderStage",h,52);q("maxUniformBuffersPerShaderStage",
|
| 79 |
+
h,56);q("minUniformBufferOffsetAlignment",h,80);q("minStorageBufferOffsetAlignment",h,84);y("maxUniformBufferBindingSize",h,64);y("maxStorageBufferBindingSize",h,72);q("maxVertexBuffers",h,88);y("maxBufferSize",h,96);q("maxVertexAttributes",h,104);q("maxVertexBufferArrayStride",h,108);q("maxInterStageShaderVariables",h,112);q("maxColorAttachments",h,116);q("maxColorAttachmentBytesPerSample",h,120);q("maxComputeWorkgroupStorageSize",h,124);q("maxComputeInvocationsPerWorkgroup",h,128);q("maxComputeWorkgroupSizeX",
|
| 80 |
+
h,132);q("maxComputeWorkgroupSizeY",h,136);q("maxComputeWorkgroupSizeZ",h,140);q("maxComputeWorkgroupsPerDimension",h,144);q("maxImmediateSize",h,148,!0);0!==l&&(u(),"maxStorageBuffersInVertexStage"in GPUSupportedLimits.prototype&&(q("maxStorageBuffersInVertexStage",l,8),q("maxStorageTexturesInVertexStage",l,12),q("maxStorageBuffersInFragmentStage",l,16),q("maxStorageTexturesInFragmentStage",l,20)));a.requiredLimits=p}if(h=(u(),C)[f+24>>>2>>>0])h={label:Z(h+4)},a.defaultQueue=h;a.label=Z(f+4)}L+=
|
| 81 |
+
1;mh(b,k.requestDevice(a).then(q=>{--L;N(()=>{W[e>>>0]=q.queue;W[d>>>0]=q;L+=1;mh(c,q.lost.then(y=>{N(()=>{q.onuncapturederror=()=>{};var z=K(),A=V(y.message);De(c,Hh[y.reason],A);J(z)});--L}));q.onuncapturederror=y=>{var z=5;y.error instanceof GPUValidationError?z=2:y.error instanceof GPUOutOfMemoryError?z=3:y.error instanceof GPUInternalError&&(z=4);var A=K();y=V(y.error.message);Ie(d,z,y);J(A)};"adapterInfo"in q||(q.adapterInfo=k.info);He(b,1,d,0)})},q=>{--L;N(()=>{var y=K(),z=V(q.message);He(b,
|
| 82 |
+
3,d,z);c&&De(c,4,z);J(y)})}))}function Ac(a){a>>>=0;var b=Y(a),c=X[a];if(c){for(var d=0;d<c.length;++d)c[d]();delete X[a]}b.destroy()}function Bc(a,b,c){a>>>=0;c>>>=0;var d=Y(a);4294967295==c&&(c=void 0);try{var e=d.getMappedRange(b>>>0,c)}catch(k){return 0}var f=Oe(16,e.byteLength);(u(),x).set(new Uint8Array(e),f>>>0);X[a].push(()=>H(f));return f}
|
| 83 |
+
function Cc(a,b,c){a>>>=0;c>>>=0;var d=Y(a);4294967295==c&&(c=void 0);try{var e=d.getMappedRange(b>>>0,c)}catch(k){return 0}var f=Oe(16,e.byteLength);(u(),x).fill(0,f,e.byteLength);X[a].push(()=>{(new Uint8Array(e)).set((u(),x).subarray(f>>>0,f+e.byteLength>>>0));H(f)});return f}
|
| 84 |
+
function Dc(a,b,c,d,e){a>>>=0;b=O(b);c=O(c);e>>>=0;var f=Y(a);X[a]=[];4294967295==e&&(e=void 0);L+=1;mh(b,f.mapAsync(c,d>>>0,e).then(()=>{--L;N(()=>{Ee(b,1,0)})},k=>{--L;N(()=>{K();var h=V(k.message);Ee(b,"AbortError"===k.name?4:"OperationError"===k.name?3:0,h);delete X[a]})}))}function Ec(a){a>>>=0;var b=Y(a),c=X[a];if(c){for(var d=0;d<c.length;++d)c[d]();delete X[a];b.unmap()}}function Fc(a){delete W[a>>>0]}
|
| 85 |
+
function Gc(a,b,c){a>>>=0;b>>>=0;c>>>=0;var d=!!(u(),C)[b+32>>>2>>>0];b={label:Z(b+4),usage:(u(),C)[b+16>>>2>>>0],size:jh(b+24),mappedAtCreation:d};a=Y(a);try{var e=a.createBuffer(b)}catch(f){return!1}W[c>>>0]=e;d&&(X[c]=[]);return!0}function Hc(a,b,c,d){a>>>=0;b=O(b);d>>>=0;c=sh(c>>>0);a=Y(a);L+=1;mh(b,a.createComputePipelineAsync(c).then(e=>{--L;N(()=>{W[d>>>0]=e;Ce(b,1,d,0)})},e=>{--L;N(()=>{var f=K(),k=V(e.message);Ce(b,"validation"===e.reason?3:"internal"===e.reason?4:0,d,k);J(f)})}))}
|
| 86 |
+
function Ic(a,b,c){a>>>=0;b>>>=0;c>>>=0;var d=(u(),C)[b>>>2>>>0],e=(u(),B)[d+4>>>2>>>0];b={label:Z(b+4),code:""};switch(e){case 2:b.code=rh(d+8)}a=Y(a).createShaderModule(b);W[c>>>0]=a}var Jc=a=>{a=Y(a);a.onuncapturederror=null;a.destroy()};
|
| 87 |
+
function Kc(a,b){b=O(b);a=Y(a>>>0);L+=1;mh(b,a.popErrorScope().then(c=>{--L;N(()=>{var d=5;c?c instanceof GPUValidationError?d=2:c instanceof GPUOutOfMemoryError?d=3:c instanceof GPUInternalError&&(d=4):d=1;var e=K(),f=c?V(c.message):0;Fe(b,1,d,f);J(e)})},c=>{--L;N(()=>{var d=K(),e=V(c.message);Fe(b,1,5,e);J(d)})}))}
|
| 88 |
+
function Lc(a,b,c,d){b=O(b);c>>>=0;d>>>=0;if(c){var e={featureLevel:yh[(u(),B)[c+4>>>2>>>0]],powerPreference:Ah[(u(),B)[c+8>>>2>>>0]],forceFallbackAdapter:!!(u(),C)[c+12>>>2>>>0]};a=(u(),C)[c>>>2>>>0];0!==a&&(u(),e.Ye=!!(u(),C)[a+8>>>2>>>0])}"gpu"in navigator?(L+=1,mh(b,navigator.gpu.requestAdapter(e).then(f=>{--L;N(()=>{if(f)W[d>>>0]=f,Ge(b,1,d,0);else{var k=K(),h=V("WebGPU not available on this browser (requestAdapter returned null)");Ge(b,3,d,h);J(k)}})},f=>{--L;N(()=>{var k=K(),h=V(f.message);
|
| 89 |
+
Ge(b,4,d,h);J(k)})}))):(e=K(),a=V("WebGPU not available on this browser (navigator.gpu is not available)"),Ge(b,3,d,a),J(e))}function Mc(a,b,c){a>>>=0;b>>>=0;c>>>=0;return Sg(async()=>{var d=[];if(c){var e=(u(),B)[c>>>2>>>0];d.length=b+1;d[b]=new Promise(h=>setTimeout(h,e,0))}else d.length=b;for(var f=0;f<b;++f){var k=jh(a+8*f);if(!(k in lh))return k;d[f]=lh[k]}d=await Promise.race(d);delete lh[d];return d})}
|
| 90 |
+
var Ih={},Kh=()=>{if(!Jh){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:fa||"./this.program"},b;for(b in Ih)void 0===Ih[b]?delete a[b]:a[b]=Ih[b];var c=[];for(b in a)c.push(`${b}=${a[b]}`);Jh=c}return Jh},Jh;function Nc(a,b){if(n)return M(19,1,a,b);a>>>=0;b>>>=0;var c=0,d=0,e;for(e of Kh()){var f=b+c;(u(),C)[a+d>>>2>>>0]=f;c+=T(e,f,Infinity)+1;d+=4}return 0}
|
| 91 |
+
function Oc(a,b){if(n)return M(20,1,a,b);a>>>=0;b>>>=0;var c=Kh();(u(),C)[a>>>2>>>0]=c.length;a=0;for(var d of c)a+=U(d)+1;(u(),C)[b>>>2>>>0]=a;return 0}function Qc(a){return n?M(21,1,a):52}function Rc(a,b,c,d,e){return n?M(22,1,a,b,c,d,e):52}function Sc(a,b,c,d){return n?M(23,1,a,b,c,d):52}function Tc(a,b,c,d){return n?M(24,1,a,b,c,d):70}var Lh=[null,[],[]];
|
| 92 |
+
function Uc(a,b,c,d){if(n)return M(25,1,a,b,c,d);b>>>=0;c>>>=0;d>>>=0;for(var e=0,f=0;f<c;f++){var k=(u(),C)[b>>>2>>>0],h=(u(),C)[b+4>>>2>>>0];b+=8;for(var l=0;l<h;l++){var p=a,q=(u(),x)[k+l>>>0],y=Lh[p];0===q||10===q?((1===p?sa:t)(hg(y)),y.length=0):y.push(q)}e+=h}(u(),C)[d>>>2>>>0]=e;return 0}function Id(a){return a>>>0}function Kd(a,b){th(Y(a>>>0).limits,b>>>0);return 1}function Ld(a,b){return Y(a>>>0).features.has(zh[b])}function Md(a){return BigInt(Y(a>>>0).size)}
|
| 93 |
+
function Nd(a){return BigInt(Y(a>>>0).usage)}function Od(a,b){a>>>=0;b>>>=0;if(b){var c=Z(b+4);b=(u(),C)[b+12>>>2>>>0];b=0!==b?{querySet:Y((u(),C)[b+4>>>2>>>0]),beginningOfPassWriteIndex:(u(),C)[b+8>>>2>>>0],endOfPassWriteIndex:(u(),C)[b+12>>>2>>>0]}:void 0;c={label:c,timestampWrites:b}}b=Y(a);a=we(0);c=b.beginComputePass(c);W[a>>>0]=c;return a}function Pd(a,b,c,d){c=O(c);d=O(d);a=Y(a>>>0);-1==d&&(d=void 0);a.clearBuffer(Y(b>>>0),c,d)}
|
| 94 |
+
function Qd(a,b,c,d,e,f){c=O(c);e=O(e);f=O(f);Y(a>>>0).copyBufferToBuffer(Y(b>>>0),c,Y(d>>>0),e,f)}function Rd(a){var b=Y(a>>>0);a=ue(0);b=b.finish();W[a>>>0]=b;return a}function Sd(a,b,c,d,e,f){f=O(f);Y(a>>>0).resolveQuerySet(Y(b>>>0),c,d,Y(e>>>0),f)}function Td(a,b,c,d){Y(a>>>0).dispatchWorkgroups(b,c,d)}function Ud(a,b,c){c=O(c);Y(a>>>0).dispatchWorkgroupsIndirect(Y(b>>>0),c)}function Vd(a){Y(a>>>0).end()}
|
| 95 |
+
function Wd(a,b,c,d,e){d>>>=0;e>>>=0;a=Y(a>>>0);c=Y(c>>>0);0==d?a.setBindGroup(b,c):a.setBindGroup(b,c,(u(),C),e>>>2,d)}function Xd(a,b){Y(a>>>0).setPipeline(Y(b>>>0))}function Yd(a,b,c){Y(a>>>0).Xe(Y(b>>>0),c)}
|
| 96 |
+
function Zd(a,b){function c(e){var f=(u(),C)[e+8>>>2>>>0],k=(u(),C)[e+32>>>2>>>0],h=(u(),C)[e+36>>>2>>>0],l=0;ph(e,{14:p=>{l=(u(),C)[p+8>>>2>>>0]}});f?(k=jh(e+24),-1==k&&(k=void 0),f={buffer:Y(f),offset:jh(e+16),size:k}):f=Y(k||h||l);return{binding:(u(),C)[e+4>>>2>>>0],resource:f}}a>>>=0;b>>>=0;b={label:Z(b+4),layout:Y((u(),C)[b+12>>>2>>>0]),entries:function(e,f){for(var k=[],h=0;h<e;++h)k.push(c(f+40*h));return k}((u(),C)[b+16>>>2>>>0],(u(),C)[b+20>>>2>>>0])};a=Y(a);var d=se(0);kh(d,a.createBindGroup(b));
|
| 97 |
+
return d}
|
| 98 |
+
function $d(a,b){function c(l){var p=(u(),C)[l+4>>>2>>>0];if(p)return{type:wh[p],hasDynamicOffset:!!(u(),C)[l+8>>>2>>>0],minBindingSize:jh(l+16)}}function d(l){if(l=(u(),C)[l+4>>>2>>>0])return{type:Ch[l]}}function e(l){var p=(u(),C)[l+4>>>2>>>0];if(p)return{sampleType:Fh[p],viewDimension:Gh[(u(),B)[l+8>>>2>>>0]],multisampled:!!(u(),C)[l+12>>>2>>>0]}}function f(l){var p=(u(),C)[l+4>>>2>>>0];if(p)return{access:Dh[p],format:Eh[(u(),B)[l+8>>>2>>>0]],viewDimension:Gh[(u(),B)[l+12>>>2>>>0]]}}function k(l){var p={binding:(u(),
|
| 99 |
+
C)[l+4>>>2>>>0],visibility:(u(),C)[l+8>>>2>>>0],buffer:c(l+24),sampler:d(l+48),texture:e(l+56),storageTexture:f(l+72)};ph(l,{13:()=>{p.externalTexture={}}});return p}a>>>=0;b>>>=0;b={label:Z(b+4),entries:function(l,p){for(var q=[],y=0;y<l;++y)q.push(k(p+88*y));return q}((u(),C)[b+12>>>2>>>0],(u(),C)[b+16>>>2>>>0])};a=Y(a);var h=te(0);kh(h,a.createBindGroupLayout(b));return h}function ae(a,b){a>>>=0;b>>>=0;var c;b&&(c={label:Z(b+4)});b=Y(a);a=ve(0);c=b.createCommandEncoder(c);W[a>>>0]=c;return a}
|
| 100 |
+
function be(a,b){a>>>=0;b>>>=0;for(var c=(u(),C)[b+12>>>2>>>0],d=(u(),C)[b+16>>>2>>>0],e=[],f=0;f<c;++f)e.push(Y((u(),C)[d+4*f>>>2>>>0]));b={label:Z(b+4),bindGroupLayouts:e,immediateSize:(u(),C)[b+20>>>2>>>0]};c=Y(a);a=xe(0);b=c.createPipelineLayout(b);W[a>>>0]=b;return a}function ce(a,b){a>>>=0;b>>>=0;b={type:Bh[(u(),B)[b+12>>>2>>>0]],count:(u(),C)[b+16>>>2>>>0]};var c=Y(a);a=ye(0);b=c.createQuerySet(b);W[a>>>0]=b;return a}function de(a,b){vh(Y(a>>>0).adapterInfo,b>>>0);return 1}
|
| 101 |
+
var Mh={"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,
|
| 102 |
+
"primitive-index":21,"texture-component-swizzle":22,"subgroup-size-control":23,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729,"chromium-experimental-subgroup-matrix":327732};function ee(a,b){b>>>=0;var c=Y(a>>>0);a=qe(4*c.features.size);var d=0,e=0;for(const f of c.features)c=Mh[f],0<=c&&((u(),B)[a+d>>>2>>>0]=c,d+=4,e++);(u(),C)[b+4>>>2>>>0]=a;(u(),C)[b>>>2>>>0]=e}function fe(a,b){th(Y(a>>>0).limits,b>>>0);return 1}
|
| 103 |
+
function ge(a,b){Y(a>>>0).pushErrorScope(xh[b])}function he(a,b,c){b>>>=0;c>>>=0;a=Y(a>>>0);b=Array.from((u(),B).subarray(c>>>2>>>0,c+4*b>>>2>>>0),d=>Y(d));a.submit(b)}function ie(a,b,c,d,e){c=O(c);d>>>=0;e>>>=0;a=Y(a>>>0);b=Y(b>>>0);d=(u(),x).subarray(d>>>0,d+e>>>0);a.writeBuffer(b,c,d,0,e)}n||Vf();n||(v=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),xa());g.wasmBinary&&(ta=g.wasmBinary);g.stackSave=()=>K();g.stackRestore=a=>J(a);g.stackAlloc=a=>Re(a);
|
| 104 |
+
g.setValue=function(a,b,c="i8"){c.endsWith("*")&&(c="*");switch(c){case "i1":(u(),w)[a>>>0]=b;break;case "i8":(u(),w)[a>>>0]=b;break;case "i16":(u(),Oa)[a>>>1>>>0]=b;break;case "i32":(u(),B)[a>>>2>>>0]=b;break;case "i64":(u(),E)[a>>>3>>>0]=BigInt(b);break;case "float":(u(),Qa)[a>>>2>>>0]=b;break;case "double":(u(),D)[a>>>3>>>0]=b;break;case "*":(u(),C)[a>>>2>>>0]=b;break;default:G(`invalid type for setValue: ${c}`)}};
|
| 105 |
+
g.getValue=function(a,b="i8"){b.endsWith("*")&&(b="*");switch(b){case "i1":return(u(),w)[a>>>0];case "i8":return(u(),w)[a>>>0];case "i16":return(u(),Oa)[a>>>1>>>0];case "i32":return(u(),B)[a>>>2>>>0];case "i64":return(u(),E)[a>>>3>>>0];case "float":return(u(),Qa)[a>>>2>>>0];case "double":return(u(),D)[a>>>3>>>0];case "*":return(u(),C)[a>>>2>>>0];default:G(`invalid type for getValue: ${b}`)}};g.UTF8ToString=ig;g.stringToUTF8=T;g.lengthBytesUTF8=U;
|
| 106 |
+
var Eg=[Jd,Uf,eg,kb,lb,mb,nb,ob,pb,qb,rb,sb,tb,ub,vb,wb,gc,hc,ic,Nc,Oc,Qc,Rc,Sc,Tc,Uc],Dg={1274364:(a,b,c,d,e)=>{if("undefined"==typeof g||!g.ed)return 1;a=ig(Number(a>>>0));a.startsWith("./")&&(a=a.substring(2));a=g.ed.get(a);if(!a)return 2;b=Number(b>>>0);c=Number(c>>>0);d=Number(d>>>0);if(b+c>a.byteLength)return 3;try{const f=a.subarray(b,b+c);switch(e){case 0:(u(),x).set(f,d>>>0);break;case 1:g.pe?g.pe(d,f):g.Re(d,f);break;default:return 4}return 0}catch{return 4}},1275188:(a,b,c)=>{g.re(a,(u(),
|
| 107 |
+
x).subarray(b>>>0,b+c>>>0))},1275252:()=>g.Pe(),1275294:a=>{g.qe(a)},1275331:()=>"undefined"!==typeof wasmOffsetConverter};function $a(){return"undefined"!==typeof wasmOffsetConverter}var me,Ka,ne,oe,pe,H,qe,re,se,te,ue,ve,we,xe,ye,ze,Ae,Be,Ce,De,Ee,Fe,Ge,He,Ie,Ha,Na,Je,Ke,Le,Me,Ne,Oe,I,Pe,Qe,J,Re,K,Se,Te,Ue,Ve,dynCall_vii,We,dynCall_v,Xe,Ye,Ze,dynCall_iii,$e,af,bf,dynCall_vi,cf,df,ef,ff,gf,hf,jf,kf,lf,mf,nf,of,pf,qf,rf,sf,tf,uf,vf,wf,xf,yf,zf,Af,Bf,Cf,Df,Ef,Ff,Gf,Hf,If,Za;
|
| 108 |
+
function bd(a,b,c,d){var e=K();try{return bf(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}}function ad(a,b,c){var d=K();try{return dynCall_iii(a,b,c)}catch(e){J(d);if(e!==e+0)throw e;I(1,0)}}function sd(a){var b=K();try{dynCall_v(a)}catch(c){J(b);if(c!==c+0)throw c;I(1,0)}}function $c(a,b){var c=K();try{return We(a,b)}catch(d){J(c);if(d!==d+0)throw d;I(1,0)}}function ud(a,b,c){var d=K();try{dynCall_vii(a,b,c)}catch(e){J(d);if(e!==e+0)throw e;I(1,0)}}
|
| 109 |
+
function td(a,b){var c=K();try{dynCall_vi(a,b)}catch(d){J(c);if(d!==d+0)throw d;I(1,0)}}function fd(a,b,c,d,e,f,k){var h=K();try{return Ze(a,b,c,d,e,f,k)}catch(l){J(h);if(l!==l+0)throw l;I(1,0)}}function yd(a,b,c,d,e,f){var k=K();try{Xe(a,b,c,d,e,f)}catch(h){J(k);if(h!==h+0)throw h;I(1,0)}}function wd(a,b,c,d){var e=K();try{af(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}}function zd(a,b,c,d,e,f,k){var h=K();try{df(a,b,c,d,e,f,k)}catch(l){J(h);if(l!==l+0)throw l;I(1,0)}}
|
| 110 |
+
function Gd(a,b,c,d,e,f,k){var h=K();try{ef(a,b,c,d,e,f,k)}catch(l){J(h);if(l!==l+0)throw l;I(1,0)}}function Fd(a,b,c,d,e,f,k,h){var l=K();try{pf(a,b,c,d,e,f,k,h)}catch(p){J(l);if(p!==p+0)throw p;I(1,0)}}function Dd(a,b,c,d,e,f,k,h,l,p,q,y){var z=K();try{ff(a,b,c,d,e,f,k,h,l,p,q,y)}catch(A){J(z);if(A!==A+0)throw A;I(1,0)}}function cd(a,b,c,d,e){var f=K();try{return cf(a,b,c,d,e)}catch(k){J(f);if(k!==k+0)throw k;I(1,0)}}
|
| 111 |
+
function Hd(a,b,c,d,e,f){var k=K();try{qf(a,b,c,d,e,f)}catch(h){J(k);if(h!==h+0)throw h;I(1,0)}}function xd(a,b,c,d,e){var f=K();try{Ye(a,b,c,d,e)}catch(k){J(f);if(k!==k+0)throw k;I(1,0)}}function Ad(a,b,c,d,e,f,k,h){var l=K();try{$e(a,b,c,d,e,f,k,h)}catch(p){J(l);if(p!==p+0)throw p;I(1,0)}}function Zc(a){var b=K();try{return rf(a)}catch(c){J(b);if(c!==c+0)throw c;I(1,0)}}function Bd(a,b,c,d,e,f,k,h,l){var p=K();try{hf(a,b,c,d,e,f,k,h,l)}catch(q){J(p);if(q!==q+0)throw q;I(1,0)}}
|
| 112 |
+
function md(a,b,c){var d=K();try{return sf(a,b,c)}catch(e){J(d);if(e!==e+0)throw e;I(1,0)}}function pd(a,b){var c=K();try{return Ef(a,b)}catch(d){J(c);if(d!==d+0)throw d;I(1,0);return 0n}}function nd(a,b,c,d){var e=K();try{return tf(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}}function od(a){var b=K();try{return gf(a)}catch(c){J(b);if(c!==c+0)throw c;I(1,0);return 0n}}function ld(a,b,c,d){var e=K();try{return uf(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}}
|
| 113 |
+
function kd(a,b,c,d,e){var f=K();try{return vf(a,b,c,d,e)}catch(k){J(f);if(k!==k+0)throw k;I(1,0)}}function jd(a,b,c,d,e,f){var k=K();try{return wf(a,b,c,d,e,f)}catch(h){J(k);if(h!==h+0)throw h;I(1,0)}}function ed(a,b,c,d,e,f){var k=K();try{return nf(a,b,c,d,e,f)}catch(h){J(k);if(h!==h+0)throw h;I(1,0)}}function dd(a,b,c,d,e,f){var k=K();try{return xf(a,b,c,d,e,f)}catch(h){J(k);if(h!==h+0)throw h;I(1,0)}}
|
| 114 |
+
function gd(a,b,c,d,e,f,k,h){var l=K();try{return of(a,b,c,d,e,f,k,h)}catch(p){J(l);if(p!==p+0)throw p;I(1,0)}}function rd(a,b,c,d,e){var f=K();try{return yf(a,b,c,d,e)}catch(k){J(f);if(k!==k+0)throw k;I(1,0);return 0n}}function Yc(a,b,c,d){var e=K();try{return zf(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}}function Wc(a,b,c,d){var e=K();try{return Af(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}}
|
| 115 |
+
function hd(a,b,c,d,e,f,k,h,l,p,q,y){var z=K();try{return Bf(a,b,c,d,e,f,k,h,l,p,q,y)}catch(A){J(z);if(A!==A+0)throw A;I(1,0)}}function Cd(a,b,c,d,e,f,k,h,l,p,q){var y=K();try{Cf(a,b,c,d,e,f,k,h,l,p,q)}catch(z){J(y);if(z!==z+0)throw z;I(1,0)}}function Ed(a,b,c,d,e,f,k,h,l,p,q,y,z,A,ja,Aa){var Nh=K();try{Df(a,b,c,d,e,f,k,h,l,p,q,y,z,A,ja,Aa)}catch(Db){J(Nh);if(Db!==Db+0)throw Db;I(1,0)}}function qd(a,b,c){var d=K();try{return kf(a,b,c)}catch(e){J(d);if(e!==e+0)throw e;I(1,0);return 0n}}
|
| 116 |
+
function Xc(a,b,c){var d=K();try{return jf(a,b,c)}catch(e){J(d);if(e!==e+0)throw e;I(1,0)}}function Vc(a,b,c){var d=K();try{return lf(a,b,c)}catch(e){J(d);if(e!==e+0)throw e;I(1,0)}}function vd(a,b,c,d){var e=K();try{mf(a,b,c,d)}catch(f){J(e);if(f!==f+0)throw f;I(1,0)}}function ke(){var a=F;a=Object.assign({},a);var b=d=>e=>d(e)>>>0,c=d=>()=>d()>>>0;a.ic=b(a.ic);a.Nc=c(a.Nc);a.Pc=b(a.Pc);a.Bd=(d=>(e,f)=>d(e,f)>>>0)(a.Bd);a.Gd=b(a.Gd);a.Hd=c(a.Hd);a.Ld=b(a.Ld);return a}
|
| 117 |
+
function Fa(){if(0<Mf)Nf=Fa;else if(n)ya?.(g),Ta();else{for(var a=Lf;0<a.length;)a.shift()(g);0<Mf?Nf=Fa:(g.calledRun=!0,va||(Ta(),ya?.(g)))}}var F;n||(F=await (Ea()),Fa());g.PTR_SIZE=4;
|
| 118 |
+
g.webgpuInit=a=>{const b=new WeakMap;let c=1,d=void 0,e=void 0;g.webgpuRegisterDevice=h=>{if(void 0!==e)throw Error("another WebGPU EP inference session is being created.");if(h){var l=b.get(h);if(!l){l=ne();const p=oh(h,l);l=[c++,l,p];b.set(h,l)}d=h;e=l[0];return l}d=void 0;e=0};const f=new Map;g.webgpuOnCreateSession=h=>{if(void 0!==e){var l=e;e=void 0;if(h){const p=oe(l);f.set(h,p);0===l&&a(d??Y(p))}d=void 0}};g.webgpuOnReleaseSession=h=>{f.delete(h)};const k=Symbol("gpuBufferMetadata");g.webgpuRegisterBuffer=
|
| 119 |
+
(h,l,p)=>{if(p)return h[k]=[p,NaN],p;if(p=h[k])return p[1]++,p[0];l=f.get(l);if(void 0===l)throw Error("Invalid session handle passed to webgpuRegisterBuffer");l=nh(h,l);h[k]=[l,1];return l};g.webgpuUnregisterBuffer=h=>{const l=h[k];if(!l)throw Error("Buffer is not registered");l[1]--;0===l[1]&&(re(l[0]),delete h[k])};g.webgpuGetBuffer=h=>Y(h);g.webgpuCreateDownloader=(h,l,p)=>{p=f.get(p);if(void 0===p)throw Error("Invalid session handle passed to webgpuRegisterBuffer");const q=Y(p),y=16*Math.ceil(Number(l)/
|
| 120 |
+
16);return async()=>{const z=q.createBuffer({size:y,usage:9});try{const A=q.createCommandEncoder();A.copyBufferToBuffer(h,0,z,0,y);q.queue.submit([A.finish()]);await z.mapAsync(GPUMapMode.READ);return z.getMappedRange().slice(0,l)}finally{z.destroy()}}};g.pe=(h,l)=>{var p=l.buffer;const q=l.byteOffset,y=l.byteLength;l=16*Math.ceil(Number(y)/16);h=Y(h);if(!d){var z=oe(e);d=Y(z)}z=d.createBuffer({mappedAtCreation:!0,size:l,usage:6});const A=z.getMappedRange();(new Uint8Array(A)).set(new Uint8Array(p,
|
| 121 |
+
q,y));z.unmap();p=d.createCommandEncoder();p.copyBufferToBuffer(z,0,h,0,l);d.queue.submit([p.finish()]);z.destroy()}};
|
| 122 |
+
g.webnnInit=a=>{const b=a[0];[g.Pe,g.qe,g.webnnEnsureTensor,g.re,g.webnnDownloadTensor,g.Oe,g.webnnEnableTraceEvent]=a.slice(1);g.webnnReleaseTensorId=g.qe;g.webnnUploadTensor=g.re;g.webnnRegisterMLContext=g.Oe;g.webnnOnRunStart=c=>b.onRunStart(c);g.webnnOnRunEnd=b.onRunEnd.bind(b);g.webnnOnReleaseSession=c=>{b.onReleaseSession(c)};g.webnnCreateMLTensorDownloader=(c,d)=>b.createMLTensorDownloader(c,d);g.webnnRegisterMLTensor=(c,d,e,f)=>b.registerMLTensor(c,d,e,f);g.webnnCreateMLContext=c=>b.createMLContext(c);
|
| 123 |
+
g.webnnRegisterGraphInput=b.registerGraphInput.bind(b);g.webnnIsGraphInput=b.isGraphInput.bind(b);g.webnnRegisterGraphOutput=b.registerGraphOutput.bind(b);g.webnnIsGraphOutput=b.isGraphOutput.bind(b);g.webnnCreateTemporaryTensor=b.createTemporaryTensor.bind(b);g.webnnIsGraphInputOutputTypeSupported=b.isGraphInputOutputTypeSupported.bind(b)};Sa?moduleRtn=g:moduleRtn=new Promise((a,b)=>{ya=a;za=b});
|
| 124 |
+
;return moduleRtn}export default ortWasmThreaded;var isPthread=globalThis.self?.name?.startsWith("em-pthread");var isNode=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(isNode)isPthread=(await import("worker_threads")).workerData==="em-pthread";isPthread&&ortWasmThreaded();
|
vendor/ort/ort-wasm-simd-threaded.asyncify.wasm
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:39f9f0894d478800487ed9f7dbe92618498db320cf55c8e3d89adff8dce658da
|
| 3 |
+
size 26781914
|
vendor/ort/ort-wasm-simd-threaded.mjs
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
async function ortWasmThreaded(moduleArg={}){var moduleRtn;var h=moduleArg,aa=!!globalThis.window,k=!!globalThis.WorkerGlobalScope,m=globalThis.process?.versions?.node&&"renderer"!=globalThis.process?.type,n=k&&self.name?.startsWith("em-pthread");if(m){const {createRequire:a}=await import("module");var require=a(import.meta.url),ba=require("worker_threads");global.Worker=ba.Worker;n=(k=!ba.jc)&&"em-pthread"==ba.workerData}h.mountExternalData=(a,b)=>{a.startsWith("./")&&(a=a.substring(2));(h.Tb||(h.Tb=new Map)).set(a,b)};
|
| 2 |
+
h.unmountExternalData=()=>{delete h.Tb;delete h.mc;delete h.lc;delete h.nc};var SharedArrayBuffer=globalThis.SharedArrayBuffer??(new WebAssembly.Memory({initial:0,maximum:0,shared:!0})).buffer.constructor,ca="./this.program",da=(a,b)=>{throw b;},ea=import.meta.url,fa="",ha,ia;
|
| 3 |
+
if(m){var fs=require("fs");ea.startsWith("file:")&&(fa=require("path").dirname(require("url").fileURLToPath(ea))+"/");ia=a=>{a=ja(a)?new URL(a):a;return fs.readFileSync(a)};ha=async a=>{a=ja(a)?new URL(a):a;return fs.readFileSync(a,void 0)};1<process.argv.length&&(ca=process.argv[1].replace(/\\/g,"/"));process.argv.slice(2);da=(a,b)=>{process.exitCode=a;throw b;}}else if(aa||k){try{fa=(new URL(".",ea)).href}catch{}m||(k&&(ia=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";
|
| 4 |
+
b.send(null);return new Uint8Array(b.response)}),ha=async a=>{if(ja(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 ka=console.log.bind(console),la=console.error.bind(console);
|
| 5 |
+
if(m){var ma=require("util"),na=a=>"object"==typeof a?ma.inspect(a):a;ka=(...a)=>fs.writeSync(1,a.map(na).join(" ")+"\n");la=(...a)=>fs.writeSync(2,a.map(na).join(" ")+"\n")}var oa=ka,p=la,q,r,pa=!1,t,ja=a=>a.startsWith("file://");function v(){x.buffer!=z.buffer&&qa()}var ra,sa;
|
| 6 |
+
if(m&&n){var ta=ba.parentPort;ta.on("message",a=>global.onmessage?.({data:a}));Object.assign(globalThis,{self:global,postMessage:a=>ta.postMessage(a)});process.on("uncaughtException",a=>{postMessage({Rb:"uncaughtException",error:a});process.exit(1)})}var ua;
|
| 7 |
+
if(n){var va=!1;self.onunhandledrejection=b=>{throw b.reason||b;};function a(b){try{var d=b.data,c=d.Rb;if("load"===c){let e=[];self.onmessage=f=>e.push(f);ua=()=>{postMessage({Rb:"loaded"});for(let f of e)a(f);self.onmessage=a};for(const f of d.ac)if(!h[f]||h[f].proxy)h[f]=(...g)=>{postMessage({Rb:"callHandler",$b:f,args:g})},"print"==f&&(oa=h[f]),"printErr"==f&&(p=h[f]);x=d.fc;qa();r=d.hc;wa();xa()}else if("run"===c){ya(d.Qb);za(d.Qb,0,0,1,0,0);Aa();Ba(d.Qb);va||=!0;try{Ca(d.dc,d.Vb)}catch(e){if("unwind"!=
|
| 8 |
+
e)throw e;}}else"setimmediate"!==d.target&&("checkMailbox"===c?va&&Da():c&&(p(`worker: received unknown command ${c}`),p(d)))}catch(e){throw Ea(),e;}}self.onmessage=a}var z,A,Fa,C,D,Ga,G,H,Ha=!1;function qa(){var a=x.buffer;h.HEAP8=z=new Int8Array(a);Fa=new Int16Array(a);h.HEAPU8=A=new Uint8Array(a);new Uint16Array(a);h.HEAP32=C=new Int32Array(a);h.HEAPU32=D=new Uint32Array(a);Ga=new Float32Array(a);G=new Float64Array(a);H=new BigInt64Array(a);new BigUint64Array(a)}
|
| 9 |
+
function Ia(){Ha=!0;n?ua():I.Va()}function J(a){a="Aborted("+a+")";p(a);pa=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");sa?.(a);throw a;}var Ja;async function Ka(a){if(!q)try{var b=await ha(a);return new Uint8Array(b)}catch{}if(a==Ja&&q)a=new Uint8Array(q);else if(ia)a=ia(a);else throw"both async and sync fetching of the wasm failed";return a}
|
| 10 |
+
async function La(a,b){try{var d=await Ka(a);return await WebAssembly.instantiate(d,b)}catch(c){p(`failed to asynchronously prepare wasm: ${c}`),J(c)}}async function Na(a){var b=Ja;if(!q&&!ja(b)&&!m)try{var d=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(d,a)}catch(c){p(`wasm streaming compile failed: ${c}`),p("falling back to ArrayBuffer instantiation")}return La(b,a)}
|
| 11 |
+
function Oa(){Pa={T:Qa,f:Ra,w:Sa,e:Ta,k:Ua,h:Va,L:Wa,b:Xa,G:Ya,ua:Za,j:$a,M:ab,La:bb,qa:cb,sa:db,Ma:eb,Ja:fb,Ca:gb,Ia:hb,Z:ib,ra:jb,oa:kb,Ka:lb,pa:mb,Ra:nb,Fa:ob,ma:pb,va:qb,ja:rb,U:sb,Ea:Ba,Oa:tb,za:ub,Aa:vb,Ba:wb,xa:xb,ya:yb,ka:zb,Ta:Ab,Qa:Bb,W:Cb,V:Db,Pa:Eb,F:Fb,Na:Gb,na:Hb,u:Ib,H:Jb,S:Kb,la:Lb,ba:Mb,Ua:Nb,Ga:Ob,Ha:Pb,ta:Qb,I:Rb,wa:Sb,Y:Tb,Da:Ub,X:Vb,$:Wb,N:Xb,aa:Yb,O:Zb,v:$b,d:ac,m:bc,n:cc,r:dc,ca:ec,E:fc,o:gc,P:hc,C:ic,J:jc,da:kc,ea:lc,z:mc,fa:nc,Q:oc,ga:pc,y:qc,D:rc,c:sc,q:tc,i:uc,_:vc,l:wc,
|
| 12 |
+
p:xc,s:yc,t:zc,x:Ac,R:Bc,A:Cc,K:Dc,B:Ec,ha:Fc,ia:Gc,g:Hc,a:x,Sa:Ic};return{a:Pa}}
|
| 13 |
+
async function wa(){function a(c,e){I=c.exports;I=Jc();Kc.push(I.xb);c=I;h._OrtInit=c.Wa;h._OrtGetLastError=c.Xa;h._OrtCreateSessionOptions=c.Ya;h._OrtAppendExecutionProvider=c.Za;h._OrtAddFreeDimensionOverride=c._a;h._OrtAddSessionConfigEntry=c.$a;h._OrtReleaseSessionOptions=c.ab;h._OrtCreateSession=c.bb;h._OrtReleaseSession=c.cb;h._OrtGetInputOutputCount=c.db;h._OrtGetInputOutputMetadata=c.eb;h._OrtFree=c.fb;h._OrtCreateTensor=c.gb;h._OrtGetTensorData=c.hb;h._OrtReleaseTensor=c.ib;h._OrtCreateRunOptions=
|
| 14 |
+
c.jb;h._OrtAddRunConfigEntry=c.kb;h._OrtReleaseRunOptions=c.lb;h._OrtCreateBinding=c.mb;h._OrtBindInput=c.nb;h._OrtBindOutput=c.ob;h._OrtClearBoundOutputs=c.pb;h._OrtReleaseBinding=c.qb;h._OrtRunWithBinding=c.rb;h._OrtRun=c.sb;h._OrtEndProfiling=c.tb;Lc=c.ub;Mc=h._free=c.vb;Nc=h._malloc=c.wb;za=c.zb;Ea=c.Ab;Oc=c.Bb;Pc=c.Cb;Qc=c.Db;Rc=c.Eb;Sc=c.Fb;K=c.Gb;L=c.Hb;Tc=c.Ib;M=c.Jb;Uc=c.Kb;N=c.Lb;Vc=c.Mb;Wc=c.Nb;Xc=c.Ob;Yc=c.Pb;Zc=c.yb;r=e;return I}var b=Oa();if(h.instantiateWasm)return new Promise(c=>{h.instantiateWasm(b,
|
| 15 |
+
(e,f)=>{c(a(e,f))})});if(n){var d=new WebAssembly.Instance(r,Oa());return a(d,r)}Ja??=h.locateFile?h.locateFile?h.locateFile("ort-wasm-simd-threaded.wasm",fa):fa+"ort-wasm-simd-threaded.wasm":(new URL("ort-wasm-simd-threaded.wasm",import.meta.url)).href;return function(c){return a(c.instance,c.module)}(await Na(b))}class $c{name="ExitStatus";constructor(a){this.message=`Program terminated with exit(${a})`;this.status=a}}
|
| 16 |
+
var ad=a=>{a.terminate();a.onmessage=()=>{}},bd=[],O=0,P=null,ed=a=>{0==Q.length&&(cd(),dd(Q[0]));var b=Q.pop();if(!b)return 6;R.push(b);S[a.Qb]=b;b.Qb=a.Qb;var d={Rb:"run",dc:a.cc,Vb:a.Vb,Qb:a.Qb};m&&b.unref();b.postMessage(d,a.Zb);return 0},T=0,U=(a,b,...d)=>{var c=16*d.length,e=N(),f=Uc(c),g=f>>>3,l;for(l of d)"bigint"==typeof l?((v(),H)[g++>>>0]=1n,(v(),H)[g++>>>0]=l):((v(),H)[g++>>>0]=0n,(v(),G)[g++>>>0]=l);a=Oc(a,0,c,f,b);M(e);return a};
|
| 17 |
+
function Ic(a){if(n)return U(0,1,a);t=a;if(!(0<T)){for(var b of R)ad(b);for(b of Q)ad(b);Q=[];R=[];S={};pa=!0}da(a,new $c(a))}function fd(a){if(n)return U(1,0,a);Qb(a)}var Qb=a=>{t=a;if(n)throw fd(a),"unwind";Ic(a)},Q=[],R=[],Kc=[],S={};function gd(){for(var a=h.numThreads-1;a--;)cd();bd.push(async()=>{var b=hd();O++;await b;O--;0==O&&P&&(b=P,P=null,b())})}var jd=a=>{var b=a.Qb;delete S[b];Q.push(a);R.splice(R.indexOf(a),1);a.Qb=0;Pc(b)};function Aa(){Kc.forEach(a=>a())}
|
| 18 |
+
var dd=a=>new Promise(b=>{a.onmessage=f=>{var g=f.data;f=g.Rb;if(g.Ub&&g.Ub!=Lc()){var l=S[g.Ub];l?l.postMessage(g,g.Zb):p(`Internal error! Worker sent a message "${f}" to target pthread ${g.Ub}, but that thread no longer exists!`)}else if("checkMailbox"===f)Da();else if("spawnThread"===f)ed(g);else if("cleanupThread"===f)kd(()=>{jd(S[g.ec])});else if("loaded"===f)a.loaded=!0,m&&!a.Qb&&a.unref(),b(a);else if("setimmediate"===g.target)a.postMessage(g);else if("uncaughtException"===f)a.onerror(g.error);
|
| 19 |
+
else if("callHandler"===f)h[g.$b](...g.args);else f&&p(`worker sent an unknown command ${f}`)};a.onerror=f=>{p(`${"worker sent an error!"} ${f.filename}:${f.lineno}: ${f.message}`);throw f;};m&&(a.on("message",f=>a.onmessage({data:f})),a.on("error",f=>a.onerror(f)));var d=[],c=[],e;for(e of c)h.propertyIsEnumerable(e)&&d.push(e);a.postMessage({Rb:"load",ac:d,fc:x,hc:r})});async function hd(){if(!n)return Promise.all(Q.map(dd))}
|
| 20 |
+
function cd(){var a=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});Q.push(a)}function ya(a){var b=(v(),D)[a+52>>>2>>>0];a=(v(),D)[a+56>>>2>>>0];Tc(b,b-a);M(b)}var ld=[],V=a=>{var b=ld[a];b||(ld[a]=b=Zc.get(a));return b},Ca=(a,b)=>{T=0;a=V(a)(b);0<T?t=a:Qc(a)},x,md=[],nd=0;function Ra(a){a>>>=0;var b=new od(a);0==(v(),z)[b.Sb+12>>>0]&&(pd(b,!0),nd--);qd(b,!1);md.push(b);return Yc(a)}
|
| 21 |
+
var W=0,Sa=()=>{K(0,0);var a=md.pop();Vc(a.Wb);W=0};function pd(a,b){b=b?1:0;(v(),z)[a.Sb+12>>>0]=b}function qd(a,b){b=b?1:0;(v(),z)[a.Sb+13>>>0]=b}class od{constructor(a){this.Wb=a;this.Sb=a-24}}var rd=a=>{var b=W;if(!b)return L(0),0;var d=new od(b);(v(),D)[d.Sb+16>>>2>>>0]=b;var c=(v(),D)[d.Sb+4>>>2>>>0];if(!c)return L(0),b;for(var e of a){if(0===e||e===c)break;if(Xc(e,c,d.Sb+16))return L(e),b}L(c);return b};function Ta(){return rd([])}function Ua(a){return rd([a>>>0])}
|
| 22 |
+
function Va(a,b,d,c){return rd([a>>>0,b>>>0,d>>>0,c>>>0])}var Wa=()=>{var a=md.pop();a||J("no exception to throw");var b=a.Wb;0==(v(),z)[a.Sb+13>>>0]&&(md.push(a),qd(a,!0),pd(a,!1),nd++);Wc(b);W=b;throw W;};function Xa(a,b,d){a>>>=0;var c=new od(a);b>>>=0;d>>>=0;(v(),D)[c.Sb+16>>>2>>>0]=0;(v(),D)[c.Sb+4>>>2>>>0]=b;(v(),D)[c.Sb+8>>>2>>>0]=d;Wc(a);W=a;nd++;throw W;}var Ya=()=>nd;function sd(a,b,d,c){return n?U(2,1,a,b,d,c):Za(a,b,d,c)}
|
| 23 |
+
function Za(a,b,d,c){a>>>=0;b>>>=0;d>>>=0;c>>>=0;if(!globalThis.SharedArrayBuffer)return 6;var e=[];if(n&&0===e.length)return sd(a,b,d,c);a={cc:d,Qb:a,Vb:c,Zb:e};return n?(a.Rb="spawnThread",postMessage(a,e),0):ed(a)}function $a(a){W||=a>>>0;throw W;}
|
| 24 |
+
var td=globalThis.TextDecoder&&new TextDecoder,ud=(a,b=0,d,c)=>{b>>>=0;var e=b;d=e+d;if(c)c=d;else{for(;a[e]&&!(e>=d);)++e;c=e}if(16<c-b&&a.buffer&&td)return td.decode(a.buffer instanceof ArrayBuffer?a.subarray(b,c):a.slice(b,c));for(e="";b<c;)if(d=a[b++],d&128){var f=a[b++]&63;if(192==(d&224))e+=String.fromCharCode((d&31)<<6|f);else{var g=a[b++]&63;d=224==(d&240)?(d&15)<<12|f<<6|g:(d&7)<<18|f<<12|g<<6|a[b++]&63;65536>d?e+=String.fromCharCode(d):(d-=65536,e+=String.fromCharCode(55296|d>>10,56320|
|
| 25 |
+
d&1023))}}else e+=String.fromCharCode(d);return e},vd=(a,b,d)=>(a>>>=0)?ud((v(),A),a,b,d):"";function ab(a,b,d){return n?U(3,1,a,b,d):0}function bb(a,b){if(n)return U(4,1,a,b)}function cb(a,b){if(n)return U(5,1,a,b)}function db(a,b,d){if(n)return U(6,1,a,b,d)}function eb(a,b,d){return n?U(7,1,a,b,d):0}function fb(a,b){if(n)return U(8,1,a,b)}function gb(a,b,d){if(n)return U(9,1,a,b,d)}function hb(a,b,d,c){if(n)return U(10,1,a,b,d,c)}function ib(a,b,d,c){if(n)return U(11,1,a,b,d,c)}
|
| 26 |
+
function jb(a,b,d,c){if(n)return U(12,1,a,b,d,c)}function kb(a){if(n)return U(13,1,a)}function lb(a,b){if(n)return U(14,1,a,b)}function mb(a,b,d){if(n)return U(15,1,a,b,d)}var nb=()=>J("");function ob(a){za(a>>>0,!k,1,!aa,131072,!1);Aa()}
|
| 27 |
+
var kd=a=>{if(!pa)try{if(a(),!(0<T))try{n?Lc()&&Qc(t):Qb(t)}catch(b){b instanceof $c||"unwind"==b||da(1,b)}}catch(b){b instanceof $c||"unwind"==b||da(1,b)}},wd=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ba(a){a>>>=0;wd||(Atomics.waitAsync((v(),C),a>>>2,a).value.then(Da),a+=128,Atomics.store((v(),C),a>>>2,1))}var Da=()=>kd(()=>{var a=Lc();a&&(Ba(a),Sc())});
|
| 28 |
+
function pb(a,b){a>>>=0;a==b>>>0?setTimeout(Da):n?postMessage({Ub:a,Rb:"checkMailbox"}):(a=S[a])&&a.postMessage({Rb:"checkMailbox"})}var xd=[];function qb(a,b,d,c,e){b>>>=0;e>>>=0;xd.length=0;d=e>>>3;for(c=e+c>>>3;d<c;){var f;(v(),H)[d++>>>0]?f=(v(),H)[d++>>>0]:f=(v(),G)[d++>>>0];xd.push(f)}return(b?yd[b]:zd[a])(...xd)}var rb=()=>{T=0};function sb(a){a>>>=0;n?postMessage({Rb:"cleanupThread",ec:a}):jd(S[a])}function tb(a){m&&S[a>>>0].ref()}
|
| 29 |
+
function ub(a,b){a=-9007199254740992>a||9007199254740992<a?NaN:Number(a);b>>>=0;a=new Date(1E3*a);(v(),C)[b>>>2>>>0]=a.getUTCSeconds();(v(),C)[b+4>>>2>>>0]=a.getUTCMinutes();(v(),C)[b+8>>>2>>>0]=a.getUTCHours();(v(),C)[b+12>>>2>>>0]=a.getUTCDate();(v(),C)[b+16>>>2>>>0]=a.getUTCMonth();(v(),C)[b+20>>>2>>>0]=a.getUTCFullYear()-1900;(v(),C)[b+24>>>2>>>0]=a.getUTCDay();a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0;(v(),C)[b+28>>>2>>>0]=a}
|
| 30 |
+
var Ad=a=>0===a%4&&(0!==a%100||0===a%400),Bd=[0,31,60,91,121,152,182,213,244,274,305,335],Cd=[0,31,59,90,120,151,181,212,243,273,304,334];
|
| 31 |
+
function vb(a,b){a=-9007199254740992>a||9007199254740992<a?NaN:Number(a);b>>>=0;a=new Date(1E3*a);(v(),C)[b>>>2>>>0]=a.getSeconds();(v(),C)[b+4>>>2>>>0]=a.getMinutes();(v(),C)[b+8>>>2>>>0]=a.getHours();(v(),C)[b+12>>>2>>>0]=a.getDate();(v(),C)[b+16>>>2>>>0]=a.getMonth();(v(),C)[b+20>>>2>>>0]=a.getFullYear()-1900;(v(),C)[b+24>>>2>>>0]=a.getDay();var d=(Ad(a.getFullYear())?Bd:Cd)[a.getMonth()]+a.getDate()-1|0;(v(),C)[b+28>>>2>>>0]=d;(v(),C)[b+36>>>2>>>0]=-(60*a.getTimezoneOffset());d=(new Date(a.getFullYear(),
|
| 32 |
+
6,1)).getTimezoneOffset();var c=(new Date(a.getFullYear(),0,1)).getTimezoneOffset();a=(d!=c&&a.getTimezoneOffset()==Math.min(c,d))|0;(v(),C)[b+32>>>2>>>0]=a}
|
| 33 |
+
function wb(a){a>>>=0;var b=new Date((v(),C)[a+20>>>2>>>0]+1900,(v(),C)[a+16>>>2>>>0],(v(),C)[a+12>>>2>>>0],(v(),C)[a+8>>>2>>>0],(v(),C)[a+4>>>2>>>0],(v(),C)[a>>>2>>>0],0),d=(v(),C)[a+32>>>2>>>0],c=b.getTimezoneOffset(),e=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),f=(new Date(b.getFullYear(),0,1)).getTimezoneOffset(),g=Math.min(f,e);0>d?(v(),C)[a+32>>>2>>>0]=Number(e!=f&&g==c):0<d!=(g==c)&&(e=Math.max(f,e),b.setTime(b.getTime()+6E4*((0<d?g:e)-c)));(v(),C)[a+24>>>2>>>0]=b.getDay();d=(Ad(b.getFullYear())?
|
| 34 |
+
Bd:Cd)[b.getMonth()]+b.getDate()-1|0;(v(),C)[a+28>>>2>>>0]=d;(v(),C)[a>>>2>>>0]=b.getSeconds();(v(),C)[a+4>>>2>>>0]=b.getMinutes();(v(),C)[a+8>>>2>>>0]=b.getHours();(v(),C)[a+12>>>2>>>0]=b.getDate();(v(),C)[a+16>>>2>>>0]=b.getMonth();(v(),C)[a+20>>>2>>>0]=b.getYear();a=b.getTime();return BigInt(isNaN(a)?-1:a/1E3)}function xb(a,b,d,c,e,f,g){return n?U(16,1,a,b,d,c,e,f,g):-52}function yb(a,b,d,c,e,f){if(n)return U(17,1,a,b,d,c,e,f)}var X={},Ib=()=>performance.timeOrigin+performance.now();
|
| 35 |
+
function zb(a,b){if(n)return U(18,1,a,b);X[a]&&(clearTimeout(X[a].id),delete X[a]);if(!b)return 0;var d=setTimeout(()=>{delete X[a];kd(()=>Rc(a,performance.timeOrigin+performance.now()))},b);X[a]={id:d,oc:b};return 0}
|
| 36 |
+
var Y=(a,b,d)=>{var c=(v(),A);b>>>=0;if(0<d){var e=b;d=b+d-1;for(var f=0;f<a.length;++f){var g=a.codePointAt(f);if(127>=g){if(b>=d)break;c[b++>>>0]=g}else if(2047>=g){if(b+1>=d)break;c[b++>>>0]=192|g>>6;c[b++>>>0]=128|g&63}else if(65535>=g){if(b+2>=d)break;c[b++>>>0]=224|g>>12;c[b++>>>0]=128|g>>6&63;c[b++>>>0]=128|g&63}else{if(b+3>=d)break;c[b++>>>0]=240|g>>18;c[b++>>>0]=128|g>>12&63;c[b++>>>0]=128|g>>6&63;c[b++>>>0]=128|g&63;f++}}c[b>>>0]=0;a=b-e}else a=0;return a};
|
| 37 |
+
function Ab(a,b,d,c){a>>>=0;b>>>=0;d>>>=0;c>>>=0;var e=(new Date).getFullYear(),f=(new Date(e,0,1)).getTimezoneOffset();e=(new Date(e,6,1)).getTimezoneOffset();var g=Math.max(f,e);(v(),D)[a>>>2>>>0]=60*g;(v(),C)[b>>>2>>>0]=Number(f!=e);b=l=>{var u=Math.abs(l);return`UTC${0<=l?"-":"+"}${String(Math.floor(u/60)).padStart(2,"0")}${String(u%60).padStart(2,"0")}`};a=b(f);b=b(e);e<f?(Y(a,d,17),Y(b,c,17)):(Y(a,c,17),Y(b,d,17))}var Eb=()=>Date.now(),Dd=1;
|
| 38 |
+
function Bb(a,b,d){d>>>=0;if(!(0<=a&&3>=a))return 28;if(0===a)a=Date.now();else if(Dd)a=performance.timeOrigin+performance.now();else return 52;a=Math.round(1E6*a);(v(),H)[d>>>3>>>0]=BigInt(a);return 0}var Ed=[];function Cb(a,b,d){a>>>=0;b>>>=0;d>>>=0;Ed.length=0;for(var c;c=(v(),A)[b++>>>0];){var e=105!=c;e&=112!=c;d+=e&&d%8?4:0;Ed.push(112==c?(v(),D)[d>>>2>>>0]:106==c?(v(),H)[d>>>3>>>0]:105==c?(v(),C)[d>>>2>>>0]:(v(),G)[d>>>3>>>0]);d+=e?8:4}return yd[a](...Ed)}var Db=()=>{};
|
| 39 |
+
function Fb(a,b){return p(vd(a>>>0,b>>>0))}var Gb=()=>{T+=1;throw"unwind";};function Hb(){return 4294901760}var Jb=()=>m?require("os").cpus().length:navigator.hardwareConcurrency,Z={},Fd=a=>{for(var b=0,d=0;d<a.length;++d){var c=a.charCodeAt(d);127>=c?b++:2047>=c?b+=2:55296<=c&&57343>=c?(b+=4,++d):b+=3}return b},Gd=a=>{var b;return(b=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(a))?+b[1]:(b=/:(\d+):\d+(?:\)|$)/.exec(a))?2147483648|+b[1]:0},Hd=a=>{for(var b of a)(a=Gd(b))&&(Z[a]=b)};
|
| 40 |
+
function Mb(){var a=Error().stack.toString().split("\n");"Error"==a[0]&&a.shift();Hd(a);Z.Xb=Gd(a[3]);Z.bc=a;return Z.Xb}function Kb(a){a=Z[a>>>0];if(!a)return 0;var b;if(b=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(a))a=b[1];else if(b=/^\s+at (.*) \(.*\)$/.exec(a))a=b[1];else if(b=/^(.+?)@/.exec(a))a=b[1];else return 0;Mc(Kb.Yb??0);b=Fd(a)+1;var d=Nc(b);d&&Y(a,d,b);Kb.Yb=d;return Kb.Yb}
|
| 41 |
+
function Lb(a){a>>>=0;var b=(v(),A).length;if(a<=b||4294901760<a)return!1;for(var d=1;4>=d;d*=2){var c=b*(1+.2/d);c=Math.min(c,a+100663296);a:{c=(Math.min(4294901760,65536*Math.ceil(Math.max(a,c)/65536))-x.buffer.byteLength+65535)/65536|0;try{x.grow(c);qa();var e=1;break a}catch(f){}e=void 0}if(e)return!0}return!1}
|
| 42 |
+
function Nb(a,b,d){a>>>=0;b>>>=0;if(Z.Xb==a)var c=Z.bc;else c=Error().stack.toString().split("\n"),"Error"==c[0]&&c.shift(),Hd(c);for(var e=3;c[e]&&Gd(c[e])!=a;)++e;for(a=0;a<d&&c[a+e];++a)(v(),C)[b+4*a>>>2>>>0]=Gd(c[a+e]);return a}
|
| 43 |
+
var Id={},Kd=()=>{if(!Jd){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:ca||"./this.program"},b;for(b in Id)void 0===Id[b]?delete a[b]:a[b]=Id[b];var d=[];for(b in a)d.push(`${b}=${a[b]}`);Jd=d}return Jd},Jd;function Ob(a,b){if(n)return U(19,1,a,b);a>>>=0;b>>>=0;var d=0,c=0,e;for(e of Kd()){var f=b+d;(v(),D)[a+c>>>2>>>0]=f;d+=Y(e,f,Infinity)+1;c+=4}return 0}
|
| 44 |
+
function Pb(a,b){if(n)return U(20,1,a,b);a>>>=0;b>>>=0;var d=Kd();(v(),D)[a>>>2>>>0]=d.length;a=0;for(var c of d)a+=Fd(c)+1;(v(),D)[b>>>2>>>0]=a;return 0}function Rb(a){return n?U(21,1,a):52}function Sb(a,b,d,c,e){return n?U(22,1,a,b,d,c,e):52}function Tb(a,b,d,c){return n?U(23,1,a,b,d,c):52}function Ub(a,b,d,c){return n?U(24,1,a,b,d,c):70}var Ld=[null,[],[]];
|
| 45 |
+
function Vb(a,b,d,c){if(n)return U(25,1,a,b,d,c);b>>>=0;d>>>=0;c>>>=0;for(var e=0,f=0;f<d;f++){var g=(v(),D)[b>>>2>>>0],l=(v(),D)[b+4>>>2>>>0];b+=8;for(var u=0;u<l;u++){var w=a,y=(v(),A)[g+u>>>0],B=Ld[w];0===y||10===y?((1===w?oa:p)(ud(B)),B.length=0):B.push(y)}e+=l}(v(),D)[c>>>2>>>0]=e;return 0}function Hc(a){return a>>>0}n||gd();n||(x=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),qa());h.wasmBinary&&(q=h.wasmBinary);h.stackSave=()=>N();h.stackRestore=a=>M(a);h.stackAlloc=a=>Uc(a);
|
| 46 |
+
h.setValue=function(a,b,d="i8"){d.endsWith("*")&&(d="*");switch(d){case "i1":(v(),z)[a>>>0]=b;break;case "i8":(v(),z)[a>>>0]=b;break;case "i16":(v(),Fa)[a>>>1>>>0]=b;break;case "i32":(v(),C)[a>>>2>>>0]=b;break;case "i64":(v(),H)[a>>>3>>>0]=BigInt(b);break;case "float":(v(),Ga)[a>>>2>>>0]=b;break;case "double":(v(),G)[a>>>3>>>0]=b;break;case "*":(v(),D)[a>>>2>>>0]=b;break;default:J(`invalid type for setValue: ${d}`)}};
|
| 47 |
+
h.getValue=function(a,b="i8"){b.endsWith("*")&&(b="*");switch(b){case "i1":return(v(),z)[a>>>0];case "i8":return(v(),z)[a>>>0];case "i16":return(v(),Fa)[a>>>1>>>0];case "i32":return(v(),C)[a>>>2>>>0];case "i64":return(v(),H)[a>>>3>>>0];case "float":return(v(),Ga)[a>>>2>>>0];case "double":return(v(),G)[a>>>3>>>0];case "*":return(v(),D)[a>>>2>>>0];default:J(`invalid type for getValue: ${b}`)}};h.UTF8ToString=vd;h.stringToUTF8=Y;h.lengthBytesUTF8=Fd;
|
| 48 |
+
var zd=[Ic,fd,sd,ab,bb,cb,db,eb,fb,gb,hb,ib,jb,kb,lb,mb,xb,yb,zb,Ob,Pb,Rb,Sb,Tb,Ub,Vb],yd={1042604:(a,b,d,c,e)=>{if("undefined"==typeof h||!h.Tb)return 1;a=vd(Number(a>>>0));a.startsWith("./")&&(a=a.substring(2));a=h.Tb.get(a);if(!a)return 2;b=Number(b>>>0);d=Number(d>>>0);c=Number(c>>>0);if(b+d>a.byteLength)return 3;try{const f=a.subarray(b,b+d);switch(e){case 0:(v(),A).set(f,c>>>0);break;case 1:h.ic?h.ic(c,f):h.kc(c,f);break;default:return 4}return 0}catch{return 4}},1043428:()=>"undefined"!==typeof wasmOffsetConverter};
|
| 49 |
+
function Qa(){return"undefined"!==typeof wasmOffsetConverter}var Lc,Mc,Nc,za,Ea,Oc,Pc,Qc,Rc,Sc,K,L,Tc,M,Uc,N,Vc,Wc,Xc,Yc,Zc,Pa;function cc(a,b,d,c){var e=N();try{return V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}}function bc(a,b,d){var c=N();try{return V(a)(b,d)}catch(e){M(c);if(e!==e+0)throw e;K(1,0)}}function sc(a){var b=N();try{V(a)()}catch(d){M(b);if(d!==d+0)throw d;K(1,0)}}function ac(a,b){var d=N();try{return V(a)(b)}catch(c){M(d);if(c!==c+0)throw c;K(1,0)}}
|
| 50 |
+
function uc(a,b,d){var c=N();try{V(a)(b,d)}catch(e){M(c);if(e!==e+0)throw e;K(1,0)}}function tc(a,b){var d=N();try{V(a)(b)}catch(c){M(d);if(c!==c+0)throw c;K(1,0)}}function gc(a,b,d,c,e,f,g){var l=N();try{return V(a)(b,d,c,e,f,g)}catch(u){M(l);if(u!==u+0)throw u;K(1,0)}}function yc(a,b,d,c,e,f){var g=N();try{V(a)(b,d,c,e,f)}catch(l){M(g);if(l!==l+0)throw l;K(1,0)}}function wc(a,b,d,c){var e=N();try{V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}}
|
| 51 |
+
function xc(a,b,d,c,e){var f=N();try{V(a)(b,d,c,e)}catch(g){M(f);if(g!==g+0)throw g;K(1,0)}}function zc(a,b,d,c,e,f,g){var l=N();try{V(a)(b,d,c,e,f,g)}catch(u){M(l);if(u!==u+0)throw u;K(1,0)}}function Gc(a,b,d,c,e,f,g){var l=N();try{V(a)(b,d,c,e,f,g)}catch(u){M(l);if(u!==u+0)throw u;K(1,0)}}function Fc(a,b,d,c,e,f,g,l){var u=N();try{V(a)(b,d,c,e,f,g,l)}catch(w){M(u);if(w!==w+0)throw w;K(1,0)}}function dc(a,b,d,c,e){var f=N();try{return V(a)(b,d,c,e)}catch(g){M(f);if(g!==g+0)throw g;K(1,0)}}
|
| 52 |
+
function mc(a,b,d){var c=N();try{return V(a)(b,d)}catch(e){M(c);if(e!==e+0)throw e;K(1,0)}}function Ac(a,b,d,c,e,f,g,l){var u=N();try{V(a)(b,d,c,e,f,g,l)}catch(w){M(u);if(w!==w+0)throw w;K(1,0)}}function Dc(a,b,d,c,e,f,g,l,u,w,y,B){var E=N();try{V(a)(b,d,c,e,f,g,l,u,w,y,B)}catch(F){M(E);if(F!==F+0)throw F;K(1,0)}}function qc(a,b,d){var c=N();try{return V(a)(b,d)}catch(e){M(c);if(e!==e+0)throw e;K(1,0);return 0n}}
|
| 53 |
+
function Bc(a,b,d,c,e,f,g,l,u){var w=N();try{V(a)(b,d,c,e,f,g,l,u)}catch(y){M(w);if(y!==y+0)throw y;K(1,0)}}function $b(a){var b=N();try{return V(a)()}catch(d){M(b);if(d!==d+0)throw d;K(1,0)}}function pc(a,b){var d=N();try{return V(a)(b)}catch(c){M(d);if(c!==c+0)throw c;K(1,0);return 0n}}function nc(a,b,d,c){var e=N();try{return V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}}function oc(a){var b=N();try{return V(a)()}catch(d){M(b);if(d!==d+0)throw d;K(1,0);return 0n}}
|
| 54 |
+
function lc(a,b,d,c){var e=N();try{return V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}}function kc(a,b,d,c,e){var f=N();try{return V(a)(b,d,c,e)}catch(g){M(f);if(g!==g+0)throw g;K(1,0)}}function jc(a,b,d,c,e,f){var g=N();try{return V(a)(b,d,c,e,f)}catch(l){M(g);if(l!==l+0)throw l;K(1,0)}}function fc(a,b,d,c,e,f){var g=N();try{return V(a)(b,d,c,e,f)}catch(l){M(g);if(l!==l+0)throw l;K(1,0)}}
|
| 55 |
+
function ec(a,b,d,c,e,f){var g=N();try{return V(a)(b,d,c,e,f)}catch(l){M(g);if(l!==l+0)throw l;K(1,0)}}function hc(a,b,d,c,e,f,g,l){var u=N();try{return V(a)(b,d,c,e,f,g,l)}catch(w){M(u);if(w!==w+0)throw w;K(1,0)}}function rc(a,b,d,c,e){var f=N();try{return V(a)(b,d,c,e)}catch(g){M(f);if(g!==g+0)throw g;K(1,0);return 0n}}function Zb(a,b,d,c){var e=N();try{return V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}}
|
| 56 |
+
function Xb(a,b,d,c){var e=N();try{return V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}}function ic(a,b,d,c,e,f,g,l,u,w,y,B){var E=N();try{return V(a)(b,d,c,e,f,g,l,u,w,y,B)}catch(F){M(E);if(F!==F+0)throw F;K(1,0)}}function Cc(a,b,d,c,e,f,g,l,u,w,y){var B=N();try{V(a)(b,d,c,e,f,g,l,u,w,y)}catch(E){M(B);if(E!==E+0)throw E;K(1,0)}}function Ec(a,b,d,c,e,f,g,l,u,w,y,B,E,F,Md,Nd){var Od=N();try{V(a)(b,d,c,e,f,g,l,u,w,y,B,E,F,Md,Nd)}catch(Ma){M(Od);if(Ma!==Ma+0)throw Ma;K(1,0)}}
|
| 57 |
+
function Yb(a,b,d){var c=N();try{return V(a)(b,d)}catch(e){M(c);if(e!==e+0)throw e;K(1,0)}}function Wb(a,b,d){var c=N();try{return V(a)(b,d)}catch(e){M(c);if(e!==e+0)throw e;K(1,0)}}function vc(a,b,d,c){var e=N();try{V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}}function Jc(){var a=I;a=Object.assign({},a);var b=c=>()=>c()>>>0,d=c=>e=>c(e)>>>0;a.ub=b(a.ub);a.wb=d(a.wb);a.Kb=d(a.Kb);a.Lb=b(a.Lb);a.Pb=d(a.Pb);return a}
|
| 58 |
+
function xa(){if(0<O)P=xa;else if(n)ra?.(h),Ia();else{for(var a=bd;0<a.length;)a.shift()(h);0<O?P=xa:(h.calledRun=!0,pa||(Ia(),ra?.(h)))}}var I;n||(I=await (wa()),xa());h.PTR_SIZE=4;Ha?moduleRtn=h:moduleRtn=new Promise((a,b)=>{ra=a;sa=b});
|
| 59 |
+
;return moduleRtn}export default ortWasmThreaded;var isPthread=globalThis.self?.name?.startsWith("em-pthread");var isNode=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(isNode)isPthread=(await import("worker_threads")).workerData==="em-pthread";isPthread&&ortWasmThreaded();
|
vendor/ort/ort-wasm-simd-threaded.wasm
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3398c10d07d229bd91b364548e130e0e51a8e5704b88c7c083ebbeb78842dee2
|
| 3 |
+
size 14239897
|
vendor/ort/ort.wasm.min.mjs
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*!
|
| 2 |
+
* ONNX Runtime Web v1.30.0
|
| 3 |
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
* Licensed under the MIT License.
|
| 5 |
+
*/
|
| 6 |
+
var Ve=Object.defineProperty;var On=Object.getOwnPropertyDescriptor;var Ln=Object.getOwnPropertyNames;var Pn=Object.prototype.hasOwnProperty;var Je=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var E=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var qe=(e,t)=>{for(var n in t)Ve(e,n,{get:t[n],enumerable:!0})},Dn=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ln(t))!Pn.call(e,r)&&r!==n&&Ve(e,r,{get:()=>t[r],enumerable:!(o=On(t,r))||o.enumerable});return e};var wt=e=>Dn(Ve({},"__esModule",{value:!0}),e);var Se,q,pe,_n,ht,Ye=E(()=>{"use strict";Se=new Map,q=[],pe=(e,t,n)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let o=Se.get(e);if(o===void 0)Se.set(e,{backend:t,priority:n});else{if(o.priority>n)return;if(o.priority===n&&o.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let r=q.indexOf(e);r!==-1&&q.splice(r,1);for(let i=0;i<q.length;i++)if(Se.get(q[i]).priority<=n){q.splice(i,0,e);return}q.push(e)}return}throw new TypeError("not a valid backend")},_n=async e=>{let t=Se.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(o){return n||(t.error=`${o}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ht=async e=>{let t=e.executionProviders||[],n=t.map(u=>typeof u=="string"?u:u.name),o=n.length===0?q:n,r,i=[],s=new Set;for(let u of o){let f=await _n(u);typeof f=="string"?i.push({name:u,err:f}):(r||(r=f),r===f&&s.add(u))}if(!r)throw new Error(`no available backend found. ERR: ${i.map(u=>`[${u.name}] ${u.err}`).join(", ")}`);for(let{name:u,err:f}of i)n.includes(u)&&console.warn(`removing requested execution provider "${u}" from session options because it is not available: ${f}`);let a=t.filter(u=>s.has(typeof u=="string"?u:u.name));return[r,new Proxy(e,{get:(u,f)=>f==="executionProviders"?a:Reflect.get(u,f)})]}});var bt=E(()=>{"use strict";Ye()});var yt,gt=E(()=>{"use strict";yt="1.30.0"});var Et,D,Ze=E(()=>{"use strict";gt();Et="warning",D={wasm:{},webgl:{},webgpu:{},versions:{common:yt},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Et=e}},get logLevel(){return Et}};Object.defineProperty(D,"logLevel",{enumerable:!0})});var B,St=E(()=>{"use strict";Ze();B=D});var Tt,It,At=E(()=>{"use strict";Tt=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let o=n.getContext("2d");if(o!=null){let r,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(r=e.dims[2],i=e.dims[3]):(r=e.dims[3],i=e.dims[2]);let s=t?.format!==void 0?t.format:"RGB",a=t?.norm,u,f;a===void 0||a.mean===void 0?u=[255,255,255,255]:typeof a.mean=="number"?u=[a.mean,a.mean,a.mean,a.mean]:(u=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(u[3]=a.mean[3])),a===void 0||a.bias===void 0?f=[0,0,0,0]:typeof a.bias=="number"?f=[a.bias,a.bias,a.bias,a.bias]:(f=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(f[3]=a.bias[3]));let l=i*r,c=0,d=l,p=l*2,h=-1;s==="RGBA"?(c=0,d=l,p=l*2,h=l*3):s==="RGB"?(c=0,d=l,p=l*2):s==="RBG"&&(c=0,p=l,d=l*2);for(let b=0;b<i;b++)for(let A=0;A<r;A++){let m=(e.data[c++]-f[0])*u[0],w=(e.data[d++]-f[1])*u[1],O=(e.data[p++]-f[2])*u[2],g=h===-1?255:(e.data[h++]-f[3])*u[3];o.fillStyle="rgba("+m+","+w+","+O+","+g+")",o.fillRect(A,b,1,1)}if("toDataURL"in n)return n.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},It=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),o;if(n!=null){let r,i,s;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(r=e.dims[2],i=e.dims[1],s=e.dims[3]):(r=e.dims[3],i=e.dims[2],s=e.dims[1]);let a=t!==void 0&&t.format!==void 0?t.format:"RGB",u=t?.norm,f,l;u===void 0||u.mean===void 0?f=[255,255,255,255]:typeof u.mean=="number"?f=[u.mean,u.mean,u.mean,u.mean]:(f=[u.mean[0],u.mean[1],u.mean[2],255],u.mean[3]!==void 0&&(f[3]=u.mean[3])),u===void 0||u.bias===void 0?l=[0,0,0,0]:typeof u.bias=="number"?l=[u.bias,u.bias,u.bias,u.bias]:(l=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(l[3]=u.bias[3]));let c=i*r;if(t!==void 0&&(t.format!==void 0&&s===4&&t.format!=="RGBA"||s===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,p=0,h=1,b=2,A=3,m=0,w=c,O=c*2,g=-1;a==="RGBA"?(m=0,w=c,O=c*2,g=c*3):a==="RGB"?(m=0,w=c,O=c*2):a==="RBG"&&(m=0,O=c,w=c*2),o=n.createImageData(r,i);for(let T=0;T<i*r;p+=d,h+=d,b+=d,A+=d,T++)o.data[p]=(e.data[m++]-l[0])*f[0],o.data[h]=(e.data[w++]-l[1])*f[1],o.data[b]=(e.data[O++]-l[2])*f[2],o.data[A]=g===-1?255:(e.data[g++]-l[3])*f[3]}else throw new Error("Can not access image data");return o}});var Xe,Bt,Ot,Lt,Pt,Dt,_t=E(()=>{"use strict";Te();Xe=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:n,width:o}=t,r=t.norm??{mean:255,bias:0},i,s;typeof r.mean=="number"?i=[r.mean,r.mean,r.mean,r.mean]:i=[r.mean[0],r.mean[1],r.mean[2],r.mean[3]??255],typeof r.bias=="number"?s=[r.bias,r.bias,r.bias,r.bias]:s=[r.bias[0],r.bias[1],r.bias[2],r.bias[3]??0];let a=t.format!==void 0?t.format:"RGBA",u=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",f=n*o,l=u==="RGBA"?new Float32Array(f*4):new Float32Array(f*3),c=4,d=0,p=1,h=2,b=3,A=0,m=f,w=f*2,O=-1;a==="RGB"&&(c=3,d=0,p=1,h=2,b=-1),u==="RGBA"?O=f*3:u==="RBG"?(A=0,w=f,m=f*2):u==="BGR"&&(w=0,m=f,A=f*2);for(let T=0;T<f;T++,d+=c,h+=c,p+=c,b+=c)l[A++]=(e[d]+s[0])/i[0],l[m++]=(e[p]+s[1])/i[1],l[w++]=(e[h]+s[2])/i[2],O!==-1&&b!==-1&&(l[O++]=(e[b]+s[3])/i[3]);return u==="RGBA"?new v("float32",l,[1,4,n,o]):new v("float32",l,[1,3,n,o])},Bt=async(e,t)=>{let n=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,o=typeof ImageData<"u"&&e instanceof ImageData,r=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,i=typeof e=="string",s,a=t??{},u=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},f=l=>typeof HTMLCanvasElement<"u"&&l instanceof HTMLCanvasElement||l instanceof OffscreenCanvas?l.getContext("2d"):null;if(n){let l=u();l.width=e.width,l.height=e.height;let c=f(l);if(c!=null){let d=e.height,p=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(d=t.resizedHeight,p=t.resizedWidth),t!==void 0){if(a=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=d,a.width=p}else a.tensorFormat="RGBA",a.height=d,a.width=p;c.drawImage(e,0,0),s=c.getImageData(0,0,p,d).data}else throw new Error("Can not access image data")}else if(o){let l,c;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(l=t.resizedHeight,c=t.resizedWidth):(l=e.height,c=e.width),t!==void 0&&(a=t),a.format="RGBA",a.height=l,a.width=c,t!==void 0){let d=u();d.width=c,d.height=l;let p=f(d);if(p!=null)p.putImageData(e,0,0),s=p.getImageData(0,0,c,l).data;else throw new Error("Can not access image data")}else s=e.data}else if(r){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let l=u();l.width=e.width,l.height=e.height;let c=f(l);if(c!=null){let d=e.height,p=e.width;return c.drawImage(e,0,0,p,d),s=c.getImageData(0,0,p,d).data,a.height=d,a.width=p,Xe(s,a)}else throw new Error("Can not access image data")}else{if(i)return new Promise((l,c)=>{let d=u(),p=f(d);if(!e||!p)return c();let h=new Image;h.crossOrigin="Anonymous",h.src=e,h.onload=()=>{d.width=h.width,d.height=h.height,p.drawImage(h,0,0,d.width,d.height);let b=p.getImageData(0,0,d.width,d.height);a.height=d.height,a.width=d.width,l(Xe(b.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return Xe(s,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Ot=(e,t)=>{let{width:n,height:o,download:r,dispose:i}=t,s=[1,o,n,4];return new v({location:"texture",type:"float32",texture:e,dims:s,download:r,dispose:i})},Lt=(e,t)=>{let{dataType:n,dims:o,download:r,dispose:i}=t;return new v({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:o,download:r,dispose:i})},Pt=(e,t)=>{let{dataType:n,dims:o,download:r,dispose:i}=t;return new v({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:o,download:r,dispose:i})},Dt=(e,t,n)=>new v({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})});var Y,me,Ut,xt,vt=E(()=>{"use strict";Y=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),me=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Ut=!1,xt=()=>{if(!Ut){Ut=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,o=typeof n<"u"&&n.from;e&&(Y.set("int64",BigInt64Array),me.set(BigInt64Array,"int64")),t&&(Y.set("uint64",BigUint64Array),me.set(BigUint64Array,"uint64")),o?(Y.set("float16",n),me.set(n,"float16")):Y.set("float16",Uint16Array)}}});var Ct,Mt,Rt=E(()=>{"use strict";Te();Ct=e=>{let t=1;for(let n=0;n<e.length;n++){let o=e[n];if(typeof o!="number"||!Number.isSafeInteger(o))throw new TypeError(`dims[${n}] must be an integer, got: ${o}`);if(o<0)throw new RangeError(`dims[${n}] must be a non-negative integer, got: ${o}`);t*=o}return t},Mt=(e,t)=>{switch(e.location){case"cpu":return new v(e.type,e.data,t);case"cpu-pinned":return new v({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new v({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new v({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new v({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}});var v,Te=E(()=>{"use strict";At();_t();vt();Rt();v=class{constructor(t,n,o){xt();let r,i;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,r=t.type,i=t.dims,t.location){case"cpu-pinned":{let a=Y.get(r);if(!a)throw new TypeError(`unsupported type "${r}" 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(r!=="float32")throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="uint8"&&r!=="bool"&&r!=="uint4"&&r!=="int4")throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="uint64"&&r!=="int8"&&r!=="uint8"&&r!=="bool"&&r!=="uint4"&&r!=="int4")throw new TypeError(`unsupported type "${r}" 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,u;if(typeof t=="string")if(r=t,u=o,t==="string"){if(!Array.isArray(n))throw new TypeError("A string tensor's data must be a string array.");a=n}else{let f=Y.get(t);if(f===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(n)){if(t==="float16"&&f===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${f.name} as data.`);t==="uint64"||t==="int64"?a=f.from(n,BigInt):a=f.from(n)}else if(n instanceof f)a=n;else if(n instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(n);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&n instanceof Uint16Array&&f!==Uint16Array)a=new globalThis.Float16Array(n.buffer,n.byteOffset,n.length);else throw new TypeError(`A ${r} tensor's data must be type of ${f}`)}else if(u=n,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let f=typeof t[0];if(f==="string")r="string",a=t;else if(f==="boolean")r="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${f}.`)}else if(t instanceof Uint8ClampedArray)r="uint8",a=Uint8Array.from(t);else{let f=me.get(t.constructor);if(f===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);r=f,a=t}if(u===void 0)u=[a.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");i=u,this.cpuData=a,this.dataLocation="cpu"}let s=Ct(i);if(this.cpuData&&s!==this.cpuData.length&&!((r==="uint4"||r==="int4")&&Math.ceil(s/2)===this.cpuData.length))throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=s}static async fromImage(t,n){return Bt(t,n)}static fromTexture(t,n){return Ot(t,n)}static fromGpuBuffer(t,n){return Lt(t,n)}static fromMLTensor(t,n){return Pt(t,n)}static fromPinnedBuffer(t,n,o){return Dt(t,n,o)}toDataURL(t){return Tt(this,t)}toImageData(t){return It(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 n=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=n,t&&this.disposer&&(this.disposer(),this.disposer=void 0),n}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 Mt(this,t)}}});var G,Ke=E(()=>{"use strict";Te();G=v});var Nt,Ft,Z,X,K,Q,Qe=E(()=>{"use strict";Ze();Nt=(e,t)=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||console.timeStamp(`${e}::ORT::${t}`)},Ft=(e,t)=>{let n=new Error().stack?.split(/\r\n|\r|\n/g)||[],o=!1;for(let r=0;r<n.length;r++){if(o&&!n[r].includes("TRACE_FUNC")){let i=`FUNC_${e}::${n[r].trim().split(" ")[1]}`;t&&(i+=`::${t}`),Nt("CPU",i);return}n[r].includes("TRACE_FUNC")&&(o=!0)}},Z=e=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||Ft("BEGIN",e)},X=e=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||Ft("END",e)},K=e=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||console.time(`ORT::${e}`)},Q=e=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||console.timeEnd(`ORT::${e}`)}});var Ie,kt=E(()=>{"use strict";Ye();Ke();Qe();Ie=class e{constructor(t){this.handler=t}async run(t,n,o){Z(),K("InferenceSession.run");let r={},i={};if(typeof t!="object"||t===null||t instanceof G||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof G)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");s=!1;for(let f of n){if(typeof f!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(f)===-1)throw new RangeError(`'fetches' contains invalid output name: ${f}.`);r[f]=null}if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else{let f=!1,l=Object.getOwnPropertyNames(n);for(let c of this.outputNames)if(l.indexOf(c)!==-1){let d=n[c];(d===null||d instanceof G)&&(f=!0,s=!1,r[c]=d)}if(f){if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else i=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let f of this.inputNames)if(typeof t[f]>"u")throw new Error(`input '${f}' is missing in 'feeds'.`);if(s)for(let f of this.outputNames)r[f]=null;let a=await this.handler.run(t,r,i),u={};for(let f in a)if(Object.hasOwnProperty.call(a,f)){let l=a[f];l instanceof G?u[f]=l:u[f]=new G(l.type,l.data,l.dims)}return Q("InferenceSession.run"),X(),u}async release(){return this.handler.dispose()}static async create(t,n,o,r){Z(),K("InferenceSession.create");let i,s={};if(typeof t=="string"){if(i=t,typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(i=t,typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let l=t,c=0,d=t.byteLength;if(typeof n=="object"&&n!==null)s=n;else if(typeof n=="number"){if(c=n,!Number.isSafeInteger(c))throw new RangeError("'byteOffset' must be an integer.");if(c<0||c>=l.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${l.byteLength}).`);if(d=t.byteLength-c,typeof o=="number"){if(d=o,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||c+d>l.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${l.byteLength-c}].`);if(typeof r=="object"&&r!==null)s=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(typeof o<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(l,c,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,u]=await ht(s),f=await a.createInferenceSessionHandler(i,u);return Q("InferenceSession.create"),X(),new e(f)}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}}});var Un,Wt=E(()=>{"use strict";kt();Un=Ie});var Gt=E(()=>{"use strict"});var $t=E(()=>{"use strict"});var zt=E(()=>{"use strict"});var Ht=E(()=>{"use strict"});var et={};qe(et,{InferenceSession:()=>Un,TRACE:()=>Nt,TRACE_EVENT_BEGIN:()=>K,TRACE_EVENT_END:()=>Q,TRACE_FUNC_BEGIN:()=>Z,TRACE_FUNC_END:()=>X,Tensor:()=>G,env:()=>B,registerBackend:()=>pe});var J=E(()=>{"use strict";bt();St();Wt();Ke();Gt();$t();Qe();zt();Ht()});var Ae=E(()=>{"use strict"});var qt={};qe(qt,{default:()=>xn});var Vt,Jt,xn,Yt=E(()=>{"use strict";tt();ee();Be();Vt="ort-wasm-proxy-worker",Jt=globalThis.self?.name===Vt;Jt&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":Oe(n.wasm).then(()=>{Le(n).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:r}=n;Pe(r,o).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:o}=n,r=we(o);postMessage({type:t,out:r});break}case"create":{let{model:o,options:r}=n;De(o,r).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":_e(n),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:r,inputs:i,outputIndices:s,options:a}=n;Ue(o,r,i,s,new Array(s.length).fill(null),a).then(u=>{u.some(f=>f[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:u},ve([...i,...u]))},u=>{postMessage({type:t,err:u})});break}case"end-profiling":xe(n),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}});xn=Jt?null:e=>new Worker(e??R,{type:"module",name:Vt})});var Kt,vn,Cn,R,Ce,nt,Mn,Rn,Qt,Nn,Zt,en,Xt,tn,Be=E(()=>{"use strict";Ae();Kt=typeof location>"u"?void 0:location.origin,vn=import.meta.url>"file:"&&import.meta.url<"file;",Cn=()=>{if(!!1){if(vn){let e=URL;return new URL(new e("ort.wasm.min.mjs",import.meta.url).href,Kt).href}return import.meta.url}},R=Cn(),Ce=()=>{if(R&&!R.startsWith("blob:"))return R.substring(0,R.lastIndexOf("/")+1)},nt=(e,t)=>{try{let n=t??R;return(n?new URL(e,n):new URL(e)).origin===Kt}catch{return!1}},Mn=(e,t)=>{let n=t??R;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Rn=(e,t)=>`${t??"./"}${e}`,Qt=async e=>{let n=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},Nn=async e=>(await import(/*webpackIgnore:true*/ /*@vite-ignore*/e)).default,Zt=(Yt(),wt(qt)).default,en=async()=>{if(!R)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(nt(R))return[void 0,Zt()];let e=await Qt(R);return[e,Zt(e)]},Xt=void 0,tn=async(e,t,n,o)=>{let r=Xt&&!(e||t);if(r)if(R)r=nt(R)||o&&!n;else if(o&&!n)r=!0;else throw new Error("cannot determine the script source URL.");if(r)return[void 0,Xt];{let i="ort-wasm-simd-threaded.mjs",s=e??Mn(i,t),a=!!1&&n&&s&&!nt(s,t),u=a?await Qt(s):s??Rn(i,t);return[a?u:void 0,await Nn(u)]}}});var rt,ot,Me,nn,Fn,kn,Wn,Oe,I,ee=E(()=>{"use strict";Be();ot=!1,Me=!1,nn=!1,Fn=()=>{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}},kn=()=>{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}},Wn=()=>{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}},Oe=async e=>{if(ot)return Promise.resolve();if(Me)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(nn)throw new Error("previous call to 'initializeWebAssembly()' failed.");Me=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Wn())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!kn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let o=Fn();n>1&&!o&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", 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."),e.numThreads=n=1);let r=e.wasmPaths,i=typeof r=="string"?r:void 0,s=r?.mjs,a=s?.href??s,u=r?.wasm,f=u?.href??u,l=e.wasmBinary,[c,d]=await tn(a,i,n>1,!!l||!!f),p=!1,h=[];if(t>0&&h.push(new Promise(b=>{setTimeout(()=>{p=!0,b()},t)})),h.push(new Promise((b,A)=>{let m={numThreads:n};if(l)m.wasmBinary=l,m.locateFile=w=>w;else if(f||i)m.locateFile=w=>f??i+w;else if(a&&a.indexOf("blob:")!==0)m.locateFile=w=>new URL(w,a).href;else if(c){let w=Ce();w&&(m.locateFile=O=>w+O)}d(m).then(w=>{Me=!1,ot=!0,rt=w,b(),c&&URL.revokeObjectURL(c)},w=>{Me=!1,nn=!0,A(w)})})),await Promise.race(h),p)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},I=()=>{if(ot&&rt)return rt;throw new Error("WebAssembly is not initialized yet.")}});var N,he,S,Re=E(()=>{"use strict";ee();N=(e,t)=>{let n=I(),o=n.lengthBytesUTF8(e)+1,r=n._malloc(o);return n.stringToUTF8(e,r,o),t.push(r),r},he=(e,t,n,o)=>{if(typeof e=="object"&&e!==null){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach(([r,i])=>{let s=t?t+r:r;if(typeof i=="object")he(i,s+".",n,o);else if(typeof i=="string"||typeof i=="number")o(s,i.toString());else if(typeof i=="boolean")o(s,i?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},S=e=>{let t=I(),n=t.stackSave();try{let o=t.PTR_SIZE,r=t.stackAlloc(2*o);t._OrtGetLastError(r,r+o);let i=Number(t.getValue(r,o===4?"i32":"i64")),s=t.getValue(r+o,"*"),a=s?t.UTF8ToString(s):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${a}`)}finally{t.stackRestore(n)}}});var rn,on=E(()=>{"use strict";ee();Re();rn=e=>{let t=I(),n=0,o=[],r=e||{};try{if(e?.logSeverityLevel===void 0)r.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)r.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(r.terminate=!1);let i=0;return e?.tag!==void 0&&(i=N(e.tag,o)),n=t._OrtCreateRunOptions(r.logSeverityLevel,r.logVerbosityLevel,!!r.terminate,i),n===0&&S("Can't create run options."),e?.extra!==void 0&&he(e.extra,"",new WeakSet,(s,a)=>{let u=N(s,o),f=N(a,o);t._OrtAddRunConfigEntry(n,u,f)!==0&&S(`Can't set a run config entry: ${s} - ${a}.`)}),[n,o]}catch(i){throw n!==0&&t._OrtReleaseRunOptions(n),o.forEach(s=>t._free(s)),i}}});var Gn,$n,zn,se,Hn,sn,an=E(()=>{"use strict";ee();Re();Gn=e=>{switch(e){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: ${e}`)}},$n=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},zn=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(e.enableMemPattern=!1)},se=(e,t,n,o)=>{let r=N(t,o),i=N(n,o);I()._OrtAddSessionConfigEntry(e,r,i)!==0&&S(`Can't set a session config entry: ${t} - ${n}.`)},Hn=async(e,t,n)=>{let o=t.executionProviders;for(let r of o){let i=typeof r=="string"?r:r.name,s=[];switch(i){case"webnn":if(i="WEBNN",se(e,"session.disable_quant_qdq","1",n),se(e,"session.disable_qdq_constant_folding","1",n),typeof r!="string"){let d=r?.deviceType;d&&se(e,"deviceType",d,n)}break;case"webgpu":if(i="JS",typeof r!="string"){let c=r;if(c?.preferredLayout){if(c.preferredLayout!=="NCHW"&&c.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${c.preferredLayout}`);se(e,"preferredLayout",c.preferredLayout,n)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let a=N(i,n),u=s.length,f=0,l=0;if(u>0){f=I()._malloc(u*I().PTR_SIZE),n.push(f),l=I()._malloc(u*I().PTR_SIZE),n.push(l);for(let c=0;c<u;c++)I().setValue(f+c*I().PTR_SIZE,s[c][0],"*"),I().setValue(l+c*I().PTR_SIZE,s[c][1],"*")}await I()._OrtAppendExecutionProvider(e,a,f,l,u)!==0&&S(`Can't append execution provider: ${i}.`)}},sn=async e=>{let t=I(),n=0,o=[],r=e||{};zn(r);try{let i=Gn(r.graphOptimizationLevel??"all"),s=$n(r.executionMode??"sequential"),a=typeof r.logId=="string"?N(r.logId,o):0,u=r.logSeverityLevel??2;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log severity level is not valid: ${u}`);let f=r.logVerbosityLevel??0;if(!Number.isInteger(f)||f<0||f>4)throw new Error(`log verbosity level is not valid: ${f}`);let l=typeof r.optimizedModelFilePath=="string"?N(r.optimizedModelFilePath,o):0;if(n=t._OrtCreateSessionOptions(i,!!r.enableCpuMemArena,!!r.enableMemPattern,s,!!r.enableProfiling,0,a,u,f,l),n===0&&S("Can't create session options."),r.executionProviders&&await Hn(n,r,o),r.enableGraphCapture!==void 0){if(typeof r.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${r.enableGraphCapture}`);se(n,"enableGraphCapture",r.enableGraphCapture.toString(),o)}if(r.freeDimensionOverrides)for(let[c,d]of Object.entries(r.freeDimensionOverrides)){if(typeof c!="string")throw new Error(`free dimension override name must be a string: ${c}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let p=N(c,o);t._OrtAddFreeDimensionOverride(n,p,d)!==0&&S(`Can't set a free dimension override: ${c} - ${d}.`)}return r.extra!==void 0&&he(r.extra,"",new WeakSet,(c,d)=>{se(n,c,d,o)}),[n,o]}catch(i){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&S("Can't release session options."),o.forEach(s=>t._free(s)),i}}});var ie,Ne,ae,un,fn,Fe,ke,cn,st=E(()=>{"use strict";ie=e=>{switch(e){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: ${e}`)}},Ne=e=>{switch(e){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: ${e}`)}},ae=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],o=typeof t=="number"?t:t.reduce((r,i)=>r*i,1);return n>0?Math.ceil(o*n):void 0},un=e=>{switch(e){case"float16":return typeof Float16Array<"u"?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: ${e}`)}},fn=e=>{switch(e){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: ${e}`)}},Fe=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",ke=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",cn=e=>{switch(e){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: ${e}`)}}});var be,it=E(()=>{"use strict";Ae();be=async e=>{if(typeof e=="string")if(!1)try{let{readFile:t}=Je("node:fs/promises");return new Uint8Array(await t(e))}catch(t){if(t.code==="ERR_FS_FILE_TOO_LARGE"){let{createReadStream:n}=Je("node:fs"),o=n(e),r=[];for await(let i of o)r.push(i);return new Uint8Array(Buffer.concat(r))}throw t}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let n=t.headers.get("Content-Length"),o=n?parseInt(n,10):0;if(o<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let r=t.body.getReader(),i;try{i=new ArrayBuffer(o)}catch(a){if(a instanceof RangeError){let u=Math.ceil(o/65536);i=new WebAssembly.Memory({initial:u,maximum:u}).buffer}else throw a}let s=0;for(;;){let{done:a,value:u}=await r.read();if(a)break;let f=u.byteLength;new Uint8Array(i,s,f).set(u),s+=f}return new Uint8Array(i,0,o)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}});var jn,Le,Pe,ue,Vn,dn,we,De,_e,ln,Ue,xe,ve,tt=E(()=>{"use strict";J();on();an();st();ee();Re();it();jn=(e,t)=>{I()._OrtInit(e,t)!==0&&S("Can't initialize onnxruntime.")},Le=async e=>{jn(e.wasm.numThreads,fn(e.logLevel))},Pe=async(e,t)=>{I().asyncInit?.();let n=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!=="low-power"&&o!=="high-performance")throw new Error(`Invalid powerPreference setting: "${o}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:o,forceFallbackAdapter:r}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},ue=new Map,Vn=e=>{let t=I(),n=t.stackSave();try{let o=t.PTR_SIZE,r=t.stackAlloc(2*o);t._OrtGetInputOutputCount(e,r,r+o)!==0&&S("Can't get session input/output count.");let s=o===4?"i32":"i64";return[Number(t.getValue(r,s)),Number(t.getValue(r+o,s))]}finally{t.stackRestore(n)}},dn=(e,t)=>{let n=I(),o=n.stackSave(),r=0;try{let i=n.PTR_SIZE,s=n.stackAlloc(2*i);n._OrtGetInputOutputMetadata(e,t,s,s+i)!==0&&S("Can't get session input/output metadata.");let u=Number(n.getValue(s,"*"));r=Number(n.getValue(s+i,"*"));let f=n.HEAP32[r/4];if(f===0)return[u,0];let l=n.HEAPU32[r/4+1],c=[];for(let d=0;d<l;d++){let p=Number(n.getValue(r+8+d*i,"*"));c.push(p!==0?n.UTF8ToString(p):Number(n.getValue(r+8+(d+l)*i,"*")))}return[u,f,c]}finally{n.stackRestore(o),r!==0&&n._OrtFree(r)}},we=e=>{let t=I(),n=t._malloc(e.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},De=async(e,t)=>{let n,o,r=I();Array.isArray(e)?[n,o]=e:e.buffer===r.HEAPU8.buffer?[n,o]=[e.byteOffset,e.byteLength]:[n,o]=we(e);let i=0,s=0,a=0,u=[],f=[],l=[];try{if([s,u]=await sn(t),t?.externalData&&r.mountExternalData){let g=[];for(let T of t.externalData){let x=typeof T=="string"?T:T.path,M=typeof T=="string"?T:T.data;g.push(be(M).then(_=>{r.mountExternalData(x,_)}))}await Promise.all(g)}for(let g of t?.executionProviders??[])if((typeof g=="string"?g:g.name)==="webnn"){if(r.shouldTransferToMLTensor=!1,typeof g!="string"){let x=g,M=x?.context,_=x?.gpuDevice,de=x?.deviceType,re=x?.powerPreference;M?r.currentContext=M:_?r.currentContext=await r.webnnCreateMLContext(_):r.currentContext=await r.webnnCreateMLContext({deviceType:de,powerPreference:re})}else r.currentContext=await r.webnnCreateMLContext();break}i=await r._OrtCreateSession(n,o,s),r.webgpuOnCreateSession?.(i),i===0&&S("Can't create a session."),r.jsepOnCreateSession?.(),r.currentContext&&(r.webnnRegisterMLContext(i,r.currentContext),r.currentContext=void 0,r.shouldTransferToMLTensor=!0);let[c,d]=Vn(i),p=!!t?.enableGraphCapture,h=[],b=[],A=[],m=[],w=[];for(let g=0;g<c;g++){let[T,x,M]=dn(i,g);T===0&&S("Can't get an input name."),f.push(T);let _=r.UTF8ToString(T);h.push(_),A.push(x===0?{name:_,isTensor:!1}:{name:_,isTensor:!0,type:Ne(x),shape:M})}for(let g=0;g<d;g++){let[T,x,M]=dn(i,g+c);T===0&&S("Can't get an output name."),l.push(T);let _=r.UTF8ToString(T);b.push(_),m.push(x===0?{name:_,isTensor:!1}:{name:_,isTensor:!0,type:Ne(x),shape:M})}return ue.set(i,[i,f,l,null,p,!1]),[i,h,b,A,m]}catch(c){throw f.forEach(d=>r._OrtFree(d)),l.forEach(d=>r._OrtFree(d)),a!==0&&r._OrtReleaseBinding(a)!==0&&S("Can't release IO binding."),i!==0&&r._OrtReleaseSession(i)!==0&&S("Can't release session."),c}finally{r._free(n),s!==0&&r._OrtReleaseSessionOptions(s)!==0&&S("Can't release session options."),u.forEach(c=>r._free(c)),r.unmountExternalData?.()}},_e=e=>{let t=I(),n=ue.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[o,r,i,s,a]=n;s&&(a&&t._OrtClearBoundOutputs(s.handle)!==0&&S("Can't clear bound outputs."),t._OrtReleaseBinding(s.handle)!==0&&S("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),r.forEach(u=>t._OrtFree(u)),i.forEach(u=>t._OrtFree(u)),t._OrtReleaseSession(o)!==0&&S("Can't release session."),ue.delete(e)},ln=async(e,t,n,o,r,i,s=!1)=>{if(!e){t.push(0);return}let a=I(),u=a.PTR_SIZE,f=e[0],l=e[1],c=e[3],d=c,p,h;if(f==="string"&&(c==="gpu-buffer"||c==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(s&&c!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(c==="gpu-buffer"){let m=e[2].gpuBuffer;h=ae(ie(f),l);{let w=a.jsepRegisterBuffer;if(!w)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');p=w(o,i,m,h)}}else if(c==="ml-tensor"){let m=e[2].mlTensor;h=ae(ie(f),l);let w=a.webnnRegisterMLTensor;if(!w)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');p=w(o,m,ie(f),l)}else{let m=e[2];if(Array.isArray(m)){h=u*m.length,p=a._malloc(h),n.push(p);for(let w=0;w<m.length;w++){if(typeof m[w]!="string")throw new TypeError(`tensor data at index ${w} is not a string`);a.setValue(p+w*u,N(m[w],n),"*")}}else{let w=a.webnnIsGraphInput,O=a.webnnIsGraphOutput;if(f!=="string"&&w&&O){let g=a.UTF8ToString(r);if(w(o,g)||O(o,g)){let T=ie(f);h=ae(T,l),d="ml-tensor";let x=a.webnnCreateTemporaryTensor,M=a.webnnUploadTensor;if(!x||!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let _=await x(o,T,l);M(_,new Uint8Array(m.buffer,m.byteOffset,m.byteLength)),p=_}else h=m.byteLength,p=a._malloc(h),n.push(p),a.HEAPU8.set(new Uint8Array(m.buffer,m.byteOffset,h),p)}else h=m.byteLength,p=a._malloc(h),n.push(p),a.HEAPU8.set(new Uint8Array(m.buffer,m.byteOffset,h),p)}}let b=a.stackSave(),A=a.stackAlloc(4*l.length);try{l.forEach((w,O)=>a.setValue(A+O*u,w,u===4?"i32":"i64"));let m=a._OrtCreateTensor(ie(f),p,h,A,l.length,cn(d));m===0&&S(`Can't create tensor for input/output. session=${o}, index=${i}.`),t.push(m)}finally{a.stackRestore(b)}},Ue=async(e,t,n,o,r,i)=>{let s=I(),a=s.PTR_SIZE,u=ue.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let f=u[0],l=u[1],c=u[2],d=u[3],p=u[4],h=u[5],b=t.length,A=o.length,m=0,w=[],O=[],g=[],T=[],x=[],M=s.stackSave(),_=s.stackAlloc(b*a),de=s.stackAlloc(b*a),re=s.stackAlloc(A*a),ct=s.stackAlloc(A*a);try{[m,w]=rn(i),K("wasm prepareInputOutputTensor");for(let y=0;y<b;y++)await ln(n[y],O,T,e,l[t[y]],t[y],p);for(let y=0;y<A;y++)await ln(r[y],g,T,e,c[o[y]],b+o[y],p);Q("wasm prepareInputOutputTensor");for(let y=0;y<b;y++)s.setValue(_+y*a,O[y],"*"),s.setValue(de+y*a,l[t[y]],"*");for(let y=0;y<A;y++)s.setValue(re+y*a,g[y],"*"),s.setValue(ct+y*a,c[o[y]],"*");s.jsepOnRunStart?.(f),s.webnnOnRunStart?.(f);let F;F=await s._OrtRun(f,de,_,b,ct,A,re,m),F!==0&&S("failed to call OrtRun().");let z=[],dt=[];K("wasm ProcessOutputTensor");for(let y=0;y<A;y++){let W=Number(s.getValue(re+y*a,"*"));if(W===g[y]||x.includes(g[y])){z.push(r[y]),W!==g[y]&&s._OrtReleaseTensor(W)!==0&&S("Can't release tensor.");continue}let lt=s.stackSave(),$=s.stackAlloc(4*a),oe=!1,P,C=0;try{s._OrtGetTensorData(W,$,$+a,$+2*a,$+3*a)!==0&&S(`Can't access output tensor data on index ${y}.`);let je=a===4?"i32":"i64",ge=Number(s.getValue($,je));C=s.getValue($+a,"*");let pt=s.getValue($+a*2,"*"),Bn=Number(s.getValue($+a*3,je)),H=[];for(let U=0;U<Bn;U++)H.push(Number(s.getValue(pt+U*a,je)));s._OrtFree(pt)!==0&&S("Can't free memory for tensor dims.");let j=H.reduce((U,L)=>U*L,1);P=Ne(ge);let le=d?.outputPreferredLocations[o[y]];if(P==="string"){if(le==="gpu-buffer"||le==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let U=[];for(let L=0;L<j;L++){let V=s.getValue(C+L*a,"*"),Ee=s.getValue(C+(L+1)*a,"*"),mt=L===j-1?void 0:Ee-V;U.push(s.UTF8ToString(V,mt))}z.push([P,H,U,"cpu"])}else if(le==="gpu-buffer"&&j>0){let U=s.jsepGetBuffer;if(!U)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let L=U(C),V=ae(ge,j);if(V===void 0||!Fe(P))throw new Error(`Unsupported data type: ${P}`);oe=!0,z.push([P,H,{gpuBuffer:L,download:s.jsepCreateDownloader(L,V,P),dispose:()=>{s._OrtReleaseTensor(W)!==0&&S("Can't release tensor.")}},"gpu-buffer"])}else if(le==="ml-tensor"&&j>0){let U=s.webnnEnsureTensor,L=s.webnnIsGraphInputOutputTypeSupported;if(!U||!L)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(ae(ge,j)===void 0||!ke(P))throw new Error(`Unsupported data type: ${P}`);if(!L(e,P,!1))throw new Error(`preferredLocation "ml-tensor" for ${P} output is not supported by current WebNN Context.`);let Ee=await U(e,C,ge,H,!1);oe=!0,z.push([P,H,{mlTensor:Ee,download:s.webnnCreateMLTensorDownloader(C,P),dispose:()=>{s.webnnReleaseTensorId(C),s._OrtReleaseTensor(W)}},"ml-tensor"])}else if(le==="ml-tensor-cpu-output"&&j>0){let U=s.webnnCreateMLTensorDownloader(C,P)(),L=z.length;oe=!0,dt.push((async()=>{let V=[L,await U];return s.webnnReleaseTensorId(C),s._OrtReleaseTensor(W),V})()),z.push([P,H,[],"cpu"])}else{let U=un(P),L=new U(j);new Uint8Array(L.buffer,L.byteOffset,L.byteLength).set(s.HEAPU8.subarray(C,C+L.byteLength)),z.push([P,H,L,"cpu"])}}finally{s.stackRestore(lt),P==="string"&&C&&s._free(C),oe||s._OrtReleaseTensor(W)}}d&&!p&&(s._OrtClearBoundOutputs(d.handle)!==0&&S("Can't clear bound outputs."),ue.set(e,[f,l,c,d,p,!1]));for(let[y,W]of await Promise.all(dt))z[y][2]=W;return Q("wasm ProcessOutputTensor"),z}finally{s.webnnOnRunEnd?.(f),s.stackRestore(M),O.forEach(F=>s._OrtReleaseTensor(F)),g.forEach(F=>s._OrtReleaseTensor(F)),T.forEach(F=>s._free(F)),m!==0&&s._OrtReleaseRunOptions(m),w.forEach(F=>s._free(F))}},xe=e=>{let t=I(),n=ue.get(e);if(!n)throw new Error("invalid session id");let o=n[0],r=t._OrtEndProfiling(o);r===0&&S("Can't get an profile file name."),t._OrtFree(r)},ve=e=>{let t=[];for(let n of e){let o=n[2];!Array.isArray(o)&&"buffer"in o&&t.push(o.buffer)}return t}});var ne,k,ye,Ge,$e,We,at,ut,fe,ce,qn,pn,mn,wn,hn,bn,yn,gn,ft=E(()=>{"use strict";J();tt();ee();Be();ne=()=>!!B.wasm.proxy&&typeof document<"u",ye=!1,Ge=!1,$e=!1,ut=new Map,fe=(e,t)=>{let n=ut.get(e);n?n.push(t):ut.set(e,[t])},ce=()=>{if(ye||!Ge||$e||!k)throw new Error("worker not ready")},qn=e=>{switch(e.data.type){case"init-wasm":ye=!1,e.data.err?($e=!0,at[1](e.data.err)):(Ge=!0,at[0]()),We&&(URL.revokeObjectURL(We),We=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=ut.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},pn=async()=>{if(!Ge){if(ye)throw new Error("multiple calls to 'initWasm()' detected.");if($e)throw new Error("previous call to 'initWasm()' failed.");if(ye=!0,ne())return new Promise((e,t)=>{k?.terminate(),en().then(([n,o])=>{try{k=o,k.onerror=i=>t(i),k.onmessage=qn,at=[e,t];let r={type:"init-wasm",in:B};if(!r.in.wasm.wasmPaths&&n){let i=Ce();i&&(r.in.wasm.wasmPaths=i)}k.postMessage(r),We=n}catch(r){t(r)}},t)});try{await Oe(B.wasm),await Le(B),Ge=!0}catch(e){throw $e=!0,e}finally{ye=!1}}},mn=async e=>{if(ne())return ce(),new Promise((t,n)=>{fe("init-ep",[t,n]);let o={type:"init-ep",in:{epName:e,env:B}};k.postMessage(o)});await Pe(B,e)},wn=async e=>ne()?(ce(),new Promise((t,n)=>{fe("copy-from",[t,n]);let o={type:"copy-from",in:{buffer:e}};k.postMessage(o,[e.buffer])})):we(e),hn=async(e,t)=>{if(ne()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ce(),new Promise((n,o)=>{fe("create",[n,o]);let r={type:"create",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),k.postMessage(r,i)})}else return De(e,t)},bn=async e=>{if(ne())return ce(),new Promise((t,n)=>{fe("release",[t,n]);let o={type:"release",in:e};k.postMessage(o)});_e(e)},yn=async(e,t,n,o,r,i)=>{if(ne()){if(n.some(s=>s[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(r.some(s=>s))throw new Error("pre-allocated output tensor is not supported for proxy.");return ce(),new Promise((s,a)=>{fe("run",[s,a]);let u=n,f={type:"run",in:{sessionId:e,inputIndices:t,inputs:u,outputIndices:o,options:i}};k.postMessage(f,ve(u))})}else return Ue(e,t,n,o,r,i)},gn=async e=>{if(ne())return ce(),new Promise((t,n)=>{fe("end-profiling",[t,n]);let o={type:"end-profiling",in:e};k.postMessage(o)});xe(e)}});var En,Yn,ze,Sn=E(()=>{"use strict";J();ft();st();Ae();it();En=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Yn=e=>{switch(e[3]){case"cpu":return new G(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Fe(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:o,dispose:r}=e[2];return G.fromGpuBuffer(n,{dataType:t,dims:e[1],download:o,dispose:r})}case"ml-tensor":{let t=e[0];if(!ke(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:o,dispose:r}=e[2];return G.fromMLTensor(n,{dataType:t,dims:e[1],download:o,dispose:r})}default:throw new Error(`invalid data location: ${e[3]}`)}},ze=class{async fetchModelAndCopyToWasmMemory(t){return wn(await be(t))}async loadModel(t,n){Z();let o;typeof t=="string"?o=await this.fetchModelAndCopyToWasmMemory(t):o=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await hn(o,n),X()}async dispose(){return bn(this.sessionId)}async run(t,n,o){Z();let r=[],i=[];Object.entries(t).forEach(d=>{let p=d[0],h=d[1],b=this.inputNames.indexOf(p);if(b===-1)throw new Error(`invalid input '${p}'`);r.push(h),i.push(b)});let s=[],a=[];Object.entries(n).forEach(d=>{let p=d[0],h=d[1],b=this.outputNames.indexOf(p);if(b===-1)throw new Error(`invalid output '${p}'`);s.push(h),a.push(b)});let u=r.map((d,p)=>En(d,()=>`input "${this.inputNames[i[p]]}"`)),f=s.map((d,p)=>d?En(d,()=>`output "${this.outputNames[a[p]]}"`):null),l=await yn(this.sessionId,i,u,a,f,o),c={};for(let d=0;d<l.length;d++)c[this.outputNames[a[d]]]=s[d]??Yn(l[d]);return X(),c}startProfiling(){}endProfiling(){gn(this.sessionId)}}});var In={};qe(In,{OnnxruntimeWebAssemblyBackend:()=>He,initializeFlags:()=>Tn,wasmBackend:()=>Zn});var Tn,He,Zn,An=E(()=>{"use strict";J();ft();Sn();Tn=()=>{(typeof B.wasm.initTimeout!="number"||B.wasm.initTimeout<0)&&(B.wasm.initTimeout=0);let e=B.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),B.wasm.simd=!1),typeof B.wasm.proxy!="boolean"&&(B.wasm.proxy=!1),typeof B.wasm.trace!="boolean"&&(B.wasm.trace=!1),typeof B.wasm.numThreads!="number"||!Number.isInteger(B.wasm.numThreads)||B.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)B.wasm.numThreads=1;else{let t=typeof navigator>"u"?Je("node:os").cpus().length:navigator.hardwareConcurrency;B.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},He=class{async init(t){Tn(),await pn(),await mn(t)}async createInferenceSessionHandler(t,n){let o=new ze;return await o.loadModel(t,n),o}},Zn=new He});J();J();J();var jt="1.30.0";var Ro=et;{let e=(An(),wt(In)).wasmBackend;pe("cpu",e,10),pe("wasm",e,10)}Object.defineProperty(B.versions,"web",{value:jt,enumerable:!0});export{Un as InferenceSession,Nt as TRACE,K as TRACE_EVENT_BEGIN,Q as TRACE_EVENT_END,Z as TRACE_FUNC_BEGIN,X as TRACE_FUNC_END,G as Tensor,Ro as default,B as env,pe as registerBackend};
|
| 7 |
+
//# sourceMappingURL=ort.wasm.min.mjs.map
|
vendor/ort/ort.webgpu.min.mjs
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*!
|
| 2 |
+
* ONNX Runtime Web v1.30.0
|
| 3 |
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
* Licensed under the MIT License.
|
| 5 |
+
*/
|
| 6 |
+
var nt=Object.defineProperty;var Hr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var qr=Object.prototype.hasOwnProperty;var ot=(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 T=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(o){throw r=[o],o}};var ve=(t,e)=>{for(var r in e)nt(t,r,{get:e[r],enumerable:!0})},Yr=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Jr(e))!qr.call(t,n)&&n!==r&&nt(t,n,{get:()=>e[n],enumerable:!(o=Hr(e,n))||o.enumerable});return t};var st=t=>Yr(nt({},"__esModule",{value:!0}),t);var Be,ne,oe,Xr,Bt,at=T(()=>{"use strict";Be=new Map,ne=[],oe=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let o=Be.get(t);if(o===void 0)Be.set(t,{backend:e,priority:r});else{if(o.priority>r)return;if(o.priority===r&&o.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=ne.indexOf(t);n!==-1&&ne.splice(n,1);for(let s=0;s<ne.length;s++)if(Be.get(ne[s]).priority<=r){ne.splice(s,0,t);return}ne.push(t)}return}throw new TypeError("not a valid backend")},Xr=async t=>{let e=Be.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(o){return r||(e.error=`${o}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},Bt=async t=>{let e=t.executionProviders||[],r=e.map(u=>typeof u=="string"?u:u.name),o=r.length===0?ne:r,n,s=[],a=new Set;for(let u of o){let f=await Xr(u);typeof f=="string"?s.push({name:u,err:f}):(n||(n=f),n===f&&a.add(u))}if(!n)throw new Error(`no available backend found. ERR: ${s.map(u=>`[${u.name}] ${u.err}`).join(", ")}`);for(let{name:u,err:f}of s)r.includes(u)&&console.warn(`removing requested execution provider "${u}" from session options because it is not available: ${f}`);let i=e.filter(u=>a.has(typeof u=="string"?u:u.name));return[n,new Proxy(t,{get:(u,f)=>f==="executionProviders"?i:Reflect.get(u,f)})]}});var Mt=T(()=>{"use strict";at()});var xt,Ot=T(()=>{"use strict";xt="1.30.0"});var Dt,U,it=T(()=>{"use strict";Ot();Dt="warning",U={wasm:{},webgl:{},webgpu:{},versions:{common:xt},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}`);Dt=t}},get logLevel(){return Dt}};Object.defineProperty(U,"logLevel",{enumerable:!0})});var v,Ut=T(()=>{"use strict";it();v=U});var Ct,Pt,_t=T(()=>{"use strict";Ct=(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 o=r.getContext("2d");if(o!=null){let n,s;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],s=t.dims[3]):(n=t.dims[3],s=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,u,f;i===void 0||i.mean===void 0?u=[255,255,255,255]:typeof i.mean=="number"?u=[i.mean,i.mean,i.mean,i.mean]:(u=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(u[3]=i.mean[3])),i===void 0||i.bias===void 0?f=[0,0,0,0]:typeof i.bias=="number"?f=[i.bias,i.bias,i.bias,i.bias]:(f=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(f[3]=i.bias[3]));let d=s*n,p=0,c=d,l=d*2,h=-1;a==="RGBA"?(p=0,c=d,l=d*2,h=d*3):a==="RGB"?(p=0,c=d,l=d*2):a==="RBG"&&(p=0,l=d,c=d*2);for(let b=0;b<s;b++)for(let E=0;E<n;E++){let y=(t.data[p++]-f[0])*u[0],m=(t.data[c++]-f[1])*u[1],A=(t.data[l++]-f[2])*u[2],w=h===-1?255:(t.data[h++]-f[3])*u[3];o.fillStyle="rgba("+y+","+m+","+A+","+w+")",o.fillRect(E,b,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Pt=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),o;if(r!=null){let n,s,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],s=t.dims[1],a=t.dims[3]):(n=t.dims[3],s=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",u=e?.norm,f,d;u===void 0||u.mean===void 0?f=[255,255,255,255]:typeof u.mean=="number"?f=[u.mean,u.mean,u.mean,u.mean]:(f=[u.mean[0],u.mean[1],u.mean[2],255],u.mean[3]!==void 0&&(f[3]=u.mean[3])),u===void 0||u.bias===void 0?d=[0,0,0,0]:typeof u.bias=="number"?d=[u.bias,u.bias,u.bias,u.bias]:(d=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(d[3]=u.bias[3]));let p=s*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 c=4,l=0,h=1,b=2,E=3,y=0,m=p,A=p*2,w=-1;i==="RGBA"?(y=0,m=p,A=p*2,w=p*3):i==="RGB"?(y=0,m=p,A=p*2):i==="RBG"&&(y=0,A=p,m=p*2),o=r.createImageData(n,s);for(let L=0;L<s*n;l+=c,h+=c,b+=c,E+=c,L++)o.data[l]=(t.data[y++]-d[0])*f[0],o.data[h]=(t.data[m++]-d[1])*f[1],o.data[b]=(t.data[A++]-d[2])*f[2],o.data[E]=w===-1?255:(t.data[w++]-d[3])*f[3]}else throw new Error("Can not access image data");return o}});var ut,Rt,Nt,Ft,Wt,kt,Gt=T(()=>{"use strict";Me();ut=(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:o}=e,n=e.norm??{mean:255,bias:0},s,a;typeof n.mean=="number"?s=[n.mean,n.mean,n.mean,n.mean]:s=[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",u=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",f=r*o,d=u==="RGBA"?new Float32Array(f*4):new Float32Array(f*3),p=4,c=0,l=1,h=2,b=3,E=0,y=f,m=f*2,A=-1;i==="RGB"&&(p=3,c=0,l=1,h=2,b=-1),u==="RGBA"?A=f*3:u==="RBG"?(E=0,m=f,y=f*2):u==="BGR"&&(m=0,y=f,E=f*2);for(let L=0;L<f;L++,c+=p,h+=p,l+=p,b+=p)d[E++]=(t[c]+a[0])/s[0],d[y++]=(t[l]+a[1])/s[1],d[m++]=(t[h]+a[2])/s[2],A!==-1&&b!==-1&&(d[A++]=(t[b]+a[3])/s[3]);return u==="RGBA"?new _("float32",d,[1,4,r,o]):new _("float32",d,[1,3,r,o])},Rt=async(t,e)=>{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,o=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,s=typeof t=="string",a,i=e??{},u=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},f=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){let d=u();d.width=t.width,d.height=t.height;let p=f(d);if(p!=null){let c=t.height,l=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(c=e.resizedHeight,l=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=c,i.width=l}else i.tensorFormat="RGBA",i.height=c,i.width=l;p.drawImage(t,0,0),a=p.getImageData(0,0,l,c).data}else throw new Error("Can not access image data")}else if(o){let d,p;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(d=e.resizedHeight,p=e.resizedWidth):(d=t.height,p=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=d,i.width=p,e!==void 0){let c=u();c.width=p,c.height=d;let l=f(c);if(l!=null)l.putImageData(t,0,0),a=l.getImageData(0,0,p,d).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 d=u();d.width=t.width,d.height=t.height;let p=f(d);if(p!=null){let c=t.height,l=t.width;return p.drawImage(t,0,0,l,c),a=p.getImageData(0,0,l,c).data,i.height=c,i.width=l,ut(a,i)}else throw new Error("Can not access image data")}else{if(s)return new Promise((d,p)=>{let c=u(),l=f(c);if(!t||!l)return p();let h=new Image;h.crossOrigin="Anonymous",h.src=t,h.onload=()=>{c.width=h.width,c.height=h.height,l.drawImage(h,0,0,c.width,c.height);let b=l.getImageData(0,0,c.width,c.height);i.height=c.height,i.width=c.width,d(ut(b.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return ut(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Nt=(t,e)=>{let{width:r,height:o,download:n,dispose:s}=e,a=[1,o,r,4];return new _({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:s})},Ft=(t,e)=>{let{dataType:r,dims:o,download:n,dispose:s}=e;return new _({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:o,download:n,dispose:s})},Wt=(t,e)=>{let{dataType:r,dims:o,download:n,dispose:s}=e;return new _({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:o,download:n,dispose:s})},kt=(t,e,r)=>new _({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})});var se,we,$t,zt,Vt=T(()=>{"use strict";se=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),we=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),$t=!1,zt=()=>{if(!$t){$t=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,o=typeof r<"u"&&r.from;t&&(se.set("int64",BigInt64Array),we.set(BigInt64Array,"int64")),e&&(se.set("uint64",BigUint64Array),we.set(BigUint64Array,"uint64")),o?(se.set("float16",r),we.set(r,"float16")):se.set("float16",Uint16Array)}}});var jt,Ht,Jt=T(()=>{"use strict";Me();jt=t=>{let e=1;for(let r=0;r<t.length;r++){let o=t[r];if(typeof o!="number"||!Number.isSafeInteger(o))throw new TypeError(`dims[${r}] must be an integer, got: ${o}`);if(o<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${o}`);e*=o}return e},Ht=(t,e)=>{switch(t.location){case"cpu":return new _(t.type,t.data,e);case"cpu-pinned":return new _({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new _({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new _({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new _({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}});var _,Me=T(()=>{"use strict";_t();Gt();Vt();Jt();_=class{constructor(e,r,o){zt();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let i=se.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,u;if(typeof e=="string")if(n=e,u=o,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let f=se.get(e);if(f===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&f===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${f.name} as data.`);e==="uint64"||e==="int64"?i=f.from(r,BigInt):i=f.from(r)}else if(r instanceof f)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&&f!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${f}`)}else if(u=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let f=typeof e[0];if(f==="string")n="string",i=e;else if(f==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${f}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let f=we.get(e.constructor);if(f===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=f,i=e}if(u===void 0)u=[i.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");s=u,this.cpuData=i,this.dataLocation="cpu"}let a=jt(s);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=s,this.size=a}static async fromImage(e,r){return Rt(e,r)}static fromTexture(e,r){return Nt(e,r)}static fromGpuBuffer(e,r){return Ft(e,r)}static fromMLTensor(e,r){return Wt(e,r)}static fromPinnedBuffer(e,r,o){return kt(e,r,o)}toDataURL(e){return Ct(this,e)}toImageData(e){return Pt(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 Ht(this,e)}}});var V,ft=T(()=>{"use strict";Me();V=_});var qt,Yt,ae,ie,Z,K,ct=T(()=>{"use strict";it();qt=(t,e)=>{(typeof U.trace>"u"?!U.wasm.trace:!U.trace)||console.timeStamp(`${t}::ORT::${e}`)},Yt=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],o=!1;for(let n=0;n<r.length;n++){if(o&&!r[n].includes("TRACE_FUNC")){let s=`FUNC_${t}::${r[n].trim().split(" ")[1]}`;e&&(s+=`::${e}`),qt("CPU",s);return}r[n].includes("TRACE_FUNC")&&(o=!0)}},ae=t=>{(typeof U.trace>"u"?!U.wasm.trace:!U.trace)||Yt("BEGIN",t)},ie=t=>{(typeof U.trace>"u"?!U.wasm.trace:!U.trace)||Yt("END",t)},Z=t=>{(typeof U.trace>"u"?!U.wasm.trace:!U.trace)||console.time(`ORT::${t}`)},K=t=>{(typeof U.trace>"u"?!U.wasm.trace:!U.trace)||console.timeEnd(`ORT::${t}`)}});var xe,Xt=T(()=>{"use strict";at();ft();ct();xe=class t{constructor(e){this.handler=e}async run(e,r,o){ae(),Z("InferenceSession.run");let n={},s={};if(typeof e!="object"||e===null||e instanceof V||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 V)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 f of r){if(typeof f!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(f)===-1)throw new RangeError(`'fetches' contains invalid output name: ${f}.`);n[f]=null}if(typeof o=="object"&&o!==null)s=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else{let f=!1,d=Object.getOwnPropertyNames(r);for(let p of this.outputNames)if(d.indexOf(p)!==-1){let c=r[p];(c===null||c instanceof V)&&(f=!0,a=!1,n[p]=c)}if(f){if(typeof o=="object"&&o!==null)s=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else s=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let f of this.inputNames)if(typeof e[f]>"u")throw new Error(`input '${f}' is missing in 'feeds'.`);if(a)for(let f of this.outputNames)n[f]=null;let i=await this.handler.run(e,n,s),u={};for(let f in i)if(Object.hasOwnProperty.call(i,f)){let d=i[f];d instanceof V?u[f]=d:u[f]=new V(d.type,d.data,d.dims)}return K("InferenceSession.run"),ie(),u}async release(){return this.handler.dispose()}static async create(e,r,o,n){ae(),Z("InferenceSession.create");let s,a={};if(typeof e=="string"){if(s=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(s=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 d=e,p=0,c=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(p=r,!Number.isSafeInteger(p))throw new RangeError("'byteOffset' must be an integer.");if(p<0||p>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(c=e.byteLength-p,typeof o=="number"){if(c=o,!Number.isSafeInteger(c))throw new RangeError("'byteLength' must be an integer.");if(c<=0||p+c>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-p}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof o<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");s=new Uint8Array(d,p,c)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,u]=await Bt(a),f=await i.createInferenceSessionHandler(s,u);return K("InferenceSession.create"),ie(),new t(f)}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}}});var Zr,Zt=T(()=>{"use strict";Xt();Zr=xe});var Kt=T(()=>{"use strict"});var Qt=T(()=>{"use strict"});var er=T(()=>{"use strict"});var tr=T(()=>{"use strict"});var dt={};ve(dt,{InferenceSession:()=>Zr,TRACE:()=>qt,TRACE_EVENT_BEGIN:()=>Z,TRACE_EVENT_END:()=>K,TRACE_FUNC_BEGIN:()=>ae,TRACE_FUNC_END:()=>ie,Tensor:()=>V,env:()=>v,registerBackend:()=>oe});var Q=T(()=>{"use strict";Mt();Ut();Zt();ft();Kt();Qt();ct();er();tr()});var Oe=T(()=>{"use strict"});var sr={};ve(sr,{default:()=>Kr});var nr,or,Kr,ar=T(()=>{"use strict";pt();ee();De();nr="ort-wasm-proxy-worker",or=globalThis.self?.name===nr;or&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":Ue(r.wasm).then(()=>{Ce(r).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})})},o=>{postMessage({type:e,err:o})});break;case"init-ep":{let{epName:o,env:n}=r;Pe(n,o).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})});break}case"copy-from":{let{buffer:o}=r,n=ge(o);postMessage({type:e,out:n});break}case"create":{let{model:o,options:n}=r;_e(o,n).then(s=>{postMessage({type:e,out:s})},s=>{postMessage({type:e,err:s})});break}case"release":Re(r),postMessage({type:e});break;case"run":{let{sessionId:o,inputIndices:n,inputs:s,outputIndices:a,options:i}=r;Ne(o,n,s,a,new Array(a.length).fill(null),i).then(u=>{u.some(f=>f[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:u},We([...s,...u]))},u=>{postMessage({type:e,err:u})});break}case"end-profiling":Fe(r),postMessage({type:e});break;default:}}catch(o){postMessage({type:e,err:o})}});Kr=or?null:t=>new Worker(t??G,{type:"module",name:nr})});var fr,Qr,en,G,ke,lt,tn,rn,cr,nn,ir,dr,ur,pr,De=T(()=>{"use strict";Oe();fr=typeof location>"u"?void 0:location.origin,Qr=import.meta.url>"file:"&&import.meta.url<"file;",en=()=>{if(!!1){if(Qr){let t=URL;return new URL(new t("ort.webgpu.min.mjs",import.meta.url).href,fr).href}return import.meta.url}},G=en(),ke=()=>{if(G&&!G.startsWith("blob:"))return G.substring(0,G.lastIndexOf("/")+1)},lt=(t,e)=>{try{let r=e??G;return(r?new URL(t,r):new URL(t)).origin===fr}catch{return!1}},tn=(t,e)=>{let r=e??G;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},rn=(t,e)=>`${e??"./"}${t}`,cr=async t=>{let r=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},nn=async t=>(await import(/*webpackIgnore:true*/ /*@vite-ignore*/t)).default,ir=(ar(),st(sr)).default,dr=async()=>{if(!G)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(lt(G))return[void 0,ir()];let t=await cr(G);return[t,ir(t)]},ur=void 0,pr=async(t,e,r,o)=>{let n=ur&&!(t||e);if(n)if(G)n=lt(G)||o&&!r;else if(o&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,ur];{let s="ort-wasm-simd-threaded.asyncify.mjs",a=t??tn(s,e),i=!!1&&r&&a&&!lt(a,e),u=i?await cr(a):a??rn(s,e);return[i?u:void 0,await nn(u)]}}});var mt,ht,Ge,lr,on,sn,an,Ue,I,ee=T(()=>{"use strict";De();ht=!1,Ge=!1,lr=!1,on=()=>{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}},sn=()=>{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}},an=()=>{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}},Ue=async t=>{if(ht)return Promise.resolve();if(Ge)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(lr)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ge=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!an())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!sn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let o=on();r>1&&!o&&(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,s=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,u=n?.wasm,f=u?.href??u,d=t.wasmBinary,[p,c]=await pr(i,s,r>1,!!d||!!f),l=!1,h=[];if(e>0&&h.push(new Promise(b=>{setTimeout(()=>{l=!0,b()},e)})),h.push(new Promise((b,E)=>{let y={numThreads:r};if(d)y.wasmBinary=d,y.locateFile=m=>m;else if(f||s)y.locateFile=m=>f??s+m;else if(i&&i.indexOf("blob:")!==0)y.locateFile=m=>new URL(m,i).href;else if(p){let m=ke();m&&(y.locateFile=A=>m+A)}c(y).then(m=>{Ge=!1,ht=!0,mt=m,b(),p&&URL.revokeObjectURL(p)},m=>{Ge=!1,lr=!0,E(m)})})),await Promise.race(h),l)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},I=()=>{if(ht&&mt)return mt;throw new Error("WebAssembly is not initialized yet.")}});var F,Te,S,$e=T(()=>{"use strict";ee();F=(t,e)=>{let r=I(),o=r.lengthBytesUTF8(t)+1,n=r._malloc(o);return r.stringToUTF8(t,n,o),e.push(n),n},Te=(t,e,r,o)=>{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,s])=>{let a=e?e+n:n;if(typeof s=="object")Te(s,a+".",r,o);else if(typeof s=="string"||typeof s=="number")o(a,s.toString());else if(typeof s=="boolean")o(a,s?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof s}`)})},S=t=>{let e=I(),r=e.stackSave();try{let o=e.PTR_SIZE,n=e.stackAlloc(2*o);e._OrtGetLastError(n,n+o);let s=Number(e.getValue(n,o===4?"i32":"i64")),a=e.getValue(n+o,"*"),i=a?e.UTF8ToString(a):"";throw new Error(`${t} ERROR_CODE: ${s}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}});var mr,hr=T(()=>{"use strict";ee();$e();mr=t=>{let e=I(),r=0,o=[],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 s=0;return t?.tag!==void 0&&(s=F(t.tag,o)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,s),r===0&&S("Can't create run options."),t?.extra!==void 0&&Te(t.extra,"",new WeakSet,(a,i)=>{let u=F(a,o),f=F(i,o);e._OrtAddRunConfigEntry(r,u,f)!==0&&S(`Can't set a run config entry: ${a} - ${i}.`)}),[r,o]}catch(s){throw r!==0&&e._OrtReleaseRunOptions(r),o.forEach(a=>e._free(a)),s}}});var un,fn,cn,Ee,te,dn,yr,br=T(()=>{"use strict";ee();$e();un=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}`)}},fn=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},cn=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)},Ee=(t,e,r,o)=>{let n=F(e,o),s=F(r,o);I()._OrtAddSessionConfigEntry(t,n,s)!==0&&S(`Can't set a session config entry: ${e} - ${r}.`)},te=(t,e,r,o)=>{let n=F(e,o),s=F(r,o);t.push([n,s])},dn=async(t,e,r)=>{let o=e.executionProviders;for(let n of o){let s=typeof n=="string"?n:n.name,a=[];switch(s){case"webnn":if(s="WEBNN",Ee(t,"session.disable_quant_qdq","1",r),Ee(t,"session.disable_qdq_constant_folding","1",r),typeof n!="string"){let c=n?.deviceType;c&&Ee(t,"deviceType",c,r)}break;case"webgpu":{s="WebGPU";let p;if(typeof n!="string"){let l=n;if(l.device)if(typeof GPUDevice<"u"&&l.device instanceof GPUDevice)p=l.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:h}=e;if(typeof h=="boolean"&&h&&te(a,"enableGraphCapture","1",r),typeof l.preferredLayout=="string"&&te(a,"preferredLayout",l.preferredLayout,r),l.forceCpuNodeNames){let b=Array.isArray(l.forceCpuNodeNames)?l.forceCpuNodeNames:[l.forceCpuNodeNames];te(a,"forceCpuNodeNames",b.join(`
|
| 7 |
+
`),r)}l.validationMode&&te(a,"validationMode",l.validationMode,r);for(let b of["storageBufferCacheMode","uniformBufferCacheMode","queryResolveBufferCacheMode","defaultBufferCacheMode"]){let E=l[b];if(E){if(E!=="disabled"&&E!=="lazyRelease"&&E!=="simple"&&E!=="bucket")throw new Error(`${b} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${E}`);te(a,b,E,r)}}}let c=I().webgpuRegisterDevice(p);if(c){let[l,h,b]=c;te(a,"deviceId",l.toString(),r),te(a,"webgpuInstance",h.toString(),r),te(a,"webgpuDevice",b.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let i=F(s,r),u=a.length,f=0,d=0;if(u>0){f=I()._malloc(u*I().PTR_SIZE),r.push(f),d=I()._malloc(u*I().PTR_SIZE),r.push(d);for(let p=0;p<u;p++)I().setValue(f+p*I().PTR_SIZE,a[p][0],"*"),I().setValue(d+p*I().PTR_SIZE,a[p][1],"*")}await I()._OrtAppendExecutionProvider(t,i,f,d,u)!==0&&S(`Can't append execution provider: ${s}.`)}},yr=async t=>{let e=I(),r=0,o=[],n=t||{};cn(n);try{let s=un(n.graphOptimizationLevel??"all"),a=fn(n.executionMode??"sequential"),i=typeof n.logId=="string"?F(n.logId,o):0,u=n.logSeverityLevel??2;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log severity level is not valid: ${u}`);let f=n.logVerbosityLevel??0;if(!Number.isInteger(f)||f<0||f>4)throw new Error(`log verbosity level is not valid: ${f}`);let d=typeof n.optimizedModelFilePath=="string"?F(n.optimizedModelFilePath,o):0;if(r=e._OrtCreateSessionOptions(s,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,u,f,d),r===0&&S("Can't create session options."),n.executionProviders&&await dn(r,n,o),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Ee(r,"enableGraphCapture",n.enableGraphCapture.toString(),o)}if(n.freeDimensionOverrides)for(let[p,c]of Object.entries(n.freeDimensionOverrides)){if(typeof p!="string")throw new Error(`free dimension override name must be a string: ${p}`);if(typeof c!="number"||!Number.isInteger(c)||c<0)throw new Error(`free dimension override value must be a non-negative integer: ${c}`);let l=F(p,o);e._OrtAddFreeDimensionOverride(r,l,c)!==0&&S(`Can't set a free dimension override: ${p} - ${c}.`)}return n.extra!==void 0&&Te(n.extra,"",new WeakSet,(p,c)=>{Ee(r,p,c,o)}),[r,o]}catch(s){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&S("Can't release session options."),o.forEach(a=>e._free(a)),s}}});var re,ze,le,fe,Se,Ve,je,yt,ce=T(()=>{"use strict";re=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}`)}},ze=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}`)}},le=(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],o=typeof e=="number"?e:e.reduce((n,s)=>n*s,1);return r>0?Math.ceil(o*r):void 0},fe=t=>{switch(t){case"float16":return typeof Float16Array<"u"?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}`)}},Se=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}`)}},Ve=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",je=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",yt=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}`)}}});var Ie,bt=T(()=>{"use strict";Oe();Ie=async t=>{if(typeof t=="string")if(!1)try{let{readFile:e}=ot("node:fs/promises");return new Uint8Array(await e(t))}catch(e){if(e.code==="ERR_FS_FILE_TOO_LARGE"){let{createReadStream:r}=ot("node:fs"),o=r(t),n=[];for await(let s of o)n.push(s);return new Uint8Array(Buffer.concat(n))}throw e}else{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"),o=r?parseInt(r,10):0;if(o<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(),s;try{s=new ArrayBuffer(o)}catch(i){if(i instanceof RangeError){let u=Math.ceil(o/65536);s=new WebAssembly.Memory({initial:u,maximum:u}).buffer}else throw i}let a=0;for(;;){let{done:i,value:u}=await n.read();if(i)break;let f=u.byteLength;new Uint8Array(s,a,f).set(u),a+=f}return new Uint8Array(s,0,o)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}});var wr,gr=T(()=>{"use strict";ce();wr=(t,e)=>new(fe(e))(t)});var pn,ln,Tr,Er,Sr,mn,N,wt=T(()=>{"use strict";ce();pn=["V","I","W","E","F"],ln=(t,e)=>{console.log(`[${pn[t]},${new Date().toISOString()}]${e}`)},Sr=(t,e)=>{Tr=t,Er=e},mn=(t,e)=>{let r=Se(t),o=Se(Tr);r>=o&&ln(r,typeof e=="function"?e():e)},N=(...t)=>{Er&&mn(...t)}});var Lr,hn,Ar,yn,Ir,bn,vr,He,Je,gt,Br,Mr=T(()=>{"use strict";ce();wt();Lr=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),hn=(t,e)=>{if(e==="int32")return t;let r=Lr.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);let o=r/8;if(t.byteLength%o!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${o}.`);let n=t.byteLength/o,s=new(fe(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i<n;i++){let u=s[i];if(u>2147483647n||u<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(u)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&s.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(s,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},Ar=(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,o=new Int32Array(t.buffer,t.byteOffset,r);switch(e){case"int64":{let n=BigInt64Array.from(o,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(o.some(s=>s<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(o,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(o.some(s=>s<-128||s>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(o,Number);return new Uint8Array(n.buffer)}case"uint8":{if(o.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(o,Number)}case"uint32":{if(o.some(s=>s<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(o,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${e}`)}},yn=1,Ir=()=>yn++,bn=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),vr=(t,e)=>{let r=Lr.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);return e.length>0?Math.ceil(e.reduce((o,n)=>o*n)*r/8):0},He=class{constructor(e){this.isDataConverted=!1;let{sessionId:r,context:o,tensor:n,dataType:s,shape:a,fallbackDataType:i}=e;this.sessionId=r,this.mlContext=o,this.mlTensor=n,this.dataType=s,this.tensorShape=a,this.fallbackDataType=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return vr(this.dataType,this.tensorShape)}destroy(){N("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let r=await this.mlContext.readTensor(this.mlTensor),o=Ar(new Uint8Array(r),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(o);return}else return new Uint8Array(o).buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,r,o){return this.mlContext===e&&this.dataType===r&&this.tensorShape.length===o.length&&this.tensorShape.every((n,s)=>n===o[s])}setIsDataConverted(e){this.isDataConverted=e}},Je=class{constructor(e,r){this.tensorManager=e;this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,r,o,n){let s=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),i;if(!a?.input.dataTypes.includes(r)){if(i=bn.get(r),!i||!a?.input.dataTypes.includes(i))throw new Error(`WebNN backend does not support data type: ${r}`);N("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${r} to ${i}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(s,r,o))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==vr(r,o))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 u=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,r,o,u,!0,!0,i),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let r=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")r=hn(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else N("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(r):this.activeUpload=new Uint8Array(r)}async download(e){if(this.activeUpload){let r=this.wrapper?.isDataConverted?Ar(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(r):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(r);return}else return r.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},gt=class{constructor(e){this.backend=e;this.tensorTrackersById=new Map;this.freeTensors=[];this.externalTensors=new Set}getMLContext(e){let r=this.backend.getMLContext(e);if(!r)throw new Error("MLContext not found for session.");return r}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Ir();return this.tensorTrackersById.set(e,new Je(this)),e}releaseTensorId(e){let r=this.tensorTrackersById.get(e);r&&(this.tensorTrackersById.delete(e),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(e,r,o,n,s){N("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${o}, shape: ${n}, copyOld: ${s}}`);let a=this.tensorTrackersById.get(r);if(!a)throw new Error("Tensor not found.");return a.ensureTensor(e,o,n,s)}upload(e,r){let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");o.upload(r)}async download(e,r){N("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${r?.byteLength}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.download(r)}releaseTensorsForSession(e){for(let r of this.freeTensors)r.sessionId===e&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==e)}registerTensor(e,r,o,n){let s=this.getMLContext(e),a=Ir(),i=new He({sessionId:e,context:s,tensor:r,dataType:o,shape:n});return this.tensorTrackersById.set(a,new Je(this,i)),this.externalTensors.add(i),a}async getCachedTensor(e,r,o,n,s,a,i){let u=this.getMLContext(e);for(let[d,p]of this.freeTensors.entries())if(p.canReuseTensor(u,r,o)){N("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, ${i?`fallbackDataType: ${i},`:""} shape: ${o}`);let c=this.freeTensors.splice(d,1)[0];return c.sessionId=e,c}N("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, ${i?`fallbackDataType: ${i},`:""} shape: ${o}}`);let f=await u.createTensor({dataType:i??r,shape:o,dimensions:o,usage:n,writable:s,readable:a});return new He({sessionId:e,context:u,tensor:f,dataType:r,shape:o,fallbackDataType:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Br=(...t)=>new gt(...t)});var xr={};ve(xr,{WebNNBackend:()=>Tt});var qe,wn,Tt,Or=T(()=>{"use strict";ce();ee();gr();Mr();wt();qe=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),wn=(t,e)=>{if(t===e)return!0;if(t===void 0||e===void 0)return!1;let r=Object.keys(t).sort(),o=Object.keys(e).sort();return r.length===o.length&&r.every((n,s)=>n===o[s]&&t[n]===e[n])},Tt=class{constructor(e){this.tensorManager=Br(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;Sr(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){N("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){N("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let o of r)N("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${o}}`),this.tensorManager.releaseTensorId(o);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let o=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(o!==-1)return this.mlContextCache[o].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let o=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(o!==-1)return this.mlContextCache[o].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let r=this.mlContextCache.findIndex(o=>wn(o.options,e));if(r!==-1)return this.mlContextCache[r].mlContext;{let o=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:o}),o}}registerMLContext(e,r){this.mlContextBySessionId.set(e,r);let o=this.sessionIdsByMLContext.get(r);o||(o=new Set,this.sessionIdsByMLContext.set(r,o)),o.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,r.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let r=this.mlContextBySessionId.get(e);if(!r)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let o=this.sessionIdsByMLContext.get(r);if(o.delete(e),o.size===0){this.sessionIdsByMLContext.delete(r);let n=this.mlContextCache.findIndex(s=>s.mlContext===r);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){N("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,o,n,s){let a=qe.get(o);if(!a)throw new Error(`Unsupported ONNX data type: ${o}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,a,n,s)}async createTemporaryTensor(e,r,o){N("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${o}}`);let n=qe.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let s=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,s,n,o,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(s):this.temporarySessionTensorIds.set(e,[s]),s}uploadTensor(e,r){if(!I().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");N("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${r.byteLength}}`),this.tensorManager.upload(e,r)}async downloadTensor(e,r){return this.tensorManager.download(e,r)}createMLTensorDownloader(e,r){return async()=>{let o=await this.tensorManager.download(e);return wr(o,r)}}registerMLTensor(e,r,o,n){let s=qe.get(o);if(!s)throw new Error(`Unsupported ONNX data type: ${o}`);let a=this.tensorManager.registerTensor(e,r,s,n);return N("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${s}, dimensions: ${n}} -> {tensorId: ${a}}`),a}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,r){let o=this.sessionGraphInputs.get(e);return o?o.includes(r):!1}isGraphOutput(e,r){let o=this.sessionGraphOutputs.get(e);return o?o.includes(r):!1}isGraphInputOutputTypeSupported(e,r,o=!0){let n=qe.get(re(r)),s=this.mlOpSupportLimitsBySessionId.get(e);return typeof n>"u"?!1:o?!!s?.input.dataTypes.includes(n):!!s?.output.dataTypes.includes(n)}flush(){}}});var gn,Ce,Pe,de,Tn,Dr,ge,_e,Re,Ur,Ne,Fe,We,pt=T(()=>{"use strict";Q();hr();br();ce();ee();$e();bt();gn=(t,e)=>{I()._OrtInit(t,e)!==0&&S("Can't initialize onnxruntime.")},Ce=async t=>{gn(t.wasm.numThreads,Se(t.logLevel))},Pe=async(t,e)=>{I().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 o=t.webgpu.powerPreference;if(o!==void 0&&o!=="low-power"&&o!=="high-performance")throw new Error(`Invalid powerPreference setting: "${o}"`);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:o,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"&&I().webgpuInit(o=>{t.webgpu.device=o}),e==="webnn"){let o=new(Or(),st(xr)).WebNNBackend(t);I().webnnInit([o,()=>o.reserveTensorId(),n=>o.releaseTensorId(n),async(n,s,a,i,u)=>o.ensureTensor(n,s,a,i,u),(n,s)=>{o.uploadTensor(n,s)},async(n,s)=>o.downloadTensor(n,s),(n,s)=>o.registerMLContext(n,s),!!t.trace])}},de=new Map,Tn=t=>{let e=I(),r=e.stackSave();try{let o=e.PTR_SIZE,n=e.stackAlloc(2*o);e._OrtGetInputOutputCount(t,n,n+o)!==0&&S("Can't get session input/output count.");let a=o===4?"i32":"i64";return[Number(e.getValue(n,a)),Number(e.getValue(n+o,a))]}finally{e.stackRestore(r)}},Dr=(t,e)=>{let r=I(),o=r.stackSave(),n=0;try{let s=r.PTR_SIZE,a=r.stackAlloc(2*s);r._OrtGetInputOutputMetadata(t,e,a,a+s)!==0&&S("Can't get session input/output metadata.");let u=Number(r.getValue(a,"*"));n=Number(r.getValue(a+s,"*"));let f=r.HEAP32[n/4];if(f===0)return[u,0];let d=r.HEAPU32[n/4+1],p=[];for(let c=0;c<d;c++){let l=Number(r.getValue(n+8+c*s,"*"));p.push(l!==0?r.UTF8ToString(l):Number(r.getValue(n+8+(c+d)*s,"*")))}return[u,f,p]}finally{r.stackRestore(o),n!==0&&r._OrtFree(n)}},ge=t=>{let e=I(),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]},_e=async(t,e)=>{let r,o,n=I();Array.isArray(t)?[r,o]=t:t.buffer===n.HEAPU8.buffer?[r,o]=[t.byteOffset,t.byteLength]:[r,o]=ge(t);let s=0,a=0,i=0,u=[],f=[],d=[];try{if([a,u]=await yr(e),e?.externalData&&n.mountExternalData){let w=[];for(let L of e.externalData){let C=typeof L=="string"?L:L.path,k=typeof L=="string"?L:L.data;w.push(Ie(k).then(x=>{n.mountExternalData(C,x)}))}await Promise.all(w)}for(let w of e?.executionProviders??[])if((typeof w=="string"?w:w.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof w!="string"){let C=w,k=C?.context,x=C?.gpuDevice,W=C?.deviceType,H=C?.powerPreference;k?n.currentContext=k:x?n.currentContext=await n.webnnCreateMLContext(x):n.currentContext=await n.webnnCreateMLContext({deviceType:W,powerPreference:H})}else n.currentContext=await n.webnnCreateMLContext();break}s=await n._OrtCreateSession(r,o,a),n.webgpuOnCreateSession?.(s),s===0&&S("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(s,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[p,c]=Tn(s),l=!!e?.enableGraphCapture,h=[],b=[],E=[],y=[],m=[];for(let w=0;w<p;w++){let[L,C,k]=Dr(s,w);L===0&&S("Can't get an input name."),f.push(L);let x=n.UTF8ToString(L);h.push(x),E.push(C===0?{name:x,isTensor:!1}:{name:x,isTensor:!0,type:ze(C),shape:k})}for(let w=0;w<c;w++){let[L,C,k]=Dr(s,w+p);L===0&&S("Can't get an output name."),d.push(L);let x=n.UTF8ToString(L);b.push(x),y.push(C===0?{name:x,isTensor:!1}:{name:x,isTensor:!0,type:ze(C),shape:k});{if(l&&e?.preferredOutputLocation===void 0){m.push("gpu-buffer");continue}let W=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[x]??"cpu",H=n.webnnIsGraphOutput;if(W==="cpu"&&H&&H(s,x)){m.push("ml-tensor-cpu-output");continue}if(W!=="cpu"&&W!=="cpu-pinned"&&W!=="gpu-buffer"&&W!=="ml-tensor")throw new Error(`Not supported preferred output location: ${W}.`);if(l&&W!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${W}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);m.push(W)}}let A=null;return m.some(w=>w==="gpu-buffer"||w==="ml-tensor"||w==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(s),i===0&&S("Can't create IO binding."),A={handle:i,outputPreferredLocations:m,outputPreferredLocationsEncoded:m.map(w=>w==="ml-tensor-cpu-output"?"ml-tensor":w).map(w=>yt(w))}),de.set(s,[s,f,d,A,l,!1]),[s,h,b,E,y]}catch(p){throw f.forEach(c=>n._OrtFree(c)),d.forEach(c=>n._OrtFree(c)),i!==0&&n._OrtReleaseBinding(i)!==0&&S("Can't release IO binding."),s!==0&&n._OrtReleaseSession(s)!==0&&S("Can't release session."),p}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&S("Can't release session options."),u.forEach(p=>n._free(p)),n.unmountExternalData?.()}},Re=t=>{let e=I(),r=de.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[o,n,s,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&S("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&S("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(u=>e._OrtFree(u)),s.forEach(u=>e._OrtFree(u)),e._OrtReleaseSession(o)!==0&&S("Can't release session."),de.delete(t)},Ur=async(t,e,r,o,n,s,a=!1)=>{if(!t){e.push(0);return}let i=I(),u=i.PTR_SIZE,f=t[0],d=t[1],p=t[3],c=p,l,h;if(f==="string"&&(p==="gpu-buffer"||p==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let y=t[2].gpuBuffer;h=le(re(f),d);{let m=i.webgpuRegisterBuffer;if(!m)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');l=m(y,o)}}else if(p==="ml-tensor"){let y=t[2].mlTensor;h=le(re(f),d);let m=i.webnnRegisterMLTensor;if(!m)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');l=m(o,y,re(f),d)}else{let y=t[2];if(Array.isArray(y)){h=u*y.length,l=i._malloc(h),r.push(l);for(let m=0;m<y.length;m++){if(typeof y[m]!="string")throw new TypeError(`tensor data at index ${m} is not a string`);i.setValue(l+m*u,F(y[m],r),"*")}}else{let m=i.webnnIsGraphInput,A=i.webnnIsGraphOutput;if(f!=="string"&&m&&A){let w=i.UTF8ToString(n);if(m(o,w)||A(o,w)){let L=re(f);h=le(L,d),c="ml-tensor";let C=i.webnnCreateTemporaryTensor,k=i.webnnUploadTensor;if(!C||!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let x=await C(o,L,d);k(x,new Uint8Array(y.buffer,y.byteOffset,y.byteLength)),l=x}else h=y.byteLength,l=i._malloc(h),r.push(l),i.HEAPU8.set(new Uint8Array(y.buffer,y.byteOffset,h),l)}else h=y.byteLength,l=i._malloc(h),r.push(l),i.HEAPU8.set(new Uint8Array(y.buffer,y.byteOffset,h),l)}}let b=i.stackSave(),E=i.stackAlloc(4*d.length);try{d.forEach((m,A)=>i.setValue(E+A*u,m,u===4?"i32":"i64"));let y=i._OrtCreateTensor(re(f),l,h,E,d.length,yt(c));y===0&&S(`Can't create tensor for input/output. session=${o}, index=${s}.`),e.push(y)}finally{i.stackRestore(b)}},Ne=async(t,e,r,o,n,s)=>{let a=I(),i=a.PTR_SIZE,u=de.get(t);if(!u)throw new Error(`cannot run inference. invalid session id: ${t}`);let f=u[0],d=u[1],p=u[2],c=u[3],l=u[4],h=u[5],b=e.length,E=o.length,y=0,m=[],A=[],w=[],L=[],C=[],k=a.stackSave(),x=a.stackAlloc(b*i),W=a.stackAlloc(b*i),H=a.stackAlloc(E*i),Lt=a.stackAlloc(E*i);try{[y,m]=mr(s),Z("wasm prepareInputOutputTensor");for(let g=0;g<b;g++)await Ur(r[g],A,L,t,d[e[g]],e[g],l);for(let g=0;g<E;g++)await Ur(n[g],w,L,t,p[o[g]],b+o[g],l);K("wasm prepareInputOutputTensor");for(let g=0;g<b;g++)a.setValue(x+g*i,A[g],"*"),a.setValue(W+g*i,d[e[g]],"*");for(let g=0;g<E;g++)a.setValue(H+g*i,w[g],"*"),a.setValue(Lt+g*i,p[o[g]],"*");if(c&&!h){let{handle:g,outputPreferredLocations:$,outputPreferredLocationsEncoded:et}=c;if(d.length!==b)throw new Error(`input count from feeds (${b}) is expected to be always equal to model's input count (${d.length}).`);Z("wasm bindInputsOutputs");for(let B=0;B<b;B++){let j=e[B];await a._OrtBindInput(g,d[j],A[B])!==0&&S(`Can't bind input[${B}] for session=${t}.`)}for(let B=0;B<E;B++){let j=o[B];n[B]?.[3]?(C.push(w[B]),a._OrtBindOutput(g,p[j],w[B],0)!==0&&S(`Can't bind pre-allocated output[${B}] for session=${t}.`)):a._OrtBindOutput(g,p[j],0,et[j])!==0&&S(`Can't bind output[${B}] to ${$[B]} for session=${t}.`)}K("wasm bindInputsOutputs"),de.set(t,[f,d,p,c,l,!0])}a.jsepOnRunStart?.(f),a.webnnOnRunStart?.(f);let D;c?D=await a._OrtRunWithBinding(f,c.handle,E,H,y):D=await a._OrtRun(f,W,x,b,Lt,E,H,y),D!==0&&S("failed to call OrtRun().");let J=[],At=[];Z("wasm ProcessOutputTensor");for(let g=0;g<E;g++){let $=Number(a.getValue(H+g*i,"*"));if($===w[g]||C.includes(w[g])){J.push(n[g]),$!==w[g]&&a._OrtReleaseTensor($)!==0&&S("Can't release tensor.");continue}let et=a.stackSave(),B=a.stackAlloc(4*i),j=!1,O,R=0;try{a._OrtGetTensorData($,B,B+i,B+2*i,B+3*i)!==0&&S(`Can't access output tensor data on index ${g}.`);let tt=i===4?"i32":"i64",Ae=Number(a.getValue(B,tt));R=a.getValue(B+i,"*");let vt=a.getValue(B+i*2,"*"),jr=Number(a.getValue(B+i*3,tt)),q=[];for(let P=0;P<jr;P++)q.push(Number(a.getValue(vt+P*i,tt)));a._OrtFree(vt)!==0&&S("Can't free memory for tensor dims.");let Y=q.reduce((P,M)=>P*M,1);O=ze(Ae);let ye=c?.outputPreferredLocations[o[g]];if(O==="string"){if(ye==="gpu-buffer"||ye==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let P=[];for(let M=0;M<Y;M++){let X=a.getValue(R+M*i,"*"),be=a.getValue(R+(M+1)*i,"*"),rt=M===Y-1?void 0:be-X;P.push(a.UTF8ToString(X,rt))}J.push([O,q,P,"cpu"])}else if(ye==="gpu-buffer"&&Y>0){let P=a.webgpuGetBuffer;if(!P)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let M=P(R),X=le(Ae,Y);if(X===void 0||!Ve(O))throw new Error(`Unsupported data type: ${O}`);j=!0;{a.webgpuRegisterBuffer(M,t,R);let be=a.webgpuCreateDownloader(M,X,t);J.push([O,q,{gpuBuffer:M,download:async()=>{let rt=await be();return new(fe(O))(rt)},dispose:()=>{a._OrtReleaseTensor($)!==0&&S("Can't release tensor.")}},"gpu-buffer"])}}else if(ye==="ml-tensor"&&Y>0){let P=a.webnnEnsureTensor,M=a.webnnIsGraphInputOutputTypeSupported;if(!P||!M)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(le(Ae,Y)===void 0||!je(O))throw new Error(`Unsupported data type: ${O}`);if(!M(t,O,!1))throw new Error(`preferredLocation "ml-tensor" for ${O} output is not supported by current WebNN Context.`);let be=await P(t,R,Ae,q,!1);j=!0,J.push([O,q,{mlTensor:be,download:a.webnnCreateMLTensorDownloader(R,O),dispose:()=>{a.webnnReleaseTensorId(R),a._OrtReleaseTensor($)}},"ml-tensor"])}else if(ye==="ml-tensor-cpu-output"&&Y>0){let P=a.webnnCreateMLTensorDownloader(R,O)(),M=J.length;j=!0,At.push((async()=>{let X=[M,await P];return a.webnnReleaseTensorId(R),a._OrtReleaseTensor($),X})()),J.push([O,q,[],"cpu"])}else{let P=fe(O),M=new P(Y);new Uint8Array(M.buffer,M.byteOffset,M.byteLength).set(a.HEAPU8.subarray(R,R+M.byteLength)),J.push([O,q,M,"cpu"])}}finally{a.stackRestore(et),O==="string"&&R&&a._free(R),j||a._OrtReleaseTensor($)}}c&&!l&&(a._OrtClearBoundOutputs(c.handle)!==0&&S("Can't clear bound outputs."),de.set(t,[f,d,p,c,l,!1]));for(let[g,$]of await Promise.all(At))J[g][2]=$;return K("wasm ProcessOutputTensor"),J}finally{a.webnnOnRunEnd?.(f),a.stackRestore(k),r.forEach(D=>{D&&D[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(D[2].gpuBuffer)}),n.forEach(D=>{D&&D[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(D[2].gpuBuffer)}),A.forEach(D=>a._OrtReleaseTensor(D)),w.forEach(D=>a._OrtReleaseTensor(D)),L.forEach(D=>a._free(D)),y!==0&&a._OrtReleaseRunOptions(y),m.forEach(D=>a._free(D))}},Fe=t=>{let e=I(),r=de.get(t);if(!r)throw new Error("invalid session id");let o=r[0],n=e._OrtEndProfiling(o);n===0&&S("Can't get an profile file name."),e._OrtFree(n)},We=t=>{let e=[];for(let r of t){let o=r[2];!Array.isArray(o)&&"buffer"in o&&e.push(o.buffer)}return e}});var pe,z,Le,Xe,Ze,Ye,Et,St,me,he,Sn,Cr,Pr,_r,Rr,Nr,Fr,Wr,It=T(()=>{"use strict";Q();pt();ee();De();pe=()=>!!v.wasm.proxy&&typeof document<"u",Le=!1,Xe=!1,Ze=!1,St=new Map,me=(t,e)=>{let r=St.get(t);r?r.push(e):St.set(t,[e])},he=()=>{if(Le||!Xe||Ze||!z)throw new Error("worker not ready")},Sn=t=>{switch(t.data.type){case"init-wasm":Le=!1,t.data.err?(Ze=!0,Et[1](t.data.err)):(Xe=!0,Et[0]()),Ye&&(URL.revokeObjectURL(Ye),Ye=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=St.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},Cr=async()=>{if(!Xe){if(Le)throw new Error("multiple calls to 'initWasm()' detected.");if(Ze)throw new Error("previous call to 'initWasm()' failed.");if(Le=!0,pe())return new Promise((t,e)=>{z?.terminate(),dr().then(([r,o])=>{try{z=o,z.onerror=s=>e(s),z.onmessage=Sn,Et=[t,e];let n={type:"init-wasm",in:v};if(!n.in.wasm.wasmPaths&&r){let s=ke();s&&(n.in.wasm.wasmPaths=s)}z.postMessage(n),Ye=r}catch(n){e(n)}},e)});try{await Ue(v.wasm),await Ce(v),Xe=!0}catch(t){throw Ze=!0,t}finally{Le=!1}}},Pr=async t=>{if(pe())return he(),new Promise((e,r)=>{me("init-ep",[e,r]);let o={type:"init-ep",in:{epName:t,env:v}};z.postMessage(o)});await Pe(v,t)},_r=async t=>pe()?(he(),new Promise((e,r)=>{me("copy-from",[e,r]);let o={type:"copy-from",in:{buffer:t}};z.postMessage(o,[t.buffer])})):ge(t),Rr=async(t,e)=>{if(pe()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return he(),new Promise((r,o)=>{me("create",[r,o]);let n={type:"create",in:{model:t,options:{...e}}},s=[];t instanceof Uint8Array&&s.push(t.buffer),z.postMessage(n,s)})}else return _e(t,e)},Nr=async t=>{if(pe())return he(),new Promise((e,r)=>{me("release",[e,r]);let o={type:"release",in:t};z.postMessage(o)});Re(t)},Fr=async(t,e,r,o,n,s)=>{if(pe()){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 he(),new Promise((a,i)=>{me("run",[a,i]);let u=r,f={type:"run",in:{sessionId:t,inputIndices:e,inputs:u,outputIndices:o,options:s}};z.postMessage(f,We(u))})}else return Ne(t,e,r,o,n,s)},Wr=async t=>{if(pe())return he(),new Promise((e,r)=>{me("end-profiling",[e,r]);let o={type:"end-profiling",in:t};z.postMessage(o)});Fe(t)}});var kr,In,Ke,Gr=T(()=>{"use strict";Q();It();ce();Oe();bt();kr=(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()}`)}},In=t=>{switch(t[3]){case"cpu":return new V(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Ve(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:o,dispose:n}=t[2];return V.fromGpuBuffer(r,{dataType:e,dims:t[1],download:o,dispose:n})}case"ml-tensor":{let e=t[0];if(!je(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:o,dispose:n}=t[2];return V.fromMLTensor(r,{dataType:e,dims:t[1],download:o,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},Ke=class{async fetchModelAndCopyToWasmMemory(e){return _r(await Ie(e))}async loadModel(e,r){ae();let o;typeof e=="string"?o=await this.fetchModelAndCopyToWasmMemory(e):o=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Rr(o,r),ie()}async dispose(){return Nr(this.sessionId)}async run(e,r,o){ae();let n=[],s=[];Object.entries(e).forEach(c=>{let l=c[0],h=c[1],b=this.inputNames.indexOf(l);if(b===-1)throw new Error(`invalid input '${l}'`);n.push(h),s.push(b)});let a=[],i=[];Object.entries(r).forEach(c=>{let l=c[0],h=c[1],b=this.outputNames.indexOf(l);if(b===-1)throw new Error(`invalid output '${l}'`);a.push(h),i.push(b)});let u=n.map((c,l)=>kr(c,()=>`input "${this.inputNames[s[l]]}"`)),f=a.map((c,l)=>c?kr(c,()=>`output "${this.outputNames[i[l]]}"`):null),d=await Fr(this.sessionId,s,u,i,f,o),p={};for(let c=0;c<d.length;c++)p[this.outputNames[i[c]]]=a[c]??In(d[c]);return ie(),p}startProfiling(){}endProfiling(){Wr(this.sessionId)}}});var zr={};ve(zr,{OnnxruntimeWebAssemblyBackend:()=>Qe,initializeFlags:()=>$r,wasmBackend:()=>Ln});var $r,Qe,Ln,Vr=T(()=>{"use strict";Q();It();Gr();$r=()=>{(typeof v.wasm.initTimeout!="number"||v.wasm.initTimeout<0)&&(v.wasm.initTimeout=0);let t=v.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.`),v.wasm.simd=!1),typeof v.wasm.proxy!="boolean"&&(v.wasm.proxy=!1),typeof v.wasm.trace!="boolean"&&(v.wasm.trace=!1),typeof v.wasm.numThreads!="number"||!Number.isInteger(v.wasm.numThreads)||v.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)v.wasm.numThreads=1;else{let e=typeof navigator>"u"?ot("node:os").cpus().length:navigator.hardwareConcurrency;v.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Qe=class{async init(e){$r(),await Cr(),await Pr(e)}async createInferenceSessionHandler(e,r){let o=new Ke;return await o.loadModel(e,r),o}},Ln=new Qe});Q();Q();Q();var rr="1.30.0";var Ls=dt;{let t=(Vr(),st(zr)).wasmBackend;oe("webgpu",t,5),oe("webnn",t,5),oe("cpu",t,10),oe("wasm",t,10)}Object.defineProperty(v.versions,"web",{value:rr,enumerable:!0});export{Zr as InferenceSession,qt as TRACE,Z as TRACE_EVENT_BEGIN,K as TRACE_EVENT_END,ae as TRACE_FUNC_BEGIN,ie as TRACE_FUNC_END,V as Tensor,Ls as default,v as env,oe as registerBackend};
|
| 8 |
+
//# sourceMappingURL=ort.webgpu.min.mjs.map
|