diff --git a/.gitattributes b/.gitattributes index b8b9fd6..52bef80 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,3 +2,9 @@ # Marked as generated/vendored so CodeQL and diff views skip them. static/utility-apps/**/*.js linguist-generated=true linguist-vendored=true static/utility-apps/**/*.mjs linguist-generated=true linguist-vendored=true +# Compiled WebAssembly runtimes (e.g. ONNX Runtime Web) are binary artifacts. +static/utility-apps/**/*.wasm binary linguist-generated=true linguist-vendored=true + +# The transcriber artifact ships a manifest of SHA-256 checksums, so its files +# must round-trip byte-for-byte — no end-of-line normalization. +static/utility-apps/whisper-transcriber/** -text diff --git a/README.md b/README.md index 86830e1..dcbfa4e 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,7 @@ npm run serve | **Batch File Renamer** | Bulk rename with find/replace, prefixes, numbering, ZIP export | React | | **Folder Structure Builder** | Design folder trees, export bash/PowerShell scripts | React + JSZip | | **Business Calendar Generator** | Generate yearly calendars with holidays, export PDF/PNG | React + PDF | +| **Whisper Transcriber** | Transcribe audio/video or microphone input to text and subtitles, fully on-device | Transformers.js + WASM/WebGPU | --- @@ -285,6 +286,7 @@ by mirroring files under `i18n//docusaurus-plugin-content-*/`. | `npm run lint` | Run ESLint over src, api and scripts | | `npm run sitemap:sections` | Generate sectioned sitemaps | | `npm run sync:webstep-viewer` | Sync WebSTEP viewer embed | +| `npm run sync:whisper-transcriber` | Build and republish the Whisper Transcriber artifact | --- @@ -324,9 +326,17 @@ AUTH_REDIRECT_URL=http://localhost:3000/auth/callback ### Adding a New Utility 1. Add utility metadata to `src/data/utilities.ts` -2. Create page route in `src/pages/utilities/` -3. Add documentation in `docs/utilities/` -4. Place standalone build assets in `static/utility-apps//` if needed +2. Add the slug and shell config to `src/data/utilityShellPages.tsx` +3. Create page route in `src/pages/utilities/` +4. Add documentation in `docs/utilities/` plus the five `i18n//…/utilities/` mirrors, and list it in `sidebars.ts` and `utilities/overview.mdx` +5. Add the catalog name/description to all six `src/i18n/locales/*.ts` dictionaries +6. Place standalone build assets in `static/utility-apps//` if needed + +Device capabilities (camera, microphone) are delegated **per utility** through the +`iframeAllow` field of `UtilityPageConfig`, paired with a path-scoped +`Permissions-Policy` rule in `vercel.json`. Never widen the global policy: the +site default stays `microphone=()`, and only the routes of the utility that +needs a device relax it. See `whisper-transcriber` for the reference wiring. --- diff --git a/docs/utilities/overview.mdx b/docs/utilities/overview.mdx index 3031101..cba2903 100644 --- a/docs/utilities/overview.mdx +++ b/docs/utilities/overview.mdx @@ -24,6 +24,7 @@ Each calculator below launches the same standalone page machinists already use. - [Busbar Calculator](./busbar-calculator.mdx) - [Gear Pair Calculator](./gear-pair-calculator.mdx) - [WIKA Log Analyzer](./wikalog-analyzer.mdx) +- [Whisper Transcriber](./whisper-transcriber.mdx) - [Tube Sheet Generator](./tube-sheet-generator.mdx) - [WebSTEP Viewer](./webstep-viewer.mdx) - [Engineering Prompt Catalog](./engineering-prompt-catalog.mdx) diff --git a/docs/utilities/whisper-transcriber.mdx b/docs/utilities/whisper-transcriber.mdx new file mode 100644 index 0000000..1e47bcd --- /dev/null +++ b/docs/utilities/whisper-transcriber.mdx @@ -0,0 +1,130 @@ +--- +title: Whisper Transcriber +description: Transcribe audio and video files or microphone recordings to editable text with Whisper running entirely in your browser, then export TXT, SRT, or WebVTT. +slug: /utilities/whisper-transcriber +image: /img/og/utilities/whisper-transcriber.png +keywords: + - whisper transcriber + - browser speech to text + - offline transcription + - meeting notes + - subtitle generator + - srt webvtt export + - webgpu wasm inference +--- + +import Head from '@docusaurus/Head'; + +# Whisper Transcriber + +Turn recordings into editable text without sending them anywhere. Audio is decoded, resampled, and transcribed by a Whisper model that runs inside a Web Worker in your own browser — there is no transcription server behind this utility. + +![Whisper Transcriber overview card](/img/og/utilities/whisper-transcriber.webp) + +Open utility + + + + + + +## What it does + +Whisper Transcriber converts speech into text on your own machine. You give it an audio or video file — or record straight from the microphone — and it produces a full transcript plus timestamped segments you can edit and export as TXT, SRT, or WebVTT subtitles. + +Everything happens in the browser tab: the media is decoded and downmixed to mono 16 kHz, the OpenAI Whisper model runs through Transformers.js on ONNX Runtime Web, and the result never leaves the page. Nothing is uploaded, queued, or stored on a server. + +The app is built as a standalone micro-application under `static/utility-apps/whisper-transcriber`. The CAD AutoScript shell embeds it in a same-origin iframe, so the transcriber can evolve in its own repository while sharing this site's catalog, article, reactions, comments, and access layer. + +## First run: the model download + +The first time you press **Transcribe**, the browser downloads the multilingual Whisper Tiny weights (about 77 MB) from the Hugging Face Hub and caches them. This is the only network traffic the utility generates, and it carries no audio — only the model files. + +- Later runs start from that cache and need no network at all. +- Clearing site data, using a private window, or browser storage pressure can evict the cache and trigger a fresh download. +- The model revision is pinned to a fixed commit, so the same version is fetched every time. + +## When to use it + +- Writing up meeting, supplier-call, or design-review notes from a recording. +- Turning site walkthrough and inspection videos into searchable text. +- Dictating punch lists or QA observations instead of typing them on site. +- Producing SRT or WebVTT subtitles for internal training and handover videos. +- Transcribing material you are not allowed to upload to a third-party service. + +## Workflow + +1. Drop an audio or video file into the drop zone, or press **Record microphone** and stop when you are done. +2. Wait for the status line to report the media as ready — it shows duration, and whether the windowed pipeline will be used. +3. Choose language, timestamps, and runtime if the defaults do not suit the recording. +4. Press **Transcribe**. On the first run, the progress bar shows the model download; after that it goes straight to inference. +5. Correct the transcript in place — the text area is editable. +6. Copy the text, or export TXT, SRT, or WebVTT. +7. Press **Clear session** to drop the media, transcript, and loaded model from memory. + +## Settings + +| Setting | Options | What it changes | +| --- | --- | --- | +| Model | Whisper Tiny (multilingual, ~77 MB) | The weights used for recognition and the size of the first download. | +| Language | Automatic, English, Russian | Automatic lets Whisper detect the language; picking one explicitly is more reliable on short or noisy clips. | +| Timestamps | Segment, Off | Segment produces the timestamped list that SRT and WebVTT export needs. Off returns plain text only. | +| Runtime | Auto (WebGPU → WASM), WASM only, WebGPU preferred | Auto uses the GPU when the browser exposes WebGPU and silently falls back to WASM. WASM only is the slower but most compatible path. | + +## Long recordings + +Short clips are decoded in one pass. Longer media is probed first and then run through a conveyor of roughly 30-second mono windows with 5 seconds of overlap, so only one window of audio sits in memory at a time while the model stays loaded between windows. The transcript fills in window by window, and **Cancel** stops the run without losing what has already been produced. + +## Privacy + +- Audio, video, filenames, transcript text, and your edits stay in the page. They are never sent to CAD AutoScript, to analytics, or to any transcription API. +- The only outbound requests are the pinned model files from the Hugging Face Hub. +- The microphone is only accessed after you press **Record microphone**, and this is the only utility on the site that is granted microphone permission at all. +- **Clear session** releases the microphone stream, the audio buffers, and the loaded model. Closing the tab does the same. +- Nothing is written to your account, and no transcript history is kept — save or export anything you want to keep before you leave the page. + +## Requirements and limits + +- A current Chromium, Firefox, or Safari release with WebAssembly support. WebGPU is optional and only adds speed. +- Roughly 77 MB of free browser cache for the model, plus working memory proportional to the recording length. +- Whisper Tiny favours speed over accuracy: expect to proofread technical vocabulary, part numbers, and proper names. +- Heavy accents, crosstalk, and noisy site audio degrade the result — a closer microphone helps far more than any setting here. +- Speaker diarization ("who said what"), live rolling transcription, and larger Whisper models are not part of this version. +- ⚠️ Transcripts are a drafting aid. Verify them against the recording before quoting them in a report, a minute of meeting, or any contractual document. + +## Related tools + +- [WIKA CPG1500 Log Analyzer](./wikalog-analyzer.mdx) +- [PDF Number Extractor](./pdf-number-extractor.mdx) +- [Focus Planner](./focus-planner.mdx) + +## Feedback / bug report + +- [Open a GitHub issue](https://github.com/YurMil/cadautoscript.com/issues) +- Email or DM with the slug `whisper-transcriber` so we can reproduce the issue. diff --git a/eslint.config.mjs b/eslint.config.mjs index 72c6237..9dcbd45 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -56,7 +56,7 @@ export default tseslint.config( }, { // The logger wrapper and build scripts are allowed to use the console. - files: ['src/lib/logger.ts', 'scripts/**/*.js', 'api/**/*.ts'], + files: ['src/lib/logger.ts', 'scripts/**/*.{js,mjs}', 'api/**/*.ts'], rules: { 'no-console': 'off', }, diff --git a/i18n/de/docusaurus-plugin-content-docs/current/utilities/overview.mdx b/i18n/de/docusaurus-plugin-content-docs/current/utilities/overview.mdx index 664de5d..a898ba0 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/utilities/overview.mdx +++ b/i18n/de/docusaurus-plugin-content-docs/current/utilities/overview.mdx @@ -24,6 +24,7 @@ Jedes unten aufgeführte Dienstprogramm startet dieselbe eigenständige Seite, d - [Busbar Calculator](./busbar-calculator.mdx) - [Gear Pair Calculator](../gear-pair-calculator/) - [WIKA Log Analyzer](./wikalog-analyzer.mdx) +- [Whisper Transcriber](./whisper-transcriber.mdx) - [Tube Sheet Generator](./tube-sheet-generator.mdx) - [WebSTEP Viewer](./webstep-viewer.mdx) - [Engineering Prompt Catalog](./engineering-prompt-catalog.mdx) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx b/i18n/de/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx new file mode 100644 index 0000000..b2e7f38 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx @@ -0,0 +1,130 @@ +--- +title: Whisper Transcriber +description: Audio- und Videodateien oder Mikrofonaufnahmen mit Whisper vollständig im Browser in bearbeitbaren Text transkribieren und als TXT, SRT oder WebVTT exportieren. +slug: /utilities/whisper-transcriber +image: /img/og/utilities/whisper-transcriber.png +keywords: + - whisper transkription + - spracherkennung im browser + - offline transkription + - besprechungsprotokoll + - untertitel generator + - srt webvtt export + - webgpu wasm inferenz +--- + +import Head from '@docusaurus/Head'; + +# Whisper Transcriber + +Verwandeln Sie Aufnahmen in bearbeitbaren Text, ohne sie irgendwohin zu senden. Das Audio wird dekodiert, umgerechnet und von einem Whisper-Modell in einem Web Worker in Ihrem eigenen Browser transkribiert — hinter diesem Werkzeug steht kein Transkriptionsserver. + +![Übersichtskarte Whisper Transcriber](/img/og/utilities/whisper-transcriber.webp) + +Utility öffnen + + + + + + +## Was das Werkzeug leistet + +Whisper Transcriber wandelt Sprache auf Ihrem eigenen Rechner in Text um. Sie übergeben eine Audio- oder Videodatei — oder nehmen direkt über das Mikrofon auf — und erhalten ein vollständiges Transkript samt Segmenten mit Zeitstempeln, die Sie bearbeiten und als TXT, SRT oder WebVTT exportieren können. + +Alles läuft im Browser-Tab: Die Medien werden dekodiert und auf Mono 16 kHz gemischt, das OpenAI-Whisper-Modell läuft über Transformers.js auf ONNX Runtime Web, und das Ergebnis verlässt die Seite nicht. Nichts wird hochgeladen, in eine Warteschlange gestellt oder auf einem Server gespeichert. + +Die Anwendung ist als eigenständige Mikroanwendung unter `static/utility-apps/whisper-transcriber` aufgebaut. Die CAD-AutoScript-Shell bettet sie in einem Same-Origin-iframe ein, sodass der Transcriber sich in seinem eigenen Repository weiterentwickeln kann und zugleich Katalog, Artikel, Reaktionen, Kommentare und Zugriffsschicht dieser Website nutzt. + +## Erster Start: der Modell-Download + +Beim ersten Klick auf **Transcribe** lädt der Browser die Gewichte des mehrsprachigen Whisper-Tiny-Modells (rund 77 MB) vom Hugging Face Hub und legt sie im Cache ab. Das ist der einzige Netzwerkverkehr dieses Werkzeugs, und er enthält kein Audio — nur die Modelldateien. + +- Spätere Läufe greifen auf den Cache zu und benötigen überhaupt kein Netz. +- Das Löschen der Websitedaten, ein privates Fenster oder Speicherdruck im Browser können den Cache verdrängen und einen erneuten Download auslösen. +- Die Modellrevision ist auf einen festen Commit gepinnt, sodass jedes Mal dieselbe Version geladen wird. + +## Wann Sie es einsetzen + +- Protokolle von Besprechungen, Lieferantengesprächen oder Design-Reviews aus einer Aufnahme erstellen. +- Videobegehungen und Inspektionen in durchsuchbaren Text überführen. +- Mängellisten und QA-Beobachtungen vor Ort diktieren statt tippen. +- SRT- oder WebVTT-Untertitel für interne Schulungs- und Übergabevideos erzeugen. +- Material transkribieren, das nicht zu einem Drittanbieterdienst hochgeladen werden darf. + +## Arbeitsablauf + +1. Ziehen Sie eine Audio- oder Videodatei in die Ablagefläche oder drücken Sie **Record microphone** und stoppen Sie, wenn Sie fertig sind. +2. Warten Sie, bis die Statuszeile die Medien als bereit meldet — sie zeigt die Dauer und ob die Fensterpipeline verwendet wird. +3. Passen Sie Sprache, Zeitstempel und Runtime an, falls die Voreinstellungen zur Aufnahme nicht passen. +4. Drücken Sie **Transcribe**. Beim ersten Lauf zeigt der Fortschrittsbalken den Modell-Download, danach geht es direkt zur Inferenz. +5. Korrigieren Sie das Transkript direkt — das Textfeld ist editierbar. +6. Kopieren Sie den Text oder exportieren Sie TXT, SRT oder WebVTT. +7. Mit **Clear session** werden Medien, Transkript und geladenes Modell aus dem Speicher entfernt. + +## Einstellungen + +| Einstellung | Optionen | Wirkung | +| --- | --- | --- | +| Model | Whisper Tiny (mehrsprachig, ~77 MB) | Die Gewichte für die Erkennung und der Umfang des ersten Downloads. | +| Language | Automatic, English, Russian | Automatic lässt Whisper die Sprache erkennen; eine explizite Wahl ist bei kurzen oder verrauschten Clips zuverlässiger. | +| Timestamps | Segment, Off | Segment erzeugt die Liste mit Zeitstempeln, die der SRT- und WebVTT-Export benötigt. Off liefert nur reinen Text. | +| Runtime | Auto (WebGPU → WASM), WASM only, WebGPU preferred | Auto nutzt die GPU, wenn der Browser WebGPU bereitstellt, und fällt still auf WASM zurück. WASM only ist langsamer, aber am kompatibelsten. | + +## Lange Aufnahmen + +Kurze Clips werden in einem Durchgang dekodiert. Längere Medien werden zunächst geprüft und dann durch ein Fließband aus etwa 30-Sekunden-Fenstern mit 5 Sekunden Überlappung geführt: Es liegt immer nur ein Fenster im Speicher, während das Modell zwischen den Fenstern geladen bleibt. Das Transkript füllt sich Fenster für Fenster, und **Cancel** stoppt den Lauf, ohne das bereits Erzeugte zu verlieren. + +## Datenschutz + +- Audio, Video, Dateinamen, Transkripttext und Ihre Änderungen bleiben auf der Seite. Sie werden weder an CAD AutoScript noch an Analytics oder eine Transkriptions-API gesendet. +- Die einzigen ausgehenden Anfragen sind die gepinnten Modelldateien vom Hugging Face Hub. +- Auf das Mikrofon wird erst nach dem Klick auf **Record microphone** zugegriffen, und dies ist die einzige Utility der Website, der überhaupt eine Mikrofonberechtigung erteilt wird. +- **Clear session** gibt den Mikrofon-Stream, die Audiopuffer und das geladene Modell frei. Das Schließen des Tabs bewirkt dasselbe. +- Es wird nichts in Ihrem Konto gespeichert und keine Transkript-Historie geführt — sichern oder exportieren Sie alles Wichtige, bevor Sie die Seite verlassen. + +## Voraussetzungen und Grenzen + +- Eine aktuelle Chromium-, Firefox- oder Safari-Version mit WebAssembly-Unterstützung. WebGPU ist optional und bringt nur Geschwindigkeit. +- Rund 77 MB freier Browser-Cache für das Modell sowie Arbeitsspeicher proportional zur Aufnahmelänge. +- Whisper Tiny bevorzugt Geschwindigkeit vor Genauigkeit: Fachbegriffe, Teilenummern und Eigennamen sollten Sie nachlesen. +- Starke Akzente, Durcheinanderreden und Baustellenlärm verschlechtern das Ergebnis — ein näheres Mikrofon hilft weit mehr als jede Einstellung hier. +- Sprechertrennung, laufende Live-Transkription und größere Whisper-Modelle sind nicht Teil dieser Version. +- ⚠️ Transkripte sind eine Entwurfshilfe. Prüfen Sie sie gegen die Aufnahme, bevor Sie daraus in einem Bericht, Protokoll oder vertraglichen Dokument zitieren. + +## Verwandte Werkzeuge + +- [WIKA CPG1500 Log Analyzer](./wikalog-analyzer.mdx) +- [PDF Number Extractor](./pdf-number-extractor.mdx) +- [Focus Planner](./focus-planner.mdx) + +## Feedback / Fehlermeldung + +- [Issue auf GitHub eröffnen](https://github.com/YurMil/cadautoscript.com/issues) +- Schreiben Sie uns mit dem Slug `whisper-transcriber`, damit wir das Problem nachstellen können. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/utilities/overview.mdx b/i18n/es/docusaurus-plugin-content-docs/current/utilities/overview.mdx index 9e04bf7..a87b0b2 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/utilities/overview.mdx +++ b/i18n/es/docusaurus-plugin-content-docs/current/utilities/overview.mdx @@ -24,6 +24,7 @@ Cada calculadora a continuación lanza la misma página independiente que los ma - [Busbar Calculator](./busbar-calculator.mdx) - [Gear Pair Calculator](../gear-pair-calculator/) - [WIKA Log Analyzer](./wikalog-analyzer.mdx) +- [Whisper Transcriber](./whisper-transcriber.mdx) - [Generador de placas de tubos](./tube-sheet-generator.mdx) - [Visor WebSTEP](./webstep-viewer.mdx) - [Catálogo de prompts de ingeniería](./engineering-prompt-catalog.mdx) diff --git a/i18n/es/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx b/i18n/es/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx new file mode 100644 index 0000000..5a8e8e4 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx @@ -0,0 +1,130 @@ +--- +title: Whisper Transcriber +description: Transcribe archivos de audio y vídeo o grabaciones de micrófono a texto editable con Whisper ejecutándose por completo en el navegador, y exporta TXT, SRT o WebVTT. +slug: /utilities/whisper-transcriber +image: /img/og/utilities/whisper-transcriber.png +keywords: + - transcripción whisper + - voz a texto en el navegador + - transcripción sin conexión + - acta de reunión + - generador de subtítulos + - exportar srt webvtt + - inferencia webgpu wasm +--- + +import Head from '@docusaurus/Head'; + +# Whisper Transcriber + +Convierte grabaciones en texto editable sin enviarlas a ninguna parte. El audio se decodifica, se remuestrea y lo transcribe un modelo Whisper que se ejecuta en un Web Worker dentro de tu propio navegador: detrás de esta utilidad no hay ningún servidor de transcripción. + +![Tarjeta de presentación de Whisper Transcriber](/img/og/utilities/whisper-transcriber.webp) + +Abrir utilidad + + + + + + +## Qué hace + +Whisper Transcriber convierte el habla en texto en tu propio equipo. Le das un archivo de audio o vídeo —o grabas directamente desde el micrófono— y obtienes una transcripción completa junto con segmentos con marcas de tiempo que puedes editar y exportar como TXT, SRT o WebVTT. + +Todo ocurre en la pestaña del navegador: el medio se decodifica y se mezcla a mono 16 kHz, el modelo Whisper de OpenAI se ejecuta mediante Transformers.js sobre ONNX Runtime Web y el resultado no sale de la página. Nada se sube, se encola ni se almacena en un servidor. + +La aplicación está construida como una microaplicación independiente en `static/utility-apps/whisper-transcriber`. El shell de CAD AutoScript la incrusta en un iframe del mismo origen, de modo que el transcriptor puede evolucionar en su propio repositorio mientras comparte el catálogo, el artículo, las reacciones, los comentarios y la capa de acceso de este sitio. + +## Primera ejecución: la descarga del modelo + +La primera vez que pulsas **Transcribe**, el navegador descarga los pesos del modelo multilingüe Whisper Tiny (unos 77 MB) desde Hugging Face Hub y los guarda en caché. Ese es el único tráfico de red que genera la utilidad, y no contiene audio: solo los archivos del modelo. + +- Las ejecuciones posteriores parten de esa caché y no necesitan red en absoluto. +- Borrar los datos del sitio, usar una ventana privada o la presión de almacenamiento del navegador pueden desalojar la caché y provocar una nueva descarga. +- La revisión del modelo está fijada a un commit concreto, así que siempre se descarga la misma versión. + +## Cuándo usarla + +- Redactar actas de reuniones, llamadas con proveedores o revisiones de diseño a partir de una grabación. +- Convertir vídeos de recorridos e inspecciones en texto que se puede buscar. +- Dictar listas de pendientes y observaciones de calidad en obra en lugar de teclearlas. +- Producir subtítulos SRT o WebVTT para vídeos internos de formación y traspaso. +- Transcribir material que no puedes subir a un servicio de terceros. + +## Flujo de trabajo + +1. Arrastra un archivo de audio o vídeo a la zona de carga, o pulsa **Record microphone** y detén la grabación al terminar. +2. Espera a que la línea de estado indique que el medio está listo: muestra la duración y si se usará la tubería por ventanas. +3. Cambia el idioma, las marcas de tiempo y el runtime si los valores por defecto no encajan con la grabación. +4. Pulsa **Transcribe**. En la primera ejecución la barra de progreso muestra la descarga del modelo; después pasa directamente a la inferencia. +5. Corrige la transcripción sobre la marcha: el área de texto es editable. +6. Copia el texto o exporta TXT, SRT o WebVTT. +7. Pulsa **Clear session** para liberar de la memoria el medio, la transcripción y el modelo cargado. + +## Ajustes + +| Ajuste | Opciones | Qué cambia | +| --- | --- | --- | +| Model | Whisper Tiny (multilingüe, ~77 MB) | Los pesos usados para el reconocimiento y el tamaño de la primera descarga. | +| Language | Automatic, English, Russian | Automatic deja que Whisper detecte el idioma; elegirlo explícitamente es más fiable en clips cortos o ruidosos. | +| Timestamps | Segment, Off | Segment genera la lista con marcas de tiempo que necesita la exportación a SRT y WebVTT. Off devuelve solo texto plano. | +| Runtime | Auto (WebGPU → WASM), WASM only, WebGPU preferred | Auto usa la GPU cuando el navegador expone WebGPU y recurre a WASM de forma transparente. WASM only es más lento pero el más compatible. | + +## Grabaciones largas + +Los clips cortos se decodifican de una sola pasada. Los medios más largos se analizan primero y luego se procesan mediante una cadena de ventanas de unos 30 segundos con 5 segundos de solapamiento, de modo que en memoria solo hay una ventana a la vez mientras el modelo permanece cargado entre ellas. La transcripción se va rellenando ventana a ventana, y **Cancel** detiene la ejecución sin perder lo ya producido. + +## Privacidad + +- El audio, el vídeo, los nombres de archivo, el texto de la transcripción y tus ediciones se quedan en la página. Nunca se envían a CAD AutoScript, a analítica ni a ninguna API de transcripción. +- Las únicas peticiones salientes son los archivos del modelo fijados en Hugging Face Hub. +- Solo se accede al micrófono después de pulsar **Record microphone**, y esta es la única utilidad del sitio a la que se concede permiso de micrófono. +- **Clear session** libera el flujo del micrófono, los búferes de audio y el modelo cargado. Cerrar la pestaña hace lo mismo. +- No se guarda nada en tu cuenta ni se conserva historial de transcripciones: guarda o exporta lo que quieras conservar antes de salir de la página. + +## Requisitos y límites + +- Una versión actual de Chromium, Firefox o Safari con soporte de WebAssembly. WebGPU es opcional y solo aporta velocidad. +- Unos 77 MB libres de caché del navegador para el modelo, además de memoria de trabajo proporcional a la duración de la grabación. +- Whisper Tiny prioriza la velocidad sobre la precisión: revisa el vocabulario técnico, los números de pieza y los nombres propios. +- Los acentos marcados, las voces superpuestas y el ruido de obra degradan el resultado; acercar el micrófono ayuda mucho más que cualquier ajuste de aquí. +- La separación por hablantes, la transcripción continua en directo y los modelos Whisper mayores no forman parte de esta versión. +- ⚠️ Las transcripciones son una ayuda de redacción. Contrástalas con la grabación antes de citarlas en un informe, un acta o cualquier documento contractual. + +## Herramientas relacionadas + +- [WIKA CPG1500 Log Analyzer](./wikalog-analyzer.mdx) +- [PDF Number Extractor](./pdf-number-extractor.mdx) +- [Focus Planner](./focus-planner.mdx) + +## Comentarios / informe de errores + +- [Abrir una incidencia en GitHub](https://github.com/YurMil/cadautoscript.com/issues) +- Escríbenos indicando el slug `whisper-transcriber` para que podamos reproducir el problema. diff --git a/i18n/et/docusaurus-plugin-content-docs/current/utilities/overview.mdx b/i18n/et/docusaurus-plugin-content-docs/current/utilities/overview.mdx index c27b292..1f395e0 100644 --- a/i18n/et/docusaurus-plugin-content-docs/current/utilities/overview.mdx +++ b/i18n/et/docusaurus-plugin-content-docs/current/utilities/overview.mdx @@ -24,6 +24,7 @@ Iga allolev kalkulaator käivitab sama eraldiseisva lehe, mida masinistid juba k - [Busbar Calculator](./busbar-calculator.mdx) - [Gear Pair Calculator](../gear-pair-calculator/) - [WIKA Log Analyzer](./wikalog-analyzer.mdx) +- [Whisper Transcriber](./whisper-transcriber.mdx) - [Tube Sheet Generator](./tube-sheet-generator.mdx) - [WebSTEP Viewer](./webstep-viewer.mdx) - [Engineering Prompt Catalog](./engineering-prompt-catalog.mdx) diff --git a/i18n/et/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx b/i18n/et/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx new file mode 100644 index 0000000..c3d7261 --- /dev/null +++ b/i18n/et/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx @@ -0,0 +1,130 @@ +--- +title: Whisper Transcriber +description: Transkribeeri heli- ja videofaile või mikrofonisalvestisi redigeeritavaks tekstiks — Whisper töötab täielikult brauseris, eksport TXT, SRT ja WebVTT vormingusse. +slug: /utilities/whisper-transcriber +image: /img/og/utilities/whisper-transcriber.png +keywords: + - whisper transkriptsioon + - kõne tekstiks brauseris + - võrguühenduseta transkribeerimine + - koosoleku protokoll + - subtiitrite generaator + - srt webvtt eksport + - webgpu wasm järeldus +--- + +import Head from '@docusaurus/Head'; + +# Whisper Transcriber + +Muuda salvestised redigeeritavaks tekstiks, saatmata neid kuhugi. Heli dekodeeritakse, teisendatakse ja transkribeeritakse Whisperi mudeliga, mis töötab Web Workeris sinu enda brauseris — selle tööriista taga ei ole ühtegi transkribeerimisserverit. + +![Whisper Transcriberi ülevaatekaart](/img/og/utilities/whisper-transcriber.webp) + +Ava utiliit + + + + + + +## Mida tööriist teeb + +Whisper Transcriber muudab kõne tekstiks sinu enda masinas. Annad talle heli- või videofaili — või salvestad otse mikrofoniga — ja saad täieliku transkriptsiooni koos ajatemplitega segmentidega, mida saab redigeerida ja eksportida TXT, SRT või WebVTT vormingusse. + +Kõik toimub brauserisakil: meedia dekodeeritakse ja miksitakse mono 16 kHz kujule, OpenAI Whisperi mudel jookseb Transformers.js kaudu ONNX Runtime Webi peal ja tulemus ei lahku lehelt. Midagi ei laadita üles, ei panda järjekorda ega salvestata serverisse. + +Rakendus on ehitatud iseseisva mikrorakendusena kaustas `static/utility-apps/whisper-transcriber`. CAD AutoScripti kest põimib selle sama päritoluga iframe'i, nii et transkribeerija saab areneda omaenda repositooriumis, kasutades samal ajal selle saidi kataloogi, artiklit, reaktsioone, kommentaare ja ligipääsukihti. + +## Esimene käivitus: mudeli allalaadimine + +Esimesel korral, kui vajutad **Transcribe**, laadib brauser Hugging Face Hubist alla mitmekeelse Whisper Tiny mudeli kaalud (umbes 77 MB) ja puhverdab need. See on ainus võrguliiklus, mida tööriist tekitab, ja see ei sisalda sinu heli — ainult mudelifaile. + +- Hilisemad käivitused kasutavad puhvrit ega vaja üldse võrku. +- Saidi andmete kustutamine, privaatne aken või brauseri salvestusruumi surve võivad puhvri välja tõrjuda ja põhjustada uue allalaadimise. +- Mudeli revisjon on kinnitatud kindla commit'i külge, nii et iga kord laaditakse sama versioon. + +## Millal seda kasutada + +- Koosolekute, tarnijakõnede või projektiülevaatuste protokollide koostamine salvestise põhjal. +- Objektiringkäikude ja ülevaatuste videote muutmine otsitavaks tekstiks. +- Puudusteloendite ja kvaliteedimärkuste dikteerimine objektil tippimise asemel. +- SRT- või WebVTT-subtiitrite tegemine sisekoolituste ja üleandmisvideote jaoks. +- Sellise materjali transkribeerimine, mida ei tohi kolmanda osapoole teenusesse üles laadida. + +## Töövoog + +1. Lohista heli- või videofail alale või vajuta **Record microphone** ja peata salvestus, kui valmis. +2. Oota, kuni olekurida teatab, et meedia on valmis — seal on näha kestus ja kas kasutatakse akendega konveierit. +3. Muuda keelt, ajatempleid ja käituskeskkonda, kui vaikeväärtused salvestisele ei sobi. +4. Vajuta **Transcribe**. Esimesel korral näitab edenemisriba mudeli allalaadimist, seejärel algab kohe tuvastus. +5. Paranda transkriptsiooni kohapeal — tekstiväli on redigeeritav. +6. Kopeeri tekst või ekspordi TXT, SRT või WebVTT. +7. Vajuta **Clear session**, et vabastada mälust meedia, transkriptsioon ja laaditud mudel. + +## Seaded + +| Seade | Valikud | Mida muudab | +| --- | --- | --- | +| Model | Whisper Tiny (mitmekeelne, ~77 MB) | Tuvastuseks kasutatavad kaalud ja esimese allalaadimise maht. | +| Language | Automatic, English, Russian | Automatic laseb Whisperil keele ise tuvastada; selge valik on lühikeste või mürarikaste klippide puhul usaldusväärsem. | +| Timestamps | Segment, Off | Segment annab ajatemplitega loendi, mida SRT- ja WebVTT-eksport vajab. Off tagastab ainult teksti. | +| Runtime | Auto (WebGPU → WASM), WASM only, WebGPU preferred | Auto kasutab GPU-d, kui brauser pakub WebGPU-d, ja langeb märkamatult WASM-ile. WASM only on aeglasem, kuid kõige ühilduvam. | + +## Pikad salvestised + +Lühikesed klipid dekodeeritakse ühe korraga. Pikem meedia uuritakse esmalt läbi ja seejärel aetakse umbes 30-sekundiliste akende konveierist läbi 5-sekundilise ülekattega: mälus on korraga ainult üks aken, samal ajal kui mudel jääb akende vahel laaditud olekusse. Transkriptsioon täitub aken akna haaval ja **Cancel** peatab töö, kaotamata juba saadud teksti. + +## Privaatsus + +- Heli, video, failinimed, transkriptsiooni tekst ja sinu muudatused jäävad lehele. Neid ei saadeta CAD AutoScripti, analüütikasse ega ühessegi transkribeerimise API-sse. +- Ainsad väljuvad päringud on kinnitatud mudelifailid Hugging Face Hubist. +- Mikrofoni kasutatakse alles pärast **Record microphone** vajutamist ja see on saidi ainus utiliit, millele mikrofoniluba üldse antakse. +- **Clear session** vabastab mikrofonivoo, helipuhvrid ja laaditud mudeli. Sakiakna sulgemine teeb sama. +- Sinu kontosse ei salvestata midagi ja transkriptsioonide ajalugu ei peeta — salvesta või ekspordi vajalik enne lehelt lahkumist. + +## Nõuded ja piirangud + +- Ajakohane Chromiumi, Firefoxi või Safari versioon WebAssembly toega. WebGPU on valikuline ja annab ainult kiirust. +- Umbes 77 MB vaba brauseripuhvrit mudeli jaoks ning salvestise pikkusega võrdeline töömälu. +- Whisper Tiny eelistab kiirust täpsusele: tehnilised terminid, detailinumbrid ja pärisnimed tuleb üle lugeda. +- Tugev aktsent, üksteisele rääkimine ja objektimüra halvendavad tulemust — lähemal olev mikrofon aitab palju rohkem kui ükski siinne seade. +- Kõnelejate eristamine, pidev reaalajas transkribeerimine ja suuremad Whisperi mudelid ei kuulu sellesse versiooni. +- ⚠️ Transkriptsioon on mustandiabi. Kontrolli seda salvestise vastu, enne kui tsiteerid seda aruandes, protokollis või mis tahes lepingulises dokumendis. + +## Seotud tööriistad + +- [WIKA CPG1500 Log Analyzer](./wikalog-analyzer.mdx) +- [PDF Number Extractor](./pdf-number-extractor.mdx) +- [Focus Planner](./focus-planner.mdx) + +## Tagasiside / veateade + +- [Ava GitHubis probleem](https://github.com/YurMil/cadautoscript.com/issues) +- Kirjuta meile slug'iga `whisper-transcriber`, et saaksime probleemi taasesitada. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/utilities/overview.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/utilities/overview.mdx index 17a77df..c776321 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/utilities/overview.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/utilities/overview.mdx @@ -24,6 +24,7 @@ import UtilityAccessTable from '@site/src/components/Utilities/UtilityAccessTabl - [Busbar Calculator](./busbar-calculator.mdx) - [Gear Pair Calculator](../gear-pair-calculator/) - [WIKA Log Analyzer](./wikalog-analyzer.mdx) +- [Whisper Transcriber](./whisper-transcriber.mdx) - [Tube Sheet Generator](./tube-sheet-generator.mdx) - [WebSTEP Viewer](./webstep-viewer.mdx) - [Engineering Prompt Catalog](./engineering-prompt-catalog.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx new file mode 100644 index 0000000..292c5ff --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx @@ -0,0 +1,130 @@ +--- +title: Whisper Transcriber +description: 'Расшифровка аудио- и видеофайлов или записи с микрофона в редактируемый текст: Whisper работает целиком в браузере, экспорт в TXT, SRT и WebVTT.' +slug: /utilities/whisper-transcriber +image: /img/og/utilities/whisper-transcriber.png +keywords: + - расшифровка аудио + - speech to text в браузере + - офлайн транскрибация + - протокол совещания + - генератор субтитров + - экспорт srt webvtt + - whisper webgpu wasm +--- + +import Head from '@docusaurus/Head'; + +# Whisper Transcriber + +Превращайте записи в редактируемый текст, никуда их не отправляя. Аудио декодируется, приводится к нужной частоте и распознаётся моделью Whisper внутри Web Worker прямо в вашем браузере — сервера расшифровки за этой утилитой нет. + +![Обзорная карточка Whisper Transcriber](/img/og/utilities/whisper-transcriber.webp) + +Открыть утилиту + + + + + + +## Что делает утилита + +Whisper Transcriber переводит речь в текст на вашем же компьютере. Вы даёте ей аудио- или видеофайл — либо записываете звук прямо с микрофона — и получаете полный транскрипт плюс сегменты с таймкодами, которые можно отредактировать и выгрузить в TXT, SRT или WebVTT. + +Всё происходит во вкладке браузера: медиа декодируется и сводится в моно 16 кГц, модель OpenAI Whisper выполняется через Transformers.js на ONNX Runtime Web, а результат не покидает страницу. Ничего не загружается на сервер, не ставится в очередь и не сохраняется. + +Приложение собрано как самостоятельное микро-приложение в `static/utility-apps/whisper-transcriber`. Оболочка CAD AutoScript встраивает его в iframe того же origin, поэтому транскрайбер развивается в собственном репозитории, но использует общий каталог, статью, реакции, комментарии и слой доступа этого сайта. + +## Первый запуск: загрузка модели + +При первом нажатии **Transcribe** браузер скачивает веса мультиязычной модели Whisper Tiny (около 77 МБ) с Hugging Face Hub и кэширует их. Это единственный сетевой трафик утилиты, и он не содержит вашего аудио — только файлы модели. + +- Последующие запуски берут модель из кэша и вообще не требуют сети. +- Очистка данных сайта, режим инкогнито или нехватка места в хранилище браузера могут вытеснить кэш и вызвать повторную загрузку. +- Ревизия модели закреплена конкретным коммитом, поэтому каждый раз скачивается одна и та же версия. + +## Когда пригодится + +- Оформление протокола совещания, звонка с поставщиком или разбора проекта по записи. +- Превращение видеообходов и инспекций в текст, по которому можно искать. +- Надиктовка списков замечаний и наблюдений QA вместо набора текста на объекте. +- Подготовка субтитров SRT или WebVTT для внутренних обучающих видео и передачи дел. +- Расшифровка материалов, которые нельзя выгружать в сторонний сервис. + +## Порядок работы + +1. Перетащите аудио- или видеофайл в зону загрузки либо нажмите **Record microphone** и остановите запись по готовности. +2. Дождитесь, пока строка статуса сообщит о готовности медиа — там видны длительность и то, будет ли использован оконный конвейер. +3. При необходимости смените язык, таймкоды и рантайм, если значения по умолчанию не подходят записи. +4. Нажмите **Transcribe**. На первом запуске прогресс покажет загрузку модели, дальше сразу начнётся распознавание. +5. Правьте транскрипт на месте — текстовое поле редактируемое. +6. Скопируйте текст или выгрузите TXT, SRT либо WebVTT. +7. Нажмите **Clear session**, чтобы выгрузить из памяти медиа, транскрипт и загруженную модель. + +## Настройки + +| Настройка | Варианты | На что влияет | +| --- | --- | --- | +| Model | Whisper Tiny (мультиязычная, ~77 МБ) | Веса для распознавания и объём первой загрузки. | +| Language | Automatic, English, Russian | Automatic определяет язык сам; явный выбор надёжнее на коротких и шумных записях. | +| Timestamps | Segment, Off | Segment даёт список сегментов с таймкодами, необходимый для экспорта SRT и WebVTT. Off возвращает только текст. | +| Runtime | Auto (WebGPU → WASM), WASM only, WebGPU preferred | Auto использует GPU, если браузер поддерживает WebGPU, и незаметно откатывается на WASM. WASM only — медленнее, но максимально совместимо. | + +## Длинные записи + +Короткие фрагменты декодируются за один проход. Длинное медиа сначала анализируется, а затем прогоняется конвейером окон примерно по 30 секунд с перекрытием в 5 секунд: в памяти одновременно находится только одно окно, а модель остаётся загруженной между ними. Транскрипт наполняется окно за окном, а **Cancel** останавливает работу, не стирая уже полученный текст. + +## Приватность + +- Аудио, видео, имена файлов, текст транскрипта и ваши правки остаются на странице. Они не отправляются ни в CAD AutoScript, ни в аналитику, ни в какой-либо API расшифровки. +- Единственные исходящие запросы — закреплённые файлы модели с Hugging Face Hub. +- Микрофон включается только после нажатия **Record microphone**, и это единственная утилита сайта, которой вообще выдано разрешение на микрофон. +- **Clear session** освобождает поток микрофона, аудиобуферы и загруженную модель. Закрытие вкладки делает то же самое. +- Ничего не записывается в ваш аккаунт, история транскриптов не ведётся — сохраните или выгрузите нужное до ухода со страницы. + +## Требования и ограничения + +- Актуальная версия Chromium, Firefox или Safari с поддержкой WebAssembly. WebGPU необязателен и лишь ускоряет работу. +- Около 77 МБ свободного кэша браузера под модель плюс рабочая память, пропорциональная длине записи. +- Whisper Tiny выбирает скорость в ущерб точности: технические термины, номера позиций и имена собственные нужно вычитывать. +- Сильный акцент, перебивающие друг друга голоса и шум на объекте ухудшают результат — микрофон ближе к говорящему помогает сильнее любых настроек. +- Разделение по говорящим, потоковая расшифровка в реальном времени и более крупные модели Whisper в эту версию не входят. +- ⚠️ Транскрипт — черновой материал. Сверьте его с записью, прежде чем цитировать в отчёте, протоколе или любом договорном документе. + +## Смежные инструменты + +- [WIKA CPG1500 Log Analyzer](./wikalog-analyzer.mdx) +- [PDF Number Extractor](./pdf-number-extractor.mdx) +- [Focus Planner](./focus-planner.mdx) + +## Обратная связь и сообщения об ошибках + +- [Создать issue на GitHub](https://github.com/YurMil/cadautoscript.com/issues) +- Напишите нам с указанием слага `whisper-transcriber`, чтобы мы могли воспроизвести проблему. diff --git a/i18n/ua/docusaurus-plugin-content-docs/current/utilities/overview.mdx b/i18n/ua/docusaurus-plugin-content-docs/current/utilities/overview.mdx index bda34f1..d5b6ec2 100644 --- a/i18n/ua/docusaurus-plugin-content-docs/current/utilities/overview.mdx +++ b/i18n/ua/docusaurus-plugin-content-docs/current/utilities/overview.mdx @@ -24,6 +24,7 @@ import UtilityAccessTable from '@site/src/components/Utilities/UtilityAccessTabl - [Busbar Calculator](./busbar-calculator.mdx) - [Gear Pair Calculator](../gear-pair-calculator/) - [WIKA Log Analyzer](./wikalog-analyzer.mdx) +- [Whisper Transcriber](./whisper-transcriber.mdx) - [Tube Sheet Generator](./tube-sheet-generator.mdx) - [WebSTEP Viewer](./webstep-viewer.mdx) - [Engineering Prompt Catalog](./engineering-prompt-catalog.mdx) diff --git a/i18n/ua/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx b/i18n/ua/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx new file mode 100644 index 0000000..ca33da5 --- /dev/null +++ b/i18n/ua/docusaurus-plugin-content-docs/current/utilities/whisper-transcriber.mdx @@ -0,0 +1,130 @@ +--- +title: Whisper Transcriber +description: 'Розшифровка аудіо- та відеофайлів або запису з мікрофона в редагований текст: Whisper працює цілком у браузері, експорт у TXT, SRT і WebVTT.' +slug: /utilities/whisper-transcriber +image: /img/og/utilities/whisper-transcriber.png +keywords: + - розшифровка аудіо + - speech to text у браузері + - офлайн транскрибація + - протокол наради + - генератор субтитрів + - експорт srt webvtt + - whisper webgpu wasm +--- + +import Head from '@docusaurus/Head'; + +# Whisper Transcriber + +Перетворюйте записи на редагований текст, нікуди їх не надсилаючи. Аудіо декодується, приводиться до потрібної частоти й розпізнається моделлю Whisper усередині Web Worker просто у вашому браузері — сервера розшифровки за цією утилітою немає. + +![Оглядова картка Whisper Transcriber](/img/og/utilities/whisper-transcriber.webp) + +Відкрити утиліту + + + + + + +## Що робить утиліта + +Whisper Transcriber перетворює мовлення на текст на вашому ж комп'ютері. Ви даєте їй аудіо- або відеофайл — чи записуєте звук просто з мікрофона — і отримуєте повний транскрипт та сегменти з таймкодами, які можна відредагувати й вивантажити у TXT, SRT або WebVTT. + +Усе відбувається у вкладці браузера: медіа декодується та зводиться в моно 16 кГц, модель OpenAI Whisper виконується через Transformers.js на ONNX Runtime Web, а результат не залишає сторінку. Нічого не завантажується на сервер, не ставиться в чергу й не зберігається. + +Застосунок зібраний як самостійний мікрозастосунок у `static/utility-apps/whisper-transcriber`. Оболонка CAD AutoScript вбудовує його в iframe того самого origin, тож транскрайбер розвивається у власному репозиторії, але користується спільним каталогом, статтею, реакціями, коментарями та шаром доступу цього сайту. + +## Перший запуск: завантаження моделі + +Під час першого натискання **Transcribe** браузер завантажує ваги багатомовної моделі Whisper Tiny (близько 77 МБ) із Hugging Face Hub і кешує їх. Це єдиний мережевий трафік утиліти, і він не містить вашого аудіо — лише файли моделі. + +- Наступні запуски беруть модель із кешу й узагалі не потребують мережі. +- Очищення даних сайту, режим анонімного перегляду або брак місця у сховищі браузера можуть витіснити кеш і спричинити повторне завантаження. +- Ревізія моделі закріплена конкретним комітом, тож щоразу завантажується та сама версія. + +## Коли це знадобиться + +- Оформлення протоколу наради, дзвінка з постачальником або розбору проєкту за записом. +- Перетворення відеообходів та інспекцій на текст, у якому можна шукати. +- Надиктовування переліків зауважень і спостережень QA замість набору тексту на об'єкті. +- Підготовка субтитрів SRT або WebVTT для внутрішніх навчальних відео та передавання справ. +- Розшифровка матеріалів, які не можна вивантажувати у сторонній сервіс. + +## Порядок роботи + +1. Перетягніть аудіо- або відеофайл у зону завантаження чи натисніть **Record microphone** і зупиніть запис, коли завершите. +2. Дочекайтеся, доки рядок статусу повідомить про готовність медіа — там видно тривалість і те, чи буде застосовано віконний конвеєр. +3. За потреби змініть мову, таймкоди та середовище виконання, якщо типові значення не пасують запису. +4. Натисніть **Transcribe**. На першому запуску прогрес показує завантаження моделі, далі одразу починається розпізнавання. +5. Правте транскрипт на місці — текстове поле редаговане. +6. Скопіюйте текст або вивантажте TXT, SRT чи WebVTT. +7. Натисніть **Clear session**, щоб вивантажити з пам'яті медіа, транскрипт і завантажену модель. + +## Налаштування + +| Налаштування | Варіанти | На що впливає | +| --- | --- | --- | +| Model | Whisper Tiny (багатомовна, ~77 МБ) | Ваги для розпізнавання та обсяг першого завантаження. | +| Language | Automatic, English, Russian | Automatic визначає мову самостійно; явний вибір надійніший на коротких і шумних записах. | +| Timestamps | Segment, Off | Segment дає список сегментів із таймкодами, потрібний для експорту SRT і WebVTT. Off повертає лише текст. | +| Runtime | Auto (WebGPU → WASM), WASM only, WebGPU preferred | Auto використовує GPU, якщо браузер підтримує WebGPU, і непомітно відкочується на WASM. WASM only — повільніше, але максимально сумісно. | + +## Довгі записи + +Короткі фрагменти декодуються за один прохід. Довге медіа спершу аналізується, а потім проганяється конвеєром вікон приблизно по 30 секунд із перекриттям у 5 секунд: у пам'яті одночасно перебуває лише одне вікно, а модель лишається завантаженою між ними. Транскрипт наповнюється вікно за вікном, а **Cancel** зупиняє роботу, не стираючи вже отриманий текст. + +## Приватність + +- Аудіо, відео, імена файлів, текст транскрипту та ваші правки лишаються на сторінці. Вони не надсилаються ні до CAD AutoScript, ні в аналітику, ні до будь-якого API розшифровки. +- Єдині вихідні запити — закріплені файли моделі з Hugging Face Hub. +- Мікрофон вмикається лише після натискання **Record microphone**, і це єдина утиліта сайту, якій узагалі надано дозвіл на мікрофон. +- **Clear session** звільняє потік мікрофона, аудіобуфери та завантажену модель. Закриття вкладки робить те саме. +- Нічого не записується у ваш акаунт, історія транскриптів не ведеться — збережіть або вивантажте потрібне до того, як залишите сторінку. + +## Вимоги та обмеження + +- Актуальна версія Chromium, Firefox або Safari з підтримкою WebAssembly. WebGPU необов'язковий і лише пришвидшує роботу. +- Близько 77 МБ вільного кешу браузера під модель плюс робоча пам'ять, пропорційна довжині запису. +- Whisper Tiny обирає швидкість коштом точності: технічні терміни, номери позицій та власні назви потрібно вичитувати. +- Сильний акцент, накладання голосів і шум на об'єкті погіршують результат — мікрофон ближче до мовця допомагає більше за будь-які налаштування. +- Розділення за мовцями, потокова розшифровка в реальному часі та більші моделі Whisper до цієї версії не входять. +- ⚠️ Транскрипт — чорновий матеріал. Звірте його із записом, перш ніж цитувати у звіті, протоколі чи будь-якому договірному документі. + +## Суміжні інструменти + +- [WIKA CPG1500 Log Analyzer](./wikalog-analyzer.mdx) +- [PDF Number Extractor](./pdf-number-extractor.mdx) +- [Focus Planner](./focus-planner.mdx) + +## Зворотний зв'язок і повідомлення про помилки + +- [Створити issue на GitHub](https://github.com/YurMil/cadautoscript.com/issues) +- Напишіть нам із зазначенням слага `whisper-transcriber`, щоб ми могли відтворити проблему. diff --git a/package.json b/package.json index 1c57471..de7c759 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "serve": "docusaurus serve", "sitemap:sections": "node scripts/sitemap-sections.js", "sync:webstep-viewer": "node scripts/sync-webstep-viewer-embed.js", + "sync:whisper-transcriber": "node scripts/sync-whisper-transcriber.mjs", "write-translations": "docusaurus write-translations", "write-heading-ids": "docusaurus write-heading-ids", "typecheck": "tsc", diff --git a/scripts/sync-whisper-transcriber.mjs b/scripts/sync-whisper-transcriber.mjs new file mode 100644 index 0000000..dd8a818 --- /dev/null +++ b/scripts/sync-whisper-transcriber.mjs @@ -0,0 +1,222 @@ +// Publishes the Whisper Transcriber static artifact into +// static/utility-apps/whisper-transcriber/. +// +// The transcriber lives in its own repository (YurMil/ws-speech-text) because +// it carries Transformers.js and ONNX Runtime Web, which must never enter the +// Docusaurus bundle. This script builds that source tree, audits the produced +// bundle, and republishes it atomically. +// +// Usage: +// npm run sync:whisper-transcriber +// WHISPER_TRANSCRIBER_DIR=/path/to/ws-speech-text npm run sync:whisper-transcriber +// npm run sync:whisper-transcriber -- --skip-build (reuse an existing dist/) + +import {createHash} from 'node:crypto'; +import {spawnSync} from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; + +const SITE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const DEFAULT_SOURCE_DIR = path.resolve( + SITE_ROOT, + '..', + 'cadautoscript-apps', + 'ws-speech-text', +); +const SOURCE_DIR = path.resolve(process.env.WHISPER_TRANSCRIBER_DIR || DEFAULT_SOURCE_DIR); +const SOURCE_DIST_DIR = path.join(SOURCE_DIR, 'dist'); +const TARGET_DIR = path.join(SITE_ROOT, 'static', 'utility-apps', 'whisper-transcriber'); +const STAGING_DIR = `${TARGET_DIR}.staging`; + +const ALLOWED_EXTENSIONS = new Set(['.js', '.css', '.wasm', '.json', '.html', '.mjs']); +// Development leftovers that must never reach production. +const FORBIDDEN_PATTERNS = [ + /localhost/i, + /127\.0\.0\.1/, + /\/@vite\//, + /sourceMappingURL/i, +]; + +const skipBuild = process.argv.includes('--skip-build'); + +function fail(message) { + throw new Error(message); +} + +function assertExists(targetPath, label) { + if (!fs.existsSync(targetPath)) { + fail(`Missing ${label}: ${targetPath}`); + } +} + +function run(command, args, cwd) { + const result = spawnSync(command, args, { + cwd, + stdio: 'inherit', + shell: process.platform === 'win32', + }); + if (result.status !== 0) { + fail(`Command failed: ${command} ${args.join(' ')}`); + } +} + +/** Walks dist/, rejecting symlinks, traversal and unexpected file types. */ +function collectFiles(rootDir) { + const files = []; + + const walk = (currentDir) => { + for (const entry of fs.readdirSync(currentDir, {withFileTypes: true})) { + const absolute = path.join(currentDir, entry.name); + const relative = path.relative(rootDir, absolute).split(path.sep).join('/'); + + if (entry.isSymbolicLink()) { + fail(`Refusing to publish symlink: ${relative}`); + } + if (relative.startsWith('..') || path.isAbsolute(relative)) { + fail(`Refusing to publish path outside dist: ${relative}`); + } + if (entry.isDirectory()) { + walk(absolute); + continue; + } + if (!entry.isFile()) { + fail(`Refusing to publish non-regular file: ${relative}`); + } + + const extension = path.extname(entry.name).toLowerCase(); + // Source maps (.map) are excluded by omission — they must not ship. + if (!ALLOWED_EXTENSIONS.has(extension)) { + fail(`Unexpected file type in dist: ${relative}`); + } + files.push(relative); + } + }; + + walk(rootDir); + return files.sort(); +} + +/** + * The entry document must reference only packaged, relative assets — an + * absolute or remote script tag would silently break the same-origin iframe + * contract the utility shell relies on. + */ +function auditEntryHtml(html, packagedAssets) { + for (const pattern of FORBIDDEN_PATTERNS) { + if (pattern.test(html)) { + fail(`Entry HTML contains a development reference (${pattern}).`); + } + } + + const referenced = [...html.matchAll(/(?:src|href)="([^"]+)"/g)].map((match) => match[1]); + for (const reference of referenced) { + if (!reference.startsWith('./')) { + fail(`Entry HTML must reference assets relatively, found: ${reference}`); + } + const normalized = reference.replace(/^\.\//, ''); + if (!packagedAssets.includes(normalized)) { + fail(`Entry HTML references an unpackaged asset: ${reference}`); + } + } + + if (referenced.length === 0) { + fail('Entry HTML references no assets — the build is probably empty.'); + } +} + +function sha256(filePath) { + return createHash('sha256').update(fs.readFileSync(filePath)).digest('hex'); +} + +/** vite.config.ts emits build-info.json alongside the bundle. */ +function readBuildInfo(distDir) { + const infoPath = path.join(distDir, 'build-info.json'); + assertExists(infoPath, 'ws-speech-text dist/build-info.json'); + const info = JSON.parse(fs.readFileSync(infoPath, 'utf8')); + if (!info.buildId || !info.version) { + fail('build-info.json is missing version or buildId.'); + } + if (info.buildId === 'unversioned') { + fail('Refusing to publish an artifact built outside a git checkout.'); + } + return info; +} + +function main() { + assertExists(SOURCE_DIR, 'ws-speech-text source directory'); + assertExists(path.join(SOURCE_DIR, 'package.json'), 'ws-speech-text package.json'); + + if (skipBuild) { + console.log('[whisper-transcriber] --skip-build: reusing existing dist/'); + } else { + console.log(`[whisper-transcriber] Building bundle from ${SOURCE_DIR}`); + run('pnpm', ['install', '--frozen-lockfile'], SOURCE_DIR); + run('pnpm', ['build'], SOURCE_DIR); + } + + assertExists(SOURCE_DIST_DIR, 'ws-speech-text dist directory'); + assertExists(path.join(SOURCE_DIST_DIR, 'index.html'), 'ws-speech-text dist/index.html'); + + const files = collectFiles(SOURCE_DIST_DIR); + const assets = files.filter((file) => file !== 'index.html'); + const entryHtml = fs.readFileSync(path.join(SOURCE_DIST_DIR, 'index.html'), 'utf8'); + auditEntryHtml(entryHtml, assets); + + const {version, buildId} = readBuildInfo(SOURCE_DIST_DIR); + + // Stage first, then swap, so a failed sync never leaves a half-published app. + fs.rmSync(STAGING_DIR, {recursive: true, force: true}); + fs.mkdirSync(STAGING_DIR, {recursive: true}); + + const checksums = {}; + let totalBytes = 0; + for (const relative of assets) { + const source = path.join(SOURCE_DIST_DIR, relative); + const destination = path.join(STAGING_DIR, relative); + fs.mkdirSync(path.dirname(destination), {recursive: true}); + fs.copyFileSync(source, destination); + checksums[relative] = sha256(source); + totalBytes += fs.statSync(source).size; + } + + // The utility shell always loads app.html (see UtilityShellPage). index.html + // is published alongside it so the directory URL also serves the app — + // trailing-slash hosting rewrites `/app.html` to `/app/`, which would break + // the relative asset paths. + for (const entryName of ['app.html', 'index.html']) { + fs.writeFileSync(path.join(STAGING_DIR, entryName), entryHtml); + checksums[entryName] = createHash('sha256').update(entryHtml).digest('hex'); + totalBytes += Buffer.byteLength(entryHtml); + } + + const manifest = { + name: 'whisper-transcriber', + version, + buildId, + buildTime: new Date().toISOString(), + entry: 'app.html', + assets, + checksums, + }; + fs.writeFileSync( + path.join(STAGING_DIR, 'manifest.json'), + `${JSON.stringify(manifest, null, 2)}\n`, + ); + + fs.rmSync(TARGET_DIR, {recursive: true, force: true}); + fs.renameSync(STAGING_DIR, TARGET_DIR); + + console.log( + `[whisper-transcriber] Published ${Object.keys(checksums).length} files to ${TARGET_DIR}`, + ); + console.log(`[whisper-transcriber] version=${version} buildId=${buildId} bytes=${totalBytes}`); +} + +try { + main(); +} catch (error) { + fs.rmSync(STAGING_DIR, {recursive: true, force: true}); + console.error(`[whisper-transcriber] ${error.message}`); + process.exit(1); +} diff --git a/sidebars.ts b/sidebars.ts index 19f28b5..da04a7f 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -75,6 +75,7 @@ const sidebars: SidebarsConfig = { 'utilities/react-table-editor', 'utilities/focus-planner', 'utilities/wikalog-analyzer', + 'utilities/whisper-transcriber', ], }, ], diff --git a/src/components/Utilities/UtilityShellPage.tsx b/src/components/Utilities/UtilityShellPage.tsx index 36e9e26..b51dbf6 100644 --- a/src/components/Utilities/UtilityShellPage.tsx +++ b/src/components/Utilities/UtilityShellPage.tsx @@ -50,6 +50,7 @@ export default function UtilityShellPage({tool, ...config}: UtilityShellPageProp features, scriptType = 'module', appPath, + iframeAllow = "camera 'self'", } = config; const iframeSrc = useBaseUrl(appPath ?? `/utility-apps/${slug}/app.html`); @@ -218,7 +219,7 @@ export default function UtilityShellPage({tool, ...config}: UtilityShellPageProp src={iframeSrc} title={title} loading="lazy" - allow="camera 'self'" + allow={iframeAllow} data-nobrokenlinkcheck > )} diff --git a/src/data/utilities.ts b/src/data/utilities.ts index ea1ae84..f16044a 100644 --- a/src/data/utilities.ts +++ b/src/data/utilities.ts @@ -372,4 +372,17 @@ export const utilities: UtilityDescriptor[] = [ href: '/utilities/wikalog-analyzer/', thumbnail: '/img/utilities/wikalog-analyzer.png', }, + { + id: 'whisper-transcriber', + relatedIds: ['wikalog-analyzer', 'doc-parser', 'focus-planner'], + category: 'productivity', + name: 'Whisper Transcriber', + description: + 'Transcribe audio and video to editable text with Whisper running fully in your browser.', + tech: 'Transformers.js + WASM / WebGPU', + standards: 'On-device inference', + features: ['File or microphone input', 'Timestamped segments', 'TXT / SRT / WebVTT export'], + href: '/utilities/whisper-transcriber/', + thumbnail: '/img/utilities/whisper-transcriber.svg', + }, ]; diff --git a/src/data/utilityShellPages.tsx b/src/data/utilityShellPages.tsx index c4b14d5..625040e 100644 --- a/src/data/utilityShellPages.tsx +++ b/src/data/utilityShellPages.tsx @@ -27,7 +27,8 @@ export type UtilityPageSlug = | 'busbar-calculator' | 'pressure-vessel-dished-end-calc' | 'gear-pair-calculator' - | 'wikalog-analyzer'; + | 'wikalog-analyzer' + | 'whisper-transcriber'; export type UtilityPageConfig = { slug: UtilityPageSlug; @@ -41,6 +42,12 @@ export type UtilityPageConfig = { scriptType?: 'module' | 'defer'; reactionSlug?: string; appPath?: string; + /** + * Permissions delegated to the embedded iframe. Capabilities are granted per + * utility, never site-wide: only tools that actually need a device get it, + * and the matching Permissions-Policy path rule lives in vercel.json. + */ + iframeAllow?: string; }; export const utilityPageConfigs: Record = { @@ -492,4 +499,27 @@ export const utilityPageConfigs: Record = { ], scriptType: 'module', }, + 'whisper-transcriber': { + slug: 'whisper-transcriber', + title: 'Whisper Transcriber', + subtitle: 'Web utility — Private speech-to-text in your browser', + description: + 'Transcribe audio and video files or microphone recordings with Whisper running entirely in your browser, then export TXT, SRT, or WebVTT.', + about: + 'Turn meeting recordings, supplier calls, site walkthroughs, and dictated inspection notes into editable text. Audio is decoded, resampled, and transcribed by a Whisper model that runs inside a Web Worker on your own machine — nothing is uploaded to a transcription service.', + tags: ['Speech-to-text', 'Whisper', 'Offline AI', 'Subtitles'], + note: + 'The first transcription downloads a ~77 MB model from the Hugging Face Hub and caches it in the browser. Later runs work from that cache, but clearing site data or browser storage pressure can evict it and trigger a fresh download.', + features: [ + 'Audio and video file upload, or record-then-transcribe from the microphone', + 'Windowed conveyor pipeline for long recordings — the model stays loaded', + 'Automatic language detection plus explicit English and Russian modes', + 'WebGPU acceleration with an automatic WASM fallback', + 'Editable transcript with timestamped segments', + 'Copy, TXT, SRT, and WebVTT export', + ], + scriptType: 'module', + // The only utility granted microphone access; see vercel.json. + iframeAllow: "microphone 'self'", + }, }; diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index cfe390f..380802b 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -261,6 +261,10 @@ export const de: TranslationDict = { name: 'WIKA Log Analyzer', description: 'WIKA CPG1500-Kalibriererprotokolle parsen, Messdaten prüfen und QC-Berichte lokal drucken.', }, + 'whisper-transcriber': { + name: 'Whisper Transcriber', + description: 'Audio und Video mit Whisper direkt im Browser in bearbeitbaren Text transkribieren.', + }, }, miniGamesPage: { eyebrow: 'Minispiele', diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 2e29553..ed108f5 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -259,6 +259,10 @@ export const en = { name: 'WIKA Log Analyzer', description: 'Parse WIKA CPG1500 calibrator logs, review measurement data, and print QC reports locally.', }, + 'whisper-transcriber': { + name: 'Whisper Transcriber', + description: 'Transcribe audio and video to editable text with Whisper running fully in your browser.', + }, }, miniGamesPage: { eyebrow: 'Mini Games', diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index c1324ed..a5824d8 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -261,6 +261,10 @@ export const es: TranslationDict = { name: 'WIKA Log Analyzer', description: 'Analiza registros del calibrador WIKA CPG1500, revisa datos e imprime informes QC localmente.', }, + 'whisper-transcriber': { + name: 'Whisper Transcriber', + description: 'Transcribe audio y vídeo a texto editable con Whisper ejecutándose en el navegador.', + }, }, miniGamesPage: { eyebrow: 'Minijuegos', diff --git a/src/i18n/locales/et.ts b/src/i18n/locales/et.ts index 368e018..713eba3 100644 --- a/src/i18n/locales/et.ts +++ b/src/i18n/locales/et.ts @@ -261,6 +261,10 @@ export const et: TranslationDict = { name: 'WIKA Log Analyzer', description: 'Parseeri WIKA CPG1500 kalibreerimisloge, vaata mõõteandmeid ja prindi QC-raportid lokaalselt.', }, + 'whisper-transcriber': { + name: 'Whisper Transcriber', + description: 'Transkribeeri heli ja video redigeeritavaks tekstiks — Whisper töötab otse brauseris.', + }, }, miniGamesPage: { eyebrow: 'Minimängud', diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index fd49774..0e36697 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -260,6 +260,10 @@ export const ru: TranslationDict = { name: 'WIKA Log Analyzer', description: 'Разбор логов калибратора WIKA CPG1500, анализ данных измерений и локальная печать QC-отчётов.', }, + 'whisper-transcriber': { + name: 'Whisper Transcriber', + description: 'Расшифровка аудио и видео в редактируемый текст: Whisper работает прямо в браузере.', + }, }, miniGamesPage: { eyebrow: 'Мини-игры', diff --git a/src/i18n/locales/ua.ts b/src/i18n/locales/ua.ts index 08369e3..9569c96 100644 --- a/src/i18n/locales/ua.ts +++ b/src/i18n/locales/ua.ts @@ -261,6 +261,10 @@ export const ua: TranslationDict = { name: 'WIKA Log Analyzer', description: 'Розбір журналів каліброатора WIKA CPG1500, аналіз вимірювань, QC-звіти офлайн.', }, + 'whisper-transcriber': { + name: 'Whisper Transcriber', + description: 'Розшифровка аудіо та відео в редагований текст: Whisper працює просто у браузері.', + }, }, miniGamesPage: { eyebrow: 'Міні-ігри', diff --git a/src/pages/utilities/whisper-transcriber.tsx b/src/pages/utilities/whisper-transcriber.tsx new file mode 100644 index 0000000..ad9447a --- /dev/null +++ b/src/pages/utilities/whisper-transcriber.tsx @@ -0,0 +1,3 @@ +import {createUtilityPage} from '@site/src/components/Utilities/createUtilityPage'; + +export default createUtilityPage('whisper-transcriber'); diff --git a/static/img/og/utilities/whisper-transcriber.png b/static/img/og/utilities/whisper-transcriber.png new file mode 100644 index 0000000..478d0e6 Binary files /dev/null and b/static/img/og/utilities/whisper-transcriber.png differ diff --git a/static/img/og/utilities/whisper-transcriber.webp b/static/img/og/utilities/whisper-transcriber.webp new file mode 100644 index 0000000..289481a Binary files /dev/null and b/static/img/og/utilities/whisper-transcriber.webp differ diff --git a/static/img/utilities/whisper-transcriber.svg b/static/img/utilities/whisper-transcriber.svg new file mode 100644 index 0000000..74f6909 --- /dev/null +++ b/static/img/utilities/whisper-transcriber.svg @@ -0,0 +1,48 @@ + + Whisper Transcriber icon + A waveform turning into lines of transcribed text next to a microphone. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/static/utility-apps/whisper-transcriber/app.html b/static/utility-apps/whisper-transcriber/app.html new file mode 100644 index 0000000..65ba537 --- /dev/null +++ b/static/utility-apps/whisper-transcriber/app.html @@ -0,0 +1,17 @@ + + + + + + + Whisper Transcriber + + + + +
+ + diff --git a/static/utility-apps/whisper-transcriber/assets/index-B5C8PNiW.js b/static/utility-apps/whisper-transcriber/assets/index-B5C8PNiW.js new file mode 100644 index 0000000..cc5f445 --- /dev/null +++ b/static/utility-apps/whisper-transcriber/assets/index-B5C8PNiW.js @@ -0,0 +1,20 @@ +(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const u of o)if(u.type==="childList")for(const c of u.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&r(c)}).observe(document,{childList:!0,subtree:!0});function i(o){const u={};return o.integrity&&(u.integrity=o.integrity),o.referrerPolicy&&(u.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?u.credentials="include":o.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function r(o){if(o.ep)return;o.ep=!0;const u=i(o);fetch(o.href,u)}})();var Nu={exports:{}},ss={};var Op;function wb(){if(Op)return ss;Op=1;var l=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function i(r,o,u){var c=null;if(u!==void 0&&(c=""+u),o.key!==void 0&&(c=""+o.key),"key"in o){u={};for(var d in o)d!=="key"&&(u[d]=o[d])}else u=o;return o=u.ref,{$$typeof:l,type:r,key:c,ref:o!==void 0?o:null,props:u}}return ss.Fragment=n,ss.jsx=i,ss.jsxs=i,ss}var zp;function xb(){return zp||(zp=1,Nu.exports=wb()),Nu.exports}var te=xb(),Uu={exports:{}},ge={};var Mp;function Cb(){if(Mp)return ge;Mp=1;var l=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),u=Symbol.for("react.consumer"),c=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),b=Symbol.iterator;function T(O){return O===null||typeof O!="object"?null:(O=b&&O[b]||O["@@iterator"],typeof O=="function"?O:null)}var w={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,E={};function x(O,Q,ne){this.props=O,this.context=Q,this.refs=E,this.updater=ne||w}x.prototype.isReactComponent={},x.prototype.setState=function(O,Q){if(typeof O!="object"&&typeof O!="function"&&O!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,O,Q,"setState")},x.prototype.forceUpdate=function(O){this.updater.enqueueForceUpdate(this,O,"forceUpdate")};function P(){}P.prototype=x.prototype;function _(O,Q,ne){this.props=O,this.context=Q,this.refs=E,this.updater=ne||w}var D=_.prototype=new P;D.constructor=_,S(D,x.prototype),D.isPureReactComponent=!0;var B=Array.isArray;function z(){}var L={H:null,A:null,T:null,S:null},H=Object.prototype.hasOwnProperty;function R(O,Q,ne){var le=ne.ref;return{$$typeof:l,type:O,key:Q,ref:le!==void 0?le:null,props:ne}}function X(O,Q){return R(O.type,Q,O.props)}function W(O){return typeof O=="object"&&O!==null&&O.$$typeof===l}function Z(O){var Q={"=":"=0",":":"=2"};return"$"+O.replace(/[=:]/g,function(ne){return Q[ne]})}var ie=/\/+/g;function ce(O,Q){return typeof O=="object"&&O!==null&&O.key!=null?Z(""+O.key):Q.toString(36)}function re(O){switch(O.status){case"fulfilled":return O.value;case"rejected":throw O.reason;default:switch(typeof O.status=="string"?O.then(z,z):(O.status="pending",O.then(function(Q){O.status==="pending"&&(O.status="fulfilled",O.value=Q)},function(Q){O.status==="pending"&&(O.status="rejected",O.reason=Q)})),O.status){case"fulfilled":return O.value;case"rejected":throw O.reason}}throw O}function N(O,Q,ne,le,pe){var we=typeof O;(we==="undefined"||we==="boolean")&&(O=null);var Pe=!1;if(O===null)Pe=!0;else switch(we){case"bigint":case"string":case"number":Pe=!0;break;case"object":switch(O.$$typeof){case l:case n:Pe=!0;break;case y:return Pe=O._init,N(Pe(O._payload),Q,ne,le,pe)}}if(Pe)return pe=pe(O),Pe=le===""?"."+ce(O,0):le,B(pe)?(ne="",Pe!=null&&(ne=Pe.replace(ie,"$&/")+"/"),N(pe,Q,ne,"",function(Ia){return Ia})):pe!=null&&(W(pe)&&(pe=X(pe,ne+(pe.key==null||O&&O.key===pe.key?"":(""+pe.key).replace(ie,"$&/")+"/")+Pe)),Q.push(pe)),1;Pe=0;var ht=le===""?".":le+":";if(B(O))for(var Ze=0;Ze>>1,Be=N[Te];if(0>>1;Teo(ne,ae))leo(pe,ne)?(N[Te]=pe,N[le]=ae,Te=le):(N[Te]=ne,N[Q]=ae,Te=Q);else if(leo(pe,ae))N[Te]=pe,N[le]=ae,Te=le;else break e}}return J}function o(N,J){var ae=N.sortIndex-J.sortIndex;return ae!==0?ae:N.id-J.id}if(l.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var u=performance;l.unstable_now=function(){return u.now()}}else{var c=Date,d=c.now();l.unstable_now=function(){return c.now()-d}}var m=[],p=[],y=1,g=null,b=3,T=!1,w=!1,S=!1,E=!1,x=typeof setTimeout=="function"?setTimeout:null,P=typeof clearTimeout=="function"?clearTimeout:null,_=typeof setImmediate<"u"?setImmediate:null;function D(N){for(var J=i(p);J!==null;){if(J.callback===null)r(p);else if(J.startTime<=N)r(p),J.sortIndex=J.expirationTime,n(m,J);else break;J=i(p)}}function B(N){if(S=!1,D(N),!w)if(i(m)!==null)w=!0,z||(z=!0,Z());else{var J=i(p);J!==null&&re(B,J.startTime-N)}}var z=!1,L=-1,H=5,R=-1;function X(){return E?!0:!(l.unstable_now()-RN&&X());){var Te=g.callback;if(typeof Te=="function"){g.callback=null,b=g.priorityLevel;var Be=Te(g.expirationTime<=N);if(N=l.unstable_now(),typeof Be=="function"){g.callback=Be,D(N),J=!0;break t}g===i(m)&&r(m),D(N)}else r(m);g=i(m)}if(g!==null)J=!0;else{var O=i(p);O!==null&&re(B,O.startTime-N),J=!1}}break e}finally{g=null,b=ae,T=!1}J=void 0}}finally{J?Z():z=!1}}}var Z;if(typeof _=="function")Z=function(){_(W)};else if(typeof MessageChannel<"u"){var ie=new MessageChannel,ce=ie.port2;ie.port1.onmessage=W,Z=function(){ce.postMessage(null)}}else Z=function(){x(W,0)};function re(N,J){L=x(function(){N(l.unstable_now())},J)}l.unstable_IdlePriority=5,l.unstable_ImmediatePriority=1,l.unstable_LowPriority=4,l.unstable_NormalPriority=3,l.unstable_Profiling=null,l.unstable_UserBlockingPriority=2,l.unstable_cancelCallback=function(N){N.callback=null},l.unstable_forceFrameRate=function(N){0>N||125Te?(N.sortIndex=ae,n(p,N),i(m)===null&&N===i(p)&&(S?(P(L),L=-1):S=!0,re(B,ae-Te))):(N.sortIndex=Be,n(m,N),w||T||(w=!0,z||(z=!0,Z()))),N},l.unstable_shouldYield=X,l.unstable_wrapCallback=function(N){var J=b;return function(){var ae=b;b=J;try{return N.apply(this,arguments)}finally{b=ae}}}})(Hu)),Hu}var Fp;function Eb(){return Fp||(Fp=1,qu.exports=_b()),qu.exports}var Lu={exports:{}},Tt={};var qp;function Ab(){if(qp)return Tt;qp=1;var l=kf();function n(m){var p="https://react.dev/errors/"+m;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(l)}catch(n){console.error(n)}}return l(),Lu.exports=Ab(),Lu.exports}var Lp;function Bb(){if(Lp)return ls;Lp=1;var l=Eb(),n=kf(),i=Pb();function r(e){var t="https://react.dev/errors/"+e;if(1Be||(e.current=Te[Be],Te[Be]=null,Be--)}function ne(e,t){Be++,Te[Be]=e.current,e.current=t}var le=O(null),pe=O(null),we=O(null),Pe=O(null);function ht(e,t){switch(ne(we,t),ne(pe,e),ne(le,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?ap(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=ap(t),e=ip(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}Q(le),ne(le,e)}function Ze(){Q(le),Q(pe),Q(we)}function Ia(e){e.memoizedState!==null&&ne(Pe,e);var t=le.current,a=ip(t,e.type);t!==a&&(ne(pe,e),ne(le,a))}function li(e){pe.current===e&&(Q(le),Q(pe)),Pe.current===e&&(Q(Pe),ns._currentValue=ae)}var oi,de;function ye(e){if(oi===void 0)try{throw Error()}catch(a){var t=a.stack.trim().match(/\n( *(at )?)/);oi=t&&t[1]||"",de=-1)":-1f||A[s]!==F[f]){var j=` +`+A[s].replace(" at new "," at ");return e.displayName&&j.includes("")&&(j=j.replace("",e.displayName)),j}while(1<=s&&0<=f);break}}}finally{je=!1,Error.prepareStackTrace=a}return(a=e?e.displayName||e.name:"")?ye(a):""}function Et(e,t){switch(e.tag){case 26:case 27:case 5:return ye(e.type);case 16:return ye("Lazy");case 13:return e.child!==t&&t!==null?ye("Suspense Fallback"):ye("Suspense");case 19:return ye("SuspenseList");case 0:case 15:return We(e.type,!1);case 11:return We(e.type.render,!1);case 1:return We(e.type,!0);case 31:return ye("Activity");default:return""}}function Jt(e){try{var t="",a=null;do t+=Et(e,a),a=e,e=e.return;while(e);return t}catch(s){return` +Error generating stack: `+s.message+` +`+s.stack}}var yn=Object.prototype.hasOwnProperty,wo=l.unstable_scheduleCallback,xo=l.unstable_cancelCallback,ty=l.unstable_shouldYield,ny=l.unstable_requestPaint,Ut=l.unstable_now,ay=l.unstable_getCurrentPriorityLevel,zf=l.unstable_ImmediatePriority,Mf=l.unstable_UserBlockingPriority,Rs=l.unstable_NormalPriority,iy=l.unstable_LowPriority,Nf=l.unstable_IdlePriority,ry=l.log,sy=l.unstable_setDisableYieldValue,mr=null,Ft=null;function na(e){if(typeof ry=="function"&&sy(e),Ft&&typeof Ft.setStrictMode=="function")try{Ft.setStrictMode(mr,e)}catch{}}var qt=Math.clz32?Math.clz32:cy,ly=Math.log,oy=Math.LN2;function cy(e){return e>>>=0,e===0?32:31-(ly(e)/oy|0)|0}var Os=256,zs=262144,Ms=4194304;function Ra(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Ns(e,t,a){var s=e.pendingLanes;if(s===0)return 0;var f=0,h=e.suspendedLanes,k=e.pingedLanes;e=e.warmLanes;var v=s&134217727;return v!==0?(s=v&~h,s!==0?f=Ra(s):(k&=v,k!==0?f=Ra(k):a||(a=v&~e,a!==0&&(f=Ra(a))))):(v=s&~h,v!==0?f=Ra(v):k!==0?f=Ra(k):a||(a=s&~e,a!==0&&(f=Ra(a)))),f===0?0:t!==0&&t!==f&&(t&h)===0&&(h=f&-f,a=t&-t,h>=a||h===32&&(a&4194048)!==0)?t:f}function pr(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function uy(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Uf(){var e=Ms;return Ms<<=1,(Ms&62914560)===0&&(Ms=4194304),e}function Co(e){for(var t=[],a=0;31>a;a++)t.push(e);return t}function gr(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function fy(e,t,a,s,f,h){var k=e.pendingLanes;e.pendingLanes=a,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=a,e.entangledLanes&=a,e.errorRecoveryDisabledLanes&=a,e.shellSuspendCounter=0;var v=e.entanglements,A=e.expirationTimes,F=e.hiddenUpdates;for(a=k&~a;0"u")return null;try{return e.activeElement||e.body}catch{return e.body}}var yy=/[\n"\\]/g;function en(e){return e.replace(yy,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function Do(e,t,a,s,f,h,k,v){e.name="",k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?e.type=k:e.removeAttribute("type"),t!=null?k==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+$t(t)):e.value!==""+$t(t)&&(e.value=""+$t(t)):k!=="submit"&&k!=="reset"||e.removeAttribute("value"),t!=null?Io(e,k,$t(t)):a!=null?Io(e,k,$t(a)):s!=null&&e.removeAttribute("value"),f==null&&h!=null&&(e.defaultChecked=!!h),f!=null&&(e.checked=f&&typeof f!="function"&&typeof f!="symbol"),v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"?e.name=""+$t(v):e.removeAttribute("name")}function Wf(e,t,a,s,f,h,k,v){if(h!=null&&typeof h!="function"&&typeof h!="symbol"&&typeof h!="boolean"&&(e.type=h),t!=null||a!=null){if(!(h!=="submit"&&h!=="reset"||t!=null)){Bo(e);return}a=a!=null?""+$t(a):"",t=t!=null?""+$t(t):a,v||t===e.value||(e.value=t),e.defaultValue=t}s=s??f,s=typeof s!="function"&&typeof s!="symbol"&&!!s,e.checked=v?e.checked:!!s,e.defaultChecked=!!s,k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"&&(e.name=k),Bo(e)}function Io(e,t,a){t==="number"&&qs(e.ownerDocument)===e||e.defaultValue===""+a||(e.defaultValue=""+a)}function mi(e,t,a,s){if(e=e.options,t){t={};for(var f=0;f"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),No=!1;if(Bn)try{var Sr={};Object.defineProperty(Sr,"passive",{get:function(){No=!0}}),window.addEventListener("test",Sr,Sr),window.removeEventListener("test",Sr,Sr)}catch{No=!1}var ia=null,Uo=null,Ls=null;function id(){if(Ls)return Ls;var e,t=Uo,a=t.length,s,f="value"in ia?ia.value:ia.textContent,h=f.length;for(e=0;e=wr),ud=" ",fd=!1;function dd(e,t){switch(e){case"keyup":return Xy.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function hd(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ki=!1;function Ky(e,t){switch(e){case"compositionend":return hd(t);case"keypress":return t.which!==32?null:(fd=!0,ud);case"textInput":return e=t.data,e===ud&&fd?null:e;default:return null}}function Yy(e,t){if(ki)return e==="compositionend"||!Vo&&dd(e,t)?(e=id(),Ls=Uo=ia=null,ki=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:a,offset:t-e};e=s}e:{for(;a;){if(a.nextSibling){a=a.nextSibling;break e}a=a.parentNode}a=void 0}a=Td(a)}}function wd(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?wd(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function xd(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=qs(e.document);t instanceof e.HTMLIFrameElement;){try{var a=typeof t.contentWindow.location.href=="string"}catch{a=!1}if(a)e=t.contentWindow;else break;t=qs(e.document)}return t}function Go(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}var nk=Bn&&"documentMode"in document&&11>=document.documentMode,bi=null,Ko=null,Er=null,Yo=!1;function Cd(e,t,a){var s=a.window===a?a.document:a.nodeType===9?a:a.ownerDocument;Yo||bi==null||bi!==qs(s)||(s=bi,"selectionStart"in s&&Go(s)?s={start:s.selectionStart,end:s.selectionEnd}:(s=(s.ownerDocument&&s.ownerDocument.defaultView||window).getSelection(),s={anchorNode:s.anchorNode,anchorOffset:s.anchorOffset,focusNode:s.focusNode,focusOffset:s.focusOffset}),Er&&_r(Er,s)||(Er=s,s=zl(Ko,"onSelect"),0>=k,f-=k,kn=1<<32-qt(t)+f|a<Se?(Ee=ue,ue=null):Ee=ue.sibling;var Ie=q(M,ue,U[Se],G);if(Ie===null){ue===null&&(ue=Ee);break}e&&ue&&Ie.alternate===null&&t(M,ue),I=h(Ie,I,Se),De===null?he=Ie:De.sibling=Ie,De=Ie,ue=Ee}if(Se===U.length)return a(M,ue),Ae&&In(M,Se),he;if(ue===null){for(;SeSe?(Ee=ue,ue=null):Ee=ue.sibling;var _a=q(M,ue,Ie.value,G);if(_a===null){ue===null&&(ue=Ee);break}e&&ue&&_a.alternate===null&&t(M,ue),I=h(_a,I,Se),De===null?he=_a:De.sibling=_a,De=_a,ue=Ee}if(Ie.done)return a(M,ue),Ae&&In(M,Se),he;if(ue===null){for(;!Ie.done;Se++,Ie=U.next())Ie=Y(M,Ie.value,G),Ie!==null&&(I=h(Ie,I,Se),De===null?he=Ie:De.sibling=Ie,De=Ie);return Ae&&In(M,Se),he}for(ue=s(ue);!Ie.done;Se++,Ie=U.next())Ie=V(ue,M,Se,Ie.value,G),Ie!==null&&(e&&Ie.alternate!==null&&ue.delete(Ie.key===null?Se:Ie.key),I=h(Ie,I,Se),De===null?he=Ie:De.sibling=Ie,De=Ie);return e&&ue.forEach(function(vb){return t(M,vb)}),Ae&&In(M,Se),he}function He(M,I,U,G){if(typeof U=="object"&&U!==null&&U.type===S&&U.key===null&&(U=U.props.children),typeof U=="object"&&U!==null){switch(U.$$typeof){case T:e:{for(var he=U.key;I!==null;){if(I.key===he){if(he=U.type,he===S){if(I.tag===7){a(M,I.sibling),G=f(I,U.props.children),G.return=M,M=G;break e}}else if(I.elementType===he||typeof he=="object"&&he!==null&&he.$$typeof===H&&ja(he)===I.type){a(M,I.sibling),G=f(I,U.props),Rr(G,U),G.return=M,M=G;break e}a(M,I);break}else t(M,I);I=I.sibling}U.type===S?(G=Fa(U.props.children,M.mode,G,U.key),G.return=M,M=G):(G=Js(U.type,U.key,U.props,null,M.mode,G),Rr(G,U),G.return=M,M=G)}return k(M);case w:e:{for(he=U.key;I!==null;){if(I.key===he)if(I.tag===4&&I.stateNode.containerInfo===U.containerInfo&&I.stateNode.implementation===U.implementation){a(M,I.sibling),G=f(I,U.children||[]),G.return=M,M=G;break e}else{a(M,I);break}else t(M,I);I=I.sibling}G=tc(U,M.mode,G),G.return=M,M=G}return k(M);case H:return U=ja(U),He(M,I,U,G)}if(re(U))return se(M,I,U,G);if(Z(U)){if(he=Z(U),typeof he!="function")throw Error(r(150));return U=he.call(U),me(M,I,U,G)}if(typeof U.then=="function")return He(M,I,rl(U),G);if(U.$$typeof===_)return He(M,I,tl(M,U),G);sl(M,U)}return typeof U=="string"&&U!==""||typeof U=="number"||typeof U=="bigint"?(U=""+U,I!==null&&I.tag===6?(a(M,I.sibling),G=f(I,U),G.return=M,M=G):(a(M,I),G=ec(U,M.mode,G),G.return=M,M=G),k(M)):a(M,I)}return function(M,I,U,G){try{Ir=0;var he=He(M,I,U,G);return Bi=null,he}catch(ue){if(ue===Pi||ue===al)throw ue;var De=Lt(29,ue,null,M.mode);return De.lanes=G,De.return=M,De}}}var Ga=Yd(!0),Qd=Yd(!1),ca=!1;function hc(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function mc(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function ua(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function fa(e,t,a){var s=e.updateQueue;if(s===null)return null;if(s=s.shared,(ze&2)!==0){var f=s.pending;return f===null?t.next=t:(t.next=f.next,f.next=t),s.pending=t,t=Ws(e),Id(e,null,a),t}return Zs(e,s,t,a),Ws(e)}function Or(e,t,a){if(t=t.updateQueue,t!==null&&(t=t.shared,(a&4194048)!==0)){var s=t.lanes;s&=e.pendingLanes,a|=s,t.lanes=a,qf(e,a)}}function pc(e,t){var a=e.updateQueue,s=e.alternate;if(s!==null&&(s=s.updateQueue,a===s)){var f=null,h=null;if(a=a.firstBaseUpdate,a!==null){do{var k={lane:a.lane,tag:a.tag,payload:a.payload,callback:null,next:null};h===null?f=h=k:h=h.next=k,a=a.next}while(a!==null);h===null?f=h=t:h=h.next=t}else f=h=t;a={baseState:s.baseState,firstBaseUpdate:f,lastBaseUpdate:h,shared:s.shared,callbacks:s.callbacks},e.updateQueue=a;return}e=a.lastBaseUpdate,e===null?a.firstBaseUpdate=t:e.next=t,a.lastBaseUpdate=t}var gc=!1;function zr(){if(gc){var e=Ai;if(e!==null)throw e}}function Mr(e,t,a,s){gc=!1;var f=e.updateQueue;ca=!1;var h=f.firstBaseUpdate,k=f.lastBaseUpdate,v=f.shared.pending;if(v!==null){f.shared.pending=null;var A=v,F=A.next;A.next=null,k===null?h=F:k.next=F,k=A;var j=e.alternate;j!==null&&(j=j.updateQueue,v=j.lastBaseUpdate,v!==k&&(v===null?j.firstBaseUpdate=F:v.next=F,j.lastBaseUpdate=A))}if(h!==null){var Y=f.baseState;k=0,j=F=A=null,v=h;do{var q=v.lane&-536870913,V=q!==v.lane;if(V?(_e&q)===q:(s&q)===q){q!==0&&q===Ei&&(gc=!0),j!==null&&(j=j.next={lane:0,tag:v.tag,payload:v.payload,callback:null,next:null});e:{var se=e,me=v;q=t;var He=a;switch(me.tag){case 1:if(se=me.payload,typeof se=="function"){Y=se.call(He,Y,q);break e}Y=se;break e;case 3:se.flags=se.flags&-65537|128;case 0:if(se=me.payload,q=typeof se=="function"?se.call(He,Y,q):se,q==null)break e;Y=g({},Y,q);break e;case 2:ca=!0}}q=v.callback,q!==null&&(e.flags|=64,V&&(e.flags|=8192),V=f.callbacks,V===null?f.callbacks=[q]:V.push(q))}else V={lane:q,tag:v.tag,payload:v.payload,callback:v.callback,next:null},j===null?(F=j=V,A=Y):j=j.next=V,k|=q;if(v=v.next,v===null){if(v=f.shared.pending,v===null)break;V=v,v=V.next,V.next=null,f.lastBaseUpdate=V,f.shared.pending=null}}while(!0);j===null&&(A=Y),f.baseState=A,f.firstBaseUpdate=F,f.lastBaseUpdate=j,h===null&&(f.shared.lanes=0),ga|=k,e.lanes=k,e.memoizedState=Y}}function Zd(e,t){if(typeof e!="function")throw Error(r(191,e));e.call(t)}function Wd(e,t){var a=e.callbacks;if(a!==null)for(e.callbacks=null,e=0;eh?h:8;var k=N.T,v={};N.T=v,zc(e,!1,t,a);try{var A=f(),F=N.S;if(F!==null&&F(v,A),A!==null&&typeof A=="object"&&typeof A.then=="function"){var j=fk(A,s);Fr(e,t,j,Kt(e))}else Fr(e,t,s,Kt(e))}catch(Y){Fr(e,t,{then:function(){},status:"rejected",reason:Y},Kt())}finally{J.p=h,k!==null&&v.types!==null&&(k.types=v.types),N.T=k}}function yk(){}function Rc(e,t,a,s){if(e.tag!==5)throw Error(r(476));var f=Ph(e).queue;Ah(e,f,t,ae,a===null?yk:function(){return Bh(e),a(s)})}function Ph(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:ae,baseState:ae,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Mn,lastRenderedState:ae},next:null};var a={};return t.next={memoizedState:a,baseState:a,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Mn,lastRenderedState:a},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Bh(e){var t=Ph(e);t.next===null&&(t=e.alternate.memoizedState),Fr(e,t.next.queue,{},Kt())}function Oc(){return gt(ns)}function Dh(){return at().memoizedState}function Ih(){return at().memoizedState}function kk(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var a=Kt();e=ua(a);var s=fa(t,e,a);s!==null&&(Ot(s,t,a),Or(s,t,a)),t={cache:cc()},e.payload=t;return}t=t.return}}function bk(e,t,a){var s=Kt();a={lane:s,revertLane:0,gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},gl(e)?Oh(t,a):(a=Jo(e,t,a,s),a!==null&&(Ot(a,e,s),zh(a,t,s)))}function Rh(e,t,a){var s=Kt();Fr(e,t,a,s)}function Fr(e,t,a,s){var f={lane:s,revertLane:0,gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null};if(gl(e))Oh(t,f);else{var h=e.alternate;if(e.lanes===0&&(h===null||h.lanes===0)&&(h=t.lastRenderedReducer,h!==null))try{var k=t.lastRenderedState,v=h(k,a);if(f.hasEagerState=!0,f.eagerState=v,Ht(v,k))return Zs(e,t,f,0),Le===null&&Qs(),!1}catch{}if(a=Jo(e,t,f,s),a!==null)return Ot(a,e,s),zh(a,t,s),!0}return!1}function zc(e,t,a,s){if(s={lane:2,revertLane:hu(),gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},gl(e)){if(t)throw Error(r(479))}else t=Jo(e,a,s,2),t!==null&&Ot(t,e,2)}function gl(e){var t=e.alternate;return e===be||t!==null&&t===be}function Oh(e,t){Ii=cl=!0;var a=e.pending;a===null?t.next=t:(t.next=a.next,a.next=t),e.pending=t}function zh(e,t,a){if((a&4194048)!==0){var s=t.lanes;s&=e.pendingLanes,a|=s,t.lanes=a,qf(e,a)}}var qr={readContext:gt,use:dl,useCallback:$e,useContext:$e,useEffect:$e,useImperativeHandle:$e,useLayoutEffect:$e,useInsertionEffect:$e,useMemo:$e,useReducer:$e,useRef:$e,useState:$e,useDebugValue:$e,useDeferredValue:$e,useTransition:$e,useSyncExternalStore:$e,useId:$e,useHostTransitionStatus:$e,useFormState:$e,useActionState:$e,useOptimistic:$e,useMemoCache:$e,useCacheRefresh:$e};qr.useEffectEvent=$e;var Mh={readContext:gt,use:dl,useCallback:function(e,t){return wt().memoizedState=[e,t===void 0?null:t],e},useContext:gt,useEffect:bh,useImperativeHandle:function(e,t,a){a=a!=null?a.concat([e]):null,ml(4194308,4,wh.bind(null,t,e),a)},useLayoutEffect:function(e,t){return ml(4194308,4,e,t)},useInsertionEffect:function(e,t){ml(4,2,e,t)},useMemo:function(e,t){var a=wt();t=t===void 0?null:t;var s=e();if(Ka){na(!0);try{e()}finally{na(!1)}}return a.memoizedState=[s,t],s},useReducer:function(e,t,a){var s=wt();if(a!==void 0){var f=a(t);if(Ka){na(!0);try{a(t)}finally{na(!1)}}}else f=t;return s.memoizedState=s.baseState=f,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:f},s.queue=e,e=e.dispatch=bk.bind(null,be,e),[s.memoizedState,e]},useRef:function(e){var t=wt();return e={current:e},t.memoizedState=e},useState:function(e){e=Ac(e);var t=e.queue,a=Rh.bind(null,be,t);return t.dispatch=a,[e.memoizedState,a]},useDebugValue:Dc,useDeferredValue:function(e,t){var a=wt();return Ic(a,e,t)},useTransition:function(){var e=Ac(!1);return e=Ah.bind(null,be,e.queue,!0,!1),wt().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,a){var s=be,f=wt();if(Ae){if(a===void 0)throw Error(r(407));a=a()}else{if(a=t(),Le===null)throw Error(r(349));(_e&127)!==0||ah(s,t,a)}f.memoizedState=a;var h={value:a,getSnapshot:t};return f.queue=h,bh(rh.bind(null,s,h,e),[e]),s.flags|=2048,Oi(9,{destroy:void 0},ih.bind(null,s,h,a,t),null),a},useId:function(){var e=wt(),t=Le.identifierPrefix;if(Ae){var a=bn,s=kn;a=(s&~(1<<32-qt(s)-1)).toString(32)+a,t="_"+t+"R_"+a,a=ul++,0<\/script>",h=h.removeChild(h.firstChild);break;case"select":h=typeof s.is=="string"?k.createElement("select",{is:s.is}):k.createElement("select"),s.multiple?h.multiple=!0:s.size&&(h.size=s.size);break;default:h=typeof s.is=="string"?k.createElement(f,{is:s.is}):k.createElement(f)}}h[mt]=t,h[At]=s;e:for(k=t.child;k!==null;){if(k.tag===5||k.tag===6)h.appendChild(k.stateNode);else if(k.tag!==4&&k.tag!==27&&k.child!==null){k.child.return=k,k=k.child;continue}if(k===t)break e;for(;k.sibling===null;){if(k.return===null||k.return===t)break e;k=k.return}k.sibling.return=k.return,k=k.sibling}t.stateNode=h;e:switch(kt(h,f,s),f){case"button":case"input":case"select":case"textarea":s=!!s.autoFocus;break e;case"img":s=!0;break e;default:s=!1}s&&Un(t)}}return Ke(t),Qc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,a),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==s&&Un(t);else{if(typeof s!="string"&&t.stateNode===null)throw Error(r(166));if(e=we.current,Ci(t)){if(e=t.stateNode,a=t.memoizedProps,s=null,f=pt,f!==null)switch(f.tag){case 27:case 5:s=f.memoizedProps}e[mt]=t,e=!!(e.nodeValue===a||s!==null&&s.suppressHydrationWarning===!0||tp(e.nodeValue,a)),e||la(t,!0)}else e=Ml(e).createTextNode(s),e[mt]=t,t.stateNode=e}return Ke(t),null;case 31:if(a=t.memoizedState,e===null||e.memoizedState!==null){if(s=Ci(t),a!==null){if(e===null){if(!s)throw Error(r(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(r(557));e[mt]=t}else qa(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Ke(t),e=!1}else a=rc(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),e=!0;if(!e)return t.flags&256?(jt(t),t):(jt(t),null);if((t.flags&128)!==0)throw Error(r(558))}return Ke(t),null;case 13:if(s=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(f=Ci(t),s!==null&&s.dehydrated!==null){if(e===null){if(!f)throw Error(r(318));if(f=t.memoizedState,f=f!==null?f.dehydrated:null,!f)throw Error(r(317));f[mt]=t}else qa(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Ke(t),f=!1}else f=rc(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=f),f=!0;if(!f)return t.flags&256?(jt(t),t):(jt(t),null)}return jt(t),(t.flags&128)!==0?(t.lanes=a,t):(a=s!==null,e=e!==null&&e.memoizedState!==null,a&&(s=t.child,f=null,s.alternate!==null&&s.alternate.memoizedState!==null&&s.alternate.memoizedState.cachePool!==null&&(f=s.alternate.memoizedState.cachePool.pool),h=null,s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(h=s.memoizedState.cachePool.pool),h!==f&&(s.flags|=2048)),a!==e&&a&&(t.child.flags|=8192),Tl(t,t.updateQueue),Ke(t),null);case 4:return Ze(),e===null&&yu(t.stateNode.containerInfo),Ke(t),null;case 10:return On(t.type),Ke(t),null;case 19:if(Q(nt),s=t.memoizedState,s===null)return Ke(t),null;if(f=(t.flags&128)!==0,h=s.rendering,h===null)if(f)Lr(s,!1);else{if(et!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(h=ol(e),h!==null){for(t.flags|=128,Lr(s,!1),e=h.updateQueue,t.updateQueue=e,Tl(t,e),t.subtreeFlags=0,e=a,a=t.child;a!==null;)Rd(a,e),a=a.sibling;return ne(nt,nt.current&1|2),Ae&&In(t,s.treeForkCount),t.child}e=e.sibling}s.tail!==null&&Ut()>_l&&(t.flags|=128,f=!0,Lr(s,!1),t.lanes=4194304)}else{if(!f)if(e=ol(h),e!==null){if(t.flags|=128,f=!0,e=e.updateQueue,t.updateQueue=e,Tl(t,e),Lr(s,!0),s.tail===null&&s.tailMode==="hidden"&&!h.alternate&&!Ae)return Ke(t),null}else 2*Ut()-s.renderingStartTime>_l&&a!==536870912&&(t.flags|=128,f=!0,Lr(s,!1),t.lanes=4194304);s.isBackwards?(h.sibling=t.child,t.child=h):(e=s.last,e!==null?e.sibling=h:t.child=h,s.last=h)}return s.tail!==null?(e=s.tail,s.rendering=e,s.tail=e.sibling,s.renderingStartTime=Ut(),e.sibling=null,a=nt.current,ne(nt,f?a&1|2:a&1),Ae&&In(t,s.treeForkCount),e):(Ke(t),null);case 22:case 23:return jt(t),kc(),s=t.memoizedState!==null,e!==null?e.memoizedState!==null!==s&&(t.flags|=8192):s&&(t.flags|=8192),s?(a&536870912)!==0&&(t.flags&128)===0&&(Ke(t),t.subtreeFlags&6&&(t.flags|=8192)):Ke(t),a=t.updateQueue,a!==null&&Tl(t,a.retryQueue),a=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(a=e.memoizedState.cachePool.pool),s=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(s=t.memoizedState.cachePool.pool),s!==a&&(t.flags|=2048),e!==null&&Q(Va),null;case 24:return a=null,e!==null&&(a=e.memoizedState.cache),t.memoizedState.cache!==a&&(t.flags|=2048),On(rt),Ke(t),null;case 25:return null;case 30:return null}throw Error(r(156,t.tag))}function xk(e,t){switch(ac(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return On(rt),Ze(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return li(t),null;case 31:if(t.memoizedState!==null){if(jt(t),t.alternate===null)throw Error(r(340));qa()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(jt(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(r(340));qa()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Q(nt),null;case 4:return Ze(),null;case 10:return On(t.type),null;case 22:case 23:return jt(t),kc(),e!==null&&Q(Va),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return On(rt),null;case 25:return null;default:return null}}function sm(e,t){switch(ac(t),t.tag){case 3:On(rt),Ze();break;case 26:case 27:case 5:li(t);break;case 4:Ze();break;case 31:t.memoizedState!==null&&jt(t);break;case 13:jt(t);break;case 19:Q(nt);break;case 10:On(t.type);break;case 22:case 23:jt(t),kc(),e!==null&&Q(Va);break;case 24:On(rt)}}function Vr(e,t){try{var a=t.updateQueue,s=a!==null?a.lastEffect:null;if(s!==null){var f=s.next;a=f;do{if((a.tag&e)===e){s=void 0;var h=a.create,k=a.inst;s=h(),k.destroy=s}a=a.next}while(a!==f)}}catch(v){Ue(t,t.return,v)}}function ma(e,t,a){try{var s=t.updateQueue,f=s!==null?s.lastEffect:null;if(f!==null){var h=f.next;s=h;do{if((s.tag&e)===e){var k=s.inst,v=k.destroy;if(v!==void 0){k.destroy=void 0,f=t;var A=a,F=v;try{F()}catch(j){Ue(f,A,j)}}}s=s.next}while(s!==h)}}catch(j){Ue(t,t.return,j)}}function lm(e){var t=e.updateQueue;if(t!==null){var a=e.stateNode;try{Wd(t,a)}catch(s){Ue(e,e.return,s)}}}function om(e,t,a){a.props=Ya(e.type,e.memoizedProps),a.state=e.memoizedState;try{a.componentWillUnmount()}catch(s){Ue(e,t,s)}}function jr(e,t){try{var a=e.ref;if(a!==null){switch(e.tag){case 26:case 27:case 5:var s=e.stateNode;break;case 30:s=e.stateNode;break;default:s=e.stateNode}typeof a=="function"?e.refCleanup=a(s):a.current=s}}catch(f){Ue(e,t,f)}}function Sn(e,t){var a=e.ref,s=e.refCleanup;if(a!==null)if(typeof s=="function")try{s()}catch(f){Ue(e,t,f)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof a=="function")try{a(null)}catch(f){Ue(e,t,f)}else a.current=null}function cm(e){var t=e.type,a=e.memoizedProps,s=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":a.autoFocus&&s.focus();break e;case"img":a.src?s.src=a.src:a.srcSet&&(s.srcset=a.srcSet)}}catch(f){Ue(e,e.return,f)}}function Zc(e,t,a){try{var s=e.stateNode;Gk(s,e.type,a,t),s[At]=t}catch(f){Ue(e,e.return,f)}}function um(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Ta(e.type)||e.tag===4}function Wc(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||um(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Ta(e.type)||e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Jc(e,t,a){var s=e.tag;if(s===5||s===6)e=e.stateNode,t?(a.nodeType===9?a.body:a.nodeName==="HTML"?a.ownerDocument.body:a).insertBefore(e,t):(t=a.nodeType===9?a.body:a.nodeName==="HTML"?a.ownerDocument.body:a,t.appendChild(e),a=a._reactRootContainer,a!=null||t.onclick!==null||(t.onclick=Pn));else if(s!==4&&(s===27&&Ta(e.type)&&(a=e.stateNode,t=null),e=e.child,e!==null))for(Jc(e,t,a),e=e.sibling;e!==null;)Jc(e,t,a),e=e.sibling}function vl(e,t,a){var s=e.tag;if(s===5||s===6)e=e.stateNode,t?a.insertBefore(e,t):a.appendChild(e);else if(s!==4&&(s===27&&Ta(e.type)&&(a=e.stateNode),e=e.child,e!==null))for(vl(e,t,a),e=e.sibling;e!==null;)vl(e,t,a),e=e.sibling}function fm(e){var t=e.stateNode,a=e.memoizedProps;try{for(var s=e.type,f=t.attributes;f.length;)t.removeAttributeNode(f[0]);kt(t,s,a),t[mt]=e,t[At]=a}catch(h){Ue(e,e.return,h)}}var Fn=!1,ot=!1,$c=!1,dm=typeof WeakSet=="function"?WeakSet:Set,ft=null;function Ck(e,t){if(e=e.containerInfo,Su=Vl,e=xd(e),Go(e)){if("selectionStart"in e)var a={start:e.selectionStart,end:e.selectionEnd};else e:{a=(a=e.ownerDocument)&&a.defaultView||window;var s=a.getSelection&&a.getSelection();if(s&&s.rangeCount!==0){a=s.anchorNode;var f=s.anchorOffset,h=s.focusNode;s=s.focusOffset;try{a.nodeType,h.nodeType}catch{a=null;break e}var k=0,v=-1,A=-1,F=0,j=0,Y=e,q=null;t:for(;;){for(var V;Y!==a||f!==0&&Y.nodeType!==3||(v=k+f),Y!==h||s!==0&&Y.nodeType!==3||(A=k+s),Y.nodeType===3&&(k+=Y.nodeValue.length),(V=Y.firstChild)!==null;)q=Y,Y=V;for(;;){if(Y===e)break t;if(q===a&&++F===f&&(v=k),q===h&&++j===s&&(A=k),(V=Y.nextSibling)!==null)break;Y=q,q=Y.parentNode}Y=V}a=v===-1||A===-1?null:{start:v,end:A}}else a=null}a=a||{start:0,end:0}}else a=null;for(Tu={focusedElem:e,selectionRange:a},Vl=!1,ft=t;ft!==null;)if(t=ft,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,ft=e;else for(;ft!==null;){switch(t=ft,h=t.alternate,e=t.flags,t.tag){case 0:if((e&4)!==0&&(e=t.updateQueue,e=e!==null?e.events:null,e!==null))for(a=0;a title"))),kt(h,s,a),h[mt]=e,ut(h),s=h;break e;case"link":var k=kp("link","href",f).get(s+(a.href||""));if(k){for(var v=0;vHe&&(k=He,He=me,me=k);var M=vd(v,me),I=vd(v,He);if(M&&I&&(V.rangeCount!==1||V.anchorNode!==M.node||V.anchorOffset!==M.offset||V.focusNode!==I.node||V.focusOffset!==I.offset)){var U=Y.createRange();U.setStart(M.node,M.offset),V.removeAllRanges(),me>He?(V.addRange(U),V.extend(I.node,I.offset)):(U.setEnd(I.node,I.offset),V.addRange(U))}}}}for(Y=[],V=v;V=V.parentNode;)V.nodeType===1&&Y.push({element:V,left:V.scrollLeft,top:V.scrollTop});for(typeof v.focus=="function"&&v.focus(),v=0;va?32:a,N.T=null,a=su,su=null;var h=ka,k=jn;if(ct=0,Fi=ka=null,jn=0,(ze&6)!==0)throw Error(r(331));var v=ze;if(ze|=4,wm(h.current),Sm(h,h.current,k,a),ze=v,Zr(0,!1),Ft&&typeof Ft.onPostCommitFiberRoot=="function")try{Ft.onPostCommitFiberRoot(mr,h)}catch{}return!0}finally{J.p=f,N.T=s,Hm(e,t)}}function Vm(e,t,a){t=nn(a,t),t=Fc(e.stateNode,t,2),e=fa(e,t,2),e!==null&&(gr(e,2),Tn(e))}function Ue(e,t,a){if(e.tag===3)Vm(e,e,a);else for(;t!==null;){if(t.tag===3){Vm(t,e,a);break}else if(t.tag===1){var s=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof s.componentDidCatch=="function"&&(ya===null||!ya.has(s))){e=nn(a,e),a=jh(2),s=fa(t,a,2),s!==null&&(Xh(a,s,t,e),gr(s,2),Tn(s));break}}t=t.return}}function uu(e,t,a){var s=e.pingCache;if(s===null){s=e.pingCache=new Ak;var f=new Set;s.set(t,f)}else f=s.get(t),f===void 0&&(f=new Set,s.set(t,f));f.has(a)||(nu=!0,f.add(a),e=Rk.bind(null,e,t,a),t.then(e,e))}function Rk(e,t,a){var s=e.pingCache;s!==null&&s.delete(t),e.pingedLanes|=e.suspendedLanes&a,e.warmLanes&=~a,Le===e&&(_e&a)===a&&(et===4||et===3&&(_e&62914560)===_e&&300>Ut()-Cl?(ze&2)===0&&qi(e,0):au|=a,Ui===_e&&(Ui=0)),Tn(e)}function jm(e,t){t===0&&(t=Uf()),e=Ua(e,t),e!==null&&(gr(e,t),Tn(e))}function Ok(e){var t=e.memoizedState,a=0;t!==null&&(a=t.retryLane),jm(e,a)}function zk(e,t){var a=0;switch(e.tag){case 31:case 13:var s=e.stateNode,f=e.memoizedState;f!==null&&(a=f.retryLane);break;case 19:s=e.stateNode;break;case 22:s=e.stateNode._retryCache;break;default:throw Error(r(314))}s!==null&&s.delete(t),jm(e,a)}function Mk(e,t){return wo(e,t)}var Il=null,Li=null,fu=!1,Rl=!1,du=!1,Sa=0;function Tn(e){e!==Li&&e.next===null&&(Li===null?Il=Li=e:Li=Li.next=e),Rl=!0,fu||(fu=!0,Uk())}function Zr(e,t){if(!du&&Rl){du=!0;do for(var a=!1,s=Il;s!==null;){if(e!==0){var f=s.pendingLanes;if(f===0)var h=0;else{var k=s.suspendedLanes,v=s.pingedLanes;h=(1<<31-qt(42|e)+1)-1,h&=f&~(k&~v),h=h&201326741?h&201326741|1:h?h|2:0}h!==0&&(a=!0,Ym(s,h))}else h=_e,h=Ns(s,s===Le?h:0,s.cancelPendingCommit!==null||s.timeoutHandle!==-1),(h&3)===0||pr(s,h)||(a=!0,Ym(s,h));s=s.next}while(a);du=!1}}function Nk(){Xm()}function Xm(){Rl=fu=!1;var e=0;Sa!==0&&Yk()&&(e=Sa);for(var t=Ut(),a=null,s=Il;s!==null;){var f=s.next,h=Gm(s,t);h===0?(s.next=null,a===null?Il=f:a.next=f,f===null&&(Li=a)):(a=s,(e!==0||(h&3)!==0)&&(Rl=!0)),s=f}ct!==0&&ct!==5||Zr(e),Sa!==0&&(Sa=0)}function Gm(e,t){for(var a=e.suspendedLanes,s=e.pingedLanes,f=e.expirationTimes,h=e.pendingLanes&-62914561;0v)break;var j=A.transferSize,Y=A.initiatorType;j&&np(Y)&&(A=A.responseEnd,k+=j*(A"u"?null:document;function mp(e,t,a){var s=Vi;if(s&&typeof t=="string"&&t){var f=en(t);f='link[rel="'+e+'"][href="'+f+'"]',typeof a=="string"&&(f+='[crossorigin="'+a+'"]'),hp.has(f)||(hp.add(f),e={rel:e,crossOrigin:a,href:t},s.querySelector(f)===null&&(t=s.createElement("link"),kt(t,"link",e),ut(t),s.head.appendChild(t)))}}function ab(e){Xn.D(e),mp("dns-prefetch",e,null)}function ib(e,t){Xn.C(e,t),mp("preconnect",e,t)}function rb(e,t,a){Xn.L(e,t,a);var s=Vi;if(s&&e&&t){var f='link[rel="preload"][as="'+en(t)+'"]';t==="image"&&a&&a.imageSrcSet?(f+='[imagesrcset="'+en(a.imageSrcSet)+'"]',typeof a.imageSizes=="string"&&(f+='[imagesizes="'+en(a.imageSizes)+'"]')):f+='[href="'+en(e)+'"]';var h=f;switch(t){case"style":h=ji(e);break;case"script":h=Xi(e)}cn.has(h)||(e=g({rel:"preload",href:t==="image"&&a&&a.imageSrcSet?void 0:e,as:t},a),cn.set(h,e),s.querySelector(f)!==null||t==="style"&&s.querySelector(es(h))||t==="script"&&s.querySelector(ts(h))||(t=s.createElement("link"),kt(t,"link",e),ut(t),s.head.appendChild(t)))}}function sb(e,t){Xn.m(e,t);var a=Vi;if(a&&e){var s=t&&typeof t.as=="string"?t.as:"script",f='link[rel="modulepreload"][as="'+en(s)+'"][href="'+en(e)+'"]',h=f;switch(s){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":h=Xi(e)}if(!cn.has(h)&&(e=g({rel:"modulepreload",href:e},t),cn.set(h,e),a.querySelector(f)===null)){switch(s){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(a.querySelector(ts(h)))return}s=a.createElement("link"),kt(s,"link",e),ut(s),a.head.appendChild(s)}}}function lb(e,t,a){Xn.S(e,t,a);var s=Vi;if(s&&e){var f=di(s).hoistableStyles,h=ji(e);t=t||"default";var k=f.get(h);if(!k){var v={loading:0,preload:null};if(k=s.querySelector(es(h)))v.loading=5;else{e=g({rel:"stylesheet",href:e,"data-precedence":t},a),(a=cn.get(h))&&Au(e,a);var A=k=s.createElement("link");ut(A),kt(A,"link",e),A._p=new Promise(function(F,j){A.onload=F,A.onerror=j}),A.addEventListener("load",function(){v.loading|=1}),A.addEventListener("error",function(){v.loading|=2}),v.loading|=4,Ul(k,t,s)}k={type:"stylesheet",instance:k,count:1,state:v},f.set(h,k)}}}function ob(e,t){Xn.X(e,t);var a=Vi;if(a&&e){var s=di(a).hoistableScripts,f=Xi(e),h=s.get(f);h||(h=a.querySelector(ts(f)),h||(e=g({src:e,async:!0},t),(t=cn.get(f))&&Pu(e,t),h=a.createElement("script"),ut(h),kt(h,"link",e),a.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},s.set(f,h))}}function cb(e,t){Xn.M(e,t);var a=Vi;if(a&&e){var s=di(a).hoistableScripts,f=Xi(e),h=s.get(f);h||(h=a.querySelector(ts(f)),h||(e=g({src:e,async:!0,type:"module"},t),(t=cn.get(f))&&Pu(e,t),h=a.createElement("script"),ut(h),kt(h,"link",e),a.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},s.set(f,h))}}function pp(e,t,a,s){var f=(f=we.current)?Nl(f):null;if(!f)throw Error(r(446));switch(e){case"meta":case"title":return null;case"style":return typeof a.precedence=="string"&&typeof a.href=="string"?(t=ji(a.href),a=di(f).hoistableStyles,s=a.get(t),s||(s={type:"style",instance:null,count:0,state:null},a.set(t,s)),s):{type:"void",instance:null,count:0,state:null};case"link":if(a.rel==="stylesheet"&&typeof a.href=="string"&&typeof a.precedence=="string"){e=ji(a.href);var h=di(f).hoistableStyles,k=h.get(e);if(k||(f=f.ownerDocument||f,k={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},h.set(e,k),(h=f.querySelector(es(e)))&&!h._p&&(k.instance=h,k.state.loading=5),cn.has(e)||(a={rel:"preload",as:"style",href:a.href,crossOrigin:a.crossOrigin,integrity:a.integrity,media:a.media,hrefLang:a.hrefLang,referrerPolicy:a.referrerPolicy},cn.set(e,a),h||ub(f,e,a,k.state))),t&&s===null)throw Error(r(528,""));return k}if(t&&s!==null)throw Error(r(529,""));return null;case"script":return t=a.async,a=a.src,typeof a=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=Xi(a),a=di(f).hoistableScripts,s=a.get(t),s||(s={type:"script",instance:null,count:0,state:null},a.set(t,s)),s):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,e))}}function ji(e){return'href="'+en(e)+'"'}function es(e){return'link[rel="stylesheet"]['+e+"]"}function gp(e){return g({},e,{"data-precedence":e.precedence,precedence:null})}function ub(e,t,a,s){e.querySelector('link[rel="preload"][as="style"]['+t+"]")?s.loading=1:(t=e.createElement("link"),s.preload=t,t.addEventListener("load",function(){return s.loading|=1}),t.addEventListener("error",function(){return s.loading|=2}),kt(t,"link",a),ut(t),e.head.appendChild(t))}function Xi(e){return'[src="'+en(e)+'"]'}function ts(e){return"script[async]"+e}function yp(e,t,a){if(t.count++,t.instance===null)switch(t.type){case"style":var s=e.querySelector('style[data-href~="'+en(a.href)+'"]');if(s)return t.instance=s,ut(s),s;var f=g({},a,{"data-href":a.href,"data-precedence":a.precedence,href:null,precedence:null});return s=(e.ownerDocument||e).createElement("style"),ut(s),kt(s,"style",f),Ul(s,a.precedence,e),t.instance=s;case"stylesheet":f=ji(a.href);var h=e.querySelector(es(f));if(h)return t.state.loading|=4,t.instance=h,ut(h),h;s=gp(a),(f=cn.get(f))&&Au(s,f),h=(e.ownerDocument||e).createElement("link"),ut(h);var k=h;return k._p=new Promise(function(v,A){k.onload=v,k.onerror=A}),kt(h,"link",s),t.state.loading|=4,Ul(h,a.precedence,e),t.instance=h;case"script":return h=Xi(a.src),(f=e.querySelector(ts(h)))?(t.instance=f,ut(f),f):(s=a,(f=cn.get(h))&&(s=g({},a),Pu(s,f)),e=e.ownerDocument||e,f=e.createElement("script"),ut(f),kt(f,"link",s),e.head.appendChild(f),t.instance=f);case"void":return null;default:throw Error(r(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(s=t.instance,t.state.loading|=4,Ul(s,a.precedence,e));return t.instance}function Ul(e,t,a){for(var s=a.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),f=s.length?s[s.length-1]:null,h=f,k=0;k title"):null)}function fb(e,t,a){if(a===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;return t.rel==="stylesheet"?(e=t.disabled,typeof t.precedence=="string"&&e==null):!0;case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function Sp(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function db(e,t,a,s){if(a.type==="stylesheet"&&(typeof s.media!="string"||matchMedia(s.media).matches!==!1)&&(a.state.loading&4)===0){if(a.instance===null){var f=ji(s.href),h=t.querySelector(es(f));if(h){t=h._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=ql.bind(e),t.then(e,e)),a.state.loading|=4,a.instance=h,ut(h);return}h=t.ownerDocument||t,s=gp(s),(f=cn.get(f))&&Au(s,f),h=h.createElement("link"),ut(h);var k=h;k._p=new Promise(function(v,A){k.onload=v,k.onerror=A}),kt(h,"link",s),a.instance=h}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(a,t),(t=a.state.preload)&&(a.state.loading&3)===0&&(e.count++,a=ql.bind(e),t.addEventListener("load",a),t.addEventListener("error",a))}}var Bu=0;function hb(e,t){return e.stylesheets&&e.count===0&&Ll(e,e.stylesheets),0Bu?50:800)+t);return e.unsuspend=a,function(){e.unsuspend=null,clearTimeout(s),clearTimeout(f)}}:null}function ql(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Ll(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Hl=null;function Ll(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Hl=new Map,t.forEach(mb,e),Hl=null,ql.call(e))}function mb(e,t){if(!(t.state.loading&4)){var a=Hl.get(e);if(a)var s=a.get(null);else{a=new Map,Hl.set(e,a);for(var f=e.querySelectorAll("link[data-precedence],style[data-precedence]"),h=0;h"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(l)}catch(n){console.error(n)}}return l(),Fu.exports=Bb(),Fu.exports}var Ib=Db();const Xe={maxSourceBytes:2*1024*1024*1024,maxDurationSeconds:10800,inlineDecodeMaxBytes:12*1024*1024,inlineDecodeMaxSeconds:90,targetSampleRate:16e3,maxRecordingSeconds:300,windowSeconds:30,overlapSeconds:5,interChunkYieldMs:16};class Ve extends Error{code;phase;recoverable;constructor(n,i,r,o=!0){super(r),this.name="AudioPipelineError",this.code=n,this.phase=i,this.recoverable=o}}function dr(l){if(l?.aborted)throw new Ve("CANCELLED","decode","Audio pipeline cancelled.")}function jp(l=Xe.interChunkYieldMs){return new Promise(n=>{window.setTimeout(n,l)})}function C(l){if(!l)throw new Error("Assertion failed.")}const Mg=l=>{const n=(l%360+360)%360;if(n===0||n===90||n===180||n===270)return n;throw new Error(`Invalid rotation ${l}.`)},Zt=l=>l&&l[l.length-1],ee=l=>{let n=0;for(;l.readBits(1)===0&&n<32;)n++;if(n>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const n=ee(l);return(n&1)===0?-(n>>1):n+1>>1},Ng=l=>l.constructor===Uint8Array?l:ArrayBuffer.isView(l)?new Uint8Array(l.buffer,l.byteOffset,l.byteLength):new Uint8Array(l),Re=l=>l.constructor===DataView?l:ArrayBuffer.isView(l)?new DataView(l.buffer,l.byteOffset,l.byteLength):new DataView(l),Mt=new TextDecoder,bf=l=>Object.fromEntries(Object.entries(l).map(([n,i])=>[i,n])),Ug={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},io=bf(Ug),Fg={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},ro=bf(Fg),qg={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},so=bf(qg),Rb=l=>l instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&l instanceof SharedArrayBuffer||ArrayBuffer.isView(l);class ho{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let n;const i=new Promise(o=>{let u=!1;n=()=>{u||(o(),this.pending--,u=!0)}}),r=this.currentPromise;return this.currentPromise=i,this.pending++,await r,n}}const Ob=/^[0-9a-fA-F]+$/,ws=l=>[...l].map(n=>n.toString(16).padStart(2,"0")).join(""),zb=l=>{C(l.length%2===0);const n=new Uint8Array(l.length/2);for(let i=0;i(l=l>>1&1431655765|(l&1431655765)<<1,l=l>>2&858993459|(l&858993459)<<2,l=l>>4&252645135|(l&252645135)<<4,l=l>>8&16711935|(l&16711935)<<8,l=l>>16&65535|(l&65535)<<16,l>>>0),Bs=(l,n,i)=>{let r=0,o=l.length-1,u=-1;for(;r<=o;){const c=r+o>>1,d=i(l[c]);d===n?(u=c,o=c-1):d{let r=0,o=l.length-1,u=-1;for(;r<=o;){const c=r+(o-r+1)/2|0;i(l[c])<=n?(u=c,r=c+1):o=c-1}return u},zt=()=>{let l,n;return{promise:new Promise((r,o)=>{l=r,n=o}),resolve:l,reject:n}},Mb=(l,n)=>{const i=l.indexOf(n);i!==-1&&l.splice(i,1)},Hg=(l,n)=>{for(let i=l.length-1;i>=0;i--)if(n(l[i]))return l[i]},Sf=(l,n)=>{for(let i=l.length-1;i>=0;i--)if(n(l[i]))return i;return-1},Nb=async function*(l){Symbol.iterator in l?yield*l[Symbol.iterator]():yield*l[Symbol.asyncIterator]()},Ub=l=>{if(!(Symbol.iterator in l)&&!(Symbol.asyncIterator in l))throw new TypeError("Argument must be an iterable or async iterable.")},xs=l=>{throw new Error(`Unexpected value: ${l}`)},mo=(l,n,i)=>{const r=l.getUint8(n),o=l.getUint8(n+1),u=l.getUint8(n+2);return i?r|o<<8|u<<16:r<<16|o<<8|u},Fb=(l,n,i)=>mo(l,n,i)<<8>>8,Gp=(l,n)=>({async next(){const i=await l.next();return i.done?{value:void 0,done:!0}:{value:n(i.value),done:!1}},return(){return l.return()},throw(i){return l.throw(i)},[Symbol.asyncIterator](){return this}}),or=(l,n,i)=>Math.max(n,Math.min(i,l)),_t="und",Cs=l=>{const n=Math.round(l);return Math.abs(l/n-1)<10*Number.EPSILON?n:l},qb=(l,n)=>Math.round(l/n)*n,Lg=(l,n)=>Math.round(l*n)/n,Vu=(l,n)=>Math.floor(l/n)*n,Hb=l=>{let n=0;for(;l;)n++,l>>=1;return n},Lb=/^[a-z]{3}$/,Vg=l=>Lb.test(l),lo=1e6*(1+Number.EPSILON);class Vb{constructor(){this.currentPromise=Promise.resolve()}call(n){return this.currentPromise=this.currentPromise.then(n)}}let ju=null;const jg=()=>ju!==null?ju:ju=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let Xu=null;const jb=()=>Xu!==null?Xu:Xu=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent)));let Gu=null;const Xb=()=>{if(Gu!==null)return Gu;if(typeof navigator>"u")return null;const l=/\bChrome\/(\d+)/.exec(navigator.userAgent);return l?Gu=Number(l[1]):null},Zi=(l,n)=>l!==-1?l:n,Kp=(l,n,i,r)=>l<=r&&i<=n,Xg=l=>{const n=atob(l),i=new Uint8Array(n.length);for(let r=0;r{if(l.length!==n.length)return!1;for(let i=0;i{Symbol.dispose??=Symbol("Symbol.dispose")},vf=l=>typeof l=="number"&&!Number.isNaN(l),Ba=(l,n)=>{if(n.includes("://"))return n;if(l.includes("://")){const d=l.indexOf("?");d!==-1&&(l=l.slice(0,d))}let i;if(n.startsWith("/")){const d=l.indexOf("://");if(d===-1)i=n;else{const m=l.indexOf("/",d+3);m===-1?i=l+n:i=l.slice(0,m)+n}}else{const d=l.lastIndexOf("/");d===-1?i=n:i=l.slice(0,d+1)+n}let r="";const o=i.indexOf("://");if(o!==-1){const d=i.indexOf("/",o+3);d!==-1&&(r=i.slice(0,d),i=i.slice(d))}const u=i.split("/"),c=[];for(const d of u)d===".."?c.pop():d!=="."&&c.push(d);return r+c.join("/")},ps=(l,n)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let o=0;o{C(Number.isInteger(l.num)),C(Number.isInteger(l.den)),C(l.den!==0);let n=Math.abs(l.num),i=Math.abs(l.den);for(;i!==0;){const o=n%i;n=i,i=o}const r=n||1;return{num:l.num/r,den:l.den/r}},Kb=l=>new Promise(n=>setTimeout(n,l));class wf{constructor(){this._listeners=new Map}on(n,i,r){this._listeners.has(n)||this._listeners.set(n,new Set);const o={fn:i,once:r?.once??!1};return this._listeners.get(n).add(o),()=>{this._listeners.get(n)?.delete(o)}}_emit(...n){const[i,r]=n,o=this._listeners.get(i);if(o)for(const u of o){try{u.fn(r)}catch(c){console.error(c)}u.once&&o.delete(u)}}}var wn;(function(l){l[l.Silent=0]="Silent",l[l.Errors=1]="Errors",l[l.Warnings=2]="Warnings",l[l.Info=3]="Info"})(wn||(wn={}));class ke{constructor(){}static get level(){return ke._level}static set level(n){if(n!==wn.Silent&&n!==wn.Errors&&n!==wn.Warnings&&n!==wn.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");ke._level=n}static get _emitter(){return ke._emitterInstance??=new wf}static on(n,i,r){return ke._emitter.on(n,i,r)}static _error(...n){ke._emitter._emit("error",n),ke._level>=wn.Errors&&console.error(...n)}static _warn(...n){ke._emitter._emit("warn",n),ke._level>=wn.Warnings&&console.warn(...n)}static _info(...n){ke._emitter._emit("info",n),ke._level>=wn.Info&&console.info(...n)}}ke._level=wn.Info;ke._emitterInstance=null;class eo{constructor(n,i){if(this.data=n,this.mimeType=i,!(n instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof i!="string")throw new TypeError("mimeType must be a string.")}}class Yb{constructor(n,i,r,o){if(this.data=n,this.mimeType=i,this.name=r,this.description=o,!(n instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(i!==void 0&&typeof i!="string")throw new TypeError("mimeType, when provided, must be a string.");if(r!==void 0&&typeof r!="string")throw new TypeError("name, when provided, must be a string.");if(o!==void 0&&typeof o!="string")throw new TypeError("description, when provided, must be a string.")}}const ea={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Me{constructor(n){this.bytes=n,this.pos=0}seekToByte(n){this.pos=8*n}readBit(){const n=Math.floor(this.pos/8),i=this.bytes[n]??0,r=7-(this.pos&7),o=(i&1<>r;return this.pos++,o}readBits(n){if(n===1)return this.readBit();let i=0;for(let r=0;r>r-o-1<{if(!l||l.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const n=new Me(l);let i=n.readBits(5);i===31&&(i=32+n.readBits(6));const r=n.readBits(4);let o=null;r===15?o=n.readBits(24):r<_s.length&&(o=_s[r]);const u=n.readBits(4);let c=null;return u>=1&&u<=7&&(c=xf[u]),{objectType:i,frequencyIndex:r,sampleRate:o,channelConfiguration:u,numberOfChannels:c}};const Qp=["avc","hevc","vp9","av1","vp8","prores"],hr=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],Qb=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Zp=[...Qb,...hr],Wp=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],ar=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Jp=".01.01.01.01.00",$p=".0.110.01.01.01.0",Cf=["ap4x","ap4h","apch","apcn","apcs","apco"],_f=l=>{const{codec:n,codecDescription:i,colorSpace:r,avcCodecInfo:o,hevcCodecInfo:u,vp9CodecInfo:c,av1CodecInfo:d,proresFormat:m}=l;if(n==="avc"){if(C(l.avcType!==null),o){const p=new Uint8Array([o.avcProfileIndication,o.profileCompatibility,o.avcLevelIndication]);return`avc${l.avcType}.${ws(p)}`}if(!i||i.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${l.avcType}.${ws(i.subarray(1,4))}`}else if(n==="hevc"){let p,y,g,b,T,w;if(u)p=u.generalProfileSpace,y=u.generalProfileIdc,g=Xp(u.generalProfileCompatibilityFlags),b=u.generalTierFlag,T=u.generalLevelIdc,w=[...u.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const E=Re(i),x=E.getUint8(1);p=x>>6&3,y=x&31,g=Xp(E.getUint32(2)),b=x>>5&1,T=E.getUint8(12),w=[];for(let P=0;P<6;P++)w.push(E.getUint8(6+P))}let S="hev1.";for(S+=["","A","B","C"][p]+y,S+=".",S+=g.toString(16).toUpperCase(),S+=".",S+=b===0?"L":"H",S+=T;w.length>0&&w[w.length-1]===0;)w.pop();return w.length>0&&(S+=".",S+=w.map(E=>E.toString(16).toUpperCase()).join(".")),S}else{if(n==="vp8")return"vp8";if(n==="vp9"){if(!c){const P=l.width*l.height;let _=Zt(ar).level;for(const D of ar)if(P<=D.maxPictureSize){_=D.level;break}return`vp09.00.${_.toString().padStart(2,"0")}.08`}const p=c.profile.toString().padStart(2,"0"),y=c.level.toString().padStart(2,"0"),g=c.bitDepth.toString().padStart(2,"0"),b=c.chromaSubsampling.toString().padStart(2,"0"),T=c.colourPrimaries.toString().padStart(2,"0"),w=c.transferCharacteristics.toString().padStart(2,"0"),S=c.matrixCoefficients.toString().padStart(2,"0"),E=c.videoFullRangeFlag.toString().padStart(2,"0");let x=`vp09.${p}.${y}.${g}.${b}`;return x+=`.${T}.${w}.${S}.${E}`,x.endsWith(Jp)&&(x=x.slice(0,-Jp.length)),x}else if(n==="av1"){if(!d){const D=l.width*l.height;let B=Zt(ar).level;for(const z of ar)if(D<=z.maxPictureSize){B=z.level;break}return`av01.0.${B.toString().padStart(2,"0")}M.08`}const p=d.profile,y=d.level.toString().padStart(2,"0"),g=d.tier?"H":"M",b=d.bitDepth.toString().padStart(2,"0"),T=d.monochrome?"1":"0",w=100*d.chromaSubsamplingX+10*d.chromaSubsamplingY+1*(d.chromaSubsamplingX&&d.chromaSubsamplingY?d.chromaSamplePosition:0),S=r?.primaries?Ug[r.primaries]:1,E=r?.transfer?Fg[r.transfer]:1,x=r?.matrix?qg[r.matrix]:1,P=r?.fullRange?1:0;let _=`av01.${p}.${y}${g}.${b}`;return _+=`.${T}.${w.toString().padStart(3,"0")}`,_+=`.${S.toString().padStart(2,"0")}`,_+=`.${E.toString().padStart(2,"0")}`,_+=`.${x.toString().padStart(2,"0")}`,_+=`.${P}`,_.endsWith($p)&&(_=_.slice(0,-$p.length)),_}else{if(n==="prores")return m??"apch";n!==null&&xs(n)}}throw new TypeError(`Unhandled codec '${n}'.`)},Ef=l=>{const{codec:n,codecDescription:i,aacCodecInfo:r}=l;if(n==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let o;return r.objectType!==null?o=r.objectType:o=Kg(i).objectType,`mp4a.40.${o}`}}else{if(n==="mp3")return"mp3";if(n==="opus")return"opus";if(n==="vorbis")return"vorbis";if(n==="flac")return"flac";if(n==="ac3")return"ac-3";if(n==="eac3")return"ec-3";if(n&&hr.includes(n))return n}throw new TypeError(`Unhandled codec '${n}'.`)},po=48e3,Yg=/^pcm-([usf])(\d+)(be)?$/,Qg=l=>{if(C(hr.includes(l)),l==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(l==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const n=Yg.exec(l);C(n);let i;n[1]==="u"?i="unsigned":n[1]==="s"?i="signed":i="float";const r=Number(n[2])/8,o=n[3]!=="be",u=l==="pcm-u8"?2**7:0;return{dataType:i,sampleSize:r,littleEndian:o,silentValue:u}},bs=l=>l.startsWith("avc1")||l.startsWith("avc3")?"avc":l.startsWith("hev1")||l.startsWith("hvc1")?"hevc":l==="vp8"?"vp8":l.startsWith("vp09")?"vp9":l.startsWith("av01")?"av1":Cf.includes(l)?"prores":l==="mp3"||l==="mp4a.69"||l==="mp4a.6B"||l==="mp4a.6b"||l==="mp4a.40.34"?"mp3":l.startsWith("mp4a.40.")||l==="mp4a.67"?"aac":l==="opus"?"opus":l==="vorbis"?"vorbis":l==="flac"?"flac":l==="ac-3"||l==="ac3"?"ac3":l==="ec-3"||l==="eac3"?"eac3":l==="ulaw"?"ulaw":l==="alaw"?"alaw":Yg.test(l)?l:l==="webvtt"?"webvtt":null;const ri=4,Zb=[44100,48e3,32e3],Wb=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Zg=1483304551,Wg=1231971951,Jb=(l,n,i,r,o)=>n===0?0:n===1?Math.floor(144*i/(r<n===0?0:n===1?144*i/(r<l===3?n===3?21:36:n===3?13:21,Af=(l,n)=>{const i=l>>>24,r=l>>>16&255,o=l>>>8&255,u=l&255;if(i!==255&&r!==255&&o!==255&&u!==255)return{header:null,bytesAdvanced:4};if(i!==255)return{header:null,bytesAdvanced:1};if((r&224)!==224)return{header:null,bytesAdvanced:1};let c=0,d=0;r&16?c=r&8?0:1:(c=1,d=1);const m=r>>3&3,p=r>>1&3,y=o>>4&15,g=(o>>2&3)%3,b=o>>1&1,T=u>>6&3,w=u>>4&3,S=u>>3&1,E=u>>2&1,x=u&3,P=Wb[c*16*4+p*16+y];if(P===-1)return{header:null,bytesAdvanced:1};const _=P*1e3,D=Zb[g]>>c+d,B=Jb(c,p,_,D,b);if(n!==null&&n{let n=2130706432,i=0;for(;n!==0;)i>>=1,i|=l&n,n>>=8;return i};var oo;(function(l){l[l.FrameCount=1]="FrameCount",l[l.FileSize=2]="FileSize",l[l.Toc=4]="Toc"})(oo||(oo={}));const Es=l=>l===3?1:2;const go=[48e3,44100,32e3],$g=[24e3,22050,16e3];var vt;(function(l){l[l.NON_IDR_SLICE=1]="NON_IDR_SLICE",l[l.SLICE_DPA=2]="SLICE_DPA",l[l.SLICE_DPB=3]="SLICE_DPB",l[l.SLICE_DPC=4]="SLICE_DPC",l[l.IDR=5]="IDR",l[l.SEI=6]="SEI",l[l.SPS=7]="SPS",l[l.PPS=8]="PPS",l[l.AUD=9]="AUD",l[l.SPS_EXT=13]="SPS_EXT"})(vt||(vt={}));var St;(function(l){l[l.RASL_N=8]="RASL_N",l[l.RASL_R=9]="RASL_R",l[l.BLA_W_LP=16]="BLA_W_LP",l[l.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",l[l.VPS_NUT=32]="VPS_NUT",l[l.SPS_NUT=33]="SPS_NUT",l[l.PPS_NUT=34]="PPS_NUT",l[l.AUD_NUT=35]="AUD_NUT",l[l.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",l[l.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(St||(St={}));const yo=function*(l){let n=0,i=-1;for(;n=l.length-2)break;n=r;let o=0;if(n+3i&&(yield{offset:i,length:n-i}),i=n+o,n=i}i!==-1&&i{if(n.description){const o=(Ng(n.description)[4]&3)+1;return e0(l,o)}else return yo(l)},Pf=l=>l&31,ko=l=>{const n=[],i=l.length;for(let r=0;r{try{const n=[],i=[],r=[];for(const d of yo(l)){const m=l.subarray(d.offset,d.offset+d.length),p=Pf(m[0]);p===vt.SPS?n.push(m):p===vt.PPS?i.push(m):p===vt.SPS_EXT&&r.push(m)}if(n.length===0||i.length===0)return null;const o=n[0],u=a0(o);C(u!==null);const c=u.profileIdc===100||u.profileIdc===110||u.profileIdc===122||u.profileIdc===144;return{configurationVersion:1,avcProfileIndication:u.profileIdc,profileCompatibility:u.constraintFlags,avcLevelIndication:u.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:n,pictureParameterSets:i,chromaFormat:c?u.chromaFormatIdc:null,bitDepthLumaMinus8:c?u.bitDepthLumaMinus8:null,bitDepthChromaMinus8:c?u.bitDepthChromaMinus8:null,sequenceParameterSetExt:c?r:null}}catch(n){return ke._error("Error building AVC Decoder Configuration Record:",n),null}},n0={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},a0=l=>{try{const n=new Me(ko(l));if(n.skipBits(1),n.skipBits(2),n.readBits(5)!==7)return null;const r=n.readAlignedByte(),o=n.readAlignedByte(),u=n.readAlignedByte();ee(n);let c=1,d=0,m=0,p=0;if((r===100||r===110||r===122||r===244||r===44||r===83||r===86||r===118||r===128)&&(c=ee(n),c===3&&(p=n.readBits(1)),d=ee(n),m=ee(n),n.skipBits(1),n.readBits(1))){for(let Z=0;Z<(c!==3?8:12);Z++)if(n.readBits(1)){const ce=Z<6?16:64;let re=8,N=8;for(let J=0;JJ.level>=u)??Zt(Wp),N=Math.min(Math.floor(re.maxDpbMbs/(Z*ce)),16);H=N,R=N}}return C(R!==null),{profileIdc:r,constraintFlags:o,levelIdc:u,frameMbsOnlyFlag:x,chromaFormatIdc:c,bitDepthLumaMinus8:d,bitDepthChromaMinus8:m,codedWidth:T,codedHeight:w,displayWidth:S,displayHeight:E,pixelAspectRatio:L,colourPrimaries:_,matrixCoefficients:B,transferCharacteristics:D,fullRangeFlag:z,numReorderFrames:H,maxDecFrameBuffering:R}}catch(n){return ke._error("Error parsing AVC SPS:",n),null}},eg=l=>{const n=ee(l);l.skipBits(4),l.skipBits(4);for(let i=0;i<=n;i++)ee(l),ee(l),l.skipBits(1);l.skipBits(5),l.skipBits(5),l.skipBits(5),l.skipBits(5)},tS=(l,n)=>{if(n.description){const o=(Ng(n.description)[21]&3)+1;return e0(l,o)}else return yo(l)},co=l=>l>>1&63,i0=l=>{try{const n=new Me(ko(l));n.skipBits(16),n.readBits(4);const i=n.readBits(3),r=n.readBits(1),{general_profile_space:o,general_tier_flag:u,general_profile_idc:c,general_profile_compatibility_flags:d,general_constraint_indicator_flags:m,general_level_idc:p}=nS(n,i);ee(n);const y=ee(n);let g=0;y===3&&(g=n.readBits(1));const b=ee(n),T=ee(n);let w=b,S=T;if(n.readBits(1)){const Z=ee(n),ie=ee(n),ce=ee(n),re=ee(n);let N=1,J=1;const ae=g===0?y:0;ae===1?(N=2,J=2):ae===2&&(N=2,J=1),w-=(Z+ie)*N,S-=(ce+re)*J}const E=ee(n),x=ee(n);ee(n);const _=n.readBits(1)?0:i;let D=0;for(let Z=_;Z<=i;Z++)ee(n),D=ee(n),ee(n);ee(n),ee(n),ee(n),ee(n),ee(n),ee(n),n.readBits(1)&&n.readBits(1)&&aS(n),n.skipBits(1),n.skipBits(1),n.readBits(1)&&(n.skipBits(4),n.skipBits(4),ee(n),ee(n),n.skipBits(1));const B=ee(n);if(iS(n,B),n.readBits(1)){const Z=ee(n);for(let ie=0;ie{try{const n=[],i=[],r=[],o=[];for(const p of yo(l)){const y=l.subarray(p.offset,p.offset+p.length),g=co(y[0]);g===St.VPS_NUT?n.push(y):g===St.SPS_NUT?i.push(y):g===St.PPS_NUT?r.push(y):(g===St.PREFIX_SEI_NUT||g===St.SUFFIX_SEI_NUT)&&o.push(y)}if(i.length===0||r.length===0)return null;const u=i0(i[0]);if(!u)return null;let c=0;if(r.length>0){const p=r[0],y=new Me(ko(p));y.skipBits(16),ee(y),ee(y),y.skipBits(1),y.skipBits(1),y.skipBits(3),y.skipBits(1),y.skipBits(1),ee(y),ee(y),Jn(y),y.skipBits(1),y.skipBits(1),y.readBits(1)&&ee(y),Jn(y),Jn(y),y.skipBits(1),y.skipBits(1),y.skipBits(1),y.skipBits(1);const g=y.readBits(1),b=y.readBits(1);!g&&!b?c=0:g&&!b?c=2:!g&&b?c=3:c=0}const d=[...n.length?[{arrayCompleteness:1,nalUnitType:St.VPS_NUT,nalUnits:n}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:St.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:St.PPS_NUT,nalUnits:r}]:[],...o.length?[{arrayCompleteness:1,nalUnitType:co(o[0][0]),nalUnits:o}]:[]];return{configurationVersion:1,generalProfileSpace:u.generalProfileSpace,generalTierFlag:u.generalTierFlag,generalProfileIdc:u.generalProfileIdc,generalProfileCompatibilityFlags:u.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:u.generalConstraintIndicatorFlags,generalLevelIdc:u.generalLevelIdc,minSpatialSegmentationIdc:u.minSpatialSegmentationIdc,parallelismType:c,chromaFormatIdc:u.chromaFormatIdc,bitDepthLumaMinus8:u.bitDepthLumaMinus8,bitDepthChromaMinus8:u.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:u.spsMaxSubLayersMinus1+1,temporalIdNested:u.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:d}}catch(n){return ke._error("Error building HEVC Decoder Configuration Record:",n),null}},nS=(l,n)=>{const i=l.readBits(2),r=l.readBits(1),o=l.readBits(5);let u=0;for(let y=0;y<32;y++)u=u<<1|l.readBits(1);const c=new Uint8Array(6);for(let y=0;y<6;y++)c[y]=l.readBits(8);const d=l.readBits(8),m=[],p=[];for(let y=0;y0)for(let y=n;y<8;y++)l.skipBits(2);for(let y=0;y{for(let n=0;n<4;n++)for(let i=0;i<(n===3?2:6);i++)if(!l.readBits(1))ee(l);else{const o=Math.min(64,1<<4+(n<<1));n>1&&Jn(l);for(let u=0;u{const i=[];for(let r=0;r{let o=0,u=0,c=0;if(n!==0&&(u=l.readBits(1)),u){if(n===i){const m=ee(l);c=n-(m+1)}else c=n-1;l.readBits(1),ee(l);const d=r[c]??0;for(let m=0;m<=d;m++)l.readBits(1)||l.readBits(1);o=r[c]}else{const d=ee(l),m=ee(l);for(let p=0;p{let i=2,r=2,o=2,u=0,c=0,d={num:1,den:1};if(l.readBits(1)){const m=l.readBits(8);if(m===255)d={num:l.readBits(16),den:l.readBits(16)};else{const p=n0[m];p&&(d=p)}}return l.readBits(1)&&l.readBits(1),l.readBits(1)&&(l.readBits(3),u=l.readBits(1),l.readBits(1)&&(i=l.readBits(8),r=l.readBits(8),o=l.readBits(8))),l.readBits(1)&&(ee(l),ee(l)),l.readBits(1),l.readBits(1),l.readBits(1),l.readBits(1)&&(ee(l),ee(l),ee(l),ee(l)),l.readBits(1)&&(l.readBits(32),l.readBits(32),l.readBits(1)&&ee(l),l.readBits(1)&&lS(l,!0,n)),l.readBits(1)&&(l.readBits(1),l.readBits(1),l.readBits(1),c=ee(l),ee(l),ee(l),ee(l),ee(l)),{pixelAspectRatio:d,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:o,fullRangeFlag:u,minSpatialSegmentationIdc:c}},lS=(l,n,i)=>{let r=!1,o=!1,u=!1;r=l.readBits(1)===1,o=l.readBits(1)===1,(r||o)&&(u=l.readBits(1)===1,u&&(l.readBits(8),l.readBits(5),l.readBits(1),l.readBits(5)),l.readBits(4),l.readBits(4),u&&l.readBits(4),l.readBits(5),l.readBits(5),l.readBits(5));for(let c=0;c<=i;c++){const d=l.readBits(1)===1;let m=!0;d||(m=l.readBits(1)===1);let p=!1;m?ee(l):p=l.readBits(1)===1;let y=1;p||(y=ee(l)+1),r&&tg(l,y,u),o&&tg(l,y,u)}},tg=(l,n,i)=>{for(let r=0;r{const n=new Me(l);if(n.readBits(2)!==2)return null;const r=n.readBits(1),u=(n.readBits(1)<<1)+r;if(u===3&&n.skipBits(1),n.readBits(1)===1||n.readBits(1)!==0||(n.skipBits(2),n.readBits(24)!==4817730))return null;let p=8;u>=2&&(p=n.readBits(1)?12:10);const y=n.readBits(3);let g=0,b=0;if(y!==7)if(b=n.readBits(1),u===1||u===3){const L=n.readBits(1),H=n.readBits(1);g=!L&&!H?3:L&&!H?2:1,n.skipBits(1)}else g=1;else g=3,b=1;const T=n.readBits(16),w=n.readBits(16),S=T+1,E=w+1,x=S*E;let P=Zt(ar).level;for(const z of ar)if(x<=z.maxPictureSize){P=z.level;break}return{profile:u,level:P,bitDepth:p,chromaSubsampling:g,videoFullRangeFlag:b,colourPrimaries:y===2?1:y===1?6:2,transferCharacteristics:y===2?1:y===1?6:2,matrixCoefficients:y===7?0:y===2?1:y===1?6:2}},l0=function*(l){const n=new Me(l),i=()=>{let r=0;for(let o=0;o<8;o++){const u=n.readAlignedByte();if(r|=(u&127)<=2**32-1?null:r};for(;n.getBitsLeft()>=8;){n.skipBits(1);const r=n.readBits(4),o=n.readBits(1),u=n.readBits(1);n.skipBits(1),o&&n.skipBits(8);let c;if(u){const d=i();if(d===null)return;c=d}else c=Math.floor(n.getBitsLeft()/8);C(n.pos%8===0),yield{type:r,data:l.subarray(n.pos/8,n.pos/8+c)},n.skipBits(c*8)}},o0=l=>{for(const{type:n,data:i}of l0(l)){if(n!==1)continue;const r=new Me(i),o=r.readBits(3);r.readBits(1);const u=r.readBits(1);let c=0,d=0,m=0;if(u)c=r.readBits(5);else{if(r.readBits(1)&&(r.skipBits(32),r.skipBits(32),r.readBits(1)))return null;const B=r.readBits(1);B&&(m=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5));const z=r.readBits(5);for(let L=0;L<=z;L++){r.skipBits(12);const H=r.readBits(5);if(L===0&&(c=H),H>7){const X=r.readBits(1);L===0&&(d=X)}if(B&&r.readBits(1)){const W=m+1;r.skipBits(W),r.skipBits(W),r.skipBits(1)}r.readBits(1)&&r.skipBits(4)}}const p=r.readBits(4),y=r.readBits(4),g=p+1;r.skipBits(g);const b=y+1;r.skipBits(b);let T=0;if(u?T=0:T=r.readBits(1),T&&(r.skipBits(4),r.skipBits(3)),r.skipBits(1),r.skipBits(1),r.skipBits(1),!u){r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const D=r.readBits(1);D&&(r.skipBits(1),r.skipBits(1));const B=r.readBits(1);let z=0;B?z=2:z=r.readBits(1),z>0&&(r.readBits(1)||r.skipBits(1)),D&&r.skipBits(3)}r.skipBits(1),r.skipBits(1),r.skipBits(1);const w=r.readBits(1);let S=8;o===2&&w?S=r.readBits(1)?12:10:o<=2&&(S=w?10:8);let E=0;o!==1&&(E=r.readBits(1));let x=1,P=1,_=0;return E||(o===0?(x=1,P=1):o===1?(x=0,P=0):S===12&&(x=r.readBits(1),x&&(P=r.readBits(1))),x&&P&&(_=r.readBits(2))),{profile:o,level:c,tier:d,bitDepth:S,monochrome:E,chromaSubsamplingX:x,chromaSubsamplingY:P,chromaSamplePosition:_}}return null},oS=l=>{const n=Re(l),i=n.getUint8(9),r=n.getUint16(10,!0),o=n.getUint32(12,!0),u=n.getInt16(16,!0),c=n.getUint8(18);let d=null;return c&&(d=l.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:o,outputGain:u,channelMappingFamily:c,channelMappingTable:d}},cS=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],uS=l=>{const n=l[0]>>3,i=l[0]&3;let r;return i===0?r=1:i===1||i===2?r=2:r=l[1]&63,{durationInSamples:cS[n]*r}},fS=l=>{if(l.length<7)throw new Error("Setup header is too short.");if(l[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...l.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");const i=l.length,r=new Uint8Array(i);for(let g=0;g97;)if(o.readBits(1)===1){u=o.pos;break}if(u===0)throw new Error("Invalid Setup header: framing bit not found.");let c=0,d=!1,m=0;for(;o.getBitsLeft()>=97;){const g=o.pos,b=o.readBits(8),T=o.readBits(16),w=o.readBits(16);if(b>63||T!==0||w!==0){o.pos=g;break}if(o.skipBits(1),c++,c>64)break;o.clone().readBits(6)+1===c&&(d=!0,m=c)}if(!d)throw new Error("Invalid Setup header: mode header not found.");if(m>63)throw new Error(`Unsupported mode count: ${m}.`);const p=m;o.pos=0,o.skipBits(u);const y=Array(p).fill(0);for(let g=p-1;g>=0;g--)o.skipBits(40),y[g]=o.readBits(1);return{modeBlockflags:y}},c0=(l,n,i)=>{switch(l){case"avc":{for(const r of eS(i,n)){const o=i[r.offset],u=Pf(o);if(u>=vt.NON_IDR_SLICE&&u<=vt.SLICE_DPC)return"delta";if(u===vt.IDR)return"key";if(u===vt.SEI&&(!jb()||Xb()>=144)){const c=i.subarray(r.offset,r.offset+r.length),d=ko(c);let m=1;do{let p=0;for(;;){const b=d[m++];if(b===void 0||(p+=b,b<255))break}let y=0;for(;;){const b=d[m++];if(b===void 0||(y+=b,b<255))break}if(p===6){const b=new Me(d);b.pos=8*m;const T=ee(b),w=b.readBits(1);if(T===0&&w===1)return"key"}m+=y}while(m{const i=Re(l);let r=0;const o=i.getUint32(r,!0);r+=4;const u=Mt.decode(l.subarray(r,r+o));r+=o,o>0&&(n.raw??={},n.raw.vendor??=u);const c=i.getUint32(r,!0);r+=4;for(let d=0;d0&&(n.trackNumber??=w),S&&Number.isInteger(S)&&S>0&&(n.tracksTotal??=S)}break;case"TRACKTOTAL":{const T=Number.parseInt(b,10);Number.isInteger(T)&&T>0&&(n.tracksTotal??=T)}break;case"DISCNUMBER":{const T=b.split("/"),w=Number.parseInt(T[0],10),S=T[1]&&Number.parseInt(T[1],10);Number.isInteger(w)&&w>0&&(n.discNumber??=w),S&&Number.isInteger(S)&&S>0&&(n.discsTotal??=S)}break;case"DISCTOTAL":{const T=Number.parseInt(b,10);Number.isInteger(T)&&T>0&&(n.discsTotal??=T)}break;case"DATE":{const T=new Date(b);Number.isNaN(T.getTime())||(n.date??=T)}break;case"GENRE":n.genre??=b;break;case"METADATA_BLOCK_PICTURE":{const T=Xg(b),w=Re(T),S=w.getUint32(0,!1),E=w.getUint32(4,!1),x=String.fromCharCode(...T.subarray(8,8+E)),P=w.getUint32(8+E,!1),_=Mt.decode(T.subarray(12+E,12+E+P)),D=w.getUint32(E+P+28),B=T.subarray(E+P+32,E+P+32+D);n.images??=[],n.images.push({data:B,mimeType:x,kind:S===3?"coverFront":S===4?"coverBack":"unknown",name:void 0,description:_||void 0})}break}}},Bf=[2,1,2,3,3,4,4,5],dS=l=>{if(l.length<7||l[0]!==11||l[1]!==119)return null;const n=new Me(l);n.skipBits(16),n.skipBits(16);const i=n.readBits(2);if(i===3)return null;const r=n.readBits(6),o=n.readBits(5);if(o>8)return null;const u=n.readBits(3),c=n.readBits(3);(c&1)!==0&&c!==1&&n.skipBits(2),(c&4)!==0&&n.skipBits(2),c===2&&n.skipBits(2);const d=n.readBits(1),m=Math.floor(r/2);return{fscod:i,bsid:o,bsmod:u,acmod:c,lfeon:d,bitRateCode:m}},hS=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],mS=1536,u0=[1,2,3,6],pS=l=>{if(l.length<6||l[0]!==11||l[1]!==119)return null;const n=new Me(l);n.skipBits(16);const i=n.readBits(2);if(n.skipBits(3),i!==0&&i!==2)return null;const r=n.readBits(11),o=n.readBits(2);let u=0,c;o===3?(u=n.readBits(2),c=3):c=n.readBits(2);const d=n.readBits(3),m=n.readBits(1),p=n.readBits(5);if(p<11||p>16)return null;const y=u0[c];let g;return o<3?g=go[o]/1e3:g=$g[u]/1e3,{dataRate:Math.round((r+1)*g/(y*16)),substreams:[{fscod:o,fscod2:u,bsid:p,bsmod:0,acmod:d,lfeon:m,numDepSub:0,chanLoc:0}]}},gS=l=>{if(l.length<2)return null;const n=new Me(l),i=n.readBits(13),r=n.readBits(3),o=[];for(let u=0;u<=r&&!(Math.ceil(n.pos/8)+3>l.length);u++){const c=n.readBits(2),d=n.readBits(5);n.skipBits(1),n.skipBits(1);const m=n.readBits(3),p=n.readBits(3),y=n.readBits(1);n.skipBits(3);const g=n.readBits(4);let b=0;g>0?b=n.readBits(9):n.skipBits(1),o.push({fscod:c,fscod2:null,bsid:d,bsmod:m,acmod:p,lfeon:y,numDepSub:g,chanLoc:b})}return o.length===0?null:{dataRate:i,substreams:o}},f0=l=>{const n=l.substreams[0];return C(n),n.fscod<3?go[n.fscod]:n.fscod2!==null&&n.fscod2<3?$g[n.fscod2]:null},d0=l=>{const n=l.substreams[0];C(n);let i=Bf[n.acmod]+n.lfeon;if(n.numDepSub>0){const r=[2,2,1,1,2,2,2,1,1];for(let o=0;o<9;o++)n.chanLoc&1<<8-o&&(i+=r[o])}return i};class ta{constructor(n){this.input=n}dispose(){}}const Wt=new Uint8Array(0);class dt{constructor(n,i,r,o,u=-1,c,d){if(this.data=n,this.type=i,this.timestamp=r,this.duration=o,this.sequenceNumber=u,n===Wt&&c===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(c===void 0&&(c=n.byteLength),!(n instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(i!=="key"&&i!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(o)||o<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(u))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(c)||c<0)throw new TypeError("byteLength must be a non-negative integer.");if(d!==void 0&&(typeof d!="object"||!d))throw new TypeError("sideData, when provided, must be an object.");if(d?.alpha!==void 0&&!(d.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(d?.alphaByteLength!==void 0&&(!Number.isInteger(d.alphaByteLength)||d.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=c,this.sideData=d??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Wt}get microsecondTimestamp(){return Math.trunc(lo*this.timestamp)}get microsecondDuration(){return Math.trunc(lo*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(n=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:n,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(n,i){if(!(n instanceof EncodedVideoChunk||n instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(n.byteLength);return n.copyTo(r),new dt(r,n.type,n.timestamp/1e6,(n.duration??0)/1e6,void 0,void 0,i)}clone(n){if(n!==void 0&&(typeof n!="object"||n===null))throw new TypeError("options, when provided, must be an object.");if(n?.data!==void 0&&!(n.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(n?.type!==void 0&&n.type!=="key"&&n.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(n?.timestamp!==void 0&&!Number.isFinite(n.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(n?.duration!==void 0&&!Number.isFinite(n.duration))throw new TypeError("options.duration, when provided, must be a number.");if(n?.sequenceNumber!==void 0&&!Number.isFinite(n.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(n?.sideData!==void 0&&(typeof n.sideData!="object"||n.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new dt(n?.data??this.data,n?.type??this.type,n?.timestamp??this.timestamp,n?.duration??this.duration,n?.sequenceNumber??this.sequenceNumber,this.byteLength,n?.sideData??this.sideData)}}const yS=l=>{let i=(l.hasVideo?"video/":l.hasAudio?"audio/":"application/")+(l.isQuickTime?"quicktime":"mp4");if(l.codecStrings.length>0){const r=[...new Set(l.codecStrings)];i+=`; codecs="${r.join(", ")}"`}return i},h0=l=>{const n=Re(l);let i=0;const r=n.getUint8(i);i+=1,i+=3;const o=ws(l.subarray(i,i+16));i+=16;let u=null;if(r>0){const d=n.getUint32(i);if(i+=4,d>0){u=[];for(let m=0;ml.systemId===n.systemId&&Gb(l.data,n.data);const Wi=8,gs=16,Aa=l=>{let n=$(l);const i=Je(l,4);let r=8;n===1&&(n=un(l),r=16);const u=n-r;return u<0?null:{name:i,totalSize:n,headerSize:r,contentSize:u}},Wa=l=>ai(l)/65536,Ku=l=>ai(l)/1073741824,Yu=l=>{let n=0;for(let i=0;i<4;i++){n<<=7;const r=oe(l);if(n|=r&127,(r&128)===0)break}return n},vn=l=>{let n=it(l);return l.skip(2),n=Math.min(n,l.remainingLength),Mt.decode(fe(l,n))},kS=l=>{const n=Aa(l);if(!n||n.name!=="data"||l.remainingLength<8)return null;const i=$(l);l.skip(4);const r=fe(l,n.contentSize-8);switch(i){case 1:return Mt.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new eo(r,"image/jpeg");case 14:return new eo(r,"image/png");case 27:return new eo(r,"image/bmp");default:return r}};const xn=16,Gn=new Uint32Array(256),Ji=new Uint32Array(256),$i=new Uint32Array(256),er=new Uint32Array(256),tr=new Uint32Array(256),bt=new Uint32Array(256),p0=new Uint32Array(10);let g0=!1;const bS=()=>{const l=new Uint8Array(256),n=new Uint8Array(256),i=new Uint8Array(256);for(let u=0,c=1;u<256;u++)i[u]=c,n[c]=u,c=c^c<<1^(c&128?283:0);const r=(u,c)=>u&&c?i[(n[u]+n[c])%255]:0;l[0]=99;for(let u=1;u<256;u++){const c=i[255-n[u]];let d=c^c<<1^c<<2^c<<3^c<<4;d=d>>>8^d&255^99,l[u]=d}for(let u=0;u<256;u++){const c=l[u],d=l.indexOf(u);Gn[u]=c<<24|c<<16|c<<8|c,bt[u]=d<<24|d<<16|d<<8|d;const m=r(d,14),p=r(d,9),y=r(d,13),g=r(d,11),b=m<<24|p<<16|y<<8|g;Ji[u]=b,$i[u]=b>>>8|b<<24,er[u]=b>>>16|b<<16,tr[u]=b>>>24|b<<8}let o=1;for(let u=0;u<10;u++)p0[u]=o<<24,o=o<<1^(o&128?283:0);g0=!0};class y0{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(xn/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(xn),this.out=new Uint8Array(xn),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:n,iv:i}){C(n.byteLength===16),C(i.byteLength===16),g0||bS();const r=new DataView(n.buffer,n.byteOffset,n.byteLength),o=new DataView(i.buffer,i.byteOffset,i.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=o.getUint32(0,!1),this.iv[1]=o.getUint32(4,!1),this.iv[2]=o.getUint32(8,!1),this.iv[3]=o.getUint32(12,!1);for(let u=4;u<44;u+=4){const c=this.roundkey[u-1];this.roundkey[u]=this.roundkey[u-4]^Gn[c>>>16&255]&4278190080^Gn[c>>>8&255]&16711680^Gn[c>>>0&255]&65280^Gn[c>>>24&255]&255^p0[u/4-1],this.roundkey[u+1]=this.roundkey[u-3]^this.roundkey[u],this.roundkey[u+2]=this.roundkey[u-2]^this.roundkey[u+1],this.roundkey[u+3]=this.roundkey[u-1]^this.roundkey[u+2]}for(let u=0,c=40;u>>24&255]&255]^$i[Gn[d>>>16&255]&255]^er[Gn[d>>>8&255]&255]^tr[Gn[d>>>0&255]&255]}}decrypt(){let n=this.inView.getUint32(0,!1)^this.roundkey[0],i=this.inView.getUint32(4,!1)^this.roundkey[1],r=this.inView.getUint32(8,!1)^this.roundkey[2],o=this.inView.getUint32(12,!1)^this.roundkey[3];const u=this.inView.getUint32(0,!1),c=this.inView.getUint32(4,!1),d=this.inView.getUint32(8,!1),m=this.inView.getUint32(12,!1);let p,y,g,b;for(let x=1;x<10;x++){const P=x*4;p=Ji[n>>>24]^$i[o>>>16&255]^er[r>>>8&255]^tr[i&255]^this.roundkey[P],y=Ji[i>>>24]^$i[n>>>16&255]^er[o>>>8&255]^tr[r&255]^this.roundkey[P+1],g=Ji[r>>>24]^$i[i>>>16&255]^er[n>>>8&255]^tr[o&255]^this.roundkey[P+2],b=Ji[o>>>24]^$i[r>>>16&255]^er[i>>>8&255]^tr[n&255]^this.roundkey[P+3],n=p,i=y,r=g,o=b}const T=bt[n>>>24&255]&4278190080^bt[o>>>16&255]&16711680^bt[r>>>8&255]&65280^bt[i>>>0&255]&255^this.roundkey[40],w=bt[i>>>24&255]&4278190080^bt[n>>>16&255]&16711680^bt[o>>>8&255]&65280^bt[r>>>0&255]&255^this.roundkey[41],S=bt[r>>>24&255]&4278190080^bt[i>>>16&255]&16711680^bt[n>>>8&255]&65280^bt[o>>>0&255]&255^this.roundkey[42],E=bt[o>>>24&255]&4278190080^bt[r>>>16&255]&16711680^bt[i>>>8&255]&65280^bt[n>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,T^this.iv[0],!1),this.outView.setUint32(4,w^this.iv[1],!1),this.outView.setUint32(8,S^this.iv[2],!1),this.outView.setUint32(12,E^this.iv[3],!1),this.iv[0]=u,this.iv[1]=c,this.iv[2]=d,this.iv[3]=m}}const SS=(l,n,i)=>{let r=!1,o=0;const u=2**16,c=16,d=new y0;return new ReadableStream({pull:async m=>{r||(d.init(await n()),r=!0);const p=u+c;let y=l.requestSliceRange(o,0,p);if(y instanceof Promise&&(y=await y),!y||y.length===0)throw new Error("Invalid ciphertext.");const g=y.length;if(g%16!==0)throw new Error("Invalid ciphertext.");const b=g===p?g-c:g,T=fe(y,b),w=new Uint8Array(b);for(let S=0;S16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const E=w.subarray(0,b-S);m.enqueue(E),m.close(),i()}},cancel:()=>{i()}})};class Df extends ta{constructor(n){super(n),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=n._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(n=>n.trackBacking)}async getMimeType(){await this.readMetadata();const n=await this.getTrackBackings(),i=await Promise.all(n.map(r=>r.getDecoderConfig().then(o=>o?.codec??null)));return yS({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>r.info?.type==="video"),hasAudio:this.tracks.some(r=>r.info?.type==="audio"),codecStrings:i.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let n=0,i=!1;for(;;){let r=this.reader.requestSliceRange(n,Wi,gs);if(r instanceof Promise&&(r=await r),!r)break;const o=n,u=Aa(r);if(!u)break;if(u.name==="ftyp"||u.name==="styp"){const c=Je(r,4);this.isQuickTime=c==="qt "}else if(u.name==="moov"){let c=this.reader.requestSlice(r.filePos,u.contentSize);if(c instanceof Promise&&(c=await c),!c)break;this.moovSlice=c,this.readContiguousBoxes(this.moovSlice);for(const d of this.tracks){const m=d.editListPreviousSegmentDurations/this.movieTimescale;d.editListOffset-=Math.round(m*d.timescale)}i=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>o+u.totalSize;break}else if(u.name==="moof"){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');const c=await this.input._initInput._getDemuxer();if(c.constructor!==Df)throw new Error("Init input must match the input's format.");await c.readMetadata(),this.movieTimescale=c.movieTimescale,this.movieDurationInTimescale=c.movieDurationInTimescale,this.metadataTags=c.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=c.fragmentTrackDefaults,this.psshBoxes=c.psshBoxes;for(const d of c.tracks){const m={id:d.id,demuxer:this,trackBacking:null,disposition:d.disposition,timescale:d.timescale,durationInMediaTimescale:d.durationInMediaTimescale,durationInMovieTimescale:d.durationInMovieTimescale,rotation:d.rotation,internalCodecId:d.internalCodecId,name:d.name,languageCode:d.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:d.editListPreviousSegmentDurations,editListOffset:d.editListOffset,encryptionInfo:d.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:d.info};if(d.trackBacking){if(C(m.info),m.info.type==="video"&&m.info.width!==-1){const p=m;m.trackBacking=new ag(p),this.tracks.push(m)}else if(m.info.type==="audio"&&m.info.numberOfChannels!==-1){const p=m;m.trackBacking=new ig(p),this.tracks.push(m)}}}i=!1;break}n=o+u.totalSize}if(i){C(this.reader.fileSize!==null);let r=this.reader.requestSlice(this.reader.fileSize-4,4);r instanceof Promise&&(r=await r),C(r);const o=$(r),u=this.reader.fileSize-o;if(u>=0&&u<=this.reader.fileSize-gs){let c=this.reader.requestSliceRange(u,Wi,gs);if(c instanceof Promise&&(c=await c),c){const d=Aa(c);if(d&&d.name==="mfra"){let m=this.reader.requestSlice(c.filePos,d.contentSize);m instanceof Promise&&(m=await m),m&&this.readContiguousBoxes(m)}}}}})()}getSampleTableForTrack(n){if(n.sampleTable)return n.sampleTable;const i={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(n.sampleTable=i,n.sampleTableByteOffset===null)return i;C(this.moovSlice);const r=this.moovSlice.slice(n.sampleTableByteOffset);if(this.currentTrack=n,this.traverseBox(r),this.currentTrack=null,n.info?.type==="audio"&&n.info.codec&&hr.includes(n.info.codec)&&i.sampleCompositionTimeOffsets.length===0){C(n.info?.type==="audio");const u=Qg(n.info.codec),c=[],d=[];for(let m=0;mH.startIndex),E=i.sampleTimingEntries[S],x=Oe(i.sampleTimingEntries,w,H=>H.startIndex),P=i.sampleTimingEntries[x],_=E.startDecodeTimestamp+(T-E.startIndex)*E.delta,B=P.startDecodeTimestamp+(w-P.startIndex)*P.delta-_,z=Zt(c);z&&z.delta===B?z.count++:c.push({startIndex:p.startChunkIndex+b,startDecodeTimestamp:_,count:1,delta:B});const L=p.samplesPerChunk*u.sampleSize*n.info.numberOfChannels;d.push(L)}p.startSampleIndex=p.startChunkIndex,p.samplesPerChunk=1}i.sampleTimingEntries=c,i.sampleSizes=d}if(i.sampleCompositionTimeOffsets.length>0){i.presentationTimestamps=[];for(const u of i.sampleTimingEntries)for(let c=0;cu.presentationTimestamp-c.presentationTimestamp),i.presentationTimestampIndexMap=Array(i.presentationTimestamps.length).fill(-1);for(let u=0;ug.moofOffset===u.moofOffset);if(y)Qu(c,y.timestamp);else{const g=Oe(m,u.moofOffset-1,b=>b.moofOffset);if(g!==-1){const b=m[g];Qu(c,b.endTimestamp)}}c.startTimestampIsFinal=!0}const p=Oe(m,c.startTimestamp,y=>y.startTimestamp);if((p===-1||m[p].moofOffset!==u.moofOffset)&&m.splice(p+1,0,{moofOffset:u.moofOffset,startTimestamp:c.startTimestamp,endTimestamp:c.endTimestamp}),c.encryptionAuxInfo&&d.encryptionInfo){const y=await b0(this.reader,d.encryptionInfo,c.encryptionAuxInfo);for(let g=0;g0){c.languageCode="";for(let p=0;p<3;p++)c.languageCode=String.fromCharCode(96+(m&31))+c.languageCode,m>>=5;Vg(c.languageCode)||(c.languageCode=_t)}}break;case"hdlr":{const c=this.currentTrack;if(!c)break;n.skip(8);const d=Je(n,4);d==="vide"?c.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}:d==="soun"&&(c.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const c=this.currentTrack;if(!c)break;c.sampleTableByteOffset=i,this.readContiguousBoxes(n.slice(o,r.contentSize))}break;case"stsd":{const c=this.currentTrack;if(!c||c.info===null||c.sampleTable)break;const d=oe(n);n.skip(3);const m=$(n);for(let p=0;p0&&(T===1?(n.skip(4),S=8*$(n),n.skip(8)):T===2&&(n.skip(4),E=G0(n),w=$(n),n.skip(4),S=$(n),x=$(n),n.skip(8))),c.info.numberOfChannels=w,c.info.sampleRate=E,c.frmaCodecString=null,this.readContiguousBoxes(n.slice(n.filePos,y+g.totalSize-n.filePos));const P=b==="enca"?c.frmaCodecString:b;if(c.frmaCodecString=null,P!=="mp4a")if(P==="opus")c.info.codec="opus",c.info.sampleRate=po;else if(P==="flac")c.info.codec="flac";else if(P==="ulaw")c.info.codec="ulaw";else if(P==="alaw")c.info.codec="alaw";else if(P==="ac-3")c.info.codec="ac3";else if(P==="ec-3")c.info.codec="eac3";else if(P==="twos")S===8?c.info.codec="pcm-s8":S===16?c.info.codec=c.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(ke._warn(`Unsupported sample size ${S} for codec 'twos'.`),c.info.codec=null);else if(P==="sowt")S===8?c.info.codec="pcm-s8":S===16?c.info.codec="pcm-s16":(ke._warn(`Unsupported sample size ${S} for codec 'sowt'.`),c.info.codec=null);else if(P==="raw ")c.info.codec="pcm-u8";else if(P==="in24")c.info.codec=c.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(P==="in32")c.info.codec=c.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(P==="fl32")c.info.codec=c.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(P==="fl64")c.info.codec=c.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(P==="ipcm"){const _=c.info.pcmSampleSize;c.info.pcmLittleEndian?_===16?c.info.codec="pcm-s16":_===24?c.info.codec="pcm-s24":_===32?c.info.codec="pcm-s32":(ke._warn(`Invalid ipcm sample size ${_}.`),c.info.codec=null):_===16?c.info.codec="pcm-s16be":_===24?c.info.codec="pcm-s24be":_===32?c.info.codec="pcm-s32be":(ke._warn(`Invalid ipcm sample size ${_}.`),c.info.codec=null)}else if(P==="fpcm"){const _=c.info.pcmSampleSize;c.info.pcmLittleEndian?_===32?c.info.codec="pcm-f32":_===64?c.info.codec="pcm-f64":(ke._warn(`Invalid fpcm sample size ${_}.`),c.info.codec=null):_===32?c.info.codec="pcm-f32be":_===64?c.info.codec="pcm-f64be":(ke._warn(`Invalid fpcm sample size ${_}.`),c.info.codec=null)}else if(P==="lpcm"&&x!==null){const _=S+7>>3,D=!!(x&1),B=!!(x&2),z=x&4?-1:0;S>0&&S<=64&&(D?S===32&&(c.info.codec=B?"pcm-f32be":"pcm-f32"):z&1<<_-1?_===1?c.info.codec="pcm-s8":_===2?c.info.codec=B?"pcm-s16be":"pcm-s16":_===3?c.info.codec=B?"pcm-s24be":"pcm-s24":_===4&&(c.info.codec=B?"pcm-s32be":"pcm-s32"):_===1&&(c.info.codec="pcm-u8")),c.info.codec===null&&ke._warn("Unsupported PCM format.")}else P===null?ke._warn("Unknown encrypted audio codec due to missing frma box."):ke._warn(`Unsupported audio codec (sample entry type '${g.name}').`)}n.filePos=y+g.totalSize}}break;case"frma":{const c=this.currentTrack;if(!c)break;const m=Je(n,4).toLowerCase();c.frmaCodecString=m}break;case"schm":{const c=this.currentTrack;if(!c)break;n.skip(4);const d=Je(n,4);d==="cenc"||d==="cens"||d==="cbcs"?c.encryptionInfo={scheme:d,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:ke._warn(`Unsupported encryption scheme '${d}'.`)}break;case"tenc":{const c=this.currentTrack;if(!c||!c.encryptionInfo)break;const d=oe(n);n.skip(3),n.skip(1);const m=oe(n);if(d>0?(c.encryptionInfo.defaultCryptByteBlock=m>>4,c.encryptionInfo.defaultSkipByteBlock=m&15):(c.encryptionInfo.defaultCryptByteBlock=0,c.encryptionInfo.defaultSkipByteBlock=0),c.encryptionInfo.defaultIsProtected=oe(n)!==0,c.encryptionInfo.defaultPerSampleIvSize=oe(n),c.encryptionInfo.defaultKid=ws(fe(n,16)),c.encryptionInfo.defaultIsProtected&&c.encryptionInfo.defaultPerSampleIvSize===0){const p=oe(n),y=new Uint8Array(16);y.set(fe(n,p),0),c.encryptionInfo.defaultConstantIv=y}}break;case"avcC":{const c=this.currentTrack;if(!c)break;C(c.info),c.info.codecDescription=fe(n,r.contentSize)}break;case"hvcC":{const c=this.currentTrack;if(!c)break;C(c.info),c.info.codecDescription=fe(n,r.contentSize)}break;case"vpcC":{const c=this.currentTrack;if(!c)break;C(c.info?.type==="video"),n.skip(4);const d=oe(n),m=oe(n),p=oe(n),y=p>>4,g=p>>1&7,b=p&1,T=oe(n),w=oe(n),S=oe(n);c.info.vp9CodecInfo={profile:d,level:m,bitDepth:y,chromaSubsampling:g,videoFullRangeFlag:b,colourPrimaries:T,transferCharacteristics:w,matrixCoefficients:S}}break;case"av1C":{const c=this.currentTrack;if(!c)break;C(c.info?.type==="video"),n.skip(1);const d=oe(n),m=d>>5,p=d&31,y=oe(n),g=y>>7,b=y>>6&1,T=y>>5&1,w=y>>4&1,S=y>>3&1,E=y>>2&1,x=y&3,P=m===2&&b?T?12:10:b?10:8;c.info.av1CodecInfo={profile:m,level:p,tier:g,bitDepth:P,monochrome:w,chromaSubsamplingX:S,chromaSubsamplingY:E,chromaSamplePosition:x}}break;case"colr":{const c=this.currentTrack;if(!c)break;C(c.info?.type==="video");const d=Je(n,4);if(d!=="nclx"&&d!=="nclc")break;const m=it(n),p=it(n),y=it(n);let g;d==="nclx"&&(g=!!(oe(n)&128)),c.info.colorSpace={primaries:io[m],transfer:ro[p],matrix:so[y],fullRange:g}}break;case"pasp":{const c=this.currentTrack;if(!c)break;C(c.info?.type==="video");const d=$(n),m=$(n);d>0&&m>0&&(d>m?c.info.squarePixelWidth=Math.round(c.info.width*d/m):c.info.squarePixelHeight=Math.round(c.info.height*m/d))}break;case"wave":this.readContiguousBoxes(n.slice(o,r.contentSize));break;case"esds":{const c=this.currentTrack;if(!c)break;C(c.info?.type==="audio"),n.skip(4);const d=oe(n);C(d===3),Yu(n),n.skip(2);const m=oe(n),p=(m&128)!==0,y=(m&64)!==0,g=(m&32)!==0;if(p&&n.skip(2),y){const E=oe(n);n.skip(E)}g&&n.skip(2);const b=oe(n);C(b===4);const T=Yu(n),w=n.filePos,S=oe(n);if(S===64||S===103?(c.info.codec="aac",c.info.aacCodecInfo={isMpeg2:S===103,objectType:null}):S===105||S===107?c.info.codec="mp3":S===221?c.info.codec="vorbis":ke._warn(`Unsupported audio codec (objectTypeIndication ${S}) - discarding track.`),n.skip(12),T>n.filePos-w){const E=oe(n);C(E===5);const x=Yu(n);if(c.info.codecDescription=fe(n,x),c.info.codec==="aac"){const P=Kg(c.info.codecDescription);P.numberOfChannels!==null&&(c.info.numberOfChannels=P.numberOfChannels),P.sampleRate!==null&&(c.info.sampleRate=P.sampleRate)}}}break;case"enda":{const c=this.currentTrack;if(!c)break;C(c.info?.type==="audio"),c.info.pcmLittleEndian=!!(it(n)&255)}break;case"pcmC":{const c=this.currentTrack;if(!c)break;C(c.info?.type==="audio"),n.skip(4);const d=oe(n);c.info.pcmLittleEndian=!!(d&1),c.info.pcmSampleSize=oe(n)}break;case"dOps":{const c=this.currentTrack;if(!c)break;C(c.info?.type==="audio"),n.skip(1);const d=oe(n),m=it(n),p=$(n),y=gf(n),g=oe(n);let b;g!==0?b=fe(n,2+d):b=new Uint8Array(0);const T=new Uint8Array(19+b.byteLength),w=new DataView(T.buffer);w.setUint32(0,1332770163,!1),w.setUint32(4,1214603620,!1),w.setUint8(8,1),w.setUint8(9,d),w.setUint16(10,m,!0),w.setUint32(12,p,!0),w.setInt16(16,y,!0),w.setUint8(18,g),T.set(b,19),c.info.codecDescription=T,c.info.numberOfChannels=d}break;case"dfLa":{const c=this.currentTrack;if(!c)break;C(c.info?.type==="audio"),n.skip(4);const d=127,m=128,p=n.filePos;for(;n.filePos>>12,_=(x>>9&7)+1;c.info.sampleRate=P,c.info.numberOfChannels=_,n.skip(20)}else n.skip(S);if(w&m)break}const y=n.filePos;n.filePos=p;const g=fe(n,y-p),b=new Uint8Array(4+g.byteLength);new DataView(b.buffer).setUint32(0,1716281667,!1),b.set(g,4),c.info.codecDescription=b}break;case"dac3":{const c=this.currentTrack;if(!c)break;C(c.info?.type==="audio");const d=fe(n,3),m=new Me(d),p=m.readBits(2);m.skipBits(8);const y=m.readBits(3),g=m.readBits(1);p<3&&(c.info.sampleRate=go[p]),c.info.numberOfChannels=Bf[y]+g}break;case"dec3":{const c=this.currentTrack;if(!c)break;C(c.info?.type==="audio");const d=fe(n,r.contentSize),m=gS(d);if(!m){ke._warn("Invalid dec3 box contents, ignoring.");break}const p=f0(m);p!==null&&(c.info.sampleRate=p),c.info.numberOfChannels=d0(m)}break;case"stts":{const c=this.currentTrack;if(!c||!c.sampleTable)break;n.skip(4);const d=$(n);let m=0,p=0;for(let y=0;yP.id===d);if(!m)break;const p=$(n),y=(p&48)>>4,g=(p&12)>>2,b=p&3,T=[oe,it,Kn,$],w=T[y],S=T[g],E=T[b],x=$(n);for(let P=0;PP.timestamp-_.timestamp);for(let P=0;P({presentationTimestamp:y.presentationTimestamp,sampleIndex:g})).sort((y,g)=>y.presentationTimestamp-g.presentationTimestamp);for(let y=0;yx.id===w);if(!S)break;const E=this.fragmentTrackDefaults.find(x=>x.trackId===w);this.currentTrack=S,S.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:E?.defaultSampleDescriptionIndex??null,defaultSampleDuration:E?.defaultSampleDuration??null,defaultSampleSize:E?.defaultSampleSize??null,defaultSampleFlags:E?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},d?S.currentFragmentState.baseDataOffset=un(n):T&&(S.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),m&&(S.currentFragmentState.sampleDescriptionIndex=$(n)),p&&(S.currentFragmentState.defaultSampleDuration=$(n)),y&&(S.currentFragmentState.defaultSampleSize=$(n)),g&&(S.currentFragmentState.defaultSampleFlags=$(n)),b&&(S.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const c=this.currentTrack;if(!c)break;C(c.currentFragmentState);const d=oe(n);n.skip(3);const m=d===0?$(n):un(n);c.currentFragmentState.startTimestamp=m}break;case"trun":{const c=this.currentTrack;if(!c)break;C(this.currentFragment),C(c.currentFragmentState);const d=oe(n),m=Kn(n),p=!!(m&1),y=!!(m&4),g=!!(m&256),b=!!(m&512),T=!!(m&1024),w=!!(m&2048),S=$(n);let E=null;p&&(E=ai(n));let x=null;y&&(x=$(n));let P;this.currentFragment.trackData.has(c.id)?(P=this.currentFragment.trackData.get(c.id),E!==null&&(P.currentOffset=c.currentFragmentState.baseDataOffset+E)):(P={track:c,currentTimestamp:0,currentOffset:c.currentFragmentState.baseDataOffset+(E??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(c.id,P));for(let _=0;_0&&(y=fe(n,p));const g=sg(c);g.defaultSampleInfoSize=m,g.sampleSizes=y,g.sampleCount=p}break;case"saio":{const c=this.currentTrack;if(!c||!c.encryptionInfo)break;const d=oe(n);if(Kn(n)&1){const b=Je(n,4),T=$(n);if(b!==c.encryptionInfo.scheme||T!==0)break}const p=$(n);if(p===0)break;p>1&&ke._warn("Multiple saio entries are not supported; using the first offset only.");let y=d===0?$(n):Number(un(n));this.currentFragment&&(y+=this.currentFragment.moofOffset);const g=sg(c);g.offset=y}break;case"senc":{const c=this.currentTrack;if(!c||!c.encryptionInfo)break;C(this.currentFragment);const d=this.currentFragment.trackData.get(c.id);if(!d)break;n.skip(1);const p=!!(Kn(n)&2),y=$(n),g=c.encryptionInfo.defaultPerSampleIvSize;C(g!==null);for(let b=0;b0?T.set(fe(n,g),0):T.set(c.encryptionInfo.defaultConstantIv,0);let w=null;if(p){const E=it(n);w=[];for(let x=0;x0&&(this.metadataTags.trackNumber??=T),w&&Number.isInteger(w)&&w>0&&(this.metadataTags.tracksTotal??=w)}break;case"trkn":if(g instanceof Uint8Array&&g.length>=6){const b=Re(g),T=b.getUint16(2,!1),w=b.getUint16(4,!1);T>0&&(this.metadataTags.trackNumber??=T),w>0&&(this.metadataTags.tracksTotal??=w)}break;case"disc":case"disk":if(g instanceof Uint8Array&&g.length>=6){const b=Re(g),T=b.getUint16(2,!1),w=b.getUint16(4,!1);T>0&&(this.metadataTags.discNumber??=T),w>0&&(this.metadataTags.discsTotal??=w)}break}}}break}return n.filePos=u,!0}}class k0{constructor(n){this.internalTrack=n,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const n=this.internalTrack.demuxer,i=this.internalTrack.trackBacking.getType();let r=0;for(const o of n.tracks)if(o.trackBacking.getType()===i&&r++,o===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const n=this.internalTrack;return n.durationInMediaTimescale<=0?null:(C(n.trackBacking),((await n.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+n.durationInMediaTimescale/n.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(n){const i=await this.fetchPacketForSampleIndex(0,n);return i||!this.internalTrack.demuxer.isFragmented?i:this.performFragmentedLookup(null,r=>r.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,n)}mapTimestampIntoTimescale(n){return Cs(n*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(n,i){const r=this.mapTimestampIntoTimescale(n),o=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),u=of(o,r),c=await this.fetchPacketForSampleIndex(u,i);return!rg(o)||!this.internalTrack.demuxer.isFragmented?c:this.performFragmentedLookup(null,d=>{const m=d.trackData.get(this.internalTrack.id);if(!m)return{sampleIndex:-1,correctSampleFound:!1};const p=Oe(m.presentationTimestamps,r,b=>b.presentationTimestamp),y=p!==-1?m.presentationTimestamps[p].sampleIndex:-1,g=p!==-1&&r{if(u===o.fragment){const c=u.trackData.get(this.internalTrack.id);if(o.sampleIndex+1{const m=d.trackData.get(this.internalTrack.id);if(!m)return{sampleIndex:-1,correctSampleFound:!1};const p=Sf(m.presentationTimestamps,b=>m.samples[b.sampleIndex].isKeyFrame&&b.presentationTimestamp<=r),y=p!==-1?m.presentationTimestamps[p].sampleIndex:-1,g=p!==-1&&r{if(u===o.fragment){const d=u.trackData.get(this.internalTrack.id).samples.findIndex((m,p)=>m.isKeyFrame&&p>o.sampleIndex);if(d!==-1)return{sampleIndex:d,correctSampleFound:!0}}else{const c=u.trackData.get(this.internalTrack.id);if(c&&c.firstKeyFrameTimestamp!==null){const d=c.samples.findIndex(m=>m.isKeyFrame);return C(d!==-1),{sampleIndex:d,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,i)}async fetchPacketForSampleIndex(n,i){if(n===-1)return null;const r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=vS(r,n);if(!o)return null;let u;if(i.metadataOnly)u=Wt;else{let p=this.internalTrack.demuxer.reader.requestSlice(o.sampleOffset,o.sampleSize);if(p instanceof Promise&&(p=await p),!p)return null;if(u=fe(p,o.sampleSize),this.internalTrack.encryptionAuxInfo){C(this.internalTrack.encryptionInfo);const y=await b0(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);nE.timestamp),g=y!==-1?this.internalTrack.fragmentLookupTable[y]:null,b=Oe(this.internalTrack.fragmentPositionCache,r,E=>E.startTimestamp),T=b!==-1?this.internalTrack.fragmentPositionCache[b]:null,w=Math.max(g?.moofOffset??0,T?.moofOffset??0)||null;let S;for(n?w===null||n.moofOffset>=w?(S=n.moofOffset+n.moofSize,d=n):S=w:S=w??0;;){if(d){const _=d.trackData.get(this.internalTrack.id);if(_&&_.startTimestamp>o)break}let E=c.reader.requestSliceRange(S,Wi,gs);if(E instanceof Promise&&(E=await E),!E)break;const x=S,P=Aa(E);if(!P)break;if(P.name==="moof"){d=await c.readFragment(x);const{sampleIndex:_,correctSampleFound:D}=i(d);if(D)return this.fetchPacketInFragment(d,_,u);_!==-1&&(m=d,p=_)}S=x+P.totalSize}if(g&&(!m||m.moofOffset{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){const i=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=i&&s0(i.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){const i=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=i&&o0(i.data)}const n={codec:_f(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})():null}}class ig extends k0{constructor(n){super(n),this.decoderConfig=null,this.internalTrack=n}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Ef(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}const of=(l,n)=>{if(l.presentationTimestamps){const i=Oe(l.presentationTimestamps,n,r=>r.presentationTimestamp);return i===-1?-1:l.presentationTimestamps[i].sampleIndex}else{const i=Oe(l.sampleTimingEntries,n,o=>o.startDecodeTimestamp);if(i===-1)return-1;const r=l.sampleTimingEntries[i];return r.startIndex+Math.min(Math.floor((n-r.startDecodeTimestamp)/r.delta),r.count-1)}},TS=(l,n)=>{if(!l.keySampleIndices)return of(l,n);if(l.presentationTimestamps){const i=Oe(l.presentationTimestamps,n,r=>r.presentationTimestamp);if(i===-1)return-1;for(let r=i;r>=0;r--){const o=l.presentationTimestamps[r].sampleIndex;if(Bs(l.keySampleIndices,o,c=>c)!==-1)return o}return-1}else{const i=of(l,n),r=Oe(l.keySampleIndices,i,o=>o);return l.keySampleIndices[r]??-1}},vS=(l,n)=>{const i=Oe(l.sampleTimingEntries,n,x=>x.startIndex),r=l.sampleTimingEntries[i];if(!r||r.startIndex+r.count<=n)return null;let u=r.startDecodeTimestamp+(n-r.startIndex)*r.delta;const c=Oe(l.sampleCompositionTimeOffsets,n,x=>x.startIndex),d=l.sampleCompositionTimeOffsets[c];d&&n-d.startIndexx.startSampleIndex),y=l.sampleToChunk[p];C(y);const g=y.startChunkIndex+Math.floor((n-y.startSampleIndex)/y.samplesPerChunk),b=l.chunkOffsets[g],T=y.startSampleIndex+(g-y.startChunkIndex)*y.samplesPerChunk;let w=0,S=b;if(l.sampleSizes.length===1)S+=m*(n-T),w+=m*y.samplesPerChunk;else for(let x=T;xx)!==-1:!0}},wS=(l,n)=>{if(!l.keySampleIndices)return n+1;const i=Oe(l.keySampleIndices,n,r=>r);return l.keySampleIndices[i+1]??-1},Qu=(l,n)=>{l.startTimestamp+=n,l.endTimestamp+=n;for(const i of l.samples)i.presentationTimestamp+=n;for(const i of l.presentationTimestamps)i.presentationTimestamp+=n},xS=l=>{const[n,i]=l,r=Math.atan2(i,n);return Number.isFinite(r)?r*(180/Math.PI):0},rg=l=>l.sampleSizes.length===0,sg=l=>l.currentFragmentState?l.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:l.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},b0=async(l,n,i)=>{if(i.resolved)return i.resolved;if(i.offset===null||i.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(i.defaultSampleInfoSize>0)r=i.defaultSampleInfoSize*i.sampleCount;else{C(i.sampleSizes);for(let d=0;d0?i.defaultSampleInfoSize:i.sampleSizes[d],p=new Uint8Array(16);u>0?p.set(fe(o,u),0):p.set(n.defaultConstantIv,0);let y=null;if(m>u){const g=it(o);y=[];for(let b=0;b{C(l.encryptionInfo);const o=l.encryptionInfo;C(o.defaultKid!==null);const u=o.defaultKid;let c;const d=l.demuxer.decryptionKeyCache.get(u);if(d)c=await d;else{if(!l.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const m=(async()=>{let p=l.demuxer.psshBoxes;if(r){p=[...p,...r.psshBoxes].filter(g=>g.keyIds===null||g.keyIds.includes(u));for(let g=0;g{const o=new Uint8Array(16);o.set(i.iv,0);const u=await crypto.subtle.importKey("raw",l,{name:"AES-CTR"},!1,["decrypt"]),c=async w=>{const S=await crypto.subtle.decrypt({name:"AES-CTR",counter:o,length:64},u,w);return new Uint8Array(S)};if(!i.subsamples)return c(r);C(n.defaultCryptByteBlock!==null&&n.defaultSkipByteBlock!==null);const d=S0(i.subsamples,n.defaultCryptByteBlock,n.defaultSkipByteBlock);let m=0;for(const w of d)for(const S of w.perSubsample)m+=S.length;const p=new Uint8Array(m);let y=0;for(const w of d)for(const S of w.perSubsample)p.set(r.subarray(S.offset,S.offset+S.length),y),y+=S.length;const g=await c(p),b=new Uint8Array(r);let T=0;for(const w of d)for(const S of w.perSubsample)b.set(g.subarray(T,T+S.length),S.offset),T+=S.length;return b},_S=(l,n,i,r)=>{const o=new y0;o.init({key:l,iv:i.iv});const u=n.defaultCryptByteBlock,c=n.defaultSkipByteBlock;if(C(u!==null&&c!==null),!i.subsamples){const y=new Uint8Array(r),g=Math.floor(r.length/16);for(let b=0;b{const r=[],o=n!==0||i!==0;let u=0;for(const c of l){u+=c.clearLen;const d=[];if(!o)c.protectedLen>0&&d.push({offset:u,length:c.protectedLen}),u+=c.protectedLen;else{let m=c.protectedLen,p=u;for(;m>0&&!(m<16*n);){const y=16*n;d.push({offset:p,length:y}),p+=y,m-=y;const g=Math.min(16*i,m);p+=g,m-=g}u+=c.protectedLen}r.push({perSubsample:d})}return r};var K;(function(l){l[l.EBML=440786851]="EBML",l[l.EBMLVersion=17030]="EBMLVersion",l[l.EBMLReadVersion=17143]="EBMLReadVersion",l[l.EBMLMaxIDLength=17138]="EBMLMaxIDLength",l[l.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",l[l.DocType=17026]="DocType",l[l.DocTypeVersion=17031]="DocTypeVersion",l[l.DocTypeReadVersion=17029]="DocTypeReadVersion",l[l.Void=236]="Void",l[l.Segment=408125543]="Segment",l[l.SeekHead=290298740]="SeekHead",l[l.Seek=19899]="Seek",l[l.SeekID=21419]="SeekID",l[l.SeekPosition=21420]="SeekPosition",l[l.Duration=17545]="Duration",l[l.Info=357149030]="Info",l[l.TimestampScale=2807729]="TimestampScale",l[l.MuxingApp=19840]="MuxingApp",l[l.WritingApp=22337]="WritingApp",l[l.Tracks=374648427]="Tracks",l[l.TrackEntry=174]="TrackEntry",l[l.TrackNumber=215]="TrackNumber",l[l.TrackUID=29637]="TrackUID",l[l.TrackType=131]="TrackType",l[l.FlagEnabled=185]="FlagEnabled",l[l.FlagDefault=136]="FlagDefault",l[l.FlagForced=21930]="FlagForced",l[l.FlagOriginal=21934]="FlagOriginal",l[l.FlagHearingImpaired=21931]="FlagHearingImpaired",l[l.FlagVisualImpaired=21932]="FlagVisualImpaired",l[l.FlagCommentary=21935]="FlagCommentary",l[l.FlagLacing=156]="FlagLacing",l[l.Name=21358]="Name",l[l.Language=2274716]="Language",l[l.LanguageBCP47=2274717]="LanguageBCP47",l[l.CodecID=134]="CodecID",l[l.CodecPrivate=25506]="CodecPrivate",l[l.CodecDelay=22186]="CodecDelay",l[l.SeekPreRoll=22203]="SeekPreRoll",l[l.DefaultDuration=2352003]="DefaultDuration",l[l.Video=224]="Video",l[l.PixelWidth=176]="PixelWidth",l[l.PixelHeight=186]="PixelHeight",l[l.DisplayWidth=21680]="DisplayWidth",l[l.DisplayHeight=21690]="DisplayHeight",l[l.DisplayUnit=21682]="DisplayUnit",l[l.AlphaMode=21440]="AlphaMode",l[l.Audio=225]="Audio",l[l.SamplingFrequency=181]="SamplingFrequency",l[l.Channels=159]="Channels",l[l.BitDepth=25188]="BitDepth",l[l.SimpleBlock=163]="SimpleBlock",l[l.BlockGroup=160]="BlockGroup",l[l.Block=161]="Block",l[l.BlockAdditions=30113]="BlockAdditions",l[l.BlockMore=166]="BlockMore",l[l.BlockAdditional=165]="BlockAdditional",l[l.BlockAddID=238]="BlockAddID",l[l.BlockDuration=155]="BlockDuration",l[l.ReferenceBlock=251]="ReferenceBlock",l[l.Cluster=524531317]="Cluster",l[l.Timestamp=231]="Timestamp",l[l.Cues=475249515]="Cues",l[l.CuePoint=187]="CuePoint",l[l.CueTime=179]="CueTime",l[l.CueTrackPositions=183]="CueTrackPositions",l[l.CueTrack=247]="CueTrack",l[l.CueClusterPosition=241]="CueClusterPosition",l[l.Colour=21936]="Colour",l[l.MatrixCoefficients=21937]="MatrixCoefficients",l[l.TransferCharacteristics=21946]="TransferCharacteristics",l[l.Primaries=21947]="Primaries",l[l.Range=21945]="Range",l[l.Projection=30320]="Projection",l[l.ProjectionType=30321]="ProjectionType",l[l.ProjectionPoseRoll=30325]="ProjectionPoseRoll",l[l.Attachments=423732329]="Attachments",l[l.AttachedFile=24999]="AttachedFile",l[l.FileDescription=18046]="FileDescription",l[l.FileName=18030]="FileName",l[l.FileMediaType=18016]="FileMediaType",l[l.FileData=18012]="FileData",l[l.FileUID=18094]="FileUID",l[l.Chapters=272869232]="Chapters",l[l.Tags=307544935]="Tags",l[l.Tag=29555]="Tag",l[l.Targets=25536]="Targets",l[l.TargetTypeValue=26826]="TargetTypeValue",l[l.TargetType=25546]="TargetType",l[l.TagTrackUID=25541]="TagTrackUID",l[l.TagEditionUID=25545]="TagEditionUID",l[l.TagChapterUID=25540]="TagChapterUID",l[l.TagAttachmentUID=25542]="TagAttachmentUID",l[l.SimpleTag=26568]="SimpleTag",l[l.TagName=17827]="TagName",l[l.TagLanguage=17530]="TagLanguage",l[l.TagString=17543]="TagString",l[l.TagBinary=17541]="TagBinary",l[l.ContentEncodings=28032]="ContentEncodings",l[l.ContentEncoding=25152]="ContentEncoding",l[l.ContentEncodingOrder=20529]="ContentEncodingOrder",l[l.ContentEncodingScope=20530]="ContentEncodingScope",l[l.ContentCompression=20532]="ContentCompression",l[l.ContentCompAlgo=16980]="ContentCompAlgo",l[l.ContentCompSettings=16981]="ContentCompSettings",l[l.ContentEncryption=20533]="ContentEncryption"})(K||(K={}));const ES=[K.EBML,K.Segment],As=[K.SeekHead,K.Info,K.Cluster,K.Tracks,K.Cues,K.Attachments,K.Chapters,K.Tags],to=[...ES,...As],cf=8,fn=2,Zn=2*cf,T0=l=>{if(l.remainingLength<1)return null;const n=oe(l);if(l.skip(-1),n===0)return null;let i=1,r=128;for(;(n&r)===0;)i++,r>>=1;return l.remainingLength{if(l.remainingLength<1)return null;const n=oe(l);if(n===0)return null;let i=1,r=128;for(;(n&r)===0;)i++,r>>=1;if(l.remainingLength{if(n<1||n>8)throw new Error("Bad unsigned int size "+n);let i=0;for(let r=0;r{if(n<1)throw new Error("Bad unsigned int size "+n);let i=0n;for(let r=0;r{const n=T0(l);return n===null||l.remainingLength{if(l.remainingLength<1)return null;if(oe(l)===255)return;l.skip(-1);const i=ys(l);if(i===null)return null;if(i!==72057594037927940)return i},Qn=l=>{C(l.remainingLength>=fn);const n=If(l);if(n===null)return null;const i=v0(l);return i===null?null:{id:n,size:i}},nr=(l,n)=>{const i=fe(l,n);let r=0;for(;r{const i=fe(l,n);let r=0;for(;r{if(n===0)return 0;if(n!==4&&n!==8)throw new Error("Bad float size "+n);return n===4?tT(l):G0(l)},uf=async(l,n,i,r)=>{const o=new Set(i);let u=n;for(;r===null||uu?r:u,found:!1}},w0=async(l,n,i,r)=>{const u=new Set(i);let c=n;for(;c{let i=(l.hasVideo?"video/":l.hasAudio?"audio/":"application/")+(l.isWebM?"webm":"x-matroska");if(l.codecStrings.length>0){const r=[...new Set(l.codecStrings.filter(Boolean))];i+=`; codecs="${r.join(", ")}"`}return i};var Yn;(function(l){l[l.None=0]="None",l[l.Xiph=1]="Xiph",l[l.FixedSize=2]="FixedSize",l[l.Ebml=3]="Ebml"})(Yn||(Yn={}));var uo;(function(l){l[l.Block=1]="Block",l[l.Private=2]="Private",l[l.Next=4]="Next"})(uo||(uo={}));var Ss;(function(l){l[l.Zlib=0]="Zlib",l[l.Bzlib=1]="Bzlib",l[l.lzo1x=2]="lzo1x",l[l.HeaderStripping=3]="HeaderStripping"})(Ss||(Ss={}));const Wu=[{id:K.SeekHead,flag:"seekHeadSeen"},{id:K.Info,flag:"infoSeen"},{id:K.Tracks,flag:"tracksSeen"},{id:K.Cues,flag:"cuesSeen"}],x0=10*2**20;class BS extends ta{constructor(n){super(n),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=n._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(n=>n.tracks.map(i=>i.trackBacking))}async getMimeType(){await this.readMetadata();const n=await this.getTrackBackings(),i=await Promise.all(n.map(r=>r.getDecoderConfig().then(o=>o?.codec??null)));return PS({isWebM:this.isWebM,hasVideo:this.segments.some(r=>r.tracks.some(o=>o.info?.type==="video")),hasAudio:this.segments.some(r=>r.tracks.some(o=>o.info?.type==="audio")),codecStrings:i.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const i of this.segments)i.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(i),i.metadataTagsCollected=!0);let n={};for(const i of this.segments)n={...n,...i.metadataTags};return n}readMetadata(){return this.readMetadataPromise??=(async()=>{let n=0;for(;;){let i=this.reader.requestSliceRange(n,fn,Zn);if(i instanceof Promise&&(i=await i),!i)break;const r=Qn(i);if(!r)break;const o=r.id;let u=r.size;const c=i.filePos;if(o===K.EBML){Ea(u);let d=this.reader.requestSlice(c,u);if(d instanceof Promise&&(d=await d),!d)break;this.readContiguousElements(d)}else if(o===K.Segment){if(await this.readSegment(c,u),u===void 0||this.reader.fileSize===null)break}else if(o===K.Cluster){if(this.reader.fileSize===null)break;u===void 0&&(u=(await uf(this.reader,c,to,this.reader.fileSize)).pos-c);const d=Zt(this.segments);d&&(d.elementEndPos=c+u)}Ea(u),n=c+u}})()}async readSegment(n,i){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:n,elementEndPos:i===void 0?null:n+i,clusterSeekStartPos:n,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=n;for(;this.currentSegment.elementEndPos===null||rw.id===y);if(T!==-1){const w=Wu[T].flag;this.currentSegment[w]=!0,Ea(g);let S=this.reader.requestSlice(b,g);S instanceof Promise&&(S=await S),S&&this.readContiguousElements(S)}else if(y===K.Tags||y===K.Attachments){y===K.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Ea(g);let w=this.reader.requestSlice(b,g);w instanceof Promise&&(w=await w),w&&this.readContiguousElements(w)}else if(y===K.Cluster){this.currentSegment.clusterSeekStartPos=m;break}if(g===void 0)break;r=b+g}if(this.currentSegment.seekEntries.sort((d,m)=>d.segmentPosition-m.segmentPosition),this.reader.fileSize!==null)for(const d of this.currentSegment.seekEntries){const m=Wu.find(w=>w.id===d.id);if(!m||this.currentSegment[m.flag])continue;let p=this.reader.requestSliceRange(n+d.segmentPosition,fn,Zn);if(p instanceof Promise&&(p=await p),!p)continue;const y=Qn(p);if(!y)continue;const{id:g,size:b}=y;if(g!==m.id)continue;Ea(b),this.currentSegment[m.flag]=!0;let T=this.reader.requestSlice(p.filePos,b);T instanceof Promise&&(T=await T),T&&this.readContiguousElements(T)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(const d of this.currentSegment.tracks)d.defaultDurationNs!==null&&(d.defaultDuration=this.currentSegment.timestampFactor*d.defaultDurationNs/1e9);const o=new Map(this.currentSegment.tracks.map(d=>[d.id,d]));for(const d of this.currentSegment.cuePoints){const m=o.get(d.trackId);m&&m.cuePoints.push(d)}for(const d of this.currentSegment.tracks){d.cuePoints.sort((m,p)=>m.time-p.time);for(let m=0;mc&&(c=d.cuePoints.length,u=d);for(const d of this.currentSegment.tracks)d.cuePoints.length===0&&(d.cuePoints=u.cuePoints);this.currentSegment=null}async readCluster(n,i){if(i.lastReadCluster?.elementStartPos===n)return i.lastReadCluster;let r=this.reader.requestSliceRange(n,fn,Zn);r instanceof Promise&&(r=await r),C(r);const o=n,u=Qn(r);C(u);const c=u.id;C(c===K.Cluster);let d=u.size;const m=r.filePos;d===void 0&&(d=(await uf(this.reader,m,to,i.elementEndPos)).pos-m);let p=this.reader.requestSlice(m,d);p instanceof Promise&&(p=await p);const y={segment:i,elementStartPos:o,elementEndPos:m+d,dataStartPos:m,timestamp:-1,trackData:new Map};if(this.currentCluster=y,p){const g=this.readContiguousElements(p,to);y.elementEndPos=g}for(const[,g]of y.trackData){const b=g.track;C(g.blocks.length>0);let T=!1;for(let x=0;x({timestamp:x.timestamp,blockIndex:P})).sort((x,P)=>x.timestamp-P.timestamp);for(let x=0;x({timestamp:x.timestamp,blockIndex:P})).sort((x,P)=>x.timestamp-P.timestamp));const w=g.blocks[g.presentationTimestamps[0].blockIndex],S=g.blocks[Zt(g.presentationTimestamps).blockIndex];g.startTimestamp=w.timestamp,g.endTimestamp=S.timestamp+S.duration;const E=Oe(b.clusterPositionCache,g.startTimestamp,x=>x.startTimestamp);(E===-1||b.clusterPositionCache[E].elementStartPos!==o)&&b.clusterPositionCache.splice(E+1,0,{elementStartPos:y.elementStartPos,startTimestamp:g.startTimestamp})}return i.lastReadCluster=y,y}getTrackDataInCluster(n,i){let r=n.trackData.get(i);if(!r){const o=n.segment.tracks.find(u=>u.id===i);if(!o)return null;r={track:o,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},n.trackData.set(i,r)}return r}expandLacedBlocks(n,i){for(let r=0;r=fn;){const r=n.filePos;if(!this.traverseElement(n,i))return r}return n.filePos}traverseElement(n,i){const r=Qn(n);if(!r||i&&i.includes(r.id))return!1;const{id:o,size:u}=r,c=n.filePos;switch(Ea(u),o){case K.DocType:this.isWebM=nr(n,u)==="webm";break;case K.Seek:{if(!this.currentSegment)break;const d={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(d),this.readContiguousElements(n.slice(c,u)),(d.id===-1||d.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case K.SeekID:{const d=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!d)break;d.id=ve(n,u)}break;case K.SeekPosition:{const d=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!d)break;d.segmentPosition=ve(n,u)}break;case K.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=ve(n,u),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case K.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Zu(n,u)}break;case K.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...ea,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(n.slice(c,u)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(d=>d.data?.type!=="decompress"||d.scope!==uo.Block||d.data.algorithm!==Ss.HeaderStripping)&&(ke._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){const d=this.currentTrack.codecId.indexOf("/"),m=d===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,d);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){const y=this.currentTrack.info.displayWidth*this.currentTrack.info.height,g=this.currentTrack.info.displayHeight*this.currentTrack.info.width;y>0&&g>0&&(y>g?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*y/g):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*g/y))}if(this.currentTrack.codecId===Yt.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Yt.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(m===Yt.vp8)this.currentTrack.info.codec="vp8";else if(m===Yt.vp9)this.currentTrack.info.codec="vp9";else if(m===Yt.av1)this.currentTrack.info.codec="av1";else if(m===Yt.prores){const y=this.currentTrack.codecPrivate?Mt.decode(this.currentTrack.codecPrivate):"";Cf.includes(y)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=y)}const p=this.currentTrack;this.currentTrack.trackBacking=new DS(p),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){m===Yt.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Yt.mp3?this.currentTrack.info.codec="mp3":m===Yt.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=po):m===Yt.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):m===Yt.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):m===Yt.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):m===Yt.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));const p=this.currentTrack;this.currentTrack.trackBacking=new IS(p),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case K.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=ve(n,u)}break;case K.TrackType:{if(!this.currentTrack)break;const d=ve(n,u);d===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1,proresFormat:null}:d===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case K.FlagEnabled:{if(!this.currentTrack)break;ve(n,u)||(this.currentTrack=null)}break;case K.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!ve(n,u)}break;case K.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!ve(n,u)}break;case K.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!ve(n,u)}break;case K.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!ve(n,u)}break;case K.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!ve(n,u)}break;case K.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!ve(n,u)}break;case K.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=nr(n,u)}break;case K.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=fe(n,u)}break;case K.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=ve(n,u)}break;case K.Name:{if(!this.currentTrack)break;this.currentTrack.name=os(n,u)}break;case K.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=nr(n,u),Vg(this.currentTrack.languageCode)||(this.currentTrack.languageCode=_t)}break;case K.LanguageBCP47:{if(!this.currentTrack)break;const m=nr(n,u).split("-")[0];m?this.currentTrack.languageCode=m:this.currentTrack.languageCode=_t,this.currentTrack.hasLanguageBcp47=!0}break;case K.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(n.slice(c,u))}break;case K.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=ve(n,u)}break;case K.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=ve(n,u)}break;case K.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=ve(n,u)}break;case K.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=ve(n,u)}break;case K.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=ve(n,u)}break;case K.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=ve(n,u)===1}break;case K.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(n.slice(c,u))}break;case K.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;const d=ve(n,u),m=so[d]??null;this.currentTrack.info.colorSpace.matrix=m}break;case K.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=ve(n,u)===2}break;case K.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;const d=ve(n,u),m=ro[d]??null;this.currentTrack.info.colorSpace.transfer=m}break;case K.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;const d=ve(n,u),m=io[d]??null;this.currentTrack.info.colorSpace.primaries=m}break;case K.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(n.slice(c,u))}break;case K.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;const m=-Zu(n,u);try{this.currentTrack.info.rotation=Mg(m)}catch{}}break;case K.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(n.slice(c,u))}break;case K.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Zu(n,u)}break;case K.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=ve(n,u)}break;case K.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=ve(n,u)}break;case K.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(n.slice(c,u)),this.currentCueTime=null}break;case K.CueTime:this.currentCueTime=ve(n,u);break;case K.CueTrackPositions:{if(this.currentCueTime===null)break;C(this.currentSegment);const d={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(d),this.readContiguousElements(n.slice(c,u)),(d.trackId===-1||d.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case K.CueTrack:{const d=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!d)break;d.trackId=ve(n,u)}break;case K.CueClusterPosition:{const d=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!d)break;C(this.currentSegment),d.clusterPosition=this.currentSegment.dataStartPos+ve(n,u)}break;case K.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=ve(n,u)}break;case K.SimpleBlock:{if(!this.currentCluster)break;const d=ys(n);if(d===null)break;const m=this.getTrackDataInCluster(this.currentCluster,d);if(!m)break;const p=gf(n),y=oe(n),g=y>>1&3;let b=!!(y&128);m.track.info?.type==="audio"&&m.track.info.codec&&(b=!0);const T=fe(n,u-(n.filePos-c)),w=m.track.decodingInstructions.length>0;m.blocks.push({timestamp:p,duration:0,isKeyFrame:b,data:T,lacing:g,decoded:!w,postProcessed:!1,mainAdditional:null})}break;case K.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(n.slice(c,u)),this.currentBlock=null}break;case K.Block:{if(!this.currentCluster)break;const d=ys(n);if(d===null)break;const m=this.getTrackDataInCluster(this.currentCluster,d);if(!m)break;const p=gf(n),g=oe(n)>>1&3,b=fe(n,u-(n.filePos-c)),T=m.track.decodingInstructions.length>0;this.currentBlock={timestamp:p,duration:0,isKeyFrame:!0,data:b,lacing:g,decoded:!T,postProcessed:!1,mainAdditional:null},m.blocks.push(this.currentBlock)}break;case K.BlockAdditions:this.readContiguousElements(n.slice(c,u));break;case K.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(n.slice(c,u)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case K.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=fe(n,u)}break;case K.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=ve(n,u)}break;case K.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=ve(n,u)}break;case K.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case K.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(n.slice(c,u));break;case K.Targets:this.readContiguousElements(n.slice(c,u));break;case K.TargetTypeValue:ve(n,u)!==50&&(this.currentTagTargetIsMovie=!1);break;case K.TagTrackUID:case K.TagEditionUID:case K.TagChapterUID:case K.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case K.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(n.slice(c,u))}break;case K.TagName:this.currentSimpleTagName=os(n,u);break;case K.TagString:{if(!this.currentSimpleTagName)break;const d=os(n,u);this.processTagValue(this.currentSimpleTagName,d)}break;case K.TagBinary:{if(!this.currentSimpleTagName)break;const d=fe(n,u);this.processTagValue(this.currentSimpleTagName,d)}break;case K.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(n.slice(c,u));const d=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(d.raw??={},d.raw[this.currentAttachedFile.fileUid.toString()]=new Yb(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const m=this.currentAttachedFile.fileName;let p="unknown";if(m){const y=m.toLowerCase();y.startsWith("cover.")?p="coverFront":y.startsWith("back.")&&(p="coverBack")}d.images??=[],d.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:p,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case K.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=AS(n,u)}break;case K.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=os(n,u)}break;case K.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=nr(n,u)}break;case K.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=fe(n,u)}break;case K.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=os(n,u)}break;case K.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(n.slice(c,u)),this.currentTrack.decodingInstructions.sort((d,m)=>m.order-d.order)}break;case K.ContentEncoding:this.currentDecodingInstruction={order:0,scope:uo.Block,data:null},this.readContiguousElements(n.slice(c,u)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case K.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=ve(n,u)}break;case K.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=ve(n,u)}break;case K.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Ss.Zlib,settings:null},this.readContiguousElements(n.slice(c,u))}break;case K.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=ve(n,u)}break;case K.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=fe(n,u)}break;case K.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return n.filePos=c+u,!0}decodeBlockData(n,i){C(n.decodingInstructions.length>0);let r=i;for(const o of n.decodingInstructions)switch(C(o.data),o.data.type){case"decompress":switch(o.data.algorithm){case Ss.HeaderStripping:if(o.data.settings&&o.data.settings.length>0){const u=o.data.settings,c=new Uint8Array(u.length+r.length);c.set(u,0),c.set(r,u.length),r=c}break}break}return r}processTagValue(n,i){if(!this.currentSegment?.metadataTags)return;const r=this.currentSegment.metadataTags;if(r.raw??={},r.raw[n]??=i,typeof i=="string")switch(n.toLowerCase()){case"title":r.title??=i;break;case"description":r.description??=i;break;case"artist":r.artist??=i;break;case"album":r.album??=i;break;case"album_artist":r.albumArtist??=i;break;case"genre":r.genre??=i;break;case"comment":r.comment??=i;break;case"lyrics":r.lyrics??=i;break;case"date":{const o=new Date(i);Number.isNaN(o.getTime())||(r.date??=o)}break;case"track_number":case"part_number":{const o=i.split("/"),u=Number.parseInt(o[0],10),c=o[1]&&Number.parseInt(o[1],10);Number.isInteger(u)&&u>0&&(r.trackNumber??=u),c&&Number.isInteger(c)&&c>0&&(r.tracksTotal??=c)}break;case"disc_number":case"disc":{const o=i.split("/"),u=Number.parseInt(o[0],10),c=o[1]&&Number.parseInt(o[1],10);Number.isInteger(u)&&u>0&&(r.discNumber??=u),c&&Number.isInteger(c)&&c>0&&(r.discsTotal??=c)}break}}}class C0{constructor(n){this.internalTrack=n,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const n=this.internalTrack.demuxer,i=this.internalTrack.trackBacking.getType();let r=0;for(const o of n.segments)for(const u of o.tracks)if(u.trackBacking.getType()===i&&r++,u===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const n=this.internalTrack.segment;if(n.duration<=0)return null;let i=n.duration/n.timestampFactor;const r=await this.getFirstPacket({metadataOnly:!0});return i+=r?.timestamp??0,i}async getLiveRefreshInterval(){return null}async getFirstPacket(n){return this.performClusterLookup(null,i=>i.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,n)}intoTimescale(n){return Cs(n*this.internalTrack.segment.timestampFactor)}async getPacket(n,i){const r=this.intoTimescale(n);return this.performClusterLookup(null,o=>{const u=o.trackData.get(this.internalTrack.id);if(!u)return{blockIndex:-1,correctBlockFound:!1};const c=Oe(u.presentationTimestamps,r,p=>p.timestamp),d=c!==-1?u.presentationTimestamps[c].blockIndex:-1,m=c!==-1&&r{if(o===r.cluster){const u=o.trackData.get(this.internalTrack.id);if(r.blockIndex+1{const u=o.trackData.get(this.internalTrack.id);if(!u)return{blockIndex:-1,correctBlockFound:!1};const c=Sf(u.presentationTimestamps,p=>u.blocks[p.blockIndex].isKeyFrame&&p.timestamp<=r),d=c!==-1?u.presentationTimestamps[c].blockIndex:-1,m=c!==-1&&r{if(o===r.cluster){const c=o.trackData.get(this.internalTrack.id).blocks.findIndex((d,m)=>d.isKeyFrame&&m>r.blockIndex);if(c!==-1)return{blockIndex:c,correctBlockFound:!0}}else{const u=o.trackData.get(this.internalTrack.id);if(u&&u.firstKeyFrameTimestamp!==null){const c=u.blocks.findIndex(d=>d.isKeyFrame);return C(c!==-1),{blockIndex:c,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,i)}async fetchPacketInCluster(n,i,r){if(i===-1)return null;const u=n.trackData.get(this.internalTrack.id).blocks[i];if(C(u),u.decoded||(u.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,u.data),u.decoded=!0),!u.postProcessed){if(this.internalTrack.info?.codec==="prores"&&!(u.data.length>=8&&u.data[4]===105&&u.data[5]===99&&u.data[6]===112&&u.data[7]===102)){const b=new Uint8Array(u.data.length+8);Re(b).setUint32(0,b.length,!1),b[4]=105,b[5]=99,b[6]=112,b[7]=102,b.set(u.data,8),u.data=b}u.postProcessed=!0}const c=r.metadataOnly?Wt:u.data,d=u.timestamp/this.internalTrack.segment.timestampFactor,m=u.duration/this.internalTrack.segment.timestampFactor,p={};u.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(p.alpha=r.metadataOnly?Wt:u.mainAdditional,p.alphaByteLength=u.mainAdditional.byteLength);const y=new dt(c,u.isKeyFrame?"key":"delta",d,m,n.dataStartPos+i,u.data.byteLength,p);return this.packetToClusterLocation.set(y,{cluster:n,blockIndex:i}),y}async performClusterLookup(n,i,r,o,u){const{demuxer:c,segment:d}=this.internalTrack;let m=null,p=null,y=-1;if(n){const{blockIndex:x,correctBlockFound:P}=i(n);if(P)return this.fetchPacketInCluster(n,x,u);x!==-1&&(p=n,y=x)}const g=Oe(this.internalTrack.cuePoints,r,x=>x.time),b=g!==-1?this.internalTrack.cuePoints[g]:null,T=Oe(this.internalTrack.clusterPositionCache,r,x=>x.startTimestamp),w=T!==-1?this.internalTrack.clusterPositionCache[T]:null,S=Math.max(b?.clusterPosition??0,w?.elementStartPos??0)||null;let E;for(n?S===null||n.elementStartPos>=S?(E=n.elementEndPos,m=n):E=S:E=S??d.clusterSeekStartPos;d.elementEndPos===null||E<=d.elementEndPos-fn;){if(m){const H=m.trackData.get(this.internalTrack.id);if(H&&H.startTimestamp>o)break}let x=c.reader.requestSliceRange(E,fn,Zn);if(x instanceof Promise&&(x=await x),!x)break;const P=E,_=Qn(x);if(!_||!As.includes(_.id)&&_.id!==K.Void){const H=await w0(c.reader,P,As,Math.min(d.elementEndPos??1/0,P+x0));if(H){E=H;continue}else break}const D=_.id;let B=_.size;const z=x.filePos;if(D===K.Cluster){m=await c.readCluster(P,d),B=m.elementEndPos-z;const{blockIndex:H,correctBlockFound:R}=i(m);if(R)return this.fetchPacketInCluster(m,H,u);H!==-1&&(p=m,y=H)}B===void 0&&(C(D!==K.Cluster),B=(await uf(c.reader,z,to,d.elementEndPos)).pos-z);const L=z+B;if(d.elementEndPos===null){let H=c.reader.requestSliceRange(L,fn,Zn);if(H instanceof Promise&&(H=await H),!H)break;if(If(H)===K.Segment){d.elementEndPos=L;break}}E=L}if(b&&(!p||p.elementStartPos{let n=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(n=await this.getFirstPacket({}));const r={codec:_f({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&n?t0(n.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&n?r0(n.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&n?s0(n.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&n?o0(n.data):null,proresFormat:this.internalTrack.info.proresFormat}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(r.displayAspectWidth=this.internalTrack.info.squarePixelWidth,r.displayAspectHeight=this.internalTrack.info.squarePixelHeight),r})():null}}class IS extends C0{constructor(n){super(n),this.decoderConfig=null,this.internalTrack=n}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Ef({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}const ff=async(l,n,i,r=null)=>{let u=n;for(;i===null||u=ri;){const m=d.filePos,p=$(d),y=l.fileSize!==null?l.fileSize-u:null,g=Af(p,y);if(g.header&&(!r||g.header.sampleRate===r.sampleRate&&g.header.mpegVersionId===r.mpegVersionId&&g.header.layer===r.layer&&Es(g.header.channel)===Es(r.channel)))return{header:g.header,startPos:u};d.filePos=m+g.bytesAdvanced,u=d.filePos}}return null};class RS extends ta{constructor(n){super(n),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new ho,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=n._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new OS(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let d=this.reader.requestSlice(this.lastLoadedPos,dn);if(d instanceof Promise&&(d=await d),!d){this.lastSampleLoaded=!0;return}const m=$n(d);if(!m)break;this.lastLoadedPos=d.filePos+m.size}const n=await ff(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!n){this.lastSampleLoaded=!0;return}const i=n.header;this.lastLoadedPos=n.startPos+i.totalSize-1;const r=Jg(i.mpegVersionId,i.channel);let o=this.reader.requestSlice(n.startPos+r,4);if(o instanceof Promise&&(o=await o),o){const d=$(o);if(d===Zg||d===Wg){if(!this.xingData){let p=this.reader.requestSlice(n.startPos+r+4,12);if(p instanceof Promise&&(p=await p),p){const y=fe(p,12),g=Re(y),b=g.getUint32(0,!1);this.xingData={frameCount:b&oo.FrameCount?g.getUint32(4,!1):null,fileSize:b&oo.FileSize?g.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=i,this.firstFrameHeaderPos=n.startPos);const u=i.audioSamplesInFrame/this.firstFrameHeader.sampleRate,c={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:u,dataStart:n.startPos,dataSize:i.totalSize};this.loadedSamples.push(c),this.nextTimestampInSamples+=i.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const n=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let i=0,r=!1;for(;;){let o=this.reader.requestSlice(i,dn);if(o instanceof Promise&&(o=await o),!o)break;const u=$n(o);if(!u)break;r=!0;let c=this.reader.requestSlice(o.filePos,u.size);if(c instanceof Promise&&(c=await c),!c)break;vo(c,u,this.metadataTags),i=o.filePos+u.size}if(!r&&this.reader.fileSize!==null&&this.reader.fileSize>=ao){let o=this.reader.requestSlice(this.reader.fileSize-ao,ao);o instanceof Promise&&(o=await o),C(o),Je(o,3)==="TAG"&&nT(o,this.metadataTags)}return this.metadataTags}finally{n()}}}class OS{constructor(n){this.demuxer=n}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return C(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const n=this.demuxer;if(C(n.firstFrameHeader!==null),C(n.firstFrameHeaderPos!==null),n.xingData){if(n.xingData.frameCount!==null)return n.xingData.frameCount*n.firstFrameHeader.audioSamplesInFrame/n.firstFrameHeader.sampleRate}else if(n.reader.fileSize!==null){const i=$b(n.firstFrameHeader.lowSamplingFrequency,n.firstFrameHeader.layer,n.firstFrameHeader.bitrate,n.firstFrameHeader.sampleRate),r=(n.reader.fileSize-n.firstFrameHeaderPos)/i;return Math.round(r)*n.firstFrameHeader.audioSamplesInFrame/n.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return _t}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return C(this.demuxer.firstFrameHeader),Es(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return C(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...ea}}async getDecoderConfig(){return C(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Es(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(n,i){if(n===-1)return null;const r=this.demuxer.loadedSamples[n];if(!r)return null;let o;if(i.metadataOnly)o=Wt;else{let u=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(u instanceof Promise&&(u=await u),!u)return null;o=fe(u,r.dataSize)}return new dt(o,"key",r.timestamp,r.duration,n,r.dataSize)}getFirstPacket(n){return this.getPacketAtIndex(0,n)}async getNextPacket(n,i){const r=await this.demuxer.readingMutex.acquire();try{const o=Bs(this.demuxer.loadedSamples,n.timestamp,c=>c.timestamp);if(o===-1)throw new Error("Packet was not created from this track.");const u=o+1;for(;u>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(u,i)}finally{r()}}async getPacket(n,i){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const o=Oe(this.demuxer.loadedSamples,n,u=>u.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,i);if(o>=0&&o+1>>0&4294967295}const MS=l=>{const n=Re(l),i=n.getUint32(22,!0);n.setUint32(22,0,!0);let r=0;for(let o=0;o>>24^u])>>>0}return n.setUint32(22,i,!0),r},NS=(l,n,i)=>{let r=0,o=null;if(l.length>0)if(n.codec==="vorbis"){C(n.vorbisInfo);const u=n.vorbisInfo.modeBlockflags.length,d=(1<>1;if(m>=n.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let p=i;const y=n.vorbisInfo.modeBlockflags[m];if(o=n.vorbisInfo.blocksizes[y],y===1){const g=(d|1)+1,b=l[0]&g?1:0;p=n.vorbisInfo.blocksizes[b]}r=p!==null?p+o>>2:0}else n.codec==="opus"&&(r=uS(l).durationInSamples);return{durationInSamples:r,vorbisBlockSize:o}},US=l=>{let n="audio/ogg";if(l.codecStrings){const i=[...new Set(l.codecStrings)];n+=`; codecs="${i.join(", ")}"`}return n};const ni=27,ur=282,FS=ur+65025,Ts=l=>{const n=l.filePos;if(rr(l)!==_0)return null;l.skip(1);const r=oe(l),o=eT(l),u=rr(l),c=rr(l),d=rr(l),m=oe(l),p=new Uint8Array(m);for(let T=0;TT+w,0),b=y+g;return{headerStartPos:n,totalSize:b,dataStartPos:n+y,dataSize:g,headerType:r,granulePosition:o,serialNumber:u,sequenceNumber:c,checksum:d,lacingValues:p}},qS=(l,n)=>{for(;l.filePos>>8&255,u=i>>>16&255,c=i>>>24&255,d=79;if(!(r!==d&&o!==d&&u!==d&&c!==d)){if(l.skip(-4),i===_0)return!0;l.skip(1)}}return!1};class HS extends ta{constructor(n){super(n),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=n._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let n=0;for(;;){let i=this.reader.requestSliceRange(n,ni,ur);if(i instanceof Promise&&(i=await i),!i)break;const r=Ts(i);if(!r||!!!(r.headerType&2))break;this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),n=r.headerStartPos+r.totalSize}for(const i of this.bitstreams){const r=await this.readPacket(i.bosPage,0);r&&(r.data.byteLength>=7&&r.data[0]===1&&r.data[1]===118&&r.data[2]===111&&r.data[3]===114&&r.data[4]===98&&r.data[5]===105&&r.data[6]===115?await this.readVorbisMetadata(r,i):r.data.byteLength>=8&&r.data[0]===79&&r.data[1]===112&&r.data[2]===117&&r.data[3]===115&&r.data[4]===72&&r.data[5]===101&&r.data[6]===97&&r.data[7]===100&&await this.readOpusMetadata(r,i),i.codecInfo.codec!==null&&this.trackBackings.push(new LS(i,this)))}})()}async readVorbisMetadata(n,i){let r=await this.findNextPacketStart(n);if(!r)return;const o=await this.readPacket(r.startPage,r.startSegmentIndex);if(!o||(r=await this.findNextPacketStart(o),!r))return;const u=await this.readPacket(r.startPage,r.startSegmentIndex);if(!u||o.data[0]!==3||u.data[0]!==5)return;const c=[],d=g=>{for(;c.push(Math.min(255,g)),!(g<255);)g-=255};d(n.data.length),d(o.data.length);const m=new Uint8Array(1+c.length+n.data.length+o.data.length+u.data.length);m[0]=2,m.set(c,1),m.set(n.data,1+c.length),m.set(o.data,1+c.length+n.data.length),m.set(u.data,1+c.length+n.data.length+o.data.length),i.codecInfo.codec="vorbis",i.description=m,i.lastMetadataPacket=u;const p=Re(n.data);i.numberOfChannels=p.getUint8(11),i.sampleRate=p.getUint32(12,!0);const y=p.getUint8(28);i.codecInfo.vorbisInfo={blocksizes:[1<<(y&15),1<<(y>>4)],modeBlockflags:fS(u.data).modeBlockflags},lf(o.data.subarray(7),this.metadataTags)}async readOpusMetadata(n,i){const r=await this.findNextPacketStart(n);if(!r)return;const o=await this.readPacket(r.startPage,r.startSegmentIndex);if(!o)return;i.codecInfo.codec="opus",i.description=n.data,i.lastMetadataPacket=o;const u=oS(n.data);i.numberOfChannels=u.outputChannelCount,i.sampleRate=po,i.codecInfo.opusInfo={preSkip:u.preSkip},lf(o.data.subarray(8),this.metadataTags)}async readPacket(n,i){C(ig+b.length,0);if(m===0)return null;const p=new Uint8Array(m);let y=0;for(let g=0;gi.getDecoderConfig().then(r=>r?.codec??null)));return US({codecStrings:n.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class LS{constructor(n,i){this.bitstream=n,this.demuxer=i,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new ho,this.internalSampleRate=n.codecInfo.codec==="opus"?po:n.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const n=this.demuxer.trackBackings.findIndex(i=>i.bitstream===this.bitstream);return C(n!==-1),n+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return C(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return _t}getDisposition(){return{...ea,primary:!1}}granulePositionToTimestampInSamples(n){return this.bitstream.codecInfo.codec==="opus"?(C(this.bitstream.codecInfo.opusInfo),n-this.bitstream.codecInfo.opusInfo.preSkip):n}createEncodedPacketFromOggPacket(n,i,r){if(!n)return null;const{durationInSamples:o,vorbisBlockSize:u}=NS(n.data,this.bitstream.codecInfo,i.vorbisLastBlocksize),c=new dt(r.metadataOnly?Wt:n.data,"key",Math.max(0,i.timestampInSamples)/this.internalSampleRate,o/this.internalSampleRate,n.endPage.headerStartPos+n.endSegmentIndex,n.data.byteLength);return this.encodedPacketToMetadata.set(c,{packet:n,timestampInSamples:i.timestampInSamples,durationInSamples:o,vorbisLastBlockSize:i.vorbisLastBlocksize,vorbisBlockSize:u}),c}async getFirstPacket(n){C(this.bitstream.lastMetadataPacket);const i=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!i)return null;let r=0;this.bitstream.codecInfo.codec==="opus"&&(C(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);const o=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(o,{timestampInSamples:r,vorbisLastBlocksize:null},n)}async getNextPacket(n,i){const r=this.encodedPacketToMetadata.get(n);if(!r)throw new Error("Packet was not created from this track.");const o=await this.demuxer.findNextPacketStart(r.packet);if(!o)return null;const u=r.timestampInSamples+r.durationInSamples,c=await this.demuxer.readPacket(o.startPage,o.startSegmentIndex);return this.createEncodedPacketFromOggPacket(c,{timestampInSamples:u,vorbisLastBlocksize:r.vorbisBlockSize},i)}async getPacket(n,i){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(n,i);const r=Cs(n*this.internalSampleRate);if(r===0)return this.getFirstPacket(i);if(r<0)return null;C(this.bitstream.lastMetadataPacket);const o=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!o)return null;let u=o.startPage,c=this.demuxer.reader.fileSize;const d=[u];e:for(;u.headerStartPos+u.totalSizer?c=R.headerStartPos:(u=R,d.push(R));continue e}}let m=o.startPage;for(const P of d){if(P.granulePosition===u.granulePosition)break;(!m||P.headerStartPos>m.headerStartPos)&&(m=P)}let p=m;const y=[p];for(;!(p.serialNumber===this.bitstream.serialNumber&&p.granulePosition===u.granulePosition);){const P=p.headerStartPos+p.totalSize;let _=this.demuxer.reader.requestSliceRange(P,ni,ur);_ instanceof Promise&&(_=await _),C(_);const D=Ts(_);C(D),p=D,p.serialNumber===this.bitstream.serialNumber&&y.push(p)}C(p.granulePosition!==-1);let g=null,b,T,w=p,S=0;if(p.headerStartPos===o.startPage.headerStartPos)b=this.granulePositionToTimestampInSamples(0),T=!0,g=0;else{b=0,T=!1;for(let D=p.lacingValues.length-1;D>=0;D--)if(p.lacingValues[D]<255){g=D+1;break}if(g===null)throw new Error("Invalid page with granule position: no packets end on this page.");S=g-1;const P={data:Wt,endPage:w,endSegmentIndex:S};if(await this.demuxer.findNextPacketStart(P)){const D=cg(y,p,g);C(D);const B=og(y,D.page,D.segmentIndex);B&&(p=B.page,g=B.segmentIndex)}else for(;;){const D=cg(y,p,g);if(!D)break;const B=og(y,D.page,D.segmentIndex);if(!B)break;if(p=B.page,g=B.segmentIndex,D.page.headerStartPos!==w.headerStartPos){w=D.page,S=D.segmentIndex;break}}}let E=null,x=null;for(;p!==null;){C(g!==null);const P=await this.demuxer.readPacket(p,g);if(!P)break;if(!(p.headerStartPos===o.startPage.headerStartPos&&gr||Math.max(z.timestampInSamples,0)===r))break}const D=await this.demuxer.findNextPacketStart(P);if(!D)break;p=D.startPage,g=D.startSegmentIndex}return E}async getPacketSequential(n,i){const r=await this.sequentialScanMutex.acquire();try{const o=Cs(n*this.internalSampleRate);n=o/this.internalSampleRate;const u=Oe(this.sequentialScanCache,o,m=>m.timestampInSamples);let c;if(u!==-1){const m=this.sequentialScanCache[u];c=this.createEncodedPacketFromOggPacket(m.packet,{timestampInSamples:m.timestampInSamples,vorbisLastBlocksize:m.vorbisLastBlockSize},i)}else c=await this.getFirstPacket(i);let d=0;for(;c&&c.timestampn)break;if(c=m,d++,d===100){d=0;const p=this.encodedPacketToMetadata.get(c);C(p),this.sequentialScanCache.length>0&&C(Zt(this.sequentialScanCache).timestampInSamples<=p.timestampInSamples),this.sequentialScanCache.push(p)}}return c}finally{r()}}getKeyPacket(n,i){return this.getPacket(n,i)}getNextKeyPacket(n,i){return this.getNextPacket(n,i)}}const og=(l,n,i)=>{let r=n,o=i;e:for(;;){for(o--,o;o>=0;o--)if(r.lacingValues[o]<255){o++;break e}if(C(o===-1),!(r.headerType&1)){o=0;break}const c=Hg(l,d=>d.headerStartPos{if(i>0)return{page:n,segmentIndex:i-1};const r=Hg(l,o=>o.headerStartPos{let n=this.reader.requestSlice(0,12);n instanceof Promise&&(n=await n),C(n);const i=Je(n,4),r=i!=="RIFX",o=i==="RF64",u=Da(n,r);let c=o?this.reader.fileSize:Math.min(u+8,this.reader.fileSize??1/0);if(Je(n,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let m=0,p=null,y=n.filePos;for(;c===null||y=18&&u!==357){const y=hs(o,r),g=i-18;if(Math.min(g,y)>=22&&u===xt.EXTENSIBLE){o.skip(6);const T=fe(o,16);u=T[0]|T[1]<<8}}if((u===xt.MULAW||u===xt.ALAW)&&(p=8),u!==xt.PCM&&u!==xt.IEEE_FLOAT&&u!==xt.ALAW&&u!==xt.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${u}). Only integer/float PCM, A-law, and μ-law are supported.`);if(u===xt.PCM&&![8,16,24,32].includes(p))throw new Error(`Unsupported WAVE PCM bit depth (${p}). Only 8, 16, 24, and 32 bits are supported.`);if(u===xt.IEEE_FLOAT&&![32,64].includes(p))throw new Error(`Unsupported WAVE float bit depth (${p}). Only 32 and 64 bits are supported.`);this.audioInfo={format:u,numberOfChannels:c,sampleRate:d,sampleSizeInBytes:Math.ceil(p/8),blockSizeInBytes:m}}async parseListChunk(n,i,r){let o=this.reader.requestSlice(n,i);if(o instanceof Promise&&(o=await o),!o)return;const u=Je(o,4);if(u!=="INFO"&&u!=="INF0")return;let c=o.filePos;for(;c<=n+i-8;){o.filePos=c;const d=Je(o,4),m=Da(o,r),p=fe(o,m);let y=0;for(let b=0;b0&&(this.metadataTags.trackNumber??=T),w&&Number.isInteger(w)&&w>0&&(this.metadataTags.tracksTotal??=w)}break;case"ICRD":case"IDIT":{const b=new Date(g);Number.isNaN(b.getTime())||(this.metadataTags.date??=b)}break;case"YEAR":{const b=Number.parseInt(g,10);Number.isInteger(b)&&b>0&&(this.metadataTags.date??=new Date(b,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=g;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=g;break}c+=8+m+(m&1)}}async parseId3Chunk(n,i){let r=this.reader.requestSlice(n,i);if(r instanceof Promise&&(r=await r),!r)return;const o=$n(r);if(o){const u=i-dn;if(o.size=Math.min(o.size,u),o.size>0){const c=r.slice(n+dn,o.size);vo(c,o,this.metadataTags)}}}getCodec(){if(C(this.audioInfo),this.audioInfo.format===xt.MULAW)return"ulaw";if(this.audioInfo.format===xt.ALAW)return"alaw";if(this.audioInfo.format===xt.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}if(this.audioInfo.format===xt.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32";if(this.audioInfo.sampleSizeInBytes===8)return"pcm-f64"}C(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Ki=2048;class jS{constructor(n){this.demuxer=n}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return C(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const n=this.demuxer.getCodec();return n?(C(this.demuxer.audioInfo),{codec:n,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return C(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return C(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return C(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return C(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return _t}getDisposition(){return{...ea}}async getPacketAtIndex(n,i){C(n>=0),C(this.demuxer.audioInfo);const r=n*Ki*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const o=Math.min(Ki*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(this.demuxer.reader.fileSize===null){let m=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,o);if(m instanceof Promise&&(m=await m),!m)return null}let u;if(i.metadataOnly)u=Wt;else{let m=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,o);m instanceof Promise&&(m=await m),C(m),u=fe(m,o)}const c=n*Ki/this.demuxer.audioInfo.sampleRate,d=o/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(n,this.demuxer.lastKnownPacketIndex),new dt(u,"key",c,d,n,o)}getFirstPacket(n){return this.getPacketAtIndex(0,n)}async getPacket(n,i){C(this.demuxer.audioInfo);const r=Math.floor(Math.min(n*this.demuxer.audioInfo.sampleRate/Ki,(this.demuxer.dataSize-1)/(Ki*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;const o=await this.getPacketAtIndex(r,i);if(o)return o;if(r===0)return null;C(this.demuxer.reader.fileSize===null);let u=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,i);for(;u;){const c=await this.getNextPacket(u,i);if(!c)break;u=c}return u}getNextPacket(n,i){C(this.demuxer.audioInfo);const r=Math.round(n.timestamp*this.demuxer.audioInfo.sampleRate/Ki);return this.getPacketAtIndex(r+1,i)}getKeyPacket(n,i){return this.getPacket(n,i)}getNextKeyPacket(n,i){return this.getNextPacket(n,i)}}const df=7,fr=9,Ps=l=>{const n=l.filePos,i=fe(l,9),r=new Me(i);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;const c=r.readBits(1),d=r.readBits(2)+1,m=r.readBits(4);if(m===15)return null;r.skipBits(1);const p=r.readBits(3);if(p===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const y=r.readBits(13);r.skipBits(11);const g=r.readBits(2)+1;if(g!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let b=null;return c===1?l.filePos-=2:b=r.readBits(16),{objectType:d,samplingFrequencyIndex:m,channelConfiguration:p,frameLength:y,numberOfAacFrames:g,crcCheck:b,startPos:n}};const fo=1024;class XS extends ta{constructor(n){super(n),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new ho,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=n._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();C(this.firstFrameHeader),this.trackBackings=[new GS(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let c=this.reader.requestSlice(this.lastLoadedPos,dn);if(c instanceof Promise&&(c=await c),!c){this.lastSampleLoaded=!0;return}const d=$n(c);if(!d)break;this.lastLoadedPos=c.filePos+d.size}let n=this.reader.requestSliceRange(this.lastLoadedPos,df,fr);if(n instanceof Promise&&(n=await n),!n){this.lastSampleLoaded=!0;return}const i=Ps(n);if(!i){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&i.startPos+i.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=i);const r=_s[i.samplingFrequencyIndex];C(r!==void 0);const o=fo/r,u={timestamp:this.nextTimestampInSamples/r,duration:o,dataStart:i.startPos,dataSize:i.frameLength};this.loadedSamples.push(u),this.nextTimestampInSamples+=fo,this.lastLoadedPos=i.startPos+i.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const n=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let i=0;for(;;){let r=this.reader.requestSlice(i,dn);if(r instanceof Promise&&(r=await r),!r)break;const o=$n(r);if(!o)break;let u=this.reader.requestSlice(r.filePos,o.size);if(u instanceof Promise&&(u=await u),!u)break;vo(u,o,this.metadataTags),i=r.filePos+o.size}return this.metadataTags}finally{n()}}}class GS{constructor(n){this.demuxer=n}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/fo}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return _t}getCodec(){return"aac"}getInternalCodecId(){return C(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){C(this.demuxer.firstFrameHeader);const n=xf[this.demuxer.firstFrameHeader.channelConfiguration];return C(n!==void 0),n}getSampleRate(){C(this.demuxer.firstFrameHeader);const n=_s[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return C(n!==void 0),n}getDisposition(){return{...ea}}async getDecoderConfig(){return C(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(n,i){if(n===-1)return null;const r=this.demuxer.loadedSamples[n];if(!r)return null;let o;if(i.metadataOnly)o=Wt;else{let u=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(u instanceof Promise&&(u=await u),!u)return null;o=fe(u,r.dataSize)}return new dt(o,"key",r.timestamp,r.duration,n,r.dataSize)}getFirstPacket(n){return this.getPacketAtIndex(0,n)}async getNextPacket(n,i){const r=await this.demuxer.readingMutex.acquire();try{const o=Bs(this.demuxer.loadedSamples,n.timestamp,c=>c.timestamp);if(o===-1)throw new Error("Packet was not created from this track.");const u=o+1;for(;u>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(u,i)}finally{r()}}async getPacket(n,i){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const o=Oe(this.demuxer.loadedSamples,n,u=>u.timestamp);if(o===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(o,i);if(o>=0&&o+1l===0?null:l===1?192:l>=2&&l<=5?144*2**l:l===6?"uncommon-u8":l===7?"uncommon-u16":l>=8&&l<=15?2**l:null,YS=(l,n)=>{switch(l){case 0:return n;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},QS=l=>{let n=0;const i=new Me(fe(l,1));for(;i.readBits(1)===1;)n++;if(n===0)return i.readBits(7);const r=[],o=n-1,u=new Me(fe(l,o)),c=8-n-1;for(let m=0;mm|p<{if(n==="uncommon-u16")return it(l)+1;if(n==="uncommon-u8")return oe(l)+1;if(typeof n=="number")return n;xs(n),C(!1)},WS=(l,n)=>n==="uncommon-u16"?it(l):n==="uncommon-u16-10"?it(l)*10:n==="uncommon-u8"?oe(l):typeof n=="number"?n:null,JS=l=>{let i=0;for(const r of l){i^=r;for(let o=0;o<8;o++)(i&128)!==0?i=i<<1^7:i<<=1,i&=255}return i};class $S extends ta{constructor(n){super(n),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new ho,this.lastSampleLoaded=!1,this.reader=n._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),C(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??=(async()=>{let n=0;for(;;){let i=this.reader.requestSlice(n,dn);if(i instanceof Promise&&(i=await i),!i){this.lastSampleLoaded=!0;return}const r=$n(i);if(!r)break;let o=this.reader.requestSlice(i.filePos,r.size);o instanceof Promise&&(o=await o),C(o),vo(o,r,this.metadataTags),n=i.filePos+r.size}for(n+=4;this.reader.fileSize===null||ny.end-r)return{num:g.num,blockSize:g.blockSize,sampleRate:g.sampleRate,size:y.end-n,isLastFrame:!0};if(oe(y)===255){const T=y.filePos,w=oe(y),S=this.blockingBit===1?249:248;if(w!==S){y.filePos=T;continue}y.skip(-2);const E=y.filePos-n,x=this.readFlacFrameHeader({slice:y,isFirstPacket:!1});if(!x){y.filePos=T;continue}if(this.blockingBit===0){if(x.num-g.num!==1){y.filePos=T;continue}}else if(x.num-g.num!==g.blockSize){y.filePos=T;continue}return{num:g.num,blockSize:g.blockSize,sampleRate:g.sampleRate,size:E,isLastFrame:!1}}}}readFlacFrameHeader({slice:n,isFirstPacket:i}){const r=n.filePos,o=fe(n,4),u=new Me(o);if(u.readBits(15)!==32764)return null;if(this.blockingBit===null){C(i);const E=u.readBits(1);this.blockingBit=E}else if(this.blockingBit===1){if(C(!i),u.readBits(1)!==1)return null}else if(this.blockingBit===0){if(C(!i),u.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");const d=KS(u.readBits(4));if(!d)return null;C(this.audioInfo);const m=YS(u.readBits(4),this.audioInfo.sampleRate);if(!m||(u.readBits(4),u.readBits(3),u.readBits(1)!==0))return null;const y=QS(n),g=ZS(n,d),b=WS(n,m);if(b===null||b!==this.audioInfo.sampleRate)return null;const T=n.filePos-r,w=oe(n);n.skip(-T),n.skip(-1);const S=JS(fe(n,T));return w!==S?null:{num:y,blockSize:g,sampleRate:b}}async advanceReader(){await this.readMetadata(),C(this.lastLoadedPos!==null),C(this.audioInfo);const n=this.lastLoadedPos,i=await this.readNextFlacFrame({startPos:n,isFirstPacket:this.loadedSamples.length===0});if(!i){this.lastSampleLoaded=!0;return}const r=this.loadedSamples[this.loadedSamples.length-1],u={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:i.blockSize,byteOffset:n,byteSize:i.size};if(this.lastLoadedPos=this.lastLoadedPos+i.size,this.loadedSamples.push(u),i.isLastFrame){this.lastSampleLoaded=!0;return}}}class e1{constructor(n){this.demuxer=n}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return C(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return C(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return _t}getTimeResolution(){return C(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return C(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...ea}}async getDecoderConfig(){return C(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(n,i){if(C(this.demuxer.audioInfo),n<0)return null;const r=await this.demuxer.readingMutex.acquire();try{for(;;){const o=Oe(this.demuxer.loadedSamples,n,m=>m.blockOffset/this.demuxer.audioInfo.sampleRate);if(o===-1){await this.demuxer.advanceReader();continue}const u=this.demuxer.loadedSamples[o],c=u.blockOffset/this.demuxer.audioInfo.sampleRate,d=u.blockSize/this.demuxer.audioInfo.sampleRate;if(c+d<=n){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,i);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(o,i)}}finally{r()}}async getNextPacket(n,i){const r=await this.demuxer.readingMutex.acquire();try{const o=n.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&o>=this.demuxer.loadedSamples.length)return null;for(;o>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(o,i)}finally{r()}}getKeyPacket(n,i){return this.getPacket(n,i)}getNextKeyPacket(n,i){return this.getNextPacket(n,i)}async getPacketAtIndex(n,i){const r=this.demuxer.loadedSamples[n];if(!r)return null;let o;if(i.metadataOnly)o=Wt;else{let d=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(d instanceof Promise&&(d=await d),!d)return null;o=fe(d,r.byteSize)}C(this.demuxer.audioInfo);const u=r.blockOffset/this.demuxer.audioInfo.sampleRate,c=r.blockSize/this.demuxer.audioInfo.sampleRate;return new dt(o,"key",u,c,n,r.byteSize)}async getFirstPacket(n){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,n)}}const Wn=9e4,Qt=188,t1=l=>{let n="video/MP2T";const i=[...new Set(l.filter(Boolean))];return i.length>0&&(n+=`; codecs="${i.join(", ")}"`),n};const A0="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",ug=new Set;class n1 extends ta{constructor(n){super(n),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=n._reader}async readMetadata(){return this.metadataPromise??=(async()=>{const n=Qt+16+1;let i=this.reader.requestSlice(0,n);i instanceof Promise&&(i=await i),C(i);const r=fe(i,n);if(r[0]===71&&r[Qt]===71)this.packetOffset=0,this.packetStride=Qt;else if(r[0]===71&&r[Qt+16]===71)this.packetOffset=0,this.packetStride=Qt+16;else if(r[4]===71&&r[4+Qt+4]===71)this.packetOffset=4,this.packetStride=Qt+4;else throw new Error("Unreachable.");const o=256;this.minReferencePointByteDistance=o*this.packetStride;let u=this.packetOffset,c=null,d=!1,m=!1;for(;;){const p=await this.readPacketHeader(u);if(!p)break;if(p.payloadUnitStartIndicator===0){u+=this.packetStride;continue}if(m&&!this.elementaryStreams.some(S=>S.pid===p.pid)){u+=this.packetStride;continue}const y=await this.readSection(u,!0,!m);if(!y)break;const g=3,b=32;let T=!1;if(!m&&y.pid!==0&&!(y.payload[0]===0&&y.payload[1]===0&&y.payload[2]===1)){const E=new Me(y.payload),x=E.readAlignedByte();E.skipBits(8*x),T=E.readBits(8)===2}if(y.pid===0&&!d){const S=new Me(y.payload),E=S.readAlignedByte();S.skipBits(8*E),S.skipBits(14);const x=S.readBits(10);for(S.skipBits(40);8*(x+g)-S.pos>b;){const P=S.readBits(16);S.skipBits(3);const _=S.readBits(13);if(P!==0){if(c!==null)throw new Error("Only files with a single program are supported.");c=_}}if(c===null)throw new Error("Program Association Table must link to a Program Map Table.");d=!0}else if((y.pid===c||T)&&!m){const S=new Me(y.payload),E=S.readAlignedByte();S.skipBits(8*E),S.skipBits(12);const x=S.readBits(12);S.skipBits(43),S.readBits(13),S.skipBits(6);const P=S.readBits(10);for(S.skipBits(8*P);8*(x+g)-S.pos>b;){const _=S.readBits(8);S.skipBits(3);const D=S.readBits(13);S.skipBits(6);const B=S.readBits(10),z=S.pos+8*B;let L=!1,H=!1;for(;S.posE.pid===y.pid);e:if(S&&!S.initialized){const E=ir(y,!0);if(!E)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${S.pid}`);if(S.firstSection=y,S.canBeTrustedWithKeyPackets=y.randomAccessIndicator===1,this.input._initInput){const _=(await this.input._initInput._getDemuxer()).elementaryStreams.find(D=>D.pid===y.pid&&D.info.codec===S.info.codec);if(_){S.info=_.info,S.initialized=!0;break e}}const x=new ks(S,E);if(S.info.type==="video"){for(;;){const P=x;if(P.suppliedPacket=null,await x.markNextPacket(),S.info.codec==="avc"){if(!x.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(S.info.avcCodecInfo=t0(x.suppliedPacket.data),!S.info.avcCodecInfo)continue;const _=S.info.avcCodecInfo.sequenceParameterSets[0];C(_);const D=a0(_);S.info.width=D.displayWidth,S.info.height=D.displayHeight;const B=D.pixelAspectRatio.num,z=D.pixelAspectRatio.den;B>0&&z>0&&(B>z?(S.info.squarePixelWidth=Math.round(S.info.width*B/z),S.info.squarePixelHeight=S.info.height):(S.info.squarePixelWidth=S.info.width,S.info.squarePixelHeight=Math.round(S.info.height*z/B))),S.info.colorSpace={primaries:io[D.colourPrimaries],transfer:ro[D.transferCharacteristics],matrix:so[D.matrixCoefficients],fullRange:!!D.fullRangeFlag},S.info.reorderSize=D.maxDecFrameBuffering;break}else if(S.info.codec==="hevc"){if(!x.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(S.info.hevcCodecInfo=r0(x.suppliedPacket.data),!S.info.hevcCodecInfo)continue;const D=S.info.hevcCodecInfo.arrays.find(z=>z.nalUnitType===St.SPS_NUT).nalUnits[0];C(D);const B=i0(D);S.info.width=B.displayWidth,S.info.height=B.displayHeight,B.pixelAspectRatio.num>B.pixelAspectRatio.den?(S.info.squarePixelWidth=Math.round(S.info.width*B.pixelAspectRatio.num/B.pixelAspectRatio.den),S.info.squarePixelHeight=S.info.height):(S.info.squarePixelWidth=S.info.width,S.info.squarePixelHeight=Math.round(S.info.height*B.pixelAspectRatio.den/B.pixelAspectRatio.num)),S.info.colorSpace={primaries:io[B.colourPrimaries],transfer:ro[B.transferCharacteristics],matrix:so[B.matrixCoefficients],fullRange:!!B.fullRangeFlag},S.info.reorderSize=B.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}S.info.decoderConfig={codec:_f({width:S.info.width,height:S.info.height,codec:S.info.codec,codecDescription:null,colorSpace:S.info.colorSpace,avcType:1,avcCodecInfo:S.info.avcCodecInfo,hevcCodecInfo:S.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:S.info.width,codedHeight:S.info.height,colorSpace:S.info.colorSpace},(S.info.width!==S.info.squarePixelWidth||S.info.height!==S.info.squarePixelHeight)&&(S.info.decoderConfig.displayAspectWidth=S.info.squarePixelWidth,S.info.decoderConfig.displayAspectHeight=S.info.squarePixelHeight),S.initialized=!0}else{if(await x.markNextPacket(),!x.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${S.pid}`);if(S.info.codec==="aac"){const P=gn.tempFromBytes(x.suppliedPacket.data),_=Ps(P);if(!_)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");S.info.aacCodecInfo={isMpeg2:!1,objectType:_.objectType},S.info.numberOfChannels=xf[_.channelConfiguration],S.info.sampleRate=_s[_.samplingFrequencyIndex]}else if(S.info.codec==="mp3"){const P=$(gn.tempFromBytes(x.suppliedPacket.data)),_=Af(P,x.suppliedPacket.data.byteLength);if(!_.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");S.info.numberOfChannels=Es(_.header.channel),S.info.sampleRate=_.header.sampleRate}else if(S.info.codec==="ac3"){const P=dS(x.suppliedPacket.data);if(!P)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(P.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");S.info.numberOfChannels=Bf[P.acmod]+P.lfeon,S.info.sampleRate=go[P.fscod]}else if(S.info.codec==="eac3"){const P=pS(x.suppliedPacket.data);if(!P)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const _=f0(P);if(_===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");S.info.numberOfChannels=d0(P),S.info.sampleRate=_}else throw new Error("Unhandled.");S.info.decoderConfig={codec:Ef({codec:S.info.codec,codecDescription:null,aacCodecInfo:S.info.aacCodecInfo}),numberOfChannels:S.info.numberOfChannels,sampleRate:S.info.sampleRate},S.initialized=!0}}}if(m&&this.elementaryStreams.every(S=>S.initialized))break;u+=this.packetStride}if(!m)throw d?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(const p of this.elementaryStreams)p.info.type==="video"?this.trackBackingEntries.push(new a1(p)):this.trackBackingEntries.push(new i1(p))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();const n=await Promise.all(this.trackBackingEntries.map(i=>i.getDecoderConfig().then(r=>r?.codec??null)));return t1(n)}async readSection(n,i,r=!1){let o=n,u=n;const c=[];let d=0,m=null,p=!0,y=0;for(;;){const b=await this.readPacket(u);if(u+=this.packetStride,!b)break;if(m){if(b.pid!==m.pid){if(r)break;continue}if(b.payloadUnitStartIndicator===1)break}else{if(b.payloadUnitStartIndicator===0)break;m=b}const T=!!(b.adaptationFieldControl&2),w=!!(b.adaptationFieldControl&1);let S=0;if(T&&(S=1+b.body[0],b===m&&S>1&&(y=b.body[1]>>6&1)),w&&(S===0?(c.push(b.body),d+=b.body.byteLength):(c.push(b.body.subarray(S)),d+=b.body.byteLength-S)),o=u,!i&&d>=64){p=!1;break}if(Bs(this.sectionEndPositions,o,x=>x)!==-1){p=!1;break}}if(p){const b=Oe(this.sectionEndPositions,o,T=>T);this.sectionEndPositions.splice(b+1,0,o)}if(!m)return null;let g;if(c.length===1)g=c[0];else{const b=c.reduce((w,S)=>w+S.length,0);g=new Uint8Array(b);let T=0;for(const w of c)g.set(w,T),T+=w.length}return{startPos:n,endPos:i?o:null,pid:m.pid,payload:g,randomAccessIndicator:y}}async readPacketHeader(n){let i=this.reader.requestSlice(n,4);if(i instanceof Promise&&(i=await i),!i)return null;if(oe(i)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const o=it(i),u=o>>14&1,c=o&8191,m=oe(i)>>4&3;return{payloadUnitStartIndicator:u,pid:c,adaptationFieldControl:m}}async readPacket(n){let i=this.reader.requestSlice(n,Qt);if(i instanceof Promise&&(i=await i),!i)return null;const r=fe(i,Qt);if(r[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const u=(r[1]<<8)+r[2],c=u>>14&1,d=u&8191,p=r[3]>>4&3;return{payloadUnitStartIndicator:c,pid:d,adaptationFieldControl:p,body:r.subarray(4)}}}const $a=(l,n)=>{if(l.payload.byteLength<3)return null;const i=new Me(l.payload);if(i.readBits(24)!==1)return null;const o=i.readBits(8);if(i.skipBits(16),o===188||o===190||o===191||o===240||o===241||o===255||o===242||o===248)return null;i.skipBits(8);const u=i.readBits(2);i.skipBits(14);let c=null;if(u===2||u===3)c=0,i.skipBits(4),c+=i.readBits(3)*(1<<30),i.skipBits(1),c+=i.readBits(15)*32768,i.skipBits(1),c+=i.readBits(15);else if(n)throw new Error(A0);return{sectionStartPos:l.startPos,sectionEndPos:l.endPos,pts:c,randomAccessIndicator:l.randomAccessIndicator}},ir=(l,n)=>{C(l.endPos!==null);const i=$a(l,n);if(!i)return null;const r=new Me(l.payload);r.skipBits(32);const o=r.readBits(16),u=6;r.skipBits(16);const c=r.readBits(8),d=r.pos+8*c;r.pos=d;const m=d/8;C(Number.isInteger(m));const p=l.payload.subarray(m,o>0?u+o:l.payload.byteLength);return{...i,data:p}};class bo{constructor(n){this.elementaryStream=n,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const n=this.elementaryStream.demuxer,i=this.elementaryStream.info.type;let r=0;for(const o of n.trackBackingEntries)if(o.getType()===i&&r++,C(o instanceof bo),o.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return _t}getDisposition(){return{...ea,primary:!1}}getTimeResolution(){return Wn}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(n,i,r){let o;return this.allPacketsAreKeyPackets()?o="key":o=n.randomAccessIndicator===1?"key":"delta",new dt(r.metadataOnly?Wt:n.data,o,n.pts/Wn,Math.max(i/Wn,0),n.sequenceNumber,n.data.byteLength)}async getFirstPacket(n){const i=this.elementaryStream.firstSection;C(i);const r=ir(i,!0);C(r);const o=new ks(this.elementaryStream,r),u=new Ju(this,o),c=await u.readNext();if(!c)return null;const d=this.createEncodedPacket(c.packet,c.duration,n);return this.packetBuffers.set(d,u),this.packetSectionStarts.set(d,c.packet.sectionStartPos),d}async getNextPacket(n,i){let r=this.packetBuffers.get(n);if(r){const y=await r.readNext();if(!y)return null;this.packetBuffers.delete(n);const g=this.createEncodedPacket(y.packet,y.duration,i);return this.packetBuffers.set(g,r),this.packetSectionStarts.set(g,y.packet.sectionStartPos),g}const o=this.packetSectionStarts.get(n);if(o===void 0)throw new Error("Packet was not created from this track.");const c=await this.elementaryStream.demuxer.readSection(o,!0);C(c);const d=ir(c,!0);C(d);const m=new ks(this.elementaryStream,d);r=new Ju(this,m);const p=n.sequenceNumber;for(;;){const y=await r.readNext();if(!y)return null;if(y.packet.sequenceNumber>p){const g=this.createEncodedPacket(y.packet,y.duration,i);return this.packetBuffers.set(g,r),this.packetSectionStarts.set(g,y.packet.sectionStartPos),g}}}async getNextKeyPacket(n,i){let r=n;for(;;){if(r=await this.getNextPacket(r,i),!r)return null;if(r.type==="key")return r}}getPacket(n,i){return this.doPacketLookup(n,!1,i)}getKeyPacket(n,i){return this.doPacketLookup(n,!0,i)}async doPacketLookup(n,i,r){const o=Cs(n*Wn),u=this.elementaryStream.demuxer,{reader:c,seekChunkSize:d}=u,m=this.elementaryStream.pid,p=async(D,B,z)=>{let L=D;for(;LD.pts),S=w!==-1?T[w]:null;if(S&&o-S.pts1){let z=0,L=B-1;for(D=z;z<=L;){const H=Math.floor((z+L)/2),R=Vu(H*d,u.packetStride)+g.sectionStartPos,X=R+d,W=await p(R,X,!1);if(!W){L=H-1;continue}W.pesPacketHeader.pts<=o?(D=H,z=H+1):L=H-1}}}b=Vu(D*d,u.packetStride)+g.sectionStartPos}let x=(await p(b,c.fileSize??1/0,!1))?.pesPacketHeader??null;x||(x=g);const P=this.getReorderSize(),_=async(D,B)=>{const z=await u.readSection(D,!0);C(z);const L=ir(z,!0);C(L);const H=new ks(this.elementaryStream,L),R=new Ju(this,H);for(;!((Zt(R.presentationOrderPackets)?.pts??-1/0)>=o||!await R.readNextPacket()););const X=Sf(R.presentationOrderPackets,B);if(X===-1)return null;const W=R.presentationOrderPackets[X],Z=X===0?0:W.pts-R.presentationOrderPackets[X-1].pts;for(;R.decodeOrderPackets[0]!==W;)R.decodeOrderPackets.shift();R.lastDuration=Z;const ie=await R.readNext();C(ie);const ce=this.createEncodedPacket(ie.packet,ie.duration,r);return this.packetBuffers.set(ce,R),this.packetSectionStarts.set(ce,ie.packet.sectionStartPos),ce};if(!i||this.allPacketsAreKeyPackets()){e:for(;;){let D=x.sectionStartPos+u.packetStride;for(;;){const B=await u.readPacketHeader(D);if(!B)break e;if(B.pid===m&&B.payloadUnitStartIndicator===1){const z=await u.readSection(D,!1);if(z){const L=$a(z,!1);if(L&&L.pts!==null){if(L.pts>o)break e;x=L,hf(this.elementaryStream,x);break}}}D+=u.packetStride}}e:for(let D=0;D=u.packetOffset;){const z=await u.readPacketHeader(B);if(!z)break e;if(z.pid===m&&z.payloadUnitStartIndicator===1){const L=await u.readSection(B,!1);if(L){const H=$a(L,!1);if(H&&H.pts!==null){x=H;break}}}B-=u.packetStride}}return _(x.sectionStartPos,D=>D.pts<=o)}else{let D=b,B=null;const z=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let L=null;const H=D<=g.sectionStartPos;let R,X=null;if(H)R=g,X=y;else{const ie=await p(D,c.fileSize??1/0,z);R=ie?.pesPacketHeader??null,X=ie?.section??null}let W=!1,Z=0;e:for(;R&&!(B!==null&&R.sectionStartPos>=B);){if(R.pts<=o){let ce;if(this.elementaryStream.canBeTrustedWithKeyPackets)ce=R.randomAccessIndicator===1;else{C(X);const re=ir(X,!0);C(re);const N=new ks(this.elementaryStream,re);await N.markNextPacket(),ce=N.suppliedPacket?.randomAccessIndicator===1}ce&&(L=R)}if(R.pts>o&&(W=!0),W&&(Z++,Z>P))break;let ie=R.sectionStartPos+u.packetStride;for(;;){const ce=await u.readPacketHeader(ie);if(!ce)break e;if(ce.pid===m&&ce.payloadUnitStartIndicator===1){const re=await u.readSection(ie,z);if(re){const N=$a(re,!1);if(N&&N.pts!==null){R=N,X=re,hf(this.elementaryStream,R);break}}}ie+=u.packetStride}}if(L){let ie=L;if(Z===0)e:for(let re=0;re=u.packetOffset;){const J=await u.readPacketHeader(N);if(!J)break e;if(J.pid===m&&J.payloadUnitStartIndicator===1){const ae=await u.readSection(N,z);if(ae){const Te=$a(ae,!1);if(Te&&Te.pts!==null){ie=Te;break}}}N-=u.packetStride}}const ce=await _(ie.sectionStartPos,re=>re.pts<=o&&re.randomAccessIndicator===1);return C(ce),ce}if(H)return null;B=D,D=Math.max(Vu(D-g.sectionStartPos-d,u.packetStride)+g.sectionStartPos,g.sectionStartPos)}}}}class a1 extends bo{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return C(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class i1 extends bo{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return C(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const hf=(l,n)=>{const i=l.referencePesPackets,r=Oe(i,n.sectionStartPos,o=>o.sectionStartPos);if(r>=0){const o=i[r];if(n.pts<=o.pts)return!1;const u=l.demuxer.minReferencePointByteDistance;if(n.sectionStartPos-o.sectionStartPos=n?n:this.bufferData(n-i).then(()=>Math.min(this.endPos-this.currentPos,n))}getCurrentPesPacket(){const n=this.pesPackets[this.currentPesPacketIndex];return C(n),n}async bufferData(n){const i=this.endPos+n;for(;this.endPos=g)break;b=T;const w=p+b;if(b+3>=g){this.seekTo(w);break}const S=y[b+1],E=y[b+2],x=y[b+3];let P=0;if(S===0&&E===0&&x===1?P=4:S===0&&E===1&&(P=3),P===0){b++;continue}const _=w;u??=_;const D=b+P,B=D+o,z=6;if(B+(i==="avc"?z:1)>g){this.seekTo(w);break}const H=y[D];let R,X,W;if(i==="avc")R=Pf(H),X=R===vt.NON_IDR_SLICE||R===vt.SLICE_DPA||R===vt.IDR,W=R===vt.SEI||R===vt.SPS||R===vt.PPS||R===vt.AUD;else{if(R=co(H),((H&1)<<5|y[D+1]>>3)>0){b+=P;continue}X=R<=St.RASL_R||R>=St.BLA_W_LP&&R<=21,W=R>=St.VPS_NUT&&R<=37||R===St.PREFIX_SEI_NUT||R>=41&&R<=44||R>=48&&R<=55}let Z=!1;if(X){let ie;if(i==="avc"){const ce=y.subarray(B,B+z),re=ee(new Me(ce));ie=!c||re<=d,d=re}else ie=y[B]>>7===1;ie&&(c?Z=!0:c=!0)}else W&&c&&(Z=!0);if(Z){const ie=_-u;return this.seekTo(u),this.supplyPacket(ie,0)}b+=P}if(mu){const m=this.endPos-u;return this.seekTo(u),this.supplyPacket(m,0)}}else{const i=n.info.codec,r=128;for(;;){let o=this.ensureBuffered(r);o instanceof Promise&&(o=await o);const u=this.currentPos;for(;this.currentPos-u>6,g=p[4]&63;if(y===3||g>37){this.seekTo(d+1);continue}const b=hS[3*g+y];C(b!==void 0),this.seekTo(d),m=this.ensureBuffered(b),m instanceof Promise&&(m=await m);const T=Math.round(mS*Wn/n.info.sampleRate);return this.supplyPacket(m,T)}else if(i==="eac3"){if(c!==11)continue;this.skip(-1);const d=this.currentPos;let m=this.ensureBuffered(5);if(m instanceof Promise&&(m=await m),m<5)return;const p=this.readBytes(5);if(p[0]!==11||p[1]!==119){this.seekTo(d+1);continue}const g=(((p[2]&7)<<8|p[3])+1)*2,T=p[4]>>6===3?3:p[4]>>4&3,w=u0[T];this.seekTo(d),m=this.ensureBuffered(g),m instanceof Promise&&(m=await m);const S=w*256,E=Math.round(S*Wn/n.info.sampleRate);return this.supplyPacket(m,E)}else throw new Error("Unhandled.")}if(o=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();const n=this.decodeOrderPackets[0],i=this.presentationOrderPackets.indexOf(n);C(i!==-1);let r;for(i===this.presentationOrderPackets.length-1?r=this.lastDuration:(r=this.presentationOrderPackets[i+1].pts-n.pts,this.lastDuration=r),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const o=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(o))break;this.presentationOrderPackets.shift()}return{packet:n,duration:r}}async readNextPacket(){if(this.reachedEnd)return!1;let n;return this.context.suppliedPacket?n=this.context.suppliedPacket:(await this.context.markNextPacket(),n=this.context.suppliedPacket),this.context.suppliedPacket=null,n?(this.decodeOrderPackets.push(n),this.processPacketThroughReorderBuffer(n),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){const n=this.decodeOrderPackets[0];for(C(n);;){const i=this.presentationOrderPackets.indexOf(n);if(i!==-1&&i<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(n){if(this.reorderBuffer.push(n),this.reorderBuffer.length>this.reorderSize){let i=0;for(let o=1;on.pts-i.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const P0="application/vnd.apple.mpegurl",fg="#EXT-X-STREAM-INF:",dg="#EXT-X-I-FRAME-STREAM-INF:",hg="#EXT-X-MEDIA:",mf="#EXTINF:",mg="#EXT-X-MAP:",pg="#EXT-X-KEY:",gg="#EXT-X-MEDIA-SEQUENCE:",yg="#EXT-X-BYTERANGE:",kg="#EXT-X-PROGRAM-DATE-TIME:",r1="#EXT-X-DISCONTINUITY",bg="#EXT-X-TARGETDURATION:",s1="#EXT-X-ENDLIST",Sg="#EXT-X-PLAYLIST-TYPE:",l1="#EXT-X-I-FRAMES-ONLY",B0=l=>l.length===0||l.startsWith("#")&&!l.startsWith("#EXT");class vs{constructor(n){this._attributes={};let i="",r="",o=!1,u=!1;for(let c=0;c{const n=[];if(this.trackDeclarations){for(const i of this.trackDeclarations)if(i.type==="video"){const r=ps(n,o=>o.getType()==="video")+1;n.push(new Tg(this,i,r))}else if(i.type==="audio"){const r=ps(n,o=>o.getType()==="audio")+1;n.push(new vg(this,i,r))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const r=await this.getInputForSegment(this.firstSegment).getTracks();for(const o of r)if(o.type==="video"){const u=ps(n,c=>c.getType()==="video")+1;n.push(new Tg(this,{id:n.length+1,type:"video"},u))}else if(o.type==="audio"){const u=ps(n,c=>c.getType()==="audio")+1;n.push(new vg(this,{id:n.length+1,type:"audio"},u))}}return n})()}async getFirstTimestampForInput(n){const i=this.firstTimestampCache.get(n);if(i!==void 0)return i;const r=await n.getFirstTimestamp();return this.firstTimestampCache.set(n,r),r}async getMediaOffset(n,i){const r=n.firstSegment??n;let o;if(this.firstSegmentFirstTimestamps.has(r))o=this.firstSegmentFirstTimestamps.get(r);else{const p=this.getInputForSegment(r);o=await this.getFirstTimestampForInput(p),this.firstSegmentFirstTimestamps.set(r,o)}if(r===n)return r.timestamp-o;const u=await this.getFirstTimestampForInput(i),c=n.timestamp-r.timestamp,m=u-o-c;return Math.abs(m)<=Math.min(.25,c)?r.timestamp-o:n.timestamp-u}dispose(){for(const n of this.inputCache)n.input.dispose();this.inputCache.length=0}}class D0{constructor(n,i,r){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=n,this.decl=i,this.number=r}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");const r=(await this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment).getTracks()).find(o=>o.type===this.decl.type&&o.number===this.number);if(!r)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=r})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(n){return this.firstInputTrack?n():this.hydrate().then(n)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),C(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(n){return this.segmentedInput.getUnixTimeForTimestamp(n)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(n){return this.segmentedInput.getDurationFromMetadata(n)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(n,i,r){C(n.sequenceNumber>=0),C(this.segmentedInput.firstSegment);const o=await this.segmentedInput.getMediaOffset(i,r.input),u=i.timestamp-this.segmentedInput.firstSegment.timestamp,c=n.clone({timestamp:Lg(n.timestamp+o,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*u)+n.sequenceNumber});return this.packetInfos.set(c,{segment:i,track:r,sourcePacket:n}),c}async getFirstPacket(n){await this.hydrate(),C(this.segmentedInput.firstSegment),C(this.firstInputTrack);const i=await this.firstInputTrack._backing.getFirstPacket(n);return i?this.createAdjustedPacket(i,this.segmentedInput.firstSegment,this.firstInputTrack):null}getNextPacket(n,i){return this._getNextInternal(n,i,!1)}getNextKeyPacket(n,i){return this._getNextInternal(n,i,!0)}async _getNextInternal(n,i,r){const o=this.packetInfos.get(n);if(!o)throw new Error("Packet was not created from this track.");const u=r?await o.track._backing.getNextKeyPacket(o.sourcePacket,i):await o.track._backing.getNextPacket(o.sourcePacket,i);if(u)return this.createAdjustedPacket(u,o.segment,o.track);let c=o.segment;for(;;){const d=await this.segmentedInput.getNextSegment(c,{skipLiveWait:i.skipLiveWait});if(!d)return null;const y=(await this.segmentedInput.getInputForSegment(d).getTracks()).find(b=>b.type===o.track.type&&b.number===o.track.number);if(!y){c=d;continue}const g=await y._backing.getFirstPacket(i);return g?this.createAdjustedPacket(g,d,y):null}}getPacket(n,i){return this._getPacketInternal(n,i,!1)}getKeyPacket(n,i){return this._getPacketInternal(n,i,!0)}async _getPacketInternal(n,i,r){let o=await this.segmentedInput.getSegmentAt(n,{skipLiveWait:i.skipLiveWait});if(!o)return null;for(await this.hydrate();o;){const u=this.segmentedInput.getInputForSegment(o),d=(await u.getTracks()).find(g=>g.type===this.firstInputTrack.type&&g.number===this.firstInputTrack.number);if(!d){o=await this.segmentedInput.getPreviousSegment(o,{skipLiveWait:i.skipLiveWait});continue}const m=await this.segmentedInput.getMediaOffset(o,u),p=n-m,y=r?await d._backing.getKeyPacket(p,i):await d._backing.getPacket(p,i);if(!y){o=await this.segmentedInput.getPreviousSegment(o,{skipLiveWait:i.skipLiveWait});continue}return this.createAdjustedPacket(y,o,d)}return null}}class Tg extends D0{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class vg extends D0{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}Tf();const I0=0,R0=1/0;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(l=>{l()});class _n extends wf{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<"u"&&(this._refFinalizationRegistry=new FinalizationRegistry(n=>{n._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new Ct;return this._sizePromise??=(async()=>{let n=this._getFileSize();return n!==void 0||(await this._read(0,1,I0,R0),n=this._getFileSize(),C(n!==void 0)),n})()}async getSize(){if(this._disposed)throw new Ct;const n=await this.getSizeOrNull();if(n===null)throw new Error("Cannot determine the size of an unsized source.");return n}slice(n,i){if(!Number.isInteger(n)||n<0)throw new TypeError("offset must be a non-negative integer.");if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new m1(this,n,i)}_dispatchRead(n,i){this.onread?.(n,i),this._emit("read",{start:n,end:i})}ref(){return new Rf(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}}class Rf{constructor(n){if(this._freed=!1,n._disposed)throw new Error("Cannot ref a disposed source.");n._incrementRefCount(),n._refFinalizationRegistry?.register(this,n,this),this._source=n}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const n=this.source;C(n._refCount>0),n._decrementRefCount(),n._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class Ds extends _n{constructor(n,i){if(typeof n!="string")throw new TypeError("rootPath must be a string.");if(typeof i!="function")throw new TypeError("requestHandler must be a function.");super(),this.rootPath=n,this.requestHandler=i}_resolveRequest(n){const i=this.requestHandler(n),r=o=>{if(!(o instanceof _n||o instanceof Rf))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const u=o instanceof _n?o.ref():o;return u.source._usedForHls||=this._usedForHls,u};return i instanceof Promise?i.then(r):r(i)}}const wg=(l,n)=>l.path===n.path;class c1 extends Ds{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(n,i,r,o){if(!this._root){if(!this._rootRequest){const u=this._resolveRequest({path:this.rootPath,isRoot:!0}),c=d=>{const m=d instanceof _n?d.ref():d;return this._root=m,this._rootRequest=null,m};u instanceof Promise?this._rootRequest=u.then(c):(c(u),C(this._root))}if(this._rootRequest)return this._rootRequest.then(u=>u.source._read(n,i,r,o))}return this._root.source._read(n,i,r,o)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(n=>n.free())}}class u1 extends _n{constructor(n,i={}){if(!(n instanceof Blob))throw new TypeError("blob must be a Blob.");if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.maxCacheSize!==void 0&&(!vf(i.maxCacheSize)||i.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(i.useStreamReader!==void 0&&typeof i.useStreamReader!="boolean")throw new TypeError("options.useStreamReader, when provided, must be a boolean.");super(),this._readers=new WeakMap,this._blob=n,this._options=i,this._orchestrator=new h1({maxCacheSize:i.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:d1.fileSystem}),this._orchestrator.fileSize=n.size}_getFileSize(){return this._orchestrator.fileSize}_read(n,i,r,o){return this._orchestrator.read(n,i,r,o)}async _runWorker(n){C(n.strictTarget);let i=this._readers.get(n);for(i===void 0&&("stream"in this._blob&&!jg()&&this._options.useStreamReader!==!1?i=this._blob.slice(n.currentPos).stream().getReader():i=null,this._readers.set(n,i));n.currentPosthis._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,i);const r=Oe(this._cache,n,y=>y.start),o=r!==-1?this._cache[r]:null;if(o&&o.start<=n&&i<=o.end)return{bytes:o.bytes,view:o.view,offset:o.start};let u=n;const c=new Uint8Array(i-n);if(r!==-1)for(let y=r;y=i)break;const b=Math.max(n,g.start);b>u&&this._throwDueToCacheMiss();const T=Math.min(i,g.end);bu&&this._throwDueToCacheMiss();const{promise:d,resolve:m,reject:p}=zt();return this._pendingSlices.push({start:n,end:i,bytes:c,resolve:m,reject:p}),this._targetIndex=Math.max(this._targetIndex,i),this._pulling||(this._pulling=!0,this._pull().catch(y=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(g=>g.reject(y)),this._pendingSlices.length=0;else throw y})),d}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex0;){const u=this._cache[0];if(this._maxRequestedIndex-u.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=i.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const d1={fileSystem:(l,n)=>(l=Math.floor((l-65536)/65536)*65536,n=Math.ceil((n+65536)/65536)*65536,{start:l,end:n})};class h1{constructor(n){this.options=n,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(n,i,r,o){C(!this.disposed);const u=this.options.prefetchProfile(n,i,this.workers),c=Math.max(u.start,r),d=Math.min(u.end,this.fileSize??1/0,o);C(c<=n&&i<=d);let m=null;const p=Oe(this.cache,n,B=>B.start),y=p!==-1?this.cache[p]:null;y&&y.start<=n&&i<=y.end&&(y.age=this.nextAge++,m={bytes:y.bytes,view:y.view,offset:y.start});const g=Oe(this.cache,c,B=>B.start),b=m?null:new Uint8Array(i-n);let T=0,w=c;const S=[];if(g!==-1){for(let B=g;B=d)break;if(z.end<=c)continue;const L=Math.max(c,z.start),H=Math.min(d,z.end);if(C(L<=H),w=b.length&&(m={bytes:b,view:Re(b),offset:n}),S.length===0)return C(m),m;const{promise:E,resolve:x,reject:P}=zt(),_=[];for(const B of S){const z=Math.max(n,B.start),L=Math.min(i,B.end);z===B.start&&L===B.end?_.push(B):zX.hole.start),R=H!==-1?this.queuedReads[H]:null;for(R&&B.start<=R.hole.end?(R.hole.end=Math.max(R.hole.end,B.end),R.strictTarget&&=z,D&&R.pendingSlices.push(D)):(H++,R={hole:{start:B.start,end:B.end},strictTarget:z,pendingSlices:D?[D]:[],age:this.nextAge++},this.queuedReads.splice(H,0,R));H+1R.hole.end)break;R.hole.end=Math.max(R.hole.end,X.hole.end),R.pendingSlices.push(...X.pendingSlices),R.strictTarget&&=X.strictTarget,R.age=Math.min(R.age,X.age),this.queuedReads.splice(H+1,1)}}}return m?E.catch(B=>{if(!this.disposed)throw B}):(C(b),m=E.then(B=>B&&{bytes:B,view:Re(B),offset:n})),m}checkHoleAgainstWorker(n,i,r){if(Kp(i.start-131072,i.start,n.currentPos,n.targetPos)){n.targetPos=Math.max(n.targetPos,i.end);for(let u=0;u=this.options.maxWorkerCount){let u=null,c=null;for(let d=0;d{if(n.running=!1,n.pendingSlices.length>0)n.pendingSlices.forEach(r=>r.reject(i)),n.pendingSlices.length=0;else if(!n.aborted&&!this.disposed)throw i}).finally(()=>{if(!n.running&&this.queuedReads.length>0){let i=0;for(let u=1;un.targetPos&&(n.targetPos=n.currentPos,this.checkQueuedReadsAgainstWorker(n));for(let u=0;uy.start&&(y.start=o),y.end<=y.start&&(c.holes.splice(p,1),p--)}c.holes.length===0&&(c.resolve(c.bytes),n.pendingSlices.splice(u,1),u--)}for(let u=0;un){o.resolve(null),i.pendingSlices.splice(r,1),r--;break}}}for(let i=0;i=n){for(const o of r.pendingSlices)o.resolve(null);this.queuedReads.splice(i,1),i--}else if(r.hole.end>n){r.hole.end=n,r.strictTarget=!0;for(let o=0;o=n&&(u.resolve(null),r.pendingSlices.splice(o,1),o--)}}}}signalWorkerStoppedRunning(n){n.running=!1,n.pendingSlices.length=0}onWorkerFinished(n){const i=this.workers.indexOf(n);C(i!==-1),n.running=!1,this.workers.splice(i,1),this.fileSize===null&&this.supplyFileSize(n.currentPos);for(const r of n.pendingSlices)r.resolve(null)}insertIntoCache(n){if(this.options.maxCacheSize===0)return;let i=Oe(this.cache,n.start,r=>r.start)+1;if(i>0){const r=this.cache[i-1];if(r.end>=n.end)return;if(r.end>n.start){const o=new Uint8Array(n.end-r.start);o.set(r.bytes,0),o.set(n.bytes,n.start-r.start),this.currentCacheSize+=n.end-r.end,r.bytes=o,r.view=Re(o),r.end=n.end,i--,n=r}else this.cache.splice(i,0,n),this.currentCacheSize+=n.bytes.length}else this.cache.splice(i,0,n),this.currentCacheSize+=n.bytes.length;for(let r=i+1;r=o.end){this.cache.splice(r,1),this.currentCacheSize-=o.bytes.length,r--;continue}const u=new Uint8Array(o.end-n.start);u.set(n.bytes,0),u.set(o.bytes,o.start-n.start),this.currentCacheSize-=n.end-o.start,n.bytes=u,n.view=Re(u),n.end=o.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let r=0,o=this.cache[0];for(let u=1;uthis._length)return null;const u=this._baseSource._read(this._offset+n,this._offset+i,this._offset+r,this._offset+o),c=d=>d?(d.offset-=this._offset,d):null;return u instanceof Promise?u.then(c):c(u)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}}var xg=function(l,n,i){if(n!=null){if(typeof n!="object"&&typeof n!="function")throw new TypeError("Object expected.");var r,o;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=n[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=n[Symbol.dispose],i&&(o=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");o&&(r=function(){try{o.call(this)}catch(u){return Promise.reject(u)}}),l.stack.push({value:n,dispose:r,async:i})}else i&&l.stack.push({async:!0});return n},Cg=(function(l){return function(n){function i(c){n.error=n.hasError?new l(c,n.error,"An error was suppressed during disposal."):c,n.hasError=!0}var r,o=0;function u(){for(;r=n.stack.pop();)try{if(!r.async&&o===1)return o=0,n.stack.push(r),Promise.resolve().then(u);if(r.dispose){var c=r.dispose.call(r.value);if(r.async)return o|=2,Promise.resolve(c).then(u,function(d){return i(d),u()})}else o|=1}catch(d){i(d)}if(o===1)return n.hasError?Promise.reject(n.error):Promise.resolve();if(n.hasError)throw n.error}return u()}})(typeof SuppressedError=="function"?SuppressedError:function(l,n,i){var r=new Error(i);return r.name="SuppressedError",r.error=l,r.suppressed=n,r});const p1=/^0[xX][0-9a-fA-F]+$/,g1=/^data:.*;base64,/i;class _g extends o1{constructor(n,i,r,o){super(n.input,i,r),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=i,this.demuxer=n,this.nextLines=o}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{const n=this.getRemainingWaitTimeMs();n>0&&await Kb(n),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){const n=performance.now()-this.lastSegmentUpdateTime,i=Math.max(0,1e3*this.refreshInterval-n);return i<=50?0:i}async updateSegments(){let n=this.nextLines;if(this.nextLines=null,!n){const _={stack:[],error:void 0,hasError:!1};try{const D=xg(_,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),z=await new no(D.source).requestEntireFile();C(z),n=K0(z,z.length,{ignore:B0}),D.source instanceof Ds&&(this.rootPath=D.source.rootPath)}catch(D){_.error=D,_.hasError=!0}finally{Cg(_)}}const i=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1;let r=!1,o=0,u=null,c=null,d=null,m=0,p=null,y=null,g=null,b=null,T=null,w=null,S=!1,E=Zt(this.segments)??null;const x=_=>{const D=_.indexOf("@"),B=Number(D===-1?_:_.slice(0,D));if(!Number.isInteger(B)||B<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${_}'.`);let z=null;if(D!==-1&&(z=Number(_.slice(D+1)),!Number.isInteger(z)||z<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${_}'.`);return{length:B,offset:z}},P=_=>{m=_,E&&(C(E.sequenceNumber!==null),E.sequenceNumber<_&&(o=E.timestamp+E.duration,p=E.firstSegment,y=E.initSegment,T=E.lastProgramDateTimeSeconds,u=E.unixEpochTimestamp!==null?E.unixEpochTimestamp+E.duration:null,E=null))};for(let _=0;_0&&w!==null&&(o=m*w),S=!0);const B=D.slice(mf.length),z=B.indexOf(","),L=z===-1?B:B.slice(0,z),H=Number(L);if(!Number.isFinite(H)||H<0)throw new Error(`Invalid #EXTINF tag duration '${L}'.`);c=H}else if(D.startsWith(mg)){const B=new vs(D.slice(mg.length)),z=B.get("uri");if(!z)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const L=B.get("byterange");let H=null;if(L!==null&&(H=x(L)),H&&H.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!E){const X={path:Ba(this.rootPath,z),offset:H?.offset??0,length:H?.length??null};if(d?.method==="AES-128"&&!d.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");y={timestamp:o,unixEpochTimestamp:u,firstSegment:null,sequenceNumber:null,location:X,duration:0,encryption:d,initSegment:null,lastProgramDateTimeSeconds:T}}c=null,b===null?g=null:b=null}else if(D.startsWith(pg)){const B=new vs(D.slice(pg.length)),z=B.get("method");if(z==="NONE")d=null;else if(z==="AES-128"){const L=B.get("uri");if(!L)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let H=null;const R=B.get("iv");if(R){if(!p1.test(R))throw new Error(`Unsupported IV format '${R}'.`);let W=R.slice(2);W=W.padStart(xn*2,"0"),H=new Uint8Array(xn);for(let Z=0;Z=8&&W[4]===112&&W[5]===115&&W[6]===115&&W[7]===104){const Z=Re(W).getUint32(0);R=h0(W.subarray(8,Math.min(Z,W.length)))}}d={method:z,psshBox:R}}else throw new Error(`Unsupported encryption method '${z}'. If you think this method should be supported, please raise an issue.`)}else if(D.startsWith(gg)){const B=D.slice(gg.length),z=Number(B);if(!Number.isInteger(z)||z<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${B}'.`);P(z)}else if(D.startsWith(yg)){const B=x(D.slice(yg.length));if(B.offset===null){if(g===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");B.offset=g}b=B,g=B.offset+B.length}else if(D.startsWith(kg)){if(E)continue;const B=D.slice(kg.length),z=Date.parse(B);if(!Number.isFinite(z))continue;const L=z/1e3;if(T===L)continue;if(T===null&&this.segments.length>0){const H=Zt(this.segments),R=H.timestamp+H.duration,X=L-R;for(const W of this.segments)W.unixEpochTimestamp=W.timestamp+X,i&&(W.timestamp=W.unixEpochTimestamp)}T=L,u=L,i&&(o=L)}else if(D===r1)p=null;else if(D.startsWith(bg)){const B=D.slice(bg.length),z=Number(B);if(!Number.isFinite(z)||z<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${B}'.`);this.refreshInterval=z,w=z}else if(D===s1){this.streamHasEnded=!0;break}else D.startsWith(Sg)&&D.slice(Sg.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!r)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(n,i){this.segments.length===0&&await this.runUpdateSegments();let r=!!i.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const o=Oe(this.segments,n,c=>c.timestamp);if(o===-1)return null;if(o0;for(;;){if(om.segment===i);if(r)return r.age=this.nextInputCacheAge++,r.input;let o=null;(i.initSegment||i.firstSegment)&&(o=this.getInputForSegment(i.initSegment??i.firstSegment));const u={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(m=>{if(!i.encryption||!(i.encryption.method==="SAMPLE-AES"||i.encryption.method==="SAMPLE-AES-CTR")||!i.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(m);let p=m.psshBoxes;const{psshBox:y}=i.encryption;return(y.keyIds===null||y.keyIds.includes(m.keyId))&&!p.some(g=>m0(g,y))&&(p=[...p,y]),this.input._formatOptions.isobmff.resolveKeyId({...m,psshBoxes:p})})}},c=new To({source:new c1(i.location.path,async m=>{C(m.isRoot);const p={...m,isRoot:!1};let y;const g=i.location.offset>0||i.location.length!==null;if(!i.encryption||i.encryption.method==="SAMPLE-AES"||i.encryption.method==="SAMPLE-AES-CTR"){if(y=await this.input._getSourceCached(p),g){const T=y.source.slice(i.location.offset,i.location.length??void 0).ref();y.free(),y=T}}else if(i.encryption.method==="AES-128"){const b=i.encryption;C(b.iv);let T=await this.input._getSourceCached(p);if(g){const x=T.source.slice(i.location.offset,i.location.length??void 0).ref();T.free(),T=x}const w=new no(T.source),S=SS(w,async()=>{const E={stack:[],error:void 0,hasError:!1};try{const x=xg(E,await this.input._getSourceCached({path:b.keyUri,isRoot:!1},W1),!1),_=await new no(x.source).requestSlice(0,xn);if(!_)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:fe(_,xn),iv:b.iv}}catch(x){E.error=x,E.hasError=!0}finally{Cg(E)}},()=>{T.free()});y=new f1(S).ref()}else C(!1);return y}),formats:this.input._formats.filter(m=>!(m instanceof F0)),initInput:o??void 0,formatOptions:u});if(c._onFormatDetermined=m=>{if((i.encryption?.method==="SAMPLE-AES"||i.encryption?.method==="SAMPLE-AES-CTR")&&!m._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:i,input:c,age:this.nextInputCacheAge++}),this.inputCache.length>4){const m=Gg(this.inputCache,p=>p.age);C(m!==-1),this.inputCache.splice(m,1)}return c}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class y1 extends ta{constructor(n){super(n),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{C(this.input._rootSource instanceof Ds);const n=await this.input._reader.requestEntireFile();C(n);const i=K0(n,n.length,{ignore:B0}),{rootPath:r}=this.input._rootSource,o=[],u=[];for(let g=1;gg.attributes.get("type").toLowerCase()==="video").map(g=>g.attributes.get("group-id")))],d=[...new Set(u.filter(g=>g.attributes.get("type").toLowerCase()==="audio").map(g=>g.attributes.get("group-id")))],m=await Promise.all(o.map(async(g,b)=>{const T=[],w=g.attributes.get("codecs");let S;if(w)S=w.split(",").map(R=>R.trim());else{const X=await this.getSegmentedInputForPath(g.fullPath).getTrackBackings(),W=await Promise.all(X.map(async Z=>({track:Z,codec:await Z.getCodec()})));S=await Promise.all(W.filter(Z=>Z.codec!==null).map(Z=>Z.track.getDecoderConfig().then(ie=>ie.codec)))}const E=g.attributes.get("video"),x=g.attributes.get("audio"),P=S.some(R=>Qp.includes(bs(R))),_=S.some(R=>Zp.includes(bs(R)));if(E!==null&&!P){if(!c.includes(E))throw new Error(`Invalid M3U8 file; variant stream references video group "${E}" which is not defined in any #EXT-X-MEDIA tags.`);const R=u.find(X=>{const W=X.attributes.get("group-id"),Z=X.attributes.get("type");return W===E&&Z.toLowerCase()==="video"});e:if(R){const X=R.attributes.get("uri");if(X===null)break e;const W=Ba(r,X),ce=(await this.getSegmentedInputForPath(W).getTrackBackings()).find(N=>N.getType()==="video");if(!ce||await ce.getCodec()===null)break e;const re=await ce.getDecoderConfig().then(N=>N?.codec??null);C(re!==null),S.push(re)}}if(x!==null&&!_){if(!d.includes(x))throw new Error(`Invalid M3U8 file; variant stream references audio group "${x}" which is not defined in any #EXT-X-MEDIA tags.`);const R=u.find(X=>{const W=X.attributes.get("group-id"),Z=X.attributes.get("type");return W===x&&Z.toLowerCase()==="audio"});e:if(R){const X=R.attributes.get("uri");if(X===null)break e;const W=Ba(r,X),ce=(await this.getSegmentedInputForPath(W).getTrackBackings()).find(N=>N.getType()==="audio");if(!ce||await ce.getCodec()===null)break e;const re=await ce.getDecoderConfig().then(N=>N?.codec??null);C(re!==null),S.push(re)}}S=[...new Set(S)];let D=null,B=null;const z=g.attributes.getAsNumber("bandwidth");C(z!==null);const L=g.attributes.getAsNumber("average-bandwidth"),H=g.attributes.get("name");for(const R of S){const X=bs(R);if(X!==null){if(Qp.includes(X)){if(D!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");D=R;const W=g.attributes.get("video");if(W===null){const Z=g.attributes.get("resolution");let ie=null,ce=null;if(Z){const re=Z.match(/^(\d+)x(\d+)$/);re&&(ie=Number(re[1]),ce=Number(re[2]))}T.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:_t,lineNumber:g.lineNumber,fullPath:g.fullPath,fullCodecString:D,pairingMask:1n<0?ie:null}})}else{if(!d.includes(W))throw new Error(`Invalid M3U8 file; variant stream references audio group "${W}" which is not defined in any #EXT-X-MEDIA tags.`);for(const Z of u){const ie=Z.attributes.get("group-id"),ce=Z.attributes.get("type");if(ie!==W||ce.toLowerCase()!=="audio")continue;const re=Z.attributes.get("channels")??g.attributes.get("channels"),N=re!==null?Number(re.split("/")[0]):null;T.push({id:-1,demuxer:this,backingTrack:null,default:Zl(Z.attributes),autoselect:Zl(Z.attributes)||Eg(Z.attributes),languageCode:Ag(Z.attributes.get("language")),lineNumber:Z.lineNumber,fullPath:Z.fullPath??g.fullPath,fullCodecString:B,pairingMask:1n<0?N:null}})}}}}}return T})),p=[],y=g=>{const b=p.find(T=>T.fullPath===g.fullPath&&T.info.type===g.info.type);b?(b.pairingMask|=g.pairingMask,b.default||=g.default,b.autoselect||=g.autoselect,b.lineNumber=Math.min(b.lineNumber,g.lineNumber),g.peakBitrate!==null&&(b.peakBitrate=Math.max(b.peakBitrate??-1/0,g.peakBitrate)),g.averageBitrate!==null&&(b.averageBitrate=Math.max(b.averageBitrate??-1/0,g.averageBitrate)),b.languageCode===_t&&(b.languageCode=g.languageCode)):(g.id=p.length+1,p.push(g))};for(const g of m)for(const b of g)y(b);p.sort((g,b)=>g.lineNumber-b.lineNumber),this.trackBackings=[];for(const g of p)g.info.type==="video"?this.trackBackings.push(new z0(g)):this.trackBackings.push(new M0(g));this.internalTracks=p})()}async getTrackBackings(){return await this.readMetadata(),C(this.trackBackings),this.trackBackings}getSegmentedInputForPath(n){let i=this.segmentedInputs.find(o=>o.path===n);if(i)return i;let r=null;return this.internalTracks&&(r=this.internalTracks.filter(u=>u.fullPath===n).map(u=>({id:u.id,type:u.info.type}))),i=new _g(this,n,r,null),this.segmentedInputs.push(i),i}async getMetadataTags(){return{}}async getMimeType(){return P0}dispose(){if(this.segmentedInputs){for(const n of this.segmentedInputs)n.dispose();this.segmentedInputs.length=0}}}class O0{constructor(n){this.internalTrack=n,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{const n=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let i=null;const o=(await n.getTrackBackings()).filter(u=>u.getType()===this.getType());if(o.length===1)i=o[0];else if(this instanceof z0){for(const u of o)if(await u.getCodec()===this.getCodec()){i=u;break}}else{C(this instanceof M0);for(const u of o)if(await u.getCodec()===this.getCodec()){i=u;break}}if(!i)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=i})()}delegate(n){return this.internalTrack.backingTrack?n():this.hydrate().then(n)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...ea,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){C(this.internalTrack.demuxer.internalTracks);const n=this.internalTrack.info.type;let i=0;for(const r of this.internalTrack.demuxer.internalTracks)if(r.info.type===n&&i++,r===this.internalTrack)break;return i}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(n){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(n))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(n){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(n)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(n){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(n)}async getPacket(n,i){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(n,i)}async getKeyPacket(n,i){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(n,i)}async getNextPacket(n,i){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(n,i)}async getNextKeyPacket(n,i){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(n,i)}}class z0 extends O0{constructor(n){super(n)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return bs(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class M0 extends O0{constructor(n){super(n)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return bs(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}const Zl=l=>{const n=l.get("default");if(n===null)return!1;const i=n.toUpperCase();if(i==="YES")return!0;if(i==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${n}".`)},Eg=l=>{const n=l.get("autoselect");if(n===null)return!1;const i=n.toUpperCase();if(i==="YES")return!0;if(i==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${n}".`)},Ag=l=>{if(l===null)return _t;const n=l.split("-")[0];return n||_t};class En{constructor(){this._isIsobmff=!1}}class N0 extends En{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(n){let i=n._reader.requestSlice(0,12);if(i instanceof Promise&&(i=await i),!i)return null;i.skip(4);const r=Je(i,4);return r!=="ftyp"&&r!=="styp"?null:Je(i,4)}_createDemuxer(n){return new Df(n)}}class k1 extends N0{async _canReadInput(n){const i=await this._getMajorBrand(n);if(i!==null)return i!=="qt ";let r=n._reader.requestSlice(4,4);if(r instanceof Promise&&(r=await r),!r)return!1;const o=Je(r,4);return o==="moof"||o==="sidx"}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class b1 extends N0{async _canReadInput(n){return await this._getMajorBrand(n)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class U0 extends En{async isSupportedEBMLOfDocType(n,i){let r=n._reader.requestSlice(0,Zn);if(r instanceof Promise&&(r=await r),!r)return!1;const o=T0(r);if(o===null||o<1||o>8||ve(r,o)!==K.EBML)return!1;const c=v0(r);if(typeof c!="number")return!1;let d=n._reader.requestSlice(r.filePos,c);if(d instanceof Promise&&(d=await d),!d)return!1;const m=r.filePos;for(;d.filePos<=m+c-fn;){const p=Qn(d);if(!p)break;const{id:y,size:g}=p,b=d.filePos;if(g===void 0)return!1;switch(y){case K.EBMLVersion:if(ve(d,g)!==1)return!1;break;case K.EBMLReadVersion:if(ve(d,g)!==1)return!1;break;case K.DocType:if(nr(d,g)!==i)return!1;break;case K.DocTypeVersion:if(ve(d,g)>4)return!1;break}d.filePos=b+g}return!0}_canReadInput(n){return this.isSupportedEBMLOfDocType(n,"matroska")}_createDemuxer(n){return new BS(n)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class S1 extends U0{_canReadInput(n){return this.isSupportedEBMLOfDocType(n,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class T1 extends En{async _canReadInput(n){let i=0;for(;;){let g=n._reader.requestSlice(i,dn);if(g instanceof Promise&&(g=await g),!g)break;const b=$n(g);if(!b)break;i=g.filePos+b.size}const r=await ff(n._reader,i,i+4096);if(!r)return!1;const o=r.header,u=Jg(o.mpegVersionId,o.channel);let c=n._reader.requestSlice(r.startPos+u,4);if(c instanceof Promise&&(c=await c),!c)return!1;const d=$(c);if(d===Zg||d===Wg)return!0;i=r.startPos+r.header.totalSize;const p=await ff(n._reader,i,i+ri);if(!p)return!1;const y=p.header;return!(o.channel!==y.channel||o.sampleRate!==y.sampleRate)}_createDemuxer(n){return new RS(n)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class v1 extends En{async _canReadInput(n){let i=n._reader.requestSlice(0,12);if(i instanceof Promise&&(i=await i),!i)return!1;const r=Je(i,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?!1:(i.skip(4),Je(i,4)==="WAVE")}_createDemuxer(n){return new VS(n)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class w1 extends En{async _canReadInput(n){let i=n._reader.requestSlice(0,4);return i instanceof Promise&&(i=await i),i?Je(i,4)==="OggS":!1}_createDemuxer(n){return new HS(n)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class x1 extends En{async _canReadInput(n){let i=0;for(;;){let o=n._reader.requestSlice(i,dn);if(o instanceof Promise&&(o=await o),!o)break;const u=$n(o);if(!u)break;i=o.filePos+u.size}let r=n._reader.requestSlice(i,4);return r instanceof Promise&&(r=await r),r?Je(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(n){return new $S(n)}}class C1 extends En{async _canReadInput(n){let i=0;for(;;){let c=n._reader.requestSlice(i,dn);if(c instanceof Promise&&(c=await c),!c)break;const d=$n(c);if(!d)break;i=c.filePos+d.size}let r=n._reader.requestSliceRange(i,df,fr);if(r instanceof Promise&&(r=await r),!r)return!1;const o=Ps(r);if(!o||(i+=o.frameLength,r=n._reader.requestSliceRange(i,df,fr),r instanceof Promise&&(r=await r),!r))return!1;const u=Ps(r);return u?o.objectType===u.objectType&&o.samplingFrequencyIndex===u.samplingFrequencyIndex&&o.channelConfiguration===u.channelConfiguration:!1}_createDemuxer(n){return new XS(n)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class _1 extends En{async _canReadInput(n){const i=Qt+16+1;let r=n._reader.requestSlice(0,i);if(r instanceof Promise&&(r=await r),!r)return!1;const o=fe(r,i);return o[0]===71&&o[Qt]===71||o[0]===71&&o[Qt+16]===71?!0:o[4]===71&&o[4+Qt+4]===71}_createDemuxer(n){return new n1(n)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class F0 extends En{async _canReadInput(n){let i=n._reader.requestSlice(0,7);if(i instanceof Promise&&(i=await i),!i||!(Je(i,7)==="#EXTM3U"))return!1;if(!(n._rootSource instanceof Ds))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return n._rootSource._usedForHls=!0,!0}_createDemuxer(n){return new y1(n)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return P0}}const E1=new k1,A1=new b1,P1=new U0,B1=new S1,D1=new T1,I1=new v1,R1=new w1,O1=new C1,z1=new x1,M1=new _1,N1=new F0,U1=[N1,E1,A1,P1,B1,I1,R1,z1,D1,O1,M1],F1=(l,n)=>{if(!l||typeof l!="object")throw new TypeError(`${n}, when provided, must be an object.`);if(l.isobmff!==void 0){if(!l.isobmff||typeof l.isobmff!="object")throw new TypeError(`${n}.isobmff, when provided, must be an object.`);if(l.isobmff.resolveKeyId!==void 0&&typeof l.isobmff.resolveKeyId!="function")throw new TypeError(`${n}.isobmff.resolveKeyId, when provided, must be a function.`)}if(l.hls!==void 0){if(!l.hls||typeof l.hls!="object")throw new TypeError(`${n}.hls, when provided, must be an object.`);if(l.hls.offsetTimestampsByDateTime!==void 0&&typeof l.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${n}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};Tf();let Pg=-1/0,Bg=-1/0,pf=null;typeof FinalizationRegistry<"u"&&(pf=new FinalizationRegistry(l=>{const n=performance.now();l.type==="video"?(n-Pg>=1e3&&(ke._error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Pg=n),typeof VideoFrame<"u"&&l.data instanceof VideoFrame&&l.data.close()):(n-Bg>=1e3&&(ke._error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Bg=n),typeof AudioData<"u"&&l.data instanceof AudioData&&l.data.close())}));const q1=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"];new Set(q1);const Wl=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class cs{constructor(){this._referenceCount=0}}class Cn{get microsecondTimestamp(){return Math.trunc(lo*this.timestamp)}get microsecondDuration(){return Math.trunc(lo*this.duration)}constructor(n){if(this._closed=!1,us(n)){if(n.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=n,this.format=n.format,this.sampleRate=n.sampleRate,this.numberOfFrames=n.numberOfFrames,this.numberOfChannels=n.numberOfChannels,this.timestamp=n.timestamp/1e6,this.duration=n.numberOfFrames/n.sampleRate}else if(n instanceof cs){if(this._data=n,n._referenceCount++,this.format=n.getFormat(),!Wl.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=n.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=n.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=n.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=n.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!n||typeof n!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Wl.has(n.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(n.sampleRate)||n.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(n.numberOfChannels)||n.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(n?.timestamp))throw new TypeError("init.timestamp must be a number.");const i=n.data.byteLength/(Pa(n.format)*n.numberOfChannels);if(!Number.isInteger(i))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=n.format,this.sampleRate=n.sampleRate,this.numberOfFrames=i,this.numberOfChannels=n.numberOfChannels,this.timestamp=n.timestamp,this.duration=i/n.sampleRate;let r;if(n.data instanceof ArrayBuffer)r=new Uint8Array(n.data);else if(ArrayBuffer.isView(n.data))r=new Uint8Array(n.data.buffer,n.data.byteOffset,n.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const o=this.numberOfFrames*this.numberOfChannels*Pa(this.format);if(r.byteLength=this.numberOfFrames)throw new RangeError("frameOffset out of range");const o=n.frameCount!==void 0?n.frameCount:this.numberOfFrames-r;if(o>this.numberOfFrames-r)throw new RangeError("frameCount out of range");const u=Pa(i),c=ei(i);if(c&&n.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!c&&n.planeIndex!==0)throw new RangeError("planeIndex out of range");return(c?o:o*this.numberOfChannels)*u}copyTo(n,i){if(!Rb(n))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(i.planeIndex)||i.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(i.format!==void 0&&!Wl.has(i.format))throw new TypeError("Invalid format.");if(i.frameOffset!==void 0&&(!Number.isInteger(i.frameOffset)||i.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(i.frameCount!==void 0&&(!Number.isInteger(i.frameCount)||i.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:r,frameCount:o,frameOffset:u}=i;let{planeIndex:c}=i;const d=this.format,m=r??this.format;if(!m)throw new Error("Destination format not determined");const p=this.numberOfFrames,y=this.numberOfChannels,g=u??0;if(g>=p)throw new RangeError("frameOffset out of range");const b=o!==void 0?o:p-g;if(b>p-g)throw new RangeError("frameCount out of range");const T=Pa(m),w=ei(m);if(w&&c>=y)throw new RangeError("planeIndex out of range");if(!w&&c!==0)throw new RangeError("planeIndex out of range");const E=(w?b:b*y)*T;if(n.byteLength2&&m!==d?H1(this._data,x,d,m,y,c,g,b):this._data.copyTo(n,{planeIndex:c,frameOffset:g,frameCount:b,format:m});else{const _=q0(d),D=Pa(d),B=ei(d);let z;if(this._data instanceof cs){const H=R=>{const X=this._data.getDataPlane(R);if(!(X instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const W=p*D*(B?1:y);if(X.byteLength!==W)throw new TypeError(`Data plane ${R} has invalid size. Expected exactly ${W} bytes, got ${X.byteLength} bytes.`);return X};if(B)if(w)z=H(c),c=0;else{z=new Uint8Array(p*D*y);for(let R=0;Rthis.numberOfFrames)throw new RangeError("startSample out of range.");if(i>this.numberOfFrames)throw new RangeError("endSample out of range.");if(i0)for(let d=0;d0&&this.copyTo(u,{planeIndex:0,format:this.format,frameOffset:n,frameCount:r});return new Cn({data:u,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+n/this.sampleRate})}close(){this._closed||(pf?.unregister(this),this._data instanceof cs?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):us(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof cs?this._createAudioDataFromData():us(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(ei(this.format)){const n=this.allocationSize({planeIndex:0,format:this.format}),i=new ArrayBuffer(n*this.numberOfChannels);for(let r=0;r0;){const y=Math.min(d,p),g=new Float32Array(o*y);for(let b=0;b0;){const g=Math.min(d,p),b=new Float32Array(o*g);for(let w=0;w{switch(l){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},ei=l=>{switch(l){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},q0=l=>{switch(l){case"u8":case"u8-planar":return(n,i)=>(n.getUint8(i)-128)/128;case"s16":case"s16-planar":return(n,i)=>n.getInt16(i,!0)/32768;case"s32":case"s32-planar":return(n,i)=>n.getInt32(i,!0)/2147483648;case"f32":case"f32-planar":return(n,i)=>n.getFloat32(i,!0)}},H0=l=>{switch(l){case"u8":case"u8-planar":return(n,i,r)=>n.setUint8(i,or((r+1)*127.5,0,255));case"s16":case"s16-planar":return(n,i,r)=>n.setInt16(i,or(Math.round(r*32767),-32768,32767),!0);case"s32":case"s32-planar":return(n,i,r)=>n.setInt32(i,or(Math.round(r*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(n,i,r)=>n.setFloat32(i,r,!0)}},us=l=>typeof AudioData<"u"&&l instanceof AudioData,H1=(l,n,i,r,o,u,c,d)=>{const m=q0(i),p=H0(r),y=Pa(i),g=Pa(r),b=ei(i);if(ei(r))if(b){const w=new ArrayBuffer(d*y),S=Re(w);l.copyTo(w,{planeIndex:u,frameOffset:c,frameCount:d,format:i});for(let E=0;E{let i=0,r=0,o=~l;o&128&&(o&=-129,i=-1),r=((o&240)>>4)+5;const u=(1<{let n=0,i=0,r=l^85;r&128&&(r&=-129,n=-1),i=((r&240)>>4)+4;let o=0;return i!==4?o=1<{if(!l||typeof l!="object")throw new TypeError("options must be an object.");if(l.metadataOnly!==void 0&&typeof l.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(l.verifyKeyPackets!==void 0&&typeof l.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(l.verifyKeyPackets&&l.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(l.skipLiveWait!==void 0&&typeof l.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},si=l=>{if(!vf(l))throw new TypeError("timestamp must be a number.")},$u=(l,n,i)=>i.verifyKeyPackets?n.then(async r=>{if(!r||r.type==="delta")return r;const o=await l.determinePacketType(r);return o&&(r.type=o),r}):n;class V0{constructor(n){if(!(n instanceof Is))throw new TypeError("track must be an InputTrack.");this._track=n}async getFirstPacket(n={}){if(Ja(n),this._track.input._disposed)throw new Ct;return $u(this._track,this._track._backing.getFirstPacket(n),n)}async getFirstKeyPacket(n={}){Ja(n);const i=await this.getFirstPacket(n);return i?i.type==="key"?i:this.getNextKeyPacket(i,n):null}async getPacket(n,i={}){if(si(n),Ja(i),this._track.input._disposed)throw new Ct;return $u(this._track,this._track._backing.getPacket(n,i),i)}async getNextPacket(n,i={}){if(!(n instanceof dt))throw new TypeError("packet must be an EncodedPacket.");if(Ja(i),this._track.input._disposed)throw new Ct;return $u(this._track,this._track._backing.getNextPacket(n,i),i)}async getKeyPacket(n,i={}){if(si(n),Ja(i),this._track.input._disposed)throw new Ct;if(!i.verifyKeyPackets)return this._track._backing.getKeyPacket(n,i);const r=await this._track._backing.getKeyPacket(n,i);return r&&(C(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),i):r)}async getNextKeyPacket(n,i={}){if(!(n instanceof dt))throw new TypeError("packet must be an EncodedPacket.");if(Ja(i),this._track.input._disposed)throw new Ct;if(!i.verifyKeyPackets)return this._track._backing.getNextKeyPacket(n,i);const r=await this._track._backing.getNextKeyPacket(n,i);return r&&(C(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,i):r)}packets(n,i,r={}){if(n!==void 0&&!(n instanceof dt))throw new TypeError("startPacket must be an EncodedPacket.");if(n!==void 0&&n.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(i!==void 0&&!(i instanceof dt))throw new TypeError("endPacket must be an EncodedPacket.");if(Ja(r),this._track.input._disposed)throw new Ct;const o=[];let{promise:u,resolve:c}=zt(),{promise:d,resolve:m}=zt(),p=!1,y=!1,g=null,b=!1;const T=[],w=()=>Math.max(2,T.length);(async()=>{let E=n??await this.getFirstPacket(r);for(;E&&!y&&!this._track.input._disposed&&!(i&&E.sequenceNumber>=i?.sequenceNumber);){if(o.length>w()){({promise:d,resolve:m}=zt()),await d;continue}o.push(E),c(),{promise:u,resolve:c}=zt(),E=await this.getNextPacket(E,r)}p=!0,c()})().catch(E=>{b||(g=E,b=!0,c())});const S=this._track;return{async next(){for(;;){if(S.input._disposed)throw new Ct;if(y)return{value:void 0,done:!0};if(b)throw g;if(o.length>0){const E=o.shift(),x=performance.now();for(T.push(x);T.length>0&&x-T[0]>=1e3;)T.shift();return m(),{value:E,done:!1}}else{if(p)return{value:void 0,done:!0};await u}}},async return(){return y=!0,m(),c(),{value:void 0,done:!0}},async throw(E){throw E},[Symbol.asyncIterator](){return this}}}}class j0{constructor(n,i){this.onSample=n,this.onError=i}}class X1{mediaSamplesInRange(n=-1/0,i=1/0,r){si(n),si(i);const o=[];let u=!1,c=null,{promise:d,resolve:m}=zt(),{promise:p,resolve:y}=zt(),g=!1,b=!1,T=!1,w=null,S=!1;const E={...r,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const _=await this._createDecoder(R=>{if(y(),R.timestamp>=i&&(b=!0),b){R.close();return}c&&(R.timestamp>n?(o.push(c),u=!0):c.close()),R.timestamp>=n&&(o.push(R),u=!0),c=u?null:R,o.length>0&&(m(),{promise:d,resolve:m}=zt())},R=>{S||(w=R,S=!0,m())}),D=this._createPacketSink(),B=await D.getKeyPacket(n,E)??await D.getFirstKeyPacket(E);let z=B;const H=D.packets(B??void 0,void 0,E);for(await H.next();z&&!b&&!this._track.input._disposed;){const R=Dg(o.length);if(o.length+_.getDecodeQueueSize()>R){({promise:p,resolve:y}=zt()),await p;continue}_.decode(z);const X=await H.next();if(X.done)break;z=X.value}await H.return(),!T&&!this._track.input._disposed&&await _.flush(),_.close(),!u&&c&&o.push(c),g=!0,m()})().catch(_=>{S||(w=_,S=!0,m())});const x=this._track,P=()=>{c?.close();for(const _ of o)_.close()};return{async next(){for(;;){if(x.input._disposed)throw P(),new Ct;if(T)return{value:void 0,done:!0};if(S)throw P(),w;if(o.length>0){const _=o.shift();return y(),{value:_,done:!1}}else if(!g)await d;else return{value:void 0,done:!0}}},async return(){return T=!0,b=!0,y(),m(),P(),{value:void 0,done:!0}},async throw(_){throw _},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(n,i){Ub(n);const r=Nb(n),o=[],u=[];let{promise:c,resolve:d}=zt(),{promise:m,resolve:p}=zt(),y=!1,g=!1,b=null,T=!1;const w=P=>{u.push(P),d(),{promise:c,resolve:d}=zt()},S={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const P=await this._createDecoder(R=>{if(p(),g){R.close();return}let X=0;for(;o.length>0&&R.timestamp-o[0]>-1e-10;)X++,o.shift();if(X>0)for(let W=0;W{T||(b=R,T=!0,d())}),_=this._createPacketSink();let D=null,B=null,z=-1;const L=async()=>{C(B);let R=B;for(P.decode(R);R.sequenceNumberX&&!g;)({promise:m,resolve:p}=zt()),await m;if(g)break;const W=await _.getNextPacket(R,S);C(W),P.decode(W),R=W}z=-1},H=async()=>{await P.flush();for(let R=0;R{T||(b=P,T=!0,d())});const E=this._track,x=()=>{for(const P of u)P?.close()};return{async next(){for(;;){if(E.input._disposed)throw x(),new Ct;if(g)return{value:void 0,done:!0};if(T)throw x(),b;if(u.length>0){const P=u.shift();return C(P!==void 0),p(),{value:P,done:!1}}else if(!y)await c;else return{value:void 0,done:!0}}},async return(){return g=!0,p(),d(),x(),{value:void 0,done:!0}},async throw(P){throw P},[Symbol.asyncIterator](){return this}}}}const Dg=l=>l===0?40:8;class G1 extends j0{constructor(n,i,r,o){super(n,i),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Vb,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const u=d=>{let m=d.timestamp;this.expectedFirstTimestamp&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp-m),m+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(m-this.currentTimestamp)>=d.duration)&&(this.currentTimestamp=m);const p=this.currentTimestamp;if(this.currentTimestamp+=d.duration,d.numberOfFrames===0){d.close();return}const y=o.sampleRate;d.setTimestamp(Math.round(p*y)/y),n(d)},c=L0.find(d=>d.supports(r,o));if(c)this.customDecoder=new c,this.customDecoder.codec=r,this.customDecoder.config=o,this.customDecoder.onSample=d=>{if(!(d instanceof Cn))throw new TypeError("The argument passed to onSample must be an AudioSample.");u(d)},this.customDecoder.onError=d=>{i(d)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(d=>i(d));else{const d=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:m=>{try{u(new Cn(m))}catch(p){this.onError(p)}},error:m=>{m.stack=d,this.onError(m)}}),this.decoder.configure(o)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(C(this.decoder),this.decoder.decodeQueueSize)}decode(n){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(n)).catch(i=>this.onError(i)).finally(()=>this.customDecoderQueueSize--)):(C(this.decoder),this.expectedFirstTimestamp??=n.timestamp,this.decoder.decode(n.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(C(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(C(this.decoder),this.decoder.close())}}class K1 extends j0{constructor(n,i,r){super(n,i),this.decoderConfig=r,this.currentTimestamp=null,C(hr.includes(r.codec)),this.codec=r.codec;const{dataType:o,sampleSize:u,littleEndian:c}=Qg(this.codec);switch(this.inputSampleSize=u,u){case 1:o==="unsigned"?this.readInputValue=(d,m)=>d.getUint8(m)-2**7:o==="signed"?this.readInputValue=(d,m)=>d.getInt8(m):o==="ulaw"?this.readInputValue=(d,m)=>V1(d.getUint8(m)):o==="alaw"?this.readInputValue=(d,m)=>j1(d.getUint8(m)):C(!1);break;case 2:o==="unsigned"?this.readInputValue=(d,m)=>d.getUint16(m,c)-2**15:o==="signed"?this.readInputValue=(d,m)=>d.getInt16(m,c):C(!1);break;case 3:o==="unsigned"?this.readInputValue=(d,m)=>mo(d,m,c)-2**23:o==="signed"?this.readInputValue=(d,m)=>Fb(d,m,c):C(!1);break;case 4:o==="unsigned"?this.readInputValue=(d,m)=>d.getUint32(m,c)-2**31:o==="signed"?this.readInputValue=(d,m)=>d.getInt32(m,c):o==="float"?this.readInputValue=(d,m)=>d.getFloat32(m,c):C(!1);break;case 8:o==="float"?this.readInputValue=(d,m)=>d.getFloat64(m,c):C(!1);break;default:xs(u),C(!1)}switch(u){case 1:o==="ulaw"||o==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(d,m,p)=>d.setInt16(m,p,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(d,m,p)=>d.setUint8(m,p+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(d,m,p)=>d.setInt16(m,p,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(d,m,p)=>d.setInt32(m,p<<8,!0);break;case 4:this.outputSampleSize=4,o==="float"?(this.outputFormat="f32",this.writeOutputValue=(d,m,p)=>d.setFloat32(m,p,!0)):(this.outputFormat="s32",this.writeOutputValue=(d,m,p)=>d.setInt32(m,p,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(d,m,p)=>d.setFloat32(m,p,!0);break;default:xs(u),C(!1)}}getDecodeQueueSize(){return 0}decode(n){const i=Re(n.data),r=n.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,o=r*this.decoderConfig.numberOfChannels*this.outputSampleSize,u=new ArrayBuffer(o),c=new DataView(u);for(let y=0;y=d)&&(this.currentTimestamp=n.timestamp);const m=this.currentTimestamp;this.currentTimestamp+=d;const p=new Cn({format:this.outputFormat,data:u,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:r,timestamp:m});this.onSample(p)}async flush(){}close(){}}class Y1 extends X1{constructor(n){if(!(n instanceof So))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=n}async _createDecoder(n,i){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),o=await this._track.getDecoderConfig();return C(r&&o),hr.includes(o.codec)?new K1(n,i,o):new G1(n,i,r,o)}_createPacketSink(){return new V0(this._track)}async getSample(n,i={}){si(n);for await(const r of this.mediaSamplesAtTimestamps([n],i))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(n,i,r={}){return this.mediaSamplesInRange(n,i,r)}samplesAtTimestamps(n,i={}){return this.mediaSamplesAtTimestamps(n,i)}}class Q1{constructor(n){if(!(n instanceof So))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Y1(n)}_audioSampleToWrappedArrayBuffer(n){const i={buffer:n.toAudioBuffer(),timestamp:n.timestamp,duration:n.duration};return n.close(),i}async getBuffer(n,i){si(n);const r=await this._audioSampleSink.getSample(n,i);return r&&this._audioSampleToWrappedArrayBuffer(r)}buffers(n,i,r){return Gp(this._audioSampleSink.samples(n,i,r),o=>this._audioSampleToWrappedArrayBuffer(o))}buffersAtTimestamps(n,i){return Gp(this._audioSampleSink.samplesAtTimestamps(n,i),r=>r&&this._audioSampleToWrappedArrayBuffer(r))}}class Is{constructor(n,i){this.input=n,this._backing=i}isVideoTrack(){return this instanceof X0}isAudioTrack(){return this instanceof So}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Qe(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Qe(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Qe(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Qe(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(n){return this._backing.getUnixTimeForTimestamp(n)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Qe(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(n){const i=await this._backing.getPacket(1/0,{metadataOnly:!0,...n}),r=(i?.timestamp??0)+(i?.duration??0);return Lg(r,await this.getTimeResolution())}async getDurationFromMetadata(n={}){return this._backing.getDurationFromMetadata(n)}async computePacketStats(n=1/0,i){const r=new V0(this);let o=1/0,u=-1/0,c=0,d=0;for await(const m of r.packets(void 0,void 0,{metadataOnly:!0,...i})){if(c>=n&&m.timestamp>=u)break;o=Math.min(o,m.timestamp),u=Math.max(u,m.timestamp+m.duration),c++,d+=m.byteLength}return{packetCount:c,averagePacketRate:c?Number((c/(u-o)).toPrecision(16)):0,averageBitrate:c?Number((8*d/(u-o)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(n){if(!(n instanceof Is))throw new TypeError("other must be an InputTrack.");return this.input!==n.input||this===n?!1:(this._backing.getPairingMask()&n._backing.getPairingMask())!==0n}async getPairableTracks(n){return this.input.getTracks(ti({filter:i=>i.canBePairedWith(this)},n))}async getPairableVideoTracks(n){return this.input.getVideoTracks(ti({filter:i=>i.canBePairedWith(this)},n))}async getPairableAudioTracks(n){return this.input.getAudioTracks(ti({filter:i=>i.canBePairedWith(this)},n))}async getPrimaryPairableVideoTrack(n){return this.input.getPrimaryVideoTrack(ti({filter:i=>i.canBePairedWith(this)},n))}async getPrimaryPairableAudioTrack(n){return this.input.getPrimaryAudioTrack(ti({filter:i=>i.canBePairedWith(this)},n))}async hasPairableTrack(n){n&&=ef(n);const i=await this.input.getTracks();for(const r of i)if(this.canBePairedWith(r)&&(!n||await n(r)))return!0;return!1}hasPairableVideoTrack(n){return n&&=ef(n),this.hasPairableTrack(async i=>i.isVideoTrack()&&(!n||await n(i)))}hasPairableAudioTrack(n){return n&&=ef(n),this.hasPairableTrack(async i=>i.isAudioTrack()&&(!n||await n(i)))}}const Qe=(l,n,i)=>{if(l instanceof Promise)throw new Error(`'${n}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return l},ef=l=>{if(l!==void 0&&typeof l!="function")throw new TypeError("predicate, when provided, must be a function.");return l?n=>{const i=o=>{if(typeof o!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return o},r=l(n);return r instanceof Promise?r.then(i):i(r)}:void 0};class X0 extends Is{constructor(n,i){super(n,i),this._pixelAspectRatioCache=null,this._backing=i}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return Qe(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()==="prores"}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Qe(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Qe(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Qe(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Qe(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Qe(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Yp({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Yp({num:Qe(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Qe(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Qe(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Qe(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){const n=await this._backing.getMetadataDisplayWidth?.();return n??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){const n=this._backing.getMetadataDisplayWidth?.();if(n!==void 0){const o=Qe(n,"displayWidth","getDisplayWidth");if(o!==null)return o}const r=Qe(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Qe(r,"displayWidth","getDisplayWidth")}async getDisplayHeight(){const n=await this._backing.getMetadataDisplayHeight?.();return n??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){const n=this._backing.getMetadataDisplayHeight?.();if(n!==void 0){const o=Qe(n,"displayHeight","getDisplayHeight");if(o!==null)return o}const r=Qe(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Qe(r,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const n=await this._backing.getColorSpace();return n.primaries==="bt2020"||n.primaries==="smpte432"||n.transfer==="pq"||n.transfer==="hlg"||n.matrix==="bt2020-ncl"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const n=await this._backing.getMetadataCodecParameterString?.();return n??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const n=await this._backing.getDecoderConfig();if(!n)return!1;const i=await this._backing.getCodec();return C(i!==null),L1.some(o=>o.supports(i,n))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(n)).supported===!0}catch(n){return ke._error("Error during decodability check:",n),!1}}async determinePacketType(n){if(!(n instanceof dt))throw new TypeError("packet must be an EncodedPacket.");if(n.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const i=await this.getCodec();if(i===null)return null;const r=await this.getDecoderConfig();return C(r),c0(i,r,n.data)}}class So extends Is{constructor(n,i){super(n,i),this._backing=i}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Qe(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Qe(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Qe(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const n=await this._backing.getMetadataCodecParameterString?.();return n??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const n=await this._backing.getDecoderConfig();if(!n)return!1;const i=await this._backing.getCodec();return C(i!==null),L0.some(r=>r.supports(i,n))||n.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(n)).supported===!0}catch(n){return ke._error("Error during decodability check:",n),!1}}async determinePacketType(n){if(!(n instanceof dt))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}const Ig=l=>-(l??-1/0),fs=l=>-l,ds=l=>{if(typeof l!="object"||!l)throw new TypeError("query must be an object.");if(l.filter!==void 0&&typeof l.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(l.sortBy!==void 0&&typeof l.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:l.filter?n=>{const i=o=>{if(typeof o!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return o},r=l.filter(n);return r instanceof Promise?r.then(i):i(r)}:void 0,sortBy:l.sortBy?n=>{const i=o=>{if(typeof o!="number"&&(!Array.isArray(o)||!o.every(u=>typeof u=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return o},r=l.sortBy(n);return r instanceof Promise?r.then(i):i(r)}:void 0}},ti=(l,n)=>({filter:l?.filter||n?.filter?i=>{const r=l?.filter?.(i)??!0,o=u=>u===!1?!1:n?.filter?.(i)??!0;return r instanceof Promise?r.then(o):o(r)}:void 0,sortBy:l?.sortBy||n?.sortBy?i=>{const r=l?.sortBy?.(i)??[],o=n?.sortBy?.(i)??[],u=(c,d)=>[...Array.isArray(c)?c:[c],...Array.isArray(d)?d:[d]];return r instanceof Promise||o instanceof Promise?Promise.all([r,o]).then(([c,d])=>u(c,d)):u(r,o)}:void 0}),tf=async(l,n)=>{let i=l;if(n?.filter){const c=l.map(m=>n.filter(m));if(c.some(m=>m instanceof Promise)){const m=await Promise.all(c);i=l.filter((p,y)=>m[y])}else i=l.filter((m,p)=>c[p])}if(!n?.sortBy)return i;const r=i.map(c=>n.sortBy(c)),u=r.some(c=>c instanceof Promise)?await Promise.all(r):r;return i.map((c,d)=>({track:c,sortValue:u[d]})).sort((c,d)=>{const m=Array.isArray(c.sortValue)?c.sortValue:[c.sortValue],p=Array.isArray(d.sortValue)?d.sortValue:[d.sortValue],y=Math.max(m.length,p.length);for(let g=0;gc.track)};Tf();const Z1=1,W1=2;class To extends wf{get disposed(){return this._disposed}constructor(n){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!n||typeof n!="object")throw new TypeError("options must be an object.");if(!Array.isArray(n.formats)||n.formats.some(i=>!(i instanceof En)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(n.source instanceof _n||n.source instanceof Rf))throw new TypeError("options.source must be a Source or SourceRef.");if(n.source instanceof _n&&n.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(n.initInput!==void 0&&!(n.initInput instanceof To))throw new TypeError("options.initInput, when provided, must be an Input.");n.formatOptions!==void 0&&F1(n.formatOptions,"formatOptions"),this._formats=n.formats,this._initInput=n.initInput??null,this._formatOptions=n.formatOptions??{},n.source instanceof _n?this._rootRef=n.source.ref():this._rootRef=n.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(n){C(this._rootSource instanceof Ds);const i=await this._rootSource._resolveRequest(n);return this._emit("source",{source:i.source,request:n,isRoot:n.isRoot}),i}_getSourceCached(n,i=Z1){const r=this._sourceCache.find(c=>c.cacheGroup===i&&wg(c.request,n));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());const o=this._sourceCachePromises.find(c=>c.cacheGroup===i&&wg(c.request,n));if(o)return o.promise.then(c=>c.sourceRef.source.ref());const u=(async()=>{const c=await this._getSourceUncached(n);if(ps(this._sourceCache,g=>g.cacheGroup===i&&g.sourceRef.source._refCount===1)>=4){const g=Gg(this._sourceCache,T=>T.cacheGroup===i&&T.sourceRef.source._refCount===1?T.age:1/0);C(g!==-1);const b=this._sourceCache[g];this._sourceCache.splice(g,1),b.sourceRef.free(),Mb(this._sourceRefs,b.sourceRef)}this._sourceRefs.push(c);const p=this._sourceCachePromises.findIndex(g=>g.request===n);return C(p!==-1),this._sourceCachePromises.splice(p,1),{request:n,sourceRef:c,age:this._nextSourceCacheAge++,cacheGroup:i}})();return this._sourceCachePromises.push({request:n,cacheGroup:i,promise:u}),u.then(c=>{const d=c.sourceRef.source.ref();return this._sourceCache.push(c),d})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new no(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const n of this._formats)if(await n._canReadInput(this))return this._format=n,this._onFormatDetermined?.(n),n._createDemuxer(this);throw new Rg})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),C(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(n){if(n instanceof Rg)return!1;throw n}}async getFirstTimestamp(n){n??=await this.getTracks();const i=n.filter(o=>o!==null);if(i.length===0)return 0;const r=await Promise.all(i.map(o=>o.getFirstTimestamp()));return Math.min(...r)}async computeDuration(n,i){n??=await this.getTracks();const r=n.filter(u=>u!==null);if(r.length===0)return 0;const o=await Promise.all(r.map(u=>u.computeDuration(i)));return Math.max(...o)}async getDurationFromMetadata(n,i){n??=await this.getTracks();const r=n.filter(c=>c!==null),u=(await Promise.all(r.map(c=>c.getDurationFromMetadata(i)))).filter(c=>c!==null);return u.length===0?null:Math.max(...u)}async getTracks(n){n&&=ds(n);const r=(await this._getTrackBackings()).map(o=>this._wrapBackingAsTrack(o));return tf(r,n)}async getVideoTracks(n){n&&=ds(n);const r=(await this.getTracks()).filter(o=>o.isVideoTrack());return tf(r,n)}async getAudioTracks(n){n&&=ds(n);const r=(await this.getTracks()).filter(o=>o.isAudioTrack());return tf(r,n)}async getPrimaryVideoTrack(n){n&&=ds(n);const i=ti(n,{sortBy:async o=>[fs((await o.getDisposition()).default),fs(await o.hasPairableAudioTrack()),fs(!await o.hasOnlyKeyPackets()),Ig(await o.getBitrate())]});return(await this.getVideoTracks(i))[0]??null}async getPrimaryAudioTrack(n){n&&=ds(n);const i=await this.getPrimaryVideoTrack(),r=ti(n,{sortBy:async u=>[fs(!i||u.canBePairedWith(i)),fs((await u.getDisposition()).default),Ig(await u.getBitrate())]});return(await this.getAudioTracks(r))[0]??null}async _getTrackBackings(){const n=await this._getDemuxer();return this._trackBackingsCache??=await n.getTrackBackings()}_wrapBackingAsTrack(n){const i=this._backingToTrack.get(n);if(i)return i;const o=n.getType()==="video"?new X0(this,n):new So(this,n);return this._backingToTrack.set(n,o),o}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(const n of this._sourceRefs)n.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(n=>n.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class Rg extends Error{constructor(n="Input has an unsupported or unrecognizable format."){super(n),this.name="UnsupportedInputFormatError"}}class Ct extends Error{constructor(n="Input has been disposed."){super(n),this.name="InputDisposedError"}}class no{constructor(n){this.source=n}get fileSize(){const n=this.source._getFileSize();if(n===void 0)throw new Error("Reading file size too early; read required first.");return n}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(n,i){if(this.source._disposed)throw new Ct;if(n<0||this.fileSizeNonStrict!==null&&n+i>this.fileSizeNonStrict)return null;if(i===0){const u=new Uint8Array(0);return new gn(u,Re(u),0,n,n)}const r=n+i,o=this.source._read(n,r,I0,R0);return o instanceof Promise?o.then(u=>u?new gn(u.bytes,u.view,u.offset,n,r):null):o?new gn(o.bytes,o.view,o.offset,n,r):null}requestSliceRange(n,i,r){if(this.source._disposed)throw new Ct;if(n<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(n,or(this.fileSizeNonStrict-n,i,r));{const o=this.requestSlice(n,r),u=c=>c||(C(this.fileSizeNonStrict!==null),this.requestSlice(n,or(this.fileSizeNonStrict-n,i,r)));return o instanceof Promise?o.then(u):u(o)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);const n=1024;return(async()=>{const i=[];let r=0;for(;;){if(i.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let c=this.requestSliceRange(r,0,n);if(c instanceof Promise&&(c=await c),!c||c.length===0)break;const d=fe(c,c.length);i.push(d),r+=c.length}const o=new Uint8Array(r);let u=0;for(const c of i)o.set(c,u),u+=c.length;return new gn(o,Re(o),0,0,r)})()}}class gn{constructor(n,i,r,o,u){this.bytes=n,this.view=i,this.offset=r,this.start=o,this.end=u,this.bufferPos=o-r}static tempFromBytes(n){return new gn(n,Re(n),0,0,n.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(n){this.bufferPos=n-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(n){this.bufferPos+=n}slice(n,i=this.end-n){if(nthis.end)throw new RangeError("Slicing outside of original slice.");return new gn(this.bytes,this.view,this.offset,n,n+i)}}const Nt=(l,n)=>{if(l.filePosl.end)throw new RangeError(`Tried reading [${l.filePos}, ${l.filePos+n}), but slice is [${l.start}, ${l.end}). This is likely an internal error, please report it alongside the file that caused it.`)},fe=(l,n)=>{Nt(l,n);const i=l.bytes.subarray(l.bufferPos,l.bufferPos+n);return l.bufferPos+=n,i},oe=l=>(Nt(l,1),l.view.getUint8(l.bufferPos++)),hs=(l,n)=>{Nt(l,2);const i=l.view.getUint16(l.bufferPos,n);return l.bufferPos+=2,i},it=l=>{Nt(l,2);const n=l.view.getUint16(l.bufferPos,!1);return l.bufferPos+=2,n},Kn=l=>{Nt(l,3);const n=mo(l.view,l.bufferPos,!1);return l.bufferPos+=3,n},gf=l=>{Nt(l,2);const n=l.view.getInt16(l.bufferPos,!1);return l.bufferPos+=2,n},Da=(l,n)=>{Nt(l,4);const i=l.view.getUint32(l.bufferPos,n);return l.bufferPos+=4,i},$=l=>{Nt(l,4);const n=l.view.getUint32(l.bufferPos,!1);return l.bufferPos+=4,n},rr=l=>{Nt(l,4);const n=l.view.getUint32(l.bufferPos,!0);return l.bufferPos+=4,n},ai=l=>{Nt(l,4);const n=l.view.getInt32(l.bufferPos,!1);return l.bufferPos+=4,n},J1=l=>{Nt(l,4);const n=l.view.getInt32(l.bufferPos,!0);return l.bufferPos+=4,n},Og=(l,n)=>{let i,r;return n?(i=Da(l,!0),r=Da(l,!0)):(r=Da(l,!1),i=Da(l,!1)),r*4294967296+i},un=l=>{const n=$(l),i=$(l);return n*4294967296+i},$1=l=>{const n=ai(l),i=$(l);return n*4294967296+i},eT=l=>{const n=rr(l);return J1(l)*4294967296+n},tT=l=>{Nt(l,4);const n=l.view.getFloat32(l.bufferPos,!1);return l.bufferPos+=4,n},G0=l=>{Nt(l,8);const n=l.view.getFloat64(l.bufferPos,!1);return l.bufferPos+=8,n},Je=(l,n)=>{Nt(l,n);let i="";for(let r=0;rMt.decode(fe(l,n)).split(` +`).map(u=>u.trim()).filter(u=>u.length>0&&!i?.ignore?.(u));var ii;(function(l){l[l.Unsynchronisation=128]="Unsynchronisation",l[l.ExtendedHeader=64]="ExtendedHeader",l[l.ExperimentalIndicator=32]="ExperimentalIndicator",l[l.Footer=16]="Footer"})(ii||(ii={}));var sr;(function(l){l[l.ISO_8859_1=0]="ISO_8859_1",l[l.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",l[l.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",l[l.UTF_8=3]="UTF_8"})(sr||(sr={}));const ao=128,dn=10,lr=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],nT=(l,n)=>{const i=l.filePos;n.raw??={},n.raw.TAG??=fe(l,ao-3),l.filePos=i;const r=Yi(l,30);r&&(n.title??=r);const o=Yi(l,30);o&&(n.artist??=o);const u=Yi(l,30);u&&(n.album??=u);const c=Yi(l,4),d=Number.parseInt(c,10);Number.isInteger(d)&&d>0&&(n.date??=new Date(String(d)));const m=fe(l,30);let p;if(m[28]===0&&m[29]!==0){const g=m[29];g>0&&(n.trackNumber??=g),l.skip(-30),p=Yi(l,28),l.skip(2)}else l.skip(-30),p=Yi(l,30);p&&(n.comment??=p);const y=oe(l);y{const i=fe(l,n),r=Zi(i.indexOf(0),i.length),o=i.subarray(0,r);let u="";for(let c=0;c{const n=l.filePos,i=Je(l,3),r=oe(l),o=oe(l),u=oe(l),c=$(l);if(i!=="ID3"||r===255||o===255||(c&2155905152)!==0)return l.filePos=n,null;let d=sf(c);return u&ii.Footer&&(d+=dn),{majorVersion:r,revision:o,flags:u,size:d}},vo=(l,n,i)=>{if(![2,3,4].includes(n.majorVersion)){ke._warn(`Unsupported ID3v2 major version: ${n.majorVersion}`);return}const r=n.flags&ii.Footer?n.size-dn:n.size,o=fe(l,r),u=new aT(n,o);if(n.flags&ii.Unsynchronisation&&n.majorVersion===3&&u.ununsynchronizeAll(),n.flags&ii.ExtendedHeader){const c=u.readU32();n.majorVersion===3?u.pos+=c:u.pos+=c-4}for(;u.pos<=u.bytes.length-u.frameHeaderSize();){const c=u.readId3V2Frame();if(!c)break;const d=u.pos,m=u.pos+c.size;let p=!1,y=!1,g=!1;if(n.majorVersion===3?(p=!!(c.flags&64),y=!!(c.flags&128)):n.majorVersion===4&&(p=!!(c.flags&4),y=!!(c.flags&8),g=!!(c.flags&2)||!!(n.flags&ii.Unsynchronisation)),p){ke._warn(`Skipping encrypted ID3v2 frame ${c.id}`),u.pos=m;continue}if(y){ke._warn(`Skipping compressed ID3v2 frame ${c.id}`),u.pos=m;continue}if(g&&u.ununsynchronizeRegion(u.pos,m),i.raw??={},c.id==="TXXX"){const b=i.raw.TXXX??={},T=u.readId3V2TextEncoding(),w=u.readId3V2Text(T,m),S=u.readId3V2Text(T,m);b[w]??=S}else c.id[0]==="T"?i.raw[c.id]??=u.readId3V2EncodingAndText(m):i.raw[c.id]??=u.readBytes(c.size);switch(u.pos=d,c.id){case"TIT2":case"TT2":i.title??=u.readId3V2EncodingAndText(m);break;case"TIT3":case"TT3":i.description??=u.readId3V2EncodingAndText(m);break;case"TPE1":case"TP1":i.artist??=u.readId3V2EncodingAndText(m);break;case"TALB":case"TAL":i.album??=u.readId3V2EncodingAndText(m);break;case"TPE2":case"TP2":i.albumArtist??=u.readId3V2EncodingAndText(m);break;case"TRCK":case"TRK":{const T=u.readId3V2EncodingAndText(m).split("/"),w=Number.parseInt(T[0],10),S=T[1]&&Number.parseInt(T[1],10);Number.isInteger(w)&&w>0&&(i.trackNumber??=w),S&&Number.isInteger(S)&&S>0&&(i.tracksTotal??=S)}break;case"TPOS":case"TPA":{const T=u.readId3V2EncodingAndText(m).split("/"),w=Number.parseInt(T[0],10),S=T[1]&&Number.parseInt(T[1],10);Number.isInteger(w)&&w>0&&(i.discNumber??=w),S&&Number.isInteger(S)&&S>0&&(i.discsTotal??=S)}break;case"TCON":case"TCO":{const b=u.readId3V2EncodingAndText(m);let T=/^\((\d+)\)/.exec(b);if(T){const w=Number.parseInt(T[1]);if(lr[w]!==void 0){i.genre??=lr[w];break}}if(T=/^\d+$/.exec(b),T){const w=Number.parseInt(T[0]);if(lr[w]!==void 0){i.genre??=lr[w];break}}i.genre??=b}break;case"TDRC":case"TDAT":{const b=u.readId3V2EncodingAndText(m),T=new Date(b);Number.isNaN(T.getTime())||(i.date??=T)}break;case"TYER":case"TYE":{const b=u.readId3V2EncodingAndText(m),T=Number.parseInt(b,10);Number.isInteger(T)&&(i.date??=new Date(String(T)))}break;case"USLT":case"ULT":{const b=u.readU8();u.pos+=3,u.readId3V2Text(b,m),i.lyrics??=u.readId3V2Text(b,m)}break;case"COMM":case"COM":{const b=u.readU8();u.pos+=3,u.readId3V2Text(b,m),i.comment??=u.readId3V2Text(b,m)}break;case"APIC":case"PIC":{const b=u.readId3V2TextEncoding();let T;if(n.majorVersion===2){const x=u.readAscii(3);T=x==="PNG"?"image/png":x==="JPG"?"image/jpeg":"image/*"}else T=u.readId3V2Text(b,m);const w=u.readU8(),S=u.readId3V2Text(b,m).trimEnd(),E=m-u.pos;if(E>=0){const x=u.readBytes(E);i.images||(i.images=[]),i.images.push({data:x,mimeType:T,kind:w===3?"coverFront":w===4?"coverBack":"unknown",description:S})}}break;default:u.pos+=c.size;break}u.pos=m}};class aT{constructor(n,i){this.header=n,this.bytes=i,this.pos=0,this.view=new DataView(i.buffer,i.byteOffset,i.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){const n=[];for(let i=0;i{const m=this.pos+d;if(m>this.bytes.length)return!1;if(m<=this.bytes.length-this.frameHeaderSize()){this.pos+=d;const p=this.readAscii(4);if(p!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(p))return!1}return!0};if(!c(r)){const d=this.header.majorVersion===4?i:sf(i);c(d)&&(r=d)}return this.pos=u,{id:n,size:r,flags:o}}}readId3V2TextEncoding(){const n=this.readU8();if(n>3)throw new Error(`Unsupported text encoding: ${n}`);return n}readId3V2Text(n,i){const r=this.pos,o=this.readBytes(i-this.pos);switch(n){case sr.ISO_8859_1:{let u="";for(let c=0;cd===0&&o[m+1]===0&&m%2===0),o.length);return this.pos=r+Math.min(c+2,o.length),u.decode(o.subarray(2,c))}else if(o[0]===254&&o[1]===255){const u=new TextDecoder("utf-16be"),c=Zi(o.findIndex((d,m)=>d===0&&o[m+1]===0&&m%2===0),o.length);return this.pos=r+Math.min(c+2,o.length),u.decode(o.subarray(2,c))}else{const u=Zi(o.findIndex(c=>c===0),o.length);return this.pos=r+Math.min(u+1,o.length),Mt.decode(o.subarray(0,u))}case sr.UTF_16_BE_NO_BOM:{const u=new TextDecoder("utf-16be"),c=Zi(o.findIndex((d,m)=>d===0&&o[m+1]===0&&m%2===0),o.length);return this.pos=r+Math.min(c+2,o.length),u.decode(o.subarray(0,c))}case sr.UTF_8:{const u=Zi(o.findIndex(c=>c===0),o.length);return this.pos=r+Math.min(u+1,o.length),Mt.decode(o.subarray(0,u))}}}readId3V2EncodingAndText(n){if(this.pos>=n)return"";const i=this.readId3V2TextEncoding();return this.readId3V2Text(i,n)}}function Y0(l){for(let n=0;n1?l[n]=1:i<-1&&(l[n]=-1)}}function Z0(l){const{numberOfChannels:n,length:i}=l,r=new Float32Array(i);if(n===1)return r.set(l.getChannelData(0)),r;const o=Array.from({length:n},(c,d)=>l.getChannelData(d)),u=1/n;for(let c=0;co+u.length,0),i=new Float32Array(n);let r=0;for(const o of l)i.set(o,r),r+=o.length;return i}function J0(l){let n=0,i=0;for(let r=0;rn&&(n=o),i+=l[r]*l[r]}return{peak:n,rms:l.length?Math.sqrt(i/l.length):0}}async function rT(l,n){const i=n?.maxDurationSeconds??Xe.maxDurationSeconds;if(l.duration>i)throw new Ve("AUDIO_TOO_LONG","normalize",`Decoded audio exceeds the ${Math.round(i/60)} minute limit.`);const r=[],o=Z0(l),u=await W0(o,l.sampleRate,Xe.targetSampleRate);if(Y0(u),Q0(u),u.length===0)throw new Ve("AUDIO_EMPTY","normalize","Normalized audio is empty.");const{peak:c,rms:d}=J0(u);return d<.001&&r.push("Audio appears very quiet. Transcription quality may be poor."),c>=.99&&r.push("Audio may be clipped."),{samples:u,sampleRate:Xe.targetSampleRate,channels:1,durationSeconds:u.length/Xe.targetSampleRate,warnings:r}}async function nf(l,n){if(n?.signal?.aborted)throw new Ve("CANCELLED","decode","Audio normalization cancelled.");if(l.size<=0)throw new Ve("AUDIO_EMPTY","input","Selected file is empty.");if(l.size>Xe.maxSourceBytes)throw new Ve("AUDIO_TOO_LARGE","input",`File exceeds the ${Math.round(Xe.maxSourceBytes/(1024*1024*1024))} GB limit.`);const i=await l.arrayBuffer();if(n?.signal?.aborted)throw new Ve("CANCELLED","decode","Audio normalization cancelled.");const r=new AudioContext;let o;try{o=await r.decodeAudioData(i.slice(0))}catch{throw new Ve("AUDIO_DECODE_UNSUPPORTED","decode","This browser could not decode the selected audio file.")}finally{await r.close().catch(()=>{})}return rT(o,n)}const sT=new Set(["mp4","m4v","mov","webm","mkv","avi","mpeg","mpg","ogv"]);function $0(l){const n=(l.type||"").toLowerCase();if(n.startsWith("video/"))return"video";if(n.startsWith("audio/"))return"audio";const i=l.name?.toLowerCase()??"",r=i.includes(".")?i.split(".").pop()??"":"";return sT.has(r)?"video":r?"audio":"unknown"}function lT(l,n){return n==="video"||l.durationSeconds>Xe.inlineDecodeMaxSeconds||l.byteLength>Xe.inlineDecodeMaxBytes}async function ey(l){return new To({source:new u1(l),formats:U1})}async function oT(l,n){if(dr(n?.signal),l.size<=0)throw new Ve("AUDIO_EMPTY","input","Selected file is empty.");if(l.size>Xe.maxSourceBytes)throw new Ve("AUDIO_TOO_LARGE","input",`File exceeds the ${Math.round(Xe.maxSourceBytes/(1024*1024*1024))} GB limit.`);const i=$0(l),r=await ey(l);try{dr(n?.signal);const o=await r.getPrimaryAudioTrack();if(!o)throw new Ve("AUDIO_TRACK_MISSING","decode",i==="video"?"This video has no audio track to transcribe.":"No audio track found in the selected file.");const u=await o.canDecode(),c=await r.computeDuration(),d=await r.getFormat();if(!Number.isFinite(c)||c<=0)throw new Ve("AUDIO_DURATION_UNKNOWN","decode","Could not determine media duration.");if(c>Xe.maxDurationSeconds)throw new Ve("AUDIO_TOO_LONG","normalize",`Media exceeds the ${Math.round(Xe.maxDurationSeconds/3600)} hour limit.`);return{kind:await r.getPrimaryVideoTrack()||i==="video"?"video":"audio",durationSeconds:c,hasAudio:!0,canDecodeAudio:u,byteLength:l.size,formatName:d.name}}catch(o){throw o instanceof Ve?o:o instanceof Ct?new Ve("CANCELLED","decode","Media probe cancelled."):new Ve("AUDIO_DECODE_UNSUPPORTED","decode","This browser could not open the selected media file.")}finally{r.dispose()}}async function*cT(l,n){const i=n?.windowSeconds??Xe.windowSeconds,r=n?.overlapSeconds??Xe.overlapSeconds,o=Math.max(1,i-r),u=await ey(l);try{dr(n?.signal);const c=await u.getPrimaryAudioTrack();if(!c)throw new Ve("AUDIO_TRACK_MISSING","decode","No audio track found in the selected file.");if(!await c.canDecode())throw new Ve("AUDIO_DECODE_UNSUPPORTED","decode","This browser cannot decode the audio track (WebCodecs).");const d=await u.computeDuration(),m=new Q1(c),p=[];for(let g=0;g=d));g+=o);p.length===0&&p.push(0);const y=p.length;for(let g=0;g({startSeconds:y.startSeconds+i,endSeconds:y.endSeconds+i,text:y.text.trim()})).filter(y=>y.text.length>0&&Number.isFinite(y.startSeconds)&&Number.isFinite(y.endSeconds)&&y.endSeconds>=y.startSeconds&&y.startSeconds>=d-.001&&y.startSecondsn.trim()).filter(Boolean).join(" ").replace(/\s+/g," ").trim()}async function dT(l){const n=Xe.overlapSeconds,i=[],r=[];let o=[],u=0;const c=l.timestamps==="none"?"segment":l.timestamps;for await(const d of cT(l.blob,{signal:l.signal})){dr(l.signal),u=Math.max(u,d.endSeconds),l.onChunkProgress?.({phase:"extract",chunkIndex:d.index,chunkTotal:d.total,windowStartSeconds:d.startSeconds,windowEndSeconds:d.endSeconds,ratio:d.total?d.index/d.total:0,message:`Extracting audio window ${d.index+1}/${d.total}…`}),l.onChunkProgress?.({phase:"infer",chunkIndex:d.index,chunkTotal:d.total,windowStartSeconds:d.startSeconds,windowEndSeconds:d.endSeconds,ratio:d.total?(d.index+.35)/d.total:0,message:`Transcribing window ${d.index+1}/${d.total}…`});const{rms:m}=J0(d.samples);if(m<4e-4){l.onChunkProgress?.({phase:"merge",chunkIndex:d.index,chunkTotal:d.total,windowStartSeconds:d.startSeconds,windowEndSeconds:d.endSeconds,ratio:d.total?(d.index+1)/d.total:1,message:`Skipped quiet window ${d.index+1}/${d.total}`}),await jp();continue}const p=await l.client.transcribe({profileId:l.profileId,runtimePreference:l.runtimePreference,audio:d.samples,language:l.language,timestamps:c,onProgress:l.onModelProgress}),y=d.index===0,g=d.index===d.total-1;if(p.warnings.length)for(const T of p.warnings)i.includes(T)||i.push(T);p.text.trim()&&r.push(p.text.trim()),o=fT(o,p.segments,d.startSeconds,d.endSeconds,n,y,g);const b={text:l.timestamps==="none"?Jl(r):o.map(T=>T.text).join(" ").trim()||Jl(r),segments:l.timestamps==="none"?[]:o,durationSeconds:u,warnings:[...i]};l.onPartialResult?.(b),l.onChunkProgress?.({phase:"merge",chunkIndex:d.index,chunkTotal:d.total,windowStartSeconds:d.startSeconds,windowEndSeconds:d.endSeconds,ratio:d.total?(d.index+1)/d.total:1,message:`Merged window ${d.index+1}/${d.total}`}),await jp()}return l.timestamps==="none"?{text:Jl(r),segments:[],durationSeconds:u,warnings:i}:{text:o.map(d=>d.text).join(" ").trim()||Jl(r),segments:o,durationSeconds:u,warnings:i}}async function hT(l){const n=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,channelCount:1}}),i=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":MediaRecorder.isTypeSupported("audio/webm")?"audio/webm":void 0,r=new MediaRecorder(n,i?{mimeType:i}:void 0),o=[],u=performance.now();let c,d,m,p,y=!1;r.ondataavailable=b=>{b.data.size>0&&o.push(b.data)},r.onerror=()=>{p?.(new Error("Microphone recording failed."))},r.onstop=()=>{n.getTracks().forEach(T=>T.stop()),c!==void 0&&window.clearInterval(c),d!==void 0&&window.clearTimeout(d);const b=new Blob(o,{type:r.mimeType||"audio/webm"});m?.(b)};const g=()=>{n.getTracks().forEach(b=>b.stop())};return c=window.setInterval(()=>{l?.((performance.now()-u)/1e3)},250),d=window.setTimeout(()=>{!y&&r.state==="recording"&&(y=!0,r.stop())},Xe.maxRecordingSeconds*1e3),r.start(250),{getElapsedSeconds:()=>(performance.now()-u)/1e3,cancel:()=>{y=!0,r.state!=="inactive"?(r.onstop=()=>g(),r.stop()):g(),c!==void 0&&window.clearInterval(c),d!==void 0&&window.clearTimeout(d),p?.(new Error("Recording cancelled."))},stop:()=>new Promise((b,T)=>{if(y){T(new Error("Recording already stopped."));return}y=!0,m=b,p=T,r.state==="recording"?r.stop():(g(),T(new Error("Recorder was not active.")))})}}function mT(l){return`${l.text.trim()} +`}function yf(l){const n=Math.max(0,l),i=Math.floor(n/3600),r=Math.floor(n%3600/60),o=Math.floor(n%60),u=Math.round((n-Math.floor(n))*1e3);return`${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")},${String(u).padStart(3,"0")}`}function zg(l){return yf(l).replace(",",".")}function pT(l){return l.map((n,i)=>`${i+1} +${yf(n.startSeconds)} --> ${yf(n.endSeconds)} +${n.text.trim()} +`).join(` +`)}function gT(l){return`WEBVTT + +${l.map(i=>`${zg(i.startSeconds)} --> ${zg(i.endSeconds)} +${i.text.trim()} +`).join(` +`)}`}function af(l,n,i){const r=new Blob([n],{type:i}),o=URL.createObjectURL(r),u=document.createElement("a");u.href=o,u.download=l,u.click(),URL.revokeObjectURL(o)}function rf(){return`transcript-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}`}const Of=[{id:"whisper-tiny-multilingual-wasm",label:"Whisper Tiny (multilingual)",modelId:"onnx-community/whisper-tiny",revision:"ff4177021cc41f7db950912b73ea4fdf7d01d8e7",multilingual:!0,approximateDownloadBytes:77e6,devices:["wasm","webgpu"],dtypeByDevice:{wasm:"q8",webgpu:"fp32"},chunkLengthSeconds:30,strideLengthSeconds:5,maxDurationSeconds:10800}],yT=Of[0].id;function kT(l){return Of.find(n=>n.id===l)}function $l(l){return l<1e6?`${Math.round(l/1e3)} KB`:`${(l/1e6).toFixed(0)} MB`}class bT{worker=null;generation=0;pending=new Map;requestSeq=0;ensureWorker(){if(this.worker)return this.worker;const n=this.generation,i=new Worker(new URL(""+new URL("whisper.worker-CA5aZLsj.js",import.meta.url).href,import.meta.url),{type:"module"});return i.onmessage=r=>{n===this.generation&&this.handleMessage(r.data)},i.onerror=()=>{n===this.generation&&(this.failAll(new Error("Inference Worker crashed.")),this.hardReset())},this.worker=i,i}nextRequestId(){return this.requestSeq+=1,`req-${this.requestSeq}-${Date.now()}`}handleMessage(n){if(n.protocol!==1)return;const i=this.pending.get(n.requestId);if(i)switch(n.type){case"PROGRESS":i.onProgress?.(n.progress);break;case"READY":case"RESULT":case"DIAGNOSTICS":this.pending.delete(n.requestId),i.resolve(n);break;case"CANCELLED":this.pending.delete(n.requestId),i.reject(Object.assign(new Error("Cancelled"),{code:"CANCELLED"}));break;case"ERROR":this.pending.delete(n.requestId),i.reject(ST(n.error));break}}post(n,i=[],r){const o=this.ensureWorker();return new Promise((u,c)=>{this.pending.set(n.requestId,{resolve:u,reject:c,onProgress:r,kind:n.type}),o.postMessage(n,i)})}prepare(n,i,r){const o=this.nextRequestId();return this.post({protocol:1,type:"PREPARE",requestId:o,profileId:n,runtimePreference:i},[],r).then(u=>({diagnostics:u.diagnostics}))}transcribe(n){const i=this.nextRequestId(),r=n.audio;return this.post({protocol:1,type:"TRANSCRIBE",requestId:i,profileId:n.profileId,runtimePreference:n.runtimePreference,audio:r,options:{language:n.language,task:"transcribe",timestamps:n.timestamps}},[r.buffer],n.onProgress).then(o=>o.result)}async cancel(n){if(this.worker){if(n){const i=this.nextRequestId();try{await this.post({protocol:1,type:"CANCEL",requestId:i,targetRequestId:n})}catch{}}this.hardReset()}}hardReset(){this.generation+=1,this.failAll(Object.assign(new Error("Cancelled"),{code:"CANCELLED"})),this.worker?.terminate(),this.worker=null}dispose(){this.hardReset()}failAll(n){for(const[,i]of this.pending)i.reject(n);this.pending.clear()}}function ST(l){return Object.assign(new Error(l.code),{code:l.code,phase:l.phase,recoverable:l.recoverable,diagnostic:l.diagnostic})}const Qi=new bT;function TT(l,n){if(n)return n.message;if(!l)return"Working…";switch(l.phase){case"download":return l.ratio!=null?`Downloading model… ${Math.round(l.ratio*100)}%`:"Downloading model…";case"runtime-init":return"Initializing runtime…";case"model-init":return"Preparing model…";case"warmup":return"Warming up…";case"inference":return l.approximate?"Transcribing… (approximate)":"Transcribing…";case"finalize":return"Finalizing…";default:return"Working…"}}function ms(l){const n=Math.max(0,Math.floor(l)),i=Math.floor(n/3600),r=Math.floor(n%3600/60),o=n%60;return i>0?`${i}:${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`:`${r}:${String(o).padStart(2,"0")}`}function vT(){const[l,n]=tt.useState("idle"),[i,r]=tt.useState("auto"),[o,u]=tt.useState("segment"),[c,d]=tt.useState("auto"),[m,p]=tt.useState(yT),[y,g]=tt.useState(null),[b,T]=tt.useState(null),[w,S]=tt.useState(null),[E,x]=tt.useState("Select an audio/video file or record from the microphone."),[P,_]=tt.useState("neutral"),[D,B]=tt.useState(""),[z,L]=tt.useState(null),[H,R]=tt.useState(null),[X,W]=tt.useState(0),[Z,ie]=tt.useState(!1),ce=tt.useRef(null),re=tt.useRef(null),N=tt.useRef(null),J=tt.useMemo(()=>kT(m),[m]),ae=l==="normalizing"||l==="preparing-model"||l==="transcribing"||l==="cancelling"||l==="recording";tt.useEffect(()=>()=>{ce.current?.abort(),re.current?.cancel(),Qi.dispose()},[]);async function Te(de){ce.current?.abort();const ye=new AbortController;ce.current=ye,n("normalizing"),x("Inspecting media (duration, audio track)…"),_("neutral"),L(null),B(""),T(null),S(null);const je=$0(de);try{const We=await oT(de,{signal:ye.signal});if(ye.signal.aborted)return;if(!We.canDecodeAudio)throw new Ve("AUDIO_DECODE_UNSUPPORTED","decode","This browser cannot decode the audio track via WebCodecs.");const Et=lT(We,We.kind),Jt=[];if(Et&&Jt.push(`Conveyor mode: ${Xe.windowSeconds}s windows, ${Xe.overlapSeconds}s overlap — model stays loaded.`),Et){g({mode:"conveyor",blob:de,mediaKind:We.kind,durationSeconds:We.durationSeconds,warnings:Jt,sourceLabel:We.kind==="video"?"Video file":"Media file",byteLength:We.byteLength,formatName:We.formatName}),n("ready"),x(`Ready · ${We.kind} · ${ms(We.durationSeconds)} · ${$l(We.byteLength)} · windowed pipeline`),_("ok");return}x("Normalizing short clip to mono 16 kHz…");const yn=await nf(de,{signal:ye.signal,maxDurationSeconds:Xe.inlineDecodeMaxSeconds});if(ye.signal.aborted)return;g({mode:"inline",samples:yn.samples,durationSeconds:yn.durationSeconds,warnings:yn.warnings,sourceLabel:je==="video"?"Video file":"Uploaded file"}),n("ready"),x(yn.warnings[0]??`Ready · ${yn.durationSeconds.toFixed(1)}s · mono 16 kHz`),_(yn.warnings.length?"neutral":"ok")}catch(We){if(ye.signal.aborted)return;if(je!=="video"&&de.size<=Xe.inlineDecodeMaxBytes)try{const Jt=await nf(de,{signal:ye.signal,maxDurationSeconds:Xe.inlineDecodeMaxSeconds});if(ye.signal.aborted)return;g({mode:"inline",samples:Jt.samples,durationSeconds:Jt.durationSeconds,warnings:Jt.warnings,sourceLabel:"Uploaded file"}),n("ready"),x(Jt.warnings[0]??`Ready · ${Jt.durationSeconds.toFixed(1)}s · mono 16 kHz`),_(Jt.warnings.length?"neutral":"ok");return}catch{}const Et=We instanceof Ve?We.message:"Could not prepare the selected media.";g(null),n("error"),x(Et),_("error")}}async function Be(de){ce.current?.abort();const ye=new AbortController;ce.current=ye,n("normalizing"),x("Normalizing recording to mono 16 kHz…"),_("neutral"),L(null),B(""),T(null),S(null);try{const je=await nf(de,{signal:ye.signal});if(ye.signal.aborted)return;g({mode:"inline",samples:je.samples,durationSeconds:je.durationSeconds,warnings:je.warnings,sourceLabel:"Microphone recording"}),n("ready"),x(je.warnings[0]??`Ready · ${je.durationSeconds.toFixed(1)}s · mono 16 kHz`),_(je.warnings.length?"neutral":"ok")}catch(je){if(ye.signal.aborted)return;const We=je instanceof Ve?je.message:"Could not prepare the recording.";g(null),n("error"),x(We),_("error")}}async function O(de){de&&await Te(de)}async function Q(de){de.preventDefault(),ie(!1);const ye=de.dataTransfer.files?.[0];ye&&await O(ye)}async function ne(){if(!ae){Pe(!1),n("recording"),W(0),x("Recording… click Stop when finished."),_("neutral");try{const de=await hT(ye=>{W(ye)});re.current=de}catch{n("error"),x("Microphone permission denied or unavailable. File upload still works."),_("error")}}}async function le(){const de=re.current;if(de){re.current=null;try{const ye=await de.stop();await Be(ye)}catch{n("error"),x("Recording failed."),_("error")}}}async function pe(){if(!y||!J)return;const de=new AbortController;ce.current=de,n("preparing-model"),x("Preparing model… first run downloads ~"+$l(J.approximateDownloadBytes)),_("neutral"),T(null),S(null);try{const ye=await Qi.prepare(m,c,T);R(ye.diagnostics),ye.diagnostics.fallbackReasonCode&&x(`WebGPU unavailable — using WASM (${ye.diagnostics.fallbackReasonCode}).`),n("transcribing"),x(y.mode==="conveyor"?"Conveyor transcription started…":"Transcribing…");let je;if(y.mode==="conveyor")je=await dT({blob:y.blob,profileId:m,runtimePreference:c,language:i,timestamps:o,client:Qi,signal:de.signal,onModelProgress:T,onChunkProgress:Et=>{S(Et),T({phase:"inference",status:"running",ratio:Et.ratio,approximate:!0})},onPartialResult:Et=>{L(Et),B(Et.text)}});else{const Et=y.samples.slice();je=await Qi.transcribe({profileId:m,runtimePreference:c,audio:Et,language:i,timestamps:o,onProgress:T})}L(je),B(je.text),n("complete"),T(null),S(null);const We=je.warnings[0];x(We??(y.mode==="conveyor"?"Transcription complete via windowed pipeline. Media stayed on-device.":"Transcription complete. Audio and text stayed in this browser session.")),_(We?"neutral":"ok")}catch(ye){const je=ye&&typeof ye=="object"&&"code"in ye?String(ye.code):"";if(je==="CANCELLED"||ye instanceof Ve&&ye.code==="CANCELLED"){n(y?"ready":"idle"),x("Cancelled."),_("neutral"),T(null),S(null);return}n("error"),x(ye instanceof Ve?ye.message:je?`Transcription failed (${je}).`:"Transcription failed."),_("error"),T(null),S(null)}}async function we(){n("cancelling"),x("Cancelling…"),ce.current?.abort(),ce.current=new AbortController,re.current?.cancel(),re.current=null,await Qi.cancel(),n(y?"ready":"idle"),T(null),S(null),x("Cancelled. Session media still available until Clear."),_("neutral")}function Pe(de=!0){ce.current?.abort(),ce.current=new AbortController,re.current?.cancel(),re.current=null,Qi.hardReset(),g(null),L(null),B(""),T(null),S(null),R(null),W(0),n("idle"),de&&(x("Session cleared. Nothing was saved."),_("neutral")),N.current&&(N.current.value="")}function ht(){const de=mT({text:D,segments:z?.segments??[],durationSeconds:z?.durationSeconds??y?.durationSeconds??0,warnings:z?.warnings??[]});af(`${rf()}.txt`,de,"text/plain;charset=utf-8")}function Ze(){z?.segments.length&&af(`${rf()}.srt`,pT(z.segments),"application/x-subrip")}function Ia(){z?.segments.length&&af(`${rf()}.vtt`,gT(z.segments),"text/vtt")}async function li(){await navigator.clipboard.writeText(D),x("Copied to clipboard."),_("ok")}const oi=w?.ratio??b?.ratio;return te.jsxs("main",{className:"shell",children:[te.jsxs("header",{className:"brand",children:[te.jsx("h1",{children:"Whisper Transcriber"}),te.jsx("p",{children:"Private speech-to-text in your browser. Audio and video are processed in a windowed conveyor (mono 16 kHz chunks) so large files do not load full PCM into memory. The model stays resident across windows."})]}),te.jsxs("section",{className:"panel","aria-labelledby":"input-heading",children:[te.jsx("h2",{id:"input-heading",children:"Input"}),te.jsxs("div",{className:`dropzone${Z?" active":""}`,onDragEnter:de=>{de.preventDefault(),ie(!0)},onDragOver:de=>de.preventDefault(),onDragLeave:()=>ie(!1),onDrop:Q,children:["Drop an audio or video file here, or choose one below.",te.jsxs("div",{className:"field",style:{marginTop:"0.85rem"},children:[te.jsx("label",{htmlFor:"audio-file",children:"Audio / video file"}),te.jsx("input",{id:"audio-file",ref:N,type:"file",accept:"audio/*,video/*,.wav,.mp3,.m4a,.ogg,.webm,.flac,.mp4,.m4v,.mov,.mkv,.avi,.mpeg,.mpg,.ogv",disabled:ae,onChange:de=>{O(de.target.files?.[0]??null)}})]})]}),te.jsxs("div",{className:"actions",children:[l==="recording"?te.jsxs("button",{type:"button",className:"btn danger",onClick:()=>{le()},children:["Stop (",ms(X),")"]}):te.jsx("button",{type:"button",className:"btn secondary",disabled:ae,onClick:()=>{ne()},children:"Record microphone"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:l==="idle"&&!y&&!z,onClick:()=>Pe(),children:"Clear session"})]})]}),te.jsxs("section",{className:"panel","aria-labelledby":"settings-heading",children:[te.jsx("h2",{id:"settings-heading",children:"Settings"}),te.jsxs("div",{className:"row",children:[te.jsxs("div",{className:"field",children:[te.jsx("label",{htmlFor:"profile",children:"Model"}),te.jsx("select",{id:"profile",value:m,disabled:ae,onChange:de=>p(de.target.value),children:Of.map(de=>te.jsxs("option",{value:de.id,children:[de.label," (~",$l(de.approximateDownloadBytes),")"]},de.id))})]}),te.jsxs("div",{className:"field",children:[te.jsx("label",{htmlFor:"language",children:"Language"}),te.jsxs("select",{id:"language",value:i,disabled:ae,onChange:de=>r(de.target.value),children:[te.jsx("option",{value:"auto",children:"Automatic"}),te.jsx("option",{value:"en",children:"English"}),te.jsx("option",{value:"ru",children:"Russian"})]})]}),te.jsxs("div",{className:"field",children:[te.jsx("label",{htmlFor:"timestamps",children:"Timestamps"}),te.jsxs("select",{id:"timestamps",value:o,disabled:ae,onChange:de=>u(de.target.value),children:[te.jsx("option",{value:"segment",children:"Segment"}),te.jsx("option",{value:"none",children:"Off"})]})]}),te.jsxs("div",{className:"field",children:[te.jsx("label",{htmlFor:"runtime",children:"Runtime"}),te.jsxs("select",{id:"runtime",value:c,disabled:ae,onChange:de=>d(de.target.value),children:[te.jsx("option",{value:"auto",children:"Auto (WebGPU → WASM)"}),te.jsx("option",{value:"wasm",children:"WASM only"}),te.jsx("option",{value:"webgpu",children:"WebGPU preferred"})]})]})]}),te.jsxs("div",{className:"actions",children:[te.jsx("button",{type:"button",className:"btn",disabled:!y||ae,onClick:()=>{pe()},children:"Transcribe"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:!ae||l==="recording",onClick:()=>{we()},children:"Cancel"})]}),te.jsx("div",{className:"status","data-tone":P,role:"status","aria-live":"polite",children:ae&&l!=="recording"?TT(b,w):E}),oi!=null&&te.jsx("div",{className:"progress","aria-hidden":"true",children:te.jsx("span",{style:{width:`${Math.round(Math.min(1,Math.max(0,oi))*100)}%`}})})]}),te.jsxs("section",{className:"panel","aria-labelledby":"result-heading",children:[te.jsx("h2",{id:"result-heading",children:"Transcript"}),te.jsxs("label",{className:"field",htmlFor:"transcript",children:["Editable result",te.jsx("textarea",{id:"transcript",className:"transcript",value:D,onChange:de=>B(de.target.value),placeholder:"Transcript appears here after inference. Large media updates window by window."})]}),te.jsxs("div",{className:"actions",children:[te.jsx("button",{type:"button",className:"btn secondary",disabled:!D,onClick:()=>{li()},children:"Copy"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:!D,onClick:ht,children:"Export TXT"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:!z?.segments.length,onClick:Ze,children:"Export SRT"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:!z?.segments.length,onClick:Ia,children:"Export WebVTT"})]}),!!z?.segments.length&&te.jsx("ul",{className:"segments","aria-label":"Timestamped segments",children:z.segments.map((de,ye)=>te.jsxs("li",{children:[te.jsxs("time",{children:[ms(de.startSeconds),"–",ms(de.endSeconds)]}),te.jsx("span",{children:de.text})]},`${de.startSeconds}-${ye}`))})]}),te.jsxs("section",{className:"panel","aria-labelledby":"diagnostics-heading",children:[te.jsx("h2",{id:"diagnostics-heading",children:"Diagnostics"}),te.jsxs("div",{className:"meta",children:[te.jsxs("span",{children:["phase: ",l]}),te.jsxs("span",{children:["mode: ",y?.mode??"—"]}),te.jsxs("span",{children:["profile: ",J?.id??"—"]}),te.jsxs("span",{children:["source: ",y?.sourceLabel??"—"]}),y?.mode==="conveyor"&&te.jsxs(te.Fragment,{children:[te.jsxs("span",{children:["media: ",y.mediaKind]}),te.jsxs("span",{children:["bytes: ",$l(y.byteLength)]}),te.jsxs("span",{children:["format: ",y.formatName??"—"]})]}),te.jsxs("span",{children:["duration: ",y?ms(y.durationSeconds):"—"]}),te.jsxs("span",{children:["window: ",Xe.windowSeconds,"s / overlap ",Xe.overlapSeconds,"s"]}),te.jsxs("span",{children:["chunk:"," ",w?`${w.chunkIndex+1}/${w.chunkTotal}`:"—"]}),te.jsxs("span",{children:["runtime: ",H?.effectiveRuntime??"—"]}),te.jsxs("span",{children:["requested: ",H?.requestedRuntime??c]}),te.jsxs("span",{children:["prep: ",H?.preparationMs!=null?`${H.preparationMs} ms`:"—"]}),te.jsxs("span",{children:["build: ","0.1.0-prototype"," · ","0d8c0a8b93e2"]})]})]})]})}class wT extends tt.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(n,i){}render(){return this.state.hasError?te.jsxs("main",{className:"shell",children:[te.jsx("h1",{children:"Whisper Transcriber"}),te.jsx("p",{role:"alert",children:"Something went wrong. Reload the page to start a new session."}),te.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:"Reload"})]}):this.props.children}}Ib.createRoot(document.getElementById("root")).render(te.jsx(tt.StrictMode,{children:te.jsx(wT,{children:te.jsx(vT,{})})})); diff --git a/static/utility-apps/whisper-transcriber/assets/index-BWGSeFCx.css b/static/utility-apps/whisper-transcriber/assets/index-BWGSeFCx.css new file mode 100644 index 0000000..7afc7fb --- /dev/null +++ b/static/utility-apps/whisper-transcriber/assets/index-BWGSeFCx.css @@ -0,0 +1 @@ +:root{color-scheme:light;--bg: #f3efe6;--bg-accent: #e7eef2;--ink: #1c2429;--muted: #5a6870;--line: #c9d2d8;--accent: #0f6e56;--accent-ink: #06382c;--danger: #9b2c2c;--surface: rgba(255, 255, 255, .72);--focus: #0b57d0;--mono: "IBM Plex Mono", "Cascadia Mono", "Consolas", monospace;--sans: "IBM Plex Sans", "Segoe UI", sans-serif;--display: "Fraunces", "Iowan Old Style", Georgia, serif}@font-face{font-family:Fraunces;font-style:normal;font-weight:600;font-display:swap;src:local("Fraunces"),local("Georgia")}*{box-sizing:border-box}html,body,#root{min-height:100%}body{margin:0;font-family:var(--sans);color:var(--ink);background:radial-gradient(1200px 600px at 10% -10%,#dfe9ef 0%,transparent 55%),radial-gradient(900px 500px at 100% 0%,#d8ebe3 0%,transparent 50%),linear-gradient(180deg,var(--bg) 0%,var(--bg-accent) 100%)}button,input,select,textarea{font:inherit}button{cursor:pointer}.shell{width:min(920px,calc(100% - 2rem));margin:0 auto;padding:2.5rem 0 4rem;display:grid;gap:1.25rem}.brand{display:grid;gap:.35rem}.brand h1{margin:0;font-family:var(--display);font-size:clamp(2rem,4vw,2.75rem);letter-spacing:-.02em;color:var(--accent-ink)}.brand p{margin:0;color:var(--muted);max-width:42rem;line-height:1.5}.panel{background:var(--surface);border:1px solid var(--line);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem 1.1rem;display:grid;gap:.85rem}.panel h2{margin:0;font-size:.95rem;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);font-weight:600}.row{display:flex;flex-wrap:wrap;gap:.75rem;align-items:end}.field{display:grid;gap:.35rem;min-width:10rem}.field label{font-size:.85rem;color:var(--muted)}.field select,.field input[type=file]{border:1px solid var(--line);background:#fff;color:var(--ink);padding:.55rem .65rem}.dropzone{border:1px dashed var(--line);background:#ffffff8c;padding:1.1rem;text-align:center;color:var(--muted);transition:border-color .12s ease,background .12s ease}.dropzone.active{border-color:var(--accent);background:#0f6e560f;color:var(--accent-ink)}.actions{display:flex;flex-wrap:wrap;gap:.6rem}.btn{border:1px solid transparent;padding:.6rem .9rem;background:var(--accent);color:#fff}.btn:hover{filter:brightness(.96)}.btn:disabled{opacity:.5;cursor:not-allowed}.btn.secondary{background:#fff;color:var(--ink);border-color:var(--line)}.btn.danger{background:#fff;color:var(--danger);border-color:color-mix(in srgb,var(--danger) 35%,white)}.status{min-height:1.4rem;color:var(--muted);font-size:.95rem}.status[data-tone=error]{color:var(--danger)}.status[data-tone=ok]{color:var(--accent-ink)}.progress{height:.35rem;background:#d9e2e7;overflow:hidden}.progress>span{display:block;height:100%;background:var(--accent);width:0%;transition:width .16s ease}.meta{display:flex;flex-wrap:wrap;gap:.75rem 1.25rem;font-family:var(--mono);font-size:.78rem;color:var(--muted)}.transcript{width:100%;min-height:14rem;resize:vertical;border:1px solid var(--line);background:#fff;padding:.85rem;line-height:1.55}.segments{margin:0;padding:0;list-style:none;display:grid;gap:.45rem;font-size:.92rem}.segments li{display:grid;grid-template-columns:7.5rem 1fr;gap:.75rem}.segments time{font-family:var(--mono);font-size:.78rem;color:var(--muted)}:focus-visible{outline:2px solid var(--focus);outline-offset:2px}@media(max-width:640px){.segments li{grid-template-columns:1fr;gap:.15rem}} diff --git a/static/utility-apps/whisper-transcriber/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm b/static/utility-apps/whisper-transcriber/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm new file mode 100644 index 0000000..b05d1ad Binary files /dev/null and b/static/utility-apps/whisper-transcriber/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm differ diff --git a/static/utility-apps/whisper-transcriber/assets/whisper.worker-CA5aZLsj.js b/static/utility-apps/whisper-transcriber/assets/whisper.worker-CA5aZLsj.js new file mode 100644 index 0000000..522d811 --- /dev/null +++ b/static/utility-apps/whisper-transcriber/assets/whisper.worker-CA5aZLsj.js @@ -0,0 +1,2845 @@ +const ii=new Map,Pn=[],vx=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=ii.get(e);if(s===void 0)ii.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){const n=Pn.indexOf(e);n!==-1&&Pn.splice(n,1);for(let o=0;o{const r=ii.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{const t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},Tx=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Pn:t;let n;const o=[],i=new Set;for(const l of s){const c=await xx(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&i.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:c}of o)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);const a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?a:Reflect.get(l,c)})]},Ex="1.21.0";let Y_="warning";const vs={wasm:{},webgl:{},webgpu:{},versions:{common:Ex},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}`);Y_=e}},get logLevel(){return Y_}};Object.defineProperty(vs,"logLevel",{enumerable:!0});const Px=vs,Cx=(e,r)=>{const t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];const s=t.getContext("2d");if(s!=null){let n,o;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[3]):(n=e.dims[3],o=e.dims[2]);const i=r?.format!==void 0?r.format:"RGB",a=r?.norm;let l,c;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));const p=o*n;let d=0,u=p,f=p*2,_=-1;i==="RGBA"?(d=0,u=p,f=p*2,_=p*3):i==="RGB"?(d=0,u=p,f=p*2):i==="RBG"&&(d=0,f=p,u=p*2);for(let y=0;y{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let n,o,i;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[1],i=e.dims[3]):(n=e.dims[3],o=e.dims[2],i=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r?.norm;let c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));const d=o*n;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const u=4;let f=0,_=1,y=2,k=3,w=0,v=d,I=d*2,T=-1;a==="RGBA"?(w=0,v=d,I=d*2,T=d*3):a==="RGB"?(w=0,v=d,I=d*2):a==="RBG"&&(w=0,I=d,v=d*2),s=t.createImageData(n,o);for(let b=0;b{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:t,width:s}=r,n=r.norm??{mean:255,bias:0};let o,i;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?i=[n.bias,n.bias,n.bias,n.bias]:i=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3);let d=4,u=0,f=1,_=2,y=3,k=0,w=c,v=c*2,I=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,y=-1),l==="RGBA"?I=c*3:l==="RBG"?(k=0,v=c,w=c*2):l==="BGR"&&(v=0,w=c,k=c*2);for(let b=0;b{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,o=typeof e=="string";let i,a=r??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){const p=l();p.width=e.width,p.height=e.height;const d=c(p);if(d!=null){let u=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(u=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=u,a.width=f}else a.tensorFormat="RGBA",a.height=u,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,u).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){const u=l();u.width=d,u.height=p;const f=c(u);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(n){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");const p=l();p.width=e.width,p.height=e.height;const d=c(p);if(d!=null){const u=e.height,f=e.width;return d.drawImage(e,0,0,f,u),i=d.getImageData(0,0,f,u).data,a.height=u,a.width=f,ql(i,a)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,d)=>{const u=l(),f=c(u);if(!e||!f)return d();const _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{u.width=_.width,u.height=_.height,f.drawImage(_,0,0,u.width,u.height);const y=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(ql(y.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return ql(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},$x=(e,r)=>{const{width:t,height:s,download:n,dispose:o}=r,i=[1,s,t,4];return new ls({location:"texture",type:"float32",texture:e,dims:i,download:n,dispose:o})},kx=(e,r)=>{const{dataType:t,dims:s,download:n,dispose:o}=r;return new ls({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:n,dispose:o})},Ax=(e,r)=>{const{dataType:t,dims:s,download:n,dispose:o}=r;return new ls({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:n,dispose:o})},Fx=(e,r,t)=>new ls({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),ao=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),li=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Z_=!1;const Ox=()=>{if(!Z_){Z_=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(ao.set("int64",BigInt64Array),li.set(BigInt64Array,"int64")),r&&(ao.set("uint64",BigUint64Array),li.set(BigUint64Array,"uint64")),s?(ao.set("float16",t),li.set(t,"float16")):ao.set("float16",Uint16Array)}},Dx=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new ls(e.type,e.data,r);case"cpu-pinned":return new ls({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new ls({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new ls({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new ls({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let ls=class{constructor(r,t,s){Ox();let n,o;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,n=r.type,o=r.dims,r.location){case"cpu-pinned":{const a=ao.get(n);if(!a)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(r.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=r.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.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=r.gpuBuffer,this.downloader=r.download,this.disposer=r.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=r.mlTensor,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,l;if(typeof r=="string")if(n=r,l=s,r==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{const c=ao.get(r);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&c===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${c.name} as data.`);r==="uint64"||r==="int64"?a=c.from(t,BigInt):a=c.from(t)}else if(t instanceof c)a=t;else if(t instanceof Uint8ClampedArray)if(r==="uint8")a=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(r==="float16"&&t instanceof Uint16Array&&c!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const c=typeof r[0];if(c==="string")n="string",a=r;else if(c==="boolean")n="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(r instanceof Uint8ClampedArray)n="uint8",a=Uint8Array.from(r);else{const c=li.get(r.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);n=c,a=r}if(l===void 0)l=[a.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");o=l,this.cpuData=a,this.dataLocation="cpu"}const i=Dx(o);if(this.cpuData&&i!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=i}static async fromImage(r,t){return Ix(r,t)}static fromTexture(r,t){return $x(r,t)}static fromGpuBuffer(r,t){return kx(r,t)}static fromMLTensor(r,t){return Ax(r,t)}static fromPinnedBuffer(r,t,s){return Fx(r,t,s)}toDataURL(r){return Cx(this,r)}toImageData(r){return Sx(this,r)}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(r){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;const t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,r&&this.disposer&&(this.disposer(),this.disposer=void 0),t}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(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Lx(this,r)}};const so=ls,Ow=(e,r)=>{(typeof vs.trace>"u"?!vs.wasm.trace:!vs.trace)||console.timeStamp(`${e}::ORT::${r}`)},Dw=(e,r)=>{const t=new Error().stack?.split(/\r\n|\r|\n/g)||[];let s=!1;for(let n=0;n{(typeof vs.trace>"u"?!vs.wasm.trace:!vs.trace)||Dw("BEGIN",e)},Xc=e=>{(typeof vs.trace>"u"?!vs.wasm.trace:!vs.trace)||Dw("END",e)};let zx=class Lw{constructor(r){this.handler=r}async run(r,t,s){Qc();const n={};let o={};if(typeof r!="object"||r===null||r instanceof so||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof so)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(const c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1;const p=Object.getOwnPropertyNames(t);for(const d of this.outputNames)if(p.indexOf(d)!==-1){const u=t[d];(u===null||u instanceof so)&&(c=!0,i=!1,n[d]=u)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const c of this.inputNames)if(typeof r[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(i)for(const c of this.outputNames)n[c]=null;const a=await this.handler.run(r,n,o),l={};for(const c in a)if(Object.hasOwnProperty.call(a,c)){const p=a[c];p instanceof so?l[c]=p:l[c]=new so(p.type,p.data,p.dims)}return Xc(),l}async release(){return this.handler.dispose()}static async create(r,t,s,n){Qc();let o,i={};if(typeof r=="string"){if(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){const p=r;let d=0,u=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(u=r.byteLength-d,typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||d+u>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,d,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await Tx(i),c=await a.createInferenceSessionHandler(o,l);return Xc(),new Lw(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const Bx=zx;var Rx=Object.freeze({__proto__:null,InferenceSession:Bx,TRACE:Ow,TRACE_FUNC_BEGIN:Qc,TRACE_FUNC_END:Xc,Tensor:so,env:Px,registerBackend:vx});var mu=Object.defineProperty,Nx=Object.getOwnPropertyDescriptor,jx=Object.getOwnPropertyNames,Vx=Object.prototype.hasOwnProperty,Ux=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ve=(e,r)=>()=>(e&&(r=e(e=0)),r),uo=(e,r)=>{for(var t in r)mu(e,t,{get:r[t],enumerable:!0})},Wx=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of jx(r))!Vx.call(e,n)&&n!==t&&mu(e,n,{get:()=>r[n],enumerable:!(s=Nx(r,n))||s.enumerable});return e},Jo=e=>Wx(mu({},"__esModule",{value:!0}),e),Lo,nn,In,ef,zw,Bw=Ve(()=>{Lo=new Map,nn=[],In=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=Lo.get(e);if(s===void 0)Lo.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){let n=nn.indexOf(e);n!==-1&&nn.splice(n,1);for(let o=0;o{let r=Lo.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{let t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},zw=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?nn:t,n,o=[],i=new Set;for(let l of s){let c=await ef(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&i.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?a:Reflect.get(l,c)})]}}),Gx=Ve(()=>{Bw()}),Rw,Kx=Ve(()=>{Rw="1.22.0-dev.20250409-89f8206ba4"}),Ql,is,Nw=Ve(()=>{Kx(),Ql="warning",is={wasm:{},webgl:{},webgpu:{},versions:{common:Rw},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}`);Ql=e}},get logLevel(){return Ql}},Object.defineProperty(is,"logLevel",{enumerable:!0})}),Jt,Hx=Ve(()=>{Nw(),Jt=is}),jw,Vw,qx=Ve(()=>{jw=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];let s=t.getContext("2d");if(s!=null){let n,o;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[3]):(n=e.dims[3],o=e.dims[2]);let i=r?.format!==void 0?r.format:"RGB",a=r?.norm,l,c;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));let p=o*n,d=0,u=p,f=p*2,_=-1;i==="RGBA"?(d=0,u=p,f=p*2,_=p*3):i==="RGB"?(d=0,u=p,f=p*2):i==="RBG"&&(d=0,f=p,u=p*2);for(let y=0;y{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let n,o,i;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[1],i=e.dims[3]):(n=e.dims[3],o=e.dims[2],i=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let d=o*n;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let u=4,f=0,_=1,y=2,k=3,w=0,v=d,I=d*2,T=-1;a==="RGBA"?(w=0,v=d,I=d*2,T=d*3):a==="RGB"?(w=0,v=d,I=d*2):a==="RBG"&&(w=0,I=d,v=d*2),s=t.createImageData(n,o);for(let b=0;b{hu(),Ha=(e,r)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:s}=r,n=r.norm??{mean:255,bias:0},o,i;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?i=[n.bias,n.bias,n.bias,n.bias]:i=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),d=4,u=0,f=1,_=2,y=3,k=0,w=c,v=c*2,I=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,y=-1),l==="RGBA"?I=c*3:l==="RBG"?(k=0,v=c,w=c*2):l==="BGR"&&(v=0,w=c,k=c*2);for(let T=0;T{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,o=typeof e=="string",i,a=r??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){let p=l();p.width=e.width,p.height=e.height;let d=c(p);if(d!=null){let u=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(u=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=u,a.width=f}else a.tensorFormat="RGBA",a.height=u,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,u).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){let u=l();u.width=d,u.height=p;let f=c(u);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(n){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=e.width,p.height=e.height;let d=c(p);if(d!=null){let u=e.height,f=e.width;return d.drawImage(e,0,0,f,u),i=d.getImageData(0,0,f,u).data,a.height=u,a.width=f,Ha(i,a)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,d)=>{let u=l(),f=c(u);if(!e||!f)return d();let _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{u.width=_.width,u.height=_.height,f.drawImage(_,0,0,u.width,u.height);let y=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(Ha(y.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Ha(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Ww=(e,r)=>{let{width:t,height:s,download:n,dispose:o}=r,i=[1,s,t,4];return new Zr({location:"texture",type:"float32",texture:e,dims:i,download:n,dispose:o})},Gw=(e,r)=>{let{dataType:t,dims:s,download:n,dispose:o}=r;return new Zr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:n,dispose:o})},Kw=(e,r)=>{let{dataType:t,dims:s,download:n,dispose:o}=r;return new Zr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:n,dispose:o})},Hw=(e,r,t)=>new Zr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),Cn,Ko,Xl,qw,Xx=Ve(()=>{Cn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Ko=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Xl=!1,qw=()=>{if(!Xl){Xl=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(Cn.set("int64",BigInt64Array),Ko.set(BigInt64Array,"int64")),r&&(Cn.set("uint64",BigUint64Array),Ko.set(BigUint64Array,"uint64")),s?(Cn.set("float16",t),Ko.set(t,"float16")):Cn.set("float16",Uint16Array)}}}),Qw,Xw,Jx=Ve(()=>{hu(),Qw=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Zr(e.type,e.data,r);case"cpu-pinned":return new Zr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Zr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Zr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Zr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Zr,hu=Ve(()=>{qx(),Qx(),Xx(),Jx(),Zr=class{constructor(e,r,t){qw();let s,n;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,n=e.dims,e.location){case"cpu-pinned":{let i=Cn.get(s);if(!i)throw new TypeError(`unsupported type "${s}" 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(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,a;if(typeof e=="string")if(s=e,a=t,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let l=Cn.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?i=l.from(r,BigInt):i=l.from(r)}else if(r instanceof l)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&&l!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(a=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",i=e;else if(l==="boolean")s="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(e);else{let l=Ko.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,i=e}if(a===void 0)a=[i.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");n=a,this.cpuData=i,this.dataLocation="cpu"}let o=Qw(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(e,r){return Uw(e,r)}static fromTexture(e,r){return Ww(e,r)}static fromGpuBuffer(e,r){return Gw(e,r)}static fromMLTensor(e,r){return Kw(e,r)}static fromPinnedBuffer(e,r,t){return Hw(e,r,t)}toDataURL(e){return jw(this,e)}toImageData(e){return Vw(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 Xw(this,e)}}}),ys,Jw=Ve(()=>{hu(),ys=Zr}),Yo,Jl,Ts,us,Yw=Ve(()=>{Nw(),Yo=(e,r)=>{(typeof is.trace>"u"?!is.wasm.trace:!is.trace)||console.timeStamp(`${e}::ORT::${r}`)},Jl=(e,r)=>{let t=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof is.trace>"u"?!is.wasm.trace:!is.trace)||Jl("BEGIN",e)},us=e=>{(typeof is.trace>"u"?!is.wasm.trace:!is.trace)||Jl("END",e)}}),Zw,Yx=Ve(()=>{Bw(),Jw(),Yw(),Zw=class eb{constructor(r){this.handler=r}async run(r,t,s){Ts();let n={},o={};if(typeof r!="object"||r===null||r instanceof ys||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof ys)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(t);for(let d of this.outputNames)if(p.indexOf(d)!==-1){let u=t[d];(u===null||u instanceof ys)&&(c=!0,i=!1,n[d]=u)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof r[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(i)for(let c of this.outputNames)n[c]=null;let a=await this.handler.run(r,n,o),l={};for(let c in a)if(Object.hasOwnProperty.call(a,c)){let p=a[c];p instanceof ys?l[c]=p:l[c]=new ys(p.type,p.data,p.dims)}return us(),l}async release(){return this.handler.dispose()}static async create(r,t,s,n){Ts();let o,i={};if(typeof r=="string"){if(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){let p=r,d=0,u=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(u=r.byteLength-d,typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||d+u>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,d,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await zw(i),c=await a.createInferenceSessionHandler(o,l);return us(),new eb(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),_u,Zx=Ve(()=>{Yx(),_u=Zw}),eT=Ve(()=>{}),tT=Ve(()=>{}),rT=Ve(()=>{}),sT=Ve(()=>{}),tb={};uo(tb,{InferenceSession:()=>_u,TRACE:()=>Yo,TRACE_FUNC_BEGIN:()=>Ts,TRACE_FUNC_END:()=>us,Tensor:()=>ys,env:()=>Jt,registerBackend:()=>In});var Es=Ve(()=>{Gx(),Hx(),Zx(),Jw(),eT(),tT(),Yw(),rT(),sT()}),fu=Ve(()=>{}),rb={};uo(rb,{default:()=>sb});var Yl,Zl,sb,nT=Ve(()=>{lv(),Fn(),gu(),Yl="ort-wasm-proxy-worker",Zl=globalThis.self?.name===Yl,Zl&&(self.onmessage=e=>{let{type:r,in:t}=e.data;try{switch(r){case"init-wasm":Mu(t.wasm).then(()=>{Lu(t).then(()=>{postMessage({type:r})},s=>{postMessage({type:r,err:s})})},s=>{postMessage({type:r,err:s})});break;case"init-ep":{let{epName:s,env:n}=t;zu(n,s).then(()=>{postMessage({type:r})},o=>{postMessage({type:r,err:o})});break}case"copy-from":{let{buffer:s}=t,n=gi(s);postMessage({type:r,out:n});break}case"create":{let{model:s,options:n}=t;Bu(s,n).then(o=>{postMessage({type:r,out:o})},o=>{postMessage({type:r,err:o})});break}case"release":Ru(t),postMessage({type:r});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:i,options:a}=t;Nu(s,n,o,i,new Array(i.length).fill(null),a).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:l},Vu([...o,...l]))},l=>{postMessage({type:r,err:l})});break}case"end-profiling":ju(t),postMessage({type:r});break;default:}}catch(s){postMessage({type:r,err:s})}}),sb=Zl?null:e=>new Worker(e??Yr,{type:"module",name:Yl})}),nb={};uo(nb,{default:()=>ob});var ec,tc,ob,tf,oT=Ve(()=>{tc=(ec=import.meta.url,async function(e={}){var r,t,s=e,n=new Promise((h,P)=>{r=h,t=P}),o=typeof window=="object",i=typeof WorkerGlobalScope<"u",a=i&&self.name?.startsWith("em-pthread");s.mountExternalData=(h,P)=>{h.startsWith("./")&&(h=h.substring(2)),(s.Eb||(s.Eb=new Map)).set(h,P)},s.unmountExternalData=()=>{delete s.Eb};var l=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let c=h=>async(...P)=>{try{if(s.Fb)throw Error("Session already started");let A=s.Fb={dc:P[0],errors:[]},L=await h(...P);if(s.Fb!==A)throw Error("Session mismatch");s.Jb?.flush();let V=A.errors;if(0Pe),0{if(h==="webgpu"){[s.Jb,s.Ub,s.Yb,s.Kb,s.Xb,s.jb,s.Zb,s.ac,s.Vb,s.Wb,s.$b]=P;let A=s.Jb;s.jsepRegisterBuffer=(L,V,ie,Pe)=>A.registerBuffer(L,V,ie,Pe),s.jsepGetBuffer=L=>A.getBuffer(L),s.jsepCreateDownloader=(L,V,ie)=>A.createDownloader(L,V,ie),s.jsepOnCreateSession=L=>{A.onCreateSession(L)},s.jsepOnReleaseSession=L=>{A.onReleaseSession(L)},s.jsepOnRunStart=L=>A.onRunStart(L),s.bc=(L,V)=>{A.upload(L,V)}}else if(h==="webnn"){let A=P[0];[s.nc,s.Nb,s.webnnEnsureTensor,s.Ob,s.webnnDownloadTensor]=P.slice(1),s.webnnReleaseTensorId=s.Nb,s.webnnUploadTensor=s.Ob,s.webnnOnRunStart=L=>A.onRunStart(L),s.webnnOnRunEnd=A.onRunEnd.bind(A),s.webnnRegisterMLContext=(L,V)=>{A.registerMLContext(L,V)},s.webnnOnReleaseSession=L=>{A.onReleaseSession(L)},s.webnnCreateMLTensorDownloader=(L,V)=>A.createMLTensorDownloader(L,V),s.webnnRegisterMLTensor=(L,V,ie,Pe)=>A.registerMLTensor(L,V,ie,Pe),s.webnnCreateMLContext=L=>A.createMLContext(L),s.webnnRegisterMLConstant=(L,V,ie,Pe,Be,Qe)=>A.registerMLConstant(L,V,ie,Pe,Be,s.Eb,Qe),s.webnnRegisterGraphInput=A.registerGraphInput.bind(A),s.webnnIsGraphInput=A.isGraphInput.bind(A),s.webnnCreateTemporaryTensor=A.createTemporaryTensor.bind(A),s.webnnIsInt64Supported=A.isInt64Supported.bind(A)}};let p=()=>{let h=(P,A,L)=>(...V)=>{let ie=Ht,Pe=A?.();V=P(...V);let Be=A?.();return Pe!==Be&&(P=Be,L(Pe),A=L=null),Ht!=ie?new Promise((Qe,at)=>{hr={resolve:Qe,reject:at}}):V};(()=>{for(let P of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])s[P]=h(s[P],()=>s[P],A=>s[P]=A)})(),c!==void 0&&(s._OrtRun=c(s._OrtRun),s._OrtRunWithBinding=c(s._OrtRunWithBinding)),p=void 0};s.asyncInit=()=>{p?.()};var d,u,f=Object.assign({},s),_=(h,P)=>{throw P},y="";(o||i)&&(i?y=self.location.href:typeof document<"u"&&document.currentScript&&(y=document.currentScript.src),ec&&(y=ec),y=y.startsWith("blob:")?"":y.slice(0,y.replace(/[?#].*/,"").lastIndexOf("/")+1),i&&(u=h=>{var P=new XMLHttpRequest;return P.open("GET",h,!1),P.responseType="arraybuffer",P.send(null),new Uint8Array(P.response)}),d=async h=>{if(le(h))return new Promise((A,L)=>{var V=new XMLHttpRequest;V.open("GET",h,!0),V.responseType="arraybuffer",V.onload=()=>{V.status==200||V.status==0&&V.response?A(V.response):L(V.status)},V.onerror=L,V.send(null)});var P=await fetch(h,{credentials:"same-origin"});if(P.ok)return P.arrayBuffer();throw Error(P.status+" : "+P.url)});var k=console.log.bind(console),w=console.error.bind(console),v=k,I=w;Object.assign(s,f),f=null;var T,b,E,x,S,O,F,H,W,B,Y,X,J,re=s.wasmBinary,ne=!1,le=h=>h.startsWith("file://");function pe(){return T.buffer!=x.buffer&&Te(),x}function oe(){return T.buffer!=x.buffer&&Te(),S}function K(){return T.buffer!=x.buffer&&Te(),O}function N(){return T.buffer!=x.buffer&&Te(),F}function D(){return T.buffer!=x.buffer&&Te(),H}function te(){return T.buffer!=x.buffer&&Te(),W}function he(){return T.buffer!=x.buffer&&Te(),B}function Ae(){return T.buffer!=x.buffer&&Te(),J}if(a){let h=function(P){try{var A=P.data,L=A.Bb;if(L==="load"){let V=[];self.onmessage=ie=>V.push(ie),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let ie of V)h(ie);self.onmessage=h};for(let ie of A.Rb)s[ie]&&!s[ie].proxy||(s[ie]=(...Pe)=>{postMessage({Bb:"callHandler",Qb:ie,args:Pe})},ie=="print"&&(v=s[ie]),ie=="printErr"&&(I=s[ie]));T=A.kc,Te(),Ie(A.lc)}else if(L==="run"){qs(A.Ab),fn(A.Ab,0,0,1,0,0),Or(),ee(A.Ab),je||(mn(),je=!0);try{Qs(A.fc,A.Hb)}catch(V){if(V!="unwind")throw V}}else A.target!=="setimmediate"&&(L==="checkMailbox"?je&&se():L&&(I(`worker: received unknown command ${L}`),I(A)))}catch(V){throw Po(),V}};var Ie,je=!1;I=function(...P){P=P.join(" "),console.error(P)},self.alert=function(...P){postMessage({Bb:"alert",text:P.join(" "),ic:hn()})},self.onunhandledrejection=P=>{throw P.reason||P},self.onmessage=h}function Te(){var h=T.buffer;s.HEAP8=x=new Int8Array(h),s.HEAP16=O=new Int16Array(h),s.HEAPU8=S=new Uint8Array(h),s.HEAPU16=F=new Uint16Array(h),s.HEAP32=H=new Int32Array(h),s.HEAPU32=W=new Uint32Array(h),s.HEAPF32=B=new Float32Array(h),s.HEAPF64=J=new Float64Array(h),s.HEAP64=Y=new BigInt64Array(h),s.HEAPU64=X=new BigUint64Array(h)}function Q(){a?startWorker(s):dt.Ca()}a||(T=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Te());var z,de=0,be=null;function ve(){if(--de==0&&be){var h=be;be=null,h()}}function xe(h){throw I(h="Aborted("+h+")"),ne=!0,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),t(h),h}function Ce(){return{a:{L:fe,Aa:De,b:or,$:Qr,A:Ps,pa:Cs,X:Ss,Z:C,qa:q,na:R,ga:G,ma:Z,J:ce,Y:ye,V:et,oa:ut,W:He,va:Tt,E:Is,Q:$s,O:Rs,D:As,u:Fs,r:ss,P:Nr,z:Dn,R:ue,ja:$,T:Me,aa:Xe,M:Je,F:Ye,ia:ee,sa:Ke,t:rr,Ba:br,w:ps,o:os,l:_r,c:ts,n:Ur,j:ra,v:sa,p:na,f:oa,s:Ys,m:aa,e:ia,k:la,i:ca,g:ua,d:Zs,da,ea:pa,fa:fo,ba:go,ca:Mo,N:Ln,xa:ha,ua:bi,h:bo,C:Rn,G:_a,ta:wo,x:fa,ra:ga,U:Ma,q:ma,y:wa,K:ba,S:yo,za:ya,ya:jn,ka:Ls,la:vo,_:Oe,B:va,I:xo,ha:xa,H:Wn,a:T,wa:Ze}}}var ge={829644:(h,P,A,L,V)=>{if(s===void 0||!s.Eb)return 1;if((h=qt(Number(h>>>0))).startsWith("./")&&(h=h.substring(2)),!(h=s.Eb.get(h)))return 2;if(P=Number(P>>>0),A=Number(A>>>0),L=Number(L>>>0),P+A>h.byteLength)return 3;try{let ie=h.subarray(P,P+A);switch(V){case 0:oe().set(ie,L>>>0);break;case 1:s.mc?s.mc(L,ie):s.bc(L,ie);break;default:return 4}return 0}catch{return 4}},830468:(h,P,A)=>{s.Ob(h,oe().subarray(P>>>0,P+A>>>0))},830532:()=>s.nc(),830574:h=>{s.Nb(h)},830611:()=>{s.Vb()},830642:()=>{s.Wb()},830671:()=>{s.$b()},830696:h=>s.Ub(h),830729:h=>s.Yb(h),830761:(h,P,A)=>{s.Kb(Number(h),Number(P),Number(A),!0)},830824:(h,P,A)=>{s.Kb(Number(h),Number(P),Number(A))},830881:()=>typeof wasmOffsetConverter<"u",830938:h=>{s.jb("Abs",h,void 0)},830989:h=>{s.jb("Neg",h,void 0)},831040:h=>{s.jb("Floor",h,void 0)},831093:h=>{s.jb("Ceil",h,void 0)},831145:h=>{s.jb("Reciprocal",h,void 0)},831203:h=>{s.jb("Sqrt",h,void 0)},831255:h=>{s.jb("Exp",h,void 0)},831306:h=>{s.jb("Erf",h,void 0)},831357:h=>{s.jb("Sigmoid",h,void 0)},831412:(h,P,A)=>{s.jb("HardSigmoid",h,{alpha:P,beta:A})},831491:h=>{s.jb("Log",h,void 0)},831542:h=>{s.jb("Sin",h,void 0)},831593:h=>{s.jb("Cos",h,void 0)},831644:h=>{s.jb("Tan",h,void 0)},831695:h=>{s.jb("Asin",h,void 0)},831747:h=>{s.jb("Acos",h,void 0)},831799:h=>{s.jb("Atan",h,void 0)},831851:h=>{s.jb("Sinh",h,void 0)},831903:h=>{s.jb("Cosh",h,void 0)},831955:h=>{s.jb("Asinh",h,void 0)},832008:h=>{s.jb("Acosh",h,void 0)},832061:h=>{s.jb("Atanh",h,void 0)},832114:h=>{s.jb("Tanh",h,void 0)},832166:h=>{s.jb("Not",h,void 0)},832217:(h,P,A)=>{s.jb("Clip",h,{min:P,max:A})},832286:h=>{s.jb("Clip",h,void 0)},832338:(h,P)=>{s.jb("Elu",h,{alpha:P})},832396:h=>{s.jb("Gelu",h,void 0)},832448:h=>{s.jb("Relu",h,void 0)},832500:(h,P)=>{s.jb("LeakyRelu",h,{alpha:P})},832564:(h,P)=>{s.jb("ThresholdedRelu",h,{alpha:P})},832634:(h,P)=>{s.jb("Cast",h,{to:P})},832692:h=>{s.jb("Add",h,void 0)},832743:h=>{s.jb("Sub",h,void 0)},832794:h=>{s.jb("Mul",h,void 0)},832845:h=>{s.jb("Div",h,void 0)},832896:h=>{s.jb("Pow",h,void 0)},832947:h=>{s.jb("Equal",h,void 0)},833e3:h=>{s.jb("Greater",h,void 0)},833055:h=>{s.jb("GreaterOrEqual",h,void 0)},833117:h=>{s.jb("Less",h,void 0)},833169:h=>{s.jb("LessOrEqual",h,void 0)},833228:(h,P,A,L,V)=>{s.jb("ReduceMean",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833403:(h,P,A,L,V)=>{s.jb("ReduceMax",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833577:(h,P,A,L,V)=>{s.jb("ReduceMin",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833751:(h,P,A,L,V)=>{s.jb("ReduceProd",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833926:(h,P,A,L,V)=>{s.jb("ReduceSum",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834100:(h,P,A,L,V)=>{s.jb("ReduceL1",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834273:(h,P,A,L,V)=>{s.jb("ReduceL2",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834446:(h,P,A,L,V)=>{s.jb("ReduceLogSum",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834623:(h,P,A,L,V)=>{s.jb("ReduceSumSquare",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834803:(h,P,A,L,V)=>{s.jb("ReduceLogSumExp",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834983:h=>{s.jb("Where",h,void 0)},835036:(h,P,A)=>{s.jb("Transpose",h,{perm:P?Array.from(D().subarray(Number(P)>>>0,Number(A)>>>0)):[]})},835160:(h,P,A,L)=>{s.jb("DepthToSpace",h,{blocksize:P,mode:qt(A),format:L?"NHWC":"NCHW"})},835293:(h,P,A,L)=>{s.jb("DepthToSpace",h,{blocksize:P,mode:qt(A),format:L?"NHWC":"NCHW"})},835426:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr,Us)=>{s.jb("ConvTranspose",h,{format:Qe?"NHWC":"NCHW",autoPad:P,dilations:[A],group:L,kernelShape:[V],pads:[ie,Pe],strides:[Be],wIsConst:()=>!!pe()[at>>>0],outputPadding:vt?Array.from(D().subarray(Number(vt)>>>0,Number(Ot)>>>0)):[],outputShape:Vt?Array.from(D().subarray(Number(Vt)>>>0,Number(xr)>>>0)):[],activation:qt(Us)})},835859:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("ConvTranspose",h,{format:Be?"NHWC":"NCHW",autoPad:P,dilations:Array.from(D().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:L,kernelShape:Array.from(D().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(D().subarray(Number(ie)>>>0,4+(Number(ie)>>>0)>>>0)),strides:Array.from(D().subarray(Number(Pe)>>>0,2+(Number(Pe)>>>0)>>>0)),wIsConst:()=>!!pe()[Qe>>>0],outputPadding:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],outputShape:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[],activation:qt(xr)})},836520:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr,Us)=>{s.jb("ConvTranspose",h,{format:Qe?"NHWC":"NCHW",autoPad:P,dilations:[A],group:L,kernelShape:[V],pads:[ie,Pe],strides:[Be],wIsConst:()=>!!pe()[at>>>0],outputPadding:vt?Array.from(D().subarray(Number(vt)>>>0,Number(Ot)>>>0)):[],outputShape:Vt?Array.from(D().subarray(Number(Vt)>>>0,Number(xr)>>>0)):[],activation:qt(Us)})},836953:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("ConvTranspose",h,{format:Be?"NHWC":"NCHW",autoPad:P,dilations:Array.from(D().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:L,kernelShape:Array.from(D().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(D().subarray(Number(ie)>>>0,4+(Number(ie)>>>0)>>>0)),strides:Array.from(D().subarray(Number(Pe)>>>0,2+(Number(Pe)>>>0)>>>0)),wIsConst:()=>!!pe()[Qe>>>0],outputPadding:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],outputShape:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[],activation:qt(xr)})},837614:(h,P)=>{s.jb("GlobalAveragePool",h,{format:P?"NHWC":"NCHW"})},837705:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("AveragePool",h,{format:xr?"NHWC":"NCHW",auto_pad:P,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],strides:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[]})},838184:(h,P)=>{s.jb("GlobalAveragePool",h,{format:P?"NHWC":"NCHW"})},838275:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("AveragePool",h,{format:xr?"NHWC":"NCHW",auto_pad:P,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],strides:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[]})},838754:(h,P)=>{s.jb("GlobalMaxPool",h,{format:P?"NHWC":"NCHW"})},838841:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("MaxPool",h,{format:xr?"NHWC":"NCHW",auto_pad:P,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],strides:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[]})},839316:(h,P)=>{s.jb("GlobalMaxPool",h,{format:P?"NHWC":"NCHW"})},839403:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("MaxPool",h,{format:xr?"NHWC":"NCHW",auto_pad:P,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],strides:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[]})},839878:(h,P,A,L,V)=>{s.jb("Gemm",h,{alpha:P,beta:A,transA:L,transB:V})},839982:h=>{s.jb("MatMul",h,void 0)},840036:(h,P,A,L)=>{s.jb("ArgMax",h,{keepDims:!!P,selectLastIndex:!!A,axis:L})},840144:(h,P,A,L)=>{s.jb("ArgMin",h,{keepDims:!!P,selectLastIndex:!!A,axis:L})},840252:(h,P)=>{s.jb("Softmax",h,{axis:P})},840315:(h,P)=>{s.jb("Concat",h,{axis:P})},840375:(h,P,A,L,V)=>{s.jb("Split",h,{axis:P,numOutputs:A,splitSizes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},840531:h=>{s.jb("Expand",h,void 0)},840585:(h,P)=>{s.jb("Gather",h,{axis:Number(P)})},840656:(h,P)=>{s.jb("GatherElements",h,{axis:Number(P)})},840735:(h,P)=>{s.jb("GatherND",h,{batch_dims:Number(P)})},840814:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt)=>{s.jb("Resize",h,{antialias:P,axes:A?Array.from(D().subarray(Number(A)>>>0,Number(L)>>>0)):[],coordinateTransformMode:qt(V),cubicCoeffA:ie,excludeOutside:Pe,extrapolationValue:Be,keepAspectRatioPolicy:qt(Qe),mode:qt(at),nearestMode:qt(vt)})},841176:(h,P,A,L,V,ie,Pe)=>{s.jb("Slice",h,{starts:P?Array.from(D().subarray(Number(P)>>>0,Number(A)>>>0)):[],ends:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[],axes:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[]})},841440:h=>{s.jb("Tile",h,void 0)},841492:(h,P,A)=>{s.jb("InstanceNormalization",h,{epsilon:P,format:A?"NHWC":"NCHW"})},841606:(h,P,A)=>{s.jb("InstanceNormalization",h,{epsilon:P,format:A?"NHWC":"NCHW"})},841720:h=>{s.jb("Range",h,void 0)},841773:(h,P)=>{s.jb("Einsum",h,{equation:qt(P)})},841854:(h,P,A,L,V)=>{s.jb("Pad",h,{mode:P,value:A,pads:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},841997:(h,P,A,L,V,ie)=>{s.jb("BatchNormalization",h,{epsilon:P,momentum:A,spatial:!!V,trainingMode:!!L,format:ie?"NHWC":"NCHW"})},842166:(h,P,A,L,V,ie)=>{s.jb("BatchNormalization",h,{epsilon:P,momentum:A,spatial:!!V,trainingMode:!!L,format:ie?"NHWC":"NCHW"})},842335:(h,P,A)=>{s.jb("CumSum",h,{exclusive:Number(P),reverse:Number(A)})},842432:(h,P,A)=>{s.jb("DequantizeLinear",h,{axis:P,blockSize:A})},842522:(h,P,A,L,V)=>{s.jb("GridSample",h,{align_corners:P,mode:qt(A),padding_mode:qt(L),format:V?"NHWC":"NCHW"})},842692:(h,P,A,L,V)=>{s.jb("GridSample",h,{align_corners:P,mode:qt(A),padding_mode:qt(L),format:V?"NHWC":"NCHW"})},842862:(h,P)=>{s.jb("ScatterND",h,{reduction:qt(P)})},842947:(h,P,A,L,V,ie,Pe,Be,Qe)=>{s.jb("Attention",h,{numHeads:P,isUnidirectional:A,maskFilterValue:L,scale:V,doRotary:ie,qkvHiddenSizes:Pe?Array.from(D().subarray(Number(Be)>>>0,Number(Be)+Pe>>>0)):[],pastPresentShareBuffer:!!Qe})},843219:h=>{s.jb("BiasAdd",h,void 0)},843274:h=>{s.jb("BiasSplitGelu",h,void 0)},843335:h=>{s.jb("FastGelu",h,void 0)},843391:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr,Us,Pa)=>{s.jb("Conv",h,{format:Ot?"NHWC":"NCHW",auto_pad:P,dilations:A?Array.from(D().subarray(Number(A)>>>0,Number(L)>>>0)):[],group:V,kernel_shape:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],pads:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],strides:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],w_is_const:()=>!!pe()[Number(Vt)>>>0],activation:qt(xr),activation_params:Us?Array.from(he().subarray(Number(Us)>>>0,Number(Pa)>>>0)):[]})},843975:h=>{s.jb("Gelu",h,void 0)},844027:(h,P,A,L,V,ie,Pe,Be,Qe)=>{s.jb("GroupQueryAttention",h,{numHeads:P,kvNumHeads:A,scale:L,softcap:V,doRotary:ie,rotaryInterleaved:Pe,smoothSoftmax:Be,localWindowSize:Qe})},844244:(h,P,A,L)=>{s.jb("LayerNormalization",h,{axis:P,epsilon:A,simplified:!!L})},844355:(h,P,A,L)=>{s.jb("LayerNormalization",h,{axis:P,epsilon:A,simplified:!!L})},844466:(h,P,A,L,V,ie)=>{s.jb("MatMulNBits",h,{k:P,n:A,accuracyLevel:L,bits:V,blockSize:ie})},844593:(h,P,A,L,V,ie)=>{s.jb("MultiHeadAttention",h,{numHeads:P,isUnidirectional:A,maskFilterValue:L,scale:V,doRotary:ie})},844752:(h,P)=>{s.jb("QuickGelu",h,{alpha:P})},844816:(h,P,A,L,V)=>{s.jb("RotaryEmbedding",h,{interleaved:!!P,numHeads:A,rotaryEmbeddingDim:L,scale:V})},844955:(h,P,A)=>{s.jb("SkipLayerNormalization",h,{epsilon:P,simplified:!!A})},845057:(h,P,A)=>{s.jb("SkipLayerNormalization",h,{epsilon:P,simplified:!!A})},845159:(h,P,A,L)=>{s.jb("GatherBlockQuantized",h,{gatherAxis:P,quantizeAxis:A,blockSize:L})},845280:h=>{s.Zb(h)},845314:(h,P)=>s.ac(Number(h),Number(P),s.Fb.dc,s.Fb.errors)};function De(h,P,A){return Xr(async()=>{await s.Xb(Number(h),Number(P),Number(A))})}function fe(){return typeof wasmOffsetConverter<"u"}class Ee{name="ExitStatus";constructor(P){this.message=`Program terminated with exit(${P})`,this.status=P}}var We=h=>{h.terminate(),h.onmessage=()=>{}},Fe=[],tt=h=>{ot.length==0&&(Rr(),zt(ot[0]));var P=ot.pop();if(!P)return 6;ht.push(P),It[h.Ab]=P,P.Ab=h.Ab;var A={Bb:"run",fc:h.ec,Hb:h.Hb,Ab:h.Ab};return P.postMessage(A,h.Mb),0},Re=0,rt=(h,P,...A)=>{for(var L=2*A.length,V=qn(),ie=Mn(8*L),Pe=ie>>>3,Be=0;Be>>0]=Qe)}return h=Co(h,0,L,ie,P),gn(V),h};function Ze(h){if(a)return rt(0,1,h);if(E=h,!(0{if(E=h,a)throw Ne(h),"unwind";Ze(h)},ot=[],ht=[],Rt=[],It={},gr=h=>{var P=h.Ab;delete It[P],ot.push(h),ht.splice(ht.indexOf(h),1),h.Ab=0,Gn(P)};function Or(){Rt.forEach(h=>h())}var zt=h=>new Promise(P=>{h.onmessage=V=>{var ie=(V=V.data).Bb;if(V.Gb&&V.Gb!=hn()){var Pe=It[V.Gb];Pe?Pe.postMessage(V,V.Mb):I(`Internal error! Worker sent a message "${ie}" to target pthread ${V.Gb}, but that thread no longer exists!`)}else ie==="checkMailbox"?se():ie==="spawnThread"?tt(V):ie==="cleanupThread"?gr(It[V.hc]):ie==="loaded"?(h.loaded=!0,P(h)):ie==="alert"?alert(`Thread ${V.ic}: ${V.text}`):V.target==="setimmediate"?h.postMessage(V):ie==="callHandler"?s[V.Qb](...V.args):ie&&I(`worker sent an unknown command ${ie}`)},h.onerror=V=>{throw I(`worker sent an error! ${V.filename}:${V.lineno}: ${V.message}`),V};var A,L=[];for(A of[])s.propertyIsEnumerable(A)&&L.push(A);h.postMessage({Bb:"load",Rb:L,kc:T,lc:b})});function Rr(){var h=new Worker((()=>{let P=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new P("ort.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});ot.push(h)}var qs=h=>{Te();var P=te()[h+52>>>2>>>0];h=te()[h+56>>>2>>>0],Io(P,P-h),gn(P)},Qs=(h,P)=>{Re=0,h=$o(h,P),0>>=0);throw P>>>=0,A>>>=0,te()[L.Ib+16>>>2>>>0]=0,te()[L.Ib+4>>>2>>>0]=P,te()[L.Ib+8>>>2>>>0]=A,h}function Sr(h,P,A,L){return a?rt(2,1,h,P,A,L):Qr(h,P,A,L)}function Qr(h,P,A,L){if(h>>>=0,A>>>=0,L>>>=0,l===void 0)return 6;var V=[];return a&&V.length===0?Sr(h,P>>>=0,A,L):(h={ec:A,Ab:h,Hb:L,Mb:V},a?(h.Bb="spawnThread",postMessage(h,V),0):tt(h))}var Bs=typeof TextDecoder<"u"?new TextDecoder:void 0,ft=(h,P=0,A=NaN)=>{var L=(P>>>=0)+A;for(A=P;h[A]&&!(A>=L);)++A;if(16(V=(240&V)==224?(15&V)<<12|ie<<6|Pe:(7&V)<<18|ie<<12|Pe<<6|63&h[P++])?L+=String.fromCharCode(V):(V-=65536,L+=String.fromCharCode(55296|V>>10,56320|1023&V))}}else L+=String.fromCharCode(V)}return L},qt=(h,P)=>(h>>>=0)?ft(oe(),h,P):"";function Ps(h,P,A){return a?rt(3,1,h,P,A):0}function Cs(h,P){if(a)return rt(4,1,h,P)}var Kr=h=>{for(var P=0,A=0;A=L?P++:2047>=L?P+=2:55296<=L&&57343>=L?(P+=4,++A):P+=3}return P},yt=(h,P,A)=>{var L=oe();if(P>>>=0,0=Pe&&(Pe=65536+((1023&Pe)<<10)|1023&h.charCodeAt(++ie)),127>=Pe){if(P>=A)break;L[P++>>>0]=Pe}else{if(2047>=Pe){if(P+1>=A)break;L[P++>>>0]=192|Pe>>6}else{if(65535>=Pe){if(P+2>=A)break;L[P++>>>0]=224|Pe>>12}else{if(P+3>=A)break;L[P++>>>0]=240|Pe>>18,L[P++>>>0]=128|Pe>>12&63}L[P++>>>0]=128|Pe>>6&63}L[P++>>>0]=128|63&Pe}}L[P>>>0]=0,h=P-V}else h=0;return h};function Ss(h,P){if(a)return rt(5,1,h,P)}function C(h,P,A){if(a)return rt(6,1,h,P,A)}function q(h,P,A){return a?rt(7,1,h,P,A):0}function R(h,P){if(a)return rt(8,1,h,P)}function G(h,P,A){if(a)return rt(9,1,h,P,A)}function Z(h,P,A,L){if(a)return rt(10,1,h,P,A,L)}function ce(h,P,A,L){if(a)return rt(11,1,h,P,A,L)}function ye(h,P,A,L){if(a)return rt(12,1,h,P,A,L)}function et(h){if(a)return rt(13,1,h)}function ut(h,P){if(a)return rt(14,1,h,P)}function He(h,P,A){if(a)return rt(15,1,h,P,A)}var Mt,qe,Tt=()=>xe(""),kt=h=>{for(var P="";oe()[h>>>0];)P+=Mt[oe()[h++>>>0]];return P},Mr={},dr={};function ar(h,P,A={}){return(function(L,V,ie={}){var Pe=V.name;if(!L)throw new qe(`type "${Pe}" must have a positive integer typeid pointer`);if(dr.hasOwnProperty(L)){if(ie.Sb)return;throw new qe(`Cannot register type '${Pe}' twice`)}dr[L]=V,Mr.hasOwnProperty(L)&&(V=Mr[L],delete Mr[L],V.forEach(Be=>Be()))})(h,P,A)}var Tr=(h,P,A)=>{switch(P){case 1:return A?L=>pe()[L>>>0]:L=>oe()[L>>>0];case 2:return A?L=>K()[L>>>1>>>0]:L=>N()[L>>>1>>>0];case 4:return A?L=>D()[L>>>2>>>0]:L=>te()[L>>>2>>>0];case 8:return A?L=>Y[L>>>3]:L=>X[L>>>3];default:throw new TypeError(`invalid integer width (${P}): ${h}`)}};function Is(h,P,A){A>>>=0,ar(h>>>=0,{name:P=kt(P>>>0),fromWireType:L=>L,toWireType:function(L,V){if(typeof V!="bigint"&&typeof V!="number")throw V=V===null?"null":(L=typeof V)=="object"||L==="array"||L==="function"?V.toString():""+V,new TypeError(`Cannot convert "${V}" to ${this.name}`);return typeof V=="number"&&(V=BigInt(V)),V},Cb:Dr,readValueFromPointer:Tr(P,A,P.indexOf("u")==-1),Db:null})}var Dr=8;function $s(h,P,A,L){ar(h>>>=0,{name:P=kt(P>>>0),fromWireType:function(V){return!!V},toWireType:function(V,ie){return ie?A:L},Cb:Dr,readValueFromPointer:function(V){return this.fromWireType(oe()[V>>>0])},Db:null})}var Lr=[],zr=[];function ts(h){9<(h>>>=0)&&--zr[h+1]==0&&(zr[h]=void 0,Lr.push(h))}var wr=h=>{if(!h)throw new qe("Cannot use deleted val. handle = "+h);return zr[h]},ir=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let P=Lr.pop()||zr.length;return zr[P]=h,zr[P+1]=1,P}};function Hr(h){return this.fromWireType(te()[h>>>2>>>0])}var rs={name:"emscripten::val",fromWireType:h=>{var P=wr(h);return ts(h),P},toWireType:(h,P)=>ir(P),Cb:Dr,readValueFromPointer:Hr,Db:null};function Rs(h){return ar(h>>>0,rs)}var ks=(h,P)=>{switch(P){case 4:return function(A){return this.fromWireType(he()[A>>>2>>>0])};case 8:return function(A){return this.fromWireType(Ae()[A>>>3>>>0])};default:throw new TypeError(`invalid float width (${P}): ${h}`)}};function As(h,P,A){A>>>=0,ar(h>>>=0,{name:P=kt(P>>>0),fromWireType:L=>L,toWireType:(L,V)=>V,Cb:Dr,readValueFromPointer:ks(P,A),Db:null})}function Fs(h,P,A,L,V){if(h>>>=0,A>>>=0,P=kt(P>>>0),V===-1&&(V=4294967295),V=Be=>Be,L===0){var ie=32-8*A;V=Be=>Be<>>ie}var Pe=P.includes("unsigned")?function(Be,Qe){return Qe>>>0}:function(Be,Qe){return Qe};ar(h,{name:P,fromWireType:V,toWireType:Pe,Cb:Dr,readValueFromPointer:Tr(P,A,L!==0),Db:null})}function ss(h,P,A){function L(ie){var Pe=te()[ie>>>2>>>0];return ie=te()[ie+4>>>2>>>0],new V(pe().buffer,ie,Pe)}var V=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][P];ar(h>>>=0,{name:A=kt(A>>>0),fromWireType:L,Cb:Dr,readValueFromPointer:L},{Sb:!0})}function Nr(h,P){ar(h>>>=0,{name:P=kt(P>>>0),fromWireType:function(A){for(var L,V=te()[A>>>2>>>0],ie=A+4,Pe=ie,Be=0;Be<=V;++Be){var Qe=ie+Be;Be!=V&&oe()[Qe>>>0]!=0||(Pe=qt(Pe,Qe-Pe),L===void 0?L=Pe:(L+="\0",L+=Pe),Pe=Qe+1)}return Jr(A),L},toWireType:function(A,L){L instanceof ArrayBuffer&&(L=new Uint8Array(L));var V=typeof L=="string";if(!(V||L instanceof Uint8Array||L instanceof Uint8ClampedArray||L instanceof Int8Array))throw new qe("Cannot pass non-string to std::string");var ie=V?Kr(L):L.length,Pe=_n(4+ie+1),Be=Pe+4;if(te()[Pe>>>2>>>0]=ie,V)yt(L,Be,ie+1);else if(V)for(V=0;V>>0]=Qe}else for(V=0;V>>0]=L[V];return A!==null&&A.push(Jr,Pe),Pe},Cb:Dr,readValueFromPointer:Hr,Db(A){Jr(A)}})}var ze=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Ue=(h,P)=>{for(var A=h>>1,L=A+P/2;!(A>=L)&&N()[A>>>0];)++A;if(32<(A<<=1)-h&&ze)return ze.decode(oe().slice(h,A));for(A="",L=0;!(L>=P/2);++L){var V=K()[h+2*L>>>1>>>0];if(V==0)break;A+=String.fromCharCode(V)}return A},nt=(h,P,A)=>{if(A??=2147483647,2>A)return 0;var L=P;A=(A-=2)<2*h.length?A/2:h.length;for(var V=0;V>>1>>>0]=ie,P+=2}return K()[P>>>1>>>0]=0,P-L},Kt=h=>2*h.length,Ns=(h,P)=>{for(var A=0,L="";!(A>=P/4);){var V=D()[h+4*A>>>2>>>0];if(V==0)break;++A,65536<=V?(V-=65536,L+=String.fromCharCode(55296|V>>10,56320|1023&V)):L+=String.fromCharCode(V)}return L},Os=(h,P,A)=>{if(P>>>=0,A??=2147483647,4>A)return 0;var L=P;A=L+A-4;for(var V=0;V=ie&&(ie=65536+((1023&ie)<<10)|1023&h.charCodeAt(++V)),D()[P>>>2>>>0]=ie,(P+=4)+4>A)break}return D()[P>>>2>>>0]=0,P-L},js=h=>{for(var P=0,A=0;A=L&&++A,P+=4}return P};function Dn(h,P,A){if(h>>>=0,P>>>=0,A=kt(A>>>=0),P===2)var L=Ue,V=nt,ie=Kt,Pe=Be=>N()[Be>>>1>>>0];else P===4&&(L=Ns,V=Os,ie=js,Pe=Be=>te()[Be>>>2>>>0]);ar(h,{name:A,fromWireType:Be=>{for(var Qe,at=te()[Be>>>2>>>0],vt=Be+4,Ot=0;Ot<=at;++Ot){var Vt=Be+4+Ot*P;Ot!=at&&Pe(Vt)!=0||(vt=L(vt,Vt-vt),Qe===void 0?Qe=vt:(Qe+="\0",Qe+=vt),vt=Vt+P)}return Jr(Be),Qe},toWireType:(Be,Qe)=>{if(typeof Qe!="string")throw new qe(`Cannot pass non-string to C++ string type ${A}`);var at=ie(Qe),vt=_n(4+at+P);return te()[vt>>>2>>>0]=at/P,V(Qe,vt+4,at+P),Be!==null&&Be.push(Jr,vt),vt},Cb:Dr,readValueFromPointer:Hr,Db(Be){Jr(Be)}})}function ue(h,P){ar(h>>>=0,{Tb:!0,name:P=kt(P>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function $(h){fn(h>>>0,!i,1,!o,131072,!1),Or()}var U=h=>{if(!ne)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(D(),h>>>2,h).value.then(se),h+=128,Atomics.store(D(),h>>>2,1))}var se=()=>{var h=hn();h&&(ee(h),U(Hn))};function Me(h,P){(h>>>=0)==P>>>0?setTimeout(se):a?postMessage({Gb:h,Bb:"checkMailbox"}):(h=It[h])&&h.postMessage({Bb:"checkMailbox"})}var $e=[];function Xe(h,P,A,L,V){for(P>>>=0,L/=2,$e.length=L,A=V>>>0>>>3,V=0;V>>0];return(P?ge[P]:Ea[h])(...$e)}var Je=()=>{Re=0};function Ye(h){h>>>=0,a?postMessage({Bb:"cleanupThread",hc:h}):gr(It[h])}function Ke(h){}var $t=(h,P)=>{var A=dr[h];if(A===void 0)throw h=Eo(h),A=kt(h),Jr(h),new qe(`${P} has unknown type ${A}`);return A},Et=(h,P,A)=>{var L=[];return h=h.toWireType(L,A),L.length&&(te()[P>>>2>>>0]=ir(L)),h};function rr(h,P,A){return P>>>=0,A>>>=0,h=wr(h>>>0),P=$t(P,"emval::as"),Et(P,A,h)}function br(h,P){return P>>>=0,h=wr(h>>>0),(P=$t(P,"emval::as")).toWireType(null,h)}var Xt=h=>{try{h()}catch(P){xe(P)}},sr=0,Ht=null,qr=0,ns=[],Er={},ds={},Yt=0,hr=null,Ir=[];function Xr(h){return(function(P){if(!ne){if(sr===0){var A=!1,L=!1;P((V=0)=>{if(!ne&&(qr=V,A=!0,L)){sr=2,Xt(()=>Ao(Ht)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),V=!1;try{var ie=(function(){var Qe=D()[Ht+8>>>2>>>0];return Qe=dt[ds[Qe]],--Re,Qe()})()}catch(Qe){ie=Qe,V=!0}var Pe=!1;if(!Ht){var Be=hr;Be&&(hr=null,(V?Be.reject:Be.resolve)(ie),Pe=!0)}if(V&&!Pe)throw ie}}),L=!0,A||(sr=1,Ht=(function(){var V=_n(65548),ie=V+12;te()[V>>>2>>>0]=ie,te()[V+4>>>2>>>0]=ie+65536,ie=ns[0];var Pe=Er[ie];return Pe===void 0&&(Pe=Yt++,Er[ie]=Pe,ds[Pe]=ie),ie=Pe,D()[V+8>>>2>>>0]=ie,V})(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),Xt(()=>Qn(Ht)))}else sr===2?(sr=0,Xt(Xn),Jr(Ht),Ht=null,Ir.forEach(U)):xe(`invalid state: ${sr}`);return qr}})(P=>{h().then(P)})}function ps(h){return h>>>=0,Xr(async()=>{var P=await wr(h);return ir(P)})}var yr=[];function os(h,P,A,L){return A>>>=0,L>>>=0,(h=yr[h>>>0])(null,P=wr(P>>>0),A,L)}var vr={},Zt=h=>{var P=vr[h];return P===void 0?kt(h):P};function _r(h,P,A,L,V){return A>>>=0,L>>>=0,V>>>=0,(h=yr[h>>>0])(P=wr(P>>>0),P[A=Zt(A)],L,V)}var lr=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Ur(h){return(h>>>=0)==0?ir(lr()):(h=Zt(h),ir(lr()[h]))}var Js=h=>{var P=yr.length;return yr.push(h),P},Ds=(h,P)=>{for(var A=Array(h),L=0;L>>2>>>0],"parameter "+L);return A},po=(h,P)=>Object.defineProperty(P,"name",{value:h});function ra(h,P,A){var L=(P=Ds(h,P>>>0)).shift();h--;var V=`return function (obj, func, destructorsRef, args) { +`,ie=0,Pe=[];A===0&&Pe.push("obj");for(var Be=["retType"],Qe=[L],at=0;atvt.name).join(", ")}) => ${L.name}>`,Js(po(A,h))}function sa(h){return h=Zt(h>>>0),ir(s[h])}function na(h,P){return P>>>=0,h=wr(h>>>0),P=wr(P),ir(h[P])}function oa(h){9<(h>>>=0)&&(zr[h+1]+=1)}function Ys(){return ir([])}function aa(h){h=wr(h>>>0);for(var P=Array(h.length),A=0;A>>0))}function la(){return ir({})}function ca(h){for(var P=wr(h>>>=0);P.length;){var A=P.pop();P.pop()(A)}ts(h)}function ua(h,P,A){P>>>=0,A>>>=0,h=wr(h>>>0),P=wr(P),A=wr(A),h[P]=A}function Zs(h,P){return P>>>=0,h=(h=$t(h>>>0,"_emval_take_value")).readValueFromPointer(P),ir(h)}function da(h,P){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),D()[P>>>2>>>0]=h.getUTCSeconds(),D()[P+4>>>2>>>0]=h.getUTCMinutes(),D()[P+8>>>2>>>0]=h.getUTCHours(),D()[P+12>>>2>>>0]=h.getUTCDate(),D()[P+16>>>2>>>0]=h.getUTCMonth(),D()[P+20>>>2>>>0]=h.getUTCFullYear()-1900,D()[P+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,D()[P+28>>>2>>>0]=h}var mo=h=>h%4==0&&(h%100!=0||h%400==0),ho=[0,31,60,91,121,152,182,213,244,274,305,335],_o=[0,31,59,90,120,151,181,212,243,273,304,334];function pa(h,P){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),D()[P>>>2>>>0]=h.getSeconds(),D()[P+4>>>2>>>0]=h.getMinutes(),D()[P+8>>>2>>>0]=h.getHours(),D()[P+12>>>2>>>0]=h.getDate(),D()[P+16>>>2>>>0]=h.getMonth(),D()[P+20>>>2>>>0]=h.getFullYear()-1900,D()[P+24>>>2>>>0]=h.getDay();var A=(mo(h.getFullYear())?ho:_o)[h.getMonth()]+h.getDate()-1|0;D()[P+28>>>2>>>0]=A,D()[P+36>>>2>>>0]=-60*h.getTimezoneOffset(),A=new Date(h.getFullYear(),6,1).getTimezoneOffset();var L=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(A!=L&&h.getTimezoneOffset()==Math.min(L,A)),D()[P+32>>>2>>>0]=h}function fo(h){h>>>=0;var P=new Date(D()[h+20>>>2>>>0]+1900,D()[h+16>>>2>>>0],D()[h+12>>>2>>>0],D()[h+8>>>2>>>0],D()[h+4>>>2>>>0],D()[h>>>2>>>0],0),A=D()[h+32>>>2>>>0],L=P.getTimezoneOffset(),V=new Date(P.getFullYear(),6,1).getTimezoneOffset(),ie=new Date(P.getFullYear(),0,1).getTimezoneOffset(),Pe=Math.min(ie,V);return 0>A?D()[h+32>>>2>>>0]=+(V!=ie&&Pe==L):0>>2>>>0]=P.getDay(),A=(mo(P.getFullYear())?ho:_o)[P.getMonth()]+P.getDate()-1|0,D()[h+28>>>2>>>0]=A,D()[h>>>2>>>0]=P.getSeconds(),D()[h+4>>>2>>>0]=P.getMinutes(),D()[h+8>>>2>>>0]=P.getHours(),D()[h+12>>>2>>>0]=P.getDate(),D()[h+16>>>2>>>0]=P.getMonth(),D()[h+20>>>2>>>0]=P.getYear(),h=P.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function go(h,P,A,L,V,ie,Pe){return a?rt(16,1,h,P,A,L,V,ie,Pe):-52}function Mo(h,P,A,L,V,ie){if(a)return rt(17,1,h,P,A,L,V,ie)}var Vs={},ma=()=>performance.timeOrigin+performance.now();function Ln(h,P){if(a)return rt(18,1,h,P);if(Vs[h]&&(clearTimeout(Vs[h].id),delete Vs[h]),!P)return 0;var A=setTimeout(()=>{delete Vs[h],U(()=>So(h,performance.timeOrigin+performance.now()))},P);return Vs[h]={id:A,qc:P},0}function ha(h,P,A,L){h>>>=0,P>>>=0,A>>>=0,L>>>=0;var V=new Date().getFullYear(),ie=new Date(V,0,1).getTimezoneOffset();V=new Date(V,6,1).getTimezoneOffset();var Pe=Math.max(ie,V);te()[h>>>2>>>0]=60*Pe,D()[P>>>2>>>0]=+(ie!=V),h=(P=Be=>{var Qe=Math.abs(Be);return`UTC${0<=Be?"-":"+"}${String(Math.floor(Qe/60)).padStart(2,"0")}${String(Qe%60).padStart(2,"0")}`})(ie),P=P(V),VDate.now();function bi(h,P,A){return 0<=h&&3>=h?(h===0?h=Date.now():h=performance.timeOrigin+performance.now(),Y[A>>>0>>>3]=BigInt(Math.round(1e6*h)),0):28}var zn=[],Bn=(h,P)=>{zn.length=0;for(var A;A=oe()[h++>>>0];){var L=A!=105;P+=(L&=A!=112)&&P%8?4:0,zn.push(A==112?te()[P>>>2>>>0]:A==106?Y[P>>>3]:A==105?D()[P>>>2>>>0]:Ae()[P>>>3>>>0]),P+=L?8:4}return zn};function bo(h,P,A){return h>>>=0,P=Bn(P>>>0,A>>>0),ge[h](...P)}function Rn(h,P,A){return h>>>=0,P=Bn(P>>>0,A>>>0),ge[h](...P)}var _a=()=>{};function fa(h,P){return I(qt(h>>>0,P>>>0))}var ga=()=>{throw Re+=1,"unwind"};function Ma(){return 4294901760}var wa=()=>navigator.hardwareConcurrency;function ba(){return xe("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function yo(h){h>>>=0;var P=oe().length;if(h<=P||4294901760=A;A*=2){var L=P*(1+.2/A);L=Math.min(L,h+100663296);e:{L=(Math.min(4294901760,65536*Math.ceil(Math.max(h,L)/65536))-T.buffer.byteLength+65535)/65536|0;try{T.grow(L),Te();var V=1;break e}catch{}V=void 0}if(V)return!0}return!1}var un=()=>(xe("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),en={},Nn=h=>{h.forEach(P=>{un()})};function ya(){var h=Error().stack.toString().split(` +`);return h[0]=="Error"&&h.shift(),Nn(h),en.Lb=un(),en.cc=h,en.Lb}function jn(h,P,A){if(h>>>=0,P>>>=0,en.Lb==h)var L=en.cc;else(L=Error().stack.toString().split(` +`))[0]=="Error"&&L.shift(),Nn(L);for(var V=3;L[V]&&un()!=h;)++V;for(h=0;h>>2>>>0]=un();return h}var dn,Vn={},Un=()=>{if(!dn){var h,P={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(h in Vn)Vn[h]===void 0?delete P[h]:P[h]=Vn[h];var A=[];for(h in P)A.push(`${h}=${P[h]}`);dn=A}return dn};function Ls(h,P){if(a)return rt(19,1,h,P);h>>>=0,P>>>=0;var A=0;return Un().forEach((L,V)=>{var ie=P+A;for(V=te()[h+4*V>>>2>>>0]=ie,ie=0;ie>>0]=L.charCodeAt(ie);pe()[V>>>0]=0,A+=L.length+1}),0}function vo(h,P){if(a)return rt(20,1,h,P);h>>>=0,P>>>=0;var A=Un();te()[h>>>2>>>0]=A.length;var L=0;return A.forEach(V=>L+=V.length+1),te()[P>>>2>>>0]=L,0}function va(h){return a?rt(21,1,h):52}function xo(h,P,A,L){return a?rt(22,1,h,P,A,L):52}function xa(h,P,A,L){return a?rt(23,1,h,P,A,L):70}var Ta=[null,[],[]];function Wn(h,P,A,L){if(a)return rt(24,1,h,P,A,L);P>>>=0,A>>>=0,L>>>=0;for(var V=0,ie=0;ie>>2>>>0],Be=te()[P+4>>>2>>>0];P+=8;for(var Qe=0;Qe>>0],vt=Ta[h];at===0||at===10?((h===1?v:I)(ft(vt)),vt.length=0):vt.push(at)}V+=Be}return te()[L>>>2>>>0]=V,0}a||(function(){for(var h=s.numThreads-1;h--;)Rr();Fe.unshift(()=>{de++,(function(P){a?P():Promise.all(ot.map(zt)).then(P)})(()=>ve())})})();for(var To=Array(256),pn=0;256>pn;++pn)To[pn]=String.fromCharCode(pn);Mt=To,qe=s.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},s.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},zr.push(0,1,void 0,1,null,1,!0,1,!1,1),s.count_emval_handles=()=>zr.length/2-5-Lr.length;var dt,Ea=[Ze,Ne,Sr,Ps,Cs,Ss,C,q,R,G,Z,ce,ye,et,ut,He,go,Mo,Ln,Ls,vo,va,xo,xa,Wn];(async function(){function h(L,V){return dt=L.exports,dt=(function(){var ie=dt,Pe={};for(let[Be,Qe]of Object.entries(ie))Pe[Be]=typeof Qe=="function"?(...at)=>{ns.push(Be);try{return Qe(...at)}finally{ne||(ns.pop(),Ht&&sr===1&&ns.length===0&&(sr=0,Re+=1,Xt(ko),typeof Fibers<"u"&&Fibers.rc()))}}:Qe;return Pe})(),dt=(function(){var ie=dt,Pe=Qe=>at=>Qe(at)>>>0,Be=Qe=>()=>Qe()>>>0;return(ie=Object.assign({},ie)).Da=Pe(ie.Da),ie.fb=Be(ie.fb),ie.hb=Pe(ie.hb),ie.tb=Pe(ie.tb),ie.ub=Be(ie.ub),ie.__cxa_get_exception_ptr=Pe(ie.__cxa_get_exception_ptr),ie})(),Rt.push(dt.ib),b=V,ve(),dt}de++;var P=Ce();if(s.instantiateWasm)return new Promise(L=>{s.instantiateWasm(P,(V,ie)=>{h(V,ie),L(V.exports)})});if(a)return new Promise(L=>{Ie=V=>{var ie=new WebAssembly.Instance(V,Ce());L(h(ie,V))}});z??=s.locateFile?s.locateFile?s.locateFile("ort-wasm-simd-threaded.jsep.wasm",y):y+"ort-wasm-simd-threaded.jsep.wasm":new URL(""+new URL("ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href,import.meta.url).href;try{var A=await(async function(L){var V=z;if(!re&&typeof WebAssembly.instantiateStreaming=="function"&&!le(V))try{var ie=fetch(V,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ie,L)}catch(Pe){I(`wasm streaming compile failed: ${Pe}`),I("falling back to ArrayBuffer instantiation")}return(async function(Pe,Be){try{var Qe=await(async function(at){if(!re)try{var vt=await d(at);return new Uint8Array(vt)}catch{}if(at==z&&re)at=new Uint8Array(re);else{if(!u)throw"both async and sync fetching of the wasm failed";at=u(at)}return at})(Pe);return await WebAssembly.instantiate(Qe,Be)}catch(at){I(`failed to asynchronously prepare wasm: ${at}`),xe(at)}})(V,L)})(P);return h(A.instance,A.module)}catch(L){return t(L),Promise.reject(L)}})();var Eo=h=>(Eo=dt.Da)(h),mn=()=>(mn=dt.Ea)();s._OrtInit=(h,P)=>(s._OrtInit=dt.Fa)(h,P),s._OrtGetLastError=(h,P)=>(s._OrtGetLastError=dt.Ga)(h,P),s._OrtCreateSessionOptions=(h,P,A,L,V,ie,Pe,Be,Qe,at)=>(s._OrtCreateSessionOptions=dt.Ha)(h,P,A,L,V,ie,Pe,Be,Qe,at),s._OrtAppendExecutionProvider=(h,P,A,L,V)=>(s._OrtAppendExecutionProvider=dt.Ia)(h,P,A,L,V),s._OrtAddFreeDimensionOverride=(h,P,A)=>(s._OrtAddFreeDimensionOverride=dt.Ja)(h,P,A),s._OrtAddSessionConfigEntry=(h,P,A)=>(s._OrtAddSessionConfigEntry=dt.Ka)(h,P,A),s._OrtReleaseSessionOptions=h=>(s._OrtReleaseSessionOptions=dt.La)(h),s._OrtCreateSession=(h,P,A)=>(s._OrtCreateSession=dt.Ma)(h,P,A),s._OrtReleaseSession=h=>(s._OrtReleaseSession=dt.Na)(h),s._OrtGetInputOutputCount=(h,P,A)=>(s._OrtGetInputOutputCount=dt.Oa)(h,P,A),s._OrtGetInputOutputMetadata=(h,P,A,L)=>(s._OrtGetInputOutputMetadata=dt.Pa)(h,P,A,L),s._OrtFree=h=>(s._OrtFree=dt.Qa)(h),s._OrtCreateTensor=(h,P,A,L,V,ie)=>(s._OrtCreateTensor=dt.Ra)(h,P,A,L,V,ie),s._OrtGetTensorData=(h,P,A,L,V)=>(s._OrtGetTensorData=dt.Sa)(h,P,A,L,V),s._OrtReleaseTensor=h=>(s._OrtReleaseTensor=dt.Ta)(h),s._OrtCreateRunOptions=(h,P,A,L)=>(s._OrtCreateRunOptions=dt.Ua)(h,P,A,L),s._OrtAddRunConfigEntry=(h,P,A)=>(s._OrtAddRunConfigEntry=dt.Va)(h,P,A),s._OrtReleaseRunOptions=h=>(s._OrtReleaseRunOptions=dt.Wa)(h),s._OrtCreateBinding=h=>(s._OrtCreateBinding=dt.Xa)(h),s._OrtBindInput=(h,P,A)=>(s._OrtBindInput=dt.Ya)(h,P,A),s._OrtBindOutput=(h,P,A,L)=>(s._OrtBindOutput=dt.Za)(h,P,A,L),s._OrtClearBoundOutputs=h=>(s._OrtClearBoundOutputs=dt._a)(h),s._OrtReleaseBinding=h=>(s._OrtReleaseBinding=dt.$a)(h),s._OrtRunWithBinding=(h,P,A,L,V)=>(s._OrtRunWithBinding=dt.ab)(h,P,A,L,V),s._OrtRun=(h,P,A,L,V,ie,Pe,Be)=>(s._OrtRun=dt.bb)(h,P,A,L,V,ie,Pe,Be),s._OrtEndProfiling=h=>(s._OrtEndProfiling=dt.cb)(h),s._JsepOutput=(h,P,A)=>(s._JsepOutput=dt.db)(h,P,A),s._JsepGetNodeName=h=>(s._JsepGetNodeName=dt.eb)(h);var hn=()=>(hn=dt.fb)(),Jr=s._free=h=>(Jr=s._free=dt.gb)(h),_n=s._malloc=h=>(_n=s._malloc=dt.hb)(h),fn=(h,P,A,L,V,ie)=>(fn=dt.kb)(h,P,A,L,V,ie),Po=()=>(Po=dt.lb)(),Co=(h,P,A,L,V)=>(Co=dt.mb)(h,P,A,L,V),Gn=h=>(Gn=dt.nb)(h),Kn=h=>(Kn=dt.ob)(h),So=(h,P)=>(So=dt.pb)(h,P),Hn=()=>(Hn=dt.qb)(),Io=(h,P)=>(Io=dt.rb)(h,P),gn=h=>(gn=dt.sb)(h),Mn=h=>(Mn=dt.tb)(h),qn=()=>(qn=dt.ub)(),$o=s.dynCall_ii=(h,P)=>($o=s.dynCall_ii=dt.vb)(h,P),Qn=h=>(Qn=dt.wb)(h),ko=()=>(ko=dt.xb)(),Ao=h=>(Ao=dt.yb)(h),Xn=()=>(Xn=dt.zb)();return s.stackSave=()=>qn(),s.stackRestore=h=>gn(h),s.stackAlloc=h=>Mn(h),s.setValue=function(h,P,A="i8"){switch(A.endsWith("*")&&(A="*"),A){case"i1":case"i8":pe()[h>>>0]=P;break;case"i16":K()[h>>>1>>>0]=P;break;case"i32":D()[h>>>2>>>0]=P;break;case"i64":Y[h>>>3]=BigInt(P);break;case"float":he()[h>>>2>>>0]=P;break;case"double":Ae()[h>>>3>>>0]=P;break;case"*":te()[h>>>2>>>0]=P;break;default:xe(`invalid type for setValue: ${A}`)}},s.getValue=function(h,P="i8"){switch(P.endsWith("*")&&(P="*"),P){case"i1":case"i8":return pe()[h>>>0];case"i16":return K()[h>>>1>>>0];case"i32":return D()[h>>>2>>>0];case"i64":return Y[h>>>3];case"float":return he()[h>>>2>>>0];case"double":return Ae()[h>>>3>>>0];case"*":return te()[h>>>2>>>0];default:xe(`invalid type for getValue: ${P}`)}},s.UTF8ToString=qt,s.stringToUTF8=yt,s.lengthBytesUTF8=Kr,(function h(){if(0{fu(),rc=typeof location>"u"?void 0:location.origin,Jc=import.meta.url>"file:"&&import.meta.url<"file;",rf=()=>{{if(Jc){let e=URL;return new URL(new e("ort.bundle.min.mjs",import.meta.url).href,rc).href}return import.meta.url}},Yr=rf(),ab=()=>{if(Yr&&!Yr.startsWith("blob:"))return Yr.substring(0,Yr.lastIndexOf("/")+1)},qa=(e,r)=>{try{let t=r??Yr;return(t?new URL(e,t):new URL(e)).origin===rc}catch{return!1}},sf=(e,r)=>{let t=r??Yr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},nf=(e,r)=>`${r??"./"}${e}`,sc=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},of=async e=>(await import(e)).default,nc=(nT(),Jo(rb)).default,ib=async()=>{if(!Yr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(qa(Yr))return[void 0,nc()];let e=await sc(Yr);return[e,nc(e)]},oc=(oT(),Jo(nb)).default,lb=async(e,r,t)=>{if(!e&&!r&&oc&&Yr&&qa(Yr))return[void 0,oc];{let s="ort-wasm-simd-threaded.jsep.mjs",n=e??sf(s,r),o=t&&n&&!qa(n,r),i=o?await sc(n):n??nf(s,r);return[o?i:void 0,await of(i)]}}}),ac,Qa,zo,ic,af,lf,cf,Mu,Qt,Fn=Ve(()=>{gu(),Qa=!1,zo=!1,ic=!1,af=()=>{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}},lf=()=>{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}},cf=()=>{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}},Mu=async e=>{if(Qa)return Promise.resolve();if(zo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(ic)throw new Error("previous call to 'initializeWebAssembly()' failed.");zo=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!cf())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!lf())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=af();t>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", 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=t=1);let n=e.wasmPaths,o=typeof n=="string"?n:void 0,i=n?.mjs,a=i?.href??i,l=n?.wasm,c=l?.href??l,p=e.wasmBinary,[d,u]=await lb(a,o,t>1),f=!1,_=[];if(r>0&&_.push(new Promise(y=>{setTimeout(()=>{f=!0,y()},r)})),_.push(new Promise((y,k)=>{let w={numThreads:t};if(p)w.wasmBinary=p;else if(c||o)w.locateFile=v=>c??o+v;else if(a&&a.indexOf("blob:")!==0)w.locateFile=v=>new URL(v,a).href;else if(d){let v=ab();v&&(w.locateFile=I=>v+I)}u(w).then(v=>{zo=!1,Qa=!0,ac=v,y(),d&&URL.revokeObjectURL(d)},v=>{zo=!1,ic=!0,k(v)})})),await Promise.race(_),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},Qt=()=>{if(Qa&&ac)return ac;throw new Error("WebAssembly is not initialized yet.")}}),bs,di,Gt,wu=Ve(()=>{Fn(),bs=(e,r)=>{let t=Qt(),s=t.lengthBytesUTF8(e)+1,n=t._malloc(s);return t.stringToUTF8(e,n,s),r.push(n),n},di=(e,r,t,s)=>{if(typeof e=="object"&&e!==null){if(t.has(e))throw new Error("Circular reference in options");t.add(e)}Object.entries(e).forEach(([n,o])=>{let i=r?r+n:n;if(typeof o=="object")di(o,i+".",t,s);else if(typeof o=="string"||typeof o=="number")s(i,o.toString());else if(typeof o=="boolean")s(i,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Gt=e=>{let r=Qt(),t=r.stackSave();try{let s=r.PTR_SIZE,n=r.stackAlloc(2*s);r._OrtGetLastError(n,n+s);let o=Number(r.getValue(n,s===4?"i32":"i64")),i=r.getValue(n+s,"*"),a=i?r.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${o}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),cb,aT=Ve(()=>{Fn(),wu(),cb=e=>{let r=Qt(),t=0,s=[],n=e||{};try{if(e?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)n.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&&(n.terminate=!1);let o=0;return e?.tag!==void 0&&(o=bs(e.tag,s)),t=r._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),t===0&&Gt("Can't create run options."),e?.extra!==void 0&&di(e.extra,"",new WeakSet,(i,a)=>{let l=bs(i,s),c=bs(a,s);r._OrtAddRunConfigEntry(t,l,c)!==0&&Gt(`Can't set a run config entry: ${i} - ${a}.`)}),[t,s]}catch(o){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(i=>r._free(i)),o}}}),uf,df,pf,Bo,mf,ub,iT=Ve(()=>{Fn(),wu(),uf=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},df=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},pf=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let r=e.extra.session;r.use_ort_model_bytes_directly||(r.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(t=>(typeof t=="string"?t:t.name)==="webgpu")&&(e.enableMemPattern=!1)},Bo=(e,r,t,s)=>{let n=bs(r,s),o=bs(t,s);Qt()._OrtAddSessionConfigEntry(e,n,o)!==0&&Gt(`Can't set a session config entry: ${r} - ${t}.`)},mf=async(e,r,t)=>{for(let s of r){let n=typeof s=="string"?s:s.name,o=[];switch(n){case"webnn":if(n="WEBNN",typeof s!="string"){let p=s?.deviceType;p&&Bo(e,"deviceType",p,t)}break;case"webgpu":if(n="JS",typeof s!="string"){let p=s;if(p?.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);Bo(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${n}`)}let i=bs(n,t),a=o.length,l=0,c=0;if(a>0){l=Qt()._malloc(a*Qt().PTR_SIZE),t.push(l),c=Qt()._malloc(a*Qt().PTR_SIZE),t.push(c);for(let p=0;p{let r=Qt(),t=0,s=[],n=e||{};pf(n);try{let o=uf(n.graphOptimizationLevel??"all"),i=df(n.executionMode??"sequential"),a=typeof n.logId=="string"?bs(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?bs(n.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,i,!!n.enableProfiling,0,a,l,c,p),t===0&&Gt("Can't create session options."),n.executionProviders&&await mf(t,n.executionProviders,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Bo(t,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[d,u]of Object.entries(n.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof u!="number"||!Number.isInteger(u)||u<0)throw new Error(`free dimension override value must be a non-negative integer: ${u}`);let f=bs(d,s);r._OrtAddFreeDimensionOverride(t,f,u)!==0&&Gt(`Can't set a free dimension override: ${d} - ${u}.`)}return n.extra!==void 0&&di(n.extra,"",new WeakSet,(d,u)=>{Bo(t,d,u,s)}),[t,s]}catch(o){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&Gt("Can't release session options."),s.forEach(i=>r._free(i)),o}}}),no,Ks,Sn,bu,pi,yu,vu,Yc,gt=Ve(()=>{no=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}`)}},Ks=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}`)}},Sn=(e,r)=>{let t=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof r=="number"?r:r.reduce((n,o)=>n*o,1);return t>0?Math.ceil(s*t):void 0},bu=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},pi=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}`)}},yu=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",vu=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Yc=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}`)}}}),xu,db=Ve(()=>{fu(),xu=async e=>{if(typeof e=="string"){let r=await fetch(e);if(!r.ok)throw new Error(`failed to load external data file: ${e}`);let t=r.headers.get("Content-Length"),s=t?parseInt(t,10):0;if(s<1073741824)return new Uint8Array(await r.arrayBuffer());{if(!r.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=r.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(a){if(a instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw a}let i=0;for(;;){let{done:a,value:l}=await n.read();if(a)break;let c=l.byteLength;new Uint8Array(o,i,c).set(l),i+=c}return new Uint8Array(o,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),hf,_f,ff,gf,Tu,Mf,Dt,Hs=Ve(()=>{gt(),hf=["V","I","W","E","F"],_f=(e,r)=>{console.log(`[${hf[e]},${new Date().toISOString()}]${r}`)},Tu=(e,r)=>{ff=e,gf=r},Mf=(e,r)=>{let t=pi(e),s=pi(ff);t>=s&&_f(t,typeof r=="function"?r():r)},Dt=(...e)=>{gf&&Mf(...e)}}),wf,lo,we,mi,pb,mb,hb,Ct=Ve(()=>{wf=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},lo=class{static calcShape(e,r,t=!1){let s=e.length,n=r.length;if(s===0)return r;if(n===0)return e;let o=Math.max(e.length,r.length),i=new Array(o);if(t){if(s<2||n<2)return;let a=wf.calcMatMulShape([e[s-2],e[s-1]],[r[n-2],r[n-1]]);if(a===void 0)return;[i[o-2],i[o-1]]=a}for(let a=t?3:1;a<=o;a++){let l=s-a<0?1:e[s-a],c=n-a<0?1:r[n-a];if(l!==c&&l>1&&c>1)return;let p=Math.max(l,c);if(l&&c)i[o-a]=Math.max(l,c);else{if(p>1)return;i[o-a]=0}}return i}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let n=1;n<=t;n++)if(e[t-n]!==1&&e[t-n]!==r[s-n])return!1;return!0}},we=class ci{static size(r){return ci.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let n=new Array(s),o=s-1;for(;o>=0;){if(r[o]%t===0){n[o]=r[o]/t;break}if(t%r[o]!==0)throw new Error("cannot convert shape");n[o]=1,t/=r[o],o--}for(o--;o>=0;o--)n[o]=r[o];return n}static sizeFromDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${r.length} dimensions.`);return ci.getSizeFromDimensionRange(r,t,r.length)}static sizeToDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${r.length} dimensions.`);return ci.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let n=1;for(let o=t;o=0;--n)s[n]=s[n+1]*r[n+1];return s}static normalizeAxis(r,t){if(r<-t&&r>=t)throw new Error("unsupported axis for this operation.");return r<0?r+t:r}static normalizeAxes(r,t){return r.map(s=>this.normalizeAxis(s,t??r.length))}static sortBasedOnPerm(r,t){return t?t.map(s=>r[s]):r.slice().reverse()}static padShape(r,t){let s=r.length;return r.map((n,o)=>n+t[o]+t[o+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,n)=>s===t[n])}},mi=class Ho{static adjustPoolAttributes(r,t,s,n,o,i){if(!r&&s.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(r)for(let a=0;a=s.length?s.push(t[a+2]):s[a]=t[a+2];for(let a=0;a=s[a]||i[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,n,o,i,a){if(a){if(o.length!==2*(r.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==r.length-2)throw new Error("length of strides should be the length of data dimensions");if(n.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{gt(),Eu=(e,r)=>new(bu(r))(e)}),Zc,lc,bf,cc,yf,uc,dc,pc,vf,fb,lT=Ve(()=>{Hs(),Zc=(e,r=!0)=>{if(e.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let t=e.byteLength/8,s=new BigInt64Array(e.buffer,e.byteOffset,t),n=new Int32Array(t);for(let o=0;o2147483647n||i<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${o}: ${i}`);n[o]=Number(i)}return r?new Uint8Array(n.buffer):n},lc=(e,r=!0)=>{if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let t=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,t),n=BigInt64Array.from(s,BigInt);return r?new Uint8Array(n.buffer):n},bf=1,cc=()=>bf++,yf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),uc=(e,r)=>{let t=yf.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,n)=>s*n)*t/8):0},dc=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:r,context:t,tensor:s,dataType:n,shape:o,shouldConvertInt64toInt32:i=!1}=e;this.sessionId=r,this.mlContext=t,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.shouldConvertInt64toInt32=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return uc(this.dataType,this.tensorShape)}destroy(){Dt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e,r){if(e){let t=await this.mlContext.readTensor(this.mlTensor),s=lc(new Uint8Array(t));if(r){(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).set(s);return}else return s.buffer}else return r?this.mlContext.readTensor(this.mlTensor,r):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,r,t){return this.mlContext===e&&this.dataType===r&&this.tensorShape.length===t.length&&this.tensorShape.every((s,n)=>s===t[n])}setIsInt64ToInt32Converted(e){this.isInt64ToInt32Converted=e}},pc=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,t,s){let n=r,o=this.tensorManager.getMLContext(e),i=n==="int64"&&!o.opSupportLimits().input.dataTypes.includes("int64");if(i&&(n="int32",Dt("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(o,n,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==uc(n,t))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 a=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,n,t,a,!0,!0,i),s&&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.shouldConvertInt64toInt32&&(r=Zc(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else Dt("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?.isInt64ToInt32Converted?lc(this.activeUpload):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(this.wrapper?.shouldConvertInt64toInt32,e):this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32)}},vf=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}reserveTensorId(){let e=cc();return this.tensorTrackersById.set(e,new pc(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,t,s,n){Dt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(r);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(e,t,s,n)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){Dt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${r?.byteLength}}`);let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");return t.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,t,s){let n=this.getMLContext(e),o=cc(),i=new dc({sessionId:e,context:n,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(o,new pc(this,i)),this.externalTensors.add(i),o}async getCachedTensor(e,r,t,s,n,o,i=!1){let a=this.getMLContext(e);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(a,r,t)){Dt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let d=this.freeTensors.splice(c,1)[0];return d.sessionId=e,d}Dt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let l=await a.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:n,readable:o});return new dc({sessionId:e,context:a,tensor:l,dataType:r,shape:t,shouldConvertInt64toInt32:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},fb=(...e)=>new vf(...e)}),Xa,xf,gb,cT=Ve(()=>{gt(),Fn(),_b(),lT(),Hs(),Xa=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),xf=(e,r)=>{if(e===r)return!0;if(e===void 0||r===void 0)return!1;let t=Object.keys(e).sort(),s=Object.keys(r).sort();return t.length===s.length&&t.every((n,o)=>n===s[o]&&e[n]===r[n])},gb=class{constructor(e){this.tensorManager=fb(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Tu(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Dt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Dt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)Dt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(s=>s.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===void 0){let t=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let r=this.mlContextCache.findIndex(t=>xf(t.options,e));if(r!==-1)return this.mlContextCache[r].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,r){this.mlContextBySessionId.set(e,r);let t=this.sessionIdsByMLContext.get(r);t||(t=new Set,this.sessionIdsByMLContext.set(r,t)),t.add(e),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e);let r=this.mlContextBySessionId.get(e);if(!r)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let t=this.sessionIdsByMLContext.get(r);if(t.delete(e),t.size===0){this.sessionIdsByMLContext.delete(r);let s=this.mlContextCache.findIndex(n=>n.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Dt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,n){let o=Xa.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,o,s,n)}async createTemporaryTensor(e,r,t){Dt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=Xa.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,n,s,t,!1);let o=this.temporarySessionTensorIds.get(e);return o?o.push(n):this.temporarySessionTensorIds.set(e,[n]),n}uploadTensor(e,r){if(!Qt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Dt("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 t=await this.tensorManager.download(e);return Eu(t,r)}}registerMLTensor(e,r,t,s){let n=Xa.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.registerTensor(e,r,n,s);return Dt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(e,r,t,s,n,o,i=!1){if(!o)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let l=o.get(a);if(!l)throw new Error(`File with name ${a} not found in preloaded files.`);if(r+t>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(r,r+t).buffer,p;switch(n.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":i?(p=Zc(new Uint8Array(c),!1),n.dataType="int32"):p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return Dt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}isInt64Supported(e){return!!this.mlContextBySessionId.get(e)?.opSupportLimits().input.dataTypes.includes("int64")}flush(){}}}),Pu=Ve(()=>{}),mc,Ja,Ya,Tf,Ef,hc,eu,Pf,Mb,uT=Ve(()=>{Hs(),Pu(),mc=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),Ja=[],Ya=e=>Math.ceil(Number(e)/16)*16,Tf=e=>{for(let r=0;rEf++,eu=async(e,r,t,s)=>{let n=Ya(t),o=e.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(r,0,o,0,n),e.flush(),await o.mapAsync(GPUMapMode.READ);let a=o.getMappedRange();if(s){let l=s();return l.set(new Uint8Array(a,0,t)),l}else return new Uint8Array(a.slice(0,t))}finally{o.destroy()}},Pf=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of mc)Ja.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,n=r.byteLength,o=Ya(n),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==n)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${n}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:o,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=a.getMappedRange();new Uint8Array(l).set(new Uint8Array(t,s,n)),a.unmap();let c=this.backend.device.createCommandEncoder();c.copyBufferToBuffer(a,0,i.gpuData.buffer,0,o),this.backend.device.queue.submit([c.finish()]),a.destroy(),Dt("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,r){let t=this.storageCache.get(e);if(!t)throw new Error("source gpu data for memcpy does not exist");let s=this.storageCache.get(r);if(!s)throw new Error("destination gpu data for memcpy does not exist");if(t.originalSize!==s.originalSize)throw new Error("inconsistent source and destination gpu data size");let n=Ya(t.originalSize),o=this.backend.getCommandEncoder();this.backend.endComputePass(),o.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,n)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return Dt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, buffer is the same, skip.`),s;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`)}else s=hc();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),Dt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Dt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=Tf(e),s,n=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,o=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(n||o){let a=(n?this.freeBuffers:this.freeUniformBuffers).get(t);a?a.length>0?s=a.pop():s=this.backend.device.createBuffer({size:t,usage:r}):s=this.backend.device.createBuffer({size:t,usage:r})}else s=this.backend.device.createBuffer({size:t,usage:r});let i={id:hc(),type:0,buffer:s};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),Dt("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){return this.storageCache.get(e)?.gpuData}release(e){let r=typeof e=="bigint"?Number(e):e,t=this.storageCache.get(r);if(!t){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return Dt("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,r){let t=this.storageCache.get(Number(e));if(!t)throw new Error("data does not exist");await eu(this.backend,t.gpuData.buffer,t.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let r=mc.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let t=this.freeBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let t=this.freeUniformBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let r of this.buffersPending)e.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let r=this.capturedPendingBuffers.get(e);r&&(r.forEach(t=>{t.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(Dt("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Mb=(...e)=>new Pf(...e)}),Cf,jt,mr=Ve(()=>{Cf=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},jt=e=>new Cf(e)}),co,Za,Ar,jr,ct,ur,tu,io,ln,lt,Ro,ke,it,wb,Cu,Sf,bb,St=Ve(()=>{gt(),Ct(),co=64,Za=(e,r)=>{if(r===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return r>1?`vec${r}`:"f16";case 1:return r>1?`vec${r}`:"f32";case 6:return r>1?`vec${r}`:"i32";case 12:return r>1?`vec${r}`:"u32";case 7:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(r!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},Ar=(e,r=1)=>{let t=Za(e,r);return typeof t=="string"?t:t[0]},jr=(e,r=1)=>{let t=Za(e,r);return typeof t=="string"?t:t[1]},ct=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:we.computeStrides(t)})}),r},ur=e=>e%4===0?4:e%2===0?2:1,tu=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,io=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,ln=(e,r)=>r===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:r===2?`(${e}.x + ${e}.y)`:r===3?`(${e}.x + ${e}.y + ${e}.z)`:e,lt=(e,r,t,s)=>e.startsWith("uniforms.")&&t>4?typeof r=="string"?s==="f16"?`${e}[(${r}) / 8][(${r}) % 8 / 4][(${r}) % 8 % 4]`:`${e}[(${r}) / 4][(${r}) % 4]`:s==="f16"?`${e}[${Math.floor(r/8)}][${Math.floor(r%8/4)}][${r%8%4}]`:`${e}[${Math.floor(r/4)}][${r%4}]`:t>1?`${e}[${r}]`:e,Ro=(e,r,t,s,n)=>{let o=typeof t=="number",i=o?t:t.length,a=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`array`,c=Za(r,n),p=typeof c=="string"?c:c[1],d=typeof c=="string"?c:c[0],u={indices:l,value:p,storage:d,tensor:r},f=oe=>typeof oe=="string"?oe:`${oe}u`,_={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},y=o?"uniforms.":"",k=`${y}${e}_shape`,w=`${y}${e}_strides`,v="";for(let oe=0;oe ${u.indices} { + var indices: ${u.indices}; + var current = offset; + ${v} + return indices; + }`,T=oe=>(_.offsetToIndices=!0,i<2?oe:`o2i_${e}(${oe})`),b=[];if(i>=2)for(let oe=i-1;oe>=0;oe--)b.push(`${lt(w,oe,i)} * (indices[${oe}])`);let E=i<2?"":` + fn i2o_${e}(indices: ${u.indices}) -> u32 { + return ${b.join("+")}; + }`,x=oe=>(_.indicesToOffset=!0,i<2?oe:`i2o_${e}(${oe})`),S=(...oe)=>i===0?"0u":`${u.indices}(${oe.map(f).join(",")})`,O=(oe,K)=>i<2?`${oe}`:`${lt(oe,K,i)}`,F=(oe,K,N)=>i<2?`${oe}=${N};`:`${lt(oe,K,i)}=${N};`,H={},W=(oe,K)=>{_.broadcastedIndicesToOffset=!0;let N=`${K.name}broadcastedIndicesTo${e}Offset`;if(N in H)return`${N}(${oe})`;let D=[];for(let te=i-1;te>=0;te--){let he=K.indicesGet("outputIndices",te+K.rank-i);D.push(`${O(w,te)} * (${he} % ${O(k,te)})`)}return H[N]=`fn ${N}(outputIndices: ${K.type.indices}) -> u32 { + return ${D.length>0?D.join("+"):"0u"}; + }`,`${N}(${oe})`},B=(oe,K)=>(()=>{if(u.storage===u.value)return`${e}[${oe}]=${K};`;if(u.storage==="vec2"&&u.value==="i32")return`${e}[${oe}]=vec2(u32(${K}), select(0u, 0xFFFFFFFFu, ${K} < 0));`;if(u.storage==="vec2"&&u.value==="u32")return`${e}[${oe}]=vec2(u32(${K}), 0u);`;if(u.storage==="u32"&&u.value==="vec4")return`${e}[${oe}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${K}));`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),Y=oe=>(()=>{if(u.storage===u.value)return`${e}[${oe}]`;if(u.storage==="vec2"&&u.value==="i32")return`i32(${e}[${oe}].x)`;if(u.storage==="vec2"&&u.value==="u32")return`u32(${e}[${oe}].x)`;if(u.storage==="u32"&&u.value==="vec4")return`vec4(bool(${e}[${oe}] & 0xFFu), bool(${e}[${oe}] & 0xFF00u), bool(${e}[${oe}] & 0xFF0000u), bool(${e}[${oe}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),X=i<2?"":` + fn get_${e}ByIndices(indices: ${u.indices}) -> ${p} { + return ${Y(`i2o_${e}(indices)`)}; + }`,J=i<2?"":(()=>{let oe=a.map(N=>`d${N}: u32`).join(", "),K=a.map(N=>`d${N}`).join(", ");return` + fn get_${e}(${oe}) -> ${p} { + return get_${e}ByIndices(${S(K)}); + }`})(),re=(...oe)=>{if(oe.length!==i)throw new Error(`indices length must be ${i}`);let K=oe.map(f).join(",");return i===0?Y("0u"):i===1?Y(K[0]):(_.get=!0,_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}(${K})`)},ne=oe=>i<2?Y(oe):(_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}ByIndices(${oe})`),le=i<2?"":` + fn set_${e}ByIndices(indices: ${u.indices}, value: ${p}) { + ${B(`i2o_${e}(indices)`,"value")} + }`,pe=i<2?"":(()=>{let oe=a.map(N=>`d${N}: u32`).join(", "),K=a.map(N=>`d${N}`).join(", ");return` + fn set_${e}(${oe}, value: ${p}) { + set_${e}ByIndices(${S(K)}, value); + }`})();return{impl:()=>{let oe=[],K=!1;return _.offsetToIndices&&(oe.push(I),K=!0),_.indicesToOffset&&(oe.push(E),K=!0),_.broadcastedIndicesToOffset&&(Object.values(H).forEach(N=>oe.push(N)),K=!0),_.set&&(oe.push(pe),K=!0),_.setByIndices&&(oe.push(le),K=!0),_.get&&(oe.push(J),K=!0),_.getByIndices&&(oe.push(X),K=!0),!o&&K&&oe.unshift(`const ${k} = ${u.indices}(${t.join(",")});`,`const ${w} = ${u.indices}(${we.computeStrides(t).join(",")});`),oe.join(` +`)},type:u,offsetToIndices:T,indicesToOffset:x,broadcastedIndicesToOffset:W,indices:S,indicesGet:O,indicesSet:F,set:(...oe)=>{if(oe.length!==i+1)throw new Error(`indices length must be ${i}`);let K=oe[i];if(typeof K!="string")throw new Error("value must be string");let N=oe.slice(0,i).map(f).join(",");return i===0?B("0u",K):i===1?B(N[0],K):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}(${N}, ${K})`)},setByOffset:B,setByIndices:(oe,K)=>i<2?B(oe,K):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}ByIndices(${oe}, ${K});`),get:re,getByOffset:Y,getByIndices:ne,usage:s,name:e,strides:w,shape:k,rank:i}},ke=(e,r,t,s=1)=>Ro(e,r,t,"input",s),it=(e,r,t,s=1)=>Ro(e,r,t,"output",s),wb=(e,r,t)=>Ro(e,r,t,"atomicOutput",1),Cu=(e,r,t,s=1)=>Ro(e,r,t,"internal",s),Sf=class{constructor(e,r){this.normalizedDispatchGroup=e,this.limits=r,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=co){let r=typeof e=="number"?e:e[0],t=typeof e=="number"?1:e[1],s=typeof e=="number"?1:e[2];if(r>this.limits.maxComputeWorkgroupSizeX||t>this.limits.maxComputeWorkgroupSizeY||s>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*t*s>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let n=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,o=n?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,i=n?`let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${r*t*s}u + local_idx;`;return`@compute @workgroup_size(${r}, ${t}, ${s}) + fn main(${o}) { + ${i} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,r){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let t=e.usage==="input"?"read":"read_write",s=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${r}) var ${e.name}: array<${s}>;`}declareVariables(...e){return e.map(r=>this.declareVariable(r,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(e,r,t=1){return this.uniforms.push({name:e,type:r,length:t}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:r,type:t,length:s}of this.uniforms)if(s&&s>4)t==="f16"?e.push(`@align(16) ${r}:array, ${Math.ceil(s/8)}>`):e.push(`${r}:array, ${Math.ceil(s/4)}>`);else{let n=s==null||s===1?t:`vec${s}<${t}>`;e.push(`${r}:${n}`)}return` + struct Uniforms { ${e.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` +`)+this.internalVariables.map(e=>e.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[e(r.type),r.length??1])}},bb=(e,r)=>new Sf(e,r)}),If,_c,$f,kf,Af,Ff,es,yb,vb,cn=Ve(()=>{gt(),Ct(),mr(),St(),If=(e,r)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(r.length!==0&&r.length!==e[0].dims.length)throw new Error(`perm size ${r.length} does not match input rank ${e[0].dims.length}`)},_c=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),$f=(e,r)=>we.sortBasedOnPerm(e,_c(e.length,r)),kf=(e,r,t,s)=>{let n=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`;for(let o=0;o{let t=[],s=[];for(let n=0;n{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,n=_c(s,r),o=$f(e.dims,n),i=e.dims,a=o,l=s<2||Ff(n,e.dims),c;if(l)return c=_=>{let y=ke("input",t,i,4),k=it("output",t,a,4);return` + ${_.registerUniform("output_size","u32").declareVariables(y,k)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let _=we.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64/4)},programUniforms:[{type:12,data:Math.ceil(_/4)}]}},getShaderSource:c};let{newShape:p,newPerm:d}=Af(e.dims,n),u=we.areEqual(d,[2,3,1]),f=we.areEqual(d,[3,1,2]);if(p.length===2||u||f){i=u?[p[0],p[1]*p[2]]:f?[p[0]*p[1],p[2]]:p,a=[i[1],i[0]];let _=16;return c=y=>{let k=ke("a",t,i.length),w=it("output",t,a.length);return` + ${y.registerUniform("output_size","u32").declareVariables(k,w)} + var tile : array, ${_}>; + ${y.mainStart([_,_,1])} + let stride = (uniforms.output_shape[1] - 1) / ${_} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${_}u + local_id.x; + let input_row = workgroup_id_x * ${_}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${k.getByIndices(`${k.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${_}u + local_id.x; + let output_row = workgroup_id_y * ${_}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${w.setByIndices(`${w.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let y=we.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/_),y:Math.ceil(a[0]/_)},programUniforms:[{type:12,data:y},...ct(i,a)]}},getShaderSource:c}}return c=_=>{let y=ke("a",t,i.length),k=it("output",t,a.length);return` + ${_.registerUniform("output_size","u32").declareVariables(y,k)} + + ${kf(n,s,y,k)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${k.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${k.setByOffset("global_idx",y.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let _=we.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ct(i,a)]}},getShaderSource:c}},yb=(e,r)=>{If(e.inputs,r.perm),e.compute(es(e.inputs[0],r.perm))},vb=e=>jt({perm:e.perm})}),Of,Df,Lf,zf,Bf,Rf,Nf,jf,Vf,Uf,_s,xb,Tb,Eb,Pb,Cb,Sb,Ib,$b,kb,Ab,dT=Ve(()=>{gt(),Ct(),St(),Su(),cn(),Of={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},Df={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},Lf={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},zf={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Bf=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let o=0;oe[o]);return[t,n]},Nf=(e,r)=>{let t=e.length+r.length,s=[],n=0;for(let o=0;o{for(let t=0;t{let t=[];if(!jf(e,r)){for(let s=0;st.push(s))}return t},Uf=(e,r,t,s,n,o,i)=>{let a=t[0].dims,l=we.size(o),c=we.size(i),p=ke("_A",t[0].dataType,a),d=it("output",n,o),u=64;l===1&&(u=256);let f=` + var aBestValues : array; + `,_=y=>` + ${y.registerUniform("reduceSize","u32").declareVariables(p,d)} + ${f} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${y.mainStart(u)} + + let outputIndex = global_idx / ${u}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${Lf[s]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${u}) { + let candidate = f32(${p.getByOffset("offset + k")}); + bestValue = ${Of[s]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${u}u); + for (var currentSize = reduceSize / 2u; reduceSize > 1u; + currentSize = reduceSize / 2u) { + let interval = DIV_CEIL(reduceSize, 2u); + if (local_idx < currentSize) { + let candidate = aBestValues[local_idx + interval]; + bestValue = ${Df[s]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${d.setByOffset("outputIndex",`${s==="mean"?`${d.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${d.type.storage}(${zf[s]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${r};${u}`,inputDependencies:["type"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:o,dataType:n}],dispatchGroup:{x:l},programUniforms:[{type:12,data:c}]})}},_s=(e,r,t,s)=>{let n=e.inputs.length===1?t:ru(e.inputs,t),o=n.axes;o.length===0&&!n.noopWithEmptyAxes&&(o=e.inputs[0].dims.map((f,_)=>_));let i=we.normalizeAxes(o,e.inputs[0].dims.length),a=i,l=e.inputs[0],c=Vf(a,e.inputs[0].dims.length);c.length>0&&(l=e.compute(es(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],a=Bf(a.length,l.dims.length));let[p,d]=Rf(l.dims,a),u=p;n.keepDims&&(u=Nf(p,i)),e.compute(Uf(r,n.cacheKey,[l],s,e.inputs[0].dataType,u,d),{inputs:[l]})},xb=(e,r)=>{_s(e,"ReduceMeanShared",r,"mean")},Tb=(e,r)=>{_s(e,"ReduceL1Shared",r,"l1")},Eb=(e,r)=>{_s(e,"ReduceL2Shared",r,"l2")},Pb=(e,r)=>{_s(e,"ReduceLogSumExpShared",r,"logSumExp")},Cb=(e,r)=>{_s(e,"ReduceMaxShared",r,"max")},Sb=(e,r)=>{_s(e,"ReduceMinShared",r,"min")},Ib=(e,r)=>{_s(e,"ReduceProdShared",r,"prod")},$b=(e,r)=>{_s(e,"ReduceSumShared",r,"sum")},kb=(e,r)=>{_s(e,"ReduceSumSquareShared",r,"sumSquare")},Ab=(e,r)=>{_s(e,"ReduceLogSumShared",r,"logSum")}}),fs,Wf,hi,ru,gs,Gf,Kf,Hf,qf,Qf,Xf,Jf,Yf,Zf,eg,Ms,Fb,Ob,Db,Lb,zb,Bb,Rb,Nb,jb,Vb,Su=Ve(()=>{gt(),Ct(),mr(),St(),dT(),fs=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},Wf=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],hi=(e,r,t,s,n,o,i=!1,a=!1)=>{let l=[],c=t[0].dims,p=c.length,d=we.normalizeAxes(n,p),u=!a&&d.length===0;c.forEach((y,k)=>{u||d.indexOf(k)>=0?i&&l.push(1):l.push(y)});let f=l.length,_=we.size(l);return{name:e,shaderCache:r,getShaderSource:y=>{let k=[],w=ke("_A",t[0].dataType,p),v=it("output",o,f),I=s(w,v,d),T=I[2];for(let b=0,E=0;b=0?(i&&E++,T=`for(var j${b}: u32 = 0; j${b} < ${c[b]}; j${b}++) { + ${I[2].includes("last_index")?`let last_index = j${b};`:""} + ${w.indicesSet("input_indices",b,`j${b}`)} + ${T} + }`):(k.push(`${w.indicesSet("input_indices",b,v.indicesGet("output_indices",E))};`),E++);return` + + ${y.registerUniform("output_size","u32").declareVariables(w,v)} + + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${w.type.indices}; + let output_indices = ${v.offsetToIndices("global_idx")}; + + ${k.join(` +`)} + ${I[0]} // init ops for reduce max/min + ${I[1]} + ${T} + ${I[3]} + ${I.length===4?v.setByOffset("global_idx","value"):I.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:l,dataType:o}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ct(c,l)]})}},ru=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),jt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},gs=(e,r,t,s)=>{let n=e.inputs,o=n.length===1?t:ru(n,t);e.compute(hi(r,{hint:o.cacheKey,inputDependencies:["rank"]},[n[0]],o.noopWithEmptyAxes&&o.axes.length===0?Wf:s,o.axes,n[0].dataType,o.keepDims,o.noopWithEmptyAxes),{inputs:[0]})},Gf=(e,r)=>{fs(e.inputs),gs(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},Kf=(e,r)=>{fs(e.inputs),gs(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},Hf=(e,r)=>{fs(e.inputs),gs(e,"ReduceL2",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},qf=(e,r)=>{fs(e.inputs),gs(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},Qf=(e,r)=>{fs(e.inputs),gs(e,"ReduceMax",r,(t,s,n)=>{let o=[];for(let i=0;i=0||n.length===0)&&o.push(t.indicesSet("input_indices",i,0));return[`${o.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},Xf=(e,r)=>{fs(e.inputs),gs(e,"ReduceMean",r,(t,s,n)=>{let o=1;for(let i=0;i=0||n.length===0)&&(o*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${o});`]})},Jf=(e,r)=>{fs(e.inputs),gs(e,"ReduceMin",r,(t,s,n)=>{let o=[];for(let i=0;i=0||n.length===0)&&o.push(`input_indices[${i}] = 0;`);return[`${o.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},Yf=(e,r)=>{fs(e.inputs),gs(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},Zf=(e,r)=>{fs(e.inputs),gs(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},eg=(e,r)=>{fs(e.inputs),gs(e,"ReduceSumSquare",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},Ms=(e,r,t)=>{if(r.length===0)return t;let s=1,n=1;for(let o=0;o1024},Fb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Xf(e,r):xb(e,r)},Ob=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Kf(e,r):Tb(e,r)},Db=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Hf(e,r):Eb(e,r)},Lb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?qf(e,r):Pb(e,r)},zb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Qf(e,r):Cb(e,r)},Bb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Jf(e,r):Sb(e,r)},Rb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Yf(e,r):Ib(e,r)},Nb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Zf(e,r):$b(e,r)},jb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?eg(e,r):kb(e,r)},Vb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Gf(e,r):Ab(e,r)}}),fc,Ub,Wb,su,pT=Ve(()=>{gt(),mr(),Su(),fc=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Ub=(e,r)=>{fc(e.inputs);let t=(s,n,o)=>{let i=[];for(let a=0;a=0||o.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` +`)}`,`var value = ${s.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?"<=":"<"} value) { + value = ${s.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",n.setByOffset("global_idx","best_index")]};e.compute(hi("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Wb=(e,r)=>{fc(e.inputs);let t=(s,n,o)=>{let i=[];for(let a=0;a=0||o.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` +`)}`,`var value = ${s.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?">=":">"} value) { + value = ${s.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",n.setByOffset("global_idx","best_index")]};e.compute(hi("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},su=e=>jt(e)}),tg,ei,rg,sg,ng,Zo,og,Gb,Iu=Ve(()=>{gt(),Ct(),Pu(),St(),tg=(e,r)=>{let t=e[0],s=e[1],n=e[2],o=e[3],i=e[4],a=e[5];if(i&&a)throw new Error("Attention cannot have both past and attention_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=t.dims[0],c=t.dims[1],p=t.dims[2];if(n.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(s.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(s.dims[0]!==p)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(n.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let d=n.dims[0]/3,u=d,f=u;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let I of r.qkvHiddenSizes)if(I%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");d=r.qkvHiddenSizes[0],u=r.qkvHiddenSizes[1],f=r.qkvHiddenSizes[2]}let _=c;if(d!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(n.dims[0]!==d+u+f)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let y=0;if(i){if(u!==f)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==u/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(y=i.dims[3])}let k=_+y,w=-1,v=0;if(o)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(a){if(a.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(a.dims[0]!==l||a.dims[1]!==r.numHeads||a.dims[2]!==c||a.dims[3]!==k)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:c,pastSequenceLength:y,kvSequenceLength:_,totalSequenceLength:k,maxSequenceLength:w,inputHiddenSize:p,hiddenSize:d,vHiddenSize:f,headSize:Math.floor(d/r.numHeads),vHeadSize:Math.floor(f/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:v,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ei=(e,r,t)=>r&&e?` + let total_sequence_length_input = u32(${r.getByOffset("0")}); + let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); + let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + `:` + ${t?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,rg=(e,r,t,s,n,o,i,a)=>{let l=ur(i?1:o),c=64,p=o/l;p{let v=it("x",e.dataType,e.dims,l),I=[v],T=i?ke("seq_lens",i.dataType,i.dims):void 0;T&&I.push(T);let b=a?ke("total_sequence_length_input",a.dataType,a.dims):void 0;b&&I.push(b);let E=jr(e.dataType),x=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${w.registerUniforms(x).declareVariables(...I)} + ${w.mainStart([c,1,1])} + let batchIdx = workgroup_id.z / uniforms.num_heads; + let headIdx = workgroup_id.z % uniforms.num_heads; + let sequence_length = uniforms.sequence_length; + var total_sequence_length = uniforms.total_sequence_length; + ${ei(T,b,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${c}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + var thread_max_vector = ${_}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${_}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(l){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${l}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${c}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${_}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${_}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(l){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${l}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${c}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + x[offset + i] = ${v.type.value}(${E}(1.0) / ${E}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${_}(x[offset + i]); + x[offset + i] = ${v.type.value}(exp(f32input - max_value) / sum); + } + } + ${i?` + for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { + x[offset + total_seq_id] = ${v.type.value}(${E}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${f};${l}`,inputDependencies:y},getShaderSource:k,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:n,z:r*t},programUniforms:u})}},sg=(e,r,t,s,n,o,i,a,l)=>{let c=i+o.kvSequenceLength,p=[o.batchSize,o.numHeads,o.sequenceLength,c],d=e>1&&s,u=o.kvNumHeads?o.kvNumHeads:o.numHeads,f=d?[o.batchSize,u,c,o.headSize]:void 0,_=o.nReps?o.nReps:1,y=o.scale===0?1/Math.sqrt(o.headSize):o.scale,k=ur(o.headSize),w=o.headSize/k,v=12,I={x:Math.ceil(c/v),y:Math.ceil(o.sequenceLength/v),z:o.batchSize*o.numHeads},T=[{type:12,data:o.sequenceLength},{type:12,data:w},{type:12,data:c},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:1,data:y},{type:12,data:i},{type:12,data:o.kvSequenceLength},{type:12,data:_}],b=d&&s&&we.size(s.dims)>0,E=["type","type"];b&&E.push("type"),n&&E.push("type"),a&&E.push("type"),l&&E.push("type");let x=[{dims:p,dataType:r.dataType,gpuDataType:0}];d&&x.push({dims:f,dataType:r.dataType,gpuDataType:0});let S=O=>{let F=ke("q",r.dataType,r.dims,k),H=ke("key",t.dataType,t.dims,k),W=[F,H];if(b){let le=ke("past_key",s.dataType,s.dims,k);W.push(le)}n&&W.push(ke("attention_bias",n.dataType,n.dims));let B=a?ke("seq_lens",a.dataType,a.dims):void 0;B&&W.push(B);let Y=l?ke("total_sequence_length_input",l.dataType,l.dims):void 0;Y&&W.push(Y);let X=it("output",r.dataType,p),J=[X];d&&J.push(it("present_key",r.dataType,f,k));let re=jr(1,k),ne=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${v}u; + + var tileQ: array<${F.type.storage}, ${v*v}>; + var tileK: array<${F.type.storage}, ${v*v}>; + ${O.registerUniforms(ne).declareVariables(...W,...J)} + ${O.mainStart([v,v,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${_===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${_===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${ei(B,Y,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${b&&d?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${d?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${re}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${b&&d?` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }`:` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${d?`if (n + local_id.y < present_sequence_length) { + present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; + }`:""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${re}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { + let headOffset = workgroup_id.z * uniforms.M * uniforms.N; + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(k){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${k}`)}})()}; + output[outputIdx] = ${X.type.value} (sum * uniforms.alpha) + ${n?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${k};${n!==void 0};${s!==void 0};${e}`,inputDependencies:E},getRunData:()=>({outputs:x,dispatchGroup:I,programUniforms:T}),getShaderSource:S}},ng=(e,r,t,s,n,o,i=void 0,a=void 0)=>{let l=o+n.kvSequenceLength,c=n.nReps?n.nReps:1,p=n.vHiddenSize*c,d=e>1&&s,u=n.kvNumHeads?n.kvNumHeads:n.numHeads,f=d?[n.batchSize,u,l,n.headSize]:void 0,_=[n.batchSize,n.sequenceLength,p],y=12,k={x:Math.ceil(n.vHeadSize/y),y:Math.ceil(n.sequenceLength/y),z:n.batchSize*n.numHeads},w=[{type:12,data:n.sequenceLength},{type:12,data:l},{type:12,data:n.vHeadSize},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:12,data:p},{type:12,data:o},{type:12,data:n.kvSequenceLength},{type:12,data:c}],v=d&&s&&we.size(s.dims)>0,I=["type","type"];v&&I.push("type"),i&&I.push("type"),a&&I.push("type");let T=[{dims:_,dataType:r.dataType,gpuDataType:0}];d&&T.push({dims:f,dataType:r.dataType,gpuDataType:0});let b=E=>{let x=ke("probs",r.dataType,r.dims),S=ke("v",t.dataType,t.dims),O=[x,S];v&&O.push(ke("past_value",s.dataType,s.dims));let F=i?ke("seq_lens",i.dataType,i.dims):void 0;i&&O.push(F);let H=a?ke("total_sequence_length_input",a.dataType,a.dims):void 0;a&&O.push(H);let W=[it("output",r.dataType,_)];d&&W.push(it("present_value",r.dataType,f));let B=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${y}u; + var tileQ: array<${x.type.value}, ${y*y}>; + var tileV: array<${x.type.value}, ${y*y}>; + ${E.registerUniforms(B).declareVariables(...O,...W)} + ${E.mainStart([y,y,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${c===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${c===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let m = global_id.y; + let n = global_id.x; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.K; + ${ei(F,H,!0)} + let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch + ${v&&d?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${d?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${x.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${v&&d?` + if (w + local_id.y < past_sequence_length) { + tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; + } + `:` + if (w + local_id.y < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; + }`} + ${d?` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }`:""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:I},getRunData:()=>({outputs:T,dispatchGroup:k,programUniforms:w}),getShaderSource:b}},Zo=(e,r,t,s,n,o,i,a,l,c,p=void 0,d=void 0)=>{let u=Math.min(e.outputCount,1+(i?1:0)+(a?1:0)),f=u>1?c.pastSequenceLength:0,_=f+c.kvSequenceLength,y=l&&we.size(l.dims)>0?l:void 0,k=[r,t];u>1&&i&&we.size(i.dims)>0&&k.push(i),y&&k.push(y),p&&k.push(p),d&&k.push(d);let w=e.compute(sg(u,r,t,i,y,c,f,p,d),{inputs:k,outputs:u>1?[-1,1]:[-1]})[0];e.compute(rg(w,c.batchSize,c.numHeads,f,c.sequenceLength,_,p,d),{inputs:p&&d?[w,p,d]:[w],outputs:[]});let v=[w,s];u>1&&a&&we.size(a.dims)>0&&v.push(a),p&&v.push(p),d&&v.push(d),e.compute(ng(u,w,s,a,c,f,p,d),{inputs:v,outputs:u>1?[0,2]:[0]})},og=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,n=r.inputHiddenSize,o=r.headSize,i=12,a={x:Math.ceil(r.headSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:s},{type:12,data:n},{type:12,data:o},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:r.hiddenSize},{type:12,data:r.hiddenSize+r.hiddenSize+r.vHiddenSize}],p=d=>{let u=it("output_q",l[0].dataType,t),f=it("output_k",l[0].dataType,t),_=it("output_v",l[0].dataType,t),y=ke("input",l[0].dataType,l[0].dims),k=ke("weight",l[1].dataType,l[1].dims),w=ke("bias",l[2].dataType,l[2].dims),v=y.type.storage,I=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${i}u; + var tileInput: array<${v}, ${i*i}>; + var tileWeightQ: array<${v}, ${i*i}>; + var tileWeightK: array<${v}, ${i*i}>; + var tileWeightV: array<${v}, ${i*i}>; + ${d.registerUniforms(I).declareVariables(y,k,w,u,f,_)} + ${d.mainStart([i,i,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${v}(0); + var valueK = ${v}(0); + var valueV = ${v}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:a,programUniforms:c}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},Gb=(e,r)=>{let t=tg(e.inputs,r),[s,n,o]=og(e,t);return Zo(e,s,n,o,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),ag,ig,lg,Kb,mT=Ve(()=>{Es(),gt(),Ct(),mr(),St(),ag=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,n,o)=>{let i=n.length;if(i!==s.length)throw new Error(`${o}: num dimensions != ${i}`);n.forEach((a,l)=>{if(a!==s[l])throw new Error(`${o}: dim[${l}] do not match`)})};if(e[0].dims.length>1){let s=r.format==="NHWC"?r.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,r.spatial?2:void 0);t(e[1].dims,s,"Invalid input scale"),t(e[2].dims,s,"Invalid input B"),t(e[3].dims,s,"Invalid input mean"),t(e[4].dims,s,"Invalid input var")}else t(e[1].dims,[1],"Invalid input scale"),t(e[2].dims,[1],"Invalid input B"),t(e[3].dims,[1],"Invalid input mean"),t(e[4].dims,[1],"Invalid input var")},ig=(e,r)=>{let{epsilon:t,spatial:s,format:n}=r,o=e[0].dims,i=s?ur(o[o.length-1]):1,a=n==="NHWC"&&o.length>1?i:1,l=we.size(o)/i,c=s,p=c?o.length:o,d=ke("x",e[0].dataType,e[0].dims,i),u=ke("scale",e[1].dataType,e[1].dims,a),f=ke("bias",e[2].dataType,e[2].dims,a),_=ke("inputMean",e[3].dataType,e[3].dims,a),y=ke("inputVar",e[4].dataType,e[4].dims,a),k=it("y",e[0].dataType,p,i),w=()=>{let I="";if(s)I=`let cOffset = ${o.length===1?"0u":n==="NHWC"?`outputIndices[${o.length-1}] / ${i}`:"outputIndices[1]"};`;else if(n==="NCHW")I=` + ${k.indicesSet("outputIndices","0","0")} + let cOffset = ${k.indicesToOffset("outputIndices")};`;else{I=`var cIndices = ${u.type.indices}(0); + cIndices[0] = outputIndices[${o.length-1}];`;for(let T=1;T` + const epsilon = ${t}; + ${I.registerUniform("outputSize","u32").declareVariables(d,u,f,_,y,k)} + ${I.mainStart()} + ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${k.offsetToIndices(`global_idx * ${i}`)}; + ${w()} + let scale = ${u.getByOffset("cOffset")}; + let bias = ${f.getByOffset("cOffset")}; + let inputMean = ${_.getByOffset("cOffset")}; + let inputVar = ${y.getByOffset("cOffset")}; + let x = ${d.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${k.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${i}`,inputDependencies:c?["rank","type","type","type","type"]:void 0},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c?[{type:12,data:l},...ct(o)]:[{type:12,data:l}]})}},lg=e=>jt(e),Kb=(e,r)=>{let{inputs:t,outputCount:s}=e,n=lg({...r,outputCount:s});if(Jt.webgpu.validateInputContent&&ag(t,n),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(ig(t,n))}}),cg,ug,Hb,hT=Ve(()=>{Ct(),St(),cg=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},ug=e=>{let r=e[0].dims,t=e[0].dims[2],s=we.size(r)/4,n=e[0].dataType,o=ke("input",n,r,4),i=ke("bias",n,[t],4),a=ke("residual",n,r,4),l=it("output",n,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:c=>` + const channels = ${t}u / 4; + ${c.declareVariables(o,i,a,l)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes(s)} + let value = ${o.getByOffset("global_idx")} + + ${i.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; + ${l.setByOffset("global_idx","value")} + }`}},Hb=e=>{cg(e.inputs),e.compute(ug(e.inputs))}}),dg,Bt,qb,Qb,Xb,Jb,Yb,Zb,ey,ty,ry,pg,sy,ny,oy,ay,qo,iy,ui,ly,cy,uy,dy,py,my,hy,_y,fy,gy,My,wy,by,yy,vy,xy,gc,Ty,nu,ou,Ey,Py,Cy,mg,hg,Sy,$u=Ve(()=>{gt(),Ct(),mr(),St(),dg=(e,r,t,s,n,o,i)=>{let a=Math.ceil(r/4),l="";typeof n=="string"?l=`${n}(a)`:l=n("a");let c=ke("inputData",t,[a],4),p=it("outputData",s,[a],4),d=[{name:"vec_size",type:"u32"}];return i&&d.push(...i),` + ${e.registerUniforms(d).declareVariables(c,p)} + + ${o??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${c.getByOffset("global_idx")}; + ${p.setByOffset("global_idx",l)} + }`},Bt=(e,r,t,s,n,o=e.dataType,i,a)=>{let l=[{type:12,data:Math.ceil(we.size(e.dims)/4)}];return i&&l.push(...i),{name:r,shaderCache:{hint:n,inputDependencies:["type"]},getShaderSource:c=>dg(c,we.size(e.dims),e.dataType,o,t,s,a),getRunData:c=>({outputs:[{dims:e.dims,dataType:o}],dispatchGroup:{x:Math.ceil(we.size(c[0].dims)/64/4)},programUniforms:l})}},qb=e=>{e.compute(Bt(e.inputs[0],"Abs","abs"))},Qb=e=>{e.compute(Bt(e.inputs[0],"Acos","acos"))},Xb=e=>{e.compute(Bt(e.inputs[0],"Acosh","acosh"))},Jb=e=>{e.compute(Bt(e.inputs[0],"Asin","asin"))},Yb=e=>{e.compute(Bt(e.inputs[0],"Asinh","asinh"))},Zb=e=>{e.compute(Bt(e.inputs[0],"Atan","atan"))},ey=e=>{e.compute(Bt(e.inputs[0],"Atanh","atanh"))},ty=e=>jt(e),ry=(e,r)=>{let t;switch(r.to){case 10:t="vec4";break;case 1:t="vec4";break;case 12:t="vec4";break;case 6:t="vec4";break;case 9:t="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${r.to}`)}e.compute(Bt(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},pg=e=>{let r,t,s=e.length>=2&&e[1].data!==0,n=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=n?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=n?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return jt({min:r,max:t})},sy=(e,r)=>{let t=r||pg(e.inputs),s=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Clip",n=>`clamp(${n}, vec4<${s}>(uniforms.min), vec4<${s}>(uniforms.max))`,void 0,t.cacheKey,void 0,[{type:e.inputs[0].dataType,data:t.min},{type:e.inputs[0].dataType,data:t.max}],[{name:"min",type:s},{name:"max",type:s}]),{inputs:[0]})},ny=e=>{e.compute(Bt(e.inputs[0],"Ceil","ceil"))},oy=e=>{e.compute(Bt(e.inputs[0],"Cos","cos"))},ay=e=>{e.compute(Bt(e.inputs[0],"Cosh","cosh"))},qo=e=>jt(e),iy=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` + const elu_alpha_ = ${t}(${r.alpha}); + + fn elu_f32(a: ${t}) -> ${t} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${t}>) -> vec4<${t}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,r.cacheKey))},ui=(e="f32")=>` +const r0: ${e} = 0.3275911; +const r1: ${e} = 0.254829592; +const r2: ${e} = -0.284496736; +const r3: ${e} = 1.421413741; +const r4: ${e} = -1.453152027; +const r5: ${e} = 1.061405429; + +fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> { + let absv = abs(v); + let x = 1.0 / (1.0 + r0 * absv); + return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); +}`,ly=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,ui(r)))},cy=e=>{e.compute(Bt(e.inputs[0],"Exp","exp"))},uy=e=>{e.compute(Bt(e.inputs[0],"Floor","floor"))},dy=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,ui(r)))},py=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"LeakyRelu",s=>`select(leaky_relu_alpha_ * ${s}, ${s}, ${s} >= vec4<${t}>(0.0))`,`const leaky_relu_alpha_ = ${t}(${r.alpha});`,r.cacheKey))},my=e=>{e.compute(Bt(e.inputs[0],"Not",r=>`!${r}`))},hy=e=>{e.compute(Bt(e.inputs[0],"Neg",r=>`-${r}`))},_y=e=>{e.compute(Bt(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},fy=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},gy=e=>{e.compute(Bt(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},My=e=>jt(e),wy=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"HardSigmoid",s=>`max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), ${r.alpha} * ${s} + vec4<${t}>(${r.beta})))`,void 0,r.cacheKey))},by=e=>{e.compute(Bt(e.inputs[0],"Sin","sin"))},yy=e=>{e.compute(Bt(e.inputs[0],"Sinh","sinh"))},vy=e=>{e.compute(Bt(e.inputs[0],"Sqrt","sqrt"))},xy=e=>{e.compute(Bt(e.inputs[0],"Tan","tan"))},gc=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Ty=e=>{e.compute(Bt(e.inputs[0],"Tanh",gc))},nu=(e="f32")=>` +const fast_gelu_a: ${e} = 0.5; +const fast_gelu_b: ${e} = 0.7978845608028654; +const fast_gelu_c: ${e} = 0.035677408136300125; + +fn tanh_v(v: vec4<${e}>) -> vec4<${e}> { + return ${gc("v")}; +} +`,ou=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Ey=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"FastGelu",ou,nu(r),void 0,e.inputs[0].dataType))},Py=(e,r)=>{let t=jr(e.inputs[0].dataType);return e.compute(Bt(e.inputs[0],"ThresholdedRelu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${t}>(${r.alpha});`,r.cacheKey)),0},Cy=e=>{e.compute(Bt(e.inputs[0],"Log","log"))},mg=(e,r)=>` +const alpha = vec4<${e}>(${r}); +const one = ${e}(1.0); +const zero = ${e}(0.0); + +fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { + let v = x *alpha; + var x1 : vec4<${e}>; + for (var i = 0; i < 4; i = i + 1) { + if (v[i] >= zero) { + x1[i] = one / (one + exp(-v[i])); + } else { + x1[i] = one - one / (one + exp(v[i])); + } + } + return x * x1; +} +`,hg=e=>`quick_gelu_impl(${e})`,Sy=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"QuickGelu",hg,mg(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),_g,fg,Iy,_T=Ve(()=>{Ct(),St(),$u(),_g=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},fg=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=ke("input",e[0].dataType,e[0].dims,4),s=ke("bias",e[0].dataType,[e[0].dims[2]],4),n=it("output",e[0].dataType,r,4),o=we.size(r)/4,i=Ar(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:a=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${a.declareVariables(t,s,n)} + + ${ui(i)} + + ${a.mainStart()} + ${a.guardAgainstOutOfBoundsWorkgroupSizes(o)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${n.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Iy=e=>{_g(e.inputs),e.compute(fg(e.inputs))}}),gg,Mg,ws,$y,ky,Ay,Fy,Oy,Dy,Ly,zy,By,Ry,fT=Ve(()=>{gt(),Ct(),St(),gg=(e,r,t,s,n,o,i,a,l,c,p,d)=>{let u,f;typeof a=="string"?u=f=(v,I)=>`${a}((${v}),(${I}))`:typeof a=="function"?u=f=a:(u=a.scalar,f=a.vector);let _=it("outputData",p,s.length,4),y=ke("aData",l,r.length,4),k=ke("bData",c,t.length,4),w;if(n)if(o){let v=we.size(r)===1,I=we.size(t)===1,T=r.length>0&&r[r.length-1]%4===0,b=t.length>0&&t[t.length-1]%4===0;v||I?w=_.setByOffset("global_idx",f(v?`${y.type.value}(${y.getByOffset("0")}.x)`:y.getByOffset("global_idx"),I?`${k.type.value}(${k.getByOffset("0")}.x)`:k.getByOffset("global_idx"))):w=` + let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; + let offsetA = ${y.broadcastedIndicesToOffset("outputIndices",_)}; + let offsetB = ${k.broadcastedIndicesToOffset("outputIndices",_)}; + ${_.setByOffset("global_idx",f(i||T?y.getByOffset("offsetA / 4u"):`${y.type.value}(${y.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||b?k.getByOffset("offsetB / 4u"):`${k.type.value}(${k.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else w=_.setByOffset("global_idx",f(y.getByOffset("global_idx"),k.getByOffset("global_idx")));else{if(!o)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let v=(I,T,b="")=>{let E=`aData[indexA${T}][componentA${T}]`,x=`bData[indexB${T}][componentB${T}]`;return` + let outputIndices${T} = ${_.offsetToIndices(`global_idx * 4u + ${T}u`)}; + let offsetA${T} = ${y.broadcastedIndicesToOffset(`outputIndices${T}`,_)}; + let offsetB${T} = ${k.broadcastedIndicesToOffset(`outputIndices${T}`,_)}; + let indexA${T} = offsetA${T} / 4u; + let indexB${T} = offsetB${T} / 4u; + let componentA${T} = offsetA${T} % 4u; + let componentB${T} = offsetB${T} % 4u; + ${I}[${T}] = ${b}(${u(E,x)}); + `};p===9?w=` + var data = vec4(0); + ${v("data",0,"u32")} + ${v("data",1,"u32")} + ${v("data",2,"u32")} + ${v("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:w=` + ${v("outputData[global_idx]",0)} + ${v("outputData[global_idx]",1)} + ${v("outputData[global_idx]",2)} + ${v("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(y,k,_)} + + ${d??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${w} + }`},Mg=(e,r,t,s,n,o,i=t.dataType)=>{let a=t.dims.map(y=>Number(y)??1),l=s.dims.map(y=>Number(y)??1),c=!we.areEqual(a,l),p=a,d=we.size(a),u=!1,f=!1,_=[c];if(c){let y=lo.calcShape(a,l,!1);if(!y)throw new Error("Can't perform binary op on the given tensors");p=y.slice(),d=we.size(p);let k=we.size(a)===1,w=we.size(l)===1,v=a.length>0&&a[a.length-1]%4===0,I=l.length>0&&l[l.length-1]%4===0;_.push(k),_.push(w),_.push(v),_.push(I);let T=1;for(let b=1;by.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:y=>gg(y,a,l,p,u,c,f,n,t.dataType,s.dataType,i,o),getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(we.size(p)/4)},...ct(a,l,p)]})}},ws=(e,r,t,s,n,o)=>{e.compute(Mg(r,n??"",e.inputs[0],e.inputs[1],t,s,o))},$y=e=>{ws(e,"Add",(r,t)=>`${r}+${t}`)},ky=e=>{ws(e,"Div",(r,t)=>`${r}/${t}`)},Ay=e=>{ws(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},Fy=e=>{ws(e,"Mul",(r,t)=>`${r}*${t}`)},Oy=e=>{let r=ke("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ws(e,"Pow",{scalar:(t,s)=>`pow_custom(${t},${s})`,vector:(t,s)=>`pow_vector_custom(${t},${s})`},` + fn pow_custom(a : ${r}, b : ${r}) -> ${r} { + if (b == ${r}(0.0)) { + return ${r}(1.0); + } else if (a < ${r}(0.0) && f32(b) != floor(f32(b))) { + return ${r}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${r}(1.0), round(f32(abs(b) % ${r}(2.0))) != 1.0) * ${r}(${r==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${r}>, b : vec4<${r}>) -> vec4<${r}> { + // TODO: implement vectorized pow + return vec4<${r}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},Dy=e=>{ws(e,"Sub",(r,t)=>`${r}-${t}`)},Ly=e=>{ws(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},zy=e=>{ws(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},By=e=>{ws(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},Ry=e=>{ws(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),wg,bg,yg,vg,Ny,jy,gT=Ve(()=>{gt(),Ct(),mr(),St(),wg=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],n=s.dataType,o=s.dims.length;e.forEach((i,a)=>{if(a!==t){if(i.dataType!==n)throw new Error("input tensors should be one type");if(i.dims.length!==o)throw new Error("input tensors should have the same shape");i.dims.forEach((l,c)=>{if(c!==r&&l!==s.dims[c])throw new Error("non concat dimensions must match")})}})},bg=(e,r)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${r}); + for (var i: u32 = 0u; i < ${e}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${e}u; + }`,yg=(e,r)=>{let t=e.length,s=[];for(let n=0;n{let n=we.size(t),o=new Array(e.length),i=new Array(e.length),a=0,l=[],c=[],p=[{type:12,data:n}];for(let y=0;y`uniforms.sizeInConcatAxis${y}`).join(","),_=y=>` + + ${(()=>{y.registerUniform("outputSize","u32");for(let k=0;k(${f}); + ${u} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${yg(i,d)} + }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}),getShaderSource:_}},Ny=(e,r)=>{let t=e.inputs,s=t[0].dims,n=we.normalizeAxis(r.axis,s.length);wg(t,n);let o=s.slice();o[n]=t.reduce((a,l)=>a+(l.dims.length>n?l.dims[n]:0),0);let i=t.filter(a=>we.size(a.dims)>0);e.compute(vg(i,n,o,t[0].dataType),{inputs:i})},jy=e=>jt({axis:e.axis})}),$n,kn,An,ku,On=Ve(()=>{gt(),Ct(),$n=(e,r,t="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${r}(0.0));`;case"Sigmoid":return`value = (${r}(1.0) / (${r}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${r}(${t}(uniforms.clip_min)), ${r}(${t}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${r}(0.0), min(${r}(1.0), ${t}(uniforms.alpha) * value + ${t}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${t}(uniforms.alpha) * value, value, value >= ${r}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},kn=(e,r)=>{e.activation==="Clip"?r.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?r.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&r.push({type:1,data:e.alpha})},An=(e,r)=>{e.activation==="Clip"?r.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?r.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&r.push({name:"alpha",type:"f32"})},ku=e=>{let r=e?.activation||"";if(r==="HardSigmoid"){let[t,s]=e?.activation_params||[.2,.5];return{activation:r,alpha:t,beta:s}}else if(r==="Clip"){let[t,s]=e?.activation_params||[mb,hb];return{activation:r,clipMax:s,clipMin:t}}else if(r==="LeakyRelu"){let[t]=e?.activation_params||[.01];return{activation:r,alpha:t}}return{activation:r}}}),Fr,Vy,Au=Ve(()=>{Fr=(e,r)=>{switch(e){case 1:return r;case 2:return`vec2<${r}>`;case 3:return`vec3<${r}>`;case 4:return`vec4<${r}>`;default:throw new Error(`${e}-component is not supported.`)}},Vy=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),Uy,MT=Ve(()=>{Uy=e=>` +fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { + return dot(coords, vec4( + shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); +} +fn getOutputIndexFromCoords(coords : vec4) -> i32 { + return dot(coords, vec4( + i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); +} +`}),Xo,Fu,Ou=Ve(()=>{gt(),Ct(),St(),On(),Xo=(e,r,t,s,n)=>{let o=s-t;return` + ${Array.from({length:t}).map((i,a)=>` + if (${lt(r.shape,a,r.rank)} != 1) { + ${r.indicesSet(e,a,lt(n,a+o,s))} + } else { + ${r.indicesSet(e,a,0)} + }`).join("")} +`},Fu=(e,r,t,s,n=!1,o)=>{let i=e[0].dims,a=e[1].dims,l=i[i.length-2],c=a[a.length-1],p=i[i.length-1],d=ur(c),u=ur(p),f=ur(l),_=we.size(t)/d/f,y=e.length>2,k=s?s.slice(0,-2):t.slice(0,-2),w=[we.size(k),l,c],v=[{type:12,data:_},{type:12,data:l},{type:12,data:c},{type:12,data:p}];kn(r,v),v.push(...ct(k,i,a)),y&&v.push(...ct(e[2].dims)),v.push(...ct(w));let I=T=>{let b=Cu("batch_dims",e[0].dataType,k.length),E=ke("a",e[0].dataType,i.length,u),x=ke("b",e[1].dataType,a.length,d),S=it("output",e[0].dataType,w.length,d),O=Ar(S.type.tensor),F=$n(r,S.type.value,O),H=[E,x],W="";if(y){let X=n?d:1;H.push(ke("bias",e[2].dataType,e[2].dims.length,X)),W=`${n?`value += bias[col / ${X}];`:`value += ${S.type.value}(bias[row + i]);`}`}let B=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];An(r,B);let Y=()=>{let X=`var a_data: ${E.type.value};`;for(let J=0;J; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) { + ${Y()} + } + for (var i = 0u; i < ${f}u; i++) { + var value = values[i]; + ${W} + ${F} + let cur_indices = ${S.type.indices}(batch, row + i, col); + let offset = ${S.indicesToOffset("cur_indices")}; + ${S.setByOffset(`offset / ${d}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${d};${u};${f};${n}`,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:o?o(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:v}),getShaderSource:I}}}),xg,Tg,au,Mc,Eg,iu,Pg,_i,Du=Ve(()=>{gt(),Ct(),St(),On(),Ou(),Au(),xg=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${r?", batchIndices":""}); + `,Tg=(e,r)=>e?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${r===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} + for (var i = 0; i < rowPerThread; i = i + 1) { + acc[i] = BCached0 * ACached0[i] + acc[i]; + acc[i] = BCached1 * ACached1[i] + acc[i]; + acc[i] = BCached2 * ACached2[i] + acc[i]; + ${r===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} + }`:` + for (var i = 0; i < rowPerThread; i = i + 1) { + let ACached = mm_Asub[tileRow + i][k]; + acc[i] = BCached0 * ACached.x + acc[i]; + acc[i] = BCached1 * ACached.y + acc[i]; + acc[i] = BCached2 * ACached.z + acc[i]; + ${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,au=(e,r,t="f32",s,n=!1,o=32,i=!1,a=32)=>{let l=r[1]*e[1],c=r[0]*e[0],p=n?l:o,d=n?o:l,u=p/r[0],f=o/r[1];if(!((n&&u===4&&e[1]===4||!n&&(u===3||u===4))&&p%r[0]===0&&o%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${n} is true, innerElementSize ${u} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${u} must be 3 or 4. + tileAWidth ${p} must be divisible by workgroupSize[0]${r[0]}. tileInner ${o} must be divisible by workgroupSize[1] ${r[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${p/u}>, ${d}>; +var mm_Bsub: array, ${c/e[0]}>, ${o}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${u}; +const tileInner = ${o}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${l}; + + let num_tiles = ${i?`${Math.ceil(a/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${f}; + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${xg(n,s)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${u===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${Tg(n,u)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},Mc=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${r?", batchIndices":""}); + `,Eg=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",iu=(e,r,t="f32",s,n=!1,o=32,i=!1,a=32,l=!1)=>{let c=e[1]*r[1],p=e[0]*r[0],d=n?c:o,u=n?o:c;if(!(u%r[1]===0&&d%r[0]===0&&o%r[1]===0))throw new Error(`tileAHight ${u} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${r[0]}, tileInner ${o} must be divisible by workgroupSize[1]${r[1]}`);let f=u/r[1],_=d/r[0],y=o/r[1],k=l?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${c}; + let globalColStart = i32(workgroupId.x) * ${p}; + + // Loop over shared dimension. + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${u}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${r[0]}) { + ${Mc(n,s)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${o}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${r[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${s?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${t}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${r[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${n?`mm_Asub[k][localRow + innerRow * ${r[1]}];`:`mm_Asub[localRow + innerRow * ${r[1]}][k];`} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + + ACached * BCached[innerCol]; + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let gRow = globalRowStart + localRow + innerRow * ${r[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${r[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${c}; + +let tileRowA = i32(localId.y) * ${f}; +let tileColA = i32(localId.x) * ${_}; +let tileRowB = i32(localId.y) * ${y}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${_}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${Mc(n,s)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${y}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${s?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${t}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${Eg(n)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${u}>; + var mm_Bsub : array, ${o}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${o}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${i?`${Math.ceil(a/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc : array, rowPerThread>; + ${k} + } +`},Pg=(e,r,t,s,n=!1)=>{let[o,i,a,l]=s,c=Ar(s[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${o.type.indices}) -> ${Fr(e,c)} { + var value = ${Fr(e,c)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${i.type.indices}; + ${Xo("aIndices",i,i.rank-2,o.rank,"batchIndices")} + ${i.indicesSet("aIndices",i.rank-2,"u32(row)")} + ${i.indicesSet("aIndices",i.rank-1,"u32(colIn)")} + value = ${i.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${o.type.indices}) -> ${Fr(e,c)} { + var value = ${Fr(e,c)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${a.type.indices}; + ${Xo("bIndices",a,a.rank-2,o.rank,"batchIndices")} + ${a.indicesSet("bIndices",a.rank-2,"u32(row)")} + ${a.indicesSet("bIndices",a.rank-1,"u32(colIn)")} + value = ${a.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Fr(e,c)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${r?`value = value + ${n?"bias[colIn]":`${Fr(e,c)}(bias[row])`};`:""} + ${t} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},_i=(e,r,t,s,n=!1,o)=>{let i=e[0].dims,a=e[1].dims,l=i.slice(0,-2),c=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),d=we.size(p),u=i[i.length-2],f=i[i.length-1],_=a[a.length-1],y=f%4===0&&_%4===0,k=u<=8?[4,1,1]:[4,4,1],w=[8,8,1],v=[Math.ceil(_/w[0]/k[0]),Math.ceil(u/w[1]/k[1]),Math.ceil(d/w[2]/k[2])],I=y?4:1,T=[...l,u,f/I],b=T.length,E=[...c,f,_/I],x=E.length,S=[d,u,_/I],O=[{type:6,data:u},{type:6,data:_},{type:6,data:f}];kn(r,O),O.push(...ct(p,T,E));let F=["rank","rank"],H=e.length>2;H&&(O.push(...ct(e[2].dims)),F.push("rank")),O.push(...ct(S));let W=B=>{let Y=p.length,X=Cu("batchDims",e[0].dataType,Y,1),J=Ar(e[0].dataType),re=ke("a",e[0].dataType,b,I),ne=ke("b",e[1].dataType,x,I),le=it("result",e[0].dataType,S.length,I),pe=[re,ne];if(H){let te=n?I:1;pe.push(ke("bias",e[2].dataType,e[2].dims.length,te))}let oe=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];An(r,oe);let K=Ar(le.type.tensor),N=$n(r,le.type.value,K),D=Pg(I,H,N,[X,re,ne,le],n);return` + ${B.registerUniforms(oe).registerInternalVariables(X).declareVariables(...pe,le)} + ${D} + ${y?au(k,w,J,X):iu(k,w,J,X)} + `};return{name:"MatMul",shaderCache:{hint:`${k};${r.activation};${y};${n}`,inputDependencies:F},getRunData:()=>({outputs:[{dims:o?o(t):t,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:O}),getShaderSource:W}}}),Cg,Wy,wT=Ve(()=>{gt(),Hs(),St(),On(),Au(),MT(),Du(),Cg=(e,r,t,s,n=!1,o,i=4,a=4,l=4,c="f32")=>{let p=O=>{switch(O){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${O} is not supported.`)}},d=O=>{switch(O){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${O} is not supported.`)}},u=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,f=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,_=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",y=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",k=e?"row":"col",w=e?"col":"row",v=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${k} / outWidth; + let outCol = ${k} % outWidth; + + let WRow = ${w} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${w} / inChannels % i32(uniforms.w_shape[1]); + let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; + let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; + let xCh = ${w} % inChannels; + var resData = ${Fr(i,c)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${_} && xCol >= 0 && xCol < ${y}) { + ${u} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${p(i)} + } + return resData;`,I=e?r&&s?` + let col = colIn * ${i}; + ${v}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${v} + } + return ${Fr(i,c)}(0.0);`:s&&t?` + let col = colIn * ${i}; + ${v}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${v} + } + return ${Fr(i,c)}(0.0);`,T=e?s&&t?d(a):` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${d(a)} + } + return ${Fr(a,c)}(0.0);`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${d(a)} + } + return ${Fr(a,c)}(0.0);`,b=Fr(l,c),E=Fr(e?i:a,c),x=Fr(e?a:i,c),S=$n(o,b,c);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${E} { + ${e?I:T} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${x} { + ${e?T:I} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${b}) { + let col = colIn * ${l}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${f} + ${Vy(n)} + ${S} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},Wy=(e,r,t,s,n,o,i,a,l)=>{let c=r.format==="NHWC",p=c?e[0].dims[3]:e[0].dims[1],d=t[0],u=c?t[2]:t[3],f=c?t[1]:t[2],_=c?t[3]:t[1],y=c&&(p%4===0||p%3===0)&&_%4===0,k=c?_:u*f,w=c?u*f:_,v=[8,8,1],I=s<=8?[4,1,1]:[4,4,1],T=[Math.ceil(k/v[0]/I[0]),Math.ceil(w/v[1]/I[1]),Math.ceil(d/v[2]/I[2])];Dt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${T}`);let b=y?c&&p%4!==0?3:4:1,E=v[1]*I[1],x=v[0]*I[0],S=Math.max(v[0]*b,v[1]),O=s%E===0,F=n%x===0,H=o%S===0,W=y?[b,4,4]:[1,1,1],B=[{type:6,data:s},{type:6,data:n},{type:6,data:o},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];kn(r,B),B.push(...ct(e[0].dims,e[1].dims));let Y=["rank","rank"];i&&(B.push(...ct(e[2].dims)),Y.push("rank")),B.push(...ct(t));let X=J=>{let re=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];An(r,re);let ne=y?4:1,le=Ar(e[0].dataType),pe=` + fn setOutputAtIndex(flatIndex : i32, value : ${y?`vec4<${le}>`:le}) { + result[flatIndex] = ${y?`vec4<${le}>`:le}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${y?`vec4<${le}>`:le}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${y?"/ 4":""}, value); + }`,oe=ke("x",e[0].dataType,e[0].dims.length,b===3?1:b),K=ke("w",e[1].dataType,e[1].dims.length,ne),N=[oe,K],D=it("result",e[0].dataType,t.length,ne);if(i){let te=ke("bias",e[2].dataType,e[2].dims.length,ne);N.push(te),pe+=` + fn getBiasByOutputCoords(coords : vec4) -> ${y?`vec4<${le}>`:le} { + return bias[coords.${c?"w":"y"}${y?"/ 4":""}]; + }`}return` + ${Uy("uniforms.result_strides")} + //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, + // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, + // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; + ${J.registerUniforms(re).declareVariables(...N,D)} + ${pe} + ${Cg(c,O,F,H,i,r,W[0],W[1],W[2],le)} + ${y?au(I,v,le,void 0,!c,S):iu(I,v,le,void 0,!c,S,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${b};${y};${O};${F};${H};${E};${x};${S}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:B}),getShaderSource:X}}}),Sg,wc,No,Ig,bc,$g,Gy,Ky,bT=Ve(()=>{gt(),Hs(),Ct(),St(),On(),Au(),Sg=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,No=(e,r)=>r<=1?e:e+(e-1)*(r-1),Ig=(e,r,t,s=1)=>{let n=No(r,s);return Math.floor((e[0]*(t-1)-t+n)/2)},bc=(e,r,t,s,n)=>{n==null&&(n=Ig(e,r[0],s[0]));let o=[0,0,0,t];for(let i=0;i<3;i++)e[i]+2*n>=r[i]&&(o[i]=Math.trunc((e[i]-r[i]+2*n)/s[i]+1));return o},$g=(e,r,t,s,n,o,i,a,l,c)=>{let p,d,u,f;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let _=bc([r,t,s,1],[a,l,c],1,[n,o,i],e);d=_[0],u=_[1],f=_[2]}else if(Array.isArray(e)){if(!e.every((y,k,w)=>y===w[0]))throw Error(`Unsupported padding parameter: ${e}`);p={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let _=bc([r,t,s,1],[a,l,c],1,[n,o,i],e[0]);d=_[0],u=_[1],f=_[2]}else if(e==="SAME_UPPER"){d=Math.ceil(r/n),u=Math.ceil(t/o),f=Math.ceil(s/i);let _=(d-1)*n+a-r,y=(u-1)*o+l-t,k=(f-1)*i+c-s,w=Math.floor(_/2),v=_-w,I=Math.floor(y/2),T=y-I,b=Math.floor(k/2),E=k-b;p={top:I,bottom:T,left:b,right:E,front:w,back:v}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:u,outWidth:f}},Gy=(e,r,t,s,n,o=!1,i="channelsLast")=>{let a,l,c,p,d;if(i==="channelsLast")[a,l,c,p,d]=e;else if(i==="channelsFirst")[a,d,l,c,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[u,,f,_,y]=r,[k,w,v]=wc(t),[I,T,b]=wc(s),E=No(f,I),x=No(_,T),S=No(y,b),{padInfo:O,outDepth:F,outHeight:H,outWidth:W}=$g(n,l,c,p,k,w,v,E,x,S),B=o?u*d:u,Y=[0,0,0,0,0];return i==="channelsFirst"?Y=[a,B,F,H,W]:i==="channelsLast"&&(Y=[a,F,H,W,B]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:c,inWidth:p,inChannels:d,outDepth:F,outHeight:H,outWidth:W,outChannels:B,padInfo:O,strideDepth:k,strideHeight:w,strideWidth:v,filterDepth:f,filterHeight:_,filterWidth:y,effectiveFilterDepth:E,effectiveFilterHeight:x,effectiveFilterWidth:S,dilationDepth:I,dilationHeight:T,dilationWidth:b,inShape:e,outShape:Y,filterShape:r}},Ky=(e,r,t,s,n,o)=>{let i=o==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((k,w)=>w)},c=[Math.ceil(Sg(l.x.map(k=>t[k]))/a[0]),1,1];Dt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${c}`);let p=1,d=we.size(t),u=[{type:12,data:d},{type:12,data:s},{type:12,data:n},{type:12,data:r.strides},{type:12,data:r.dilations}];kn(r,u),u.push(...ct(e[0].dims,e[1].dims));let f=["rank","rank"],_=e.length===3;_&&(u.push(...ct(e[2].dims)),f.push("rank")),u.push(...ct(t));let y=k=>{let w=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:n.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];An(r,w);let v=1,I=Ar(e[0].dataType),T=ke("x",e[0].dataType,e[0].dims.length,p),b=ke("W",e[1].dataType,e[1].dims.length,v),E=[T,b],x=it("result",e[0].dataType,t.length,v),S="";if(_){let H=ke("bias",e[2].dataType,e[2].dims.length,v);E.push(H),S+=` + fn getBiasByOutputCoords(coords : array) -> ${I} { + return bias[${i?lt("coords",4,5):lt("coords",1,5)}]; + }`}let O=Fr(p,I),F=$n(r,O,I);return` + ${S} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${T.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${b.getByIndices("aIndices")}; + } + ${k.registerUniforms(w).declareVariables(...E,x)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${x.offsetToIndices("global_idx")}; + let batch = ${lt("coords",0,T.rank)}; + let d2 = ${i?lt("coords",T.rank-1,T.rank):lt("coords",1,T.rank)}; + let xFRCCorner = vec3(${i?lt("coords",1,T.rank):lt("coords",2,T.rank)}, + ${i?lt("coords",2,T.rank):lt("coords",3,T.rank)}, + ${i?lt("coords",3,T.rank):lt("coords",4,T.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${i?lt("uniforms.x_shape",1,T.rank):lt("uniforms.x_shape",2,T.rank)}; + let xShapeZ = ${i?lt("uniforms.x_shape",2,T.rank):lt("uniforms.x_shape",3,T.rank)}; + let xShapeW = ${i?lt("uniforms.x_shape",3,T.rank):lt("uniforms.x_shape",4,T.rank)}; + let xShapeU = ${i?lt("uniforms.x_shape",4,T.rank):lt("uniforms.x_shape",1,T.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${i?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${i?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${i?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${_?"value = value + getBiasByOutputCoords(coords)":""}; + ${F} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${i};${p};${_}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:c[0],y:c[1],z:c[2]},programUniforms:u}),getShaderSource:y}}}),Hy,qy,yT=Ve(()=>{gt(),Ct(),St(),On(),Hy=(e,r,t,s)=>{let n=e.length>2,o=n?"value += b[output_channel];":"",i=e[0].dims,a=e[1].dims,l=r.format==="NHWC",c=l?t[3]:t[1],p=c/r.group,d=l&&p>=4?ur(c):1,u=we.size(t)/d,f=[{type:12,data:u},{type:12,data:r.dilations},{type:12,data:[r.strides[0],r.strides[1]]},{type:12,data:[r.pads[0],r.pads[1]]},{type:12,data:p}];kn(r,f),f.push(...ct(i,[a[0],a[1],a[2],a[3]/d]));let _=n?["rank","rank","rank"]:["rank","rank"];f.push(...ct([t[0],t[1],t[2],t[3]/d]));let y=k=>{let w=it("output",e[0].dataType,t.length,d),v=Ar(w.type.tensor),I=$n(r,w.type.value,v),T=ke("x",e[0].dataType,i.length),b=ke("w",e[1].dataType,a.length,d),E=[T,b];n&&E.push(ke("b",e[2].dataType,e[2].dims,d));let x=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:r.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];An(r,x);let S=l?` + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { + continue; + } + + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + let xVal = ${T.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${b.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { + continue; + } + + let xVal = ${T.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${b.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${k.registerUniforms(x).declareVariables(...E,w)} + + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${w.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${l?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${d} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}]; + + var value: ${w.type.value} = ${w.type.value}(0); + ${S} + ${o} + ${I} + ${w.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${d}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:y}},qy=(e,r,t,s)=>{let n=e.length>2,o=ur(t[3]),i=ur(t[2]),a=we.size(t)/o/i,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/o],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/o],p=[t[0],t[1],t[2],t[3]/o],d=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];kn(r,d),d.push(...ct(l,c,p));let u=(i-1)*r.strides[1]+c[1],f=_=>{let y=it("output",e[0].dataType,p.length,o),k=Ar(y.type.tensor),w=$n(r,y.type.value,k),v=ke("x",e[0].dataType,l.length,o),I=ke("w",e[1].dataType,c.length,o),T=[v,I];n&&T.push(ke("b",e[2].dataType,e[2].dims,o));let b=n?"value += b[output_channel];":"",E=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return An(r,E),` + ${_.registerUniforms(E).declareVariables(...T,y)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${i}u; + let col = (index1 % width1) * ${i}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${v.type.value}, ${u}>; + var values: array<${y.type.value}, ${i}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${c[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${u}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${v.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${v.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) { + let w_val = ${I.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${i}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${i}u; i++) { + var value = values[i]; + ${b} + ${w} + ${y.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${o};${i};${u};${c[0]};${c[1]}`,inputDependencies:n?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:f}}}),kg,ti,Ag,ri,lu,yc,Fg,Og,cu,vT=Ve(()=>{Ct(),wT(),bT(),Du(),yT(),On(),Ou(),cn(),kg=(e,r,t,s,n,o)=>{let i=e[0],a=e.slice(o?1:2,o?3:4),l=a.length,c=r[0],p=r.slice(2).map((u,f)=>u+(u-1)*(t[f]-1)),d=a.map((u,f)=>u+s[f]+s[f+l]).map((u,f)=>Math.floor((u-p[f]+n[f])/n[f]));return d.splice(0,0,i),d.splice(o?3:1,0,c),d},ti=[2,3,1,0],Ag=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[1]*r.group;if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ri=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=ku(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],n=e.dilations,o=e.group,i=e.kernel_shape,a=e.pads,l=e.strides,c=e.w_is_const();return{autoPad:s,format:t,dilations:n,group:o,kernelShape:i,pads:a,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},yc=(e,r,t,s)=>{let n=t.format==="NHWC",o=kg(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,n);if(t.group!==1){let E=[r[0]];if(n){let x=e.kernelCustomData.wT??e.compute(es(r[1],ti),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=x),E.push(x)}else E.push(r[1]);r.length===3&&E.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&n&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(qy(E,t,o,s),{inputs:E}):e.compute(Hy(E,t,o,s),{inputs:E});return}let i=r.length===3,a=r[0].dims[n?1:2],l=r[0].dims[n?2:3],c=r[0].dims[n?3:1],p=r[1].dims[2],d=r[1].dims[3],u=o[n?1:2],f=o[n?2:3],_=o[n?3:1],y=n&&p===a&&d===l&&t.pads[0]===0&&t.pads[1]===0;if(y||p===1&&d===1&&t.dilations[0]===1&&t.dilations[1]===1&&t.strides[0]===1&&t.strides[1]===1&&t.pads[0]===0&&t.pads[1]===0){let E=o[0],x,S,O,F=[];if(n){let B=e.kernelCustomData.wT??e.compute(es(r[1],ti),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=B),y){let Y=a*l*c;x=r[0].reshape([1,E,Y]),S=B.reshape([1,Y,_]),O=[1,E,_]}else x=r[0].reshape([E,a*l,c]),S=B.reshape([1,c,_]),O=[E,u*f,_];F.push(x),F.push(S)}else x=r[0].reshape([E,c,a*l]),S=r[1].reshape([1,_,c]),O=[E,_,u*f],F.push(S),F.push(x);i&&F.push(r[2]);let H=O[2],W=F[0].dims[F[0].dims.length-1];H<8&&W<8?e.compute(Fu(F,t,o,O,n,s),{inputs:F}):e.compute(_i(F,t,o,O,n,s),{inputs:F});return}let k=!0,w=e.kernelCustomData.wT??e.compute(es(r[1],ti),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=w);let v=[r[0],w];i&&v.push(r[2]);let I=n?u*f:_,T=n?_:u*f,b=p*d*c;e.compute(Wy(v,t,o,I,T,b,i,k,s),{inputs:v})},Fg=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let n=[0,r.pads[0],0,r.pads[1]],o=[1].concat(r.strides),i=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=ri({...r,pads:n,strides:o,dilations:i,kernelShape:a},s);yc(e,s,l,c=>t?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},Og=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",n=ri(t,r),o=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=Gy(r[0].dims,r[1].dims,t.strides,t.dilations,o,!1,s);e.compute(Ky(r,n,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},cu=(e,r)=>{if(Ag(e.inputs,r),e.inputs[0].dims.length===3)Fg(e,r);else if(e.inputs[0].dims.length===5)Og(e,e.inputs,r);else{let t=ri(r,e.inputs);yc(e,e.inputs,t)}}}),Qy,xT=Ve(()=>{gt(),Hs(),Ct(),St(),Qy=(e,r,t)=>{let s=e.length>2,n=r.outputShape,o=r.format==="NHWC",i=r.group,a=e[1].dims,l=a[2]/i,c=a[3],p=o?ur(l):1,d=o&&c===1&&l>=4,u=d?Math.floor(l/4)*4:Math.floor(l/p)*p,f=l-u,_=o?ur(c):1,y=o?c===1?p:_:1,k=we.size(n)/_,w=[Math.ceil(k/64),1,1];Dt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${w}`);let v=["rank","rank"],I=[r.strides[0],r.strides[1]],T=[r.kernelShape[o?1:2],r.kernelShape[o?2:3]],b=[r.dilations[0],r.dilations[1]],E=[T[0]+(r.dilations[0]<=1?0:(r.kernelShape[o?1:2]-1)*(r.dilations[0]-1)),T[1]+(r.dilations[1]<=1?0:(r.kernelShape[o?2:3]-1)*(r.dilations[1]-1))],x=[E[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),E[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],S=[{type:12,data:k},{type:12,data:I},{type:12,data:T},{type:12,data:b},{type:12,data:E},{type:6,data:x},{type:12,data:u},{type:12,data:l},{type:12,data:c},...ct(e[0].dims,e[1].dims)];s&&(S.push(...ct(e[2].dims)),v.push("rank")),S.push(...ct(n));let O=F=>{let H=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:I.length},{name:"filter_dims",type:"u32",length:T.length},{name:"dilations",type:"u32",length:T.length},{name:"effective_filter_dims",type:"u32",length:E.length},{name:"pads",type:"i32",length:x.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],W=Ar(e[0].dataType),B=o?1:2,Y=o?2:3,X=o?3:1,J=ke("W",e[1].dataType,e[1].dims.length,y),re=ke("Dy",e[0].dataType,e[0].dims.length,p),ne=[re,J];s&&ne.push(ke("bias",e[2].dataType,[n[X]].length,_));let le=it("result",e[0].dataType,n.length,_),pe=()=>{let N="";if(d)p===4?N+=` + let xValue = ${re.getByOffset("x_offset")}; + let wValue = ${J.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue); + x_offset += 1u; + w_offset += 1u;`:p===2?N+=` + dotProd = dotProd + dot(vec4<${W}>(${re.getByOffset("x_offset")}, ${re.getByOffset("x_offset + 1u")}), vec4<${W}>(${J.getByOffset("w_offset")}, ${J.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;`:p===1&&(N+=` + dotProd = dotProd + dot(vec4<${W}>(${re.getByOffset("x_offset")}, ${re.getByOffset("x_offset + 1u")}, ${re.getByOffset("x_offset + 2u")}, ${re.getByOffset("x_offset + 3u")}), vec4<${W}>(${J.getByOffset("w_offset")}, ${J.getByOffset("w_offset + 1u")}, ${J.getByOffset("w_offset + 2u")}, ${J.getByOffset("w_offset + 3u")})); + x_offset += 4u; + w_offset += 4u;`);else if(N+=` + let xValue = ${o?re.getByOffset(`${re.indicesToOffset(`${re.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):re.get("batch","inputChannel","idyR","idyC")}; + `,p===1)N+=` + let w_offset = ${J.indicesToOffset(`${J.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${J.getByOffset(`w_offset / ${y}`)}; + dotProd = dotProd + xValue * wValue;`;else for(let D=0;D{if(f===0)return"";if(!d)throw new Error(`packInputAs4 ${d} is not true.`);let N="";if(p===1){N+="dotProd = dotProd";for(let D=0;D(i32(r), i32(c)) - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + let groupId = d1 / uniforms.output_channels_per_group; + let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = ${le.type.value}(0.0); + var wR: u32 = 0; + if (uniforms.dilations.x == 1) { + // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 + wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); + } + for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${W}(dyRCorner) + ${W}(wR)) / ${W}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${W}(uniforms.Dy_shape[${B}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + var wC: u32 = 0; + if (uniforms.dilations.y == 1) { + // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 + wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); + } + for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${W}(dyCCorner) + ${W}(wC)) / ${W}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${W}(uniforms.Dy_shape[${Y}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + ${d?` + var x_offset = ${re.indicesToOffset(`${re.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; + var w_offset = ${J.indicesToOffset(`${J.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${y}; + `:""} + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${d?4:p}) { + ${pe()} + inputChannel = inputChannel + ${d?4:p}; + } + ${oe()} + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${s?` + bias[d1 / ${_}]`:""}; + ${le.setByOffset("global_idx","value")}; + `;return` + ${F.registerUniforms(H).declareVariables(...ne,le)} + ${F.mainStart()} + ${F.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${K}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${y}${_}${d}${f}`,inputDependencies:v},getRunData:()=>({dispatchGroup:{x:w[0],y:w[1],z:w[2]},outputs:[{dims:t?t(n):n,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:O}}}),Dg,Lg,zg,vc,Xy,Bg,xc,Rg,Jy,TT=Ve(()=>{xT(),On(),cn(),Dg=(e,r,t,s,n,o)=>(e-1)*r+t+(s-1)*n+1-o,Lg=(e,r,t,s,n)=>{let o=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=o,t[n]=e-o):r==="SAME_LOWER"&&(t[s]=e-o,t[n]=o)},zg=(e,r,t,s,n,o,i,a,l,c)=>{let p=e.length-2,d=c.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((d,u)=>d*u,1)===0){t.length=0;for(let d=2;dd+u,0)===0){let d=r[0].dims.length-2;l=new Array(d).fill(1)}let c=e.strides.slice();if(c.reduce((d,u)=>d+u,0)===0){let d=r[0].dims.length-2;c=new Array(d).fill(1)}zg(a,t,l,e.autoPad,e.group,n,c,s,i,o);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:n,outputPadding:i,outputShape:o,dilations:l,strides:c}),p},Xy=e=>{let r=ku(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],n=e.dilations,o=e.group,i=e.kernelShape,a=e.pads,l=e.strides,c=e.wIsConst(),p=e.outputPadding,d=e.outputShape;return{autoPad:s,format:t,dilations:n,group:o,kernelShape:i,outputPadding:p,outputShape:d,pads:a,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},Bg=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[0];if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==n))throw new Error("invalid bias");let o=e[0].dims.length-2;if(r.dilations.reduce((i,a)=>i+a,0)>0&&r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.reduce((i,a)=>i+a,0)>0&&r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.reduce((i,a)=>i+a,0)>0&&r.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(r.outputPadding.length!==o&&r.outputPadding.length!==0)throw new Error(`output_padding should be ${o}D`);if(r.kernelShape.reduce((i,a)=>i+a,0)>0&&r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(r.outputShape.length!==0&&r.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},xc=(e,r,t,s)=>{let n=e.kernelCustomData.wT??e.compute(es(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=n);let o=[r[0],n];r.length===3&&o.push(r[2]),e.compute(Qy(o,t,s),{inputs:o})},Rg=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let n=r.kernelShape;(n.length===0||n[0]===0)&&(n=[e.inputs[1].dims[2]]);let o=r.dilations;(o.length===0||o[0]===0)&&(o=[1]);let i=r.strides;(i.length===0||i[0]===0)&&(i=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],i=[1].concat(i),o=[1].concat(o),n=[1].concat(n);let l=r.outputPadding;l=[0].concat(l);let c=vc({...r,pads:a,strides:i,dilations:o,kernelShape:n,outputPadding:l},s);xc(e,s,c,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Jy=(e,r)=>{if(Bg(e.inputs,r),e.inputs[0].dims.length===3)Rg(e,r);else{let t=vc(r,e.inputs);xc(e,e.inputs,t)}}}),Ng,Yy,Zy,ET=Ve(()=>{gt(),Ct(),mr(),St(),Ng=(e,r,t,s)=>{let n=we.size(r),o=r.length,i=ke("input",e,o),a=it("output",e,o),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),c=we.normalizeAxis(l,o),p=d=>{let u=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,f=lt("uniforms.input_shape","uniforms.axis",o),_=s.reverse?u+(s.exclusive?" + 1":""):"0",y=s.reverse?f:u+(s.exclusive?"":" + 1");return` + ${d.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,a)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${a.offsetToIndices("global_idx")}; + var sum = ${a.type.value}(0); + let first : i32 = ${_}; + let last : i32 = ${y}; + for (var i : i32 = first; i < last; i++) { + ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${i.getByIndices("inputIndices")}; + } + ${a.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},{type:12,data:c},...ct(r,r)]}),getShaderSource:p}},Yy=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,n=e.inputs[1];e.compute(Ng(s,t,n,r),{inputs:[0]})},Zy=e=>{let r=e.exclusive===1,t=e.reverse===1;return jt({exclusive:r,reverse:t})}}),jg,Vg,Ug,e0,t0,PT=Ve(()=>{gt(),Ct(),mr(),St(),jg=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},Vg=(e,r,t,s)=>{let n=[];n.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`);for(let o=0;o{let t,s,n,o,i,a,l=r.format==="NHWC",c=r.blocksize,p=r.mode==="DCR";l?([t,s,n,o]=e.dims,i=p?[t,s,n,c,c,o/c**2]:[t,s,n,o/c**2,c,c],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,n,o]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=p?[t,c,c,o/c**2,s,n]:[t,o/c**2,c,c,s,n],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(i),u=d.dims.length,f=e.dataType,_=ke("a",f,u),y=it("output",f,u),k=w=>` + ${w.registerUniform("output_size","u32").declareVariables(_,y)} + + ${Vg(a,u,_,y)} + + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${y.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${y.setByOffset("global_idx",_.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:w=>{let v=l?[t,s*c,n*c,o/c**2]:[t,o/c**2,s*c,n*c],I=we.size(v),T=d.dims,b=we.sortBasedOnPerm(T,a);return{outputs:[{dims:v,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil(I/64)},programUniforms:[{type:12,data:I},...ct(T,b)]}},getShaderSource:k}},e0=(e,r)=>{jg(e.inputs),e.compute(Ug(e.inputs[0],r))},t0=e=>jt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),si,jo,Tc,Wg,Gg,Kg,Hg,Ec,qg,r0,s0,CT=Ve(()=>{gt(),Ct(),mr(),St(),si="[a-zA-Z]|\\.\\.\\.",jo="("+si+")+",Tc="^"+jo+"$",Wg="("+jo+",)*"+jo,Gg="^"+Wg+"$",Kg=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,r){let t=this.symbolToIndices.get(e);t===void 0?t=[r]:t.push(r),this.symbolToIndices.set(e,t)}},Hg=class{constructor(e,r){this.equation=r,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,s]=r.includes("->")?r.split("->",2):[r,""];if(!t.match(RegExp(Gg)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,o)=>{let i=e[o].dims.slice();if(!n.match(RegExp(Tc)))throw new Error("Invalid LHS term");let a=this.processTerm(n,!0,i,o);this.lhs.push(a)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,o])=>o.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(jo)))throw new Error("Invalid RHS");s.match(RegExp(si,"g"))?.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(n);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(e,r,t){let s=this.symbolToInfo.get(e);if(s!==void 0){if(s.dimValue!==r&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(t)}else s={count:1,dimValue:r,inputIndices:[t]};this.symbolToInfo.set(e,s)}processTerm(e,r,t,s=-1){let n=t.length,o=!1,i=[],a=0;if(!e.match(RegExp(Tc))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(si,"g")),c=new Kg(s);return l?.forEach((p,d)=>{if(p==="..."){if(o)throw new Error("Only one ellipsis is allowed per input term");o=!0;let u=n-l.length+1;if(u<0)throw new Error("Ellipsis out of bounds");if(i=t.slice(a,a+u),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let f=0;fe+"_max",qg=(e,r,t,s)=>{let n=e.map(c=>c.length).map((c,p)=>ke(`input${p}`,r,c)),o=we.size(s),i=it("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(c=>!t.rhs.symbolToIndices.has(c)),l=c=>{let p=[],d="var prod = 1.0;",u="var sum = 0.0;",f="sum += prod;",_=[],y=[],k=[],w=[],v=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((T,b)=>{if(t.rhs.symbolToIndices.has(b)){let E=t.rhs.symbolToIndices.get(b)?.[0];E!==void 0&&t.lhs.forEach((x,S)=>{if(T.inputIndices.includes(S)){let O=x.symbolToIndices.get(b);if(O===void 0)throw new Error("Invalid symbol error");O.forEach(F=>{p.push(`${n[S].indicesSet(`input${S}Indices`,F,i.indicesGet("outputIndices",E))}`)})}})}else t.lhs.forEach((E,x)=>{if(T.inputIndices.includes(x)){let S=E.symbolToIndices.get(b);if(S===void 0)throw new Error("Invalid symbol error");S.forEach(O=>{_.push(`${n[x].indicesSet(`input${x}Indices`,O,`${b}`)}`)}),w.push(`prod *= ${n[x].getByIndices(`input${x}Indices`)};`)}}),y.push(`for(var ${b}: u32 = 0; ${b} < uniforms.${Ec(b)}; ${b}++) {`),k.push("}")});let I=v?[...p,`let sum = ${n.map((T,b)=>T.getByIndices(`input${b}Indices`)).join(" * ")};`]:[...p,u,...y,..._,d,...w,f,...k];return` + ${c.registerUniforms(a.map(T=>({name:`${Ec(T)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...n,i)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${n.map((T,b)=>`var input${b}Indices: ${n[b].type.indices};`).join(` +`)} + ${I.join(` +`)}; + ${i.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let c=a.filter(d=>t.symbolToInfo.has(d)).map(d=>({type:12,data:t.symbolToInfo.get(d)?.dimValue||0}));c.push({type:12,data:o});let p=e.map((d,u)=>[...ct(d)]).reduce((d,u)=>d.concat(u),c);return p.push(...ct(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}},getShaderSource:l}},r0=(e,r)=>{let t=new Hg(e.inputs,r.equation),s=t.outputDims,n=e.inputs.map((o,i)=>o.dims);e.compute(qg(n,e.inputs[0].dataType,t,s))},s0=e=>{let r=e.equation.replace(/\s+/g,"");return jt({equation:r})}}),Qg,Pc,Xg,Jg,n0,ST=Ve(()=>{gt(),Ct(),St(),Qg=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=t.length{let t=e.length-r.length,s=[];for(let n=0;ne.length>r.length?Pc(e,r):Pc(r,e),Jg=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=Xg(r,t),n=e[0].dataType,o=n===9||we.size(r)===1,i=n===9||r.length>0&&r[r.length-1]%4===0?4:1,a=o||s.length>0&&s[s.length-1]%4===0?4:1,l=Math.ceil(we.size(s)/a),c=d=>{let u=ke("input",n,r.length,i),f=it("output",n,s.length,a),_;if(n===9){let y=(k,w,v="")=>` + let outputIndices${w} = ${f.offsetToIndices(`outputOffset + ${w}u`)}; + let offset${w} = ${u.broadcastedIndicesToOffset(`outputIndices${w}`,f)}; + let index${w} = offset${w} / 4u; + let component${w} = offset${w} % 4u; + ${k}[${w}] = ${v}(${u.getByOffset(`index${w}`)}[component${w}]); + `;_=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${y("data",0,"u32")} + ${y("data",1,"u32")} + ${y("data",2,"u32")} + ${y("data",3,"u32")} + ${f.setByOffset("global_idx","data")} + }`}else _=` + let outputIndices = ${f.offsetToIndices(`global_idx * ${a}`)}; + let inputOffset = ${u.broadcastedIndicesToOffset("outputIndices",f)}; + let data = ${f.type.value}(${u.getByOffset(`inputOffset / ${i}`)}); + ${f.setByOffset("global_idx","data")} + }`;return` + ${d.registerUniform("vec_size","u32").declareVariables(u,f)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${_}`},p=[{type:12,data:l},...ct(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${i}${a}`,inputDependencies:["rank"]},getShaderSource:c,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},n0=e=>{Qg(e.inputs),e.compute(Jg(e.inputs),{inputs:[0]})}}),Yg,o0,IT=Ve(()=>{gt(),Ct(),St(),$u(),Yg=e=>{let r=e[0].dataType,t=we.size(e[0].dims),s=we.size(e[1].dims),n=s%4===0,o=i=>{let a=ke("x",r,[1],4),l=ke("bias",r,[1],4),c=it("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],d=f=>` + let bias${f}_offset: u32 = (global_idx * 4 + ${f}) % uniforms.bias_size; + let bias${f} = ${l.getByOffset(`bias${f}_offset / 4`)}[bias${f}_offset % 4];`,u=n?` + let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${d(0)}${d(1)}${d(2)}${d(3)} + let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(p).declareVariables(a,l,c)} + + ${nu(jr(r))} + + ${i.mainStart(co)} + ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${a.getByOffset("global_idx")}; + ${u} + let x_in = x + bias; + ${c.setByOffset("global_idx",ou("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${n}`,inputDependencies:["type","type"]},getShaderSource:o,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/co/4)}})}},o0=e=>{e.inputs.length<2||we.size(e.inputs[1].dims)===0?Ey(e):e.compute(Yg(e.inputs))}}),Zg,eM,a0,i0,$T=Ve(()=>{gt(),Ct(),mr(),St(),Zg=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},eM=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t.length,o=we.normalizeAxis(r.axis,n),i=t.slice(0);i.splice(o,1,...s);let a=t[o],l=e[0].dataType===9?4:1,c=Math.ceil(we.size(i)/l),p=[{type:12,data:c},{type:6,data:a},{type:12,data:o},...ct(e[0].dims,e[1].dims,i)],d=u=>{let f=ke("data",e[0].dataType,e[0].dims.length,l),_=ke("inputIndices",e[1].dataType,e[1].dims.length),y=it("output",e[0].dataType,i.length,l),k=v=>{let I=s.length,T=`var indicesIndices${v} = ${_.type.indices}(0);`;for(let b=0;b1?`indicesIndices${v}[${b}]`:`indicesIndices${v}`} = ${i.length>1?`outputIndices${v}[uniforms.axis + ${b}]`:`outputIndices${v}`};`;T+=` + var idx${v} = ${_.getByIndices(`indicesIndices${v}`)}; + if (idx${v} < 0) { + idx${v} = idx${v} + uniforms.axisDimLimit; + } + var dataIndices${v} : ${f.type.indices}; + `;for(let b=0,E=0;b1?`dataIndices${v}[${b}]`:`dataIndices${v}`} = u32(idx${v});`,E+=I):(T+=`${n>1?`dataIndices${v}[${b}]`:`dataIndices${v}`} = ${i.length>1?`outputIndices${v}[${E}]`:`outputIndices${v}`};`,E++);return T},w;if(e[0].dataType===9){let v=(I,T,b="")=>` + let outputIndices${T} = ${y.offsetToIndices(`outputOffset + ${T}u`)}; + ${k(T)}; + let offset${T} = ${f.indicesToOffset(`dataIndices${T}`)}; + let index${T} = offset${T} / 4u; + let component${T} = offset${T} % 4u; + ${I}[${T}] = ${b}(${f.getByOffset(`index${T}`)}[component${T}]); + `;w=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${v("value",0,"u32")} + ${v("value",1,"u32")} + ${v("value",2,"u32")} + ${v("value",3,"u32")} + ${y.setByOffset("global_idx","value")} + `}else w=` + let outputIndices = ${y.offsetToIndices("global_idx")}; + ${k("")}; + let value = ${f.getByIndices("dataIndices")}; + ${y.setByOffset("global_idx","value")}; + `;return` + ${u.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(f,_,y)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${w} + }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:d}},a0=e=>jt({axis:e.axis}),i0=(e,r)=>{let t=e.inputs;Zg(t),e.compute(eM(e.inputs,r))}}),tM,l0,c0,kT=Ve(()=>{gt(),Ct(),St(),tM=(e,r,t,s,n,o,i,a,l)=>{let c=[{type:12,data:o},{type:12,data:s},{type:12,data:n},{type:12,data:t},{type:12,data:i},{type:12,data:a},{type:12,data:l}],p=[o];c.push(...ct(r.dims,p));let d=u=>{let f=ke("indices_data",r.dataType,r.dims.length),_=it("input_slice_offsets_data",12,1,1),y=[f,_],k=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:n.length},{name:"sizes_from_slice_dims_data",type:"u32",length:t.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${u.registerUniforms(k).declareVariables(...y)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${n.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${t.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${n.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:c}),getShaderSource:d},{inputs:[r],outputs:[-1]})[0]},l0=(e,r)=>{let t=e.inputs,s=t[0].dims,n=t[0].dataType,o=t[1].dims,i=o[o.length-1],a=we.sizeToDimension(o,o.length-1),l=we.sizeFromDimension(s,r.batchDims+i),c=we.sizeToDimension(s,r.batchDims),p=we.sizeFromDimension(s,r.batchDims),d=a/c,u=new Array(i),f=l;for(let T=0;Ts.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let k=o.slice(0,-1).concat(s.slice(y)),w=we.size(k),v=[{type:12,data:w},{type:12,data:l},...ct(t[0].dims,_.dims,k)],I=T=>{let b=ke("data",t[0].dataType,t[0].dims.length),E=ke("slice_offsets",12,_.dims.length),x=it("output",t[0].dataType,k.length);return` + ${T.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(b,E,x)} + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; + output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; + }`};e.compute({name:"GatherND",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:k,dataType:n}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:v}),getShaderSource:I},{inputs:[t[0],_]})},c0=e=>({batchDims:e.batch_dims,cacheKey:""})}),rM,sM,u0,d0,AT=Ve(()=>{gt(),Ct(),mr(),St(),rM=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=we.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,n=e[0],o=e[2],i=e.length===4?e[3]:void 0;if(o.dims.length!==n.dims.length||!n.dims.map((a,l)=>l===t?Math.ceil(a/s)===o.dims[l]:a===o.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==n.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==o.dims.length||!i.dims.map((a,l)=>a===o.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},sM=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t.length,o=we.normalizeAxis(r.gatherAxis,n),i=we.normalizeAxis(r.quantizeAxis,n),a=t.slice(0);a.splice(o,1,...s);let l=we.size(a),c=e[2].dataType,p=e[0].dataType===22,d=[{type:12,data:l},{type:12,data:i},{type:12,data:o},{type:12,data:r.blockSize},...ct(...e.map((f,_)=>f.dims),a)],u=f=>{let _=ke("data",e[0].dataType,e[0].dims.length),y=ke("inputIndices",e[1].dataType,e[1].dims.length),k=ke("scales",e[2].dataType,e[2].dims.length),w=e.length>3?ke("zeroPoint",e[3].dataType,e[3].dims.length):void 0,v=it("output",c,a.length),I=[_,y,k];w&&I.push(w);let T=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${f.registerUniforms(T).declareVariables(...I,v)} + ${f.mainStart()} + let output_indices = ${v.offsetToIndices("global_idx")}; + var indices_indices = ${y.type.indices}(0); + ${s.length>1?` + for (var i: u32 = 0; i < ${s.length}; i++) { + let index = ${v.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${y.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${v.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${_.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${v.indicesGet("output_indices","i")}; + ${_.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${y.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${t[o]}; + } + ${_.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${a.length}; i++) { + let index = ${v.indicesGet("output_indices",`i + ${s.length} - 1`)}; + ${_.indicesSet("data_indices","i","index")}; + } + let data_offset = ${_.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${_.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); + let quantized_data = quantized_data_vec[data_index / 2]; + var scale_indices = data_indices; + let quantize_axis_index = ${k.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${k.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${k.getByIndices("scale_indices")}; + ${w?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${w.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${w.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${jr(c)}(quantized_data - zero_point) * scale; + ${v.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((f,_)=>_!==1).map(f=>f.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(f,_)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:c}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:u}},u0=(e,r)=>{let t=e.inputs;rM(t,r),e.compute(sM(e.inputs,r))},d0=e=>jt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),nM,oM,p0,m0,FT=Ve(()=>{gt(),Ct(),mr(),St(),nM=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`)},oM=(e,r)=>{let t=e[0].dims,s=e[0].dataType,n=t.length,o=e[1].dims,i=e[1].dataType,a=we.normalizeAxis(r.axis,n),l=t[a],c=o.slice(0),p=we.size(c),d=ke("input",s,n),u=ke("indicesInput",i,o.length),f=it("output",s,c.length),_=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return _.push(...ct(t,o,c)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:_}),getShaderSource:y=>` + ${y.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,u,f)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${f.offsetToIndices("global_idx")}; + + var idx = ${u.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${d.type.indices}(outputIndices); + ${d.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${d.getByIndices("inputIndices")}; + + ${f.setByOffset("global_idx","value")}; + }`}},p0=e=>jt({axis:e.axis}),m0=(e,r)=>{let t=e.inputs;nM(t),e.compute(oM(e.inputs,r))}}),aM,iM,h0,_0,OT=Ve(()=>{gt(),Ct(),St(),aM=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},iM=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[n,o,i]=pb.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[n,o];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,c=Math.ceil(o/l),p=Math.ceil(n/l),d=!0,u=we.size(a),f=[{type:12,data:d?c:u},{type:12,data:n},{type:12,data:o},{type:12,data:i},{type:1,data:r.alpha},{type:1,data:r.beta}],_=["type","type"];e.length===3&&(f.push(...ct(e[2].dims)),_.push("rank")),f.push(...ct(a));let y=w=>{let v="";r.transA&&r.transB?v="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?v="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?v="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(v="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let I=r.alpha===1?"":"value *= uniforms.alpha;",T=ke("a",e[0].dataType,e[0].dims),b=ke("b",e[1].dataType,e[1].dims),E=T.type.value,x=null,S=[T,b];e.length===3&&(x=ke("c",e[2].dataType,e[2].dims.length),S.push(x));let O=it("output",e[0].dataType,a.length);S.push(O);let F=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` + ${w.registerUniforms(F).declareVariables(...S)} + + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${E}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${v} + } + + ${I} + ${x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",O)}; value += ${E}(uniforms.beta) * ${x.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},k=w=>{let v=ke("a",e[0].dataType,e[0].dims),I=ke("b",e[1].dataType,e[1].dims),T=null,b=[v,I];e.length===3&&(T=ke("c",e[2].dataType,e[2].dims.length),b.push(T));let E=it("output",e[0].dataType,a.length);b.push(E);let x=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],S="",O="";r.transA&&r.transB?(O=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${v.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${I.type.value}(0); + } + `,S="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(O=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${v.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${I.type.value}(0); + } + `,S="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(O=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${v.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${I.type.value}(0); + } + `,S="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(O=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${v.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${I.type.value}(0); + } + `,S="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let F=r.alpha===1?"":"value *= uniforms.alpha;";return` + ${w.registerUniforms(x).declareVariables(...b)} + var tile_a: array, ${l}>; + var tile_b: array, ${l}>; + ${w.mainStart([l,l,1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${l}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${l}; + let num_tiles = (uniforms.K - 1) / ${l} + 1; + var k_start = 0u; + var value = ${E.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${O} + k_start = k_start + ${l}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${l}; k++) { + ${S} + } + workgroupBarrier(); + } + + ${F} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${T!=null?`let cOffset = ${T.broadcastedIndicesToOffset("vec2(m, n)",E)}; value += ${E.type.value}(uniforms.beta) * ${T.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return d?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:c*p},programUniforms:f}),getShaderSource:k}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:y}},h0=e=>{let r=e.transA,t=e.transB,s=e.alpha,n=e.beta;return{transA:r,transB:t,alpha:s,beta:n,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},_0=(e,r)=>{aM(e.inputs),e.compute(iM(e.inputs,r))}}),zs,Ws,vn,xn,lM,cM,uM,dM,pM,mM,hM,_M,f0,g0,DT=Ve(()=>{gt(),Ct(),mr(),St(),[zs,Ws,vn,xn]=[0,1,2,3],lM=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},cM=` + fn gs_get_cubic_coeffs(x: f32) -> vec4 { + let cubic_alpha = -0.75f; + let x_abs = abs(x); + var coeffs: vec4; + coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); + coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); + coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); + coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); + return coeffs; + } +`,uM=e=>` + fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { + var v: vec4; + var coeffs = gs_get_cubic_coeffs(x); + for (var i = 0; i < 4; i++) { + v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; + } + coeffs = gs_get_cubic_coeffs(y); + let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); + return pixel; + } +`,dM=e=>` + fn gs_denormalize(n: f32, length: i32) -> f32 { + ${e.alignCorners===0?` + // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] + return ((n + 1.0) * f32(length) - 1.0) / 2.0; + `:` + // alignCorners: true => [-1, 1] to [0, length - 1] + return (n + 1.0) / 2.0 * (f32(length - 1)); + `} + } +`,pM=e=>` + ${e.paddingMode==="reflection"?` + fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { + var dx = 0.0; + var fx = f32(x); + let range = x_max - x_min; + if (fx < x_min) { + dx = x_min - fx; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_min + r; + } else { + fx = x_max - r; + } + } else if (fx > x_max) { + dx = fx - x_max; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_max - r; + } else { + fx = x_min + r; + } + } + return u32(fx); + }`:""} +`,mM=(e,r,t)=>` + fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${r} { + var pixel = ${r}(0); + var indices = vec4(0); + indices[${zs}] = batch; + indices[${Ws}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${vn}] = u32(r); + indices[${xn}] = u32(c); + } else { + return ${r}(0); + } + `;case"border":return` + indices[${vn}] = u32(clamp(r, 0, H - 1)); + indices[${xn}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${vn}] = gs_reflect(r, border[1], border[3]); + indices[${xn}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,hM=(e,r,t)=>(()=>{switch(t.mode){case"nearest":return` + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${zs}], indices[${Ws}], border); + `;case"bilinear":return` + let x1 = i32(floor(x)); + let y1 = i32(floor(y)); + let x2 = x1 + 1; + let y2 = y1 + 1; + + let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${zs}], indices[${Ws}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${zs}], indices[${Ws}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${zs}], indices[${Ws}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${zs}], indices[${Ws}], border); + + let dx2 = ${r}(f32(x2) - x); + let dx1 = ${r}(x - f32(x1)); + let dy2 = ${r}(f32(y2) - y); + let dy1 = ${r}(y - f32(y1)); + let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); + `;case"bicubic":return` + let x0 = i32(floor(x)) - 1; + let y0 = i32(floor(y)) - 1; + var p: mat4x4<${r}>; + for (var h = 0; h < 4; h++) { + for (var w = 0; w < 4; w++) { + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${zs}], indices[${Ws}], border); + } + } + + let dx = x - f32(x0 + 1); + let dy = y - f32(y0 + 1); + let result = gs_bicubic_interpolate(p, dx, dy); + `;default:throw new Error(`mode ${t.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,_M=(e,r)=>{let t=ke("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],n=ke("grid",e[1].dataType,s.length,2),o=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];r.format==="NHWC"&&(o=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[zs,Ws,vn,xn]=[0,3,1,2]);let i=it("output",e[0].dataType,o.length),a=t.type.value,l=we.size(o),c=[{type:12,data:l},...ct(e[0].dims,s,o)],p=d=>` + ${d.registerUniform("output_size","u32").declareVariables(t,n,i)} + ${cM} + ${uM(a)} + ${dM(r)} + ${pM(r)} + ${mM(t,a,r)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${vn}]); + let W_in = i32(uniforms.x_shape[${xn}]); + + ${r.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${i.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${zs}], indices[${vn}], indices[${xn}]); + let nxy = ${n.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${hM(i,a,r)} + }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:d=>{let u=we.size(o);return{outputs:[{dims:o,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}},getShaderSource:p}},f0=(e,r)=>{lM(e.inputs),e.compute(_M(e.inputs,r))},g0=e=>jt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Gr,fM,M0,Cc,gM,Qo,w0,b0=Ve(()=>{gt(),Ct(),mr(),Pu(),Iu(),St(),cn(),Gr=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,fM=(e,r)=>{let t=e[0],s=Gr(e,1),n=Gr(e,2),o=Gr(e,3),i=Gr(e,4),a=Gr(e,5),l=Gr(e,6),c=Gr(e,7);if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let p=t.dims[0],d=t.dims[1],u=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],f=d,_=0,y=0,k=Math.floor(u/r.numHeads);if(l&&c&&we.size(l.dims)&&we.size(c.dims)){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==p||l.dims[1]!==r.numHeads||l.dims[3]!==k)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==p||c.dims[1]!==r.numHeads||c.dims[3]!==k)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');_=l.dims[2],y=l.dims[2]}else if(l&&we.size(l.dims)||c&&we.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(s&&we.size(s.dims)>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(s.dims[2]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');w=2,f=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==k)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(n)throw new Error('Expect "value" be none when "key" has packed kv format.');w=5,f=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==k)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');w=0,f=s.dims[2]}}else{if(t.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(t.dims[2]!==r.numHeads||t.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}if(o&&we.size(o.dims)>0){if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let v=_+f,I=0;if(i&&we.size(i.dims)>0){I=8;let x=i.dims;throw x.length===1?x[0]===p?I=1:x[0]===3*p+2&&(I=3):x.length===2&&x[0]===p&&x[1]===v&&(I=5),I===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let T=!1,b=u;if(n&&we.size(n.dims)>0){if(n.dims.length!==3&&n.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==n.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(n.dims.length===3){if(f!==n.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');b=n.dims[2]}else{if(f!==n.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');b=n.dims[1]*n.dims[3],T=!0}}let E=!1;if(i&&we.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(a&&we.size(a.dims)>0){if(a.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(a.dims[0]!==p||a.dims[1]!==r.numHeads||a.dims[2]!==d||a.dims[3]!==v)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:d,pastSequenceLength:_,kvSequenceLength:f,totalSequenceLength:v,maxSequenceLength:y,inputHiddenSize:0,hiddenSize:u,vHiddenSize:b,headSize:k,vHeadSize:Math.floor(b/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:I,scale:r.scale,broadcastResPosBias:E,passPastInKv:T,qkvFormat:w}},M0=e=>jt({...e}),Cc=jt({perm:[0,2,1,3]}),gM=(e,r,t,s,n,o,i)=>{let a=[s,n,o],l=we.size(a),c=[{type:12,data:l},{type:12,data:i},{type:12,data:o}],p=d=>{let u=it("qkv_with_bias",r.dataType,a),f=ke("qkv",r.dataType,a),_=ke("bias",t.dataType,a),y=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${d.registerUniforms(y).declareVariables(f,_,u)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; + + qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; + }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},Qo=(e,r,t,s,n,o,i,a)=>{let l=o;if(i&&we.size(i.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=gM(e,o,i,r,s,t*n,a),l=l.reshape([r,s,t,n]),t===1||s===1?l:e.compute(es(l,Cc.perm),{inputs:[l],outputs:[-1]})[0]}else return o.dims.length===3&&(l=o.reshape([r,s,t,n])),t===1||s===1?l:e.compute(es(l,Cc.perm),{inputs:[l],outputs:[-1]})[0]},w0=(e,r)=>{let t=fM(e.inputs,r),s=e.inputs[0],n=Gr(e.inputs,1),o=Gr(e.inputs,2),i=Gr(e.inputs,3),a=Gr(e.inputs,4),l=Gr(e.inputs,5),c=Gr(e.inputs,6),p=Gr(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if(n?.dims.length===5)throw new Error("Packed KV is not implemented");let d=n&&o&&n.dims.length===4&&o.dims.length===4,u=Qo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(d)return Zo(e,u,n,o,a,void 0,c,p,l,t);if(!n||!o)throw new Error("key and value must be provided");let f=Qo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,n,i,t.hiddenSize),_=Qo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,o,i,2*t.hiddenSize);Zo(e,u,f,_,a,void 0,c,p,l,t)}}),MM,wM,bM,yM,uu,y0,v0,x0=Ve(()=>{gt(),Ct(),mr(),St(),MM=e=>{if(!e||e.length<1)throw new Error("too few inputs")},wM=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(n=>t.push(Number(n))),s=t.length),jt({numOutputs:s,axis:r.axis,splitSizes:t})},bM=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${lt("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,yM=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=we.size(t),n=e[0].dataType,o=we.normalizeAxis(r.axis,t.length),i=new Array(r.numOutputs),a=ke("input",n,t.length),l=new Array(r.numOutputs),c=[],p=[],d=0,u=[{type:12,data:s}];for(let _=0;_` + ${_.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...i)} + ${bM(l.length)} + ${yM(i)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${a.offsetToIndices("global_idx")}; + var index = ${a.indicesGet("indices",o)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${lt("uniforms.size_in_split_axis","output_number - 1u",l.length)}; + ${a.indicesSet("indices",o,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:f,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:u})}},y0=(e,r)=>{MM(e.inputs);let t=e.inputs.length===1?r:wM(e.inputs,r);e.compute(uu(e.inputs,t),{inputs:[0]})},v0=e=>{let r=e.axis,t=e.splitSizes,s=e.numOutputs<0?t.length:e.numOutputs;if(s!==t.length)throw new Error("numOutputs and splitSizes lengh must be equal");return jt({axis:r,numOutputs:s,splitSizes:t})}}),vM,fi,T0,E0=Ve(()=>{gt(),Ct(),mr(),St(),vM=(e,r)=>{let[t,s,n,o]=e,{numHeads:i,rotaryEmbeddingDim:a}=r;if(t.dims.length!==3&&t.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${t.dims.length}`);if(!we.areEqual(s.dims,[])&&!we.areEqual(s.dims,[1])&&s.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${s.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(!we.areEqual(n.dims,o.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],c=t.dims[t.dims.length-2],p=n.dims[0],d=we.sizeFromDimension(t.dims,1)/c,u=a===0?n.dims[1]*2:d/i;if(a>u)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(l!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(c!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(u/2!==n.dims[1]&&a/2!==n.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${n.dims[1]}`);if(c>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},fi=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:n,scale:o}=r,i=e[0].dims[0],a=we.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],c=a/l,p=e[2].dims[1],d=n===0?p*2:c/s,u=new Array(i,l,c/d,d-p),f=we.computeStrides(u),_=[{type:1,data:o},{type:12,data:u},{type:12,data:f},...e[0].dims.length===3?new Array({type:12,data:[a,c,d,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,d,l*d,1]}):[],...ct(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],y=k=>{let w=ke("input",e[0].dataType,e[0].dims.length),v=ke("position_ids",e[1].dataType,e[1].dims.length),I=ke("cos_cache",e[2].dataType,e[2].dims.length),T=ke("sin_cache",e[3].dataType,e[3].dims.length),b=it("output",e[0].dataType,e[0].dims.length);return k.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:f.length},{name:"input_output_strides",type:"u32",length:f.length}]),` + ${k.declareVariables(w,v,I,T,b)} + + ${k.mainStart(co)} + let half_rotary_emb_dim = uniforms.${I.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${k.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${v.broadcastedIndicesToOffset("bsnh.xy",it("",v.type.tensor,2))}; + let position_id = + u32(${v.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${t}); + let j = i + select(half_rotary_emb_dim, 1, ${t}); + let re = ${w.getByOffset("i")} * ${I.get("position_id","bsnh[3]")} - + ${w.getByOffset("j")} * ${T.get("position_id","bsnh[3]")}; + ${b.setByOffset("i","re")} + let im = ${w.getByOffset("i")} * ${T.get("position_id","bsnh[3]")} + + ${w.getByOffset("j")} * ${I.get("position_id","bsnh[3]")}; + ${b.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${b.setByOffset("k",w.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:jt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(we.size(u)/co)},programUniforms:_})}},T0=(e,r)=>{vM(e.inputs,r),e.compute(fi(e.inputs,r))}}),xM,TM,Sc,EM,P0,LT=Ve(()=>{mr(),gt(),Iu(),b0(),x0(),cn(),E0(),St(),xM=(e,r)=>{if(r.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let t=e[0],s=e[1],n=e[2],o=e[3],i=e[4];if(r.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(r.localWindowSize!==-1)throw new Error("Local attention is not supported");if(r.softcap!==0)throw new Error("Softcap is not supported");if(r.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(r.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let a=!1,l=t.dims[0],c=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],d=c,u=0,f=!s||s.dims.length===0,_=Math.floor(f?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);f&&(p=_*r.numHeads);let y=o&&o.dims.length!==0,k=i&&i.dims.length!==0;if(y&&o.dims.length===4&&o.dims[0]===l&&o.dims[1]!==r.kvNumHeads&&o.dims[2]===r.kvNumHeads&&o.dims[3]===_)throw new Error("BSNH pastKey/pastValue is not supported");if(y&&k){if(o.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');u=o.dims[2]}else if(y||k)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w=1;if(s&&s.dims.length>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(t.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');d=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(n)throw new Error('Expect "value" be none when "key" has packed kv format.');d=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=s.dims[2]}}else{if(t.dims.length!==3&&t.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(t.dims.length===5&&(t.dims[2]!==r.numHeads||t.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}let v=0,I=!1,T=r.kvNumHeads?_*r.kvNumHeads:p;if(n&&n.dims.length>0){if(n.dims.length!==3&&n.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==n.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(n.dims.length===3){if(d!==n.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');T=n.dims[2]}else{if(d!==n.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');T=n.dims[1]*n.dims[3],I=!0}}let b=e.length>4?e[5]:void 0;if(b&&b.dims.length!==1&&b.dims[0]!==l)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:l,sequenceLength:c,pastSequenceLength:u,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:T,headSize:_,vHeadSize:Math.floor(T/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:v,scale:r.scale,broadcastResPosBias:!1,passPastInKv:I,qkvFormat:w}},TM=jt({perm:[0,2,1,3]}),Sc=(e,r,t)=>{let s=r,n=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,n,t.headSize]),s=e.compute(es(s,TM.perm),{inputs:[s],outputs:[-1]})[0]),s},EM=(e,r,t,s)=>{let n=7,o=["type","type"],i=[e*r],a=e*r,l=[{type:12,data:a},{type:12,data:r},{type:12,data:e}],c=p=>{let d=ke("seq_lens",t.dataType,t.dims),u=ke("total_seq_lens",s.dataType,s.dims),f=it("pos_ids",n,i),_=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` + ${p.registerUniforms(_).declareVariables(d,u,f)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let total_sequence_length = u32(${u.getByOffset("0")}); + let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length; + let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length; + let batch_idx = global_idx / uniforms.sequence_length; + let sequence_idx = i32(global_idx % uniforms.sequence_length); + var pos_id: i32 = 0; + let seqlen = ${d.getByOffset("batch_idx")}; + let total_seqlen = seqlen + 1; + if (is_first_prompt) { + if (sequence_idx < total_seqlen) { + pos_id = sequence_idx; + } else { + pos_id = 1; + } + ${f.setByOffset("global_idx","pos_id")} + } else if (is_subsequent_prompt) { + let past_seqlen = total_seqlen - i32(uniforms.sequence_length); + if (past_seqlen + sequence_idx < total_seqlen) { + pos_id = past_seqlen + sequence_idx; + } else { + pos_id = 1; + } + ${f.setByOffset("global_idx","pos_id")} + } else if (global_idx < uniforms.batch_size) { + ${f.setByOffset("global_idx","seqlen")} + }; + } + `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${r}`,inputDependencies:o},getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:c}},P0=(e,r)=>{let t=xM(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],n=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,o=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,i=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,c=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,d=jt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[u,f,_]=!n&&!o?e.compute(uu([s],d),{inputs:[s],outputs:[-1,-1,-1]}):[s,n,o],y,k;if(r.doRotary){let T=e.compute(EM(t.batchSize,t.sequenceLength,l,c),{inputs:[l,c],outputs:[-1]})[0],b=e.inputs[7],E=e.inputs[8],x=jt({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),S=[u,T,b,E],O=[-1];y=e.compute(fi(S,x),{inputs:S,outputs:O})[0],S.splice(0,1,f);let F=jt({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});k=e.compute(fi(S,F),{inputs:S,outputs:O})[0]}let w=Qo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?y:u,void 0,0),v=Sc(e,r.doRotary?k:f,t),I=Sc(e,_,t);Zo(e,w,v,I,void 0,void 0,i,a,void 0,t,l,c)}}),Ic,PM,CM,C0,zT=Ve(()=>{gt(),Ct(),cn(),St(),Ic=(e,r,t,s,n,o,i,a)=>{let l=ur(o),c=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,d=n*i,u=64;d===1&&(u=256);let f=[n,i,o/l],_=[n,i,2],y=["rank","type","type"],k=[];k.push(...ct(f,_));let w=v=>{let I=ke("x",r.dataType,3,l),T=ke("scale",t.dataType,t.dims),b=ke("bias",s.dataType,s.dims),E=it("output",1,3,2),x=[I,T,b,E];return` + var workgroup_shared : array<${p}, ${u}>; + const workgroup_size = ${u}u; + ${v.declareVariables(...x)} + ${v.mainStart(u)} + let batch = workgroup_index / uniforms.x_shape[1]; + let channel = workgroup_index % uniforms.x_shape[1]; + let hight = uniforms.x_shape[2]; + // initialize workgroup memory + var sum = ${c}(0); + var squared_sum = ${c}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${c}(${I.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${p}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${ln("workgroup_shared[0][0]",l)} / f32(hight * ${l}); + let squared_sum_final = ${ln("workgroup_shared[0][1]",l)} / f32(hight * ${l}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${a})); + let channel_scale = inv_std_dev * f32(scale[channel]); + let channel_shift = f32(bias[channel]) - sum_final * channel_scale; + output[workgroup_index] = vec2f(channel_scale, channel_shift); + } + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${a};${u}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:_,dataType:1}],dispatchGroup:{x:d},programUniforms:k}),getShaderSource:w},{inputs:[r,t,s],outputs:[-1]})[0]},PM=(e,r,t)=>{let s=r[0].dims,n=s,o=2,i=s[0],a=s[1],l=we.sizeFromDimension(s,o),c=ur(l),p=we.size(n)/c,d=Ic(e,r[0],r[1],r[2],i,l,a,t.epsilon),u=[i,a,l/c],f=[i,a],_=["type","none"],y=k=>{let w=ke("x",r[0].dataType,u.length,c),v=ke("scale_shift",1,f.length,2),I=it("output",r[0].dataType,u.length,c),T=[w,v,I];return` + ${k.registerUniform("output_size","u32").declareVariables(...T)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${I.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${v.getByIndices("vec2(batch, channel)")}; + let value = ${w.getByOffset("global_idx")} * ${I.type.value}(scale_shift.x) + ${I.type.value}(scale_shift.y); + ${I.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${c}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:n,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...ct(u,f,u)]}),getShaderSource:y},{inputs:[r[0],d]})},CM=(e,r,t)=>{let s=r[0].dims,n=s,o=s[0],i=s[s.length-1],a=we.sizeFromDimension(s,1)/i,l=ur(i),c=we.size(n)/l,p=[{type:12,data:a},{type:12,data:Math.floor(i/l)}],d=["type","type"],u=!1,f=[0,s.length-1];for(let w=0;ws[f[v]])),y=Ic(e,_,r[1],r[2],o,a,i,t.epsilon),k=w=>{let v=Ar(r[0].dataType),I=l===1?"vec2f":`mat${l}x2f`,T=x=>{let S=x===0?"x":"y",O=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${v}(${O}(scale.${S}))`;case 2:return`vec2<${v}>(${O}(scale[0].${S}, scale[1].${S}))`;case 4:return`vec4<${v}>(${O}(scale[0].${S}, scale[1].${S}, scale[2].${S}, scale[3].${S}))`;default:throw new Error(`Not supported compoents ${l}`)}},b=ke("input",r[0].dataType,r[0].dims,l),E=it("output",r[0].dataType,n,l);return` + @group(0) @binding(0) var input : array<${b.type.storage}>; + @group(0) @binding(1) var scale_input : array<${I}>; + @group(0) @binding(2) var output : array<${E.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${w.mainStart()} + let current_image_number = global_idx / (uniforms.C * uniforms.H); + let current_channel_number = global_idx % uniforms.C; + + let scale_offset = current_image_number * uniforms.C + current_channel_number; + let scale = scale_input[scale_offset]; + output[global_idx] = fma(input[global_idx], ${T(0)}, ${T(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:n,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:k},{inputs:[r[0],y]})},C0=(e,r)=>{r.format==="NHWC"?CM(e,e.inputs,r):PM(e,e.inputs,r)}}),SM,IM,S0,BT=Ve(()=>{gt(),Ct(),St(),SM=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},IM=(e,r,t)=>{let s=r.simplified,n=e[0].dims,o=e[1],i=!s&&e[2],a=n,l=we.normalizeAxis(r.axis,n.length),c=we.sizeToDimension(n,l),p=we.sizeFromDimension(n,l),d=we.size(o.dims),u=i?we.size(i.dims):0;if(d!==p||i&&u!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. + Size of scale and bias (if provided) must match this. + Got scale size of ${d} and bias size of ${u}`);let f=[];for(let b=0;b1,v=t>2,I=b=>{let E=Ar(e[0].dataType),x=[ke("x",e[0].dataType,e[0].dims,_),ke("scale",o.dataType,o.dims,_)];i&&x.push(ke("bias",i.dataType,i.dims,_)),x.push(it("output",e[0].dataType,a,_)),w&&x.push(it("mean_data_output",1,f)),v&&x.push(it("inv_std_output",1,f));let S=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${b.registerUniforms(S).declareVariables(...x)} + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${tu("f32",_)}; + var mean_square_vector = ${tu("f32",_)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${io(E,_,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${ln("mean_vector",_)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${ln("mean_square_vector",_)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${io(E,_,"x[j + offset]")}; + let f32scale = ${io(E,_,"scale[j]")}; + output[j + offset] = ${x[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${io(E,_,"bias[j]")}`:""} + ); + } + + ${w?"mean_data_output[global_idx] = mean":""}; + ${v?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},T=[{dims:a,dataType:e[0].dataType}];return w&&T.push({dims:f,dataType:1}),v&&T.push({dims:f,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${t};${s}`,inputDependencies:y},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:k}),getShaderSource:I}},S0=(e,r)=>{SM(e.inputs),e.compute(IM(e.inputs,r,e.outputCount))}}),$M,I0,RT=Ve(()=>{Ct(),Ou(),Du(),$M=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},I0=e=>{$M(e.inputs);let r=lo.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!r)throw new Error("Can't use matmul on the given tensors");let t=r[r.length-1],s=e.inputs[0].dims[e.inputs[0].dims.length-1];if(t<8&&s<8)e.compute(Fu(e.inputs,{activation:""},r));else{let n=r[r.length-2],o=we.size(e.inputs[0].dims.slice(0,-2)),i=we.size(e.inputs[1].dims.slice(0,-2));if(o!==1&&n===1&&i===1){let a=e.inputs[0].reshape([1,o,s]),l=e.inputs[1].reshape([1,s,t]),c=[1,o,t],p=[a,l];e.compute(_i(p,{activation:""},r,c),{inputs:p})}else e.compute(_i(e.inputs,{activation:""},r))}}}),kM,AM,FM,$0,k0,NT=Ve(()=>{gt(),Ct(),mr(),St(),kM=(e,r)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=e[0],s=t.dims.length;if(t.dims[s-1]!==r.k)throw new Error("The last dim of input shape does not match the k value");let n=Math.floor((r.k+r.blockSize-1)/r.blockSize),o=r.blockSize/8*r.bits,i=e[1];if(!we.areEqual(i.dims,[r.n,n,o]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(we.size(a)!==r.n*n)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,c=r.bits>4?r.n*n:r.n*Math.floor((n+1)/2);if(we.size(l)!==c)throw new Error("zeroPoints input size error.")}},AM=(e,r)=>{let t=e[0].dims,s=t.length,n=t[s-2],o=r.k,i=r.n,a=t.slice(0,s-2),l=we.size(a),c=e[1].dims[2]/4,p=e[0].dataType,d=ur(r.k),u=ur(c),f=ur(i),_=a.concat([n,i]),y=n>1&&i/f%2===0?2:1,k=we.size(_)/f/y,w=64,v=[],I=[l,n,o/d],T=we.convertShape(e[1].dims).slice();T.splice(-1,1,c/u),v.push(...ct(I)),v.push(...ct(T)),v.push(...ct(e[2].dims)),e.length===4&&v.push(...ct(we.convertShape(e[3].dims)));let b=[l,n,i/f];v.push(...ct(b));let E=x=>{let S=I.length,O=ke("a",e[0].dataType,S,d),F=ke("b",12,T.length,u),H=ke("scales",e[2].dataType,e[2].dims.length),W=[O,F,H],B=e.length===4?ke("zero_points",12,e[3].dims.length):void 0;B&&W.push(B);let Y=b.length,X=it("output",e[0].dataType,Y,f),J=Ar(e[0].dataType),re=(()=>{switch(d){case 1:return`array<${J}, 8>`;case 2:return`mat4x2<${J}>`;case 4:return`mat2x4<${J}>`;default:throw new Error(`${d}-component is not supported.`)}})(),ne=()=>{let oe=` + // reuse a data + var input_offset = ${O.indicesToOffset(`${O.type.indices}(batch, row, word_offset)`)}; + var a_data: ${re}; + for (var j: u32 = 0; j < ${8/d}; j++) { + a_data[j] = ${O.getByOffset("input_offset")}; + input_offset++; + } + `;for(let K=0;K> 4) & b_mask); + b_quantized_values = ${re}(${Array.from({length:4},(N,D)=>`${J}(b_value_lower[${D}]), ${J}(b_value_upper[${D}])`).join(", ")}); + b_dequantized_values = ${d===1?`${re}(${Array.from({length:8},(N,D)=>`(b_quantized_values[${D}] - ${B?`zero_point${K}`:"zero_point"}) * scale${K}`).join(", ")});`:`(b_quantized_values - ${re}(${Array(8).fill(`${B?`zero_point${K}`:"zero_point"}`).join(",")})) * scale${K};`}; + workgroup_shared[local_id.x * ${y} + ${Math.floor(K/f)}]${f>1?`[${K%f}]`:""} += ${Array.from({length:8/d},(N,D)=>`${d===1?`a_data[${D}] * b_dequantized_values[${D}]`:`dot(a_data[${D}], b_dequantized_values[${D}])`}`).join(" + ")}; + `;return oe},le=()=>{let oe=` + var col_index = col * ${f}; + ${B?` + let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; + var zero_point_byte_count: u32; + var zero_point_word_index: u32; + var zero_point_byte_offset: u32; + let zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32; + var zero_point_word: u32;`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${J}(8);`} + `;for(let K=0;K> 0x1u); + zero_point_word_index = zero_point_byte_count >> 0x2u; + zero_point_byte_offset = zero_point_byte_count & 0x3u; + zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + zero_point_word = ${B.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${K} = ${J}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return oe},pe=()=>{let oe=`col_index = col * ${f};`;for(let K=0;K; + var b_value_upper: vec4; + var b_quantized_values: ${re}; + var b_dequantized_values: ${re};`,oe};return` + var workgroup_shared: array<${X.type.value}, ${y*w}>; + ${x.declareVariables(...W,X)} + ${x.mainStart([w,1,1])} + let output_indices = ${X.offsetToIndices(`(global_idx / ${w}) * ${y}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let nBlocksPerCol = uniforms.b_shape[1]; + + for (var block = local_id.x; block < nBlocksPerCol; block += ${w}) { + //process one block + var word_offset: u32 = block * ${r.blockSize/d}; + ${le()} + for (var word: u32 = 0; word < ${c}; word += ${u}) { + ${pe()} + for (var i: u32 = 0; i < ${u}; i++) { + ${ne()} + word_offset += ${8/d}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${y}) { + var output_value: ${X.type.value} = ${X.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${w}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${y}; + } + ${X.setByIndices(`${X.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${d};${u};${f};${y};${w}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:k},programUniforms:v}),getShaderSource:E}},FM=(e,r)=>{let t=e[0].dims,s=t.length,n=t[s-2],o=r.k,i=r.n,a=t.slice(0,s-2),l=we.size(a),c=e[1].dims[2]/4,p=e[0].dataType,d=ur(r.k),u=ur(c),f=a.concat([n,i]),_=128,y=i%8===0?8:i%4===0?4:1,k=_/y,w=k*u*8,v=w/d,I=w/r.blockSize,T=we.size(f)/y,b=[],E=[l,n,o/d],x=we.convertShape(e[1].dims).slice();x.splice(-1,1,c/u),b.push(...ct(E)),b.push(...ct(x)),b.push(...ct(e[2].dims)),e.length===4&&b.push(...ct(we.convertShape(e[3].dims)));let S=[l,n,i];b.push(...ct(S));let O=F=>{let H=E.length,W=ke("a",e[0].dataType,H,d),B=ke("b",12,x.length,u),Y=ke("scales",e[2].dataType,e[2].dims.length),X=[W,B,Y],J=e.length===4?ke("zero_points",12,e[3].dims.length):void 0;J&&X.push(J);let re=S.length,ne=it("output",e[0].dataType,re),le=Ar(e[0].dataType),pe=()=>{switch(d){case 1:return` + let a_data0 = vec4<${le}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${le}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` + let a_data0 = vec4<${le}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${le}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` + let a_data0 = sub_a[word_offset]; + let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${d}-component is not supported.`)}};return` + var sub_a: array<${W.type.value}, ${v}>; + var inter_results: array, ${y}>; + ${F.declareVariables(...X,ne)} + ${F.mainStart([k,y,1])} + let output_indices = ${ne.offsetToIndices(`workgroup_index * ${y}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let n_blocks_per_col = uniforms.b_shape[1]; + let num_tiles = (n_blocks_per_col - 1) / ${I} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${v}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${v}; a_offset += ${_}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${W.getByIndices(`${W.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${W.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${I} + local_id.x; + ${J?` + let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; + let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); + let zero_point_word_index = zero_point_byte_count >> 0x2u; + let zero_point_byte_offset = zero_point_byte_count & 0x3u; + let zero_point_nibble_offset: u32 = block & 0x1u; + let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + let zero_point_word = ${J.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${le}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${le}(8);`} + let scale = ${Y.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${B.getByIndices(`${B.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${r.blockSize/d}; + for (var i: u32 = 0; i < ${u}; i++) { + ${pe()} + let b_value = ${u===1?"b_data":"b_data[i]"}; + let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); + let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); + let b_quantized_values = mat2x4<${le}>(${Array.from({length:4},(oe,K)=>`${le}(b_value_lower[${K}]), ${le}(b_value_upper[${K}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${le}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(oe,K)=>`${`dot(a_data${K}, b_dequantized_values[${K}])`}`).join(" + ")}; + word_offset += ${8/d}; + } + workgroupBarrier(); + } + + if (local_idx < ${y}) { + var output_value: ${ne.type.value} = ${ne.type.value}(0); + for (var b = 0u; b < ${k}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${ne.setByIndices(`${ne.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${d};${u};${k};${y}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:T},programUniforms:b}),getShaderSource:O}},$0=(e,r)=>{kM(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(FM(e.inputs,r)):e.compute(AM(e.inputs,r))},k0=e=>jt(e)}),OM,DM,LM,zM,BM,RM,NM,jM,A0,jT=Ve(()=>{gt(),Ct(),St(),OM=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let r=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(r=e[3].dims[0]*2===e[1].dims[0]),!r)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},DM=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` + k = i32(${e.indicesGet("indices",n)}) - ${lt("uniforms.pads",n,t)}; + if (k < 0) { + break; + } + if (k >= i32(${lt("uniforms.x_shape",n,r)})) { + break; + } + offset += k * i32(${lt("uniforms.x_strides",n,r)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + } + `},LM=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` + k = i32(${e.indicesGet("indices",n)}) - ${lt("uniforms.pads",n,t)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${lt("uniforms.x_shape",n,r)}) - 1); + k = k % _2n_1; + if(k >= i32(${lt("uniforms.x_shape",n,r)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${lt("uniforms.x_strides",n,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},zM=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` + k = i32(${e.indicesGet("indices",n)}) - ${lt("uniforms.pads",n,t)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${lt("uniforms.x_shape",n,r)})) { + k = i32(${lt("uniforms.x_shape",n,r)}) - 1; + } + offset += k * i32(${lt("uniforms.x_strides",n,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},BM=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` + k = i32(${e.indicesGet("indices",n)}) - ${lt("uniforms.pads",n,t)}; + if (k < 0) { + k += i32(${lt("uniforms.x_shape",n,r)}]); + } + if (k >= i32(${lt("uniforms.x_shape",n,r)})) { + k -= i32(${lt("uniforms.x_shape",n,r)}); + } + offset += k * i32(${lt("uniforms.x_strides",n,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},RM=(e,r,t)=>{switch(t.mode){case 0:return DM(e,r,t.pads.length);case 1:return LM(e,r,t.pads.length);case 2:return zM(e,r,t.pads.length);case 3:return BM(e,r,t.pads.length);default:throw new Error("Invalid mode")}},NM=(e,r)=>{let t=we.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,n=we.size(t),o=[{type:12,data:n},{type:6,data:r.pads}],i=e.length>=3&&e[2].data;r.mode===0&&o.push({type:i?e[2].dataType:1,data:r.value}),o.push(...ct(e[0].dims,t));let a=["rank"],l=c=>{let p=it("output",e[0].dataType,t.length),d=ke("x",e[0].dataType,s.length),u=d.type.value,f=RM(p,s.length,r),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&_.push({name:"constant_value",type:i?u:"f32"}),` + ${c.registerUniforms(_).declareVariables(d,p)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${p.offsetToIndices("global_idx")}; + + var value = ${u}(0); + ${f} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${i}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(we.size(t)/64)},programUniforms:o}),getShaderSource:l}},jM=(e,r)=>{if(e.length>1){let t=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,n=e[0].dims.length,o=new Int32Array(2*n).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;lo[Number(l)]=Number(a));let i=[];return o.forEach(a=>i.push(a)),{mode:r.mode,value:s,pads:i}}else return r},A0=(e,r)=>{OM(e.inputs);let t=jM(e.inputs,r);e.compute(NM(e.inputs,t),{inputs:[0]})}}),Vo,$c,kc,Ac,Fc,VM,UM,Oc,Dc,F0,O0,Lc,D0,L0,zc,z0,B0,R0,N0,VT=Ve(()=>{Es(),gt(),Ct(),St(),Vo=e=>{if(Jt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},$c=(e,r,t)=>{let s=r.format==="NHWC",n=e.dims.slice();s&&n.splice(1,0,n.pop());let o=Object.hasOwnProperty.call(r,"dilations"),i=r.kernelShape.slice(),a=r.strides.slice(),l=o?r.dilations.slice():[],c=r.pads.slice();mi.adjustPoolAttributes(t,n,i,a,l,c);let p=mi.computePoolOutputShape(t,n,a,l,i,c,r.autoPad),d=Object.assign({},r);o?Object.assign(d,{kernelShape:i,strides:a,pads:c,dilations:l,cacheKey:r.cacheKey}):Object.assign(d,{kernelShape:i,strides:a,pads:c,cacheKey:r.cacheKey});let u=p.slice();return u.push(u.splice(1,1)[0]),[d,s?u:p]},kc=(e,r)=>{let t=r.format==="NHWC",s=we.size(e),n=we.size(r.kernelShape),o=[{type:12,data:s},{type:12,data:n}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let a=r.kernelShape[r.kernelShape.length-1],l=r.strides[r.strides.length-1],c=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],d=!!(c+p);o.push({type:12,data:a},{type:12,data:l},{type:12,data:c},{type:12,data:p}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(r.kernelShape.length===2){let f=r.kernelShape[r.kernelShape.length-2],_=r.strides[r.strides.length-2],y=r.pads[r.pads.length/2-2],k=r.pads[r.pads.length-2];u=!!(y+k),o.push({type:12,data:f},{type:12,data:_},{type:12,data:y},{type:12,data:k}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[o,i,!0,d,u]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=we.computeStrides(r.kernelShape);o.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),i.push({name:"kernelStrides",type:"u32",length:a.length},{name:"pads",type:"u32",length:r.pads.length},{name:"strides",type:"u32",length:r.strides.length});let l=r.pads.reduce((c,p)=>c+p);return[o,i,!!l,!1,!1]}},Ac=(e,r,t,s,n,o,i,a,l,c,p,d)=>{let u=n.format==="NHWC",f=r.type.value,_=it("output",r.type.tensor,s);if(n.kernelShape.length<=2){let y="",k="",w="",v=t-(u?2:1);if(p?y=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${v}] < 0 || xIndices[${v}] + >= uniforms.x_shape[${v}]) { + pad++; + continue; + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${o} + }`:y=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${o} + }`,n.kernelShape.length===2){let I=t-(u?3:2);d?k=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${I}] = indices[${I}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${I}] < 0 || xIndices[${I}] >= uniforms.x_shape[${I}]) { + pad += i32(uniforms.kw); + continue; + } + `:k=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${I}] = indices[${I}] * uniforms.sh - uniforms.phStart + j; + `,w=` + } + `}return` + ${e.registerUniforms(l).declareVariables(r,_)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${_.offsetToIndices("global_idx")}; + var xIndices = ${_.offsetToIndices("global_idx")}; + + var value = ${f}(${a}); + var pad = 0; + ${k} + ${y} + ${w} + ${i} + + output[global_idx] = value; + }`}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let y=n.kernelShape.length,k=n.pads.length,w="";return c?w=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${o} + }`:w=` + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${o} + `,` + ${e.registerUniforms(l).declareVariables(r,_)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${_.offsetToIndices("global_idx")}; + var xIndices = ${_.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${f}(${a}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${y-1}u; j++) { + offsets[j] = offset / ${lt("uniforms.kernelStrides","j",y)}; + offset -= offsets[j] * ${lt("uniforms.kernelStrides","j",y)}; + } + offsets[${y-1}] = offset; + + isPad = false; + for (var j = ${t-y}u; j < ${t}u; j++) { + xIndices[j] = indices[j] * ${lt("uniforms.strides",`j - ${t-y}u`,y)} + + offsets[j - ${t-y}u] - ${lt("uniforms.pads","j - 2u",k)}; + ${w} + } + ${i} + + output[global_idx] = value; + }`}},Fc=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,VM=e=>`${Fc(e)};${e.countIncludePad}`,UM=e=>`${Fc(e)};${e.storageOrder};${e.dilations}`,Oc=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Dc=(e,r,t,s)=>{let[n,o]=$c(r,s,t),i=ke("x",r.dataType,r.dims.length),a=i.type.value,l="value += x_val;",c="";n.countIncludePad?c+=`value /= ${a}(uniforms.kernelSize);`:c+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,d,u,f,_]=kc(o,n);p.push(...ct(r.dims,o));let y=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${u};${f};${_}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:o,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(we.size(o)/64)},programUniforms:p}),getShaderSource:k=>Ac(k,i,r.dims.length,o.length,n,l,c,0,d,u,f,_)}},F0=e=>{let r=e.count_include_pad!==0,t=Oc(e);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:r,...t,cacheKey:""};return{...s,cacheKey:VM(s)}},O0=(e,r)=>{Vo(e.inputs),e.compute(Dc("AveragePool",e.inputs[0],!1,r))},Lc={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},D0=e=>{let r=e.format;return{format:r,...Lc,cacheKey:r}},L0=(e,r)=>{Vo(e.inputs),e.compute(Dc("GlobalAveragePool",e.inputs[0],!0,r))},zc=(e,r,t,s)=>{let[n,o]=$c(r,s,t),i=` + value = max(x_val, value); + `,a="",l=ke("x",r.dataType,r.dims.length),c=["rank"],[p,d,u,f,_]=kc(o,n);return p.push(...ct(r.dims,o)),{name:e,shaderCache:{hint:`${s.cacheKey};${u};${f};${_}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:o,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(we.size(o)/64)},programUniforms:p}),getShaderSource:y=>Ac(y,l,r.dims.length,o.length,n,i,a,r.dataType===10?-65504:-1e5,d,u,f,_)}},z0=(e,r)=>{Vo(e.inputs),e.compute(zc("MaxPool",e.inputs[0],!1,r))},B0=e=>{let r=e.storage_order,t=e.dilations,s=Oc(e);if(r!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let n={storageOrder:r,dilations:t,...s,cacheKey:""};return{...n,cacheKey:UM(n)}},R0=e=>{let r=e.format;return{format:r,...Lc,cacheKey:r}},N0=(e,r)=>{Vo(e.inputs),e.compute(zc("GlobalMaxPool",e.inputs[0],!0,r))}}),WM,GM,j0,V0,UT=Ve(()=>{gt(),Ct(),mr(),St(),WM=(e,r)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((t,s)=>t===e[2].dims[s]).reduce((t,s)=>t&&s,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(r.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((n,o)=>o===r.axis||n===e[0].dims[o]).reduce((n,o)=>n&&o,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let t=e[0].dims[r.axis],s=e[1].dims[r.axis];if(r.blockSizeMath.ceil(t/(s-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},GM=(e,r)=>{let t=we.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,n=s===3,o=e[0].dims,i=e[1].dataType,a=we.size(o),l=s===3||s===2,c=l?[Math.ceil(we.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,d=e.length>2?e[2]:void 0,u=d?l?[Math.ceil(we.size(d.dims)/4)]:d.dims:void 0,f=p.length===0||p.length===1&&p[0]===1,_=f===!1&&p.length===1,y=ur(a),k=f&&(!l||y===4),w=k?y:1,v=k&&!l?y:1,I=ke("input",l?12:s,c.length,v),T=ke("scale",i,p.length),b=d?ke("zero_point",l?12:s,u.length):void 0,E=it("output",i,o.length,w),x=[I,T];b&&x.push(b);let S=[c,p];d&&S.push(u);let O=[{type:12,data:a/w},{type:12,data:t},{type:12,data:r.blockSize},...ct(...S,o)],F=H=>{let W=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${H.registerUniforms(W).declareVariables(...x,E)} + ${H.mainStart()} + ${H.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${E.offsetToIndices("global_idx")}; + + // Set input x + ${l?` + let input = ${I.getByOffset("global_idx / 4")}; + let x_vec = ${n?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${w===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${I.getByOffset("global_idx")};`}; + + // Set scale input + ${f?`let scale_value= ${T.getByOffset("0")}`:_?` + let scale_index = ${E.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${T.getByOffset("scale_index")};`:` + var scale_indices: ${T.type.indices} = output_indices; + let index = ${T.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${T.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${T.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${b?f?l?` + let zero_point_input = ${b.getByOffset("0")}; + let zero_point_vec = ${n?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${b.getByOffset("0")}`:_?l?` + let zero_point_index = ${E.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${b.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${n?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${E.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${b.getByOffset("zero_point_index")};`:l?` + let zero_point_offset = ${T.indicesToOffset("scale_indices")}; + let zero_point_input = ${b.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${n?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${b.getByIndices("scale_indices")};`:`let zero_point_value = ${l?n?"i32":"u32":I.type.value}(0);`}; + // Compute and write output + ${E.setByOffset("global_idx",`${E.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:b?["rank","rank","rank"]:["rank","rank"]},getShaderSource:F,getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(a/w/64),y:1,z:1},programUniforms:O})}},j0=(e,r)=>{WM(e.inputs,r),e.compute(GM(e.inputs,r))},V0=e=>jt({axis:e.axis,blockSize:e.blockSize})}),KM,HM,U0,WT=Ve(()=>{Es(),gt(),St(),KM=(e,r,t)=>{let s=e===r,n=er&&t>0;if(s||n||o)throw new Error("Range these inputs' contents are invalid.")},HM=(e,r,t,s)=>{let n=Math.abs(Math.ceil((r-e)/t)),o=[n],i=n,a=[{type:12,data:i},{type:s,data:e},{type:s,data:t},...ct(o)],l=c=>{let p=it("output",s,o.length),d=p.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:d},{name:"delta",type:d}];return` + ${c.registerUniforms(u).declareVariables(p)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${d}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:o,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:a})}},U0=e=>{let r=0,t=0,s=0;e.inputs[0].dataType===6?(r=e.inputs[0].getInt32Array()[0],t=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(r=e.inputs[0].getFloat32Array()[0],t=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),Jt.webgpu.validateInputContent&&KM(r,t,s),e.compute(HM(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),qM,Bc,Rc,QM,W0,G0,GT=Ve(()=>{gt(),Ct(),mr(),St(),qM=(e,r,t,s)=>{if(e!=="none"&&s!=="i32"&&s!=="u32"&&s!=="f32")throw new Error(`Input ${s} is not supported with reduction ${e}.`);let n=`{ + var oldValue = 0; + loop { + let newValueF32 =`,o=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${r}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${r}=${t};`;case"add":return s==="i32"||s==="u32"?`atomicAdd(&${r}, bitcast<${s}>(${t}));`:` + ${n}bitcast<${s}>(oldValue) + (${t})${o}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` + ${n}max(bitcast(oldValue), (${t}))${o}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${n}min(bitcast<${s}>(oldValue), (${t}))${o}`;case"mul":return`${n}(bitcast<${s}>(oldValue) * (${t}))${o}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Bc=(e,r)=>`${e===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[${r?"i - indices_start":"i"}]; + let dim_value = uniforms.output_shape[${r?"i - indices_start":"i"} + uniforms.last_index_dimension];`} + + if (index >= 0) { + if (index >= i32(dim_value)) { + index = i32(dim_value - 1); + } + } else { + if (index < -i32(dim_value)) { + index = 0; + } else { + index += i32(dim_value); + } + } + data_offset += u32((u32(index) * element_count_dim));`,Rc=(e,r,t)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * ${t?"global_idx":"idx"} + i]; + ${qM(e.reduction,"output[data_offset + i]","value",r)} + }`,QM=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t,o=1,i=Math.ceil(we.size(s)/o),a=s[s.length-1],l=we.sizeFromDimension(t,a),c=we.sizeFromDimension(s,0)/a,p=[{type:12,data:i},{type:12,data:a},{type:12,data:l},...ct(e[1].dims,e[2].dims,n)],d=u=>{let f=ke("indices",e[1].dataType,e[1].dims.length),_=ke("updates",e[2].dataType,e[2].dims.length,o),y=r.reduction!=="none"&&r.reduction!==""?wb("output",e[0].dataType,n.length):it("output",e[0].dataType,n.length,o);return` + ${u.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(f,_,y)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var hasDuplicates = false; + if (${r.reduction==="none"}) { + for (var i = 0; i < ${c}; i = i + 1) { + for (var j = i + 1; j < ${c}; j = j + 1) { + var index_i = i32(indices[i].x); + var index_j = i32(indices[j].x); + if (index_i == index_j) { + hasDuplicates = true; + break; + } + } + if (hasDuplicates) { + break; + } + } + } + + if (${r.reduction==="none"} && hasDuplicates) { + if (global_idx != 0u) { + return; + } + // Process each index-update pair individually when duplicates exist + for (var idx = 0u; idx < ${c}u; idx++) { + var data_offset = 0u; + for (var i = 0u; i < uniforms.last_index_dimension; i++) { + var index = i32(indices[idx * uniforms.last_index_dimension + i].x); + ${Bc(t.length,!1)} + } + ${Rc(r,y.type.value,!1)} + } + return; + } + + var data_offset = 0u; + var indices_start = uniforms.last_index_dimension * global_idx; + var indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${Bc(t.length,!0)} + } + ${Rc(r,y.type.value,!0)} + }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:d}},W0=e=>jt({reduction:e.reduction}),G0=(e,r)=>{e.compute(QM(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),XM,JM,YM,Nc,ZM,ew,tw,rw,sw,nw,ow,aw,jc,iw,lw,cw,uw,dw,K0,H0,KT=Ve(()=>{gt(),Ct(),mr(),St(),XM=(e,r)=>{if(e.every(t=>t>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(r.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(r.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},JM=(e,r,t)=>{r.every(n=>n>=0&&n{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(t).fill(1);return r.forEach((n,o)=>s[n]=e[o]),s},YM=(e,r,t,s,n,o)=>{let[i,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(p=>o.push(p));else if(r.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(a>0&&e.length>a&&e[a].dims.length===1&&e[a].dims[0]>0){if(e[a].getFloat32Array().forEach(p=>s.push(p)),s.length!==0&&s.length!==c&&t>=18&&s.length!==r.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");XM(s,r),r.axes.length>0&&JM(s,r.axes,c).forEach((p,d)=>s[d]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>n.push(Number(p))),n.length!==0&&n.length!==c&&t>=18&&n.length!==r.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(r.axes.length>0){if(s.length!==0&&s.length!==r.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(n.length!==0&&n.length!==r.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof s<"u"&&typeof n<"u"&&s.length>0&&n.length>c)throw new Error("Resize requires only of scales or sizes to be specified")},Nc=(e,r,t,s)=>` + // The whole part and the fractional part are calculated separately due to inaccuracy of floating + // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an + // offset-by-one error later in floor(). + let big = (${e}) * (${r}); + let whole = ${s}(big / (${t})); + let fract = ${s}(big % (${t})) / ${s}(${t}); + return whole + fract; +`,ZM=(e,r)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${r} { `+(()=>{switch(e){case"asymmetric":return` + if (xScale < 1.0 || floor(xScale) != xScale) { + return ${r}(xResized) / ${r}(xScale); + } else { + ${Nc("xResized","lengthOriginal","lengthResized",r)} + } + `;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${r}(xResized) + 0.5) / ${r}(xScale);`;case"align_corners":return`if (lengthResized == 1) { + return 0.0; + } else { + ${Nc("xResized","lengthOriginal - 1","lengthResized - 1",r)} + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${r}(roiStart) * ${r}(lengthOriginal - 1) + + (${r}(xResized) * ${r}(roiEnd - roiStart) * ${r}(lengthOriginal - 1)) / + ${r}(lengthResized - 1); + } else { + return 0.5 * ${r}(roiStart + roiEnd) * ${r}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${r}xScale * ${r}(lengthResized); + const adjustment = ${r}(lengthResized) / outputWidth; + const center = ${r}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + return offset + ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;case"half_pixel":return`return ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",ew=(e,r,t)=>`fn getNearestPixelFromOriginal(xOriginal: ${t}, isDownSample: bool) -> ${t} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";default:if(r<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",tw=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),n=e.length===0?s:e.slice();return r.length>0?(r.forEach((o,i)=>{s[o]=n[i],s[i+t]=n[r.length+i]}),s):n},rw=(e,r,t,s)=>{let n=[];if(t.length>0)if(s.length>0){if(e.forEach(o=>n.push(o)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((o,i)=>n[o]=t[i])}else t.forEach(o=>n.push(o));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");n=e.map((o,i)=>Math.round(o*r[i]))}return n},sw=(e,r,t)=>{let s=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(o=>r[o]),Number.MAX_VALUE):Math.min(...r,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(o=>r[o]),Number.MIN_VALUE):Math.max(...r,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${t.keepAspectRatioPolicy} is not supported`)}})();r.fill(1,0,r.length);let n=e.slice();return t.axes.length>0?(t.axes.forEach(o=>r[o]=s),t.axes.forEach(o=>n[o]=Math.round(e[o]*r[o]))):(r.fill(s,0,r.length),n.forEach((o,i)=>n[i]=Math.round(o*r[i]))),n},nw=(e,r,t,s,n)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${t.length}> { + var original_indices: array<${e.type.value}, ${t.length}>; + for (var i:u32 = 0; i < ${t.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${lt("uniforms.scales","i",s)}; + var roi_low = ${lt("uniforms.roi","i",n)}; + var roi_hi = ${lt("uniforms.roi",`i + ${r.length}`,n)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${lt("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${lt("uniforms.output_shape","i",t.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,ow=(e,r,t,s,n,o,i)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${r.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${lt("uniforms.scales","i",n)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${lt("uniforms.roi","i",o)}; + var roi_hi = ${lt("uniforms.roi",`i + ${t.length}`,o)}; + var input_shape_i = ${lt("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${lt("uniforms.output_shape","i",s.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${i} || (original_idx >= 0 && original_idx < ${r.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${r.type.value}(input_shape_i - 1)) { + input_index = input_shape_i - 1; + } else { + input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); + } + } else { + input_index = u32(original_idx); + } + } + ${e.indicesSet("input_indices","i","input_index")} + } + return input_indices; + }`,aw=(e,r)=>` + fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { + for (var i:u32 = 0; i < ${r.length}; i++) { + var input_index = ${e.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${lt("uniforms.input_shape","i",r.length)}) { + return false; + } + } + return true; + }`,jc=(e,r,t,s)=>e.rank>s?` + ${e.indicesSet("input_indices",r,"channel")}; + ${e.indicesSet("input_indices",t,"batch")}; +`:"",iw=(e,r,t,s,n)=>{let[o,i,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],c=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${c} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(row, ${t[i]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; + ${jc(e,l,o,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${c} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${c} = originalIndices[${i}]; + var col:${c} = originalIndices[${a}]; + ${s?`if (row < 0 || row > (${t[i]} - 1) || col < 0 || col > (${t[a]} - 1)) { + return ${n}; + }`:""}; + row = max(0, min(row, ${t[i]} - 1)); + col = max(0, min(col, ${t[a]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${t.length>2?`u32(originalIndices[${l}])`:"0"}; + var batch: u32 = ${t.length>2?`u32(originalIndices[${o}])`:"0"}; + var x11: ${c} = getInputValue(batch, channel, row1, col1); + var x12: ${c} = getInputValue(batch, channel, row1, col2); + var x21: ${c} = getInputValue(batch, channel, row2, col1); + var x22: ${c} = getInputValue(batch, channel, row2, col2); + var dx1: ${c} = abs(row - ${c}(row1)); + var dx2: ${c} = abs(${c}(row2) - row); + var dy1: ${c} = abs(col - ${c}(col1)); + var dy2: ${c} = abs(${c}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},lw=(e,r,t,s,n,o,i,a,l,c)=>{let p=t.length===2,[d,u]=p?[0,1]:[2,3],f=e.type.value,_=y=>{let k=y===d?"row":"col";return` + fn ${k}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${f} { + var output_index = ${r.indicesGet("output_indices",y)}; + var originalIdx: ${f} = getOriginalCoordinateFromResizedCoordinate(output_index, ${n[y]}, + ${s[y]}, ${t[y]}, ${o[y]}, ${o[y]} + ${t.length}); + var fractOriginalIdx: ${f} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${a} && (originalIdx < 0 || originalIdx > (${t[y]} - 1))) { + return ${l}; + } + var data: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${k}: ${f} = originalIdx + ${f}(i); + if (${k} < 0 || ${k} >= ${t[y]}) { + ${c?`coefs[i + 1] = 0.0; + continue;`:a?`return ${l};`:`${k} = max(0, min(${k}, ${t[y]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",y,`u32(${k})`)}; + data[i + 1] = ${y===d?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${_(d)}; + ${_(u)}; + fn getCubicInterpolationCoefs(s: ${f}) -> array<${f}, 4> { + var absS = abs(s); + var coeffs: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${f} = 1.0 - absS; + var twoMinusAbsS: ${f} = 2.0 - absS; + var onePlusAbsS: ${f} = 1.0 + absS; + coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; + coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; + coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${f}, 4>, coefs: array<${f}, 4>) -> ${f} { + var coefsSum: ${f} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; + return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; + } + + fn bicubicInterpolation(output_indices: ${r.type.indices}) -> ${f} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},cw=(e,r,t,s,n)=>{let[o,i,a,l,c]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${p} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(depth, ${t[i]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(height, ${t[a]} - 1))`)}; + ${e.indicesSet("input_indices",l,`max(0, min(width, ${t[l]} - 1))`)}; + ${jc(e,c,o,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${r.type.indices}) -> ${p} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${p} = originalIndices[${i}]; + var height:${p} = originalIndices[${a}]; + var width:${p} = originalIndices[${l}]; + ${s?`if (depth < 0 || depth > (${t[i]} - 1) || height < 0 || height > (${t[a]} - 1) || width < 0 || (width > ${t[l]} - 1)) { + return ${n}; + }`:""}; + + depth = max(0, min(depth, ${t[i]} - 1)); + height = max(0, min(height, ${t[a]} - 1)); + width = max(0, min(width, ${t[l]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${t.length>3?`u32(originalIndices[${c}])`:"0"}; + var batch: u32 = ${t.length>3?`u32(originalIndices[${o}])`:"0"}; + + var x111: ${p} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${p} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${p} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${p} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${p} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${p} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${p} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${p} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${p} = abs(depth - ${p}(depth1)); + var dx2: ${p} = abs(${p}(depth2) - depth); + var dy1: ${p} = abs(height - ${p}(height1)); + var dy2: ${p} = abs(${p}(height2) - height); + var dz1: ${p} = abs(width - ${p}(width1)); + var dz2: ${p} = abs(${p}(width2) - width); + if (depth1 == depth2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (height1 == height2) { + dy1 = 0.5; + dy2 = 0.5; + } + if (width1 == width2) { + dz1 = 0.5; + dz2 = 0.5; + } + return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); + }`},uw=(e,r,t,s,n,o)=>{let i=e.dims,a=tw(o,r.axes,i.length),l=rw(i,s,n,r.axes),c=s.slice();s.length===0&&(c=i.map((v,I)=>v===0?1:l[I]/v),r.keepAspectRatioPolicy!=="stretch"&&(l=sw(i,c,r)));let p=it("output",e.dataType,l.length),d=ke("input",e.dataType,i.length),u=we.size(l),f=i.length===l.length&&i.every((v,I)=>v===l[I]),_=r.coordinateTransformMode==="tf_crop_and_resize",y=r.extrapolationValue,k=d.type.value,w=v=>` + ${f?"":` + ${ZM(r.coordinateTransformMode,k)}; + ${(()=>{switch(r.mode){case"nearest":return` + ${aw(d,i)}; + ${ew(r.nearestMode,t,k)}; + ${ow(d,p,i,l,c.length,a.length,_)}; + `;case"linear":return` + ${nw(p,i,l,c.length,a.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${iw(d,p,i,_,y)}`;if(i.length===3||i.length===5)return`${cw(d,p,i,_,y)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(i.length===2||i.length===4)return`${lw(d,p,i,l,c,a,r.cubicCoeffA,_,r.extrapolationValue,r.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${v.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",a.length).declareVariables(d,p)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${f?"output[global_idx] = input[global_idx];":` + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${d.type.indices}; + ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${d.getByIndices("input_indices")}; + } else { + output[global_idx] = ${r.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${r.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${r.cacheKey}|${t}|${c.length>0?r.mode==="cubic"?c:c.length:""}|${n.length>0?n:""}|${a.length>0?a:""}|${f}|${r.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:1,data:c},{type:1,data:a},...ct(i,l)]})}},dw=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},K0=(e,r)=>{let t=[],s=[],n=[],o=dw(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");YM(e.inputs,r,o,t,s,n),e.compute(uw(e.inputs[0],r,o,t,s,n),{inputs:[0]})},H0=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,n=e.cubicCoeffA,o=e.excludeOutside!==0,i=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return jt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:n,excludeOutside:o,extrapolationValue:i,keepAspectRatioPolicy:a,mode:l,nearestMode:c})}}),pw,mw,q0,HT=Ve(()=>{gt(),Ct(),St(),pw=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let r=e[0],t=e[1],s=e[2];if(r.dataType!==t.dataType||r.dataType!==s.dataType)throw new Error("All inputs must have the same data type");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Input must be 2D or 3D");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Skip must be 2D or 3D");let n=r.dims[r.dims.length-1],o=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==n)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==o)throw new Error("Skip must have the same sequence length as input");if(s.dims.length!==1)throw new Error("Gamma must be 1D");if(s.dims[s.dims.length-1]!==n)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==n)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==n)throw new Error("Bias must have the same hidden size as input")}},mw=(e,r,t,s)=>{let n=r.simplified,o=e[0].dims,i=we.size(o),a=o,l=i,c=o.slice(-1)[0],p=s?o.slice(0,-1).concat(1):[],d=!n&&e.length>3,u=e.length>4,f=s&&t>1,_=s&&t>2,y=t>3,k=64,w=ur(c),v=[{type:12,data:l},{type:12,data:w},{type:12,data:c},{type:1,data:r.epsilon}],I=b=>{let E=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],x=[ke("x",e[0].dataType,e[0].dims,w),ke("skip",e[1].dataType,e[1].dims,w),ke("gamma",e[2].dataType,e[2].dims,w)];d&&x.push(ke("beta",e[3].dataType,e[3].dims,w)),u&&x.push(ke("bias",e[4].dataType,e[4].dims,w)),x.push(it("output",e[0].dataType,a,w)),f&&x.push(it("mean_output",1,p)),_&&x.push(it("inv_std_output",1,p)),y&&x.push(it("input_skip_bias_sum",e[0].dataType,a,w));let S=Ar(e[0].dataType),O=Ar(1,w);return` + + ${b.registerUniforms(E).declareVariables(...x)} + var sum_shared : array<${O}, ${k}>; + var sum_squared_shared : array<${O}, ${k}>; + + ${b.mainStart([k,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${k}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${k}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${k-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${u?"bias[offset1d + i]":S+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${y?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${io(S,w,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${k}; + for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { + reduce_size = curr_size + (reduce_size & 1); + if (ix < curr_size) { + sum_shared[ix] += sum_shared[ix + reduce_size]; + sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; + } + workgroupBarrier(); + } + + let sum = sum_shared[0]; + let square_sum = sum_squared_shared[0]; + let mean = ${ln("sum",w)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${ln("square_sum",w)} / f32(uniforms.hidden_size) ${n?"":"- mean * mean"} + uniforms.epsilon); + ${f?"mean_output[global_idx] = mean;":""} + ${_?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${n?"":`- ${S}(mean)`}) * + ${S}(inv_std_dev) * gamma[offset1d + i] + ${d?"+ beta[offset1d + i]":""}; + } + }`},T=[{dims:a,dataType:e[0].dataType}];return t>1&&T.push({dims:p,dataType:1}),t>2&&T.push({dims:p,dataType:1}),t>3&&T.push({dims:o,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${w};${f};${_};${y}`,inputDependencies:e.map((b,E)=>"type")},getShaderSource:I,getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(l/c)},programUniforms:v})}},q0=(e,r)=>{pw(e.inputs);let t=[0];e.outputCount>1&&t.push(-3),e.outputCount>2&&t.push(-3),e.outputCount>3&&t.push(3),e.compute(mw(e.inputs,r,e.outputCount,!1),{outputs:t})}}),hw,Uo,_w,Vc,fw,gw,Q0,X0,qT=Ve(()=>{gt(),Ct(),mr(),St(),hw=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");if(r.axes.length!==0){if(r.axes.length!==r.starts.length||r.axes.length!==r.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(r.starts.length!==r.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((t,s)=>{if(e[s+1].dataType!==6&&e[s+1].dataType!==7)throw new Error(`Input ${s} must be an array of int32 or int64`)})},Uo=(e,r)=>{let t=[];if(e.length>r)if(e[r].dataType===7)e[r].getBigInt64Array().forEach(s=>t.push(Number(s)));else if(e[r].dataType===6)e[r].getInt32Array().forEach(s=>t.push(Number(s)));else throw new Error(`Input ${r} must be an array of int32 or int64`);return t},_w=(e,r)=>{if(e.length>1){let t=Uo(e,1),s=Uo(e,2),n=Uo(e,3);return n.length===0&&(n=[...Array(e[0].dims.length).keys()]),jt({starts:t,ends:s,axes:n})}else return r},Vc=(e,r,t,s,n)=>{let o=e;return e<0&&(o+=t[s[r]]),n[r]<0?Math.max(0,Math.min(o,t[s[r]]-1)):Math.max(0,Math.min(o,t[s[r]]))},fw=(e,r,t)=>`fn calculateInputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${t.length}; i >= 0; i--) { + let input_shape_i = ${lt("uniforms.input_shape","i",t.length)}; + let steps_i = ${lt("uniforms.steps","i",t.length)}; + let signs_i = ${lt("uniforms.signs","i",t.length)}; + let starts_i = ${lt("uniforms.starts","i",t.length)}; + var output_index = ${r.indicesGet("output_indices","i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${e.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,gw=(e,r)=>{let t=e[0].dims,s=we.size(t),n=r.axes.length>0?we.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],o=Uo(e,4);o.forEach(w=>w!==0||(()=>{throw new Error("step cannot be 0")})),o.length===0&&(o=Array(n.length).fill(1));let i=r.starts.map((w,v)=>Vc(w,v,t,n,o)),a=r.ends.map((w,v)=>Vc(w,v,t,n,o));if(n.length!==i.length||n.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(n.length!==t.length)for(let w=0;wMath.sign(w));o.forEach((w,v,I)=>{if(w<0){let T=(a[v]-i[v])/w,b=i[v],E=b+T*o[v];i[v]=E,a[v]=b,I[v]=-w}});let c=t.slice(0);n.forEach((w,v)=>{c[w]=Math.ceil((a[w]-i[w])/o[w])});let p={dims:c,dataType:e[0].dataType},d=it("output",e[0].dataType,c.length),u=ke("input",e[0].dataType,e[0].dims.length),f=we.size(c),_=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:o.length}],y=[{type:12,data:f},{type:12,data:i},{type:6,data:l},{type:12,data:o},...ct(e[0].dims,c)],k=w=>` + ${w.registerUniforms(_).declareVariables(u,d)} + ${fw(u,d,t)} + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${d.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${d.setByOffset("global_idx",u.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${o.length}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:y})}},Q0=(e,r)=>{hw(e.inputs,r);let t=_w(e.inputs,r);e.compute(gw(e.inputs,t),{inputs:[0]})},X0=e=>{let r=e.starts,t=e.ends,s=e.axes;return jt({starts:r,ends:t,axes:s})}}),Mw,ww,J0,Y0,QT=Ve(()=>{gt(),Ct(),mr(),cn(),St(),Mw=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},ww=(e,r)=>{let t=e.inputs[0],s=t.dims,n=we.size(s),o=s.length,i=we.normalizeAxis(r.axis,o),a=iS),c[i]=o-1,c[o-1]=i,l=e.compute(es(t,c),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,d=p[o-1],u=n/d,f=ur(d),_=d/f,y=64;u===1&&(y=256);let k=(x,S)=>S===4?`max(max(${x}.x, ${x}.y), max(${x}.z, ${x}.w))`:S===2?`max(${x}.x, ${x}.y)`:S===3?`max(max(${x}.x, ${x}.y), ${x}.z)`:x,w=ke("x",l.dataType,l.dims,f),v=it("result",l.dataType,l.dims,f),I=w.type.value,T=Ar(l.dataType)==="f32"?`var threadMax = ${I}(-3.402823e+38f);`:`var threadMax = ${I}(-65504.0h);`,b=x=>` + var rowMaxShared : ${I}; + var rowSumShared : ${I}; + var threadShared : array<${I}, ${y}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${I} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${I}) { + let index = row * row_stride + col; + result[index] = value; + } + ${x.registerUniform("packedCols","i32").declareVariables(w,v)} + ${x.mainStart(y)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${y}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${T} + for (var col = lindex; col < cols; col += wg) { + let value = getValue(row, col, row_stride); + threadMax = max(threadMax, value); + } + if (lindex < cols) { + threadShared[lindex] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, wg); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (lindex < currSize) { + threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); + } + workgroupBarrier(); + } + if (lindex == 0) { + rowMaxShared = ${I}(${k("threadShared[0]",f)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${I}(0.0); + for (var col = lindex; col < cols; col += wg) { + let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); + threadSum += subExp; + } + threadShared[lindex] = threadSum; + workgroupBarrier(); + + for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { + if (lindex < currSize) { + threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; + } + workgroupBarrier(); + } + if (lindex == 0) { + rowSumShared = ${I}(${ln("threadShared[0]",f)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`,E=e.compute({name:"Softmax",shaderCache:{hint:`${f};${y}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:_}]}),getShaderSource:b},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(es(E,c),{inputs:[E]})},J0=(e,r)=>{Mw(e.inputs),ww(e,r)},Y0=e=>jt({axis:e.axis})}),Uc,bw,yw,vw,Z0,XT=Ve(()=>{gt(),Ct(),St(),Uc=e=>Array.from(e.getBigInt64Array(),Number),bw=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Uc(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},yw=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Uc(e[1]),n=yw(t,s),o=we.size(n),i=e[0].dataType,a=ke("input",i,t.length),l=it("output",i,n.length),c=p=>` + const inputShape = ${a.indices(...t)}; + ${p.registerUniform("output_size","u32").declareVariables(a,l)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${l.offsetToIndices("global_idx")}; + var input_indices: ${a.type.indices}; + for (var i = 0; i < ${t.length}; i++) { + let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i; + + ${a.indicesSet("input_indices","i","input_dim_value")} + } + ${l.setByOffset("global_idx",a.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},...ct(e[0].dims,n)]}),getShaderSource:c}},Z0=e=>{bw(e.inputs),e.compute(vw(e.inputs),{inputs:[0]})}}),xw,Tw,ev,JT=Ve(()=>{gt(),Ct(),St(),xw=(e,r,t,s,n)=>{let o=it("output_data",n,t.length,4),i=ke("a_data",r[1].dataType,r[1].dims.length,4),a=ke("b_data",r[2].dataType,r[2].dims.length,4),l=ke("c_data",r[0].dataType,r[0].dims.length,4),c,p=(d,u,f)=>`select(${u}, ${d}, ${f})`;if(!s)c=o.setByOffset("global_idx",p(i.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let d=(u,f,_="")=>{let y=`a_data[index_a${f}][component_a${f}]`,k=`b_data[index_b${f}][component_b${f}]`,w=`bool(c_data[index_c${f}] & (0xffu << (component_c${f} * 8)))`;return` + let output_indices${f} = ${o.offsetToIndices(`global_idx * 4u + ${f}u`)}; + let offset_a${f} = ${i.broadcastedIndicesToOffset(`output_indices${f}`,o)}; + let offset_b${f} = ${a.broadcastedIndicesToOffset(`output_indices${f}`,o)}; + let offset_c${f} = ${l.broadcastedIndicesToOffset(`output_indices${f}`,o)}; + let index_a${f} = offset_a${f} / 4u; + let index_b${f} = offset_b${f} / 4u; + let index_c${f} = offset_c${f} / 4u; + let component_a${f} = offset_a${f} % 4u; + let component_b${f} = offset_b${f} % 4u; + let component_c${f} = offset_c${f} % 4u; + ${u}[${f}] = ${_}(${p(y,k,w)}); + `};n===9?c=` + var data = vec4(0); + ${d("data",0,"u32")} + ${d("data",1,"u32")} + ${d("data",2,"u32")} + ${d("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=` + ${d("output_data[global_idx]",0)} + ${d("output_data[global_idx]",1)} + ${d("output_data[global_idx]",2)} + ${d("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(l,i,a,o)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${c} + }`},Tw=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,n=e[1].dataType,o=!(we.areEqual(r,t)&&we.areEqual(t,s)),i=r,a=we.size(r);if(o){let c=lo.calcShape(lo.calcShape(r,t,!1),s,!1);if(!c)throw new Error("Can't perform where op on the given tensors");i=c,a=we.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>xw(c,e,i,o,n),getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...ct(s,r,t,i)]})}},ev=e=>{e.compute(Tw(e.inputs))}}),tv,YT=Ve(()=>{pT(),Iu(),mT(),hT(),_T(),fT(),gT(),vT(),TT(),ET(),PT(),CT(),ST(),IT(),$T(),kT(),AT(),FT(),OT(),DT(),LT(),zT(),BT(),RT(),NT(),b0(),jT(),VT(),UT(),WT(),GT(),Su(),KT(),E0(),HT(),qT(),QT(),x0(),XT(),cn(),$u(),JT(),tv=new Map([["Abs",[qb]],["Acos",[Qb]],["Acosh",[Xb]],["Add",[$y]],["ArgMax",[Wb,su]],["ArgMin",[Ub,su]],["Asin",[Jb]],["Asinh",[Yb]],["Atan",[Zb]],["Atanh",[ey]],["Attention",[Gb]],["AveragePool",[O0,F0]],["BatchNormalization",[Kb]],["BiasAdd",[Hb]],["BiasSplitGelu",[Iy]],["Cast",[ry,ty]],["Ceil",[ny]],["Clip",[sy]],["Concat",[Ny,jy]],["Conv",[cu,lu]],["ConvTranspose",[Jy,Xy]],["Cos",[oy]],["Cosh",[ay]],["CumSum",[Yy,Zy]],["DepthToSpace",[e0,t0]],["DequantizeLinear",[j0,V0]],["Div",[ky]],["Einsum",[r0,s0]],["Elu",[iy,qo]],["Equal",[Ay]],["Erf",[ly]],["Exp",[cy]],["Expand",[n0]],["FastGelu",[o0]],["Floor",[uy]],["FusedConv",[cu,lu]],["Gather",[i0,a0]],["GatherElements",[m0,p0]],["GatherBlockQuantized",[u0,d0]],["GatherND",[l0,c0]],["Gelu",[dy]],["Gemm",[_0,h0]],["GlobalAveragePool",[L0,D0]],["GlobalMaxPool",[N0,R0]],["Greater",[Ly]],["GreaterOrEqual",[By]],["GridSample",[f0,g0]],["GroupQueryAttention",[P0]],["HardSigmoid",[wy,My]],["InstanceNormalization",[C0]],["LayerNormalization",[S0]],["LeakyRelu",[py,qo]],["Less",[zy]],["LessOrEqual",[Ry]],["Log",[Cy]],["MatMul",[I0]],["MatMulNBits",[$0,k0]],["MaxPool",[z0,B0]],["Mul",[Fy]],["MultiHeadAttention",[w0,M0]],["Neg",[hy]],["Not",[my]],["Pad",[A0]],["Pow",[Oy]],["QuickGelu",[Sy,qo]],["Range",[U0]],["Reciprocal",[_y]],["ReduceMin",[Bb]],["ReduceMean",[Fb]],["ReduceMax",[zb]],["ReduceSum",[Nb]],["ReduceProd",[Rb]],["ReduceL1",[Ob]],["ReduceL2",[Db]],["ReduceLogSum",[Vb]],["ReduceLogSumExp",[Lb]],["ReduceSumSquare",[jb]],["Relu",[fy]],["Resize",[K0,H0]],["RotaryEmbedding",[T0]],["ScatterND",[G0,W0]],["Sigmoid",[gy]],["Sin",[by]],["Sinh",[yy]],["Slice",[Q0,X0]],["SkipLayerNormalization",[q0]],["Split",[y0,v0]],["Sqrt",[vy]],["Softmax",[J0,Y0]],["Sub",[Dy]],["Tan",[xy]],["Tanh",[Ty]],["ThresholdedRelu",[Py,qo]],["Tile",[Z0]],["Transpose",[yb,vb]],["Where",[ev]]])}),rv,ZT=Ve(()=>{Es(),Hs(),St(),rv=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t,s,n){Ts(e.programInfo.name);let o=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let c of r)a.push({binding:a.length,resource:{buffer:c.buffer}});for(let c of t)a.push({binding:a.length,resource:{buffer:c.buffer}});n&&a.push({binding:a.length,resource:n});let l=o.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}i.setPipeline(e.computePipeline),i.setBindGroup(0,l),i.dispatchWorkgroups(...s),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),us(e.programInfo.name)}dispose(){}build(e,r){Ts(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(c=>{t.features.has(c.feature)&&s.push(`enable ${c.extension};`)});let n=bb(r,this.backend.device.limits),o=e.getShaderSource(n),i=`${s.join(` +`)} +${n.additionalImplementations} +${o}`,a=t.createShaderModule({code:i,label:e.name});Dt("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return us(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:n.variablesInfo}}normalizeDispatchGroupSize(e){let r=typeof e=="number"?e:e.x,t=typeof e=="number"?1:e.y||1,s=typeof e=="number"?1:e.z||1,n=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=n&&t<=n&&s<=n)return[r,t,s];let o=r*t*s,i=Math.ceil(Math.sqrt(o));if(i>n){if(i=Math.ceil(Math.cbrt(o)),i>n)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),sv={};uo(sv,{WebGpuBackend:()=>nv});var Ew,Pw,Cw,nv,e1=Ve(()=>{Es(),gt(),Hs(),_b(),uT(),YT(),ZT(),Ew=(e,r)=>{if(r.length!==e.length)throw new Error(`inputDependencies length ${r.length} is not equal to inputTensors length ${e.length}.`);let t=[];for(let s=0;s{let s=e.name;return e.shaderCache?.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${Ew(r,e.shaderCache?.inputDependencies??new Array(r.length).fill("dims"))}`,s},Cw=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},nv=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,r){this.env=e;let t=[],s={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},n=o=>r.features.has(o)&&t.push(o)&&!0;n("chromium-experimental-timestamp-query-inside-passes")||n("timestamp-query"),n("shader-f16"),n("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new Cw(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Mb(this),this.programManager=new rv(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Tu(e.logLevel,!!e.debug),this.device.onuncapturederror=o=>{o.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${o.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ts(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let s=0;s"u"&&(this.queryTimeBase=u);let _=Number(u-this.queryTimeBase),y=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(_)||!Number.isSafeInteger(y))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:p.map(k=>({dims:k.dims,dataType:Ks(k.dataType)})),outputsMetadata:d.map(k=>({dims:k.dims,dataType:Ks(k.dataType)})),kernelId:o,kernelType:a,kernelName:l,programName:c,startTime:_,endTime:y});else{let k="";p.forEach((v,I)=>{k+=`input[${I}]: [${v.dims}] | ${Ks(v.dataType)}, `});let w="";d.forEach((v,I)=>{w+=`output[${I}]: [${v.dims}] | ${Ks(v.dataType)}, `}),console.log(`[profiling] kernel "${o}|${a}|${l}|${c}" ${k}${w}execution time: ${y-_} ns`)}Yo("GPU",`${c}::${u}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),us()}run(e,r,t,s,n,o){Ts(e.name);let i=[];for(let v=0;vI):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let d=[],u=[];for(let v=0;v=o)throw new Error(`Invalid output index: ${p[v]}`);if(p[v]===-3)continue;let I=p[v]===-1,T=p[v]===-2,b=I||T?n(a[v].dataType,a[v].dims):s(p[v],a[v].dataType,a[v].dims);if(d.push(b),b.data===0)continue;let E=this.gpuDataManager.get(b.data);if(!E)throw new Error(`no GPU data for output: ${b.data}`);if(I&&this.temporaryData.push(E),T){let x=this.kernelPersistentData.get(this.currentKernelId);x||(x=[],this.kernelPersistentData.set(this.currentKernelId,x)),x.push(E)}u.push(E)}if(i.length!==r.length||u.length!==d.length){if(u.length===0)return us(e.name),d;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let f;if(c){let v=0,I=[];c.forEach(x=>{let S=typeof x.data=="number"?[x.data]:x.data;if(S.length===0)return;let O=x.type===10?2:4,F,H;x.type===10?(H=S.length>4?16:S.length>2?8:S.length*O,F=S.length>4?16:O*S.length):(H=S.length<=2?S.length*O:16,F=16),v=Math.ceil(v/H)*H,I.push(v);let W=x.type===10?8:4;v+=S.length>4?Math.ceil(S.length/W)*F:S.length*O});let T=16;v=Math.ceil(v/T)*T;let b=new ArrayBuffer(v);c.forEach((x,S)=>{let O=I[S],F=typeof x.data=="number"?[x.data]:x.data;if(x.type===6)new Int32Array(b,O,F.length).set(F);else if(x.type===12)new Uint32Array(b,O,F.length).set(F);else if(x.type===10)new Uint16Array(b,O,F.length).set(F);else if(x.type===1)new Float32Array(b,O,F.length).set(F);else throw new Error(`Unsupported uniform type: ${Ks(x.type)}`)});let E=this.gpuDataManager.create(v,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(E.buffer,0,b,0,v),this.gpuDataManager.release(E.id),f={offset:0,size:v,buffer:E.buffer}}let _=this.programManager.normalizeDispatchGroupSize(l),y=_[1]===1&&_[2]===1,k=Pw(e,r,y),w=this.programManager.getArtifact(k);if(w||(w=this.programManager.build(e,_),this.programManager.setArtifact(k,w),Dt("info",()=>`[artifact] key: ${k}, programName: ${e.name}`)),c&&w.uniformVariablesInfo){if(c.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${c.length} in program "${w.programInfo.name}".`);for(let v=0;v`[ProgramManager] run "${e.name}" (key=${k}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let v={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:r,outputTensorViews:d};this.pendingKernels.push(v),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(v)}return this.programManager.run(w,i,u,_,f),us(e.name),d}upload(e,r){this.gpuDataManager.upload(e,r)}memcpy(e,r){this.gpuDataManager.memcpy(e,r)}async download(e,r){await this.gpuDataManager.download(e,r)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,r,t,s){let n=tv.get(e);if(!n)throw new Error(`kernel not implemented: ${e}`);let o={kernelType:e,kernelName:s,kernelEntry:n[0],attributes:[n[1],t]};this.kernels.set(r,o)}releaseKernel(e){let r=this.kernelPersistentData.get(e);if(r){for(let t of r)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,r,t){let s=this.kernels.get(e);if(!s)throw new Error(`kernel not created: ${e}`);let n=s.kernelType,o=s.kernelName,i=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${n}] ${o}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),Dt("info",()=>`[WebGPU] Start to run kernel "[${n}] ${o}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(r,a[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${n}] ${o}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${n}] ${o}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let n=this.sessionExternalDataMapping.get(e);n||(n=new Map,this.sessionExternalDataMapping.set(e,n));let o=n.get(r),i=this.gpuDataManager.registerExternalBuffer(t,s,o);return n.set(r,[i,t]),i}unregisterBuffers(e){let r=this.sessionExternalDataMapping.get(e);r&&(r.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let r=this.gpuDataManager.get(e);if(!r)throw new Error(`no GPU data for buffer: ${e}`);return r.buffer}createDownloader(e,r,t){return async()=>{let s=await eu(this,e,r);return Eu(s.buffer,t)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Dt("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){Dt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Dt("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),t=e.length;this.pendingKernels=[];for(let s=0;s=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),ov={};uo(ov,{init:()=>av});var ni,Sw,av,t1=Ve(()=>{gt(),Hs(),Ct(),cT(),ni=class iv{constructor(r,t,s,n){this.module=r,this.dataType=t,this.data=s,this.dims=n}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=we.size(this.dims);return r===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,r)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let r=we.size(this.dims);return r===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,r)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let r=we.size(this.dims);return r===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,r)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let r=we.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(we.size(r)!==we.size(this.dims))throw new Error("Invalid new shape");return new iv(this.module,this.dataType,this.data,r)}},Sw=class{constructor(e,r,t){this.module=e,this.backend=r,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=r.adapterInfo;let s=e.PTR_SIZE,n=t/e.PTR_SIZE,o=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*n++,o));let i=Number(e.getValue(s*n++,o));this.outputCount=Number(e.getValue(s*n++,o)),this.customDataOffset=Number(e.getValue(s*n++,"*")),this.customDataSize=Number(e.getValue(s*n++,o));let a=[];for(let l=0;ltypeof i=="number"?this.inputs[i]:i)??this.inputs,s=r?.outputs??[],n=(i,a,l)=>new ni(this.module,a,this.output(i,l),l),o=(i,a)=>{let l=Sn(i,a);if(!l)throw new Error(`Unsupported data type: ${i}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new ni(this.module,i,c,a)};return this.backend.run(e,t,s,n,o,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,n=s===4?"i32":"i64",o=this.module.stackAlloc((1+r.length)*s);this.module.setValue(o,r.length,n);for(let i=0;i{let n=r.jsepInit;if(!n)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let o=(e1(),Jo(sv)).WebGpuBackend,i=new o;await i.initialize(t,s),n("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,c,p=!1)=>{if(p)Dt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(c)}`),i.memcpy(Number(a),Number(l));else{Dt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(c)}`);let d=r.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(c));i.upload(Number(l),d)}},async(a,l,c)=>{Dt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${c}`),await i.download(Number(a),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+c)>>>0))},(a,l,c)=>i.createKernel(a,Number(l),c,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,c,p)=>{Dt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${a}, contextDataOffset=${l}`);let d=new Sw(r,i,Number(l));return i.computeKernel(Number(a),d,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let o=new gb(t);n("webnn",[o,()=>o.reserveTensorId(),i=>o.releaseTensorId(i),async(i,a,l,c,p)=>o.ensureTensor(i,a,l,c,p),(i,a)=>{o.uploadTensor(i,a)},async(i,a)=>o.downloadTensor(i,a)])}}}),Iw,Lu,zu,on,$w,Wc,gi,Bu,Ru,Gc,Nu,ju,Vu,lv=Ve(()=>{aT(),iT(),gt(),Fn(),wu(),db(),Iw=(e,r)=>{Qt()._OrtInit(e,r)!==0&&Gt("Can't initialize onnxruntime.")},Lu=async e=>{Iw(e.wasm.numThreads,pi(e.logLevel))},zu=async(e,r)=>{Qt().asyncInit?.();{let t=(t1(),Jo(ov)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let s=e.webgpu.adapter;if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw new Error(`Invalid powerPreference setting: "${n}"`);let o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:o}),!s)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await t("webgpu",Qt(),e,s)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await t("webnn",Qt(),e)}}},on=new Map,$w=e=>{let r=Qt(),t=r.stackSave();try{let s=r.PTR_SIZE,n=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,n,n+s)!==0&&Gt("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(r.getValue(n,o)),Number(r.getValue(n+s,o))]}finally{r.stackRestore(t)}},Wc=(e,r)=>{let t=Qt(),s=t.stackSave(),n=0;try{let o=t.PTR_SIZE,i=t.stackAlloc(2*o);t._OrtGetInputOutputMetadata(e,r,i,i+o)!==0&&Gt("Can't get session input/output metadata.");let a=Number(t.getValue(i,"*"));n=Number(t.getValue(i+o,"*"));let l=t.HEAP32[n/4];if(l===0)return[a,0];let c=t.HEAPU32[n/4+1],p=[];for(let d=0;d{let r=Qt(),t=r._malloc(e.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return r.HEAPU8.set(e,t),[t,e.byteLength]},Bu=async(e,r)=>{let t,s,n=Qt();Array.isArray(e)?[t,s]=e:e.buffer===n.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=gi(e);let o=0,i=0,a=0,l=[],c=[],p=[];try{if([i,l]=await ub(r),r?.externalData&&n.mountExternalData){let T=[];for(let b of r.externalData){let E=typeof b=="string"?b:b.path;T.push(xu(typeof b=="string"?b:b.data).then(x=>{n.mountExternalData(E,x)}))}await Promise.all(T)}for(let T of r?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof T!="string"){let b=T,E=b?.context,x=b?.gpuDevice,S=b?.deviceType,O=b?.powerPreference;E?n.currentContext=E:x?n.currentContext=await n.webnnCreateMLContext(x):n.currentContext=await n.webnnCreateMLContext({deviceType:S,powerPreference:O})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(t,s,i),n.webgpuOnCreateSession?.(o),o===0&&Gt("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[d,u]=$w(o),f=!!r?.enableGraphCapture,_=[],y=[],k=[],w=[],v=[];for(let T=0;TT==="gpu-buffer"||T==="ml-tensor")&&(a=n._OrtCreateBinding(o),a===0&&Gt("Can't create IO binding."),I={handle:a,outputPreferredLocations:v,outputPreferredLocationsEncoded:v.map(T=>Yc(T))}),on.set(o,[o,c,p,I,f,!1]),[o,_,y,k,w]}catch(d){throw c.forEach(u=>n._OrtFree(u)),p.forEach(u=>n._OrtFree(u)),a!==0&&n._OrtReleaseBinding(a)!==0&&Gt("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Gt("Can't release session."),d}finally{n._free(t),i!==0&&n._OrtReleaseSessionOptions(i)!==0&&Gt("Can't release session options."),l.forEach(d=>n._free(d)),n.unmountExternalData?.()}},Ru=e=>{let r=Qt(),t=on.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,n,o,i,a]=t;i&&(a&&r._OrtClearBoundOutputs(i.handle)!==0&&Gt("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&Gt("Can't release IO binding.")),r.jsepOnReleaseSession?.(e),r.webnnOnReleaseSession?.(e),r.webgpuOnReleaseSession?.(e),n.forEach(l=>r._OrtFree(l)),o.forEach(l=>r._OrtFree(l)),r._OrtReleaseSession(s)!==0&&Gt("Can't release session."),on.delete(e)},Gc=async(e,r,t,s,n,o,i=!1)=>{if(!e){r.push(0);return}let a=Qt(),l=a.PTR_SIZE,c=e[0],p=e[1],d=e[3],u=d,f,_;if(c==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let w=e[2].gpuBuffer;_=Sn(no(c),p);{let v=a.jsepRegisterBuffer;if(!v)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');f=v(s,o,w,_)}}else if(d==="ml-tensor"){let w=e[2].mlTensor;_=Sn(no(c),p);let v=a.webnnRegisterMLTensor;if(!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');f=v(s,w,no(c),p)}else{let w=e[2];if(Array.isArray(w)){_=l*w.length,f=a._malloc(_),t.push(f);for(let v=0;va.setValue(k+I*l,v,l===4?"i32":"i64"));let w=a._OrtCreateTensor(no(c),f,_,k,p.length,Yc(u));w===0&&Gt(`Can't create tensor for input/output. session=${s}, index=${o}.`),r.push(w)}finally{a.stackRestore(y)}},Nu=async(e,r,t,s,n,o)=>{let i=Qt(),a=i.PTR_SIZE,l=on.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],p=l[1],d=l[2],u=l[3],f=l[4],_=l[5],y=r.length,k=s.length,w=0,v=[],I=[],T=[],b=[],E=i.stackSave(),x=i.stackAlloc(y*a),S=i.stackAlloc(y*a),O=i.stackAlloc(k*a),F=i.stackAlloc(k*a);try{[w,v]=cb(o);for(let B=0;BAe*Ie,1);ne=Ks(oe);let he=u?.outputPreferredLocations[s[B]];if(ne==="string"){if(he==="gpu-buffer"||he==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ae=[];for(let Ie=0;Ie0){let Ae=i.jsepGetBuffer;if(!Ae)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ie=Ae(le),je=Sn(oe,te);if(je===void 0||!yu(ne))throw new Error(`Unsupported data type: ${ne}`);re=!0,W.push([ne,D,{gpuBuffer:Ie,download:i.jsepCreateDownloader(Ie,je,ne),dispose:()=>{i._OrtReleaseTensor(Y)!==0&&Gt("Can't release tensor.")}},"gpu-buffer"])}else if(he==="ml-tensor"&&te>0){let Ae=i.webnnEnsureTensor,Ie=i.webnnIsInt64Supported;if(!Ae||!Ie)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Sn(oe,te)===void 0||!vu(ne))throw new Error(`Unsupported data type: ${ne}`);if(ne==="int64"&&!Ie(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let je=await Ae(e,le,oe,D,!1);re=!0,W.push([ne,D,{mlTensor:je,download:i.webnnCreateMLTensorDownloader(le,ne),dispose:()=>{i.webnnReleaseTensorId(le),i._OrtReleaseTensor(Y)}},"ml-tensor"])}else{let Ae=bu(ne),Ie=new Ae(te);new Uint8Array(Ie.buffer,Ie.byteOffset,Ie.byteLength).set(i.HEAPU8.subarray(le,le+Ie.byteLength)),W.push([ne,D,Ie,"cpu"])}}finally{i.stackRestore(X),ne==="string"&&le&&i._free(le),re||i._OrtReleaseTensor(Y),i.webnnOnRunEnd?.(c)}}return u&&!f&&(i._OrtClearBoundOutputs(u.handle)!==0&&Gt("Can't clear bound outputs."),on.set(e,[c,p,d,u,f,!1])),W}finally{i.stackRestore(E),I.forEach(H=>i._OrtReleaseTensor(H)),T.forEach(H=>i._OrtReleaseTensor(H)),b.forEach(H=>i._free(H)),w!==0&&i._OrtReleaseRunOptions(w),v.forEach(H=>i._free(H))}},ju=e=>{let r=Qt(),t=on.get(e);if(!t)throw new Error("invalid session id");let s=t[0],n=r._OrtEndProfiling(s);n===0&&Gt("Can't get an profile file name."),r._OrtFree(n)},Vu=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),an,as,ro,Wo,Go,oi,Kc,ai,Tn,En,kw,cv,uv,dv,pv,mv,hv,_v,fv=Ve(()=>{Es(),lv(),Fn(),gu(),an=()=>!!Jt.wasm.proxy&&typeof document<"u",ro=!1,Wo=!1,Go=!1,ai=new Map,Tn=(e,r)=>{let t=ai.get(e);t?t.push(r):ai.set(e,[r])},En=()=>{if(ro||!Wo||Go||!as)throw new Error("worker not ready")},kw=e=>{switch(e.data.type){case"init-wasm":ro=!1,e.data.err?(Go=!0,Kc[1](e.data.err)):(Wo=!0,Kc[0]()),oi&&(URL.revokeObjectURL(oi),oi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=ai.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},cv=async()=>{if(!Wo){if(ro)throw new Error("multiple calls to 'initWasm()' detected.");if(Go)throw new Error("previous call to 'initWasm()' failed.");if(ro=!0,an())return new Promise((e,r)=>{as?.terminate(),ib().then(([t,s])=>{try{as=s,as.onerror=o=>r(o),as.onmessage=kw,Kc=[e,r];let n={type:"init-wasm",in:Jt};!n.in.wasm.wasmPaths&&(t||Jc)&&(n.in.wasm.wasmPaths={wasm:new URL(""+new URL("ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href,import.meta.url).href}),as.postMessage(n),oi=t}catch(n){r(n)}},r)});try{await Mu(Jt.wasm),await Lu(Jt),Wo=!0}catch(e){throw Go=!0,e}finally{ro=!1}}},uv=async e=>{if(an())return En(),new Promise((r,t)=>{Tn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Jt}};as.postMessage(s)});await zu(Jt,e)},dv=async e=>an()?(En(),new Promise((r,t)=>{Tn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};as.postMessage(s,[e.buffer])})):gi(e),pv=async(e,r)=>{if(an()){if(r?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return En(),new Promise((t,s)=>{Tn("create",[t,s]);let n={type:"create",in:{model:e,options:{...r}}},o=[];e instanceof Uint8Array&&o.push(e.buffer),as.postMessage(n,o)})}else return Bu(e,r)},mv=async e=>{if(an())return En(),new Promise((r,t)=>{Tn("release",[r,t]);let s={type:"release",in:e};as.postMessage(s)});Ru(e)},hv=async(e,r,t,s,n,o)=>{if(an()){if(t.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return En(),new Promise((i,a)=>{Tn("run",[i,a]);let l=t,c={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:o}};as.postMessage(c,Vu(l))})}else return Nu(e,r,t,s,n,o)},_v=async e=>{if(an())return En(),new Promise((r,t)=>{Tn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};as.postMessage(s)});ju(e)}}),Hc,Aw,gv,r1=Ve(()=>{Es(),fv(),gt(),fu(),db(),Hc=(e,r)=>{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 ${r()}`)}},Aw=e=>{switch(e[3]){case"cpu":return new ys(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!yu(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:n}=e[2];return ys.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:n})}case"ml-tensor":{let r=e[0];if(!vu(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:n}=e[2];return ys.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},gv=class{async fetchModelAndCopyToWasmMemory(e){return dv(await xu(e))}async loadModel(e,r){Ts();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await pv(t,r),us()}async dispose(){return mv(this.sessionId)}async run(e,r,t){Ts();let s=[],n=[];Object.entries(e).forEach(d=>{let u=d[0],f=d[1],_=this.inputNames.indexOf(u);if(_===-1)throw new Error(`invalid input '${u}'`);s.push(f),n.push(_)});let o=[],i=[];Object.entries(r).forEach(d=>{let u=d[0],f=d[1],_=this.outputNames.indexOf(u);if(_===-1)throw new Error(`invalid output '${u}'`);o.push(f),i.push(_)});let a=s.map((d,u)=>Hc(d,()=>`input "${this.inputNames[n[u]]}"`)),l=o.map((d,u)=>d?Hc(d,()=>`output "${this.outputNames[i[u]]}"`):null),c=await hv(this.sessionId,n,a,i,l,t),p={};for(let d=0;dpu,initializeFlags:()=>du,wasmBackend:()=>wv});var du,pu,wv,s1=Ve(()=>{Es(),fv(),r1(),du=()=>{(typeof Jt.wasm.initTimeout!="number"||Jt.wasm.initTimeout<0)&&(Jt.wasm.initTimeout=0);let e=Jt.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.`),Jt.wasm.simd=!1),typeof Jt.wasm.proxy!="boolean"&&(Jt.wasm.proxy=!1),typeof Jt.wasm.trace!="boolean"&&(Jt.wasm.trace=!1),typeof Jt.wasm.numThreads!="number"||!Number.isInteger(Jt.wasm.numThreads)||Jt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Jt.wasm.numThreads=1;else{let r=typeof navigator>"u"?Ux("node:os").cpus().length:navigator.hardwareConcurrency;Jt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},pu=class{async init(e){du(),await cv(),await uv(e)}async createInferenceSessionHandler(e,r){let t=new gv;return await t.loadModel(e,r),t}},wv=new pu});Es();Es();Es();var n1="1.22.0-dev.20250409-89f8206ba4",o1=tb;{let e=(s1(),Jo(Mv)).wasmBackend;In("webgpu",e,5),In("webnn",e,5),In("cpu",e,10),In("wasm",e,10)}Object.defineProperty(Jt.versions,"web",{value:n1,enumerable:!0});var a1=Object.freeze({__proto__:null,get InferenceSession(){return _u},get TRACE(){return Yo},get TRACE_FUNC_BEGIN(){return Ts},get TRACE_FUNC_END(){return us},get Tensor(){return ys},default:o1,get env(){return Jt},get registerBackend(){return In}}),qc={},i1={"onnxruntime-common":(e=>{e.exports=Rx}),"onnxruntime-web":(e=>{e.exports=a1}),"?2ce3":(()=>{}),"?7992":(()=>{}),"?5af5":(()=>{}),"?2b25":(()=>{}),"?db59":(()=>{}),"?383f":(()=>{}),"?fa4b":(()=>{}),"./node_modules/@huggingface/jinja/dist/index.js":((e,r,t)=>{t.r(r),t.d(r,{Environment:()=>ot,Interpreter:()=>gr,Template:()=>Ss,parse:()=>Ae,tokenize:()=>d});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),n=class{constructor(C,q){this.value=C,this.type=q}};function o(C){return/\w/.test(C)}function i(C){return/[0-9]/.test(C)}function a(C){return/\s/.test(C)}var l=[["{%",s.OpenStatement],["%}",s.CloseStatement],["{{",s.OpenExpression],["}}",s.CloseExpression],["(",s.OpenParen],[")",s.CloseParen],["{",s.OpenCurlyBracket],["}",s.CloseCurlyBracket],["[",s.OpenSquareBracket],["]",s.CloseSquareBracket],[",",s.Comma],[".",s.Dot],[":",s.Colon],["|",s.Pipe],["<=",s.ComparisonBinaryOperator],[">=",s.ComparisonBinaryOperator],["==",s.ComparisonBinaryOperator],["!=",s.ComparisonBinaryOperator],["<",s.ComparisonBinaryOperator],[">",s.ComparisonBinaryOperator],["+",s.AdditiveBinaryOperator],["-",s.AdditiveBinaryOperator],["~",s.AdditiveBinaryOperator],["*",s.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],c=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function p(C,q={}){return C.endsWith(` +`)&&(C=C.slice(0,-1)),q.lstrip_blocks&&(C=C.replace(/^[ \t]*({[#%-])/gm,"$1")),q.trim_blocks&&(C=C.replace(/([#%-]})\n/g,"$1")),C.replace(/{%\s*(end)?generation\s*%}/gs,"")}function d(C,q={}){const R=[],G=p(C,q);let Z=0,ce=0;const ye=He=>{let Mt="";for(;He(G[Z]);){if(G[Z]==="\\"){if(++Z,Z>=G.length)throw new SyntaxError("Unexpected end of input");const qe=G[Z++],Tt=c.get(qe);if(Tt===void 0)throw new SyntaxError(`Unexpected escaped character: ${qe}`);Mt+=Tt;continue}if(Mt+=G[Z++],Z>=G.length)throw new SyntaxError("Unexpected end of input")}return Mt},et=()=>{const He=R.at(-1);He&&He.type===s.Text&&(He.value=He.value.trimEnd(),He.value===""&&R.pop())},ut=()=>{for(;Z0){R.push(new n(qe,s.Text));continue}}if(G[Z]==="{"&&G[Z+1]==="#"){Z+=2;const qe=G[Z]==="-";qe&&++Z;let Tt="";for(;G[Z]!=="#"||G[Z+1]!=="}";){if(Z+2>=G.length)throw new SyntaxError("Missing end of comment tag");Tt+=G[Z++]}const kt=Tt.endsWith("-");kt&&(Tt=Tt.slice(0,-1)),qe&&et(),R.push(new n(Tt,s.Comment)),Z+=2,kt&&ut();continue}if(G.slice(Z,Z+3)==="{%-"){et(),R.push(new n("{%",s.OpenStatement)),Z+=3;continue}if(G.slice(Z,Z+3)==="{{-"){et(),R.push(new n("{{",s.OpenExpression)),ce=0,Z+=3;continue}if(ye(a),G.slice(Z,Z+3)==="-%}"){R.push(new n("%}",s.CloseStatement)),Z+=3,ut();continue}if(G.slice(Z,Z+3)==="-}}"){R.push(new n("}}",s.CloseExpression)),Z+=3,ut();continue}const Mt=G[Z];if(Mt==="-"||Mt==="+"){const qe=R.at(-1)?.type;if(qe===s.Text||qe===void 0)throw new SyntaxError(`Unexpected character: ${Mt}`);switch(qe){case s.Identifier:case s.NumericLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++Z;const Tt=ye(i);R.push(new n(`${Mt}${Tt}`,Tt.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[qe,Tt]of l){if(qe==="}}"&&ce>0)continue;if(G.slice(Z,Z+qe.length)===qe){R.push(new n(qe,Tt)),Tt===s.OpenExpression?ce=0:Tt===s.OpenCurlyBracket?++ce:Tt===s.CloseCurlyBracket&&--ce,Z+=qe.length;continue e}}if(Mt==="'"||Mt==='"'){++Z;const qe=ye(Tt=>Tt!==Mt);R.push(new n(qe,s.StringLiteral)),++Z;continue}if(i(Mt)){let qe=ye(i);if(G[Z]==="."&&i(G[Z+1])){++Z;const Tt=ye(i);qe=`${qe}.${Tt}`}R.push(new n(qe,s.NumericLiteral));continue}if(o(Mt)){const qe=ye(o);R.push(new n(qe,s.Identifier));continue}throw new SyntaxError(`Unexpected character: ${Mt}`)}return R}var u=class{type="Statement"},f=class extends u{constructor(C){super(),this.body=C}type="Program"},_=class extends u{constructor(C,q,R){super(),this.test=C,this.body=q,this.alternate=R}type="If"},y=class extends u{constructor(C,q,R,G){super(),this.loopvar=C,this.iterable=q,this.body=R,this.defaultBlock=G}type="For"},k=class extends u{type="Break"},w=class extends u{type="Continue"},v=class extends u{constructor(C,q,R){super(),this.assignee=C,this.value=q,this.body=R}type="Set"},I=class extends u{constructor(C,q,R){super(),this.name=C,this.args=q,this.body=R}type="Macro"},T=class extends u{constructor(C){super(),this.value=C}type="Comment"},b=class extends u{type="Expression"},E=class extends b{constructor(C,q,R){super(),this.object=C,this.property=q,this.computed=R}type="MemberExpression"},x=class extends b{constructor(C,q){super(),this.callee=C,this.args=q}type="CallExpression"},S=class extends b{constructor(C){super(),this.value=C}type="Identifier"},O=class extends b{constructor(C){super(),this.value=C}type="Literal"},F=class extends O{type="IntegerLiteral"},H=class extends O{type="FloatLiteral"},W=class extends O{type="StringLiteral"},B=class extends O{type="ArrayLiteral"},Y=class extends O{type="TupleLiteral"},X=class extends O{type="ObjectLiteral"},J=class extends b{constructor(C,q,R){super(),this.operator=C,this.left=q,this.right=R}type="BinaryExpression"},re=class extends b{constructor(C,q){super(),this.operand=C,this.filter=q}type="FilterExpression"},ne=class extends u{constructor(C,q){super(),this.filter=C,this.body=q}type="FilterStatement"},le=class extends b{constructor(C,q){super(),this.lhs=C,this.test=q}type="SelectExpression"},pe=class extends b{constructor(C,q,R){super(),this.operand=C,this.negate=q,this.test=R}type="TestExpression"},oe=class extends b{constructor(C,q){super(),this.operator=C,this.argument=q}type="UnaryExpression"},K=class extends b{constructor(C=void 0,q=void 0,R=void 0){super(),this.start=C,this.stop=q,this.step=R}type="SliceExpression"},N=class extends b{constructor(C,q){super(),this.key=C,this.value=q}type="KeywordArgumentExpression"},D=class extends b{constructor(C){super(),this.argument=C}type="SpreadExpression"},te=class extends u{constructor(C,q,R){super(),this.call=C,this.callerArgs=q,this.body=R}type="CallStatement"},he=class extends b{constructor(C,q,R){super(),this.condition=C,this.trueExpr=q,this.falseExpr=R}type="Ternary"};function Ae(C){const q=new f([]);let R=0;function G(ze,Ue){const nt=C[R++];if(!nt||nt.type!==ze)throw new Error(`Parser Error: ${Ue}. ${nt.type} !== ${ze}.`);return nt}function Z(ze){if(!ut(ze))throw new SyntaxError(`Expected ${ze}`);++R}function ce(){switch(C[R].type){case s.Comment:return new T(C[R++].value);case s.Text:return He();case s.OpenStatement:return Mt();case s.OpenExpression:return qe();default:throw new SyntaxError(`Unexpected token type: ${C[R].type}`)}}function ye(...ze){return R+ze.length<=C.length&&ze.every((Ue,nt)=>Ue===C[R+nt].type)}function et(...ze){return C[R]?.type===s.OpenStatement&&C[R+1]?.type===s.Identifier&&ze.includes(C[R+1]?.value)}function ut(...ze){return R+ze.length<=C.length&&ze.every((Ue,nt)=>C[R+nt].type==="Identifier"&&Ue===C[R+nt].value)}function He(){return new W(G(s.Text,"Expected text token").value)}function Mt(){if(G(s.OpenStatement,"Expected opening statement token"),C[R].type!==s.Identifier)throw new SyntaxError(`Unknown statement, got ${C[R].type}`);const ze=C[R].value;let Ue;switch(ze){case"set":++R,Ue=Tt();break;case"if":++R,Ue=kt(),G(s.OpenStatement,"Expected {% token"),Z("endif"),G(s.CloseStatement,"Expected %} token");break;case"macro":++R,Ue=Mr(),G(s.OpenStatement,"Expected {% token"),Z("endmacro"),G(s.CloseStatement,"Expected %} token");break;case"for":++R,Ue=ar(),G(s.OpenStatement,"Expected {% token"),Z("endfor"),G(s.CloseStatement,"Expected %} token");break;case"call":{++R;let nt=null;ye(s.OpenParen)&&(nt=Hr());const Kt=Nr();if(Kt.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const Ns=Hr();G(s.CloseStatement,"Expected closing statement token");const Os=[];for(;!et("endcall");)Os.push(ce());G(s.OpenStatement,"Expected '{%'"),Z("endcall"),G(s.CloseStatement,"Expected closing statement token");const js=new x(Kt,Ns);Ue=new te(js,nt,Os);break}case"break":++R,G(s.CloseStatement,"Expected closing statement token"),Ue=new k;break;case"continue":++R,G(s.CloseStatement,"Expected closing statement token"),Ue=new w;break;case"filter":{++R;let nt=Nr();nt instanceof S&&ye(s.OpenParen)&&(nt=ir(nt)),G(s.CloseStatement,"Expected closing statement token");const Kt=[];for(;!et("endfilter");)Kt.push(ce());G(s.OpenStatement,"Expected '{%'"),Z("endfilter"),G(s.CloseStatement,"Expected '%}'"),Ue=new ne(nt,Kt);break}default:throw new SyntaxError(`Unknown statement type: ${ze}`)}return Ue}function qe(){G(s.OpenExpression,"Expected opening expression token");const ze=Tr();return G(s.CloseExpression,"Expected closing expression token"),ze}function Tt(){const ze=dr();let Ue=null;const nt=[];if(ye(s.Equals))++R,Ue=dr();else{for(G(s.CloseStatement,"Expected %} token");!et("endset");)nt.push(ce());G(s.OpenStatement,"Expected {% token"),Z("endset")}return G(s.CloseStatement,"Expected closing statement token"),new v(ze,Ue,nt)}function kt(){const ze=Tr();G(s.CloseStatement,"Expected closing statement token");const Ue=[],nt=[];for(;!et("elif","else","endif");)Ue.push(ce());if(et("elif")){++R,++R;const Kt=kt();nt.push(Kt)}else if(et("else"))for(++R,++R,G(s.CloseStatement,"Expected closing statement token");!et("endif");)nt.push(ce());return new _(ze,Ue,nt)}function Mr(){const ze=Nr();if(ze.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Ue=Hr();G(s.CloseStatement,"Expected closing statement token");const nt=[];for(;!et("endmacro");)nt.push(ce());return new I(ze,Ue,nt)}function dr(ze=!1){const Ue=ze?Nr:Tr,nt=[Ue()],Kt=ye(s.Comma);for(;Kt&&(++R,nt.push(Ue()),!!ye(s.Comma)););return Kt?new Y(nt):nt[0]}function ar(){const ze=dr(!0);if(!(ze instanceof S||ze instanceof Y))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${ze.type} instead`);if(!ut("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++R;const Ue=Tr();G(s.CloseStatement,"Expected closing statement token");const nt=[];for(;!et("endfor","else");)nt.push(ce());const Kt=[];if(et("else"))for(++R,++R,G(s.CloseStatement,"Expected closing statement token");!et("endfor");)Kt.push(ce());return new y(ze,Ue,nt,Kt)}function Tr(){return Is()}function Is(){const ze=Dr();if(ut("if")){++R;const Ue=Dr();if(ut("else")){++R;const nt=Is();return new he(Ue,ze,nt)}else return new le(ze,Ue)}return ze}function Dr(){let ze=$s();for(;ut("or");){const Ue=C[R];++R;const nt=$s();ze=new J(Ue,ze,nt)}return ze}function $s(){let ze=Lr();for(;ut("and");){const Ue=C[R];++R;const nt=Lr();ze=new J(Ue,ze,nt)}return ze}function Lr(){let ze;for(;ut("not");){const Ue=C[R];++R;const nt=Lr();ze=new oe(Ue,nt)}return ze??zr()}function zr(){let ze=ts();for(;;){let Ue;if(ut("not","in"))Ue=new n("not in",s.Identifier),R+=2;else if(ut("in"))Ue=C[R++];else if(ye(s.ComparisonBinaryOperator))Ue=C[R++];else break;const nt=ts();ze=new J(Ue,ze,nt)}return ze}function ts(){let ze=As();for(;ye(s.AdditiveBinaryOperator);){const Ue=C[R];++R;const nt=As();ze=new J(Ue,ze,nt)}return ze}function wr(){const ze=ks(Nr());return ye(s.OpenParen)?ir(ze):ze}function ir(ze){let Ue=new x(ze,Hr());return Ue=ks(Ue),ye(s.OpenParen)&&(Ue=ir(Ue)),Ue}function Hr(){G(s.OpenParen,"Expected opening parenthesis for arguments list");const ze=rs();return G(s.CloseParen,"Expected closing parenthesis for arguments list"),ze}function rs(){const ze=[];for(;!ye(s.CloseParen);){let Ue;if(C[R].type===s.MultiplicativeBinaryOperator&&C[R].value==="*"){++R;const nt=Tr();Ue=new D(nt)}else if(Ue=Tr(),ye(s.Equals)){if(++R,!(Ue instanceof S))throw new SyntaxError("Expected identifier for keyword argument");const nt=Tr();Ue=new N(Ue,nt)}ze.push(Ue),ye(s.Comma)&&++R}return ze}function Rs(){const ze=[];let Ue=!1;for(;!ye(s.CloseSquareBracket);)ye(s.Colon)?(ze.push(void 0),++R,Ue=!0):(ze.push(Tr()),ye(s.Colon)&&(++R,Ue=!0));if(ze.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Ue){if(ze.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new K(...ze)}return ze[0]}function ks(ze){for(;ye(s.Dot)||ye(s.OpenSquareBracket);){const Ue=C[R];++R;let nt;const Kt=Ue.type===s.OpenSquareBracket;if(Kt)nt=Rs(),G(s.CloseSquareBracket,"Expected closing square bracket");else if(nt=Nr(),nt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");ze=new E(ze,nt,Kt)}return ze}function As(){let ze=Fs();for(;ye(s.MultiplicativeBinaryOperator);){const Ue=C[R++],nt=Fs();ze=new J(Ue,ze,nt)}return ze}function Fs(){let ze=ss();for(;ut("is");){++R;const Ue=ut("not");Ue&&++R;const nt=Nr();if(!(nt instanceof S))throw new SyntaxError("Expected identifier for the test");ze=new pe(ze,Ue,nt)}return ze}function ss(){let ze=wr();for(;ye(s.Pipe);){++R;let Ue=Nr();if(!(Ue instanceof S))throw new SyntaxError("Expected identifier for the filter");ye(s.OpenParen)&&(Ue=ir(Ue)),ze=new re(ze,Ue)}return ze}function Nr(){const ze=C[R++];switch(ze.type){case s.NumericLiteral:{const Ue=ze.value;return Ue.includes(".")?new H(Number(Ue)):new F(Number(Ue))}case s.StringLiteral:{let Ue=ze.value;for(;ye(s.StringLiteral);)Ue+=C[R++].value;return new W(Ue)}case s.Identifier:return new S(ze.value);case s.OpenParen:{const Ue=dr();return G(s.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),Ue}case s.OpenSquareBracket:{const Ue=[];for(;!ye(s.CloseSquareBracket);)Ue.push(Tr()),ye(s.Comma)&&++R;return++R,new B(Ue)}case s.OpenCurlyBracket:{const Ue=new Map;for(;!ye(s.CloseCurlyBracket);){const nt=Tr();G(s.Colon,"Expected colon between key and value in object literal");const Kt=Tr();Ue.set(nt,Kt),ye(s.Comma)&&++R}return++R,new X(Ue)}default:throw new SyntaxError(`Unexpected token: ${ze.type}`)}}for(;R=0?(q=(q??=0)<0?Math.max(C.length+q,0):Math.min(q,C.length),R=(R??=C.length)<0?Math.max(C.length+R,0):Math.min(R,C.length)):(q=(q??=C.length-1)<0?Math.max(C.length+q,-1):Math.min(q,C.length-1),R=(R??=-1)<-1?Math.max(C.length+R,-1):Math.min(R,C.length-1));const ce=[];for(let ye=q;Z*yeq.toUpperCase())}function Q(C){return z(new Date,C)}function z(C,q){const R=new Intl.DateTimeFormat(void 0,{month:"long"}),G=new Intl.DateTimeFormat(void 0,{month:"short"}),Z=ce=>ce<10?"0"+ce:ce.toString();return q.replace(/%[YmdbBHM%]/g,ce=>{switch(ce){case"%Y":return C.getFullYear().toString();case"%m":return Z(C.getMonth()+1);case"%d":return Z(C.getDate());case"%b":return G.format(C);case"%B":return R.format(C);case"%H":return Z(C.getHours());case"%M":return Z(C.getMinutes());case"%%":return"%";default:return ce}})}function de(C){return C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function be(C,q,R,G){if(G===0)return C;let Z=G==null||G<0?1/0:G;const ce=q.length===0?new RegExp("(?=)","gu"):new RegExp(de(q),"gu");return C.replaceAll(ce,ye=>Z>0?(--Z,R):ye)}var ve=class extends Error{},xe=class extends Error{},Ce=class{type="RuntimeValue";value;builtins=new Map;constructor(C=void 0){this.value=C}__bool__(){return new Ee(!!this.value)}toString(){return String(this.value)}},ge=class extends Ce{type="IntegerValue"},De=class extends Ce{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},fe=class extends Ce{type="StringValue";builtins=new Map([["upper",new Ze(()=>new fe(this.value.toUpperCase()))],["lower",new Ze(()=>new fe(this.value.toLowerCase()))],["strip",new Ze(()=>new fe(this.value.trim()))],["title",new Ze(()=>new fe(Te(this.value)))],["capitalize",new Ze(()=>new fe(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new ge(this.value.length)],["rstrip",new Ze(()=>new fe(this.value.trimEnd()))],["lstrip",new Ze(()=>new fe(this.value.trimStart()))],["startswith",new Ze(C=>{if(C.length===0)throw new Error("startswith() requires at least one argument");const q=C[0];if(q instanceof fe)return new Ee(this.value.startsWith(q.value));if(q instanceof Re){for(const R of q.value){if(!(R instanceof fe))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(R.value))return new Ee(!0)}return new Ee(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Ze(C=>{if(C.length===0)throw new Error("endswith() requires at least one argument");const q=C[0];if(q instanceof fe)return new Ee(this.value.endsWith(q.value));if(q instanceof Re){for(const R of q.value){if(!(R instanceof fe))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(R.value))return new Ee(!0)}return new Ee(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Ze(C=>{const q=C[0]??new Ne;if(!(q instanceof fe||q instanceof Ne))throw new Error("sep argument must be a string or null");const R=C[1]??new ge(-1);if(!(R instanceof ge))throw new Error("maxsplit argument must be a number");let G=[];if(q instanceof Ne){const Z=this.value.trimStart();for(const{0:ce,index:ye}of Z.matchAll(/\S+/g)){if(R.value!==-1&&G.length>=R.value&&ye!==void 0){G.push(ce+Z.slice(ye+ce.length));break}G.push(ce)}}else{if(q.value==="")throw new Error("empty separator");G=this.value.split(q.value),R.value!==-1&&G.length>R.value&&G.push(G.splice(R.value).join(q.value))}return new Re(G.map(Z=>new fe(Z)))})],["replace",new Ze(C=>{if(C.length<2)throw new Error("replace() requires at least two arguments");const q=C[0],R=C[1];if(!(q instanceof fe&&R instanceof fe))throw new Error("replace() arguments must be strings");let G;if(C.length>2?C[2].type==="KeywordArgumentsValue"?G=C[2].value.get("count")??new Ne:G=C[2]:G=new Ne,!(G instanceof ge||G instanceof Ne))throw new Error("replace() count argument must be a number or null");return new fe(be(this.value,q.value,R.value,G.value))})]])},Ee=class extends Ce{type="BooleanValue"};function We(C,q,R,G=!0){const Z=R??0;switch(C.type){case"NullValue":return"null";case"UndefinedValue":return G?"null":"undefined";case"IntegerValue":case"FloatValue":case"StringValue":case"BooleanValue":return JSON.stringify(C.value);case"ArrayValue":case"ObjectValue":{const ce=q?" ".repeat(q):"",ye=` +`+ce.repeat(Z),et=ye+ce;if(C.type==="ArrayValue"){const ut=C.value.map(He=>We(He,q,Z+1,G));return q?`[${et}${ut.join(`,${et}`)}${ye}]`:`[${ut.join(", ")}]`}else{const ut=Array.from(C.value.entries()).map(([He,Mt])=>{const qe=`"${He}": ${We(Mt,q,Z+1,G)}`;return q?`${et}${qe}`:qe});return q?`{${ut.join(",")}${ye}}`:`{${ut.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${C.type}`)}}var Fe=class extends Ce{type="ObjectValue";__bool__(){return new Ee(this.value.size>0)}builtins=new Map([["get",new Ze(([C,q])=>{if(!(C instanceof fe))throw new Error(`Object key must be a string: got ${C.type}`);return this.value.get(C.value)??q??new Ne})],["items",new Ze(()=>this.items())],["keys",new Ze(()=>this.keys())],["values",new Ze(()=>this.values())],["dictsort",new Ze(C=>{let q=new Map;const R=C.filter(et=>et instanceof tt?(q=et.value,!1):!0),G=R.at(0)??q.get("case_sensitive")??new Ee(!1);if(!(G instanceof Ee))throw new Error("case_sensitive must be a boolean");const Z=R.at(1)??q.get("by")??new fe("key");if(!(Z instanceof fe))throw new Error("by must be a string");if(!["key","value"].includes(Z.value))throw new Error("by must be either 'key' or 'value'");const ce=R.at(2)??q.get("reverse")??new Ee(!1);if(!(ce instanceof Ee))throw new Error("reverse must be a boolean");const ye=Array.from(this.value.entries()).map(([et,ut])=>new Re([new fe(et),ut])).sort((et,ut)=>{const He=Z.value==="key"?0:1,Mt=et.value[He],qe=ut.value[He],Tt=It(Mt,qe,G.value);return ce.value?-Tt:Tt});return new Re(ye)})]]);items(){return new Re(Array.from(this.value.entries()).map(([C,q])=>new Re([new fe(C),q])))}keys(){return new Re(Array.from(this.value.keys()).map(C=>new fe(C)))}values(){return new Re(Array.from(this.value.values()))}toString(){return We(this,null,0,!1)}},tt=class extends Fe{type="KeywordArgumentsValue"},Re=class extends Ce{type="ArrayValue";builtins=new Map([["length",new ge(this.value.length)]]);__bool__(){return new Ee(this.value.length>0)}toString(){return We(this,null,0,!1)}},rt=class extends Re{type="TupleValue"},Ze=class extends Ce{type="FunctionValue"},Ne=class extends Ce{type="NullValue"},Oe=class extends Ce{type="UndefinedValue"},ot=class{constructor(C){this.parent=C}variables=new Map([["namespace",new Ze(C=>{if(C.length===0)return new Fe(new Map);if(C.length!==1||!(C[0]instanceof Fe))throw new Error("`namespace` expects either zero arguments or a single object argument");return C[0]})]]);tests=new Map([["boolean",C=>C.type==="BooleanValue"],["callable",C=>C instanceof Ze],["odd",C=>{if(!(C instanceof ge))throw new Error(`cannot odd on ${C.type}`);return C.value%2!==0}],["even",C=>{if(!(C instanceof ge))throw new Error(`cannot even on ${C.type}`);return C.value%2===0}],["false",C=>C.type==="BooleanValue"&&!C.value],["true",C=>C.type==="BooleanValue"&&C.value],["none",C=>C.type==="NullValue"],["string",C=>C.type==="StringValue"],["number",C=>C instanceof ge||C instanceof De],["integer",C=>C instanceof ge],["iterable",C=>C.type==="ArrayValue"||C.type==="StringValue"],["mapping",C=>C.type==="ObjectValue"],["lower",C=>{const q=C.value;return C.type==="StringValue"&&q===q.toLowerCase()}],["upper",C=>{const q=C.value;return C.type==="StringValue"&&q===q.toUpperCase()}],["none",C=>C.type==="NullValue"],["defined",C=>C.type!=="UndefinedValue"],["undefined",C=>C.type==="UndefinedValue"],["equalto",(C,q)=>C.value===q.value],["eq",(C,q)=>C.value===q.value]]);set(C,q){return this.declareVariable(C,Or(q))}declareVariable(C,q){if(this.variables.has(C))throw new SyntaxError(`Variable already declared: ${C}`);return this.variables.set(C,q),q}setVariable(C,q){return this.variables.set(C,q),q}resolve(C){if(this.variables.has(C))return this;if(this.parent)return this.parent.resolve(C);throw new Error(`Unknown variable: ${C}`)}lookupVariable(C){try{return this.resolve(C).variables.get(C)??new Oe}catch{return new Oe}}};function ht(C){C.set("false",!1),C.set("true",!0),C.set("none",null),C.set("raise_exception",q=>{throw new Error(q)}),C.set("range",Ie),C.set("strftime_now",Q),C.set("True",!0),C.set("False",!1),C.set("None",null)}function Rt(C,q){const R=q.split(".");let G=C;for(const Z of R)if(G instanceof Fe)G=G.value.get(Z)??new Oe;else if(G instanceof Re){const ce=parseInt(Z,10);if(!isNaN(ce)&&ce>=0&&cece instanceof ge||ce instanceof De||ce instanceof Ee,Z=ce=>ce instanceof Ee?ce.value?1:0:ce.value;if(G(C)&&G(q)){const ce=Z(C),ye=Z(q);return ceye?1:0}if(C.type!==q.type)throw new Error(`Cannot compare different types: ${C.type} and ${q.type}`);if(C.type==="StringValue"){let ce=C.value,ye=q.value;return R||(ce=ce.toLowerCase(),ye=ye.toLowerCase()),ceye?1:0}else throw new Error(`Cannot compare type: ${C.type}`)}var gr=class{global;constructor(C){this.global=C??new ot}run(C){return this.evaluate(C,this.global)}evaluateBinaryExpression(C,q){const R=this.evaluate(C.left,q);switch(C.operator.value){case"and":return R.__bool__().value?this.evaluate(C.right,q):R;case"or":return R.__bool__().value?R:this.evaluate(C.right,q)}const G=this.evaluate(C.right,q);switch(C.operator.value){case"==":return new Ee(R.value==G.value);case"!=":return new Ee(R.value!=G.value)}if(R instanceof Oe||G instanceof Oe){if(G instanceof Oe&&["in","not in"].includes(C.operator.value))return new Ee(C.operator.value==="not in");throw new Error(`Cannot perform operation ${C.operator.value} on undefined values`)}else{if(R instanceof Ne||G instanceof Ne)throw new Error("Cannot perform operation on null values");if(C.operator.value==="~")return new fe(R.value.toString()+G.value.toString());if((R instanceof ge||R instanceof De)&&(G instanceof ge||G instanceof De)){const Z=R.value,ce=G.value;switch(C.operator.value){case"+":case"-":case"*":{const ye=C.operator.value==="+"?Z+ce:C.operator.value==="-"?Z-ce:Z*ce;return R instanceof De||G instanceof De?new De(ye):new ge(ye)}case"/":return new De(Z/ce);case"%":{const ye=Z%ce;return R instanceof De||G instanceof De?new De(ye):new ge(ye)}case"<":return new Ee(Z":return new Ee(Z>ce);case">=":return new Ee(Z>=ce);case"<=":return new Ee(Z<=ce)}}else if(R instanceof Re&&G instanceof Re){if(C.operator.value==="+")return new Re(R.value.concat(G.value))}else if(G instanceof Re){const Z=G.value.find(ce=>ce.value===R.value)!==void 0;switch(C.operator.value){case"in":return new Ee(Z);case"not in":return new Ee(!Z)}}}if((R instanceof fe||G instanceof fe)&&C.operator.value==="+")return new fe(R.value.toString()+G.value.toString());if(R instanceof fe&&G instanceof fe)switch(C.operator.value){case"in":return new Ee(G.value.includes(R.value));case"not in":return new Ee(!G.value.includes(R.value))}if(R instanceof fe&&G instanceof Fe)switch(C.operator.value){case"in":return new Ee(G.value.has(R.value));case"not in":return new Ee(!G.value.has(R.value))}throw new SyntaxError(`Unknown operator "${C.operator.value}" between ${R.type} and ${G.type}`)}evaluateArguments(C,q){const R=[],G=new Map;for(const Z of C)if(Z.type==="SpreadExpression"){const ce=Z,ye=this.evaluate(ce.argument,q);if(!(ye instanceof Re))throw new Error(`Cannot unpack non-iterable type: ${ye.type}`);for(const et of ye.value)R.push(et)}else if(Z.type==="KeywordArgumentExpression"){const ce=Z;G.set(ce.key.value,this.evaluate(ce.value,q))}else{if(G.size>0)throw new Error("Positional arguments must come before keyword arguments");R.push(this.evaluate(Z,q))}return[R,G]}applyFilter(C,q,R){if(q.type==="Identifier"){const G=q;if(G.value==="tojson")return new fe(We(C));if(C instanceof Re)switch(G.value){case"list":return C;case"first":return C.value[0];case"last":return C.value[C.value.length-1];case"length":return new ge(C.value.length);case"reverse":return new Re(C.value.slice().reverse());case"sort":return new Re(C.value.slice().sort((Z,ce)=>It(Z,ce,!1)));case"join":return new fe(C.value.map(Z=>Z.value).join(""));case"string":return new fe(We(C,null,0,!1));case"unique":{const Z=new Set,ce=[];for(const ye of C.value)Z.has(ye.value)||(Z.add(ye.value),ce.push(ye));return new Re(ce)}default:throw new Error(`Unknown ArrayValue filter: ${G.value}`)}else if(C instanceof fe)switch(G.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const Z=C.builtins.get(G.value);if(Z instanceof Ze)return Z.value([],R);if(Z instanceof ge)return Z;throw new Error(`Unknown StringValue filter: ${G.value}`)}case"trim":return new fe(C.value.trim());case"indent":return new fe(C.value.split(` +`).map((Z,ce)=>ce===0||Z.length===0?Z:" "+Z).join(` +`));case"join":case"string":return C;case"int":{const Z=parseInt(C.value,10);return new ge(isNaN(Z)?0:Z)}case"float":{const Z=parseFloat(C.value);return new De(isNaN(Z)?0:Z)}default:throw new Error(`Unknown StringValue filter: ${G.value}`)}else if(C instanceof ge||C instanceof De)switch(G.value){case"abs":return C instanceof ge?new ge(Math.abs(C.value)):new De(Math.abs(C.value));case"int":return new ge(Math.floor(C.value));case"float":return new De(C.value);default:throw new Error(`Unknown NumericValue filter: ${G.value}`)}else if(C instanceof Fe)switch(G.value){case"items":return new Re(Array.from(C.value.entries()).map(([Z,ce])=>new Re([new fe(Z),ce])));case"length":return new ge(C.value.size);default:{const Z=C.builtins.get(G.value);if(Z)return Z instanceof Ze?Z.value([],R):Z;throw new Error(`Unknown ObjectValue filter: ${G.value}`)}}else if(C instanceof Ee)switch(G.value){case"bool":return new Ee(C.value);case"int":return new ge(C.value?1:0);case"float":return new De(C.value?1:0);case"string":return new fe(C.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${G.value}`)}throw new Error(`Cannot apply filter "${G.value}" to type: ${C.type}`)}else if(q.type==="CallExpression"){const G=q;if(G.callee.type!=="Identifier")throw new Error(`Unknown filter: ${G.callee.type}`);const Z=G.callee.value;if(Z==="tojson"){const[,ce]=this.evaluateArguments(G.args,R),ye=ce.get("indent")??new Ne;if(!(ye instanceof ge||ye instanceof Ne))throw new Error("If set, indent must be a number");return new fe(We(C,ye.value))}else if(Z==="join"){let ce;if(C instanceof fe)ce=Array.from(C.value);else if(C instanceof Re)ce=C.value.map(He=>He.value);else throw new Error(`Cannot apply filter "${Z}" to type: ${C.type}`);const[ye,et]=this.evaluateArguments(G.args,R),ut=ye.at(0)??et.get("separator")??new fe("");if(!(ut instanceof fe))throw new Error("separator must be a string");return new fe(ce.join(ut.value))}else if(Z==="int"||Z==="float"){const[ce,ye]=this.evaluateArguments(G.args,R),et=ce.at(0)??ye.get("default")??(Z==="int"?new ge(0):new De(0));if(C instanceof fe){const ut=Z==="int"?parseInt(C.value,10):parseFloat(C.value);return isNaN(ut)?et:Z==="int"?new ge(ut):new De(ut)}else{if(C instanceof ge||C instanceof De)return C;if(C instanceof Ee)return Z==="int"?new ge(C.value?1:0):new De(C.value?1:0);throw new Error(`Cannot apply filter "${Z}" to type: ${C.type}`)}}else if(Z==="default"){const[ce,ye]=this.evaluateArguments(G.args,R),et=ce[0]??new fe(""),ut=ce[1]??ye.get("boolean")??new Ee(!1);if(!(ut instanceof Ee))throw new Error("`default` filter flag must be a boolean");return C instanceof Oe||ut.value&&!C.__bool__().value?et:C}if(C instanceof Re){switch(Z){case"sort":{const[ce,ye]=this.evaluateArguments(G.args,R),et=ce.at(0)??ye.get("reverse")??new Ee(!1);if(!(et instanceof Ee))throw new Error("reverse must be a boolean");const ut=ce.at(1)??ye.get("case_sensitive")??new Ee(!1);if(!(ut instanceof Ee))throw new Error("case_sensitive must be a boolean");const He=ce.at(2)??ye.get("attribute")??new Ne;if(!(He instanceof fe||He instanceof ge||He instanceof Ne))throw new Error("attribute must be a string, integer, or null");const Mt=qe=>{if(He instanceof Ne)return qe;const Tt=He instanceof ge?String(He.value):He.value;return Rt(qe,Tt)};return new Re(C.value.slice().sort((qe,Tt)=>{const kt=Mt(qe),Mr=Mt(Tt),dr=It(kt,Mr,ut.value);return et.value?-dr:dr}))}case"selectattr":case"rejectattr":{const ce=Z==="selectattr";if(C.value.some(qe=>!(qe instanceof Fe)))throw new Error(`\`${Z}\` can only be applied to array of objects`);if(G.args.some(qe=>qe.type!=="StringLiteral"))throw new Error(`arguments of \`${Z}\` must be strings`);const[ye,et,ut]=G.args.map(qe=>this.evaluate(qe,R));let He;if(et){const qe=R.tests.get(et.value);if(!qe)throw new Error(`Unknown test: ${et.value}`);He=qe}else He=(...qe)=>qe[0].__bool__().value;const Mt=C.value.filter(qe=>{const Tt=qe.value.get(ye.value),kt=Tt?He(Tt,ut):!1;return ce?kt:!kt});return new Re(Mt)}case"map":{const[,ce]=this.evaluateArguments(G.args,R);if(ce.has("attribute")){const ye=ce.get("attribute");if(!(ye instanceof fe))throw new Error("attribute must be a string");const et=ce.get("default"),ut=C.value.map(He=>{if(!(He instanceof Fe))throw new Error("items in map must be an object");const Mt=Rt(He,ye.value);return Mt instanceof Oe?et??new Oe:Mt});return new Re(ut)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${Z}`)}else if(C instanceof fe){switch(Z){case"indent":{const[ce,ye]=this.evaluateArguments(G.args,R),et=ce.at(0)??ye.get("width")??new ge(4);if(!(et instanceof ge))throw new Error("width must be a number");const ut=ce.at(1)??ye.get("first")??new Ee(!1),He=ce.at(2)??ye.get("blank")??new Ee(!1),Mt=C.value.split(` +`),qe=" ".repeat(et.value),Tt=Mt.map((kt,Mr)=>!ut.value&&Mr===0||!He.value&&kt.length===0?kt:qe+kt);return new fe(Tt.join(` +`))}case"replace":{const ce=C.builtins.get("replace");if(!(ce instanceof Ze))throw new Error("replace filter not available");const[ye,et]=this.evaluateArguments(G.args,R);return ce.value([...ye,new tt(et)],R)}}throw new Error(`Unknown StringValue filter: ${Z}`)}else if(C instanceof Fe){const ce=C.builtins.get(Z);if(ce&&ce instanceof Ze){const[ye,et]=this.evaluateArguments(G.args,R);return et.size>0&&ye.push(new tt(et)),ce.value(ye,R)}throw new Error(`Unknown ObjectValue filter: ${Z}`)}else throw new Error(`Cannot apply filter "${Z}" to type: ${C.type}`)}throw new Error(`Unknown filter: ${q.type}`)}evaluateFilterExpression(C,q){const R=this.evaluate(C.operand,q);return this.applyFilter(R,C.filter,q)}evaluateTestExpression(C,q){const R=this.evaluate(C.operand,q),G=q.tests.get(C.test.value);if(!G)throw new Error(`Unknown test: ${C.test.value}`);const Z=G(R);return new Ee(C.negate?!Z:Z)}evaluateSelectExpression(C,q){return this.evaluate(C.test,q).__bool__().value?this.evaluate(C.lhs,q):new Oe}evaluateUnaryExpression(C,q){const R=this.evaluate(C.argument,q);if(C.operator.value==="not")return new Ee(!R.value);throw new SyntaxError(`Unknown operator: ${C.operator.value}`)}evaluateTernaryExpression(C,q){return this.evaluate(C.condition,q).__bool__().value?this.evaluate(C.trueExpr,q):this.evaluate(C.falseExpr,q)}evalProgram(C,q){return this.evaluateBlock(C.body,q)}evaluateBlock(C,q){let R="";for(const G of C){const Z=this.evaluate(G,q);Z.type!=="NullValue"&&Z.type!=="UndefinedValue"&&(R+=Z.toString())}return new fe(R)}evaluateIdentifier(C,q){return q.lookupVariable(C.value)}evaluateCallExpression(C,q){const[R,G]=this.evaluateArguments(C.args,q);G.size>0&&R.push(new tt(G));const Z=this.evaluate(C.callee,q);if(Z.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${Z.type}`);return Z.value(R,q)}evaluateSliceExpression(C,q,R){if(!(C instanceof Re||C instanceof fe))throw new Error("Slice object must be an array or string");const G=this.evaluate(q.start,R),Z=this.evaluate(q.stop,R),ce=this.evaluate(q.step,R);if(!(G instanceof ge||G instanceof Oe))throw new Error("Slice start must be numeric or undefined");if(!(Z instanceof ge||Z instanceof Oe))throw new Error("Slice stop must be numeric or undefined");if(!(ce instanceof ge||ce instanceof Oe))throw new Error("Slice step must be numeric or undefined");return C instanceof Re?new Re(je(C.value,G.value,Z.value,ce.value)):new fe(je(Array.from(C.value),G.value,Z.value,ce.value).join(""))}evaluateMemberExpression(C,q){const R=this.evaluate(C.object,q);let G;if(C.computed){if(C.property.type==="SliceExpression")return this.evaluateSliceExpression(R,C.property,q);G=this.evaluate(C.property,q)}else G=new fe(C.property.value);let Z;if(R instanceof Fe){if(!(G instanceof fe))throw new Error(`Cannot access property with non-string: got ${G.type}`);Z=R.value.get(G.value)??R.builtins.get(G.value)}else if(R instanceof Re||R instanceof fe)if(G instanceof ge)Z=R.value.at(G.value),R instanceof fe&&(Z=new fe(R.value.at(G.value)));else if(G instanceof fe)Z=R.builtins.get(G.value);else throw new Error(`Cannot access property with non-string/non-number: got ${G.type}`);else{if(!(G instanceof fe))throw new Error(`Cannot access property with non-string: got ${G.type}`);Z=R.builtins.get(G.value)}return Z instanceof Ce?Z:new Oe}evaluateSet(C,q){const R=C.value?this.evaluate(C.value,q):this.evaluateBlock(C.body,q);if(C.assignee.type==="Identifier"){const G=C.assignee.value;q.setVariable(G,R)}else if(C.assignee.type==="TupleLiteral"){const G=C.assignee;if(!(R instanceof Re))throw new Error(`Cannot unpack non-iterable type in set: ${R.type}`);const Z=R.value;if(Z.length!==G.value.length)throw new Error(`Too ${G.value.length>Z.length?"few":"many"} items to unpack in set`);for(let ce=0;cekt.setVariable(C.loopvar.value,qe);else if(C.loopvar.type==="TupleLiteral"){const kt=C.loopvar;if(qe.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${qe.type}`);const Mr=qe;if(kt.value.length!==Mr.value.length)throw new Error(`Too ${kt.value.length>Mr.value.length?"few":"many"} items to unpack`);Tt=dr=>{for(let ar=0;ar0?ce[He-1]:new Oe],["nextitem",He{const Z=new ot(G);R=R.slice();let ce;R.at(-1)?.type==="KeywordArgumentsValue"&&(ce=R.pop());for(let ye=0;ye{const He=new ot(ut);if(C.callerArgs)for(let Mt=0;Mtthis.evaluate(R,q)));case"TupleLiteral":return new rt(C.value.map(R=>this.evaluate(R,q)));case"ObjectLiteral":{const R=new Map;for(const[G,Z]of C.value){const ce=this.evaluate(G,q);if(!(ce instanceof fe))throw new Error(`Object keys must be strings: got ${ce.type}`);R.set(ce.value,this.evaluate(Z,q))}return new Fe(R)}case"Identifier":return this.evaluateIdentifier(C,q);case"CallExpression":return this.evaluateCallExpression(C,q);case"MemberExpression":return this.evaluateMemberExpression(C,q);case"UnaryExpression":return this.evaluateUnaryExpression(C,q);case"BinaryExpression":return this.evaluateBinaryExpression(C,q);case"FilterExpression":return this.evaluateFilterExpression(C,q);case"FilterStatement":return this.evaluateFilterStatement(C,q);case"TestExpression":return this.evaluateTestExpression(C,q);case"SelectExpression":return this.evaluateSelectExpression(C,q);case"Ternary":return this.evaluateTernaryExpression(C,q);case"Comment":return new Ne;default:throw new SyntaxError(`Unknown node type: ${C.type}`)}}};function Or(C){switch(typeof C){case"number":return Number.isInteger(C)?new ge(C):new De(C);case"string":return new fe(C);case"boolean":return new Ee(C);case"undefined":return new Oe;case"object":return C===null?new Ne:Array.isArray(C)?new Re(C.map(Or)):new Fe(new Map(Object.entries(C).map(([q,R])=>[q,Or(R)])));case"function":return new Ze((q,R)=>{const G=C(...q.map(Z=>Z.value))??null;return Or(G)});default:throw new Error(`Cannot convert to runtime value: ${C}`)}}var zt=` +`,Rr="{%- ",qs=" -%}";function Qs(C){switch(C.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return C.operator.value==="and"?1:C.operator.value==="in"||C.operator.value==="not in"?2:0}return 0}function Xs(C,q=" "){const R=typeof q=="number"?" ".repeat(q):q;return Sr(C.body,0,R).replace(/\n$/,"")}function or(...C){return Rr+C.join(" ")+qs}function Sr(C,q,R){return C.map(G=>Qr(G,q,R)).join(zt)}function Qr(C,q,R){const G=R.repeat(q);switch(C.type){case"Program":return Sr(C.body,q,R);case"If":return Bs(C,q,R);case"For":return ft(C,q,R);case"Set":return qt(C,q,R);case"Macro":return Ps(C,q,R);case"Break":return G+or("break");case"Continue":return G+or("continue");case"CallStatement":return Cs(C,q,R);case"FilterStatement":return Kr(C,q,R);case"Comment":return G+"{# "+C.value+" #}";default:return G+"{{- "+yt(C)+" -}}"}}function Bs(C,q,R){const G=R.repeat(q),Z=[];let ce=C;for(;ce&&(Z.push({test:ce.test,body:ce.body}),ce.alternate.length===1&&ce.alternate[0].type==="If");)ce=ce.alternate[0];let ye=G+or("if",yt(Z[0].test))+zt+Sr(Z[0].body,q+1,R);for(let et=1;et0&&(ye+=zt+G+or("else")+zt+Sr(ce.alternate,q+1,R)),ye+=zt+G+or("endif"),ye}function ft(C,q,R){const G=R.repeat(q);let Z="";if(C.iterable.type==="SelectExpression"){const ye=C.iterable;Z=`${yt(ye.lhs)} if ${yt(ye.test)}`}else Z=yt(C.iterable);let ce=G+or("for",yt(C.loopvar),"in",Z)+zt+Sr(C.body,q+1,R);return C.defaultBlock.length>0&&(ce+=zt+G+or("else")+zt+Sr(C.defaultBlock,q+1,R)),ce+=zt+G+or("endfor"),ce}function qt(C,q,R){const G=R.repeat(q),Z=yt(C.assignee),ce=C.value?yt(C.value):"",ye=G+or("set",`${Z}${C.value?" = "+ce:""}`);return C.body.length===0?ye:ye+zt+Sr(C.body,q+1,R)+zt+G+or("endset")}function Ps(C,q,R){const G=R.repeat(q),Z=C.args.map(yt).join(", ");return G+or("macro",`${C.name.value}(${Z})`)+zt+Sr(C.body,q+1,R)+zt+G+or("endmacro")}function Cs(C,q,R){const G=R.repeat(q),Z=C.callerArgs&&C.callerArgs.length>0?`(${C.callerArgs.map(yt).join(", ")})`:"",ce=yt(C.call);let ye=G+or(`call${Z}`,ce)+zt;return ye+=Sr(C.body,q+1,R)+zt,ye+=G+or("endcall"),ye}function Kr(C,q,R){const G=R.repeat(q),Z=C.filter.type==="Identifier"?C.filter.value:yt(C.filter);let ce=G+or("filter",Z)+zt;return ce+=Sr(C.body,q+1,R)+zt,ce+=G+or("endfilter"),ce}function yt(C,q=-1){switch(C.type){case"SpreadExpression":return`*${yt(C.argument)}`;case"Identifier":return C.value;case"IntegerLiteral":return`${C.value}`;case"FloatLiteral":return`${C.value}`;case"StringLiteral":return JSON.stringify(C.value);case"BinaryExpression":{const R=C,G=Qs(R),Z=yt(R.left,G),ce=yt(R.right,G+1),ye=`${Z} ${R.operator.value} ${ce}`;return G`${yt(G)}: ${yt(Z)}`).join(", ")}}`;case"SliceExpression":{const R=C,G=R.start?yt(R.start):"",Z=R.stop?yt(R.stop):"",ce=R.step?`:${yt(R.step)}`:"";return`${G}:${Z}${ce}`}case"KeywordArgumentExpression":{const R=C;return`${R.key.value}=${yt(R.value)}`}case"Ternary":{const R=C,G=`${yt(R.trueExpr)} if ${yt(R.condition,0)} else ${yt(R.falseExpr)}`;return q>-1?`(${G})`:G}default:throw new Error(`Unknown expression type: ${C.type}`)}}var Ss=class{parsed;constructor(C){const q=d(C,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Ae(q)}render(C){const q=new ot;if(ht(q),C)for(const[Z,ce]of Object.entries(C))q.set(Z,ce);return new gr(q).run(this.parsed).value}format(C){return Xs(this.parsed,C?.indent||" ")}}}),"./src/backends/onnx.js":((e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>k,deviceToExecutionProviders:()=>_,isONNXProxy:()=>E,isONNXTensor:()=>T,runInferenceSession:()=>I});var n=t("./src/env.js"),o=t("?2ce3"),i=t("onnxruntime-web"),a=t("onnxruntime-common");const l=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),c=[];let p,d;const u=Symbol.for("onnxruntime");if(u in globalThis)d=globalThis[u];else if(n.apis.IS_NODE_ENV){switch(d=o??(s||(s=t.t(o,2))),process.platform){case"win32":c.push("dml");break;case"linux":process.arch==="x64"&&c.push("cuda");break}c.push("cpu"),p=["cpu"]}else d=i,n.apis.IS_WEBNN_AVAILABLE&&c.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),n.apis.IS_WEBGPU_AVAILABLE&&c.push("webgpu"),c.push("wasm"),p=["wasm"];const f=d.InferenceSession;function _(x=null){if(!x)return p;switch(x){case"auto":return c;case"gpu":return c.filter(S=>["webgpu","cuda","dml","webnn-gpu"].includes(S))}if(c.includes(x))return[l[x]??x];throw new Error(`Unsupported device: "${x}". Should be one of: ${c.join(", ")}.`)}let y=null;async function k(x,S,O){y&&await y;const F=f.create(x,S);y??=F;const H=await F;return H.config=O,H}let w=Promise.resolve();const v=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;async function I(x,S){const O=()=>x.run(S);return await(v?w=w.then(O):O())}function T(x){return x instanceof d.Tensor}const b=d?.env;b?.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!b.wasm.wasmPaths&&(b.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${n.env.version}/dist/`),b.wasm.proxy=!1),b?.webgpu&&(b.webgpu.powerPreference="high-performance");function E(){return b?.wasm?.proxy}n.env.backends.onnx=b}),"./src/base/feature_extraction_utils.js":((e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>i,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),n=t("./src/utils/generic.js"),o=t("./src/utils/hub.js");class i extends n.Callable{constructor(c){super(),this.config=c}static async from_pretrained(c,p={}){const d=await(0,o.getModelJSON)(c,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(d)}}function a(l,c){if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${c} expects input to be a Float32Array or a Float64Array, but got ${l?.constructor?.name??typeof l} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}}),"./src/base/image_processors_utils.js":((e,r,t)=>{t.r(r),t.d(r,{ImageProcessor:()=>T,center_to_corners_format:()=>d,post_process_instance_segmentation:()=>I,post_process_object_detection:()=>u,post_process_panoptic_segmentation:()=>v,post_process_semantic_segmentation:()=>f});var s=t("./src/utils/generic.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");t("./src/utils/image.js");var i=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function c(b,E,x=0,S=null){const O=b/E;let F=(0,o.bankers_round)(O)*E;return S!==null&&F>S&&(F=Math.floor(O)*E),FE&&K.push(D)}else{let D=(0,o.max)(oe.data)[1];if(D===B-1||(N=(0,o.softmax)(oe.data),N[D]he*J[(Ae+1)%2])),re.boxes.push(te),re.classes.push(D),re.scores.push(N[D])}}Y.push(re)}return Y}function f(b,E=null){const x=b.logits,S=x.dims[0];if(E!==null&&E.length!==S)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const O=[];for(let F=0;FJ[K]&&(J[K]=oe[K],re[K]=pe)}const ne=new Array(W.dims[0]);for(let pe=0;pepe!==void 0);O.push({segmentation:X,labels:le})}return O}function _(b,E,x,S){const O=[],F=[],H=[];for(let W=0;Wx&&(O.push(Y),F.push(re),H.push(X))}return[O,F,H]}function y(b,E,x,S=.5,O=.8){const F=[];let H=0,W=0;const B=E[x].data;for(let X=0;X=S&&++W;let Y=H>0&&W>0;return Y&&(Y=H/W>O),[Y,F]}function k(b,E,x,S,O,F=null,H=null){const[W,B]=H??b[0].dims,Y=new n.Tensor("int32",new Int32Array(W*B),[W,B]),X=[];if(H!==null)for(let pe=0;pere[N]&&(J[N]=pe,re[N]=K[N])}let ne=0;const le=Y.data;for(let pe=0;pe200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(b,E)/Math.min(b,E)}`);let F=Math.round(b/x)*x,H=Math.round(E/x)*x;if(F*H>O){const W=Math.sqrt(b*E/O);F=Math.floor(b/W/x)*x,H=Math.floor(E/W/x)*x}else if(F*HF?Y=Math.floor(F*B/O):F>O&&(B=Math.floor(O*Y/F)),await E.resize(Y,B,{resample:S}))}async crop_margin(E,x=200){const S=E.clone().grayscale(),O=(0,o.min)(S.data)[0],H=(0,o.max)(S.data)[0]-O;if(H===0)return E;const W=x/255;let B=S.width,Y=S.height,X=0,J=0;const re=S.data;for(let ne=0;nethis.preprocess(F)));return{pixel_values:(0,n.stack)(S.map(F=>F.pixel_values),0),original_sizes:S.map(F=>F.original_size),reshaped_input_sizes:S.map(F=>F.reshaped_input_size)}}static async from_pretrained(E,x={}){const S=await(0,a.getModelJSON)(E,l.IMAGE_PROCESSOR_NAME,!0,x);return new this(S)}}}),"./src/base/processing_utils.js":((e,r,t)=>{t.r(r),t.d(r,{Processor:()=>i});var s=t("./src/utils/constants.js"),n=t("./src/utils/generic.js"),o=t("./src/utils/hub.js");class i extends n.Callable{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(l,c,p){super(),this.config=l,this.components=c,this.chat_template=p}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(l,c={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,chat_template:this.chat_template??void 0,...c})}batch_decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...l)}decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...l)}async _call(l,...c){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...c);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,c={}){const[p,d,u]=await Promise.all([this.uses_processor_config?(0,o.getModelJSON)(l,s.PROCESSOR_NAME,!0,c):{},Promise.all(this.classes.filter(f=>f in this).map(async f=>{const _=await this[f].from_pretrained(l,c);return[f.replace(/_class$/,""),_]})).then(Object.fromEntries),this.uses_chat_template_file?(0,o.getModelText)(l,s.CHAT_TEMPLATE_NAME,!0,c):null]);return new this(p,d,u)}}}),"./src/configs.js":((e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>p,PretrainedConfig:()=>c,getCacheShapes:()=>a});var s=t("./src/utils/core.js"),n=t("./src/utils/hub.js");async function o(d,u){return await(0,n.getModelJSON)(d,"config.json",!0,u)}function i(d){const u={};let f={};switch(d.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"voxtral":case"smolvlm":case"gemma3n":case"mistral3":f=i(d.text_config);break;case"moondream1":f=i(d.phi_config);break;case"musicgen":f=i(d.decoder);break;case"multi_modality":f=i(d.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":u.num_heads="num_attention_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size";break;case"llama":case"llama4_text":case"nanochat":case"arcee":case"lfm2":case"smollm3":case"olmo":case"olmo2":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size",u.num_attention_heads="num_attention_heads",u.dim_kv="head_dim";break;case"qwen3":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"glm":case"helium":case"ernie4_5":case"ministral":case"ministral3":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.dim_kv="head_dim";break;case"openelm":u.num_heads="num_kv_heads",u.num_layers="num_transformer_layers",u.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":u.num_heads="num_heads",u.num_layers="num_layers",u.hidden_size="hidden_size";break;case"bloom":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="hidden_size";break;case"mpt":u.num_heads="n_heads",u.num_layers="n_layers",u.hidden_size="d_model";break;case"exaone":u.num_heads="num_key_value_heads",u.num_layers="num_layers",u.dim_kv="head_dim",u.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":u.num_decoder_layers="num_decoder_layers",u.num_decoder_heads="num_heads",u.decoder_dim_kv="d_kv",u.num_encoder_layers="num_layers",u.num_encoder_heads="num_heads",u.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="d_model",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="d_model";break;case"speecht5":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="hidden_size",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="hidden_size";break;case"trocr":u.num_encoder_layers=u.num_decoder_layers="decoder_layers",u.num_encoder_heads=u.num_decoder_heads="decoder_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="d_model";break;case"musicgen_decoder":u.num_encoder_layers=u.num_decoder_layers="num_hidden_layers",u.num_encoder_heads=u.num_decoder_heads="num_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"moonshine":u.num_decoder_layers="decoder_num_hidden_layers",u.num_decoder_heads="decoder_num_key_value_heads",u.num_encoder_layers="encoder_num_hidden_layers",u.num_encoder_heads="encoder_num_key_value_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const y=i(d.decoder),k="num_decoder_layers"in y,w=(0,s.pick)(d,["model_type","is_encoder_decoder"]);return k?(w.num_decoder_layers=y.num_decoder_layers,w.num_decoder_heads=y.num_decoder_heads,w.decoder_hidden_size=y.decoder_hidden_size,w.num_encoder_layers=y.num_encoder_layers,w.num_encoder_heads=y.num_encoder_heads,w.encoder_hidden_size=y.encoder_hidden_size):(w.num_layers=y.num_layers,w.num_heads=y.num_heads,w.hidden_size=y.hidden_size),w}const _={...f,...(0,s.pick)(d,["model_type","multi_query","is_encoder_decoder"])};for(const y in u)_[y]=d[u[y]];return _}function a(d,u){if(d.model_type==="lfm2"){const f=u?.prefix??"past_key_values",_=f==="present"?"present":"past",y={},{layer_types:k,num_attention_heads:w,num_key_value_heads:v,hidden_size:I,conv_L_cache:T}=d,b=I/w,E=u?.batch_size??1;for(let x=0;x{t.r(r),t.d(r,{apis:()=>w,env:()=>x});var s=t("?db59"),n=t("?383f"),o=t("?fa4b");const i="3.8.1",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),c=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,d=typeof navigator<"u"&&"ml"in navigator,u=typeof process<"u",f=u&&process?.release?.name==="node",_=!S(s),y=!S(n),k=typeof globalThis.Deno<"u",w=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:c,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:d,IS_PROCESS_AVAILABLE:u,IS_NODE_ENV:f,IS_FS_AVAILABLE:_,IS_PATH_AVAILABLE:y}),v=_&&y;let I="./";if(v){const O=Object(import.meta).url;O?I=n.dirname(n.dirname(o.fileURLToPath(O))):typeof __dirname<"u"&&(I=n.dirname(__dirname))}const T=v?n.join(I,"/.cache/"):null,b="/models/",E=v?n.join(I,b):b,x={version:i,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:E,useFS:_,useBrowserCache:c&&!k,useFSCache:_,cacheDir:T,useCustomCache:!1,customCache:null};function S(O){return Object.keys(O).length===0}}),"./src/generation/configuration_utils.js":((e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>n});var s=t("./src/utils/core.js");class n{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(i){Object.assign(this,(0,s.pick)(i,Object.getOwnPropertyNames(this)))}}}),"./src/generation/logits_process.js":((e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>w,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>c,LogitsProcessor:()=>o,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>_,MinNewTokensLengthLogitsProcessor:()=>y,NoBadWordsLogitsProcessor:()=>k,NoRepeatNGramLogitsProcessor:()=>u,RepetitionPenaltyLogitsProcessor:()=>f,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>v,TopKLogitsWarper:()=>T,TopPLogitsWarper:()=>I,WhisperTimeStampLogitsProcessor:()=>d});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var n=t("./src/utils/maths.js");class o extends s.Callable{_call(E,x){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(E,x){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(E){this.processors.push(E)}extend(E){this.processors.push(...E)}_call(E,x){let S=x;for(const O of this.processors)S=O(E,S);return S}[Symbol.iterator](){return this.processors.values()}}class l extends o{constructor(E){super(),this.bos_token_id=E}_call(E,x){for(let S=0;S=1&&F[F.length-1]>=this.timestamp_begin,W=F.length<2||F[F.length-2]>=this.timestamp_begin;if(H&&(W?O.subarray(this.timestamp_begin).fill(-1/0):O.subarray(0,this.eos_token_id).fill(-1/0)),E[S].length===this.begin_index&&this.max_initial_timestamp_index!==null){const J=this.timestamp_begin+this.max_initial_timestamp_index;O.subarray(J+1).fill(-1/0)}const B=(0,n.log_softmax)(O),Y=Math.log(B.subarray(this.timestamp_begin).map(Math.exp).reduce((J,re)=>J+re)),X=(0,n.max)(B.subarray(0,this.timestamp_begin))[0];Y>X&&O.subarray(0,this.timestamp_begin).fill(-1/0)}return x}}class u extends o{constructor(E){super(),this.no_repeat_ngram_size=E}getNgrams(E){const x=E.length,S=[];for(let F=0;F1 to use the classifier free guidance processor, got guidance scale ${E}.`);this.guidance_scale=E}_call(E,x){if(x.dims[0]!==2*E.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${x.dims[0]} for the logits and ${E.length} for the input ids.`);const S=E.length,O=x.slice([0,S],null),F=x.slice([S,x.dims[0]],null);for(let H=0;H1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${E}`);if(!Number.isInteger(S)||S<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${S}`);this.top_p=E,this.filter_value=x,this.min_tokens_to_keep=S}}class T extends i{constructor(E,{filter_value:x=-1/0,min_tokens_to_keep:S=1}={}){if(super(),!Number.isInteger(E)||E<0)throw new Error(`\`top_k\` must be a positive integer, but is ${E}`);this.top_k=Math.max(E,S),this.filter_value=x}}}),"./src/generation/logits_sampler.js":((e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>i});var s=t("./src/utils/generic.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class i extends s.Callable{constructor(d){super(),this.generation_config=d}async _call(d){return this.sample(d)}async sample(d){throw Error("sample should be implemented in subclasses.")}getLogits(d,u){let f=d.dims.at(-1),_=d.data;if(u===-1)_=_.slice(-f);else{let y=u*f;_=_.slice(y,y+f)}return _}randomSelect(d){let u=0;for(let _=0;_1)return new c(d);if(d.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${d.num_return_sequences}.`);return new a(d)}}class a extends i{async sample(d){const u=(0,o.max)(d.data)[1];return[[BigInt(u),0]]}}class l extends i{async sample(d){let u=d.dims.at(-1);this.generation_config.top_k>0&&(u=Math.min(this.generation_config.top_k,u));const[f,_]=await(0,n.topk)(d,u),y=(0,o.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},()=>{const k=this.randomSelect(y);return[_.data[k],Math.log(y[k])]})}}class c extends i{async sample(d){let u=d.dims.at(-1);this.generation_config.top_k>0&&(u=Math.min(this.generation_config.top_k,u));const[f,_]=await(0,n.topk)(d,u),y=(0,o.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},(k,w)=>[_.data[w],Math.log(y[w])])}}}),"./src/generation/stopping_criteria.js":((e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>i,StoppingCriteria:()=>n,StoppingCriteriaList:()=>o});var s=t("./src/utils/generic.js");class n extends s.Callable{_call(p,d){throw Error("StoppingCriteria needs to be subclassed")}}class o extends s.Callable{constructor(){super(),this.criteria=[]}push(p){this.criteria.push(p)}extend(p){p instanceof o?p=p.criteria:p instanceof n&&(p=[p]),this.criteria.push(...p)}_call(p,d){const u=new Array(p.length).fill(!1);for(const f of this.criteria){const _=f(p,d);for(let y=0;yd.length>=this.max_length)}}class a extends n{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,d){return p.map(u=>{const f=u.at(-1);return this.eos_token_id.some(_=>f==_)})}}class l extends n{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,d){return new Array(p.length).fill(this.interrupted)}}}),"./src/generation/streamers.js":((e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>i,TextStreamer:()=>l,WhisperTextStreamer:()=>c});var s=t("./src/utils/core.js"),n=t("./src/tokenizers.js"),o=t("./src/env.js");class i{put(d){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const a=o.apis.IS_PROCESS_AVAILABLE?p=>process.stdout.write(p):p=>console.log(p);class l extends i{constructor(d,{skip_prompt:u=!1,callback_function:f=null,token_callback_function:_=null,skip_special_tokens:y=!0,decode_kwargs:k={},...w}={}){super(),this.tokenizer=d,this.skip_prompt=u,this.callback_function=f??a,this.token_callback_function=_,this.decode_kwargs={skip_special_tokens:y,...k,...w},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(d){if(d.length>1)throw Error("TextStreamer only supports batch size of 1");const u=this.next_tokens_are_prompt;if(u&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const f=d[0];this.token_callback_function?.(f),this.token_cache=(0,s.mergeArrays)(this.token_cache,f);const _=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let y;u||_.endsWith(` +`)?(y=_.slice(this.print_len),this.token_cache=[],this.print_len=0):_.length>0&&(0,n.is_chinese_char)(_.charCodeAt(_.length-1))?(y=_.slice(this.print_len),this.print_len+=y.length):(y=_.slice(this.print_len,_.lastIndexOf(" ")+1),this.print_len+=y.length),this.on_finalized_text(y,!1)}end(){let d;this.token_cache.length>0?(d=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):d="",this.next_tokens_are_prompt=!0,this.on_finalized_text(d,!0)}on_finalized_text(d,u){d.length>0&&this.callback_function?.(d),u&&this.callback_function===a&&o.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.(` +`)}}class c extends l{constructor(d,{skip_prompt:u=!1,callback_function:f=null,token_callback_function:_=null,on_chunk_start:y=null,on_chunk_end:k=null,on_finalize:w=null,time_precision:v=.02,skip_special_tokens:I=!0,decode_kwargs:T={}}={}){super(d,{skip_prompt:u,skip_special_tokens:I,callback_function:f,token_callback_function:_,decode_kwargs:T}),this.timestamp_begin=d.timestamp_begin,this.on_chunk_start=y,this.on_chunk_end=k,this.on_finalize=w,this.time_precision=v,this.waiting_for_timestamp=!1}put(d){if(d.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const u=d[0];if(u.length===1){const f=Number(u[0])-this.timestamp_begin;if(f>=0){const _=f*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(_):this.on_chunk_start?.(_),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(u);return}}return super.put(d)}end(){super.end(),this.on_finalize?.()}}}),"./src/models.js":((e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>Mo,ASTModel:()=>go,ASTPreTrainedModel:()=>fo,AlbertForMaskedLM:()=>Ke,AlbertForQuestionAnswering:()=>Ye,AlbertForSequenceClassification:()=>Je,AlbertModel:()=>Xe,AlbertPreTrainedModel:()=>$e,ArceeForCausalLM:()=>Gu,ArceeModel:()=>Wu,ArceePreTrainedModel:()=>yi,AutoModel:()=>Bv,AutoModelForAudioClassification:()=>sx,AutoModelForAudioFrameClassification:()=>ox,AutoModelForAudioTextToText:()=>hx,AutoModelForCTC:()=>rx,AutoModelForCausalLM:()=>Gv,AutoModelForDepthEstimation:()=>cx,AutoModelForDocumentQuestionAnswering:()=>ax,AutoModelForImageClassification:()=>Qv,AutoModelForImageFeatureExtraction:()=>px,AutoModelForImageMatting:()=>ix,AutoModelForImageSegmentation:()=>Xv,AutoModelForImageTextToText:()=>mx,AutoModelForImageToImage:()=>lx,AutoModelForMaskGeneration:()=>tx,AutoModelForMaskedLM:()=>Kv,AutoModelForNormalEstimation:()=>ux,AutoModelForObjectDetection:()=>Zv,AutoModelForPoseEstimation:()=>dx,AutoModelForQuestionAnswering:()=>Hv,AutoModelForSemanticSegmentation:()=>Jv,AutoModelForSeq2SeqLM:()=>jv,AutoModelForSequenceClassification:()=>Rv,AutoModelForSpeechSeq2Seq:()=>Vv,AutoModelForTextToSpectrogram:()=>Uv,AutoModelForTextToWaveform:()=>Wv,AutoModelForTokenClassification:()=>Nv,AutoModelForUniversalSegmentation:()=>Yv,AutoModelForVision2Seq:()=>qv,AutoModelForXVector:()=>nx,AutoModelForZeroShotObjectDetection:()=>ex,BartForConditionalGeneration:()=>Yt,BartForSequenceClassification:()=>hr,BartModel:()=>ds,BartPretrainedModel:()=>Er,BaseModelOutput:()=>be,BeitForImageClassification:()=>mp,BeitModel:()=>pp,BeitPreTrainedModel:()=>el,BertForMaskedLM:()=>Ce,BertForQuestionAnswering:()=>fe,BertForSequenceClassification:()=>ge,BertForTokenClassification:()=>De,BertModel:()=>xe,BertPreTrainedModel:()=>ve,BlenderbotForConditionalGeneration:()=>_r,BlenderbotModel:()=>Zt,BlenderbotPreTrainedModel:()=>vr,BlenderbotSmallForConditionalGeneration:()=>Js,BlenderbotSmallModel:()=>Ur,BlenderbotSmallPreTrainedModel:()=>lr,BloomForCausalLM:()=>Dd,BloomModel:()=>Od,BloomPreTrainedModel:()=>Vi,CLIPModel:()=>vo,CLIPPreTrainedModel:()=>Ls,CLIPSegForImageSegmentation:()=>Co,CLIPSegModel:()=>Po,CLIPSegPreTrainedModel:()=>fn,CLIPTextModel:()=>va,CLIPTextModelWithProjection:()=>xo,CLIPVisionModel:()=>xa,CLIPVisionModelWithProjection:()=>Ta,CamembertForMaskedLM:()=>ce,CamembertForQuestionAnswering:()=>ut,CamembertForSequenceClassification:()=>ye,CamembertForTokenClassification:()=>et,CamembertModel:()=>Z,CamembertPreTrainedModel:()=>G,CausalLMOutput:()=>rn,CausalLMOutputWithPast:()=>fx,ChineseCLIPModel:()=>Eo,ChineseCLIPPreTrainedModel:()=>Ea,ClapAudioModelWithProjection:()=>$h,ClapModel:()=>Sh,ClapPreTrainedModel:()=>Oa,ClapTextModelWithProjection:()=>Ih,CodeGenForCausalLM:()=>Be,CodeGenModel:()=>Pe,CodeGenPreTrainedModel:()=>ie,CohereForCausalLM:()=>md,CohereModel:()=>pd,CoherePreTrainedModel:()=>Ai,ConvBertForMaskedLM:()=>ft,ConvBertForQuestionAnswering:()=>Cs,ConvBertForSequenceClassification:()=>qt,ConvBertForTokenClassification:()=>Ps,ConvBertModel:()=>Bs,ConvBertPreTrainedModel:()=>Qr,ConvNextForImageClassification:()=>im,ConvNextModel:()=>am,ConvNextPreTrainedModel:()=>_l,ConvNextV2ForImageClassification:()=>cm,ConvNextV2Model:()=>lm,ConvNextV2PreTrainedModel:()=>fl,DFineForObjectDetection:()=>Pp,DFineModel:()=>Ep,DFinePreTrainedModel:()=>al,DINOv3ConvNextModel:()=>gm,DINOv3ConvNextPreTrainedModel:()=>fm,DINOv3ViTModel:()=>_m,DINOv3ViTPreTrainedModel:()=>hm,DPTForDepthEstimation:()=>Vp,DPTModel:()=>jp,DPTPreTrainedModel:()=>pl,DacDecoderModel:()=>M_,DacDecoderOutput:()=>__,DacEncoderModel:()=>g_,DacEncoderOutput:()=>h_,DacModel:()=>f_,DacPreTrainedModel:()=>ja,DebertaForMaskedLM:()=>qe,DebertaForQuestionAnswering:()=>Mr,DebertaForSequenceClassification:()=>Tt,DebertaForTokenClassification:()=>kt,DebertaModel:()=>Mt,DebertaPreTrainedModel:()=>He,DebertaV2ForMaskedLM:()=>Tr,DebertaV2ForQuestionAnswering:()=>$s,DebertaV2ForSequenceClassification:()=>Is,DebertaV2ForTokenClassification:()=>Dr,DebertaV2Model:()=>ar,DebertaV2PreTrainedModel:()=>dr,DecisionTransformerModel:()=>Jh,DecisionTransformerPreTrainedModel:()=>Xh,DeiTForImageClassification:()=>kp,DeiTModel:()=>$p,DeiTPreTrainedModel:()=>ll,DepthAnythingForDepthEstimation:()=>Wp,DepthAnythingPreTrainedModel:()=>Up,DepthProForDepthEstimation:()=>Qp,DepthProPreTrainedModel:()=>qp,DetrForObjectDetection:()=>_p,DetrForSegmentation:()=>tl,DetrModel:()=>hp,DetrObjectDetectionOutput:()=>rl,DetrPreTrainedModel:()=>Ca,DetrSegmentationOutput:()=>fp,Dinov2ForImageClassification:()=>dm,Dinov2Model:()=>um,Dinov2PreTrainedModel:()=>gl,Dinov2WithRegistersForImageClassification:()=>mm,Dinov2WithRegistersModel:()=>pm,Dinov2WithRegistersPreTrainedModel:()=>Ml,DistilBertForMaskedLM:()=>Hr,DistilBertForQuestionAnswering:()=>ir,DistilBertForSequenceClassification:()=>ts,DistilBertForTokenClassification:()=>wr,DistilBertModel:()=>zr,DistilBertPreTrainedModel:()=>Lr,DonutSwinModel:()=>om,DonutSwinPreTrainedModel:()=>nm,EdgeTamModel:()=>Sm,EfficientNetForImageClassification:()=>zh,EfficientNetModel:()=>Lh,EfficientNetPreTrainedModel:()=>Al,ElectraForMaskedLM:()=>Ss,ElectraForQuestionAnswering:()=>R,ElectraForSequenceClassification:()=>C,ElectraForTokenClassification:()=>q,ElectraModel:()=>yt,ElectraPreTrainedModel:()=>Kr,Ernie4_5ForCausalLM:()=>xh,Ernie4_5Model:()=>vh,Ernie4_5PreTrainedModel:()=>Cl,EsmForMaskedLM:()=>ks,EsmForSequenceClassification:()=>As,EsmForTokenClassification:()=>Fs,EsmModel:()=>Rs,EsmPreTrainedModel:()=>rs,ExaoneForCausalLM:()=>td,ExaoneModel:()=>ed,ExaonePreTrainedModel:()=>Pi,FalconForCausalLM:()=>Ch,FalconModel:()=>Ph,FalconPreTrainedModel:()=>Il,FastViTForImageClassification:()=>tp,FastViTModel:()=>ep,FastViTPreTrainedModel:()=>Qi,Florence2ForConditionalGeneration:()=>Ma,Florence2PreTrainedModel:()=>ga,GLPNForDepthEstimation:()=>sm,GLPNModel:()=>rm,GLPNPreTrainedModel:()=>hl,GPT2LMHeadModel:()=>So,GPT2Model:()=>Kn,GPT2PreTrainedModel:()=>Gn,GPTBigCodeForCausalLM:()=>V,GPTBigCodeModel:()=>L,GPTBigCodePreTrainedModel:()=>A,GPTJForCausalLM:()=>P,GPTJModel:()=>h,GPTJPreTrainedModel:()=>Xn,GPTNeoForCausalLM:()=>$o,GPTNeoModel:()=>qn,GPTNeoPreTrainedModel:()=>Mn,GPTNeoXForCausalLM:()=>Ao,GPTNeoXModel:()=>ko,GPTNeoXPreTrainedModel:()=>Qn,Gemma2ForCausalLM:()=>gd,Gemma2Model:()=>fd,Gemma2PreTrainedModel:()=>Oi,Gemma3ForCausalLM:()=>yd,Gemma3Model:()=>bd,Gemma3PreTrainedModel:()=>Li,Gemma3nForConditionalGeneration:()=>Nn,Gemma3nPreTrainedModel:()=>en,GemmaForCausalLM:()=>_d,GemmaModel:()=>hd,GemmaPreTrainedModel:()=>Fi,GlmForCausalLM:()=>Zu,GlmModel:()=>Yu,GlmPreTrainedModel:()=>Ei,GraniteForCausalLM:()=>cd,GraniteModel:()=>ld,GraniteMoeHybridForCausalLM:()=>dd,GraniteMoeHybridModel:()=>ud,GraniteMoeHybridPreTrainedModel:()=>ki,GranitePreTrainedModel:()=>$i,GroundingDinoForObjectDetection:()=>wm,GroundingDinoPreTrainedModel:()=>Mm,GroupViTModel:()=>Zd,GroupViTPreTrainedModel:()=>Yd,HeliumForCausalLM:()=>Ju,HeliumModel:()=>Xu,HeliumPreTrainedModel:()=>Ti,HieraForImageClassification:()=>Fp,HieraModel:()=>Ap,HieraPreTrainedModel:()=>cl,HubertForCTC:()=>th,HubertForSequenceClassification:()=>rh,HubertModel:()=>eh,HubertPreTrainedModel:()=>Ev,IJepaForImageClassification:()=>Ud,IJepaModel:()=>Vd,IJepaPreTrainedModel:()=>Ki,Idefics3ForConditionalGeneration:()=>jn,Idefics3PreTrainedModel:()=>ya,ImageMattingOutput:()=>Q_,JAISLMHeadModel:()=>gn,JAISModel:()=>Io,JAISPreTrainedModel:()=>Hn,JinaCLIPModel:()=>hn,JinaCLIPPreTrainedModel:()=>mn,JinaCLIPTextModel:()=>Jr,JinaCLIPVisionModel:()=>_n,Lfm2ForCausalLM:()=>Hu,Lfm2Model:()=>Ku,Lfm2PreTrainedModel:()=>vi,LiteWhisperForConditionalGeneration:()=>ha,Llama4ForCausalLM:()=>Vt,Llama4PreTrainedModel:()=>Ot,LlamaForCausalLM:()=>vt,LlamaModel:()=>at,LlamaPreTrainedModel:()=>Qe,LlavaForConditionalGeneration:()=>Rn,LlavaOnevisionForConditionalGeneration:()=>_a,LlavaPreTrainedModel:()=>bo,LlavaQwen2ForCausalLM:()=>yo,LongT5ForConditionalGeneration:()=>sr,LongT5Model:()=>Xt,LongT5PreTrainedModel:()=>br,M2M100ForConditionalGeneration:()=>Fm,M2M100Model:()=>Am,M2M100PreTrainedModel:()=>yl,MBartForCausalLM:()=>os,MBartForConditionalGeneration:()=>ps,MBartForSequenceClassification:()=>yr,MBartModel:()=>Xr,MBartPreTrainedModel:()=>Ir,MPNetForMaskedLM:()=>Os,MPNetForQuestionAnswering:()=>ue,MPNetForSequenceClassification:()=>js,MPNetForTokenClassification:()=>Dn,MPNetModel:()=>Ns,MPNetPreTrainedModel:()=>Kt,MT5ForConditionalGeneration:()=>ns,MT5Model:()=>qr,MT5PreTrainedModel:()=>Ht,MarianMTModel:()=>km,MarianModel:()=>$m,MarianPreTrainedModel:()=>bl,MaskFormerForInstanceSegmentation:()=>tm,MaskFormerModel:()=>em,MaskFormerPreTrainedModel:()=>ml,MaskedLMOutput:()=>$r,Metric3DForDepthEstimation:()=>Jp,Metric3DPreTrainedModel:()=>Xp,Metric3Dv2ForDepthEstimation:()=>Zp,Metric3Dv2PreTrainedModel:()=>Yp,MgpstrForSceneTextRecognition:()=>r_,MgpstrModelOutput:()=>e_,MgpstrPreTrainedModel:()=>t_,MimiDecoderModel:()=>m_,MimiDecoderOutput:()=>u_,MimiEncoderModel:()=>p_,MimiEncoderOutput:()=>c_,MimiModel:()=>d_,MimiPreTrainedModel:()=>Na,Ministral3ForCausalLM:()=>yh,Ministral3Model:()=>bh,Ministral3PreTrainedModel:()=>Pl,MinistralForCausalLM:()=>wh,MinistralModel:()=>Mh,MinistralPreTrainedModel:()=>El,Mistral3ForConditionalGeneration:()=>un,MistralForCausalLM:()=>gh,MistralModel:()=>fh,MistralPreTrainedModel:()=>Tl,MobileBertForMaskedLM:()=>ze,MobileBertForQuestionAnswering:()=>nt,MobileBertForSequenceClassification:()=>Ue,MobileBertModel:()=>Nr,MobileBertPreTrainedModel:()=>ss,MobileLLMForCausalLM:()=>sd,MobileLLMModel:()=>rd,MobileLLMPreTrainedModel:()=>Ci,MobileNetV1ForImageClassification:()=>Rh,MobileNetV1ForSemanticSegmentation:()=>Nh,MobileNetV1Model:()=>Bh,MobileNetV1PreTrainedModel:()=>La,MobileNetV2ForImageClassification:()=>Vh,MobileNetV2ForSemanticSegmentation:()=>Uh,MobileNetV2Model:()=>jh,MobileNetV2PreTrainedModel:()=>za,MobileNetV3ForImageClassification:()=>Gh,MobileNetV3ForSemanticSegmentation:()=>Kh,MobileNetV3Model:()=>Wh,MobileNetV3PreTrainedModel:()=>Ba,MobileNetV4ForImageClassification:()=>qh,MobileNetV4ForSemanticSegmentation:()=>Qh,MobileNetV4Model:()=>Hh,MobileNetV4PreTrainedModel:()=>Ra,MobileViTForImageClassification:()=>op,MobileViTModel:()=>np,MobileViTPreTrainedModel:()=>Xi,MobileViTV2ForImageClassification:()=>ip,MobileViTV2Model:()=>ap,MobileViTV2PreTrainedModel:()=>Ji,ModelOutput:()=>de,ModernBertDecoderForCausalLM:()=>gr,ModernBertDecoderModel:()=>It,ModernBertDecoderPreTrainedModel:()=>Rt,ModernBertForMaskedLM:()=>Oe,ModernBertForSequenceClassification:()=>ot,ModernBertForTokenClassification:()=>ht,ModernBertModel:()=>Ne,ModernBertPreTrainedModel:()=>Ze,Moondream1ForConditionalGeneration:()=>fa,MoonshineForConditionalGeneration:()=>zn,MoonshineModel:()=>bi,MoonshinePreTrainedModel:()=>wo,MptForCausalLM:()=>zd,MptModel:()=>Ld,MptPreTrainedModel:()=>Ui,MultiModalityCausalLM:()=>Zh,MultiModalityPreTrainedModel:()=>Yh,MusicgenForCausalLM:()=>Iv,MusicgenForConditionalGeneration:()=>Ol,MusicgenModel:()=>Sv,MusicgenPreTrainedModel:()=>Fl,NanoChatForCausalLM:()=>Pa,NanoChatModel:()=>Us,NanoChatPreTrainedModel:()=>xr,NeoBertForMaskedLM:()=>Fe,NeoBertForQuestionAnswering:()=>rt,NeoBertForSequenceClassification:()=>tt,NeoBertForTokenClassification:()=>Re,NeoBertModel:()=>We,NeoBertPreTrainedModel:()=>Ee,NomicBertModel:()=>zt,NomicBertPreTrainedModel:()=>Or,OPTForCausalLM:()=>Rd,OPTModel:()=>Bd,OPTPreTrainedModel:()=>Wi,Olmo2ForCausalLM:()=>id,Olmo2Model:()=>ad,Olmo2PreTrainedModel:()=>Ii,OlmoForCausalLM:()=>od,OlmoModel:()=>nd,OlmoPreTrainedModel:()=>Si,OpenELMForCausalLM:()=>xd,OpenELMModel:()=>vd,OpenELMPreTrainedModel:()=>zi,OwlViTForObjectDetection:()=>cp,OwlViTModel:()=>lp,OwlViTPreTrainedModel:()=>Yi,Owlv2ForObjectDetection:()=>dp,Owlv2Model:()=>up,Owlv2PreTrainedModel:()=>Zi,PaliGemmaForConditionalGeneration:()=>ba,PaliGemmaPreTrainedModel:()=>wa,ParakeetForCTC:()=>Rm,ParakeetPreTrainedModel:()=>Bm,PatchTSMixerForPrediction:()=>a_,PatchTSMixerModel:()=>o_,PatchTSMixerPreTrainedModel:()=>Ll,PatchTSTForPrediction:()=>n_,PatchTSTModel:()=>s_,PatchTSTPreTrainedModel:()=>Dl,Phi3ForCausalLM:()=>Fd,Phi3Model:()=>Ad,Phi3PreTrainedModel:()=>ji,Phi3VForCausalLM:()=>Un,Phi3VPreTrainedModel:()=>Vn,PhiForCausalLM:()=>kd,PhiModel:()=>$d,PhiPreTrainedModel:()=>Ni,PreTrainedModel:()=>z,PretrainedMixin:()=>Ut,PvtForImageClassification:()=>Hd,PvtModel:()=>Kd,PvtPreTrainedModel:()=>Hi,PyAnnoteForAudioFrameClassification:()=>jm,PyAnnoteModel:()=>Nm,PyAnnotePreTrainedModel:()=>vl,QuestionAnsweringModelOutput:()=>Br,Qwen2ForCausalLM:()=>Ed,Qwen2Model:()=>Td,Qwen2PreTrainedModel:()=>Bi,Qwen2VLForConditionalGeneration:()=>Id,Qwen2VLPreTrainedModel:()=>Sd,Qwen3ForCausalLM:()=>Cd,Qwen3Model:()=>Pd,Qwen3PreTrainedModel:()=>Ri,RFDetrForObjectDetection:()=>xp,RFDetrModel:()=>vp,RFDetrObjectDetectionOutput:()=>Tp,RFDetrPreTrainedModel:()=>ol,RTDetrForObjectDetection:()=>Mp,RTDetrModel:()=>gp,RTDetrObjectDetectionOutput:()=>Fo,RTDetrPreTrainedModel:()=>sl,RTDetrV2ForObjectDetection:()=>bp,RTDetrV2Model:()=>wp,RTDetrV2ObjectDetectionOutput:()=>yp,RTDetrV2PreTrainedModel:()=>nl,ResNetForImageClassification:()=>Dp,ResNetModel:()=>Op,ResNetPreTrainedModel:()=>ul,RoFormerForMaskedLM:()=>Qs,RoFormerForQuestionAnswering:()=>Sr,RoFormerForSequenceClassification:()=>Xs,RoFormerForTokenClassification:()=>or,RoFormerModel:()=>qs,RoFormerPreTrainedModel:()=>Rr,RobertaForMaskedLM:()=>ra,RobertaForQuestionAnswering:()=>oa,RobertaForSequenceClassification:()=>sa,RobertaForTokenClassification:()=>na,RobertaModel:()=>po,RobertaPreTrainedModel:()=>Ds,Sam2ImageSegmentationOutput:()=>Pm,Sam2Model:()=>$a,Sam2PreTrainedModel:()=>Cm,Sam3TrackerModel:()=>Im,SamImageSegmentationOutput:()=>Em,SamModel:()=>Tm,SamPreTrainedModel:()=>xm,SapiensForDepthEstimation:()=>Kp,SapiensForNormalEstimation:()=>Hp,SapiensForSemanticSegmentation:()=>Gp,SapiensPreTrainedModel:()=>Ia,SegformerForImageClassification:()=>Ah,SegformerForSemanticSegmentation:()=>Fh,SegformerModel:()=>Cv,SegformerPreTrainedModel:()=>Da,Seq2SeqLMOutput:()=>_x,SequenceClassifierOutput:()=>xt,SiglipModel:()=>To,SiglipPreTrainedModel:()=>Wn,SiglipTextModel:()=>pn,SiglipVisionModel:()=>dt,SmolLM3ForCausalLM:()=>Qu,SmolLM3Model:()=>qu,SmolLM3PreTrainedModel:()=>xi,SmolVLMForConditionalGeneration:()=>dn,SnacDecoderModel:()=>y_,SnacEncoderModel:()=>b_,SnacModel:()=>w_,SnacPreTrainedModel:()=>Va,SpeechT5ForSpeechToText:()=>uh,SpeechT5ForTextToSpeech:()=>dh,SpeechT5HifiGan:()=>ph,SpeechT5Model:()=>Pv,SpeechT5PreTrainedModel:()=>Fa,SqueezeBertForMaskedLM:()=>ee,SqueezeBertForQuestionAnswering:()=>Me,SqueezeBertForSequenceClassification:()=>se,SqueezeBertModel:()=>U,SqueezeBertPreTrainedModel:()=>$,StableLmForCausalLM:()=>Dh,StableLmModel:()=>Oh,StableLmPreTrainedModel:()=>kl,Starcoder2ForCausalLM:()=>Eh,Starcoder2Model:()=>Th,Starcoder2PreTrainedModel:()=>Sl,StyleTextToSpeech2Model:()=>ch,StyleTextToSpeech2PreTrainedModel:()=>lh,SupertonicForConditionalGeneration:()=>xl,SupertonicPreTrainedModel:()=>mh,Swin2SRForImageSuperResolution:()=>Np,Swin2SRModel:()=>Rp,Swin2SRPreTrainedModel:()=>dl,SwinForImageClassification:()=>zp,SwinForSemanticSegmentation:()=>Bp,SwinModel:()=>Lp,SwinPreTrainedModel:()=>Sa,T5ForConditionalGeneration:()=>rr,T5Model:()=>Et,T5PreTrainedModel:()=>$t,TableTransformerForObjectDetection:()=>Sp,TableTransformerModel:()=>Cp,TableTransformerObjectDetectionOutput:()=>Ip,TableTransformerPreTrainedModel:()=>il,TokenClassifierOutput:()=>Pr,TrOCRForCausalLM:()=>_h,TrOCRPreTrainedModel:()=>hh,UltravoxModel:()=>zl,UltravoxPreTrainedModel:()=>i_,UniSpeechForCTC:()=>Gm,UniSpeechForSequenceClassification:()=>Km,UniSpeechModel:()=>Wm,UniSpeechPreTrainedModel:()=>ka,UniSpeechSatForAudioFrameClassification:()=>Xm,UniSpeechSatForCTC:()=>qm,UniSpeechSatForSequenceClassification:()=>Qm,UniSpeechSatModel:()=>Hm,UniSpeechSatPreTrainedModel:()=>Oo,VaultGemmaForCausalLM:()=>wd,VaultGemmaModel:()=>Md,VaultGemmaPreTrainedModel:()=>Di,ViTForImageClassification:()=>jd,ViTMAEModel:()=>Qd,ViTMAEPreTrainedModel:()=>qd,ViTMSNForImageClassification:()=>Jd,ViTMSNModel:()=>Xd,ViTMSNPreTrainedModel:()=>qi,ViTModel:()=>Nd,ViTPreTrainedModel:()=>Gi,VisionEncoderDecoderModel:()=>Bn,VitMatteForImageMatting:()=>sp,VitMattePreTrainedModel:()=>rp,VitPoseForPoseEstimation:()=>Gd,VitPosePreTrainedModel:()=>Wd,VitsModel:()=>$l,VitsModelOutput:()=>X_,VitsPreTrainedModel:()=>kh,VoxtralForConditionalGeneration:()=>l_,Wav2Vec2BertForCTC:()=>Ym,Wav2Vec2BertForSequenceClassification:()=>Zm,Wav2Vec2BertModel:()=>Jm,Wav2Vec2BertPreTrainedModel:()=>Aa,Wav2Vec2ForAudioFrameClassification:()=>zm,Wav2Vec2ForCTC:()=>Dm,Wav2Vec2ForSequenceClassification:()=>Lm,Wav2Vec2Model:()=>Om,Wav2Vec2PreTrainedModel:()=>tn,WavLMForAudioFrameClassification:()=>ih,WavLMForCTC:()=>nh,WavLMForSequenceClassification:()=>oh,WavLMForXVector:()=>ah,WavLMModel:()=>sh,WavLMPreTrainedModel:()=>Jn,WeSpeakerResNetModel:()=>Um,WeSpeakerResNetPreTrainedModel:()=>Vm,WhisperForConditionalGeneration:()=>Ln,WhisperModel:()=>ma,WhisperPreTrainedModel:()=>Vs,XLMForQuestionAnswering:()=>ua,XLMForSequenceClassification:()=>la,XLMForTokenClassification:()=>ca,XLMModel:()=>aa,XLMPreTrainedModel:()=>Ys,XLMRobertaForMaskedLM:()=>mo,XLMRobertaForQuestionAnswering:()=>pa,XLMRobertaForSequenceClassification:()=>ho,XLMRobertaForTokenClassification:()=>_o,XLMRobertaModel:()=>da,XLMRobertaPreTrainedModel:()=>Zs,XLMWithLMHeadModel:()=>ia,XVectorOutput:()=>q_,YolosForObjectDetection:()=>ym,YolosModel:()=>bm,YolosObjectDetectionOutput:()=>vm,YolosPreTrainedModel:()=>wl});var s=t("./src/configs.js"),n=t("./src/backends/onnx.js"),o=t("./src/utils/dtypes.js"),i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),c=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),d=t("./src/generation/configuration_utils.js"),u=t("./src/utils/tensor.js"),f=t("./src/utils/image.js"),_=t("./src/utils/maths.js"),y=t("./src/generation/stopping_criteria.js"),k=t("./src/generation/logits_sampler.js"),w=t("./src/env.js"),v=t("./src/models/whisper/generation_whisper.js"),I=t("./src/models/whisper/common_whisper.js");const T={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11,ImageAudioTextToText:12,Supertonic:13},b=new Map,E=new Map,x=new Map;async function S(g,M,j){let ae=j.config?.["transformers.js_config"]??{},me=j.device??ae.device;me&&typeof me!="string"&&(me.hasOwnProperty(M)?me=me[M]:(console.warn(`device not specified for "${M}". Using the default device.`),me=null));const _e=me??(w.apis.IS_NODE_ENV?"cpu":"wasm"),Se=(0,n.deviceToExecutionProviders)(_e),Le=ae.device_config??{};Le.hasOwnProperty(_e)&&(ae={...ae,...Le[_e]});let Ge=j.dtype??ae.dtype;if(typeof Ge!="string"&&(Ge&&Ge.hasOwnProperty(M)?Ge=Ge[M]:(Ge=o.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??o.DATA_TYPES.fp32,console.warn(`dtype not specified for "${M}". Using the default dtype (${Ge}) for this device (${_e}).`))),Ge===o.DATA_TYPES.auto){let At=ae.dtype;typeof At!="string"&&(At=At?.[M]),At&&At!==o.DATA_TYPES.auto&&o.DATA_TYPES.hasOwnProperty(At)?Ge=At:Ge=o.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??o.DATA_TYPES.fp32}const st=Ge;if(o.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(st)){if(st===o.DATA_TYPES.fp16&&_e==="webgpu"&&!await(0,o.isWebGpuFp16Supported)())throw new Error(`The device (${_e}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${st}. Should be one of: ${Object.keys(o.DATA_TYPES).join(", ")}`);const wt=ae.kv_cache_dtype,bt=wt?typeof wt=="string"?wt:wt[st]??"float32":void 0;if(bt&&!["float32","float16"].includes(bt))throw new Error(`Invalid kv_cache_dtype: ${bt}. Should be one of: float32, float16`);const Pt={dtype:st,kv_cache_dtype:bt,device:_e},mt=o.DEFAULT_DTYPE_SUFFIX_MAPPING[st],Lt=`${M}${mt}.onnx`,_t=`${j.subfolder??""}/${Lt}`,pt={...j.session_options};pt.executionProviders??=Se;const Ft=ae.free_dimension_overrides;Ft?pt.freeDimensionOverrides??=Ft:_e.startsWith("webnn")&&!pt.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${_e}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const Wt=w.apis.IS_NODE_ENV&&w.env.useFSCache,er=(0,l.getModelFile)(g,_t,!0,j,Wt),nr=j.use_external_data_format??ae.use_external_data_format;let pr=[];if(nr){let At;typeof nr=="object"?nr.hasOwnProperty(Lt)?At=nr[Lt]:nr.hasOwnProperty(M)?At=nr[M]:At=!1:At=nr;const cr=+At;if(cr>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${cr}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let kr=0;kr{const eo=await(0,l.getModelFile)(g,Wr,!0,j,Wt);ms(eo instanceof Uint8Array?{path:wn,data:eo}:wn)}))}}else pt.externalData!==void 0&&(pr=pt.externalData.map(async At=>{if(typeof At.data=="string"){const cr=await(0,l.getModelFile)(g,At.data,!0,j);return{...At,data:cr}}return At}));if(pr.length>0){const At=await Promise.all(pr);w.apis.IS_NODE_ENV||(pt.externalData=At)}if(_e==="webgpu"){const At=(0,s.getCacheShapes)(j.config,{prefix:"present"});if(Object.keys(At).length>0&&!(0,n.isONNXProxy)()){const cr={};for(const kr in At)cr[kr]="gpu-buffer";pt.preferredOutputLocation=cr}}return{buffer_or_path:await er,session_options:pt,session_config:Pt}}async function O(g,M,j){return Object.fromEntries(await Promise.all(Object.keys(M).map(async ae=>{const{buffer_or_path:me,session_options:_e,session_config:Se}=await S(g,M[ae],j),Le=await(0,n.createInferenceSession)(me,_e,Se);return[ae,Le]})))}async function F(g,M,j){return Object.fromEntries(await Promise.all(Object.keys(M).map(async ae=>{const me=await(0,l.getModelJSON)(g,M[ae],!1,j);return[ae,me]})))}function H(g,M){const j=Object.create(null),ae=[];for(const Se of g.inputNames){const Le=M[Se];if(!(Le instanceof u.Tensor)){ae.push(Se);continue}j[Se]=(0,n.isONNXProxy)()?Le.clone():Le}if(ae.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ae.join(", ")}.`);const me=Object.keys(M).length,_e=g.inputNames.length;if(me>_e){let Se=Object.keys(M).filter(Le=>!g.inputNames.includes(Le));console.warn(`WARNING: Too many inputs were provided (${me} > ${_e}). The following inputs will be ignored: "${Se.join(", ")}".`)}return j}async function W(g,M){const j=H(g,M);try{const ae=Object.fromEntries(Object.entries(j).map(([_e,Se])=>[_e,Se.ort_tensor])),me=await(0,n.runInferenceSession)(g,ae);return B(me)}catch(ae){const me=Object.fromEntries(Object.entries(j).map(([_e,Se])=>{const Le={type:Se.type,dims:Se.dims,location:Se.location};return Le.location!=="gpu-buffer"&&(Le.data=Se.data),[_e,Le]}));throw console.error(`An error occurred during model execution: "${ae}".`),console.error("Inputs given to model:",me),ae}}function B(g){for(let M in g)(0,n.isONNXTensor)(g[M])?g[M]=new u.Tensor(g[M]):typeof g[M]=="object"&&B(g[M]);return g}function Y(g){if(g instanceof u.Tensor)return g;if(g.length===0)throw Error("items must be non-empty");if(Array.isArray(g[0])){if(g.some(M=>M.length!==g[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new u.Tensor("int64",BigInt64Array.from(g.flat().map(M=>BigInt(M))),[g.length,g[0].length])}else return new u.Tensor("int64",BigInt64Array.from(g.map(M=>BigInt(M))),[1,g.length])}function X(g){return new u.Tensor("bool",[g],[1])}async function J(g,M){let{encoder_outputs:j,input_ids:ae,decoder_input_ids:me,..._e}=M;if(!j){const Le=(0,a.pick)(M,g.sessions.model.inputNames);j=(await re(g,Le)).last_hidden_state}return _e.input_ids=me,_e.encoder_hidden_states=j,g.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(_e.encoder_attention_mask=M.attention_mask),await le(g,_e,!0)}async function re(g,M){const j=g.sessions.model,ae=(0,a.pick)(M,j.inputNames);if(j.inputNames.includes("inputs_embeds")&&!ae.inputs_embeds){if(!M.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ae.inputs_embeds=await g.encode_text({input_ids:M.input_ids})}if(j.inputNames.includes("token_type_ids")&&!ae.token_type_ids){if(!ae.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");ae.token_type_ids=(0,u.zeros_like)(ae.input_ids)}if(j.inputNames.includes("pixel_mask")&&!ae.pixel_mask){if(!ae.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const me=ae.pixel_values.dims;ae.pixel_mask=(0,u.ones)([me[0],me[2],me[3]])}return await W(j,ae)}async function ne(g,M){const j=await g.encode(M);return await g.decode(j)}async function le(g,M,j=!1){const ae=g.sessions[j?"decoder_model_merged":"model"],{past_key_values:me,..._e}=M;if(ae.inputNames.includes("use_cache_branch")&&(_e.use_cache_branch=X(!!me)),ae.inputNames.includes("position_ids")&&_e.attention_mask&&!_e.position_ids){const Le=["paligemma","gemma3_text","gemma3"].includes(g.config.model_type)?1:0;_e.position_ids=Ae(_e,me,Le)}g.addPastKeyValues(_e,me);const Se=(0,a.pick)(_e,ae.inputNames);return await W(ae,Se)}function pe({modality_token_id:g,inputs_embeds:M,modality_features:j,input_ids:ae,attention_mask:me}){const _e=ae.tolist().map(st=>st.reduce((wt,bt,Pt)=>(bt==g&&wt.push(Pt),wt),[])),Se=_e.reduce((st,wt)=>st+wt.length,0),Le=j.dims[0];if(Se!==Le)throw new Error(`Number of tokens and features do not match: tokens: ${Se}, features ${Le}`);let Ge=0;for(let st=0;st<_e.length;++st){const wt=_e[st],bt=M[st];for(let Pt=0;Pt_e.dims[1]||me<_e.dims[1]&&(j.input_ids=_e.slice(null,[me,null]))}return j}function je(g,M,j,ae){return j.past_key_values&&(M=M.map(me=>[me.at(-1)])),{...j,decoder_input_ids:Y(M)}}function Te(g,...M){return g.config.is_encoder_decoder?je(g,...M):Ie(g,...M)}function Q(g,M,j,ae){const me=!!j.past_key_values;return ae.guidance_scale!==null&&ae.guidance_scale>1&&(me?j.input_ids=(0,u.cat)([j.input_ids,j.input_ids],0):(j.input_ids=(0,u.cat)([j.input_ids,(0,u.full_like)(j.input_ids,BigInt(ae.pad_token_id))],0),j.attention_mask=(0,u.cat)([j.attention_mask,(0,u.full_like)(j.attention_mask,0n)],0))),(me||!j.pixel_values)&&(j.pixel_values=(0,u.full)([0,0,3,384,384],1)),me&&(j.images_seq_mask=new u.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),j.images_emb_mask=new u.Tensor("bool",new Array(0).fill(!1),[1,1,0])),j}class z extends i.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(M,j,ae){super(),this.config=M,this.sessions=j,this.configs=ae;const me=x.get(this.constructor),_e=b.get(me);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,_e){case T.DecoderOnly:this.can_generate=!0,this._forward=le,this._prepare_inputs_for_generation=Ie;break;case T.Seq2Seq:case T.Vision2Seq:case T.Musicgen:this.can_generate=!0,this._forward=J,this._prepare_inputs_for_generation=je;break;case T.EncoderDecoder:this._forward=J;break;case T.ImageTextToText:this.can_generate=!0,this._forward=te,this._prepare_inputs_for_generation=Te;break;case T.AudioTextToText:this.can_generate=!0,this._forward=D,this._prepare_inputs_for_generation=Te;break;case T.Phi3V:case T.ImageAudioTextToText:this.can_generate=!0,this._prepare_inputs_for_generation=Te;break;case T.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Q;break;case T.AutoEncoder:this._forward=ne;break;default:this._forward=re;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const M=[];for(const j of Object.values(this.sessions))j?.handler?.dispose&&M.push(j.handler.dispose());return await Promise.all(M)}static async from_pretrained(M,{progress_callback:j=null,config:ae=null,cache_dir:me=null,local_files_only:_e=!1,revision:Se="main",model_file_name:Le=null,subfolder:Ge="onnx",device:st=null,dtype:wt=null,use_external_data_format:bt=null,session_options:Pt={}}={}){let mt={progress_callback:j,config:ae,cache_dir:me,local_files_only:_e,revision:Se,model_file_name:Le,subfolder:Ge,device:st,dtype:wt,use_external_data_format:bt,session_options:Pt};const Lt=x.get(this),_t=b.get(Lt);ae=mt.config=await s.AutoConfig.from_pretrained(M,mt);let pt;if(_t===T.DecoderOnly)pt=await Promise.all([O(M,{model:mt.model_file_name??"model"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.Seq2Seq||_t===T.Vision2Seq)pt=await Promise.all([O(M,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.MaskGeneration)pt=await Promise.all([O(M,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},mt)]);else if(_t===T.EncoderDecoder)pt=await Promise.all([O(M,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},mt)]);else if(_t===T.ImageTextToText){const Ft={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};ae.is_encoder_decoder&&(Ft.model="encoder_model"),pt=await Promise.all([O(M,Ft,mt),F(M,{generation_config:"generation_config.json"},mt)])}else if(_t===T.AudioTextToText){const Ft={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};pt=await Promise.all([O(M,Ft,mt),F(M,{generation_config:"generation_config.json"},mt)])}else if(_t===T.ImageAudioTextToText){const Ft={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};pt=await Promise.all([O(M,Ft,mt),F(M,{generation_config:"generation_config.json"},mt)])}else if(_t===T.Musicgen)pt=await Promise.all([O(M,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.MultiModality)pt=await Promise.all([O(M,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.Phi3V)pt=await Promise.all([O(M,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.AutoEncoder)pt=await Promise.all([O(M,{encoder_model:"encoder_model",decoder_model:"decoder_model"},mt)]);else if(_t===T.Supertonic)pt=await Promise.all([O(M,{text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"},mt)]);else{if(_t!==T.EncoderOnly){const Ft=Lt??ae?.model_type;Ft!=="custom"&&console.warn(`Model type for '${Ft}' not found, assuming encoder-only architecture. Please report this at ${c.GITHUB_ISSUE_URL}.`)}pt=await Promise.all([O(M,{model:mt.model_file_name??"model"},mt)])}return new this(ae,...pt)}async _call(M){return await this.forward(M)}async forward(M){return await this._forward(this,M)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(M,j,ae=null){const me=new p.LogitsProcessorList;if(M.repetition_penalty!==null&&M.repetition_penalty!==1&&me.push(new p.RepetitionPenaltyLogitsProcessor(M.repetition_penalty)),M.no_repeat_ngram_size!==null&&M.no_repeat_ngram_size>0&&me.push(new p.NoRepeatNGramLogitsProcessor(M.no_repeat_ngram_size)),M.bad_words_ids!==null&&me.push(new p.NoBadWordsLogitsProcessor(M.bad_words_ids,M.eos_token_id)),M.min_length!==null&&M.eos_token_id!==null&&M.min_length>0&&me.push(new p.MinLengthLogitsProcessor(M.min_length,M.eos_token_id)),M.min_new_tokens!==null&&M.eos_token_id!==null&&M.min_new_tokens>0&&me.push(new p.MinNewTokensLengthLogitsProcessor(j,M.min_new_tokens,M.eos_token_id)),M.forced_bos_token_id!==null&&me.push(new p.ForcedBOSTokenLogitsProcessor(M.forced_bos_token_id)),M.forced_eos_token_id!==null&&me.push(new p.ForcedEOSTokenLogitsProcessor(M.max_length,M.forced_eos_token_id)),M.begin_suppress_tokens!==null){const _e=j>1||M.forced_bos_token_id===null?j:j+1;me.push(new p.SuppressTokensAtBeginLogitsProcessor(M.begin_suppress_tokens,_e))}return M.guidance_scale!==null&&M.guidance_scale>1&&me.push(new p.ClassifierFreeGuidanceLogitsProcessor(M.guidance_scale)),M.temperature===0&&M.do_sample&&(console.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),M.do_sample=!1),M.do_sample&&M.temperature!==null&&M.temperature!==1&&me.push(new p.TemperatureLogitsWarper(M.temperature)),ae!==null&&me.extend(ae),me}_prepare_generation_config(M,j,ae=d.GenerationConfig){const me={...this.config};for(const Se of["decoder","generator","text_config"])Se in me&&Object.assign(me,me[Se]);const _e=new ae(me);return Object.assign(_e,this.generation_config??{}),M&&Object.assign(_e,M),j&&Object.assign(_e,(0,a.pick)(j,Object.getOwnPropertyNames(_e))),_e}_get_stopping_criteria(M,j=null){const ae=new y.StoppingCriteriaList;return M.max_length!==null&&ae.push(new y.MaxLengthCriteria(M.max_length,this.config.max_position_embeddings??null)),M.eos_token_id!==null&&ae.push(new y.EosTokenCriteria(M.eos_token_id)),j&&ae.extend(j),ae}_validate_model_class(){if(!this.can_generate){const M=[Nl,jl,Rl,Bl],j=x.get(this.constructor),ae=new Set,me=this.config.model_type;for(const Se of M){const Le=Se.get(me);Le&&ae.add(Le[0])}let _e=`The current model class (${j}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ae.size>0&&(_e+=` Please use the following class instead: ${[...ae].join(", ")}`),Error(_e)}}prepare_inputs_for_generation(...M){return this._prepare_inputs_for_generation(this,...M)}_update_model_kwargs_for_generation({generated_input_ids:M,outputs:j,model_inputs:ae,is_encoder_decoder:me}){return ae.past_key_values=this.getPastKeyValues(j,ae.past_key_values),ae.input_ids=new u.Tensor("int64",M.flat(),[M.length,1]),me||(ae.attention_mask=(0,u.cat)([ae.attention_mask,(0,u.ones)([ae.attention_mask.dims[0],1])],1)),ae.position_ids=null,ae}_prepare_model_inputs({inputs:M,bos_token_id:j,model_kwargs:ae}){const me=(0,a.pick)(ae,this.forward_params),_e=this.main_input_name;if(_e in me){if(M)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else me[_e]=M;return{inputs_tensor:me[_e],model_inputs:me,model_input_name:_e}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:M,model_inputs:j,model_input_name:ae,generation_config:me}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!j.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Se,pixel_values:Le,attention_mask:Ge,...st}=j,wt=await this._prepare_inputs_embeds(j);j={...st,...(0,a.pick)(wt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:_e}=await re(this,j);if(me.guidance_scale!==null&&me.guidance_scale>1)_e=(0,u.cat)([_e,(0,u.full_like)(_e,0)],0),"attention_mask"in j&&(j.attention_mask=(0,u.cat)([j.attention_mask,(0,u.zeros_like)(j.attention_mask)],0));else if(j.decoder_input_ids){const Se=Y(j.decoder_input_ids).dims[0];if(Se!==_e.dims[0]){if(_e.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${_e.dims[0]}) than the decoder inputs (${Se}).`);_e=(0,u.cat)(Array.from({length:Se},()=>_e),0)}}return j.encoder_outputs=_e,j}_prepare_decoder_input_ids_for_generation({batch_size:M,model_input_name:j,model_kwargs:ae,decoder_start_token_id:me,bos_token_id:_e,generation_config:Se}){let{decoder_input_ids:Le,...Ge}=ae;if(!(Le instanceof u.Tensor)){if(Le)Array.isArray(Le[0])||(Le=Array.from({length:M},()=>Le));else if(me??=_e,this.config.model_type==="musicgen")Le=Array.from({length:M*this.config.decoder.num_codebooks},()=>[me]);else if(Array.isArray(me)){if(me.length!==M)throw new Error(`\`decoder_start_token_id\` expcted to have length ${M} but got ${me.length}`);Le=me}else Le=Array.from({length:M},()=>[me]);Le=Y(Le)}return ae.decoder_attention_mask=(0,u.ones_like)(Le),{input_ids:Le,model_inputs:Ge}}async generate({inputs:M=null,generation_config:j=null,logits_processor:ae=null,stopping_criteria:me=null,streamer:_e=null,...Se}){this._validate_model_class(),j=this._prepare_generation_config(j,Se);let{inputs_tensor:Le,model_inputs:Ge,model_input_name:st}=this._prepare_model_inputs({inputs:M,model_kwargs:Se});const wt=this.config.is_encoder_decoder;wt&&("encoder_outputs"in Ge||(Ge=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Le,model_inputs:Ge,model_input_name:st,generation_config:j})));let bt;wt?{input_ids:bt,model_inputs:Ge}=this._prepare_decoder_input_ids_for_generation({batch_size:Ge[st].dims.at(0),model_input_name:st,model_kwargs:Ge,decoder_start_token_id:j.decoder_start_token_id,bos_token_id:j.bos_token_id,generation_config:j}):bt=Ge[st];let Pt=bt.dims.at(-1);j.max_new_tokens!==null&&(j.max_length=Pt+j.max_new_tokens);const mt=this._get_logits_processor(j,Pt,ae),Lt=this._get_stopping_criteria(j,me),_t=Ge[st].dims.at(0),pt=k.LogitsSampler.getSampler(j),Ft=new Array(_t).fill(0),Wt=bt.tolist();_e&&_e.put(Wt);let er,nr={};for(;;){if(Ge=this.prepare_inputs_for_generation(Wt,Ge,j),er=await this.forward(Ge),j.output_attentions&&j.return_dict_in_generate){const Wr=this.getAttentions(er);for(const ms in Wr)ms in nr||(nr[ms]=[]),nr[ms].push(Wr[ms])}const At=er.logits.slice(null,-1,null),cr=mt(Wt,At),kr=[];for(let Wr=0;WrWr))break;Ge=this._update_model_kwargs_for_generation({generated_input_ids:kr,outputs:er,model_inputs:Ge,is_encoder_decoder:wt})}_e&&_e.end();const pr=this.getPastKeyValues(er,Ge.past_key_values,!0),fr=new u.Tensor("int64",Wt.flat(),[Wt.length,Wt[0].length]);if(j.return_dict_in_generate)return{sequences:fr,past_key_values:pr,...nr};for(const At of Object.values(er))At.location==="gpu-buffer"&&At.dispose();return fr}getPastKeyValues(M,j,ae=!1){const me=Object.create(null);for(const _e in M)if(_e.startsWith("present")){const Se=_e.replace("present_conv","past_conv").replace("present","past_key_values"),Le=_e.includes("encoder");if(Le&&j?me[Se]=j[Se]:me[Se]=M[_e],j&&(!Le||ae)){const Ge=j[Se];Ge.location==="gpu-buffer"&&Ge.dispose()}}return me}getAttentions(M){const j={};for(const ae of["cross_attentions","encoder_attentions","decoder_attentions"])for(const me in M)me.startsWith(ae)&&(ae in j||(j[ae]=[]),j[ae].push(M[me]));return j}addPastKeyValues(M,j){if(j)Object.assign(M,j);else{const ae=this.sessions.decoder_model_merged??this.sessions.model,me=(M[this.main_input_name]??M.attention_mask)?.dims?.[0]??1,_e=ae?.config?.kv_cache_dtype??"float32",Se=_e==="float16"?u.DataTypeMap.float16:u.DataTypeMap.float32,Le=(0,s.getCacheShapes)(this.config,{batch_size:me});for(const Ge in Le){const st=Le[Ge].reduce((wt,bt)=>wt*bt,1);M[Ge]=new u.Tensor(_e,new Se(st),Le[Ge])}}}async encode_image({pixel_values:M}){return(await W(this.sessions.vision_encoder,{pixel_values:M})).image_features}async encode_text({input_ids:M}){return(await W(this.sessions.embed_tokens,{input_ids:M})).inputs_embeds}async encode_audio({audio_values:M}){return(await W(this.sessions.audio_encoder,{audio_values:M})).audio_features}}class de{}class be extends de{constructor({last_hidden_state:M,hidden_states:j=null,attentions:ae=null}){super(),this.last_hidden_state=M,this.hidden_states=j,this.attentions=ae}}class ve extends z{}class xe extends ve{}class Ce extends ve{async _call(M){return new $r(await super._call(M))}}class ge extends ve{async _call(M){return new xt(await super._call(M))}}class De extends ve{async _call(M){return new Pr(await super._call(M))}}class fe extends ve{async _call(M){return new Br(await super._call(M))}}class Ee extends z{}class We extends Ee{}class Fe extends Ee{async _call(M){return new $r(await super._call(M))}}class tt extends Ee{async _call(M){return new xt(await super._call(M))}}class Re extends Ee{async _call(M){return new Pr(await super._call(M))}}class rt extends Ee{async _call(M){return new Br(await super._call(M))}}class Ze extends z{}class Ne extends Ze{}class Oe extends Ze{async _call(M){return new $r(await super._call(M))}}class ot extends Ze{async _call(M){return new xt(await super._call(M))}}class ht extends Ze{async _call(M){return new Pr(await super._call(M))}}class Rt extends z{}class It extends Rt{}class gr extends Rt{}class Or extends z{}class zt extends Or{}class Rr extends z{}class qs extends Rr{}class Qs extends Rr{async _call(M){return new $r(await super._call(M))}}class Xs extends Rr{async _call(M){return new xt(await super._call(M))}}class or extends Rr{async _call(M){return new Pr(await super._call(M))}}class Sr extends Rr{async _call(M){return new Br(await super._call(M))}}class Qr extends z{}class Bs extends Qr{}class ft extends Qr{async _call(M){return new $r(await super._call(M))}}class qt extends Qr{async _call(M){return new xt(await super._call(M))}}class Ps extends Qr{async _call(M){return new Pr(await super._call(M))}}class Cs extends Qr{async _call(M){return new Br(await super._call(M))}}class Kr extends z{}class yt extends Kr{}class Ss extends Kr{async _call(M){return new $r(await super._call(M))}}class C extends Kr{async _call(M){return new xt(await super._call(M))}}class q extends Kr{async _call(M){return new Pr(await super._call(M))}}class R extends Kr{async _call(M){return new Br(await super._call(M))}}class G extends z{}class Z extends G{}class ce extends G{async _call(M){return new $r(await super._call(M))}}class ye extends G{async _call(M){return new xt(await super._call(M))}}class et extends G{async _call(M){return new Pr(await super._call(M))}}class ut extends G{async _call(M){return new Br(await super._call(M))}}class He extends z{}class Mt extends He{}class qe extends He{async _call(M){return new $r(await super._call(M))}}class Tt extends He{async _call(M){return new xt(await super._call(M))}}class kt extends He{async _call(M){return new Pr(await super._call(M))}}class Mr extends He{async _call(M){return new Br(await super._call(M))}}class dr extends z{}class ar extends dr{}class Tr extends dr{async _call(M){return new $r(await super._call(M))}}class Is extends dr{async _call(M){return new xt(await super._call(M))}}class Dr extends dr{async _call(M){return new Pr(await super._call(M))}}class $s extends dr{async _call(M){return new Br(await super._call(M))}}class Lr extends z{}class zr extends Lr{}class ts extends Lr{async _call(M){return new xt(await super._call(M))}}class wr extends Lr{async _call(M){return new Pr(await super._call(M))}}class ir extends Lr{async _call(M){return new Br(await super._call(M))}}class Hr extends Lr{async _call(M){return new $r(await super._call(M))}}class rs extends z{}class Rs extends rs{}class ks extends rs{async _call(M){return new $r(await super._call(M))}}class As extends rs{async _call(M){return new xt(await super._call(M))}}class Fs extends rs{async _call(M){return new Pr(await super._call(M))}}class ss extends z{}class Nr extends ss{}class ze extends ss{async _call(M){return new $r(await super._call(M))}}class Ue extends ss{async _call(M){return new xt(await super._call(M))}}class nt extends ss{async _call(M){return new Br(await super._call(M))}}class Kt extends z{}class Ns extends Kt{}class Os extends Kt{async _call(M){return new $r(await super._call(M))}}class js extends Kt{async _call(M){return new xt(await super._call(M))}}class Dn extends Kt{async _call(M){return new Pr(await super._call(M))}}class ue extends Kt{async _call(M){return new Br(await super._call(M))}}class $ extends z{}class U extends ${}class ee extends ${async _call(M){return new $r(await super._call(M))}}class se extends ${async _call(M){return new xt(await super._call(M))}}class Me extends ${async _call(M){return new Br(await super._call(M))}}class $e extends z{}class Xe extends $e{}class Je extends $e{async _call(M){return new xt(await super._call(M))}}class Ye extends $e{async _call(M){return new Br(await super._call(M))}}class Ke extends $e{async _call(M){return new $r(await super._call(M))}}class $t extends z{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class Et extends $t{}class rr extends $t{}class br extends z{}class Xt extends br{}class sr extends br{}class Ht extends z{}class qr extends Ht{}class ns extends Ht{}class Er extends z{}class ds extends Er{}class Yt extends Er{}class hr extends Er{async _call(M){return new xt(await super._call(M))}}class Ir extends z{}class Xr extends Ir{}class ps extends Ir{}class yr extends Ir{async _call(M){return new xt(await super._call(M))}}class os extends Ir{}class vr extends z{}class Zt extends vr{}class _r extends vr{}class lr extends z{}class Ur extends lr{}class Js extends lr{}class Ds extends z{}class po extends Ds{}class ra extends Ds{async _call(M){return new $r(await super._call(M))}}class sa extends Ds{async _call(M){return new xt(await super._call(M))}}class na extends Ds{async _call(M){return new Pr(await super._call(M))}}class oa extends Ds{async _call(M){return new Br(await super._call(M))}}class Ys extends z{}class aa extends Ys{}class ia extends Ys{async _call(M){return new $r(await super._call(M))}}class la extends Ys{async _call(M){return new xt(await super._call(M))}}class ca extends Ys{async _call(M){return new Pr(await super._call(M))}}class ua extends Ys{async _call(M){return new Br(await super._call(M))}}class Zs extends z{}class da extends Zs{}class mo extends Zs{async _call(M){return new $r(await super._call(M))}}class ho extends Zs{async _call(M){return new xt(await super._call(M))}}class _o extends Zs{async _call(M){return new Pr(await super._call(M))}}class pa extends Zs{async _call(M){return new Br(await super._call(M))}}class fo extends z{}class go extends fo{}class Mo extends fo{}class Vs extends z{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]}class ma extends Vs{}class Ln extends Vs{_prepare_generation_config(M,j){return super._prepare_generation_config(M,j,v.WhisperGenerationConfig)}_retrieve_init_tokens(M){const j=[M.decoder_start_token_id];let ae=M.language;const me=M.task;if(M.is_multilingual){ae||(console.warn("No language specified - defaulting to English (en)."),ae="en");const Se=`<|${(0,I.whisper_language_to_code)(ae)}|>`;j.push(M.lang_to_id[Se]),j.push(M.task_to_id[me??"transcribe"])}else if(ae||me)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!M.return_timestamps&&M.no_timestamps_token_id&&j.at(-1)!==M.no_timestamps_token_id?j.push(M.no_timestamps_token_id):M.return_timestamps&&j.at(-1)===M.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),j.pop()),j.filter(_e=>_e!=null)}async generate({inputs:M=null,generation_config:j=null,logits_processor:ae=null,stopping_criteria:me=null,..._e}){j=this._prepare_generation_config(j,_e);const Se=_e.decoder_input_ids??this._retrieve_init_tokens(j);if(j.return_timestamps&&(ae??=new p.LogitsProcessorList,ae.push(new p.WhisperTimeStampLogitsProcessor(j,Se))),j.begin_suppress_tokens&&(ae??=new p.LogitsProcessorList,ae.push(new p.SuppressTokensAtBeginLogitsProcessor(j.begin_suppress_tokens,Se.length))),j.return_token_timestamps){if(!j.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");j.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),j.output_attentions=!0,j.return_dict_in_generate=!0}const Le=await super.generate({inputs:M,generation_config:j,logits_processor:ae,decoder_input_ids:Se,..._e});return j.return_token_timestamps&&(Le.token_timestamps=this._extract_token_timestamps(Le,j.alignment_heads,j.num_frames)),Le}_extract_token_timestamps(M,j,ae=null,me=.02){if(!M.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");ae==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let _e=this.config.median_filter_width;_e===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),_e=7);const Se=M.cross_attentions,Le=Array.from({length:this.config.decoder_layers},(_t,pt)=>(0,u.cat)(Se.map(Ft=>Ft[pt]),2)),Ge=(0,u.stack)(j.map(([_t,pt])=>{if(_t>=Le.length)throw new Error(`Layer index ${_t} is out of bounds for cross attentions (length ${Le.length}).`);return ae?Le[_t].slice(null,pt,null,[0,ae]):Le[_t].slice(null,pt)})).transpose(1,0,2,3),[st,wt]=(0,u.std_mean)(Ge,-2,0,!0),bt=Ge.clone();for(let _t=0;_tFt[At+1]-Ft[At]),nr=(0,a.mergeArrays)([1],er).map(fr=>!!fr),pr=[];for(let fr=0;frArray.from({length:M.dims[0]},er=>Array.from({length:M.dims[1]},nr=>1))),Lt=j?j.tolist():[],_t=ae?ae.tolist():[];let pt=0,Ft=0;for(let Wt=0;WtPt[Wt][Cr]==1),pr=er.reduce((tr,Cr,sn)=>(Cr==Ge&&tr.push(sn),tr),[]).map(tr=>er[tr+1]),fr=pr.filter(tr=>tr==Se).length,At=pr.filter(tr=>tr==Le).length;let cr=[],kr=0,wn=fr,Wr=At;for(let tr=0;trhs>kr&&yn==Se),sn=er.findIndex((yn,hs)=>hs>kr&&yn==Le),bn=wn>0&&Cr!==-1?Cr:er.length+1,to=Wr>0&&sn!==-1?sn:er.length+1;let Wa,Vl,Ul,Wl;bn0?(0,_.max)(cr.at(-1))[0]+1:0;cr.push(Array.from({length:3*Kl},(yn,hs)=>J_+hs%Kl));const Hl=Kl+J_,Ka=Mx*Gl*Ga,wx=Array.from({length:Ka},(yn,hs)=>Hl+Math.floor(hs/(Gl*Ga))),bx=Array.from({length:Ka},(yn,hs)=>Hl+Math.floor(hs/Ga)%Gl),yx=Array.from({length:Ka},(yn,hs)=>Hl+hs%Ga);cr.push([wx,bx,yx].flat()),kr=Wa+Ka}if(kr0?(0,_.max)(cr.at(-1))[0]+1:0,Cr=er.length-kr;cr.push(Array.from({length:3*Cr},(sn,bn)=>tr+bn%Cr))}const ms=cr.reduce((tr,Cr)=>tr+Cr.length,0),Zn=new Array(ms);let eo=0;for(let tr=0;tr<3;++tr)for(let Cr=0;Crbt[pt%bt.length]),Lt=Array.from({length:Pt[0]},(_t,pt)=>(0,_.max)(bt.subarray(Pt[1]*pt,Pt[1]*(pt+1)))[0]+1n+BigInt(Pt[1]));return[new u.Tensor("int64",mt,[3,...Pt]),new u.Tensor("int64",Lt,[Lt.length,1])]}else{const[bt,Pt]=M.dims,mt=BigInt64Array.from({length:3*bt*Pt},(Lt,_t)=>BigInt(Math.floor(_t%Pt/bt)));return[new u.Tensor("int64",mt,[3,...M.dims]),(0,u.zeros)([bt,1])]}}async encode_image({pixel_values:M,image_grid_thw:j}){return(await W(this.sessions.vision_encoder,{pixel_values:M,grid_thw:j})).image_features}_merge_input_ids_with_image_features(M){return oe({image_token_id:this.config.image_token_id,...M})}prepare_inputs_for_generation(M,j,ae){if(j.attention_mask&&!j.position_ids)if(!j.past_key_values)[j.position_ids,j.rope_deltas]=this.get_rope_index(j.input_ids,j.image_grid_thw,j.video_grid_thw,j.attention_mask);else{j.pixel_values=null;const me=BigInt(Object.values(j.past_key_values)[0].dims.at(-2)),_e=j.rope_deltas.map(Se=>me+Se);j.position_ids=(0,u.stack)([_e,_e,_e],0)}return j}}class Ni extends z{}class $d extends Ni{}class kd extends Ni{}class ji extends z{}class Ad extends ji{}class Fd extends ji{}class Vi extends z{}class Od extends Vi{}class Dd extends Vi{}class Ui extends z{}class Ld extends Ui{}class zd extends Ui{}class Wi extends z{}class Bd extends Wi{}class Rd extends Wi{}class Gi extends z{}class Nd extends Gi{}class jd extends Gi{async _call(M){return new xt(await super._call(M))}}class Ki extends z{}class Vd extends Ki{}class Ud extends Ki{async _call(M){return new xt(await super._call(M))}}class Wd extends z{}class Gd extends Wd{}class Hi extends z{}class Kd extends Hi{}class Hd extends Hi{async _call(M){return new xt(await super._call(M))}}class qd extends z{}class Qd extends qd{}class qi extends z{}class Xd extends qi{}class Jd extends qi{async _call(M){return new xt(await super._call(M))}}class Yd extends z{}class Zd extends Yd{}class Qi extends z{}class ep extends Qi{}class tp extends Qi{async _call(M){return new xt(await super._call(M))}}class rp extends z{}class sp extends rp{async _call(M){return new Q_(await super._call(M))}}class Xi extends z{}class np extends Xi{}class op extends Xi{async _call(M){return new xt(await super._call(M))}}class Ji extends z{}class ap extends Ji{}class ip extends Ji{async _call(M){return new xt(await super._call(M))}}class Yi extends z{}class lp extends Yi{}class cp extends Yi{}class Zi extends z{}class up extends Zi{}class dp extends Zi{}class el extends z{}class pp extends el{}class mp extends el{async _call(M){return new xt(await super._call(M))}}class Ca extends z{}class hp extends Ca{}class _p extends Ca{async _call(M){return new rl(await super._call(M))}}class tl extends Ca{async _call(M){return new fp(await super._call(M))}}class rl extends de{constructor({logits:M,pred_boxes:j}){super(),this.logits=M,this.pred_boxes=j}}class fp extends de{constructor({logits:M,pred_boxes:j,pred_masks:ae}){super(),this.logits=M,this.pred_boxes=j,this.pred_masks=ae}}class sl extends z{}class gp extends sl{}class Mp extends sl{async _call(M){return new Fo(await super._call(M))}}class Fo extends de{constructor({logits:M,pred_boxes:j}){super(),this.logits=M,this.pred_boxes=j}}class nl extends z{}class wp extends nl{}class bp extends nl{async _call(M){return new yp(await super._call(M))}}class yp extends Fo{}class ol extends z{}class vp extends ol{}class xp extends ol{async _call(M){return new Tp(await super._call(M))}}class Tp extends Fo{}class al extends z{}class Ep extends al{}class Pp extends al{async _call(M){return new Fo(await super._call(M))}}class il extends z{}class Cp extends il{}class Sp extends il{async _call(M){return new Ip(await super._call(M))}}class Ip extends rl{}class ll extends z{}class $p extends ll{}class kp extends ll{async _call(M){return new xt(await super._call(M))}}class cl extends z{}class Ap extends cl{}class Fp extends cl{async _call(M){return new xt(await super._call(M))}}class ul extends z{}class Op extends ul{}class Dp extends ul{async _call(M){return new xt(await super._call(M))}}class Sa extends z{}class Lp extends Sa{}class zp extends Sa{async _call(M){return new xt(await super._call(M))}}class Bp extends Sa{}class dl extends z{}class Rp extends dl{}class Np extends dl{}class pl extends z{}class jp extends pl{}class Vp extends pl{}class Up extends z{}class Wp extends Up{}class Ia extends z{}class Gp extends Ia{}class Kp extends Ia{}class Hp extends Ia{}class qp extends z{}class Qp extends qp{}class Xp extends z{}class Jp extends Xp{}class Yp extends z{}class Zp extends Yp{}class ml extends z{}class em extends ml{}class tm extends ml{}class hl extends z{}class rm extends hl{}class sm extends hl{}class nm extends z{}class om extends nm{}class _l extends z{}class am extends _l{}class im extends _l{async _call(M){return new xt(await super._call(M))}}class fl extends z{}class lm extends fl{}class cm extends fl{async _call(M){return new xt(await super._call(M))}}class gl extends z{}class um extends gl{}class dm extends gl{async _call(M){return new xt(await super._call(M))}}class Ml extends z{}class pm extends Ml{}class mm extends Ml{async _call(M){return new xt(await super._call(M))}}class hm extends z{}class _m extends hm{}class fm extends z{}class gm extends fm{}class Mm extends z{}class wm extends Mm{}class wl extends z{}class bm extends wl{}class ym extends wl{async _call(M){return new vm(await super._call(M))}}class vm extends de{constructor({logits:M,pred_boxes:j}){super(),this.logits=M,this.pred_boxes=j}}class xm extends z{}class Tm extends xm{async get_image_embeddings({pixel_values:M}){return await re(this,{pixel_values:M})}async forward(M){!M.image_embeddings||!M.image_positional_embeddings?M={...M,...await this.get_image_embeddings(M)}:M={...M},M.input_labels??=(0,u.ones)(M.input_points.dims.slice(0,-1));const j={image_embeddings:M.image_embeddings,image_positional_embeddings:M.image_positional_embeddings};return M.input_points&&(j.input_points=M.input_points),M.input_labels&&(j.input_labels=M.input_labels),M.input_boxes&&(j.input_boxes=M.input_boxes),await W(this.sessions.prompt_encoder_mask_decoder,j)}async _call(M){return new Em(await super._call(M))}}class Em extends de{constructor({iou_scores:M,pred_masks:j}){super(),this.iou_scores=M,this.pred_masks=j}}class Pm extends de{constructor({iou_scores:M,pred_masks:j,object_score_logits:ae}){super(),this.iou_scores=M,this.pred_masks=j,this.object_score_logits=ae}}class Cm extends z{}class $a extends Cm{async get_image_embeddings({pixel_values:M}){return await re(this,{pixel_values:M})}async forward(M){const{num_feature_levels:j}=this.config.vision_config;if(Array.from({length:j},(Se,Le)=>`image_embeddings.${Le}`).some(Se=>!M[Se])?M={...M,...await this.get_image_embeddings(M)}:M={...M},M.input_points){if(M.input_boxes&&M.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");const Se=M.input_points.dims;M.input_labels??=(0,u.ones)(Se.slice(0,-1)),M.input_boxes??=(0,u.full)([Se[0],0,4],0)}else if(M.input_boxes){const Se=M.input_boxes.dims;M.input_labels=(0,u.full)([Se[0],Se[1],0],-1n),M.input_points=(0,u.full)([Se[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");const me=this.sessions.prompt_encoder_mask_decoder,_e=(0,a.pick)(M,me.inputNames);return await W(me,_e)}async _call(M){return new Pm(await super._call(M))}}class Sm extends $a{}class Im extends $a{}class bl extends z{}class $m extends bl{}class km extends bl{}class yl extends z{}class Am extends yl{}class Fm extends yl{}class tn extends z{}class Om extends tn{}class Dm extends tn{async _call(M){return new rn(await super._call(M))}}class Lm extends tn{async _call(M){return new xt(await super._call(M))}}class zm extends tn{async _call(M){return new Pr(await super._call(M))}}class Bm extends z{}class Rm extends Bm{async _call(M){return new rn(await super._call(M))}}class vl extends z{}class Nm extends vl{}class jm extends vl{async _call(M){return new Pr(await super._call(M))}}class Vm extends z{}class Um extends Vm{}class ka extends z{}class Wm extends ka{}class Gm extends ka{async _call(M){return new rn(await super._call(M))}}class Km extends ka{async _call(M){return new xt(await super._call(M))}}class Oo extends z{}class Hm extends Oo{}class qm extends Oo{async _call(M){return new rn(await super._call(M))}}class Qm extends Oo{async _call(M){return new xt(await super._call(M))}}class Xm extends Oo{async _call(M){return new Pr(await super._call(M))}}class Aa extends z{}class Jm extends Aa{}class Ym extends Aa{async _call(M){return new rn(await super._call(M))}}class Zm extends Aa{async _call(M){return new xt(await super._call(M))}}class Ev extends z{}class eh extends tn{}class th extends tn{async _call(M){return new rn(await super._call(M))}}class rh extends tn{async _call(M){return new xt(await super._call(M))}}class Jn extends z{}class sh extends Jn{}class nh extends Jn{async _call(M){return new rn(await super._call(M))}}class oh extends Jn{async _call(M){return new xt(await super._call(M))}}class ah extends Jn{async _call(M){return new q_(await super._call(M))}}class ih extends Jn{async _call(M){return new Pr(await super._call(M))}}class lh extends z{}class ch extends lh{}class Fa extends z{}class Pv extends Fa{}class uh extends Fa{}class dh extends Fa{async generate_speech(M,j,{threshold:ae=.5,minlenratio:me=0,maxlenratio:_e=20,vocoder:Se=null}={}){const Le={input_ids:M},{encoder_outputs:Ge,encoder_attention_mask:st}=await re(this,Le),wt=Ge.dims[1]/this.config.reduction_factor,bt=Math.floor(wt*_e),Pt=Math.floor(wt*me),mt=this.config.num_mel_bins;let Lt=[],_t=null,pt=null,Ft=0;for(;;){++Ft;const nr=X(!!pt);let pr;pt?pr=pt.output_sequence_out:pr=new u.Tensor("float32",new Float32Array(mt),[1,1,mt]);let fr={use_cache_branch:nr,output_sequence:pr,encoder_attention_mask:st,speaker_embeddings:j,encoder_hidden_states:Ge};this.addPastKeyValues(fr,_t),pt=await W(this.sessions.decoder_model_merged,fr),_t=this.getPastKeyValues(pt,_t);const{prob:At,spectrum:cr}=pt;if(Lt.push(cr),Ft>=Pt&&(Array.from(At.data).filter(kr=>kr>=ae).length>0||Ft>=bt))break}const Wt=(0,u.cat)(Lt),{waveform:er}=await W(Se.sessions.model,{spectrogram:Wt});return{spectrogram:Wt,waveform:er}}}class ph extends z{main_input_name="spectrogram"}class mh extends z{}class xl extends mh{async generate_speech({input_ids:M,attention_mask:j,style:ae,num_inference_steps:me=5,speed:_e=1.05}){const{sampling_rate:Se,chunk_compress_factor:Le,base_chunk_size:Ge,latent_dim:st}=this.config,{last_hidden_state:wt,durations:bt}=await W(this.sessions.text_encoder,{input_ids:M,attention_mask:j,style:ae});bt.div_(_e);const Pt=bt.max().item()*Se,mt=Ge*Le,Lt=Math.floor((Pt+mt-1)/mt),_t=M.dims[0],pt=(0,u.ones)([_t,Lt]),Ft=(0,u.full)([_t],me);let Wt=(0,u.randn)([_t,st*Le,Lt]);for(let nr=0;nr0&&Pt<=_e&&(M.data[Se++]=M.data[st])}const Le=Math.floor(j/me),Ge=Se/(Le*me);return new u.Tensor(M.type,M.data.slice(0,Se),[Le,me,Ge])}prepare_inputs_for_generation(M,j,ae){let me=structuredClone(M);for(let Se=0;Se=Le&&(me[Se][Le]=BigInt(this.config.decoder.pad_token_id));return ae.guidance_scale!==null&&ae.guidance_scale>1&&(me=me.concat(me)),super.prepare_inputs_for_generation(me,j,ae)}async generate(M){const j=await super.generate(M),ae=this._apply_and_filter_by_delay_pattern_mask(j).unsqueeze_(0),{audio_values:me}=await W(this.sessions.encodec_decode,{audio_codes:ae});return me}}class La extends z{}class Bh extends La{}class Rh extends La{async _call(M){return new xt(await super._call(M))}}class Nh extends La{}class za extends z{}class jh extends za{}class Vh extends za{async _call(M){return new xt(await super._call(M))}}class Uh extends za{}class Ba extends z{}class Wh extends Ba{}class Gh extends Ba{async _call(M){return new xt(await super._call(M))}}class Kh extends Ba{}class Ra extends z{}class Hh extends Ra{}class qh extends Ra{async _call(M){return new xt(await super._call(M))}}class Qh extends Ra{}class Xh extends z{}class Jh extends Xh{}class Yh extends z{}class Zh extends Yh{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...M){super(...M),this._generation_mode="text"}async forward(M){const j=this._generation_mode??"text";let ae;if(j==="text"||!M.past_key_values){const Ge=this.sessions.prepare_inputs_embeds,st=(0,a.pick)(M,Ge.inputNames);ae=await W(Ge,st)}else{const Ge=this.sessions.gen_img_embeds,st=(0,a.pick)({image_ids:M.input_ids},Ge.inputNames);ae=await W(Ge,st)}const me={...M,...ae},_e=await le(this,me),Se=this.sessions[j==="text"?"lm_head":"gen_head"];if(!Se)throw new Error(`Unable to find "${Se}" generation head`);const Le=await W(Se,(0,a.pick)(_e,Se.inputNames));return{...ae,..._e,...Le}}async generate(M){return this._generation_mode="text",super.generate(M)}async generate_images(M){this._generation_mode="image";const j=(M.inputs??M[this.main_input_name]).dims[1],me=(await super.generate(M)).slice(null,[j,null]),_e=this.sessions.image_decode,{decoded_image:Se}=await W(_e,{generated_tokens:me}),Le=Se.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Ge=[];for(const st of Le){const wt=f.RawImage.fromTensor(st);Ge.push(wt)}return Ge}}class e_ extends de{constructor({char_logits:M,bpe_logits:j,wp_logits:ae}){super(),this.char_logits=M,this.bpe_logits=j,this.wp_logits=ae}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class t_ extends z{}class r_ extends t_{async _call(M){return new e_(await super._call(M))}}class Dl extends z{}class s_ extends Dl{}class n_ extends Dl{}class Ll extends z{}class o_ extends Ll{}class a_ extends Ll{}class i_ extends z{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]}class zl extends i_{_merge_input_ids_with_audio_features(M){const j=M.audio_features.dims.at(-1),ae=M.audio_features.view(-1,j);return K({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...M,audio_features:ae})}}class l_ extends zl{}class Na extends z{main_input_name="input_values";forward_params=["input_values"]}class c_ extends de{constructor({audio_codes:M}){super(),this.audio_codes=M}}class u_ extends de{constructor({audio_values:M}){super(),this.audio_values=M}}class d_ extends Na{async encode(M){return new c_(await W(this.sessions.encoder_model,M))}async decode(M){return new u_(await W(this.sessions.decoder_model,M))}}class p_ extends Na{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"encoder_model"})}}class m_ extends Na{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"decoder_model"})}}class ja extends z{main_input_name="input_values";forward_params=["input_values"]}class h_ extends de{constructor({audio_codes:M}){super(),this.audio_codes=M}}class __ extends de{constructor({audio_values:M}){super(),this.audio_values=M}}class f_ extends ja{async encode(M){return new h_(await W(this.sessions.encoder_model,M))}async decode(M){return new __(await W(this.sessions.decoder_model,M))}}class g_ extends ja{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"encoder_model"})}}class M_ extends ja{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"decoder_model"})}}class Va extends z{main_input_name="input_values";forward_params=["input_values"]}class w_ extends Va{async encode(M){return await W(this.sessions.encoder_model,M)}async decode(M){return await W(this.sessions.decoder_model,M)}}class b_ extends Va{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"encoder_model"})}}class y_ extends Va{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"decoder_model"})}}class Ut{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(M,{progress_callback:j=null,config:ae=null,cache_dir:me=null,local_files_only:_e=!1,revision:Se="main",model_file_name:Le=null,subfolder:Ge="onnx",device:st=null,dtype:wt=null,use_external_data_format:bt=null,session_options:Pt={}}={}){const mt={progress_callback:j,config:ae,cache_dir:me,local_files_only:_e,revision:Se,model_file_name:Le,subfolder:Ge,device:st,dtype:wt,use_external_data_format:bt,session_options:Pt};if(mt.config=await s.AutoConfig.from_pretrained(M,mt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const Lt=mt.config.model_type;for(const _t of this.MODEL_CLASS_MAPPINGS){let pt=_t.get(Lt);if(!pt){for(const Ft of _t.values())if(Ft[0]===Lt){pt=Ft;break}if(!pt)continue}return await pt[1].from_pretrained(M,mt)}if(this.BASE_IF_FAIL)return H_.has(Lt)||console.warn(`Unknown model class "${Lt}", attempting to construct from base class.`),await z.from_pretrained(M,mt);throw Error(`Unsupported model type: ${Lt}`)}}const $v=new Map([["bert",["BertModel",xe]],["neobert",["NeoBertModel",We]],["modernbert",["ModernBertModel",Ne]],["nomic_bert",["NomicBertModel",zt]],["roformer",["RoFormerModel",qs]],["electra",["ElectraModel",yt]],["esm",["EsmModel",Rs]],["convbert",["ConvBertModel",Bs]],["camembert",["CamembertModel",Z]],["deberta",["DebertaModel",Mt]],["deberta-v2",["DebertaV2Model",ar]],["mpnet",["MPNetModel",Ns]],["albert",["AlbertModel",Xe]],["distilbert",["DistilBertModel",zr]],["roberta",["RobertaModel",po]],["xlm",["XLMModel",aa]],["xlm-roberta",["XLMRobertaModel",da]],["clap",["ClapModel",Sh]],["clip",["CLIPModel",vo]],["clipseg",["CLIPSegModel",Po]],["chinese_clip",["ChineseCLIPModel",Eo]],["siglip",["SiglipModel",To]],["jina_clip",["JinaCLIPModel",hn]],["mobilebert",["MobileBertModel",Nr]],["squeezebert",["SqueezeBertModel",U]],["wav2vec2",["Wav2Vec2Model",Om]],["wav2vec2-bert",["Wav2Vec2BertModel",Jm]],["unispeech",["UniSpeechModel",Wm]],["unispeech-sat",["UniSpeechSatModel",Hm]],["hubert",["HubertModel",eh]],["wavlm",["WavLMModel",sh]],["audio-spectrogram-transformer",["ASTModel",go]],["vits",["VitsModel",$l]],["pyannote",["PyAnnoteModel",Nm]],["wespeaker-resnet",["WeSpeakerResNetModel",Um]],["detr",["DetrModel",hp]],["rt_detr",["RTDetrModel",gp]],["rt_detr_v2",["RTDetrV2Model",wp]],["rf_detr",["RFDetrModel",vp]],["d_fine",["DFineModel",Ep]],["table-transformer",["TableTransformerModel",Cp]],["vit",["ViTModel",Nd]],["ijepa",["IJepaModel",Vd]],["pvt",["PvtModel",Kd]],["vit_msn",["ViTMSNModel",Xd]],["vit_mae",["ViTMAEModel",Qd]],["groupvit",["GroupViTModel",Zd]],["fastvit",["FastViTModel",ep]],["mobilevit",["MobileViTModel",np]],["mobilevitv2",["MobileViTV2Model",ap]],["owlvit",["OwlViTModel",lp]],["owlv2",["Owlv2Model",up]],["beit",["BeitModel",pp]],["deit",["DeiTModel",$p]],["hiera",["HieraModel",Ap]],["convnext",["ConvNextModel",am]],["convnextv2",["ConvNextV2Model",lm]],["dinov2",["Dinov2Model",um]],["dinov2_with_registers",["Dinov2WithRegistersModel",pm]],["dinov3_vit",["DINOv3ViTModel",_m]],["dinov3_convnext",["DINOv3ConvNextModel",gm]],["resnet",["ResNetModel",Op]],["swin",["SwinModel",Lp]],["swin2sr",["Swin2SRModel",Rp]],["donut-swin",["DonutSwinModel",om]],["yolos",["YolosModel",bm]],["dpt",["DPTModel",jp]],["glpn",["GLPNModel",rm]],["hifigan",["SpeechT5HifiGan",ph]],["efficientnet",["EfficientNetModel",Lh]],["decision_transformer",["DecisionTransformerModel",Jh]],["patchtst",["PatchTSTForPrediction",s_]],["patchtsmixer",["PatchTSMixerForPrediction",o_]],["mobilenet_v1",["MobileNetV1Model",Bh]],["mobilenet_v2",["MobileNetV2Model",jh]],["mobilenet_v3",["MobileNetV3Model",Wh]],["mobilenet_v4",["MobileNetV4Model",Hh]],["maskformer",["MaskFormerModel",em]],["mgp-str",["MgpstrForSceneTextRecognition",r_]],["style_text_to_speech_2",["StyleTextToSpeech2Model",ch]]]),kv=new Map([["t5",["T5Model",Et]],["longt5",["LongT5Model",Xt]],["mt5",["MT5Model",qr]],["bart",["BartModel",ds]],["mbart",["MBartModel",Xr]],["marian",["MarianModel",$m]],["whisper",["WhisperModel",ma]],["m2m_100",["M2M100Model",Am]],["blenderbot",["BlenderbotModel",Zt]],["blenderbot-small",["BlenderbotSmallModel",Ur]]]),Av=new Map([["mimi",["MimiModel",d_]],["dac",["DacModel",f_]],["snac",["SnacModel",w_]]]),Fv=new Map([["bloom",["BloomModel",Od]],["jais",["JAISModel",Io]],["gpt2",["GPT2Model",Kn]],["gptj",["GPTJModel",h]],["gpt_bigcode",["GPTBigCodeModel",L]],["gpt_neo",["GPTNeoModel",qn]],["gpt_neox",["GPTNeoXModel",ko]],["codegen",["CodeGenModel",Pe]],["llama",["LlamaModel",at]],["nanochat",["NanoChatModel",Us]],["arcee",["ArceeModel",Wu]],["lfm2",["Lfm2Model",Ku]],["smollm3",["SmolLM3Model",qu]],["exaone",["ExaoneModel",ed]],["olmo",["OlmoModel",nd]],["olmo2",["Olmo2Model",ad]],["mobilellm",["MobileLLMModel",rd]],["granite",["GraniteModel",ld]],["granitemoehybrid",["GraniteMoeHybridModel",ud]],["cohere",["CohereModel",pd]],["gemma",["GemmaModel",hd]],["gemma2",["Gemma2Model",fd]],["vaultgemma",["VaultGemmaModel",Md]],["gemma3_text",["Gemma3Model",bd]],["helium",["HeliumModel",Xu]],["glm",["GlmModel",Yu]],["openelm",["OpenELMModel",vd]],["qwen2",["Qwen2Model",Td]],["qwen3",["Qwen3Model",Pd]],["phi",["PhiModel",$d]],["phi3",["Phi3Model",Ad]],["mpt",["MptModel",Ld]],["opt",["OPTModel",Bd]],["mistral",["MistralModel",fh]],["ministral",["MinistralModel",Mh]],["ministral3",["Ministral3Model",bh]],["ernie4_5",["Ernie4_5Model",vh]],["starcoder2",["Starcoder2Model",Th]],["falcon",["FalconModel",Ph]],["stablelm",["StableLmModel",Oh]],["modernbert-decoder",["ModernBertDecoderModel",It]]]),Bl=new Map([["speecht5",["SpeechT5ForSpeechToText",uh]],["whisper",["WhisperForConditionalGeneration",Ln]],["lite-whisper",["LiteWhisperForConditionalGeneration",ha]],["moonshine",["MoonshineForConditionalGeneration",zn]]]),v_=new Map([["speecht5",["SpeechT5ForTextToSpeech",dh]]]),x_=new Map([["vits",["VitsModel",$l]],["musicgen",["MusicgenForConditionalGeneration",Ol]],["supertonic",["SupertonicForConditionalGeneration",xl]]]),T_=new Map([["bert",["BertForSequenceClassification",ge]],["neobert",["NeoBertForSequenceClassification",tt]],["modernbert",["ModernBertForSequenceClassification",ot]],["roformer",["RoFormerForSequenceClassification",Xs]],["electra",["ElectraForSequenceClassification",C]],["esm",["EsmForSequenceClassification",As]],["convbert",["ConvBertForSequenceClassification",qt]],["camembert",["CamembertForSequenceClassification",ye]],["deberta",["DebertaForSequenceClassification",Tt]],["deberta-v2",["DebertaV2ForSequenceClassification",Is]],["mpnet",["MPNetForSequenceClassification",js]],["albert",["AlbertForSequenceClassification",Je]],["distilbert",["DistilBertForSequenceClassification",ts]],["roberta",["RobertaForSequenceClassification",sa]],["xlm",["XLMForSequenceClassification",la]],["xlm-roberta",["XLMRobertaForSequenceClassification",ho]],["bart",["BartForSequenceClassification",hr]],["mbart",["MBartForSequenceClassification",yr]],["mobilebert",["MobileBertForSequenceClassification",Ue]],["squeezebert",["SqueezeBertForSequenceClassification",se]]]),E_=new Map([["bert",["BertForTokenClassification",De]],["neobert",["NeoBertForTokenClassification",Re]],["modernbert",["ModernBertForTokenClassification",ht]],["roformer",["RoFormerForTokenClassification",or]],["electra",["ElectraForTokenClassification",q]],["esm",["EsmForTokenClassification",Fs]],["convbert",["ConvBertForTokenClassification",Ps]],["camembert",["CamembertForTokenClassification",et]],["deberta",["DebertaForTokenClassification",kt]],["deberta-v2",["DebertaV2ForTokenClassification",Dr]],["mpnet",["MPNetForTokenClassification",Dn]],["distilbert",["DistilBertForTokenClassification",wr]],["roberta",["RobertaForTokenClassification",na]],["xlm",["XLMForTokenClassification",ca]],["xlm-roberta",["XLMRobertaForTokenClassification",_o]]]),Rl=new Map([["t5",["T5ForConditionalGeneration",rr]],["longt5",["LongT5ForConditionalGeneration",sr]],["mt5",["MT5ForConditionalGeneration",ns]],["bart",["BartForConditionalGeneration",Yt]],["mbart",["MBartForConditionalGeneration",ps]],["marian",["MarianMTModel",km]],["m2m_100",["M2M100ForConditionalGeneration",Fm]],["blenderbot",["BlenderbotForConditionalGeneration",_r]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Js]]]),Nl=new Map([["bloom",["BloomForCausalLM",Dd]],["gpt2",["GPT2LMHeadModel",So]],["jais",["JAISLMHeadModel",gn]],["gptj",["GPTJForCausalLM",P]],["gpt_bigcode",["GPTBigCodeForCausalLM",V]],["gpt_neo",["GPTNeoForCausalLM",$o]],["gpt_neox",["GPTNeoXForCausalLM",Ao]],["codegen",["CodeGenForCausalLM",Be]],["llama",["LlamaForCausalLM",vt]],["nanochat",["NanoChatForCausalLM",Pa]],["llama4_text",["Llama4ForCausalLM",Vt]],["arcee",["ArceeForCausalLM",Gu]],["lfm2",["Lfm2ForCausalLM",Hu]],["smollm3",["SmolLM3ForCausalLM",Qu]],["exaone",["ExaoneForCausalLM",td]],["olmo",["OlmoForCausalLM",od]],["olmo2",["Olmo2ForCausalLM",id]],["mobilellm",["MobileLLMForCausalLM",sd]],["granite",["GraniteForCausalLM",cd]],["granitemoehybrid",["GraniteMoeHybridForCausalLM",dd]],["cohere",["CohereForCausalLM",md]],["gemma",["GemmaForCausalLM",_d]],["gemma2",["Gemma2ForCausalLM",gd]],["vaultgemma",["VaultGemmaForCausalLM",wd]],["gemma3_text",["Gemma3ForCausalLM",yd]],["helium",["HeliumForCausalLM",Ju]],["glm",["GlmForCausalLM",Zu]],["openelm",["OpenELMForCausalLM",xd]],["qwen2",["Qwen2ForCausalLM",Ed]],["qwen3",["Qwen3ForCausalLM",Cd]],["phi",["PhiForCausalLM",kd]],["phi3",["Phi3ForCausalLM",Fd]],["mpt",["MptForCausalLM",zd]],["opt",["OPTForCausalLM",Rd]],["mbart",["MBartForCausalLM",os]],["mistral",["MistralForCausalLM",gh]],["ministral",["MinistralForCausalLM",wh]],["ministral3",["Ministral3ForCausalLM",yh]],["ernie4_5",["Ernie4_5ForCausalLM",xh]],["starcoder2",["Starcoder2ForCausalLM",Eh]],["falcon",["FalconForCausalLM",Ch]],["trocr",["TrOCRForCausalLM",_h]],["stablelm",["StableLmForCausalLM",Dh]],["modernbert-decoder",["ModernBertDecoderForCausalLM",gr]],["phi3_v",["Phi3VForCausalLM",Un]]]),Ov=new Map([["multi_modality",["MultiModalityCausalLM",Zh]]]),P_=new Map([["bert",["BertForMaskedLM",Ce]],["neobert",["NeoBertForMaskedLM",Fe]],["modernbert",["ModernBertForMaskedLM",Oe]],["roformer",["RoFormerForMaskedLM",Qs]],["electra",["ElectraForMaskedLM",Ss]],["esm",["EsmForMaskedLM",ks]],["convbert",["ConvBertForMaskedLM",ft]],["camembert",["CamembertForMaskedLM",ce]],["deberta",["DebertaForMaskedLM",qe]],["deberta-v2",["DebertaV2ForMaskedLM",Tr]],["mpnet",["MPNetForMaskedLM",Os]],["albert",["AlbertForMaskedLM",Ke]],["distilbert",["DistilBertForMaskedLM",Hr]],["roberta",["RobertaForMaskedLM",ra]],["xlm",["XLMWithLMHeadModel",ia]],["xlm-roberta",["XLMRobertaForMaskedLM",mo]],["mobilebert",["MobileBertForMaskedLM",ze]],["squeezebert",["SqueezeBertForMaskedLM",ee]]]),C_=new Map([["bert",["BertForQuestionAnswering",fe]],["neobert",["NeoBertForQuestionAnswering",rt]],["roformer",["RoFormerForQuestionAnswering",Sr]],["electra",["ElectraForQuestionAnswering",R]],["convbert",["ConvBertForQuestionAnswering",Cs]],["camembert",["CamembertForQuestionAnswering",ut]],["deberta",["DebertaForQuestionAnswering",Mr]],["deberta-v2",["DebertaV2ForQuestionAnswering",$s]],["mpnet",["MPNetForQuestionAnswering",ue]],["albert",["AlbertForQuestionAnswering",Ye]],["distilbert",["DistilBertForQuestionAnswering",ir]],["roberta",["RobertaForQuestionAnswering",oa]],["xlm",["XLMForQuestionAnswering",ua]],["xlm-roberta",["XLMRobertaForQuestionAnswering",pa]],["mobilebert",["MobileBertForQuestionAnswering",nt]],["squeezebert",["SqueezeBertForQuestionAnswering",Me]]]),jl=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Bn]],["idefics3",["Idefics3ForConditionalGeneration",jn]],["smolvlm",["SmolVLMForConditionalGeneration",dn]]]),S_=new Map([["llava",["LlavaForConditionalGeneration",Rn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",_a]],["moondream1",["Moondream1ForConditionalGeneration",fa]],["florence2",["Florence2ForConditionalGeneration",Ma]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Id]],["idefics3",["Idefics3ForConditionalGeneration",jn]],["smolvlm",["SmolVLMForConditionalGeneration",dn]],["paligemma",["PaliGemmaForConditionalGeneration",ba]],["llava_qwen2",["LlavaQwen2ForCausalLM",yo]],["gemma3n",["Gemma3nForConditionalGeneration",Nn]],["mistral3",["Mistral3ForConditionalGeneration",un]]]),I_=new Map([["ultravox",["UltravoxModel",zl]],["voxtral",["VoxtralForConditionalGeneration",l_]]]),Dv=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Bn]]]),$_=new Map([["vit",["ViTForImageClassification",jd]],["ijepa",["IJepaForImageClassification",Ud]],["pvt",["PvtForImageClassification",Hd]],["vit_msn",["ViTMSNForImageClassification",Jd]],["fastvit",["FastViTForImageClassification",tp]],["mobilevit",["MobileViTForImageClassification",op]],["mobilevitv2",["MobileViTV2ForImageClassification",ip]],["beit",["BeitForImageClassification",mp]],["deit",["DeiTForImageClassification",kp]],["hiera",["HieraForImageClassification",Fp]],["convnext",["ConvNextForImageClassification",im]],["convnextv2",["ConvNextV2ForImageClassification",cm]],["dinov2",["Dinov2ForImageClassification",dm]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",mm]],["resnet",["ResNetForImageClassification",Dp]],["swin",["SwinForImageClassification",zp]],["segformer",["SegformerForImageClassification",Ah]],["efficientnet",["EfficientNetForImageClassification",zh]],["mobilenet_v1",["MobileNetV1ForImageClassification",Rh]],["mobilenet_v2",["MobileNetV2ForImageClassification",Vh]],["mobilenet_v3",["MobileNetV3ForImageClassification",Gh]],["mobilenet_v4",["MobileNetV4ForImageClassification",qh]]]),k_=new Map([["detr",["DetrForObjectDetection",_p]],["rt_detr",["RTDetrForObjectDetection",Mp]],["rt_detr_v2",["RTDetrV2ForObjectDetection",bp]],["rf_detr",["RFDetrForObjectDetection",xp]],["d_fine",["DFineForObjectDetection",Pp]],["table-transformer",["TableTransformerForObjectDetection",Sp]],["yolos",["YolosForObjectDetection",ym]]]),A_=new Map([["owlvit",["OwlViTForObjectDetection",cp]],["owlv2",["Owlv2ForObjectDetection",dp]],["grounding-dino",["GroundingDinoForObjectDetection",wm]]]),Yn=new Map([["detr",["DetrForSegmentation",tl]],["clipseg",["CLIPSegForImageSegmentation",Co]]]),F_=new Map([["segformer",["SegformerForSemanticSegmentation",Fh]],["sapiens",["SapiensForSemanticSegmentation",Gp]],["swin",["SwinForSemanticSegmentation",Bp]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",Nh]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",Uh]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Kh]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Qh]]]),O_=new Map([["detr",["DetrForSegmentation",tl]],["maskformer",["MaskFormerForInstanceSegmentation",tm]]]),D_=new Map([["sam",["SamModel",Tm]],["sam2",["Sam2Model",$a]],["edgetam",["EdgeTamModel",Sm]],["sam3_tracker",["Sam3TrackerModel",Im]]]),L_=new Map([["wav2vec2",["Wav2Vec2ForCTC",Dm]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Ym]],["unispeech",["UniSpeechForCTC",Gm]],["unispeech-sat",["UniSpeechSatForCTC",qm]],["wavlm",["WavLMForCTC",nh]],["hubert",["HubertForCTC",th]],["parakeet_ctc",["ParakeetForCTC",Rm]]]),z_=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Lm]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Zm]],["unispeech",["UniSpeechForSequenceClassification",Km]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Qm]],["wavlm",["WavLMForSequenceClassification",oh]],["hubert",["HubertForSequenceClassification",rh]],["audio-spectrogram-transformer",["ASTForAudioClassification",Mo]]]),B_=new Map([["wavlm",["WavLMForXVector",ah]]]),R_=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Xm]],["wavlm",["WavLMForAudioFrameClassification",ih]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",zm]],["pyannote",["PyAnnoteForAudioFrameClassification",jm]]]),N_=new Map([["vitmatte",["VitMatteForImageMatting",sp]]]),Lv=new Map([["patchtst",["PatchTSTForPrediction",n_]],["patchtsmixer",["PatchTSMixerForPrediction",a_]]]),j_=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Np]]]),V_=new Map([["dpt",["DPTForDepthEstimation",Vp]],["depth_anything",["DepthAnythingForDepthEstimation",Wp]],["glpn",["GLPNForDepthEstimation",sm]],["sapiens",["SapiensForDepthEstimation",Kp]],["depth_pro",["DepthProForDepthEstimation",Qp]],["metric3d",["Metric3DForDepthEstimation",Jp]],["metric3dv2",["Metric3Dv2ForDepthEstimation",Zp]]]),U_=new Map([["sapiens",["SapiensForNormalEstimation",Hp]]]),W_=new Map([["vitpose",["VitPoseForPoseEstimation",Gd]]]),G_=new Map([["clip",["CLIPVisionModelWithProjection",Ta]],["siglip",["SiglipVisionModel",dt]],["jina_clip",["JinaCLIPVisionModel",_n]]]),K_=[[$v,T.EncoderOnly],[kv,T.EncoderDecoder],[Fv,T.DecoderOnly],[Av,T.AutoEncoder],[T_,T.EncoderOnly],[E_,T.EncoderOnly],[Rl,T.Seq2Seq],[Bl,T.Seq2Seq],[Nl,T.DecoderOnly],[Ov,T.MultiModality],[P_,T.EncoderOnly],[C_,T.EncoderOnly],[jl,T.Vision2Seq],[S_,T.ImageTextToText],[I_,T.AudioTextToText],[$_,T.EncoderOnly],[Yn,T.EncoderOnly],[O_,T.EncoderOnly],[F_,T.EncoderOnly],[N_,T.EncoderOnly],[Lv,T.EncoderOnly],[j_,T.EncoderOnly],[V_,T.EncoderOnly],[U_,T.EncoderOnly],[W_,T.EncoderOnly],[k_,T.EncoderOnly],[A_,T.EncoderOnly],[D_,T.MaskGeneration],[L_,T.EncoderOnly],[z_,T.EncoderOnly],[v_,T.Seq2Seq],[x_,T.EncoderOnly],[B_,T.EncoderOnly],[R_,T.EncoderOnly],[G_,T.EncoderOnly]];for(const[g,M]of K_)for(const[j,ae]of g.values())b.set(j,M),x.set(ae,j),E.set(j,ae);const zv=[["MusicgenForConditionalGeneration",Ol,T.Musicgen],["Phi3VForCausalLM",Un,T.Phi3V],["CLIPTextModelWithProjection",xo,T.EncoderOnly],["SiglipTextModel",pn,T.EncoderOnly],["JinaCLIPTextModel",Jr,T.EncoderOnly],["ClapTextModelWithProjection",Ih,T.EncoderOnly],["ClapAudioModelWithProjection",$h,T.EncoderOnly],["DacEncoderModel",g_,T.EncoderOnly],["DacDecoderModel",M_,T.EncoderOnly],["MimiEncoderModel",p_,T.EncoderOnly],["MimiDecoderModel",m_,T.EncoderOnly],["SnacEncoderModel",b_,T.EncoderOnly],["SnacDecoderModel",y_,T.EncoderOnly],["Gemma3nForConditionalGeneration",Nn,T.ImageAudioTextToText],["SupertonicForConditionalGeneration",xl,T.Supertonic]];for(const[g,M,j]of zv)b.set(g,j),x.set(M,g),E.set(g,M);const H_=new Map([["modnet",Yn],["birefnet",Yn],["isnet",Yn],["ben",Yn]]);for(const[g,M]of H_.entries())M.set(g,["PreTrainedModel",z]),b.set(g,T.EncoderOnly),x.set(z,g),E.set(g,z);class Bv extends Ut{static MODEL_CLASS_MAPPINGS=K_.map(M=>M[0]);static BASE_IF_FAIL=!0}class Rv extends Ut{static MODEL_CLASS_MAPPINGS=[T_]}class Nv extends Ut{static MODEL_CLASS_MAPPINGS=[E_]}class jv extends Ut{static MODEL_CLASS_MAPPINGS=[Rl]}class Vv extends Ut{static MODEL_CLASS_MAPPINGS=[Bl]}class Uv extends Ut{static MODEL_CLASS_MAPPINGS=[v_]}class Wv extends Ut{static MODEL_CLASS_MAPPINGS=[x_]}class Gv extends Ut{static MODEL_CLASS_MAPPINGS=[Nl]}class Kv extends Ut{static MODEL_CLASS_MAPPINGS=[P_]}class Hv extends Ut{static MODEL_CLASS_MAPPINGS=[C_]}class qv extends Ut{static MODEL_CLASS_MAPPINGS=[jl]}class Qv extends Ut{static MODEL_CLASS_MAPPINGS=[$_]}class Xv extends Ut{static MODEL_CLASS_MAPPINGS=[Yn]}class Jv extends Ut{static MODEL_CLASS_MAPPINGS=[F_]}class Yv extends Ut{static MODEL_CLASS_MAPPINGS=[O_]}class Zv extends Ut{static MODEL_CLASS_MAPPINGS=[k_]}class ex extends Ut{static MODEL_CLASS_MAPPINGS=[A_]}class tx extends Ut{static MODEL_CLASS_MAPPINGS=[D_]}class rx extends Ut{static MODEL_CLASS_MAPPINGS=[L_]}class sx extends Ut{static MODEL_CLASS_MAPPINGS=[z_]}class nx extends Ut{static MODEL_CLASS_MAPPINGS=[B_]}class ox extends Ut{static MODEL_CLASS_MAPPINGS=[R_]}class ax extends Ut{static MODEL_CLASS_MAPPINGS=[Dv]}class ix extends Ut{static MODEL_CLASS_MAPPINGS=[N_]}class lx extends Ut{static MODEL_CLASS_MAPPINGS=[j_]}class cx extends Ut{static MODEL_CLASS_MAPPINGS=[V_]}class ux extends Ut{static MODEL_CLASS_MAPPINGS=[U_]}class dx extends Ut{static MODEL_CLASS_MAPPINGS=[W_]}class px extends Ut{static MODEL_CLASS_MAPPINGS=[G_]}class mx extends Ut{static MODEL_CLASS_MAPPINGS=[S_]}class hx extends Ut{static MODEL_CLASS_MAPPINGS=[I_]}class _x extends de{constructor({logits:M,past_key_values:j,encoder_outputs:ae,decoder_attentions:me=null,cross_attentions:_e=null}){super(),this.logits=M,this.past_key_values=j,this.encoder_outputs=ae,this.decoder_attentions=me,this.cross_attentions=_e}}class xt extends de{constructor({logits:M,...j}){super(),this.logits=M;const ae=Object.values(j);ae.length>0&&(this.attentions=ae)}}class q_ extends de{constructor({logits:M,embeddings:j}){super(),this.logits=M,this.embeddings=j}}class Pr extends de{constructor({logits:M}){super(),this.logits=M}}class $r extends de{constructor({logits:M}){super(),this.logits=M}}class Br extends de{constructor({start_logits:M,end_logits:j}){super(),this.start_logits=M,this.end_logits=j}}class rn extends de{constructor({logits:M}){super(),this.logits=M}}class fx extends de{constructor({logits:M,past_key_values:j}){super(),this.logits=M,this.past_key_values=j}}class Q_ extends de{constructor({alphas:M}){super(),this.alphas=M}}class X_ extends de{constructor({waveform:M,spectrogram:j}){super(),this.waveform=M,this.spectrogram=j}}}),"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":((e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,c=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=c,this.window=(0,n.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(a,l){return(0,n.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:l,transpose:!0})}async _call(a){(0,s.validate_audio_inputs)(a,"ASTFeatureExtractor");const l=await this._extract_fbank_features(a,this.config.max_length);if(this.config.do_normalize){const c=this.std*2,p=l.data;for(let d=0;d{t.r(r),t.d(r,{AutoFeatureExtractor:()=>i});var s=t("./src/utils/constants.js"),n=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var o=t("./src/models/feature_extractors.js");class i{static async from_pretrained(l,c={}){const p=await(0,n.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,c),d=p.feature_extractor_type,u=o[d];if(!u)throw new Error(`Unknown feature_extractor_type: '${d}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new u(p)}}}),"./src/models/auto/image_processing_auto.js":((e,r,t)=>{t.r(r),t.d(r,{AutoImageProcessor:()=>a});var s=t("./src/utils/constants.js"),n=t("./src/utils/hub.js"),o=t("./src/base/image_processors_utils.js"),i=t("./src/models/image_processors.js");class a{static async from_pretrained(c,p={}){const d=await(0,n.getModelJSON)(c,s.IMAGE_PROCESSOR_NAME,!0,p),u=d.image_processor_type??d.feature_extractor_type;let f=i[u?.replace(/Fast$/,"")];return f||(u!==void 0&&console.warn(`Image processor type '${u}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),f=o.ImageProcessor),new f(d)}}}),"./src/models/auto/processing_auto.js":((e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>c});var s=t("./src/utils/constants.js"),n=t("./src/utils/hub.js"),o=t("./src/base/processing_utils.js"),i=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class c{static async from_pretrained(d,u={}){const f=await(0,n.getModelJSON)(d,s.IMAGE_PROCESSOR_NAME,!0,u),{image_processor_type:_,feature_extractor_type:y,processor_class:k}=f;if(k&&i[k])return i[k].from_pretrained(d,u);if(!_&&!y)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const w={};if(_){const I=a[_.replace(/Fast$/,"")];if(!I)throw new Error(`Unknown image_processor_type: '${_}'.`);w.image_processor=new I(f)}if(y){const I=a[y];if(I)w.image_processor=new I(f);else{const T=l[y];if(!T)throw new Error(`Unknown feature_extractor_type: '${y}'.`);w.feature_extractor=new T(f)}}const v={};return new o.Processor(v,w,null)}}}),"./src/models/beit/image_processing_beit.js":((e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/bit/image_processing_bit.js":((e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/chinese_clip/image_processing_chinese_clip.js":((e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/clap/feature_extraction_clap.js":((e,r,t)=>{t.r(r),t.d(r,{ClapFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,n.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,n.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,n.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,c,p){let d;const u=a.length-l;if(u>0)if(c==="rand_trunc"){const f=Math.floor(Math.random()*(u+1));a=a.subarray(f,f+l),d=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${c}" not implemented`);else{if(u<0){let f=new Float64Array(l);if(f.set(a),p==="repeat")for(let _=a.length;_{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>o,CLIPImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/convnext/image_processing_convnext.js":((e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>o,ConvNextImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){const l=this.size?.shortest_edge;if(l===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(l<384){const c=Math.floor(l/this.crop_pct),[p,d]=this.get_resize_output_image_size(a,{shortest_edge:c});a=await a.resize(p,d,{resample:this.resample}),a=await a.center_crop(l,l)}else a=await a.resize(l,l,{resample:this.resample});return a}}class o extends n{}}),"./src/models/dac/feature_extraction_dac.js":((e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>n});var s=t("./src/models/encodec/feature_extraction_encodec.js");class n extends s.EncodecFeatureExtractor{}}),"./src/models/deit/image_processing_deit.js":((e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>o,DeiTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/detr/image_processing_detr.js":((e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{async _call(l){const c=await super._call(l),p=[c.pixel_values.dims[0],64,64],d=(0,n.full)(p,1n);return{...c,pixel_mask:d}}post_process_object_detection(...l){return(0,s.post_process_object_detection)(...l)}post_process_panoptic_segmentation(...l){return(0,s.post_process_panoptic_segmentation)(...l)}post_process_instance_segmentation(...l){return(0,s.post_process_instance_segmentation)(...l)}}class i extends o{}}),"./src/models/dinov3_vit/image_processing_dinov3_vit.js":((e,r,t)=>{t.r(r),t.d(r,{DINOv3ViTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/donut/image_processing_donut.js":((e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>o,DonutImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{pad_image(a,l,c,p={}){const[d,u,f]=l;let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(f).fill(_));let y=this.image_std;Array.isArray(y)||(y=new Array(f).fill(_));const k=_.map((w,v)=>-w/y[v]);return super.pad_image(a,l,c,{center:!0,constant_values:k,...p})}}class o extends n{}}),"./src/models/dpt/image_processing_dpt.js":((e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>o,DPTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/efficientnet/image_processing_efficientnet.js":((e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{constructor(i){super(i),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(a=>a*a))}}}),"./src/models/encodec/feature_extraction_encodec.js":((e,r,t)=>{t.r(r),t.d(r,{EncodecFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js");class o extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"EncodecFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=this.config.feature_size;if(a.length%l!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${l}).`);const c=[1,l,a.length/l];return{input_values:new n.Tensor("float32",a,c)}}}}),"./src/models/feature_extractors.js":((e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>o.ClapFeatureExtractor,DacFeatureExtractor:()=>i.DacFeatureExtractor,EncodecFeatureExtractor:()=>n.EncodecFeatureExtractor,Gemma3nAudioFeatureExtractor:()=>a.Gemma3nAudioFeatureExtractor,ImageFeatureExtractor:()=>w.ImageProcessor,MoonshineFeatureExtractor:()=>l.MoonshineFeatureExtractor,ParakeetFeatureExtractor:()=>c.ParakeetFeatureExtractor,PyAnnoteFeatureExtractor:()=>p.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>u.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>f.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>_.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>y.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>k.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),n=t("./src/models/encodec/feature_extraction_encodec.js"),o=t("./src/models/clap/feature_extraction_clap.js"),i=t("./src/models/dac/feature_extraction_dac.js"),a=t("./src/models/gemma3n/feature_extraction_gemma3n.js"),l=t("./src/models/moonshine/feature_extraction_moonshine.js"),c=t("./src/models/parakeet/feature_extraction_parakeet.js"),p=t("./src/models/pyannote/feature_extraction_pyannote.js"),d=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),u=t("./src/models/snac/feature_extraction_snac.js"),f=t("./src/models/speecht5/feature_extraction_speecht5.js"),_=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),y=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),k=t("./src/models/whisper/feature_extraction_whisper.js"),w=t("./src/base/image_processors_utils.js")}),"./src/models/florence2/processing_florence2.js":((e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;constructor(l,c,p){super(l,c,p);const{tasks_answer_post_processing_type:d,task_prompts_without_inputs:u,task_prompts_with_input:f}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(d??{})),this.task_prompts_without_inputs=new Map(Object.entries(u??{})),this.task_prompts_with_input=new Map(Object.entries(f??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const c=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))c.push(this.task_prompts_without_inputs.get(p));else{for(const[d,u]of this.task_prompts_with_input)if(p.includes(d)){c.push(u.replaceAll("{input}",p).replaceAll(d,""));break}c.length!==l.length&&c.push(p)}return c}post_process_generation(l,c,p){const d=this.tasks_answer_post_processing_type.get(c)??"pure_text";l=l.replaceAll("","").replaceAll("","");let u;switch(d){case"pure_text":u=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const f=d==="ocr"?"quad_boxes":"bboxes",_=l.matchAll(this.regexes[f]),y=[],k=[];for(const[w,v,...I]of _)y.push(v?v.trim():y.at(-1)??""),k.push(I.map((T,b)=>(Number(T)+.5)/this.size_per_bin*p[b%2]));u={labels:y,[f]:k};break;default:throw new Error(`Task "${c}" (of type "${d}") not yet implemented.`)}return{[c]:u}}async _call(l,c=null,p={}){if(!l&&!c)throw new Error("Either text or images must be provided");const d=await this.image_processor(l,p),u=c?this.tokenizer(this.construct_prompts(c),p):{};return{...d,...u}}}}),"./src/models/gemma3n/feature_extraction_gemma3n.js":((e,r,t)=>{t.r(r),t.d(r,{Gemma3nAudioFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const{fft_length:c,feature_size:p,min_frequency:d,max_frequency:u,sampling_rate:f,frame_length:_}=this.config,y=(0,o.mel_filter_bank)(Math.floor(1+c/2),p,d,u,f,null,"htk",!1);this.mel_filters=y,this.window=(0,o.window_function)(_,"hann")}async _extract_fbank_features(l,c){return(0,o.spectrogram)(l,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(l,{max_length:c=48e4,truncation:p=!0,padding:d=!0,pad_to_multiple_of:u=128}={}){if((0,s.validate_audio_inputs)(l,"Gemma3nAudioFeatureExtractor"),p&&l.length>c&&(l=l.slice(0,c)),d&&l.length%u!==0){const y=u-l.length%u,k=new Float64Array(l.length+y);k.set(l),this.config.padding_value!==0&&k.fill(this.config.padding_value,l.length),l=k}const f=await this._extract_fbank_features(l,this.config.max_length),_=(0,n.full)([1,f.dims[0]],!0);return{input_features:f.unsqueeze_(0),input_features_mask:_}}}}),"./src/models/gemma3n/processing_gemma3n.js":((e,r,t)=>{t.r(r),t.d(r,{Gemma3nProcessor:()=>a});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js");t("./src/utils/image.js"),t("./src/utils/audio.js");class a extends s.Processor{static image_processor_class=n.AutoImageProcessor;static feature_extractor_class=o.AutoFeatureExtractor;static tokenizer_class=i.AutoTokenizer;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(c,p,d){super(c,p,d),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:u,boa_token:f,audio_token:_,eoa_token:y,image_token_id:k,boi_token:w,image_token:v,eoi_token:I}=this.tokenizer.config;this.audio_token_id=u,this.boa_token=f,this.audio_token=_;const T=_.repeat(this.audio_seq_length);this.full_audio_sequence=` + +${f}${T}${y} + +`,this.image_token_id=k,this.boi_token=w,this.image_token=v;const b=v.repeat(this.image_seq_length);this.full_image_sequence=` + +${w}${b}${I} + +`}async _call(c,p=null,d=null,u={}){typeof c=="string"&&(c=[c]);let f;d&&(f=await this.feature_extractor(d,u),c=c.map(k=>k.replaceAll(this.audio_token,this.full_audio_sequence)));let _;return p&&(_=await this.image_processor(p,u),c=c.map(k=>k.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(c,u),..._,...f}}}}),"./src/models/glpn/image_processing_glpn.js":((e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/grounding_dino/image_processing_grounding_dino.js":((e,r,t)=>{t.r(r),t.d(r,{GroundingDinoImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{async _call(a){const l=await super._call(a),c=l.pixel_values.dims,p=(0,n.ones)([c[0],c[2],c[3]]);return{...l,pixel_mask:p}}}}),"./src/models/grounding_dino/processing_grounding_dino.js":((e,r,t)=>{t.r(r),t.d(r,{GroundingDinoProcessor:()=>l});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js"),i=t("./src/base/image_processors_utils.js");function a(c,p){const u=c.dims.at(-1)-1,f=c.tolist();f.fill(!1,0,1),f.fill(!1,u);const _=p.tolist();return f.map((y,k)=>y?k:null).filter(y=>y!==null).map(y=>_[y])}class l extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;async _call(p,d,u={}){const f=p?await this.image_processor(p,u):{};return{...d?this.tokenizer(d,u):{},...f}}post_process_grounded_object_detection(p,d,{box_threshold:u=.25,text_threshold:f=.25,target_sizes:_=null}={}){const{logits:y,pred_boxes:k}=p,w=y.dims[0];if(_!==null&&_.length!==w)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const v=y.dims.at(1),I=y.sigmoid(),T=I.max(-1).tolist(),b=k.tolist().map(x=>x.map(S=>(0,i.center_to_corners_format)(S))),E=[];for(let x=0;xB.map((Y,X)=>Y*S[(X+1)%2])));const O=T[x],F=[],H=[],W=[];for(let B=0;B{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{constructor(a){super(a),this.do_image_splitting=a.do_image_splitting??!0,this.max_image_size=a.max_image_size}get_resize_for_vision_encoder(a,l){let[c,p]=a.dims.slice(-2);const d=p/c;return p>=c?(p=Math.ceil(p/l)*l,c=Math.floor(p/d),c=Math.ceil(c/l)*l):(c=Math.ceil(c/l)*l,p=Math.floor(c*d),p=Math.ceil(p/l)*l),{height:c,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:c=!1}={}){let p;if(!Array.isArray(a))p=[[a]];else{if(a.length===0||!a[0])throw new Error("No images provided.");Array.isArray(a[0])?p=a:p=[a]}let d=[],u=[],f=[];const _=[],y=[];for(const x of p){let S=await Promise.all(x.map(H=>this.preprocess(H)));_.push(...S.map(H=>H.original_size)),y.push(...S.map(H=>H.reshaped_input_size)),S.forEach(H=>H.pixel_values.unsqueeze_(0));const{longest_edge:O}=this.max_image_size;let F;if(l??this.do_image_splitting){let H=new Array(S.length),W=new Array(S.length);F=await Promise.all(S.map(async(B,Y)=>{const X=this.get_resize_for_vision_encoder(B.pixel_values,O),J=await(0,n.interpolate_4d)(B.pixel_values,{size:[X.height,X.width]}),{frames:re,num_splits_h:ne,num_splits_w:le}=await this.split_image(J,this.max_image_size);return H[Y]=ne,W[Y]=le,(0,n.cat)(re,0)})),u.push(H),f.push(W)}else{const H=[O,O];F=await Promise.all(S.map(W=>(0,n.interpolate_4d)(W.pixel_values,{size:H}))),u.push(new Array(S.length).fill(0)),f.push(new Array(S.length).fill(0))}d.push((0,n.cat)(F,0))}const k=d.length,[w,v,I,T]=d[0].dims;let b,E;if(k===1)b=d[0].unsqueeze_(0),E=(0,n.full)([k,w,I,T],!0);else{const x=Math.max(...d.map(F=>F.dims.at(0)));E=(0,n.full)([k,x,I,T],!0);const S=E.data,O=x*I*T;for(let F=0;Fc||f>p){_=Math.ceil(u/c),y=Math.ceil(f/p);const k=Math.ceil(u/_),w=Math.ceil(f/y);for(let T=0;T<_;++T)for(let b=0;b{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");var i=t("./src/utils/core.js");function a(d,u,f,_,y,k){let w="";for(let v=0;v`+y.repeat(d);w+=` +`}return w+=` +${_}${k}`+y.repeat(d)+`${_}`,w}function l(d,u,f,_){return`${u}${_}`+f.repeat(d)+`${u}`}function c(d,u,f,_,y,k){return d===0&&u===0?l(f,_,y,k):a(f,d,u,_,y,k)}class p extends s.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(u,f=null,_={}){_.return_row_col_info??=!0;let y;f&&(y=await this.image_processor(f,_)),Array.isArray(u)||(u=[u]);const k=y.rows??[new Array(u.length).fill(0)],w=y.cols??[new Array(u.length).fill(0)],v=this.config.image_seq_len,I=[],T=[];for(let E=0;Ec(B,O[Y],v,this.fake_image_token,this.image_token,this.global_img_token)),H=x.split(this.image_token);if(H.length===0)throw new Error("The image token should be present in the text.");let W=H[0];for(let B=0;B{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>n.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>o.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DINOv3ViTImageProcessor:()=>p.DINOv3ViTImageProcessor,DPTFeatureExtractor:()=>u.DPTFeatureExtractor,DPTImageProcessor:()=>u.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>c.DetrFeatureExtractor,DetrImageProcessor:()=>c.DetrImageProcessor,DonutFeatureExtractor:()=>d.DonutFeatureExtractor,DonutImageProcessor:()=>d.DonutImageProcessor,EfficientNetImageProcessor:()=>f.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>y.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>k.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>v.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>I.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>T.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>b.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>b.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>E.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>E.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>x.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>x.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>S.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>S.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>O.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>O.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>F.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>F.MobileViTImageProcessor,NougatImageProcessor:()=>H.NougatImageProcessor,OwlViTFeatureExtractor:()=>B.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>B.OwlViTImageProcessor,Owlv2ImageProcessor:()=>W.Owlv2ImageProcessor,Phi3VImageProcessor:()=>Y.Phi3VImageProcessor,PixtralImageProcessor:()=>X.PixtralImageProcessor,PvtImageProcessor:()=>J.PvtImageProcessor,Qwen2VLImageProcessor:()=>re.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>ne.RTDetrImageProcessor,Sam2ImageProcessor:()=>pe.Sam2ImageProcessor,Sam3ImageProcessor:()=>oe.Sam3ImageProcessor,SamImageProcessor:()=>le.SamImageProcessor,SegformerFeatureExtractor:()=>K.SegformerFeatureExtractor,SegformerImageProcessor:()=>K.SegformerImageProcessor,SiglipImageProcessor:()=>N.SiglipImageProcessor,SmolVLMImageProcessor:()=>D.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>te.Swin2SRImageProcessor,VLMImageProcessor:()=>w.VLMImageProcessor,ViTFeatureExtractor:()=>he.ViTFeatureExtractor,ViTImageProcessor:()=>he.ViTImageProcessor,VitMatteImageProcessor:()=>Ae.VitMatteImageProcessor,VitPoseImageProcessor:()=>Ie.VitPoseImageProcessor,YolosFeatureExtractor:()=>je.YolosFeatureExtractor,YolosImageProcessor:()=>je.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),n=t("./src/models/bit/image_processing_bit.js"),o=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),i=t("./src/models/clip/image_processing_clip.js"),a=t("./src/models/convnext/image_processing_convnext.js"),l=t("./src/models/deit/image_processing_deit.js"),c=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/dinov3_vit/image_processing_dinov3_vit.js"),d=t("./src/models/donut/image_processing_donut.js"),u=t("./src/models/dpt/image_processing_dpt.js"),f=t("./src/models/efficientnet/image_processing_efficientnet.js"),_=t("./src/models/glpn/image_processing_glpn.js"),y=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),k=t("./src/models/idefics3/image_processing_idefics3.js"),w=t("./src/models/janus/image_processing_janus.js"),v=t("./src/models/jina_clip/image_processing_jina_clip.js"),I=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),T=t("./src/models/mask2former/image_processing_mask2former.js"),b=t("./src/models/maskformer/image_processing_maskformer.js"),E=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),x=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),S=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),O=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),F=t("./src/models/mobilevit/image_processing_mobilevit.js"),H=t("./src/models/nougat/image_processing_nougat.js"),W=t("./src/models/owlv2/image_processing_owlv2.js"),B=t("./src/models/owlvit/image_processing_owlvit.js"),Y=t("./src/models/phi3_v/image_processing_phi3_v.js"),X=t("./src/models/pixtral/image_processing_pixtral.js"),J=t("./src/models/pvt/image_processing_pvt.js"),re=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),ne=t("./src/models/rt_detr/image_processing_rt_detr.js"),le=t("./src/models/sam/image_processing_sam.js"),pe=t("./src/models/sam2/image_processing_sam2.js"),oe=t("./src/models/sam3/image_processing_sam3.js"),K=t("./src/models/segformer/image_processing_segformer.js"),N=t("./src/models/siglip/image_processing_siglip.js"),D=t("./src/models/smolvlm/image_processing_smolvlm.js"),te=t("./src/models/swin2sr/image_processing_swin2sr.js"),he=t("./src/models/vit/image_processing_vit.js"),Ae=t("./src/models/vitmatte/image_processing_vitmatte.js"),Ie=t("./src/models/vitpose/image_processing_vitpose.js"),je=t("./src/models/yolos/image_processing_yolos.js")}),"./src/models/janus/image_processing_janus.js":((e,r,t)=>{t.r(r),t.d(r,{VLMImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{constructor(i){super({do_pad:!0,pad_size:{width:i.image_size,height:i.image_size},...i}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(i,a,l,c){return super.pad_image(i,a,l,{constant_values:this.constant_values,center:!0,...c})}}}),"./src/models/janus/processing_janus.js":((e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>c});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js"),i=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class c extends s.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;static uses_processor_config=!0;constructor(d,u,f){super(d,u,f),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(d,{images:u=null,chat_template:f="default"}={}){u?Array.isArray(u)||(u=[u]):u=await Promise.all(d.filter(F=>F.images).flatMap(F=>F.images).map(F=>l.RawImage.read(F)));const _=this.tokenizer,y=_.apply_chat_template(d,{tokenize:!1,add_generation_prompt:!0,chat_template:f}),k=F=>_.encode(F,{add_special_tokens:!1}),w=y.split(this.image_tag),v=w.length-1;if(u.length!==v)throw new Error(`Number of images provided (${u.length}) does not match number of "${this.image_tag}" image tags (${v})`);const[I,T,b]=_.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let E=k(w[0]),x=new Array(E.length).fill(!1);for(let F=1;F0){const F=await this.image_processor(u);return F.pixel_values.unsqueeze_(0),{...O,...F}}return O}}}),"./src/models/jina_clip/image_processing_jina_clip.js":((e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{constructor(i){const{resize_mode:a,fill_color:l,interpolation:c,size:p,...d}=i,u=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},f=c==="bicubic"?3:2;super({...d,size:u,resample:f,do_center_crop:!0,crop_size:p,do_normalize:!0})}}}),"./src/models/jina_clip/processing_jina_clip.js":((e,r,t)=>{t.r(r),t.d(r,{JinaCLIPProcessor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;async _call(l=null,c=null,p={}){if(!l&&!c)throw new Error("Either text or images must be provided");const d=l?this.tokenizer(l,p):{},u=c?await this.image_processor(c,p):{};return{...d,...u}}}}),"./src/models/llava/processing_llava.js":((e,r,t)=>{t.r(r),t.d(r,{LlavaProcessor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;static uses_processor_config=!0;async _call(l,c=null,p={}){const d=await this.image_processor(l,p);if(c){const[f,_]=d.pixel_values.dims.slice(-2),{image_token:y,patch_size:k,num_additional_image_tokens:w}=this.config,v=Math.floor(f/k)*Math.floor(_/k)+w;c=structuredClone(c),Array.isArray(c)||(c=[c]);for(let I=0;I{t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/mask2former/image_processing_mask2former.js":((e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>n});var s=t("./src/models/maskformer/image_processing_maskformer.js");class n extends s.MaskFormerImageProcessor{}}),"./src/models/maskformer/image_processing_maskformer.js":((e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>o,MaskFormerImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_panoptic_segmentation(...a){return(0,s.post_process_panoptic_segmentation)(...a)}post_process_instance_segmentation(...a){return(0,s.post_process_instance_segmentation)(...a)}}class o extends n{}}),"./src/models/mgp_str/processing_mgp_str.js":((e,r,t)=>{t.r(r),t.d(r,{MgpstrProcessor:()=>l});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js"),i=t("./src/utils/maths.js");const a={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class l extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(p,d){if(!a.hasOwnProperty(d))throw new Error(`Format ${d} is not supported.`);const[u,f]=a[d],_=this[u].bind(this),[y,k]=p.dims,w=[],v=[],I=p.tolist();for(let b=0;b0?S.reduce((F,H)=>F*H,1):0;v.push(x),w.push(O)}return[_(v),w]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}batch_decode([p,d,u]){const[f,_]=this._decode_helper(p,"char"),[y,k]=this._decode_helper(d,"bpe"),[w,v]=this._decode_helper(u,"wp"),I=[],T=[];for(let b=0;b{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>o,MobileNetV1ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":((e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>o,MobileNetV2ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":((e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>o,MobileNetV3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":((e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>o,MobileNetV4ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/mobilevit/image_processing_mobilevit.js":((e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>o,MobileViTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/moonshine/feature_extraction_moonshine.js":((e,r,t)=>{t.r(r),t.d(r,{MoonshineFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js");class o extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"MoonshineFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=[1,a.length];return{input_values:new n.Tensor("float32",a,l)}}}}),"./src/models/moonshine/processing_moonshine.js":((e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=s.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/nougat/image_processing_nougat.js":((e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>n});var s=t("./src/models/donut/image_processing_donut.js");class n extends s.DonutImageProcessor{}}),"./src/models/owlv2/image_processing_owlv2.js":((e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>n});var s=t("./src/models/owlvit/image_processing_owlvit.js");class n extends s.OwlViTImageProcessor{}}),"./src/models/owlvit/image_processing_owlvit.js":((e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>o,OwlViTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class o extends n{}}),"./src/models/owlvit/processing_owlvit.js":((e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor}}),"./src/models/paligemma/processing_paligemma.js":((e,r,t)=>{t.r(r),t.d(r,{PaliGemmaProcessor:()=>l});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");const i="";function a(c,p,d,u,f){return`${u.repeat(d*f)}${p}${c} +`}class l extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;static uses_processor_config=!1;async _call(p,d=null,u={}){d||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),d=""),Array.isArray(p)||(p=[p]),Array.isArray(d)||(d=[d]);const f=this.tokenizer.bos_token,_=this.image_processor.config.image_seq_length;let y;d.some(v=>v.includes(i))?y=d.map(v=>{const I=v.replaceAll(i,i.repeat(_)),T=I.lastIndexOf(i),b=T===-1?0:T+i.length;return I.slice(0,b)+f+I.slice(b)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),y=d.map(v=>a(v,f,_,i,p.length)));const k=this.tokenizer(y,u);return{...await this.image_processor(p,u),...k}}}}),"./src/models/parakeet/feature_extraction_parakeet.js":((e,r,t)=>{t.r(r),t.d(r,{ParakeetFeatureExtractor:()=>a});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/audio.js");const i=1e-5;class a extends s.FeatureExtractor{constructor(c){super(c),this.config.mel_filters??=(0,o.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");const p=(0,o.window_function)(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);const d=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(p,d)}async _extract_fbank_features(c){const p=this.config.preemphasis;c=new Float64Array(c);for(let u=c.length-1;u>=1;--u)c[u]-=p*c[u-1];return await(0,o.spectrogram)(c,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(c){(0,s.validate_audio_inputs)(c,"ParakeetFeatureExtractor");const p=await this._extract_fbank_features(c),d=Math.floor((c.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),u=p.data;u.fill(0,d*p.dims[1]);const[f,_]=p.dims,y=new Float64Array(_),k=new Float64Array(_);for(let I=0;I1?d-1:1;for(let I=0;I<_;++I){const T=y[I]/d,b=(k[I]-d*T*T)/w,x=1/(Math.sqrt(b)+i);for(let S=0;S{t.r(r),t.d(r,{Phi3VImageProcessor:()=>p});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");const o=336,i=[2,3],{ceil:a,floor:l,sqrt:c}=Math;class p extends s.ImageProcessor{constructor(u){super({...u,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=u.num_crops}calc_num_image_tokens_from_image_size(u,f){const{num_img_tokens:_}=this.config;return l((l(f/o)*l(u/o)+1)*_+1+(l(f/o)+1)*c(_))}get_resize_output_image_size(u,f){const _=this._num_crops,[y,k]=u.size;let w=y/k,v=1;for(;v*Math.ceil(v/w)<=_;)v+=1;v-=1;const I=Math.floor(v*336),T=Math.floor(I/w);return[I,T]}pad_image(u,f,_,y={}){const[k,w]=f,v=o*a(k/o),I=o*a(w/o),T=[1,1,1].map((b,E)=>(b-this.image_mean[E])/this.image_std[E]);return super.pad_image(u,f,{width:I,height:v},{center:!0,constant_values:T,...y})}async _call(u,{num_crops:f=null}={}){if(this._num_crops=f??=this.config.num_crops,f<4||c(f)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(u)||(u=[u]);const _=u.length,y=await Promise.all(u.map(x=>this.preprocess(x))),k=y.map(x=>x.original_size),w=y.map(x=>x.reshaped_input_size),v=[];for(const{pixel_values:x}of y){x.unsqueeze_(0);const[S,O]=x.dims.slice(-2),F=await(0,n.interpolate_4d)(x,{size:[o,o],mode:"bicubic"});if(f>0){const H=[],W=c(f),B=l(O/W),Y=l(S/W);for(let J=0;Jx.map(S=>o*a(S/o))),b=new n.Tensor("int64",T.flat(),[_,2]),E=T.map(([x,S])=>this.calc_num_image_tokens_from_image_size(S,x));return{pixel_values:I,original_sizes:k,reshaped_input_sizes:w,image_sizes:b,num_img_tokens:E}}}}),"./src/models/phi3_v/processing_phi3_v.js":((e,r,t)=>{t.r(r),t.d(r,{Phi3VProcessor:()=>l});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");const i="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;async _call(p,d=null,{padding:u=!0,truncation:f=!0,num_crops:_=null}={}){Array.isArray(p)||(p=[p]);let y,k;if(d){k=await this.image_processor(d,{num_crops:_});const{num_img_tokens:w}=k,v=p.map((T,b)=>T.split(a).join(i.repeat(w[b])));y=this.tokenizer(v,{padding:u,truncation:f});const I=this.tokenizer.model.convert_tokens_to_ids([i])[0];y.input_ids.map_(T=>T==I?-T:T)}else y=this.tokenizer(p);return{...y,...k}}}}),"./src/models/pixtral/image_processing_pixtral.js":((e,r,t)=>{t.r(r),t.d(r,{PixtralImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{get_resize_output_image_size(i,a){const{longest_edge:l}=a;if(l===void 0)throw new Error("size must contain 'longest_edge'");const[c,p]=i.size,d=Math.max(c,p)/l;let u=c,f=p;d>1&&(u=Math.floor(c/d),f=Math.floor(p/d));const{patch_size:_,spatial_merge_size:y}=this.config;if(!y)throw new Error("config must contain 'spatial_merge_size'");const k=_*y,w=Math.floor((u-1)/k)+1,v=Math.floor((f-1)/k)+1;return[w*k,v*k]}}}),"./src/models/pixtral/processing_pixtral.js":((e,r,t)=>{t.r(r),t.d(r,{PixtralProcessor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;static uses_processor_config=!0;async _call(l,c=null,p={}){const d=await this.image_processor(l,p);if(c){const[f,_]=d.pixel_values.dims.slice(-2),{image_token:y,image_break_token:k,image_end_token:w,patch_size:v,spatial_merge_size:I}=this.config,T=v*I,b=Math.floor(f/T),E=Math.floor(_/T);c=structuredClone(c),Array.isArray(c)||(c=[c]);for(let x=0;x{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,Gemma3nProcessor:()=>n.Gemma3nProcessor,GroundingDinoProcessor:()=>o.GroundingDinoProcessor,Idefics3Processor:()=>i.Idefics3Processor,JinaCLIPProcessor:()=>l.JinaCLIPProcessor,LlavaProcessor:()=>c.LlavaProcessor,MgpstrProcessor:()=>p.MgpstrProcessor,MoonshineProcessor:()=>d.MoonshineProcessor,OwlViTProcessor:()=>u.OwlViTProcessor,PaliGemmaProcessor:()=>f.PaliGemmaProcessor,Phi3VProcessor:()=>_.Phi3VProcessor,PixtralProcessor:()=>y.PixtralProcessor,PyAnnoteProcessor:()=>k.PyAnnoteProcessor,Qwen2VLProcessor:()=>w.Qwen2VLProcessor,Sam2Processor:()=>I.Sam2Processor,Sam2VideoProcessor:()=>I.Sam2VideoProcessor,SamProcessor:()=>v.SamProcessor,SmolVLMProcessor:()=>T.SmolVLMProcessor,SpeechT5Processor:()=>b.SpeechT5Processor,UltravoxProcessor:()=>E.UltravoxProcessor,VLChatProcessor:()=>a.VLChatProcessor,VoxtralProcessor:()=>x.VoxtralProcessor,Wav2Vec2Processor:()=>S.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>O.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>F.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),n=t("./src/models/gemma3n/processing_gemma3n.js"),o=t("./src/models/grounding_dino/processing_grounding_dino.js"),i=t("./src/models/idefics3/processing_idefics3.js"),a=t("./src/models/janus/processing_janus.js"),l=t("./src/models/jina_clip/processing_jina_clip.js"),c=t("./src/models/llava/processing_llava.js"),p=t("./src/models/mgp_str/processing_mgp_str.js"),d=t("./src/models/moonshine/processing_moonshine.js"),u=t("./src/models/owlvit/processing_owlvit.js"),f=t("./src/models/paligemma/processing_paligemma.js"),_=t("./src/models/phi3_v/processing_phi3_v.js"),y=t("./src/models/pixtral/processing_pixtral.js"),k=t("./src/models/pyannote/processing_pyannote.js"),w=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),v=t("./src/models/sam/processing_sam.js"),I=t("./src/models/sam2/processing_sam2.js"),T=t("./src/models/smolvlm/processing_smolvlm.js"),b=t("./src/models/speecht5/processing_speecht5.js"),E=t("./src/models/ultravox/processing_ultravox.js"),x=t("./src/models/voxtral/processing_voxtral.js"),S=t("./src/models/wav2vec2/processing_wav2vec2.js"),O=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),F=t("./src/models/whisper/processing_whisper.js")}),"./src/models/pvt/image_processing_pvt.js":((e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/pyannote/feature_extraction_pyannote.js":((e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");class i extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const c=[1,1,l.length];return{input_values:new n.Tensor("float32",l,c)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,c){const p=c/this.samples_to_frames(c)/this.config.sampling_rate,d=[];for(const u of l.tolist()){const f=[];let _=-1;for(let y=0;y({id:y,start:k*p,end:w*p,confidence:v/(w-k)})))}return d}}}),"./src/models/pyannote/processing_pyannote.js":((e,r,t)=>{t.r(r),t.d(r,{PyAnnoteProcessor:()=>o});var s=t("./src/base/processing_utils.js"),n=t("./src/models/pyannote/feature_extraction_pyannote.js");class o extends s.Processor{static feature_extractor_class=n.PyAnnoteFeatureExtractor;async _call(a){return await this.feature_extractor(a)}post_process_speaker_diarization(...a){return this.feature_extractor.post_process_speaker_diarization(...a)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}}),"./src/models/qwen2_vl/image_processing_qwen2_vl.js":((e,r,t)=>{t.r(r),t.d(r,{Qwen2VLImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{async _call(a,...l){const{pixel_values:c,original_sizes:p,reshaped_input_sizes:d}=await super._call(a,...l);let u=c;const{temporal_patch_size:f,merge_size:_,patch_size:y}=this.config;u.dims[0]===1&&(u=(0,n.cat)(Array.from({length:f},()=>u),0));const k=u.dims[0]/f,w=u.dims[1],v=Math.floor(u.dims[2]/y),I=Math.floor(u.dims[3]/y),T=u.view(k,f,w,Math.floor(v/_),_,y,Math.floor(I/_),_,y).permute(0,3,6,4,7,2,1,5,8).view(k*v*I,w*f*y*y),b=new n.Tensor("int64",[k,v,I],[1,3]);return{pixel_values:T,image_grid_thw:b,original_sizes:p,reshaped_input_sizes:d}}}}),"./src/models/qwen2_vl/processing_qwen2_vl.js":((e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");class i extends s.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;async _call(l,c=null,...p){Array.isArray(l)||(l=[l]);let d,u;if(c&&(d=await this.image_processor(c),u=d.image_grid_thw),u){let _=this.image_processor.config.merge_size**2,y=0;const k=u.tolist();l=l.map(w=>{for(;w.includes("<|image_pad|>");){const v=Number(k[y++].reduce((I,T)=>I*T,1n));w=w.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(v/_)))}return w.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...d}}}}),"./src/models/rt_detr/image_processing_rt_detr.js":((e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_object_detection(...i){return(0,s.post_process_object_detection)(...i)}}}),"./src/models/sam/image_processing_sam.js":((e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/core.js"),o=t("./src/utils/tensor.js");class i extends s.ImageProcessor{reshape_input_points(l,c,p,d=!1){l=structuredClone(l);let u=(0,n.calculateDimensions)(l);if(u.length===3)d||(u=[1,...u]),l=[l];else if(u.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let f=0;fd!==c.dims[u]))throw Error(`The first ${p.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new o.Tensor("int64",l.flat(1/0).map(BigInt),p)}async _call(l,{input_points:c=null,input_labels:p=null,input_boxes:d=null}={}){const u=await super._call(l);if(c&&(u.input_points=this.reshape_input_points(c,u.original_sizes,u.reshaped_input_sizes)),p){if(!u.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");u.input_labels=this.add_input_labels(p,u.input_points)}return d&&(u.input_boxes=this.reshape_input_points(d,u.original_sizes,u.reshaped_input_sizes,!0)),u}async post_process_masks(l,c,p,{mask_threshold:d=0,binarize:u=!0,pad_size:f=null}={}){const _=[];f=f??this.pad_size??this.size;const y=[f.height,f.width];for(let k=0;kd&&(b[E]=1);I=new o.Tensor("bool",b,I.dims)}_.push(I)}return _}generate_crop_boxes(l,c,{crop_n_layers:p=0,overlap_ratio:d=512/1500,points_per_crop:u=32,crop_n_points_downscale_factor:f=1}={}){}}}),"./src/models/sam/processing_sam.js":((e,r,t)=>{t.r(r),t.d(r,{SamProcessor:()=>o});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js");class o extends s.Processor{static image_processor_class=n.AutoImageProcessor;async _call(...a){return await this.image_processor(...a)}post_process_masks(...a){return this.image_processor.post_process_masks(...a)}reshape_input_points(...a){return this.image_processor.reshape_input_points(...a)}}}),"./src/models/sam2/image_processing_sam2.js":((e,r,t)=>{t.r(r),t.d(r,{Sam2ImageProcessor:()=>s.SamImageProcessor});var s=t("./src/models/sam/image_processing_sam.js")}),"./src/models/sam2/processing_sam2.js":((e,r,t)=>{t.r(r),t.d(r,{Sam2Processor:()=>n,Sam2VideoProcessor:()=>o});var s=t("./src/models/sam/processing_sam.js");class n extends s.SamProcessor{}class o extends n{}}),"./src/models/sam3/image_processing_sam3.js":((e,r,t)=>{t.r(r),t.d(r,{Sam3ImageProcessor:()=>s.Sam2ImageProcessor});var s=t("./src/models/sam2/image_processing_sam2.js")}),"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":((e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const c=this.config.sampling_rate,p=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(c/2),c,null,"kaldi",!0);this.mel_filters=p,this.window=(0,o.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(l,c){return l=l.map(p=>p*32768),(0,o.spectrogram)(l,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:c,transpose:!0})}async _call(l,{padding:c=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:d=!0,return_attention_mask:u=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let f=await this._extract_fbank_features(l,this.config.max_length);if(d){const[b,E]=f.dims,x=f.data;for(let S=0;S0){const O=new Float32Array(E*(b+S));O.set(x),O.fill(this.config.padding_value,x.length);const F=b+S;f=new n.Tensor(f.type,O,[F,E]),u&&(_=new n.Tensor("int64",new BigInt64Array(F),[1,F]),_.data.fill(1n,0,b))}}const[y,k]=f.dims,w=this.config.stride;if(y%w!==0)throw new Error(`The number of frames (${y}) must be a multiple of the stride (${w}).`);const I=f.view(1,Math.floor(y/w),k*w),T={input_features:I};if(u){const b=I.dims[1],E=new BigInt64Array(b);if(_){const x=_.data;for(let S=1,O=0;S{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>o,SegformerImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class o extends n{}}),"./src/models/siglip/image_processing_siglip.js":((e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/smolvlm/image_processing_smolvlm.js":((e,r,t)=>{t.r(r),t.d(r,{SmolVLMImageProcessor:()=>s.Idefics3ImageProcessor});var s=t("./src/models/idefics3/image_processing_idefics3.js")}),"./src/models/smolvlm/processing_smolvlm.js":((e,r,t)=>{t.r(r),t.d(r,{SmolVLMProcessor:()=>s.Idefics3Processor});var s=t("./src/models/idefics3/processing_idefics3.js")}),"./src/models/snac/feature_extraction_snac.js":((e,r,t)=>{t.r(r),t.d(r,{SnacFeatureExtractor:()=>n});var s=t("./src/models/dac/feature_extraction_dac.js");class n extends s.DacFeatureExtractor{}}),"./src/models/speecht5/feature_extraction_speecht5.js":((e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");class n extends s.FeatureExtractor{}}),"./src/models/speecht5/processing_speecht5.js":((e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js");class i extends s.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=o.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/swin2sr/image_processing_swin2sr.js":((e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{pad_image(i,a,l,c={}){const[p,d,u]=a;return super.pad_image(i,a,{width:d+(l-d%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...c})}}}),"./src/models/ultravox/processing_ultravox.js":((e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=s.AutoFeatureExtractor;static uses_processor_config=!0;async _call(l,c=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let d={};if(c){const f=c.length,{input_features:_}=await this.feature_extractor(c,{...p,max_length:f}),y=Math.round(f/this.config.encoder_ds_factor+1e-4),k=1+Math.ceil(y/this.config.stack_factor);d.audio_token_len=[k],d.audio_values=_;const w=this.config.audio_placeholder;if(!l.includes(w))throw new Error(`The input text does not contain the image token ${w}.`);l=l.replaceAll(w,w.repeat(k))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...d}}}}),"./src/models/vit/image_processing_vit.js":((e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>o,ViTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/vitmatte/image_processing_vitmatte.js":((e,r,t)=>{t.r(r),t.d(r,{VitMatteImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{async _call(a,l){Array.isArray(a)||(a=[a]),Array.isArray(l)||(l=[l]);const c=await Promise.all(a.map(u=>this.preprocess(u))),p=await Promise.all(l.map(u=>this.preprocess(u,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,n.stack)(c.map((u,f)=>(0,n.cat)([u.pixel_values,p[f].pixel_values],0)),0),original_sizes:c.map(u=>u.original_size),reshaped_input_sizes:c.map(u=>u.reshaped_input_size)}}}}),"./src/models/vitpose/image_processing_vitpose.js":((e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_pose_estimation(i,a,{threshold:l=null}={}){const c=i.tolist(),[p,d,u,f]=i.dims,_=[];for(let y=0;y{t.r(r),t.d(r,{VoxtralProcessor:()=>d});var s=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js"),i=t("./src/utils/tensor.js");const a="[AUDIO]",l="[BEGIN_AUDIO]",c=375;function p(u,f){const _=[];for(let y=0;yp(F,T)),E=b.map(F=>F.length),x=b.flat(),S=(await Promise.all(x.map(F=>this.feature_extractor(F,y)))).map(F=>F.input_features);k.audio_values=S.length>1?(0,i.cat)(S,0):S[0];let O=v[0];for(let F=0;F{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js");class o extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const c=a.reduce((d,u)=>d+u,0)/a.length,p=a.reduce((d,u)=>d+(u-c)**2,0)/a.length;return a.map(d=>(d-c)/Math.sqrt(p+1e-7))}async _call(a){(0,s.validate_audio_inputs)(a,"Wav2Vec2FeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));let l=a;this.config.do_normalize&&(l=this._zero_mean_unit_var_norm(l));const c=[1,l.length];return{input_values:new n.Tensor("float32",l,c),attention_mask:new n.Tensor("int64",new BigInt64Array(l.length).fill(1n),c)}}}}),"./src/models/wav2vec2/processing_wav2vec2.js":((e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>i});var s=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=s.AutoTokenizer;static feature_extractor_class=n.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":((e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>i});var s=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=s.AutoTokenizer;static feature_extractor_class=n.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/wespeaker/feature_extraction_wespeaker.js":((e,r,t)=>{t.r(r),t.d(r,{WeSpeakerFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,c=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=c,this.window=(0,n.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(a){return a=a.map(l=>l*32768),(0,n.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(a){(0,s.validate_audio_inputs)(a,"WeSpeakerFeatureExtractor");const l=(await this._extract_fbank_features(a)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const c=l.mean(1).data,p=l.data,[d,u,f]=l.dims;for(let _=0;_{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>n,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>o,whisper_language_to_code:()=>i});const s=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],n=new Map(s),o=new Map([...s.map(([a,l])=>[l,a]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function i(a){a=a.toLowerCase();let l=o.get(a);if(l===void 0){const c=a.match(/^<\|([a-z]{2})\|>$/);if(c&&(a=c[1]),n.has(a))l=a;else{const d=a.length===2?n.keys():n.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(d))}`)}}return l}}),"./src/models/whisper/feature_extraction_whisper.js":((e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var n=t("./src/utils/audio.js"),o=t("./src/utils/maths.js");class i extends s.FeatureExtractor{constructor(l){super(l),this.config.mel_filters??=(0,n.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=(0,n.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const c=await(0,n.spectrogram)(l,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(l.length/this.config.hop_length),this.config.nb_max_frames)}),p=c.data,d=(0,o.max)(p)[0];for(let u=0;ud?(l.length>this.config.n_samples&&console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),p=l.slice(0,d)):(p=new Float32Array(d),p.set(l)),{input_features:(await this._extract_fbank_features(p)).unsqueeze_(0)}}}}),"./src/models/whisper/generation_whisper.js":((e,r,t)=>{t.r(r),t.d(r,{WhisperGenerationConfig:()=>n});var s=t("./src/generation/configuration_utils.js");class n extends s.GenerationConfig{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1}}),"./src/models/whisper/processing_whisper.js":((e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=s.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/yolos/image_processing_yolos.js":((e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>o,YolosImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class o extends n{}}),"./src/ops/registry.js":((e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>i});var s=t("./src/backends/onnx.js"),n=t("./src/utils/tensor.js");const o=async(a,l,c)=>{const p=await(0,s.createInferenceSession)(new Uint8Array(a),l);return(async d=>{const u=(0,s.isONNXProxy)(),f=Object.fromEntries(Object.entries(d).map(([y,k])=>[y,(u?k.clone():k).ort_tensor])),_=await(0,s.runInferenceSession)(p,f);return Array.isArray(c)?c.map(y=>new n.Tensor(_[y])):new n.Tensor(_[c])})};class i{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=o([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=o([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=o([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=o([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=o([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=o([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=o([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=o([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}}),"./src/pipelines.js":((e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>W,AutomaticSpeechRecognitionPipeline:()=>Y,BackgroundRemovalPipeline:()=>ne,DepthEstimationPipeline:()=>te,DocumentQuestionAnsweringPipeline:()=>K,FeatureExtractionPipeline:()=>F,FillMaskPipeline:()=>I,ImageClassificationPipeline:()=>J,ImageFeatureExtractionPipeline:()=>H,ImageSegmentationPipeline:()=>re,ImageToImagePipeline:()=>D,ImageToTextPipeline:()=>X,ObjectDetectionPipeline:()=>pe,Pipeline:()=>y,QuestionAnsweringPipeline:()=>v,SummarizationPipeline:()=>b,Text2TextGenerationPipeline:()=>T,TextClassificationPipeline:()=>k,TextGenerationPipeline:()=>S,TextToAudioPipeline:()=>N,TokenClassificationPipeline:()=>w,TranslationPipeline:()=>E,ZeroShotAudioClassificationPipeline:()=>B,ZeroShotClassificationPipeline:()=>O,ZeroShotImageClassificationPipeline:()=>le,ZeroShotObjectDetectionPipeline:()=>oe,pipeline:()=>Ie});var s=t("./src/tokenizers.js"),n=t("./src/models.js"),o=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),c=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),d=t("./src/utils/image.js");async function u(Te){return Array.isArray(Te)||(Te=[Te]),await Promise.all(Te.map(Q=>d.RawImage.read(Q)))}async function f(Te,Q){return Array.isArray(Te)||(Te=[Te]),await Promise.all(Te.map(z=>typeof z=="string"||z instanceof URL?(0,c.read_audio)(z,Q):z instanceof Float64Array?new Float32Array(z):z))}function _(Te,Q){Q&&(Te=Te.map(xe=>xe|0));const[z,de,be,ve]=Te;return{xmin:z,ymin:de,xmax:be,ymax:ve}}class y extends i.Callable{constructor({task:Q,model:z,tokenizer:de=null,processor:be=null}){super(),this.task=Q,this.model=z,this.tokenizer=de,this.processor=be}async dispose(){await this.model.dispose()}}class k extends y{constructor(Q){super(Q)}async _call(Q,{top_k:z=1}={}){const de=this.tokenizer(Q,{padding:!0,truncation:!0}),be=await this.model(de),ve=this.model.config.problem_type==="multi_label_classification"?ge=>ge.sigmoid():ge=>new p.Tensor("float32",(0,l.softmax)(ge.data),ge.dims),xe=this.model.config.id2label,Ce=[];for(const ge of be.logits){const De=ve(ge),fe=await(0,p.topk)(De,z),Ee=fe[0].tolist(),Fe=fe[1].tolist().map((tt,Re)=>({label:xe?xe[tt]:`LABEL_${tt}`,score:Ee[Re]}));z===1?Ce.push(...Fe):Ce.push(Fe)}return Array.isArray(Q)||z===1?Ce:Ce[0]}}class w extends y{constructor(Q){super(Q)}async _call(Q,{ignore_labels:z=["O"]}={}){const de=Array.isArray(Q),be=this.tokenizer(de?Q:[Q],{padding:!0,truncation:!0}),xe=(await this.model(be)).logits,Ce=this.model.config.id2label,ge=[];for(let De=0;DeOe==this.tokenizer.sep_token_id);ge[Ee].map((Oe,ot)=>Oe==1&&(ot===0||ot>Fe&&De.findIndex(ht=>ht==We[ot])===-1));const tt=ve[Ee].tolist(),Re=xe[Ee].tolist();for(let Oe=1;Oeot==We[Oe])!==-1)&&(tt[Oe]=-1/0,Re[Oe]=-1/0);const rt=(0,l.softmax)(tt).map((Oe,ot)=>[Oe,ot]),Ze=(0,l.softmax)(Re).map((Oe,ot)=>[Oe,ot]);rt[0][0]=0,Ze[0][0]=0;const Ne=(0,a.product)(rt,Ze).filter(Oe=>Oe[0][1]<=Oe[1][1]).map(Oe=>[Oe[0][1],Oe[1][1],Oe[0][0]*Oe[1][0]]).sort((Oe,ot)=>ot[2]-Oe[2]);for(let Oe=0;Oett==this.tokenizer.mask_token_id);if(De===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const fe=be[Ce][De],Ee=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(fe.data),fe.dims),z),We=Ee[0].tolist(),Fe=Ee[1].tolist();ve.push(Fe.map((tt,Re)=>{const rt=ge.slice();return rt[De]=tt,{score:We[Re],token:Number(tt),token_str:this.tokenizer.decode([tt]),sequence:this.tokenizer.decode(rt,{skip_special_tokens:!0})}}))}return Array.isArray(Q)?ve:ve[0]}}class T extends y{_key="generated_text";constructor(Q){super(Q)}async _call(Q,z={}){Array.isArray(Q)||(Q=[Q]),this.model.config.prefix&&(Q=Q.map(ge=>this.model.config.prefix+ge));const de=this.model.config.task_specific_params;de&&de[this.task]&&de[this.task].prefix&&(Q=Q.map(ge=>de[this.task].prefix+ge));const be=this.tokenizer,ve={padding:!0,truncation:!0};let xe;this instanceof E&&"_build_translation_inputs"in be?xe=be._build_translation_inputs(Q,ve,z):xe=be(Q,ve);const Ce=await this.model.generate({...xe,...z});return be.batch_decode(Ce,{skip_special_tokens:!0}).map(ge=>({[this._key]:ge}))}}class b extends T{_key="summary_text";constructor(Q){super(Q)}}class E extends T{_key="translation_text";constructor(Q){super(Q)}}function x(Te){return Array.isArray(Te)&&Te.every(Q=>"role"in Q&&"content"in Q)}class S extends y{constructor(Q){super(Q)}async _call(Q,z={}){let de=!1,be=!1,ve=z.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,xe;if(typeof Q=="string")xe=Q=[Q];else if(Array.isArray(Q)&&Q.every(Fe=>typeof Fe=="string"))de=!0,xe=Q;else{if(x(Q))Q=[Q];else if(Array.isArray(Q)&&Q.every(x))de=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");be=!0,xe=Q.map(Fe=>this.tokenizer.apply_chat_template(Fe,{tokenize:!1,add_generation_prompt:!0})),ve=!1}const Ce=be?!1:z.return_full_text??!0;this.tokenizer.padding_side="left";const ge=this.tokenizer(xe,{add_special_tokens:ve,padding:!0,truncation:!0}),De=await this.model.generate({...ge,...z}),fe=this.tokenizer.batch_decode(De,{skip_special_tokens:!0});let Ee;!Ce&&ge.input_ids.dims.at(-1)>0&&(Ee=this.tokenizer.batch_decode(ge.input_ids,{skip_special_tokens:!0}).map(Fe=>Fe.length));const We=Array.from({length:Q.length},Fe=>[]);for(let Fe=0;Fe[z.toLowerCase(),de])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(Q,z,{hypothesis_template:de="This example is {}.",multi_label:be=!1}={}){const ve=Array.isArray(Q);ve||(Q=[Q]),Array.isArray(z)||(z=[z]);const xe=z.map(De=>de.replace("{}",De)),Ce=be||z.length===1,ge=[];for(const De of Q){const fe=[];for(const Fe of xe){const tt=this.tokenizer(De,{text_pair:Fe,padding:!0,truncation:!0}),Re=await this.model(tt);Ce?fe.push([Re.logits.data[this.contradiction_id],Re.logits.data[this.entailment_id]]):fe.push(Re.logits.data[this.entailment_id])}const We=(Ce?fe.map(Fe=>(0,l.softmax)(Fe)[1]):(0,l.softmax)(fe)).map((Fe,tt)=>[Fe,tt]).sort((Fe,tt)=>tt[0]-Fe[0]);ge.push({sequence:De,labels:We.map(Fe=>z[Fe[1]]),scores:We.map(Fe=>Fe[0])})}return ve?ge:ge[0]}}class F extends y{constructor(Q){super(Q)}async _call(Q,{pooling:z="none",normalize:de=!1,quantize:be=!1,precision:ve="binary"}={}){const xe=this.tokenizer(Q,{padding:!0,truncation:!0}),Ce=await this.model(xe);let ge=Ce.last_hidden_state??Ce.logits??Ce.token_embeddings;switch(z){case"none":break;case"mean":ge=(0,p.mean_pooling)(ge,xe.attention_mask);break;case"first_token":case"cls":ge=ge.slice(null,0);break;case"last_token":case"eos":ge=ge.slice(null,-1);break;default:throw Error(`Pooling method '${z}' not supported.`)}return de&&(ge=ge.normalize(2,-1)),be&&(ge=(0,p.quantize_embeddings)(ge,ve)),ge}}class H extends y{constructor(Q){super(Q)}async _call(Q,{pool:z=null}={}){const de=await u(Q),{pixel_values:be}=await this.processor(de),ve=await this.model({pixel_values:be});let xe;if(z){if(!("pooler_output"in ve))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");xe=ve.pooler_output}else xe=ve.last_hidden_state??ve.logits??ve.image_embeds;return xe}}class W extends y{constructor(Q){super(Q)}async _call(Q,{top_k:z=5}={}){const de=this.processor.feature_extractor.config.sampling_rate,be=await f(Q,de),ve=this.model.config.id2label,xe=[];for(const Ce of be){const ge=await this.processor(Ce),fe=(await this.model(ge)).logits[0],Ee=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(fe.data),fe.dims),z),We=Ee[0].tolist(),tt=Ee[1].tolist().map((Re,rt)=>({label:ve?ve[Re]:`LABEL_${Re}`,score:We[rt]}));xe.push(tt)}return Array.isArray(Q)?xe:xe[0]}}class B extends y{constructor(Q){super(Q)}async _call(Q,z,{hypothesis_template:de="This is a sound of {}."}={}){const be=!Array.isArray(Q);be&&(Q=[Q]);const ve=z.map(fe=>de.replace("{}",fe)),xe=this.tokenizer(ve,{padding:!0,truncation:!0}),Ce=this.processor.feature_extractor.config.sampling_rate,ge=await f(Q,Ce),De=[];for(const fe of ge){const Ee=await this.processor(fe),We=await this.model({...xe,...Ee}),Fe=(0,l.softmax)(We.logits_per_audio.data);De.push([...Fe].map((tt,Re)=>({score:tt,label:z[Re]})))}return be?De[0]:De}}class Y extends y{constructor(Q){super(Q)}async _call(Q,z={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(Q,z);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(Q,z);case"moonshine":return this._call_moonshine(Q,z);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(Q,z){z.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),z.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const de=!Array.isArray(Q);de&&(Q=[Q]);const be=this.processor.feature_extractor.config.sampling_rate,ve=await f(Q,be),xe=[];for(const Ce of ve){const ge=await this.processor(Ce),fe=(await this.model(ge)).logits[0],Ee=[];for(const Fe of fe)Ee.push((0,l.max)(Fe.data)[1]);const We=this.tokenizer.decode(Ee,{skip_special_tokens:!0}).trim();xe.push({text:We})}return de?xe[0]:xe}async _call_whisper(Q,z){const de=z.return_timestamps??!1,be=z.chunk_length_s??0,ve=z.force_full_sequences??!1;let xe=z.stride_length_s??null;const Ce={...z};de==="word"&&(Ce.return_token_timestamps=!0,Ce.return_timestamps=!1);const ge=!Array.isArray(Q);ge&&(Q=[Q]);const De=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,fe=this.processor.feature_extractor.config.hop_length,Ee=this.processor.feature_extractor.config.sampling_rate,We=await f(Q,Ee),Fe=[];for(const tt of We){let Re=[];if(be>0){if(xe===null)xe=be/6;else if(be<=xe)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Ne=Ee*be,Oe=Ee*xe,ot=Ne-2*Oe;let ht=0;for(;;){const Rt=ht+Ne,It=tt.subarray(ht,Rt),gr=await this.processor(It),Or=ht===0,zt=Rt>=tt.length;if(Re.push({stride:[It.length,Or?0:Oe,zt?0:Oe],input_features:gr.input_features,is_last:zt}),zt)break;ht+=ot}}else Re=[{stride:[tt.length,0,0],input_features:(await this.processor(tt)).input_features,is_last:!0}];for(const Ne of Re){Ce.num_frames=Math.floor(Ne.stride[0]/fe);const Oe=await this.model.generate({inputs:Ne.input_features,...Ce});de==="word"?(Ne.tokens=Oe.sequences.tolist()[0],Ne.token_timestamps=Oe.token_timestamps.tolist()[0].map(ot=>(0,l.round)(ot,2))):Ne.tokens=Oe[0].tolist(),Ne.stride=Ne.stride.map(ot=>ot/Ee)}const[rt,Ze]=this.tokenizer._decode_asr(Re,{time_precision:De,return_timestamps:de,force_full_sequences:ve});Fe.push({text:rt,...Ze})}return ge?Fe[0]:Fe}async _call_moonshine(Q,z){const de=!Array.isArray(Q);de&&(Q=[Q]);const be=this.processor.feature_extractor.config.sampling_rate,ve=await f(Q,be),xe=[];for(const Ce of ve){const ge=await this.processor(Ce),De=Math.floor(Ce.length/be)*6,fe=await this.model.generate({max_new_tokens:De,...z,...ge}),Ee=this.processor.batch_decode(fe,{skip_special_tokens:!0})[0];xe.push({text:Ee})}return de?xe[0]:xe}}class X extends y{constructor(Q){super(Q)}async _call(Q,z={}){const de=Array.isArray(Q),be=await u(Q),{pixel_values:ve}=await this.processor(be),xe=[];for(const Ce of ve){Ce.dims=[1,...Ce.dims];const ge=await this.model.generate({inputs:Ce,...z}),De=this.tokenizer.batch_decode(ge,{skip_special_tokens:!0}).map(fe=>({generated_text:fe.trim()}));xe.push(De)}return de?xe:xe[0]}}class J extends y{constructor(Q){super(Q)}async _call(Q,{top_k:z=5}={}){const de=await u(Q),{pixel_values:be}=await this.processor(de),ve=await this.model({pixel_values:be}),xe=this.model.config.id2label,Ce=[];for(const ge of ve.logits){const De=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(ge.data),ge.dims),z),fe=De[0].tolist(),We=De[1].tolist().map((Fe,tt)=>({label:xe?xe[Fe]:`LABEL_${Fe}`,score:fe[tt]}));Ce.push(We)}return Array.isArray(Q)?Ce:Ce[0]}}class re extends y{constructor(Q){super(Q),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(Q,{threshold:z=.5,mask_threshold:de=.5,overlap_mask_area_threshold:be=.8,label_ids_to_fuse:ve=null,target_sizes:xe=null,subtask:Ce=null}={}){if(Array.isArray(Q)&&Q.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const De=await u(Q),fe=De.map(Ne=>[Ne.height,Ne.width]),Ee=await this.processor(De),{inputNames:We,outputNames:Fe}=this.model.sessions.model;if(!We.includes("pixel_values")){if(We.length!==1)throw Error(`Expected a single input name, but got ${We.length} inputs: ${We}.`);const Ne=We[0];if(Ne in Ee)throw Error(`Input name ${Ne} already exists in the inputs.`);Ee[Ne]=Ee.pixel_values}const tt=await this.model(Ee);let Re=null;if(Ce!==null)Re=this.subtasks_mapping[Ce];else if(this.processor.image_processor){for(const[Ne,Oe]of Object.entries(this.subtasks_mapping))if(Oe in this.processor.image_processor){Re=this.processor.image_processor[Oe].bind(this.processor.image_processor),Ce=Ne;break}}const rt=this.model.config.id2label,Ze=[];if(Ce)if(Ce==="panoptic"||Ce==="instance"){const Ne=Re(tt,z,de,be,ve,xe??fe)[0],Oe=Ne.segmentation;for(const ot of Ne.segments_info){const ht=new Uint8ClampedArray(Oe.data.length);for(let It=0;Itgr<-1e-5||gr>1+1e-5)&&Rt.sigmoid_();const It=await d.RawImage.fromTensor(Rt.mul_(255).to("uint8")).resize(ht[1],ht[0]);Ze.push({label:null,score:null,mask:It})}}return Ze}}class ne extends re{constructor(Q){super(Q)}async _call(Q,z={}){if(Array.isArray(Q)&&Q.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const be=await u(Q),ve=await super._call(Q,z);return be.map((Ce,ge)=>{const De=Ce.clone();return De.putAlpha(ve[ge].mask),De})}}class le extends y{constructor(Q){super(Q)}async _call(Q,z,{hypothesis_template:de="This is a photo of {}"}={}){const be=Array.isArray(Q),ve=await u(Q),xe=z.map(We=>de.replace("{}",We)),Ce=this.tokenizer(xe,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:ge}=await this.processor(ve),De=await this.model({...Ce,pixel_values:ge}),fe=this.model.config.model_type==="siglip"?We=>We.sigmoid().data:We=>(0,l.softmax)(We.data),Ee=[];for(const We of De.logits_per_image){const tt=[...fe(We)].map((Re,rt)=>({score:Re,label:z[rt]}));tt.sort((Re,rt)=>rt.score-Re.score),Ee.push(tt)}return be?Ee:Ee[0]}}class pe extends y{constructor(Q){super(Q)}async _call(Q,{threshold:z=.9,percentage:de=!1}={}){const be=Array.isArray(Q);if(be&&Q.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const ve=await u(Q),xe=de?null:ve.map(Fe=>[Fe.height,Fe.width]),{pixel_values:Ce,pixel_mask:ge}=await this.processor(ve),De=await this.model({pixel_values:Ce,pixel_mask:ge}),fe=this.processor.image_processor.post_process_object_detection(De,z,xe),Ee=this.model.config.id2label,We=fe.map(Fe=>Fe.boxes.map((tt,Re)=>({score:Fe.scores[Re],label:Ee[Fe.classes[Re]],box:_(tt,!de)})));return be?We:We[0]}}class oe extends y{constructor(Q){super(Q)}async _call(Q,z,{threshold:de=.1,top_k:be=null,percentage:ve=!1}={}){const xe=Array.isArray(Q),Ce=await u(Q),ge=this.tokenizer(z,{padding:!0,truncation:!0}),De=await this.processor(Ce),fe=[];for(let Ee=0;Ee({score:Ze.scores[Oe],label:Ze.labels[Oe],box:_(Ne,!ve)}))}else{const Ze=this.processor.image_processor.post_process_object_detection(Re,de,Fe,!0)[0];rt=Ze.boxes.map((Ne,Oe)=>({score:Ze.scores[Oe],label:z[Ze.classes[Oe]],box:_(Ne,!ve)}))}rt.sort((Ze,Ne)=>Ne.score-Ze.score),be!==null&&(rt=rt.slice(0,be)),fe.push(rt)}return xe?fe:fe[0]}}class K extends y{constructor(Q){super(Q)}async _call(Q,z,de={}){const be=(await u(Q))[0],{pixel_values:ve}=await this.processor(be),xe=`${z}`,Ce=this.tokenizer(xe,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,ge=await this.model.generate({inputs:ve,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ce,...de}),fe=this.tokenizer.batch_decode(ge)[0].match(/(.*?)<\/s_answer>/);let Ee=null;return fe&&fe.length>=2&&(Ee=fe[1].trim()),[{answer:Ee}]}}class N extends y{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(Q){super(Q),this.vocoder=Q.vocoder??null}async _prepare_speaker_embeddings(Q){if((typeof Q=="string"||Q instanceof URL)&&(Q=new Float32Array(await(await fetch(Q)).arrayBuffer())),Q instanceof Float32Array)Q=new p.Tensor("float32",Q,[Q.length]);else if(!(Q instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");return Q}async _call(Q,{speaker_embeddings:z=null,num_inference_steps:de,speed:be}={}){return this.processor?this._call_text_to_spectrogram(Q,{speaker_embeddings:z}):this.model.config.model_type==="supertonic"?this._call_supertonic(Q,{speaker_embeddings:z,num_inference_steps:de,speed:be}):this._call_text_to_waveform(Q)}async _call_supertonic(Q,{speaker_embeddings:z,num_inference_steps:de,speed:be}){if(!z)throw new Error("Speaker embeddings must be provided for Supertonic models.");z=await this._prepare_speaker_embeddings(z);const{sampling_rate:ve,style_dim:xe}=this.model.config;z=z.view(1,-1,xe);const Ce=this.tokenizer(Q,{padding:!0,truncation:!0}),{waveform:ge}=await this.model.generate_speech({...Ce,style:z,num_inference_steps:de,speed:be});return new c.RawAudio(ge.data,ve)}async _call_text_to_waveform(Q){const z=this.tokenizer(Q,{padding:!0,truncation:!0}),{waveform:de}=await this.model(z),be=this.model.config.sampling_rate;return new c.RawAudio(de.data,be)}async _call_text_to_spectrogram(Q,{speaker_embeddings:z}){this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await n.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));const{input_ids:de}=this.tokenizer(Q,{padding:!0,truncation:!0});z=await this._prepare_speaker_embeddings(z),z=z.view(1,-1);const{waveform:be}=await this.model.generate_speech(de,z,{vocoder:this.vocoder}),ve=this.processor.feature_extractor.config.sampling_rate;return new c.RawAudio(be.data,ve)}}class D extends y{constructor(Q){super(Q)}async _call(Q){const z=await u(Q),de=await this.processor(z),be=await this.model(de),ve=[];for(const xe of be.reconstruction){const Ce=xe.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");ve.push(d.RawImage.fromTensor(Ce))}return ve.length>1?ve:ve[0]}}class te extends y{constructor(Q){super(Q)}async _call(Q){const z=await u(Q),de=await this.processor(z),{predicted_depth:be}=await this.model(de),ve=[];for(let xe=0;xe1?ve:ve[0]}}const he=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:k,model:n.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:w,model:n.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:v,model:n.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:I,model:n.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:b,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:E,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:T,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:S,model:n.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:O,model:n.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:W,model:n.AutoModelForAudioClassification,processor:o.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:B,model:n.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:Y,model:[n.AutoModelForSpeechSeq2Seq,n.AutoModelForCTC],processor:o.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:N,model:[n.AutoModelForTextToWaveform,n.AutoModelForTextToSpectrogram],processor:[o.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:X,model:n.AutoModelForVision2Seq,processor:o.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:J,model:n.AutoModelForImageClassification,processor:o.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:re,model:[n.AutoModelForImageSegmentation,n.AutoModelForSemanticSegmentation,n.AutoModelForUniversalSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:ne,model:[n.AutoModelForImageSegmentation,n.AutoModelForSemanticSegmentation,n.AutoModelForUniversalSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:le,model:n.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:pe,model:n.AutoModelForObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:oe,model:n.AutoModelForZeroShotObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:K,model:n.AutoModelForDocumentQuestionAnswering,processor:o.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:D,model:n.AutoModelForImageToImage,processor:o.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:te,model:n.AutoModelForDepthEstimation,processor:o.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:F,model:n.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:o.AutoProcessor,pipeline:H,model:[n.AutoModelForImageFeatureExtraction,n.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Ae=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function Ie(Te,Q=null,{progress_callback:z=null,config:de=null,cache_dir:be=null,local_files_only:ve=!1,revision:xe="main",device:Ce=null,dtype:ge=null,subfolder:De="onnx",use_external_data_format:fe=null,model_file_name:Ee=null,session_options:We={}}={}){Te=Ae[Te]??Te;const Fe=he[Te.split("_",1)[0]];if(!Fe)throw Error(`Unsupported pipeline: ${Te}. Must be one of [${Object.keys(he)}]`);Q||(Q=Fe.default.model,console.log(`No model specified. Using default model: "${Q}".`));const tt={progress_callback:z,config:de,cache_dir:be,local_files_only:ve,revision:xe,device:Ce,dtype:ge,subfolder:De,use_external_data_format:fe,model_file_name:Ee,session_options:We},Re=new Map([["tokenizer",Fe.tokenizer],["model",Fe.model],["processor",Fe.processor]]),rt=await je(Re,Q,tt);rt.task=Te,(0,a.dispatchCallback)(z,{status:"ready",task:Te,model:Q});const Ze=Fe.pipeline;return new Ze(rt)}async function je(Te,Q,z){const de=Object.create(null),be=[];for(const[ve,xe]of Te.entries()){if(!xe)continue;let Ce;Array.isArray(xe)?Ce=new Promise(async(ge,De)=>{let fe;for(const Ee of xe){if(Ee===null){ge(null);return}try{ge(await Ee.from_pretrained(Q,z));return}catch(We){if(We.message?.includes("Unsupported model type"))fe=We;else if(We.message?.includes("Could not locate file"))fe=We;else{De(We);return}}}De(fe)}):Ce=xe.from_pretrained(Q,z),de[ve]=Ce,be.push(Ce)}await Promise.all(be);for(const[ve,xe]of Object.entries(de))de[ve]=await xe;return de}}),"./src/tokenizers.js":((e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Ps,AutoTokenizer:()=>Dn,BartTokenizer:()=>He,BertTokenizer:()=>qt,BlenderbotSmallTokenizer:()=>Ue,BlenderbotTokenizer:()=>ze,BloomTokenizer:()=>kt,CLIPTokenizer:()=>As,CamembertTokenizer:()=>Z,CodeGenTokenizer:()=>ks,CodeLlamaTokenizer:()=>ar,CohereTokenizer:()=>Os,ConvBertTokenizer:()=>q,DebertaTokenizer:()=>yt,DebertaV2Tokenizer:()=>Ss,DistilBertTokenizer:()=>G,ElectraTokenizer:()=>ye,EsmTokenizer:()=>Lr,FalconTokenizer:()=>Dr,GPT2Tokenizer:()=>ut,GPTNeoXTokenizer:()=>$s,GemmaTokenizer:()=>ts,Grok1Tokenizer:()=>wr,HerbertTokenizer:()=>C,LlamaTokenizer:()=>dr,M2M100Tokenizer:()=>rs,MBart50Tokenizer:()=>qe,MBartTokenizer:()=>Mt,MPNetTokenizer:()=>Is,MarianTokenizer:()=>ss,MgpstrTokenizer:()=>js,MobileBertTokenizer:()=>Cs,NllbTokenizer:()=>Hr,NougatTokenizer:()=>Kt,PreTrainedTokenizer:()=>ft,Qwen2Tokenizer:()=>zr,RoFormerTokenizer:()=>R,RobertaTokenizer:()=>Tt,SiglipTokenizer:()=>Fs,SpeechT5Tokenizer:()=>nt,SqueezeBertTokenizer:()=>Kr,T5Tokenizer:()=>et,TokenizerModel:()=>H,VitsTokenizer:()=>Ns,Wav2Vec2CTCTokenizer:()=>Nr,WhisperTokenizer:()=>Rs,XLMRobertaTokenizer:()=>Tr,XLMTokenizer:()=>ce,is_chinese_char:()=>I});var s=t("./src/utils/generic.js"),n=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),c=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function d(ue,$){const U=await Promise.all([(0,o.getModelJSON)(ue,"tokenizer.json",!0,$),(0,o.getModelJSON)(ue,"tokenizer_config.json",!0,$)]);return $.legacy!==null&&(U[1].legacy=$.legacy),U}function u(ue,$){const U=[];let ee=0;for(const se of ue.matchAll($)){const Me=se[0];ee0&&U.push(Me),ee=se.index+Me.length}return ee=19968&&ue<=40959||ue>=13312&&ue<=19903||ue>=131072&&ue<=173791||ue>=173824&&ue<=177983||ue>=177984&&ue<=178207||ue>=178208&&ue<=183983||ue>=63744&&ue<=64255||ue>=194560&&ue<=195103}function T(ue,$,U){const ee=[];let se=0;for(;sethis.tokens_to_ids.get(U)??this.unk_token_id)}convert_ids_to_tokens($){return $.map(U=>this.vocab[U]??this.unk_token)}}class W extends H{constructor($){super($),this.tokens_to_ids=_($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.max_input_chars_per_word=$.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[U,ee]of this.tokens_to_ids)this.vocab[ee]=U}encode($){const U=[];for(const ee of $){const se=[...ee];if(se.length>this.max_input_chars_per_word){U.push(this.unk_token);continue}let Me=!1,$e=0;const Xe=[];for(;$e0&&(Ke=this.config.continuing_subword_prefix+Ke),this.tokens_to_ids.has(Ke)){Ye=Ke;break}--Je}if(Ye===null){Me=!0;break}Xe.push(Ye),$e=Je}Me?U.push(this.unk_token):U.push(...Xe)}return U}}class B extends H{constructor($,U){super($);const ee=$.vocab.length;this.vocab=new Array(ee),this.scores=new Array(ee);for(let se=0;se[se,Me])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=U.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,i.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes($){const U=$.chars,ee=1;let se=0;for(;se{const ue=[...Array.from({length:94},(se,Me)=>Me+33),...Array.from({length:12},(se,Me)=>Me+161),...Array.from({length:82},(se,Me)=>Me+174)],$=ue.slice();let U=0;for(let se=0;se<256;++se)ue.includes(se)||(ue.push(se),$.push(256+U),U+=1);const ee=$.map(se=>String.fromCharCode(se));return Object.fromEntries(ue.map((se,Me)=>[se,ee[Me]]))})(),X=(0,n.reverseDictionary)(Y);class J extends H{constructor($){super($),this.tokens_to_ids=_($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ee,se]of this.tokens_to_ids)this.vocab[se]=ee;const U=Array.isArray($.merges[0]);this.merges=U?$.merges:$.merges.map(ee=>ee.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ee,se)=>[JSON.stringify(ee),se])),this.end_of_word_suffix=$.end_of_word_suffix,this.continuing_subword_suffix=$.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new l.LRUCache(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe($){if($.length===0)return[];const U=this.cache.get($);if(U!==void 0)return U;const ee=Array.from($);this.end_of_word_suffix&&(ee[ee.length-1]+=this.end_of_word_suffix);let se=[];if(ee.length>1){const Me=new l.PriorityQueue((Je,Ye)=>Je.score`<0x${Xe.toString(16).toUpperCase().padStart(2,"0")}>`);$e.every(Xe=>this.tokens_to_ids.has(Xe))?U.push(...$e):U.push(this.unk_token)}else U.push(this.unk_token)}return U}}class re extends H{constructor($,U){super($),this.tokens_to_ids=_(U.target_lang?$.vocab[U.target_lang]:$.vocab),this.bos_token=U.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=U.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=U.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=U.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[ee,se]of this.tokens_to_ids)this.vocab[se]=ee}encode($){return $}}class ne extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"BertNormalizer":return new Te($);case"Precompiled":return new zt($);case"Sequence":return new je($);case"Replace":return new le($);case"NFC":return new oe($);case"NFD":return new K($);case"NFKC":return new N($);case"NFKD":return new D($);case"Strip":return new te($);case"StripAccents":return new he($);case"Lowercase":return new Ae($);case"Prepend":return new Ie($);default:throw new Error(`Unknown Normalizer type: ${$.type}`)}}normalize($){throw Error("normalize should be implemented in subclass.")}_call($){return this.normalize($)}}class le extends ne{normalize($){const U=f(this.config.pattern);return U===null?$:$.replaceAll(U,this.config.content)}}class pe extends ne{form=void 0;normalize($){return $=$.normalize(this.form),$}}class oe extends pe{form="NFC"}class K extends pe{form="NFD"}class N extends pe{form="NFKC"}class D extends pe{form="NFKD"}class te extends ne{normalize($){return this.config.strip_left&&this.config.strip_right?$=$.trim():(this.config.strip_left&&($=$.trimStart()),this.config.strip_right&&($=$.trimEnd())),$}}class he extends ne{normalize($){return $=w($),$}}class Ae extends ne{normalize($){return $=$.toLowerCase(),$}}class Ie extends ne{normalize($){return $=this.config.prepend+$,$}}class je extends ne{constructor($){super($),this.normalizers=$.normalizers.map(U=>ne.fromConfig(U))}normalize($){return this.normalizers.reduce((U,ee)=>ee.normalize(U),$)}}class Te extends ne{_tokenize_chinese_chars($){const U=[];for(let ee=0;ee<$.length;++ee){const se=$[ee],Me=se.charCodeAt(0);I(Me)?(U.push(" "),U.push(se),U.push(" ")):U.push(se)}return U.join("")}stripAccents($){return $.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}_is_control($){switch($){case" ":case` +`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test($)}}_clean_text($){const U=[];for(const ee of $){const se=ee.charCodeAt(0);se===0||se===65533||this._is_control(ee)||(/^\s$/.test(ee)?U.push(" "):U.push(ee))}return U.join("")}normalize($){return this.config.clean_text&&($=this._clean_text($)),this.config.handle_chinese_chars&&($=this._tokenize_chinese_chars($)),this.config.lowercase?($=$.toLowerCase(),this.config.strip_accents!==!1&&($=this.stripAccents($))):this.config.strip_accents&&($=this.stripAccents($)),$}}class Q extends s.Callable{static fromConfig($){if($===null)return null;switch($.type){case"BertPreTokenizer":return new z($);case"Sequence":return new Rr($);case"Whitespace":return new qs($);case"WhitespaceSplit":return new Qs($);case"Metaspace":return new gr($);case"ByteLevel":return new de($);case"Split":return new be($);case"Punctuation":return new ve($);case"Digits":return new xe($);case"Replace":return new Xs($);case"FixedLength":return new or($);default:throw new Error(`Unknown PreTokenizer type: ${$.type}`)}}pre_tokenize_text($,U){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize($,U){return(Array.isArray($)?$.map(ee=>this.pre_tokenize_text(ee,U)):this.pre_tokenize_text($,U)).flat()}_call($,U){return this.pre_tokenize($,U)}}class z extends Q{constructor($){super(),this.pattern=new RegExp(`[^\\s${E}]+|[${E}]`,"gu")}pre_tokenize_text($,U){return $.trim().match(this.pattern)||[]}}class de extends Q{constructor($){super(),this.config=$,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Y,this.text_encoder=new TextEncoder}pre_tokenize_text($,U){return this.add_prefix_space&&!$.startsWith(" ")&&($=" "+$),(this.use_regex?$.match(this.pattern)||[]:[$]).map(se=>Array.from(this.text_encoder.encode(se),Me=>this.byte_encoder[Me]).join(""))}}class be extends Q{constructor($){super(),this.config=$,this.pattern=f(this.config.pattern,this.config.invert)}pre_tokenize_text($,U){return this.pattern===null?[]:this.config.invert?$.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?$.split(this.pattern).filter(ee=>ee):u($,this.pattern)}}class ve extends Q{constructor($){super(),this.config=$,this.pattern=new RegExp(`[^${E}]+|[${E}]+`,"gu")}pre_tokenize_text($,U){return $.match(this.pattern)||[]}}class xe extends Q{constructor($){super(),this.config=$;const U=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(U,"gu")}pre_tokenize_text($,U){return $.match(this.pattern)||[]}}class Ce extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"TemplateProcessing":return new fe($);case"ByteLevel":return new Ee($);case"RobertaProcessing":return new De($);case"BertProcessing":return new ge($);case"Sequence":return new We($);default:throw new Error(`Unknown PostProcessor type: ${$.type}`)}}post_process($,...U){throw Error("post_process should be implemented in subclass.")}_call($,...U){return this.post_process($,...U)}}class ge extends Ce{constructor($){super($),this.cls=$.cls[0],this.sep=$.sep[0]}post_process($,U=null,{add_special_tokens:ee=!0}={}){ee&&($=(0,n.mergeArrays)([this.cls],$,[this.sep]));let se=new Array($.length).fill(0);if(U!==null){const Me=ee&&this instanceof De?[this.sep]:[],$e=ee?[this.sep]:[];$=(0,n.mergeArrays)($,Me,U,$e),se=(0,n.mergeArrays)(se,new Array(U.length+Me.length+$e.length).fill(1))}return{tokens:$,token_type_ids:se}}}class De extends ge{}class fe extends Ce{constructor($){super($),this.single=$.single,this.pair=$.pair}post_process($,U=null,{add_special_tokens:ee=!0}={}){const se=U===null?this.single:this.pair;let Me=[],$e=[];for(const Xe of se)"SpecialToken"in Xe?ee&&(Me.push(Xe.SpecialToken.id),$e.push(Xe.SpecialToken.type_id)):"Sequence"in Xe&&(Xe.Sequence.id==="A"?(Me=(0,n.mergeArrays)(Me,$),$e=(0,n.mergeArrays)($e,new Array($.length).fill(Xe.Sequence.type_id))):Xe.Sequence.id==="B"&&(Me=(0,n.mergeArrays)(Me,U),$e=(0,n.mergeArrays)($e,new Array(U.length).fill(Xe.Sequence.type_id))));return{tokens:Me,token_type_ids:$e}}}class Ee extends Ce{post_process($,U=null){return U&&($=(0,n.mergeArrays)($,U)),{tokens:$}}}class We extends Ce{constructor($){super($),this.processors=$.processors.map(U=>Ce.fromConfig(U))}post_process($,U=null,ee={}){let se;for(const Me of this.processors)if(Me instanceof Ee)$=Me.post_process($).tokens,U&&(U=Me.post_process(U).tokens);else{const $e=Me.post_process($,U,ee);$=$e.tokens,se=$e.token_type_ids}return{tokens:$,token_type_ids:se}}}class Fe extends s.Callable{constructor($){super(),this.config=$,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=$.trim_offsets}static fromConfig($){if($===null)return null;switch($.type){case"WordPiece":return new Ne($);case"Metaspace":return new Or($);case"ByteLevel":return new Oe($);case"Replace":return new tt($);case"ByteFallback":return new Re($);case"Fuse":return new rt($);case"Strip":return new Ze($);case"Sequence":return new ht($);case"CTC":return new ot($);case"BPEDecoder":return new Rt($);default:throw new Error(`Unknown Decoder type: ${$.type}`)}}_call($){return this.decode($)}decode($){return this.decode_chain($).join("")}decode_chain($){throw Error("`decode_chain` should be implemented in subclass.")}}class tt extends Fe{decode_chain($){const U=f(this.config.pattern);return U===null?$:$.map(ee=>ee.replaceAll(U,this.config.content))}}class Re extends Fe{constructor($){super($),this.text_decoder=new TextDecoder}decode_chain($){const U=[];let ee=[];for(const se of $){let Me=null;if(se.length===6&&se.startsWith("<0x")&&se.endsWith(">")){const $e=parseInt(se.slice(3,5),16);isNaN($e)||(Me=$e)}if(Me!==null)ee.push(Me);else{if(ee.length>0){const $e=this.text_decoder.decode(Uint8Array.from(ee));U.push($e),ee=[]}U.push(se)}}if(ee.length>0){const se=this.text_decoder.decode(Uint8Array.from(ee));U.push(se),ee=[]}return U}}class rt extends Fe{decode_chain($){return[$.join("")]}}class Ze extends Fe{constructor($){super($),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain($){return $.map(U=>{let ee=0;for(let Me=0;Me(ee!==0&&(U.startsWith(this.config.prefix)?U=U.replace(this.config.prefix,""):U=" "+U),this.cleanup&&(U=k(U)),U))}}class Oe extends Fe{constructor($){super($),this.byte_decoder=X,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string($){const U=$.join(""),ee=new Uint8Array([...U].map(Me=>this.byte_decoder[Me]));return this.text_decoder.decode(ee)}decode_chain($){const U=[];let ee=[];for(const se of $)this.added_tokens.find(Me=>Me.content===se)!==void 0?(ee.length>0&&(U.push(this.convert_tokens_to_string(ee)),ee=[]),U.push(se)):ee.push(se);return ee.length>0&&U.push(this.convert_tokens_to_string(ee)),U}}class ot extends Fe{constructor($){super($),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string($){if($.length===0)return"";const U=[$[0]];for(let Me=1;Me<$.length;++Me)$[Me]!==U.at(-1)&&U.push($[Me]);let se=U.filter(Me=>Me!==this.pad_token).join("");return this.cleanup&&(se=k(se).replaceAll(this.word_delimiter_token," ").trim()),se}decode_chain($){return[this.convert_tokens_to_string($)]}}class ht extends Fe{constructor($){super($),this.decoders=$.decoders.map(U=>Fe.fromConfig(U))}decode_chain($){return this.decoders.reduce((U,ee)=>ee.decode_chain(U),$)}}class Rt extends Fe{constructor($){super($),this.suffix=this.config.suffix}decode_chain($){return $.map((U,ee)=>U.replaceAll(this.suffix,ee===$.length-1?"":" "))}}class It extends Fe{decode_chain($){let U="";for(let ee=1;ee<$.length;ee+=2)U+=$[ee];return[U]}}class gr extends Q{constructor($){super(),this.replacement=$.replacement,this.strRep=$.str_rep||this.replacement,this.prepend_scheme=$.prepend_scheme??"always"}pre_tokenize_text($,{section_index:U=void 0}={}){let ee=$.replaceAll(" ",this.strRep);return!ee.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&U===0)&&(ee=this.strRep+ee),[ee]}}class Or extends Fe{constructor($){super($),this.replacement=$.replacement}decode_chain($){const U=[];for(let ee=0;ee<$.length;++ee){let se=$[ee].replaceAll(this.replacement," ");ee==0&&se.startsWith(" ")&&(se=se.substring(1)),U.push(se)}return U}}class zt extends ne{constructor($){super($),this.charsmap=$.precompiled_charsmap}normalize($){return $=$.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),$=$.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),$.includes("~")?$=$.split("~").map(ee=>ee.normalize("NFKC")).join("~"):$=$.normalize("NFKC"),$}}class Rr extends Q{constructor($){super(),this.tokenizers=$.pretokenizers.map(U=>Q.fromConfig(U))}pre_tokenize_text($,U){return this.tokenizers.reduce((ee,se)=>se.pre_tokenize(ee,U),[$])}}class qs extends Q{constructor($){super()}pre_tokenize_text($,U){return $.match(/\w+|[^\w\s]+/g)||[]}}class Qs extends Q{constructor($){super()}pre_tokenize_text($,U){return b($)}}class Xs extends Q{constructor($){super(),this.config=$,this.pattern=f(this.config.pattern),this.content=this.config.content}pre_tokenize_text($,U){return this.pattern===null?[$]:[$.replaceAll(this.pattern,this.config.content)]}}class or extends Q{constructor($){super(),this._length=$.length}pre_tokenize_text($,U){const ee=[];for(let se=0;se<$.length;se+=this._length)ee.push($.slice(se,se+this._length));return ee}}const Sr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Qr(ue,$,U,ee){for(const se of Object.keys(ue)){const Me=$-ue[se].length,$e=U(se),Xe=new Array(Me).fill($e);ue[se]=ee==="right"?(0,n.mergeArrays)(ue[se],Xe):(0,n.mergeArrays)(Xe,ue[se])}}function Bs(ue,$){for(const U of Object.keys(ue))ue[U].length=$}class ft extends s.Callable{return_token_type_ids=!1;padding_side="right";constructor($,U){super(),this.config=U,this.normalizer=ne.fromConfig($.normalizer),this.pre_tokenizer=Q.fromConfig($.pre_tokenizer),this.model=H.fromConfig($.model,U),this.post_processor=Ce.fromConfig($.post_processor),this.decoder=Fe.fromConfig($.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ee of $.added_tokens){const se=new F(ee);this.added_tokens.push(se),this.model.tokens_to_ids.set(se.content,se.id),this.model.vocab[se.id]=se.content,se.special&&(this.special_tokens.push(se.content),this.all_special_ids.push(se.id))}if(this.additional_special_tokens=U.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new l.DictionarySplitter(this.added_tokens.map(ee=>ee.content)),this.added_tokens_map=new Map(this.added_tokens.map(ee=>[ee.content,ee])),this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=U.model_max_length,this.remove_space=U.remove_space,this.clean_up_tokenization_spaces=U.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=U.do_lowercase_and_remove_accent??!1,U.padding_side&&(this.padding_side=U.padding_side),this.add_bos_token=U.add_bos_token,this.add_eos_token=U.add_eos_token,this.legacy=!1,this.chat_template=U.chat_template??null,Array.isArray(this.chat_template)){const ee=Object.create(null);for(const{name:se,template:Me}of this.chat_template){if(typeof se!="string"||typeof Me!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ee[se]=Me}this.chat_template=ee}this._compiled_template_cache=new Map}getToken(...$){for(const U of $){const ee=this.config[U];if(ee)if(typeof ee=="object"){if(ee.__type==="AddedToken")return ee.content;throw Error(`Unknown token: ${ee}`)}else return ee}return null}static async from_pretrained($,{progress_callback:U=null,config:ee=null,cache_dir:se=null,local_files_only:Me=!1,revision:$e="main",legacy:Xe=null}={}){const Je=await d($,{progress_callback:U,config:ee,cache_dir:se,local_files_only:Me,revision:$e,legacy:Xe});return new this(...Je)}_call($,{text_pair:U=null,add_special_tokens:ee=!0,padding:se=!1,truncation:Me=null,max_length:$e=null,return_tensor:Xe=!0,return_token_type_ids:Je=null}={}){const Ye=Array.isArray($);let Ke;if(Ye){if($.length===0)throw Error("text array must be non-empty");if(U!==null){if(Array.isArray(U)){if($.length!==U.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Ke=$.map((Et,rr)=>this._encode_plus(Et,{text_pair:U[rr],add_special_tokens:ee,return_token_type_ids:Je}))}else Ke=$.map(Et=>this._encode_plus(Et,{add_special_tokens:ee,return_token_type_ids:Je}))}else{if($==null)throw Error("text may not be null or undefined");if(Array.isArray(U))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Ke=[this._encode_plus($,{text_pair:U,add_special_tokens:ee,return_token_type_ids:Je})]}if($e===null?$e=this.model_max_length:Me===null&&(se===!0?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),$e=this.model_max_length):se===!1&&(console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),Me=!0)),se===!0&&($e=Math.min((0,i.max)(Ke.map(Et=>Et.input_ids.length))[0],$e??1/0)),$e=Math.min($e,this.model_max_length??1/0),se||Me)for(let Et=0;Et$e?Me&&Bs(Ke[Et],$e):se&&Qr(Ke[Et],$e,rr=>rr==="input_ids"?this.pad_token_id:0,this.padding_side));const $t={};if(Xe){if(!(se&&Me)&&Ke.some(rr=>{for(const br of Object.keys(rr))if(rr[br].length!==Ke[0][br]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const Et=[Ke.length,Ke[0].input_ids.length];for(const rr of Object.keys(Ke[0]))$t[rr]=new a.Tensor("int64",BigInt64Array.from(Ke.flatMap(br=>br[rr]).map(BigInt)),Et)}else{for(const Et of Object.keys(Ke[0]))$t[Et]=Ke.map(rr=>rr[Et]);if(!Ye)for(const Et of Object.keys($t))$t[Et]=$t[Et][0]}return $t}_encode_text($){if($===null)return null;const U=this.added_tokens_splitter.split($);for(let se=0;se0&&(U[se-1]=U[se-1].trimEnd()),Me.rstrip&&se{if(se.length===0)return[];if(this.added_tokens_map.has(se))return[se];if(this.remove_space===!0&&(se=se.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(se=v(se)),this.normalizer!==null&&(se=this.normalizer(se)),se.length===0)return[];const $e=this.pre_tokenizer!==null?this.pre_tokenizer(se,{section_index:Me}):[se];return this.model($e)})}_encode_plus($,{text_pair:U=null,add_special_tokens:ee=!0,return_token_type_ids:se=null}={}){const{tokens:Me,token_type_ids:$e}=this._tokenize_helper($,{pair:U,add_special_tokens:ee}),Xe=this.model.convert_tokens_to_ids(Me),Je={input_ids:Xe,attention_mask:new Array(Xe.length).fill(1)};return(se??this.return_token_type_ids)&&$e&&(Je.token_type_ids=$e),Je}_tokenize_helper($,{pair:U=null,add_special_tokens:ee=!1}={}){const se=this._encode_text($),Me=this._encode_text(U);return this.post_processor?this.post_processor(se,Me,{add_special_tokens:ee}):{tokens:(0,n.mergeArrays)(se??[],Me??[])}}tokenize($,{pair:U=null,add_special_tokens:ee=!1}={}){return this._tokenize_helper($,{pair:U,add_special_tokens:ee}).tokens}encode($,{text_pair:U=null,add_special_tokens:ee=!0,return_token_type_ids:se=null}={}){return this._encode_plus($,{text_pair:U,add_special_tokens:ee,return_token_type_ids:se}).input_ids}batch_decode($,U={}){return $ instanceof a.Tensor&&($=$.tolist()),$.map(ee=>this.decode(ee,U))}decode($,U={}){if($ instanceof a.Tensor&&($=y($)),!Array.isArray($)||$.length===0||!(0,n.isIntegralNumber)($[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single($,U)}decode_single($,{skip_special_tokens:U=!1,clean_up_tokenization_spaces:ee=null}){let se=this.model.convert_ids_to_tokens($);U&&(se=se.filter($e=>!this.special_tokens.includes($e)));let Me=this.decoder?this.decoder(se):se.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Me=Me.replaceAll(this.decoder.end_of_word_suffix," "),U&&(Me=Me.trim())),(ee??this.clean_up_tokenization_spaces)&&(Me=k(Me)),Me}get_chat_template({chat_template:$=null,tools:U=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ee=this.chat_template;if($!==null&&Object.hasOwn(ee,$))$=ee[$];else if($===null)if(U!==null&&"tool_use"in ee)$=ee.tool_use;else if("default"in ee)$=ee.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(ee).sort()}.`)}else if($===null)if(this.chat_template)$=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return $}apply_chat_template($,{tools:U=null,documents:ee=null,chat_template:se=null,add_generation_prompt:Me=!1,tokenize:$e=!0,padding:Xe=!1,truncation:Je=!1,max_length:Ye=null,return_tensor:Ke=!0,return_dict:$t=!1,tokenizer_kwargs:Et={},...rr}={}){if(se=this.get_chat_template({chat_template:se,tools:U}),typeof se!="string")throw Error(`chat_template must be a string, but got ${typeof se}`);let br=this._compiled_template_cache.get(se);br===void 0&&(br=new c.Template(se),this._compiled_template_cache.set(se,br));const Xt=Object.create(null);for(const Ht of Sr){const qr=this.getToken(Ht);qr&&(Xt[Ht]=qr)}const sr=br.render({messages:$,add_generation_prompt:Me,tools:U,documents:ee,...Xt,...rr});if($e){const Ht=this._call(sr,{add_special_tokens:!1,padding:Xe,truncation:Je,max_length:Ye,return_tensor:Ke,...Et});return $t?Ht:Ht.input_ids}return sr}}class qt extends ft{return_token_type_ids=!0}class Ps extends ft{return_token_type_ids=!0}class Cs extends ft{return_token_type_ids=!0}class Kr extends ft{return_token_type_ids=!0}class yt extends ft{return_token_type_ids=!0}class Ss extends ft{return_token_type_ids=!0}class C extends ft{return_token_type_ids=!0}class q extends ft{return_token_type_ids=!0}class R extends ft{return_token_type_ids=!0}class G extends ft{}class Z extends ft{}class ce extends ft{return_token_type_ids=!0;constructor($,U){super($,U),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class ye extends ft{return_token_type_ids=!0}class et extends ft{}class ut extends ft{}class He extends ft{}class Mt extends ft{constructor($,U){super($,U),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ee=>this.languageRegex.test(ee)),this.lang_to_token=ee=>ee}_build_translation_inputs($,U,ee){return ir(this,$,U,ee)}}class qe extends Mt{}class Tt extends ft{}class kt extends ft{}const Mr="▁";class dr extends ft{padding_side="left";constructor($,U){super($,U),this.legacy=U.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new gr({replacement:Mr,prepend_scheme:"first"}))}_encode_text($){if($===null)return null;if(this.legacy||$.length===0)return super._encode_text($);let U=super._encode_text(Mr+$.replaceAll(Mr," "));return U.length>1&&U[0]===Mr&&this.special_tokens.includes(U[1])&&(U=U.slice(1)),U}}class ar extends ft{}class Tr extends ft{}class Is extends ft{}class Dr extends ft{}class $s extends ft{}class Lr extends ft{}class zr extends ft{}class ts extends ft{}class wr extends ft{}function ir(ue,$,U,ee){if(!("language_codes"in ue)||!Array.isArray(ue.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in ue)||!(ue.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in ue)||typeof ue.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const se=ee.src_lang,Me=ee.tgt_lang;if(!ue.language_codes.includes(Me))throw new Error(`Target language code "${Me}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);if(se!==void 0){if(!ue.language_codes.includes(se))throw new Error(`Source language code "${se}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);for(const $e of ue.post_processor.config.single)if("SpecialToken"in $e&&ue.languageRegex.test($e.SpecialToken.id)){$e.SpecialToken.id=ue.lang_to_token(se);break}}return ee.forced_bos_token_id=ue.model.convert_tokens_to_ids([ue.lang_to_token(Me)])[0],ue._call($,U)}class Hr extends ft{constructor($,U){super($,U),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ee=>this.languageRegex.test(ee)),this.lang_to_token=ee=>ee}_build_translation_inputs($,U,ee){return ir(this,$,U,ee)}}class rs extends ft{constructor($,U){super($,U),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ee=>this.languageRegex.test(ee)).map(ee=>ee.slice(2,-2)),this.lang_to_token=ee=>`__${ee}__`}_build_translation_inputs($,U,ee){return ir(this,$,U,ee)}}class Rs extends ft{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr($,{return_timestamps:U=!1,return_language:ee=!1,time_precision:se=null,force_full_sequences:Me=!0}={}){if(se===null)throw Error("Must specify time_precision");let $e=null;const Xe=U==="word";function Je(){return{language:$e,timestamp:[null,null],text:""}}const Ye=[];let Ke=Je(),$t=0;const Et=this.timestamp_begin,br=Et+1500;let Xt=[],sr=[],Ht=!1,qr=null;const ns=new Set(this.all_special_ids);for(const Yt of $){const hr=Yt.tokens,Ir=Xe?Yt.token_timestamps:null;let Xr=null,ps=Et;if("stride"in Yt){const[vr,Zt,_r]=Yt.stride;if($t-=Zt,qr=vr-_r,Zt&&(ps=Zt/se+Et),_r)for(let lr=hr.length-1;lr>=0;--lr){const Ur=Number(hr[lr]);if(Ur>=Et){if(Xr!==null&&(Ur-Et)*se=Et&&Zt<=br){const _r=(Zt-Et)*se+$t,lr=(0,i.round)(_r,2);if(Xr!==null&&Zt>=Xr)Ht=!0;else if(Ht||Xt.length>0&&Zt0?(Xt.push(yr),Xe&&sr.push(os)):Xt.every(vr=>vr.length===0)&&(Ke=Je(),Xt=[],yr=[],sr=[],os=[])}if(Xt.length>0){if(Me&&U)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Yt,hr]=this.findLongestCommonSequence(Xt,sr),Ir=this.decode(Yt);Ke.text=Ir,Xe&&(Ke.words=this.collateWordTimestamps(Yt,hr,$e)),Ye.push(Ke)}let Er=Object.create(null);const ds=Ye.map(Yt=>Yt.text).join("");if(U||ee){for(let Yt=0;Yt0;let Xe=$e?[]:null,Je=$e?U[0]:null;for(let Ye=1;Ye<$.length;++Ye){const Ke=$[Ye];let $t=0,Et=[se,se,0,0];const rr=Ke.length;for(let Er=1;ErZt===ps[_r]&&Je[ds+_r]<=U[Ye][Ir+_r]).length:yr=hr.filter((Zt,_r)=>Zt===ps[_r]).length;const os=Er/1e4,vr=yr/Er+os;yr>1&&vr>$t&&($t=vr,Et=[ds,Yt,Ir,Xr])}const[br,Xt,sr,Ht]=Et,qr=Math.floor((Xt+br)/2),ns=Math.floor((Ht+sr)/2);Me.push(...ee.slice(0,qr)),ee=Ke.slice(ns),se=ee.length,$e&&(Xe.push(...Je.slice(0,qr)),Je=U[Ye].slice(ns))}return Me.push(...ee),$e?(Xe.push(...Je),[Me,Xe]):[Me,[]]}collateWordTimestamps($,U,ee){const[se,Me,$e]=this.combineTokensIntoWords($,ee),Xe=[];for(let Je=0;Je=se){const Xe=(($e-se)*ee).toFixed(2);Me.push(`<|${Xe}|>`),Me.push([])}else Me[Me.length-1].push($e);return Me=Me.map($e=>typeof $e=="string"?$e:super.decode($e,U)),Me.join("")}splitTokensOnUnicode($){const U=this.decode($,{decode_with_timestamps:!0}),ee="�",se=[],Me=[],$e=[];let Xe=[],Je=[],Ye=0;for(let Ke=0;Ke<$.length;++Ke){const $t=$[Ke];Xe.push($t),Je.push(Ke);const Et=this.decode(Xe,{decode_with_timestamps:!0});(!Et.includes(ee)||U[Ye+Et.indexOf(ee)]===ee)&&(se.push(Et),Me.push(Xe),$e.push(Je),Xe=[],Je=[],Ye+=Et.length)}return[se,Me,$e]}splitTokensOnSpaces($){const[U,ee,se]=this.splitTokensOnUnicode($),Me=[],$e=[],Xe=[],Je=new RegExp(`^[${E}]$`,"gu");for(let Ye=0;Ye=this.model.tokens_to_ids.get("<|endoftext|>"),br=Ke.startsWith(" "),Xt=Ke.trim(),sr=Je.test(Xt);if(rr||br||sr||Me.length===0)Me.push(Ke),$e.push($t),Xe.push(Et);else{const Ht=Me.length-1;Me[Ht]+=Ke,$e[Ht].push(...$t),Xe[Ht].push(...Et)}}return[Me,$e,Xe]}mergePunctuations($,U,ee,se,Me){const $e=structuredClone($),Xe=structuredClone(U),Je=structuredClone(ee);let Ye=$e.length-2,Ke=$e.length-1;for(;Ye>=0;)$e[Ye].startsWith(" ")&&se.includes($e[Ye].trim())?($e[Ke]=$e[Ye]+$e[Ke],Xe[Ke]=(0,n.mergeArrays)(Xe[Ye],Xe[Ke]),Je[Ke]=(0,n.mergeArrays)(Je[Ye],Je[Ke]),$e[Ye]="",Xe[Ye]=[],Je[Ye]=[]):Ke=Ye,--Ye;for(Ye=0,Ke=1;Ke<$e.length;)!$e[Ye].endsWith(" ")&&Me.includes($e[Ke])?($e[Ye]+=$e[Ke],Xe[Ye]=(0,n.mergeArrays)(Xe[Ye],Xe[Ke]),Je[Ye]=(0,n.mergeArrays)(Je[Ye],Je[Ke]),$e[Ke]="",Xe[Ke]=[],Je[Ke]=[]):Ye=Ke,++Ke;return[$e.filter($t=>$t),Xe.filter($t=>$t.length>0),Je.filter($t=>$t.length>0)]}}class ks extends ft{}class As extends ft{}class Fs extends ft{}class ss extends ft{constructor($,U){super($,U),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ee=>this.languageRegex.test(ee)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text($){if($===null)return null;const[U,...ee]=$.trim().split(this.languageRegex);if(ee.length===0)return super._encode_text(U);if(ee.length===2){const[se,Me]=ee;return this.supported_language_codes.includes(se)||console.warn(`Unsupported language code "${se}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,n.mergeArrays)([se],super._encode_text(Me))}}}class Nr extends ft{}class ze extends ft{}class Ue extends ft{}class nt extends ft{}class Kt extends ft{}class Ns extends ft{constructor($,U){super($,U),this.decoder=new It({})}}class Os extends ft{}class js extends ft{}class Dn{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:et,DistilBertTokenizer:G,CamembertTokenizer:Z,DebertaTokenizer:yt,DebertaV2Tokenizer:Ss,BertTokenizer:qt,HerbertTokenizer:C,ConvBertTokenizer:q,RoFormerTokenizer:R,XLMTokenizer:ce,ElectraTokenizer:ye,MobileBertTokenizer:Cs,SqueezeBertTokenizer:Kr,AlbertTokenizer:Ps,GPT2Tokenizer:ut,BartTokenizer:He,MBartTokenizer:Mt,MBart50Tokenizer:qe,RobertaTokenizer:Tt,WhisperTokenizer:Rs,CodeGenTokenizer:ks,CLIPTokenizer:As,SiglipTokenizer:Fs,MarianTokenizer:ss,BloomTokenizer:kt,NllbTokenizer:Hr,M2M100Tokenizer:rs,LlamaTokenizer:dr,CodeLlamaTokenizer:ar,XLMRobertaTokenizer:Tr,MPNetTokenizer:Is,FalconTokenizer:Dr,GPTNeoXTokenizer:$s,EsmTokenizer:Lr,Wav2Vec2CTCTokenizer:Nr,BlenderbotTokenizer:ze,BlenderbotSmallTokenizer:Ue,SpeechT5Tokenizer:nt,NougatTokenizer:Kt,VitsTokenizer:Ns,Qwen2Tokenizer:zr,GemmaTokenizer:ts,Grok1Tokenizer:wr,CohereTokenizer:Os,MgpstrTokenizer:js,PreTrainedTokenizer:ft};static async from_pretrained($,{progress_callback:U=null,config:ee=null,cache_dir:se=null,local_files_only:Me=!1,revision:$e="main",legacy:Xe=null}={}){const[Je,Ye]=await d($,{progress_callback:U,config:ee,cache_dir:se,local_files_only:Me,revision:$e,legacy:Xe}),Ke=Ye.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let $t=this.TOKENIZER_CLASS_MAPPING[Ke];return $t||(console.warn(`Unknown tokenizer class "${Ke}", attempting to construct from base class.`),$t=ft),new $t(Je,Ye)}}}),"./src/utils/audio.js":((e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>W,hamming:()=>u,hanning:()=>d,mel_filter_bank:()=>I,read_audio:()=>c,spectrogram:()=>S,window_function:()=>O});var s=t("./src/utils/hub.js"),n=t("./src/utils/maths.js"),o=t("./src/utils/core.js"),i=t("./src/env.js"),a=t("./src/utils/tensor.js"),l=t("?7992");async function c(B,Y){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const X=await(await(0,s.getFile)(B)).arrayBuffer(),J=new AudioContext({sampleRate:Y});typeof Y>"u"&&console.warn(`No sampling rate provided, using default of ${J.sampleRate}Hz.`);const re=await J.decodeAudioData(X);let ne;if(re.numberOfChannels===2){const le=Math.sqrt(2),pe=re.getChannelData(0),oe=re.getChannelData(1);ne=new Float32Array(pe.length);for(let K=0;K2595*Math.log10(1+B/700),kaldi:B=>1127*Math.log(1+B/700),slaney:(B,Y=1e3,X=15,J=27/Math.log(6.4))=>B>=Y?X+Math.log(B/Y)*J:3*B/200};function _(B,Y="htk"){const X=f[Y];if(!X)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof B=="number"?X(B):B.map(J=>X(J))}const y={htk:B=>700*(10**(B/2595)-1),kaldi:B=>700*(Math.exp(B/1127)-1),slaney:(B,Y=1e3,X=15,J=Math.log(6.4)/27)=>B>=X?Y*Math.exp(J*(B-X)):200*B/3};function k(B,Y="htk"){const X=y[Y];if(!X)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof B=="number"?X(B):B.map(J=>X(J))}function w(B,Y){const X=Float64Array.from({length:Y.length-1},(le,pe)=>Y[pe+1]-Y[pe]),J=Array.from({length:B.length},()=>new Array(Y.length));for(let le=0;lenew Array(B.length));for(let le=0;leB+J*ne)}function I(B,Y,X,J,re,ne=null,le="htk",pe=!1){if(ne!==null&&ne!=="slaney")throw new Error('norm must be one of null or "slaney"');if(B<2)throw new Error(`Require num_frequency_bins: ${B} >= 2`);if(X>J)throw new Error(`Require min_frequency: ${X} <= max_frequency: ${J}`);const oe=_(X,le),K=_(J,le),N=v(oe,K,Y+2);let D=k(N,le),te;if(pe){const Ae=re/((B-1)*2);te=_(Float64Array.from({length:B},(Ie,je)=>je*Ae),le),D=N}else te=v(0,Math.floor(re/2),B);const he=w(te,D);if(ne!==null&&ne==="slaney")for(let Ae=0;Aere)throw Error(`frame_length (${X}) may not be larger than fft_length (${re})`);if(xe!==X)throw new Error(`Length of the window (${xe}) must equal frame_length (${X})`);if(J<=0)throw new Error("hop_length must be greater than zero");if(ne===null&&D!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!N)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(le)switch(pe){case"reflect":{const Ne=Math.floor((re-1)/2)+1;B=T(B,Ne,Ne);break}case"constant":{const Ne=Math.floor(re/2),Oe=new B.constructor(B.length+2*Ne);Oe.set(B,Ne),B=Oe;break}default:throw new Error(`pad_mode="${pe}" not implemented yet.`)}let Ce=Math.floor(1+Math.floor((B.length-X)/J));Q!==null&&CeCe?de&&(fe=z):fe=De=z);const Ee=new n.FFT(re),We=new Float64Array(re),Fe=new Float64Array(Ee.outputBufferSize),tt=new Float32Array(ge*fe);for(let Ne=0;Ne=1;--ht)We[ht]-=K*We[ht-1];We[0]*=1-K}for(let ht=0;htMath.pow(pe,.85));break;default:throw new Error(`Unknown window type ${Y}.`)}if(X&&(le=le.subarray(0,B)),J===null)return le;if(B>J)throw new Error(`Length of the window (${B}) may not be larger than frame_length (${J})`);return le}function F(B,Y){let X=44;const J=new ArrayBuffer(X+B.length*4),re=new DataView(J);H(re,0,"RIFF"),re.setUint32(4,36+B.length*4,!0),H(re,8,"WAVE"),H(re,12,"fmt "),re.setUint32(16,16,!0),re.setUint16(20,3,!0),re.setUint16(22,1,!0),re.setUint32(24,Y,!0),re.setUint32(28,Y*4,!0),re.setUint16(32,4,!0),re.setUint16(34,32,!0),H(re,36,"data"),re.setUint32(40,B.length*4,!0);for(let ne=0;ne{let ne=await re.arrayBuffer();l.writeFileSync(J,Buffer.from(ne))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await X(Y,this.toBlob())}}}),"./src/utils/constants.js":((e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>n,FEATURE_EXTRACTOR_NAME:()=>o,GENERATION_CONFIG_NAME:()=>c,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",n="config.json",o="preprocessor_config.json",i=o,a="processor_config.json",l="chat_template.jinja",c="generation_config.json"}),"./src/utils/core.js":((e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>c,calculateReflectOffset:()=>f,count:()=>w,dispatchCallback:()=>s,escapeRegExp:()=>o,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>k,mergeArrays:()=>d,pick:()=>y,pop:()=>p,product:()=>u,reverseDictionary:()=>n,saveBlob:()=>_});function s(v,I){v&&v(I)}function n(v){return Object.fromEntries(Object.entries(v).map(([I,T])=>[T,I]))}function o(v){return v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(v){return v?.prototype?.__proto__?.constructor?.name==="TypedArray"}function a(v){return Number.isInteger(v)||typeof v=="bigint"}function l(v){return v==null||v===-1}function c(v){const I=[];let T=v;for(;Array.isArray(T);)I.push(T.length),T=T[0];return I}function p(v,I,T=void 0){const b=v[I];if(b!==void 0)return delete v[I],b;if(T===void 0)throw Error(`Key ${I} does not exist in object.`);return T}function d(...v){return Array.prototype.concat.apply([],v)}function u(...v){return v.reduce((I,T)=>I.flatMap(b=>T.map(E=>[b,E])))}function f(v,I){return Math.abs((v+I)%(2*I)-I)}function _(v,I){const T=URL.createObjectURL(I),b=document.createElement("a");b.href=T,b.download=v,b.click(),b.remove(),URL.revokeObjectURL(T)}function y(v,I){return Object.assign({},...I.map(T=>{if(v[T]!==void 0)return{[T]:v[T]}}))}function k(v){let I=0;for(const T of v)++I;return I}function w(v,I){let T=0;for(const b of v)b===I&&++T;return T}}),"./src/utils/data-structures.js":((e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>n,DictionarySplitter:()=>l,LRUCache:()=>c,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(d=(f,_)=>f>_,u=1/0){this._heap=[],this._comparator=d,this._maxSize=u}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...d){return this.extend(d)}extend(d){for(const u of d)if(this.size0&&this._swap(0,u),this._heap.pop(),this._siftDown(),d}replace(d){const u=this.peek();return this._heap[0]=d,this._siftDown(),u}_parent(d){return(d+1>>>1)-1}_left(d){return(d<<1)+1}_right(d){return d+1<<1}_greater(d,u){return this._comparator(this._heap[d],this._heap[u])}_swap(d,u){const f=this._heap[d];this._heap[d]=this._heap[u],this._heap[u]=f}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(d){for(;d>0&&this._greater(d,this._parent(d));)this._swap(d,this._parent(d)),d=this._parent(d)}_siftDown(){let d=0;for(;this._left(d)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const _=new a(this.bosTokenId,0,0,0,0),y=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(_.clone()),this.nodes.push(y.clone()),this.beginNodes[this.len].push(y),this.endNodes[0].push(_)}insert(d,u,f,_){const y=this.nodes.length,k=new a(_,y,d,u,f);this.beginNodes[d].push(k),this.endNodes[d+u].push(k),this.nodes.push(k)}viterbi(){const d=this.len;let u=0;for(;u<=d;){if(this.beginNodes[u].length==0)return[];for(let w of this.beginNodes[u]){w.prev=null;let v=0,I=null;for(let T of this.endNodes[u]){const b=T.backtraceScore+w.score;(I===null||b>v)&&(I=T.clone(),v=b)}if(I!==null)w.prev=I,w.backtraceScore=v;else return[]}++u}const f=[],y=this.beginNodes[d][0].prev;if(y===null)return[];let k=y.clone();for(;k.prev!==null;)f.push(k.clone()),k=k.clone().prev.clone();return f.reverse(),f}piece(d){return this.chars.slice(d.pos,d.pos+d.length).join("")}tokens(){return this.viterbi().map(u=>this.piece(u))}tokenIds(){return this.viterbi().map(u=>u.tokenId)}}class a{constructor(d,u,f,_,y){this.tokenId=d,this.nodeId=u,this.pos=f,this.length=_,this.score=y,this.prev=null,this.backtraceScore=0}clone(){const d=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return d.prev=this.prev,d.backtraceScore=this.backtraceScore,d}}class l{constructor(d){this.trie=this._buildTrie(d)}_buildTrie(d){const u=Object.create(null);for(const f of d){let _=u;for(let y=0;y_&&u.push(d.slice(_,y)),u.push(w),y+=w.length,_=y):++y}return _this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}}),"./src/utils/devices.js":((e,r,t)=>{t.r(r),t.d(r,{DEVICE_TYPES:()=>s});const s=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})}),"./src/utils/dtypes.js":((e,r,t)=>{t.r(r),t.d(r,{DATA_TYPES:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>o});var s=t("./src/env.js"),n=t("./src/utils/devices.js");const o=(function(){let c;return async function(){if(c===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)c=!1;else try{c=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{c=!1}return c}})(),i=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[n.DEVICE_TYPES.wasm]:i.q8}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized",[i.q4]:"_q4",[i.q4f16]:"_q4f16",[i.bnb4]:"_bnb4"})}),"./src/utils/generic.js":((e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let n=function(...o){return n._call(...o)};return Object.setPrototypeOf(n,new.target.prototype)}_call(...n){throw Error("Must implement _call method in subclass")}}}),"./src/utils/hub.js":((e,r,t)=>{t.r(r),t.d(r,{MAX_EXTERNAL_DATA_CHUNKS:()=>a,getFile:()=>f,getModelFile:()=>v,getModelJSON:()=>T,getModelText:()=>I});var s=t("?7992"),n=t("?5af5"),o=t("./src/env.js"),i=t("./src/utils/core.js");const a=100,l={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class c{constructor(S){if(this.filePath=S,this.headers=new Headers,this.exists=s.existsSync(S),this.exists){this.status=200,this.statusText="OK";let O=s.statSync(S);this.headers.set("content-length",O.size.toString()),this.updateContentType();const F=s.createReadStream(S);this.body=new ReadableStream({start(H){F.on("data",W=>H.enqueue(W)),F.on("end",()=>H.close()),F.on("error",W=>H.error(W))},cancel(){F.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const S=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[S]??"application/octet-stream")}clone(){let S=new c(this.filePath);return S.exists=this.exists,S.status=this.status,S.statusText=this.statusText,S.headers=new Headers(this.headers),S}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const S=await s.promises.readFile(this.filePath);return new Blob([S],{type:this.headers.get("content-type")})}async text(){return await s.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function p(x,S=null,O=null){let F;try{F=new URL(x)}catch{return!1}return!(S&&!S.includes(F.protocol)||O&&!O.includes(F.hostname))}const d=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function u(x){return!(!d.test(x)||x.includes("..")||x.includes("--")||x.endsWith(".git")||x.endsWith(".ipynb"))}async function f(x){if(o.env.useFS&&!p(x,["http:","https:","blob:"]))return new c(x instanceof URL?x.protocol==="file:"?x.pathname:x.toString():x);if(typeof process<"u"&&process?.release?.name==="node"){const S=!!qc?.TESTING_REMOTELY,O=o.env.version,F=new Headers;if(F.set("User-Agent",`transformers.js/${O}; is_ci/${S};`),p(x,["http:","https:"],["huggingface.co","hf.co"])){const W=qc?.HF_TOKEN??qc?.HF_ACCESS_TOKEN;W&&F.set("Authorization",`Bearer ${W}`)}return fetch(x,{headers:F})}else return fetch(x)}const _={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function y(x,S,O){if(!O)return null;const F=_[x]??`Error (${x}) occurred while trying to load file`;throw Error(`${F}: "${S}".`)}class k{constructor(S){this.path=S}async match(S){let O=n.join(this.path,S),F=new c(O);if(F.exists)return F}async put(S,O,F=void 0){let H=n.join(this.path,S);try{const W=O.headers.get("Content-Length"),B=parseInt(W??"0");let Y=0;await s.promises.mkdir(n.dirname(H),{recursive:!0});const X=s.createWriteStream(H),J=O.body.getReader();for(;;){const{done:re,value:ne}=await J.read();if(re)break;await new Promise((pe,oe)=>{X.write(ne,K=>{if(K){oe(K);return}pe()})}),Y+=ne.length;const le=B?Y/B*100:0;F?.({progress:le,loaded:Y,total:B})}X.close()}catch(W){try{await s.promises.unlink(H)}catch{}throw W}}}async function w(x,...S){for(let O of S)try{let F=await x.match(O);if(F)return F}catch{continue}}async function v(x,S,O=!0,F={},H=!1){if(!o.env.allowLocalModels){if(F.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!o.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,i.dispatchCallback)(F.progress_callback,{status:"initiate",name:x,file:S});let W;if(!W&&o.env.useCustomCache){if(!o.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!o.env.customCache.match||!o.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");W=o.env.customCache}if(!W&&o.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{W=await caches.open("transformers-cache")}catch(te){console.warn("An error occurred while opening the browser cache:",te)}}if(!W&&o.env.useFSCache){if(!o.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");W=new k(F.cache_dir??o.env.cacheDir)}const B=F.revision??"main",Y=E(x,S),X=u(x),J=X?E(o.env.localModelPath,Y):Y,re=E(o.env.remoteHost,o.env.remotePathTemplate.replaceAll("{model}",x).replaceAll("{revision}",encodeURIComponent(B)),S);let ne;const le=W instanceof k?B==="main"?Y:E(x,B,S):re;let pe=!1,oe;W&&(oe=await w(W,J,le));const K=oe!==void 0;if(oe===void 0){if(o.env.allowLocalModels)if(p(Y,["http:","https:"])){if(F.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${Y}.`);if(!o.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${Y}.`)}else try{oe=await f(J),ne=J}catch(he){console.warn(`Unable to load from local path "${J}": "${he}"`)}if(oe===void 0||oe.status===404){if(F.local_files_only||!o.env.allowRemoteModels){if(O)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${J}".`);return null}if(!X)throw Error(`Local file missing at "${J}" and download aborted due to invalid model ID "${x}".`);if(oe=await f(re),oe.status!==200)return y(oe.status,re,O);ne=le}pe=W&&typeof Response<"u"&&oe instanceof Response&&oe.status===200}(0,i.dispatchCallback)(F.progress_callback,{status:"download",name:x,file:S});let N;if(!(o.apis.IS_NODE_ENV&&H)){let te;F.progress_callback?K&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(te=new Uint8Array(await oe.arrayBuffer()),(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:x,file:S,progress:100,loaded:te.length,total:te.length})):te=await b(oe,he=>{(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:x,file:S,...he})}):te=new Uint8Array(await oe.arrayBuffer()),N=te}if(pe&&ne&&await W.match(ne)===void 0)if(N)await W.put(ne,new Response(N,{headers:oe.headers})).catch(te=>{console.warn(`Unable to add response to browser cache: ${te}.`)});else{const te=F.progress_callback?he=>(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:x,file:S,...he}):void 0;await W.put(ne,oe,te)}if((0,i.dispatchCallback)(F.progress_callback,{status:"done",name:x,file:S}),N){if(!o.apis.IS_NODE_ENV&&H)throw new Error("Cannot return path in a browser environment.");return N}if(oe instanceof c)return oe.filePath;const D=await W?.match(ne);if(D instanceof c)return D.filePath;if(D instanceof Response)return new Uint8Array(await D.arrayBuffer());if(typeof D=="string")return D;throw new Error("Unable to get model file path or buffer.")}async function I(x,S,O=!0,F={}){const H=await v(x,S,O,F,!1);return H===null?null:new TextDecoder("utf-8").decode(H)}async function T(x,S,O=!0,F={}){const H=await I(x,S,O,F);return H===null?{}:JSON.parse(H)}async function b(x,S){const O=x.headers.get("Content-Length");O===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let F=parseInt(O??"0"),H=new Uint8Array(F),W=0;const B=x.body.getReader();async function Y(){const{done:X,value:J}=await B.read();if(X)return;const re=W+J.length;if(re>F){F=re;const le=new Uint8Array(F);le.set(H),H=le}H.set(J,W),W=re;const ne=W/F*100;return S({progress:ne,loaded:W,total:F}),Y()}return await Y(),H}function E(...x){return x=x.map((S,O)=>(O&&(S=S.replace(new RegExp("^/"),"")),O!==x.length-1&&(S=S.replace(new RegExp("/$"),"")),S)),x.join("/")}}),"./src/utils/image.js":((e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>_,load_image:()=>y});var s=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),o=t("./src/env.js"),i=t("./src/utils/tensor.js"),a=t("?2b25");let l,c,p;const d=o.apis.IS_BROWSER_ENV||o.apis.IS_WEBWORKER_ENV;if(d)l=(k,w)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(k,w)},p=self.createImageBitmap,c=self.ImageData;else if(a)p=async k=>{const v=(await k.metadata()).channels,{data:I,info:T}=await k.rotate().raw().toBuffer({resolveWithObject:!0}),b=new _(new Uint8ClampedArray(I),T.width,T.height,T.channels);return v!==void 0&&v!==T.channels&&b.convert(v),b};else throw new Error("Unable to load image processing library.");const u={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},f=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _{constructor(w,v,I,T){this.data=w,this.width=v,this.height=I,this.channels=T}get size(){return[this.width,this.height]}static async read(w){if(w instanceof _)return w;if(typeof w=="string"||w instanceof URL)return await this.fromURL(w);if(w instanceof Blob)return await this.fromBlob(w);if(typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&w instanceof OffscreenCanvas)return this.fromCanvas(w);throw new Error(`Unsupported input type: ${typeof w}`)}static fromCanvas(w){if(!d)throw new Error("fromCanvas() is only supported in browser environments.");const I=w.getContext("2d").getImageData(0,0,w.width,w.height).data;return new _(I,w.width,w.height,4)}static async fromURL(w){const v=await(0,n.getFile)(w);if(v.status!==200)throw new Error(`Unable to read image from "${w}" (${v.status} ${v.statusText})`);const I=await v.blob();return this.fromBlob(I)}static async fromBlob(w){if(d){const v=await p(w),I=l(v.width,v.height).getContext("2d");return I.drawImage(v,0,0),new this(I.getImageData(0,0,v.width,v.height).data,v.width,v.height,4)}else{const v=a(await w.arrayBuffer());return await p(v)}}static fromTensor(w,v="CHW"){if(w.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${w.dims.length} dimensions.`);if(v==="CHW")w=w.transpose(1,2,0);else if(v!=="HWC")throw new Error(`Unsupported channel format: ${v}`);if(!(w.data instanceof Uint8ClampedArray||w.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${w.type}`);switch(w.dims[2]){case 1:case 2:case 3:case 4:return new _(w.data,w.dims[1],w.dims[0],w.dims[2]);default:throw new Error(`Unsupported number of channels: ${w.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const w=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let v=0,I=0;v=0?S=I:F=-I,T>=0?O=T:H=-T,x.drawImage(E,S,O,w,v,F,H,w,v),new _(x.getImageData(0,0,w,v).data,w,v,4).convert(b)}else{let b=this.toSharp();if(I>=0&&T>=0)b=b.extract({left:Math.floor(I),top:Math.floor(T),width:w,height:v});else if(I<=0&&T<=0){const E=Math.floor(-T),x=Math.floor(-I);b=b.extend({top:E,left:x,right:w-this.width-x,bottom:v-this.height-E})}else{let E=[0,0],x=0;T<0?(E[0]=Math.floor(-T),E[1]=v-this.height-E[0]):x=Math.floor(T);let S=[0,0],O=0;I<0?(S[0]=Math.floor(-I),S[1]=w-this.width-S[0]):O=Math.floor(I),b=b.extend({top:E[0],bottom:E[1],left:S[0],right:S[1]}).extract({left:O,top:x,width:w,height:v})}return await p(b)}}async toBlob(w="image/png",v=1){if(!d)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:w,quality:v})}toTensor(w="CHW"){let v=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(w!=="HWC")if(w==="CHW")v=v.permute(2,0,1);else throw new Error(`Unsupported channel format: ${w}`);return v}toCanvas(){if(!d)throw new Error("toCanvas() is only supported in browser environments.");const w=this.clone().rgba(),v=l(w.width,w.height),I=new c(w.data,w.width,w.height);return v.getContext("2d").putImageData(I,0,0),v}split(){const{data:w,width:v,height:I,channels:T}=this,b=w.constructor,E=w.length/T,x=Array.from({length:T},()=>new b(E));for(let S=0;Snew _(S,v,I,1))}_update(w,v,I,T=null){return this.data=w,this.width=v,this.height=I,T!==null&&(this.channels=T),this}clone(){return new _(this.data.slice(),this.width,this.height,this.channels)}convert(w){if(this.channels===w)return this;switch(w){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(w){if(d){if(o.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const v=w.split(".").pop().toLowerCase(),I=f.get(v)??"image/png",T=await this.toBlob(I);(0,s.saveBlob)(w,T)}else{if(o.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(w);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(d)throw new Error("toSharp() is only supported in server-side environments.");return a(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const y=_.read.bind(_)}),"./src/utils/maths.js":((e,r,t)=>{t.r(r),t.d(r,{FFT:()=>y,bankers_round:()=>v,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>I,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>c,max:()=>d,medianFilter:()=>k,min:()=>p,permute_data:()=>n,round:()=>w,softmax:()=>o});function s(T,[b,E,x],[S,O],F="bilinear",H=!1){const W=O/x,B=S/E,Y=new T.constructor(S*O*b),X=E*x,J=S*O;for(let re=0;re=0;--H)S[H]=W,x[H]=b[E[H]],W*=x[H];const O=E.map((H,W)=>S[E.indexOf(W)]),F=new T.constructor(T.length);for(let H=0;H=0;--B)W+=Y%b[B]*O[B],Y=Math.floor(Y/b[B]);F[W]=T[H]}return[F,x]}function o(T){const b=d(T)[0],E=T.map(O=>Math.exp(O-b)),x=E.reduce((O,F)=>O+F,0);return E.map(O=>O/x)}function i(T){const b=d(T)[0];let E=0;for(let O=0;OO-b-x)}function a(T,b){let E=0;for(let x=0;xb+E*E,0))}function p(T){if(T.length===0)throw Error("Array must not be empty");let b=T[0],E=0;for(let x=1;xb&&(b=T[x],E=x);return[b,E]}function u(T){return T>0&&(T&T-1)===0}class f{constructor(b){if(this.size=b|0,this.size<=1||!u(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=b<<1,this.table=new Float64Array(this.size*2);for(let x=0;xx;x<<=1)++E;this._width=E%2===0?E-1:E,this._bitrev=new Int32Array(1<>>S&3)<>>1);for(let S=0;S>>1]=b[S];return x}toComplexArray(b,E){const x=E||this.createComplexArray();for(let S=0;S>>1],x[S+1]=0;return x}transform(b,E){if(b===E)throw new Error("Input and output buffers must be different");this._transform4(b,E,1)}realTransform(b,E){if(b===E)throw new Error("Input and output buffers must be different");this._realTransform4(b,E,1)}inverseTransform(b,E){if(b===E)throw new Error("Input and output buffers must be different");this._transform4(b,E,-1);for(let x=0;x>=2;F>=2;F>>=2){H=S/F<<1;const J=H>>>2;for(W=0;W>>1,F>>>1)}else for(W=0,B=0;W>>1,F>>>1,x)}const X=this.table;for(F>>=2;F>=2;F>>=2){H=S/F<<1;const re=H>>>1,ne=re>>>1,le=ne>>>1;for(W=0;W>>1;for(let re=2;re>1;++Y){const X=(Y+1-b)**2/2,J=Math.sqrt(W**2+B**2)**X,re=X*Math.atan2(B,W),ne=2*Y;O[ne]=J*Math.cos(re),O[ne+1]=J*Math.sin(re),F[ne]=O[ne],F[ne+1]=-O[ne+1]}this._slicedChirpBuffer=O.subarray(E,x),this._f=new f(S>>1),this._f.transform(this._chirpBuffer,F)}_transform(b,E,x){const S=this._buffer1,O=this._buffer2,F=this._outBuffer1,H=this._outBuffer2,W=this._chirpBuffer,B=this._slicedChirpBuffer,Y=this._a;if(x)for(let X=0;X>1,ne=E[re];S[X]=ne*B[X],S[J]=ne*B[J]}else for(let X=0;X=T.length&&(W=2*(T.length-1)-W),x[F++]=T[W]}x.sort(),E[O]=x[S]}return E}function w(T,b){const E=Math.pow(10,b);return Math.round(T*E)/E}function v(T){const b=Math.round(T);return Math.abs(T)%1===.5?b%2===0?b:b-1:b}function I(T){const b=T.length,E=T[0].length,x=[b+1,E+1],S=Array.from({length:x[0]},()=>Array(x[1]).fill(1/0));S[0][0]=0;const O=Array.from({length:x[0]},()=>Array(x[1]).fill(-1));for(let Y=1;Y0||H>0;)switch(W.push(F-1),B.push(H-1),O[F][H]){case 0:--F,--H;break;case 1:--F;break;case 2:--H;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${F}, ${H}]. Please file a bug report.`)}return W.reverse(),B.reverse(),[W,B]}}),"./src/utils/tensor.js":((e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>E,full:()=>B,full_like:()=>Y,interpolate:()=>p,interpolate_4d:()=>d,layer_norm:()=>v,matmul:()=>u,mean:()=>F,mean_pooling:()=>w,ones:()=>X,ones_like:()=>J,permute:()=>c,quantize_embeddings:()=>oe,rand:()=>le,randn:()=>pe,rfft:()=>f,slice:()=>k,stack:()=>x,std_mean:()=>O,topk:()=>_,zeros:()=>re,zeros_like:()=>ne});var s=t("./src/utils/maths.js"),n=t("./src/backends/onnx.js"),o=t("./src/ops/registry.js");const i=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class a{get dims(){return this.ort_tensor.dims}set dims(N){this.ort_tensor.dims=N}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...N){return(0,n.isONNXTensor)(N[0])?this.ort_tensor=N[0]:this.ort_tensor=new n.Tensor(N[0],N[1],N[2]),new Proxy(this,{get:(D,te)=>{if(typeof te=="string"){let he=Number(te);if(Number.isInteger(he))return D._getitem(he)}return D[te]},set:(D,te,he)=>D[te]=he})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[N,...D]=this.dims;if(D.length>0){const te=D.reduce((he,Ae)=>he*Ae);for(let he=0;he0){const he=te.reduce((Ae,Ie)=>Ae*Ie);return this._subarray(N,he,te)}else return new a(this.type,[this.data[N]],te)}indexOf(N){const D=this.data;for(let te=0;teve)throw new Error(`Invalid slice: ${de}`);const xe=[Math.max(be,0),Math.min(ve,this.dims[z])];te.push(xe),D.push(xe[1]-xe[0])}else throw new Error(`Invalid slice: ${de}`)}const he=te.map(([z,de])=>de-z),Ae=he.reduce((z,de)=>z*de),Ie=this.data,je=new Ie.constructor(Ae),Te=this.stride();let Q=!0;for(let z=1;z=0;--be){const xe=he[be];de+=(ve%xe+te[be][0])*Te[be],ve=Math.floor(ve/xe)}je[z]=Ie[de]}return new a(this.type,je,D)}permute(...N){return c(this,N)}transpose(...N){return this.permute(...N)}sum(N=null,D=!1){return this.norm(1,N,D)}norm(N="fro",D=null,te=!1){if(N==="fro")N=2;else if(typeof N=="string")throw Error(`Unsupported norm: ${N}`);const he=this.data,Ae=(Q,z)=>Q+z**N;if(D===null){const Q=he.reduce(Ae,0)**(1/N);return new a(this.type,[Q],[])}const[Ie,je,Te]=S(Ae,this,D,te);if(N!==1)for(let Q=0;Q=0;--Te){const de=this.dims[Te];if(Te!==D){const be=Q%de;je+=be*z,z*=this.dims[Te]}Q=Math.floor(Q/de)}he[Ie]/=Ae[je]}return this}normalize(N=2,D=1){return this.clone().normalize_(N,D)}stride(){return H(this.dims)}squeeze(N=null){return new a(this.type,this.data,I(this.dims,N))}squeeze_(N=null){return this.dims=I(this.dims,N),this}unsqueeze(N=null){return new a(this.type,this.data,T(this.dims,N))}unsqueeze_(N=null){return this.dims=T(this.dims,N),this}flatten_(N=0,D=-1){D=(D+this.dims.length)%this.dims.length;let te=this.dims.slice(0,N),he=this.dims.slice(N,D+1),Ae=this.dims.slice(D+1);return this.dims=[...te,he.reduce((Ie,je)=>Ie*je,1),...Ae],this}flatten(N=0,D=-1){return this.clone().flatten_(N,D)}view(...N){let D=-1;for(let he=0;heje!==D?Ae*Ie:Ae,1);N[D]=te.length/he}return new a(this.type,te,N)}neg_(){const N=this.data;for(let D=0;DN?1:0;return new a("bool",D,this.dims)}lt(N){const D=new Uint8Array(this.data.length),te=this.data;for(let he=0;heMath.min(Ie,je),this,N,D,1/0);return new a(te,he,Ae)}max(N=null,D=!1){if(N===null){const Ie=(0,s.max)(this.data)[0];return new a(this.type,[Ie],[])}const[te,he,Ae]=S((Ie,je)=>Math.max(Ie,je),this,N,D,-1/0);return new a(te,he,Ae)}argmin(N=null,D=!1){if(N!==null)throw new Error("`dim !== null` not yet implemented.");const te=(0,s.min)(this.data)[1];return new a("int64",[BigInt(te)],[])}argmax(N=null,D=!1){if(N!==null)throw new Error("`dim !== null` not yet implemented.");const te=(0,s.max)(this.data)[1];return new a("int64",[BigInt(te)],[])}to(N){if(this.type===N)return this;if(!i.hasOwnProperty(N))throw new Error(`Unsupported type: ${N}`);let D;const te=["int64","uint64"].includes(this.type),he=["int64","uint64"].includes(N);return te&&!he?D=Number:!te&&he&&(["float16","float32","float64"].includes(this.type)?D=Ae=>BigInt(Math.floor(Ae)):D=BigInt),new a(N,i[N].from(this.data,D),this.dims)}}function l(K,N){const D=K.length,te=N.reduce((Ae,Ie)=>Ae*Ie);if(D!==te)throw Error(`cannot reshape array of size ${D} into shape (${N})`);let he=K;for(let Ae=N.length-1;Ae>=0;Ae--)he=he.reduce((Ie,je)=>{let Te=Ie[Ie.length-1];return Te.lengthnew a("int64",K,[K.length]);async function k(K,N,D,te,he){return await(await o.TensorOpRegistry.slice)({x:K,s:y(N),e:y(D),a:y(te),t:y(he??new Array(te.length).fill(1))})}function w(K,N){const D=K.data,te=N.data,he=[K.dims[0],K.dims[2]],Ae=new D.constructor(he[0]*he[1]),[Ie,je,Te]=K.dims;let Q=0;for(let z=0;zD!==1):typeof N=="number"?K[N]===1&&K.splice(N,1):Array.isArray(N)&&(K=K.filter((D,te)=>D!==1||!N.includes(te))),K}function T(K,N){return N=b(N,K.length+1),K=K.slice(),K.splice(N,0,1),K}function b(K,N,D=null,te=!0){if(K<-N||K>=N){if(te)throw new Error(`IndexError: index ${K} is out of bounds for dimension${D===null?"":" "+D} with size ${N}`);return K<-N?0:N}return K<0&&(K=(K%N+N)%N),K}function E(K,N=0){N=b(N,K[0].dims.length);const D=K[0].dims.slice();D[N]=K.reduce((Ie,je)=>Ie+je.dims[N],0);const te=D.reduce((Ie,je)=>Ie*je,1),he=new K[0].data.constructor(te),Ae=K[0].type;if(N===0){let Ie=0;for(const je of K){const Te=je.data;he.set(Te,Ie),Ie+=Te.length}}else{let Ie=0;for(let je=0;je=0;--be){const Ce=Q[be];let ge=ve%Ce;be===N&&(ge+=Ie),de+=ge*xe,xe*=D[be],ve=Math.floor(ve/Ce)}he[de]=Te[z]}Ie+=Q[N]}}return new a(Ae,he,D)}function x(K,N=0){return E(K.map(D=>D.unsqueeze(N)),N)}function S(K,N,D=null,te=!1,he=null){const Ae=N.data,Ie=N.dims;D=b(D,Ie.length);const je=Ie.slice();je[D]=1;const Te=new Ae.constructor(Ae.length/Ie[D]);he!==null&&Te.fill(he);for(let Q=0;Q=0;--de){const xe=Ie[de];if(de!==D){const Ce=be%xe;z+=Ce*ve,ve*=je[de]}be=Math.floor(be/xe)}Te[z]=K(Te[z],Ae[Q],Q,z)}return te||je.splice(D,1),[N.type,Te,je]}function O(K,N=null,D=1,te=!1){const he=K.data,Ae=K.dims;if(N===null){const ve=he.reduce((De,fe)=>De+fe,0)/he.length,xe=Math.sqrt(he.reduce((De,fe)=>De+(fe-ve)**2,0)/(he.length-D)),Ce=new a(K.type,[ve],[]);return[new a(K.type,[xe],[]),Ce]}N=b(N,Ae.length);const Ie=F(K,N,te),je=Ie.data,[Te,Q,z]=S((be,ve,xe,Ce)=>be+(ve-je[Ce])**2,K,N,te);for(let be=0;beQ+z,0);return new a(K.type,[Te/he.length],[])}N=b(N,te.length);const[Ae,Ie,je]=S((Te,Q)=>Te+Q,K,N,D);if(te[N]!==1)for(let Te=0;Te=0;--D)N[D]=te,te*=K[D];return N}function W(K,N,D,te){const he=K.reduce((Ae,Ie)=>Ae*Ie,1);return new a(D,new te(he).fill(N),K)}function B(K,N){let D,te;if(typeof N=="number")D="float32",te=Float32Array;else if(typeof N=="bigint")D="int64",te=BigInt64Array;else if(typeof N=="boolean")D="bool",te=Uint8Array;else throw new Error(`Unsupported data type: ${typeof N}`);return W(K,N,D,te)}function Y(K,N){return B(K.dims,N)}function X(K){return W(K,1n,"int64",BigInt64Array)}function J(K){return X(K.dims)}function re(K){return W(K,0n,"int64",BigInt64Array)}function ne(K){return re(K.dims)}function le(K){const N=K.reduce((D,te)=>D*te,1);return new a("float32",Float32Array.from({length:N},()=>Math.random()),K)}function pe(K){const N=K.reduce((te,he)=>te*he,1);function D(){const te=1-Math.random(),he=1-Math.random();return Math.sqrt(-2*Math.log(te))*Math.cos(2*Math.PI*he)}return new a("float32",Float32Array.from({length:N},()=>D()),K)}function oe(K,N){if(K.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(K.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(N))throw new Error("The precision must be either 'binary' or 'ubinary'");const D=N==="binary",te=D?"int8":"uint8",he=D?Int8Array:Uint8Array,Ae=K.data,Ie=new he(Ae.length/8);for(let je=0;je0?1:0,Q=Math.floor(je/8),z=je%8;Ie[Q]|=Te<<7-z,D&&z===0&&(Ie[Q]-=128)}return new a(te,Ie,[K.dims[0],K.dims[1]/8])}}),"./src/utils/video.js":((e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>i,RawVideoFrame:()=>o,load_video:()=>a});var s=t("./src/utils/image.js"),n=t("./src/env.js");class o{constructor(c,p){this.image=c,this.timestamp=p}}class i{constructor(c,p){c.length>0&&c[0]instanceof s.RawImage&&(c=c.map((d,u)=>new o(d,(u+1)/(c.length+1)*p))),this.frames=c,this.duration=p}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function a(l,{num_frames:c=null,fps:p=null}={}){if(!n.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(c==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const d=[],u=document.createElement("video");if(u.crossOrigin="anonymous",u.muted=!0,typeof l=="string")u.src=l;else if(l instanceof Blob)u.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)u.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(I=>u.onloadedmetadata=I),u.seekable.start(0)===u.seekable.end(0)){const T=await(await fetch(u.src)).blob();u.src=URL.createObjectURL(T),await new Promise(b=>u.onloadedmetadata=b)}const f=u.duration;let _,y;c!=null?(_=c,y=c===1?0:f/(c-1)):(y=1/p,_=Math.floor(f/y));let k=[];for(let I=0;I<_;++I)k.push(c===1?f/2:I*y);const w=document.createElement("canvas");w.width=u.videoWidth,w.height=u.videoHeight;const v=w.getContext("2d",{willReadFrequently:!0});for(const I of k){u.currentTime=I,await new Promise(x=>{u.onseeked=x}),v.drawImage(u,0,0,w.width,w.height);const T=v.getImageData(0,0,w.width,w.height),b=new s.RawImage(T.data,w.width,w.height,4),E=new o(b,I);d.push(E)}return u.remove(),new i(d,f)}})},Fw={};function Nt(e){var r=Fw[e];if(r!==void 0)return r.exports;var t=Fw[e]={exports:{}};return i1[e](t,t.exports,Nt),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;Nt.t=function(t,s){if(s&1&&(t=this(t)),s&8||typeof t=="object"&&t&&(s&4&&t.__esModule||s&16&&typeof t.then=="function"))return t;var n=Object.create(null);Nt.r(n);var o={};r=r||[null,e({}),e([]),e(e)];for(var i=s&2&&t;typeof i=="object"&&!~r.indexOf(i);i=e(i))Object.getOwnPropertyNames(i).forEach(a=>o[a]=()=>t[a]);return o.default=()=>t,Nt.d(n,o),n}})();Nt.d=(e,r)=>{for(var t in r)Nt.o(r,t)&&!Nt.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})};Nt.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);Nt.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var m={};(()=>{Nt.r(m),Nt.d(m,{ASTFeatureExtractor:()=>d.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,ArceeForCausalLM:()=>t.ArceeForCausalLM,ArceeModel:()=>t.ArceeModel,ArceePreTrainedModel:()=>t.ArceePreTrainedModel,AudioClassificationPipeline:()=>r.AudioClassificationPipeline,AutoConfig:()=>n.AutoConfig,AutoFeatureExtractor:()=>u.AutoFeatureExtractor,AutoImageProcessor:()=>y.AutoImageProcessor,AutoModel:()=>t.AutoModel,AutoModelForAudioClassification:()=>t.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>t.AutoModelForAudioFrameClassification,AutoModelForAudioTextToText:()=>t.AutoModelForAudioTextToText,AutoModelForCTC:()=>t.AutoModelForCTC,AutoModelForCausalLM:()=>t.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>t.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>t.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>t.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>t.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>t.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>t.AutoModelForImageSegmentation,AutoModelForImageTextToText:()=>t.AutoModelForImageTextToText,AutoModelForImageToImage:()=>t.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>t.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>t.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>t.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>t.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>t.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>t.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>t.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>t.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>t.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>t.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>t.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>t.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>t.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>t.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>t.AutoModelForVision2Seq,AutoModelForXVector:()=>t.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>t.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>v.AutoProcessor,AutoTokenizer:()=>s.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>r.AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline:()=>r.BackgroundRemovalPipeline,BartForConditionalGeneration:()=>t.BartForConditionalGeneration,BartForSequenceClassification:()=>t.BartForSequenceClassification,BartModel:()=>t.BartModel,BartPretrainedModel:()=>t.BartPretrainedModel,BartTokenizer:()=>s.BartTokenizer,BaseModelOutput:()=>t.BaseModelOutput,BaseStreamer:()=>I.BaseStreamer,BeitFeatureExtractor:()=>_.BeitFeatureExtractor,BeitForImageClassification:()=>t.BeitForImageClassification,BeitModel:()=>t.BeitModel,BeitPreTrainedModel:()=>t.BeitPreTrainedModel,BertForMaskedLM:()=>t.BertForMaskedLM,BertForQuestionAnswering:()=>t.BertForQuestionAnswering,BertForSequenceClassification:()=>t.BertForSequenceClassification,BertForTokenClassification:()=>t.BertForTokenClassification,BertModel:()=>t.BertModel,BertPreTrainedModel:()=>t.BertPreTrainedModel,BertTokenizer:()=>s.BertTokenizer,BitImageProcessor:()=>_.BitImageProcessor,BlenderbotForConditionalGeneration:()=>t.BlenderbotForConditionalGeneration,BlenderbotModel:()=>t.BlenderbotModel,BlenderbotPreTrainedModel:()=>t.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>t.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>t.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>t.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>s.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>s.BlenderbotTokenizer,BloomForCausalLM:()=>t.BloomForCausalLM,BloomModel:()=>t.BloomModel,BloomPreTrainedModel:()=>t.BloomPreTrainedModel,BloomTokenizer:()=>s.BloomTokenizer,CLIPFeatureExtractor:()=>_.CLIPFeatureExtractor,CLIPImageProcessor:()=>_.CLIPImageProcessor,CLIPModel:()=>t.CLIPModel,CLIPPreTrainedModel:()=>t.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>t.CLIPSegForImageSegmentation,CLIPSegModel:()=>t.CLIPSegModel,CLIPSegPreTrainedModel:()=>t.CLIPSegPreTrainedModel,CLIPTextModel:()=>t.CLIPTextModel,CLIPTextModelWithProjection:()=>t.CLIPTextModelWithProjection,CLIPTokenizer:()=>s.CLIPTokenizer,CLIPVisionModel:()=>t.CLIPVisionModel,CLIPVisionModelWithProjection:()=>t.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>t.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>t.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>t.CamembertForSequenceClassification,CamembertForTokenClassification:()=>t.CamembertForTokenClassification,CamembertModel:()=>t.CamembertModel,CamembertPreTrainedModel:()=>t.CamembertPreTrainedModel,CamembertTokenizer:()=>s.CamembertTokenizer,CausalLMOutput:()=>t.CausalLMOutput,CausalLMOutputWithPast:()=>t.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>_.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>d.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>b.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>s.CodeGenTokenizer,CodeLlamaTokenizer:()=>s.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>s.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>s.ConvBertTokenizer,ConvNextFeatureExtractor:()=>_.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>_.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DFineForObjectDetection:()=>t.DFineForObjectDetection,DFineModel:()=>t.DFineModel,DFinePreTrainedModel:()=>t.DFinePreTrainedModel,DINOv3ConvNextModel:()=>t.DINOv3ConvNextModel,DINOv3ConvNextPreTrainedModel:()=>t.DINOv3ConvNextPreTrainedModel,DINOv3ViTImageProcessor:()=>_.DINOv3ViTImageProcessor,DINOv3ViTModel:()=>t.DINOv3ViTModel,DINOv3ViTPreTrainedModel:()=>t.DINOv3ViTPreTrainedModel,DPTFeatureExtractor:()=>_.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>_.DPTImageProcessor,DPTModel:()=>t.DPTModel,DPTPreTrainedModel:()=>t.DPTPreTrainedModel,DacDecoderModel:()=>t.DacDecoderModel,DacDecoderOutput:()=>t.DacDecoderOutput,DacEncoderModel:()=>t.DacEncoderModel,DacEncoderOutput:()=>t.DacEncoderOutput,DacFeatureExtractor:()=>d.DacFeatureExtractor,DacModel:()=>t.DacModel,DacPreTrainedModel:()=>t.DacPreTrainedModel,DataTypeMap:()=>l.DataTypeMap,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>s.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>s.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>_.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>_.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>r.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>_.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>_.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>s.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>r.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>_.DonutFeatureExtractor,DonutImageProcessor:()=>_.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EdgeTamModel:()=>t.EdgeTamModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>_.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>s.ElectraTokenizer,EncodecFeatureExtractor:()=>d.EncodecFeatureExtractor,EosTokenCriteria:()=>T.EosTokenCriteria,Ernie4_5ForCausalLM:()=>t.Ernie4_5ForCausalLM,Ernie4_5Model:()=>t.Ernie4_5Model,Ernie4_5PreTrainedModel:()=>t.Ernie4_5PreTrainedModel,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>s.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>c.FFT,FalconForCausalLM:()=>t.FalconForCausalLM,FalconModel:()=>t.FalconModel,FalconPreTrainedModel:()=>t.FalconPreTrainedModel,FalconTokenizer:()=>s.FalconTokenizer,FastViTForImageClassification:()=>t.FastViTForImageClassification,FastViTModel:()=>t.FastViTModel,FastViTPreTrainedModel:()=>t.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>r.FeatureExtractionPipeline,FeatureExtractor:()=>p.FeatureExtractor,FillMaskPipeline:()=>r.FillMaskPipeline,Florence2ForConditionalGeneration:()=>t.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>t.Florence2PreTrainedModel,Florence2Processor:()=>w.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>b.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>b.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>t.GLPNForDepthEstimation,GLPNModel:()=>t.GLPNModel,GLPNPreTrainedModel:()=>t.GLPNPreTrainedModel,GPT2LMHeadModel:()=>t.GPT2LMHeadModel,GPT2Model:()=>t.GPT2Model,GPT2PreTrainedModel:()=>t.GPT2PreTrainedModel,GPT2Tokenizer:()=>s.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>t.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>t.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>t.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>t.GPTJForCausalLM,GPTJModel:()=>t.GPTJModel,GPTJPreTrainedModel:()=>t.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>t.GPTNeoForCausalLM,GPTNeoModel:()=>t.GPTNeoModel,GPTNeoPreTrainedModel:()=>t.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>t.GPTNeoXForCausalLM,GPTNeoXModel:()=>t.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>t.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>s.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>t.Gemma2ForCausalLM,Gemma2Model:()=>t.Gemma2Model,Gemma2PreTrainedModel:()=>t.Gemma2PreTrainedModel,Gemma3ForCausalLM:()=>t.Gemma3ForCausalLM,Gemma3Model:()=>t.Gemma3Model,Gemma3PreTrainedModel:()=>t.Gemma3PreTrainedModel,Gemma3nAudioFeatureExtractor:()=>d.Gemma3nAudioFeatureExtractor,Gemma3nForConditionalGeneration:()=>t.Gemma3nForConditionalGeneration,Gemma3nPreTrainedModel:()=>t.Gemma3nPreTrainedModel,Gemma3nProcessor:()=>w.Gemma3nProcessor,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>s.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GraniteMoeHybridForCausalLM:()=>t.GraniteMoeHybridForCausalLM,GraniteMoeHybridModel:()=>t.GraniteMoeHybridModel,GraniteMoeHybridPreTrainedModel:()=>t.GraniteMoeHybridPreTrainedModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>w.GroundingDinoProcessor,GroupViTModel:()=>t.GroupViTModel,GroupViTPreTrainedModel:()=>t.GroupViTPreTrainedModel,HeliumForCausalLM:()=>t.HeliumForCausalLM,HeliumModel:()=>t.HeliumModel,HeliumPreTrainedModel:()=>t.HeliumPreTrainedModel,HerbertTokenizer:()=>s.HerbertTokenizer,HieraForImageClassification:()=>t.HieraForImageClassification,HieraModel:()=>t.HieraModel,HieraPreTrainedModel:()=>t.HieraPreTrainedModel,HubertForCTC:()=>t.HubertForCTC,HubertForSequenceClassification:()=>t.HubertForSequenceClassification,HubertModel:()=>t.HubertModel,HubertPreTrainedModel:()=>t.HubertPreTrainedModel,IJepaForImageClassification:()=>t.IJepaForImageClassification,IJepaModel:()=>t.IJepaModel,IJepaPreTrainedModel:()=>t.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>t.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>_.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>w.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>d.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>f.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>T.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>_.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>w.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,Lfm2ForCausalLM:()=>t.Lfm2ForCausalLM,Lfm2Model:()=>t.Lfm2Model,Lfm2PreTrainedModel:()=>t.Lfm2PreTrainedModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,Llama4ForCausalLM:()=>t.Llama4ForCausalLM,Llama4PreTrainedModel:()=>t.Llama4PreTrainedModel,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>_.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LlavaProcessor:()=>w.LlavaProcessor,LlavaQwen2ForCausalLM:()=>t.LlavaQwen2ForCausalLM,LogitsProcessor:()=>b.LogitsProcessor,LogitsProcessorList:()=>b.LogitsProcessorList,LogitsWarper:()=>b.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,Mask2FormerImageProcessor:()=>_.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>_.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>_.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>T.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>w.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>b.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>b.MinNewTokensLengthLogitsProcessor,Ministral3ForCausalLM:()=>t.Ministral3ForCausalLM,Ministral3Model:()=>t.Ministral3Model,Ministral3PreTrainedModel:()=>t.Ministral3PreTrainedModel,MinistralForCausalLM:()=>t.MinistralForCausalLM,MinistralModel:()=>t.MinistralModel,MinistralPreTrainedModel:()=>t.MinistralPreTrainedModel,Mistral3ForConditionalGeneration:()=>t.Mistral3ForConditionalGeneration,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>_.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>_.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>_.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>_.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>_.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>_.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>_.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>_.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>_.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>_.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertDecoderForCausalLM:()=>t.ModernBertDecoderForCausalLM,ModernBertDecoderModel:()=>t.ModernBertDecoderModel,ModernBertDecoderPreTrainedModel:()=>t.ModernBertDecoderPreTrainedModel,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>d.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>w.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NanoChatForCausalLM:()=>t.NanoChatForCausalLM,NanoChatModel:()=>t.NanoChatModel,NanoChatPreTrainedModel:()=>t.NanoChatPreTrainedModel,NeoBertForMaskedLM:()=>t.NeoBertForMaskedLM,NeoBertForQuestionAnswering:()=>t.NeoBertForQuestionAnswering,NeoBertForSequenceClassification:()=>t.NeoBertForSequenceClassification,NeoBertForTokenClassification:()=>t.NeoBertForTokenClassification,NeoBertModel:()=>t.NeoBertModel,NeoBertPreTrainedModel:()=>t.NeoBertPreTrainedModel,NllbTokenizer:()=>s.NllbTokenizer,NoBadWordsLogitsProcessor:()=>b.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>b.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>_.NougatImageProcessor,NougatTokenizer:()=>s.NougatTokenizer,OPTForCausalLM:()=>t.OPTForCausalLM,OPTModel:()=>t.OPTModel,OPTPreTrainedModel:()=>t.OPTPreTrainedModel,ObjectDetectionPipeline:()=>r.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>t.Olmo2ForCausalLM,Olmo2Model:()=>t.Olmo2Model,Olmo2PreTrainedModel:()=>t.Olmo2PreTrainedModel,OlmoForCausalLM:()=>t.OlmoForCausalLM,OlmoModel:()=>t.OlmoModel,OlmoPreTrainedModel:()=>t.OlmoPreTrainedModel,OpenELMForCausalLM:()=>t.OpenELMForCausalLM,OpenELMModel:()=>t.OpenELMModel,OpenELMPreTrainedModel:()=>t.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>_.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>_.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>w.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>_.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>w.PaliGemmaProcessor,ParakeetFeatureExtractor:()=>d.ParakeetFeatureExtractor,ParakeetForCTC:()=>t.ParakeetForCTC,ParakeetPreTrainedModel:()=>t.ParakeetPreTrainedModel,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>_.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>w.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PixtralImageProcessor:()=>_.PixtralImageProcessor,PixtralProcessor:()=>w.PixtralProcessor,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>n.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>k.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>_.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>d.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>w.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>t.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>r.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>t.Qwen2ForCausalLM,Qwen2Model:()=>t.Qwen2Model,Qwen2PreTrainedModel:()=>t.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>s.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>t.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>_.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>w.Qwen2VLProcessor,Qwen3ForCausalLM:()=>t.Qwen3ForCausalLM,Qwen3Model:()=>t.Qwen3Model,Qwen3PreTrainedModel:()=>t.Qwen3PreTrainedModel,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>_.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>o.RawAudio,RawImage:()=>i.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>b.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>s.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>s.RobertaTokenizer,Sam2ImageProcessor:()=>_.Sam2ImageProcessor,Sam2ImageSegmentationOutput:()=>t.Sam2ImageSegmentationOutput,Sam2Model:()=>t.Sam2Model,Sam2PreTrainedModel:()=>t.Sam2PreTrainedModel,Sam2Processor:()=>w.Sam2Processor,Sam2VideoProcessor:()=>w.Sam2VideoProcessor,Sam3ImageProcessor:()=>_.Sam3ImageProcessor,Sam3TrackerModel:()=>t.Sam3TrackerModel,SamImageProcessor:()=>_.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>w.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>_.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>_.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>_.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>s.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SmolLM3ForCausalLM:()=>t.SmolLM3ForCausalLM,SmolLM3Model:()=>t.SmolLM3Model,SmolLM3PreTrainedModel:()=>t.SmolLM3PreTrainedModel,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>_.SmolVLMImageProcessor,SmolVLMProcessor:()=>w.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>d.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>w.SpeechT5Processor,SpeechT5Tokenizer:()=>s.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>s.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>T.StoppingCriteria,StoppingCriteriaList:()=>T.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SupertonicForConditionalGeneration:()=>t.SupertonicForConditionalGeneration,SupertonicPreTrainedModel:()=>t.SupertonicPreTrainedModel,SuppressTokensAtBeginLogitsProcessor:()=>b.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>_.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinForSemanticSegmentation:()=>t.SwinForSemanticSegmentation,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>s.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>b.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>I.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>b.TopKLogitsWarper,TopPLogitsWarper:()=>b.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>w.UltravoxProcessor,UniSpeechForCTC:()=>t.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>t.UniSpeechForSequenceClassification,UniSpeechModel:()=>t.UniSpeechModel,UniSpeechPreTrainedModel:()=>t.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>t.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>t.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>t.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>t.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>t.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>w.VLChatProcessor,VLMImageProcessor:()=>_.VLMImageProcessor,VaultGemmaForCausalLM:()=>t.VaultGemmaForCausalLM,VaultGemmaModel:()=>t.VaultGemmaModel,VaultGemmaPreTrainedModel:()=>t.VaultGemmaPreTrainedModel,ViTFeatureExtractor:()=>_.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>_.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>_.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>_.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,VoxtralForConditionalGeneration:()=>t.VoxtralForConditionalGeneration,VoxtralProcessor:()=>w.VoxtralProcessor,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>s.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>d.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>w.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>w.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>d.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>d.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>w.WhisperProcessor,WhisperTextStreamer:()=>I.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>b.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>s.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>s.XLMRobertaTokenizer,XLMTokenizer:()=>s.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>_.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>_.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>r.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>r.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>r.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>r.ZeroShotObjectDetectionPipeline,bankers_round:()=>c.bankers_round,cat:()=>l.cat,cos_sim:()=>c.cos_sim,dot:()=>c.dot,dynamic_time_warping:()=>c.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getCacheShapes:()=>n.getCacheShapes,hamming:()=>o.hamming,hanning:()=>o.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>c.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>i.load_image,load_video:()=>a.load_video,log_softmax:()=>c.log_softmax,magnitude:()=>c.magnitude,matmul:()=>l.matmul,max:()=>c.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>c.medianFilter,mel_filter_bank:()=>o.mel_filter_bank,min:()=>c.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>c.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,randn:()=>l.randn,read_audio:()=>o.read_audio,rfft:()=>l.rfft,round:()=>c.round,slice:()=>l.slice,softmax:()=>c.softmax,spectrogram:()=>o.spectrogram,stack:()=>l.stack,std_mean:()=>l.std_mean,topk:()=>l.topk,window_function:()=>o.window_function,zeros:()=>l.zeros,zeros_like:()=>l.zeros_like});var e=Nt("./src/env.js"),r=Nt("./src/pipelines.js"),t=Nt("./src/models.js"),s=Nt("./src/tokenizers.js"),n=Nt("./src/configs.js"),o=Nt("./src/utils/audio.js"),i=Nt("./src/utils/image.js"),a=Nt("./src/utils/video.js"),l=Nt("./src/utils/tensor.js"),c=Nt("./src/utils/maths.js"),p=Nt("./src/base/feature_extraction_utils.js"),d=Nt("./src/models/feature_extractors.js"),u=Nt("./src/models/auto/feature_extraction_auto.js"),f=Nt("./src/base/image_processors_utils.js"),_=Nt("./src/models/image_processors.js"),y=Nt("./src/models/auto/image_processing_auto.js"),k=Nt("./src/base/processing_utils.js"),w=Nt("./src/models/processors.js"),v=Nt("./src/models/auto/processing_auto.js"),I=Nt("./src/generation/streamers.js"),T=Nt("./src/generation/stopping_criteria.js"),b=Nt("./src/generation/logits_process.js")})();m.ASTFeatureExtractor;m.ASTForAudioClassification;m.ASTModel;m.ASTPreTrainedModel;m.AlbertForMaskedLM;m.AlbertForQuestionAnswering;m.AlbertForSequenceClassification;m.AlbertModel;m.AlbertPreTrainedModel;m.AlbertTokenizer;m.ArceeForCausalLM;m.ArceeModel;m.ArceePreTrainedModel;m.AudioClassificationPipeline;m.AutoConfig;m.AutoFeatureExtractor;m.AutoImageProcessor;m.AutoModel;m.AutoModelForAudioClassification;m.AutoModelForAudioFrameClassification;m.AutoModelForAudioTextToText;m.AutoModelForCTC;m.AutoModelForCausalLM;m.AutoModelForDepthEstimation;m.AutoModelForDocumentQuestionAnswering;m.AutoModelForImageClassification;m.AutoModelForImageFeatureExtraction;m.AutoModelForImageMatting;m.AutoModelForImageSegmentation;m.AutoModelForImageTextToText;m.AutoModelForImageToImage;m.AutoModelForMaskGeneration;m.AutoModelForMaskedLM;m.AutoModelForNormalEstimation;m.AutoModelForObjectDetection;m.AutoModelForPoseEstimation;m.AutoModelForQuestionAnswering;m.AutoModelForSemanticSegmentation;m.AutoModelForSeq2SeqLM;m.AutoModelForSequenceClassification;m.AutoModelForSpeechSeq2Seq;m.AutoModelForTextToSpectrogram;m.AutoModelForTextToWaveform;m.AutoModelForTokenClassification;m.AutoModelForUniversalSegmentation;m.AutoModelForVision2Seq;m.AutoModelForXVector;m.AutoModelForZeroShotObjectDetection;m.AutoProcessor;m.AutoTokenizer;m.AutomaticSpeechRecognitionPipeline;m.BackgroundRemovalPipeline;m.BartForConditionalGeneration;m.BartForSequenceClassification;m.BartModel;m.BartPretrainedModel;m.BartTokenizer;m.BaseModelOutput;m.BaseStreamer;m.BeitFeatureExtractor;m.BeitForImageClassification;m.BeitModel;m.BeitPreTrainedModel;m.BertForMaskedLM;m.BertForQuestionAnswering;m.BertForSequenceClassification;m.BertForTokenClassification;m.BertModel;m.BertPreTrainedModel;m.BertTokenizer;m.BitImageProcessor;m.BlenderbotForConditionalGeneration;m.BlenderbotModel;m.BlenderbotPreTrainedModel;m.BlenderbotSmallForConditionalGeneration;m.BlenderbotSmallModel;m.BlenderbotSmallPreTrainedModel;m.BlenderbotSmallTokenizer;m.BlenderbotTokenizer;m.BloomForCausalLM;m.BloomModel;m.BloomPreTrainedModel;m.BloomTokenizer;m.CLIPFeatureExtractor;m.CLIPImageProcessor;m.CLIPModel;m.CLIPPreTrainedModel;m.CLIPSegForImageSegmentation;m.CLIPSegModel;m.CLIPSegPreTrainedModel;m.CLIPTextModel;m.CLIPTextModelWithProjection;m.CLIPTokenizer;m.CLIPVisionModel;m.CLIPVisionModelWithProjection;m.CamembertForMaskedLM;m.CamembertForQuestionAnswering;m.CamembertForSequenceClassification;m.CamembertForTokenClassification;m.CamembertModel;m.CamembertPreTrainedModel;m.CamembertTokenizer;m.CausalLMOutput;m.CausalLMOutputWithPast;m.ChineseCLIPFeatureExtractor;m.ChineseCLIPModel;m.ChineseCLIPPreTrainedModel;m.ClapAudioModelWithProjection;m.ClapFeatureExtractor;m.ClapModel;m.ClapPreTrainedModel;m.ClapTextModelWithProjection;m.ClassifierFreeGuidanceLogitsProcessor;m.CodeGenForCausalLM;m.CodeGenModel;m.CodeGenPreTrainedModel;m.CodeGenTokenizer;m.CodeLlamaTokenizer;m.CohereForCausalLM;m.CohereModel;m.CoherePreTrainedModel;m.CohereTokenizer;m.ConvBertForMaskedLM;m.ConvBertForQuestionAnswering;m.ConvBertForSequenceClassification;m.ConvBertForTokenClassification;m.ConvBertModel;m.ConvBertPreTrainedModel;m.ConvBertTokenizer;m.ConvNextFeatureExtractor;m.ConvNextForImageClassification;m.ConvNextImageProcessor;m.ConvNextModel;m.ConvNextPreTrainedModel;m.ConvNextV2ForImageClassification;m.ConvNextV2Model;m.ConvNextV2PreTrainedModel;m.DFineForObjectDetection;m.DFineModel;m.DFinePreTrainedModel;m.DINOv3ConvNextModel;m.DINOv3ConvNextPreTrainedModel;m.DINOv3ViTImageProcessor;m.DINOv3ViTModel;m.DINOv3ViTPreTrainedModel;m.DPTFeatureExtractor;m.DPTForDepthEstimation;m.DPTImageProcessor;m.DPTModel;m.DPTPreTrainedModel;m.DacDecoderModel;m.DacDecoderOutput;m.DacEncoderModel;m.DacEncoderOutput;m.DacFeatureExtractor;m.DacModel;m.DacPreTrainedModel;m.DataTypeMap;m.DebertaForMaskedLM;m.DebertaForQuestionAnswering;m.DebertaForSequenceClassification;m.DebertaForTokenClassification;m.DebertaModel;m.DebertaPreTrainedModel;m.DebertaTokenizer;m.DebertaV2ForMaskedLM;m.DebertaV2ForQuestionAnswering;m.DebertaV2ForSequenceClassification;m.DebertaV2ForTokenClassification;m.DebertaV2Model;m.DebertaV2PreTrainedModel;m.DebertaV2Tokenizer;m.DecisionTransformerModel;m.DecisionTransformerPreTrainedModel;m.DeiTFeatureExtractor;m.DeiTForImageClassification;m.DeiTImageProcessor;m.DeiTModel;m.DeiTPreTrainedModel;m.DepthAnythingForDepthEstimation;m.DepthAnythingPreTrainedModel;m.DepthEstimationPipeline;m.DepthProForDepthEstimation;m.DepthProPreTrainedModel;m.DetrFeatureExtractor;m.DetrForObjectDetection;m.DetrForSegmentation;m.DetrImageProcessor;m.DetrModel;m.DetrObjectDetectionOutput;m.DetrPreTrainedModel;m.DetrSegmentationOutput;m.Dinov2ForImageClassification;m.Dinov2Model;m.Dinov2PreTrainedModel;m.Dinov2WithRegistersForImageClassification;m.Dinov2WithRegistersModel;m.Dinov2WithRegistersPreTrainedModel;m.DistilBertForMaskedLM;m.DistilBertForQuestionAnswering;m.DistilBertForSequenceClassification;m.DistilBertForTokenClassification;m.DistilBertModel;m.DistilBertPreTrainedModel;m.DistilBertTokenizer;m.DocumentQuestionAnsweringPipeline;m.DonutFeatureExtractor;m.DonutImageProcessor;m.DonutSwinModel;m.DonutSwinPreTrainedModel;m.EdgeTamModel;m.EfficientNetForImageClassification;m.EfficientNetImageProcessor;m.EfficientNetModel;m.EfficientNetPreTrainedModel;m.ElectraForMaskedLM;m.ElectraForQuestionAnswering;m.ElectraForSequenceClassification;m.ElectraForTokenClassification;m.ElectraModel;m.ElectraPreTrainedModel;m.ElectraTokenizer;m.EncodecFeatureExtractor;m.EosTokenCriteria;m.Ernie4_5ForCausalLM;m.Ernie4_5Model;m.Ernie4_5PreTrainedModel;m.EsmForMaskedLM;m.EsmForSequenceClassification;m.EsmForTokenClassification;m.EsmModel;m.EsmPreTrainedModel;m.EsmTokenizer;m.ExaoneForCausalLM;m.ExaoneModel;m.ExaonePreTrainedModel;m.FFT;m.FalconForCausalLM;m.FalconModel;m.FalconPreTrainedModel;m.FalconTokenizer;m.FastViTForImageClassification;m.FastViTModel;m.FastViTPreTrainedModel;m.FeatureExtractionPipeline;m.FeatureExtractor;m.FillMaskPipeline;m.Florence2ForConditionalGeneration;m.Florence2PreTrainedModel;m.Florence2Processor;m.ForcedBOSTokenLogitsProcessor;m.ForcedEOSTokenLogitsProcessor;m.GLPNFeatureExtractor;m.GLPNForDepthEstimation;m.GLPNModel;m.GLPNPreTrainedModel;m.GPT2LMHeadModel;m.GPT2Model;m.GPT2PreTrainedModel;m.GPT2Tokenizer;m.GPTBigCodeForCausalLM;m.GPTBigCodeModel;m.GPTBigCodePreTrainedModel;m.GPTJForCausalLM;m.GPTJModel;m.GPTJPreTrainedModel;m.GPTNeoForCausalLM;m.GPTNeoModel;m.GPTNeoPreTrainedModel;m.GPTNeoXForCausalLM;m.GPTNeoXModel;m.GPTNeoXPreTrainedModel;m.GPTNeoXTokenizer;m.Gemma2ForCausalLM;m.Gemma2Model;m.Gemma2PreTrainedModel;m.Gemma3ForCausalLM;m.Gemma3Model;m.Gemma3PreTrainedModel;m.Gemma3nAudioFeatureExtractor;m.Gemma3nForConditionalGeneration;m.Gemma3nPreTrainedModel;m.Gemma3nProcessor;m.GemmaForCausalLM;m.GemmaModel;m.GemmaPreTrainedModel;m.GemmaTokenizer;m.GlmForCausalLM;m.GlmModel;m.GlmPreTrainedModel;m.GraniteForCausalLM;m.GraniteModel;m.GraniteMoeHybridForCausalLM;m.GraniteMoeHybridModel;m.GraniteMoeHybridPreTrainedModel;m.GranitePreTrainedModel;m.Grok1Tokenizer;m.GroundingDinoForObjectDetection;m.GroundingDinoImageProcessor;m.GroundingDinoPreTrainedModel;m.GroundingDinoProcessor;m.GroupViTModel;m.GroupViTPreTrainedModel;m.HeliumForCausalLM;m.HeliumModel;m.HeliumPreTrainedModel;m.HerbertTokenizer;m.HieraForImageClassification;m.HieraModel;m.HieraPreTrainedModel;m.HubertForCTC;m.HubertForSequenceClassification;m.HubertModel;m.HubertPreTrainedModel;m.IJepaForImageClassification;m.IJepaModel;m.IJepaPreTrainedModel;m.Idefics3ForConditionalGeneration;m.Idefics3ImageProcessor;m.Idefics3PreTrainedModel;m.Idefics3Processor;m.ImageClassificationPipeline;m.ImageFeatureExtractionPipeline;m.ImageFeatureExtractor;m.ImageMattingOutput;m.ImageProcessor;m.ImageSegmentationPipeline;m.ImageToImagePipeline;m.ImageToTextPipeline;m.InterruptableStoppingCriteria;m.JAISLMHeadModel;m.JAISModel;m.JAISPreTrainedModel;m.JinaCLIPImageProcessor;m.JinaCLIPModel;m.JinaCLIPPreTrainedModel;m.JinaCLIPProcessor;m.JinaCLIPTextModel;m.JinaCLIPVisionModel;m.Lfm2ForCausalLM;m.Lfm2Model;m.Lfm2PreTrainedModel;m.LiteWhisperForConditionalGeneration;m.Llama4ForCausalLM;m.Llama4PreTrainedModel;m.LlamaForCausalLM;m.LlamaModel;m.LlamaPreTrainedModel;m.LlamaTokenizer;m.LlavaForConditionalGeneration;m.LlavaOnevisionForConditionalGeneration;m.LlavaOnevisionImageProcessor;m.LlavaPreTrainedModel;m.LlavaProcessor;m.LlavaQwen2ForCausalLM;m.LogitsProcessor;m.LogitsProcessorList;m.LogitsWarper;m.LongT5ForConditionalGeneration;m.LongT5Model;m.LongT5PreTrainedModel;m.M2M100ForConditionalGeneration;m.M2M100Model;m.M2M100PreTrainedModel;m.M2M100Tokenizer;m.MBart50Tokenizer;m.MBartForCausalLM;m.MBartForConditionalGeneration;m.MBartForSequenceClassification;m.MBartModel;m.MBartPreTrainedModel;m.MBartTokenizer;m.MPNetForMaskedLM;m.MPNetForQuestionAnswering;m.MPNetForSequenceClassification;m.MPNetForTokenClassification;m.MPNetModel;m.MPNetPreTrainedModel;m.MPNetTokenizer;m.MT5ForConditionalGeneration;m.MT5Model;m.MT5PreTrainedModel;m.MarianMTModel;m.MarianModel;m.MarianPreTrainedModel;m.MarianTokenizer;m.Mask2FormerImageProcessor;m.MaskFormerFeatureExtractor;m.MaskFormerForInstanceSegmentation;m.MaskFormerImageProcessor;m.MaskFormerModel;m.MaskFormerPreTrainedModel;m.MaskedLMOutput;m.MaxLengthCriteria;m.Metric3DForDepthEstimation;m.Metric3DPreTrainedModel;m.Metric3Dv2ForDepthEstimation;m.Metric3Dv2PreTrainedModel;m.MgpstrForSceneTextRecognition;m.MgpstrModelOutput;m.MgpstrPreTrainedModel;m.MgpstrProcessor;m.MgpstrTokenizer;m.MimiDecoderModel;m.MimiDecoderOutput;m.MimiEncoderModel;m.MimiEncoderOutput;m.MimiModel;m.MimiPreTrainedModel;m.MinLengthLogitsProcessor;m.MinNewTokensLengthLogitsProcessor;m.Ministral3ForCausalLM;m.Ministral3Model;m.Ministral3PreTrainedModel;m.MinistralForCausalLM;m.MinistralModel;m.MinistralPreTrainedModel;m.Mistral3ForConditionalGeneration;m.MistralForCausalLM;m.MistralModel;m.MistralPreTrainedModel;m.MobileBertForMaskedLM;m.MobileBertForQuestionAnswering;m.MobileBertForSequenceClassification;m.MobileBertModel;m.MobileBertPreTrainedModel;m.MobileBertTokenizer;m.MobileLLMForCausalLM;m.MobileLLMModel;m.MobileLLMPreTrainedModel;m.MobileNetV1FeatureExtractor;m.MobileNetV1ForImageClassification;m.MobileNetV1ForSemanticSegmentation;m.MobileNetV1ImageProcessor;m.MobileNetV1Model;m.MobileNetV1PreTrainedModel;m.MobileNetV2FeatureExtractor;m.MobileNetV2ForImageClassification;m.MobileNetV2ForSemanticSegmentation;m.MobileNetV2ImageProcessor;m.MobileNetV2Model;m.MobileNetV2PreTrainedModel;m.MobileNetV3FeatureExtractor;m.MobileNetV3ForImageClassification;m.MobileNetV3ForSemanticSegmentation;m.MobileNetV3ImageProcessor;m.MobileNetV3Model;m.MobileNetV3PreTrainedModel;m.MobileNetV4FeatureExtractor;m.MobileNetV4ForImageClassification;m.MobileNetV4ForSemanticSegmentation;m.MobileNetV4ImageProcessor;m.MobileNetV4Model;m.MobileNetV4PreTrainedModel;m.MobileViTFeatureExtractor;m.MobileViTForImageClassification;m.MobileViTImageProcessor;m.MobileViTModel;m.MobileViTPreTrainedModel;m.MobileViTV2ForImageClassification;m.MobileViTV2Model;m.MobileViTV2PreTrainedModel;m.ModelOutput;m.ModernBertDecoderForCausalLM;m.ModernBertDecoderModel;m.ModernBertDecoderPreTrainedModel;m.ModernBertForMaskedLM;m.ModernBertForSequenceClassification;m.ModernBertForTokenClassification;m.ModernBertModel;m.ModernBertPreTrainedModel;m.Moondream1ForConditionalGeneration;m.MoonshineFeatureExtractor;m.MoonshineForConditionalGeneration;m.MoonshineModel;m.MoonshinePreTrainedModel;m.MoonshineProcessor;m.MptForCausalLM;m.MptModel;m.MptPreTrainedModel;m.MultiModalityCausalLM;m.MultiModalityPreTrainedModel;m.MusicgenForCausalLM;m.MusicgenForConditionalGeneration;m.MusicgenModel;m.MusicgenPreTrainedModel;m.NanoChatForCausalLM;m.NanoChatModel;m.NanoChatPreTrainedModel;m.NeoBertForMaskedLM;m.NeoBertForQuestionAnswering;m.NeoBertForSequenceClassification;m.NeoBertForTokenClassification;m.NeoBertModel;m.NeoBertPreTrainedModel;m.NllbTokenizer;m.NoBadWordsLogitsProcessor;m.NoRepeatNGramLogitsProcessor;m.NomicBertModel;m.NomicBertPreTrainedModel;m.NougatImageProcessor;m.NougatTokenizer;m.OPTForCausalLM;m.OPTModel;m.OPTPreTrainedModel;m.ObjectDetectionPipeline;m.Olmo2ForCausalLM;m.Olmo2Model;m.Olmo2PreTrainedModel;m.OlmoForCausalLM;m.OlmoModel;m.OlmoPreTrainedModel;m.OpenELMForCausalLM;m.OpenELMModel;m.OpenELMPreTrainedModel;m.OwlViTFeatureExtractor;m.OwlViTForObjectDetection;m.OwlViTImageProcessor;m.OwlViTModel;m.OwlViTPreTrainedModel;m.OwlViTProcessor;m.Owlv2ForObjectDetection;m.Owlv2ImageProcessor;m.Owlv2Model;m.Owlv2PreTrainedModel;m.PaliGemmaForConditionalGeneration;m.PaliGemmaPreTrainedModel;m.PaliGemmaProcessor;m.ParakeetFeatureExtractor;m.ParakeetForCTC;m.ParakeetPreTrainedModel;m.PatchTSMixerForPrediction;m.PatchTSMixerModel;m.PatchTSMixerPreTrainedModel;m.PatchTSTForPrediction;m.PatchTSTModel;m.PatchTSTPreTrainedModel;m.Phi3ForCausalLM;m.Phi3Model;m.Phi3PreTrainedModel;m.Phi3VForCausalLM;m.Phi3VImageProcessor;m.Phi3VPreTrainedModel;m.Phi3VProcessor;m.PhiForCausalLM;m.PhiModel;m.PhiPreTrainedModel;m.Pipeline;m.PixtralImageProcessor;m.PixtralProcessor;m.PreTrainedModel;m.PreTrainedTokenizer;m.PretrainedConfig;m.PretrainedMixin;m.Processor;m.PvtForImageClassification;m.PvtImageProcessor;m.PvtModel;m.PvtPreTrainedModel;m.PyAnnoteFeatureExtractor;m.PyAnnoteForAudioFrameClassification;m.PyAnnoteModel;m.PyAnnotePreTrainedModel;m.PyAnnoteProcessor;m.QuestionAnsweringModelOutput;m.QuestionAnsweringPipeline;m.Qwen2ForCausalLM;m.Qwen2Model;m.Qwen2PreTrainedModel;m.Qwen2Tokenizer;m.Qwen2VLForConditionalGeneration;m.Qwen2VLImageProcessor;m.Qwen2VLPreTrainedModel;m.Qwen2VLProcessor;m.Qwen3ForCausalLM;m.Qwen3Model;m.Qwen3PreTrainedModel;m.RFDetrForObjectDetection;m.RFDetrModel;m.RFDetrObjectDetectionOutput;m.RFDetrPreTrainedModel;m.RTDetrForObjectDetection;m.RTDetrImageProcessor;m.RTDetrModel;m.RTDetrObjectDetectionOutput;m.RTDetrPreTrainedModel;m.RTDetrV2ForObjectDetection;m.RTDetrV2Model;m.RTDetrV2ObjectDetectionOutput;m.RTDetrV2PreTrainedModel;m.RawAudio;m.RawImage;m.RawVideo;m.RawVideoFrame;m.RepetitionPenaltyLogitsProcessor;m.ResNetForImageClassification;m.ResNetModel;m.ResNetPreTrainedModel;m.RoFormerForMaskedLM;m.RoFormerForQuestionAnswering;m.RoFormerForSequenceClassification;m.RoFormerForTokenClassification;m.RoFormerModel;m.RoFormerPreTrainedModel;m.RoFormerTokenizer;m.RobertaForMaskedLM;m.RobertaForQuestionAnswering;m.RobertaForSequenceClassification;m.RobertaForTokenClassification;m.RobertaModel;m.RobertaPreTrainedModel;m.RobertaTokenizer;m.Sam2ImageProcessor;m.Sam2ImageSegmentationOutput;m.Sam2Model;m.Sam2PreTrainedModel;m.Sam2Processor;m.Sam2VideoProcessor;m.Sam3ImageProcessor;m.Sam3TrackerModel;m.SamImageProcessor;m.SamImageSegmentationOutput;m.SamModel;m.SamPreTrainedModel;m.SamProcessor;m.SapiensForDepthEstimation;m.SapiensForNormalEstimation;m.SapiensForSemanticSegmentation;m.SapiensPreTrainedModel;m.SeamlessM4TFeatureExtractor;m.SegformerFeatureExtractor;m.SegformerForImageClassification;m.SegformerForSemanticSegmentation;m.SegformerImageProcessor;m.SegformerModel;m.SegformerPreTrainedModel;m.Seq2SeqLMOutput;m.SequenceClassifierOutput;m.SiglipImageProcessor;m.SiglipModel;m.SiglipPreTrainedModel;m.SiglipTextModel;m.SiglipTokenizer;m.SiglipVisionModel;m.SmolLM3ForCausalLM;m.SmolLM3Model;m.SmolLM3PreTrainedModel;m.SmolVLMForConditionalGeneration;m.SmolVLMImageProcessor;m.SmolVLMProcessor;m.SnacDecoderModel;m.SnacEncoderModel;m.SnacFeatureExtractor;m.SnacModel;m.SnacPreTrainedModel;m.SpeechT5FeatureExtractor;m.SpeechT5ForSpeechToText;m.SpeechT5ForTextToSpeech;m.SpeechT5HifiGan;m.SpeechT5Model;m.SpeechT5PreTrainedModel;m.SpeechT5Processor;m.SpeechT5Tokenizer;m.SqueezeBertForMaskedLM;m.SqueezeBertForQuestionAnswering;m.SqueezeBertForSequenceClassification;m.SqueezeBertModel;m.SqueezeBertPreTrainedModel;m.SqueezeBertTokenizer;m.StableLmForCausalLM;m.StableLmModel;m.StableLmPreTrainedModel;m.Starcoder2ForCausalLM;m.Starcoder2Model;m.Starcoder2PreTrainedModel;m.StoppingCriteria;m.StoppingCriteriaList;m.StyleTextToSpeech2Model;m.StyleTextToSpeech2PreTrainedModel;m.SummarizationPipeline;m.SupertonicForConditionalGeneration;m.SupertonicPreTrainedModel;m.SuppressTokensAtBeginLogitsProcessor;m.Swin2SRForImageSuperResolution;m.Swin2SRImageProcessor;m.Swin2SRModel;m.Swin2SRPreTrainedModel;m.SwinForImageClassification;m.SwinForSemanticSegmentation;m.SwinModel;m.SwinPreTrainedModel;m.T5ForConditionalGeneration;m.T5Model;m.T5PreTrainedModel;m.T5Tokenizer;m.TableTransformerForObjectDetection;m.TableTransformerModel;m.TableTransformerObjectDetectionOutput;m.TableTransformerPreTrainedModel;m.TemperatureLogitsWarper;m.Tensor;m.Text2TextGenerationPipeline;m.TextClassificationPipeline;m.TextGenerationPipeline;m.TextStreamer;m.TextToAudioPipeline;m.TokenClassificationPipeline;m.TokenClassifierOutput;m.TokenizerModel;m.TopKLogitsWarper;m.TopPLogitsWarper;m.TrOCRForCausalLM;m.TrOCRPreTrainedModel;m.TranslationPipeline;m.UltravoxModel;m.UltravoxPreTrainedModel;m.UltravoxProcessor;m.UniSpeechForCTC;m.UniSpeechForSequenceClassification;m.UniSpeechModel;m.UniSpeechPreTrainedModel;m.UniSpeechSatForAudioFrameClassification;m.UniSpeechSatForCTC;m.UniSpeechSatForSequenceClassification;m.UniSpeechSatModel;m.UniSpeechSatPreTrainedModel;m.VLChatProcessor;m.VLMImageProcessor;m.VaultGemmaForCausalLM;m.VaultGemmaModel;m.VaultGemmaPreTrainedModel;m.ViTFeatureExtractor;m.ViTForImageClassification;m.ViTImageProcessor;m.ViTMAEModel;m.ViTMAEPreTrainedModel;m.ViTMSNForImageClassification;m.ViTMSNModel;m.ViTMSNPreTrainedModel;m.ViTModel;m.ViTPreTrainedModel;m.VisionEncoderDecoderModel;m.VitMatteForImageMatting;m.VitMatteImageProcessor;m.VitMattePreTrainedModel;m.VitPoseForPoseEstimation;m.VitPoseImageProcessor;m.VitPosePreTrainedModel;m.VitsModel;m.VitsModelOutput;m.VitsPreTrainedModel;m.VitsTokenizer;m.VoxtralForConditionalGeneration;m.VoxtralProcessor;m.Wav2Vec2BertForCTC;m.Wav2Vec2BertForSequenceClassification;m.Wav2Vec2BertModel;m.Wav2Vec2BertPreTrainedModel;m.Wav2Vec2CTCTokenizer;m.Wav2Vec2FeatureExtractor;m.Wav2Vec2ForAudioFrameClassification;m.Wav2Vec2ForCTC;m.Wav2Vec2ForSequenceClassification;m.Wav2Vec2Model;m.Wav2Vec2PreTrainedModel;m.Wav2Vec2Processor;m.Wav2Vec2ProcessorWithLM;m.WavLMForAudioFrameClassification;m.WavLMForCTC;m.WavLMForSequenceClassification;m.WavLMForXVector;m.WavLMModel;m.WavLMPreTrainedModel;m.WeSpeakerFeatureExtractor;m.WeSpeakerResNetModel;m.WeSpeakerResNetPreTrainedModel;m.WhisperFeatureExtractor;m.WhisperForConditionalGeneration;m.WhisperModel;m.WhisperPreTrainedModel;m.WhisperProcessor;m.WhisperTextStreamer;m.WhisperTimeStampLogitsProcessor;m.WhisperTokenizer;m.XLMForQuestionAnswering;m.XLMForSequenceClassification;m.XLMForTokenClassification;m.XLMModel;m.XLMPreTrainedModel;m.XLMRobertaForMaskedLM;m.XLMRobertaForQuestionAnswering;m.XLMRobertaForSequenceClassification;m.XLMRobertaForTokenClassification;m.XLMRobertaModel;m.XLMRobertaPreTrainedModel;m.XLMRobertaTokenizer;m.XLMTokenizer;m.XLMWithLMHeadModel;m.XVectorOutput;m.YolosFeatureExtractor;m.YolosForObjectDetection;m.YolosImageProcessor;m.YolosModel;m.YolosObjectDetectionOutput;m.YolosPreTrainedModel;m.ZeroShotAudioClassificationPipeline;m.ZeroShotClassificationPipeline;m.ZeroShotImageClassificationPipeline;m.ZeroShotObjectDetectionPipeline;m.bankers_round;m.cat;m.cos_sim;m.dot;m.dynamic_time_warping;var bv=m.env;m.full;m.full_like;m.getCacheShapes;m.hamming;m.hanning;m.interpolate;m.interpolate_4d;m.interpolate_data;m.is_chinese_char;m.layer_norm;m.load_image;m.load_video;m.log_softmax;m.magnitude;m.matmul;m.max;m.mean;m.mean_pooling;m.medianFilter;m.mel_filter_bank;m.min;m.ones;m.ones_like;m.permute;m.permute_data;var l1=m.pipeline;m.quantize_embeddings;m.rand;m.randn;m.read_audio;m.rfft;m.round;m.slice;m.softmax;m.spectrogram;m.stack;m.std_mean;m.topk;m.window_function;m.zeros;m.zeros_like;const yv=[{id:"whisper-tiny-multilingual-wasm",label:"Whisper Tiny (multilingual)",modelId:"onnx-community/whisper-tiny",revision:"ff4177021cc41f7db950912b73ea4fdf7d01d8e7",multilingual:!0,approximateDownloadBytes:77e6,devices:["wasm","webgpu"],dtypeByDevice:{wasm:"q8",webgpu:"fp32"},chunkLengthSeconds:30,strideLengthSeconds:5,maxDurationSeconds:10800}];yv[0].id;function Mi(e){return yv.find(r=>r.id===e)}bv.allowLocalModels=!1;bv.useBrowserCache=!0;const c1="0.1.0-prototype",u1="0d8c0a8b93e2",vv="3.x";let Vr=null,oo=null,ea=new Set;function cs(e){self.postMessage(e)}function Gs(e,r){ea.has(e)||cs({protocol:1,type:"PROGRESS",requestId:e,progress:r})}function Uu(e,r){if(ea.has(e)){cs({protocol:1,type:"CANCELLED",requestId:e});return}cs({protocol:1,type:"ERROR",requestId:e,error:r})}function wi(e={}){return{appVersion:c1,buildId:u1,transformersVersion:vv,cacheState:"unknown",...e}}function ta(e){return ea.has(e)}async function d1(e,r,t){const s=Mi(e);if(!s)throw xs("PROFILE_UNKNOWN","prepare",!1);const n=performance.now();let o="wasm",i;Gs(t,{phase:"manifest",status:"completed",ratio:1}),Gs(t,{phase:"runtime-init",status:"started"});const a=typeof navigator<"u"&&"gpu"in navigator,l=r==="webgpu"||r==="auto"&&a;if(r==="webgpu"&&!a)throw xs("RUNTIME_UNSUPPORTED","prepare",!0,!0);const c=async u=>{const f=s.dtypeByDevice[u]??(u==="webgpu"?"fp32":"q8");return l1("automatic-speech-recognition",s.modelId,{revision:s.revision,device:u,dtype:f,progress_callback:_=>{ta(t)||(_.status==="progress"||_.status==="download")&&Gs(t,{phase:"download",status:"running",fileId:_.file,loadedBytes:_.loaded,totalBytes:_.total,ratio:typeof _.progress=="number"?_.progress/100:_.total?(_.loaded??0)/_.total:void 0})}})};let p;if(l)try{Gs(t,{phase:"model-init",status:"started"}),p=await c("webgpu"),o="webgpu"}catch{i="WEBGPU_INIT_FAILED",Gs(t,{phase:"runtime-init",status:"started"}),p=await c("wasm"),o="wasm"}else Gs(t,{phase:"model-init",status:"started"}),p=await c("wasm"),o="wasm";if(ta(t))throw xs("CANCELLED","prepare",!0);return Gs(t,{phase:"warmup",status:"completed",ratio:1}),{fingerprint:[s.modelId,s.revision,o,s.dtypeByDevice[o]??"default",vv].join("|"),pipeline:p,effectiveRuntime:o,profileId:s.id,modelRevision:s.revision,preparationMs:Math.round(performance.now()-n),fallbackReasonCode:i}}async function xv(e,r,t){const s=Mi(e);if(!s)throw xs("PROFILE_UNKNOWN","prepare",!1);const n=r==="wasm"?"wasm":r==="webgpu"?"webgpu":Vr?.effectiveRuntime??"auto",o=`${s.modelId}|${s.revision}|`;return Vr&&Vr.profileId===e&&Vr.fingerprint.startsWith(o)&&(r==="auto"||Vr.effectiveRuntime===n||r==="webgpu"&&Vr.effectiveRuntime==="wasm"&&Vr.fallbackReasonCode)?Vr:(oo||(oo=d1(e,r,t).then(i=>(Vr=i,oo=null,i)).catch(i=>{throw oo=null,Vr=null,i})),oo)}function p1(e,r){const t=[],s=e??{},n=(s.text??"").trim(),o=[];if(Array.isArray(s.chunks))for(const i of s.chunks){const a=i.timestamp?.[0],l=i.timestamp?.[1];typeof a!="number"||typeof l!="number"||!Number.isFinite(a)||!Number.isFinite(l)||li.text).join(" ").trim(),segments:o,durationSeconds:r,warnings:t}}function xs(e,r,t,s){return{code:e,phase:r,recoverable:t,fallbackAvailable:s}}function m1(e){if(!(e instanceof Float32Array)||e.length===0)throw xs("AUDIO_INVALID","infer",!0);for(let r=0;r{const r=e.data;if(!r||r.protocol!==1){cs({protocol:1,type:"ERROR",requestId:r?.requestId??"unknown",error:xs("PROTOCOL_UNSUPPORTED","prepare",!1)});return}switch(r.type){case"PREPARE":h1(r);break;case"TRANSCRIBE":_1(r);break;case"CANCEL":ea.add(r.targetRequestId),cs({protocol:1,type:"CANCELLED",requestId:r.requestId});break;case"DISPOSE":Vr=null,oo=null,ea=new Set,cs({protocol:1,type:"DIAGNOSTICS",requestId:r.requestId,diagnostics:wi()});break;case"GET_DIAGNOSTICS":cs({protocol:1,type:"DIAGNOSTICS",requestId:r.requestId,diagnostics:wi({modelProfileId:Vr?.profileId,modelRevision:Vr?.modelRevision,effectiveRuntime:Vr?.effectiveRuntime,preparationMs:Vr?.preparationMs,fallbackReasonCode:Vr?.fallbackReasonCode})});break;default:Uu(r.requestId,xs("INTERNAL","prepare",!1))}}; diff --git a/static/utility-apps/whisper-transcriber/build-info.json b/static/utility-apps/whisper-transcriber/build-info.json new file mode 100644 index 0000000..84a651e --- /dev/null +++ b/static/utility-apps/whisper-transcriber/build-info.json @@ -0,0 +1,4 @@ +{ + "version": "0.1.0-prototype", + "buildId": "0d8c0a8b93e2" +} diff --git a/static/utility-apps/whisper-transcriber/index.html b/static/utility-apps/whisper-transcriber/index.html new file mode 100644 index 0000000..65ba537 --- /dev/null +++ b/static/utility-apps/whisper-transcriber/index.html @@ -0,0 +1,17 @@ + + + + + + + Whisper Transcriber + + + + +
+ + diff --git a/static/utility-apps/whisper-transcriber/manifest.json b/static/utility-apps/whisper-transcriber/manifest.json new file mode 100644 index 0000000..237da77 --- /dev/null +++ b/static/utility-apps/whisper-transcriber/manifest.json @@ -0,0 +1,23 @@ +{ + "name": "whisper-transcriber", + "version": "0.1.0-prototype", + "buildId": "0d8c0a8b93e2", + "buildTime": "2026-07-21T11:21:08.856Z", + "entry": "app.html", + "assets": [ + "assets/index-B5C8PNiW.js", + "assets/index-BWGSeFCx.css", + "assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm", + "assets/whisper.worker-CA5aZLsj.js", + "build-info.json" + ], + "checksums": { + "assets/index-B5C8PNiW.js": "09b2ad1591b54aa369e7b95594a885f8f613cb766d2466369d3c606c69db6e71", + "assets/index-BWGSeFCx.css": "ee3f659b1fd58be6a87f3cce8818dbaed8bbdc0a24d55ac26728081e77303450", + "assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm": "c46655e8a94afc45338d4cb2b840475f88e5012d524509916e505079c00bfa39", + "assets/whisper.worker-CA5aZLsj.js": "0cadb55011ceb1263a570aad4b6c588b17f17af9430466a0a4a69277e1a830dc", + "build-info.json": "16c1ad1b392cc798e8d073cc61dd07dc5791534391966a276fa9ce6976781edb", + "app.html": "2aabc82b640868b67b619de781e7a8616d24fbfab2666005ef9a490b578ddcdb", + "index.html": "2aabc82b640868b67b619de781e7a8616d24fbfab2666005ef9a490b578ddcdb" + } +} diff --git a/vercel.json b/vercel.json index 306f98b..2bfcbde 100644 --- a/vercel.json +++ b/vercel.json @@ -26,7 +26,25 @@ }, { "key": "Content-Security-Policy", - "value": "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' https://challenges.cloudflare.com https://va.vercel-scripts.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self' https://*.supabase.co wss://*.supabase.co https://api.stripe.com https://challenges.cloudflare.com https://*.vercel-insights.com https://vitals.vercel-insights.com; frame-src 'self' blob: https://challenges.cloudflare.com; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'" + "value": "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' https://challenges.cloudflare.com https://va.vercel-scripts.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self' https://*.supabase.co wss://*.supabase.co https://api.stripe.com https://challenges.cloudflare.com https://*.vercel-insights.com https://vitals.vercel-insights.com https://huggingface.co https://*.huggingface.co https://*.hf.co; frame-src 'self' blob: https://challenges.cloudflare.com; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'" + } + ] + }, + { + "source": "/utilities/whisper-transcriber/:path*", + "headers": [ + { + "key": "Permissions-Policy", + "value": "camera=(self), microphone=(self), geolocation=()" + } + ] + }, + { + "source": "/utility-apps/whisper-transcriber/:path*", + "headers": [ + { + "key": "Permissions-Policy", + "value": "camera=(self), microphone=(self), geolocation=()" } ] },