llm-testrunner-components 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +165 -242
- package/dist/cjs/index.cjs.js +298 -232
- package/dist/cjs/index.cjs.js.map +1 -1
- package/dist/collection/components/llm-test-runner/llm-test-runner.import-export.test.js +25 -54
- package/dist/collection/components/llm-test-runner/llm-test-runner.import-export.test.js.map +1 -1
- package/dist/collection/components/llm-test-runner/llm-test-runner.js +6 -49
- package/dist/collection/components/llm-test-runner/llm-test-runner.js.map +1 -1
- package/dist/collection/components/llm-test-runner/test-cases/evaluation/evaluation-summary.css +60 -21
- package/dist/collection/components/llm-test-runner/test-cases/evaluation/evaluation-summary.js +3 -1
- package/dist/collection/components/llm-test-runner/test-cases/evaluation/evaluation-summary.js.map +1 -1
- package/dist/collection/components/llm-test-runner/test-cases/expected-outcome-renderer.js +31 -11
- package/dist/collection/components/llm-test-runner/test-cases/expected-outcome-renderer.js.map +1 -1
- package/dist/collection/components/llm-test-runner/test-cases/llm-test-case-row.css +17 -0
- package/dist/collection/components/llm-test-runner/test-cases/llm-test-case-row.js +2 -12
- package/dist/collection/components/llm-test-runner/test-cases/llm-test-case-row.js.map +1 -1
- package/dist/collection/components/llm-test-runner/test-cases/llm-test-cases.js +2 -2
- package/dist/collection/components/llm-test-runner/test-cases/llm-test-cases.js.map +1 -1
- package/dist/collection/lib/evaluation/evaluation-engine.js +63 -42
- package/dist/collection/lib/evaluation/evaluation-engine.js.map +1 -1
- package/dist/collection/lib/evaluation/evaluation-service.js +15 -3
- package/dist/collection/lib/evaluation/evaluation-service.js.map +1 -1
- package/dist/collection/lib/evaluation/{rouge1-evaluator.test.js → evaluators/rouge1-evaluator.test.js} +2 -2
- package/dist/collection/lib/evaluation/evaluators/rouge1-evaluator.test.js.map +1 -0
- package/dist/collection/lib/evaluation/field-evaluation-approach.js +24 -0
- package/dist/collection/lib/evaluation/field-evaluation-approach.js.map +1 -0
- package/dist/collection/lib/evaluation/index.js +0 -4
- package/dist/collection/lib/evaluation/index.js.map +1 -1
- package/dist/collection/lib/evaluation/types.js.map +1 -1
- package/dist/collection/lib/import-export/test-results-csv.js +47 -33
- package/dist/collection/lib/import-export/test-results-csv.js.map +1 -1
- package/dist/collection/lib/import-export/test-suite-exporter.js +0 -1
- package/dist/collection/lib/import-export/test-suite-exporter.js.map +1 -1
- package/dist/collection/lib/test-cases/test-case-factory.js +17 -27
- package/dist/collection/lib/test-cases/test-case-factory.js.map +1 -1
- package/dist/collection/lib/test-cases/test-case-mutations.js +60 -9
- package/dist/collection/lib/test-cases/test-case-mutations.js.map +1 -1
- package/dist/collection/schemas/expected-outcome.js +20 -2
- package/dist/collection/schemas/expected-outcome.js.map +1 -1
- package/dist/collection/schemas/test-case.js +2 -20
- package/dist/collection/schemas/test-case.js.map +1 -1
- package/dist/collection/types/llm-test-runner.js.map +1 -1
- package/dist/collection/types/test-case.js.map +1 -1
- package/dist/components/index.js +1 -1
- package/dist/components/llm-test-runner.js +1 -1
- package/dist/components/p-Bb89MYYu.js +7 -0
- package/dist/components/p-Bb89MYYu.js.map +1 -0
- package/dist/esm/index.js +298 -232
- package/dist/esm/index.js.map +1 -1
- package/dist/llm-testrunner/index.esm.js +2 -2
- package/dist/llm-testrunner/index.esm.js.map +1 -1
- package/dist/types/components/llm-test-runner/llm-test-runner.d.ts +0 -1
- package/dist/types/components/llm-test-runner/test-cases/expected-outcome-renderer.d.ts +3 -6
- package/dist/types/components/llm-test-runner/test-cases/llm-test-case-row.d.ts +0 -2
- package/dist/types/components/llm-test-runner/test-cases/llm-test-cases.d.ts +0 -2
- package/dist/types/lib/evaluation/evaluation-engine.d.ts +4 -2
- package/dist/types/lib/evaluation/field-evaluation-approach.d.ts +6 -0
- package/dist/types/lib/evaluation/index.d.ts +0 -1
- package/dist/types/lib/evaluation/types.d.ts +26 -0
- package/dist/types/lib/import-export/test-suite-exporter.d.ts +0 -4
- package/dist/types/lib/test-cases/test-case-factory.d.ts +2 -3
- package/dist/types/lib/test-cases/test-case-mutations.d.ts +21 -5
- package/dist/types/schemas/expected-outcome.d.ts +65 -17
- package/dist/types/schemas/test-case.d.ts +51 -95
- package/dist/types/types/llm-test-runner.d.ts +1 -1
- package/dist/types/types/test-case.d.ts +1 -1
- package/package.json +9 -2
- package/dist/collection/lib/evaluation/rouge1-evaluator.test.js.map +0 -1
- package/dist/components/p-BF90yb1z.js +0 -7
- package/dist/components/p-BF90yb1z.js.map +0 -1
- /package/dist/types/lib/evaluation/{rouge1-evaluator.test.d.ts → evaluators/rouge1-evaluator.test.d.ts} +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{h,c as getAugmentedNamespace,d as getDefaultExportFromCjs,p as proxyCustomElement,t as transformTag,H,e as createEvent}from"./p-D9BrlHdP.js";import{d as defineCustomElement$3}from"./p-CE5-1jfZ.js";import{d as defineCustomElement$2}from"./p-Dv7cB5FU.js";import{d as defineCustomElement$1}from"./p-BZrzx5jG.js";function _mergeNamespaces(e,t){t.forEach((function(t){t&&typeof t!=="string"&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if(n!=="default"&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:true,get:function(){return t[n]}})}}))}));return Object.freeze(e)}const ErrorMessage=({message:e,onClear:t})=>{if(!e){return null}return h("div",{class:"error-message"},h("span",null,e),t&&h("button",{type:"button",class:"error-message__close",title:"Close",onClick:t},"×"))};class RateLimitedFetcher{queue=[];delay;timer;constructor(e){this.delay=e}startQueue(){if(this.timer)return;this.timer=setInterval((()=>{const e=this.queue.shift();if(e)e();if(this.queue.length===0){this.stop()}}),this.delay)}schedule(e){return new Promise(((t,n)=>{this.queue.push((()=>{e().then(t).catch(n)}));this.startQueue()}))}stop(){if(this.timer){clearInterval(this.timer);this.timer=undefined}}async runAll(e){const t=e.map((e=>this.schedule(e)));return Promise.all(t)}}function readFileAsync(e){return new Promise(((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result);r.onerror=()=>n(r.error);r.readAsText(e)}))}function downloadFile(e,t,n){const r=new Blob([e],{type:n});const o=URL.createObjectURL(r);const i=document.createElement("a");i.href=o;i.download=t;document.body.appendChild(i);i.click();document.body.removeChild(i);URL.revokeObjectURL(o)}function formatTestSuiteAsJson(e){const t=e.map((e=>({id:e.id,question:e.question,expectedOutcome:e.expectedOutcome})));return JSON.stringify(t,null,2)}function escapeCsvField(e){if(e.includes(",")||e.includes('"')||e.includes("\n")){return`"${e.replace(/"/g,'""')}"`}return e}function exportTestResultsToCsv(e){const t=[];const n=e.reduce(((e,t)=>Math.max(e,(t.expectedOutcome||[]).length)),0);const r=["Question","Response Time (s)"];for(let e=1;e<=n;e++){r.push("Field Name");r.push("Expected Keywords");r.push("Generated Keywords");r.push("Evaluation Strategy");r.push("Passed Evaluation");r.push("Keyword Match");r.push("Score");if(e<n){r.push("")}}t.push(r.join(","));e.forEach((e=>{const r=e.responseTime?(e.responseTime/1e3).toFixed(3):"N/A";const o=[escapeCsvField(e.question),r];for(let t=0;t<n;t++){const r=e.expectedOutcome?.[t];const i=e.evaluationResult?.fieldResults?.find((e=>e.index===t));const s=i?.expectedValue??(r?r.type==="chips-input"?r.value.join(", "):r.value:"");const a=(i?.keywordMatches||[]).filter((e=>e.found)).map((e=>e.keyword)).join("; ");const c=(i?.keywordMatches||[]).filter((e=>e.found)).length;const u=i?.keywordMatches?.length||0;const l=u>0?`${c}/${u}`:"";const f=i?.evaluationApproachResult?.score!==undefined?i.evaluationApproachResult.score.toFixed(2):"";o.push(escapeCsvField(r?.label||""));o.push(escapeCsvField(s||""));o.push(escapeCsvField(a));o.push(escapeCsvField(i?.evaluationParameters.approach||r?.evaluationParameters?.approach||""));o.push(i?i.passed?"TRUE":"FALSE":"");o.push(l);o.push(f);if(t<n-1){o.push("")}}t.push(o.join(","))}));return t.join("\n")}var byteToHex=[];for(var i=0;i<256;++i){byteToHex.push((i+256).toString(16).slice(1))}function unsafeStringify(e,t=0){return(byteToHex[e[t+0]]+byteToHex[e[t+1]]+byteToHex[e[t+2]]+byteToHex[e[t+3]]+"-"+byteToHex[e[t+4]]+byteToHex[e[t+5]]+"-"+byteToHex[e[t+6]]+byteToHex[e[t+7]]+"-"+byteToHex[e[t+8]]+byteToHex[e[t+9]]+"-"+byteToHex[e[t+10]]+byteToHex[e[t+11]]+byteToHex[e[t+12]]+byteToHex[e[t+13]]+byteToHex[e[t+14]]+byteToHex[e[t+15]]).toLowerCase()}var getRandomValues;var rnds8=new Uint8Array(16);function rng(){if(!getRandomValues){getRandomValues=typeof crypto!=="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto);if(!getRandomValues){throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported")}}return getRandomValues(rnds8)}var randomUUID=typeof crypto!=="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var native={randomUUID};function v4(e,t,n){if(native.randomUUID&&true&&!e){return native.randomUUID()}e=e||{};var r=e.random||(e.rng||rng)();r[6]=r[6]&15|64;r[8]=r[8]&63|128;return unsafeStringify(r)}var EvaluationApproach;(function(e){e["EXACT"]="exact";e["SEMANTIC"]="semantic";e["ROUGE_1"]="rouge-1";e["ROUGE_L"]="rouge-L";e["BLEU"]="bleu"})(EvaluationApproach||(EvaluationApproach={}));const EvaluationApproachValues=Object.values(EvaluationApproach);const DEFAULT_ROUGE_PASS_SCORE=.7;const DEFAULT_SEMANTIC_PASS_SCORE=.7;const DEFAULT_BLEU_PASS_SCORE=.7;const SELECT_ONLY_APPROACHES=[EvaluationApproach.EXACT];function getAllowedApproachesForFieldType(e){if(e==="select"){return SELECT_ONLY_APPROACHES}return EvaluationApproachValues}function isApproachAllowedForFieldType(e,t){return getAllowedApproachesForFieldType(e).includes(t)}function normalizeEvaluationParametersForField(e,t){const n=getAllowedApproachesForFieldType(e);const r=n[0];const o=t?.approach;const i=o&&n.includes(o)?o:r;return{...t,approach:i}}const DEFAULT_EXPECTED_OUTCOME_SCHEMA=[{type:"textarea",label:"Expected Outcome",placeholder:"Enter expected outcome...",rows:2}];function normalizeExpectedOutcomeField(e){return{...e,evaluationParameters:normalizeEvaluationParametersForField(e.type,e.evaluationParameters)}}function createTestCase(e=DEFAULT_EXPECTED_OUTCOME_SCHEMA){return{id:v4(),question:"",expectedOutcome:createExpectedOutcomeFromSchema(e),isRunning:false}}function createExpectedOutcomeFieldFromSchema(e){switch(e.type){case"text":return{type:"text",label:e.label,placeholder:e.placeholder,value:"",evaluationParameters:normalizeEvaluationParametersForField(e.type,e.evaluationParameters)};case"textarea":return{type:"textarea",label:e.label,placeholder:e.placeholder,rows:e.rows,value:"",evaluationParameters:normalizeEvaluationParametersForField(e.type,e.evaluationParameters)};case"chips-input":return{type:"chips-input",label:e.label,placeholder:e.placeholder,value:[],evaluationParameters:normalizeEvaluationParametersForField(e.type,e.evaluationParameters)};case"select":return{type:"select",label:e.label,placeholder:e.placeholder,value:"",options:e.options,evaluationParameters:normalizeEvaluationParametersForField(e.type,e.evaluationParameters)};default:{const t=e;return t}}}function createExpectedOutcomeFromSchema(e){return e.map(createExpectedOutcomeFieldFromSchema)}function createTestCaseFromInput(e){return{...e,expectedOutcome:e.expectedOutcome.map(normalizeExpectedOutcomeField)}}function $constructor(e,t,n){function r(n,r){if(!n._zod){Object.defineProperty(n,"_zod",{value:{def:r,constr:s,traits:new Set},enumerable:false})}if(n._zod.traits.has(e)){return}n._zod.traits.add(e);t(n,r);const o=s.prototype;const i=Object.keys(o);for(let e=0;e<i.length;e++){const t=i[e];if(!(t in n)){n[t]=o[t].bind(n)}}}const o=n?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(e){var t;const o=n?.Parent?new i:this;r(o,e);(t=o._zod).deferred??(t.deferred=[]);for(const e of o._zod.deferred){e()}return o}Object.defineProperty(s,"init",{value:r});Object.defineProperty(s,Symbol.hasInstance,{value:t=>{if(n?.Parent&&t instanceof n.Parent)return true;return t?._zod?.traits?.has(e)}});Object.defineProperty(s,"name",{value:e});return s}class $ZodAsyncError extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}}class $ZodEncodeError extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}const globalConfig={};function config(e){return globalConfig}function getEnumValues(e){const t=Object.values(e).filter((e=>typeof e==="number"));const n=Object.entries(e).filter((([e,n])=>t.indexOf(+e)===-1)).map((([e,t])=>t));return n}function jsonStringifyReplacer(e,t){if(typeof t==="bigint")return t.toString();return t}function cached(e){return{get value(){{const t=e();Object.defineProperty(this,"value",{value:t});return t}}}}function nullish(e){return e===null||e===undefined}function cleanRegex(e){const t=e.startsWith("^")?1:0;const n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function floatSafeRemainder(e,t){const n=(e.toString().split(".")[1]||"").length;const r=t.toString();let o=(r.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);if(e?.[1]){o=Number.parseInt(e[1])}}const i=n>o?n:o;const s=Number.parseInt(e.toFixed(i).replace(".",""));const a=Number.parseInt(t.toFixed(i).replace(".",""));return s%a/10**i}const EVALUATING=Symbol("evaluating");function defineLazy(e,t,n){let r=undefined;Object.defineProperty(e,t,{get(){if(r===EVALUATING){return undefined}if(r===undefined){r=EVALUATING;r=n()}return r},set(n){Object.defineProperty(e,t,{value:n})},configurable:true})}function assignProp(e,t,n){Object.defineProperty(e,t,{value:n,writable:true,enumerable:true,configurable:true})}function mergeDefs(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function esc(e){return JSON.stringify(e)}function slugify(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function isObject(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}const allowsEval=cached((()=>{if(typeof navigator!=="undefined"&&navigator?.userAgent?.includes("Cloudflare")){return false}try{const e=Function;new e("");return true}catch(e){return false}}));function isPlainObject(e){if(isObject(e)===false)return false;const t=e.constructor;if(t===undefined)return true;if(typeof t!=="function")return true;const n=t.prototype;if(isObject(n)===false)return false;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===false){return false}return true}function shallowClone(e){if(isPlainObject(e))return{...e};if(Array.isArray(e))return[...e];return e}const propertyKeyTypes=new Set(["string","number","symbol"]);function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(e,t,n){const r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function normalizeParams(e){const t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==undefined){if(t?.error!==undefined)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}delete t.message;if(typeof t.error==="string")return{...t,error:()=>t.error};return t}function optionalKeys(e){return Object.keys(e).filter((t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional"))}const NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function pick(e,t){const n=e._zod.def;const r=n.checks;const o=r&&r.length>0;if(o){throw new Error(".pick() cannot be used on object schemas containing refinements")}const i=mergeDefs(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape)){throw new Error(`Unrecognized key: "${r}"`)}if(!t[r])continue;e[r]=n.shape[r]}assignProp(this,"shape",e);return e},checks:[]});return clone(e,i)}function omit(e,t){const n=e._zod.def;const r=n.checks;const o=r&&r.length>0;if(o){throw new Error(".omit() cannot be used on object schemas containing refinements")}const i=mergeDefs(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape)){throw new Error(`Unrecognized key: "${e}"`)}if(!t[e])continue;delete r[e]}assignProp(this,"shape",r);return r},checks:[]});return clone(e,i)}function extend(e,t){if(!isPlainObject(t)){throw new Error("Invalid input to extend: expected a plain object")}const n=e._zod.def.checks;const r=n&&n.length>0;if(r){const n=e._zod.def.shape;for(const e in t){if(Object.getOwnPropertyDescriptor(n,e)!==undefined){throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}}}const o=mergeDefs(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};assignProp(this,"shape",n);return n}});return clone(e,o)}function safeExtend(e,t){if(!isPlainObject(t)){throw new Error("Invalid input to safeExtend: expected a plain object")}const n=mergeDefs(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};assignProp(this,"shape",n);return n}});return clone(e,n)}function merge(e,t){const n=mergeDefs(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};assignProp(this,"shape",n);return n},get catchall(){return t._zod.def.catchall},checks:[]});return clone(e,n)}function partial(e,t,n){const r=t._zod.def;const o=r.checks;const i=o&&o.length>0;if(i){throw new Error(".partial() cannot be used on object schemas containing refinements")}const s=mergeDefs(t._zod.def,{get shape(){const r=t._zod.def.shape;const o={...r};if(n){for(const t in n){if(!(t in r)){throw new Error(`Unrecognized key: "${t}"`)}if(!n[t])continue;o[t]=e?new e({type:"optional",innerType:r[t]}):r[t]}}else{for(const t in r){o[t]=e?new e({type:"optional",innerType:r[t]}):r[t]}}assignProp(this,"shape",o);return o},checks:[]});return clone(t,s)}function required(e,t,n){const r=mergeDefs(t._zod.def,{get shape(){const r=t._zod.def.shape;const o={...r};if(n){for(const t in n){if(!(t in o)){throw new Error(`Unrecognized key: "${t}"`)}if(!n[t])continue;o[t]=new e({type:"nonoptional",innerType:r[t]})}}else{for(const t in r){o[t]=new e({type:"nonoptional",innerType:r[t]})}}assignProp(this,"shape",o);return o}});return clone(t,r)}function aborted(e,t=0){if(e.aborted===true)return true;for(let n=t;n<e.issues.length;n++){if(e.issues[n]?.continue!==true){return true}}return false}function prefixIssues(e,t){return t.map((t=>{var n;(n=t).path??(n.path=[]);t.path.unshift(e);return t}))}function unwrapMessage(e){return typeof e==="string"?e:e?.message}function finalizeIssue(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const o=unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(n.customError?.(e))??unwrapMessage(n.localeError?.(e))??"Invalid input";r.message=o}delete r.inst;delete r.continue;if(!t?.reportInput){delete r.input}return r}function getLengthableOrigin(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function issue(...e){const[t,n,r]=e;if(typeof t==="string"){return{message:t,code:"custom",input:n,inst:r}}return{...t}}const initializer$1=(e,t)=>{e.name="$ZodError";Object.defineProperty(e,"_zod",{value:e._zod,enumerable:false});Object.defineProperty(e,"issues",{value:t,enumerable:false});e.message=JSON.stringify(t,jsonStringifyReplacer,2);Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:false})};const $ZodError=$constructor("$ZodError",initializer$1);const $ZodRealError=$constructor("$ZodError",initializer$1,{Parent:Error});function flattenError(e,t=e=>e.message){const n={};const r=[];for(const o of e.issues){if(o.path.length>0){n[o.path[0]]=n[o.path[0]]||[];n[o.path[0]].push(t(o))}else{r.push(t(o))}}return{formErrors:r,fieldErrors:n}}function formatError(e,t=e=>e.message){const n={_errors:[]};const r=e=>{for(const o of e.issues){if(o.code==="invalid_union"&&o.errors.length){o.errors.map((e=>r({issues:e})))}else if(o.code==="invalid_key"){r({issues:o.issues})}else if(o.code==="invalid_element"){r({issues:o.issues})}else if(o.path.length===0){n._errors.push(t(o))}else{let e=n;let r=0;while(r<o.path.length){const n=o.path[r];const i=r===o.path.length-1;if(!i){e[n]=e[n]||{_errors:[]}}else{e[n]=e[n]||{_errors:[]};e[n]._errors.push(t(o))}e=e[n];r++}}}};r(e);return n}const _parse=e=>(t,n,r,o)=>{const i=r?Object.assign(r,{async:false}):{async:false};const s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise){throw new $ZodAsyncError}if(s.issues.length){const t=new(o?.Err??e)(s.issues.map((e=>finalizeIssue(e,i,config()))));captureStackTrace(t,o?.callee);throw t}return s.value};const _parseAsync=e=>async(t,n,r,o)=>{const i=r?Object.assign(r,{async:true}):{async:true};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)s=await s;if(s.issues.length){const t=new(o?.Err??e)(s.issues.map((e=>finalizeIssue(e,i,config()))));captureStackTrace(t,o?.callee);throw t}return s.value};const _safeParse=e=>(t,n,r)=>{const o=r?{...r,async:false}:{async:false};const i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise){throw new $ZodAsyncError}return i.issues.length?{success:false,error:new(e??$ZodError)(i.issues.map((e=>finalizeIssue(e,o,config()))))}:{success:true,data:i.value}};const safeParse$1=_safeParse($ZodRealError);const _safeParseAsync=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:true}):{async:true};let i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)i=await i;return i.issues.length?{success:false,error:new e(i.issues.map((e=>finalizeIssue(e,o,config()))))}:{success:true,data:i.value}};const safeParseAsync$1=_safeParseAsync($ZodRealError);const _encode=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return _parse(e)(t,n,o)};const _decode=e=>(t,n,r)=>_parse(e)(t,n,r);const _encodeAsync=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return _parseAsync(e)(t,n,o)};const _decodeAsync=e=>async(t,n,r)=>_parseAsync(e)(t,n,r);const _safeEncode=e=>(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return _safeParse(e)(t,n,o)};const _safeDecode=e=>(t,n,r)=>_safeParse(e)(t,n,r);const _safeEncodeAsync=e=>async(t,n,r)=>{const o=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return _safeParseAsync(e)(t,n,o)};const _safeDecodeAsync=e=>async(t,n,r)=>_safeParseAsync(e)(t,n,r);const cuid=/^[cC][^\s-]{8,}$/;const cuid2=/^[0-9a-z]+$/;const ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;const xid=/^[0-9a-vA-V]{20}$/;const ksuid=/^[A-Za-z0-9]{27}$/;const nanoid=/^[a-zA-Z0-9_-]{21}$/;const duration$1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;const guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;const uuid=e=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};const email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;const _emoji$1=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function emoji(){return new RegExp(_emoji$1,"u")}const ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;const ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;const cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;const cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;const base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;const base64url=/^[A-Za-z0-9_-]*$/;const e164=/^\+[1-9]\d{6,14}$/;const dateSource=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;const date$1=new RegExp(`^${dateSource}$`);function timeSource(e){const t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;const n=typeof e.precision==="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`;return n}function time$1(e){return new RegExp(`^${timeSource(e)}$`)}function datetime$1(e){const t=timeSource({precision:e.precision});const n=["Z"];if(e.local)n.push("");if(e.offset)n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${dateSource}T(?:${r})$`)}const string$1=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:`[\\s\\S]*`;return new RegExp(`^${t}$`)};const integer=/^-?\d+$/;const number$1=/^-?\d+(?:\.\d+)?$/;const boolean$1=/^(?:true|false)$/i;const lowercase=/^[^A-Z]*$/;const uppercase=/^[^a-z]*$/;const $ZodCheck=$constructor("$ZodCheck",((e,t)=>{var n;e._zod??(e._zod={});e._zod.def=t;(n=e._zod).onattach??(n.onattach=[])}));const numericOriginMap={number:"number",bigint:"bigint",object:"date"};const $ZodCheckLessThan=$constructor("$ZodCheckLessThan",((e,t)=>{$ZodCheck.init(e,t);const n=numericOriginMap[typeof t.value];e._zod.onattach.push((e=>{const n=e._zod.bag;const r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<r){if(t.inclusive)n.maximum=t.value;else n.exclusiveMaximum=t.value}}));e._zod.check=r=>{if(t.inclusive?r.value<=t.value:r.value<t.value){return}r.issues.push({origin:n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}));const $ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",((e,t)=>{$ZodCheck.init(e,t);const n=numericOriginMap[typeof t.value];e._zod.onattach.push((e=>{const n=e._zod.bag;const r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>r){if(t.inclusive)n.minimum=t.value;else n.exclusiveMinimum=t.value}}));e._zod.check=r=>{if(t.inclusive?r.value>=t.value:r.value>t.value){return}r.issues.push({origin:n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}));const $ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",((e,t)=>{$ZodCheck.init(e,t);e._zod.onattach.push((e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}));e._zod.check=n=>{if(typeof n.value!==typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");const r=typeof n.value==="bigint"?n.value%t.value===BigInt(0):floatSafeRemainder(n.value,t.value)===0;if(r)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}));const $ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",((e,t)=>{$ZodCheck.init(e,t);t.format=t.format||"float64";const n=t.format?.includes("int");const r=n?"int":"number";const[o,i]=NUMBER_FORMAT_RANGES[t.format];e._zod.onattach.push((e=>{const r=e._zod.bag;r.format=t.format;r.minimum=o;r.maximum=i;if(n)r.pattern=integer}));e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:false,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0){s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:true,continue:!t.abort})}else{s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:true,continue:!t.abort})}return}}if(a<o){s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:true,inst:e,continue:!t.abort})}if(a>i){s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:true,inst:e,continue:!t.abort})}}}));const $ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",((e,t)=>{var n;$ZodCheck.init(e,t);(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!nullish(t)&&t.length!==undefined});e._zod.onattach.push((e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<n)e._zod.bag.maximum=t.maximum}));e._zod.check=n=>{const r=n.value;const o=r.length;if(o<=t.maximum)return;const i=getLengthableOrigin(r);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:true,input:r,inst:e,continue:!t.abort})}}));const $ZodCheckMinLength=$constructor("$ZodCheckMinLength",((e,t)=>{var n;$ZodCheck.init(e,t);(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!nullish(t)&&t.length!==undefined});e._zod.onattach.push((e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>n)e._zod.bag.minimum=t.minimum}));e._zod.check=n=>{const r=n.value;const o=r.length;if(o>=t.minimum)return;const i=getLengthableOrigin(r);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:true,input:r,inst:e,continue:!t.abort})}}));const $ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",((e,t)=>{var n;$ZodCheck.init(e,t);(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!nullish(t)&&t.length!==undefined});e._zod.onattach.push((e=>{const n=e._zod.bag;n.minimum=t.length;n.maximum=t.length;n.length=t.length}));e._zod.check=n=>{const r=n.value;const o=r.length;if(o===t.length)return;const i=getLengthableOrigin(r);const s=o>t.length;n.issues.push({origin:i,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:true,exact:true,input:n.value,inst:e,continue:!t.abort})}}));const $ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",((e,t)=>{var n,r;$ZodCheck.init(e,t);e._zod.onattach.push((e=>{const n=e._zod.bag;n.format=t.format;if(t.pattern){n.patterns??(n.patterns=new Set);n.patterns.add(t.pattern)}}));if(t.pattern)(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0;if(t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}));const $ZodCheckRegex=$constructor("$ZodCheckRegex",((e,t)=>{$ZodCheckStringFormat.init(e,t);e._zod.check=n=>{t.pattern.lastIndex=0;if(t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}));const $ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",((e,t)=>{t.pattern??(t.pattern=lowercase);$ZodCheckStringFormat.init(e,t)}));const $ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",((e,t)=>{t.pattern??(t.pattern=uppercase);$ZodCheckStringFormat.init(e,t)}));const $ZodCheckIncludes=$constructor("$ZodCheckIncludes",((e,t)=>{$ZodCheck.init(e,t);const n=escapeRegex(t.includes);const r=new RegExp(typeof t.position==="number"?`^.{${t.position}}${n}`:n);t.pattern=r;e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set);t.patterns.add(r)}));e._zod.check=n=>{if(n.value.includes(t.includes,t.position))return;n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}));const $ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",((e,t)=>{$ZodCheck.init(e,t);const n=new RegExp(`^${escapeRegex(t.prefix)}.*`);t.pattern??(t.pattern=n);e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set);t.patterns.add(n)}));e._zod.check=n=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}));const $ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",((e,t)=>{$ZodCheck.init(e,t);const n=new RegExp(`.*${escapeRegex(t.suffix)}$`);t.pattern??(t.pattern=n);e._zod.onattach.push((e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set);t.patterns.add(n)}));e._zod.check=n=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}));const $ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",((e,t)=>{$ZodCheck.init(e,t);e._zod.check=e=>{e.value=t.tx(e.value)}}));class Doc{constructor(e=[]){this.content=[];this.indent=0;if(this)this.args=e}indented(e){this.indent+=1;e(this);this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"});e(this,{execution:"async"});return}const t=e;const n=t.split("\n").filter((e=>e));const r=Math.min(...n.map((e=>e.length-e.trimStart().length)));const o=n.map((e=>e.slice(r))).map((e=>" ".repeat(this.indent*2)+e));for(const e of o){this.content.push(e)}}compile(){const e=Function;const t=this?.args;const n=this?.content??[``];const r=[...n.map((e=>` ${e}`))];return new e(...t,r.join("\n"))}}const version={major:4,minor:3,patch:6};const $ZodType=$constructor("$ZodType",((e,t)=>{var n;e??(e={});e._zod.def=t;e._zod.bag=e._zod.bag||{};e._zod.version=version;const r=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck")){r.unshift(e)}for(const t of r){for(const n of t._zod.onattach){n(e)}}if(r.length===0){(n=e._zod).deferred??(n.deferred=[]);e._zod.deferred?.push((()=>{e._zod.run=e._zod.parse}))}else{const t=(e,t,n)=>{let r=aborted(e);let o;for(const i of t){if(i._zod.def.when){const t=i._zod.def.when(e);if(!t)continue}else if(r){continue}const t=e.issues.length;const s=i._zod.check(e);if(s instanceof Promise&&n?.async===false){throw new $ZodAsyncError}if(o||s instanceof Promise){o=(o??Promise.resolve()).then((async()=>{await s;const n=e.issues.length;if(n===t)return;if(!r)r=aborted(e,t)}))}else{const n=e.issues.length;if(n===t)continue;if(!r)r=aborted(e,t)}}if(o){return o.then((()=>e))}return e};const n=(n,o,i)=>{if(aborted(n)){n.aborted=true;return n}const s=t(o,r,i);if(s instanceof Promise){if(i.async===false)throw new $ZodAsyncError;return s.then((t=>e._zod.parse(t,i)))}return e._zod.parse(s,i)};e._zod.run=(o,i)=>{if(i.skipChecks){return e._zod.parse(o,i)}if(i.direction==="backward"){const t=e._zod.parse({value:o.value,issues:[]},{...i,skipChecks:true});if(t instanceof Promise){return t.then((e=>n(e,o,i)))}return n(t,o,i)}const s=e._zod.parse(o,i);if(s instanceof Promise){if(i.async===false)throw new $ZodAsyncError;return s.then((e=>t(e,r,i)))}return t(s,r,i)}}defineLazy(e,"~standard",(()=>({validate:t=>{try{const n=safeParse$1(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return safeParseAsync$1(e,t).then((e=>e.success?{value:e.data}:{issues:e.error?.issues}))}},vendor:"zod",version:1})))}));const $ZodString=$constructor("$ZodString",((e,t)=>{$ZodType.init(e,t);e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??string$1(e._zod.bag);e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}if(typeof n.value==="string")return n;n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e});return n}}));const $ZodStringFormat=$constructor("$ZodStringFormat",((e,t)=>{$ZodCheckStringFormat.init(e,t);$ZodString.init(e,t)}));const $ZodGUID=$constructor("$ZodGUID",((e,t)=>{t.pattern??(t.pattern=guid);$ZodStringFormat.init(e,t)}));const $ZodUUID=$constructor("$ZodUUID",((e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8};const n=e[t.version];if(n===undefined)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=uuid(n))}else t.pattern??(t.pattern=uuid());$ZodStringFormat.init(e,t)}));const $ZodEmail=$constructor("$ZodEmail",((e,t)=>{t.pattern??(t.pattern=email);$ZodStringFormat.init(e,t)}));const $ZodURL=$constructor("$ZodURL",((e,t)=>{$ZodStringFormat.init(e,t);e._zod.check=n=>{try{const r=n.value.trim();const o=new URL(r);if(t.hostname){t.hostname.lastIndex=0;if(!t.hostname.test(o.hostname)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})}}if(t.protocol){t.protocol.lastIndex=0;if(!t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})}}if(t.normalize){n.value=o.href}else{n.value=r}return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}));const $ZodEmoji=$constructor("$ZodEmoji",((e,t)=>{t.pattern??(t.pattern=emoji());$ZodStringFormat.init(e,t)}));const $ZodNanoID=$constructor("$ZodNanoID",((e,t)=>{t.pattern??(t.pattern=nanoid);$ZodStringFormat.init(e,t)}));const $ZodCUID=$constructor("$ZodCUID",((e,t)=>{t.pattern??(t.pattern=cuid);$ZodStringFormat.init(e,t)}));const $ZodCUID2=$constructor("$ZodCUID2",((e,t)=>{t.pattern??(t.pattern=cuid2);$ZodStringFormat.init(e,t)}));const $ZodULID=$constructor("$ZodULID",((e,t)=>{t.pattern??(t.pattern=ulid);$ZodStringFormat.init(e,t)}));const $ZodXID=$constructor("$ZodXID",((e,t)=>{t.pattern??(t.pattern=xid);$ZodStringFormat.init(e,t)}));const $ZodKSUID=$constructor("$ZodKSUID",((e,t)=>{t.pattern??(t.pattern=ksuid);$ZodStringFormat.init(e,t)}));const $ZodISODateTime=$constructor("$ZodISODateTime",((e,t)=>{t.pattern??(t.pattern=datetime$1(t));$ZodStringFormat.init(e,t)}));const $ZodISODate=$constructor("$ZodISODate",((e,t)=>{t.pattern??(t.pattern=date$1);$ZodStringFormat.init(e,t)}));const $ZodISOTime=$constructor("$ZodISOTime",((e,t)=>{t.pattern??(t.pattern=time$1(t));$ZodStringFormat.init(e,t)}));const $ZodISODuration=$constructor("$ZodISODuration",((e,t)=>{t.pattern??(t.pattern=duration$1);$ZodStringFormat.init(e,t)}));const $ZodIPv4=$constructor("$ZodIPv4",((e,t)=>{t.pattern??(t.pattern=ipv4);$ZodStringFormat.init(e,t);e._zod.bag.format=`ipv4`}));const $ZodIPv6=$constructor("$ZodIPv6",((e,t)=>{t.pattern??(t.pattern=ipv6);$ZodStringFormat.init(e,t);e._zod.bag.format=`ipv6`;e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}));const $ZodCIDRv4=$constructor("$ZodCIDRv4",((e,t)=>{t.pattern??(t.pattern=cidrv4);$ZodStringFormat.init(e,t)}));const $ZodCIDRv6=$constructor("$ZodCIDRv6",((e,t)=>{t.pattern??(t.pattern=cidrv6);$ZodStringFormat.init(e,t);e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}}));function isValidBase64(e){if(e==="")return true;if(e.length%4!==0)return false;try{atob(e);return true}catch{return false}}const $ZodBase64=$constructor("$ZodBase64",((e,t)=>{t.pattern??(t.pattern=base64);$ZodStringFormat.init(e,t);e._zod.bag.contentEncoding="base64";e._zod.check=n=>{if(isValidBase64(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}));function isValidBase64URL(e){if(!base64url.test(e))return false;const t=e.replace(/[-_]/g,(e=>e==="-"?"+":"/"));const n=t.padEnd(Math.ceil(t.length/4)*4,"=");return isValidBase64(n)}const $ZodBase64URL=$constructor("$ZodBase64URL",((e,t)=>{t.pattern??(t.pattern=base64url);$ZodStringFormat.init(e,t);e._zod.bag.contentEncoding="base64url";e._zod.check=n=>{if(isValidBase64URL(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}));const $ZodE164=$constructor("$ZodE164",((e,t)=>{t.pattern??(t.pattern=e164);$ZodStringFormat.init(e,t)}));function isValidJWT(e,t=null){try{const n=e.split(".");if(n.length!==3)return false;const[r]=n;if(!r)return false;const o=JSON.parse(atob(r));if("typ"in o&&o?.typ!=="JWT")return false;if(!o.alg)return false;if(t&&(!("alg"in o)||o.alg!==t))return false;return true}catch{return false}}const $ZodJWT=$constructor("$ZodJWT",((e,t)=>{$ZodStringFormat.init(e,t);e._zod.check=n=>{if(isValidJWT(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}));const $ZodNumber=$constructor("$ZodNumber",((e,t)=>{$ZodType.init(e,t);e._zod.pattern=e._zod.bag.pattern??number$1;e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const o=n.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o)){return n}const i=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?"Infinity":undefined:undefined;n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}});return n}}));const $ZodNumberFormat=$constructor("$ZodNumberFormat",((e,t)=>{$ZodCheckNumberFormat.init(e,t);$ZodNumber.init(e,t)}));const $ZodBoolean=$constructor("$ZodBoolean",((e,t)=>{$ZodType.init(e,t);e._zod.pattern=boolean$1;e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const o=n.value;if(typeof o==="boolean")return n;n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e});return n}}));const $ZodUnknown=$constructor("$ZodUnknown",((e,t)=>{$ZodType.init(e,t);e._zod.parse=e=>e}));const $ZodNever=$constructor("$ZodNever",((e,t)=>{$ZodType.init(e,t);e._zod.parse=(t,n)=>{t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e});return t}}));function handleArrayResult(e,t,n){if(e.issues.length){t.issues.push(...prefixIssues(n,e.issues))}t.value[n]=e.value}const $ZodArray=$constructor("$ZodArray",((e,t)=>{$ZodType.init(e,t);e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o)){n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e});return n}n.value=Array(o.length);const i=[];for(let e=0;e<o.length;e++){const s=o[e];const a=t.element._zod.run({value:s,issues:[]},r);if(a instanceof Promise){i.push(a.then((t=>handleArrayResult(t,n,e))))}else{handleArrayResult(a,n,e)}}if(i.length){return Promise.all(i).then((()=>n))}return n}}));function handlePropertyResult(e,t,n,r,o){if(e.issues.length){if(o&&!(n in r)){return}t.issues.push(...prefixIssues(n,e.issues))}if(e.value===undefined){if(n in r){t.value[n]=undefined}}else{t.value[n]=e.value}}function normalizeDef(e){const t=Object.keys(e.shape);for(const n of t){if(!e.shape?.[n]?._zod?.traits?.has("$ZodType")){throw new Error(`Invalid element at key "${n}": expected a Zod schema`)}}const n=optionalKeys(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function handleCatchall(e,t,n,r,o,i){const s=[];const a=o.keySet;const c=o.catchall._zod;const u=c.def.type;const l=c.optout==="optional";for(const o in t){if(a.has(o))continue;if(u==="never"){s.push(o);continue}const i=c.run({value:t[o],issues:[]},r);if(i instanceof Promise){e.push(i.then((e=>handlePropertyResult(e,n,o,t,l))))}else{handlePropertyResult(i,n,o,t,l)}}if(s.length){n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i})}if(!e.length)return n;return Promise.all(e).then((()=>n))}const $ZodObject=$constructor("$ZodObject",((e,t)=>{$ZodType.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};Object.defineProperty(t,"shape",{value:n});return n}})}const r=cached((()=>normalizeDef(t)));defineLazy(e._zod,"propValues",(()=>{const e=t.shape;const n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n}));const o=isObject;const i=t.catchall;let s;e._zod.parse=(t,n)=>{s??(s=r.value);const a=t.value;if(!o(a)){t.issues.push({expected:"object",code:"invalid_type",input:a,inst:e});return t}t.value={};const c=[];const u=s.shape;for(const e of s.keys){const r=u[e];const o=r._zod.optout==="optional";const i=r._zod.run({value:a[e],issues:[]},n);if(i instanceof Promise){c.push(i.then((n=>handlePropertyResult(n,t,e,a,o))))}else{handlePropertyResult(i,t,e,a,o)}}if(!i){return c.length?Promise.all(c).then((()=>t)):t}return handleCatchall(c,a,t,n,r.value,e)}}));const $ZodObjectJIT=$constructor("$ZodObjectJIT",((e,t)=>{$ZodObject.init(e,t);const n=e._zod.parse;const r=cached((()=>normalizeDef(t)));const o=e=>{const t=new Doc(["shape","payload","ctx"]);const n=r.value;const o=e=>{const t=esc(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);const i=Object.create(null);let s=0;for(const e of n.keys){i[e]=`key_${s++}`}t.write(`const newResult = {};`);for(const r of n.keys){const n=i[r];const s=esc(r);const a=e[r];const c=a?._zod?.optout==="optional";t.write(`const ${n} = ${o(r)};`);if(c){t.write(`\n if (${n}.issues.length) {\n if (${s} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `)}else{t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `)}}t.write(`payload.value = newResult;`);t.write(`return payload;`);const a=t.compile();return(t,n)=>a(e,t,n)};let i;const s=isObject;const a=!globalConfig.jitless;const c=allowsEval;const u=a&&c.value;const l=t.catchall;let f;e._zod.parse=(c,d)=>{f??(f=r.value);const h=c.value;if(!s(h)){c.issues.push({expected:"object",code:"invalid_type",input:h,inst:e});return c}if(a&&u&&d?.async===false&&d.jitless!==true){if(!i)i=o(t.shape);c=i(c,d);if(!l)return c;return handleCatchall([],h,c,d,f,e)}return n(c,d)}}));function handleUnionResults(e,t,n,r){for(const n of e){if(n.issues.length===0){t.value=n.value;return t}}const o=e.filter((e=>!aborted(e)));if(o.length===1){t.value=o[0].value;return o[0]}t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((e=>e.issues.map((e=>finalizeIssue(e,r,config())))))});return t}const $ZodUnion=$constructor("$ZodUnion",((e,t)=>{$ZodType.init(e,t);defineLazy(e._zod,"optin",(()=>t.options.some((e=>e._zod.optin==="optional"))?"optional":undefined));defineLazy(e._zod,"optout",(()=>t.options.some((e=>e._zod.optout==="optional"))?"optional":undefined));defineLazy(e._zod,"values",(()=>{if(t.options.every((e=>e._zod.values))){return new Set(t.options.flatMap((e=>Array.from(e._zod.values))))}return undefined}));defineLazy(e._zod,"pattern",(()=>{if(t.options.every((e=>e._zod.pattern))){const e=t.options.map((e=>e._zod.pattern));return new RegExp(`^(${e.map((e=>cleanRegex(e.source))).join("|")})$`)}return undefined}));const n=t.options.length===1;const r=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(n){return r(o,i)}let s=false;const a=[];for(const e of t.options){const t=e._zod.run({value:o.value,issues:[]},i);if(t instanceof Promise){a.push(t);s=true}else{if(t.issues.length===0)return t;a.push(t)}}if(!s)return handleUnionResults(a,o,e,i);return Promise.all(a).then((t=>handleUnionResults(t,o,e,i)))}}));const $ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",((e,t)=>{t.inclusive=false;$ZodUnion.init(e,t);const n=e._zod.parse;defineLazy(e._zod,"propValues",(()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){if(!e[t])e[t]=new Set;for(const r of n){e[t].add(r)}}}return e}));const r=cached((()=>{const e=t.options;const n=new Map;for(const r of e){const e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const t of e){if(n.has(t)){throw new Error(`Duplicate discriminator value "${String(t)}"`)}n.set(t,r)}}return n}));e._zod.parse=(o,i)=>{const s=o.value;if(!isObject(s)){o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e});return o}const a=r.value.get(s?.[t.discriminator]);if(a){return a._zod.run(o,i)}if(t.unionFallback){return n(o,i)}o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e});return o}}));const $ZodIntersection=$constructor("$ZodIntersection",((e,t)=>{$ZodType.init(e,t);e._zod.parse=(e,n)=>{const r=e.value;const o=t.left._zod.run({value:r,issues:[]},n);const i=t.right._zod.run({value:r,issues:[]},n);const s=o instanceof Promise||i instanceof Promise;if(s){return Promise.all([o,i]).then((([t,n])=>handleIntersectionResults(e,t,n)))}return handleIntersectionResults(e,o,i)}}));function mergeValues(e,t){if(e===t){return{valid:true,data:e}}if(e instanceof Date&&t instanceof Date&&+e===+t){return{valid:true,data:e}}if(isPlainObject(e)&&isPlainObject(t)){const n=Object.keys(t);const r=Object.keys(e).filter((e=>n.indexOf(e)!==-1));const o={...e,...t};for(const n of r){const r=mergeValues(e[n],t[n]);if(!r.valid){return{valid:false,mergeErrorPath:[n,...r.mergeErrorPath]}}o[n]=r.data}return{valid:true,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length){return{valid:false,mergeErrorPath:[]}}const n=[];for(let r=0;r<e.length;r++){const o=e[r];const i=t[r];const s=mergeValues(o,i);if(!s.valid){return{valid:false,mergeErrorPath:[r,...s.mergeErrorPath]}}n.push(s.data)}return{valid:true,data:n}}return{valid:false,mergeErrorPath:[]}}function handleIntersectionResults(e,t,n){const r=new Map;let o;for(const n of t.issues){if(n.code==="unrecognized_keys"){o??(o=n);for(const e of n.keys){if(!r.has(e))r.set(e,{});r.get(e).l=true}}else{e.issues.push(n)}}for(const t of n.issues){if(t.code==="unrecognized_keys"){for(const e of t.keys){if(!r.has(e))r.set(e,{});r.get(e).r=true}}else{e.issues.push(t)}}const i=[...r].filter((([,e])=>e.l&&e.r)).map((([e])=>e));if(i.length&&o){e.issues.push({...o,keys:i})}if(aborted(e))return e;const s=mergeValues(t.value,n.value);if(!s.valid){throw new Error(`Unmergable intersection. Error path: `+`${JSON.stringify(s.mergeErrorPath)}`)}e.value=s.data;return e}const $ZodEnum=$constructor("$ZodEnum",((e,t)=>{$ZodType.init(e,t);const n=getEnumValues(t.entries);const r=new Set(n);e._zod.values=r;e._zod.pattern=new RegExp(`^(${n.filter((e=>propertyKeyTypes.has(typeof e))).map((e=>typeof e==="string"?escapeRegex(e):e.toString())).join("|")})$`);e._zod.parse=(t,o)=>{const i=t.value;if(r.has(i)){return t}t.issues.push({code:"invalid_value",values:n,input:i,inst:e});return t}}));const $ZodLiteral=$constructor("$ZodLiteral",((e,t)=>{$ZodType.init(e,t);if(t.values.length===0){throw new Error("Cannot create literal schema with no valid values")}const n=new Set(t.values);e._zod.values=n;e._zod.pattern=new RegExp(`^(${t.values.map((e=>typeof e==="string"?escapeRegex(e):e?escapeRegex(e.toString()):String(e))).join("|")})$`);e._zod.parse=(r,o)=>{const i=r.value;if(n.has(i)){return r}r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e});return r}}));const $ZodTransform=$constructor("$ZodTransform",((e,t)=>{$ZodType.init(e,t);e._zod.parse=(n,r)=>{if(r.direction==="backward"){throw new $ZodEncodeError(e.constructor.name)}const o=t.transform(n.value,n);if(r.async){const e=o instanceof Promise?o:Promise.resolve(o);return e.then((e=>{n.value=e;return n}))}if(o instanceof Promise){throw new $ZodAsyncError}n.value=o;return n}}));function handleOptionalResult(e,t){if(e.issues.length&&t===undefined){return{issues:[],value:undefined}}return e}const $ZodOptional=$constructor("$ZodOptional",((e,t)=>{$ZodType.init(e,t);e._zod.optin="optional";e._zod.optout="optional";defineLazy(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,undefined]):undefined));defineLazy(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${cleanRegex(e.source)})?$`):undefined}));e._zod.parse=(e,n)=>{if(t.innerType._zod.optin==="optional"){const r=t.innerType._zod.run(e,n);if(r instanceof Promise)return r.then((t=>handleOptionalResult(t,e.value)));return handleOptionalResult(r,e.value)}if(e.value===undefined){return e}return t.innerType._zod.run(e,n)}}));const $ZodExactOptional=$constructor("$ZodExactOptional",((e,t)=>{$ZodOptional.init(e,t);defineLazy(e._zod,"values",(()=>t.innerType._zod.values));defineLazy(e._zod,"pattern",(()=>t.innerType._zod.pattern));e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}));const $ZodNullable=$constructor("$ZodNullable",((e,t)=>{$ZodType.init(e,t);defineLazy(e._zod,"optin",(()=>t.innerType._zod.optin));defineLazy(e._zod,"optout",(()=>t.innerType._zod.optout));defineLazy(e._zod,"pattern",(()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${cleanRegex(e.source)}|null)$`):undefined}));defineLazy(e._zod,"values",(()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):undefined));e._zod.parse=(e,n)=>{if(e.value===null)return e;return t.innerType._zod.run(e,n)}}));const $ZodDefault=$constructor("$ZodDefault",((e,t)=>{$ZodType.init(e,t);e._zod.optin="optional";defineLazy(e._zod,"values",(()=>t.innerType._zod.values));e._zod.parse=(e,n)=>{if(n.direction==="backward"){return t.innerType._zod.run(e,n)}if(e.value===undefined){e.value=t.defaultValue;return e}const r=t.innerType._zod.run(e,n);if(r instanceof Promise){return r.then((e=>handleDefaultResult(e,t)))}return handleDefaultResult(r,t)}}));function handleDefaultResult(e,t){if(e.value===undefined){e.value=t.defaultValue}return e}const $ZodPrefault=$constructor("$ZodPrefault",((e,t)=>{$ZodType.init(e,t);e._zod.optin="optional";defineLazy(e._zod,"values",(()=>t.innerType._zod.values));e._zod.parse=(e,n)=>{if(n.direction==="backward"){return t.innerType._zod.run(e,n)}if(e.value===undefined){e.value=t.defaultValue}return t.innerType._zod.run(e,n)}}));const $ZodNonOptional=$constructor("$ZodNonOptional",((e,t)=>{$ZodType.init(e,t);defineLazy(e._zod,"values",(()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter((e=>e!==undefined))):undefined}));e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);if(o instanceof Promise){return o.then((t=>handleNonOptionalResult(t,e)))}return handleNonOptionalResult(o,e)}}));function handleNonOptionalResult(e,t){if(!e.issues.length&&e.value===undefined){e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t})}return e}const $ZodCatch=$constructor("$ZodCatch",((e,t)=>{$ZodType.init(e,t);defineLazy(e._zod,"optin",(()=>t.innerType._zod.optin));defineLazy(e._zod,"optout",(()=>t.innerType._zod.optout));defineLazy(e._zod,"values",(()=>t.innerType._zod.values));e._zod.parse=(e,n)=>{if(n.direction==="backward"){return t.innerType._zod.run(e,n)}const r=t.innerType._zod.run(e,n);if(r instanceof Promise){return r.then((r=>{e.value=r.value;if(r.issues.length){e.value=t.catchValue({...e,error:{issues:r.issues.map((e=>finalizeIssue(e,n,config())))},input:e.value});e.issues=[]}return e}))}e.value=r.value;if(r.issues.length){e.value=t.catchValue({...e,error:{issues:r.issues.map((e=>finalizeIssue(e,n,config())))},input:e.value});e.issues=[]}return e}}));const $ZodPipe=$constructor("$ZodPipe",((e,t)=>{$ZodType.init(e,t);defineLazy(e._zod,"values",(()=>t.in._zod.values));defineLazy(e._zod,"optin",(()=>t.in._zod.optin));defineLazy(e._zod,"optout",(()=>t.out._zod.optout));defineLazy(e._zod,"propValues",(()=>t.in._zod.propValues));e._zod.parse=(e,n)=>{if(n.direction==="backward"){const r=t.out._zod.run(e,n);if(r instanceof Promise){return r.then((e=>handlePipeResult(e,t.in,n)))}return handlePipeResult(r,t.in,n)}const r=t.in._zod.run(e,n);if(r instanceof Promise){return r.then((e=>handlePipeResult(e,t.out,n)))}return handlePipeResult(r,t.out,n)}}));function handlePipeResult(e,t,n){if(e.issues.length){e.aborted=true;return e}return t._zod.run({value:e.value,issues:e.issues},n)}const $ZodReadonly=$constructor("$ZodReadonly",((e,t)=>{$ZodType.init(e,t);defineLazy(e._zod,"propValues",(()=>t.innerType._zod.propValues));defineLazy(e._zod,"values",(()=>t.innerType._zod.values));defineLazy(e._zod,"optin",(()=>t.innerType?._zod?.optin));defineLazy(e._zod,"optout",(()=>t.innerType?._zod?.optout));e._zod.parse=(e,n)=>{if(n.direction==="backward"){return t.innerType._zod.run(e,n)}const r=t.innerType._zod.run(e,n);if(r instanceof Promise){return r.then(handleReadonlyResult)}return handleReadonlyResult(r)}}));function handleReadonlyResult(e){e.value=Object.freeze(e.value);return e}const $ZodCustom=$constructor("$ZodCustom",((e,t)=>{$ZodCheck.init(e,t);$ZodType.init(e,t);e._zod.parse=(e,t)=>e;e._zod.check=n=>{const r=n.value;const o=t.fn(r);if(o instanceof Promise){return o.then((t=>handleRefineResult(t,n,r,e)))}handleRefineResult(o,n,r,e);return}}));function handleRefineResult(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)e.params=r._zod.def.params;t.issues.push(issue(e))}}var _a;class $ZodRegistry{constructor(){this._map=new WeakMap;this._idmap=new Map}add(e,...t){const n=t[0];this._map.set(e,n);if(n&&typeof n==="object"&&"id"in n){this._idmap.set(n.id,e)}return this}clear(){this._map=new WeakMap;this._idmap=new Map;return this}remove(e){const t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t){this._idmap.delete(t.id)}this._map.delete(e);return this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:undefined}return this._map.get(e)}has(e){return this._map.has(e)}}function registry(){return new $ZodRegistry}(_a=globalThis).__zod_globalRegistry??(_a.__zod_globalRegistry=registry());const globalRegistry=globalThis.__zod_globalRegistry;function _string(e,t){return new e({type:"string",...normalizeParams(t)})}function _email(e,t){return new e({type:"string",format:"email",check:"string_format",abort:false,...normalizeParams(t)})}function _guid(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:false,...normalizeParams(t)})}function _uuid(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:false,...normalizeParams(t)})}function _uuidv4(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:false,version:"v4",...normalizeParams(t)})}function _uuidv6(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:false,version:"v6",...normalizeParams(t)})}function _uuidv7(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:false,version:"v7",...normalizeParams(t)})}function _url(e,t){return new e({type:"string",format:"url",check:"string_format",abort:false,...normalizeParams(t)})}function _emoji(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:false,...normalizeParams(t)})}function _nanoid(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:false,...normalizeParams(t)})}function _cuid(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:false,...normalizeParams(t)})}function _cuid2(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:false,...normalizeParams(t)})}function _ulid(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:false,...normalizeParams(t)})}function _xid(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:false,...normalizeParams(t)})}function _ksuid(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:false,...normalizeParams(t)})}function _ipv4(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:false,...normalizeParams(t)})}function _ipv6(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:false,...normalizeParams(t)})}function _cidrv4(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:false,...normalizeParams(t)})}function _cidrv6(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:false,...normalizeParams(t)})}function _base64(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:false,...normalizeParams(t)})}function _base64url(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:false,...normalizeParams(t)})}function _e164(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:false,...normalizeParams(t)})}function _jwt(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:false,...normalizeParams(t)})}function _isoDateTime(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:false,local:false,precision:null,...normalizeParams(t)})}function _isoDate(e,t){return new e({type:"string",format:"date",check:"string_format",...normalizeParams(t)})}function _isoTime(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(t)})}function _isoDuration(e,t){return new e({type:"string",format:"duration",check:"string_format",...normalizeParams(t)})}function _number(e,t){return new e({type:"number",checks:[],...normalizeParams(t)})}function _int(e,t){return new e({type:"number",check:"number_format",abort:false,format:"safeint",...normalizeParams(t)})}function _boolean(e,t){return new e({type:"boolean",...normalizeParams(t)})}function _unknown(e){return new e({type:"unknown"})}function _never(e,t){return new e({type:"never",...normalizeParams(t)})}function _lt(e,t){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(t),value:e,inclusive:false})}function _lte(e,t){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(t),value:e,inclusive:true})}function _gt(e,t){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(t),value:e,inclusive:false})}function _gte(e,t){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(t),value:e,inclusive:true})}function _multipleOf(e,t){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(t),value:e})}function _maxLength(e,t){const n=new $ZodCheckMaxLength({check:"max_length",...normalizeParams(t),maximum:e});return n}function _minLength(e,t){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(t),minimum:e})}function _length(e,t){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(t),length:e})}function _regex(e,t){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(t),pattern:e})}function _lowercase(e){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(e)})}function _uppercase(e){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(e)})}function _includes(e,t){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(t),includes:e})}function _startsWith(e,t){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(t),prefix:e})}function _endsWith(e,t){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(t),suffix:e})}function _overwrite(e){return new $ZodCheckOverwrite({check:"overwrite",tx:e})}function _normalize(e){return _overwrite((t=>t.normalize(e)))}function _trim(){return _overwrite((e=>e.trim()))}function _toLowerCase(){return _overwrite((e=>e.toLowerCase()))}function _toUpperCase(){return _overwrite((e=>e.toUpperCase()))}function _slugify(){return _overwrite((e=>slugify(e)))}function _array(e,t,n){return new e({type:"array",element:t,...normalizeParams(n)})}function _custom(e,t,n){const r=normalizeParams(n);r.abort??(r.abort=true);const o=new e({type:"custom",check:"custom",fn:t,...r});return o}function _refine(e,t,n){const r=new e({type:"custom",check:"custom",fn:t,...normalizeParams(n)});return r}function _superRefine(e){const t=_check((n=>{n.addIssue=e=>{if(typeof e==="string"){n.issues.push(issue(e,n.value,t._zod.def))}else{const r=e;if(r.fatal)r.continue=false;r.code??(r.code="custom");r.input??(r.input=n.value);r.inst??(r.inst=t);r.continue??(r.continue=!t._zod.def.abort);n.issues.push(issue(r))}};return e(n.value,n)}));return t}function _check(e,t){const n=new $ZodCheck({check:"custom",...normalizeParams(t)});n._zod.check=e;return n}function initializeContext(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??globalRegistry,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??undefined}}function process$1(e,t,n={path:[],schemaPath:[]}){var r;const o=e._zod.def;const i=t.seen.get(e);if(i){i.count++;const t=n.schemaPath.includes(e);if(t){i.cycle=n.path}return i.schema}const s={schema:{},count:1,cycle:undefined,path:n.path};t.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a){s.schema=a}else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema){e._zod.processJSONSchema(t,s.schema,r)}else{const n=s.schema;const i=t.processors[o.type];if(!i){throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`)}i(e,t,n,r)}const i=e._zod.parent;if(i){if(!s.ref)s.ref=i;process$1(i,t,r);t.seen.get(i).isParent=true}}const c=t.metadataRegistry.get(e);if(c)Object.assign(s.schema,c);if(t.io==="input"&&isTransforming(e)){delete s.schema.examples;delete s.schema.default}if(t.io==="input"&&s.schema._prefault)(r=s.schema).default??(r.default=s.schema._prefault);delete s.schema._prefault;const u=t.seen.get(e);return u.schema}function extractDefs(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=r.get(n);if(e&&e!==t[0]){throw new Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`)}r.set(n,t[0])}}const o=t=>{const r=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id;const o=e.external.uri??(e=>e);if(n){return{ref:o(n)}}const i=t[1].defId??t[1].schema.id??`schema${e.counter++}`;t[1].defId=i;return{defId:i,ref:`${o("__shared")}#/${r}/${i}`}}if(t[1]===n){return{ref:"#"}}const o=`#`;const i=`${o}/${r}/`;const s=t[1].schema.id??`__schema${e.counter++}`;return{defId:s,ref:i+s}};const i=e=>{if(e[1].schema.$ref){return}const t=e[1];const{ref:n,defId:r}=o(e);t.def={...t.schema};if(r)t.defId=r;const i=t.schema;for(const e in i){delete i[e]}i.$ref=n};if(e.cycles==="throw"){for(const t of e.seen.entries()){const e=t[1];if(e.cycle){throw new Error("Cycle detected: "+`#/${e.cycle?.join("/")}/<root>`+'\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.')}}}for(const n of e.seen.entries()){const r=n[1];if(t===n[0]){i(n);continue}if(e.external){const r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){i(n);continue}}const o=e.metadataRegistry.get(n[0])?.id;if(o){i(n);continue}if(r.cycle){i(n);continue}if(r.count>1){if(e.reused==="ref"){i(n);continue}}}}function finalize(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(n.ref===null)return;const o=n.def??n.schema;const i={...o};const s=n.ref;n.ref=null;if(s){r(s);const n=e.seen.get(s);const a=n.schema;if(a.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")){o.allOf=o.allOf??[];o.allOf.push(a)}else{Object.assign(o,a)}Object.assign(o,i);const c=t._zod.parent===s;if(c){for(const e in o){if(e==="$ref"||e==="allOf")continue;if(!(e in i)){delete o[e]}}}if(a.$ref&&n.def){for(const e in o){if(e==="$ref"||e==="allOf")continue;if(e in n.def&&JSON.stringify(o[e])===JSON.stringify(n.def[e])){delete o[e]}}}}const a=t._zod.parent;if(a&&a!==s){r(a);const t=e.seen.get(a);if(t?.schema.$ref){o.$ref=t.schema.$ref;if(t.def){for(const e in o){if(e==="$ref"||e==="allOf")continue;if(e in t.def&&JSON.stringify(o[e])===JSON.stringify(t.def[e])){delete o[e]}}}}}e.override({zodSchema:t,jsonSchema:o,path:n.path??[]})};for(const t of[...e.seen.entries()].reverse()){r(t[0])}const o={};if(e.target==="draft-2020-12"){o.$schema="https://json-schema.org/draft/2020-12/schema"}else if(e.target==="draft-07"){o.$schema="http://json-schema.org/draft-07/schema#"}else if(e.target==="draft-04"){o.$schema="http://json-schema.org/draft-04/schema#"}else;if(e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(n)}Object.assign(o,n.def??n.schema);const i=e.external?.defs??{};for(const t of e.seen.entries()){const e=t[1];if(e.def&&e.defId){i[e.defId]=e.def}}if(e.external);else{if(Object.keys(i).length>0){if(e.target==="draft-2020-12"){o.$defs=i}else{o.definitions=i}}}try{const n=JSON.parse(JSON.stringify(o));Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(t,"input",e.processors),output:createStandardJSONSchemaMethod(t,"output",e.processors)}},enumerable:false,writable:false});return n}catch(e){throw new Error("Error converting schema to JSON.")}}function isTransforming(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return false;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return true;if(r.type==="array")return isTransforming(r.element,n);if(r.type==="set")return isTransforming(r.valueType,n);if(r.type==="lazy")return isTransforming(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"){return isTransforming(r.innerType,n)}if(r.type==="intersection"){return isTransforming(r.left,n)||isTransforming(r.right,n)}if(r.type==="record"||r.type==="map"){return isTransforming(r.keyType,n)||isTransforming(r.valueType,n)}if(r.type==="pipe"){return isTransforming(r.in,n)||isTransforming(r.out,n)}if(r.type==="object"){for(const e in r.shape){if(isTransforming(r.shape[e],n))return true}return false}if(r.type==="union"){for(const e of r.options){if(isTransforming(e,n))return true}return false}if(r.type==="tuple"){for(const e of r.items){if(isTransforming(e,n))return true}if(r.rest&&isTransforming(r.rest,n))return true;return false}return false}const createToJSONSchemaMethod=(e,t={})=>n=>{const r=initializeContext({...n,processors:t});process$1(e,r);extractDefs(r,e);return finalize(r,e)};const createStandardJSONSchemaMethod=(e,t,n={})=>r=>{const{libraryOptions:o,target:i}=r??{};const s=initializeContext({...o??{},target:i,io:t,processors:n});process$1(e,s);extractDefs(s,e);return finalize(s,e)};const formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""};const stringProcessor=(e,t,n,r)=>{const o=n;o.type="string";const{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof i==="number")o.minLength=i;if(typeof s==="number")o.maxLength=s;if(a){o.format=formatMap[a]??a;if(o.format==="")delete o.format;if(a==="time"){delete o.format}}if(u)o.contentEncoding=u;if(c&&c.size>0){const e=[...c];if(e.length===1)o.pattern=e[0].source;else if(e.length>1){o.allOf=[...e.map((e=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:e.source})))]}}};const numberProcessor=(e,t,n,r)=>{const o=n;const{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))o.type="integer";else o.type="number";if(typeof l==="number"){if(t.target==="draft-04"||t.target==="openapi-3.0"){o.minimum=l;o.exclusiveMinimum=true}else{o.exclusiveMinimum=l}}if(typeof i==="number"){o.minimum=i;if(typeof l==="number"&&t.target!=="draft-04"){if(l>=i)delete o.minimum;else delete o.exclusiveMinimum}}if(typeof u==="number"){if(t.target==="draft-04"||t.target==="openapi-3.0"){o.maximum=u;o.exclusiveMaximum=true}else{o.exclusiveMaximum=u}}if(typeof s==="number"){o.maximum=s;if(typeof u==="number"&&t.target!=="draft-04"){if(u<=s)delete o.maximum;else delete o.exclusiveMaximum}}if(typeof c==="number")o.multipleOf=c};const booleanProcessor=(e,t,n,r)=>{n.type="boolean"};const neverProcessor=(e,t,n,r)=>{n.not={}};const unknownProcessor=(e,t,n,r)=>{};const enumProcessor=(e,t,n,r)=>{const o=e._zod.def;const i=getEnumValues(o.entries);if(i.every((e=>typeof e==="number")))n.type="number";if(i.every((e=>typeof e==="string")))n.type="string";n.enum=i};const literalProcessor=(e,t,n,r)=>{const o=e._zod.def;const i=[];for(const e of o.values){if(e===undefined){if(t.unrepresentable==="throw"){throw new Error("Literal `undefined` cannot be represented in JSON Schema")}}else if(typeof e==="bigint"){if(t.unrepresentable==="throw"){throw new Error("BigInt literals cannot be represented in JSON Schema")}else{i.push(Number(e))}}else{i.push(e)}}if(i.length===0);else if(i.length===1){const e=i[0];n.type=e===null?"null":typeof e;if(t.target==="draft-04"||t.target==="openapi-3.0"){n.enum=[e]}else{n.const=e}}else{if(i.every((e=>typeof e==="number")))n.type="number";if(i.every((e=>typeof e==="string")))n.type="string";if(i.every((e=>typeof e==="boolean")))n.type="boolean";if(i.every((e=>e===null)))n.type="null";n.enum=i}};const customProcessor=(e,t,n,r)=>{if(t.unrepresentable==="throw"){throw new Error("Custom types cannot be represented in JSON Schema")}};const transformProcessor=(e,t,n,r)=>{if(t.unrepresentable==="throw"){throw new Error("Transforms cannot be represented in JSON Schema")}};const arrayProcessor=(e,t,n,r)=>{const o=n;const i=e._zod.def;const{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")o.minItems=s;if(typeof a==="number")o.maxItems=a;o.type="array";o.items=process$1(i.element,t,{...r,path:[...r.path,"items"]})};const objectProcessor=(e,t,n,r)=>{const o=n;const i=e._zod.def;o.type="object";o.properties={};const s=i.shape;for(const e in s){o.properties[e]=process$1(s[e],t,{...r,path:[...r.path,"properties",e]})}const a=new Set(Object.keys(s));const c=new Set([...a].filter((e=>{const n=i.shape[e]._zod;if(t.io==="input"){return n.optin===undefined}else{return n.optout===undefined}})));if(c.size>0){o.required=Array.from(c)}if(i.catchall?._zod.def.type==="never"){o.additionalProperties=false}else if(!i.catchall){if(t.io==="output")o.additionalProperties=false}else if(i.catchall){o.additionalProperties=process$1(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})}};const unionProcessor=(e,t,n,r)=>{const o=e._zod.def;const i=o.inclusive===false;const s=o.options.map(((e,n)=>process$1(e,t,{...r,path:[...r.path,i?"oneOf":"anyOf",n]})));if(i){n.oneOf=s}else{n.anyOf=s}};const intersectionProcessor=(e,t,n,r)=>{const o=e._zod.def;const i=process$1(o.left,t,{...r,path:[...r.path,"allOf",0]});const s=process$1(o.right,t,{...r,path:[...r.path,"allOf",1]});const a=e=>"allOf"in e&&Object.keys(e).length===1;const c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=c};const nullableProcessor=(e,t,n,r)=>{const o=e._zod.def;const i=process$1(o.innerType,t,r);const s=t.seen.get(e);if(t.target==="openapi-3.0"){s.ref=o.innerType;n.nullable=true}else{n.anyOf=[i,{type:"null"}]}};const nonoptionalProcessor=(e,t,n,r)=>{const o=e._zod.def;process$1(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType};const defaultProcessor=(e,t,n,r)=>{const o=e._zod.def;process$1(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType;n.default=JSON.parse(JSON.stringify(o.defaultValue))};const prefaultProcessor=(e,t,n,r)=>{const o=e._zod.def;process$1(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType;if(t.io==="input")n._prefault=JSON.parse(JSON.stringify(o.defaultValue))};const catchProcessor=(e,t,n,r)=>{const o=e._zod.def;process$1(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(undefined)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s};const pipeProcessor=(e,t,n,r)=>{const o=e._zod.def;const i=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;process$1(i,t,r);const s=t.seen.get(e);s.ref=i};const readonlyProcessor=(e,t,n,r)=>{const o=e._zod.def;process$1(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType;n.readOnly=true};const optionalProcessor=(e,t,n,r)=>{const o=e._zod.def;process$1(o.innerType,t,r);const i=t.seen.get(e);i.ref=o.innerType};const ZodISODateTime=$constructor("ZodISODateTime",((e,t)=>{$ZodISODateTime.init(e,t);ZodStringFormat.init(e,t)}));function datetime(e){return _isoDateTime(ZodISODateTime,e)}const ZodISODate=$constructor("ZodISODate",((e,t)=>{$ZodISODate.init(e,t);ZodStringFormat.init(e,t)}));function date(e){return _isoDate(ZodISODate,e)}const ZodISOTime=$constructor("ZodISOTime",((e,t)=>{$ZodISOTime.init(e,t);ZodStringFormat.init(e,t)}));function time(e){return _isoTime(ZodISOTime,e)}const ZodISODuration=$constructor("ZodISODuration",((e,t)=>{$ZodISODuration.init(e,t);ZodStringFormat.init(e,t)}));function duration(e){return _isoDuration(ZodISODuration,e)}const initializer=(e,t)=>{$ZodError.init(e,t);e.name="ZodError";Object.defineProperties(e,{format:{value:t=>formatError(e,t)},flatten:{value:t=>flattenError(e,t)},addIssue:{value:t=>{e.issues.push(t);e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},addIssues:{value:t=>{e.issues.push(...t);e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return e.issues.length===0}}})};const ZodRealError=$constructor("ZodError",initializer,{Parent:Error});const parse=_parse(ZodRealError);const parseAsync=_parseAsync(ZodRealError);const safeParse=_safeParse(ZodRealError);const safeParseAsync=_safeParseAsync(ZodRealError);const encode=_encode(ZodRealError);const decode=_decode(ZodRealError);const encodeAsync=_encodeAsync(ZodRealError);const decodeAsync=_decodeAsync(ZodRealError);const safeEncode=_safeEncode(ZodRealError);const safeDecode=_safeDecode(ZodRealError);const safeEncodeAsync=_safeEncodeAsync(ZodRealError);const safeDecodeAsync=_safeDecodeAsync(ZodRealError);const ZodType=$constructor("ZodType",((e,t)=>{$ZodType.init(e,t);Object.assign(e["~standard"],{jsonSchema:{input:createStandardJSONSchemaMethod(e,"input"),output:createStandardJSONSchemaMethod(e,"output")}});e.toJSONSchema=createToJSONSchemaMethod(e,{});e.def=t;e.type=t.type;Object.defineProperty(e,"_def",{value:t});e.check=(...n)=>e.clone(mergeDefs(t,{checks:[...t.checks??[],...n.map((e=>typeof e==="function"?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e))]}),{parent:true});e.with=e.check;e.clone=(t,n)=>clone(e,t,n);e.brand=()=>e;e.register=(t,n)=>{t.add(e,n);return e};e.parse=(t,n)=>parse(e,t,n,{callee:e.parse});e.safeParse=(t,n)=>safeParse(e,t,n);e.parseAsync=async(t,n)=>parseAsync(e,t,n,{callee:e.parseAsync});e.safeParseAsync=async(t,n)=>safeParseAsync(e,t,n);e.spa=e.safeParseAsync;e.encode=(t,n)=>encode(e,t,n);e.decode=(t,n)=>decode(e,t,n);e.encodeAsync=async(t,n)=>encodeAsync(e,t,n);e.decodeAsync=async(t,n)=>decodeAsync(e,t,n);e.safeEncode=(t,n)=>safeEncode(e,t,n);e.safeDecode=(t,n)=>safeDecode(e,t,n);e.safeEncodeAsync=async(t,n)=>safeEncodeAsync(e,t,n);e.safeDecodeAsync=async(t,n)=>safeDecodeAsync(e,t,n);e.refine=(t,n)=>e.check(refine(t,n));e.superRefine=t=>e.check(superRefine(t));e.overwrite=t=>e.check(_overwrite(t));e.optional=()=>optional(e);e.exactOptional=()=>exactOptional(e);e.nullable=()=>nullable(e);e.nullish=()=>optional(nullable(e));e.nonoptional=t=>nonoptional(e,t);e.array=()=>array(e);e.or=t=>union([e,t]);e.and=t=>intersection(e,t);e.transform=t=>pipe(e,transform(t));e.default=t=>_default(e,t);e.prefault=t=>prefault(e,t);e.catch=t=>_catch(e,t);e.pipe=t=>pipe(e,t);e.readonly=()=>readonly(e);e.describe=t=>{const n=e.clone();globalRegistry.add(n,{description:t});return n};Object.defineProperty(e,"description",{get(){return globalRegistry.get(e)?.description},configurable:true});e.meta=(...t)=>{if(t.length===0){return globalRegistry.get(e)}const n=e.clone();globalRegistry.add(n,t[0]);return n};e.isOptional=()=>e.safeParse(undefined).success;e.isNullable=()=>e.safeParse(null).success;e.apply=t=>t(e);return e}));const _ZodString=$constructor("_ZodString",((e,t)=>{$ZodString.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>stringProcessor(e,t,n);const n=e._zod.bag;e.format=n.format??null;e.minLength=n.minimum??null;e.maxLength=n.maximum??null;e.regex=(...t)=>e.check(_regex(...t));e.includes=(...t)=>e.check(_includes(...t));e.startsWith=(...t)=>e.check(_startsWith(...t));e.endsWith=(...t)=>e.check(_endsWith(...t));e.min=(...t)=>e.check(_minLength(...t));e.max=(...t)=>e.check(_maxLength(...t));e.length=(...t)=>e.check(_length(...t));e.nonempty=(...t)=>e.check(_minLength(1,...t));e.lowercase=t=>e.check(_lowercase(t));e.uppercase=t=>e.check(_uppercase(t));e.trim=()=>e.check(_trim());e.normalize=(...t)=>e.check(_normalize(...t));e.toLowerCase=()=>e.check(_toLowerCase());e.toUpperCase=()=>e.check(_toUpperCase());e.slugify=()=>e.check(_slugify())}));const ZodString=$constructor("ZodString",((e,t)=>{$ZodString.init(e,t);_ZodString.init(e,t);e.email=t=>e.check(_email(ZodEmail,t));e.url=t=>e.check(_url(ZodURL,t));e.jwt=t=>e.check(_jwt(ZodJWT,t));e.emoji=t=>e.check(_emoji(ZodEmoji,t));e.guid=t=>e.check(_guid(ZodGUID,t));e.uuid=t=>e.check(_uuid(ZodUUID,t));e.uuidv4=t=>e.check(_uuidv4(ZodUUID,t));e.uuidv6=t=>e.check(_uuidv6(ZodUUID,t));e.uuidv7=t=>e.check(_uuidv7(ZodUUID,t));e.nanoid=t=>e.check(_nanoid(ZodNanoID,t));e.guid=t=>e.check(_guid(ZodGUID,t));e.cuid=t=>e.check(_cuid(ZodCUID,t));e.cuid2=t=>e.check(_cuid2(ZodCUID2,t));e.ulid=t=>e.check(_ulid(ZodULID,t));e.base64=t=>e.check(_base64(ZodBase64,t));e.base64url=t=>e.check(_base64url(ZodBase64URL,t));e.xid=t=>e.check(_xid(ZodXID,t));e.ksuid=t=>e.check(_ksuid(ZodKSUID,t));e.ipv4=t=>e.check(_ipv4(ZodIPv4,t));e.ipv6=t=>e.check(_ipv6(ZodIPv6,t));e.cidrv4=t=>e.check(_cidrv4(ZodCIDRv4,t));e.cidrv6=t=>e.check(_cidrv6(ZodCIDRv6,t));e.e164=t=>e.check(_e164(ZodE164,t));e.datetime=t=>e.check(datetime(t));e.date=t=>e.check(date(t));e.time=t=>e.check(time(t));e.duration=t=>e.check(duration(t))}));function string(e){return _string(ZodString,e)}const ZodStringFormat=$constructor("ZodStringFormat",((e,t)=>{$ZodStringFormat.init(e,t);_ZodString.init(e,t)}));const ZodEmail=$constructor("ZodEmail",((e,t)=>{$ZodEmail.init(e,t);ZodStringFormat.init(e,t)}));const ZodGUID=$constructor("ZodGUID",((e,t)=>{$ZodGUID.init(e,t);ZodStringFormat.init(e,t)}));const ZodUUID=$constructor("ZodUUID",((e,t)=>{$ZodUUID.init(e,t);ZodStringFormat.init(e,t)}));const ZodURL=$constructor("ZodURL",((e,t)=>{$ZodURL.init(e,t);ZodStringFormat.init(e,t)}));const ZodEmoji=$constructor("ZodEmoji",((e,t)=>{$ZodEmoji.init(e,t);ZodStringFormat.init(e,t)}));const ZodNanoID=$constructor("ZodNanoID",((e,t)=>{$ZodNanoID.init(e,t);ZodStringFormat.init(e,t)}));const ZodCUID=$constructor("ZodCUID",((e,t)=>{$ZodCUID.init(e,t);ZodStringFormat.init(e,t)}));const ZodCUID2=$constructor("ZodCUID2",((e,t)=>{$ZodCUID2.init(e,t);ZodStringFormat.init(e,t)}));const ZodULID=$constructor("ZodULID",((e,t)=>{$ZodULID.init(e,t);ZodStringFormat.init(e,t)}));const ZodXID=$constructor("ZodXID",((e,t)=>{$ZodXID.init(e,t);ZodStringFormat.init(e,t)}));const ZodKSUID=$constructor("ZodKSUID",((e,t)=>{$ZodKSUID.init(e,t);ZodStringFormat.init(e,t)}));const ZodIPv4=$constructor("ZodIPv4",((e,t)=>{$ZodIPv4.init(e,t);ZodStringFormat.init(e,t)}));const ZodIPv6=$constructor("ZodIPv6",((e,t)=>{$ZodIPv6.init(e,t);ZodStringFormat.init(e,t)}));const ZodCIDRv4=$constructor("ZodCIDRv4",((e,t)=>{$ZodCIDRv4.init(e,t);ZodStringFormat.init(e,t)}));const ZodCIDRv6=$constructor("ZodCIDRv6",((e,t)=>{$ZodCIDRv6.init(e,t);ZodStringFormat.init(e,t)}));const ZodBase64=$constructor("ZodBase64",((e,t)=>{$ZodBase64.init(e,t);ZodStringFormat.init(e,t)}));const ZodBase64URL=$constructor("ZodBase64URL",((e,t)=>{$ZodBase64URL.init(e,t);ZodStringFormat.init(e,t)}));const ZodE164=$constructor("ZodE164",((e,t)=>{$ZodE164.init(e,t);ZodStringFormat.init(e,t)}));const ZodJWT=$constructor("ZodJWT",((e,t)=>{$ZodJWT.init(e,t);ZodStringFormat.init(e,t)}));const ZodNumber=$constructor("ZodNumber",((e,t)=>{$ZodNumber.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>numberProcessor(e,t,n);e.gt=(t,n)=>e.check(_gt(t,n));e.gte=(t,n)=>e.check(_gte(t,n));e.min=(t,n)=>e.check(_gte(t,n));e.lt=(t,n)=>e.check(_lt(t,n));e.lte=(t,n)=>e.check(_lte(t,n));e.max=(t,n)=>e.check(_lte(t,n));e.int=t=>e.check(int(t));e.safe=t=>e.check(int(t));e.positive=t=>e.check(_gt(0,t));e.nonnegative=t=>e.check(_gte(0,t));e.negative=t=>e.check(_lt(0,t));e.nonpositive=t=>e.check(_lte(0,t));e.multipleOf=(t,n)=>e.check(_multipleOf(t,n));e.step=(t,n)=>e.check(_multipleOf(t,n));e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null;e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null;e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5);e.isFinite=true;e.format=n.format??null}));function number(e){return _number(ZodNumber,e)}const ZodNumberFormat=$constructor("ZodNumberFormat",((e,t)=>{$ZodNumberFormat.init(e,t);ZodNumber.init(e,t)}));function int(e){return _int(ZodNumberFormat,e)}const ZodBoolean=$constructor("ZodBoolean",((e,t)=>{$ZodBoolean.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>booleanProcessor(e,t,n)}));function boolean(e){return _boolean(ZodBoolean,e)}const ZodUnknown=$constructor("ZodUnknown",((e,t)=>{$ZodUnknown.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(e,t,n)=>unknownProcessor()}));function unknown(){return _unknown(ZodUnknown)}const ZodNever=$constructor("ZodNever",((e,t)=>{$ZodNever.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>neverProcessor(e,t,n)}));function never(e){return _never(ZodNever,e)}const ZodArray=$constructor("ZodArray",((e,t)=>{$ZodArray.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>arrayProcessor(e,t,n,r);e.element=t.element;e.min=(t,n)=>e.check(_minLength(t,n));e.nonempty=t=>e.check(_minLength(1,t));e.max=(t,n)=>e.check(_maxLength(t,n));e.length=(t,n)=>e.check(_length(t,n));e.unwrap=()=>e.element}));function array(e,t){return _array(ZodArray,e,t)}const ZodObject=$constructor("ZodObject",((e,t)=>{$ZodObjectJIT.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>objectProcessor(e,t,n,r);defineLazy(e,"shape",(()=>t.shape));e.keyof=()=>_enum(Object.keys(e._zod.def.shape));e.catchall=t=>e.clone({...e._zod.def,catchall:t});e.passthrough=()=>e.clone({...e._zod.def,catchall:unknown()});e.loose=()=>e.clone({...e._zod.def,catchall:unknown()});e.strict=()=>e.clone({...e._zod.def,catchall:never()});e.strip=()=>e.clone({...e._zod.def,catchall:undefined});e.extend=t=>extend(e,t);e.safeExtend=t=>safeExtend(e,t);e.merge=t=>merge(e,t);e.pick=t=>pick(e,t);e.omit=t=>omit(e,t);e.partial=(...t)=>partial(ZodOptional,e,t[0]);e.required=(...t)=>required(ZodNonOptional,e,t[0])}));function object(e,t){const n={type:"object",shape:e??{},...normalizeParams(t)};return new ZodObject(n)}const ZodUnion=$constructor("ZodUnion",((e,t)=>{$ZodUnion.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>unionProcessor(e,t,n,r);e.options=t.options}));function union(e,t){return new ZodUnion({type:"union",options:e,...normalizeParams(t)})}const ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",((e,t)=>{ZodUnion.init(e,t);$ZodDiscriminatedUnion.init(e,t)}));function discriminatedUnion(e,t,n){return new ZodDiscriminatedUnion({type:"union",options:t,discriminator:e,...normalizeParams(n)})}const ZodIntersection=$constructor("ZodIntersection",((e,t)=>{$ZodIntersection.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>intersectionProcessor(e,t,n,r)}));function intersection(e,t){return new ZodIntersection({type:"intersection",left:e,right:t})}const ZodEnum=$constructor("ZodEnum",((e,t)=>{$ZodEnum.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>enumProcessor(e,t,n);e.enum=t.entries;e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const o={};for(const r of e){if(n.has(r)){o[r]=t.entries[r]}else throw new Error(`Key ${r} not found in enum`)}return new ZodEnum({...t,checks:[],...normalizeParams(r),entries:o})};e.exclude=(e,r)=>{const o={...t.entries};for(const t of e){if(n.has(t)){delete o[t]}else throw new Error(`Key ${t} not found in enum`)}return new ZodEnum({...t,checks:[],...normalizeParams(r),entries:o})}}));function _enum(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map((e=>[e,e]))):e;return new ZodEnum({type:"enum",entries:n,...normalizeParams(t)})}const ZodLiteral=$constructor("ZodLiteral",((e,t)=>{$ZodLiteral.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>literalProcessor(e,t,n);e.values=new Set(t.values);Object.defineProperty(e,"value",{get(){if(t.values.length>1){throw new Error("This schema contains multiple valid literal values. Use `.values` instead.")}return t.values[0]}})}));function literal(e,t){return new ZodLiteral({type:"literal",values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const ZodTransform=$constructor("ZodTransform",((e,t)=>{$ZodTransform.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>transformProcessor(e,t);e._zod.parse=(n,r)=>{if(r.direction==="backward"){throw new $ZodEncodeError(e.constructor.name)}n.addIssue=r=>{if(typeof r==="string"){n.issues.push(issue(r,n.value,t))}else{const t=r;if(t.fatal)t.continue=false;t.code??(t.code="custom");t.input??(t.input=n.value);t.inst??(t.inst=e);n.issues.push(issue(t))}};const o=t.transform(n.value,n);if(o instanceof Promise){return o.then((e=>{n.value=e;return n}))}n.value=o;return n}}));function transform(e){return new ZodTransform({type:"transform",transform:e})}const ZodOptional=$constructor("ZodOptional",((e,t)=>{$ZodOptional.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r);e.unwrap=()=>e._zod.def.innerType}));function optional(e){return new ZodOptional({type:"optional",innerType:e})}const ZodExactOptional=$constructor("ZodExactOptional",((e,t)=>{$ZodExactOptional.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r);e.unwrap=()=>e._zod.def.innerType}));function exactOptional(e){return new ZodExactOptional({type:"optional",innerType:e})}const ZodNullable=$constructor("ZodNullable",((e,t)=>{$ZodNullable.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>nullableProcessor(e,t,n,r);e.unwrap=()=>e._zod.def.innerType}));function nullable(e){return new ZodNullable({type:"nullable",innerType:e})}const ZodDefault=$constructor("ZodDefault",((e,t)=>{$ZodDefault.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>defaultProcessor(e,t,n,r);e.unwrap=()=>e._zod.def.innerType;e.removeDefault=e.unwrap}));function _default(e,t){return new ZodDefault({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():shallowClone(t)}})}const ZodPrefault=$constructor("ZodPrefault",((e,t)=>{$ZodPrefault.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>prefaultProcessor(e,t,n,r);e.unwrap=()=>e._zod.def.innerType}));function prefault(e,t){return new ZodPrefault({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():shallowClone(t)}})}const ZodNonOptional=$constructor("ZodNonOptional",((e,t)=>{$ZodNonOptional.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>nonoptionalProcessor(e,t,n,r);e.unwrap=()=>e._zod.def.innerType}));function nonoptional(e,t){return new ZodNonOptional({type:"nonoptional",innerType:e,...normalizeParams(t)})}const ZodCatch=$constructor("ZodCatch",((e,t)=>{$ZodCatch.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>catchProcessor(e,t,n,r);e.unwrap=()=>e._zod.def.innerType;e.removeCatch=e.unwrap}));function _catch(e,t){return new ZodCatch({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}const ZodPipe=$constructor("ZodPipe",((e,t)=>{$ZodPipe.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>pipeProcessor(e,t,n,r);e.in=t.in;e.out=t.out}));function pipe(e,t){return new ZodPipe({type:"pipe",in:e,out:t})}const ZodReadonly=$constructor("ZodReadonly",((e,t)=>{$ZodReadonly.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>readonlyProcessor(e,t,n,r);e.unwrap=()=>e._zod.def.innerType}));function readonly(e){return new ZodReadonly({type:"readonly",innerType:e})}const ZodCustom=$constructor("ZodCustom",((e,t)=>{$ZodCustom.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>customProcessor(e,t)}));function custom(e,t){return _custom(ZodCustom,(()=>true),t)}function refine(e,t={}){return _refine(ZodCustom,e,t)}function superRefine(e){return _superRefine(e)}const nonEmptyString=string().trim().min(1);const optionalPositiveInt=number().int().positive().optional();const optionalString=string().optional();const selectOptionsSchema=array(nonEmptyString).min(1);const optionalNumber=number().optional();const evaluationParametersSchema=object({approach:_enum(EvaluationApproach),threshold:optionalNumber});const selectEvaluationParametersSchema=evaluationParametersSchema.superRefine(((e,t)=>{if(!isApproachAllowedForFieldType("select",e.approach)){t.addIssue({code:"custom",path:["approach"],message:`select fields only support "${EvaluationApproach.EXACT}" evaluation approach.`})}}));const defaultExpectedOutcomeBaseSchema=object({label:nonEmptyString,placeholder:optionalString});const createDefaultExpectedOutcomeFieldSchemas=e=>({text:e.extend({type:literal("text"),evaluationParameters:evaluationParametersSchema.optional()}),textarea:e.extend({type:literal("textarea"),rows:optionalPositiveInt,evaluationParameters:evaluationParametersSchema.optional()}),chipsInput:e.extend({type:literal("chips-input"),evaluationParameters:evaluationParametersSchema.optional()}),select:e.extend({type:literal("select"),options:selectOptionsSchema,evaluationParameters:selectEvaluationParametersSchema.optional()})});function hasDuplicateChips(e){const t=new Set;for(const n of e){const e=n.trim().toLowerCase();if(t.has(e)){return true}t.add(e)}return false}const defaultFieldDefinitions=createDefaultExpectedOutcomeFieldSchemas(defaultExpectedOutcomeBaseSchema);const expectedOutcomeSchemaFieldSchema=discriminatedUnion("type",[defaultFieldDefinitions.text,defaultFieldDefinitions.textarea,defaultFieldDefinitions.chipsInput,defaultFieldDefinitions.select]);const expectedOutcomeSchemaSchema=array(expectedOutcomeSchemaFieldSchema).min(1);const expectedOutcomeFieldSchema=discriminatedUnion("type",[defaultFieldDefinitions.text.extend({value:string()}),defaultFieldDefinitions.textarea.extend({value:string()}),defaultFieldDefinitions.chipsInput.extend({value:array(string()).superRefine(((e,t)=>{if(hasDuplicateChips(e)){t.addIssue({code:"custom",message:"chips-input values must be unique (case-insensitive, trimmed)."})}}))}),defaultFieldDefinitions.select.extend({value:string()}).superRefine(((e,t)=>{if(!e.options.includes(e.value)){t.addIssue({code:"custom",path:["value"],message:"select value must be one of the provided options."})}}))]);const expectedOutcomeArraySchema=array(expectedOutcomeFieldSchema).min(1);function validateExpectedOutcomeSchema(e){const t=expectedOutcomeSchemaSchema.safeParse(e);if(!t.success){throw new Error(`Invalid expectedOutcomeSchema: ${t.error.issues[0].message}`)}}const testCaseInputSchema=object({id:string(),question:string(),expectedOutcome:expectedOutcomeArraySchema});const testCaseInputArraySchema=array(testCaseInputSchema);object({id:string(),question:string(),expectedOutcome:expectedOutcomeArraySchema,output:string().optional(),isRunning:boolean().optional(),error:string().optional(),evaluationResult:custom().optional(),responseTime:number().optional()});function validateTestCaseInputArray(e){const t=testCaseInputArraySchema.safeParse(e);if(!t.success){const e=t.error.issues[0];const n=e.code==="invalid_type"?"Invalid JSON structure. Expected a JSON array.":e.message;throw new Error(n)}}function importTestSuite(e){try{const t=JSON.parse(e);validateTestCaseInputArray(t);const n=t.map(((e,t)=>{try{return createTestCaseFromInput(e)}catch(e){const n=e instanceof Error?e.message:"Unknown error";throw new Error(`Invalid test case at index ${t}: ${n}`)}}));return{success:true,testCases:n}}catch(e){return{success:false,error:e instanceof Error?e.message:"Error processing file. Please ensure it is a valid JSON array."}}}function applyExpectedOutcomeChange(e,t){const{index:n}=t;const r=[...e.expectedOutcome||[]];const o=r[n];if(!o){return e}switch(t.operation){case"set-value":{if(o.type==="chips-input"){return e}r[n]={...o,value:t.value};return{...e,expectedOutcome:r}}case"add-chip":{if(o.type!=="chips-input"){return e}r[n]={...o,value:[...o.value,t.value]};return{...e,expectedOutcome:r}}case"remove-chip":{if(o.type!=="chips-input"){return e}r[n]={...o,value:o.value.filter((e=>e!==t.value))};return{...e,expectedOutcome:r}}case"set-evaluation-approach":return updateExpectedOutcomeFieldApproach(e,n,t.value)}}function updateExpectedOutcomeFieldApproach(e,t,n){const r=[...e.expectedOutcome||[]];const o=r[t];if(!o){return e}const i=o.evaluationParameters;r[t]={...o,evaluationParameters:normalizeEvaluationParametersForField(o.type,{...i,approach:n})};return{...e,expectedOutcome:r}}async function performEvaluation(e){const{testCaseId:t,expectedOutcome:n,actualResponse:r}=e;const o=n?n.split(/[\n,]+/).map((e=>e.trim())).filter((e=>e.length>0)):[];const i=evaluateKeywords(o,r);const s=i.length;const a=i.filter((e=>e.found)).length;const c=a===s;return{testCaseId:t,passed:c,keywordMatches:i,timestamp:(new Date).toISOString(),evaluationParameters:e.evaluationParameters,evaluationApproachResult:{score:s>0?a/s:1,approachUsed:EvaluationApproach.EXACT}}}function evaluateKeywords(e,t){const n=t.toLowerCase();return e.map((e=>{const t=e.toLowerCase();const r=n.includes(t);return{keyword:e,found:r,evaluationApproachResult:{score:r?1:0,approachUsed:EvaluationApproach.EXACT}}}))}var u=[/\b(can)(not)\b/i,/\b(d)('ye)\b/i,/\b(gim)(me)\b/i,/\b(gon)(na)\b/i,/\b(got)(ta)\b/i,/\b(lem)(me)\b/i,/\b(more)('n)\b/i,/\b(wan)(na) /i,/\ ('t)(is)\b/i,/\ ('t)(was)\b/i];function m(e){if(e.length===0)return[];let t=e.replace(/^\"/," `` ").replace(/([ (\[{<])"/g,"$1 `` ").replace(/\.\.\.*/g," ... ").replace(/[;@#$%&]/g," $& ").replace(/([^\.])(\.)([\]\)}>"\']*)\s*$/g,"$1 $2$3 ").replace(/[,?!]/g," $& ").replace(/[\]\[\(\)\{\}<>]/g," $& ").replace(/---*/g," -- ");t=` ${t} `,t=t.replace(/"/g," '' ").replace(/([^'])' /g,"$1 ' ").replace(/'([sSmMdD]) /g," '$1 ").replace(/('ll|'LL|'re|'RE|'ve|'VE|n't|N'T) /g," $1 ");let n=-1;for(;n++<u.length;)t=t.replace(u[n]," $1 $2 ");return t=t.replace(/\ \ +/g," ").replace(/^\ |\ $/g,""),t.split(" ")}function C(e,t=Map){return(()=>{let n=new t;return t=>{if(n.has(t)){let e=n.get(t);if(e!==void 0)return e}let r=e(t);return n.set(t,r),r}})()}function x(e,t=1){if(e<0)throw RangeError("Input must be a positive number");return e<2?t:x(e-1,e*t)}C(x);var G={start:false,end:false,val:"<S>"};function E(e,t=2,n={}){if(t<1)throw new RangeError("ngram size cannot be smaller than 1");if(e.length<t)throw new RangeError("ngram size cannot be larger than the number of tokens available");if(Object.keys(n).length!==0){let r={...G,...n},o=e.slice(0);if(r.start)for(let e=0;e<t-1;e++)o.unshift(r.val);if(r.end)for(let e=0;e<t-1;e++)o.push(r.val);e=o}let r=[];for(let n=0;n<e.length-t+1;n++)r.push(e.slice(n,n+t).join(" "));return r}function f(e,t){let n=new Set(e),r=new Set(t);return Array.from(n).filter((e=>r.has(e)))}function T(e,t){if(e.length===0||t.length===0)return[];let n=Array(e.length+1).fill(0).map((()=>Array(t.length+1).fill(0)));for(let r=1;r<=e.length;r++)for(let o=1;o<=t.length;o++)e[r-1]===t[o-1]?n[r][o]=n[r-1][o-1]+1:n[r][o]=Math.max(n[r-1][o],n[r][o-1]);let r=[],o=e.length,i=t.length;for(;o>0&&i>0;)e[o-1]===t[i-1]?(r.unshift(e[o-1]),o--,i--):n[o-1][i]>n[o][i-1]?o--:i--;return r}function W(e,t,n){if(e.length===0)throw new RangeError("Candidate cannot be an empty string");if(t.length===0)throw new RangeError("Reference cannot be an empty string");let r=Object.assign({n:1,nGram:E,tokenizer:m},n),o=r.nGram(r.tokenizer(e),r.n),i=r.nGram(r.tokenizer(t),r.n);return f(o,i).length/i.length}function evaluateKeyword$2(e,t,n){let r=0;try{if(e.trim().length>0&&t.length>0){const n=W(t,e.trim(),{n:1});r=isNaN(n)?0:n}else{console.warn(`ROUGE-1 not computed for keyword "${e}": Keyword or Candidate is missing.`)}}catch(t){console.error(`ROUGE-1 computation failed for keyword "${e}":`,t)}const o=r>=n;const i={score:r,approachUsed:EvaluationApproach.ROUGE_1};return{keyword:e,found:o,evaluationApproachResult:i}}async function performRouge1Evaluation(e){const{testCaseId:t,actualResponse:n,expectedOutcome:r,evaluationParameters:o}=e;const i=r?r.split(/[\n,]+/).map((e=>e.trim())).filter((e=>e.length>0)):[];const s=(n||"").trim();const a=o.threshold??DEFAULT_ROUGE_PASS_SCORE;let c=0;const u=i.length;const l=i.map((e=>{const t=evaluateKeyword$2(e,s,a);if(t.found){c++}return t}));const f=c===u;const d={score:c/u,approachUsed:EvaluationApproach.ROUGE_1};return{testCaseId:t,passed:f,keywordMatches:l,timestamp:(new Date).toISOString(),evaluationParameters:{...o,threshold:a},evaluationApproachResult:d}}function dispatchCallback(e,t){if(e)e(t)}function reverseDictionary(e){return Object.fromEntries(Object.entries(e).map((([e,t])=>[t,e])))}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Callable=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}};function isTypedArray(e){return e?.prototype?.__proto__?.constructor?.name==="TypedArray"}function isIntegralNumber(e){return Number.isInteger(e)||typeof e==="bigint"}function exists(e){return e!==undefined&&e!==null}function calculateDimensions(e){const t=[];let n=e;while(Array.isArray(n)){t.push(n.length);n=n[0]}return t}function pop(e,t,n=undefined){const r=e[t];if(r!==undefined){delete e[t];return r}if(n===undefined){throw Error(`Key ${t} does not exist in object.`)}return n}function mergeArrays(...e){return Array.prototype.concat.apply([],e)}function product(...e){return e.reduce(((e,t)=>e.flatMap((e=>t.map((t=>[e,t]))))))}function calculateReflectOffset(e,t){return Math.abs((e+t)%(2*t)-t)}var sharp={};var ONNX_NODE=Object.freeze({__proto__:null,default:sharp});var ortWeb_min$1={exports:{}};const backends={};const backendsSortedByPriority=[];const registerBackend=(e,t,n)=>{if(t&&typeof t.init==="function"&&typeof t.createSessionHandler==="function"){const r=backends[e];if(r===undefined){backends[e]={backend:t,priority:n}}else if(r.priority>n){return}else if(r.priority===n){if(r.backend!==t){throw new Error(`cannot register backend "${e}" using priority ${n}`)}}if(n>=0){const t=backendsSortedByPriority.indexOf(e);if(t!==-1){backendsSortedByPriority.splice(t,1)}for(let t=0;t<backendsSortedByPriority.length;t++){if(backends[backendsSortedByPriority[t]].priority<=n){backendsSortedByPriority.splice(t,0,e);return}}backendsSortedByPriority.push(e)}return}throw new TypeError("not a valid backend")};const resolveBackend=async e=>{const t=e.length===0?backendsSortedByPriority:e;const n=[];for(const e of t){const t=backends[e];if(t){if(t.initialized){return t.backend}else if(t.aborted){continue}const r=!!t.initPromise;try{if(!r){t.initPromise=t.backend.init()}await t.initPromise;t.initialized=true;return t.backend}catch(o){if(!r){n.push({name:e,err:o})}t.aborted=true}finally{delete t.initPromise}}}throw new Error(`no available backend found. ERR: ${n.map((e=>`[${e.name}] ${e.err}`)).join(", ")}`)};class EnvImpl{constructor(){this.wasm={};this.webgl={};this.logLevelInternal="warning"}set logLevel(e){if(e===undefined){return}if(typeof e!=="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1){throw new Error(`Unsupported logging level: ${e}`)}this.logLevelInternal=e}get logLevel(){return this.logLevelInternal}}const env$2=new EnvImpl;const isBigInt64ArrayAvailable=typeof BigInt64Array!=="undefined"&&typeof BigInt64Array.from==="function";const isBigUint64ArrayAvailable=typeof BigUint64Array!=="undefined"&&typeof BigUint64Array.from==="function";const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]);const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);if(isBigInt64ArrayAvailable){NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64",BigInt64Array);NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array,"int64")}if(isBigUint64ArrayAvailable){NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64",BigUint64Array);NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array,"uint64")}const calculateSize=e=>{let t=1;for(let n=0;n<e.length;n++){const r=e[n];if(typeof r!=="number"||!Number.isSafeInteger(r)){throw new TypeError(`dims[${n}] must be an integer, got: ${r}`)}if(r<0){throw new RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`)}t*=r}return t};let Tensor$2=class e{constructor(e,t,n){let r;let o;let i;if(typeof e==="string"){r=e;i=n;if(e==="string"){if(!Array.isArray(t)){throw new TypeError("A string tensor's data must be a string array.")}o=t}else{const n=NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(e);if(n===undefined){throw new TypeError(`Unsupported tensor type: ${e}.`)}if(Array.isArray(t)){o=n.from(t)}else if(t instanceof n){o=t}else{throw new TypeError(`A ${r} tensor's data must be type of ${n}`)}}}else{i=t;if(Array.isArray(e)){if(e.length===0){throw new TypeError("Tensor type cannot be inferred from an empty array.")}const t=typeof e[0];if(t==="string"){r="string";o=e}else if(t==="boolean"){r="bool";o=Uint8Array.from(e)}else{throw new TypeError(`Invalid element type of data array: ${t}.`)}}else{const t=NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(e.constructor);if(t===undefined){throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`)}r=t;o=e}}if(i===undefined){i=[o.length]}else if(!Array.isArray(i)){throw new TypeError("A tensor's dims must be a number array")}const s=calculateSize(i);if(s!==o.length){throw new Error(`Tensor's size(${s}) does not match data length(${o.length}).`)}this.dims=i;this.type=r;this.data=o;this.size=s}static bufferToTensor(t,n){if(t===undefined){throw new Error("Image buffer must be defined")}if(n.height===undefined||n.width===undefined){throw new Error("Image height and width must be defined")}const{height:r,width:o}=n;const i=n.norm;let s;let a;if(i===undefined||i.mean===undefined){s=255}else{s=i.mean}if(i===undefined||i.bias===undefined){a=0}else{a=i.bias}const c=n.bitmapFormat!==undefined?n.bitmapFormat:"RGBA";const u=n.tensorFormat!==undefined?n.tensorFormat!==undefined?n.tensorFormat:"RGB":"RGB";const l=r*o;const f=u==="RGBA"?new Float32Array(l*4):new Float32Array(l*3);let d=4,h=0,p=1,m=2,w=3;let g=0,v=l,y=l*2,_=-1;if(c==="RGB"){d=3;h=0;p=1;m=2;w=-1}if(u==="RGBA"){_=l*3}else if(u==="RBG"){g=0;y=l;v=l*2}else if(u==="BGR"){y=0;v=l;g=l*2}for(let e=0;e<l;e++,h+=d,m+=d,p+=d,w+=d){f[g++]=(t[h]+a)/s;f[v++]=(t[p]+a)/s;f[y++]=(t[m]+a)/s;if(_!==-1&&w!==-1){f[_++]=(t[w]+a)/s}}const b=u==="RGBA"?new e("float32",f,[1,4,r,o]):new e("float32",f,[1,3,r,o]);return b}static async fromImage(t,n){const r=typeof HTMLImageElement!=="undefined"&&t instanceof HTMLImageElement;const o=typeof ImageData!=="undefined"&&t instanceof ImageData;const i=typeof ImageBitmap!=="undefined"&&t instanceof ImageBitmap;const s=typeof String!=="undefined"&&(t instanceof String||typeof t==="string");let a;let c={};if(r){const e=document.createElement("canvas");const r=e.getContext("2d");if(r!=null){let o=t.naturalHeight;let i=t.naturalWidth;if(n!==undefined&&n.resizedHeight!==undefined&&n.resizedWidth!==undefined){o=n.resizedHeight;i=n.resizedWidth}if(n!==undefined){c=n;if(n.tensorFormat!==undefined){throw new Error("Image input config format must be RGBA for HTMLImageElement")}else{c.tensorFormat="RGBA"}if(n.height!==undefined&&n.height!==o){throw new Error("Image input config height doesn't match HTMLImageElement height")}else{c.height=o}if(n.width!==undefined&&n.width!==i){throw new Error("Image input config width doesn't match HTMLImageElement width")}else{c.width=i}}else{c.tensorFormat="RGBA";c.height=o;c.width=i}e.width=i;e.height=o;r.drawImage(t,0,0,i,o);a=r.getImageData(0,0,i,o).data}else{throw new Error("Can not access image data")}}else if(o){const e="RGBA";let r;let o;if(n!==undefined&&n.resizedWidth!==undefined&&n.resizedHeight!==undefined){r=n.resizedHeight;o=n.resizedWidth}else{r=t.height;o=t.width}if(n!==undefined){c=n;if(n.bitmapFormat!==undefined&&n.bitmapFormat!==e){throw new Error("Image input config format must be RGBA for ImageData")}else{c.bitmapFormat="RGBA"}}else{c.bitmapFormat="RGBA"}c.height=r;c.width=o;if(n!==undefined){const e=document.createElement("canvas");e.width=o;e.height=r;const n=e.getContext("2d");if(n!=null){n.putImageData(t,0,0);a=n.getImageData(0,0,o,r).data}else{throw new Error("Can not access image data")}}else{a=t.data}}else if(i){if(n===undefined){throw new Error("Please provide image config with format for Imagebitmap")}if(n.bitmapFormat!==undefined){throw new Error("Image input config format must be defined for ImageBitmap")}const r=document.createElement("canvas").getContext("2d");if(r!=null){const o=t.height;const i=t.width;r.drawImage(t,0,0,i,o);a=r.getImageData(0,0,i,o).data;if(n!==undefined){if(n.height!==undefined&&n.height!==o){throw new Error("Image input config height doesn't match ImageBitmap height")}else{c.height=o}if(n.width!==undefined&&n.width!==i){throw new Error("Image input config width doesn't match ImageBitmap width")}else{c.width=i}}else{c.height=o;c.width=i}return e.bufferToTensor(a,c)}else{throw new Error("Can not access image data")}}else if(s){return new Promise(((r,o)=>{const i=document.createElement("canvas");const s=i.getContext("2d");if(!t||!s){return o()}const a=new Image;a.crossOrigin="Anonymous";a.src=t;a.onload=()=>{i.width=a.width;i.height=a.height;s.drawImage(a,0,0,i.width,i.height);const t=s.getImageData(0,0,i.width,i.height);if(n!==undefined){if(n.height!==undefined&&n.height!==i.height){throw new Error("Image input config height doesn't match ImageBitmap height")}else{c.height=i.height}if(n.width!==undefined&&n.width!==i.width){throw new Error("Image input config width doesn't match ImageBitmap width")}else{c.width=i.width}}else{c.height=i.height;c.width=i.width}r(e.bufferToTensor(t.data,c))}}))}else{throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==undefined){return e.bufferToTensor(a,c)}else{throw new Error("Input data provided is not supported - aborted tensor creation")}}toImageData(e){var t,n;const r=document.createElement("canvas").getContext("2d");let o;if(r!=null){const i=this.dims[3];const s=this.dims[2];const a=this.dims[1];const c=e!==undefined?e.format!==undefined?e.format:"RGB":"RGB";const u=e!==undefined?((t=e.norm)===null||t===void 0?void 0:t.mean)!==undefined?e.norm.mean:255:255;const l=e!==undefined?((n=e.norm)===null||n===void 0?void 0:n.bias)!==undefined?e.norm.bias:0:0;const f=s*i;if(e!==undefined){if(e.height!==undefined&&e.height!==s){throw new Error("Image output config height doesn't match tensor height")}if(e.width!==undefined&&e.width!==i){throw new Error("Image output config width doesn't match tensor width")}if(e.format!==undefined&&(a===4&&e.format!=="RGBA")||a===3&&(e.format!=="RGB"&&e.format!=="BGR")){throw new Error("Tensor format doesn't match input tensor dims")}}const d=4;let h=0,p=1,m=2,w=3;let g=0,v=f,y=f*2,_=-1;if(c==="RGBA"){g=0;v=f;y=f*2;_=f*3}else if(c==="RGB"){g=0;v=f;y=f*2}else if(c==="RBG"){g=0;y=f;v=f*2}o=r.createImageData(i,s);for(let e=0;e<s*i;h+=d,p+=d,m+=d,w+=d,e++){o.data[h]=(this.data[g++]-l)*u;o.data[p]=(this.data[v++]-l)*u;o.data[m]=(this.data[y++]-l)*u;o.data[w]=_===-1?255:(this.data[_++]-l)*u}}else{throw new Error("Can not access image data")}return o}reshape(t){return new e(this.type,this.data,t)}};const Tensor$1=Tensor$2;let InferenceSession$2=class e{constructor(e){this.handler=e}async run(e,t,n){const r={};let o={};if(typeof e!=="object"||e===null||e instanceof Tensor$1||Array.isArray(e)){throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.")}let i=true;if(typeof t==="object"){if(t===null){throw new TypeError("Unexpected argument[1]: cannot be null.")}if(t instanceof Tensor$1){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=false;for(const e of t){if(typeof e!=="string"){throw new TypeError("'fetches' must be a string array or an object.")}if(this.outputNames.indexOf(e)===-1){throw new RangeError(`'fetches' contains invalid output name: ${e}.`)}r[e]=null}if(typeof n==="object"&&n!==null){o=n}else if(typeof n!=="undefined"){throw new TypeError("'options' must be an object.")}}else{let e=false;const s=Object.getOwnPropertyNames(t);for(const n of this.outputNames){if(s.indexOf(n)!==-1){const o=t[n];if(o===null||o instanceof Tensor$1){e=true;i=false;r[n]=o}}}if(e){if(typeof n==="object"&&n!==null){o=n}else if(typeof n!=="undefined"){throw new TypeError("'options' must be an object.")}}else{o=t}}}else if(typeof t!=="undefined"){throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.")}for(const t of this.inputNames){if(typeof e[t]==="undefined"){throw new Error(`input '${t}' is missing in 'feeds'.`)}}if(i){for(const e of this.outputNames){r[e]=null}}const s=await this.handler.run(e,r,o);const a={};for(const e in s){if(Object.hasOwnProperty.call(s,e)){a[e]=new Tensor$1(s[e].type,s[e].data,s[e].dims)}}return a}static async create(t,n,r,o){let i;let s={};if(typeof t==="string"){i=t;if(typeof n==="object"&&n!==null){s=n}else if(typeof n!=="undefined"){throw new TypeError("'options' must be an object.")}}else if(t instanceof Uint8Array){i=t;if(typeof n==="object"&&n!==null){s=n}else if(typeof n!=="undefined"){throw new TypeError("'options' must be an object.")}}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer!=="undefined"&&t instanceof SharedArrayBuffer){const e=t;let a=0;let c=t.byteLength;if(typeof n==="object"&&n!==null){s=n}else if(typeof n==="number"){a=n;if(!Number.isSafeInteger(a)){throw new RangeError("'byteOffset' must be an integer.")}if(a<0||a>=e.byteLength){throw new RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`)}c=t.byteLength-a;if(typeof r==="number"){c=r;if(!Number.isSafeInteger(c)){throw new RangeError("'byteLength' must be an integer.")}if(c<=0||a+c>e.byteLength){throw new RangeError(`'byteLength' is out of range (0, ${e.byteLength-a}].`)}if(typeof o==="object"&&o!==null){s=o}else if(typeof o!=="undefined"){throw new TypeError("'options' must be an object.")}}else if(typeof r!=="undefined"){throw new TypeError("'byteLength' must be a number.")}}else if(typeof n!=="undefined"){throw new TypeError("'options' must be an object.")}i=new Uint8Array(e,a,c)}else{throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.")}const a=s.executionProviders||[];const c=a.map((e=>typeof e==="string"?e:e.name));const u=await resolveBackend(c);const l=await u.createSessionHandler(i,s);return new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const InferenceSession$1=InferenceSession$2;var lib=Object.freeze({__proto__:null,InferenceSession:InferenceSession$1,Tensor:Tensor$1,env:env$2,registerBackend});var require$$0=getAugmentedNamespace(lib);
|
|
2
|
+
/*!
|
|
3
|
+
* ONNX Runtime Web v1.14.0
|
|
4
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
5
|
+
* Licensed under the MIT License.
|
|
6
|
+
*/var hasRequiredOrtWeb_min;function requireOrtWeb_min(){if(hasRequiredOrtWeb_min)return ortWeb_min$1.exports;hasRequiredOrtWeb_min=1;(function(module,exports){!function(e,t){module.exports=t(require$$0)}(self,(__WEBPACK_EXTERNAL_MODULE__1670__=>(()=>{var __webpack_modules__={3474:(e,t,n)=>{var r,o=(r=(r="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){function t(){return k.buffer!=F&&W(k.buffer),N}function o(){return k.buffer!=F&&W(k.buffer),D}function i(){return k.buffer!=F&&W(k.buffer),R}function s(){return k.buffer!=F&&W(k.buffer),L}function a(){return k.buffer!=F&&W(k.buffer),j}var c,u,l;e=e||{},c||(c=void 0!==e?e:{}),c.ready=new Promise((function(e,t){u=e,l=t}));var f,d,h,p,m,w,g=Object.assign({},c),v="./this.program",y=(e,t)=>{throw t},_="object"==typeof window,b="function"==typeof importScripts,x="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,T=c.ENVIRONMENT_IS_PTHREAD||false,M="";function E(e){return c.locateFile?c.locateFile(e,M):M+e}if(x){let t;M=b?n(908).dirname(M)+"/":"//",w=()=>{m||(p=n(1384),m=n(908))},f=function(e,t){return w(),e=m.normalize(e),p.readFileSync(e,t?void 0:"utf8")},h=e=>((e=f(e,true)).buffer||(e=new Uint8Array(e)),e),d=(e,t,n)=>{w(),e=m.normalize(e),p.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},1<process.argv.length&&(v=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof ce))throw e})),process.on("unhandledRejection",(function(e){throw e})),y=(e,t)=>{if(J())throw process.exitCode=e,t;t instanceof ce||P("exiting due to exception: "+t),process.exit(e)},c.inspect=function(){return"[Emscripten Module object]"};try{t=n(9925)}catch(e){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),e}n.g.Worker=t.Worker}else(_||b)&&(b?M=self.location.href:"undefined"!=typeof document&&document.currentScript&&(M=document.currentScript.src),r&&(M=r),M=0!==M.indexOf("blob:")?M.substr(0,M.replace(/[?#].*/,"").lastIndexOf("/")+1):"",x||(f=e=>{var t=new XMLHttpRequest;return t.open("GET",e,false),t.send(null),t.responseText},b&&(h=e=>{var t=new XMLHttpRequest;return t.open("GET",e,false),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),d=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,true),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)}));x&&"undefined"==typeof performance&&(n.g.performance=n(6953).performance);var S=console.log.bind(console),A=console.warn.bind(console);x&&(w(),S=e=>p.writeSync(1,e+"\n"),A=e=>p.writeSync(2,e+"\n"));var $,O=c.print||S,P=c.printErr||A;Object.assign(c,g),g=null,c.thisProgram&&(v=c.thisProgram),c.quit&&(y=c.quit),c.wasmBinary&&($=c.wasmBinary);var C=c.noExitRuntime||false;"object"!=typeof WebAssembly&&oe("no native wasm support detected");var k,I,F,N,D,R,L,j,z=false,U="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function B(e,t,n){var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16<n-t&&e.buffer&&U)return U.decode(e.buffer instanceof SharedArrayBuffer?e.slice(t,n):e.subarray(t,n));for(r="";t<n;){var o=e[t++];if(128&o){var i=63&e[t++];if(192==(224&o))r+=String.fromCharCode((31&o)<<6|i);else{var s=63&e[t++];65536>(o=224==(240&o)?(15&o)<<12|i<<6|s:(7&o)<<18|i<<12|s<<6|63&e[t++])?r+=String.fromCharCode(o):(o-=65536,r+=String.fromCharCode(55296|o>>10,56320|1023&o))}}else r+=String.fromCharCode(o)}return r}function V(e,t){return(e>>>=0)?B(o(),e,t):""}function Z(e,t,n,r){if(!(0<r))return 0;var o=n>>>=0;r=n+r-1;for(var i=0;i<e.length;++i){var s=e.charCodeAt(i);if(55296<=s&&57343>=s&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++i)),127>=s){if(n>=r)break;t[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;t[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;t[n++>>>0]=224|s>>12}else{if(n+3>=r)break;t[n++>>>0]=240|s>>18,t[n++>>>0]=128|s>>12&63}t[n++>>>0]=128|s>>6&63}t[n++>>>0]=128|63&s}}return t[n>>>0]=0,n-o}function G(e){for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t}function W(e){F=e,c.HEAP8=N=new Int8Array(e),c.HEAP16=new Int16Array(e),c.HEAP32=R=new Int32Array(e),c.HEAPU8=D=new Uint8Array(e),c.HEAPU16=new Uint16Array(e),c.HEAPU32=L=new Uint32Array(e),c.HEAPF32=new Float32Array(e),c.HEAPF64=j=new Float64Array(e)}T&&(F=c.buffer);var q=c.INITIAL_MEMORY||16777216;if(T)k=c.wasmMemory,F=c.buffer;else if(c.wasmMemory)k=c.wasmMemory;else if(!((k=new WebAssembly.Memory({initial:q/65536,maximum:65536,shared:true})).buffer instanceof SharedArrayBuffer))throw P("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),x&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");k&&(F=k.buffer),q=F.byteLength,W(F);var H,X=[],Y=[],Q=[],K=[];function J(){return C||false}function ee(){var e=c.preRun.shift();X.unshift(e)}var te,ne=0,re=null;function oe(e){throw T?postMessage({cmd:"onAbort",arg:e}):c.onAbort&&c.onAbort(e),P(e="Aborted("+e+")"),z=true,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),l(e),e}function ie(){return te.startsWith("data:application/octet-stream;base64,")}function se(){var e=te;try{if(e==te&&$)return new Uint8Array($);if(h)return h(e);throw"both async and sync fetching of the wasm failed"}catch(e){oe(e)}}te="ort-wasm-threaded.wasm",ie()||(te=E(te));var ae={};function ce(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function ue(e){(e=he.Vb[e])||oe(),he.mc(e)}function le(e){var t=he.Cc();if(!t)return 6;he.ac.push(t),he.Vb[e.Ub]=t,t.Ub=e.Ub;var n={cmd:"run",start_routine:e.Ic,arg:e.zc,pthread_ptr:e.Ub};return t.$b=()=>{n.time=performance.now(),t.postMessage(n,e.Nc)},t.loaded&&(t.$b(),delete t.$b),0}function fe(e){if(T)return qe(1,1,e);J()||(he.oc(),c.onExit&&c.onExit(e),z=true),y(e,new ce(e))}function de(e,t){if(!t&&T)throw we(e),"unwind";J()||T||(gt(),pe(Q),wt(0),rt[1].length&&ot(1,10),rt[2].length&&ot(2,10),he.oc()),fe(e)}var he={Yb:[],ac:[],qc:[],Vb:{},fc:function(){T&&he.Ec()},Pc:function(){},Ec:function(){he.receiveObjectTransfer=he.Gc,he.threadInitTLS=he.pc,he.setExitStatus=he.nc,C=false},nc:function(){},oc:function(){for(var e of Object.values(he.Vb))he.mc(e);for(e of he.Yb)e.terminate();he.Yb=[]},mc:function(e){var t=e.Ub;delete he.Vb[t],he.Yb.push(e),he.ac.splice(he.ac.indexOf(e),1),e.Ub=0,xt(t)},Gc:function(){},pc:function(){he.qc.forEach((e=>e()))},Fc:function(e,t){e.onmessage=n=>{var r=(n=n.data).cmd;if(e.Ub&&(he.Bc=e.Ub),n.targetThread&&n.targetThread!=ht()){var o=he.Vb[n.Qc];o?o.postMessage(n,n.transferList):P('Internal error! Worker sent a message "'+r+'" to target pthread '+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?Ue(n.queue):"spawnThread"===r?le(n):"cleanupThread"===r?ue(n.thread):"killThread"===r?(n=n.thread,r=he.Vb[n],delete he.Vb[n],r.terminate(),xt(n),he.ac.splice(he.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?he.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(e.loaded=true,t&&t(e),e.$b&&(e.$b(),delete e.$b)):"print"===r?O("Thread "+n.threadId+": "+n.text):"printErr"===r?P("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?e.postMessage(n):"onAbort"===r?c.onAbort&&c.onAbort(n.arg):r&&P("worker sent an unknown command "+r);he.Bc=void 0},e.onerror=e=>{throw P("worker sent an error! "+e.filename+":"+e.lineno+": "+e.message),e},x&&(e.on("message",(function(t){e.onmessage({data:t})})),e.on("error",(function(t){e.onerror(t)})),e.on("detachedExit",(function(){}))),e.postMessage({cmd:"load",urlOrBlob:c.mainScriptUrlOrBlob||r,wasmMemory:k,wasmModule:I})},yc:function(){var e=E("ort-wasm-threaded.worker.js");he.Yb.push(new Worker(e))},Cc:function(){return 0==he.Yb.length&&(he.yc(),he.Fc(he.Yb[0])),he.Yb.pop()}};function pe(e){for(;0<e.length;)e.shift()(c)}function me(e){var t=St();return e=e(),At(t),e}function we(e){if(T)return qe(2,0,e);try{de(e)}catch(e){e instanceof ce||"unwind"==e||y(1,e)}}c.PThread=he,c.establishStackSpace=function(){var e=ht(),t=i()[e+44>>2>>>0];e=i()[e+48>>2>>>0],Et(t,t-e),At(t)};var ge=[];function ve(e){var t=ge[e];return t||(e>=ge.length&&(ge.length=e+1),ge[e]=t=H.get(e)),t}c.invokeEntryPoint=function(e,t){e=ve(e)(t),J()?he.nc(e):Tt(e)};var ye,_e,be=[],xe=0,Te=0;function Me(e){this.Zb=e,this.Sb=e-24,this.xc=function(e){s()[this.Sb+4>>2>>>0]=e},this.bc=function(){return s()[this.Sb+4>>2>>>0]},this.wc=function(e){s()[this.Sb+8>>2>>>0]=e},this.Dc=function(){return s()[this.Sb+8>>2>>>0]},this.rc=function(){i()[this.Sb>>2>>>0]=0},this.hc=function(e){e=e?1:0,t()[this.Sb+12>>0>>>0]=e},this.uc=function(){return 0!=t()[this.Sb+12>>0>>>0]},this.ic=function(e){e=e?1:0,t()[this.Sb+13>>0>>>0]=e},this.kc=function(){return 0!=t()[this.Sb+13>>0>>>0]},this.fc=function(e,t){this.cc(0),this.xc(e),this.wc(t),this.rc(),this.hc(false),this.ic(false)},this.sc=function(){Atomics.add(i(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(i(),this.Sb>>2,1)},this.cc=function(e){s()[this.Sb+16>>2>>>0]=e},this.tc=function(){return s()[this.Sb+16>>2>>>0]},this.vc=function(){if(Pt(this.bc()))return s()[this.Zb>>2>>>0];var e=this.tc();return 0!==e?e:this.Zb}}function Ee(e){return mt(new Me(e).Sb)}function Se(e,t,n,r){return T?qe(3,1,e,t,n,r):Ae(e,t,n,r)}function Ae(e,t,n,r){if("undefined"==typeof SharedArrayBuffer)return P("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var o=[];return T&&0===o.length?Se(e,t,n,r):(e={Ic:n,Ub:e,zc:r,Nc:o},T?(e.Oc="spawnThread",postMessage(e,o),0):le(e))}function $e(e,t,n){return T?qe(4,1,e,t,n):0}function Oe(e,t){if(T)return qe(5,1,e,t)}function Pe(e,t){if(T)return qe(6,1,e,t)}function Ce(e,t,n){if(T)return qe(7,1,e,t,n)}function ke(e,t,n){return T?qe(8,1,e,t,n):0}function Ie(e,t){if(T)return qe(9,1,e,t)}function Fe(e,t,n){if(T)return qe(10,1,e,t,n)}function Ne(e,t,n,r){if(T)return qe(11,1,e,t,n,r)}function De(e,t,n,r){if(T)return qe(12,1,e,t,n,r)}function Re(e,t,n,r){if(T)return qe(13,1,e,t,n,r)}function Le(e){if(T)return qe(14,1,e)}function je(e,t){if(T)return qe(15,1,e,t)}function ze(e,t,n){if(T)return qe(16,1,e,t,n)}function Ue(e){Atomics.store(i(),e>>2,1),ht()&&bt(e),Atomics.compareExchange(i(),e>>2,1,0)}function Be(e){return s()[e>>>2]+4294967296*i()[e+4>>>2]}function Ve(e,t,n,r,o,i){return T?qe(17,1,e,t,n,r,o,i):-52}function Ze(e,t,n,r,o,i){if(T)return qe(18,1,e,t,n,r,o,i)}function Ge(e){var n=G(e)+1,r=pt(n);return r&&Z(e,t(),r,n),r}function We(e,t,n){function r(e){return(e=e.toTimeString().match(/\(([A-Za-z ]+)\)$/))?e[1]:"GMT"}if(T)return qe(19,1,e,t,n);var o=(new Date).getFullYear(),a=new Date(o,0,1),c=new Date(o,6,1);o=a.getTimezoneOffset();var u=c.getTimezoneOffset(),l=Math.max(o,u);i()[e>>2>>>0]=60*l,i()[t>>2>>>0]=Number(o!=u),e=r(a),t=r(c),e=Ge(e),t=Ge(t),u<o?(s()[n>>2>>>0]=e,s()[n+4>>2>>>0]=t):(s()[n>>2>>>0]=t,s()[n+4>>2>>>0]=e)}function qe(e,t){var n=arguments.length-2,r=arguments;return me((()=>{for(var o=$t(8*n),i=o>>3,s=0;s<n;s++){var c=r[2+s];a()[i+s>>>0]=c}return _t(e,n,o,t)}))}c.executeNotifiedProxyingQueue=Ue,_e=x?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:T?()=>performance.now()-c.__performance_now_clock_drift:()=>performance.now();var He,Xe=[],Ye={};function Qe(){if(!He){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:v||"./this.program"};for(e in Ye)void 0===Ye[e]?delete t[e]:t[e]=Ye[e];var n=[];for(e in t)n.push(e+"="+t[e]);He=n}return He}function Ke(e,n){if(T)return qe(20,1,e,n);var r=0;return Qe().forEach((function(o,i){var a=n+r;for(i=s()[e+4*i>>2>>>0]=a,a=0;a<o.length;++a)t()[i++>>0>>>0]=o.charCodeAt(a);t()[i>>0>>>0]=0,r+=o.length+1})),0}function Je(e,t){if(T)return qe(21,1,e,t);var n=Qe();s()[e>>2>>>0]=n.length;var r=0;return n.forEach((function(e){r+=e.length+1})),s()[t>>2>>>0]=r,0}function et(e){return T?qe(22,1,e):52}function tt(e,t,n,r){return T?qe(23,1,e,t,n,r):52}function nt(e,t,n,r,o){return T?qe(24,1,e,t,n,r,o):70}var rt=[null,[],[]];function ot(e,t){var n=rt[e];0===t||10===t?((1===e?O:P)(B(n,0)),n.length=0):n.push(t)}function it(e,t,n,r){if(T)return qe(25,1,e,t,n,r);for(var i=0,a=0;a<n;a++){var c=s()[t>>2>>>0],u=s()[t+4>>2>>>0];t+=8;for(var l=0;l<u;l++)ot(e,o()[c+l>>>0]);i+=u}return s()[r>>2>>>0]=i,0}var st=0;function at(e){return 0==e%4&&(0!=e%100||0==e%400)}var ct=[31,29,31,30,31,30,31,31,30,31,30,31],ut=[31,28,31,30,31,30,31,31,30,31,30,31];function lt(e,n,r,o){function s(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.length<t;)e=n[0]+e;return e}function a(e,t){return s(e,t,"0")}function c(e,t){function n(e){return 0>e?-1:0<e?1:0}var r;return 0===(r=n(e.getFullYear()-t.getFullYear()))&&0===(r=n(e.getMonth()-t.getMonth()))&&(r=n(e.getDate()-t.getDate())),r}function u(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function l(e){var t=e.Wb;for(e=new Date(new Date(e.Xb+1900,0,1).getTime());0<t;){var n=e.getMonth(),r=(at(e.getFullYear())?ct:ut)[n];if(!(t>r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=u(new Date(e.getFullYear(),0,4)),n=u(n),0>=c(t,e)?0>=c(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var f=i()[o+40>>2>>>0];for(var d in o={Lc:i()[o>>2>>>0],Kc:i()[o+4>>2>>>0],dc:i()[o+8>>2>>>0],jc:i()[o+12>>2>>>0],ec:i()[o+16>>2>>>0],Xb:i()[o+20>>2>>>0],Tb:i()[o+24>>2>>>0],Wb:i()[o+28>>2>>>0],Rc:i()[o+32>>2>>>0],Jc:i()[o+36>>2>>>0],Mc:f?V(f):""},r=V(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(d,"g"),f[d]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(d in f={"%a":function(e){return h[e.Tb].substring(0,3)},"%A":function(e){return h[e.Tb]},"%b":function(e){return p[e.ec].substring(0,3)},"%B":function(e){return p[e.ec]},"%C":function(e){return a((e.Xb+1900)/100|0,2)},"%d":function(e){return a(e.jc,2)},"%e":function(e){return s(e.jc,2," ")},"%g":function(e){return l(e).toString().substring(2)},"%G":function(e){return l(e)},"%H":function(e){return a(e.dc,2)},"%I":function(e){return 0==(e=e.dc)?e=12:12<e&&(e-=12),a(e,2)},"%j":function(e){for(var t=0,n=0;n<=e.ec-1;t+=(at(e.Xb+1900)?ct:ut)[n++]);return a(e.jc+t,3)},"%m":function(e){return a(e.ec+1,2)},"%M":function(e){return a(e.Kc,2)},"%n":function(){return"\n"},"%p":function(e){return 0<=e.dc&&12>e.dc?"AM":"PM"},"%S":function(e){return a(e.Lc,2)},"%t":function(){return"\t"},"%u":function(e){return e.Tb||7},"%U":function(e){return a(Math.floor((e.Wb+7-e.Tb)/7),2)},"%V":function(e){var t=Math.floor((e.Wb+7-(e.Tb+6)%7)/7);if(2>=(e.Tb+371-e.Wb-2)%7&&t++,t)53==t&&(4==(n=(e.Tb+371-e.Wb)%7)||3==n&&at(e.Xb)||(t=1));else{t=52;var n=(e.Tb+7-e.Wb-1)%7;(4==n||5==n&&at(e.Xb%400-1))&&t++}return a(t,2)},"%w":function(e){return e.Tb},"%W":function(e){return a(Math.floor((e.Wb+7-(e.Tb+6)%7)/7),2)},"%y":function(e){return(e.Xb+1900).toString().substring(2)},"%Y":function(e){return e.Xb+1900},"%z":function(e){var t=0<=(e=e.Jc);return e=Math.abs(e)/60,(t?"+":"-")+String("0000"+(e/60*100+e%60)).slice(-4)},"%Z":function(e){return e.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\0\0"),f)r.includes(d)&&(r=r.replace(new RegExp(d,"g"),f[d](o)));return d=function(e){var t=Array(G(e)+1);return Z(e,t,0,t.length),t}(r=r.replace(/\0\0/g,"%")),d.length>n?0:(function(e,n){t().set(e,n>>>0)}(d,e),d.length-1)}he.fc();var ft=[null,fe,we,Se,$e,Oe,Pe,Ce,ke,Ie,Fe,Ne,De,Re,Le,je,ze,Ve,Ze,We,Ke,Je,et,tt,nt,it],dt={b:function(e){return pt(e+24)+24},n:function(e){return(e=new Me(e)).uc()||(e.hc(true),xe--),e.ic(false),be.push(e),e.sc(),e.vc()},ma:function(e){throw P("Unexpected exception thrown, this is not properly supported - aborting"),z=true,e},x:function(){Mt(0);var e=be.pop();if(e.Hc()&&!e.kc()){var t=e.Dc();t&&ve(t)(e.Zb),Ee(e.Zb)}Te=0},e:function(){var e=Te;if(!e)return st=0;var t=new Me(e);t.cc(e);var n=t.bc();if(!n)return st=0,e;for(var r=Array.prototype.slice.call(arguments),o=0;o<r.length;o++){var i=r[o];if(0===i||i===n)break;if(Ot(i,n,t.Sb+16))return st=i,e}return st=n,e},l:function(){var e=Te;if(!e)return st=0;var t=new Me(e);t.cc(e);var n=t.bc();if(!n)return st=0,e;for(var r=Array.prototype.slice.call(arguments),o=0;o<r.length;o++){var i=r[o];if(0===i||i===n)break;if(Ot(i,n,t.Sb+16))return st=i,e}return st=n,e},h:function(){var e=Te;if(!e)return st=0;var t=new Me(e);t.cc(e);var n=t.bc();if(!n)return st=0,e;for(var r=Array.prototype.slice.call(arguments),o=0;o<r.length;o++){var i=r[o];if(0===i||i===n)break;if(Ot(i,n,t.Sb+16))return st=i,e}return st=n,e},t:Ee,M:function(){var e=be.pop();e||oe("no exception to throw");var t=e.Zb;throw e.kc()||(be.push(e),e.ic(true),e.hc(false),xe++),Te=t,t},c:function(e,t,n){throw new Me(e).fc(t,n),Te=e,xe++,e},pa:function(){return xe},Fa:function(e){vt(e,!b,1,!_),he.pc()},T:function(e){T?postMessage({cmd:"cleanupThread",thread:e}):ue(e)},xa:Ae,j:function(e){throw Te||(Te=e),e},H:$e,Ma:Oe,ua:Pe,wa:Ce,oa:ke,Ka:Ie,Ca:Fe,Ja:Ne,V:De,va:Re,sa:Le,La:je,ta:ze,Ta:function(){},X:function(){oe("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ua:function(){oe("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},W:function(){return Date.now()},ya:function(){return 2097152},Oa:function(){return true},za:function(e,t,n,r){if(e==t)setTimeout((()=>Ue(r)));else if(T)postMessage({targetThread:e,cmd:"processProxyingQueue",queue:r});else{if(!(e=he.Vb[e]))return;e.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(e,t){e=new Date(1e3*Be(e)),i()[t>>2>>>0]=e.getUTCSeconds(),i()[t+4>>2>>>0]=e.getUTCMinutes(),i()[t+8>>2>>>0]=e.getUTCHours(),i()[t+12>>2>>>0]=e.getUTCDate(),i()[t+16>>2>>>0]=e.getUTCMonth(),i()[t+20>>2>>>0]=e.getUTCFullYear()-1900,i()[t+24>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[t+28>>2>>>0]=e},Qa:function(e,t){e=new Date(1e3*Be(e)),i()[t>>2>>>0]=e.getSeconds(),i()[t+4>>2>>>0]=e.getMinutes(),i()[t+8>>2>>>0]=e.getHours(),i()[t+12>>2>>>0]=e.getDate(),i()[t+16>>2>>>0]=e.getMonth(),i()[t+20>>2>>>0]=e.getFullYear()-1900,i()[t+24>>2>>>0]=e.getDay();var n=new Date(e.getFullYear(),0,1),r=(e.getTime()-n.getTime())/864e5|0;i()[t+28>>2>>>0]=r,i()[t+36>>2>>>0]=-60*e.getTimezoneOffset(),r=new Date(e.getFullYear(),6,1).getTimezoneOffset(),e=0|(r!=(n=n.getTimezoneOffset())&&e.getTimezoneOffset()==Math.min(n,r)),i()[t+32>>2>>>0]=e},Ra:function(e){var t=new Date(i()[e+20>>2>>>0]+1900,i()[e+16>>2>>>0],i()[e+12>>2>>>0],i()[e+8>>2>>>0],i()[e+4>>2>>>0],i()[e>>2>>>0],0),n=i()[e+32>>2>>>0],r=t.getTimezoneOffset(),o=new Date(t.getFullYear(),0,1),s=new Date(t.getFullYear(),6,1).getTimezoneOffset(),a=o.getTimezoneOffset(),c=Math.min(a,s);return 0>n?i()[e+32>>2>>>0]=Number(s!=a&&c==r):0<n!=(c==r)&&(s=Math.max(a,s),t.setTime(t.getTime()+6e4*((0<n?c:s)-r))),i()[e+24>>2>>>0]=t.getDay(),n=(t.getTime()-o.getTime())/864e5|0,i()[e+28>>2>>>0]=n,i()[e>>2>>>0]=t.getSeconds(),i()[e+4>>2>>>0]=t.getMinutes(),i()[e+8>>2>>>0]=t.getHours(),i()[e+12>>2>>>0]=t.getDate(),i()[e+16>>2>>>0]=t.getMonth(),t.getTime()/1e3|0},Aa:Ve,Ba:Ze,Sa:function e(t,n,r){e.Ac||(e.Ac=true,We(t,n,r))},y:function(){oe("")},U:function(){if(!x&&!b){var e="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";ye||(ye={}),ye[e]||(ye[e]=1,x&&(e="warning: "+e),P(e))}},ra:function(){return 4294901760},B:_e,Ia:function(e,t,n){o().copyWithin(e>>>0,t>>>0,t+n>>>0)},F:function(){return x?n(3993).cpus().length:navigator.hardwareConcurrency},Da:function(e,t,n){Xe.length=t,n>>=3;for(var r=0;r<t;r++)Xe[r]=a()[n+r>>>0];return(0>e?ae[-e-1]:ft[e]).apply(null,Xe)},qa:function(e){var t=o().length;if((e>>>=0)<=t||4294901760<e)return false;for(var n=1;4>=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);var i=Math;r=Math.max(e,r),i=i.min.call(i,4294901760,r+(65536-r%65536)%65536);e:{try{k.grow(i-F.byteLength+65535>>>16),W(k.buffer);var s=1;break e}catch(e){}s=void 0}if(s)return true}return false},Na:function(){throw"unwind"},Ga:Ke,Ha:Je,J:de,I:et,S:tt,ga:nt,R:it,d:function(){return st},na:function e(r,o){e.lc||(e.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}if(x)try{var t=n(Object(function(){var e=new Error("Cannot find module 'crypto'");throw e.code="MODULE_NOT_FOUND",e}()));return()=>t.randomBytes(1)[0]}catch(e){}return()=>oe("randomDevice")}());for(var i=0;i<o;i++)t()[r+i>>0>>>0]=e.lc();return 0},ia:function(e,t,n){var r=St();try{return ve(e)(t,n)}catch(e){if(At(r),e!==e+0)throw e;Mt(1,0)}},ja:function(e,t,n){var r=St();try{return ve(e)(t,n)}catch(e){if(At(r),e!==e+0)throw e;Mt(1,0)}},K:function(e){var t=St();try{return ve(e)()}catch(e){if(At(t),e!==e+0)throw e;Mt(1,0)}},f:function(e,t){var n=St();try{return ve(e)(t)}catch(e){if(At(n),e!==e+0)throw e;Mt(1,0)}},P:function(e,t,n){var r=St();try{return ve(e)(t,n)}catch(e){if(At(r),e!==e+0)throw e;Mt(1,0)}},Q:function(e,t,n){var r=St();try{return ve(e)(t,n)}catch(e){if(At(r),e!==e+0)throw e;Mt(1,0)}},k:function(e,t,n){var r=St();try{return ve(e)(t,n)}catch(e){if(At(r),e!==e+0)throw e;Mt(1,0)}},p:function(e,t,n,r){var o=St();try{return ve(e)(t,n,r)}catch(e){if(At(o),e!==e+0)throw e;Mt(1,0)}},q:function(e,t,n,r,o){var i=St();try{return ve(e)(t,n,r,o)}catch(e){if(At(i),e!==e+0)throw e;Mt(1,0)}},N:function(e,t,n,r,o,i){var s=St();try{return ve(e)(t,n,r,o,i)}catch(e){if(At(s),e!==e+0)throw e;Mt(1,0)}},s:function(e,t,n,r,o,i){var s=St();try{return ve(e)(t,n,r,o,i)}catch(e){if(At(s),e!==e+0)throw e;Mt(1,0)}},w:function(e,t,n,r,o,i,s){var a=St();try{return ve(e)(t,n,r,o,i,s)}catch(e){if(At(a),e!==e+0)throw e;Mt(1,0)}},L:function(e,t,n,r,o,i,s,a){var c=St();try{return ve(e)(t,n,r,o,i,s,a)}catch(e){if(At(c),e!==e+0)throw e;Mt(1,0)}},E:function(e,t,n,r,o,i,s,a,c,u,l,f){var d=St();try{return ve(e)(t,n,r,o,i,s,a,c,u,l,f)}catch(e){if(At(d),e!==e+0)throw e;Mt(1,0)}},aa:function(e,t,n,r,o,i,s,a){var c=St();try{return jt(e,t,n,r,o,i,s,a)}catch(e){if(At(c),e!==e+0)throw e;Mt(1,0)}},_:function(e,t,n,r,o,i,s){var a=St();try{return kt(e,t,n,r,o,i,s)}catch(e){if(At(a),e!==e+0)throw e;Mt(1,0)}},Z:function(e,t,n,r,o){var i=St();try{return zt(e,t,n,r,o)}catch(e){if(At(i),e!==e+0)throw e;Mt(1,0)}},ca:function(e,t,n,r){var o=St();try{return Rt(e,t,n,r)}catch(e){if(At(o),e!==e+0)throw e;Mt(1,0)}},$:function(e){var t=St();try{return Ct(e)}catch(e){if(At(t),e!==e+0)throw e;Mt(1,0)}},ba:function(e,t){var n=St();try{return Lt(e,t)}catch(e){if(At(n),e!==e+0)throw e;Mt(1,0)}},Y:function(e,t,n){var r=St();try{return It(e,t,n)}catch(e){if(At(r),e!==e+0)throw e;Mt(1,0)}},g:function(e){var t=St();try{ve(e)()}catch(e){if(At(t),e!==e+0)throw e;Mt(1,0)}},r:function(e,t){var n=St();try{ve(e)(t)}catch(e){if(At(n),e!==e+0)throw e;Mt(1,0)}},i:function(e,t,n){var r=St();try{ve(e)(t,n)}catch(e){if(At(r),e!==e+0)throw e;Mt(1,0)}},ha:function(e,t,n,r){var o=St();try{ve(e)(t,n,r)}catch(e){if(At(o),e!==e+0)throw e;Mt(1,0)}},m:function(e,t,n,r){var o=St();try{ve(e)(t,n,r)}catch(e){if(At(o),e!==e+0)throw e;Mt(1,0)}},v:function(e,t,n,r,o){var i=St();try{ve(e)(t,n,r,o)}catch(e){if(At(i),e!==e+0)throw e;Mt(1,0)}},u:function(e,t,n,r,o,i){var s=St();try{ve(e)(t,n,r,o,i)}catch(e){if(At(s),e!==e+0)throw e;Mt(1,0)}},O:function(e,t,n,r,o,i,s){var a=St();try{ve(e)(t,n,r,o,i,s)}catch(e){if(At(a),e!==e+0)throw e;Mt(1,0)}},A:function(e,t,n,r,o,i,s,a){var c=St();try{ve(e)(t,n,r,o,i,s,a)}catch(e){if(At(c),e!==e+0)throw e;Mt(1,0)}},ka:function(e,t,n,r,o,i,s,a,c){var u=St();try{ve(e)(t,n,r,o,i,s,a,c)}catch(e){if(At(u),e!==e+0)throw e;Mt(1,0)}},C:function(e,t,n,r,o,i,s,a,c,u,l){var f=St();try{ve(e)(t,n,r,o,i,s,a,c,u,l)}catch(e){if(At(f),e!==e+0)throw e;Mt(1,0)}},D:function(e,t,n,r,o,i,s,a,c,u,l,f,d,h,p,m){var w=St();try{ve(e)(t,n,r,o,i,s,a,c,u,l,f,d,h,p,m)}catch(e){if(At(w),e!==e+0)throw e;Mt(1,0)}},fa:function(e,t,n,r,o,i,s,a){var c=St();try{Ft(e,t,n,r,o,i,s,a)}catch(e){if(At(c),e!==e+0)throw e;Mt(1,0)}},da:function(e,t,n,r,o,i,s,a,c,u,l,f){var d=St();try{Dt(e,t,n,r,o,i,s,a,c,u,l,f)}catch(e){if(At(d),e!==e+0)throw e;Mt(1,0)}},ea:function(e,t,n,r,o,i){var s=St();try{Nt(e,t,n,r,o,i)}catch(e){if(At(s),e!==e+0)throw e;Mt(1,0)}},o:function(e){return e},a:k||c.wasmMemory,G:function(e){st=e},la:lt,z:function(e,t,n,r){return lt(e,t,n,r)}};!function(){function e(e,t){c.asm=e.exports,he.qc.push(c.asm.sb),H=c.asm.ub,Y.unshift(c.asm.Va),I=t,T||(ne--,c.monitorRunDependencies&&c.monitorRunDependencies(ne),0==ne&&(re&&(e=re,re=null,e())))}function t(t){e(t.instance,t.module)}function n(e){return function(){if(!$&&(_||b)){if("function"==typeof fetch&&!te.startsWith("file://"))return fetch(te,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+te+"'";return e.arrayBuffer()})).catch((function(){return se()}));if(d)return new Promise((function(e,t){d(te,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return se()}))}().then((function(e){return WebAssembly.instantiate(e,r)})).then((function(e){return e})).then(e,(function(e){P("failed to asynchronously prepare wasm: "+e),oe(e)}))}var r={a:dt};if(T||(ne++,c.monitorRunDependencies&&c.monitorRunDependencies(ne)),c.instantiateWasm)try{return c.instantiateWasm(r,e)}catch(e){return P("Module.instantiateWasm callback failed with error: "+e),false}($||"function"!=typeof WebAssembly.instantiateStreaming||ie()||te.startsWith("file://")||x||"function"!=typeof fetch?n(t):fetch(te,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,r).then(t,(function(e){return P("wasm streaming compile failed: "+e),P("falling back to ArrayBuffer instantiation"),n(t)}))}))).catch(l)}(),c.___wasm_call_ctors=function(){return(c.___wasm_call_ctors=c.asm.Va).apply(null,arguments)},c._OrtInit=function(){return(c._OrtInit=c.asm.Wa).apply(null,arguments)},c._OrtCreateSessionOptions=function(){return(c._OrtCreateSessionOptions=c.asm.Xa).apply(null,arguments)},c._OrtAppendExecutionProvider=function(){return(c._OrtAppendExecutionProvider=c.asm.Ya).apply(null,arguments)},c._OrtAddSessionConfigEntry=function(){return(c._OrtAddSessionConfigEntry=c.asm.Za).apply(null,arguments)},c._OrtReleaseSessionOptions=function(){return(c._OrtReleaseSessionOptions=c.asm._a).apply(null,arguments)},c._OrtCreateSession=function(){return(c._OrtCreateSession=c.asm.$a).apply(null,arguments)},c._OrtReleaseSession=function(){return(c._OrtReleaseSession=c.asm.ab).apply(null,arguments)},c._OrtGetInputCount=function(){return(c._OrtGetInputCount=c.asm.bb).apply(null,arguments)},c._OrtGetOutputCount=function(){return(c._OrtGetOutputCount=c.asm.cb).apply(null,arguments)},c._OrtGetInputName=function(){return(c._OrtGetInputName=c.asm.db).apply(null,arguments)},c._OrtGetOutputName=function(){return(c._OrtGetOutputName=c.asm.eb).apply(null,arguments)},c._OrtFree=function(){return(c._OrtFree=c.asm.fb).apply(null,arguments)},c._OrtCreateTensor=function(){return(c._OrtCreateTensor=c.asm.gb).apply(null,arguments)},c._OrtGetTensorData=function(){return(c._OrtGetTensorData=c.asm.hb).apply(null,arguments)},c._OrtReleaseTensor=function(){return(c._OrtReleaseTensor=c.asm.ib).apply(null,arguments)},c._OrtCreateRunOptions=function(){return(c._OrtCreateRunOptions=c.asm.jb).apply(null,arguments)},c._OrtAddRunConfigEntry=function(){return(c._OrtAddRunConfigEntry=c.asm.kb).apply(null,arguments)},c._OrtReleaseRunOptions=function(){return(c._OrtReleaseRunOptions=c.asm.lb).apply(null,arguments)},c._OrtRun=function(){return(c._OrtRun=c.asm.mb).apply(null,arguments)},c._OrtEndProfiling=function(){return(c._OrtEndProfiling=c.asm.nb).apply(null,arguments)};var ht=c._pthread_self=function(){return(ht=c._pthread_self=c.asm.ob).apply(null,arguments)},pt=c._malloc=function(){return(pt=c._malloc=c.asm.pb).apply(null,arguments)},mt=c._free=function(){return(mt=c._free=c.asm.qb).apply(null,arguments)},wt=c._fflush=function(){return(wt=c._fflush=c.asm.rb).apply(null,arguments)};c.__emscripten_tls_init=function(){return(c.__emscripten_tls_init=c.asm.sb).apply(null,arguments)};var gt=c.___funcs_on_exit=function(){return(gt=c.___funcs_on_exit=c.asm.tb).apply(null,arguments)},vt=c.__emscripten_thread_init=function(){return(vt=c.__emscripten_thread_init=c.asm.vb).apply(null,arguments)};c.__emscripten_thread_crashed=function(){return(c.__emscripten_thread_crashed=c.asm.wb).apply(null,arguments)};var yt,_t=c._emscripten_run_in_main_runtime_thread_js=function(){return(_t=c._emscripten_run_in_main_runtime_thread_js=c.asm.xb).apply(null,arguments)},bt=c.__emscripten_proxy_execute_task_queue=function(){return(bt=c.__emscripten_proxy_execute_task_queue=c.asm.yb).apply(null,arguments)},xt=c.__emscripten_thread_free_data=function(){return(xt=c.__emscripten_thread_free_data=c.asm.zb).apply(null,arguments)},Tt=c.__emscripten_thread_exit=function(){return(Tt=c.__emscripten_thread_exit=c.asm.Ab).apply(null,arguments)},Mt=c._setThrew=function(){return(Mt=c._setThrew=c.asm.Bb).apply(null,arguments)},Et=c._emscripten_stack_set_limits=function(){return(Et=c._emscripten_stack_set_limits=c.asm.Cb).apply(null,arguments)},St=c.stackSave=function(){return(St=c.stackSave=c.asm.Db).apply(null,arguments)},At=c.stackRestore=function(){return(At=c.stackRestore=c.asm.Eb).apply(null,arguments)},$t=c.stackAlloc=function(){return($t=c.stackAlloc=c.asm.Fb).apply(null,arguments)},Ot=c.___cxa_can_catch=function(){return(Ot=c.___cxa_can_catch=c.asm.Gb).apply(null,arguments)},Pt=c.___cxa_is_pointer_type=function(){return(Pt=c.___cxa_is_pointer_type=c.asm.Hb).apply(null,arguments)},Ct=c.dynCall_j=function(){return(Ct=c.dynCall_j=c.asm.Ib).apply(null,arguments)},kt=c.dynCall_iiiiij=function(){return(kt=c.dynCall_iiiiij=c.asm.Jb).apply(null,arguments)},It=c.dynCall_jii=function(){return(It=c.dynCall_jii=c.asm.Kb).apply(null,arguments)},Ft=c.dynCall_viiiiij=function(){return(Ft=c.dynCall_viiiiij=c.asm.Lb).apply(null,arguments)},Nt=c.dynCall_vjji=function(){return(Nt=c.dynCall_vjji=c.asm.Mb).apply(null,arguments)},Dt=c.dynCall_viiijjjii=function(){return(Dt=c.dynCall_viiijjjii=c.asm.Nb).apply(null,arguments)},Rt=c.dynCall_iij=function(){return(Rt=c.dynCall_iij=c.asm.Ob).apply(null,arguments)},Lt=c.dynCall_ji=function(){return(Lt=c.dynCall_ji=c.asm.Pb).apply(null,arguments)},jt=c.dynCall_iiiiiij=function(){return(jt=c.dynCall_iiiiiij=c.asm.Qb).apply(null,arguments)},zt=c.dynCall_iiij=function(){return(zt=c.dynCall_iiij=c.asm.Rb).apply(null,arguments)};function Ut(){function e(){if(!yt&&(yt=true,c.calledRun=true,!z)&&(T||pe(Y),u(c),c.onRuntimeInitialized&&c.onRuntimeInitialized(),!T)){if(c.postRun)for("function"==typeof c.postRun&&(c.postRun=[c.postRun]);c.postRun.length;){var e=c.postRun.shift();K.unshift(e)}pe(K)}}if(!(0<ne))if(T)u(c),T||pe(Y),postMessage({cmd:"loaded"});else{if(c.preRun)for("function"==typeof c.preRun&&(c.preRun=[c.preRun]);c.preRun.length;)ee();pe(X),0<ne||(c.setStatus?(c.setStatus("Running..."),setTimeout((function(){setTimeout((function(){c.setStatus("")}),1),e()}),1)):e())}}if(c.UTF8ToString=V,c.stringToUTF8=function(e,t,n){return Z(e,o(),t,n)},c.lengthBytesUTF8=G,c.keepRuntimeAlive=J,c.wasmMemory=k,c.stackSave=St,c.stackRestore=At,c.stackAlloc=$t,c.ExitStatus=ce,c.PThread=he,re=function e(){yt||Ut(),yt||(re=e)},c.preInit)for("function"==typeof c.preInit&&(c.preInit=[c.preInit]);0<c.preInit.length;)c.preInit.pop()();return Ut(),e.ready});e.exports=o},932:(e,t,n)=>{var r,o=(r=(r="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){var t,o,i;e=e||{},t||(t=void 0!==e?e:{}),t.ready=new Promise((function(e,t){o=e,i=t}));var s,a,c,u,l,f,d=Object.assign({},t),h="./this.program",p=(e,t)=>{throw t},m="object"==typeof window,w="function"==typeof importScripts,g="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,v="";g?(v=w?n(908).dirname(v)+"/":"//",f=()=>{l||(u=n(1384),l=n(908))},s=function(e,t){return f(),e=l.normalize(e),u.readFileSync(e,t?void 0:"utf8")},c=e=>((e=s(e,true)).buffer||(e=new Uint8Array(e)),e),a=(e,t,n)=>{f(),e=l.normalize(e),u.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},1<process.argv.length&&(h=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof Y))throw e})),process.on("unhandledRejection",(function(e){throw e})),p=(e,t)=>{if(x||0<U)throw process.exitCode=e,t;t instanceof Y||b("exiting due to exception: "+t),process.exit(e)},t.inspect=function(){return"[Emscripten Module object]"}):(m||w)&&(w?v=self.location.href:"undefined"!=typeof document&&document.currentScript&&(v=document.currentScript.src),r&&(v=r),v=0!==v.indexOf("blob:")?v.substr(0,v.replace(/[?#].*/,"").lastIndexOf("/")+1):"",s=e=>{var t=new XMLHttpRequest;return t.open("GET",e,false),t.send(null),t.responseText},w&&(c=e=>{var t=new XMLHttpRequest;return t.open("GET",e,false),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),a=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,true),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)});var y,_=t.print||console.log.bind(console),b=t.printErr||console.warn.bind(console);Object.assign(t,d),d=null,t.thisProgram&&(h=t.thisProgram),t.quit&&(p=t.quit),t.wasmBinary&&(y=t.wasmBinary);var x=t.noExitRuntime||false;"object"!=typeof WebAssembly&&W("no native wasm support detected");var T,M,E,S,A,$,O=false,P="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function C(e,t,n){var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16<n-t&&e.buffer&&P)return P.decode(e.subarray(t,n));for(r="";t<n;){var o=e[t++];if(128&o){var i=63&e[t++];if(192==(224&o))r+=String.fromCharCode((31&o)<<6|i);else{var s=63&e[t++];65536>(o=224==(240&o)?(15&o)<<12|i<<6|s:(7&o)<<18|i<<12|s<<6|63&e[t++])?r+=String.fromCharCode(o):(o-=65536,r+=String.fromCharCode(55296|o>>10,56320|1023&o))}}else r+=String.fromCharCode(o)}return r}function k(e,t){return(e>>>=0)?C(S,e,t):""}function I(e,t,n,r){if(!(0<r))return 0;var o=n>>>=0;r=n+r-1;for(var i=0;i<e.length;++i){var s=e.charCodeAt(i);if(55296<=s&&57343>=s&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++i)),127>=s){if(n>=r)break;t[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;t[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;t[n++>>>0]=224|s>>12}else{if(n+3>=r)break;t[n++>>>0]=240|s>>18,t[n++>>>0]=128|s>>12&63}t[n++>>>0]=128|s>>6&63}t[n++>>>0]=128|63&s}}return t[n>>>0]=0,n-o}function F(e){for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t}function N(){var e=T.buffer;M=e,t.HEAP8=E=new Int8Array(e),t.HEAP16=new Int16Array(e),t.HEAP32=A=new Int32Array(e),t.HEAPU8=S=new Uint8Array(e),t.HEAPU16=new Uint16Array(e),t.HEAPU32=$=new Uint32Array(e),t.HEAPF32=new Float32Array(e),t.HEAPF64=new Float64Array(e)}var D,R=[],L=[],j=[],z=[],U=0;function B(){var e=t.preRun.shift();R.unshift(e)}var V,Z=0,G=null;function W(e){throw t.onAbort&&t.onAbort(e),b(e="Aborted("+e+")"),O=true,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),i(e),e}function q(){return V.startsWith("data:application/octet-stream;base64,")}if(V="ort-wasm.wasm",!q()){var H=V;V=t.locateFile?t.locateFile(H,v):v+H}function X(){var e=V;try{if(e==V&&y)return new Uint8Array(y);if(c)return c(e);throw"both async and sync fetching of the wasm failed"}catch(e){W(e)}}function Y(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function Q(e){for(;0<e.length;)e.shift()(t)}var K=[],J=0,ee=0;function te(e){this.Db=e,this.zb=e-24,this.Ub=function(e){$[this.zb+4>>2>>>0]=e},this.Eb=function(){return $[this.zb+4>>2>>>0]},this.Sb=function(e){$[this.zb+8>>2>>>0]=e},this.Wb=function(){return $[this.zb+8>>2>>>0]},this.Tb=function(){A[this.zb>>2>>>0]=0},this.Ib=function(e){E[this.zb+12>>0>>>0]=e?1:0},this.Pb=function(){return 0!=E[this.zb+12>>0>>>0]},this.Jb=function(e){E[this.zb+13>>0>>>0]=e?1:0},this.Lb=function(){return 0!=E[this.zb+13>>0>>>0]},this.Rb=function(e,t){this.Fb(0),this.Ub(e),this.Sb(t),this.Tb(),this.Ib(false),this.Jb(false)},this.Nb=function(){A[this.zb>>2>>>0]+=1},this.Xb=function(){var e=A[this.zb>>2>>>0];return A[this.zb>>2>>>0]=e-1,1===e},this.Fb=function(e){$[this.zb+16>>2>>>0]=e},this.Ob=function(){return $[this.zb+16>>2>>>0]},this.Qb=function(){if(Ae(this.Eb()))return $[this.Db>>2>>>0];var e=this.Ob();return 0!==e?e:this.Db}}function ne(e){return ye(new te(e).zb)}var re=[];function oe(e){var t=re[e];return t||(e>=re.length&&(re.length=e+1),re[e]=t=D.get(e)),t}function ie(e){var t=F(e)+1,n=ve(t);return n&&I(e,E,n,t),n}var se={};function ae(){if(!ce){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:h||"./this.program"};for(e in se)void 0===se[e]?delete t[e]:t[e]=se[e];var n=[];for(e in t)n.push(e+"="+t[e]);ce=n}return ce}var ce,ue=[null,[],[]];function le(e,t){var n=ue[e];0===t||10===t?((1===e?_:b)(C(n,0)),n.length=0):n.push(t)}var fe=0;function de(e){return 0==e%4&&(0!=e%100||0==e%400)}var he=[31,29,31,30,31,30,31,31,30,31,30,31],pe=[31,28,31,30,31,30,31,31,30,31,30,31];function me(e,t,n,r){function o(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.length<t;)e=n[0]+e;return e}function i(e,t){return o(e,t,"0")}function s(e,t){function n(e){return 0>e?-1:0<e?1:0}var r;return 0===(r=n(e.getFullYear()-t.getFullYear()))&&0===(r=n(e.getMonth()-t.getMonth()))&&(r=n(e.getDate()-t.getDate())),r}function a(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function c(e){var t=e.Bb;for(e=new Date(new Date(e.Cb+1900,0,1).getTime());0<t;){var n=e.getMonth(),r=(de(e.getFullYear())?he:pe)[n];if(!(t>r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=a(new Date(e.getFullYear(),0,4)),n=a(n),0>=s(t,e)?0>=s(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var u=A[r+40>>2>>>0];for(var l in r={$b:A[r>>2>>>0],Zb:A[r+4>>2>>>0],Gb:A[r+8>>2>>>0],Kb:A[r+12>>2>>>0],Hb:A[r+16>>2>>>0],Cb:A[r+20>>2>>>0],Ab:A[r+24>>2>>>0],Bb:A[r+28>>2>>>0],bc:A[r+32>>2>>>0],Yb:A[r+36>>2>>>0],ac:u?k(u):""},n=k(n),u={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),u[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(l in u={"%a":function(e){return f[e.Ab].substring(0,3)},"%A":function(e){return f[e.Ab]},"%b":function(e){return d[e.Hb].substring(0,3)},"%B":function(e){return d[e.Hb]},"%C":function(e){return i((e.Cb+1900)/100|0,2)},"%d":function(e){return i(e.Kb,2)},"%e":function(e){return o(e.Kb,2," ")},"%g":function(e){return c(e).toString().substring(2)},"%G":function(e){return c(e)},"%H":function(e){return i(e.Gb,2)},"%I":function(e){return 0==(e=e.Gb)?e=12:12<e&&(e-=12),i(e,2)},"%j":function(e){for(var t=0,n=0;n<=e.Hb-1;t+=(de(e.Cb+1900)?he:pe)[n++]);return i(e.Kb+t,3)},"%m":function(e){return i(e.Hb+1,2)},"%M":function(e){return i(e.Zb,2)},"%n":function(){return"\n"},"%p":function(e){return 0<=e.Gb&&12>e.Gb?"AM":"PM"},"%S":function(e){return i(e.$b,2)},"%t":function(){return"\t"},"%u":function(e){return e.Ab||7},"%U":function(e){return i(Math.floor((e.Bb+7-e.Ab)/7),2)},"%V":function(e){var t=Math.floor((e.Bb+7-(e.Ab+6)%7)/7);if(2>=(e.Ab+371-e.Bb-2)%7&&t++,t)53==t&&(4==(n=(e.Ab+371-e.Bb)%7)||3==n&&de(e.Cb)||(t=1));else{t=52;var n=(e.Ab+7-e.Bb-1)%7;(4==n||5==n&&de(e.Cb%400-1))&&t++}return i(t,2)},"%w":function(e){return e.Ab},"%W":function(e){return i(Math.floor((e.Bb+7-(e.Ab+6)%7)/7),2)},"%y":function(e){return(e.Cb+1900).toString().substring(2)},"%Y":function(e){return e.Cb+1900},"%z":function(e){var t=0<=(e=e.Yb);return e=Math.abs(e)/60,(t?"+":"-")+String("0000"+(e/60*100+e%60)).slice(-4)},"%Z":function(e){return e.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\0\0"),u)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),u[l](r)));return l=function(e){var t=Array(F(e)+1);return I(e,t,0,t.length),t}(n=n.replace(/\0\0/g,"%")),l.length>t?0:(E.set(l,e>>>0),l.length-1)}var we={a:function(e){return ve(e+24)+24},m:function(e){return(e=new te(e)).Pb()||(e.Ib(true),J--),e.Jb(false),K.push(e),e.Nb(),e.Qb()},ia:function(e){throw b("Unexpected exception thrown, this is not properly supported - aborting"),O=true,e},w:function(){xe(0);var e=K.pop();if(e.Xb()&&!e.Lb()){var t=e.Wb();t&&oe(t)(e.Db),ne(e.Db)}ee=0},d:function(){var e=ee;if(!e)return fe=0;var t=new te(e);t.Fb(e);var n=t.Eb();if(!n)return fe=0,e;for(var r=Array.prototype.slice.call(arguments),o=0;o<r.length;o++){var i=r[o];if(0===i||i===n)break;if(Se(i,n,t.zb+16))return fe=i,e}return fe=n,e},k:function(){var e=ee;if(!e)return fe=0;var t=new te(e);t.Fb(e);var n=t.Eb();if(!n)return fe=0,e;for(var r=Array.prototype.slice.call(arguments),o=0;o<r.length;o++){var i=r[o];if(0===i||i===n)break;if(Se(i,n,t.zb+16))return fe=i,e}return fe=n,e},g:function(){var e=ee;if(!e)return fe=0;var t=new te(e);t.Fb(e);var n=t.Eb();if(!n)return fe=0,e;for(var r=Array.prototype.slice.call(arguments),o=0;o<r.length;o++){var i=r[o];if(0===i||i===n)break;if(Se(i,n,t.zb+16))return fe=i,e}return fe=n,e},s:ne,L:function(){var e=K.pop();e||W("no exception to throw");var t=e.Db;throw e.Lb()||(K.push(e),e.Jb(true),e.Ib(false),J++),ee=t,t},b:function(e,t,n){throw new te(e).Rb(t,n),ee=e,J++,e},la:function(){return J},i:function(e){throw ee||(ee=e),e},H:function(){return 0},Ba:function(){},pa:function(){},ra:function(){},ka:function(){return 0},za:function(){},ua:function(){},ya:function(){},R:function(){},qa:function(){},na:function(){},Aa:function(){},oa:function(){},Ha:function(){},Ja:function(){W("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ia:function(){W("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},S:function(){return Date.now()},Ca:function(){return true},Da:function(e,t){e=new Date(1e3*($[e>>>2]+4294967296*A[e+4>>>2])),A[t>>2>>>0]=e.getUTCSeconds(),A[t+4>>2>>>0]=e.getUTCMinutes(),A[t+8>>2>>>0]=e.getUTCHours(),A[t+12>>2>>>0]=e.getUTCDate(),A[t+16>>2>>>0]=e.getUTCMonth(),A[t+20>>2>>>0]=e.getUTCFullYear()-1900,A[t+24>>2>>>0]=e.getUTCDay(),A[t+28>>2>>>0]=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(e,t){e=new Date(1e3*($[e>>>2]+4294967296*A[e+4>>>2])),A[t>>2>>>0]=e.getSeconds(),A[t+4>>2>>>0]=e.getMinutes(),A[t+8>>2>>>0]=e.getHours(),A[t+12>>2>>>0]=e.getDate(),A[t+16>>2>>>0]=e.getMonth(),A[t+20>>2>>>0]=e.getFullYear()-1900,A[t+24>>2>>>0]=e.getDay();var n=new Date(e.getFullYear(),0,1);A[t+28>>2>>>0]=(e.getTime()-n.getTime())/864e5|0,A[t+36>>2>>>0]=-60*e.getTimezoneOffset();var r=new Date(e.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),A[t+32>>2>>>0]=0|(r!=n&&e.getTimezoneOffset()==Math.min(n,r))},Fa:function(e){var t=new Date(A[e+20>>2>>>0]+1900,A[e+16>>2>>>0],A[e+12>>2>>>0],A[e+8>>2>>>0],A[e+4>>2>>>0],A[e>>2>>>0],0),n=A[e+32>>2>>>0],r=t.getTimezoneOffset(),o=new Date(t.getFullYear(),0,1),i=new Date(t.getFullYear(),6,1).getTimezoneOffset(),s=o.getTimezoneOffset(),a=Math.min(s,i);return 0>n?A[e+32>>2>>>0]=Number(i!=s&&a==r):0<n!=(a==r)&&(i=Math.max(s,i),t.setTime(t.getTime()+6e4*((0<n?a:i)-r))),A[e+24>>2>>>0]=t.getDay(),A[e+28>>2>>>0]=(t.getTime()-o.getTime())/864e5|0,A[e>>2>>>0]=t.getSeconds(),A[e+4>>2>>>0]=t.getMinutes(),A[e+8>>2>>>0]=t.getHours(),A[e+12>>2>>>0]=t.getDate(),A[e+16>>2>>>0]=t.getMonth(),t.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function e(t,n,r){e.Vb||(e.Vb=true,function(e,t,n){function r(e){return(e=e.toTimeString().match(/\(([A-Za-z ]+)\)$/))?e[1]:"GMT"}var o=(new Date).getFullYear(),i=new Date(o,0,1),s=new Date(o,6,1);o=i.getTimezoneOffset();var a=s.getTimezoneOffset();A[e>>2>>>0]=60*Math.max(o,a),A[t>>2>>>0]=Number(o!=a),e=r(i),t=r(s),e=ie(e),t=ie(t),a<o?($[n>>2>>>0]=e,$[n+4>>2>>>0]=t):($[n>>2>>>0]=t,$[n+4>>2>>>0]=e)}(t,n,r))},B:function(){W("")},ma:function(){return 4294901760},I:g?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.now(),xa:function(e,t,n){S.copyWithin(e>>>0,t>>>0,t+n>>>0)},G:function(e){var t=S.length;if(4294901760<(e>>>=0))return false;for(var n=1;4>=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);var o=Math;r=Math.max(e,r),o=o.min.call(o,4294901760,r+(65536-r%65536)%65536);e:{try{T.grow(o-M.byteLength+65535>>>16),N();var i=1;break e}catch(e){}i=void 0}if(i)return true}return false},va:function(e,t){var n=0;return ae().forEach((function(r,o){var i=t+n;for(o=$[e+4*o>>2>>>0]=i,i=0;i<r.length;++i)E[o++>>0>>>0]=r.charCodeAt(i);E[o>>0>>>0]=0,n+=r.length+1})),0},wa:function(e,t){var n=ae();$[e>>2>>>0]=n.length;var r=0;return n.forEach((function(e){r+=e.length+1})),$[t>>2>>>0]=r,0},ba:function(e){x||0<U||(be(),Q(j),_e(0),ue[1].length&&le(1,10),ue[2].length&&le(2,10)),x||0<U||(t.onExit&&t.onExit(e),O=true),p(e,new Y(e))},E:function(){return 52},Q:function(){return 52},ca:function(){return 70},P:function(e,t,n,r){for(var o=0,i=0;i<n;i++){var s=$[t>>2>>>0],a=$[t+4>>2>>>0];t+=8;for(var c=0;c<a;c++)le(e,S[s+c>>>0]);o+=a}return $[r>>2>>>0]=o,0},c:function(){return fe},ja:function e(t,r){e.Mb||(e.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}if(g)try{var t=n(Object(function(){var e=new Error("Cannot find module 'crypto'");throw e.code="MODULE_NOT_FOUND",e}()));return()=>t.randomBytes(1)[0]}catch(e){}return()=>W("randomDevice")}());for(var o=0;o<r;o++)E[t+o>>0>>>0]=e.Mb();return 0},ea:function(e,t,n){var r=Te();try{return oe(e)(t,n)}catch(e){if(Me(r),e!==e+0)throw e;xe(1,0)}},fa:function(e,t,n){var r=Te();try{return oe(e)(t,n)}catch(e){if(Me(r),e!==e+0)throw e;xe(1,0)}},J:function(e){var t=Te();try{return oe(e)()}catch(e){if(Me(t),e!==e+0)throw e;xe(1,0)}},e:function(e,t){var n=Te();try{return oe(e)(t)}catch(e){if(Me(n),e!==e+0)throw e;xe(1,0)}},N:function(e,t,n){var r=Te();try{return oe(e)(t,n)}catch(e){if(Me(r),e!==e+0)throw e;xe(1,0)}},O:function(e,t,n){var r=Te();try{return oe(e)(t,n)}catch(e){if(Me(r),e!==e+0)throw e;xe(1,0)}},j:function(e,t,n){var r=Te();try{return oe(e)(t,n)}catch(e){if(Me(r),e!==e+0)throw e;xe(1,0)}},o:function(e,t,n,r){var o=Te();try{return oe(e)(t,n,r)}catch(e){if(Me(o),e!==e+0)throw e;xe(1,0)}},p:function(e,t,n,r,o){var i=Te();try{return oe(e)(t,n,r,o)}catch(e){if(Me(i),e!==e+0)throw e;xe(1,0)}},M:function(e,t,n,r,o,i){var s=Te();try{return oe(e)(t,n,r,o,i)}catch(e){if(Me(s),e!==e+0)throw e;xe(1,0)}},r:function(e,t,n,r,o,i){var s=Te();try{return oe(e)(t,n,r,o,i)}catch(e){if(Me(s),e!==e+0)throw e;xe(1,0)}},v:function(e,t,n,r,o,i,s){var a=Te();try{return oe(e)(t,n,r,o,i,s)}catch(e){if(Me(a),e!==e+0)throw e;xe(1,0)}},K:function(e,t,n,r,o,i,s,a){var c=Te();try{return oe(e)(t,n,r,o,i,s,a)}catch(e){if(Me(c),e!==e+0)throw e;xe(1,0)}},D:function(e,t,n,r,o,i,s,a,c,u,l,f){var d=Te();try{return oe(e)(t,n,r,o,i,s,a,c,u,l,f)}catch(e){if(Me(d),e!==e+0)throw e;xe(1,0)}},X:function(e,t,n,r,o,i,s,a){var c=Te();try{return De(e,t,n,r,o,i,s,a)}catch(e){if(Me(c),e!==e+0)throw e;xe(1,0)}},V:function(e,t,n,r,o,i,s){var a=Te();try{return Oe(e,t,n,r,o,i,s)}catch(e){if(Me(a),e!==e+0)throw e;xe(1,0)}},U:function(e,t,n,r,o){var i=Te();try{return Re(e,t,n,r,o)}catch(e){if(Me(i),e!==e+0)throw e;xe(1,0)}},Z:function(e,t,n,r){var o=Te();try{return Fe(e,t,n,r)}catch(e){if(Me(o),e!==e+0)throw e;xe(1,0)}},W:function(e){var t=Te();try{return $e(e)}catch(e){if(Me(t),e!==e+0)throw e;xe(1,0)}},Y:function(e,t){var n=Te();try{return Ne(e,t)}catch(e){if(Me(n),e!==e+0)throw e;xe(1,0)}},T:function(e,t,n){var r=Te();try{return Pe(e,t,n)}catch(e){if(Me(r),e!==e+0)throw e;xe(1,0)}},f:function(e){var t=Te();try{oe(e)()}catch(e){if(Me(t),e!==e+0)throw e;xe(1,0)}},q:function(e,t){var n=Te();try{oe(e)(t)}catch(e){if(Me(n),e!==e+0)throw e;xe(1,0)}},h:function(e,t,n){var r=Te();try{oe(e)(t,n)}catch(e){if(Me(r),e!==e+0)throw e;xe(1,0)}},da:function(e,t,n,r){var o=Te();try{oe(e)(t,n,r)}catch(e){if(Me(o),e!==e+0)throw e;xe(1,0)}},l:function(e,t,n,r){var o=Te();try{oe(e)(t,n,r)}catch(e){if(Me(o),e!==e+0)throw e;xe(1,0)}},t:function(e,t,n,r,o){var i=Te();try{oe(e)(t,n,r,o)}catch(e){if(Me(i),e!==e+0)throw e;xe(1,0)}},u:function(e,t,n,r,o,i){var s=Te();try{oe(e)(t,n,r,o,i)}catch(e){if(Me(s),e!==e+0)throw e;xe(1,0)}},x:function(e,t,n,r,o,i,s){var a=Te();try{oe(e)(t,n,r,o,i,s)}catch(e){if(Me(a),e!==e+0)throw e;xe(1,0)}},z:function(e,t,n,r,o,i,s,a){var c=Te();try{oe(e)(t,n,r,o,i,s,a)}catch(e){if(Me(c),e!==e+0)throw e;xe(1,0)}},ga:function(e,t,n,r,o,i,s,a,c){var u=Te();try{oe(e)(t,n,r,o,i,s,a,c)}catch(e){if(Me(u),e!==e+0)throw e;xe(1,0)}},A:function(e,t,n,r,o,i,s,a,c,u,l){var f=Te();try{oe(e)(t,n,r,o,i,s,a,c,u,l)}catch(e){if(Me(f),e!==e+0)throw e;xe(1,0)}},C:function(e,t,n,r,o,i,s,a,c,u,l,f,d,h,p,m){var w=Te();try{oe(e)(t,n,r,o,i,s,a,c,u,l,f,d,h,p,m)}catch(e){if(Me(w),e!==e+0)throw e;xe(1,0)}},aa:function(e,t,n,r,o,i,s,a){var c=Te();try{Ce(e,t,n,r,o,i,s,a)}catch(e){if(Me(c),e!==e+0)throw e;xe(1,0)}},_:function(e,t,n,r,o,i,s,a,c,u,l,f){var d=Te();try{Ie(e,t,n,r,o,i,s,a,c,u,l,f)}catch(e){if(Me(d),e!==e+0)throw e;xe(1,0)}},$:function(e,t,n,r,o,i){var s=Te();try{ke(e,t,n,r,o,i)}catch(e){if(Me(s),e!==e+0)throw e;xe(1,0)}},n:function(e){return e},F:function(e){fe=e},ha:me,y:function(e,t,n,r){return me(e,t,n,r)}};!function(){function e(e){t.asm=e.exports,T=t.asm.Ka,N(),D=t.asm.ib,L.unshift(t.asm.La),Z--,t.monitorRunDependencies&&t.monitorRunDependencies(Z),0==Z&&(G&&(e=G,G=null,e()))}function n(t){e(t.instance)}function r(e){return function(){if(!y&&(m||w)){if("function"==typeof fetch&&!V.startsWith("file://"))return fetch(V,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+V+"'";return e.arrayBuffer()})).catch((function(){return X()}));if(a)return new Promise((function(e,t){a(V,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return X()}))}().then((function(e){return WebAssembly.instantiate(e,o)})).then((function(e){return e})).then(e,(function(e){b("failed to asynchronously prepare wasm: "+e),W(e)}))}var o={a:we};if(Z++,t.monitorRunDependencies&&t.monitorRunDependencies(Z),t.instantiateWasm)try{return t.instantiateWasm(o,e)}catch(e){return b("Module.instantiateWasm callback failed with error: "+e),false}(y||"function"!=typeof WebAssembly.instantiateStreaming||q()||V.startsWith("file://")||g||"function"!=typeof fetch?r(n):fetch(V,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,o).then(n,(function(e){return b("wasm streaming compile failed: "+e),b("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(i)}(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.La).apply(null,arguments)},t._OrtInit=function(){return(t._OrtInit=t.asm.Ma).apply(null,arguments)},t._OrtCreateSessionOptions=function(){return(t._OrtCreateSessionOptions=t.asm.Na).apply(null,arguments)},t._OrtAppendExecutionProvider=function(){return(t._OrtAppendExecutionProvider=t.asm.Oa).apply(null,arguments)},t._OrtAddSessionConfigEntry=function(){return(t._OrtAddSessionConfigEntry=t.asm.Pa).apply(null,arguments)},t._OrtReleaseSessionOptions=function(){return(t._OrtReleaseSessionOptions=t.asm.Qa).apply(null,arguments)},t._OrtCreateSession=function(){return(t._OrtCreateSession=t.asm.Ra).apply(null,arguments)},t._OrtReleaseSession=function(){return(t._OrtReleaseSession=t.asm.Sa).apply(null,arguments)},t._OrtGetInputCount=function(){return(t._OrtGetInputCount=t.asm.Ta).apply(null,arguments)},t._OrtGetOutputCount=function(){return(t._OrtGetOutputCount=t.asm.Ua).apply(null,arguments)},t._OrtGetInputName=function(){return(t._OrtGetInputName=t.asm.Va).apply(null,arguments)},t._OrtGetOutputName=function(){return(t._OrtGetOutputName=t.asm.Wa).apply(null,arguments)},t._OrtFree=function(){return(t._OrtFree=t.asm.Xa).apply(null,arguments)},t._OrtCreateTensor=function(){return(t._OrtCreateTensor=t.asm.Ya).apply(null,arguments)},t._OrtGetTensorData=function(){return(t._OrtGetTensorData=t.asm.Za).apply(null,arguments)},t._OrtReleaseTensor=function(){return(t._OrtReleaseTensor=t.asm._a).apply(null,arguments)},t._OrtCreateRunOptions=function(){return(t._OrtCreateRunOptions=t.asm.$a).apply(null,arguments)},t._OrtAddRunConfigEntry=function(){return(t._OrtAddRunConfigEntry=t.asm.ab).apply(null,arguments)},t._OrtReleaseRunOptions=function(){return(t._OrtReleaseRunOptions=t.asm.bb).apply(null,arguments)},t._OrtRun=function(){return(t._OrtRun=t.asm.cb).apply(null,arguments)},t._OrtEndProfiling=function(){return(t._OrtEndProfiling=t.asm.db).apply(null,arguments)};var ge,ve=t._malloc=function(){return(ve=t._malloc=t.asm.eb).apply(null,arguments)},ye=t._free=function(){return(ye=t._free=t.asm.fb).apply(null,arguments)},_e=t._fflush=function(){return(_e=t._fflush=t.asm.gb).apply(null,arguments)},be=t.___funcs_on_exit=function(){return(be=t.___funcs_on_exit=t.asm.hb).apply(null,arguments)},xe=t._setThrew=function(){return(xe=t._setThrew=t.asm.jb).apply(null,arguments)},Te=t.stackSave=function(){return(Te=t.stackSave=t.asm.kb).apply(null,arguments)},Me=t.stackRestore=function(){return(Me=t.stackRestore=t.asm.lb).apply(null,arguments)},Ee=t.stackAlloc=function(){return(Ee=t.stackAlloc=t.asm.mb).apply(null,arguments)},Se=t.___cxa_can_catch=function(){return(Se=t.___cxa_can_catch=t.asm.nb).apply(null,arguments)},Ae=t.___cxa_is_pointer_type=function(){return(Ae=t.___cxa_is_pointer_type=t.asm.ob).apply(null,arguments)},$e=t.dynCall_j=function(){return($e=t.dynCall_j=t.asm.pb).apply(null,arguments)},Oe=t.dynCall_iiiiij=function(){return(Oe=t.dynCall_iiiiij=t.asm.qb).apply(null,arguments)},Pe=t.dynCall_jii=function(){return(Pe=t.dynCall_jii=t.asm.rb).apply(null,arguments)},Ce=t.dynCall_viiiiij=function(){return(Ce=t.dynCall_viiiiij=t.asm.sb).apply(null,arguments)},ke=t.dynCall_vjji=function(){return(ke=t.dynCall_vjji=t.asm.tb).apply(null,arguments)},Ie=t.dynCall_viiijjjii=function(){return(Ie=t.dynCall_viiijjjii=t.asm.ub).apply(null,arguments)},Fe=t.dynCall_iij=function(){return(Fe=t.dynCall_iij=t.asm.vb).apply(null,arguments)},Ne=t.dynCall_ji=function(){return(Ne=t.dynCall_ji=t.asm.wb).apply(null,arguments)},De=t.dynCall_iiiiiij=function(){return(De=t.dynCall_iiiiiij=t.asm.xb).apply(null,arguments)},Re=t.dynCall_iiij=function(){return(Re=t.dynCall_iiij=t.asm.yb).apply(null,arguments)};function Le(){function e(){if(!ge&&(ge=true,t.calledRun=true,!O)){if(Q(L),o(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),t.postRun)for("function"==typeof t.postRun&&(t.postRun=[t.postRun]);t.postRun.length;){var e=t.postRun.shift();z.unshift(e)}Q(z)}}if(!(0<Z)){if(t.preRun)for("function"==typeof t.preRun&&(t.preRun=[t.preRun]);t.preRun.length;)B();Q(R),0<Z||(t.setStatus?(t.setStatus("Running..."),setTimeout((function(){setTimeout((function(){t.setStatus("")}),1),e()}),1)):e())}}if(t.UTF8ToString=k,t.stringToUTF8=function(e,t,n){return I(e,S,t,n)},t.lengthBytesUTF8=F,t.stackSave=Te,t.stackRestore=Me,t.stackAlloc=Ee,G=function e(){ge||Le(),ge||(G=e)},t.preInit)for("function"==typeof t.preInit&&(t.preInit=[t.preInit]);0<t.preInit.length;)t.preInit.pop()();return Le(),e.ready});e.exports=o},4537:e=>{e.exports=function(e,t){for(var n=new Array(arguments.length-1),r=0,o=2,i=true;o<arguments.length;)n[r++]=arguments[o++];return new Promise((function(o,s){n[r]=function(e){if(i)if(i=false,e)s(e);else{for(var t=new Array(arguments.length-1),n=0;n<t.length;)t[n++]=arguments[n];o.apply(null,t)}};try{e.apply(t||null,n)}catch(e){i&&(i=false,s(e))}}))}},7419:(e,t)=>{var n=t;n.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&"="===e.charAt(t);)++n;return Math.ceil(3*e.length)/4-n};for(var r=new Array(64),o=new Array(123),i=0;i<64;)o[r[i]=i<26?i+65:i<52?i+71:i<62?i-4:i-59|43]=i++;n.encode=function(e,t,n){for(var o,i=null,s=[],a=0,c=0;t<n;){var u=e[t++];switch(c){case 0:s[a++]=r[u>>2],o=(3&u)<<4,c=1;break;case 1:s[a++]=r[o|u>>4],o=(15&u)<<2,c=2;break;case 2:s[a++]=r[o|u>>6],s[a++]=r[63&u],c=0}a>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),a=0)}return c&&(s[a++]=r[o],s[a++]=61,1===c&&(s[a++]=61)),i?(a&&i.push(String.fromCharCode.apply(String,s.slice(0,a))),i.join("")):String.fromCharCode.apply(String,s.slice(0,a))};var s="invalid encoding";n.decode=function(e,t,n){for(var r,i=n,a=0,c=0;c<e.length;){var u=e.charCodeAt(c++);if(61===u&&a>1)break;if(void 0===(u=o[u]))throw Error(s);switch(a){case 0:r=u,a=1;break;case 1:t[n++]=r<<2|(48&u)>>4,r=u,a=2;break;case 2:t[n++]=(15&r)<<4|(60&u)>>2,r=u,a=3;break;case 3:t[n++]=(3&r)<<6|u,a=0}}if(1===a)throw Error(s);return n-i},n.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},9211:e=>{function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var n=this._listeners[e],r=0;r<n.length;)n[r].fn===t?n.splice(r,1):++r;return this},t.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var n=[],r=1;r<arguments.length;)n.push(arguments[r++]);for(r=0;r<t.length;)t[r].fn.apply(t[r++].ctx,n)}return this}},945:e=>{function t(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),n=new Uint8Array(t.buffer),r=128===n[3];function o(e,r,o){t[0]=e,r[o]=n[0],r[o+1]=n[1],r[o+2]=n[2],r[o+3]=n[3]}function i(e,r,o){t[0]=e,r[o]=n[3],r[o+1]=n[2],r[o+2]=n[1],r[o+3]=n[0]}function s(e,r){return n[0]=e[r],n[1]=e[r+1],n[2]=e[r+2],n[3]=e[r+3],t[0]}function a(e,r){return n[3]=e[r],n[2]=e[r+1],n[1]=e[r+2],n[0]=e[r+3],t[0]}e.writeFloatLE=r?o:i,e.writeFloatBE=r?i:o,e.readFloatLE=r?s:a,e.readFloatBE=r?a:s}():function(){function t(e,t,n,r){var o=t<0?1:0;if(o&&(t=-t),0===t)e(1/t>0?0:2147483648,n,r);else if(isNaN(t))e(2143289344,n,r);else if(t>34028234663852886e22)e((o<<31|2139095040)>>>0,n,r);else if(t<11754943508222875e-54)e((o<<31|Math.round(t/1401298464324817e-60))>>>0,n,r);else{var i=Math.floor(Math.log(t)/Math.LN2);e((o<<31|i+127<<23|8388607&Math.round(t*Math.pow(2,-i)*8388608))>>>0,n,r)}}function s(e,t,n){var r=e(t,n),o=2*(r>>31)+1,i=r>>>23&255,s=8388607&r;return 255===i?s?NaN:o*(1/0):0===i?1401298464324817e-60*o*s:o*Math.pow(2,i-150)*(s+8388608)}e.writeFloatLE=t.bind(null,n),e.writeFloatBE=t.bind(null,r),e.readFloatLE=s.bind(null,o),e.readFloatBE=s.bind(null,i)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),n=new Uint8Array(t.buffer),r=128===n[7];function o(e,r,o){t[0]=e,r[o]=n[0],r[o+1]=n[1],r[o+2]=n[2],r[o+3]=n[3],r[o+4]=n[4],r[o+5]=n[5],r[o+6]=n[6],r[o+7]=n[7]}function i(e,r,o){t[0]=e,r[o]=n[7],r[o+1]=n[6],r[o+2]=n[5],r[o+3]=n[4],r[o+4]=n[3],r[o+5]=n[2],r[o+6]=n[1],r[o+7]=n[0]}function s(e,r){return n[0]=e[r],n[1]=e[r+1],n[2]=e[r+2],n[3]=e[r+3],n[4]=e[r+4],n[5]=e[r+5],n[6]=e[r+6],n[7]=e[r+7],t[0]}function a(e,r){return n[7]=e[r],n[6]=e[r+1],n[5]=e[r+2],n[4]=e[r+3],n[3]=e[r+4],n[2]=e[r+5],n[1]=e[r+6],n[0]=e[r+7],t[0]}e.writeDoubleLE=r?o:i,e.writeDoubleBE=r?i:o,e.readDoubleLE=r?s:a,e.readDoubleBE=r?a:s}():function(){function t(e,t,n,r,o,i){var s=r<0?1:0;if(s&&(r=-r),0===r)e(0,o,i+t),e(1/r>0?0:2147483648,o,i+n);else if(isNaN(r))e(0,o,i+t),e(2146959360,o,i+n);else if(r>17976931348623157e292)e(0,o,i+t),e((s<<31|2146435072)>>>0,o,i+n);else{var a;if(r<22250738585072014e-324)e((a=r/5e-324)>>>0,o,i+t),e((s<<31|a/4294967296)>>>0,o,i+n);else{var c=Math.floor(Math.log(r)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=r*Math.pow(2,-c))>>>0,o,i+t),e((s<<31|c+1023<<20|1048576*a&1048575)>>>0,o,i+n)}}}function s(e,t,n,r,o){var i=e(r,o+t),s=e(r,o+n),a=2*(s>>31)+1,c=s>>>20&2047,u=4294967296*(1048575&s)+i;return 2047===c?u?NaN:a*(1/0):0===c?5e-324*a*u:a*Math.pow(2,c-1075)*(u+4503599627370496)}e.writeDoubleLE=t.bind(null,n,0,4),e.writeDoubleBE=t.bind(null,r,4,0),e.readDoubleLE=s.bind(null,o,0,4),e.readDoubleBE=s.bind(null,i,4,0)}(),e}function n(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function r(e,t,n){t[n]=e>>>24,t[n+1]=e>>>16&255,t[n+2]=e>>>8&255,t[n+3]=255&e}function o(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function i(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},7199:module=>{function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},6662:e=>{e.exports=function(e,t,n){var r=n||8192,o=r>>>1,i=null,s=r;return function(n){if(n<1||n>o)return e(n);s+n>r&&(i=e(r),s=0);var a=t.call(i,s,s+=n);return 7&s&&(s=1+(7|s)),a}}},4997:(e,t)=>{var n=t;n.length=function(e){for(var t=0,n=0,r=0;r<e.length;++r)(n=e.charCodeAt(r))<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(r+1))?(++r,t+=4):t+=3;return t},n.read=function(e,t,n){if(n-t<1)return"";for(var r,o=null,i=[],s=0;t<n;)(r=e[t++])<128?i[s++]=r:r>191&&r<224?i[s++]=(31&r)<<6|63&e[t++]:r>239&&r<365?(r=((7&r)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[s++]=55296+(r>>10),i[s++]=56320+(1023&r)):i[s++]=(15&r)<<12|(63&e[t++])<<6|63&e[t++],s>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o?(s&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))},n.write=function(e,t,n){for(var r,o,i=n,s=0;s<e.length;++s)(r=e.charCodeAt(s))<128?t[n++]=r:r<2048?(t[n++]=r>>6|192,t[n++]=63&r|128):55296==(64512&r)&&56320==(64512&(o=e.charCodeAt(s+1)))?(r=65536+((1023&r)<<10)+(1023&o),++s,t[n++]=r>>18|240,t[n++]=r>>12&63|128,t[n++]=r>>6&63|128,t[n++]=63&r|128):(t[n++]=r>>12|224,t[n++]=r>>6&63|128,t[n++]=63&r|128);return n-i}},3442:(e,t)=>{t.__esModule=true;var n=function(){function e(t){if(!t)throw new TypeError("Invalid argument; `value` has no value.");this.value=e.EMPTY,t&&e.isGuid(t)&&(this.value=t)}return e.isGuid=function(t){var n=t.toString();return t&&(t instanceof e||e.validator.test(n))},e.create=function(){return new e([e.gen(2),e.gen(1),e.gen(1),e.gen(1),e.gen(3)].join("-"))},e.createEmpty=function(){return new e("emptyguid")},e.parse=function(t){return new e(t)},e.raw=function(){return[e.gen(2),e.gen(1),e.gen(1),e.gen(1),e.gen(3)].join("-")},e.gen=function(e){for(var t="",n=0;n<e;n++)t+=(65536*(1+Math.random())|0).toString(16).substring(1);return t},e.prototype.equals=function(t){return e.isGuid(t)&&this.value===t.toString()},e.prototype.isEmpty=function(){return this.value===e.EMPTY},e.prototype.toString=function(){return this.value},e.prototype.toJSON=function(){return{value:this.value}},e.validator=new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$","i"),e.EMPTY="00000000-0000-0000-0000-000000000000",e}();t.Guid=n},3720:e=>{e.exports=n;var t=null;try{t=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function n(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function r(e){return true===(e&&e.__isLong__)}Object.defineProperty(n.prototype,"__isLong__",{value:true}),n.isLong=r;var o={},i={};function s(e,t){var n,r,s;return t?(s=0<=(e>>>=0)&&e<256)&&(r=i[e])?r:(n=c(e,(0|e)<0?-1:0,true),s&&(i[e]=n),n):(s=-128<=(e|=0)&&e<128)&&(r=o[e])?r:(n=c(e,e<0?-1:0,false),s&&(o[e]=n),n)}function a(e,t){if(isNaN(e))return t?g:w;if(t){if(e<0)return g;if(e>=h)return x}else{if(e<=-p)return T;if(e+1>=p)return b}return e<0?a(-e,t).neg():c(e%d|0,e/d|0,t)}function c(e,t,r){return new n(e,t,r)}n.fromInt=s,n.fromNumber=a,n.fromBits=c;var u=Math.pow;function l(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return w;if("number"==typeof t?(n=t,t=false):t=!!t,(n=n||10)<2||36<n)throw RangeError("radix");var r;if((r=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===r)return l(e.substring(1),t,n).neg();for(var o=a(u(n,8)),i=w,s=0;s<e.length;s+=8){var c=Math.min(8,e.length-s),f=parseInt(e.substring(s,s+c),n);if(c<8){var d=a(u(n,c));i=i.mul(d).add(a(f))}else i=(i=i.mul(o)).add(a(f))}return i.unsigned=t,i}function f(e,t){return"number"==typeof e?a(e,t):"string"==typeof e?l(e,t):c(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}n.fromString=l,n.fromValue=f;var d=4294967296,h=d*d,p=h/2,m=s(1<<24),w=s(0);n.ZERO=w;var g=s(0,true);n.UZERO=g;var v=s(1);n.ONE=v;var y=s(1,true);n.UONE=y;var _=s(-1);n.NEG_ONE=_;var b=c(-1,2147483647,false);n.MAX_VALUE=b;var x=c(-1,-1,true);n.MAX_UNSIGNED_VALUE=x;var T=c(0,-2147483648,false);n.MIN_VALUE=T;var M=n.prototype;M.toInt=function(){return this.unsigned?this.low>>>0:this.low},M.toNumber=function(){return this.unsigned?(this.high>>>0)*d+(this.low>>>0):this.high*d+(this.low>>>0)},M.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(T)){var t=a(e),n=this.div(t),r=n.mul(t).sub(this);return n.toString(e)+r.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var o=a(u(e,6),this.unsigned),i=this,s="";;){var c=i.div(o),l=(i.sub(c.mul(o)).toInt()>>>0).toString(e);if((i=c).isZero())return l+s;for(;l.length<6;)l="0"+l;s=""+l+s}},M.getHighBits=function(){return this.high},M.getHighBitsUnsigned=function(){return this.high>>>0},M.getLowBits=function(){return this.low},M.getLowBitsUnsigned=function(){return this.low>>>0},M.getNumBitsAbs=function(){if(this.isNegative())return this.eq(T)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<<t);t--);return 0!=this.high?t+33:t+1},M.isZero=function(){return 0===this.high&&0===this.low},M.eqz=M.isZero,M.isNegative=function(){return!this.unsigned&&this.high<0},M.isPositive=function(){return this.unsigned||this.high>=0},M.isOdd=function(){return 1==(1&this.low)},M.isEven=function(){return 0==(1&this.low)},M.equals=function(e){return r(e)||(e=f(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},M.eq=M.equals,M.notEquals=function(e){return!this.eq(e)},M.neq=M.notEquals,M.ne=M.notEquals,M.lessThan=function(e){return this.comp(e)<0},M.lt=M.lessThan,M.lessThanOrEqual=function(e){return this.comp(e)<=0},M.lte=M.lessThanOrEqual,M.le=M.lessThanOrEqual,M.greaterThan=function(e){return this.comp(e)>0},M.gt=M.greaterThan,M.greaterThanOrEqual=function(e){return this.comp(e)>=0},M.gte=M.greaterThanOrEqual,M.ge=M.greaterThanOrEqual,M.compare=function(e){if(r(e)||(e=f(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},M.comp=M.compare,M.negate=function(){return!this.unsigned&&this.eq(T)?T:this.not().add(v)},M.neg=M.negate,M.add=function(e){r(e)||(e=f(e));var t=this.high>>>16,n=65535&this.high,o=this.low>>>16,i=65535&this.low,s=e.high>>>16,a=65535&e.high,u=e.low>>>16,l=0,d=0,h=0,p=0;return h+=(p+=i+(65535&e.low))>>>16,d+=(h+=o+u)>>>16,l+=(d+=n+a)>>>16,l+=t+s,c((h&=65535)<<16|(p&=65535),(l&=65535)<<16|(d&=65535),this.unsigned)},M.subtract=function(e){return r(e)||(e=f(e)),this.add(e.neg())},M.sub=M.subtract,M.multiply=function(e){if(this.isZero())return w;if(r(e)||(e=f(e)),t)return c(t.mul(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned);if(e.isZero())return w;if(this.eq(T))return e.isOdd()?T:w;if(e.eq(T))return this.isOdd()?T:w;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(m)&&e.lt(m))return a(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,o=65535&this.high,i=this.low>>>16,s=65535&this.low,u=e.high>>>16,l=65535&e.high,d=e.low>>>16,h=65535&e.low,p=0,g=0,v=0,y=0;return v+=(y+=s*h)>>>16,g+=(v+=i*h)>>>16,v&=65535,g+=(v+=s*d)>>>16,p+=(g+=o*h)>>>16,g&=65535,p+=(g+=i*d)>>>16,g&=65535,p+=(g+=s*l)>>>16,p+=n*h+o*d+i*l+s*u,c((v&=65535)<<16|(y&=65535),(p&=65535)<<16|(g&=65535),this.unsigned)},M.mul=M.multiply,M.divide=function(e){if(r(e)||(e=f(e)),e.isZero())throw Error("division by zero");var n,o,i;if(t)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?c((this.unsigned?t.div_u:t.div_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?g:w;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return g;if(e.gt(this.shru(1)))return y;i=g}else{if(this.eq(T))return e.eq(v)||e.eq(_)?T:e.eq(T)?v:(n=this.shr(1).div(e).shl(1)).eq(w)?e.isNegative()?v:_:(o=this.sub(e.mul(n)),i=n.add(o.div(e)));if(e.eq(T))return this.unsigned?g:w;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();i=w}for(o=this;o.gte(e);){n=Math.max(1,Math.floor(o.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(n)/Math.LN2),l=s<=48?1:u(2,s-48),d=a(n),h=d.mul(e);h.isNegative()||h.gt(o);)h=(d=a(n-=l,this.unsigned)).mul(e);d.isZero()&&(d=v),i=i.add(d),o=o.sub(h)}return i},M.div=M.divide,M.modulo=function(e){return r(e)||(e=f(e)),t?c((this.unsigned?t.rem_u:t.rem_s)(this.low,this.high,e.low,e.high),t.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},M.mod=M.modulo,M.rem=M.modulo,M.not=function(){return c(~this.low,~this.high,this.unsigned)},M.and=function(e){return r(e)||(e=f(e)),c(this.low&e.low,this.high&e.high,this.unsigned)},M.or=function(e){return r(e)||(e=f(e)),c(this.low|e.low,this.high|e.high,this.unsigned)},M.xor=function(e){return r(e)||(e=f(e)),c(this.low^e.low,this.high^e.high,this.unsigned)},M.shiftLeft=function(e){return r(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?c(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):c(0,this.low<<e-32,this.unsigned)},M.shl=M.shiftLeft,M.shiftRight=function(e){return r(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?c(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):c(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},M.shr=M.shiftRight,M.shiftRightUnsigned=function(e){if(r(e)&&(e=e.toInt()),0==(e&=63))return this;var t=this.high;return e<32?c(this.low>>>e|t<<32-e,t>>>e,this.unsigned):c(32===e?t:t>>>e-32,0,this.unsigned)},M.shru=M.shiftRightUnsigned,M.shr_u=M.shiftRightUnsigned,M.toSigned=function(){return this.unsigned?c(this.low,this.high,false):this},M.toUnsigned=function(){return this.unsigned?this:c(this.low,this.high,true)},M.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},M.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},M.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},n.fromBytes=function(e,t,r){return r?n.fromBytesLE(e,t):n.fromBytesBE(e,t)},n.fromBytesLE=function(e,t){return new n(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},n.fromBytesBE=function(e,t){return new n(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}},1446:(e,t,n)=>{var r,o,i,s=n(2100),a=s.Reader,c=s.Writer,u=s.util,l=s.roots.default||(s.roots.default={});l.onnx=((i={}).Version=(r={},(o=Object.create(r))[r[0]="_START_VERSION"]=0,o[r[1]="IR_VERSION_2017_10_10"]=1,o[r[2]="IR_VERSION_2017_10_30"]=2,o[r[3]="IR_VERSION_2017_11_3"]=3,o[r[4]="IR_VERSION_2019_1_22"]=4,o[r[5]="IR_VERSION"]=5,o),i.AttributeProto=function(){function e(e){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.name="",e.prototype.refAttrName="",e.prototype.docString="",e.prototype.type=0,e.prototype.f=0,e.prototype.i=u.Long?u.Long.fromBits(0,0,false):0,e.prototype.s=u.newBuffer([]),e.prototype.t=null,e.prototype.g=null,e.prototype.floats=u.emptyArray,e.prototype.ints=u.emptyArray,e.prototype.strings=u.emptyArray,e.prototype.tensors=u.emptyArray,e.prototype.graphs=u.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=c.create()),null!=e.name&&e.hasOwnProperty("name")&&t.uint32(10).string(e.name),null!=e.f&&e.hasOwnProperty("f")&&t.uint32(21).float(e.f),null!=e.i&&e.hasOwnProperty("i")&&t.uint32(24).int64(e.i),null!=e.s&&e.hasOwnProperty("s")&&t.uint32(34).bytes(e.s),null!=e.t&&e.hasOwnProperty("t")&&l.onnx.TensorProto.encode(e.t,t.uint32(42).fork()).ldelim(),null!=e.g&&e.hasOwnProperty("g")&&l.onnx.GraphProto.encode(e.g,t.uint32(50).fork()).ldelim(),null!=e.floats&&e.floats.length){t.uint32(58).fork();for(var n=0;n<e.floats.length;++n)t.float(e.floats[n]);t.ldelim()}if(null!=e.ints&&e.ints.length){for(t.uint32(66).fork(),n=0;n<e.ints.length;++n)t.int64(e.ints[n]);t.ldelim()}if(null!=e.strings&&e.strings.length)for(n=0;n<e.strings.length;++n)t.uint32(74).bytes(e.strings[n]);if(null!=e.tensors&&e.tensors.length)for(n=0;n<e.tensors.length;++n)l.onnx.TensorProto.encode(e.tensors[n],t.uint32(82).fork()).ldelim();if(null!=e.graphs&&e.graphs.length)for(n=0;n<e.graphs.length;++n)l.onnx.GraphProto.encode(e.graphs[n],t.uint32(90).fork()).ldelim();return null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(106).string(e.docString),null!=e.type&&e.hasOwnProperty("type")&&t.uint32(160).int32(e.type),null!=e.refAttrName&&e.hasOwnProperty("refAttrName")&&t.uint32(170).string(e.refAttrName),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.AttributeProto;e.pos<n;){var o=e.uint32();switch(o>>>3){case 1:r.name=e.string();break;case 21:r.refAttrName=e.string();break;case 13:r.docString=e.string();break;case 20:r.type=e.int32();break;case 2:r.f=e.float();break;case 3:r.i=e.int64();break;case 4:r.s=e.bytes();break;case 5:r.t=l.onnx.TensorProto.decode(e,e.uint32());break;case 6:r.g=l.onnx.GraphProto.decode(e,e.uint32());break;case 7:if(r.floats&&r.floats.length||(r.floats=[]),2==(7&o))for(var i=e.uint32()+e.pos;e.pos<i;)r.floats.push(e.float());else r.floats.push(e.float());break;case 8:if(r.ints&&r.ints.length||(r.ints=[]),2==(7&o))for(i=e.uint32()+e.pos;e.pos<i;)r.ints.push(e.int64());else r.ints.push(e.int64());break;case 9:r.strings&&r.strings.length||(r.strings=[]),r.strings.push(e.bytes());break;case 10:r.tensors&&r.tensors.length||(r.tensors=[]),r.tensors.push(l.onnx.TensorProto.decode(e,e.uint32()));break;case 11:r.graphs&&r.graphs.length||(r.graphs=[]),r.graphs.push(l.onnx.GraphProto.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(null!=e.refAttrName&&e.hasOwnProperty("refAttrName")&&!u.isString(e.refAttrName))return"refAttrName: string expected";if(null!=e.docString&&e.hasOwnProperty("docString")&&!u.isString(e.docString))return"docString: string expected";if(null!=e.type&&e.hasOwnProperty("type"))switch(e.type){default:return"type: enum value expected";case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:}if(null!=e.f&&e.hasOwnProperty("f")&&"number"!=typeof e.f)return"f: number expected";if(null!=e.i&&e.hasOwnProperty("i")&&!(u.isInteger(e.i)||e.i&&u.isInteger(e.i.low)&&u.isInteger(e.i.high)))return"i: integer|Long expected";if(null!=e.s&&e.hasOwnProperty("s")&&!(e.s&&"number"==typeof e.s.length||u.isString(e.s)))return"s: buffer expected";if(null!=e.t&&e.hasOwnProperty("t")&&(n=l.onnx.TensorProto.verify(e.t)))return"t."+n;if(null!=e.g&&e.hasOwnProperty("g")&&(n=l.onnx.GraphProto.verify(e.g)))return"g."+n;if(null!=e.floats&&e.hasOwnProperty("floats")){if(!Array.isArray(e.floats))return"floats: array expected";for(var t=0;t<e.floats.length;++t)if("number"!=typeof e.floats[t])return"floats: number[] expected"}if(null!=e.ints&&e.hasOwnProperty("ints")){if(!Array.isArray(e.ints))return"ints: array expected";for(t=0;t<e.ints.length;++t)if(!(u.isInteger(e.ints[t])||e.ints[t]&&u.isInteger(e.ints[t].low)&&u.isInteger(e.ints[t].high)))return"ints: integer|Long[] expected"}if(null!=e.strings&&e.hasOwnProperty("strings")){if(!Array.isArray(e.strings))return"strings: array expected";for(t=0;t<e.strings.length;++t)if(!(e.strings[t]&&"number"==typeof e.strings[t].length||u.isString(e.strings[t])))return"strings: buffer[] expected"}if(null!=e.tensors&&e.hasOwnProperty("tensors")){if(!Array.isArray(e.tensors))return"tensors: array expected";for(t=0;t<e.tensors.length;++t)if(n=l.onnx.TensorProto.verify(e.tensors[t]))return"tensors."+n}if(null!=e.graphs&&e.hasOwnProperty("graphs")){if(!Array.isArray(e.graphs))return"graphs: array expected";for(t=0;t<e.graphs.length;++t){var n;if(n=l.onnx.GraphProto.verify(e.graphs[t]))return"graphs."+n}}return null},e.fromObject=function(e){if(e instanceof l.onnx.AttributeProto)return e;var t=new l.onnx.AttributeProto;switch(null!=e.name&&(t.name=String(e.name)),null!=e.refAttrName&&(t.refAttrName=String(e.refAttrName)),null!=e.docString&&(t.docString=String(e.docString)),e.type){case"UNDEFINED":case 0:t.type=0;break;case"FLOAT":case 1:t.type=1;break;case"INT":case 2:t.type=2;break;case"STRING":case 3:t.type=3;break;case"TENSOR":case 4:t.type=4;break;case"GRAPH":case 5:t.type=5;break;case"FLOATS":case 6:t.type=6;break;case"INTS":case 7:t.type=7;break;case"STRINGS":case 8:t.type=8;break;case"TENSORS":case 9:t.type=9;break;case"GRAPHS":case 10:t.type=10}if(null!=e.f&&(t.f=Number(e.f)),null!=e.i&&(u.Long?(t.i=u.Long.fromValue(e.i)).unsigned=false:"string"==typeof e.i?t.i=parseInt(e.i,10):"number"==typeof e.i?t.i=e.i:"object"==typeof e.i&&(t.i=new u.LongBits(e.i.low>>>0,e.i.high>>>0).toNumber())),null!=e.s&&("string"==typeof e.s?u.base64.decode(e.s,t.s=u.newBuffer(u.base64.length(e.s)),0):e.s.length&&(t.s=e.s)),null!=e.t){if("object"!=typeof e.t)throw TypeError(".onnx.AttributeProto.t: object expected");t.t=l.onnx.TensorProto.fromObject(e.t)}if(null!=e.g){if("object"!=typeof e.g)throw TypeError(".onnx.AttributeProto.g: object expected");t.g=l.onnx.GraphProto.fromObject(e.g)}if(e.floats){if(!Array.isArray(e.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");t.floats=[];for(var n=0;n<e.floats.length;++n)t.floats[n]=Number(e.floats[n])}if(e.ints){if(!Array.isArray(e.ints))throw TypeError(".onnx.AttributeProto.ints: array expected");for(t.ints=[],n=0;n<e.ints.length;++n)u.Long?(t.ints[n]=u.Long.fromValue(e.ints[n])).unsigned=false:"string"==typeof e.ints[n]?t.ints[n]=parseInt(e.ints[n],10):"number"==typeof e.ints[n]?t.ints[n]=e.ints[n]:"object"==typeof e.ints[n]&&(t.ints[n]=new u.LongBits(e.ints[n].low>>>0,e.ints[n].high>>>0).toNumber())}if(e.strings){if(!Array.isArray(e.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");for(t.strings=[],n=0;n<e.strings.length;++n)"string"==typeof e.strings[n]?u.base64.decode(e.strings[n],t.strings[n]=u.newBuffer(u.base64.length(e.strings[n])),0):e.strings[n].length&&(t.strings[n]=e.strings[n])}if(e.tensors){if(!Array.isArray(e.tensors))throw TypeError(".onnx.AttributeProto.tensors: array expected");for(t.tensors=[],n=0;n<e.tensors.length;++n){if("object"!=typeof e.tensors[n])throw TypeError(".onnx.AttributeProto.tensors: object expected");t.tensors[n]=l.onnx.TensorProto.fromObject(e.tensors[n])}}if(e.graphs){if(!Array.isArray(e.graphs))throw TypeError(".onnx.AttributeProto.graphs: array expected");for(t.graphs=[],n=0;n<e.graphs.length;++n){if("object"!=typeof e.graphs[n])throw TypeError(".onnx.AttributeProto.graphs: object expected");t.graphs[n]=l.onnx.GraphProto.fromObject(e.graphs[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.floats=[],n.ints=[],n.strings=[],n.tensors=[],n.graphs=[]),t.defaults){if(n.name="",n.f=0,u.Long){var r=new u.Long(0,0,false);n.i=t.longs===String?r.toString():t.longs===Number?r.toNumber():r}else n.i=t.longs===String?"0":0;t.bytes===String?n.s="":(n.s=[],t.bytes!==Array&&(n.s=u.newBuffer(n.s))),n.t=null,n.g=null,n.docString="",n.type=t.enums===String?"UNDEFINED":0,n.refAttrName=""}if(null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.f&&e.hasOwnProperty("f")&&(n.f=t.json&&!isFinite(e.f)?String(e.f):e.f),null!=e.i&&e.hasOwnProperty("i")&&("number"==typeof e.i?n.i=t.longs===String?String(e.i):e.i:n.i=t.longs===String?u.Long.prototype.toString.call(e.i):t.longs===Number?new u.LongBits(e.i.low>>>0,e.i.high>>>0).toNumber():e.i),null!=e.s&&e.hasOwnProperty("s")&&(n.s=t.bytes===String?u.base64.encode(e.s,0,e.s.length):t.bytes===Array?Array.prototype.slice.call(e.s):e.s),null!=e.t&&e.hasOwnProperty("t")&&(n.t=l.onnx.TensorProto.toObject(e.t,t)),null!=e.g&&e.hasOwnProperty("g")&&(n.g=l.onnx.GraphProto.toObject(e.g,t)),e.floats&&e.floats.length){n.floats=[];for(var o=0;o<e.floats.length;++o)n.floats[o]=t.json&&!isFinite(e.floats[o])?String(e.floats[o]):e.floats[o]}if(e.ints&&e.ints.length)for(n.ints=[],o=0;o<e.ints.length;++o)"number"==typeof e.ints[o]?n.ints[o]=t.longs===String?String(e.ints[o]):e.ints[o]:n.ints[o]=t.longs===String?u.Long.prototype.toString.call(e.ints[o]):t.longs===Number?new u.LongBits(e.ints[o].low>>>0,e.ints[o].high>>>0).toNumber():e.ints[o];if(e.strings&&e.strings.length)for(n.strings=[],o=0;o<e.strings.length;++o)n.strings[o]=t.bytes===String?u.base64.encode(e.strings[o],0,e.strings[o].length):t.bytes===Array?Array.prototype.slice.call(e.strings[o]):e.strings[o];if(e.tensors&&e.tensors.length)for(n.tensors=[],o=0;o<e.tensors.length;++o)n.tensors[o]=l.onnx.TensorProto.toObject(e.tensors[o],t);if(e.graphs&&e.graphs.length)for(n.graphs=[],o=0;o<e.graphs.length;++o)n.graphs[o]=l.onnx.GraphProto.toObject(e.graphs[o],t);return null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),null!=e.type&&e.hasOwnProperty("type")&&(n.type=t.enums===String?l.onnx.AttributeProto.AttributeType[e.type]:e.type),null!=e.refAttrName&&e.hasOwnProperty("refAttrName")&&(n.refAttrName=e.refAttrName),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.AttributeType=function(){var e={},t=Object.create(e);return t[e[0]="UNDEFINED"]=0,t[e[1]="FLOAT"]=1,t[e[2]="INT"]=2,t[e[3]="STRING"]=3,t[e[4]="TENSOR"]=4,t[e[5]="GRAPH"]=5,t[e[6]="FLOATS"]=6,t[e[7]="INTS"]=7,t[e[8]="STRINGS"]=8,t[e[9]="TENSORS"]=9,t[e[10]="GRAPHS"]=10,t}(),e}(),i.ValueInfoProto=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.name="",e.prototype.type=null,e.prototype.docString="",e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=c.create()),null!=e.name&&e.hasOwnProperty("name")&&t.uint32(10).string(e.name),null!=e.type&&e.hasOwnProperty("type")&&l.onnx.TypeProto.encode(e.type,t.uint32(18).fork()).ldelim(),null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(26).string(e.docString),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.ValueInfoProto;e.pos<n;){var o=e.uint32();switch(o>>>3){case 1:r.name=e.string();break;case 2:r.type=l.onnx.TypeProto.decode(e,e.uint32());break;case 3:r.docString=e.string();break;default:e.skipType(7&o)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(null!=e.type&&e.hasOwnProperty("type")){var t=l.onnx.TypeProto.verify(e.type);if(t)return"type."+t}return null!=e.docString&&e.hasOwnProperty("docString")&&!u.isString(e.docString)?"docString: string expected":null},e.fromObject=function(e){if(e instanceof l.onnx.ValueInfoProto)return e;var t=new l.onnx.ValueInfoProto;if(null!=e.name&&(t.name=String(e.name)),null!=e.type){if("object"!=typeof e.type)throw TypeError(".onnx.ValueInfoProto.type: object expected");t.type=l.onnx.TypeProto.fromObject(e.type)}return null!=e.docString&&(t.docString=String(e.docString)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.name="",n.type=null,n.docString=""),null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.type&&e.hasOwnProperty("type")&&(n.type=l.onnx.TypeProto.toObject(e.type,t)),null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),i.NodeProto=function(){function e(e){if(this.input=[],this.output=[],this.attribute=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.input=u.emptyArray,e.prototype.output=u.emptyArray,e.prototype.name="",e.prototype.opType="",e.prototype.domain="",e.prototype.attribute=u.emptyArray,e.prototype.docString="",e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=c.create()),null!=e.input&&e.input.length)for(var n=0;n<e.input.length;++n)t.uint32(10).string(e.input[n]);if(null!=e.output&&e.output.length)for(n=0;n<e.output.length;++n)t.uint32(18).string(e.output[n]);if(null!=e.name&&e.hasOwnProperty("name")&&t.uint32(26).string(e.name),null!=e.opType&&e.hasOwnProperty("opType")&&t.uint32(34).string(e.opType),null!=e.attribute&&e.attribute.length)for(n=0;n<e.attribute.length;++n)l.onnx.AttributeProto.encode(e.attribute[n],t.uint32(42).fork()).ldelim();return null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(50).string(e.docString),null!=e.domain&&e.hasOwnProperty("domain")&&t.uint32(58).string(e.domain),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.NodeProto;e.pos<n;){var o=e.uint32();switch(o>>>3){case 1:r.input&&r.input.length||(r.input=[]),r.input.push(e.string());break;case 2:r.output&&r.output.length||(r.output=[]),r.output.push(e.string());break;case 3:r.name=e.string();break;case 4:r.opType=e.string();break;case 7:r.domain=e.string();break;case 5:r.attribute&&r.attribute.length||(r.attribute=[]),r.attribute.push(l.onnx.AttributeProto.decode(e,e.uint32()));break;case 6:r.docString=e.string();break;default:e.skipType(7&o)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.input&&e.hasOwnProperty("input")){if(!Array.isArray(e.input))return"input: array expected";for(var t=0;t<e.input.length;++t)if(!u.isString(e.input[t]))return"input: string[] expected"}if(null!=e.output&&e.hasOwnProperty("output")){if(!Array.isArray(e.output))return"output: array expected";for(t=0;t<e.output.length;++t)if(!u.isString(e.output[t]))return"output: string[] expected"}if(null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(null!=e.opType&&e.hasOwnProperty("opType")&&!u.isString(e.opType))return"opType: string expected";if(null!=e.domain&&e.hasOwnProperty("domain")&&!u.isString(e.domain))return"domain: string expected";if(null!=e.attribute&&e.hasOwnProperty("attribute")){if(!Array.isArray(e.attribute))return"attribute: array expected";for(t=0;t<e.attribute.length;++t){var n=l.onnx.AttributeProto.verify(e.attribute[t]);if(n)return"attribute."+n}}return null!=e.docString&&e.hasOwnProperty("docString")&&!u.isString(e.docString)?"docString: string expected":null},e.fromObject=function(e){if(e instanceof l.onnx.NodeProto)return e;var t=new l.onnx.NodeProto;if(e.input){if(!Array.isArray(e.input))throw TypeError(".onnx.NodeProto.input: array expected");t.input=[];for(var n=0;n<e.input.length;++n)t.input[n]=String(e.input[n])}if(e.output){if(!Array.isArray(e.output))throw TypeError(".onnx.NodeProto.output: array expected");for(t.output=[],n=0;n<e.output.length;++n)t.output[n]=String(e.output[n])}if(null!=e.name&&(t.name=String(e.name)),null!=e.opType&&(t.opType=String(e.opType)),null!=e.domain&&(t.domain=String(e.domain)),e.attribute){if(!Array.isArray(e.attribute))throw TypeError(".onnx.NodeProto.attribute: array expected");for(t.attribute=[],n=0;n<e.attribute.length;++n){if("object"!=typeof e.attribute[n])throw TypeError(".onnx.NodeProto.attribute: object expected");t.attribute[n]=l.onnx.AttributeProto.fromObject(e.attribute[n])}}return null!=e.docString&&(t.docString=String(e.docString)),t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.input=[],n.output=[],n.attribute=[]),t.defaults&&(n.name="",n.opType="",n.docString="",n.domain=""),e.input&&e.input.length){n.input=[];for(var r=0;r<e.input.length;++r)n.input[r]=e.input[r]}if(e.output&&e.output.length)for(n.output=[],r=0;r<e.output.length;++r)n.output[r]=e.output[r];if(null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.opType&&e.hasOwnProperty("opType")&&(n.opType=e.opType),e.attribute&&e.attribute.length)for(n.attribute=[],r=0;r<e.attribute.length;++r)n.attribute[r]=l.onnx.AttributeProto.toObject(e.attribute[r],t);return null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),null!=e.domain&&e.hasOwnProperty("domain")&&(n.domain=e.domain),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),i.ModelProto=function(){function e(e){if(this.opsetImport=[],this.metadataProps=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.irVersion=u.Long?u.Long.fromBits(0,0,false):0,e.prototype.opsetImport=u.emptyArray,e.prototype.producerName="",e.prototype.producerVersion="",e.prototype.domain="",e.prototype.modelVersion=u.Long?u.Long.fromBits(0,0,false):0,e.prototype.docString="",e.prototype.graph=null,e.prototype.metadataProps=u.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=c.create()),null!=e.irVersion&&e.hasOwnProperty("irVersion")&&t.uint32(8).int64(e.irVersion),null!=e.producerName&&e.hasOwnProperty("producerName")&&t.uint32(18).string(e.producerName),null!=e.producerVersion&&e.hasOwnProperty("producerVersion")&&t.uint32(26).string(e.producerVersion),null!=e.domain&&e.hasOwnProperty("domain")&&t.uint32(34).string(e.domain),null!=e.modelVersion&&e.hasOwnProperty("modelVersion")&&t.uint32(40).int64(e.modelVersion),null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(50).string(e.docString),null!=e.graph&&e.hasOwnProperty("graph")&&l.onnx.GraphProto.encode(e.graph,t.uint32(58).fork()).ldelim(),null!=e.opsetImport&&e.opsetImport.length)for(var n=0;n<e.opsetImport.length;++n)l.onnx.OperatorSetIdProto.encode(e.opsetImport[n],t.uint32(66).fork()).ldelim();if(null!=e.metadataProps&&e.metadataProps.length)for(n=0;n<e.metadataProps.length;++n)l.onnx.StringStringEntryProto.encode(e.metadataProps[n],t.uint32(114).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.ModelProto;e.pos<n;){var o=e.uint32();switch(o>>>3){case 1:r.irVersion=e.int64();break;case 8:r.opsetImport&&r.opsetImport.length||(r.opsetImport=[]),r.opsetImport.push(l.onnx.OperatorSetIdProto.decode(e,e.uint32()));break;case 2:r.producerName=e.string();break;case 3:r.producerVersion=e.string();break;case 4:r.domain=e.string();break;case 5:r.modelVersion=e.int64();break;case 6:r.docString=e.string();break;case 7:r.graph=l.onnx.GraphProto.decode(e,e.uint32());break;case 14:r.metadataProps&&r.metadataProps.length||(r.metadataProps=[]),r.metadataProps.push(l.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.irVersion&&e.hasOwnProperty("irVersion")&&!(u.isInteger(e.irVersion)||e.irVersion&&u.isInteger(e.irVersion.low)&&u.isInteger(e.irVersion.high)))return"irVersion: integer|Long expected";if(null!=e.opsetImport&&e.hasOwnProperty("opsetImport")){if(!Array.isArray(e.opsetImport))return"opsetImport: array expected";for(var t=0;t<e.opsetImport.length;++t)if(n=l.onnx.OperatorSetIdProto.verify(e.opsetImport[t]))return"opsetImport."+n}if(null!=e.producerName&&e.hasOwnProperty("producerName")&&!u.isString(e.producerName))return"producerName: string expected";if(null!=e.producerVersion&&e.hasOwnProperty("producerVersion")&&!u.isString(e.producerVersion))return"producerVersion: string expected";if(null!=e.domain&&e.hasOwnProperty("domain")&&!u.isString(e.domain))return"domain: string expected";if(null!=e.modelVersion&&e.hasOwnProperty("modelVersion")&&!(u.isInteger(e.modelVersion)||e.modelVersion&&u.isInteger(e.modelVersion.low)&&u.isInteger(e.modelVersion.high)))return"modelVersion: integer|Long expected";if(null!=e.docString&&e.hasOwnProperty("docString")&&!u.isString(e.docString))return"docString: string expected";if(null!=e.graph&&e.hasOwnProperty("graph")&&(n=l.onnx.GraphProto.verify(e.graph)))return"graph."+n;if(null!=e.metadataProps&&e.hasOwnProperty("metadataProps")){if(!Array.isArray(e.metadataProps))return"metadataProps: array expected";for(t=0;t<e.metadataProps.length;++t){var n;if(n=l.onnx.StringStringEntryProto.verify(e.metadataProps[t]))return"metadataProps."+n}}return null},e.fromObject=function(e){if(e instanceof l.onnx.ModelProto)return e;var t=new l.onnx.ModelProto;if(null!=e.irVersion&&(u.Long?(t.irVersion=u.Long.fromValue(e.irVersion)).unsigned=false:"string"==typeof e.irVersion?t.irVersion=parseInt(e.irVersion,10):"number"==typeof e.irVersion?t.irVersion=e.irVersion:"object"==typeof e.irVersion&&(t.irVersion=new u.LongBits(e.irVersion.low>>>0,e.irVersion.high>>>0).toNumber())),e.opsetImport){if(!Array.isArray(e.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");t.opsetImport=[];for(var n=0;n<e.opsetImport.length;++n){if("object"!=typeof e.opsetImport[n])throw TypeError(".onnx.ModelProto.opsetImport: object expected");t.opsetImport[n]=l.onnx.OperatorSetIdProto.fromObject(e.opsetImport[n])}}if(null!=e.producerName&&(t.producerName=String(e.producerName)),null!=e.producerVersion&&(t.producerVersion=String(e.producerVersion)),null!=e.domain&&(t.domain=String(e.domain)),null!=e.modelVersion&&(u.Long?(t.modelVersion=u.Long.fromValue(e.modelVersion)).unsigned=false:"string"==typeof e.modelVersion?t.modelVersion=parseInt(e.modelVersion,10):"number"==typeof e.modelVersion?t.modelVersion=e.modelVersion:"object"==typeof e.modelVersion&&(t.modelVersion=new u.LongBits(e.modelVersion.low>>>0,e.modelVersion.high>>>0).toNumber())),null!=e.docString&&(t.docString=String(e.docString)),null!=e.graph){if("object"!=typeof e.graph)throw TypeError(".onnx.ModelProto.graph: object expected");t.graph=l.onnx.GraphProto.fromObject(e.graph)}if(e.metadataProps){if(!Array.isArray(e.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");for(t.metadataProps=[],n=0;n<e.metadataProps.length;++n){if("object"!=typeof e.metadataProps[n])throw TypeError(".onnx.ModelProto.metadataProps: object expected");t.metadataProps[n]=l.onnx.StringStringEntryProto.fromObject(e.metadataProps[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.opsetImport=[],n.metadataProps=[]),t.defaults){if(u.Long){var r=new u.Long(0,0,false);n.irVersion=t.longs===String?r.toString():t.longs===Number?r.toNumber():r}else n.irVersion=t.longs===String?"0":0;n.producerName="",n.producerVersion="",n.domain="",u.Long?(r=new u.Long(0,0,false),n.modelVersion=t.longs===String?r.toString():t.longs===Number?r.toNumber():r):n.modelVersion=t.longs===String?"0":0,n.docString="",n.graph=null}if(null!=e.irVersion&&e.hasOwnProperty("irVersion")&&("number"==typeof e.irVersion?n.irVersion=t.longs===String?String(e.irVersion):e.irVersion:n.irVersion=t.longs===String?u.Long.prototype.toString.call(e.irVersion):t.longs===Number?new u.LongBits(e.irVersion.low>>>0,e.irVersion.high>>>0).toNumber():e.irVersion),null!=e.producerName&&e.hasOwnProperty("producerName")&&(n.producerName=e.producerName),null!=e.producerVersion&&e.hasOwnProperty("producerVersion")&&(n.producerVersion=e.producerVersion),null!=e.domain&&e.hasOwnProperty("domain")&&(n.domain=e.domain),null!=e.modelVersion&&e.hasOwnProperty("modelVersion")&&("number"==typeof e.modelVersion?n.modelVersion=t.longs===String?String(e.modelVersion):e.modelVersion:n.modelVersion=t.longs===String?u.Long.prototype.toString.call(e.modelVersion):t.longs===Number?new u.LongBits(e.modelVersion.low>>>0,e.modelVersion.high>>>0).toNumber():e.modelVersion),null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),null!=e.graph&&e.hasOwnProperty("graph")&&(n.graph=l.onnx.GraphProto.toObject(e.graph,t)),e.opsetImport&&e.opsetImport.length){n.opsetImport=[];for(var o=0;o<e.opsetImport.length;++o)n.opsetImport[o]=l.onnx.OperatorSetIdProto.toObject(e.opsetImport[o],t)}if(e.metadataProps&&e.metadataProps.length)for(n.metadataProps=[],o=0;o<e.metadataProps.length;++o)n.metadataProps[o]=l.onnx.StringStringEntryProto.toObject(e.metadataProps[o],t);return n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),i.StringStringEntryProto=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.key="",e.prototype.value="",e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=c.create()),null!=e.key&&e.hasOwnProperty("key")&&t.uint32(10).string(e.key),null!=e.value&&e.hasOwnProperty("value")&&t.uint32(18).string(e.value),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.StringStringEntryProto;e.pos<n;){var o=e.uint32();switch(o>>>3){case 1:r.key=e.string();break;case 2:r.value=e.string();break;default:e.skipType(7&o)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.key&&e.hasOwnProperty("key")&&!u.isString(e.key)?"key: string expected":null!=e.value&&e.hasOwnProperty("value")&&!u.isString(e.value)?"value: string expected":null},e.fromObject=function(e){if(e instanceof l.onnx.StringStringEntryProto)return e;var t=new l.onnx.StringStringEntryProto;return null!=e.key&&(t.key=String(e.key)),null!=e.value&&(t.value=String(e.value)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.key="",n.value=""),null!=e.key&&e.hasOwnProperty("key")&&(n.key=e.key),null!=e.value&&e.hasOwnProperty("value")&&(n.value=e.value),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),i.TensorAnnotation=function(){function e(e){if(this.quantParameterTensorNames=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.tensorName="",e.prototype.quantParameterTensorNames=u.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=c.create()),null!=e.tensorName&&e.hasOwnProperty("tensorName")&&t.uint32(10).string(e.tensorName),null!=e.quantParameterTensorNames&&e.quantParameterTensorNames.length)for(var n=0;n<e.quantParameterTensorNames.length;++n)l.onnx.StringStringEntryProto.encode(e.quantParameterTensorNames[n],t.uint32(18).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.TensorAnnotation;e.pos<n;){var o=e.uint32();switch(o>>>3){case 1:r.tensorName=e.string();break;case 2:r.quantParameterTensorNames&&r.quantParameterTensorNames.length||(r.quantParameterTensorNames=[]),r.quantParameterTensorNames.push(l.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.tensorName&&e.hasOwnProperty("tensorName")&&!u.isString(e.tensorName))return"tensorName: string expected";if(null!=e.quantParameterTensorNames&&e.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(e.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var t=0;t<e.quantParameterTensorNames.length;++t){var n=l.onnx.StringStringEntryProto.verify(e.quantParameterTensorNames[t]);if(n)return"quantParameterTensorNames."+n}}return null},e.fromObject=function(e){if(e instanceof l.onnx.TensorAnnotation)return e;var t=new l.onnx.TensorAnnotation;if(null!=e.tensorName&&(t.tensorName=String(e.tensorName)),e.quantParameterTensorNames){if(!Array.isArray(e.quantParameterTensorNames))throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected");t.quantParameterTensorNames=[];for(var n=0;n<e.quantParameterTensorNames.length;++n){if("object"!=typeof e.quantParameterTensorNames[n])throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected");t.quantParameterTensorNames[n]=l.onnx.StringStringEntryProto.fromObject(e.quantParameterTensorNames[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.quantParameterTensorNames=[]),t.defaults&&(n.tensorName=""),null!=e.tensorName&&e.hasOwnProperty("tensorName")&&(n.tensorName=e.tensorName),e.quantParameterTensorNames&&e.quantParameterTensorNames.length){n.quantParameterTensorNames=[];for(var r=0;r<e.quantParameterTensorNames.length;++r)n.quantParameterTensorNames[r]=l.onnx.StringStringEntryProto.toObject(e.quantParameterTensorNames[r],t)}return n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),i.GraphProto=function(){function e(e){if(this.node=[],this.initializer=[],this.input=[],this.output=[],this.valueInfo=[],this.quantizationAnnotation=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.node=u.emptyArray,e.prototype.name="",e.prototype.initializer=u.emptyArray,e.prototype.docString="",e.prototype.input=u.emptyArray,e.prototype.output=u.emptyArray,e.prototype.valueInfo=u.emptyArray,e.prototype.quantizationAnnotation=u.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=c.create()),null!=e.node&&e.node.length)for(var n=0;n<e.node.length;++n)l.onnx.NodeProto.encode(e.node[n],t.uint32(10).fork()).ldelim();if(null!=e.name&&e.hasOwnProperty("name")&&t.uint32(18).string(e.name),null!=e.initializer&&e.initializer.length)for(n=0;n<e.initializer.length;++n)l.onnx.TensorProto.encode(e.initializer[n],t.uint32(42).fork()).ldelim();if(null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(82).string(e.docString),null!=e.input&&e.input.length)for(n=0;n<e.input.length;++n)l.onnx.ValueInfoProto.encode(e.input[n],t.uint32(90).fork()).ldelim();if(null!=e.output&&e.output.length)for(n=0;n<e.output.length;++n)l.onnx.ValueInfoProto.encode(e.output[n],t.uint32(98).fork()).ldelim();if(null!=e.valueInfo&&e.valueInfo.length)for(n=0;n<e.valueInfo.length;++n)l.onnx.ValueInfoProto.encode(e.valueInfo[n],t.uint32(106).fork()).ldelim();if(null!=e.quantizationAnnotation&&e.quantizationAnnotation.length)for(n=0;n<e.quantizationAnnotation.length;++n)l.onnx.TensorAnnotation.encode(e.quantizationAnnotation[n],t.uint32(114).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.GraphProto;e.pos<n;){var o=e.uint32();switch(o>>>3){case 1:r.node&&r.node.length||(r.node=[]),r.node.push(l.onnx.NodeProto.decode(e,e.uint32()));break;case 2:r.name=e.string();break;case 5:r.initializer&&r.initializer.length||(r.initializer=[]),r.initializer.push(l.onnx.TensorProto.decode(e,e.uint32()));break;case 10:r.docString=e.string();break;case 11:r.input&&r.input.length||(r.input=[]),r.input.push(l.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 12:r.output&&r.output.length||(r.output=[]),r.output.push(l.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 13:r.valueInfo&&r.valueInfo.length||(r.valueInfo=[]),r.valueInfo.push(l.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 14:r.quantizationAnnotation&&r.quantizationAnnotation.length||(r.quantizationAnnotation=[]),r.quantizationAnnotation.push(l.onnx.TensorAnnotation.decode(e,e.uint32()));break;default:e.skipType(7&o)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.node&&e.hasOwnProperty("node")){if(!Array.isArray(e.node))return"node: array expected";for(var t=0;t<e.node.length;++t)if(n=l.onnx.NodeProto.verify(e.node[t]))return"node."+n}if(null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(null!=e.initializer&&e.hasOwnProperty("initializer")){if(!Array.isArray(e.initializer))return"initializer: array expected";for(t=0;t<e.initializer.length;++t)if(n=l.onnx.TensorProto.verify(e.initializer[t]))return"initializer."+n}if(null!=e.docString&&e.hasOwnProperty("docString")&&!u.isString(e.docString))return"docString: string expected";if(null!=e.input&&e.hasOwnProperty("input")){if(!Array.isArray(e.input))return"input: array expected";for(t=0;t<e.input.length;++t)if(n=l.onnx.ValueInfoProto.verify(e.input[t]))return"input."+n}if(null!=e.output&&e.hasOwnProperty("output")){if(!Array.isArray(e.output))return"output: array expected";for(t=0;t<e.output.length;++t)if(n=l.onnx.ValueInfoProto.verify(e.output[t]))return"output."+n}if(null!=e.valueInfo&&e.hasOwnProperty("valueInfo")){if(!Array.isArray(e.valueInfo))return"valueInfo: array expected";for(t=0;t<e.valueInfo.length;++t)if(n=l.onnx.ValueInfoProto.verify(e.valueInfo[t]))return"valueInfo."+n}if(null!=e.quantizationAnnotation&&e.hasOwnProperty("quantizationAnnotation")){if(!Array.isArray(e.quantizationAnnotation))return"quantizationAnnotation: array expected";for(t=0;t<e.quantizationAnnotation.length;++t){var n;if(n=l.onnx.TensorAnnotation.verify(e.quantizationAnnotation[t]))return"quantizationAnnotation."+n}}return null},e.fromObject=function(e){if(e instanceof l.onnx.GraphProto)return e;var t=new l.onnx.GraphProto;if(e.node){if(!Array.isArray(e.node))throw TypeError(".onnx.GraphProto.node: array expected");t.node=[];for(var n=0;n<e.node.length;++n){if("object"!=typeof e.node[n])throw TypeError(".onnx.GraphProto.node: object expected");t.node[n]=l.onnx.NodeProto.fromObject(e.node[n])}}if(null!=e.name&&(t.name=String(e.name)),e.initializer){if(!Array.isArray(e.initializer))throw TypeError(".onnx.GraphProto.initializer: array expected");for(t.initializer=[],n=0;n<e.initializer.length;++n){if("object"!=typeof e.initializer[n])throw TypeError(".onnx.GraphProto.initializer: object expected");t.initializer[n]=l.onnx.TensorProto.fromObject(e.initializer[n])}}if(null!=e.docString&&(t.docString=String(e.docString)),e.input){if(!Array.isArray(e.input))throw TypeError(".onnx.GraphProto.input: array expected");for(t.input=[],n=0;n<e.input.length;++n){if("object"!=typeof e.input[n])throw TypeError(".onnx.GraphProto.input: object expected");t.input[n]=l.onnx.ValueInfoProto.fromObject(e.input[n])}}if(e.output){if(!Array.isArray(e.output))throw TypeError(".onnx.GraphProto.output: array expected");for(t.output=[],n=0;n<e.output.length;++n){if("object"!=typeof e.output[n])throw TypeError(".onnx.GraphProto.output: object expected");t.output[n]=l.onnx.ValueInfoProto.fromObject(e.output[n])}}if(e.valueInfo){if(!Array.isArray(e.valueInfo))throw TypeError(".onnx.GraphProto.valueInfo: array expected");for(t.valueInfo=[],n=0;n<e.valueInfo.length;++n){if("object"!=typeof e.valueInfo[n])throw TypeError(".onnx.GraphProto.valueInfo: object expected");t.valueInfo[n]=l.onnx.ValueInfoProto.fromObject(e.valueInfo[n])}}if(e.quantizationAnnotation){if(!Array.isArray(e.quantizationAnnotation))throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected");for(t.quantizationAnnotation=[],n=0;n<e.quantizationAnnotation.length;++n){if("object"!=typeof e.quantizationAnnotation[n])throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected");t.quantizationAnnotation[n]=l.onnx.TensorAnnotation.fromObject(e.quantizationAnnotation[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.node=[],n.initializer=[],n.input=[],n.output=[],n.valueInfo=[],n.quantizationAnnotation=[]),t.defaults&&(n.name="",n.docString=""),e.node&&e.node.length){n.node=[];for(var r=0;r<e.node.length;++r)n.node[r]=l.onnx.NodeProto.toObject(e.node[r],t)}if(null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),e.initializer&&e.initializer.length)for(n.initializer=[],r=0;r<e.initializer.length;++r)n.initializer[r]=l.onnx.TensorProto.toObject(e.initializer[r],t);if(null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),e.input&&e.input.length)for(n.input=[],r=0;r<e.input.length;++r)n.input[r]=l.onnx.ValueInfoProto.toObject(e.input[r],t);if(e.output&&e.output.length)for(n.output=[],r=0;r<e.output.length;++r)n.output[r]=l.onnx.ValueInfoProto.toObject(e.output[r],t);if(e.valueInfo&&e.valueInfo.length)for(n.valueInfo=[],r=0;r<e.valueInfo.length;++r)n.valueInfo[r]=l.onnx.ValueInfoProto.toObject(e.valueInfo[r],t);if(e.quantizationAnnotation&&e.quantizationAnnotation.length)for(n.quantizationAnnotation=[],r=0;r<e.quantizationAnnotation.length;++r)n.quantizationAnnotation[r]=l.onnx.TensorAnnotation.toObject(e.quantizationAnnotation[r],t);return n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),i.TensorProto=function(){function e(e){if(this.dims=[],this.floatData=[],this.int32Data=[],this.stringData=[],this.int64Data=[],this.externalData=[],this.doubleData=[],this.uint64Data=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.dims=u.emptyArray,e.prototype.dataType=0,e.prototype.segment=null,e.prototype.floatData=u.emptyArray,e.prototype.int32Data=u.emptyArray,e.prototype.stringData=u.emptyArray,e.prototype.int64Data=u.emptyArray,e.prototype.name="",e.prototype.docString="",e.prototype.rawData=u.newBuffer([]),e.prototype.externalData=u.emptyArray,e.prototype.dataLocation=0,e.prototype.doubleData=u.emptyArray,e.prototype.uint64Data=u.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=c.create()),null!=e.dims&&e.dims.length){t.uint32(10).fork();for(var n=0;n<e.dims.length;++n)t.int64(e.dims[n]);t.ldelim()}if(null!=e.dataType&&e.hasOwnProperty("dataType")&&t.uint32(16).int32(e.dataType),null!=e.segment&&e.hasOwnProperty("segment")&&l.onnx.TensorProto.Segment.encode(e.segment,t.uint32(26).fork()).ldelim(),null!=e.floatData&&e.floatData.length){for(t.uint32(34).fork(),n=0;n<e.floatData.length;++n)t.float(e.floatData[n]);t.ldelim()}if(null!=e.int32Data&&e.int32Data.length){for(t.uint32(42).fork(),n=0;n<e.int32Data.length;++n)t.int32(e.int32Data[n]);t.ldelim()}if(null!=e.stringData&&e.stringData.length)for(n=0;n<e.stringData.length;++n)t.uint32(50).bytes(e.stringData[n]);if(null!=e.int64Data&&e.int64Data.length){for(t.uint32(58).fork(),n=0;n<e.int64Data.length;++n)t.int64(e.int64Data[n]);t.ldelim()}if(null!=e.name&&e.hasOwnProperty("name")&&t.uint32(66).string(e.name),null!=e.rawData&&e.hasOwnProperty("rawData")&&t.uint32(74).bytes(e.rawData),null!=e.doubleData&&e.doubleData.length){for(t.uint32(82).fork(),n=0;n<e.doubleData.length;++n)t.double(e.doubleData[n]);t.ldelim()}if(null!=e.uint64Data&&e.uint64Data.length){for(t.uint32(90).fork(),n=0;n<e.uint64Data.length;++n)t.uint64(e.uint64Data[n]);t.ldelim()}if(null!=e.docString&&e.hasOwnProperty("docString")&&t.uint32(98).string(e.docString),null!=e.externalData&&e.externalData.length)for(n=0;n<e.externalData.length;++n)l.onnx.StringStringEntryProto.encode(e.externalData[n],t.uint32(106).fork()).ldelim();return null!=e.dataLocation&&e.hasOwnProperty("dataLocation")&&t.uint32(112).int32(e.dataLocation),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.TensorProto;e.pos<n;){var o=e.uint32();switch(o>>>3){case 1:if(r.dims&&r.dims.length||(r.dims=[]),2==(7&o))for(var i=e.uint32()+e.pos;e.pos<i;)r.dims.push(e.int64());else r.dims.push(e.int64());break;case 2:r.dataType=e.int32();break;case 3:r.segment=l.onnx.TensorProto.Segment.decode(e,e.uint32());break;case 4:if(r.floatData&&r.floatData.length||(r.floatData=[]),2==(7&o))for(i=e.uint32()+e.pos;e.pos<i;)r.floatData.push(e.float());else r.floatData.push(e.float());break;case 5:if(r.int32Data&&r.int32Data.length||(r.int32Data=[]),2==(7&o))for(i=e.uint32()+e.pos;e.pos<i;)r.int32Data.push(e.int32());else r.int32Data.push(e.int32());break;case 6:r.stringData&&r.stringData.length||(r.stringData=[]),r.stringData.push(e.bytes());break;case 7:if(r.int64Data&&r.int64Data.length||(r.int64Data=[]),2==(7&o))for(i=e.uint32()+e.pos;e.pos<i;)r.int64Data.push(e.int64());else r.int64Data.push(e.int64());break;case 8:r.name=e.string();break;case 12:r.docString=e.string();break;case 9:r.rawData=e.bytes();break;case 13:r.externalData&&r.externalData.length||(r.externalData=[]),r.externalData.push(l.onnx.StringStringEntryProto.decode(e,e.uint32()));break;case 14:r.dataLocation=e.int32();break;case 10:if(r.doubleData&&r.doubleData.length||(r.doubleData=[]),2==(7&o))for(i=e.uint32()+e.pos;e.pos<i;)r.doubleData.push(e.double());else r.doubleData.push(e.double());break;case 11:if(r.uint64Data&&r.uint64Data.length||(r.uint64Data=[]),2==(7&o))for(i=e.uint32()+e.pos;e.pos<i;)r.uint64Data.push(e.uint64());else r.uint64Data.push(e.uint64());break;default:e.skipType(7&o)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.dims&&e.hasOwnProperty("dims")){if(!Array.isArray(e.dims))return"dims: array expected";for(var t=0;t<e.dims.length;++t)if(!(u.isInteger(e.dims[t])||e.dims[t]&&u.isInteger(e.dims[t].low)&&u.isInteger(e.dims[t].high)))return"dims: integer|Long[] expected"}if(null!=e.dataType&&e.hasOwnProperty("dataType")&&!u.isInteger(e.dataType))return"dataType: integer expected";if(null!=e.segment&&e.hasOwnProperty("segment")&&(n=l.onnx.TensorProto.Segment.verify(e.segment)))return"segment."+n;if(null!=e.floatData&&e.hasOwnProperty("floatData")){if(!Array.isArray(e.floatData))return"floatData: array expected";for(t=0;t<e.floatData.length;++t)if("number"!=typeof e.floatData[t])return"floatData: number[] expected"}if(null!=e.int32Data&&e.hasOwnProperty("int32Data")){if(!Array.isArray(e.int32Data))return"int32Data: array expected";for(t=0;t<e.int32Data.length;++t)if(!u.isInteger(e.int32Data[t]))return"int32Data: integer[] expected"}if(null!=e.stringData&&e.hasOwnProperty("stringData")){if(!Array.isArray(e.stringData))return"stringData: array expected";for(t=0;t<e.stringData.length;++t)if(!(e.stringData[t]&&"number"==typeof e.stringData[t].length||u.isString(e.stringData[t])))return"stringData: buffer[] expected"}if(null!=e.int64Data&&e.hasOwnProperty("int64Data")){if(!Array.isArray(e.int64Data))return"int64Data: array expected";for(t=0;t<e.int64Data.length;++t)if(!(u.isInteger(e.int64Data[t])||e.int64Data[t]&&u.isInteger(e.int64Data[t].low)&&u.isInteger(e.int64Data[t].high)))return"int64Data: integer|Long[] expected"}if(null!=e.name&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(null!=e.docString&&e.hasOwnProperty("docString")&&!u.isString(e.docString))return"docString: string expected";if(null!=e.rawData&&e.hasOwnProperty("rawData")&&!(e.rawData&&"number"==typeof e.rawData.length||u.isString(e.rawData)))return"rawData: buffer expected";if(null!=e.externalData&&e.hasOwnProperty("externalData")){if(!Array.isArray(e.externalData))return"externalData: array expected";for(t=0;t<e.externalData.length;++t){var n;if(n=l.onnx.StringStringEntryProto.verify(e.externalData[t]))return"externalData."+n}}if(null!=e.dataLocation&&e.hasOwnProperty("dataLocation"))switch(e.dataLocation){default:return"dataLocation: enum value expected";case 0:case 1:}if(null!=e.doubleData&&e.hasOwnProperty("doubleData")){if(!Array.isArray(e.doubleData))return"doubleData: array expected";for(t=0;t<e.doubleData.length;++t)if("number"!=typeof e.doubleData[t])return"doubleData: number[] expected"}if(null!=e.uint64Data&&e.hasOwnProperty("uint64Data")){if(!Array.isArray(e.uint64Data))return"uint64Data: array expected";for(t=0;t<e.uint64Data.length;++t)if(!(u.isInteger(e.uint64Data[t])||e.uint64Data[t]&&u.isInteger(e.uint64Data[t].low)&&u.isInteger(e.uint64Data[t].high)))return"uint64Data: integer|Long[] expected"}return null},e.fromObject=function(e){if(e instanceof l.onnx.TensorProto)return e;var t=new l.onnx.TensorProto;if(e.dims){if(!Array.isArray(e.dims))throw TypeError(".onnx.TensorProto.dims: array expected");t.dims=[];for(var n=0;n<e.dims.length;++n)u.Long?(t.dims[n]=u.Long.fromValue(e.dims[n])).unsigned=false:"string"==typeof e.dims[n]?t.dims[n]=parseInt(e.dims[n],10):"number"==typeof e.dims[n]?t.dims[n]=e.dims[n]:"object"==typeof e.dims[n]&&(t.dims[n]=new u.LongBits(e.dims[n].low>>>0,e.dims[n].high>>>0).toNumber())}if(null!=e.dataType&&(t.dataType=0|e.dataType),null!=e.segment){if("object"!=typeof e.segment)throw TypeError(".onnx.TensorProto.segment: object expected");t.segment=l.onnx.TensorProto.Segment.fromObject(e.segment)}if(e.floatData){if(!Array.isArray(e.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");for(t.floatData=[],n=0;n<e.floatData.length;++n)t.floatData[n]=Number(e.floatData[n])}if(e.int32Data){if(!Array.isArray(e.int32Data))throw TypeError(".onnx.TensorProto.int32Data: array expected");for(t.int32Data=[],n=0;n<e.int32Data.length;++n)t.int32Data[n]=0|e.int32Data[n]}if(e.stringData){if(!Array.isArray(e.stringData))throw TypeError(".onnx.TensorProto.stringData: array expected");for(t.stringData=[],n=0;n<e.stringData.length;++n)"string"==typeof e.stringData[n]?u.base64.decode(e.stringData[n],t.stringData[n]=u.newBuffer(u.base64.length(e.stringData[n])),0):e.stringData[n].length&&(t.stringData[n]=e.stringData[n])}if(e.int64Data){if(!Array.isArray(e.int64Data))throw TypeError(".onnx.TensorProto.int64Data: array expected");for(t.int64Data=[],n=0;n<e.int64Data.length;++n)u.Long?(t.int64Data[n]=u.Long.fromValue(e.int64Data[n])).unsigned=false:"string"==typeof e.int64Data[n]?t.int64Data[n]=parseInt(e.int64Data[n],10):"number"==typeof e.int64Data[n]?t.int64Data[n]=e.int64Data[n]:"object"==typeof e.int64Data[n]&&(t.int64Data[n]=new u.LongBits(e.int64Data[n].low>>>0,e.int64Data[n].high>>>0).toNumber())}if(null!=e.name&&(t.name=String(e.name)),null!=e.docString&&(t.docString=String(e.docString)),null!=e.rawData&&("string"==typeof e.rawData?u.base64.decode(e.rawData,t.rawData=u.newBuffer(u.base64.length(e.rawData)),0):e.rawData.length&&(t.rawData=e.rawData)),e.externalData){if(!Array.isArray(e.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");for(t.externalData=[],n=0;n<e.externalData.length;++n){if("object"!=typeof e.externalData[n])throw TypeError(".onnx.TensorProto.externalData: object expected");t.externalData[n]=l.onnx.StringStringEntryProto.fromObject(e.externalData[n])}}switch(e.dataLocation){case"DEFAULT":case 0:t.dataLocation=0;break;case"EXTERNAL":case 1:t.dataLocation=1}if(e.doubleData){if(!Array.isArray(e.doubleData))throw TypeError(".onnx.TensorProto.doubleData: array expected");for(t.doubleData=[],n=0;n<e.doubleData.length;++n)t.doubleData[n]=Number(e.doubleData[n])}if(e.uint64Data){if(!Array.isArray(e.uint64Data))throw TypeError(".onnx.TensorProto.uint64Data: array expected");for(t.uint64Data=[],n=0;n<e.uint64Data.length;++n)u.Long?(t.uint64Data[n]=u.Long.fromValue(e.uint64Data[n])).unsigned=true:"string"==typeof e.uint64Data[n]?t.uint64Data[n]=parseInt(e.uint64Data[n],10):"number"==typeof e.uint64Data[n]?t.uint64Data[n]=e.uint64Data[n]:"object"==typeof e.uint64Data[n]&&(t.uint64Data[n]=new u.LongBits(e.uint64Data[n].low>>>0,e.uint64Data[n].high>>>0).toNumber(true))}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.dims=[],n.floatData=[],n.int32Data=[],n.stringData=[],n.int64Data=[],n.doubleData=[],n.uint64Data=[],n.externalData=[]),t.defaults&&(n.dataType=0,n.segment=null,n.name="",t.bytes===String?n.rawData="":(n.rawData=[],t.bytes!==Array&&(n.rawData=u.newBuffer(n.rawData))),n.docString="",n.dataLocation=t.enums===String?"DEFAULT":0),e.dims&&e.dims.length){n.dims=[];for(var r=0;r<e.dims.length;++r)"number"==typeof e.dims[r]?n.dims[r]=t.longs===String?String(e.dims[r]):e.dims[r]:n.dims[r]=t.longs===String?u.Long.prototype.toString.call(e.dims[r]):t.longs===Number?new u.LongBits(e.dims[r].low>>>0,e.dims[r].high>>>0).toNumber():e.dims[r]}if(null!=e.dataType&&e.hasOwnProperty("dataType")&&(n.dataType=e.dataType),null!=e.segment&&e.hasOwnProperty("segment")&&(n.segment=l.onnx.TensorProto.Segment.toObject(e.segment,t)),e.floatData&&e.floatData.length)for(n.floatData=[],r=0;r<e.floatData.length;++r)n.floatData[r]=t.json&&!isFinite(e.floatData[r])?String(e.floatData[r]):e.floatData[r];if(e.int32Data&&e.int32Data.length)for(n.int32Data=[],r=0;r<e.int32Data.length;++r)n.int32Data[r]=e.int32Data[r];if(e.stringData&&e.stringData.length)for(n.stringData=[],r=0;r<e.stringData.length;++r)n.stringData[r]=t.bytes===String?u.base64.encode(e.stringData[r],0,e.stringData[r].length):t.bytes===Array?Array.prototype.slice.call(e.stringData[r]):e.stringData[r];if(e.int64Data&&e.int64Data.length)for(n.int64Data=[],r=0;r<e.int64Data.length;++r)"number"==typeof e.int64Data[r]?n.int64Data[r]=t.longs===String?String(e.int64Data[r]):e.int64Data[r]:n.int64Data[r]=t.longs===String?u.Long.prototype.toString.call(e.int64Data[r]):t.longs===Number?new u.LongBits(e.int64Data[r].low>>>0,e.int64Data[r].high>>>0).toNumber():e.int64Data[r];if(null!=e.name&&e.hasOwnProperty("name")&&(n.name=e.name),null!=e.rawData&&e.hasOwnProperty("rawData")&&(n.rawData=t.bytes===String?u.base64.encode(e.rawData,0,e.rawData.length):t.bytes===Array?Array.prototype.slice.call(e.rawData):e.rawData),e.doubleData&&e.doubleData.length)for(n.doubleData=[],r=0;r<e.doubleData.length;++r)n.doubleData[r]=t.json&&!isFinite(e.doubleData[r])?String(e.doubleData[r]):e.doubleData[r];if(e.uint64Data&&e.uint64Data.length)for(n.uint64Data=[],r=0;r<e.uint64Data.length;++r)"number"==typeof e.uint64Data[r]?n.uint64Data[r]=t.longs===String?String(e.uint64Data[r]):e.uint64Data[r]:n.uint64Data[r]=t.longs===String?u.Long.prototype.toString.call(e.uint64Data[r]):t.longs===Number?new u.LongBits(e.uint64Data[r].low>>>0,e.uint64Data[r].high>>>0).toNumber(true):e.uint64Data[r];if(null!=e.docString&&e.hasOwnProperty("docString")&&(n.docString=e.docString),e.externalData&&e.externalData.length)for(n.externalData=[],r=0;r<e.externalData.length;++r)n.externalData[r]=l.onnx.StringStringEntryProto.toObject(e.externalData[r],t);return null!=e.dataLocation&&e.hasOwnProperty("dataLocation")&&(n.dataLocation=t.enums===String?l.onnx.TensorProto.DataLocation[e.dataLocation]:e.dataLocation),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.DataType=function(){var e={},t=Object.create(e);return t[e[0]="UNDEFINED"]=0,t[e[1]="FLOAT"]=1,t[e[2]="UINT8"]=2,t[e[3]="INT8"]=3,t[e[4]="UINT16"]=4,t[e[5]="INT16"]=5,t[e[6]="INT32"]=6,t[e[7]="INT64"]=7,t[e[8]="STRING"]=8,t[e[9]="BOOL"]=9,t[e[10]="FLOAT16"]=10,t[e[11]="DOUBLE"]=11,t[e[12]="UINT32"]=12,t[e[13]="UINT64"]=13,t[e[14]="COMPLEX64"]=14,t[e[15]="COMPLEX128"]=15,t[e[16]="BFLOAT16"]=16,t}(),e.Segment=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.begin=u.Long?u.Long.fromBits(0,0,false):0,e.prototype.end=u.Long?u.Long.fromBits(0,0,false):0,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=c.create()),null!=e.begin&&e.hasOwnProperty("begin")&&t.uint32(8).int64(e.begin),null!=e.end&&e.hasOwnProperty("end")&&t.uint32(16).int64(e.end),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.TensorProto.Segment;e.pos<n;){var o=e.uint32();switch(o>>>3){case 1:r.begin=e.int64();break;case 2:r.end=e.int64();break;default:e.skipType(7&o)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.begin&&e.hasOwnProperty("begin")&&!(u.isInteger(e.begin)||e.begin&&u.isInteger(e.begin.low)&&u.isInteger(e.begin.high))?"begin: integer|Long expected":null!=e.end&&e.hasOwnProperty("end")&&!(u.isInteger(e.end)||e.end&&u.isInteger(e.end.low)&&u.isInteger(e.end.high))?"end: integer|Long expected":null},e.fromObject=function(e){if(e instanceof l.onnx.TensorProto.Segment)return e;var t=new l.onnx.TensorProto.Segment;return null!=e.begin&&(u.Long?(t.begin=u.Long.fromValue(e.begin)).unsigned=false:"string"==typeof e.begin?t.begin=parseInt(e.begin,10):"number"==typeof e.begin?t.begin=e.begin:"object"==typeof e.begin&&(t.begin=new u.LongBits(e.begin.low>>>0,e.begin.high>>>0).toNumber())),null!=e.end&&(u.Long?(t.end=u.Long.fromValue(e.end)).unsigned=false:"string"==typeof e.end?t.end=parseInt(e.end,10):"number"==typeof e.end?t.end=e.end:"object"==typeof e.end&&(t.end=new u.LongBits(e.end.low>>>0,e.end.high>>>0).toNumber())),t},e.toObject=function(e,t){t||(t={});var n={};if(t.defaults){if(u.Long){var r=new u.Long(0,0,false);n.begin=t.longs===String?r.toString():t.longs===Number?r.toNumber():r}else n.begin=t.longs===String?"0":0;u.Long?(r=new u.Long(0,0,false),n.end=t.longs===String?r.toString():t.longs===Number?r.toNumber():r):n.end=t.longs===String?"0":0}return null!=e.begin&&e.hasOwnProperty("begin")&&("number"==typeof e.begin?n.begin=t.longs===String?String(e.begin):e.begin:n.begin=t.longs===String?u.Long.prototype.toString.call(e.begin):t.longs===Number?new u.LongBits(e.begin.low>>>0,e.begin.high>>>0).toNumber():e.begin),null!=e.end&&e.hasOwnProperty("end")&&("number"==typeof e.end?n.end=t.longs===String?String(e.end):e.end:n.end=t.longs===String?u.Long.prototype.toString.call(e.end):t.longs===Number?new u.LongBits(e.end.low>>>0,e.end.high>>>0).toNumber():e.end),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),e.DataLocation=function(){var e={},t=Object.create(e);return t[e[0]="DEFAULT"]=0,t[e[1]="EXTERNAL"]=1,t}(),e}(),i.TensorShapeProto=function(){function e(e){if(this.dim=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.dim=u.emptyArray,e.create=function(t){return new e(t)},e.encode=function(e,t){if(t||(t=c.create()),null!=e.dim&&e.dim.length)for(var n=0;n<e.dim.length;++n)l.onnx.TensorShapeProto.Dimension.encode(e.dim[n],t.uint32(10).fork()).ldelim();return t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.TensorShapeProto;e.pos<n;){var o=e.uint32();o>>>3==1?(r.dim&&r.dim.length||(r.dim=[]),r.dim.push(l.onnx.TensorShapeProto.Dimension.decode(e,e.uint32()))):e.skipType(7&o)}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.dim&&e.hasOwnProperty("dim")){if(!Array.isArray(e.dim))return"dim: array expected";for(var t=0;t<e.dim.length;++t){var n=l.onnx.TensorShapeProto.Dimension.verify(e.dim[t]);if(n)return"dim."+n}}return null},e.fromObject=function(e){if(e instanceof l.onnx.TensorShapeProto)return e;var t=new l.onnx.TensorShapeProto;if(e.dim){if(!Array.isArray(e.dim))throw TypeError(".onnx.TensorShapeProto.dim: array expected");t.dim=[];for(var n=0;n<e.dim.length;++n){if("object"!=typeof e.dim[n])throw TypeError(".onnx.TensorShapeProto.dim: object expected");t.dim[n]=l.onnx.TensorShapeProto.Dimension.fromObject(e.dim[n])}}return t},e.toObject=function(e,t){t||(t={});var n={};if((t.arrays||t.defaults)&&(n.dim=[]),e.dim&&e.dim.length){n.dim=[];for(var r=0;r<e.dim.length;++r)n.dim[r]=l.onnx.TensorShapeProto.Dimension.toObject(e.dim[r],t)}return n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.Dimension=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}var t;return e.prototype.dimValue=u.Long?u.Long.fromBits(0,0,false):0,e.prototype.dimParam="",e.prototype.denotation="",Object.defineProperty(e.prototype,"value",{get:u.oneOfGetter(t=["dimValue","dimParam"]),set:u.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=c.create()),null!=e.dimValue&&e.hasOwnProperty("dimValue")&&t.uint32(8).int64(e.dimValue),null!=e.dimParam&&e.hasOwnProperty("dimParam")&&t.uint32(18).string(e.dimParam),null!=e.denotation&&e.hasOwnProperty("denotation")&&t.uint32(26).string(e.denotation),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.TensorShapeProto.Dimension;e.pos<n;){var o=e.uint32();switch(o>>>3){case 1:r.dimValue=e.int64();break;case 2:r.dimParam=e.string();break;case 3:r.denotation=e.string();break;default:e.skipType(7&o)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";var t={};if(null!=e.dimValue&&e.hasOwnProperty("dimValue")&&(t.value=1,!(u.isInteger(e.dimValue)||e.dimValue&&u.isInteger(e.dimValue.low)&&u.isInteger(e.dimValue.high))))return"dimValue: integer|Long expected";if(null!=e.dimParam&&e.hasOwnProperty("dimParam")){if(1===t.value)return"value: multiple values";if(t.value=1,!u.isString(e.dimParam))return"dimParam: string expected"}return null!=e.denotation&&e.hasOwnProperty("denotation")&&!u.isString(e.denotation)?"denotation: string expected":null},e.fromObject=function(e){if(e instanceof l.onnx.TensorShapeProto.Dimension)return e;var t=new l.onnx.TensorShapeProto.Dimension;return null!=e.dimValue&&(u.Long?(t.dimValue=u.Long.fromValue(e.dimValue)).unsigned=false:"string"==typeof e.dimValue?t.dimValue=parseInt(e.dimValue,10):"number"==typeof e.dimValue?t.dimValue=e.dimValue:"object"==typeof e.dimValue&&(t.dimValue=new u.LongBits(e.dimValue.low>>>0,e.dimValue.high>>>0).toNumber())),null!=e.dimParam&&(t.dimParam=String(e.dimParam)),null!=e.denotation&&(t.denotation=String(e.denotation)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.denotation=""),null!=e.dimValue&&e.hasOwnProperty("dimValue")&&("number"==typeof e.dimValue?n.dimValue=t.longs===String?String(e.dimValue):e.dimValue:n.dimValue=t.longs===String?u.Long.prototype.toString.call(e.dimValue):t.longs===Number?new u.LongBits(e.dimValue.low>>>0,e.dimValue.high>>>0).toNumber():e.dimValue,t.oneofs&&(n.value="dimValue")),null!=e.dimParam&&e.hasOwnProperty("dimParam")&&(n.dimParam=e.dimParam,t.oneofs&&(n.value="dimParam")),null!=e.denotation&&e.hasOwnProperty("denotation")&&(n.denotation=e.denotation),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),e}(),i.TypeProto=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}var t;return e.prototype.tensorType=null,e.prototype.denotation="",Object.defineProperty(e.prototype,"value",{get:u.oneOfGetter(t=["tensorType"]),set:u.oneOfSetter(t)}),e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=c.create()),null!=e.tensorType&&e.hasOwnProperty("tensorType")&&l.onnx.TypeProto.Tensor.encode(e.tensorType,t.uint32(10).fork()).ldelim(),null!=e.denotation&&e.hasOwnProperty("denotation")&&t.uint32(50).string(e.denotation),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.TypeProto;e.pos<n;){var o=e.uint32();switch(o>>>3){case 1:r.tensorType=l.onnx.TypeProto.Tensor.decode(e,e.uint32());break;case 6:r.denotation=e.string();break;default:e.skipType(7&o)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.tensorType&&e.hasOwnProperty("tensorType")){var t=l.onnx.TypeProto.Tensor.verify(e.tensorType);if(t)return"tensorType."+t}return null!=e.denotation&&e.hasOwnProperty("denotation")&&!u.isString(e.denotation)?"denotation: string expected":null},e.fromObject=function(e){if(e instanceof l.onnx.TypeProto)return e;var t=new l.onnx.TypeProto;if(null!=e.tensorType){if("object"!=typeof e.tensorType)throw TypeError(".onnx.TypeProto.tensorType: object expected");t.tensorType=l.onnx.TypeProto.Tensor.fromObject(e.tensorType)}return null!=e.denotation&&(t.denotation=String(e.denotation)),t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.denotation=""),null!=e.tensorType&&e.hasOwnProperty("tensorType")&&(n.tensorType=l.onnx.TypeProto.Tensor.toObject(e.tensorType,t),t.oneofs&&(n.value="tensorType")),null!=e.denotation&&e.hasOwnProperty("denotation")&&(n.denotation=e.denotation),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e.Tensor=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.elemType=0,e.prototype.shape=null,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=c.create()),null!=e.elemType&&e.hasOwnProperty("elemType")&&t.uint32(8).int32(e.elemType),null!=e.shape&&e.hasOwnProperty("shape")&&l.onnx.TensorShapeProto.encode(e.shape,t.uint32(18).fork()).ldelim(),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.TypeProto.Tensor;e.pos<n;){var o=e.uint32();switch(o>>>3){case 1:r.elemType=e.int32();break;case 2:r.shape=l.onnx.TensorShapeProto.decode(e,e.uint32());break;default:e.skipType(7&o)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){if("object"!=typeof e||null===e)return"object expected";if(null!=e.elemType&&e.hasOwnProperty("elemType")&&!u.isInteger(e.elemType))return"elemType: integer expected";if(null!=e.shape&&e.hasOwnProperty("shape")){var t=l.onnx.TensorShapeProto.verify(e.shape);if(t)return"shape."+t}return null},e.fromObject=function(e){if(e instanceof l.onnx.TypeProto.Tensor)return e;var t=new l.onnx.TypeProto.Tensor;if(null!=e.elemType&&(t.elemType=0|e.elemType),null!=e.shape){if("object"!=typeof e.shape)throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");t.shape=l.onnx.TensorShapeProto.fromObject(e.shape)}return t},e.toObject=function(e,t){t||(t={});var n={};return t.defaults&&(n.elemType=0,n.shape=null),null!=e.elemType&&e.hasOwnProperty("elemType")&&(n.elemType=e.elemType),null!=e.shape&&e.hasOwnProperty("shape")&&(n.shape=l.onnx.TensorShapeProto.toObject(e.shape,t)),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),e}(),i.OperatorSetIdProto=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n)null!=e[t[n]]&&(this[t[n]]=e[t[n]])}return e.prototype.domain="",e.prototype.version=u.Long?u.Long.fromBits(0,0,false):0,e.create=function(t){return new e(t)},e.encode=function(e,t){return t||(t=c.create()),null!=e.domain&&e.hasOwnProperty("domain")&&t.uint32(10).string(e.domain),null!=e.version&&e.hasOwnProperty("version")&&t.uint32(16).int64(e.version),t},e.encodeDelimited=function(e,t){return this.encode(e,t).ldelim()},e.decode=function(e,t){e instanceof a||(e=a.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new l.onnx.OperatorSetIdProto;e.pos<n;){var o=e.uint32();switch(o>>>3){case 1:r.domain=e.string();break;case 2:r.version=e.int64();break;default:e.skipType(7&o)}}return r},e.decodeDelimited=function(e){return e instanceof a||(e=new a(e)),this.decode(e,e.uint32())},e.verify=function(e){return"object"!=typeof e||null===e?"object expected":null!=e.domain&&e.hasOwnProperty("domain")&&!u.isString(e.domain)?"domain: string expected":null!=e.version&&e.hasOwnProperty("version")&&!(u.isInteger(e.version)||e.version&&u.isInteger(e.version.low)&&u.isInteger(e.version.high))?"version: integer|Long expected":null},e.fromObject=function(e){if(e instanceof l.onnx.OperatorSetIdProto)return e;var t=new l.onnx.OperatorSetIdProto;return null!=e.domain&&(t.domain=String(e.domain)),null!=e.version&&(u.Long?(t.version=u.Long.fromValue(e.version)).unsigned=false:"string"==typeof e.version?t.version=parseInt(e.version,10):"number"==typeof e.version?t.version=e.version:"object"==typeof e.version&&(t.version=new u.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber())),t},e.toObject=function(e,t){t||(t={});var n={};if(t.defaults)if(n.domain="",u.Long){var r=new u.Long(0,0,false);n.version=t.longs===String?r.toString():t.longs===Number?r.toNumber():r}else n.version=t.longs===String?"0":0;return null!=e.domain&&e.hasOwnProperty("domain")&&(n.domain=e.domain),null!=e.version&&e.hasOwnProperty("version")&&("number"==typeof e.version?n.version=t.longs===String?String(e.version):e.version:n.version=t.longs===String?u.Long.prototype.toString.call(e.version):t.longs===Number?new u.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber():e.version),n},e.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},e}(),i),e.exports=l},2100:(e,t,n)=>{e.exports=n(9482)},9482:(e,t,n)=>{var r=t;function o(){r.util._configure(),r.Writer._configure(r.BufferWriter),r.Reader._configure(r.BufferReader)}r.build="minimal",r.Writer=n(1173),r.BufferWriter=n(3155),r.Reader=n(1408),r.BufferReader=n(593),r.util=n(9693),r.rpc=n(5994),r.roots=n(5054),r.configure=o,o()},1408:(e,t,n)=>{e.exports=c;var r,o=n(9693),i=o.LongBits,s=o.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var u,l="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},f=function(){return o.Buffer?function(e){return(c.create=function(e){return o.Buffer.isBuffer(e)?new r(e):l(e)})(e)}:l};function d(){var e=new i(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw a(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function h(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function p(){if(this.pos+8>this.len)throw a(this,8);return new i(h(this.buf,this.pos+=4),h(this.buf,this.pos+=4))}c.create=f(),c.prototype._slice=o.Array.prototype.subarray||o.Array.prototype.slice,c.prototype.uint32=(u=4294967295,function(){if(u=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return u;if(u=(u|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return u;if(u=(u|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return u;if(u=(u|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return u;if(u=(u|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return u;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return u}),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return h(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|h(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=o.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=o.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw a(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,n):t===n?new this.buf.constructor(0):this._slice.call(this.buf,t,n)},c.prototype.string=function(){var e=this.bytes();return s.read(e,0,e.length)},c.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c._configure=function(e){r=e,c.create=f(),r._configure();var t=o.Long?"toLong":"toNumber";o.merge(c.prototype,{int64:function(){return d.call(this)[t](false)},uint64:function(){return d.call(this)[t](true)},sint64:function(){return d.call(this).zzDecode()[t](false)},fixed64:function(){return p.call(this)[t](true)},sfixed64:function(){return p.call(this)[t](false)}})}},593:(e,t,n)=>{e.exports=i;var r=n(1408);(i.prototype=Object.create(r.prototype)).constructor=i;var o=n(9693);function i(e){r.call(this,e)}i._configure=function(){o.Buffer&&(i.prototype._slice=o.Buffer.prototype.slice)},i.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},i._configure()},5054:e=>{e.exports={}},5994:(e,t,n)=>{t.Service=n(7948)},7948:(e,t,n)=>{e.exports=o;var r=n(9693);function o(e,t,n){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");r.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(n)}(o.prototype=Object.create(r.EventEmitter.prototype)).constructor=o,o.prototype.rpcCall=function e(t,n,o,i,s){if(!i)throw TypeError("request must be specified");var a=this;if(!s)return r.asPromise(e,a,t,n,o,i);if(a.rpcImpl)try{return a.rpcImpl(t,n[a.requestDelimited?"encodeDelimited":"encode"](i).finish(),(function(e,n){if(e)return a.emit("error",e,t),s(e);if(null!==n){if(!(n instanceof o))try{n=o[a.responseDelimited?"decodeDelimited":"decode"](n)}catch(e){return a.emit("error",e,t),s(e)}return a.emit("data",n,t),s(null,n)}a.end(true)}))}catch(e){return a.emit("error",e,t),void setTimeout((function(){s(e)}),0)}else setTimeout((function(){s(Error("already ended"))}),0)},o.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},1945:(e,t,n)=>{e.exports=o;var r=n(9693);function o(e,t){this.lo=e>>>0,this.hi=t>>>0}var i=o.zero=new o(0,0);i.toNumber=function(){return 0},i.zzEncode=i.zzDecode=function(){return this},i.length=function(){return 1};var s=o.zeroHash="\0\0\0\0\0\0\0\0";o.fromNumber=function(e){if(0===e)return i;var t=e<0;t&&(e=-e);var n=e>>>0,r=(e-n)/4294967296>>>0;return t&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new o(n,r)},o.from=function(e){if("number"==typeof e)return o.fromNumber(e);if(r.isString(e)){if(!r.Long)return o.fromNumber(parseInt(e,10));e=r.Long.fromString(e)}return e.low||e.high?new o(e.low>>>0,e.high>>>0):i},o.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+4294967296*n)}return this.lo+4294967296*this.hi},o.prototype.toLong=function(e){return r.Long?new r.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;o.fromHash=function(e){return e===s?i:new o((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},o.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},o.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},o.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},o.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}},9693:function(e,t,n){var r=t;function o(e,t,n){for(var r=Object.keys(t),o=0;o<r.length;++o)void 0!==e[r[o]]&&n||(e[r[o]]=t[r[o]]);return e}function i(e){function t(e,n){if(!(this instanceof t))return new t(e,n);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),n&&o(this,n)}return(t.prototype=Object.create(Error.prototype)).constructor=t,Object.defineProperty(t.prototype,"name",{get:function(){return e}}),t.prototype.toString=function(){return this.name+": "+this.message},t}r.asPromise=n(4537),r.base64=n(7419),r.EventEmitter=n(9211),r.float=n(945),r.inquire=n(7199),r.utf8=n(4997),r.pool=n(6662),r.LongBits=n(1945),r.isNode=Boolean(void 0!==n.g&&n.g&&n.g.process&&n.g.process.versions&&n.g.process.versions.node),r.global=r.isNode&&n.g||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,r.emptyArray=Object.freeze?Object.freeze([]):[],r.emptyObject=Object.freeze?Object.freeze({}):{},r.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},r.isString=function(e){return"string"==typeof e||e instanceof String},r.isObject=function(e){return e&&"object"==typeof e},r.isset=r.isSet=function(e,t){var n=e[t];return!(null==n||!e.hasOwnProperty(t))&&("object"!=typeof n||(Array.isArray(n)?n.length:Object.keys(n).length)>0)},r.Buffer=function(){try{var e=r.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),r._Buffer_from=null,r._Buffer_allocUnsafe=null,r.newBuffer=function(e){return"number"==typeof e?r.Buffer?r._Buffer_allocUnsafe(e):new r.Array(e):r.Buffer?r._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(e){return e?r.LongBits.from(e).toHash():r.LongBits.zeroHash},r.longFromHash=function(e,t){var n=r.LongBits.fromHash(e);return r.Long?r.Long.fromBits(n.lo,n.hi,t):n.toNumber(Boolean(t))},r.merge=o,r.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},r.newError=i,r.ProtocolError=i("ProtocolError"),r.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var e=Object.keys(this),n=e.length-1;n>-1;--n)if(1===t[e[n]]&&void 0!==this[e[n]]&&null!==this[e[n]])return e[n]}},r.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}},r.toJSONOptions={longs:String,enums:String,bytes:String,json:true},r._configure=function(){var e=r.Buffer;e?(r._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,n){return new e(t,n)},r._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):r._Buffer_from=r._Buffer_allocUnsafe=null}},1173:(e,t,n)=>{e.exports=f;var r,o=n(9693),i=o.LongBits,s=o.base64,a=o.utf8;function c(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}function u(){}function l(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function f(){this.len=0,this.head=new c(u,0,0),this.tail=this.head,this.states=null}var d=function(){return o.Buffer?function(){return(f.create=function(){return new r})()}:function(){return new f}};function h(e,t,n){t[n]=255&e}function p(e,t){this.len=e,this.next=void 0,this.val=t}function m(e,t,n){for(;e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function w(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}f.create=d(),f.alloc=function(e){return new o.Array(e)},o.Array!==Array&&(f.alloc=o.pool(f.alloc,o.Array.prototype.subarray)),f.prototype._push=function(e,t,n){return this.tail=this.tail.next=new c(e,t,n),this.len+=t,this},p.prototype=Object.create(c.prototype),p.prototype.fn=function(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e},f.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new p((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},f.prototype.int32=function(e){return e<0?this._push(m,10,i.fromNumber(e)):this.uint32(e)},f.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},f.prototype.uint64=function(e){var t=i.from(e);return this._push(m,t.length(),t)},f.prototype.int64=f.prototype.uint64,f.prototype.sint64=function(e){var t=i.from(e).zzEncode();return this._push(m,t.length(),t)},f.prototype.bool=function(e){return this._push(h,1,e?1:0)},f.prototype.fixed32=function(e){return this._push(w,4,e>>>0)},f.prototype.sfixed32=f.prototype.fixed32,f.prototype.fixed64=function(e){var t=i.from(e);return this._push(w,4,t.lo)._push(w,4,t.hi)},f.prototype.sfixed64=f.prototype.fixed64,f.prototype.float=function(e){return this._push(o.float.writeFloatLE,4,e)},f.prototype.double=function(e){return this._push(o.float.writeDoubleLE,8,e)};var g=o.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var r=0;r<e.length;++r)t[n+r]=e[r]};f.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(h,1,0);if(o.isString(e)){var n=f.alloc(t=s.length(e));s.decode(e,n,0),e=n}return this.uint32(t)._push(g,t,e)},f.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(h,1,0)},f.prototype.fork=function(){return this.states=new l(this),this.head=this.tail=new c(u,0,0),this.len=0,this},f.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(u,0,0),this.len=0),this},f.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this},f.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t},f._configure=function(e){r=e,f.create=d(),r._configure()}},3155:(e,t,n)=>{e.exports=i;var r=n(1173);(i.prototype=Object.create(r.prototype)).constructor=i;var o=n(9693);function i(){r.call(this)}function s(e,t,n){e.length<40?o.utf8.write(e,t,n):t.utf8Write?t.utf8Write(e,n):t.write(e,n)}i._configure=function(){i.alloc=o._Buffer_allocUnsafe,i.writeBytesBuffer=o.Buffer&&o.Buffer.prototype instanceof Uint8Array&&"set"===o.Buffer.prototype.set.name?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var r=0;r<e.length;)t[n++]=e[r++]}},i.prototype.bytes=function(e){o.isString(e)&&(e=o._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(i.writeBytesBuffer,t,e),this},i.prototype.string=function(e){var t=o.Buffer.byteLength(e);return this.uint32(t),t&&this._push(s,t,e),this},i._configure()},7714:(e,t,n)=>{t.R=void 0;const r=n(6919),o=n(7448);t.R=new class{async init(){}async createSessionHandler(e,t){const n=new r.Session(t);return await n.loadModel(e),new o.OnnxjsSessionHandler(n)}}},4200:(e,t,n)=>{t.c8=t.rX=void 0;const r=n(1670),o=n(5381),i=n(2157),s=n(2306);t.rX=()=>{if(("number"!=typeof r.env.wasm.initTimeout||r.env.wasm.initTimeout<0)&&(r.env.wasm.initTimeout=0),"boolean"!=typeof r.env.wasm.simd&&(r.env.wasm.simd=true),"boolean"!=typeof r.env.wasm.proxy&&(r.env.wasm.proxy=false),"number"!=typeof r.env.wasm.numThreads||!Number.isInteger(r.env.wasm.numThreads)||r.env.wasm.numThreads<=0){const e="undefined"==typeof navigator?(0,o.cpus)().length:navigator.hardwareConcurrency;r.env.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},t.c8=new class{async init(){(0,t.rX)(),await(0,i.initWasm)()}async createSessionHandler(e,t){const n=new s.OnnxruntimeWebAssemblySessionHandler;return await n.loadModel(e,t),Promise.resolve(n)}}},6018:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:true,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:true}),o(n(1670),t);const i=n(1670);{const e=n(7714).R;(0,i.registerBackend)("webgl",e,-10)}{const e=n(4200).c8;(0,i.registerBackend)("cpu",e,10),(0,i.registerBackend)("wasm",e,10),(0,i.registerBackend)("xnnpack",e,9)}},246:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true}),t.createAttributeWithCacheKey=void 0;class n{constructor(e){Object.assign(this,e)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map((e=>`${this[e]}`)).join(";")),this._cacheKey}}t.createAttributeWithCacheKey=e=>new n(e)},7778:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.Attribute=void 0;const r=n(1446),o=n(9395),i=n(9162),s=n(2517);var a=o.onnxruntime.experimental.fbs;class c{constructor(e){if(this._attributes=new Map,null!=e){for(const t of e)t instanceof r.onnx.AttributeProto?this._attributes.set(t.name,[c.getValue(t),c.getType(t)]):t instanceof a.Attribute&&this._attributes.set(t.name(),[c.getValue(t),c.getType(t)]);if(this._attributes.size<e.length)throw new Error("duplicated attribute names")}}set(e,t,n){this._attributes.set(e,[n,t])}delete(e){this._attributes.delete(e)}getFloat(e,t){return this.get(e,"float",t)}getInt(e,t){return this.get(e,"int",t)}getString(e,t){return this.get(e,"string",t)}getTensor(e,t){return this.get(e,"tensor",t)}getFloats(e,t){return this.get(e,"floats",t)}getInts(e,t){return this.get(e,"ints",t)}getStrings(e,t){return this.get(e,"strings",t)}getTensors(e,t){return this.get(e,"tensors",t)}get(e,t,n){const r=this._attributes.get(e);if(void 0===r){if(void 0!==n)return n;throw new Error(`required attribute not found: ${e}`)}if(r[1]!==t)throw new Error(`type mismatch: expected ${t} but got ${r[1]}`);return r[0]}static getType(e){const t=e instanceof r.onnx.AttributeProto?e.type:e.type();switch(t){case r.onnx.AttributeProto.AttributeType.FLOAT:return"float";case r.onnx.AttributeProto.AttributeType.INT:return"int";case r.onnx.AttributeProto.AttributeType.STRING:return"string";case r.onnx.AttributeProto.AttributeType.TENSOR:return"tensor";case r.onnx.AttributeProto.AttributeType.FLOATS:return"floats";case r.onnx.AttributeProto.AttributeType.INTS:return"ints";case r.onnx.AttributeProto.AttributeType.STRINGS:return"strings";case r.onnx.AttributeProto.AttributeType.TENSORS:return"tensors";default:throw new Error(`attribute type is not supported yet: ${r.onnx.AttributeProto.AttributeType[t]}`)}}static getValue(e){const t=e instanceof r.onnx.AttributeProto?e.type:e.type();if(t===r.onnx.AttributeProto.AttributeType.GRAPH||t===r.onnx.AttributeProto.AttributeType.GRAPHS)throw new Error("graph attribute is not supported yet");const n=this.getValueNoCheck(e);if(t===r.onnx.AttributeProto.AttributeType.INT&&s.LongUtil.isLong(n))return s.LongUtil.longToNumber(n);if(t===r.onnx.AttributeProto.AttributeType.INTS){const e=n,t=new Array(e.length);for(let n=0;n<e.length;n++){const r=e[n];t[n]=s.LongUtil.longToNumber(r)}return t}if(t===r.onnx.AttributeProto.AttributeType.TENSOR)return e instanceof r.onnx.AttributeProto?i.Tensor.fromProto(n):i.Tensor.fromOrtTensor(n);if(t===r.onnx.AttributeProto.AttributeType.TENSORS){if(e instanceof r.onnx.AttributeProto)return n.map((e=>i.Tensor.fromProto(e)));if(e instanceof a.Attribute)return n.map((e=>i.Tensor.fromOrtTensor(e)))}if(t===r.onnx.AttributeProto.AttributeType.STRING&&e instanceof r.onnx.AttributeProto){const e=n;return(0,s.decodeUtf8String)(e)}return t===r.onnx.AttributeProto.AttributeType.STRINGS&&e instanceof r.onnx.AttributeProto?n.map(s.decodeUtf8String):n}static getValueNoCheck(e){return e instanceof r.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(e):this.getValueNoCheckFromOrtFormat(e)}static getValueNoCheckFromOnnxFormat(e){switch(e.type){case r.onnx.AttributeProto.AttributeType.FLOAT:return e.f;case r.onnx.AttributeProto.AttributeType.INT:return e.i;case r.onnx.AttributeProto.AttributeType.STRING:return e.s;case r.onnx.AttributeProto.AttributeType.TENSOR:return e.t;case r.onnx.AttributeProto.AttributeType.GRAPH:return e.g;case r.onnx.AttributeProto.AttributeType.FLOATS:return e.floats;case r.onnx.AttributeProto.AttributeType.INTS:return e.ints;case r.onnx.AttributeProto.AttributeType.STRINGS:return e.strings;case r.onnx.AttributeProto.AttributeType.TENSORS:return e.tensors;case r.onnx.AttributeProto.AttributeType.GRAPHS:return e.graphs;default:throw new Error(`unsupported attribute type: ${r.onnx.AttributeProto.AttributeType[e.type]}`)}}static getValueNoCheckFromOrtFormat(e){switch(e.type()){case a.AttributeType.FLOAT:return e.f();case a.AttributeType.INT:return e.i();case a.AttributeType.STRING:return e.s();case a.AttributeType.TENSOR:return e.t();case a.AttributeType.GRAPH:return e.g();case a.AttributeType.FLOATS:return e.floatsArray();case a.AttributeType.INTS:{const t=[];for(let n=0;n<e.intsLength();n++)t.push(e.ints(n));return t}case a.AttributeType.STRINGS:{const t=[];for(let n=0;n<e.stringsLength();n++)t.push(e.strings(n));return t}case a.AttributeType.TENSORS:{const t=[];for(let n=0;n<e.tensorsLength();n++)t.push(e.tensors(n));return t}default:throw new Error(`unsupported attribute type: ${a.AttributeType[e.type()]}`)}}}t.Attribute=c},7091:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.resolveBackend=t.backend=void 0;const r=n(5038),o=new Map;async function i(e){const n=t.backend;if(void 0!==n[e]&&function(e){const t=e;return"initialize"in t&&"function"==typeof t.initialize&&"createSessionHandler"in t&&"function"==typeof t.createSessionHandler&&"dispose"in t&&"function"==typeof t.dispose}(n[e])){const t=n[e];let r=t.initialize();if("object"==typeof r&&"then"in r&&(r=await r),r)return o.set(e,t),t}}t.backend={webgl:new r.WebGLBackend},t.resolveBackend=async function e(t){if(!t)return e(["webgl"]);{const e="string"==typeof t?[t]:t;for(const t of e){const e=o.get(t);if(e)return e;const n=await i(t);if(n)return n}}throw new Error("no available backend to use")}},5038:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.WebGLBackend=void 0;const r=n(1670),o=n(6231),i=n(6416),s=n(7305);t.WebGLBackend=class{get contextId(){return r.env.webgl.contextId}set contextId(e){r.env.webgl.contextId=e}get matmulMaxBatchSize(){return r.env.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(e){r.env.webgl.matmulMaxBatchSize=e}get textureCacheMode(){return r.env.webgl.textureCacheMode}set textureCacheMode(e){r.env.webgl.textureCacheMode=e}get pack(){return r.env.webgl.pack}set pack(e){r.env.webgl.pack=e}get async(){return r.env.webgl.async}set async(e){r.env.webgl.async=e}initialize(){try{return this.glContext=(0,s.createWebGLContext)(this.contextId),"number"!=typeof this.matmulMaxBatchSize&&(this.matmulMaxBatchSize=16),"string"!=typeof this.textureCacheMode&&(this.textureCacheMode="full"),"boolean"!=typeof this.pack&&(this.pack=false),"boolean"!=typeof this.async&&(this.async=false),o.Logger.setWithEnv(r.env),o.Logger.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),true}catch(e){return o.Logger.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${e}`),false}}createSessionHandler(e){return new i.WebGLSessionHandler(this,e)}dispose(){this.glContext.dispose()}}},5107:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.CoordsGlslLib=void 0;const r=n(2517),o=n(8520),i=n(5060),s=n(7859),a=n(9390);class c extends o.GlslLib{constructor(e){super(e)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.offsetToCoords()),this.coordsToOffset()),this.toVec()),this.valueFrom()),this.getCommonUtilFuncs()),this.getInputsSamplingSnippets()),this.getOutputSamplingSnippet())}getCustomTypes(){return{}}offsetToCoords(){return{offsetToCoords:new o.GlslLibRoutine("\n vec2 offsetToCoords(int offset, int width, int height) {\n int t = offset / width;\n int s = offset - t*width;\n vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);\n return coords;\n }\n ")}}coordsToOffset(){return{coordsToOffset:new o.GlslLibRoutine("\n int coordsToOffset(vec2 coords, int width, int height) {\n float s = coords.s * float(width);\n float t = coords.t * float(height);\n int offset = int(t) * width + int(s);\n return offset;\n }\n ")}}getOutputSamplingSnippet(){const e=this.context.outputTextureLayout;return e.isPacked?this.getPackedOutputSamplingSnippet(e):this.getUnpackedOutputSamplingSnippet(e)}getPackedOutputSamplingSnippet(e){const t=e.unpackedShape,n=[e.width,e.height],r={},s="getOutputCoords";switch(t.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputPacked1DCoords(t,n);break;case 2:r[s]=this.getOutputPacked2DCoords(t,n);break;case 3:r[s]=this.getOutputPacked3DCoords(t,n);break;default:r[s]=this.getOutputPackedNDCoords(t,n)}const a=`\n void setOutput(vec4 val) {\n ${(0,i.getGlsl)(this.context.glContext.version).output} = val;\n }\n `;return r.floatTextureSetRGBA=new o.GlslLibRoutine(a),r}getUnpackedOutputSamplingSnippet(e){const t=e.unpackedShape,n=[e.width,e.height],r={},s="getOutputCoords";switch(t.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputUnpacked1DCoords(t,n);break;case 2:r[s]=this.getOutputUnpacked2DCoords(t,n);break;case 3:r[s]=this.getOutputUnpacked3DCoords(t,n);break;case 4:r[s]=this.getOutputUnpacked4DCoords(t,n);break;case 5:r[s]=this.getOutputUnpacked5DCoords(t,n);break;case 6:r[s]=this.getOutputUnpacked6DCoords(t,n);break;default:throw new Error(`Unsupported output dimensionality: ${t.length}`)}const a=`\n void setOutput(float val) {\n ${(0,i.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0);\n }\n `;return r.floatTextureSetR=new o.GlslLibRoutine(a),r}getOutputScalarCoords(){return new o.GlslLibRoutine("\n int getOutputCoords() {\n return 0;\n }\n ")}getOutputPacked1DCoords(e,t){const n=t;let r="";return 1===n[0]?(r=`\n int getOutputCoords() {\n return 2 * int(TexCoords.y * ${n[1]}.0);\n }\n `,new o.GlslLibRoutine(r)):1===n[1]?(r=`\n int getOutputCoords() {\n return 2 * int(TexCoords.x * ${n[0]}.0);\n }\n `,new o.GlslLibRoutine(r)):(r=`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n return 2 * (resTexRC.y * ${n[0]} + resTexRC.x);\n }\n `,new o.GlslLibRoutine(r))}getOutputPacked2DCoords(e,t){let n="";if(r.ArrayUtil.arraysEqual(e,t))return n=`\n ivec2 getOutputCoords() {\n return 2 * ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]}));\n }\n `,new o.GlslLibRoutine(n);const i=t,s=Math.ceil(e[1]/2);return n=`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${i[0]}, ${i[1]}));\n\n int index = resTexRC.y * ${i[0]} + resTexRC.x;\n\n // reverse r and c order for packed texture\n int r = imod(index, ${s}) * 2;\n int c = 2 * (index / ${s});\n\n return ivec2(r, c);\n }\n `,new o.GlslLibRoutine(n)}getOutputPacked3DCoords(e,t){const n=[t[0],t[1]],r=Math.ceil(e[2]/2),i=r*Math.ceil(e[1]/2),s=`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n int index = resTexRC.y * ${n[0]} + resTexRC.x;\n\n int b = index / ${i};\n index -= b * ${i};\n\n // reverse r and c order for packed texture\n int r = imod(index, ${r}) * 2;\n int c = 2 * (index / ${r});\n\n return ivec3(b, r, c);\n }\n `;return new o.GlslLibRoutine(s)}getOutputPackedNDCoords(e,t){const n=[t[0],t[1]],r=Math.ceil(e[e.length-1]/2),i=r*Math.ceil(e[e.length-2]/2);let s=i,a="",c="b, r, c";for(let t=2;t<e.length-1;t++)s*=e[e.length-t-1],a=`\n int b${t} = index / ${s};\n index -= b${t} * ${s};\n `+a,c=`b${t}, `+c;const u=`\n ivec${e.length} getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n int index = resTexRC.y * ${n[0]} + resTexRC.x;\n\n ${a}\n\n int b = index / ${i};\n index -= b * ${i};\n\n // reverse r and c order for packed texture\n int r = imod(index, ${r}) * 2;\n int c = 2 * (index / ${r});\n\n return ivec${e.length}(${c});\n }\n `;return new o.GlslLibRoutine(u)}getOutputUnpacked1DCoords(e,t){const n=`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n return resTexRC.y * ${t[0]} + resTexRC.x;\n }\n `;return new o.GlslLibRoutine(n)}getOutputUnpacked2DCoords(e,t){const n=`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n int r = index / ${e[1]};\n int c = index - r * ${e[1]};\n return ivec2(r, c);\n }\n `;return new o.GlslLibRoutine(n)}getOutputUnpacked3DCoords(e,t){let n="";const r=e.length;let i=null;r<2&&(i=[]),i=new Array(r-1),i[r-2]=e[r-1];for(let t=r-3;t>=0;--t)i[t]=i[t+1]*e[t+1];const s=["r","c","d"],a=i.map(((e,t)=>`int ${s[t]} = index / ${e}; ${t===i.length-1?`int ${s[t+1]} = index - ${s[t]} * ${e}`:`index -= ${s[t]} * ${e}`};`)).join("");return n=`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n ${a}\n return ivec3(r, c, d);\n }\n `,new o.GlslLibRoutine(n)}getOutputUnpacked4DCoords(e,t){let n="";const r=e.length;let i=null;r<2&&(i=[]),i=new Array(r-1),i[r-2]=e[r-1];for(let t=r-3;t>=0;--t)i[t]=i[t+1]*e[t+1];const s=["r","c","d","d2"],a=i.map(((e,t)=>`int ${s[t]} = index / ${e}; ${t===i.length-1?`int ${s[t+1]} = index - ${s[t]} * ${e}`:`index -= ${s[t]} * ${e}`};`)).join("");return n=`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n ${a}\n return ivec4(r, c, d, d2);\n }\n `,new o.GlslLibRoutine(n)}getOutputUnpacked5DCoords(e,t){let n="";const r=e.length;let i=null;r<2&&(i=[]),i=new Array(r-1),i[r-2]=e[r-1];for(let t=r-3;t>=0;--t)i[t]=i[t+1]*e[t+1];const s=["r","c","d","d2","d3"],a=i.map(((e,t)=>`int ${s[t]} = index / ${e}; ${t===i.length-1?`int ${s[t+1]} = index - ${s[t]} * ${e}`:`index -= ${s[t]} * ${e}`};`)).join("");return n=`\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n ${a}\n return ivec5(r, c, d, d2, d3);\n }\n `,new o.GlslLibRoutine(n)}getOutputUnpacked6DCoords(e,t){let n="";const r=e.length;let i=null;r<2&&(i=[]),i=new Array(r-1),i[r-2]=e[r-1];for(let t=r-3;t>=0;--t)i[t]=i[t+1]*e[t+1];const s=["r","c","d","d2","d3","d4"],a=i.map(((e,t)=>`int ${s[t]} = index / ${e}; ${t===i.length-1?`int ${s[t+1]} = index - ${s[t]} * ${e}`:`index -= ${s[t]} * ${e}`};`)).join("");return n=`\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.y * ${t[0]} + resTexRC.x;\n ${a}\n return ivec6(r, c, d, d2, d3, d4);\n }\n `,new o.GlslLibRoutine(n)}getCommonUtilFuncs(){const e={};let t="uvFromFlat";e[t]=new o.GlslLibRoutine("\n vec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texC = index / texNumR;\n int texR = index - texC * texNumR;\n // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to\n // v.\n return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);\n }\n "),t="packedUVfrom1D",e[t]=new o.GlslLibRoutine("\n vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),t="packedUVfrom2D",e[t]=new o.GlslLibRoutine("\n vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),t="packedUVfrom3D",e[t]=new o.GlslLibRoutine("\n vec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),t="sampleTexture";const n=(0,i.getGlsl)(this.context.glContext.version);return e[t]=new o.GlslLibRoutine(`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${n.texture2D}(textureSampler, uv).r;\n }`),e}getInputsSamplingSnippets(){const e={},t=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach(((n,r)=>{const o=this.context.inputTextureLayouts[r],i=(0,a.generateShaderFuncNameFromInputSamplerName)(n);o.isPacked?e[i]=this.getPackedSamplerFromInput(i,n,o):e[i]=this.getUnpackedSamplerFromInput(i,n,o);const s=(0,a.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(n);o.unpackedShape.length<=t.unpackedShape.length&&(o.isPacked?e[s]=this.getPackedSamplerAtOutputCoords(s,o,t,n):e[s]=this.getUnpackedSamplerAtOutputCoords(s,o,t,n))})),e}getPackedSamplerAtOutputCoords(e,t,n,i){const s=t.unpackedShape,c=n.unpackedShape,u=i,l=(0,a.generateShaderFuncNameFromInputSamplerName)(u),f=s.length,d=c.length,h=r.BroadcastUtil.getBroadcastDims(s,c),p=(0,a.getCoordsDataType)(d),m=d-f;let w;const g=(0,a.getGlChannels)();w=0===f?"":d<2&&h.length>=1?"coords = 0;":h.map((e=>`coords.${g[e+m]} = 0;`)).join("\n");let v="";v=d<2&&f>0?"coords":s.map(((e,t)=>`coords.${g[t+m]}`)).join(", ");let y="return outputValue;";const _=1===r.ShapeUtil.size(s),b=1===r.ShapeUtil.size(c);if(1!==f||_||b){if(_&&!b)y=1===d?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(h.length){const e=f-2,t=f-1;h.indexOf(e)>-1&&h.indexOf(t)>-1?y="return vec4(outputValue.x);":h.indexOf(e)>-1?y="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":h.indexOf(t)>-1&&(y="return vec4(outputValue.xx, outputValue.zz);")}}else y="\n return vec4(outputValue.xy, outputValue.xy);\n ";const x=`\n vec4 ${e}() {\n ${p} coords = getOutputCoords();\n \n int lastDim = coords.${g[d-1]};\n coords.${g[d-1]} = coords.${g[d-2]};\n coords.${g[d-2]} = lastDim;\n \n ${w}\n vec4 outputValue = ${l}(${v});\n ${y}\n }\n `;return new o.GlslLibRoutine(x,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(e,t,n,i){const s=[n.width,n.height],c=[t.width,t.height],u=t.unpackedShape.length,l=n.unpackedShape.length,f=t.unpackedShape,d=n.unpackedShape,h=(0,a.generateShaderFuncNameFromInputSamplerName)(i);if(u===l&&r.ArrayUtil.arraysEqual(c,s)){const t=`\n float ${e}() {\n return sampleTexture(${i}, TexCoords);\n }\n `;return new o.GlslLibRoutine(t,["coordinates.sampleTexture"])}const p=(0,a.getCoordsDataType)(l),m=r.BroadcastUtil.getBroadcastDims(f,d),w=l-u;let g;const v=(0,a.getGlChannels)();g=0===u?"":l<2&&m.length>=1?"coords = 0;":m.map((e=>`coords.${v[e+w]} = 0;`)).join("\n");let y="";y=l<2&&u>0?"coords":t.unpackedShape.map(((e,t)=>`coords.${v[t+w]}`)).join(", ");const _=`\n float ${e}() {\n ${p} coords = getOutputCoords();\n ${g}\n return ${h}(${y});\n }\n `;return new o.GlslLibRoutine(_,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(e,t,n){switch(n.unpackedShape.length){case 0:return this.getPackedSamplerScalar(e,t);case 1:return this.getPackedSampler1D(e,t,n);case 2:return this.getPackedSampler2D(e,t,n);case 3:return this.getPackedSampler3D(e,t,n);default:return this.getPackedSamplerND(e,t,n)}}getUnpackedSamplerFromInput(e,t,n){const r=n.unpackedShape;switch(r.length){case 0:return this.getUnpackedSamplerScalar(e,t,n);case 1:return this.getUnpackedSampler1D(e,t,n);case 2:return this.getUnpackedSampler2D(e,t,n);case 3:return this.getUnpackedSampler3D(e,t,n);case 4:return this.getUnpackedSampler4D(e,t,n);case 5:return this.getUnpackedSampler5D(e,t,n);case 6:return this.getUnpackedSampler6D(e,t,n);default:throw new Error(`Unsupported dimension ${r.length}-D`)}}getPackedSamplerScalar(e,t){const n=`\n vec4 ${e}() {\n return ${(0,i.getGlsl)(this.context.glContext.version).texture2D}(${t}, halfCR);\n }\n `;return new o.GlslLibRoutine(n)}getPackedSampler1D(e,t,n){const r=[n.width,n.height],s=[r[1],r[0]],a=(0,i.getGlsl)(this.context.glContext.version),c=`vec4 ${e}(int index) {\n vec2 uv = packedUVfrom1D(\n ${s[0]}, ${s[1]}, index);\n return ${a.texture2D}(${t}, uv);\n }`;return new o.GlslLibRoutine(c,["coordinates.packedUVfrom1D"])}getPackedSampler2D(e,t,n){const s=n.unpackedShape,a=[n.width,n.height],c=(0,i.getGlsl)(this.context.glContext.version),u=a[0],l=a[1];if(null!=a&&r.ArrayUtil.arraysEqual(s,a)){const n=`vec4 ${e}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${l}.0, ${u}.0);\n return ${c.texture2D}(${t}, uv);\n }`;return new o.GlslLibRoutine(n)}const f=a,d=Math.ceil(s[1]/2),h=`vec4 ${e}(int row, int col) {\n vec2 uv = packedUVfrom2D(${f[1]}, ${f[0]}, ${d}, row, col);\n return ${c.texture2D}(${t}, uv);\n }`;return new o.GlslLibRoutine(h,["coordinates.packedUVfrom2D"])}getPackedSampler3D(e,t,n){const r=n.unpackedShape,s=[n.width,n.height],c=[s[0],s[1]],u=(0,i.getGlsl)(this.context.glContext.version);if(1===r[0]){const i=r.slice(1),s=[1,2],c=(0,a.squeezeInputShape)(r,i),u=["b","row","col"],l=JSON.parse(JSON.stringify(n));l.unpackedShape=c;const f=this.getPackedSamplerFromInput(e,t,l),d=`${f.routineBody}\n vec4 ${e}(int b, int row, int col) {\n return ${e}(${(0,a.getSqueezedParams)(u,s)});\n } `;return new o.GlslLibRoutine(d,f.dependencies)}const l=c[0],f=c[1],d=Math.ceil(r[2]/2),h=`vec4 ${e}(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n ${f}, ${l}, ${d*Math.ceil(r[1]/2)}, ${d}, b, row, col);\n return ${u.texture2D}(${t}, uv);}`;return new o.GlslLibRoutine(h,["coordinates.packedUVfrom3D"])}getPackedSamplerND(e,t,n){const r=n.unpackedShape,s=r.length,a=[n.width,n.height],c=(0,i.getGlsl)(this.context.glContext.version),u=[a[0],a[1]],l=u[1],f=u[0],d=Math.ceil(r[s-1]/2);let h=d*Math.ceil(r[s-2]/2),p="int b, int row, int col",m=`b * ${h} + (row / 2) * ${d} + (col / 2)`;for(let e=2;e<s-1;e++)p=`int b${e}, `+p,h*=r[s-e-1],m=`b${e} * ${h} + `+m;const w=`vec4 ${e}(${p}) {\n int index = ${m};\n int texR = index / ${f};\n int texC = index - texR * ${f};\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${f}, ${l});\n return ${c.texture2D}(${t}, uv);\n }`;return new o.GlslLibRoutine(w)}getUnpackedSamplerScalar(e,t,n){const[r,i]=[n.width,n.height];if(1===r&&1===i){const n=`\n float ${e}() {\n return sampleTexture(${t}, halfCR);\n }\n `;return new o.GlslLibRoutine(n,["coordinates.sampleTexture"])}const s=`\n float ${e}() {\n int offset_${t} = coordsToOffset(TexCoords, ${r}, ${i});\n vec2 uv = uvFromFlat(${r}, ${i}, offset_${t});\n return sampleTexture(${t}, uv);\n }\n `;return new o.GlslLibRoutine(s,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler1D(e,t,n){const r=n.width,i=n.height;if(1===i&&1===r){const n=`\n float ${e}(int index) {\n return sampleTexture(${t}, halfCR);\n }\n `;return new o.GlslLibRoutine(n,["coordinates.sampleTexture"])}if(1===i){const n=`\n float ${e}(int index) {\n vec2 uv = vec2((float(index) + 0.5) / ${r}.0, 0.5);\n return sampleTexture(${t}, uv);\n }\n `;return new o.GlslLibRoutine(n,["coordinates.sampleTexture"])}if(1===r){const n=`\n float ${e}(int index) {\n vec2 uv = vec2(0.5, (float(index) + 0.5) / ${i}.0);\n return sampleTexture(${t}, uv);\n }\n `;return new o.GlslLibRoutine(n,["coordinates.sampleTexture"])}const s=`\n float ${e}(int index) {\n vec2 uv = uvFromFlat(${r}, ${i}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new o.GlslLibRoutine(s,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler2D(e,t,n){const i=n.unpackedShape,c=[n.height,n.width];if(null!=c&&r.ArrayUtil.arraysEqual(i,c)){const n=`\n float ${e}(int row, int col) {\n vec2 uv = (vec2(row, col) + halfCR) / vec2(${c[1]}.0, ${c[0]}.0);\n return sampleTexture(${t}, uv);\n }\n `;return new o.GlslLibRoutine(n,["coordinates.sampleTexture"])}const{newShape:u,keptDims:l}=(0,s.squeezeShape)(i),f=u;if(f.length<i.length){const r=(0,a.squeezeInputShape)(i,f),s=JSON.parse(JSON.stringify(n));s.unpackedShape=r;const c=["col","row"],u=`\n ${this.getUnpackedSamplerFromInput(e,t,s).routineBody}\n float ${e}(int row, int col) {\n return ${e}(${(0,a.getSqueezedParams)(c,l)});\n }\n `;return new o.GlslLibRoutine(u,["coordinates.sampleTexture"])}const d=c[1],h=c[0];if(1===h){const n=`\n float ${e}(int row, int col) {\n int offset_${t} = coordsToOffset(TexCoords, ${d}, ${h});\n float index = dot(vec3(row, col, offset_${t}), vec3(${i[1]}, 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / ${d}.0);\n return sampleTexture(${t}, uv);\n }\n `;return new o.GlslLibRoutine(n,["coordinates.sampleTexture","coordinates.coordsToOffset"])}if(1===d){const n=`\n float ${e}(int row, int col) {\n int offset_${t} = coordsToOffset(TexCoords, ${d}, ${h});\n float index = dot(vec3(row, col, offset_${t}), vec3(${i[1]}, 1, 1));\n vec2 uv = vec2((index + 0.5) / ${h}.0, 0.5);\n return sampleTexture(${t}, uv);\n }\n `;return new o.GlslLibRoutine(n,["coordinates.sampleTexture","coordinates.coordsToOffset"])}const p=`\n float ${e}(int row, int col) {\n int index = col * ${i[1]} + row;\n vec2 uv = uvFromFlat(${d}, ${h}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new o.GlslLibRoutine(p,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler3D(e,t,n){const r=n.unpackedShape,i=r[1]*r[2],c=r[2],{newShape:u,keptDims:l}=(0,s.squeezeShape)(r),f=u;if(f.length<r.length){const i=(0,a.squeezeInputShape)(r,f),s=["batch","col","row"],c=JSON.parse(JSON.stringify(n));c.unpackedShape=i;const u=this.getUnpackedSamplerFromInput(e,t,c),d=l.reverse(),h=`\n ${u.routineBody}\n float ${e}(int batch, int row, int col) {\n return ${e}(${(0,a.getSqueezedParams)(s,d)});\n }\n `;return new o.GlslLibRoutine(h,u.dependencies)}const d=`\n float ${e}(int depth, int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = depth * ${i} + col * ${c} + row;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new o.GlslLibRoutine(d,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler4D(e,t,n){const r=n.unpackedShape,i=r[3],s=r[2]*i,a=`\n float ${e}(int row, int col, int depth, int depth2) {\n int index = row * ${r[1]*s} + col * ${s} +\n depth2 * ${i} + depth;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new o.GlslLibRoutine(a,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler5D(e,t,n){const r=n.unpackedShape,i=r[4],c=r[3]*i,u=r[2]*c,l=r[1]*u,{newShape:f,keptDims:d}=(0,s.squeezeShape)(r);if(f.length<r.length){const i=(0,a.squeezeInputShape)(r,f),s=["row","col","depth","depth2","depth3"],c=JSON.parse(JSON.stringify(n));c.unpackedShape=i;const u=`\n ${this.getUnpackedSamplerFromInput(e,t,c).routineBody}\n float ${e}(int row, int col, int depth, int depth2, int depth3) {\n return ${e}(${(0,a.getSqueezedParams)(s,d)});\n }\n `;return new o.GlslLibRoutine(u,["coordinates.sampleTexture","coordinates.uvFromFlat"])}const h=`\n float ${e}(int row, int col, int depth, int depth2, int depth3) {\n int index = row * ${l} + col * ${u} + depth * ${c} +\n depth3 * ${i} + depth2;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new o.GlslLibRoutine(h,["coordinates.sampleTexture","coordinates.uvFromFlat"])}getUnpackedSampler6D(e,t,n){const r=n.unpackedShape,i=r[5],c=r[4]*i,u=r[3]*c,l=r[2]*u,f=r[1]*l,{newShape:d,keptDims:h}=(0,s.squeezeShape)(r);if(d.length<r.length){const i=(0,a.squeezeInputShape)(r,d),s=["row","col","depth","depth2","depth3","depth4"],c=JSON.parse(JSON.stringify(n));c.unpackedShape=i;const u=`\n ${this.getUnpackedSamplerFromInput(e,t,c).routineBody}\n float ${e}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${e}(${(0,a.getSqueezedParams)(s,h)});\n }\n `;return new o.GlslLibRoutine(u,["coordinates.sampleTexture","coordinates.uvFromFlat"])}const p=`\n float ${e}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = row * ${f} + col * ${l} + depth * ${u} +\n depth2 * ${c} + depth3 * ${i} + depth4;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${t}, uv);\n }\n `;return new o.GlslLibRoutine(p,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}toVec(){const e=this.context.outputTextureLayout,t=e.shape.length,n=e.strides,r=e.width,i=e.height,s=[];for(let e=0;e<t-1;++e)s.push(`\n c[${e}] = offset / ${n[e]};`),s.push(`\n offset -= c[${e}] * ${n[e]};`);s.push(`\n c[${t-1}] = offset;`);const a=`\n void toVec(vec2 texCoords, out int c[${t}]) {\n int offset = coordsToOffset(texCoords, ${r}, ${i});\n ${s.join("")}\n }\n void toVec(int offset, out int c[${t}]) {\n ${s.join("")}\n }\n `;return{toVec:new o.GlslLibRoutine(a,["coordinates.coordsToOffset"])}}valueFrom(){const e={};return this.context.programInfo.inputNames.forEach(((t,n)=>{const r=this.context.inputTextureLayouts[n],i=(r.unpackedShape.length>0?r.unpackedShape:r.shape).length;let s=`_${t}`;e[s]=new o.GlslLibRoutine(this.getValueFromSingle(t,i,r.width,r.height,false),[`shapeUtils.indicesToOffset${s}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),s+="_T",e[s]=new o.GlslLibRoutine(this.getValueFromSingle(t,i,r.width,r.height,true),[`shapeUtils.indicesToOffset${s}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])})),e}getValueFromSingle(e,t,n,r,o){let s=`_${e}`;return o&&(s+="_T"),`\n float ${s}(int m[${t}]) {\n int offset = indicesToOffset${s}(m);\n vec2 coords = offsetToCoords(offset, ${n}, ${r});\n float value = getColorAsFloat(${(0,i.getGlsl)(this.context.glContext.version).texture2D}(${e}, coords));\n return value;\n }\n `}getPackedValueFrom(e,t,n,r,o){let s=`_${e}_Pack`;return o&&(s+="_T"),`\n vec4 ${s}(int m[${t}]) {\n int offset = indicesToOffset_${e}(m);\n vec2 coords = offsetToCoords(offset, ${n}, ${r});\n return ${(0,i.getGlsl)(this.context.glContext.version).texture2D}(${e}, coords);\n }\n `}}t.CoordsGlslLib=c},8520:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:true}),t.TopologicalSortGlslRoutines=t.GlslLibRoutineNode=t.GlslLibRoutine=t.GlslLib=t.GlslContext=t.FunctionType=void 0,(n=t.FunctionType||(t.FunctionType={}))[n.ValueBased=0]="ValueBased",n[n.Positional=1]="Positional",t.GlslContext=class{constructor(e,t,n,r){this.glContext=e,this.programInfo=t,this.inputTextureLayouts=n,this.outputTextureLayout=r}},t.GlslLib=class{constructor(e){this.context=e}},t.GlslLibRoutine=class{constructor(e,t){this.routineBody=e,this.dependencies=t}},t.GlslLibRoutineNode=class{constructor(e,t,n){this.name=e,this.dependencies=n||[],t&&(this.routineBody=t)}addDependency(e){e&&this.dependencies.push(e)}},t.TopologicalSortGlslRoutines=class{static returnOrderedNodes(e){if(!e||0===e.length)return[];if(1===e.length)return e;const t=new Set,n=new Set,r=new Array;return this.createOrderedNodes(e,t,n,r),r}static createOrderedNodes(e,t,n,r){for(let o=0;o<e.length;++o)this.dfsTraverse(e[o],t,n,r)}static dfsTraverse(e,t,n,r){if(!e||n.has(e.name))return;if(t.has(e.name))throw new Error("Cyclic dependency detected. Can't topologically sort routines needed for shader.");t.add(e.name);const o=e.dependencies;if(o&&o.length>0)for(let e=0;e<o.length;++e)this.dfsTraverse(o[e],t,n,r);r.push(e),n.add(e.name),t.delete(e.name)}}},7341:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.EncodingGlslLib=void 0;const r=n(8520);class o extends r.GlslLib{constructor(e){super(e)}getFunctions(){return Object.assign(Object.assign({},this.encodeFloat32()),this.decodeFloat32())}getCustomTypes(){return{}}encodeFloat32(){return{encode:new r.GlslLibRoutine("highp vec4 encode(highp float f) {\n return vec4(f, 0.0, 0.0, 0.0);\n }\n ")}}decodeFloat32(){return{decode:new r.GlslLibRoutine("highp float decode(highp vec4 rgba) {\n return rgba.r;\n }\n ")}}encodeUint8(){const e=o.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new r.GlslLibRoutine(`\n highp vec4 encode(highp float f) {\n highp float F = abs(f);\n highp float Sign = step(0.0,-f);\n highp float Exponent = floor(log2(F));\n highp float Mantissa = (exp2(- Exponent) * F);\n Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa));\n highp vec4 rgba;\n rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0));\n rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0);\n rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0)));\n rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0)));\n ${e}\n rgba = rgba / 255.0; // values need to be normalized to [0,1]\n return rgba;\n }\n `)}}decodeUint8(){const e=o.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new r.GlslLibRoutine(`\n highp float decode(highp vec4 rgba) {\n rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255]\n ${e}\n highp float Sign = 1.0 - step(128.0,rgba[0])*2.0;\n highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0;\n highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000);\n highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 ));\n return Result;\n }\n `)}}static isLittleEndian(){const e=new ArrayBuffer(4),t=new Uint32Array(e),n=new Uint8Array(e);if(t[0]=3735928559,239===n[0])return true;if(222===n[0])return false;throw new Error("unknown endianness")}}t.EncodingGlslLib=o},9894:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.FragColorGlslLib=void 0;const r=n(8520),o=n(5060);class i extends r.GlslLib{constructor(e){super(e)}getFunctions(){return Object.assign(Object.assign({},this.setFragColor()),this.getColorAsFloat())}getCustomTypes(){return{}}setFragColor(){const e=(0,o.getGlsl)(this.context.glContext.version);return{setFragColor:new r.GlslLibRoutine(`\n void setFragColor(float value) {\n ${e.output} = encode(value);\n }\n `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new r.GlslLibRoutine("\n float getColorAsFloat(vec4 color) {\n return decode(color);\n }\n ",["encoding.decode"])}}}t.FragColorGlslLib=i},2848:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true}),t.replaceInlines=void 0;const n=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;t.replaceInlines=function(e){const t={};let r;for(;null!==(r=n.exec(e));){const e=r[3].split(",").map((e=>{const t=e.trim().split(" ");return t&&2===t.length?{type:t[0],name:t[1]}:null})).filter((e=>null!==e));t[r[2]]={params:e,body:r[4]}}for(const n in t){const o="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__",n),i=new RegExp(o,"gm");for(;null!==(r=i.exec(e));){const o=r[1],i=r[2],s=r[3].split(","),a=o?`${o} ${i};`:"";let c=t[n].body,u="";t[n].params.forEach(((e,t)=>{e&&(u+=`${e.type} ${e.name} = ${s[t]};\n`)})),c=`${u}\n ${c}`,c=c.replace("return",`${i} = `);const l=`\n ${a}\n {\n ${c}\n }\n `;e=e.replace(r[0],l)}}return e.replace(n,"")}},8879:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.GlslPreprocessor=void 0;const r=n(8520),o=n(2848),i=n(5483),s=n(5060);t.GlslPreprocessor=class{constructor(e,t,n,o){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new r.GlslContext(e,t,n,o),Object.keys(i.glslRegistry).forEach((e=>{const t=new i.glslRegistry[e](this.context);this.libs[e]=t}));const s=this.glslLibRoutineDependencyGraph;for(const e in this.libs){const t=this.libs[e].getFunctions();for(const n in t){const o=e+"."+n;let i;s[o]?(i=s[o],i.routineBody=t[n].routineBody):(i=new r.GlslLibRoutineNode(o,t[n].routineBody),s[o]=i);const a=t[n].dependencies;if(a)for(let e=0;e<a.length;++e)if(s[a[e]])i.addDependency(s[a[e]]);else{const t=new r.GlslLibRoutineNode(a[e]);s[a[e]]=t,i.addDependency(t)}}}}preprocess(){const e=this.context.programInfo;let t=e.shaderSource;return this.context.programInfo.hasMain||(t=`${t}\n ${(0,s.getDefaultFragShaderMain)(this.context.glContext.version,this.context.outputTextureLayout.shape.length)}`),t=(0,o.replaceInlines)(t),`${(0,s.getFragShaderPreamble)(this.context.glContext.version)}\n ${this.getUniforms(e.inputNames,e.variables)}\n ${this.getImports(t)}\n ${t}`}getImports(e){const t=this.selectGlslLibRoutinesToBeIncluded(e);if(0===t.length)return"";let n="";for(let e=0;e<t.length;++e){if(!t[e].routineBody)throw new Error(`Missing body for the Glsl Library routine: ${t[e].name}`);n+=t[e].routineBody+"\n"}return n}selectGlslLibRoutinesToBeIncluded(e){const t=[];return Object.keys(this.glslLibRoutineDependencyGraph).forEach((n=>{const r=n.split(".")[1];-1!==e.indexOf(r)&&t.push(this.glslLibRoutineDependencyGraph[n])})),r.TopologicalSortGlslRoutines.returnOrderedNodes(t)}getUniforms(e,t){const n=[];if(e)for(const t of e)n.push(`uniform sampler2D ${t};`);if(t)for(const e of t)n.push(`uniform ${e.type} ${e.name}${e.arrayLength?`[${e.arrayLength}]`:""};`);return n.join("\n")}}},5483:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.glslRegistry=void 0;const r=n(5107),o=n(7341),i=n(9894),s=n(2655),a=n(3891);t.glslRegistry={encoding:o.EncodingGlslLib,fragcolor:i.FragColorGlslLib,vec:a.VecGlslLib,shapeUtils:s.ShapeUtilsGlslLib,coordinates:r.CoordsGlslLib}},2655:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.ShapeUtilsGlslLib=void 0;const r=n(8520);class o extends r.GlslLib{constructor(e){super(e)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.bcastIndex()),this.bcastMatmulIndex()),this.offsetToIndices()),this.indicesToOffset()),this.incrementIndices())}getCustomTypes(){return{}}bcastIndex(){const e=this.context.outputTextureLayout.shape.length,t={};return this.context.programInfo.inputNames.forEach(((n,o)=>{const i=this.context.inputTextureLayouts[o].unpackedShape;if(i.length<=e){const o=i.length,s=e-o,a=`bcastIndices_${n}`;let c="";for(let e=0;e<o;++e)c+=`\n realIndices[${e}] = int( mod(float(bcastedIndices[${s+e}]), ${i[e]}.0) );\n `;const u=`\n void ${a} (int bcastedIndices[${e}], out int realIndices[${o}]) {\n ${c}\n }\n `;t[a]=new r.GlslLibRoutine(u)}})),t}bcastMatmulIndex(){const e=this.context.outputTextureLayout.shape.length,t={};return this.context.programInfo.inputNames.forEach(((n,o)=>{const i=this.context.inputTextureLayouts[o].shape;if(!(i.length<2||i.length>e)){const o=i.length,s=e-o,a=`bcastMatmulIndices_${n}`;let c="";for(let e=0;e<o-2;++e)c+=`\n realIndices[${e}] = int( mod(float(bcastedIndices[${s+e}]), ${i[e]}.0) );\n `;const u=`\n void ${a}(int bcastedIndices[${e}], out int realIndices[${o}]) {\n ${c}\n realIndices[${o-1}] = bcastedIndices[${e-1}];\n realIndices[${o-2}] = bcastedIndices[${e-2}];\n }\n `;t[a]=new r.GlslLibRoutine(u)}})),t}indicesToOffset(){const e={};return this.context.programInfo.inputNames.forEach(((t,n)=>{const i=this.context.inputTextureLayouts[n].shape,s=this.context.inputTextureLayouts[n].strides,a=i.length;let c=`indicesToOffset_${t}`;e[c]=new r.GlslLibRoutine(o.indexToOffsetSingle(c,a,s)),c=`indicesToOffset_${t}_T`,e[c]=new r.GlslLibRoutine(o.indexToOffsetSingle(c,a,s.slice().reverse()))})),e}static indexToOffsetSingle(e,t,n){let r="";for(let e=t-1;e>=0;--e)r+=`\n offset += indices[${e}] * ${n[e]};\n `;return`\n int ${e}(int indices[${t}]) {\n int offset = 0;\n ${r}\n return offset;\n }\n `}offsetToIndices(){const e={};return this.context.programInfo.inputNames.forEach(((t,n)=>{const i=this.context.inputTextureLayouts[n].shape,s=this.context.inputTextureLayouts[n].strides,a=i.length;let c=`offsetToIndices_${t}`;e[c]=new r.GlslLibRoutine(o.offsetToIndicesSingle(c,a,s)),c=`offsetToIndices_${t}_T`,e[c]=new r.GlslLibRoutine(o.offsetToIndicesSingle(c,a,s.slice().reverse()))})),e}static offsetToIndicesSingle(e,t,n){const r=[];for(let e=0;e<t-1;++e)r.push(`\n indices[${e}] = offset / ${n[e]};`),r.push(`\n offset -= indices[${e}] * ${n[e]};`);return r.push(`\n indices[${t-1}] = offset;`),`\n void ${e}(int offset, out int indices[${t}]) {\n ${r.join("")}\n }\n `}incrementIndices(){const e={};return this.context.programInfo.inputNames.forEach(((t,n)=>{const o=this.context.inputTextureLayouts[n].shape,i=o.length,s=`incrementIndices_${t}`;let a="";for(let e=0;e<i;++e)a+=`\n shape[${e}] = ${o[e]};`;const c=`\n void ${s}(int axis, out int indices[${i}]) {\n int shape[${i}];\n ${a};\n for(int i = ${i} -1 ; i >= 0; --i) {\n if(i > axis) continue;\n indices[i] += 1;\n if(indices[i] < shape[i]) {\n break;\n }\n indices[i] = 0;\n }\n }\n `;e[s]=new r.GlslLibRoutine(c)})),e}}t.ShapeUtilsGlslLib=o},5060:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true}),t.getDefaultFragShaderMain=t.getFragShaderPreamble=t.getVertexShaderSource=t.getGlsl=void 0;const n={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},r={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"};function o(e){return 1===e?n:r}t.getGlsl=o,t.getVertexShaderSource=function(e){const t=o(e);return`${t.version}\n precision highp float;\n ${t.attribute} vec3 position;\n ${t.attribute} vec2 textureCoord;\n\n ${t.varyingVertex} vec2 TexCoords;\n\n void main()\n {\n gl_Position = vec4(position, 1.0);\n TexCoords = textureCoord;\n }`},t.getFragShaderPreamble=function(e){const t=o(e);return`${t.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${t.varyingFrag} vec2 TexCoords;\n ${t.outputDeclaration}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n // Custom vector types to handle higher dimenalities.\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n `},t.getDefaultFragShaderMain=function(e,t){return`\n void main() {\n int indices[${t}];\n toVec(TexCoords, indices);\n vec4 result = vec4(process(indices));\n ${o(e).output} = result;\n }\n `}},3891:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.VecGlslLib=void 0;const r=n(8520);class o extends r.GlslLib{constructor(e){super(e)}getCustomTypes(){return{}}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign({},this.binaryVecFunctions()),this.copyVec()),this.setVecItem()),this.getVecItem())}binaryVecFunctions(){const e=this.context.outputTextureLayout.shape.length,t={add:"+=",sub:"-=",mul:"*=",div:"/="},n={};for(const o in t){const i=`${o}Vec`;let s="";for(let n=0;n<e;++n)s+=`\n dest[${n}] ${t[o]} src[${n}];\n `;const a=`\n void ${i}(int src[${e}], out int dest[${e}]) {\n ${s}\n }\n `;n[i]=new r.GlslLibRoutine(a)}return n}copyVec(){const e=this.context.outputTextureLayout.shape.length;let t="";for(let n=0;n<e;++n)t+=`\n dest[${n}] = src[${n}];\n `;const n=`\n void copyVec(int src[${e}], out int dest[${e}]) {\n ${t}\n }\n `;return{copyVec:new r.GlslLibRoutine(n)}}setVecItem(){const e=this.context.outputTextureLayout.shape.length;let t=`\n if(index < 0)\n index =${e} + index;\n if (index == 0)\n m[0] = value;\n `;for(let n=1;n<e-1;++n)t+=`\n else if (index == ${n})\n m[${n}] = value;\n `;t+=`\n else\n m[${e-1}] = value;\n `;const n=`\n void setVecItem(out int m[${e}], int index, int value) {\n ${t}\n }\n `;return{setVecItem:new r.GlslLibRoutine(n)}}getVecItem(){const e=this.context.outputTextureLayout.shape.length;let t=`\n if(index < 0)\n index = ${e} + index;\n if (index == 0)\n return m[0];\n `;for(let n=1;n<e-1;++n)t+=`\n else if (index == ${n})\n return m[${n}];\n `;t+=`\n else\n return m[${e-1}];\n `;const n=`\n int getVecItem(int m[${e}], int index) {\n ${t}\n }\n `;return{getVecItem:new r.GlslLibRoutine(n)}}}t.VecGlslLib=o},8316:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.WebGLInferenceHandler=void 0;const r=n(6231),o=n(9162),i=n(2517),s=n(2403),a=n(7019),c=n(8710),u=n(5611),l=n(4057),f=n(2039);t.WebGLInferenceHandler=class{constructor(e){this.session=e,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(e,t){return(0,l.calculateTextureWidthAndHeight)(this.session.layoutStrategy,e,t)}executeProgram(e,t){if(t.length<e.inputNames.length)throw new Error(`Input size mustn't be less than ${e.inputNames.length}.`);if(e.inputNames.length!==e.inputTypes.length)throw new Error("input names size does not match input types");const n=[];for(let r=0;r<e.inputNames.length;++r)n[r]=this.getOrCreateTextureData(t[r],e.inputTypes[r]);const r=((e,t)=>{const n=t.map((e=>`${e.unpackedShape.join(",")};${e.width}x${e.height}`)).join("_");let r=e.name;return e.cacheHint&&(r+="["+e.cacheHint+"]"),r+=":"+n,r})(e,n);let o=this.session.programManager.getArtifact(r);const i=o?o.programInfo:"function"==typeof e.get?e.get():e,s=(0,l.createTextureLayoutFromTextureType)(this.session.layoutStrategy,i.output.dims,i.output.textureType),a=this.createTextureData(s,i.output.type);return o||(o=this.session.programManager.build(i,n,a),this.session.programManager.setArtifact(r,o)),this.runProgram(o,n,a),a}run(e,t){return this.executeProgram(e,t).tensor}runProgram(e,t,n){for(let n=0;n<t.length;++n)if(!!t[n].isPacked!=(e.programInfo.inputTypes[n]===f.TextureType.packed))throw new Error(`input[${n}] property packed inconsistent`);if(!!n.isPacked!=(e.programInfo.output.textureType===f.TextureType.packed))throw new Error("output property packed inconsistent");this.session.programManager.run(e,t,n)}getOrCreateTextureData(e,t){let n=this.getTextureData(e.dataId,t===f.TextureType.packed);if(!n&&(n=this.getTextureData(e.dataId,t!==f.TextureType.packed),n))return t===f.TextureType.packed?this.pack(n):this.unpack(n);if(!n){const r=(0,l.createTextureLayoutFromTextureType)(this.session.layoutStrategy,e.dims,t);if(t===f.TextureType.packedLastDimension){const n=1,r=4,o=e.dims;if(4===o.length){const i=[o[0],Math.ceil(o[1]*o[2]*o[3]/r)],s=(0,l.createTextureLayoutFromTextureType)(this.session.layoutStrategy,i,t);let a=e.numberData;if(o[1]*o[2]*o[3]%r!=0){const t=o[0],i=o[1]*o[2]*o[3],s=Math.ceil(i*n/r)*r;a=new Float32Array(t*s);for(let r=0;r<t;++r){const t=r*i,o=r*s+r%n*i;a.set(e.numberData.subarray(t,t+i),o)}}return this.createTextureData(s,e.type,a,e,1)}}if(t===f.TextureType.packed){const t=(0,l.createTextureLayoutFromShape)(this.session.layoutStrategy,e.dims,1,[],{reverseWH:true}),r=this.createTextureData(t,e.type,e.numberData,e,1);n=this.pack(r)}else n=this.createTextureData(r,e.type,e.numberData,e,1)}return n}createTextureDataFromLayoutBindTensor(e,t,n,r){return this.createTextureData(e,t,n,r,1)}createTextureData(e,t,n,o,i){r.Logger.verbose("InferenceHandler",`Creating TextureData: layout:[${JSON.stringify(e)}]`);const s=this.session.textureManager.createTextureFromLayout(t,e,n,i);return this.createTextureDataFromTexture(e,t,s,o)}reshapeUnpacked(e,t){const n=this.getOrCreateTextureData(e,f.TextureType.unpacked),r={channels:n.channels,height:n.height,width:n.width,shape:0!==t.length?t:[1],strides:i.ShapeUtil.computeStrides(t),unpackedShape:t};return this.createTextureDataFromTexture(r,e.type,n.texture).tensor}reshapePacked(e,t){const n=this.getOrCreateTextureData(e,f.TextureType.packed);if((0,a.isReshapeCheap)(e.dims,t)){const r={channels:n.channels,height:n.height,width:n.width,shape:0!==t.length?t:[1],strides:i.ShapeUtil.computeStrides(t),unpackedShape:t,isPacked:true};return this.createTextureDataFromTexture(r,e.type,n.texture).tensor}const r=(0,a.processDims3D)(e.dims),o=(0,a.processDims3D)(t),s=this.reshapePacked(e,r),c=this.run((0,a.createPackedReshape3DProgramInfoLoader)(this,s,o),[s]);return this.reshapePacked(c,t)}cast(e,t){const n=this.getOrCreateTextureData(e,f.TextureType.unpacked);return this.createTextureDataFromTexture(n,t,n.texture).tensor}createTextureDataFromTexture(e,t,n,r,i){const s=Object.assign(Object.assign({},e),{tensor:r||new o.Tensor(e.unpackedShape,t,(e=>this.readTexture(s)),(async e=>this.readTextureAsync(s)),void 0,i),texture:n});return this.setTextureData(s.tensor.dataId,s,e.isPacked),s}getTextureData(e,t=false){return this.session.isInitializer(e)?this.session.getTextureData(e,t):t?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,t,n=false){this.session.isInitializer(e)?this.session.setTextureData(e,t,n):(n?this.packedTextureDataCache:this.unpackedTextureDataCache).set(e,t)}isTextureLayoutCached(e,t=false){return!!this.getTextureData(e.dataId,t)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((e=>this.session.textureManager.releaseTexture(e))),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((e=>this.session.textureManager.releaseTexture(e))),this.unpackedTextureDataCache=new Map}readTexture(e){return e.isPacked?this.readTexture(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,c.encodeAsUint8)(this,e))}async readTextureAsync(e){return e.isPacked?this.readTextureAsync(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,c.encodeAsUint8)(this,e))}pack(e){return this.executeProgram((0,s.createPackProgramInfoLoader)(this,e.tensor),[e.tensor])}unpack(e){return this.executeProgram((0,u.createUnpackProgramInfoLoader)(this,e.tensor),[e.tensor])}}},1640:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:true,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return o(t,e),t};Object.defineProperty(t,"__esModule",{value:true}),t.WEBGL_OP_RESOLVE_RULES=void 0;const s=n(2898),a=i(n(7839)),c=n(4196),u=n(2069),l=n(8138),f=n(9663),d=n(5193),h=n(7992),p=n(1253),m=n(4776),w=n(6572),g=n(3346),v=n(5623),y=n(2870),_=n(2143),b=n(4939),x=n(718),T=n(2268),M=n(8117),E=n(2278),S=n(5524),A=n(5975),$=n(3933),O=n(6558),P=n(5723),C=n(3738),k=i(n(4909)),I=n(8428),F=n(9793);t.WEBGL_OP_RESOLVE_RULES=[["Abs","","6+",k.abs],["Acos","","7+",k.acos],["Add","","7+",a.add],["And","","7+",a.and],["Asin","","7+",k.asin],["Atan","","7+",k.atan],["AveragePool","","7+",_.averagePool,_.parseAveragePoolAttributes],["BatchNormalization","","7+",s.batchNormalization,s.parseBatchNormalizationAttributes],["Cast","","6+",c.cast,c.parseCastAttributes],["Ceil","","6+",k.ceil],["Clip","","6-10",k.clip,k.parseClipAttributes],["Clip","","11+",k.clipV11],["Concat","","4+",u.concat,u.parseConcatAttributes],["Conv","","1+",l.conv,l.parseConvAttributes],["ConvTranspose","","1+",f.convTranspose,f.parseConvTransposeAttributes],["Cos","","7+",k.cos],["Div","","7+",a.div],["Dropout","","7+",k.identity],["DepthToSpace","","1+",d.depthToSpace,d.parseDepthToSpaceAttributes],["Equal","","7+",a.equal],["Elu","","6+",k.elu,k.parseEluAttributes],["Exp","","6+",k.exp],["Flatten","","1+",h.flatten,h.parseFlattenAttributes],["Floor","","6+",k.floor],["FusedConv","com.microsoft","1+",l.conv,l.parseConvAttributes],["Gather","","1+",p.gather,p.parseGatherAttributes],["Gemm","","7-10",m.gemm,m.parseGemmAttributesV7],["Gemm","","11+",m.gemm,m.parseGemmAttributesV11],["GlobalAveragePool","","1+",_.globalAveragePool,_.parseGlobalAveragePoolAttributes],["GlobalMaxPool","","1+",_.globalMaxPool],["Greater","","7+",a.greater],["Identity","","1+",k.identity],["ImageScaler","","1+",w.imageScaler,w.parseImageScalerAttributes],["InstanceNormalization","","6+",g.instanceNormalization,g.parseInstanceNormalizationAttributes],["LeakyRelu","","6+",k.leakyRelu,k.parseLeakyReluAttributes],["Less","","7+",a.less],["Log","","6+",k.log],["MatMul","","1+",v.matMul,v.parseMatMulAttributes],["MaxPool","","1+",_.maxPool,_.parseMaxPoolAttributes],["Mul","","7+",a.mul],["Neg","","6+",k.neg],["Not","","1+",k.not],["Or","","7+",a.or],["Pad","","2-10",y.padV2,y.parsePadAttributesV2],["Pad","","11+",y.padV11,y.parsePadAttributesV11],["Pow","","7+",a.pow],["PRelu","","7+",a.pRelu],["ReduceLogSum","","1+",b.reduceLogSum,b.parseReduceAttributes],["ReduceMax","","1+",b.reduceMax,b.parseReduceAttributes],["ReduceMean","","1+",b.reduceMean,b.parseReduceAttributes],["ReduceMin","","1+",b.reduceMin,b.parseReduceAttributes],["ReduceProd","","1+",b.reduceProd,b.parseReduceAttributes],["ReduceSum","","1-12",b.reduceSum,b.parseReduceAttributes],["ReduceSumSquare","","1+",b.reduceLogSumSquare,b.parseReduceAttributes],["Relu","","6+",k.relu],["Reshape","","5+",x.reshape],["Resize","","10",T.resize,T.parseResizeAttributesV10],["Resize","","11+",T.resize,T.parseResizeAttributesV11],["Shape","","1+",M.shape],["Sigmoid","","6+",k.sigmoid],["Sin","","7+",k.sin],["Slice","","10+",E.sliceV10],["Slice","","1-9",E.slice,E.parseSliceAttributes],["Softmax","","1-12",S.softmax,S.parseSoftmaxAttributes],["Softmax","","13+",S.softmaxV13,S.parseSoftmaxAttributesV13],["Split","","2-12",A.split,A.parseSplitAttributes],["Sqrt","","6+",k.sqrt],["Squeeze","","1-12",$.squeeze,$.parseSqueezeAttributes],["Squeeze","","13+",$.squeezeV13],["Sub","","7+",a.sub],["Sum","","6+",O.sum],["Tan","","7+",k.tan],["Tanh","","6+",k.tanh],["Tile","","6+",P.tile],["Transpose","","1+",C.transpose,C.parseTransposeAttributes],["Upsample","","7-8",F.upsample,F.parseUpsampleAttributesV7],["Upsample","","9",F.upsample,F.parseUpsampleAttributesV9],["Unsqueeze","","1-12",I.unsqueeze,I.parseUnsqueezeAttributes],["Unsqueeze","","13+",I.unsqueezeV13],["Xor","","7+",a.xor]]},2898:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseBatchNormalizationAttributes=t.batchNormalization=void 0;const r=n(246),o=n(5060),i=n(2039),s={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[i.TextureType.unpacked,i.TextureType.unpacked,i.TextureType.unpacked,i.TextureType.unpacked,i.TextureType.unpacked]};t.batchNormalization=(e,t,n)=>(c(t),[e.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>a(e,t,n)}),t)]),t.parseBatchNormalizationAttributes=e=>{const t=e.attributes.getFloat("epsilon",1e-5),n=e.attributes.getFloat("momentum",.9),o=e.attributes.getInt("spatial",1);return(0,r.createAttributeWithCacheKey)({epsilon:t,momentum:n,spatial:o})};const a=(e,t,n)=>{const r=(0,o.getGlsl)(e.session.backend.glContext.version),a=t[0].dims.length,[c,u]=e.calculateTextureWidthAndHeight(t[1].dims,i.TextureType.unpacked),l=`\n float process(int[${a}] indices) {\n vec2 position = offsetToCoords(indices[1], ${c}, ${u});\n float scale = getColorAsFloat(${r.texture2D}(Scale, position));\n float mean = getColorAsFloat(${r.texture2D}(Mean, position));\n float variance = getColorAsFloat(${r.texture2D}(Variance, position));\n float b = getColorAsFloat(${r.texture2D}(B, position));\n\n return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n.epsilon})) ) + b;\n }`;return Object.assign(Object.assign({},s),{output:{dims:t[0].dims,type:t[0].type,textureType:i.TextureType.unpacked},shaderSource:l})},c=e=>{if(!e||5!==e.length)throw new Error("BatchNormalization requires 5 inputs.");const t=e[0],n=e[1],r=e[2],o=e[3],i=e[4];if(t.dims.length<3||1!==n.dims.length||1!==r.dims.length||1!==o.dims.length||1!==i.dims.length)throw new Error("invalid input shape.");if(n.dims[0]!==t.dims[1]||r.dims[0]!==t.dims[1]||o.dims[0]!==t.dims[1]||i.dims[0]!==t.dims[1])throw new Error("invalid input shape.");if("float32"!==t.type&&"float64"!==t.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type||"float32"!==o.type&&"float64"!==o.type||"float32"!==i.type&&"float64"!==i.type)throw new Error("invalid input tensor types.")}},7839:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.xor=t.sub=t.pRelu=t.pow=t.or=t.mul=t.less=t.greater=t.equal=t.div=t.and=t.add=t.glslPRelu=t.glslPow=t.glslXor=t.glslOr=t.glslAnd=t.glslLess=t.glslGreater=t.glslEqual=t.glslSub=t.glslMul=t.glslDiv=t.glslAdd=void 0;const r=n(2517),o=n(8520),i=n(5060),s=n(2039);function a(){const e="add_";return{body:`\n float ${e}(float a, float b) {\n return a + b;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return v1 + v2;\n }\n `,name:e,type:o.FunctionType.ValueBased}}function c(){const e="div_";return{body:`\n float ${e}(float a, float b) {\n return a / b;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return v1 / v2;\n }\n `,name:e,type:o.FunctionType.ValueBased}}function u(){const e="mul_";return{body:`\n float ${e}(float a, float b) {\n return a * b;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return v1 * v2;\n }\n `,name:e,type:o.FunctionType.ValueBased}}function l(){const e="sub_";return{body:`\n float ${e}(float a, float b) {\n return a - b;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return v1 - v2;\n }\n `,name:e,type:o.FunctionType.ValueBased}}function f(){const e="equal_";return{body:`\n float ${e}(float a, float b) {\n return float(a == b);\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return vec4(equal(v1, v2));\n }\n `,name:e,type:o.FunctionType.ValueBased}}function d(){const e="greater_";return{body:`\n float ${e}(float a, float b) {\n return float(a > b);\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return vec4( v1.r > v2.r ,\n v1.g > v2.g,\n v1.b > v2.b,\n v1.a > v2.a );\n }\n `,name:e,type:o.FunctionType.ValueBased}}function h(){const e="less_";return{body:`\n float ${e}(float a, float b) {\n return float(a < b);\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return vec4( v1.r < v2.r ,\n v1.g < v2.g,\n v1.b < v2.b,\n v1.a < v2.a );\n }\n `,name:e,type:o.FunctionType.ValueBased}}function p(){const e="and_";return{body:`\n float ${e}(float a, float b) {\n return float( bool(a) && bool(b) );\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r && b2.r ,\n b1.g && b2.g,\n b1.b && b2.b,\n b1.a && b2.a );\n }\n `,name:e,type:o.FunctionType.ValueBased}}function m(){const e="or_";return{body:`\n float ${e}(float a, float b) {\n return float( bool(a) || bool(b) );\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r || b2.r ,\n b1.g || b2.g,\n b1.b || b2.b,\n b1.a || b2.a );\n }\n `,name:e,type:o.FunctionType.ValueBased}}function w(){const e="xor_";return{body:`\n float ${e}(float a, float b) {\n return float( bool(a) ^^ bool(b) );\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r ^^ b2.r ,\n b1.g ^^ b2.g,\n b1.b ^^ b2.b,\n b1.a ^^ b2.a );\n }\n `,name:e,type:o.FunctionType.ValueBased}}function g(){return function(e){const t=`${e}_`;return{body:`\n float ${t}(float a, float b) {\n return ${e}(a, b);\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return ${e}(v1, v2);\n }\n `,name:t,type:o.FunctionType.ValueBased}}("pow")}function v(){const e="prelu_";return{body:`\n float ${e}(float a, float b) {\n return a < 0.0 ? a * b: a;\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return vec4(\n v1.r < 0.0 ? v1.r * v2.r: v1.r,\n v1.g < 0.0 ? v1.g * v2.g: v1.g,\n v1.b < 0.0 ? v1.b * v2.b: v1.b,\n v1.a < 0.0 ? v1.a * v2.a: v1.a\n );\n }\n `,name:e,type:o.FunctionType.ValueBased}}t.glslAdd=a,t.glslDiv=c,t.glslMul=u,t.glslSub=l,t.glslEqual=f,t.glslGreater=d,t.glslLess=h,t.glslAnd=p,t.glslOr=m,t.glslXor=w,t.glslPow=g,t.glslPRelu=v;const y=(e,t,n,r=t[0].type,o)=>{const i=e.session.pack?s.TextureType.packed:s.TextureType.unpacked;return{name:n.name,inputNames:["A","B"],inputTypes:[i,i],cacheHint:o,get:()=>_(e,t,n,r)}},_=(e,t,n,o=t[0].type)=>{const a=e.session.pack?s.TextureType.packed:s.TextureType.unpacked,c=!r.ShapeUtil.areEqual(t[0].dims,t[1].dims);let u=t[0].dims;const l=e.session.pack;if(c){const s=r.BroadcastUtil.calcShape(t[0].dims,t[1].dims,false);if(!s)throw new Error("Can't perform binary op on the given tensors");u=s;const c=u.length,f=0!==t[0].dims.length?t[0].dims.length:1,d=0!==t[1].dims.length?t[1].dims.length:1,h=0!==t[0].dims.length?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",p=0!==t[1].dims.length?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",m=(0,i.getGlsl)(e.session.backend.glContext.version),w=l?`\n ${n.body}\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n vec4 result = ${n.name}(a, b);\n ${m.output} = result;\n }`:`\n ${n.body}\n float process(int indices[${c}]) {\n int aindices[${f}];\n int bindices[${d}];\n ${h}\n ${p}\n return ${n.name}(_A(aindices), _B(bindices));\n }`;return{name:n.name,inputNames:["A","B"],inputTypes:[a,a],output:{dims:u,type:o,textureType:a},shaderSource:w,hasMain:l}}const f=(0,i.getGlsl)(e.session.backend.glContext.version),d=`\n ${n.body}\n void main() {\n vec4 v1 = ${f.texture2D}(A, TexCoords);\n vec4 v2 = ${f.texture2D}(B, TexCoords);\n vec4 result = ${n.name}(v1, v2);\n ${f.output} = result;\n }\n `;return{name:n.name,inputNames:["A","B"],inputTypes:[a,a],output:{dims:t[0].dims,type:o,textureType:a},shaderSource:d,hasMain:true}};t.add=(e,t)=>[e.run(y(e,t,a()),t)],t.and=(e,t)=>[e.run(y(e,t,p(),"bool"),t)],t.div=(e,t)=>[e.run(y(e,t,c()),t)],t.equal=(e,t)=>[e.run(y(e,t,f(),"bool"),t)],t.greater=(e,t)=>[e.run(y(e,t,d(),"bool"),t)],t.less=(e,t)=>[e.run(y(e,t,h(),"bool"),t)],t.mul=(e,t)=>[e.run(y(e,t,u()),t)],t.or=(e,t)=>[e.run(y(e,t,m(),"bool"),t)],t.pow=(e,t)=>[e.run(y(e,t,g()),t)],t.pRelu=(e,t)=>[e.run(y(e,t,v()),t)],t.sub=(e,t)=>[e.run(y(e,t,l()),t)],t.xor=(e,t)=>[e.run(y(e,t,w(),"bool"),t)]},4196:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseCastAttributes=t.cast=void 0;const r=n(2517);t.cast=(e,t,n)=>(o(t),[e.cast(t[0],n)]),t.parseCastAttributes=e=>r.ProtoUtil.tensorDataTypeFromProto(e.attributes.getInt("to"));const o=e=>{if(!e||1!==e.length)throw new Error("Cast requires 1 input.");if("string"===e[0].type)throw new Error("Invalid input type.")}},1163:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.createPackedConcatProgramInfoLoader=void 0;const r=n(5060),o=n(2039),i=n(9390),s=n(2827);t.createPackedConcatProgramInfoLoader=(e,t,n)=>{const c=(u=t.length,l=n.cacheKey,{name:"Concat (packed)",inputNames:Array.from({length:u},((e,t)=>`X${t}`)),inputTypes:Array(u).fill(o.TextureType.packed),cacheHint:l});var u,l;return Object.assign(Object.assign({},c),{get:()=>((e,t,n,c)=>{const u=n[0].dims.slice();if(c>=u.length||c<-1*u.length)throw new Error("axis specified for concat doesn't match input dimensionality");c<0&&(c=u.length+c);const l=u.slice(0);for(let e=1;e<n.length;e++){const t=n[e].dims.slice();for(let e=0;e<u.length;e++)if(e===c)l[c]+=t[e];else if(u[e]!==t[e])throw new Error("non concat dimensions must match")}const f=l.length,d=(0,s.getChannels)("coords",f),h=(0,i.getCoordsDataType)(f),p=(0,s.unpackFromChannel)(),m=n.map((e=>e.dims)),w=(0,i.getGlChannels)(f),g=new Array(m.length-1);g[0]=m[0][c];for(let e=1;e<g.length;e++)g[e]=g[e-1]+m[e][c];const v=w[c],y=w.slice(-2),_=w.join();let b=`if (${v} < ${g[0]}) {\n return getChannel(\n getX0(${_}), vec2(${y.join()}));\n }`;for(let e=1;e<g.length;e++){const t=g[e-1];b+=`\n if (${v} < ${g[e]} && ${v} >= ${g[e-1]}) {\n return getChannel(\n getX${e}(${a(w,v,t)}),\n vec2(${a(y,v,t)}));\n }`}const x=g.length,T=g[g.length-1];b+=`\n return getChannel(\n getX${x}(${a(w,v,T)}),\n vec2(${a(y,v,T)}));`;const M=(0,r.getGlsl)(e.session.backend.glContext.version),E=`\n ${p}\n float getValue(${w.map((e=>"int "+e))}) {\n ${b}\n }\n\n void main() {\n ${h} coords = getOutputCoords();\n int lastDim = coords.${w[f-1]};\n coords.${w[f-1]} = coords.${w[f-2]};\n coords.${w[f-2]} = lastDim;\n\n vec4 result = vec4(getValue(${d}), 0., 0., 0.);\n\n ${d[f-1]} = ${d[f-1]} + 1;\n if (${d[f-1]} < ${l[f-1]}) {\n result.g = getValue(${d});\n }\n\n ${d[f-2]} = ${d[f-2]} + 1;\n if (${d[f-2]} < ${l[f-2]}) {\n result.a = getValue(${d});\n }\n\n ${d[f-1]} = ${d[f-1]} - 1;\n if (${d[f-2]} < ${l[f-2]} &&\n ${d[f-1]} < ${l[f-1]}) {\n result.b = getValue(${d});\n }\n ${M.output} = result;\n }\n `;return Object.assign(Object.assign({},t),{output:{dims:l,type:n[0].type,textureType:o.TextureType.packed},shaderSource:E,hasMain:true})})(e,c,t,n.axis)})};const a=(e,t,n)=>{const r=e.indexOf(t);return e.map(((e,t)=>t===r?`${e} - ${n}`:e)).join()}},2069:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseConcatAttributes=t.concat=void 0;const r=n(246),o=n(2039),i=n(1163);t.concat=(e,t,n)=>(f(t),e.session.pack&&t[0].dims.length>1?[e.run((0,i.createPackedConcatProgramInfoLoader)(e,t,n),t)]:[e.run(s(e,t,n),t)]);const s=(e,t,n)=>{const r=(i=t.length,s=n.cacheKey,{name:"Concat",inputNames:Array.from({length:i},((e,t)=>`X${t}`)),inputTypes:Array(i).fill(o.TextureType.unpacked),cacheHint:s});var i,s;return Object.assign(Object.assign({},r),{get:()=>((e,t,n,r)=>{const i=n[0].dims.slice();if(r>=i.length||r<-1*i.length)throw new Error("axis specified for concat doesn't match input dimensionality");r<0&&(r=i.length+r);const s=i.slice(0);for(let e=1;e<n.length;e++){const t=n[e].dims.slice();for(let e=0;e<i.length;e++)if(e===r)s[r]+=t[e];else if(i[e]!==t[e])throw new Error("non concat dimensions must match")}const f=s.length,d=new Array(n.length);let h=0;for(let e=0;e<d.length;++e)h+=n[e].dims[r],d[e]=h;let p="";p=n.length<5?a(d):c(d);const m=`\n ${u(n.length,f)}\n ${l(d)}\n ${p}\n float process(int indices[${f}]) {\n int textureIndex = getTextureWhereDataResides (indices[${r}]);\n\n if(textureIndex != 0) {\n indices[${r}] = indices[${r}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1)));\n }\n\n return fetchDataFromCorrectTexture(textureIndex, indices);\n }`;return Object.assign(Object.assign({},t),{output:{dims:s,type:n[0].type,textureType:o.TextureType.unpacked},shaderSource:m})})(0,r,t,n.axis)})},a=e=>`int getTextureWhereDataResides(int index) {\n ${e.map(((e,t)=>`if(index<${e}) {return ${t};}\n`)).join("")}\n }`,c=e=>a(e),u=(e,t)=>{const n=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${t}]) {`];for(let t=0;t<e;++t)0===t?n.push(`\tif (textureIndex == ${t}) { return _X${t}(indices); }`):t===e-1?n.push(`\telse { return _X${t}(indices); }`):n.push(`\telse if (textureIndex == ${t}) { return _X${t}(indices); }`);return n.push("\t}"),n.join("\n")},l=e=>{const t=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let n=0;n<e.length;++n)0===n?t.push(`\tif (index == ${n}) { return ${e[n]}; }`):n===e.length-1?t.push(`\telse { return ${e[n]}; }`):t.push(`\telse if (index == ${n}) { return ${e[n]}; }`);return t.push("\t}"),t.join("\n")};t.parseConcatAttributes=e=>(0,r.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis")});const f=e=>{if(!e||e.length<1)throw new Error("too few inputs");const t=e[0].type,n=e[0].dims.length;if("string"===t)throw new Error("string tensor is not supported yet");for(const r of e){if(r.type!==t)throw new Error("input tensors should be one type");if(r.dims.length!==n)throw new Error("input tensors should have the same shape")}}},4770:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.createUnpackedGroupedConvProgramInfoLoader=void 0;const r=n(6231),o=n(5060),i=n(2039),s=n(8138),a=n(2823);t.createUnpackedGroupedConvProgramInfoLoader=(e,t,n)=>{const c=(u=t.length>2,l=n.cacheKey,{name:"GroupedConv",inputNames:u?["X","W","Bias"]:["X","W"],inputTypes:u?[i.TextureType.unpacked,i.TextureType.unpacked,i.TextureType.unpacked]:[i.TextureType.unpacked,i.TextureType.unpacked],cacheHint:l});var u,l;return Object.assign(Object.assign({},c),{get:()=>((e,t,n,c)=>{const u=t.length>2?"value += getBias(output_channel);":"",l=t[0].dims.slice(),f=t[1].dims.slice(),d=f[0]/c.group;r.Logger.verbose("GroupedConv",`autpPad:${c.autoPad}, dilations:${c.dilations}, group:${c.group}, kernelShape:${c.kernelShape}, pads:${c.pads}, strides:${c.strides}`);const h=(0,s.calculateOutputShape)(l,f,c.dilations,c.pads,c.strides),p=(0,o.getGlsl)(e.session.backend.glContext.version),{activationFunction:m,applyActivation:w}=(0,a.getActivationSnippet)(c),g=`\n const ivec2 strides = ivec2(${c.strides[0]}, ${c.strides[1]});\n const ivec2 pads = ivec2(${c.pads[0]}, ${c.pads[1]});\n ${m}\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int output_channel = coords.y;\n ivec2 xRCCorner = coords.zw * strides - pads;\n int group_id = output_channel / ${d};\n\n float value = 0.0;\n for (int wInChannel = 0; wInChannel < ${f[1]}; wInChannel++) {\n int input_channel = group_id * ${f[1]} + wInChannel;\n for (int wHeight = 0; wHeight < ${f[2]}; wHeight++) {\n int xHeight = xRCCorner.x + wHeight * ${c.dilations[0]};\n\n if (xHeight < 0 || xHeight >= ${l[2]}) {\n continue;\n }\n\n for (int wWidth = 0; wWidth < ${f[3]}; wWidth++) {\n int xWidth = xRCCorner.y + wWidth * ${c.dilations[1]};\n if (xWidth < 0 || xWidth >= ${l[3]}) {\n continue;\n }\n\n float xVal = getX(batch, input_channel, xWidth, xHeight);\n float wVal = getW(output_channel, wInChannel, wWidth, wHeight);\n value += xVal*wVal;\n }\n }\n }\n ${u}\n ${w}\n ${p.output} = vec4(value, .0, .0, .0);\n }\n`;return Object.assign(Object.assign({},n),{output:{dims:h,type:t[0].type,textureType:i.TextureType.unpacked},shaderSource:g,hasMain:true})})(e,t,c,n)})}},1386:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.conv2DPacked=t.conv2DPackedPointwise=void 0;const r=n(8138),o=n(8555),i=n(708);t.conv2DPackedPointwise=(e,t,n)=>{const o=t[0].dims,s=t[1].dims,a=(0,r.calculateOutputShape)(o,s,n.dilations,n.pads,n.strides),c=e.reshapePacked(t[0],[o[1],o[2]*o[3]]),u=e.reshapePacked(t[1],[s[0],s[1]]),l=t.length>2?[u,c,t[2]]:[u,c],f=e.run((0,i.createPackedMatmulProgramInfoLoader)(e,l,n),l);return e.reshapePacked(f,a)},t.conv2DPacked=(e,t,n)=>{const s=t[0].dims,a=t[1].dims,c=(0,r.calculateOutputShape)(s,a,n.dilations,n.pads,n.strides),u=e.run((0,o.createPackedIm2ColProgramInfoLoader)(e,t[0],t[1],c,n),[t[0]]),l=e.reshapePacked(t[1],[a[0],a[1]*a[2]*a[3]]),f=3===t.length?[l,u,t[2]]:[l,u],d=e.run((0,i.createPackedMatmulProgramInfoLoader)(e,f,n),f);return e.reshapePacked(d,c)}},9663:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseConvTransposeAttributes=t.convTranspose=void 0;const r=n(246),o=n(5060),i=n(2039),s=n(2823),a=(e,t,n,r,o,i)=>(e-1)*t+n+(r-1)*o+1-i,c=(e,t,n,r,o)=>{const i=Math.floor(e/2);"SAME_UPPER"===t?(n[r]=i,n[o]=e-i):"SAME_LOWER"===t&&(n[r]=e-i,n[o]=i)};t.convTranspose=(e,t,n)=>(d(t,n),u(e,t,n));const u=(e,t,n)=>{const r=f(n,t);return[l(e,t,r)]},l=(e,t,n)=>e.run(((e,t,n)=>{const r=(a=t.length>2,c=n.cacheKey,{name:"ConvTranspose",inputNames:a?["X","W","B"]:["X","W"],inputTypes:a?[i.TextureType.unpacked,i.TextureType.unpacked,i.TextureType.unpacked]:[i.TextureType.unpacked,i.TextureType.unpacked],cacheHint:c});var a,c;return Object.assign(Object.assign({},r),{get:()=>((e,t,n,r)=>{const a=t.length>2?"getB(output_channel)":"0.0",c=t[0].dims,u=t[1].dims,l=u[1],f=u[0]/r.group,d=[t[0].dims[0],t[1].dims[1]*r.group,...r.outputShape],h=(0,o.getGlsl)(e.session.backend.glContext.version),{activationFunction:p,applyActivation:m}=(0,s.getActivationSnippet)(r),w=`\n const ivec2 strides = ivec2(${r.strides[0]}, ${r.strides[1]});\n const ivec2 pads = ivec2(${r.pads[0]}, ${r.pads[1]});\n ${p}\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int output_channel = coords.y;\n\n ivec2 loc = coords.zw + pads;\n\n int group_id = output_channel / ${l};\n int wOutChannel = output_channel - group_id * ${l};\n\n float value = ${a};\n for (int inChannelOffset = 0; inChannelOffset < ${f}; inChannelOffset++) {\n int input_channel = group_id * ${f} + inChannelOffset;\n for (int wWOff = 0; wWOff < ${u[2]}; wWOff++) {\n for (int wHOff = 0; wHOff < ${u[3]}; wHOff++) {\n ivec2 wOff = ivec2(wWOff * ${r.dilations[0]}, wHOff * ${r.dilations[1]});\n ivec2 wLoc = loc - wOff;\n ivec2 wLocIn = wLoc / strides;\n if (\n wLocIn * strides == wLoc &&\n wLocIn.x >= 0 && wLocIn.x < ${c[2]} &&\n wLocIn.y >= 0 && wLocIn.y < ${c[3]}\n ) {\n float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x);\n float wVal = getW(input_channel, wOutChannel, wHOff, wWOff);\n value += xVal * wVal;\n }\n }\n }\n }\n ${m}\n ${h.output} = vec4(value, .0, .0, .0);\n }\n`;return Object.assign(Object.assign({},n),{output:{dims:d,type:t[0].type,textureType:i.TextureType.unpacked},shaderSource:w,hasMain:true})})(e,t,r,n)})})(e,t,n),t),f=(e,t)=>{const n=e.kernelShape.slice();if(0===e.kernelShape.length)for(let e=2;e<t[1].dims.length;++e)n.push(t[1].dims[e]);const r=e.pads.slice(),o=e.outputShape.slice();((e,t,n,r,o,i,s,u)=>{const l=e.length-2,f=0===u.length;for(let d=0;d<l;++d){const h=f?e[d+2]*i[d]:u[d],p=a(e[d+2],i[d],o[d],t[d],n[d],h);c(p,r,o,d,d+l),f&&u.push(i[d]*(e[d+2]-1)+s[d]+(t[d]-1)*n[d]+1-o[d]-o[d+l])}})(t[0].dims,n,e.dilations,e.autoPad,r,e.strides,e.outputPadding,o);const i=Object.assign({},e);return Object.assign(i,{kernelShape:n,pads:r,outputShape:o,cacheKey:e.cacheKey}),i};t.parseConvTransposeAttributes=e=>{const t=e.attributes,n=(0,s.parseInternalActivationAttributes)(t),o=t.getString("auto_pad","NOTSET"),i=t.getInts("dilations",[1,1]),a=t.getInt("group",1),c=t.getInts("kernel_shape",[]),u=t.getInts("output_padding",[0,0]),l=t.getInts("output_shape",[]),f=t.getInts("pads",[0,0,0,0]),d=t.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:o,dilations:i,group:a,kernelShape:c,outputPadding:u,outputShape:l,pads:f,strides:d},n))};const d=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length||4!==e[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(e[0].dims[1]!==e[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");const n=e[1].dims[1]*t.group;if(3===e.length&&(1!==e[2].dims.length||e[2].dims[0]!==n))throw new Error("invalid bias");const r=e[0].dims.length-2;if(t.dilations.length!==r)throw new Error(`dilations should be ${r}D`);if(t.strides.length!==r)throw new Error(`strides should be ${r}D`);if(t.pads.length!==2*r)throw new Error(`pads should be ${2*r}D`);if(t.outputPadding.length!==r)throw new Error(`output_padding should be ${r}D`);if(0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(0!==t.outputShape.length&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape");if("float32"!==e[0].type||"float32"!==e[1].type)throw new Error("ConvTranspose input(X,W) should be float tensor");if(3===e.length&&"float32"!==e[2].type)throw new Error("ConvTranspose input(bias) should be float tensor")}},8138:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseConvAttributes=t.conv=t.calculateOutputShape=void 0;const r=n(246),o=n(2517),i=n(4770),s=n(1386),a=n(9828),c=n(2823),u=n(3248),l=n(5623);t.calculateOutputShape=(e,t,n,r,o)=>{const i=e[0],s=e.slice(2),a=s.length,c=t[0],u=t.slice(2).map(((e,t)=>e+(e-1)*(n[t]-1))),l=s.map(((e,t)=>e+r[t]+r[t+a])).map(((e,t)=>Math.floor((e-u[t]+o[t])/o[t])));return[i,c].concat(...l)},t.conv=(e,t,n)=>(m(t,n),f(e,t,n));const f=(e,t,n)=>{const r=p(n,t),o=e.session.pack,a=1===r.kernelShape[0]&&1===r.kernelShape[1];return r.group>1?[e.run((0,i.createUnpackedGroupedConvProgramInfoLoader)(e,t,r),t)]:a&&o?[d(e,t,r)]:o&&4===t[0].dims.length&&1===t[0].dims[0]&&!a?[(0,s.conv2DPacked)(e,t,r)]:[h(e,t,r)]},d=(e,n,r)=>{const o=n[0].dims,i=n[1].dims,s=(0,t.calculateOutputShape)(o,i,r.dilations,r.pads,r.strides),a=e.reshapeUnpacked(n[0],[o[1],o[2]*o[3]]),c=e.reshapeUnpacked(n[1],[i[0],i[1]]),u=n.length>2?[c,a,n[2]]:[c,a],f=e.run((0,l.createMatmulProgramInfoLoader)(u,r),u);return e.reshapeUnpacked(f,s)},h=(e,n,r)=>{const o=n[0].dims,i=n[1].dims,s=(0,t.calculateOutputShape)(o,i,r.dilations,r.pads,r.strides),c=e.run((0,u.createIm2ColProgramInfoLoader)(e,n[0],n[1],s,r),[n[0]]),l=3===n.length?[c,n[1],n[2]]:[c,n[1]];return e.run((0,a.createDotProductProgramInfoLoader)(e,n,s,r),l)},p=(e,t)=>{const n=e.kernelShape.slice();if(0===e.kernelShape.length)for(let e=2;e<t[1].dims.length;++e)n.push(t[1].dims[e]);const r=e.pads.slice();o.PoolConvUtil.adjustPadsBasedOnAutoPad(t[0].dims,e.strides,e.dilations,n,r,e.autoPad);const i=Object.assign({},e);return Object.assign(i,{kernelShape:n,pads:r,cacheKey:e.cacheKey}),i};t.parseConvAttributes=e=>{const t=e.attributes,n=(0,c.parseInternalActivationAttributes)(t),o=t.getString("auto_pad","NOTSET"),i=t.getInts("dilations",[1,1]),s=t.getInt("group",1),a=t.getInts("kernel_shape",[]),u=t.getInts("pads",[0,0,0,0]),l=t.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:o,dilations:i,group:s,kernelShape:a,pads:u,strides:l},n))};const m=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length||4!==e[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(e[0].dims[1]!==e[1].dims[1]*t.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===e.length&&(1!==e[2].dims.length||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");const n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if("float32"!==e[0].type||"float32"!==e[1].type)throw new Error("Conv input(X,W) should be float tensor");if(3===e.length&&"float32"!==e[2].type)throw new Error("Conv input(bias) should be float tensor")}},5193:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseDepthToSpaceAttributes=t.depthToSpace=void 0;const r=n(3738);t.depthToSpace=(e,t,n)=>{o(t);const i=n.blocksize,s=i*i,a="DCR"===n.mode?[0,3,4,1,5,2]:[0,1,4,2,5,3],c="DCR"===n.mode?[t[0].dims[0],i,i,t[0].dims[1]/s,t[0].dims[2],t[0].dims[3]]:[t[0].dims[0],t[0].dims[1]/s,i,i,t[0].dims[2],t[0].dims[3]],u=e.reshapeUnpacked(t[0],c),l={perm:a,cacheKey:`${a}`},[f]=(0,r.transpose)(e,[u],l),d=[t[0].dims[0],t[0].dims[1]/s,t[0].dims[2]*i,t[0].dims[3]*i];return[e.reshapeUnpacked(f,d)]},t.parseDepthToSpaceAttributes=e=>{const t=e.attributes.getInt("blocksize");if(t<1)throw new Error(`blocksize must be >= 1, but got : ${t} for DepthToSpace`);const n=e.attributes.getString("mode","DCR");if("DCR"!==n&&"CRD"!==n)throw new Error(`unrecognized mode: ${n} for DepthToSpace`);return{mode:n,blocksize:t}};const o=e=>{if(1!==e.length)throw new Error(`DepthToSpace expect 1 inputs, but got ${e.length}`);if("string"===e[0].type||4!==e[0].dims.length)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}},9828:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.createDotProductProgramInfoLoader=void 0;const r=n(2517),o=n(5060),i=n(2039),s=n(2823),a=n(3248);t.createDotProductProgramInfoLoader=(e,t,n,c)=>{const u=((e,t)=>({name:"ConvDotProduct",inputNames:e?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:e?[i.TextureType.unpacked,i.TextureType.packedLastDimension,i.TextureType.unpacked]:[i.TextureType.unpacked,i.TextureType.packedLastDimension],cacheKey:t.activationCacheKey}))(t.length>2,c);return Object.assign(Object.assign({},u),{get:()=>((e,t,n,c,u)=>{const l=n[0].dims,f=n[1].dims,d=[f[0],Math.ceil(l[1]*f[2]*f[3]/4)],h=(0,a.calculateIm2ColDims)(l,f,c),[p,m]=e.calculateTextureWidthAndHeight(d,i.TextureType.packedLastDimension),w=r.ShapeUtil.computeStrides(h),[g,v]=e.calculateTextureWidthAndHeight(h,i.TextureType.packedLastDimension),y=c.length,_=n.length<3?"0.0":"_B(b)",b=Math.ceil(l[1]*f[2]*f[3]/4),{activationFunction:x,applyActivation:T}=(0,s.getActivationSnippet)(u),M=(0,o.getGlsl)(e.session.backend.glContext.version),E=`\n${x}\nfloat process(int indices[${y}]) {\n int b[1];\n b[0] = indices[1];\n int im2col[4];\n im2col[0] = indices[0];\n im2col[1] = indices[2];\n im2col[2] = indices[3];\n int im2colOffset = im2col[0] * ${w[0]} + im2col[1] * ${w[1]} + im2col[2] * ${w[2]};\n int kernelOffset = indices[1] * ${d[1]};\n float value = ${_};\n for (int i = 0; i < ${b}; ++i) {\n vec2 im2colCoords = offsetToCoords(im2colOffset, ${g}, ${v});\n vec2 kernelCoords = offsetToCoords(kernelOffset, ${p}, ${m});\n value += dot(${M.texture2D}(Im2Col, im2colCoords), ${M.texture2D}(K, kernelCoords));\n ++im2colOffset;\n ++kernelOffset;\n }\n ${T}\n return value;\n}`;return Object.assign(Object.assign({},t),{output:{dims:c,type:n[0].type,textureType:i.TextureType.unpacked},shaderSource:E})})(e,u,t,n,c)})}},7992:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseFlattenAttributes=t.flatten=void 0;const r=n(2517);t.flatten=(e,t,n)=>{o(t,n);const i=r.ShapeUtil.flattenShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],i)]},t.parseFlattenAttributes=e=>e.attributes.getInt("axis",1);const o=(e,t)=>{if(!e||1!==e.length)throw new Error("Flatten requires 1 input.");const n=e[0].dims.length;if(0===n)throw new Error("scalar tensor is not supported.");if(t<-n||t>n)throw new Error("Invalid axis");if("string"===e[0].type)throw new Error("string tensor is not supported.")}},2823:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseInternalActivationAttributes=t.getActivationSnippet=void 0;const r=n(2517),o=n(4909);t.getActivationSnippet=function(e){let t;switch(e.activation){case"Relu":t=(0,o.glslRelu)();break;case"Sigmoid":t=(0,o.glslSigmoid)();break;case"Clip":t=(0,o.glslClip)(e.clipMin,e.clipMax);break;default:return{activationFunction:"",applyActivation:""}}const n=t.name;return{activationFunction:t.body,applyActivation:`value = ${n}_(value);`}},t.parseInternalActivationAttributes=e=>{const t=e.getString("activation","");if("Clip"===t){const[n,o]=e.getFloats("activation_params",[r.MIN_CLIP,r.MAX_CLIP]);return{activation:t,clipMax:o,clipMin:n,activationCacheKey:`${t}:${n},${o}`}}return{activation:t,activationCacheKey:t}}},1253:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseGatherAttributes=t.gather=void 0;const r=n(246),o=n(782),i=n(2517),s=n(2039);t.gather=(e,t,n)=>(u(t,n.axis),[e.run(c(e,t,n),t)]),t.parseGatherAttributes=e=>(0,r.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis",0)});const a={name:"Gather",inputNames:["A","B"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},c=(e,t,n)=>{const r=Object.assign(Object.assign({},a),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((e,t,n,r)=>{const o=n[0].dims.slice(),a=n[1].dims.slice(),c=new Array(o.length+a.length-1);r=i.ShapeUtil.normalizeAxis(r,o.length);const u=[];for(let e=0;e<c.length;e++)e<r?(c[e]=o[e],u.push(`inputIdx[${e}] = outputIdx[${e}];`)):e<r+a.length?(c[e]=a[e-r],u.push(`indexDataIdx[${e-r}] = outputIdx[${e}];`)):(c[e]=o[e-a.length+1],u.push(`inputIdx[${e-a.length+1}] = outputIdx[${e}];`));const l=`\n float process(int outputIdx[${c.length||1}]) {\n int inputIdx[${o.length}];\n int indexDataIdx[${a.length||1}];\n indexDataIdx[0] = 0;\n ${u.join("\n ")}\n int idx = int(_B(indexDataIdx));\n inputIdx[${r}] = idx < 0 ? idx + ${o[r]} : idx;\n return _A(inputIdx);\n }`;return Object.assign(Object.assign({},t),{output:{dims:c,type:n[0].type,textureType:s.TextureType.unpacked},shaderSource:l})})(0,r,t,n.axis)})},u=(e,t)=>{if(!e||2!==e.length)throw new Error("Gather requires 2 inputs.");const n=e[0].dims.length;if(n<1)throw new Error("Invalid input shape.");if(t<-n||t>n-1)throw new Error("Invalid axis.");if(-1===o.NUMBER_TYPES.indexOf(e[0].type))throw new Error("Invaid input type.");if("int32"!==e[1].type&&"int16"!==e[1].type)throw new Error("Invaid input type.")}},4776:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseGemmAttributesV11=t.parseGemmAttributesV7=t.gemm=void 0;const r=n(246),o=n(2517),i=n(2039);t.gemm=(e,t,n)=>(u(t,n),[e.run(a(t,n),t)]);const s=(e,t)=>{const n=0!==e.attributes.getInt("transA",0),o=0!==e.attributes.getInt("transB",0),i=e.attributes.getFloat("alpha",1),s=e.attributes.getFloat("beta",1);return(0,r.createAttributeWithCacheKey)({transA:n,transB:o,alpha:i,beta:s,isOptionalC:t})};t.parseGemmAttributesV7=e=>s(e,false),t.parseGemmAttributesV11=e=>s(e,true);const a=(e,t)=>{const n={name:"Gemm",inputNames:3===e.length?["A","B","C"]:["A","B"],inputTypes:3===e.length?[i.TextureType.unpacked,i.TextureType.unpacked,i.TextureType.unpacked]:[i.TextureType.unpacked,i.TextureType.unpacked],key:t.cacheKey};return Object.assign(Object.assign({},n),{get:()=>c(n,e,t)})},c=(e,t,n)=>{const r=t[0].dims.slice(),s=t[1].dims.slice(),[a,c]=o.GemmUtil.getShapeOfGemmResult(r,n.transA,s,n.transB,3===t.length?t[2].dims:void 0),u=[a,c];if(!u)throw new Error("Can't use gemm on the given tensors");let l=r[r.length-1],f="";n.transA&&(l=r[0]),n.transA&&n.transB?f="value += _A_T(a) * _B_T(b);":n.transA&&!n.transB?f="value += _A_T(a) * _B(b);":!n.transA&&n.transB?f="value += _A(a) * _B_T(b);":n.transA||n.transB||(f="value += _A(a) * _B(b);");const d=u.length,h=`\n float process(int indices[${d}]) {\n int a[${d}];\n int b[${d}];\n ${3===t.length?`int c[${t[2].dims.length}];`:""}\n\n copyVec(indices, a);\n copyVec(indices, b);\n ${3===t.length?"bcastIndices_C(indices, c);":""}\n\n float value = 0.0;\n for (int k=0; k<${l}; ++k) {\n a[${d-1}] = k;\n b[${d-2}] = k;\n ${f}\n }\n\n value = value * alpha;\n ${3===t.length?"value += beta * _C(c);":""}\n return value;\n }`;return Object.assign(Object.assign({},e),{output:{dims:u,type:t[0].type,textureType:i.TextureType.unpacked},variables:[{name:"alpha",type:"float",data:n.alpha},{name:"beta",type:"float",data:n.beta}],shaderSource:h})},u=(e,t)=>{if(!e)throw new Error("Input is missing");if(t.isOptionalC&&(e.length<2||e.length>3))throw new Error("Invaid input shape.");if(!t.isOptionalC&&3!==e.length)throw new Error("Gemm requires 3 inputs");if(3===e.length&&1!==e[2].dims.length&&2!==e[2].dims.length)throw new Error("Invalid input shape of C");if("float32"!==e[0].type&&"float64"!==e[0].type||"float32"!==e[1].type&&"float64"!==e[1].type||3===e.length&&"float32"!==e[2].type&&"float64"!==e[2].type)throw new Error("Invalid input type.");if(e[0].type!==e[1].type||3===e.length&&e[0].type!==e[2].type)throw new Error("Input types are mismatched")}},8555:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.createPackedIm2ColProgramInfoLoader=void 0;const r=n(5060),o=n(2039),i=n(2827);t.createPackedIm2ColProgramInfoLoader=(e,t,n,s,a)=>{const c=(u=a.cacheKey,{name:"Im2Col (packed)",inputNames:["A"],inputTypes:[o.TextureType.packed],cacheHint:u});var u;return Object.assign(Object.assign({},c),{get:()=>((e,t,n,s,a,c)=>{const u=n.dims,l=s.dims,f=a.length,d=[l[1]*l[2]*l[3],a[2]*a[3]],h=l[2]*l[3],p=(0,i.unpackFromChannel)(),m=(0,r.getGlsl)(e.session.backend.glContext.version);let w="";for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)w+=`\n blockIndex = rc.x + ${t};\n pos = rc.y + ${e};\n\n if(blockIndex < ${d[1]} && pos < ${d[0]}) {\n offsetY = int(blockIndex / (${a[f-1]})) * ${c.strides[0]} -\n ${c.pads[0]};\n d0 = offsetY + ${c.dilations[0]} * (imod(pos, ${h}) / ${l[2]});\n\n if(d0 < ${u[2]} && d0 >= 0) {\n offsetX = imod(blockIndex, ${a[f-1]}) * ${c.strides[1]} -\n ${c.pads[1]};\n d1 = offsetX + ${c.dilations[1]} * imod(imod(pos, ${h}), ${l[2]});\n\n if(d1 < ${u[3]} && d1 >= 0) {\n\n ch = int(float(pos)/ ${h}.);\n innerDims = vec2(d0, d1);\n result[${2*e+t}] = getChannel(\n getA(0, ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n\n `;const g=`\n ${p}\n\n void main() {\n ivec2 rc = getOutputCoords();\n vec4 result = vec4(0.0);\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n ${w}\n ${m.output} = result;\n }\n `;return Object.assign(Object.assign({},t),{output:{dims:d,type:n.type,textureType:o.TextureType.packed},shaderSource:g,hasMain:true})})(e,c,t,n,s,a)})}},3248:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.calculateIm2ColDims=t.createIm2ColProgramInfoLoader=void 0;const r=n(2039);t.createIm2ColProgramInfoLoader=(e,n,o,i,s)=>{const a=(c=s.cacheKey,{name:"Im2Col",inputNames:["X"],inputTypes:[r.TextureType.unpacked],cacheHint:c});var c;return Object.assign(Object.assign({},a),{get:()=>((e,n,o,i,s,a)=>{const c=o.dims,u=i.dims,l=s.length,f=(0,t.calculateIm2ColDims)(c,u,s,4),d=`\n const int XC = ${c[1]};\n const int XH = ${c[2]};\n const int XW = ${c[3]};\n const int KH = ${a.kernelShape[0]};\n const int KW = ${a.kernelShape[1]};\n const int dilationH = ${a.dilations[0]};\n const int dilationW = ${a.dilations[1]};\n const int strideH = ${a.strides[0]};\n const int strideW = ${a.strides[1]};\n const int padH = ${a.pads[0]};\n const int padW = ${a.pads[1]};\n const int KHKW = KH*KW;\n const int XCKHKW = XC * KHKW;\n const int outputChannels = 4;\n vec4 process(int indices[${l}]) {\n int b = indices[0]; // batch size\n int oh = indices[1] * strideH - padH; //output height\n int ow = indices[2] * strideW - padW; //output width\n int p = indices[3] * outputChannels; //patch\n vec4 value = vec4(0.0);\n for(int i=0; i < outputChannels; ++i) {\n if(p < XCKHKW) {\n int patchC = p / KHKW;\n int patchH = (p - patchC*KHKW) / KW;\n int patchW = (p - patchC*KHKW) - patchH * KW;\n int xh2 = oh + patchH * dilationH;\n int xw2 = ow + patchW * dilationW;\n int x[${c.length}];\n x[0] = b;\n x[1] = patchC;\n x[2] = xh2;\n x[3] = xw2;\n if(xh2 >= 0 &&\n xh2 < XH &&\n xw2 >= 0 &&\n xw2 < XW) {\n value[i] = _X(x);\n }\n }\n ++p;\n }\n return value;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:f,type:o.type,textureType:r.TextureType.packedLastDimension},shaderSource:d})})(0,a,n,o,i,s)})},t.calculateIm2ColDims=(e,t,n,r=4)=>[n[0],n[2],n[3],Math.ceil(e[1]*t[2]*t[3]/r)]},6572:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseImageScalerAttributes=t.imageScaler=void 0;const r=n(246),o=n(2039);t.imageScaler=(e,t,n)=>(c(t),[e.run(s(e,t,n),t)]),t.parseImageScalerAttributes=e=>{const t=e.attributes.getFloat("scale"),n=e.attributes.getFloats("bias");return(0,r.createAttributeWithCacheKey)({scale:t,bias:n})};const i={name:"ImageScaler",inputNames:["X"],inputTypes:[o.TextureType.unpacked]},s=(e,t,n)=>{const r=Object.assign(Object.assign({},i),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((e,t,n,r)=>{const i=n[0].dims.slice(),s=i.length,c=`\n ${a(r.bias.length)}\n float process(int indices[${s}]) {\n return _X(indices) * scale + getBias(bias, indices[1]);\n }`;return Object.assign(Object.assign({},t),{output:{dims:i,type:n[0].type,textureType:o.TextureType.unpacked},variables:[{name:"bias",type:"float",arrayLength:r.bias.length,data:r.bias},{name:"scale",type:"float",data:r.scale}],shaderSource:c})})(0,r,t,n)})},a=e=>{const t=[`float getBias(float bias[${e}], int channel) {`];for(let n=0;n<e;++n)0===n?t.push(`\tif (channel == ${n}) { return bias[${n}]; }`):n===e-1?t.push(`\telse { return bias[${n}]; }`):t.push(`\telse if (channel == ${n}) { return bias[${n}]; }`);return t.push("\t}"),t.join("\n")},c=e=>{if(!e||1!==e.length)throw new Error("ImageScaler requires 1 input.");if(4!==e[0].dims.length)throw new Error("Invalid input shape.");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type.")}},3346:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseInstanceNormalizationAttributes=t.instanceNormalization=void 0;const r=n(5060),o=n(2039);t.instanceNormalization=(e,t,n)=>{u(t);const r=e.run(s(t[0]),t);return[e.run(c(e,t[0],n,r.dims),[t[0],r,t[1],t[2]])]},t.parseInstanceNormalizationAttributes=e=>e.attributes.getFloat("epsilon",1e-5);const i={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[o.TextureType.unpacked]},s=e=>Object.assign(Object.assign({},i),{get:()=>((e,t)=>{const n=t.dims.slice(),r=n[1],i=n[2]*n[3],s=[n[0],r],a=`\n vec4 process(int[2] indices) {\n vec4 v = vec4(0.0);\n int a[4];\n a[0] = indices[0];\n a[1] = indices[1];\n float temp = 0.0;\n for(int a2=0; a2<${n[2]}; a2++) {\n a[2] = a2;\n for(int a3=0; a3<${n[3]}; a3++) {\n a[3] = a3;\n float x = _X(a);\n temp += x;\n }\n }\n float mean = temp / float(${i});\n temp = 0.0;\n for(int a2=0; a2<${n[2]}; a2++) {\n a[2] = a2;\n for(int a3=0; a3<${n[3]}; a3++) {\n a[3] = a3;\n float x = _X(a);\n temp += (x - mean) * (x - mean);\n }\n }\n v.r = mean;\n v.g = temp / float(${i});\n\n return v;\n }`;return Object.assign(Object.assign({},e),{output:{dims:s,type:t.type,textureType:o.TextureType.packedLastDimension},shaderSource:a})})(i,e)}),a={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[o.TextureType.unpacked,o.TextureType.packedLastDimension,o.TextureType.unpacked,o.TextureType.unpacked]},c=(e,t,n,i)=>{const s=Object.assign(Object.assign({},a),{cacheHint:`${n}`});return Object.assign(Object.assign({},s),{get:()=>((e,t,n,i,s)=>{const a=(0,r.getGlsl)(e.session.backend.glContext.version),[c,u]=e.calculateTextureWidthAndHeight(s,o.TextureType.packedLastDimension),[l,f]=[c/4,u],d=`\n vec4 get_MeanAndVariance(int[2] mv) {\n int offset = indicesToOffset_MeanAndVariance(mv);\n vec2 coords = offsetToCoords(offset, ${l}, ${f});\n return ${a.texture2D}(MeanAndVariance, coords);\n }\n\n float process(int[4] indices) {\n int mv[2];\n mv[0] = indices[0];\n mv[1] = indices[1];\n vec4 mean_and_variance = get_MeanAndVariance(mv);\n float mean = mean_and_variance.r;\n float variance = mean_and_variance.g;\n\n int sb[1];\n sb[0] = indices[1];\n float scale = _Scale(sb);\n float b = _B(sb);\n\n return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b;\n }`;return Object.assign(Object.assign({},t),{output:{dims:n.dims,type:n.type,textureType:o.TextureType.unpacked},variables:[{name:"epsilon",type:"float",data:i}],shaderSource:d})})(e,s,t,n,i)})},u=e=>{if(!e||3!==e.length)throw new Error("InstanceNormalization requires 3 inputs.");const t=e[0],n=e[1],r=e[2];if(t.dims.length<3||1!==n.dims.length||1!==r.dims.length)throw new Error("Invalid input shape.");if(n.dims[0]!==t.dims[1]||r.dims[0]!==t.dims[1])throw new Error("Input shapes are mismatched.");if("float32"!==t.type&&"float64"!==t.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type)throw new Error("Invalid input type.");if(4!==e[0].dims.length)throw new Error("Only support 4-D input shape.")}},708:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.createPackedMatmulProgramInfoLoader=void 0;const r=n(2517),o=n(5060),i=n(2039),s=n(9390),a=n(2823),c=n(5623);t.createPackedMatmulProgramInfoLoader=(e,t,n)=>{const u=(l=t.length>2,f=n.activationCacheKey,{name:"MatMul (packed)",inputNames:l?["A","B","Bias"]:["A","B"],inputTypes:l?[i.TextureType.packed,i.TextureType.packed,i.TextureType.packed]:[i.TextureType.packed,i.TextureType.packed],cacheHint:f});var l,f;return Object.assign(Object.assign({},u),{get:()=>((e,t,n,u)=>{const l=n.length>2,f=l?"value += getBiasForMatmul();":"",d=n[0].dims,h=n[1].dims,p=r.BroadcastUtil.calcShape(d,h,true),m=!r.ShapeUtil.areEqual(n[0].dims,n[1].dims);if(!p)throw new Error("Can't use matmul on the given tensors");const w=d[d.length-1],g=Math.ceil(w/2),v=d.length,y=h.length,_=(0,o.getGlsl)(e.session.backend.glContext.version),b=(0,s.getCoordsDataType)(p.length),x=p.length,T=(0,s.getGlChannels)(),{activationFunction:M,applyActivation:E}=(0,a.getActivationSnippet)(u),S=l?`${(0,c.getBiasForMatmul)(b,T,n[2].dims,p,true)}`:"",A=m?`${function(e,t,n,o){let i=[],s=[];const a=n[0].dims,c=n[1].dims,u=a.length,l=c.length,f=o.length,d=f-u,h=f-l;i=a.map(((e,n)=>`coords.${t[n+d]}`)),i[u-1]="i*2",i.join(", "),s=c.map(((e,n)=>`coords.${t[n+h]}`)),s[l-2]="i*2",s.join(", ");const p=r.BroadcastUtil.getBroadcastDims(a,o),m=r.BroadcastUtil.getBroadcastDims(c,o),w=p.map((e=>`coords.${t[e+d]} = 0;`)).join("\n"),g=m.map((e=>`coords.${t[e+h]} = 0;`)).join("\n"),v=`int lastDim = coords.${t[f-1]};\n coords.${t[f-1]} = coords.${t[f-2]};\n coords.${t[f-2]} = lastDim;`;return`\nvec4 getAAtOutCoordsMatmul(int i) {\n ${e} coords = getOutputCoords();\n ${v}\n ${w}\n vec4 outputValue = getA(${i});\n return outputValue;\n}\n\nvec4 getBAtOutCoordsMatmul(int i) {\n ${e} coords = getOutputCoords();\n ${v}\n ${g}\n vec4 outputValue = getB(${s});\n return outputValue;\n}`}(b,T,n,p)}`:"",$=m?"getAAtOutCoordsMatmul(i)":`getA(${function(e,t){let n="";for(let r=0;r<t-2;r++)n+=`rc.${e[r]}, `;return n+=`rc.${e[t-2]}, i*2`,n}(T,v)})`,O=m?"getBAtOutCoordsMatmul(i)":`getB(${function(e,t){let n="";for(let r=0;r<t-2;r++)n+=`rc.${e[r]}, `;return n+=`i*2, rc.${e[t-1]}`,n}(T,y)})`,P=`\n ${A}\n ${S}\n ${M}\n void main() {\n ${m?"":`${b} rc =\n getOutputCoords(); int lastDim = rc.${T[x-1]}; rc.${T[x-1]} =\n rc.${T[x-2]}; rc.${T[x-2]} = lastDim;\n `}\n\n vec4 value = vec4(0);\n for (int i = 0; i < ${g}; i++) {\n vec4 a = ${$};\n vec4 b = ${O};\n\n value += (a.rrbb * b.rgrg);\n value += (a.ggaa * b.baba);\n }\n ${f}\n ${E}\n ${_.output} = value;\n }`;return Object.assign(Object.assign({},t),{output:{dims:p,type:n[0].type,textureType:i.TextureType.packed},shaderSource:P,hasMain:true})})(e,u,t,n)})}},5623:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.getBiasForMatmul=t.createMatmulProgramInfoLoader=t.parseMatMulAttributes=t.matMul=void 0;const r=n(2517),o=n(2039),i=n(9390),s=n(2823),a=n(708);function c(e,t){const n=(a=e.length>2,c=t.activationCacheKey,{name:"MatMul",inputNames:a?["A","B","Bias"]:["A","B"],inputTypes:a?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],cacheHint:c});var a,c;return Object.assign(Object.assign({},n),{get:()=>function(e,t,n){const a=t[0].dims,c=t[1].dims,u=r.BroadcastUtil.calcShape(a,c,true);if(!u)throw new Error("Can't use matmul on the given tensors");const f=(0,i.getCoordsDataType)(u.length),d=(0,i.getGlChannels)(),{activationFunction:h,applyActivation:p}=(0,s.getActivationSnippet)(n),m=t.length>2,w=m?"value += getBiasForMatmul();":"",g=m?`${l(f,d,t[2].dims,u,false)}`:"",v=u.length,y=a.length,_=c.length,b=`\n ${h}\n ${g}\n float process(int indices[${v}]) {\n int a[${y}];\n int b[${_}];\n bcastMatmulIndices_A(indices, a);\n bcastMatmulIndices_B(indices, b);\n\n float value;\n for (int k=0; k<${a[a.length-1]}; ++k) {\n a[${y-1}] = k;\n b[${_-2}] = k;\n value += _A(a) * _B(b);\n }\n ${w}\n ${p}\n return value;\n }`;return Object.assign(Object.assign({},e),{output:{dims:u,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:b})}(n,e,t)})}t.matMul=(e,t,n)=>(u(t),e.session.pack?[e.run((0,a.createPackedMatmulProgramInfoLoader)(e,t,n),t)]:[e.run(c(t,n),t)]),t.parseMatMulAttributes=e=>(0,s.parseInternalActivationAttributes)(e.attributes),t.createMatmulProgramInfoLoader=c;const u=e=>{if(!e||2!==e.length)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.");if("float32"!==e[0].type&&"float64"!==e[0].type||"float32"!==e[1].type&&"float64"!==e[1].type)throw new Error("inputs should be float type");if(e[0].type!==e[1].type)throw new Error("inputs types should match")};function l(e,t,n,o,i){let s="";const a=n.length,c=o.length,u=c-a;s=c<2&&a>0?"coords":n.map(((e,n)=>`coords.${t[n+u]}`)).join(", ");const l=r.BroadcastUtil.getBroadcastDims(n,o).map((e=>`coords.${t[e+u]} = 0;`)).join("\n");let f="vec4(outputValue.xx, outputValue.yy)";return 1===r.ShapeUtil.size(n)&&(f="vec4(outputValue.x)"),i?`\nvec4 getBiasForMatmul() {\n ${e} coords = getOutputCoords();\n ${l}\n vec4 outputValue = getBias(${s});\n return ${f};\n}`:`\nfloat getBiasForMatmul() {\n ${e} coords = getOutputCoords();\n ${l}\n return getBias(coords.x);\n}`}t.getBiasForMatmul=l},2403:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.createPackProgramInfoLoader=void 0;const r=n(5060),o=n(2039),i=n(9390),s=n(2827),a={name:"pack",inputNames:["A"],inputTypes:[o.TextureType.unpackedReversed]};t.createPackProgramInfoLoader=(e,t)=>Object.assign(Object.assign({},a),{get:()=>((e,t)=>{const n=(0,r.getGlsl)(e.session.backend.glContext.version),c=t.dims,u=c.length,l=t.dims.length,f=(0,i.getCoordsDataType)(l),d=(0,s.getChannels)("rc",l),h=(p=l,m=d,w=c[c.length-2],g=c[c.length-1],0===p||1===p?"":`\n int r = ${m[p-2]};\n int c = ${m[p-1]};\n int rp1 = ${m[p-2]} + 1;\n int cp1 = ${m[p-1]} + 1;\n bool rEdge = rp1 >= ${g};\n bool cEdge = cp1 >= ${w};\n `);var p,m,w,g;let v;v=0===u?[1,1]:1===u?[c[0],1]:[c[l-1],c[l-2]];const y=function(e,t,n){if(0===e)return"false";if(1===e)return`rc > ${t[0]}`;let r="";for(let o=e-2;o<e;o++)r+=`${n[o]} >= ${t[o-e+2]}`,o<e-1&&(r+="||");return r}(l,v,d),_=function(e,t){const n=e.length;if(0===n)return"getA(), 0, 0, 0";if(1===n)return`getA(rc),\n rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),\n 0, 0`;let r="";if(n>2)for(let e=0;e<n-2;++e)r+=`${t[e]},`;return`getA(${r}r, c),\n rEdge ? 0. : getA(${r}rp1, c),\n cEdge ? 0. : getA(${r}r, cp1),\n rEdge || cEdge ? 0. : getA(${r}rp1, cp1)`}(c,d),b=`\n void main() {\n ${f} rc = getOutputCoords();\n\n if(${y}) {\n ${n.output} = vec4(0);\n } else {\n ${h}\n\n ${n.output} = vec4(${_});\n }\n }\n `;return Object.assign(Object.assign({},a),{hasMain:true,output:{dims:t.dims,type:t.type,textureType:o.TextureType.packed},shaderSource:b})})(e,t)})},2827:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.unpackFromChannel=t.getChannels=t.getVecChannels=void 0;const r=n(9390);function o(e,t){return(0,r.getGlChannels)(t).map((t=>`${e}.${t}`))}t.getVecChannels=o,t.getChannels=function(e,t){return 1===t?[e]:o(e,t)},t.unpackFromChannel=function(){return"\n float getChannel(vec4 frag, int dim) {\n int modCoord = imod(dim, 2);\n return modCoord == 0 ? frag.r : frag.g;\n }\n\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n "}},2870:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parsePadAttributesV11=t.padV11=t.parsePadAttributesV2=t.padV2=void 0;const r=n(246),o=n(2517),i=n(5060),s=n(2039),a={name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};t.padV2=(e,t,n)=>(l(t),[e.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>u(e,t[0],n)}),t)]),t.parsePadAttributesV2=e=>{const t=e.attributes.getString("mode","constant"),n=e.attributes.getFloat("value",0),o=e.attributes.getInts("pads");return(0,r.createAttributeWithCacheKey)({mode:t,value:n,pads:o})},t.padV11=(e,n,r)=>{f(n);const o=c(e,n,r);return(0,t.padV2)(e,[n[0]],o)},t.parsePadAttributesV11=e=>e.attributes.getString("mode","constant");const c=(e,t,n)=>{if(!e.session.isInitializer(t[1].dataId)||t.length>=3&&!e.session.isInitializer(t[2].dataId))throw new Error("dynamic pad attributes are not allowed");const o=Array.from(t[1].integerData),i=t.length>=3?t[2].floatData[0]:0;return(0,r.createAttributeWithCacheKey)({mode:n,pads:o,value:i})},u=(e,t,n)=>{const r=o.ShapeUtil.padShape(t.dims.slice(),n.pads),i=r.length,a=`\n ${d(e,t,n)}\n float process(int[${i}] indices) {\n return padA(indices);\n }`;return{name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked],output:{dims:r,type:t.type,textureType:s.TextureType.unpacked},shaderSource:a}},l=e=>{if(!e||1!==e.length)throw new Error("Pad requires 1 input");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type.")},f=e=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Pad requires 2 or 3 inputs");if("int32"!==e[1].type)throw new Error("Invalid input type.");if(e.length>=3&&"string"===e[2].type)throw new Error("Invalid input type.")},d=(e,t,n)=>{const r=(0,i.getGlsl)(e.session.backend.glContext.version),[a,c]=e.calculateTextureWidthAndHeight(t.dims,s.TextureType.unpacked),u=o.ShapeUtil.computeStrides(t.dims);switch(n.mode){case"constant":return h(r,t.dims,u,a,c,n.pads,n.value);case"reflect":return p(r,t.dims,u,a,c,n.pads);case"edge":return m(r,t.dims,u,a,c,n.pads);default:throw new Error("Invalid mode")}},h=(e,t,n,r,o,i,s)=>{const a=t.length;let c="";for(let e=a-1;e>=0;--e)c+=`\n k = m[${e}] - ${i[e]};\n if (k < 0) return constant;\n if (k >= ${t[e]}) return constant;\n offset += k * ${n[e]};\n `;return`\n float padA(int m[${a}]) {\n const float constant = float(${s});\n int offset = 0;\n int k = 0;\n ${c}\n vec2 coords = offsetToCoords(offset, ${r}, ${o});\n float value = getColorAsFloat(${e.texture2D}(A, coords));\n return value;\n }\n `},p=(e,t,n,r,o,i)=>{const s=t.length;let a="";for(let e=s-1;e>=0;--e)a+=`\n k = m[${e}] - ${i[e]};\n if (k < 0) { k = -k; }\n {\n const int _2n_1 = ${2*(t[e]-1)};\n k = int( mod( float(k), float(_2n_1) ) ) ;\n if(k >= ${t[e]}) { k = _2n_1 - k; }\n }\n offset += k * ${n[e]};\n `;return`\n float padA(int m[${s}]) {\n int offset = 0;\n int k = 0;\n ${a}\n vec2 coords = offsetToCoords(offset, ${r}, ${o});\n float value = getColorAsFloat(${e.texture2D}(A, coords));\n return value;\n }\n `},m=(e,t,n,r,o,i)=>{const s=t.length;let a="";for(let e=s-1;e>=0;--e)a+=`\n k = m[${e}] - ${i[e]};\n if (k < 0) k = 0;\n if (k >= ${t[e]}) k = ${t[e]-1};\n offset += k * ${n[e]};\n `;return`\n float padA(int m[${s}]) {\n int offset = 0;\n int k = 0;\n ${a}\n vec2 coords = offsetToCoords(offset, ${r}, ${o});\n float value = getColorAsFloat(${e.texture2D}(A, coords));\n return value;\n }\n `}},2143:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.globalMaxPool=t.parseMaxPoolAttributes=t.maxPool=t.parseGlobalAveragePoolAttributes=t.globalAveragePool=t.parseAveragePoolAttributes=t.averagePool=void 0;const r=n(246),o=n(2517),i=n(2039);t.averagePool=(e,t,n)=>{f(t);const r={name:"AveragePool",inputNames:["X"],inputTypes:[i.TextureType.unpacked],cacheHint:n.cacheKey};return[e.run(Object.assign(Object.assign({},r),{get:()=>s(t,r,false,n)}),t)]},t.parseAveragePoolAttributes=e=>{const t=e.attributes.getString("auto_pad","NOTSET"),n=e.attributes.getInt("ceil_mode",0),o=0!==e.attributes.getInt("count_include_pad",0),i=e.attributes.getInts("kernel_shape"),s=e.attributes.getInts("strides",[]),a=e.attributes.getInts("pads",[]);if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,r.createAttributeWithCacheKey)({autoPad:t,ceilMode:n,countIncludePad:o,kernelShape:i,strides:s,pads:a})};const s=(e,t,n,r)=>{const[s,a]=c(e,r,n),u=o.ShapeUtil.size(s.kernelShape);let l="";s.countIncludePad?l+=`value /= float(${u});`:l+=`value /= float(${u} - pad);`;const f=`\n ${d(e[0].dims,s,"value += _X(x);",l,"0.0")}\n `;return Object.assign(Object.assign({},t),{output:{dims:a,type:e[0].type,textureType:i.TextureType.unpacked},shaderSource:f})};t.globalAveragePool=(e,t,n)=>{f(t);const r={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[i.TextureType.unpacked],cacheHint:`${n.countIncludePad}`};return[e.run(Object.assign(Object.assign({},r),{get:()=>s(t,r,true,n)}),t)]},t.parseGlobalAveragePoolAttributes=e=>{const t=0!==e.attributes.getInt("count_include_pad",0);return(0,r.createAttributeWithCacheKey)({autoPad:"",ceilMode:0,countIncludePad:t,kernelShape:[],strides:[],pads:[]})},t.maxPool=(e,t,n)=>{f(t);const r={name:"MaxPool",inputNames:["X"],inputTypes:[i.TextureType.unpacked],cacheHint:n.cacheKey};return[e.run(Object.assign(Object.assign({},r),{get:()=>a(t,r,false,n)}),t)]},t.parseMaxPoolAttributes=e=>{const t=e.attributes.getString("auto_pad","NOTSET"),n=e.attributes.getInt("ceil_mode",0),o=e.attributes.getInts("kernel_shape"),i=e.attributes.getInts("strides",[]),s=e.attributes.getInts("pads",[]),a=e.attributes.getInt("storage_order",0),c=e.attributes.getInts("dilations",[]);if(0!==a)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,r.createAttributeWithCacheKey)({autoPad:t,ceilMode:n,countIncludePad:false,kernelShape:o,strides:i,pads:s,storageOrder:a,dilations:c})};const a=(e,t,n,r)=>{const[o,s]=c(e,r,n),a=`\n ${d(e[0].dims,o,"\n value = max(_X(x), value);\n ","","-1e5")}\n `;return Object.assign(Object.assign({},t),{output:{dims:s,type:e[0].type,textureType:i.TextureType.unpacked},shaderSource:a})},c=(e,t,n)=>{const r=e[0].dims.slice(),i=Object.hasOwnProperty.call(t,"dilations"),s=t.kernelShape.slice(),a=t.strides.slice(),c=i?t.dilations.slice():[],u=t.pads.slice();o.PoolConvUtil.adjustPoolAttributes(n,r,s,a,c,u);const l=o.PoolConvUtil.computePoolOutputShape(n,r,a,c,s,u,t.autoPad),f=Object.assign({},t);return i?Object.assign(f,{kernelShape:s,strides:a,pads:u,dilations:c,cacheKey:t.cacheKey}):Object.assign(f,{kernelShape:s,strides:a,pads:u,cacheKey:t.cacheKey}),[f,l]},u={autoPad:"",ceilMode:0,countIncludePad:false,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},l={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[i.TextureType.unpacked]};t.globalMaxPool=(e,t)=>(f(t),[e.run(Object.assign(Object.assign({},l),{get:()=>a(t,l,true,u)}),t)]);const f=e=>{if(!e||1!==e.length)throw new Error("Pool ops requires 1 input.");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type.")},d=(e,t,n,r,i)=>{const s=e.length;if(t.kernelShape.length<=2){const o=t.kernelShape[t.kernelShape.length-1],a=t.strides[t.strides.length-1],c=t.pads[t.pads.length/2-1],u=t.pads[t.pads.length-1],l=e[s-1];let f="",d="",h="";if(f=c+u!==0?`\n for (int i = 0; i < ${o}; i++) {\n x[${s} - 1] = indices[${s} - 1] * ${a} - ${c} + i;\n if (x[${s} - 1] < 0 || x[${s} - 1] >= ${l}) {\n pad++;\n continue;\n }\n ${n}\n }`:`\n for (int i = 0; i < ${o}; i++) {\n x[${s} - 1] = indices[${s} - 1] * ${a} - ${c} + i;\n ${n}\n }`,2===t.kernelShape.length){const n=t.kernelShape[t.kernelShape.length-2],r=t.strides[t.strides.length-2],i=t.pads[t.pads.length/2-2],a=t.pads[t.pads.length-2],c=e[s-2];d=i+a!==0?`\n for (int j = 0; j < ${n}; j++) {\n x[${s} - 2] = indices[${s} - 2] * ${r} - ${i} + j;\n if (x[${s} - 2] < 0 || x[${s} - 2] >= ${c}) {\n pad+= ${o};\n continue;\n }\n `:`\n for (int j = 0; j < ${n}; j++) {\n x[${s} - 2] = indices[${s} - 2] * ${r} - ${i} + j;\n `,h="\n }\n "}return`\n float process(int indices[${s}]) {\n int x[${s}];\n copyVec(indices, x);\n\n float value = ${i};\n int pad = 0;\n ${d}\n ${f}\n ${h}\n ${r}\n return value;\n }\n `}{const a=o.ShapeUtil.size(t.kernelShape),c=o.ShapeUtil.computeStrides(t.kernelShape),u=c.length,l=t.pads.length,f=p(u),d=h(e,"inputDims"),m=h(t.pads,"pads"),w=h(c,"kernelStrides"),g=h(t.strides,"strides");let v="";return v=t.pads.reduce(((e,t)=>e+t))?`\n if (x[j] >= inputDims[j] || x[j] < 0) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n ${n}\n }`:`\n }\n ${n}\n `,`\n ${f}\n float process(int indices[${s}]) {\n int x[${s}];\n copyVec(indices, x);\n int offset[${u}];\n int pads[${l}];\n int inputDims[${s}];\n int kernelStrides[${u}];\n int strides[${u}];\n ${m}\n ${d}\n ${g}\n ${w}\n\n float value = ${i};\n int pad = 0;\n bool isPad = false;\n for (int i = 0; i < ${a}; i++) {\n offsetToIndices(i, kernelStrides, offset);\n isPad = false;\n for (int j = ${s} - ${u}; j < ${s}; j++) {\n x[j] = indices[j] * strides[j - ${s} + ${u}]\n + offset[j - ${s} + ${u}] - pads[j - 2];\n ${v}\n }\n ${r}\n\n return value;\n }\n `}},h=(e,t)=>{let n="";for(let r=0;r<e.length;r++)n+=`\n ${t}[${r}] = ${e[r]};\n `;return n},p=e=>`\n void offsetToIndices(int offset, int[${e}] strides, out int[${e}] indices) {\n if (${e} == 0) {\n return;\n }\n for (int i = 0; i < ${e} - 1; ++i) {\n indices[i] = offset / strides[i];\n offset -= indices[i] * strides[i];\n }\n indices[${e} - 1] = offset;\n }`},4939:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.reduceLogSumSquare=t.reduceLogSum=t.reduceProd=t.reduceMin=t.reduceMax=t.reduceMean=t.reduceSum=t.parseReduceAttributes=void 0;const r=n(246),o=n(782),i=n(2517),s=n(2039),a=(e,t,n,r,o)=>{u(t);const i={name:r,inputNames:["A"],inputTypes:[s.TextureType.unpacked]};return[e.run(Object.assign(Object.assign({},i),{cacheHint:n.cacheKey,get:()=>c(e,t,n,r,o,i)}),t)]};t.parseReduceAttributes=e=>{const t=e.attributes.getInts("axes",[]),n=1===e.attributes.getInt("keepdims",1);return(0,r.createAttributeWithCacheKey)({axes:t,keepDims:n})};const c=(e,t,n,r,o,a)=>{const c=[],u=t[0].dims.length||1,l=[],f=i.ShapeUtil.normalizeAxes(n.axes,t[0].dims.length),d=o(t,f);let h=d[1];for(let e=0;e<t[0].dims.length;e++)f.indexOf(e)>=0||0===f.length?(n.keepDims&&c.push(1),h=`\n for(int j${e} = 0; j${e} < ${t[0].dims[e]}; j${e}++) {\n inputIdx[${e}] = j${e};\n ${h}\n }`):(l.push(`inputIdx[${e}] = outputIdx[${c.length}];`),c.push(t[0].dims[e]));const p=`\n float process(int outputIdx[${c.length||1}]) {\n float value; // final result\n int inputIdx[${u}]; // addressing input data\n ${l.join("\n")}\n ${d[0]} // init ops for reduce max/min\n ${h}\n ${d[2]} // final computation for reduce mean\n return value;\n }`;return Object.assign(Object.assign({},a),{output:{dims:c,type:t[0].type,textureType:s.TextureType.unpacked},shaderSource:p})},u=e=>{if(!e||1!==e.length)throw new Error("Reduce op requires 1 input.");if(-1===o.NUMBER_TYPES.indexOf(e[0].type))throw new Error("Invalid input type.")};t.reduceSum=(e,t,n)=>a(e,t,n,"ReduceSum",(()=>["value = 0.0;","value += _A(inputIdx);",""])),t.reduceMean=(e,t,n)=>a(e,t,n,"ReduceMean",((e,t)=>{let n=1;for(let r=0;r<e[0].dims.length;r++)(t.indexOf(r)>=0||0===t.length)&&(n*=e[0].dims[r]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${n}.;`]})),t.reduceMax=(e,t,n)=>a(e,t,n,"ReduceMax",((e,t)=>{const n=[];for(let r=0;r<e[0].dims.length;r++)(t.indexOf(r)>=0||0===t.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]})),t.reduceMin=(e,t,n)=>a(e,t,n,"ReduceMin",((e,t)=>{const n=[];for(let r=0;r<e[0].dims.length;r++)(t.indexOf(r)>=0||0===t.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]})),t.reduceProd=(e,t,n)=>a(e,t,n,"ReduceProd",(()=>["value = 1.0;","value *= _A(inputIdx);",""])),t.reduceLogSum=(e,t,n)=>a(e,t,n,"ReduceLogSum",(()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"])),t.reduceLogSumSquare=(e,t,n)=>a(e,t,n,"ReduceLogSumSquare",(()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""]))},7019:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.isReshapeCheap=t.processDims3D=t.createPackedReshape3DProgramInfoLoader=void 0;const r=n(2517),o=n(5060),i=n(2039),s=n(2827);t.createPackedReshape3DProgramInfoLoader=(e,t,n)=>{const a=(e=>({name:"Reshape (packed)",inputTypes:[i.TextureType.packed],inputNames:["A"],cacheHint:`${e}`}))(n);return Object.assign(Object.assign({},a),{get:()=>((e,t,n,a)=>{const c=t.dims,u=a;let l="";for(let e=0;e<4;e++){let t="";switch(e){case 0:t="outputCoords = rc;";break;case 1:t="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:t="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:t="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}l+=`\n ${t}\n ${e>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""}\n int flattenedIndex = getFlattenedIndex(outputCoords);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex);\n vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${e}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims);\n\n ${e>0?"}":""}\n `}const f=(0,o.getGlsl)(e.session.backend.glContext.version),d=`\n ${function(e){const t=r.ShapeUtil.computeStrides(e),n=["b","r","c"],o="index";return`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${t.map(((e,r)=>`int ${n[r]} = ${o} / ${e}; ${r===t.length-1?`int ${n[r+1]} = ${o} - ${n[r]} * ${e}`:`index -= ${n[r]} * ${e}`};`)).join("")}\n return ivec3(b, r, c);\n }\n `}(c)}\n ${function(e){const t=r.ShapeUtil.computeStrides(e);return`\n int getFlattenedIndex(ivec3 coords) {\n // reverse y, z order\n return coords.x * ${t[0]} + coords.z * ${t[1]} + coords.y;\n }\n`}(u)}\n ${(0,s.unpackFromChannel)()}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.0);\n\n ivec3 outputCoords;\n int rows = ${u[2]};\n int cols = ${u[1]};\n\n ${l}\n ${f.output} = result;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:u,type:t.type,textureType:i.TextureType.packed},shaderSource:d,hasMain:true})})(e,t,a,n)})},t.processDims3D=function(e){if(0===e.length)return[1,1,1];let t=1;for(let n=0;n<e.length-2;++n)t*=e[n];return[t,e.length>1?e[e.length-2]:1,e[e.length-1]]},t.isReshapeCheap=function(e,t){let n=false;return n=0===e.length||0===t.length||(e.length<2||t.length<2?e[e.length-1]===t[t.length-1]:e[e.length-1]===t[t.length-1]&&e[e.length-2]===t[t.length-2]),n}},718:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.reshape=void 0;const r=n(2517);t.reshape=(e,t)=>{const n=r.ShapeUtil.calculateReshapedDims(t[0].dims,t[1].integerData);return e.session.pack?[e.reshapePacked(t[0],n)]:[e.reshapeUnpacked(t[0],n)]}},2268:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseResizeAttributesV11=t.parseResizeAttributesV10=t.resize=void 0;const r=n(5060),o=n(2039),i=n(9390),s=n(2827),a=n(9793),c={name:"Resize",inputNames:["A"],inputTypes:[o.TextureType.packed]};t.resize=(e,t,n)=>((0,a.validateInputs)(t,n),[e.run(Object.assign(Object.assign({},c),{cacheHint:n.cacheKey,get:()=>u(e,t,n)}),t)]),t.parseResizeAttributesV10=e=>(0,a.parseUpsampleAttributes)(e,10),t.parseResizeAttributesV11=e=>(0,a.parseUpsampleAttributes)(e,11);const u=(e,t,n)=>{const a=(0,r.getGlsl)(e.session.backend.glContext.version),[u,f]=l(t,n);if(u.every((e=>1===e))&&"tf_crop_and_resize"!==n.coordinateTransformMode)return Object.assign(Object.assign({},c),{output:{dims:f,type:t[0].type,textureType:o.TextureType.packed},hasMain:true,shaderSource:`void main() {\n vec4 v = ${a.texture2D}(X, TexCoords);\n ${a.output} = v;\n }`});const d=f.length;if(d<2)throw new Error(`output dimension should be at least 2, but got ${d}`);const h=f[d-2],p=f[d-1],m=t[0].dims;if(d!==m.length)throw new Error(`output dimension should match input ${m.length}, but got ${d}`);const w=m[d-2],g=m[d-1],v=u[d-2],y=u[d-1];let _="";if("linear"!==n.mode)throw new Error(`resize (packed) does not support mode: '${n.mode}'`);switch(n.coordinateTransformMode){case"asymmetric":_="\n vec4 getSourceFracIndex(ivec4 coords) {\n return vec4(coords) / scaleWHWH;\n }\n ";break;case"half_pixel":_="\n vec4 getSourceFracIndex(ivec4 coords) {\n return (vec4(coords) + 0.5) / scaleWHWH - 0.5;\n }\n ";break;case"pytorch_half_pixel":_=`\n vec4 getSourceFracIndex(ivec4 coords) {\n vec4 fcoords = vec4(coords);\n return vec4(\n ${p}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0,\n ${h}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0,\n ${p}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0,\n ${h}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0\n );\n }\n `;break;case"align_corners":_=`\n vec4 getSourceFracIndex(ivec4 coords) {\n vec4 resized = vec4(${p}.0 - 1.0, ${h}.0 - 1.0, ${p}.0 - 1.0,\n ${h}.0 - 1.0);\n vec4 original = vec4(${g}.0 - 1.0, ${w}.0 - 1.0, ${g}.0 - 1.0,\n ${w}.0 - 1.0);\n vec4 new_scale = original / resized;\n return vec4(coords) * new_scale;\n }\n `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${n.coordinateTransformMode}'`)}const b=(0,i.getCoordsDataType)(d),x=`\n const vec2 inputWH = vec2(${w}.0, ${g}.0);\n const vec4 scaleWHWH = vec4(float(${v}), float(${y}), float(${v}), float(${y}));\n ${(0,s.unpackFromChannel)()}\n ${_}\n float getAValue(int x10, int r, int c, int d) {\n return getChannel(getA(x10, r, c, d), vec2(c, d));\n }\n void main() {\n ${b} rc = getOutputCoords();\n\n int batch = rc[0];\n int depth = rc[1];\n\n // retrieve the 4 coordinates that is used in the 4 packed output values.\n ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1);\n\n // calculate the source index in fraction\n vec4 sourceFrac = getSourceFracIndex(coords);\n\n // get the lower and upper bound of the 4 values that will be packed into one texel.\n ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy)));\n ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw)));\n ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy)));\n ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw)));\n\n bool hasNextRow = rc.w < ${h-1};\n bool hasNextCol = rc.z < ${p-1};\n\n // pack x00, x01, x10, x11's top-left corner into one vec4 structure\n vec4 topLeft = vec4(\n getAValue(batch, depth, x00.x, x00.y),\n hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0);\n\n // pack x00, x01, x10, x11's top-right corner into one vec4 structure\n vec4 topRight = vec4(\n getAValue(batch, depth, x00.x, x00.w),\n hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0);\n\n // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure\n vec4 bottomLeft = vec4(\n getAValue(batch, depth, x00.z, x00.y),\n hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0);\n\n // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure\n vec4 bottomRight = vec4(\n getAValue(batch, depth, x00.z, x00.w),\n hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0);\n\n // calculate the interpolation fraction on u and v direction\n vec4 frac = vec4(sourceFrac) - floor(sourceFrac);\n vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0));\n\n vec4 top = mix(topLeft, topRight, clampFrac.ywyw);\n vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw);\n vec4 newValue = mix(top, bottom, clampFrac.xxzz);\n\n ${a.output} = vec4(newValue);\n }\n `;return Object.assign(Object.assign({},c),{output:{dims:f,type:t[0].type,textureType:o.TextureType.packed},hasMain:true,shaderSource:x})},l=(e,t)=>{const n=e[0].dims;let r,o=t.scales;if(0===o.length){const i=e[t.scalesInputIdx];if(i&&0!==i.size){if(e[t.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");o=f(i,t.mode,t.isResize)}else{const i=e[t.sizesInputIdx];if(!i||0===i.size)throw new Error("Either scales or sizes MUST be provided as input.");r=Array.from(i.integerData),o=d(r,n,t.mode,t.isResize)}}else if(e[t.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");const i=r||n.map(((e,t)=>Math.floor(e*o[t])));return[o,i]},f=(e,t,n)=>{const r=Array.from(e.floatData);return(0,a.scalesValidation)(r,t,n),r},d=(e,t,n,r)=>{const o=t.length,i=new Array(o);for(let n=0,r=o;n<r;n++)if(0===t[n]){if(0!==e[n])throw new Error("Input dim is zero but required output dim is non-zero.");i[n]=1}else i[n]=e[n]/t[n];return(0,a.scalesValidation)(i,n,r),i}},8117:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.shape=void 0;const r=n(9162);t.shape=(e,t)=>(o(t),[new r.Tensor([t[0].dims.length],"int32",void 0,void 0,new Int32Array(t[0].dims))]);const o=e=>{if(!e||1!==e.length)throw new Error("Shape requires 1 input.")}},2278:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.sliceV10=t.parseSliceAttributes=t.slice=void 0;const r=n(246),o=n(782),i=n(2517),s=n(2039),a={name:"Slice",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};t.slice=(e,t,n)=>(u(t),[e.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>c(e,t[0],n)}),t)]),t.parseSliceAttributes=e=>{const t=e.attributes.getInts("starts"),n=e.attributes.getInts("ends"),o=e.attributes.getInts("axes",[]);return(0,r.createAttributeWithCacheKey)({starts:t,ends:n,axes:o})};const c=(e,t,n)=>{const r=0===n.axes.length?t.dims.slice(0).map(((e,t)=>t)):n.axes,o=i.ShapeUtil.normalizeAxes(r,t.dims.length),c=n.starts.map(((e,n)=>e>t.dims[o[n]]-1?t.dims[o[n]]:i.ShapeUtil.normalizeAxis(e,t.dims[o[n]]))),u=n.ends.map(((e,n)=>e>t.dims[o[n]]-1?t.dims[o[n]]:i.ShapeUtil.normalizeAxis(e,t.dims[o[n]]))),l=t.dims.slice(),f=[];for(let e=0;e<o.length;e++)l[o[e]]=u[e]-c[e],c[e]>0&&f.push(`outputIdx[${o[e]}] += ${c[e]};`);const d=`\n float process(int outputIdx[${l.length}]) {\n ${f.join("\n ")}\n return _A(outputIdx);\n }`;return Object.assign(Object.assign({},a),{output:{dims:l,type:t.type,textureType:s.TextureType.unpacked},shaderSource:d})},u=e=>{if(!e||1!==e.length)throw new Error("Slice requires 1 input.");if(-1===o.NUMBER_TYPES.indexOf(e[0].type))throw new Error("Invalid input type.")};t.sliceV10=(e,t)=>{f(t);const n=l(e,t);return[e.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>c(e,t[0],n)}),[t[0]])]};const l=(e,t)=>{if(!e.session.isInitializer(t[1].dataId)||!e.session.isInitializer(t[2].dataId)||t.length>=4&&!e.session.isInitializer(t[3].dataId)||t.length>=5&&!e.session.isInitializer(t[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(t.length>=5&&t[4].integerData.some((e=>1!==e)))throw new Error("currently non-1 steps is not supported for Slice");const n=Array.from(t[1].integerData),r=Array.from(t[2].integerData),o=t.length>=4?Array.from(t[3].integerData):[];return{starts:n,ends:r,axes:o,cacheKey:`${o};${n};${r}`}},f=e=>{if(!e||e.length<3||e.length>5)throw new Error("Invalid input number.");if("int32"!==e[1].type||1!==e[1].dims.length)throw new Error("Invalid input type.");if("int32"!==e[2].type||1!==e[2].dims.length)throw new Error("Invalid input type.");if(e.length>=4&&("int32"!==e[3].type||1!==e[3].dims.length))throw new Error("Invalid input type.");if(e.length>=5&&("int32"!==e[4].type||1!==e[4].dims.length))throw new Error("Invalid input type.")}},5524:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.softmaxV13=t.parseSoftmaxAttributesV13=t.parseSoftmaxAttributes=t.softmax=void 0;const r=n(246),o=n(2517),i=n(5060),s=n(2039),a=n(3738),c={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[s.TextureType.unpacked]},u={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},l={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked,s.TextureType.unpacked]};t.softmax=(e,t,n)=>{m(t);const r=t[0].dims.slice(),i=o.ShapeUtil.normalizeAxis(n.axis,r.length),s=o.ShapeUtil.sizeToDimension(r,i),a=o.ShapeUtil.sizeFromDimension(r,i);return f(e,t,n,s,a)},t.parseSoftmaxAttributes=e=>(0,r.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis",1)}),t.parseSoftmaxAttributesV13=e=>(0,r.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis",-1)}),t.softmaxV13=(e,t,n)=>{m(t);const i=t[0].dims.slice(),s=o.ShapeUtil.normalizeAxis(n.axis,i.length),c=i.length,u=s!==c-1,l=[];let d,h=[],p=[];u&&(h=Array.from({length:c}).map(((e,t)=>t)),h[s]=c-1,h[c-1]=s,h.map((e=>l.push(i[e]))),d=(0,r.createAttributeWithCacheKey)({perm:h}),p=(0,a.transpose)(e,t,d));const w=u?o.ShapeUtil.sizeToDimension(l,c-1):o.ShapeUtil.sizeToDimension(i,c-1),g=u?o.ShapeUtil.sizeFromDimension(l,c-1):o.ShapeUtil.sizeFromDimension(i,c-1),v=f(e,u?p:t,n,w,g);return u?(0,a.transpose)(e,v,d):v};const f=(e,t,n,r,o)=>{const i=d(e,t[0],r,o,[r]),s=e.run(Object.assign(Object.assign({},c),{cacheHint:n.cacheKey,get:()=>i}),t),a=h(e,t[0],r,o,i.output.dims,[r]),f=e.run(Object.assign(Object.assign({},u),{cacheHint:n.cacheKey,get:()=>a}),[t[0],s]),m=p(e,t[0],r,o,i.output.dims,a.output.dims);return[e.run(Object.assign(Object.assign({},l),{cacheHint:n.cacheKey,get:()=>m}),[t[0],s,f])]},d=(e,t,n,r,o)=>{const[a,u]=e.calculateTextureWidthAndHeight(t.dims,s.TextureType.unpacked),l=o.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==o.length)throw new Error("Dimensionality of the output should be 1");if(o[0]!==n)throw new Error("Shape of the output should be equal to logical row count");const f=(0,i.getGlsl)(e.session.backend.glContext.version),d=`\n float process(int[${l}] indices) {\n int logical_row_start_offset = indices[0] * ${r};\n\n float max = getColorAsFloat(${f.texture2D}(A, offsetToCoords(logical_row_start_offset, ${a},\n ${u} )));\n for(int i=1; i<${r}; ++i)\n {\n float current = getColorAsFloat(${f.texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n ${a}, ${u})));\n if(current > max)\n max = current;\n }\n\n return max;\n }`;return Object.assign(Object.assign({},c),{output:{dims:o,type:t.type,textureType:s.TextureType.unpacked},shaderSource:d})},h=(e,t,n,r,o,a)=>{const[c,l]=e.calculateTextureWidthAndHeight(t.dims,s.TextureType.unpacked),f=a.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==a.length)throw new Error("Dimensionality of the output should be 1");if(a[0]!==n)throw new Error("Shape of the output should be equal to logical row count");if(1!==o.length)throw new Error("Dimensionality of the intermediate results should be 1");if(o[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const d=`\n float process(int[${f}] indices) {\n int logical_row_start_offset = indices[0] * ${r};\n\n float norm_factor = 0.0;\n float max = _Max(indices);\n for(int i=0; i<${r}; ++i)\n {\n norm_factor += exp(getColorAsFloat(${(0,i.getGlsl)(e.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n ${c}, ${l}))) - max);\n }\n\n return norm_factor;\n }`;return Object.assign(Object.assign({},u),{output:{dims:a,type:t.type,textureType:s.TextureType.unpacked},shaderSource:d})},p=(e,t,n,r,o,i)=>{const[a,c]=e.calculateTextureWidthAndHeight(t.dims,s.TextureType.unpacked),u=t.dims.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==o.length||1!==i.length)throw new Error("Dimensionality of the intermediate results should be 1");if(o[0]!==n||i[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const f=`\n float process(int[${u}] indices) {\n\n // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)\n int offset = coordsToOffset(TexCoords, ${a}, ${c});\n\n //determine the logical row for this index\n int logical_row_index[1];\n logical_row_index[0] = offset / ${r};\n\n float norm_factor = _Norm(logical_row_index);\n\n // avoid possible division by 0\n // if norm_facor is 0, all elements are zero\n // if so, return 0\n if(norm_factor == 0.0)\n return 0.0;\n\n return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;\n }`;return Object.assign(Object.assign({},l),{output:{dims:t.dims,type:t.type,textureType:s.TextureType.unpacked},shaderSource:f})},m=e=>{if(!e||1!==e.length)throw new Error("Softmax requires 1 input.");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type")}},5975:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseSplitAttributes=t.split=void 0;const r=n(246),o=n(2517),i=n(2039),s={name:"Split",inputNames:["A"],inputTypes:[i.TextureType.unpacked]};t.split=(e,t,n)=>{u(t);const r=o.ShapeUtil.normalizeAxis(n.axis,t[0].dims.length),i=a(e,t,r,n),l=[];for(let o=0;o<i;++o)l.push(e.run(Object.assign(Object.assign({},s),{cacheHint:`${n.cacheKey};${o}`,get:()=>c(e,t[0],n,r,o)}),t));return l},t.parseSplitAttributes=e=>{const t=e.attributes.getInt("axis",0),n=e.attributes.getInts("split",[]),o=e.outputs.length;return(0,r.createAttributeWithCacheKey)({axis:t,split:n,numOutputs:o})};const a=(e,t,n,r)=>{const[,i]=o.SplitUtil.splitShape(t[0].dims,n,r.split,r.numOutputs);return i.length},c=(e,t,n,r,a)=>{const[c,u]=o.SplitUtil.splitShape(t.dims,r,n.split,n.numOutputs),l=u[a],f=c[a],d=`\n float process(int indices[${f.length}]) {\n indices[${r}] += ${l};\n return _A(indices);\n }\n `;return Object.assign(Object.assign({},s),{cacheHint:`${n.cacheKey}:${a}`,output:{dims:f,type:t.type,textureType:i.TextureType.unpacked},shaderSource:d})},u=e=>{if(!e||1!==e.length)throw new Error("Split requires one input.");if("int8"!==e[0].type&&"uint8"!==e[0].type&&"int16"!==e[0].type&&"uint16"!==e[0].type&&"int32"!==e[0].type&&"uint32"!==e[0].type&&"float32"!==e[0].type&&"float64"!==e[0].type&&"bool"!==e[0].type)throw new Error("Invalid input type.")}},3933:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseSqueezeAttributes=t.squeezeV13=t.squeeze=void 0;const r=n(2517);t.squeeze=(e,t,n)=>{o(t);const i=r.ShapeUtil.squeezeShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],i)]},t.squeezeV13=(e,n)=>(i(n),(0,t.squeeze)(e,[n[0]],Array.from(n[1].integerData))),t.parseSqueezeAttributes=e=>e.attributes.getInts("axes");const o=e=>{if(!e||1!==e.length)throw new Error("Squeeze requires 1 input.");if("string"===e[0].type)throw new Error("invalid input tensor types.")},i=e=>{if(!e||2!==e.length)throw new Error("Squeeze requires 2 inputs.");if("int32"!==e[1].type)throw new Error("Invalid input type.")}},6558:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.sum=void 0;const r=n(5060),o=n(2039);t.sum=(e,t)=>{s(t);const n={name:"Sum",inputNames:t.map(((e,t)=>`X${t}`)),inputTypes:new Array(t.length).fill(o.TextureType.unpacked)};return[e.run(Object.assign(Object.assign({},n),{get:()=>i(e,t,n)}),t)]};const i=(e,t,n)=>{const i=(0,r.getGlsl)(e.session.backend.glContext.version),s=t[0].dims.slice(),a=`\n void main() {\n vec4 result = ${t.map(((e,t)=>`${i.texture2D}(X${t},TexCoords)`)).join(" + ")};\n ${i.output} = result;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:s,type:t[0].type,textureType:o.TextureType.unpacked},hasMain:true,shaderSource:a})},s=e=>{if(!e||0===e.length)throw new Error("Sum requires inputs.");const t=e[0].dims.length;for(let n=1;n<e.length;n++){if(t!==e[n].dims.length)throw new Error("Input shapes are mismatched.");for(let r=0;r<t;r++)if(e[0].dims[r]!==e[n].dims[r])throw new Error("Input shapes are not matched.")}if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("Invalid input type.");for(let t=1;t<e.length;t++)if(e[0].type!==e[t].type)throw new Error("Input types are not matched.")}},5723:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.tile=void 0;const r=n(782),o=n(2039);t.tile=(e,t)=>{s(t);const n={name:"Tile",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};return[e.run(Object.assign(Object.assign({},n),{get:()=>i(e,t,n)}),t)]};const i=(e,t,n)=>{const r=t[0].dims.slice(),i=new Array(r.length),s=[];for(let e=0;e<r.length;e++)i[e]=r[e]*t[1].numberData[e],s.push(`inputIdx[${e}] = int(mod(float(outputIdx[${e}]), ${r[e]}.));`);const a=i.length,c=`\n float process(int outputIdx[${a}]) {\n int inputIdx[${a}];\n ${s.join("\n")}\n return _A(inputIdx);\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:i,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:c})},s=e=>{if(!e||2!==e.length)throw new Error("Tile requires 2 input.");if(1!==e[1].dims.length)throw new Error("The second input shape must 1 dimension.");if(e[1].dims[0]!==e[0].dims.length)throw new Error("Invalid input shape.");if(-1===r.NUMBER_TYPES.indexOf(e[0].type))throw new Error("Invalid input type.");if("int32"!==e[1].type&&"int16"!==e[1].type)throw new Error("Invalid repeat type.")}},3738:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseTransposeAttributes=t.transpose=void 0;const r=n(246),o=n(2517),i=n(2039),s={name:"Transpose",inputNames:["A"],inputTypes:[i.TextureType.unpacked]};t.transpose=(e,t,n)=>(f(t),[e.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>a(e,t[0],n.perm)}),t)]),t.parseTransposeAttributes=e=>(0,r.createAttributeWithCacheKey)({perm:e.attributes.getInts("perm",[])});const a=(e,t,n)=>{const r=t.dims;n=c(r,n);const o=u(r,n),a=r.length,f=`\n ${l("perm",n,a)}\n float process(int indices[${a}]) {\n int a[${a}];\n perm(a, indices);\n return _A(a);\n }`;return Object.assign(Object.assign({},s),{output:{dims:o,type:t.type,textureType:i.TextureType.unpacked},shaderSource:f})},c=(e,t)=>(t&&t.length!==e.length&&(t=[...e.keys()].reverse()),t),u=(e,t)=>(t=c(e,t),o.ShapeUtil.sortBasedOnPerm(e,t)),l=(e,t,n)=>{const r=[];r.push(`void ${e}(out int a[${n}], int src[${n}]) {`);for(let e=0;e<n;++e)r.push(`\ta[${t[e]}]=src[${e}];`);return r.push("\t}"),r.join("\n")},f=e=>{if(!e||1!==e.length)throw new Error("Transpose requires 1 input.");if("float32"!==e[0].type&&"float64"!==e[0].type)throw new Error("input should be float tensor")}},8710:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.encodeAsUint8=void 0;const r=n(5060),o=n(2039);t.encodeAsUint8=(e,t)=>{const n=t.shape,i=(0,r.getGlsl)(e.session.backend.glContext.version),s=`\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n bool isNaN(float val) {\n return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n highp vec4 encodeAsUint8(highp float v) {\n if (isNaN(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n\n void main() {\n float value = ${i.texture2D}(X,TexCoords).r;\n ${i.output} = encodeAsUint8(value);\n }`,a={name:"Uint8Encode",inputTypes:[o.TextureType.unpacked],inputNames:["X"],output:{dims:n,type:t.tensor.type,textureType:o.TextureType.downloadUint8AsFloat},shaderSource:s,hasMain:true};return e.executeProgram(a,[t.tensor])}},4909:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.tanh=t.tan=t.sqrt=t.sin=t.sigmoid=t.relu=t.not=t.neg=t.log=t.parseLeakyReluAttributes=t.leakyRelu=t.identity=t.floor=t.exp=t.parseEluAttributes=t.elu=t.cos=t.ceil=t.clipV11=t.parseClipAttributes=t.clip=t.atan=t.asin=t.acos=t.abs=t.glslTanh=t.glslTan=t.glslSqrt=t.glslSigmoid=t.glslRelu=t.glslSin=t.glslNot=t.glslNeg=t.glslLog=t.glslLeakyRelu=t.glslIdentity=t.glslClip=t.glslFloor=t.glslExp=t.glslElu=t.glslCos=t.glslCeil=t.glslAtan=t.glslAsin=t.glslAcos=t.glslAbs=void 0;const r=n(246),o=n(2517),i=n(8520),s=n(5060),a=n(2039);function c(){return O("abs")}function u(){return O("acos")}function l(){return O("asin")}function f(){return O("atan")}function d(){return O("ceil")}function h(){return O("cos")}function p(e){const t="elu";return{body:`\n const float alpha = float(${e});\n\n float ${t}_(float a) {\n return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;\n }\n vec4 ${t}_(vec4 v) {\n return vec4(${t}_(v.x), ${t}_(v.y), ${t}_(v.z), ${t}_(v.w));\n }\n `,name:t,type:i.FunctionType.ValueBased}}function m(){return O("exp")}function w(){return O("floor")}function g(e,t){const n="clip";return{body:`\n const float min = float(${e});\n const float max = float(${t});\n\n float ${n}_(float a) {\n return clamp(a, min, max);\n }\n vec4 ${n}_(vec4 v) {\n return clamp(v, min, max);\n }\n `,name:n,type:i.FunctionType.ValueBased}}function v(){const e="indentity";return{body:`\n float ${e}_(float a) {\n return a;\n }\n vec4 ${e}_(vec4 v) {\n return v;\n }\n `,name:e,type:i.FunctionType.ValueBased}}function y(e){const t="leakyRelu";return{body:`\n const float alpha = float(${e});\n\n float ${t}_(float a) {\n return a < 0.0 ? a * alpha : a;\n }\n vec4 ${t}_(vec4 v) {\n return vec4(${t}_(v.x), ${t}_(v.y), ${t}_(v.z), ${t}_(v.w));\n }\n `,name:t,type:i.FunctionType.ValueBased}}function _(){return O("log")}function b(){const e="neg";return{body:`\n float ${e}_(float a) {\n return -a;\n }\n vec4 ${e}_(vec4 v) {\n return -v;\n }\n `,name:e,type:i.FunctionType.ValueBased}}function x(){const e="not";return{body:`\n float ${e}_(float a) {\n return float( ! bool(a) );\n }\n bool ${e}_(bool a) {\n return !a;\n }\n vec4 ${e}_(vec4 v) {\n return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));\n }\n bvec4 ${e}_(bvec4 v) {\n return bvec4(!v.x, !v.y, !v.z, !v.w);\n }\n `,name:e,type:i.FunctionType.ValueBased}}function T(){return O("sin")}function M(){const e="relu";return{body:`\n float ${e}_(float a) {\n return max( a, 0.0 );\n }\n vec4 ${e}_(vec4 v) {\n return max( v, 0.0 );\n }\n `,name:e,type:i.FunctionType.ValueBased}}function E(){const e="sigmoid";return{body:`\n float ${e}_(float a) {\n return 1.0 / (1.0 + exp(-a));\n }\n vec4 ${e}_(vec4 v) {\n return 1.0 / (1.0 + exp(-v));\n }\n `,name:e,type:i.FunctionType.ValueBased}}function S(){return O("sqrt")}function A(){return O("tan")}function $(){const e="tanh";return{body:`\n float ${e}_(float a) {\n a = clamp(a, -10., 10.);\n a = exp(2.*a);\n return (a - 1.) / (a + 1.);\n }\n vec4 ${e}_(vec4 v) {\n v = clamp(v, -10., 10.);\n v = exp(2.*v);\n return (v - 1.) / (v + 1.);\n }\n `,name:e,type:i.FunctionType.ValueBased}}function O(e){return{body:`\n float ${e}_(float a) {\n return ${e}(a);\n }\n vec4 ${e}_(vec4 v) {\n return ${e}(v);\n }\n `,name:e,type:i.FunctionType.ValueBased}}t.glslAbs=c,t.glslAcos=u,t.glslAsin=l,t.glslAtan=f,t.glslCeil=d,t.glslCos=h,t.glslElu=p,t.glslExp=m,t.glslFloor=w,t.glslClip=g,t.glslIdentity=v,t.glslLeakyRelu=y,t.glslLog=_,t.glslNeg=b,t.glslNot=x,t.glslSin=T,t.glslRelu=M,t.glslSigmoid=E,t.glslSqrt=S,t.glslTan=A,t.glslTanh=$;const P=(e,t,n,r)=>{const o=e.session.pack?a.TextureType.packed:a.TextureType.unpacked,i={name:n.name,inputTypes:[o],inputNames:["A"],cacheHint:r};return Object.assign(Object.assign({},i),{get:()=>((e,t,n,r)=>{const o=e.session.pack?a.TextureType.packed:a.TextureType.unpacked,i=(0,s.getGlsl)(e.session.backend.glContext.version);return Object.assign(Object.assign({},t),{output:{dims:n.dims,type:n.type,textureType:o},shaderSource:`\n ${r.body}\n void main() {\n vec4 v = ${i.texture2D}(A, TexCoords);\n v = ${r.name}_(v);\n ${i.output} = v;\n }\n `,hasMain:true})})(e,i,t,n)})};t.abs=(e,t)=>[e.run(P(e,t[0],c()),t)],t.acos=(e,t)=>[e.run(P(e,t[0],u()),t)],t.asin=(e,t)=>[e.run(P(e,t[0],l()),t)],t.atan=(e,t)=>[e.run(P(e,t[0],f()),t)],t.clip=(e,t,n)=>[e.run(P(e,t[0],g(n.min,n.max),n.cacheKey),t)],t.parseClipAttributes=e=>(0,r.createAttributeWithCacheKey)({min:e.attributes.getFloat("min",o.MIN_CLIP),max:e.attributes.getFloat("max",o.MAX_CLIP)}),t.clipV11=(e,n)=>{const r=C(e,n);return(0,t.clip)(e,[n[0]],r)};const C=(e,t)=>{if(t.length>=3&&(!e.session.isInitializer(t[1].dataId)||!e.session.isInitializer(t[2].dataId)))throw new Error("dynamic clip attributes are not allowed");const n=t.length>=3?t[1].numberData[0]:o.MIN_CLIP,i=t.length>=3?t[2].numberData[0]:o.MAX_CLIP;return(0,r.createAttributeWithCacheKey)({min:n,max:i})};t.ceil=(e,t)=>[e.run(P(e,t[0],d()),t)],t.cos=(e,t)=>[e.run(P(e,t[0],h()),t)],t.elu=(e,t,n)=>[e.run(P(e,t[0],p(n.alpha),n.cacheKey),t)],t.parseEluAttributes=e=>(0,r.createAttributeWithCacheKey)({alpha:e.attributes.getFloat("alpha",1)}),t.exp=(e,t)=>[e.run(P(e,t[0],m()),t)],t.floor=(e,t)=>[e.run(P(e,t[0],w()),t)],t.identity=(e,t)=>[e.run(P(e,t[0],v()),t)],t.leakyRelu=(e,t,n)=>[e.run(P(e,t[0],y(n.alpha),n.cacheKey),t)],t.parseLeakyReluAttributes=e=>(0,r.createAttributeWithCacheKey)({alpha:e.attributes.getFloat("alpha",.01)}),t.log=(e,t)=>[e.run(P(e,t[0],_()),t)],t.neg=(e,t)=>[e.run(P(e,t[0],b()),t)],t.not=(e,t)=>[e.run(P(e,t[0],x()),t)],t.relu=(e,t)=>[e.run(P(e,t[0],M()),t)],t.sigmoid=(e,t)=>[e.run(P(e,t[0],E()),t)],t.sin=(e,t)=>[e.run(P(e,t[0],T()),t)],t.sqrt=(e,t)=>[e.run(P(e,t[0],S()),t)],t.tan=(e,t)=>[e.run(P(e,t[0],A()),t)],t.tanh=(e,t)=>[e.run(P(e,t[0],$()),t)]},5611:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.createUnpackProgramInfoLoader=t.createUnpackProgramInfo=void 0;const r=n(5060),o=n(2039),i=n(9390),s=n(2827),a={name:"unpack",inputNames:["A"],inputTypes:[o.TextureType.packed]};t.createUnpackProgramInfo=(e,t)=>{const n=t.dims.length,c=(0,s.getChannels)("rc",n),u=c.slice(-2),l=(0,i.getCoordsDataType)(n),f=(0,s.unpackFromChannel)(),d=0===t.dims.length?"":function(e,t){if(1===e)return"rc";let n="";for(let r=0;r<e;r++)n+=t[r],r<e-1&&(n+=",");return n}(n,c),h=n<=1?"rc":`vec2(${u.join(",")})`,p=`\n ${f}\n void main() {\n ${l} rc = getOutputCoords();\n\n // Sample the texture with the coords to get the rgba channel value.\n vec4 packedInput = getA(${d});\n\n ${(0,r.getGlsl)(e.session.backend.glContext.version).output} = vec4(getChannel(packedInput, ${h}), 0, 0, 0);\n }\n `;return Object.assign(Object.assign({},a),{hasMain:true,output:{dims:t.dims,type:t.type,textureType:o.TextureType.unpacked},shaderSource:p})},t.createUnpackProgramInfoLoader=(e,n)=>Object.assign(Object.assign({},a),{get:()=>(0,t.createUnpackProgramInfo)(e,n)})},8428:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.parseUnsqueezeAttributes=t.unsqueezeV13=t.unsqueeze=void 0;const r=n(2517);t.unsqueeze=(e,t,n)=>{o(t);const i=r.ShapeUtil.unsqueezeShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],i)]},t.unsqueezeV13=(e,n)=>(i(n),(0,t.unsqueeze)(e,[n[0]],Array.from(n[1].integerData))),t.parseUnsqueezeAttributes=e=>e.attributes.getInts("axes");const o=e=>{if(!e||1!==e.length)throw new Error("Unsqueeze requires 1 input.");if("string"===e[0].type)throw new Error("invalid input tensor types.")},i=e=>{if(!e||2!==e.length)throw new Error("Unsqueeze requires 2 inputs.");if("int32"!==e[1].type)throw new Error("Invalid input type.")}},9793:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.scalesValidation=t.validateInputs=t.parseUpsampleAttributes=t.parseUpsampleAttributesV9=t.parseUpsampleAttributesV7=t.upsample=void 0;const r=n(246),o=n(5060),i=n(2039),s={name:"Upsample",inputNames:["X"],inputTypes:[i.TextureType.unpacked]};t.upsample=(e,n,r)=>((0,t.validateInputs)(n,r),[e.run(Object.assign(Object.assign({},s),{cacheHint:r.cacheKey,get:()=>a(e,n,r)}),n)]),t.parseUpsampleAttributesV7=e=>(0,t.parseUpsampleAttributes)(e,7),t.parseUpsampleAttributesV9=e=>(0,t.parseUpsampleAttributes)(e,9),t.parseUpsampleAttributes=(e,n)=>{const o=n>=10,i=e.attributes.getString("mode","nearest");if("nearest"!==i&&"linear"!==i&&(n<11||"cubic"!==i))throw new Error(`unrecognized mode: ${i}`);let s=[];n<9&&(s=e.attributes.getFloats("scales"),(0,t.scalesValidation)(s,i,o));const a=e.attributes.getFloat("extrapolation_value",0),c=n>10?e.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(-1===["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(c))throw new Error(`coordinate_transform_mode '${c}' is not supported`);const u="tf_crop_and_resize"===c,l=u,f="nearest"===i&&n>=11?e.attributes.getString("nearest_mode","round_prefer_floor"):"";if(-1===["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(f))throw new Error(`nearest_mode '${f}' is not supported`);const d=e.attributes.getFloat("cubic_coeff_a",-.75),h=0!==e.attributes.getInt("exclude_outside",0);if(h&&"cubic"!==i)throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");const p=n<11||"nearest"===i&&"asymmetric"===c&&"floor"===f;let m=0,w=0,g=0;return n>10?e.inputs.length>2?(m=1,w=2,g=3):(w=1,g=2):9===n&&(w=1),(0,r.createAttributeWithCacheKey)({opset:n,isResize:o,mode:i,scales:s,extrapolationValue:a,coordinateTransformMode:c,useExtrapolation:l,needRoiInput:u,nearestMode:f,cubicCoefficientA:d,excludeOutside:h,useNearest2xOptimization:p,roiInputIdx:m,scalesInputIdx:w,sizesInputIdx:g})};const a=(e,t,n)=>{const r=(0,o.getGlsl)(e.session.backend.glContext.version),[a,c]=e.calculateTextureWidthAndHeight(t[0].dims,i.TextureType.unpacked),u=t[0].dims.map(((e,t)=>Math.floor(e*n.scales[t]))),[l,f]=e.calculateTextureWidthAndHeight(u,i.TextureType.unpacked),d=u.length,h=new Array(d),p=new Array(d);let m=`\n int output_pitches[${d}];\n int input_pitches[${d}];\n `;for(let e=d-1;e>=0;e--)h[e]=e===d-1?1:h[e+1]*u[e+1],p[e]=e===d-1?1:p[e+1]*t[0].dims[e+1],m+=`\n output_pitches[${e}] = ${h[e]};\n input_pitches[${e}] = ${p[e]};\n `;const w=`\n float getInputFloat(int index) {\n vec2 coords = offsetToCoords(index, ${a}, ${c});\n float value = getColorAsFloat(${r.texture2D}(X, coords));\n return value;\n }\n `,g="nearest"===n.mode?`\n ${w}\n float process(int indices[${d}]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${l}, ${f});\n\n ${m}\n\n int d, m;\n for (int dim = 0; dim < ${d}; ++dim) {\n d = output_index / output_pitches[dim];\n m = output_index - d * output_pitches[dim];\n output_index = m;\n\n if (scales[dim] != 1 && d > 0) {\n int d2 = d / scales[dim];\n m = d - d2 * scales[dim];\n d = d2;\n }\n input_index += input_pitches[dim] * d;\n }\n\n return getInputFloat(input_index);\n }`:4===d?`\n ${w}\n float process(int indices[4]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${l}, ${f});\n\n ${m}\n\n int m;\n int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3;\n index_of_dim0 = output_index / output_pitches[0];\n m = output_index - index_of_dim0 * output_pitches[0];\n index_of_dim1 = m / output_pitches[1];\n m = m - index_of_dim1 * output_pitches[1];\n index_of_dim2 = m / output_pitches[2];\n m = m - index_of_dim2 * output_pitches[2];\n index_of_dim3 = m;\n\n int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset;\n index_of_input_dim2 = index_of_dim2 / scales[2];\n y_offset = index_of_dim2 - index_of_input_dim2 * scales[2];\n index_of_input_dim3 = index_of_dim3 / scales[3];\n x_offset = index_of_dim3 - index_of_input_dim3 * scales[3];\n\n input_index = index_of_dim0 * input_pitches[0] +\n index_of_dim1 * input_pitches[1] +\n index_of_input_dim2 * input_pitches[2] +\n index_of_input_dim3;\n\n float x00 = getInputFloat(input_index);\n float x10, x01, x11;\n\n bool end_of_dim2 = false;\n if (index_of_input_dim2 == (${t[0].dims[2]} - 1)) {\n // It's the end in dimension 2\n x01 = x00;\n end_of_dim2 = true;\n } else {\n x01 = getInputFloat(input_index + input_pitches[2]);\n }\n\n if (index_of_input_dim3 == (input_pitches[2] - 1)) {\n // It's the end in dimension 3\n x10 = x00;\n x11 = x01;\n }\n else {\n x10 = getInputFloat(input_index + 1);\n x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1);\n }\n\n float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]);\n float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]);\n return y0 + float(x_offset) * (y1 - y0) / float(scales[3]);\n }`:`\n ${w}\n float process(int indices[2]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${l}, ${f});\n\n ${m}\n\n int m;\n int index_of_dim0, index_of_dim1;\n index_of_dim0 = output_index / output_pitches[0];\n m = output_index - index_of_dim0 * output_pitches[0];\n index_of_dim1 = m;\n\n int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset;\n index_of_input_dim0 = index_of_dim0 / scales[0];\n y_offset = index_of_dim0 - index_of_input_dim0 * scales[0];\n index_of_input_dim1 = index_of_dim1 / scales[1];\n x_offset = index_of_dim1 - index_of_input_dim1 * scales[1];\n\n input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1;\n\n float x00 = getInputFloat(input_index);\n float x10, x01, x11;\n\n bool end_of_dim0 = false;\n if (index_of_input_dim0 == (${t[0].dims[0]} - 1)) {\n // It's the end in dimension 0\n x01 = x00;\n end_of_dim0 = true;\n } else {\n x01 = getInputFloat(input_index + input_pitches[0]);\n }\n\n if (index_of_input_dim1 == (input_pitches[0] - 1)) {\n // It's the end in dimension 1\n x10 = x00;\n x11 = x01;\n }\n else {\n x10 = getInputFloat(input_index + 1);\n x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);\n }\n\n float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);\n float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);\n return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);\n }`;return Object.assign(Object.assign({},s),{output:{dims:u,type:t[0].type,textureType:i.TextureType.unpacked},shaderSource:g,variables:[{name:"scales",type:"int",arrayLength:n.scales.length,data:n.scales.map((e=>Math.ceil(e)))}]})};t.validateInputs=(e,t)=>{if(!e||t.opset<9&&1!==e.length||t.opset>=9&&t.opset<11&&2!==e.length||t.opset>=11&&e.length<2)throw new Error("invalid inputs.");if(t.scales.length>0&&e[0].dims.length!==t.scales.length)throw new Error("Invalid input shape.");if("string"===e[0].type)throw new Error("Invalid input tensor types.")},t.scalesValidation=(e,t,n)=>{if(n){for(const t of e)if(t<=0)throw new Error("Scale value should be greater than 0.")}else for(const t of e)if(t<1)throw new Error("Scale value should be greater than or equal to 1.");if(!("linear"!==t&&"cubic"!==t||2===e.length||4===e.length&&1===e[0]&&1===e[1]))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${n?"Resize":"Upsample"} opeartor.`)}},1958:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.ProgramManager=void 0;const r=n(1670),o=n(6231),i=n(8879),s=n(5060);t.ProgramManager=class{constructor(e,t,n){this.profiler=e,this.glContext=t,this.textureLayoutStrategy=n,this.repo=new Map,this.attributesBound=false}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n){var r;this.profiler.event("op",`ProgramManager.run ${null!==(r=e.programInfo.name)&&void 0!==r?r:"unknown kernel"}`,(()=>{var r;const i=this.glContext.gl,s=e.program;i.useProgram(s);try{this.bindOutput(n),this.attributesBound||this.bindAttributes(e.attribLocations),this.bindUniforms(e.uniformLocations,null!==(r=e.programInfo.variables)&&void 0!==r?r:[],t)}catch(t){throw o.Logger.error("ProgramManager",e.programInfo.shaderSource),t}this.profiler.event("backend","GlContext.draw()",(()=>{this.glContext.draw()}))}),this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach((e=>this.glContext.deleteProgram(e.program)))}build(e,t,n){return this.profiler.event("backend","ProgramManager.build",(()=>{const r=new i.GlslPreprocessor(this.glContext,e,t,n),o=r.preprocess(),s=this.compile(o);return{programInfo:e,program:s,uniformLocations:this.getUniformLocations(s,r.context.programInfo.inputNames,r.context.programInfo.variables),attribLocations:this.getAttribLocations(s)}}))}compile(e){if(!this.vertexShader){o.Logger.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");const e=(0,s.getVertexShaderSource)(this.glContext.version);this.vertexShader=this.glContext.compileShader(e,this.glContext.gl.VERTEX_SHADER)}r.env.debug&&o.Logger.verbose("ProrgramManager",`FragShader:\n${e}\n`);const t=this.glContext.compileShader(e,this.glContext.gl.FRAGMENT_SHADER),n=this.glContext.createProgram(this.vertexShader,t);return this.glContext.deleteShader(t),n}bindOutput(e){const t=e.width,n=e.height;o.Logger.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${t}/${n}, shape=${e.shape}, type=${e.tensor.type}`),this.glContext.attachFramebuffer(e.texture,t,n)}bindAttributes(e){const t=e.position,n=e.textureCoord;this.glContext.setVertexAttributes(t,n),this.attributesBound=true}bindUniforms(e,t,n){var r;const o=this.glContext.gl;let i=0;for(const{name:s,type:a,location:c,arrayLength:u}of e){const e=null===(r=t.find((e=>e.name===s)))||void 0===r?void 0:r.data;if("sampler2D"!==a&&!e)throw new Error(`variable '${s}' does not have data defined in program info`);switch(a){case"sampler2D":this.bindTexture(n[i],c,i),i++;break;case"float":u?o.uniform1fv(c,e):o.uniform1f(c,e);break;case"int":u?o.uniform1iv(c,e):o.uniform1i(c,e);break;default:throw new Error(`Uniform not implemented: ${a}`)}}}bindTexture(e,t,n){this.glContext.bindTextureToUniform(e.texture,n,t)}getAttribLocations(e){return{position:this.getAttribLocation(e,"position"),textureCoord:this.getAttribLocation(e,"textureCoord")}}getUniformLocations(e,t,n){const r=[];if(t)for(const n of t)r.push({name:n,type:"sampler2D",location:this.getUniformLocation(e,n)});if(n)for(const t of n)r.push(Object.assign(Object.assign({},t),{location:this.getUniformLocation(e,t.name)}));return r}getUniformLocation(e,t){const n=this.glContext.gl.getUniformLocation(e,t);if(null===n)throw new Error(`Uniform ${t} not found.`);return n}getAttribLocation(e,t){return this.glContext.gl.getAttribLocation(e,t)}}},6416:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.WebGLSessionHandler=void 0;const r=n(6231),o=n(1047),i=n(8316),s=n(1640),a=n(1958),c=n(7859),u=n(5702);t.WebGLSessionHandler=class{constructor(e,t){this.backend=e,this.context=t,this.layoutStrategy=new c.PreferLogicalStrategy(e.glContext.maxTextureSize),this.programManager=new a.ProgramManager(this.context.profiler,e.glContext,this.layoutStrategy),this.textureManager=new u.TextureManager(e.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:"full"===e.textureCacheMode}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=e.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new i.WebGLInferenceHandler(this)}onGraphInitialized(e){const t=e.getValues().filter((e=>-1===e.from&&e.tensor)).map((e=>e.tensor.dataId));this.initializers=new Set(t)}isInitializer(e){return!!this.initializers&&this.initializers.has(e)}addInitializer(e){this.initializers.add(e)}getTextureData(e,t){return t?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,t,n=false){r.Logger.verbose("WebGLSessionHandler","Storing Texture data in cache"),n?this.packedTextureDataCache.set(e,t):this.unpackedTextureDataCache.set(e,t)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((e=>this.textureManager.releaseTexture(e,true))),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((e=>this.textureManager.releaseTexture(e,true))),this.unpackedTextureDataCache=new Map}resolve(e,t,n){const r=(0,o.resolveOperator)(e,t,s.WEBGL_OP_RESOLVE_RULES);return{impl:r.opImpl,context:r.opInit?r.opInit(e,n):e}}}},7769:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.Uint8DataEncoder=t.RGBAFloatDataEncoder=t.RedFloat32DataEncoder=void 0;const r=n(6231);t.RedFloat32DataEncoder=class{constructor(e,t=1){if(1===t)this.internalFormat=e.R32F,this.format=e.RED,this.textureType=e.FLOAT,this.channelSize=t;else{if(4!==t)throw new Error(`Invalid number of channels: ${t}`);this.internalFormat=e.RGBA32F,this.format=e.RGBA,this.textureType=e.FLOAT,this.channelSize=t}}encode(e,t){let n,o;return e.constructor!==Float32Array&&(r.Logger.warning("Encoder","data was not of type Float32; creating new Float32Array"),o=new Float32Array(e)),t*this.channelSize>e.length?(r.Logger.warning("Encoder","Source data too small. Allocating larger array"),o=e,n=this.allocate(t*this.channelSize),o.forEach(((e,t)=>n[t]=e))):(o=e,n=o),n}allocate(e){return new Float32Array(4*e)}decode(e,t){return 1===this.channelSize?e.filter(((e,t)=>t%4==0)).subarray(0,t):e.subarray(0,t)}},t.RGBAFloatDataEncoder=class{constructor(e,t=1,n){if(1!==t&&4!==t)throw new Error(`Invalid number of channels: ${t}`);this.internalFormat=e.RGBA,this.format=e.RGBA,this.channelSize=t,this.textureType=n||e.FLOAT}encode(e,t){let n=e;return 1===this.channelSize&&(r.Logger.verbose("Encoder","Exploding into a larger array"),n=this.allocate(t),e.forEach(((e,t)=>n[4*t]=e))),n}allocate(e){return new Float32Array(4*e)}decode(e,t){return 1===this.channelSize?e.filter(((e,t)=>t%4==0)).subarray(0,t):e.subarray(0,t)}},t.Uint8DataEncoder=class{constructor(e,t=1){if(this.channelSize=4,1===t)this.internalFormat=e.ALPHA,this.format=e.ALPHA,this.textureType=e.UNSIGNED_BYTE,this.channelSize=t;else{if(4!==t)throw new Error(`Invalid number of channels: ${t}`);this.internalFormat=e.RGBA,this.format=e.RGBA,this.textureType=e.UNSIGNED_BYTE,this.channelSize=t}}encode(e,t){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}allocate(e){return new Uint8Array(e*this.channelSize)}decode(e,t){if(e instanceof Uint8Array)return e.subarray(0,t);throw new Error(`Invalid array type: ${e.constructor}`)}}},7859:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.getBatchDim=t.sizeToSquarishShape=t.getRowsCols=t.sizeFromShape=t.isInt=t.parseAxisParam=t.squeezeShape=t.PreferLogicalStrategy=t.AlwaysKeepOriginalSizeStrategy=void 0;const r=n(6231),o=n(2517);function i(e,t){const n=[],r=[],o=null!=t&&Array.isArray(t)&&0===t.length,i=null==t||o?null:s(t,e).sort();let a=0;for(let t=0;t<e.length;++t){if(null!=i){if(i[a]===t&&1!==e[t])throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`);(null==i[a]||i[a]>t)&&1===e[t]&&(n.push(e[t]),r.push(t)),i[a]<=t&&a++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}function s(e,t){const n=t.length;return e=null==e?t.map(((e,t)=>t)):[].concat(e),(0,o.assert)(e.every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),(0,o.assert)(e.every(a),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function a(e){return e%1==0}function c(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function u(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}t.AlwaysKeepOriginalSizeStrategy=class{constructor(e){this.maxTextureSize=e}computeTextureWH(e,t){if(0===e.length)return[1,1];const n=this.maxTextureSize;if(t&&void 0!==t.breakAxis){const o=t.breakAxis>=e.length?1:e.slice(t.breakAxis).reduce(((e,t)=>e*t)),i=t.breakAxis<=0?1:e.slice(0,t.breakAxis).reduce(((e,t)=>e*t));if(!(o>n||i>n))return[o,i];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${e}, breakAxis:${t.breakAxis}`)}const o=e.reduce(((e,t)=>e*t));let i=Math.floor(Math.sqrt(o));for(;i<n&&i<o&&o%i!=0;i++);if(i>=n||o%i!=0)throw new Error(`The given dimensions are outside this GPU's boundaries: ${e}`);return[i,o/i]}},t.PreferLogicalStrategy=class{constructor(e){this.maxTextureSize=e}computeTextureWH(e,t){const n=this.computeTexture(e,t);return t&&t.isPacked&&(n[0]/=2,n[1]/=2),t&&t.reverseWH?[n[1],n[0]]:n}computeTexture(e,t){const n=t&&t.isPacked;if(0===e.length)return n?[2,2]:[1,1];let o=this.maxTextureSize;if(t&&void 0!==t.breakAxis){const n=t.breakAxis>=e.length?1:e.slice(t.breakAxis).reduce(((e,t)=>e*t)),i=t.breakAxis<=0?1:e.slice(0,t.breakAxis).reduce(((e,t)=>e*t));if(!(n>o||i>o))return[n,i];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${e}, breakAxis:${t.breakAxis}`)}let s=e.slice(0);if(n&&(o*=2,s=s.map(((e,t)=>t>=s.length-2?s[t]%2==0?s[t]:s[t]+1:s[t])),1===s.length&&(s=[2,s[0]])),2!==s.length){const e=i(s);s=e.newShape}const a=c(s);return s.length<=1&&a<=o?[1,a]:2===s.length&&s[0]<=o&&s[1]<=o?s:3===s.length&&s[0]*s[1]<=o&&s[2]<=o?[s[0]*s[1],s[2]]:3===s.length&&s[0]<=o&&s[1]*s[2]<=o?[s[0],s[1]*s[2]]:4===s.length&&s[0]*s[1]*s[2]<=o&&s[3]<=o?[s[0]*s[1]*s[2],s[3]]:4===s.length&&s[0]<=o&&s[1]*s[2]*s[3]<=o?[s[0],s[1]*s[2]*s[3]]:n?u(a/4).map((e=>2*e)):u(a)}},t.squeezeShape=i,t.parseAxisParam=s,t.isInt=a,t.sizeFromShape=c,t.getRowsCols=function(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]},t.sizeToSquarishShape=u,t.getBatchDim=function(e,t=2){return c(e.slice(0,e.length-t))}},4057:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.createTextureLayoutFromShape=t.calculateTextureWidthAndHeight=t.createTextureLayoutFromTextureType=void 0;const r=n(2517),o=n(2039);t.createTextureLayoutFromTextureType=(e,n,r)=>{const i=r===o.TextureType.unpacked||r===o.TextureType.unpackedReversed?1:4,s=r===o.TextureType.packed,a=r===o.TextureType.unpackedReversed||r===o.TextureType.packed,c=r===o.TextureType.packedLastDimension?n.length-1:void 0,u=r===o.TextureType.packedLastDimension?n.map(((e,t)=>t===n.length-1?4*e:e)):void 0;return(0,t.createTextureLayoutFromShape)(e,n,i,u,{isPacked:s,reverseWH:a,breakAxis:c})},t.calculateTextureWidthAndHeight=(e,n,r)=>{const o=(0,t.createTextureLayoutFromTextureType)(e,n,r);return[o.width,o.height]},t.createTextureLayoutFromShape=(e,t,n=1,o,i)=>{const s=!(!i||!i.isPacked),[a,c]=e.computeTextureWH(s&&o||t,i),u=t.length;let l=t.slice(0);if(0===u&&(l=[1]),1===n)o=t;else if(s){if(4!==n)throw new Error("a packed texture must be 4-channel");o=t,u>0&&(l[u-1]=Math.ceil(l[u-1]/2)),u>1&&(l[u-2]=Math.ceil(l[u-2]/2))}else if(!o)throw new Error("Unpacked shape is needed when using channels > 1");return{width:a,height:c,channels:n,isPacked:s,shape:l,strides:r.ShapeUtil.computeStrides(l),unpackedShape:o,reversedWH:i&&i.reverseWH}}},5702:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.TextureManager=void 0;const r=n(6231);t.TextureManager=class{constructor(e,t,n,r){this.glContext=e,this.layoutStrategy=t,this.profiler=n,this.config=r,this.pendingRead=new Map,r.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(e,t,n,o){const i=this.toEncoderType(e),s=this.glContext.getEncoder(i,t.channels||1,o);if(t.isPacked&&1===o)throw new Error("not implemented");const a=t.width,c=t.height;let u,l;if(this.config.reuseTextures){u=`${a}x${c}_${s.format}_${s.internalFormat}_${s.textureType}`,l=this.inUseTextures.get(u),l||(l=[],this.inUseTextures.set(u,l));const t=this.idleTextures.get(u);if(t&&t.length>0){const r=t.pop();return l.push(r),1===o&&this.glContext.updateTexture(r,a,c,s,this.toTextureData(e,n)),r}}r.Logger.verbose("TextureManager",`Creating new texture of size ${t.width}x${t.height}`);const f=this.glContext.allocateTexture(a,c,s,this.toTextureData(e,n));return this.config.reuseTextures&&(l.push(f),this.textureLookup.set(f,u)),f}readTexture(e,t,n){return n||(n=1),this.profiler.event("backend","TextureManager.readTexture",(()=>{const r=e.shape.reduce(((e,t)=>e*t))*n,o=this.glContext.readTexture(e.texture,e.width,e.height,r,this.toEncoderType(t),n);return this.toTensorData(t,o)}))}async readTextureAsync(e,t,n){const r=e.tensor.dataId;if(n||(n=1),this.pendingRead.has(r)){const e=this.pendingRead.get(r);return new Promise((t=>null==e?void 0:e.push(t)))}return this.profiler.event("backend","TextureManager.readTextureAsync",(async()=>{this.pendingRead.set(r,[]);const o=e.shape.reduce(((e,t)=>e*t))*n;await this.glContext.createAndWaitForFence();const i=this.glContext.readTexture(e.texture,e.width,e.height,o,this.toEncoderType(t),n),s=this.toTensorData(t,i),a=this.pendingRead.get(r);return this.pendingRead.delete(r),null==a||a.forEach((e=>e(s))),s}))}readUint8TextureAsFloat(e){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",(()=>{const t=e.shape.reduce(((e,t)=>e*t)),n=this.glContext.readTexture(e.texture,e.width,e.height,4*t,"byte",4);return new Float32Array(n.buffer,n.byteOffset,t)}))}releaseTexture(e,t){let n;if(this.config.reuseTextures&&(n=this.textureLookup.get(e.texture),n)){t&&this.textureLookup.delete(n);const r=this.inUseTextures.get(n);if(r){const t=r.indexOf(e.texture);if(-1!==t){r.splice(t,1);let o=this.idleTextures.get(n);o||(o=[],this.idleTextures.set(n,o)),o.push(e.texture)}}}n&&!t||(r.Logger.verbose("TextureManager",`Deleting texture of size ${e.width}x${e.height}`),this.glContext.deleteTexture(e.texture))}toTensorData(e,t){switch(e){case"int16":return t instanceof Int16Array?t:Int16Array.from(t);case"int32":return t instanceof Int32Array?t:Int32Array.from(t);case"int8":return t instanceof Int8Array?t:Int8Array.from(t);case"uint16":return t instanceof Uint16Array?t:Uint16Array.from(t);case"uint32":return t instanceof Uint32Array?t:Uint32Array.from(t);case"uint8":case"bool":return t instanceof Uint8Array?t:Uint8Array.from(t);case"float32":return t instanceof Float32Array?t:Float32Array.from(t);case"float64":return t instanceof Float64Array?t:Float64Array.from(t);default:throw new Error(`TensorData type ${e} is not supported`)}}toTextureData(e,t){if(t)return t instanceof Float32Array?t:new Float32Array(t)}toEncoderType(e){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}},2039:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:true}),t.TextureType=void 0,(n=t.TextureType||(t.TextureType={}))[n.unpacked=0]="unpacked",n[n.unpackedReversed=1]="unpackedReversed",n[n.packed=2]="packed",n[n.downloadUint8AsFloat=3]="downloadUint8AsFloat",n[n.packedLastDimension=4]="packedLastDimension"},9390:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.getGlChannels=t.getCoordsDataType=t.getSqueezedParams=t.squeezeInputShape=t.generateShaderFuncNameFromInputSamplerNameAtOutCoords=t.generateShaderFuncNameFromInputSamplerName=t.repeatedTry=t.getPackedShape=void 0;const r=n(2517);t.getPackedShape=function(e){const t=e.length;return e.slice(0,t-1).concat(e[t-1]/4)},t.repeatedTry=async function(e,t=e=>0,n){return new Promise(((r,o)=>{let i=0;const s=()=>{if(e())return void r();i++;const a=t(i);null!=n&&i>=n?o():setTimeout(s,a)};s()}))},t.generateShaderFuncNameFromInputSamplerName=function(e){return(0,r.assert)(void 0!==e&&0!==e.length,(()=>"empty string found for sampler name")),"get"+e.charAt(0).toUpperCase()+e.slice(1)},t.generateShaderFuncNameFromInputSamplerNameAtOutCoords=function(e){return(0,r.assert)(void 0!==e&&0!==e.length,(()=>"empty string found for sampler name")),"get"+e.charAt(0).toUpperCase()+e.slice(1)+"AtOutCoords"},t.squeezeInputShape=function(e,t){let n=JSON.parse(JSON.stringify(e));return n=t,n},t.getSqueezedParams=function(e,t){return t.map((t=>e[t])).join(", ")},t.getCoordsDataType=function(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)},t.getGlChannels=function(e=6){return["x","y","z","w","u","v"].slice(0,e)}},7305:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.createNewWebGLContext=t.createWebGLContext=void 0;const r=n(6231),o=n(1713),i={};function s(e){const t=function(){if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas)throw new TypeError("failed to create canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}const e=document.createElement("canvas");return e.width=1,e.height=1,e}();let n;const i={alpha:false,depth:false,antialias:false,stencil:false,preserveDrawingBuffer:false,premultipliedAlpha:false,failIfMajorPerformanceCaveat:false};if((!e||"webgl2"===e)&&(n=t.getContext("webgl2",i),n))try{return new o.WebGLContext(n,2)}catch(e){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${e}`)}if((!e||"webgl"===e)&&(n=t.getContext("webgl",i)||t.getContext("experimental-webgl",i),n))try{return new o.WebGLContext(n,1)}catch(e){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${e}`)}throw new Error("WebGL is not supported")}t.createWebGLContext=function e(t){let n;t&&"webgl2"!==t||!("webgl2"in i)?t&&"webgl"!==t||!("webgl"in i)||(n=i.webgl):n=i.webgl2,n=n||s(t),t=t||1===n.version?"webgl":"webgl2";const r=n.gl;return i[t]=n,r.isContextLost()?(delete i[t],e(t)):(r.disable(r.DEPTH_TEST),r.disable(r.STENCIL_TEST),r.disable(r.BLEND),r.disable(r.DITHER),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SAMPLE_COVERAGE),r.enable(r.SCISSOR_TEST),r.enable(r.CULL_FACE),r.cullFace(r.BACK),n)},t.createNewWebGLContext=s},1713:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:true,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return o(t,e),t};Object.defineProperty(t,"__esModule",{value:true}),t.WebGLContext=t.linearSearchLastTrue=void 0;const s=n(1670),a=i(n(7769)),c=n(9390);function u(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}t.linearSearchLastTrue=u,t.WebGLContext=class{constructor(e,t){this.frameBufferBound=false,this.itemsToPoll=[],this.gl=e,this.version=t,this.getExtensions(),this.vertexbuffer=this.createVertexbuffer(),this.framebuffer=this.createFramebuffer(),this.queryVitalParameters()}allocateTexture(e,t,n,r){const o=this.gl,i=o.createTexture();o.bindTexture(o.TEXTURE_2D,i),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE);const s=r?n.encode(r,e*t):null;return o.texImage2D(o.TEXTURE_2D,0,n.internalFormat,e,t,0,n.format,n.textureType,s),this.checkError(),i}updateTexture(e,t,n,r,o){const i=this.gl;i.bindTexture(i.TEXTURE_2D,e);const s=r.encode(o,t*n);i.texSubImage2D(i.TEXTURE_2D,0,0,0,t,n,r.format,r.textureType,s),this.checkError()}attachFramebuffer(e,t,n){const r=this.gl;r.bindTexture(r.TEXTURE_2D,e),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0),this.checkError(),r.viewport(0,0,t,n),r.scissor(0,0,t,n)}readTexture(e,t,n,r,o,i){const s=this.gl;i||(i=1),this.frameBufferBound||this.attachFramebuffer(e,t,n);const a=this.getEncoder(o,i),c=a.allocate(t*n);return s.bindTexture(s.TEXTURE_2D,e),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,e,0),s.readPixels(0,0,t,n,s.RGBA,a.textureType,c),this.checkError(),a.decode(c,r)}isFramebufferReady(){return true}getActiveTexture(){const e=this.gl;return"TEXTURE"+(e.getParameter(this.gl.ACTIVE_TEXTURE)-e.TEXTURE0)}getTextureBinding(){return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D)}getFramebufferBinding(){return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)}setVertexAttributes(e,t){const n=this.gl;n.vertexAttribPointer(e,3,n.FLOAT,false,20,0),n.enableVertexAttribArray(e),-1!==t&&(n.vertexAttribPointer(t,2,n.FLOAT,false,20,12),n.enableVertexAttribArray(t)),this.checkError()}createProgram(e,t){const n=this.gl,r=n.createProgram();return n.attachShader(r,e),n.attachShader(r,t),n.linkProgram(r),r}compileShader(e,t){const n=this.gl,r=n.createShader(t);if(!r)throw new Error(`createShader() returned null with type ${t}`);if(n.shaderSource(r,e),n.compileShader(r),false===n.getShaderParameter(r,n.COMPILE_STATUS))throw new Error(`Failed to compile shader: ${n.getShaderInfoLog(r)}\nShader source:\n${e}`);return r}deleteShader(e){this.gl.deleteShader(e)}bindTextureToUniform(e,t,n){const r=this.gl;r.activeTexture(r.TEXTURE0+t),this.checkError(),r.bindTexture(r.TEXTURE_2D,e),this.checkError(),r.uniform1i(n,t),this.checkError()}draw(){this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.checkError()}checkError(){if(s.env.debug){const e=this.gl,t=e.getError();let n="";switch(t){case e.NO_ERROR:return;case e.INVALID_ENUM:n="INVALID_ENUM";break;case e.INVALID_VALUE:n="INVALID_VALUE";break;case e.INVALID_OPERATION:n="INVALID_OPERATION";break;case e.INVALID_FRAMEBUFFER_OPERATION:n="INVALID_FRAMEBUFFER_OPERATION";break;case e.OUT_OF_MEMORY:n="OUT_OF_MEMORY";break;case e.CONTEXT_LOST_WEBGL:n="CONTEXT_LOST_WEBGL";break;default:n=`Unknown WebGL Error: ${t.toString(16)}`}throw new Error(n)}}deleteTexture(e){this.gl.deleteTexture(e)}deleteProgram(e){this.gl.deleteProgram(e)}getEncoder(e,t,n=0){if(2===this.version)return new a.RedFloat32DataEncoder(this.gl,t);switch(e){case"float":return 1===n||this.isRenderFloat32Supported?new a.RGBAFloatDataEncoder(this.gl,t):new a.RGBAFloatDataEncoder(this.gl,t,this.textureHalfFloatExtension.HALF_FLOAT_OES);case"int":throw new Error("not implemented");case"byte":return new a.Uint8DataEncoder(this.gl,t);default:throw new Error(`Invalid dataType: ${e}`)}}clearActiveTextures(){const e=this.gl;for(let t=0;t<this.maxTextureImageUnits;++t)e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,null)}dispose(){if(this.disposed)return;const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteFramebuffer(this.framebuffer),e.bindBuffer(e.ARRAY_BUFFER,null),e.deleteBuffer(this.vertexbuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),e.finish(),this.disposed=true}createDefaultGeometry(){return new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0])}createVertexbuffer(){const e=this.gl,t=e.createBuffer();if(!t)throw new Error("createBuffer() returned null");const n=this.createDefaultGeometry();return e.bindBuffer(e.ARRAY_BUFFER,t),e.bufferData(e.ARRAY_BUFFER,n,e.STATIC_DRAW),this.checkError(),t}createFramebuffer(){const e=this.gl.createFramebuffer();if(!e)throw new Error("createFramebuffer returned null");return e}queryVitalParameters(){const e=this.gl;if(this.isFloatTextureAttachableToFrameBuffer=this.checkFloatTextureAttachableToFrameBuffer(),this.isRenderFloat32Supported=this.checkRenderFloat32(),this.isFloat32DownloadSupported=this.checkFloat32Download(),1===this.version&&!this.textureHalfFloatExtension&&!this.isRenderFloat32Supported)throw new Error("both float32 and float16 TextureType are not supported");this.isBlendSupported=!this.isRenderFloat32Supported||this.checkFloat32Blend(),this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.maxTextureImageUnits=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}getExtensions(){2===this.version?(this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float"),this.disjointTimerQueryWebgl2Extension=this.gl.getExtension("EXT_disjoint_timer_query_webgl2")):(this.textureFloatExtension=this.gl.getExtension("OES_texture_float"),this.textureHalfFloatExtension=this.gl.getExtension("OES_texture_half_float"))}checkFloatTextureAttachableToFrameBuffer(){const e=this.gl,t=e.createTexture();e.bindTexture(e.TEXTURE_2D,t);const n=2===this.version?e.RGBA32F:e.RGBA;e.texImage2D(e.TEXTURE_2D,0,n,1,1,0,e.RGBA,e.FLOAT,null);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0);const o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(t),e.deleteFramebuffer(r),o}checkRenderFloat32(){if(2===this.version){if(!this.colorBufferFloatExtension)return false}else if(!this.textureFloatExtension)return false;return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Download(){if(2===this.version){if(!this.colorBufferFloatExtension)return false}else{if(!this.textureFloatExtension)return false;if(!this.gl.getExtension("WEBGL_color_buffer_float"))return false}return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Blend(){const e=this.gl;let t,n,r,o,i;try{t=e.createTexture(),n=e.createFramebuffer(),e.bindTexture(e.TEXTURE_2D,t);const s=2===this.version?e.RGBA32F:e.RGBA;return e.texImage2D(e.TEXTURE_2D,0,s,1,1,0,e.RGBA,e.FLOAT,null),e.bindFramebuffer(e.FRAMEBUFFER,n),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),e.enable(e.BLEND),r=e.createShader(e.VERTEX_SHADER),!!r&&(e.shaderSource(r,"void main(){}"),e.compileShader(r),o=e.createShader(e.FRAGMENT_SHADER),!!o&&(e.shaderSource(o,"precision highp float;void main(){gl_FragColor=vec4(0.5);}"),e.compileShader(o),i=e.createProgram(),!!i&&(e.attachShader(i,r),e.attachShader(i,o),e.linkProgram(i),e.useProgram(i),e.drawArrays(e.POINTS,0,1),e.getError()===e.NO_ERROR)))}finally{e.disable(e.BLEND),i&&e.deleteProgram(i),r&&e.deleteShader(r),o&&e.deleteShader(o),n&&(e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteFramebuffer(n)),t&&(e.bindTexture(e.TEXTURE_2D,null),e.deleteTexture(t))}}beginTimer(){if(2===this.version&&this.disjointTimerQueryWebgl2Extension){const e=this.gl,t=this.disjointTimerQueryWebgl2Extension,n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}throw new Error("WebGL1 profiling currently not supported.")}endTimer(){if(2!==this.version||!this.disjointTimerQueryWebgl2Extension)throw new Error("WebGL1 profiling currently not supported");{const e=this.gl,t=this.disjointTimerQueryWebgl2Extension;e.endQuery(t.TIME_ELAPSED_EXT)}}isTimerResultAvailable(e){let t=false,n=false;if(2!==this.version||!this.disjointTimerQueryWebgl2Extension)throw new Error("WebGL1 profiling currently not supported");{const r=this.gl,o=this.disjointTimerQueryWebgl2Extension;t=r.getQueryParameter(e,r.QUERY_RESULT_AVAILABLE),n=r.getParameter(o.GPU_DISJOINT_EXT)}return t&&!n}getTimerResult(e){let t=0;if(2!==this.version)throw new Error("WebGL1 profiling currently not supported");{const n=this.gl;t=n.getQueryParameter(e,n.QUERY_RESULT),n.deleteQuery(e)}return t/1e6}async waitForQueryAndGetTime(e){return await(0,c.repeatedTry)((()=>this.isTimerResultAvailable(e))),this.getTimerResult(e)}async createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t;const n=e,r=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),t=null===r?()=>true:()=>{const e=n.clientWaitSync(r,0,0);return e===n.ALREADY_SIGNALED||e===n.CONDITION_SATISFIED},{query:r,isFencePassed:t}}async pollFence(e){return new Promise((t=>{this.addItemToPoll((()=>e.isFencePassed()),(()=>t()))}))}pollItems(){const e=u(this.itemsToPoll.map((e=>e.isDoneFn)));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}async addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||await(0,c.repeatedTry)((()=>(this.pollItems(),0===this.itemsToPoll.length)))}}},1036:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.ExecutionPlan=void 0;const r=n(6231);class o{constructor(e,t){this.op=e,this.node=t}}t.ExecutionPlan=class{constructor(e,t,n){this.graph=e,this.profiler=n,this.initialize(t)}initialize(e){this.profiler.event("session","ExecutionPlan.initialize",(()=>{const t=this.graph.getNodes();if(t.length!==e.length)throw new Error("The size of nodes and OPs do not match.");this._ops=e.map(((e,n)=>new o(e,t[n]))),this.reset(),this._starter=[],this._ops.forEach(((e,t)=>{let n=true;for(const t of e.node.inputs)if(!this._values[t]&&-1===this.graph.getInputIndices().indexOf(t)){n=false;break}n&&this._starter.push(t)}))}))}reset(){this._values=this.graph.getValues().map((e=>e.tensor))}async execute(e,t){return this.profiler.event("session","ExecutionPlan.execute",(async()=>{this.reset();const n=e.createInferenceHandler(),o=this.graph.getInputIndices();if(t.length!==o.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${t.length} expected: ${o.length}`);t.forEach(((e,t)=>{const n=o[t];this._values[n]=e}));const i=this._starter.slice(0),s=this.graph.getValues(),a=this.graph.getNodes();let c=0;for(;c<i.length;){const e=i[c++],t=this._ops[e],o=t.node.inputs.map((e=>this._values[e]));if(-1!==o.indexOf(void 0))throw new Error(`unresolved input detected: op: ${t.node}`);const u=o;r.Logger.verbose("ExecPlan",`Runing op:${t.node.name} (${u.map(((e,n)=>`'${t.node.inputs[n]}': ${e.type}[${e.dims.join(",")}]`)).join(", ")})`);const l=await this.profiler.event("node",t.node.name,(async()=>t.op.impl(n,u,t.op.context)));if(l.length!==t.node.outputs.length)throw new Error("the size of output does not match model definition.");l.forEach(((e,n)=>{const r=t.node.outputs[n];if(this._values[r])throw new Error(`output [${r}] already has value: op:${t.node.name}`);this._values[r]=e}));const f=new Set;l.forEach(((e,n)=>{const r=t.node.outputs[n];for(const e of s[r].to){const t=a[e];let n=true;for(const e of t.inputs)if(!this._values[e]){n=false;break}n&&f.add(e)}})),i.push(...f)}const u=[];for(let e=0;e<this.graph.getOutputIndices().length;e++){const t=this.graph.getOutputIndices()[e],n=this._values[t];if(void 0===n)throw new Error(`required output [${t}] does not have value`);0===t?await n.getData():n.data,u.push(n)}return r.Logger.verbose("ExecPlan","disposing of inferenceHandler"),n.dispose(),u}))}}},7070:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.Graph=void 0;const r=n(1446),o=n(7778),i=n(9395),s=n(9162),a=n(2517);var c=i.onnxruntime.experimental.fbs;t.Graph={from:(e,t)=>new f(e,t)};class u{constructor(e){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,e&&(this.type=a.ProtoUtil.tensorValueTypeFromProto(e.type.tensorType))}get from(){return this._from}get to(){return this._to}}class l{constructor(e,t){e instanceof r.onnx.NodeProto?(this.name=e.name,this.opType=e.opType,this.attributes=new o.Attribute(e.attribute)):e instanceof c.Node&&(this.name=null!=t?t:e.name(),this.opType=e.opType(),this.attributes=new o.Attribute(a.ProtoUtil.tensorAttributesFromORTFormat(e))),this.inputs=[],this.outputs=[],this.executeNode=true}}class f{constructor(e,t){if(!e)throw new TypeError("graph is empty");this.buildGraph(e),this.transformGraph(t),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(e){if(e instanceof r.onnx.GraphProto)this.buildGraphFromOnnxFormat(e);else{if(!(e instanceof c.Graph))throw new TypeError("Graph type is not supported.");this.buildGraphFromOrtFormat(e)}}buildGraphFromOnnxFormat(e){const t=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const n=new Map;if(!e.input)throw new Error("missing information in graph: input");const r=[];for(const n of e.input){if(t.has(n.name))throw new Error(`duplicated input name: ${n.name}`);const e=this._allData.push(new u(n))-1;t.set(n.name,e),r.push(n.name)}if(!e.initializer)throw new Error("missing information in graph: initializer");for(const n of e.initializer){let e=t.get(n.name);if(void 0===e){const r=new u;r.type={shape:{dims:a.ProtoUtil.tensorDimsFromProto(n.dims)},tensorType:a.ProtoUtil.tensorDataTypeFromProto(n.dataType)},e=this._allData.push(r)-1,t.set(n.name,e)}this._allData[e]._from=-1,this._allData[e].tensor=s.Tensor.fromProto(n)}for(let e=0;e<this._allData.length;e++)this._allData[e].tensor||(this._allInputIndices.push(e),this._allInputNames.push(r[e]));if(!e.output)throw new Error("missing information in graph: output");for(const n of e.output){if(t.has(n.name))throw new Error(`duplicated output name: ${n.name}`);const e=this._allData.push(new u(n))-1;t.set(n.name,e),this._allOutputIndices.push(e),this._allOutputNames.push(n.name)}if(!e.node)throw new Error("missing information in graph: node");for(const t of e.node){if(!t.name)for(let e=0;;e++){const r=`unnamed_${t.opType}_${e}`;if(!n.has(r)){t.name=r;break}}if(n.has(t.name))throw new Error(`duplicated node name: ${t.name}`);const e=this._nodes.push(new l(t))-1;n.set(t.name,e)}for(let n=0;n<this._nodes.length;n++){const r=this._nodes[n],o=e.node[n];if(!o.output)throw new Error(`missing output for node: ${o.name}`);for(const e of o.output){let i=t.get(e);if(void 0===i&&(i=this._allData.push(new u)-1,t.set(e,i)),r.outputs.push(i),void 0!==this._allData[i]._from)throw new Error(`multiple nodes output to one data value: ${i}`);if(this._allData[i]._from=n,"Constant"===o.opType){if(!o.attribute||1!==o.attribute.length||!o.attribute[0].t)throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(!o.output||1!==o.output.length)throw new Error("missing output or incorrect number of outputs for this Constant operator");r.outputs.pop(),r.executeNode=false,this._allData[i]._from=-1,this._allData[i].tensor=s.Tensor.fromProto(o.attribute[0].t)}}}for(let n=0;n<this._nodes.length;n++){const r=this._nodes[n],o=e.node[n];if(!o.input)throw new Error(`missing input for node: ${o.name}`);for(const e of o.input){const i=t.get(e);if(void 0===i){if(""===e&&3===o.input.length&&"Resize"===o.opType)continue;throw new Error(`unrecognized input '${e}' for node: ${o.name}`)}r.inputs.push(i),this._allData[i]._to.push(n)}}return true}buildGraphFromOrtFormat(e){var t,n,r;const o=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const i=new Map,f=[];for(let i=0;i<e.inputsLength();i++){const s=e.inputs(i);if(o.has(s))throw new Error(`duplicated input name: ${s}`);for(let i=0;i<e.nodeArgsLength();i++)if((null===(t=e.nodeArgs(i))||void 0===t?void 0:t.name())===s){const t=new u;if((null===(r=null===(n=e.nodeArgs(i))||void 0===n?void 0:n.type())||void 0===r?void 0:r.valueType())!==c.TypeInfoValue.tensor_type)throw new Error("Unexpected value type for the nodeArg.");const l=e.nodeArgs(i).type().value(new c.TensorTypeAndShape),d=a.ProtoUtil.tensorDataTypeFromProto(l.elemType()),h=l.shape(),p=[];for(let e=0;e<h.dimLength();e++)p.push(a.LongUtil.longToNumber(h.dim(e).value().dimValue()));t.type={shape:{dims:p},tensorType:d};const m=this._allData.push(t)-1;o.set(s,m),f.push(s)}}for(let t=0;t<e.initializersLength();t++){const n=e.initializers(t);let r=o.get(n.name());if(void 0===r){const e=new u,t=a.ProtoUtil.tensorDimsFromORTFormat(n),i=a.ProtoUtil.tensorDataTypeFromProto(n.dataType());e.type={shape:{dims:t},tensorType:i},r=this._allData.push(e)-1,o.set(n.name(),r)}this._allData[r]._from=-1,this._allData[r].tensor=s.Tensor.fromOrtTensor(n)}for(let e=0;e<this._allData.length;e++)this._allData[e].tensor||(this._allInputIndices.push(e),this._allInputNames.push(f[e]));for(let t=0;t<e.outputsLength();t++){const n=e.outputs(t);if(o.has(n))throw new Error(`duplicated output name: ${n}`);const r=this._allData.push(new u)-1;o.set(n,r),this._allOutputIndices.push(r),this._allOutputNames.push(n)}if(!e.nodes)throw new Error("missing information in graph: node");for(let t=0;t<e.nodesLength();t++){const n=e.nodes(t);let r=n.name();if(!r)for(let e=0;r=`unnamed_${n.opType()}_${e}`,i.has(r);e++);if(i.has(r))throw new Error(`duplicated node name: ${r}`);const o=this._nodes.push(new l(n,r))-1;i.set(r,o)}for(let t=0;t<this._nodes.length;t++){const n=this._nodes[t],r=e.nodes(t);if(null==r)throw new Error(`No node exists at index ${t}`);if(0===(null==r?void 0:r.outputsLength()))throw new Error(`missing output for node: ${r.name}`);for(let e=0;e<(null==r?void 0:r.outputsLength());e++){const i=null==r?void 0:r.outputs(e);let a=o.get(i);if(void 0===a&&(a=this._allData.push(new u)-1,o.set(i,a)),n.outputs.push(a),void 0!==this._allData[a]._from)throw new Error(`multiple nodes output to one data value: ${a}`);if(this._allData[a]._from=t,"Constant"===r.opType()){if(1!==r.attributesLength()||!r.attributes(0).t())throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(1!==r.outputsLength())throw new Error("missing output or incorrect number of outputs for this Constant operator");n.outputs.pop(),n.executeNode=false,this._allData[a]._from=-1,this._allData[a].tensor=s.Tensor.fromOrtTensor(r.attributes(0).t())}}}for(let t=0;t<this._nodes.length;t++){const n=this._nodes[t],r=e.nodes(t);if(0===r.inputsLength())throw new Error(`missing input for node: ${r.name}`);for(let e=0;e<r.inputsLength();e++){const i=r.inputs(e),s=o.get(i);if(void 0===s)throw new Error(`unrecognized input '${i}' for node: ${r.name()}`);n.inputs.push(s),this._allData[s]._to.push(t)}}}checkIsAcyclic(){const e=new Set;this._allInputIndices.forEach((t=>{this._allData[t]._to.forEach((t=>{e.add(t)}))}));const t=Array.from(e),n=new Array(this._nodes.length).fill("white");for(;t.length>0;){const e=t.pop();"gray"===n[e]?n[e]="black":(t.push(e),n[e]="gray",this._nodes[e].outputs.forEach((r=>{const o=this._allData[r];if(void 0!==o.tensor)throw new Error("node outputs should not be initialized");if(o._from!==e)throw new Error("from property of the Value object doesn't match index of Node being processed");o._to.forEach((e=>{if("gray"===n[e])throw new Error("model graph is cyclic");"white"===n[e]&&t.push(e)}))})))}}transformGraph(e){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),e&&e.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let e=0;for(let t=0;t<this._nodes.length;t++)this._nodes[t].executeNode?e>0&&(this._nodes[t].inputs.forEach((n=>{const r=this._allData[n]._to.indexOf(t+e);-1!==r&&(this._allData[n]._to[r]=t)})),this._nodes[t].outputs.forEach((n=>{this._allData[n]._from&&this._allData[n]._from===t+e&&(this._allData[n]._from=t)}))):(e++,this._nodes[t].outputs.forEach((e=>{this._allData[e]._from=-2})),this._nodes.splice(t,1),t--);e=0;for(let t=0;t<this._allData.length;t++)if(-2!==this._allData[t].from||-1!==this._allOutputIndices.indexOf(t+e)){if(e>0){let n=-1;void 0!==this._allData[t].from&&-1!==this._allData[t].from?(n=this._nodes[this._allData[t].from].outputs.indexOf(t+e),-1!==n&&(this._nodes[this._allData[t].from].outputs[n]=t)):(n=this._allInputIndices.indexOf(t+e),-1!==n&&(this._allInputIndices[n]=t)),this._allData[t].to.forEach((r=>{n=this._nodes[r].inputs.indexOf(t+e),-1!==n&&(this._nodes[r].inputs[n]=t)})),0===this._allData[t].to.length&&(n=this._allOutputIndices.indexOf(t+e),-1!==n&&(this._allOutputIndices[n]=t))}}else e++,this._allData.splice(t,1),t--}deleteNode(e){const t=this._nodes[e];if(t.outputs.length>1)for(let e=1;e<t.outputs.length;e++)if(this._allData[t.outputs[e]].to.length>0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ");t.executeNode=false;const n=t.inputs[0],r=t.outputs[0],o=this._allData[r].to,i=this._allData[n].to.indexOf(e);if(-1===i)throw new Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[n].to.splice(i,1),this._allData[r]._to=[];const s=this._allOutputIndices.indexOf(r);if(-1!==s&&(this._allOutputIndices[s]=n),o&&o.length>0)for(const e of o){const t=this._nodes[e].inputs.indexOf(r);if(-1===t)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[e].inputs[t]=n,this._allData[n].to.push(e)}}removeAllDropoutNodes(){let e=0;for(const t of this._nodes){if("Dropout"===t.opType){if(1!==t.inputs.length)throw new Error("Dropout nodes should only contain one input. ");if(1!==t.outputs.length&&2!==t.outputs.length)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(2===t.outputs.length&&0!==this._allData[t.outputs[1]]._to.length)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(e)}e++}}removeAllIdentityNodes(){let e=0;for(const t of this._nodes)"Identity"===t.opType&&this.deleteNode(e),e++}isActivation(e){switch(e.opType){case"Relu":case"Sigmoid":case"Clip":return true;default:return false}}fuseConvActivationNodes(){for(const e of this._nodes)if("Conv"===e.opType){const t=this._allData[e.outputs[0]]._to;if(1===t.length&&this.isActivation(this._nodes[t[0]])){const n=this._nodes[t[0]];if("Clip"===n.opType)if(1===n.inputs.length)try{e.attributes.set("activation_params","floats",[n.attributes.getFloat("min"),n.attributes.getFloat("max")])}catch(t){e.attributes.set("activation_params","floats",[a.MIN_CLIP,a.MAX_CLIP])}else{if(!(n.inputs.length>=3&&void 0!==this._allData[n.inputs[1]].tensor&&void 0!==this._allData[n.inputs[2]].tensor))continue;e.attributes.set("activation_params","floats",[this._allData[n.inputs[1]].tensor.floatData[0],this._allData[n.inputs[2]].tensor.floatData[0]])}e.attributes.set("activation","string",n.opType),this.deleteNode(t[0])}}}}},6231:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true}),t.now=t.Profiler=t.Logger=void 0;const n={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},r={none:new class{log(e,t,n){}},console:new class{log(e,t,n){console.log(`${this.color(e)} ${n?"[35m"+n+"[0m ":""}${t}`)}color(e){switch(e){case"verbose":return"[34;40mv[0m";case"info":return"[32mi[0m";case"warning":return"[30;43mw[0m";case"error":return"[31;40me[0m";case"fatal":return"[101mf[0m";default:throw new Error(`unsupported severity: ${e}`)}}}},o={provider:"console",minimalSeverity:"warning",logDateTime:true,logSourceLocation:false};let i={"":o};function s(e,t,n,r){if(void 0===t)return o=e,{verbose:s.verbose.bind(null,o),info:s.info.bind(null,o),warning:s.warning.bind(null,o),error:s.error.bind(null,o),fatal:s.fatal.bind(null,o)};if(void 0===n)a(e,t);else if("number"==typeof n&&void 0===r)a(e,t);else if("string"==typeof n&&void 0===r)a(e,n,0,t);else{if("string"!=typeof n||"number"!=typeof r)throw new TypeError("input is valid");a(e,n,0,t)}var o}function a(e,t,o,s){const a=i[s||""]||i[""];n[e]<n[a.minimalSeverity]||(a.logDateTime&&(t=`${(new Date).toISOString()}|${t}`),r[a.provider].log(e,t,s))}!function(e){function t(e){i={},n("",e||{})}function n(e,n){if("*"===e)t(n);else{const t=i[e]||o;i[e]={provider:n.provider||t.provider,minimalSeverity:n.minimalSeverity||t.minimalSeverity,logDateTime:void 0===n.logDateTime?t.logDateTime:n.logDateTime,logSourceLocation:void 0===n.logSourceLocation?t.logSourceLocation:n.logSourceLocation}}}e.verbose=function(t,n){e("verbose",t,n)},e.info=function(t,n){e("info",t,n)},e.warning=function(t,n){e("warning",t,n)},e.error=function(t,n){e("error",t,n)},e.fatal=function(t,n){e("fatal",t,n)},e.reset=t,e.set=n,e.setWithEnv=function(e){const t={};e.logLevel&&(t.minimalSeverity=e.logLevel),n("",t)}}(s||(s={})),t.Logger=s;class c{constructor(e,t,n,r,o,i){this.category=e,this.name=t,this.startTime=n,this.endCallback=r,this.timer=o,this.ctx=i}end(){return this.endCallback(this)}async checkTimer(){if(void 0===this.ctx||void 0===this.timer)throw new Error("No webgl timer found");return this.ctx.endTimer(),this.ctx.waitForQueryAndGetTime(this.timer)}}class u{constructor(e,t,n,r){this.category=e,this.name=t,this.startTime=n,this.endTime=r}}t.Profiler=class{static create(e){return void 0===e?new this:new this(e.maxNumberEvents,e.flushBatchSize,e.flushIntervalInMilliseconds)}constructor(e,t,n){this._started=false,this._flushPointer=0,this._started=false,this._maxNumberEvents=void 0===e?1e4:e,this._flushBatchSize=void 0===t?10:t,this._flushIntervalInMilliseconds=void 0===n?5e3:n}start(){this._started=true,this._timingEvents=[],this._flushTime=(0,t.now)(),this._flushPointer=0}stop(){for(this._started=false;this._flushPointer<this._timingEvents.length;this._flushPointer++)this.logOneEvent(this._timingEvents[this._flushPointer])}event(e,t,n,r){const o=this._started?this.begin(e,t,r):void 0;let i=false;const s=n();if(s&&"function"==typeof s.then)return i=true,new Promise(((e,t)=>{s.then((async t=>{o&&await o.end(),e(t)}),(async e=>{o&&await o.end(),t(e)}))}));if(!i&&o){const e=o.end();if(e&&"function"==typeof e.then)return new Promise(((t,n)=>{e.then((()=>{t(s)}),(e=>{n(e)}))}))}return s}begin(e,n,r){if(!this._started)throw new Error("profiler is not started yet");if(void 0===r){const r=(0,t.now)();return this.flush(r),new c(e,n,r,(e=>this.endSync(e)))}{const t=r.beginTimer();return new c(e,n,0,(async e=>this.end(e)),t,r)}}async end(e){const t=await e.checkTimer();this._timingEvents.length<this._maxNumberEvents&&(this._timingEvents.push(new u(e.category,e.name,e.startTime,t)),this.flush(t))}endSync(e){const n=(0,t.now)();this._timingEvents.length<this._maxNumberEvents&&(this._timingEvents.push(new u(e.category,e.name,e.startTime,n)),this.flush(n))}logOneEvent(e){t.Logger.verbose(`Profiler.${e.category}`,`${(e.endTime-e.startTime).toFixed(2)}ms on event '${e.name}' at ${e.endTime.toFixed(2)}`)}flush(e){if(this._timingEvents.length-this._flushPointer>=this._flushBatchSize||e-this._flushTime>=this._flushIntervalInMilliseconds){for(const e=this._flushPointer;this._flushPointer<e+this._flushBatchSize&&this._flushPointer<this._timingEvents.length;this._flushPointer++)this.logOneEvent(this._timingEvents[this._flushPointer]);this._flushTime=(0,t.now)()}}get started(){return this._started}},t.now="undefined"!=typeof performance&&performance.now?()=>performance.now():Date.now},2644:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.Model=void 0;const r=n(5686),o=n(1446),i=n(7070),s=n(9395),a=n(2517);var c=s.onnxruntime.experimental.fbs;t.Model=class{constructor(){}load(e,t,n){if(!n)try{return void this.loadFromOnnxFormat(e,t)}catch(e){if(void 0!==n)throw e}this.loadFromOrtFormat(e,t)}loadFromOnnxFormat(e,t){const n=o.onnx.ModelProto.decode(e);if(a.LongUtil.longToNumber(n.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=n.opsetImport.map((e=>({domain:e.domain,version:a.LongUtil.longToNumber(e.version)}))),this._graph=i.Graph.from(n.graph,t)}loadFromOrtFormat(e,t){const n=new r.flatbuffers.ByteBuffer(e),o=c.InferenceSession.getRootAsInferenceSession(n).model();if(a.LongUtil.longToNumber(o.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let e=0;e<o.opsetImportLength();e++){const t=o.opsetImport(e);this._opsets.push({domain:null==t?void 0:t.domain(),version:a.LongUtil.longToNumber(t.version())})}this._graph=i.Graph.from(o.graph(),t)}get graph(){return this._graph}get opsets(){return this._opsets}}},782:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true}),t.FLOAT_TYPES=t.INT_TYPES=t.NUMBER_TYPES=void 0,t.NUMBER_TYPES=["float32","float64","int32","int16","int8","uint16","uint32","uint8"],t.INT_TYPES=["int32","int16","int8","uint16","uint32","uint8"],t.FLOAT_TYPES=["float32","float64"]},1047:(e,t)=>{function n(e,t){if(t.endsWith("+")){const n=Number.parseInt(t.substring(0,t.length-1),10);return!isNaN(n)&&n<=e}if(2===t.split("-").length){const n=t.split("-"),r=Number.parseInt(n[0],10),o=Number.parseInt(n[1],10);return!isNaN(r)&&!isNaN(o)&&r<=e&&e<=o}return Number.parseInt(t,10)===e}Object.defineProperty(t,"__esModule",{value:true}),t.resolveOperator=void 0,t.resolveOperator=function(e,t,r){for(const o of r){const r=o[0],i=o[1],s=o[2],a=o[3],c=o[4];if(e.opType===r)for(const e of t)if((e.domain===i||"ai.onnx"===e.domain&&""===i)&&n(e.version,s))return{opImpl:a,opInit:c}}throw new TypeError(`cannot resolve operator '${e.opType}' with opsets: ${t.map((e=>`${e.domain||"ai.onnx"} v${e.version}`)).join(", ")}`)}},9395:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.onnxruntime=void 0;const r=n(5686);var o,i;o=t.onnxruntime||(t.onnxruntime={}),function(e){!function(e){e[e.UNDEFINED=0]="UNDEFINED",e[e.FLOAT=1]="FLOAT",e[e.INT=2]="INT",e[e.STRING=3]="STRING",e[e.TENSOR=4]="TENSOR",e[e.GRAPH=5]="GRAPH",e[e.FLOATS=6]="FLOATS",e[e.INTS=7]="INTS",e[e.STRINGS=8]="STRINGS",e[e.TENSORS=9]="TENSORS",e[e.GRAPHS=10]="GRAPHS",e[e.SPARSE_TENSOR=11]="SPARSE_TENSOR",e[e.SPARSE_TENSORS=12]="SPARSE_TENSORS"}(e.AttributeType||(e.AttributeType={}))}((i=o.experimental||(o.experimental={})).fbs||(i.fbs={})),function(e){!function(e){!function(e){!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.VALUE=1]="VALUE",e[e.PARAM=2]="PARAM"}(e.DimensionValueType||(e.DimensionValueType={}))}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){!function(e){e[e.UNDEFINED=0]="UNDEFINED",e[e.FLOAT=1]="FLOAT",e[e.UINT8=2]="UINT8",e[e.INT8=3]="INT8",e[e.UINT16=4]="UINT16",e[e.INT16=5]="INT16",e[e.INT32=6]="INT32",e[e.INT64=7]="INT64",e[e.STRING=8]="STRING",e[e.BOOL=9]="BOOL",e[e.FLOAT16=10]="FLOAT16",e[e.DOUBLE=11]="DOUBLE",e[e.UINT32=12]="UINT32",e[e.UINT64=13]="UINT64",e[e.COMPLEX64=14]="COMPLEX64",e[e.COMPLEX128=15]="COMPLEX128",e[e.BFLOAT16=16]="BFLOAT16"}(e.TensorDataType||(e.TensorDataType={}))}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){!function(e){e[e.Primitive=0]="Primitive",e[e.Fused=1]="Fused"}(e.NodeType||(e.NodeType={}))}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){!function(e){e[e.NONE=0]="NONE",e[e.tensor_type=1]="tensor_type",e[e.sequence_type=2]="sequence_type",e[e.map_type=3]="map_type"}(e.TypeInfoValue||(e.TypeInfoValue={}))}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsShape(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsShape(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}dim(t,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new e.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}dimLength(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__vector_len(this.bb_pos+e):0}static startShape(e){e.startObject(1)}static addDim(e,t){e.addFieldOffset(0,t,0)}static createDimVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startDimVector(e,t){e.startVector(4,t,4)}static endShape(e){return e.endObject()}static createShape(e,t){return n.startShape(e),n.addDim(e,t),n.endShape(e)}}t.Shape=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDimension(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsDimension(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}value(t){let n=this.bb.__offset(this.bb_pos,4);return n?(t||new e.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}denotation(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}static startDimension(e){e.startObject(2)}static addValue(e,t){e.addFieldOffset(0,t,0)}static addDenotation(e,t){e.addFieldOffset(1,t,0)}static endDimension(e){return e.endObject()}static createDimension(e,t,r){return n.startDimension(e),n.addValue(e,t),n.addDenotation(e,r),n.endDimension(e)}}t.Dimension=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsDimensionValue(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsDimensionValue(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}dimType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt8(this.bb_pos+t):e.experimental.fbs.DimensionValueType.UNKNOWN}dimValue(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}dimParam(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}static startDimensionValue(e){e.startObject(3)}static addDimType(t,n){t.addFieldInt8(0,n,e.experimental.fbs.DimensionValueType.UNKNOWN)}static addDimValue(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addDimParam(e,t){e.addFieldOffset(2,t,0)}static endDimensionValue(e){return e.endObject()}static createDimensionValue(e,t,r,o){return n.startDimensionValue(e),n.addDimType(e,t),n.addDimValue(e,r),n.addDimParam(e,o),n.endDimensionValue(e)}}t.DimensionValue=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsTensorTypeAndShape(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsTensorTypeAndShape(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}elemType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.TensorDataType.UNDEFINED}shape(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startTensorTypeAndShape(e){e.startObject(2)}static addElemType(t,n){t.addFieldInt32(0,n,e.experimental.fbs.TensorDataType.UNDEFINED)}static addShape(e,t){e.addFieldOffset(1,t,0)}static endTensorTypeAndShape(e){return e.endObject()}static createTensorTypeAndShape(e,t,r){return n.startTensorTypeAndShape(e),n.addElemType(e,t),n.addShape(e,r),n.endTensorTypeAndShape(e)}}t.TensorTypeAndShape=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsMapType(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsMapType(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}keyType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.TensorDataType.UNDEFINED}valueType(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startMapType(e){e.startObject(2)}static addKeyType(t,n){t.addFieldInt32(0,n,e.experimental.fbs.TensorDataType.UNDEFINED)}static addValueType(e,t){e.addFieldOffset(1,t,0)}static endMapType(e){return e.endObject()}static createMapType(e,t,r){return n.startMapType(e),n.addKeyType(e,t),n.addValueType(e,r),n.endMapType(e)}}t.MapType=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSequenceType(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSequenceType(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}elemType(t){let n=this.bb.__offset(this.bb_pos,4);return n?(t||new e.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startSequenceType(e){e.startObject(1)}static addElemType(e,t){e.addFieldOffset(0,t,0)}static endSequenceType(e){return e.endObject()}static createSequenceType(e,t){return n.startSequenceType(e),n.addElemType(e,t),n.endSequenceType(e)}}t.SequenceType=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){(e.fbs||(e.fbs={})).EdgeEnd=class{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static createEdgeEnd(e,t,n,r){return e.prep(4,12),e.writeInt32(r),e.writeInt32(n),e.writeInt32(t),e.offset()}}}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsNodeEdge(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsNodeEdge(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}nodeIndex(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readUint32(this.bb_pos+e):0}inputEdges(t,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new e.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*t,this.bb):null}inputEdgesLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}outputEdges(t,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new e.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*t,this.bb):null}outputEdgesLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}static startNodeEdge(e){e.startObject(3)}static addNodeIndex(e,t){e.addFieldInt32(0,t,0)}static addInputEdges(e,t){e.addFieldOffset(1,t,0)}static startInputEdgesVector(e,t){e.startVector(12,t,4)}static addOutputEdges(e,t){e.addFieldOffset(2,t,0)}static startOutputEdgesVector(e,t){e.startVector(12,t,4)}static endNodeEdge(e){return e.endObject()}static createNodeEdge(e,t,r,o){return n.startNodeEdge(e),n.addNodeIndex(e,t),n.addInputEdges(e,r),n.addOutputEdges(e,o),n.endNodeEdge(e)}}t.NodeEdge=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsNode(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsNode(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}docString(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}domain(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}sinceVersion(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt32(this.bb_pos+e):0}index(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readUint32(this.bb_pos+e):0}opType(e){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__string(this.bb_pos+t,e):null}type(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.NodeType.Primitive}executionProviderType(e){let t=this.bb.__offset(this.bb_pos,18);return t?this.bb.__string(this.bb_pos+t,e):null}inputs(e,t){let n=this.bb.__offset(this.bb_pos,20);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}inputsLength(){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__vector_len(this.bb_pos+e):0}outputs(e,t){let n=this.bb.__offset(this.bb_pos,22);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}outputsLength(){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.__vector_len(this.bb_pos+e):0}attributes(t,n){let r=this.bb.__offset(this.bb_pos,24);return r?(n||new e.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}attributesLength(){let e=this.bb.__offset(this.bb_pos,24);return e?this.bb.__vector_len(this.bb_pos+e):0}inputArgCounts(e){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.readInt32(this.bb.__vector(this.bb_pos+t)+4*e):0}inputArgCountsLength(){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.__vector_len(this.bb_pos+e):0}inputArgCountsArray(){let e=this.bb.__offset(this.bb_pos,26);return e?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}implicitInputs(e,t){let n=this.bb.__offset(this.bb_pos,28);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}implicitInputsLength(){let e=this.bb.__offset(this.bb_pos,28);return e?this.bb.__vector_len(this.bb_pos+e):0}static startNode(e){e.startObject(13)}static addName(e,t){e.addFieldOffset(0,t,0)}static addDocString(e,t){e.addFieldOffset(1,t,0)}static addDomain(e,t){e.addFieldOffset(2,t,0)}static addSinceVersion(e,t){e.addFieldInt32(3,t,0)}static addIndex(e,t){e.addFieldInt32(4,t,0)}static addOpType(e,t){e.addFieldOffset(5,t,0)}static addType(t,n){t.addFieldInt32(6,n,e.experimental.fbs.NodeType.Primitive)}static addExecutionProviderType(e,t){e.addFieldOffset(7,t,0)}static addInputs(e,t){e.addFieldOffset(8,t,0)}static createInputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startInputsVector(e,t){e.startVector(4,t,4)}static addOutputs(e,t){e.addFieldOffset(9,t,0)}static createOutputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startOutputsVector(e,t){e.startVector(4,t,4)}static addAttributes(e,t){e.addFieldOffset(10,t,0)}static createAttributesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startAttributesVector(e,t){e.startVector(4,t,4)}static addInputArgCounts(e,t){e.addFieldOffset(11,t,0)}static createInputArgCountsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addInt32(t[n]);return e.endVector()}static startInputArgCountsVector(e,t){e.startVector(4,t,4)}static addImplicitInputs(e,t){e.addFieldOffset(12,t,0)}static createImplicitInputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startImplicitInputsVector(e,t){e.startVector(4,t,4)}static endNode(e){return e.endObject()}static createNode(e,t,r,o,i,s,a,c,u,l,f,d,h,p){return n.startNode(e),n.addName(e,t),n.addDocString(e,r),n.addDomain(e,o),n.addSinceVersion(e,i),n.addIndex(e,s),n.addOpType(e,a),n.addType(e,c),n.addExecutionProviderType(e,u),n.addInputs(e,l),n.addOutputs(e,f),n.addAttributes(e,d),n.addInputArgCounts(e,h),n.addImplicitInputs(e,p),n.endNode(e)}}t.Node=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsValueInfo(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsValueInfo(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}docString(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}type(t){let n=this.bb.__offset(this.bb_pos,8);return n?(t||new e.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startValueInfo(e){e.startObject(3)}static addName(e,t){e.addFieldOffset(0,t,0)}static addDocString(e,t){e.addFieldOffset(1,t,0)}static addType(e,t){e.addFieldOffset(2,t,0)}static endValueInfo(e){return e.endObject()}static createValueInfo(e,t,r,o){return n.startValueInfo(e),n.addName(e,t),n.addDocString(e,r),n.addType(e,o),n.endValueInfo(e)}}t.ValueInfo=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsTypeInfo(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsTypeInfo(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}denotation(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}valueType(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):e.experimental.fbs.TypeInfoValue.NONE}value(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__union(e,this.bb_pos+t):null}static startTypeInfo(e){e.startObject(3)}static addDenotation(e,t){e.addFieldOffset(0,t,0)}static addValueType(t,n){t.addFieldInt8(1,n,e.experimental.fbs.TypeInfoValue.NONE)}static addValue(e,t){e.addFieldOffset(2,t,0)}static endTypeInfo(e){return e.endObject()}static createTypeInfo(e,t,r,o){return n.startTypeInfo(e),n.addDenotation(e,t),n.addValueType(e,r),n.addValue(e,o),n.endTypeInfo(e)}}t.TypeInfo=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){class t{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsOperatorSetId(e,n){return(n||new t).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsOperatorSetId(e,n){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new t).__init(e.readInt32(e.position())+e.position(),e)}domain(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}version(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}static startOperatorSetId(e){e.startObject(2)}static addDomain(e,t){e.addFieldOffset(0,t,0)}static addVersion(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static endOperatorSetId(e){return e.endObject()}static createOperatorSetId(e,n,r){return t.startOperatorSetId(e),t.addDomain(e,n),t.addVersion(e,r),t.endOperatorSetId(e)}}e.OperatorSetId=t}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsTensor(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsTensor(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}docString(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dims(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+8*e):this.bb.createLong(0,0)}dimsLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}dataType(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.TensorDataType.UNDEFINED}rawData(e){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readUint8(this.bb.__vector(this.bb_pos+t)+e):0}rawDataLength(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}rawDataArray(){let e=this.bb.__offset(this.bb_pos,12);return e?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}stringData(e,t){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}stringDataLength(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__vector_len(this.bb_pos+e):0}static startTensor(e){e.startObject(6)}static addName(e,t){e.addFieldOffset(0,t,0)}static addDocString(e,t){e.addFieldOffset(1,t,0)}static addDims(e,t){e.addFieldOffset(2,t,0)}static createDimsVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startDimsVector(e,t){e.startVector(8,t,8)}static addDataType(t,n){t.addFieldInt32(3,n,e.experimental.fbs.TensorDataType.UNDEFINED)}static addRawData(e,t){e.addFieldOffset(4,t,0)}static createRawDataVector(e,t){e.startVector(1,t.length,1);for(let n=t.length-1;n>=0;n--)e.addInt8(t[n]);return e.endVector()}static startRawDataVector(e,t){e.startVector(1,t,1)}static addStringData(e,t){e.addFieldOffset(5,t,0)}static createStringDataVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startStringDataVector(e,t){e.startVector(4,t,4)}static endTensor(e){return e.endObject()}static createTensor(e,t,r,o,i,s,a){return n.startTensor(e),n.addName(e,t),n.addDocString(e,r),n.addDims(e,o),n.addDataType(e,i),n.addRawData(e,s),n.addStringData(e,a),n.endTensor(e)}}t.Tensor=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSparseTensor(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSparseTensor(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}values(t){let n=this.bb.__offset(this.bb_pos,4);return n?(t||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}indices(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}dims(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+8*e):this.bb.createLong(0,0)}dimsLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}static startSparseTensor(e){e.startObject(3)}static addValues(e,t){e.addFieldOffset(0,t,0)}static addIndices(e,t){e.addFieldOffset(1,t,0)}static addDims(e,t){e.addFieldOffset(2,t,0)}static createDimsVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startDimsVector(e,t){e.startVector(8,t,8)}static endSparseTensor(e){return e.endObject()}static createSparseTensor(e,t,r,o){return n.startSparseTensor(e),n.addValues(e,t),n.addIndices(e,r),n.addDims(e,o),n.endSparseTensor(e)}}t.SparseTensor=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsAttribute(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsAttribute(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}name(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}docString(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}type(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt32(this.bb_pos+t):e.experimental.fbs.AttributeType.UNDEFINED}f(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readFloat32(this.bb_pos+e):0}i(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}s(e){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__string(this.bb_pos+t,e):null}t(t){let n=this.bb.__offset(this.bb_pos,16);return n?(t||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}g(t){let n=this.bb.__offset(this.bb_pos,18);return n?(t||new e.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}floats(e){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.readFloat32(this.bb.__vector(this.bb_pos+t)+4*e):0}floatsLength(){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__vector_len(this.bb_pos+e):0}floatsArray(){let e=this.bb.__offset(this.bb_pos,20);return e?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}ints(e){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.readInt64(this.bb.__vector(this.bb_pos+t)+8*e):this.bb.createLong(0,0)}intsLength(){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.__vector_len(this.bb_pos+e):0}strings(e,t){let n=this.bb.__offset(this.bb_pos,24);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}stringsLength(){let e=this.bb.__offset(this.bb_pos,24);return e?this.bb.__vector_len(this.bb_pos+e):0}tensors(t,n){let r=this.bb.__offset(this.bb_pos,26);return r?(n||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}tensorsLength(){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.__vector_len(this.bb_pos+e):0}graphs(t,n){let r=this.bb.__offset(this.bb_pos,28);return r?(n||new e.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}graphsLength(){let e=this.bb.__offset(this.bb_pos,28);return e?this.bb.__vector_len(this.bb_pos+e):0}static startAttribute(e){e.startObject(13)}static addName(e,t){e.addFieldOffset(0,t,0)}static addDocString(e,t){e.addFieldOffset(1,t,0)}static addType(t,n){t.addFieldInt32(2,n,e.experimental.fbs.AttributeType.UNDEFINED)}static addF(e,t){e.addFieldFloat32(3,t,0)}static addI(e,t){e.addFieldInt64(4,t,e.createLong(0,0))}static addS(e,t){e.addFieldOffset(5,t,0)}static addT(e,t){e.addFieldOffset(6,t,0)}static addG(e,t){e.addFieldOffset(7,t,0)}static addFloats(e,t){e.addFieldOffset(8,t,0)}static createFloatsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addFloat32(t[n]);return e.endVector()}static startFloatsVector(e,t){e.startVector(4,t,4)}static addInts(e,t){e.addFieldOffset(9,t,0)}static createIntsVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startIntsVector(e,t){e.startVector(8,t,8)}static addStrings(e,t){e.addFieldOffset(10,t,0)}static createStringsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startStringsVector(e,t){e.startVector(4,t,4)}static addTensors(e,t){e.addFieldOffset(11,t,0)}static createTensorsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startTensorsVector(e,t){e.startVector(4,t,4)}static addGraphs(e,t){e.addFieldOffset(12,t,0)}static createGraphsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startGraphsVector(e,t){e.startVector(4,t,4)}static endAttribute(e){return e.endObject()}static createAttribute(e,t,r,o,i,s,a,c,u,l,f,d,h,p){return n.startAttribute(e),n.addName(e,t),n.addDocString(e,r),n.addType(e,o),n.addF(e,i),n.addI(e,s),n.addS(e,a),n.addT(e,c),n.addG(e,u),n.addFloats(e,l),n.addInts(e,f),n.addStrings(e,d),n.addTensors(e,h),n.addGraphs(e,p),n.endAttribute(e)}}t.Attribute=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsGraph(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsGraph(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}initializers(t,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new e.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}initializersLength(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__vector_len(this.bb_pos+e):0}nodeArgs(t,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new e.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodeArgsLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}nodes(t,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new e.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodesLength(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__vector_len(this.bb_pos+e):0}maxNodeIndex(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readUint32(this.bb_pos+e):0}nodeEdges(t,n){let r=this.bb.__offset(this.bb_pos,12);return r?(n||new e.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodeEdgesLength(){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__vector_len(this.bb_pos+e):0}inputs(e,t){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}inputsLength(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__vector_len(this.bb_pos+e):0}outputs(e,t){let n=this.bb.__offset(this.bb_pos,16);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*e,t):null}outputsLength(){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__vector_len(this.bb_pos+e):0}sparseInitializers(t,n){let r=this.bb.__offset(this.bb_pos,18);return r?(n||new e.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}sparseInitializersLength(){let e=this.bb.__offset(this.bb_pos,18);return e?this.bb.__vector_len(this.bb_pos+e):0}static startGraph(e){e.startObject(8)}static addInitializers(e,t){e.addFieldOffset(0,t,0)}static createInitializersVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startInitializersVector(e,t){e.startVector(4,t,4)}static addNodeArgs(e,t){e.addFieldOffset(1,t,0)}static createNodeArgsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startNodeArgsVector(e,t){e.startVector(4,t,4)}static addNodes(e,t){e.addFieldOffset(2,t,0)}static createNodesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startNodesVector(e,t){e.startVector(4,t,4)}static addMaxNodeIndex(e,t){e.addFieldInt32(3,t,0)}static addNodeEdges(e,t){e.addFieldOffset(4,t,0)}static createNodeEdgesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startNodeEdgesVector(e,t){e.startVector(4,t,4)}static addInputs(e,t){e.addFieldOffset(5,t,0)}static createInputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startInputsVector(e,t){e.startVector(4,t,4)}static addOutputs(e,t){e.addFieldOffset(6,t,0)}static createOutputsVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startOutputsVector(e,t){e.startVector(4,t,4)}static addSparseInitializers(e,t){e.addFieldOffset(7,t,0)}static createSparseInitializersVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startSparseInitializersVector(e,t){e.startVector(4,t,4)}static endGraph(e){return e.endObject()}static createGraph(e,t,r,o,i,s,a,c,u){return n.startGraph(e),n.addInitializers(e,t),n.addNodeArgs(e,r),n.addNodes(e,o),n.addMaxNodeIndex(e,i),n.addNodeEdges(e,s),n.addInputs(e,a),n.addOutputs(e,c),n.addSparseInitializers(e,u),n.endGraph(e)}}t.Graph=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsModel(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsModel(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}irVersion(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}opsetImport(t,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new e.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}opsetImportLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}producerName(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}producerVersion(e){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.__string(this.bb_pos+t,e):null}domain(e){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__string(this.bb_pos+t,e):null}modelVersion(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}docString(e){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.__string(this.bb_pos+t,e):null}graph(t){let n=this.bb.__offset(this.bb_pos,18);return n?(t||new e.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}graphDocString(e){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__string(this.bb_pos+t,e):null}static startModel(e){e.startObject(9)}static addIrVersion(e,t){e.addFieldInt64(0,t,e.createLong(0,0))}static addOpsetImport(e,t){e.addFieldOffset(1,t,0)}static createOpsetImportVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startOpsetImportVector(e,t){e.startVector(4,t,4)}static addProducerName(e,t){e.addFieldOffset(2,t,0)}static addProducerVersion(e,t){e.addFieldOffset(3,t,0)}static addDomain(e,t){e.addFieldOffset(4,t,0)}static addModelVersion(e,t){e.addFieldInt64(5,t,e.createLong(0,0))}static addDocString(e,t){e.addFieldOffset(6,t,0)}static addGraph(e,t){e.addFieldOffset(7,t,0)}static addGraphDocString(e,t){e.addFieldOffset(8,t,0)}static endModel(e){return e.endObject()}static createModel(e,t,r,o,i,s,a,c,u,l){return n.startModel(e),n.addIrVersion(e,t),n.addOpsetImport(e,r),n.addProducerName(e,o),n.addProducerVersion(e,i),n.addDomain(e,s),n.addModelVersion(e,a),n.addDocString(e,c),n.addGraph(e,u),n.addGraphDocString(e,l),n.endModel(e)}}t.Model=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(e){!function(e){class t{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsKernelCreateInfos(e,n){return(n||new t).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsKernelCreateInfos(e,n){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new t).__init(e.readInt32(e.position())+e.position(),e)}nodeIndices(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readUint32(this.bb.__vector(this.bb_pos+t)+4*e):0}nodeIndicesLength(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__vector_len(this.bb_pos+e):0}nodeIndicesArray(){let e=this.bb.__offset(this.bb_pos,4);return e?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+e),this.bb.__vector_len(this.bb_pos+e)):null}kernelDefHashes(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint64(this.bb.__vector(this.bb_pos+t)+8*e):this.bb.createLong(0,0)}kernelDefHashesLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}static startKernelCreateInfos(e){e.startObject(2)}static addNodeIndices(e,t){e.addFieldOffset(0,t,0)}static createNodeIndicesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addInt32(t[n]);return e.endVector()}static startNodeIndicesVector(e,t){e.startVector(4,t,4)}static addKernelDefHashes(e,t){e.addFieldOffset(1,t,0)}static createKernelDefHashesVector(e,t){e.startVector(8,t.length,8);for(let n=t.length-1;n>=0;n--)e.addInt64(t[n]);return e.endVector()}static startKernelDefHashesVector(e,t){e.startVector(8,t,8)}static endKernelCreateInfos(e){return e.endObject()}static createKernelCreateInfos(e,n,r){return t.startKernelCreateInfos(e),t.addNodeIndices(e,n),t.addKernelDefHashes(e,r),t.endKernelCreateInfos(e)}}e.KernelCreateInfos=t}(e.fbs||(e.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSubGraphSessionState(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSubGraphSessionState(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}graphId(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}sessionState(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startSubGraphSessionState(e){e.startObject(2)}static addGraphId(e,t){e.addFieldOffset(0,t,0)}static addSessionState(e,t){e.addFieldOffset(1,t,0)}static endSubGraphSessionState(e){let t=e.endObject();return e.requiredField(t,4),t}static createSubGraphSessionState(e,t,r){return n.startSubGraphSessionState(e),n.addGraphId(e,t),n.addSessionState(e,r),n.endSubGraphSessionState(e)}}t.SubGraphSessionState=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSessionState(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSessionState(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}kernels(t){let n=this.bb.__offset(this.bb_pos,4);return n?(t||new e.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}subGraphSessionStates(t,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new e.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}subGraphSessionStatesLength(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__vector_len(this.bb_pos+e):0}static startSessionState(e){e.startObject(2)}static addKernels(e,t){e.addFieldOffset(0,t,0)}static addSubGraphSessionStates(e,t){e.addFieldOffset(1,t,0)}static createSubGraphSessionStatesVector(e,t){e.startVector(4,t.length,4);for(let n=t.length-1;n>=0;n--)e.addOffset(t[n]);return e.endVector()}static startSubGraphSessionStatesVector(e,t){e.startVector(4,t,4)}static endSessionState(e){return e.endObject()}static createSessionState(e,t,r){return n.startSessionState(e),n.addKernels(e,t),n.addSubGraphSessionStates(e,r),n.endSessionState(e)}}t.SessionState=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={})),function(e){!function(t){!function(t){class n{constructor(){this.bb=null,this.bb_pos=0}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsInferenceSession(e,t){return(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsInferenceSession(e,t){return e.setPosition(e.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(t||new n).__init(e.readInt32(e.position())+e.position(),e)}static bufferHasIdentifier(e){return e.__has_identifier("ORTM")}ortVersion(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}model(t){let n=this.bb.__offset(this.bb_pos,6);return n?(t||new e.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}sessionState(t){let n=this.bb.__offset(this.bb_pos,8);return n?(t||new e.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startInferenceSession(e){e.startObject(3)}static addOrtVersion(e,t){e.addFieldOffset(0,t,0)}static addModel(e,t){e.addFieldOffset(1,t,0)}static addSessionState(e,t){e.addFieldOffset(2,t,0)}static endInferenceSession(e){return e.endObject()}static finishInferenceSessionBuffer(e,t){e.finish(t,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(e,t){e.finish(t,"ORTM",true)}static createInferenceSession(e,t,r,o){return n.startInferenceSession(e),n.addOrtVersion(e,t),n.addModel(e,r),n.addSessionState(e,o),n.endInferenceSession(e)}}t.InferenceSession=n}(t.fbs||(t.fbs={}))}(e.experimental||(e.experimental={}))}(t.onnxruntime||(t.onnxruntime={}))},7448:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.OnnxjsSessionHandler=void 0;const r=n(1670),o=n(9162);t.OnnxjsSessionHandler=class{constructor(e){this.session=e,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(e,t,n){const i=new Map;for(const t in e)if(Object.hasOwnProperty.call(e,t)){const n=e[t];i.set(t,new o.Tensor(n.dims,n.type,void 0,void 0,n.data))}const s=await this.session.run(i),a={};return s.forEach(((e,t)=>{a[t]=new r.Tensor(e.type,e.data,e.dims)})),a}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}},6919:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.Session=void 0;const r=n(7067),o=n(1296),i=n(7091),s=n(1036),a=n(6231),c=n(2644);t.Session=class{constructor(e={}){this._initialized=false,this.backendHint=e.backendHint,this.profiler=a.Profiler.create(e.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(e,t,n){await this.profiler.event("session","Session.loadModel",(async()=>{const s=await(0,i.resolveBackend)(this.backendHint);if(this.sessionHandler=s.createSessionHandler(this.context),this._model=new c.Model,"string"==typeof e){const t=e.endsWith(".ort");if("undefined"==typeof fetch){const n=await(0,o.promisify)(r.readFile)(e);this.initialize(n,t)}else{const n=await fetch(e),r=await n.arrayBuffer();this.initialize(new Uint8Array(r),t)}}else if(ArrayBuffer.isView(e))this.initialize(e);else{const r=new Uint8Array(e,t||0,n||e.byteLength);this.initialize(r)}}))}initialize(e,t){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",(()=>{const n=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(e,n,t),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new s.ExecutionPlan(this._model.graph,this._ops,this.profiler)})),this._initialized=true}async run(e){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",(async()=>{const t=this.normalizeAndValidateInputs(e),n=await this._executionPlan.execute(this.sessionHandler,t);return this.createOutput(n)}))}normalizeAndValidateInputs(e){const t=this._model.graph.getInputNames();if(Array.isArray(e)){if(e.length!==t.length)throw new Error(`incorrect input array length: expected ${t.length} but got ${e.length}`)}else{if(e.size!==t.length)throw new Error(`incorrect input map size: expected ${t.length} but got ${e.size}`);const n=new Array(e.size);let r=0;for(let o=0;o<t.length;++o){const i=e.get(t[o]);if(!i)throw new Error(`missing input tensor for: '${name}'`);n[r++]=i}e=n}if(this.context.graphInputTypes&&0!==this.context.graphInputTypes.length&&this.context.graphInputDims&&0!==this.context.graphInputDims.length)this.validateInputTensorDims(this.context.graphInputDims,e,false);else{const t=this._model.graph.getInputIndices(),n=this._model.graph.getValues(),r=new Array(t.length);for(let o=0;o<t.length;++o){const i=n[t[o]];r[o]=i.type.shape.dims,this.context.graphInputTypes.push(i.type.tensorType),this.context.graphInputDims.push(e[o].dims)}this.validateInputTensorDims(r,e,true)}return this.validateInputTensorTypes(this.context.graphInputTypes,e),e}validateInputTensorTypes(e,t){for(let n=0;n<t.length;n++){const r=e[n],o=t[n].type;if(r!==o)throw new Error(`input tensor[${n}] check failed: expected type '${r}' but got ${o}`)}}validateInputTensorDims(e,t,n){for(let r=0;r<t.length;r++){const o=e[r],i=t[r].dims;if(!this.compareTensorDims(o,i,n))throw new Error(`input tensor[${r}] check failed: expected shape '[${o.join(",")}]' but got [${i.join(",")}]`)}}compareTensorDims(e,t,n){if(e.length!==t.length)return false;for(let r=0;r<e.length;++r)if(e[r]!==t[r]&&(!n||0!==e[r]))return false;return true}createOutput(e){const t=this._model.graph.getOutputNames();if(e.length!==t.length)throw new Error("expected number of outputs do not match number of generated outputs");const n=new Map;for(let r=0;r<t.length;++r)n.set(t[r],e[r]);return n}initializeOps(e){const t=e.getNodes();this._ops=new Array(t.length);for(let n=0;n<t.length;n++)this._ops[n]=this.sessionHandler.resolve(t[n],this._model.opsets,e)}}},9162:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true}),t.Tensor=void 0;const o=n(3442),i=r(n(3720)),s=n(1446),a=n(9395),c=n(2517);var u=a.onnxruntime.experimental.fbs;class l{get data(){if(void 0===this.cache){const e=this.dataProvider(this.dataId);if(e.length!==this.size)throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");this.cache=e}return this.cache}get stringData(){if("string"!==this.type)throw new TypeError("data type is not string");return this.data}get integerData(){switch(this.type){case"uint8":case"int8":case"uint16":case"int16":case"int32":case"uint32":case"bool":return this.data;default:throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)")}}get floatData(){switch(this.type){case"float32":case"float64":return this.data;default:throw new TypeError("data type is not float (float32, float64)")}}get numberData(){if("string"!==this.type)return this.data;throw new TypeError("type cannot be non-number (string)")}get(e){return this.data[c.ShapeUtil.indicesToOffset(e,this.strides)]}set(e,t){this.data[c.ShapeUtil.indicesToOffset(e,this.strides)]=t}async getData(){return void 0===this.cache&&(this.cache=await this.asyncDataProvider(this.dataId)),this.cache}get strides(){return this._strides||(this._strides=c.ShapeUtil.computeStrides(this.dims)),this._strides}constructor(e,t,n,r,i,s=o.Guid.create()){this.dims=e,this.type=t,this.dataProvider=n,this.asyncDataProvider=r,this.cache=i,this.dataId=s,this.size=c.ShapeUtil.validateDimsAndCalcSize(e);const a=this.size,u=void 0===n&&void 0===r&&void 0===i;if(void 0!==i&&i.length!==a)throw new RangeError("Input dims doesn't match data length.");if("string"===t){if(!(void 0===i||Array.isArray(i)&&i.every((e=>"string"==typeof e))))throw new TypeError("cache should be a string array");u&&(this.cache=new Array(a))}else{if(void 0!==i){const e=d(t);if(!(i instanceof e))throw new TypeError(`cache should be type ${e.name}`)}if(u){const e=new ArrayBuffer(a*function(e){switch(e){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${e}`)}}(t));this.cache=function(e,t){return new(d(t))(e)}(e,t)}}}static fromProto(e){if(!e)throw new Error("cannot construct Value from an empty tensor");const t=c.ProtoUtil.tensorDataTypeFromProto(e.dataType),n=c.ProtoUtil.tensorDimsFromProto(e.dims),r=new l(n,t);if("string"===t)e.stringData.forEach(((e,t)=>{r.data[t]=(0,c.decodeUtf8String)(e)}));else if(e.rawData&&"number"==typeof e.rawData.byteLength&&e.rawData.byteLength>0){const t=r.data,n=new DataView(e.rawData.buffer,e.rawData.byteOffset,e.rawData.byteLength),o=f(e.dataType),i=e.rawData.byteLength/o;if(e.rawData.byteLength%o!=0)throw new Error("invalid buffer length");if(t.length!==i)throw new Error("buffer length mismatch");for(let r=0;r<i;r++){const i=p(n,e.dataType,r*o);t[r]=i}}else{let t;switch(e.dataType){case s.onnx.TensorProto.DataType.FLOAT:t=e.floatData;break;case s.onnx.TensorProto.DataType.INT32:case s.onnx.TensorProto.DataType.INT16:case s.onnx.TensorProto.DataType.UINT16:case s.onnx.TensorProto.DataType.INT8:case s.onnx.TensorProto.DataType.UINT8:case s.onnx.TensorProto.DataType.BOOL:t=e.int32Data;break;case s.onnx.TensorProto.DataType.INT64:t=e.int64Data;break;case s.onnx.TensorProto.DataType.DOUBLE:t=e.doubleData;break;case s.onnx.TensorProto.DataType.UINT32:case s.onnx.TensorProto.DataType.UINT64:t=e.uint64Data;break;default:throw new Error("unspecific error")}if(null==t)throw new Error("failed to populate data from a tensorproto value");const n=r.data;if(n.length!==t.length)throw new Error("array length mismatch");for(let r=0;r<t.length;r++){const o=t[r];i.default.isLong(o)?n[r]=h(o,e.dataType):n[r]=o}}return r}static fromData(e,t,n){return new l(t,n,void 0,void 0,e)}static fromOrtTensor(e){if(!e)throw new Error("cannot construct Value from an empty tensor");const t=c.ProtoUtil.tensorDimsFromORTFormat(e),n=c.ProtoUtil.tensorDataTypeFromProto(e.dataType()),r=new l(t,n);if("string"===n)for(let t=0;t<e.stringDataLength();t++)r.data[t]=e.stringData(t);else if(e.rawDataArray()&&"number"==typeof e.rawDataLength()&&e.rawDataLength()>0){const t=r.data,n=new DataView(e.rawDataArray().buffer,e.rawDataArray().byteOffset,e.rawDataLength()),o=f(e.dataType()),i=e.rawDataLength()/o;if(e.rawDataLength()%o!=0)throw new Error("invalid buffer length");if(t.length!==i)throw new Error("buffer length mismatch");for(let r=0;r<i;r++){const i=p(n,e.dataType(),r*o);t[r]=i}}return r}}function f(e){switch(e){case s.onnx.TensorProto.DataType.UINT8:case s.onnx.TensorProto.DataType.INT8:case s.onnx.TensorProto.DataType.BOOL:return 1;case s.onnx.TensorProto.DataType.UINT16:case s.onnx.TensorProto.DataType.INT16:return 2;case s.onnx.TensorProto.DataType.FLOAT:case s.onnx.TensorProto.DataType.INT32:case s.onnx.TensorProto.DataType.UINT32:return 4;case s.onnx.TensorProto.DataType.INT64:case s.onnx.TensorProto.DataType.DOUBLE:case s.onnx.TensorProto.DataType.UINT64:return 8;default:throw new Error(`cannot calculate sizeof() on type ${s.onnx.TensorProto.DataType[e]}`)}}function d(e){switch(e){case"bool":case"uint8":return Uint8Array;case"int8":return Int8Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"float32":return Float32Array;case"float64":return Float64Array;default:throw new Error("unspecified error")}}function h(e,t){if(t===s.onnx.TensorProto.DataType.INT64||t===u.TensorDataType.INT64){if(e.greaterThanOrEqual(2147483648)||e.lessThan(-2147483648))throw new TypeError("int64 is not supported")}else{if(t!==s.onnx.TensorProto.DataType.UINT32&&t!==u.TensorDataType.UINT32&&t!==s.onnx.TensorProto.DataType.UINT64&&t!==u.TensorDataType.UINT64)throw new TypeError(`not a LONG type: ${s.onnx.TensorProto.DataType[t]}`);if(e.greaterThanOrEqual(4294967296)||e.lessThan(0))throw new TypeError("uint64 is not supported")}return e.toNumber()}function p(e,t,n){switch(t){case s.onnx.TensorProto.DataType.BOOL:case s.onnx.TensorProto.DataType.UINT8:return e.getUint8(n);case s.onnx.TensorProto.DataType.INT8:return e.getInt8(n);case s.onnx.TensorProto.DataType.UINT16:return e.getUint16(n,true);case s.onnx.TensorProto.DataType.INT16:return e.getInt16(n,true);case s.onnx.TensorProto.DataType.FLOAT:return e.getFloat32(n,true);case s.onnx.TensorProto.DataType.INT32:return e.getInt32(n,true);case s.onnx.TensorProto.DataType.UINT32:return e.getUint32(n,true);case s.onnx.TensorProto.DataType.INT64:return h(i.default.fromBits(e.getUint32(n,true),e.getUint32(n+4,true),false),t);case s.onnx.TensorProto.DataType.DOUBLE:return e.getFloat64(n,true);case s.onnx.TensorProto.DataType.UINT64:return h(i.default.fromBits(e.getUint32(n,true),e.getUint32(n+4,true),true),t);default:throw new Error(`cannot read from DataView for type ${s.onnx.TensorProto.DataType[t]}`)}}t.Tensor=l},2517:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true}),t.decodeUtf8String=t.MAX_CLIP=t.MIN_CLIP=t.PoolConvUtil=t.ReduceUtil=t.SplitUtil=t.MathUtil=t.ShapeUtil=t.LongUtil=t.ProtoUtil=t.GemmUtil=t.arrayCopyHelper=t.BroadcastUtil=t.MatMulUtil=t.ArrayUtil=t.assert=t.checkInputsShape=void 0;const o=n(5686),i=r(n(3720)),s=n(1446),a=n(9162);t.checkInputsShape=function(e,...t){if(!e||e.length!==t.length)return false;for(let n=0;n<e.length;n++)if(!e[n].dims||e[n].dims.length!==t[n])return false;return true},t.assert=function(e,t){if(!e)throw new Error("string"==typeof t?t:t())},t.ArrayUtil=class{static arraysEqual(e,t){if(e.length!==t.length)return false;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return false;return true}};class c{static preprocessInputShapes(e,t){return[1===e.length?[1,e[0]]:e,1===t.length?[t[0],1]:t]}static postprocessOutputShape(e,t,n){1===t&&e.splice(e.length-2,1),1===n&&e.pop()}static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}}t.MatMulUtil=c;class u{static calcShape(e,t,n=false){const r=e.length,o=t.length;if(0===r)return t;if(0===o)return e;const i=Math.max(e.length,t.length),s=new Array(i);if(n){if(r<2||o<2)return;const n=c.calcMatMulShape([e[r-2],e[r-1]],[t[o-2],t[o-1]]);if(void 0===n)return;[s[i-2],s[i-1]]=n}for(let a=n?3:1;a<=i;a++){const n=r-a<0?1:e[r-a],c=o-a<0?1:t[o-a];if(n!==c&&n>1&&c>1)return;s[i-a]=Math.max(n,c)}return s}static index(e,t){const n=new Array(t.length);return u.fillIndex(e,t,n),n}static fillIndex(e,t,n){const r=e.length-t.length;for(let o=0;o<t.length;o++)n[o]=e[r+o]%t[o]}static calc(e,t,n,r,o){const i=u.calcShape(e.dims,t.dims);if(i){if(r&&!d.areEqual(i,e.dims))return;const s=d.size(i),c=r?e:new a.Tensor(i,o||e.type);if(0===i.length)c.set([],n(e.get([]),t.get([])));else{const r=new Array(i.length),o=new Array(e.dims.length),a=new Array(t.dims.length);let l,f=0,d=0,h=false,p=false;0===e.dims.length&&(f=e.get([]),h=true),0===t.dims.length&&(d=t.get([]),p=true);for(let m=0;m<s;m++){l=m;for(let e=i.length-1;e>=0;e--)r[e]=l%i[e],l=Math.floor(l/i[e]);h||(u.fillIndex(r,e.dims,o),f=e.get(o)),p||(u.fillIndex(r,t.dims,a),d=t.get(a)),c.set(r,n(f,d))}}return c}}static isValidBroadcast(e,t){const n=e.length,r=t.length;if(n>r)return false;for(let o=1;o<=n;o++)if(1!==e[n-o]&&e[n-o]!==t[r-o])return false;return true}static getBroadcastDims(e,t){const n=e.length,r=[];for(let o=0;o<n;o++){const i=n-1-o,s=e[i]||1;(t[t.length-1-o]||1)>1&&1===s&&r.unshift(i)}return r}}t.BroadcastUtil=u,t.arrayCopyHelper=function(e,t,n,r,o){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+o>t.length)throw new Error("source indices to be copied are outside bounds");if(n+o>e.length)throw new Error("target array is too small to hold result");for(let i=0;i<o;i++)e[n+i]=t[r+i]},t.GemmUtil=class{static getShapeOfGemmResult(e,t,n,r,o){if(2!==e.length||2!==n.length)throw new Error("shape need to be of size 2");let i,s,a;t?(i=e[1],s=e[0]):(i=e[0],s=e[1]);let c=-1;if(r?(a=n[0],c=1):(a=n[1],c=0),n[c]!==s)throw new Error("dimension mismatch");if(i<=0||a<=0||s<=0)throw new Error("invalid shape specified");if(o&&!u.isValidBroadcast(o,[i,a]))throw new Error("gemm: invalid bias shape for broadcast");return[i,a,s]}};class l{static tensorDataTypeFromProto(e){switch(e){case s.onnx.TensorProto.DataType.INT8:return"int8";case s.onnx.TensorProto.DataType.UINT8:return"uint8";case s.onnx.TensorProto.DataType.BOOL:return"bool";case s.onnx.TensorProto.DataType.INT16:return"int16";case s.onnx.TensorProto.DataType.UINT16:return"uint16";case s.onnx.TensorProto.DataType.INT32:return"int32";case s.onnx.TensorProto.DataType.UINT32:return"uint32";case s.onnx.TensorProto.DataType.FLOAT:return"float32";case s.onnx.TensorProto.DataType.DOUBLE:return"float64";case s.onnx.TensorProto.DataType.STRING:return"string";case s.onnx.TensorProto.DataType.INT64:return"int32";case s.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw new Error(`unsupported data type: ${s.onnx.TensorProto.DataType[e]}`)}}static tensorDataTypeStringToEnum(e){switch(e){case"int8":return s.onnx.TensorProto.DataType.INT8;case"uint8":return s.onnx.TensorProto.DataType.UINT8;case"bool":return s.onnx.TensorProto.DataType.BOOL;case"int16":return s.onnx.TensorProto.DataType.INT16;case"uint16":return s.onnx.TensorProto.DataType.UINT16;case"int32":return s.onnx.TensorProto.DataType.INT32;case"uint32":return s.onnx.TensorProto.DataType.UINT32;case"float32":return s.onnx.TensorProto.DataType.FLOAT;case"float64":return s.onnx.TensorProto.DataType.DOUBLE;case"string":return s.onnx.TensorProto.DataType.STRING;case"int64":return s.onnx.TensorProto.DataType.INT64;case"uint64":return s.onnx.TensorProto.DataType.UINT64;default:throw new Error(`unsupported data type: ${e}`)}}static tensorDimsFromProto(e){return e.map((e=>i.default.isLong(e)?e.toNumber():e))}static tensorValueTypeFromProto(e){return{tensorType:l.tensorDataTypeFromProto(e.elemType),shape:{dims:l.tensorDimsFromProto(e.shape.dim.map((e=>e.dimValue)))}}}static tensorDimsFromORTFormat(e){const t=[];for(let n=0;n<e.dimsLength();n++)t.push(f.longToNumber(e.dims(n)));return t}static tensorAttributesFromORTFormat(e){const t=[];for(let n=0;n<e.attributesLength();n++)t.push(e.attributes(n));return t}}t.ProtoUtil=l;class f{static longToNumber(e,t){return i.default.isLong(e)?e.toNumber():e instanceof o.flatbuffers.Long?i.default.fromValue({low:e.low,high:e.high,unsigned:null!=t&&t}).toNumber():e}static isLong(e){return i.default.isLong(e)||e instanceof o.flatbuffers.Long}}t.LongUtil=f;class d{static size(e){return d.getSizeFromDimensionRange(e,0,e.length)}static sizeFromDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return d.getSizeFromDimensionRange(e,t,e.length)}static sizeToDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${e.length} dimensions.`);return d.getSizeFromDimensionRange(e,0,t)}static getSizeFromDimensionRange(e,t,n){let r=1;for(let o=t;o<n;o++){if(e[o]<=0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.");r*=e[o]}return r}static computeStrides(e){const t=e.length;if(0===t)return[];if(1===t)return[1];const n=new Array(t);n[t-1]=1,n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}static transpose(e){return e.slice().reverse()}static indicesToOffset(e,t,n){void 0===n&&(n=e.length);let r=0;for(let o=0;o<n;++o)r+=t[o]*e[o];return r}static offsetToIndices(e,t){const n=t.length;if(0===n)return[];if(1===n)return[e*t[0]];const r=new Array(t.length);for(let n=0;n<r.length-1;++n)r[n]=Math.floor(e/t[n]),e-=r[n]*t[n];return r[r.length-1]=e,r}static normalizeAxis(e,t){if(e<-t&&e>=t)throw new Error("unsupported axis for this operation.");return e<0?e+t:e}static normalizeAxes(e,t){return e.map((e=>this.normalizeAxis(e,t)))}static incrementIndex(e,t,n){if(0===t.length||0===e.length)throw new Error("Index incrementing unsupported for scalar Tensor");if(void 0===n)n=t.length;else if(n<=0||n>t.length)throw new Error("Incorrect axis to increment on");for(let r=n-1;r>=0&&(e[r]++,!(e[r]<t[r]));--r)e[r]=0}static calculateReshapedDims(e,t){if(0===t.length){if(0===e.length||1===d.size(e))return[];throw new Error("cannot reshape to a scalar Tensor")}const n=t.length,r=new Array(n);let o=-1,i=1;for(let s=0;s<n;s++){if(t[s]<-1)throw new Error("a dimension in shape hints cannot be less than -1");if(-1===t[s]){if(-1!==o)throw new Error("at most one dimension in shape hints can be -1");o=s}else{if(0===t[s]){if(s>=e.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");r[s]=e[s]}else r[s]=t[s];i*=r[s]}}const s=d.size(e);if(-1!==o){if(s%i!=0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${e}] Output shape: [${t}]`);r[o]=s/i}else if(i!==s)throw new Error("reshapedDims and originalDims don't have matching sizes");return r}static sortBasedOnPerm(e,t){return t?t.map((t=>e[t])):e.slice().reverse()}static padShape(e,t){const n=e.length;return e.map(((e,r)=>e+t[r]+t[r+n]))}static areEqual(e,t){return e.length===t.length&&e.every(((e,n)=>e===t[n]))}static validateDimsAndCalcSize(e){if(e.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let t=1;for(const n of e){if(!Number.isInteger(n))throw new TypeError(`Invalid shape: ${n} is not an integer`);if(n<0||n>2147483647)throw new TypeError(`Invalid shape: length ${n} is not allowed`);t*=n}return t}static flattenShape(e,t){t<0&&(t+=e.length);const n=e.reduce(((e,t)=>e*t),1),r=e.slice(t).reduce(((e,t)=>e*t),1);return[n/r,r]}static squeezeShape(e,t){const n=new Array;t=d.normalizeAxes(t,e.length);for(let r=0;r<e.length;r++){const o=t.indexOf(r)>=0;if(o&&1!==e[r])throw new Error("squeeze an axis of size different than 1");(0===t.length&&e[r]>1||t.length>0&&!o)&&n.push(e[r])}return n}static unsqueezeShape(e,t){const n=new Array(e.length+t.length);n.fill(0);for(let e=0;e<t.length;e++){const r=d.normalizeAxis(t[e],n.length);if(r>=n.length)throw new Error("'axes' has an out of range axis");if(0!==n[r])throw new Error("'axes' has a duplicate axis");n[r]=1}let r=0;for(let t=0;t<n.length;t++)0===n[t]&&(n[t]=e[r++]);if(r!==e.length)throw new Error("the unsqueezed dimension could not be established");return n}}t.ShapeUtil=d,t.MathUtil=class{static sqr(e,t,n,r,o){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+o>t.length)throw new Error("source indices to be copied are outside bounds");if(n+o>e.length)throw new Error("target array is too small to hold result");for(let i=0;i<o;i++)e[n+i]+=Math.pow(t[r+i],2)}static axpy(e,t,n,r,o,i){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+o>t.length)throw new Error("source indices to be copied are outside bounds");if(n+o>e.length)throw new Error("target array is too small to hold result");for(let s=0;s<o;s++)e[n+s]+=i*t[r+s]}static powx(e,t,n,r,o,i){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+o>t.length)throw new Error("source indices to be copied are outside bounds");if(n+o>e.length)throw new Error("target array is too small to hold result");for(let s=0;s<o;s++)e[n+s]=Math.pow(t[r+s],i)}static mul(e,t,n,r,o){if(r<0||r>=t.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=e.length)throw new Error("targetIndex out of bounds");if(r+o>t.length)throw new Error("source indices to be copied are outside bounds");if(n+o>e.length)throw new Error("target array is too small to hold result");for(let i=0;i<o;i++)e[n+i]=t[r+i]*e[n+i]}};class h{static splitShape(e,t,n,r){if(0===n.length){if(!r)throw new Error("need to know number of outputs when the 'split' attribute is not specified");h.determineSplit(e[t],r,n)}const o=[],i=[0];for(let r=0;r<n.length;++r){0!==r&&i.push(i[r-1]+n[r-1]);const s=e.slice();s[t]=n[r],o.push(s)}return[o,i]}static determineSplit(e,t,n){if(e%t!=0)throw new Error("cannot split tensor to equal sized parts");for(let r=0;r<t;++r)n.push(e/t)}}t.SplitUtil=h;class p{static calcReduce(e,t,n,r,o){const i=e.dims.slice(0);0===t.length&&i.forEach(((e,n)=>t.push(n)));const s=p.calcReduceShape(i,t,true),c=d.size(s),l=new a.Tensor(s,e.type),f=d.computeStrides(s),h=d.computeStrides(i),m=new Array(i.length);for(let n=0;n<c;n++){const s=d.offsetToIndices(n,f);u.fillIndex(s,i,m),l.set(s,p.calcReduceByAxis(e.numberData,t,i,0,d.indicesToOffset(m,h),r,o))}return n?l:new a.Tensor(p.calcReduceShape(i,t,n),l.type,void 0,void 0,l.data,l.dataId)}static calcReduceByAxis(e,t,n,r,o,i,s){let a=0;if(r>=t.length)return i(e[o]);const c=t[r],u=c>=n.length?1:d.size(n.slice(c+1));for(let l=0;l<n[c];l++)a=0===l?p.calcReduceByAxis(e,t,n,r+1,o,i,s):s(a,p.calcReduceByAxis(e,t,n,r+1,o,i,s)),o+=u;return a}static calcReduceShape(e,t,n){const r=e.slice();for(let e=0;e<t.length;e++)r[t[e]]=n?1:0;return r.filter((e=>0!==e))}}t.ReduceUtil=p;class m{static adjustPoolAttributes(e,t,n,r,o,i){if(!e&&n.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let e=0;e<t.length-2;e++)e>=n.length?n.push(t[e+2]):n[e]=t[e+2];for(let e=0;e<n.length;e++)if(e<r.length){if(r[e]<0)throw new Error("strides should be greater than or equal to 1")}else r.push(1);for(let e=0;e<n.length;e++)if(e<o.length){if(o[e]<0)throw new Error("dilations should be greater than or equal to 1")}else o.push(1);for(let e=0;e<2*n.length;e++)if(e<i.length){if(i[e]<0)throw new Error("pad should be greater than or equal to 1")}else i.push(0);for(let e=0;e<n.length;e++){if(n[e]<=0)throw new Error("kernel shapes need to be greater than 0");if(i[e]>=n[e]||i[e+n.length]>=n[e])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,t,n,r,o,i){if(i){if(o.length!==2*(e.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==e.length-2)throw new Error("length of strides should be the length of data dimensions");if(r.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let s=0;s<e.length-2;s++)m.adjustPadAndReturnShape(e[s+2],t[s],n[s],r[s],o,s,s+e.length-2,i)}}static computePoolOutputShape(e,t,n,r,o,i,s){if(t.length<=0)throw new Error("input shape must be of size greater than 0");const a=[t[0],t[1]];return m.computeShapeHelper(e,t,a,n,r,o,i,s),a}static computeConvOutputShape(e,t,n,r,o,i,s){if(e.length<=0||t.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");const a=[e[0],t[0]];return m.computeShapeHelper(false,e,a,n,r,o,i,s),a}static computeShapeHelper(e,t,n,r,o,i,s,a){if(e)for(let e=0;e<t.length-2;e++)n.push(1);else for(let e=0;e<t.length-2;e++)n.push(m.adjustPadAndReturnShape(t[e+2],r[e],o[e],i[e],s,e,e+t.length-2,a))}static adjustPadAndReturnShape(e,t,n,r,o,i,s,a){const c=n*(r-1)+1;if(!a||"NOTSET"===a)return Math.floor((e+o[i]+o[s]-c)/t+1);switch(a){case"VALID":return o[i]=0,o[s]=0,Math.floor((e-c)/t+1);case"SAME_LOWER":case"SAME_UPPER":if(1!==n)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{const n=((e+t-1)/t-1)*t+r-e;return o[i]="SAME_LOWER"===a?Math.floor((n+1)/2):Math.floor(n/2),o[s]=n-o[i],Math.floor((e+n-r)/t+1)}default:throw new Error("Unsupported AutoPad type")}}}t.PoolConvUtil=m,t.MIN_CLIP=-34028234663852886e22,t.MAX_CLIP=34028234663852886e22,t.decodeUtf8String=function(e){return(new TextDecoder).decode(e)}},7967:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true}),t.iterateExtraOptions=void 0,t.iterateExtraOptions=(e,n,r,o)=>{if("object"==typeof e&&null!==e){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach((([e,i])=>{const s=n?n+e:e;if("object"==typeof i)(0,t.iterateExtraOptions)(i,s+".",r,o);else if("string"==typeof i||"number"==typeof i)o(s,i.toString());else{if("boolean"!=typeof i)throw new Error("Can't handle extra config type: "+typeof i);o(s,i?"1":"0")}}))}},2157:function(e,t,n){var r,o=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:true,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&o(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:true}),t.endProfiling=t.run=t.releaseSession=t.createSession=t.createSessionFinalize=t.createSessionAllocate=t.initOrt=t.initWasm=void 0;const a=n(1670),c=s(n(349)),u=n(6361),l=()=>!!a.env.wasm.proxy&&"undefined"!=typeof document;let f,d,h,p=false,m=false,w=false;const g=[],v=[],y=[],_=[],b=[],x=[],T=()=>{if(p||!m||w||!f)throw new Error("worker not ready")},M=e=>{switch(e.data.type){case"init-wasm":p=false,e.data.err?(w=true,d[1](e.data.err)):(m=true,d[0]());break;case"init-ort":e.data.err?h[1](e.data.err):h[0]();break;case"create_allocate":e.data.err?g.shift()[1](e.data.err):g.shift()[0](e.data.out);break;case"create_finalize":e.data.err?v.shift()[1](e.data.err):v.shift()[0](e.data.out);break;case"create":e.data.err?y.shift()[1](e.data.err):y.shift()[0](e.data.out);break;case"release":e.data.err?_.shift()[1](e.data.err):_.shift()[0]();break;case"run":e.data.err?b.shift()[1](e.data.err):b.shift()[0](e.data.out);break;case"end-profiling":e.data.err?x.shift()[1](e.data.err):x.shift()[0]()}},E="undefined"!=typeof document?null===(r=null===document||void 0===document?void 0:document.currentScript)||void 0===r?void 0:r.src:void 0;t.initWasm=async()=>{if(l()){if(m)return;if(p)throw new Error("multiple calls to 'initWasm()' detected.");if(w)throw new Error("previous call to 'initWasm()' failed.");return p=true,void 0===a.env.wasm.wasmPaths&&E&&0!==E.indexOf("blob:")&&(a.env.wasm.wasmPaths=E.substr(0,+E.lastIndexOf("/")+1)),new Promise(((e,t)=>{null==f||f.terminate(),f=n(9710).Z(),f.onmessage=M,d=[e,t];const r={type:"init-wasm",in:a.env.wasm};f.postMessage(r)}))}return(0,u.initializeWebAssembly)(a.env.wasm)},t.initOrt=async(e,t)=>{if(l())return T(),new Promise(((n,r)=>{h=[n,r];const o={type:"init-ort",in:{numThreads:e,loggingLevel:t}};f.postMessage(o)}));c.initOrt(e,t)},t.createSessionAllocate=async e=>l()?(T(),new Promise(((t,n)=>{g.push([t,n]);const r={type:"create_allocate",in:{model:e}};f.postMessage(r,[e.buffer])}))):c.createSessionAllocate(e),t.createSessionFinalize=async(e,t)=>l()?(T(),new Promise(((n,r)=>{v.push([n,r]);const o={type:"create_finalize",in:{modeldata:e,options:t}};f.postMessage(o)}))):c.createSessionFinalize(e,t),t.createSession=async(e,t)=>l()?(T(),new Promise(((n,r)=>{y.push([n,r]);const o={type:"create",in:{model:e,options:t}};f.postMessage(o,[e.buffer])}))):c.createSession(e,t),t.releaseSession=async e=>{if(l())return T(),new Promise(((t,n)=>{_.push([t,n]);const r={type:"release",in:e};f.postMessage(r)}));c.releaseSession(e)},t.run=async(e,t,n,r,o)=>l()?(T(),new Promise(((i,s)=>{b.push([i,s]);const a={type:"run",in:{sessionId:e,inputIndices:t,inputs:n,outputIndices:r,options:o}};f.postMessage(a,c.extractTransferableBuffers(n))}))):c.run(e,t,n,r,o),t.endProfiling=async e=>{if(l())return T(),new Promise(((t,n)=>{x.push([t,n]);const r={type:"end-profiling",in:e};f.postMessage(r)}));c.endProfiling(e)}},586:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.setRunOptions=void 0;const r=n(7967),o=n(4983),i=n(6361);t.setRunOptions=e=>{const t=(0,i.getInstance)();let n=0;const s=[],a=e||{};try{if(void 0===(null==e?void 0:e.logSeverityLevel))a.logSeverityLevel=2;else if("number"!=typeof e.logSeverityLevel||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(void 0===(null==e?void 0:e.logVerbosityLevel))a.logVerbosityLevel=0;else if("number"!=typeof e.logVerbosityLevel||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);void 0===(null==e?void 0:e.terminate)&&(a.terminate=false);let i=0;if(void 0!==(null==e?void 0:e.tag)&&(i=(0,o.allocWasmString)(e.tag,s)),n=t._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,i),0===n)throw new Error("Can't create run options");return void 0!==(null==e?void 0:e.extra)&&(0,r.iterateExtraOptions)(e.extra,"",new WeakSet,((e,r)=>{const i=(0,o.allocWasmString)(e,s),a=(0,o.allocWasmString)(r,s);if(0!==t._OrtAddRunConfigEntry(n,i,a))throw new Error(`Can't set a run config entry: ${e} - ${r}`)})),[n,s]}catch(e){throw 0!==n&&t._OrtReleaseRunOptions(n),s.forEach(t._free),e}}},2306:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.OnnxruntimeWebAssemblySessionHandler=void 0;const r=n(2806),o=n(1670),i=n(2850),s=n(2157);let a;t.OnnxruntimeWebAssemblySessionHandler=class{async createSessionAllocate(e){const t=await fetch(e),n=await t.arrayBuffer();return(0,s.createSessionAllocate)(new Uint8Array(n))}async loadModel(e,t){if(a||(await(0,s.initOrt)(o.env.wasm.numThreads,(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}`)}})(o.env.logLevel)),a=true),"string"==typeof e)if("undefined"==typeof fetch){const n=await(0,i.promisify)(r.readFile)(e);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(n,t)}else{const n=await this.createSessionAllocate(e);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSessionFinalize)(n,t)}else[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(e,t)}async dispose(){return(0,s.releaseSession)(this.sessionId)}async run(e,t,n){const r=[],i=[];Object.entries(e).forEach((e=>{const t=e[0],n=e[1],o=this.inputNames.indexOf(t);if(-1===o)throw new Error(`invalid input '${t}'`);r.push(n),i.push(o)}));const a=[];Object.entries(t).forEach((e=>{const t=e[0],n=this.outputNames.indexOf(t);if(-1===n)throw new Error(`invalid output '${t}'`);a.push(n)}));const c=await(0,s.run)(this.sessionId,i,r.map((e=>[e.type,e.dims,e.data])),a,n),u={};for(let e=0;e<c.length;e++)u[this.outputNames[a[e]]]=new o.Tensor(c[e][0],c[e][2],c[e][1]);return u}startProfiling(){}endProfiling(){(0,s.endProfiling)(this.sessionId)}}},4919:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.setSessionOptions=void 0;const r=n(7967),o=n(4983),i=n(6361);t.setSessionOptions=e=>{const t=(0,i.getInstance)();let n=0;const s=[],a=e||{};(e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});const t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1")})(a);try{void 0===(null==e?void 0:e.graphOptimizationLevel)&&(a.graphOptimizationLevel="all");const c=(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}`)}})(a.graphOptimizationLevel);void 0===(null==e?void 0:e.enableCpuMemArena)&&(a.enableCpuMemArena=true),void 0===(null==e?void 0:e.enableMemPattern)&&(a.enableMemPattern=true),void 0===(null==e?void 0:e.executionMode)&&(a.executionMode="sequential");const u=(e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}})(a.executionMode);let l=0;if(void 0!==(null==e?void 0:e.logId)&&(l=(0,o.allocWasmString)(e.logId,s)),void 0===(null==e?void 0:e.logSeverityLevel))a.logSeverityLevel=2;else if("number"!=typeof e.logSeverityLevel||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(void 0===(null==e?void 0:e.logVerbosityLevel))a.logVerbosityLevel=0;else if("number"!=typeof e.logVerbosityLevel||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);if(void 0===(null==e?void 0:e.enableProfiling)&&(a.enableProfiling=false),n=t._OrtCreateSessionOptions(c,!!a.enableCpuMemArena,!!a.enableMemPattern,u,!!a.enableProfiling,0,l,a.logSeverityLevel,a.logVerbosityLevel),0===n)throw new Error("Can't create session options");return(null==e?void 0:e.executionProviders)&&((e,t,n)=>{for(const r of t){let t="string"==typeof r?r:r.name;switch(t){case"xnnpack":t="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${t}`)}const s=(0,o.allocWasmString)(t,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(e,s))throw new Error(`Can't append execution provider: ${t}`)}})(n,e.executionProviders,s),void 0!==(null==e?void 0:e.extra)&&(0,r.iterateExtraOptions)(e.extra,"",new WeakSet,((e,r)=>{const i=(0,o.allocWasmString)(e,s),a=(0,o.allocWasmString)(r,s);if(0!==t._OrtAddSessionConfigEntry(n,i,a))throw new Error(`Can't set a session config entry: ${e} - ${r}`)})),[n,s]}catch(e){throw 0!==n&&t._OrtReleaseSessionOptions(n),s.forEach(t._free),e}}},4983:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.allocWasmString=void 0;const r=n(6361);t.allocWasmString=(e,t)=>{const n=(0,r.getInstance)(),o=n.lengthBytesUTF8(e)+1,i=n._malloc(o);return n.stringToUTF8(e,i,o),t.push(i),i}},349:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true}),t.extractTransferableBuffers=t.endProfiling=t.run=t.releaseSession=t.createSession=t.createSessionFinalize=t.createSessionAllocate=t.initOrt=void 0;const r=n(586),o=n(4919),i=n(4983),s=n(6361);t.initOrt=(e,t)=>{const n=(0,s.getInstance)()._OrtInit(e,t);if(0!==n)throw new Error(`Can't initialize onnxruntime. error code = ${n}`)};const a=new Map;t.createSessionAllocate=e=>{const t=(0,s.getInstance)(),n=t._malloc(e.byteLength);return t.HEAPU8.set(e,n),[n,e.byteLength]},t.createSessionFinalize=(e,t)=>{const n=(0,s.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,o.setSessionOptions)(t),r=n._OrtCreateSession(e[0],e[1],i),0===r)throw new Error("Can't create a session")}finally{n._free(e[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const u=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],d=[],h=[],p=[];for(let e=0;e<u;e++){const t=n._OrtGetInputName(r,e);if(0===t)throw new Error("Can't get an input name");d.push(t),f.push(n.UTF8ToString(t))}for(let e=0;e<l;e++){const t=n._OrtGetOutputName(r,e);if(0===t)throw new Error("Can't get an output name");p.push(t),h.push(n.UTF8ToString(t))}return a.set(r,[r,d,p]),[r,f,h]},t.createSession=(e,n)=>{const r=(0,t.createSessionAllocate)(e);return(0,t.createSessionFinalize)(r,n)},t.releaseSession=e=>{const t=(0,s.getInstance)(),n=a.get(e);if(!n)throw new Error("invalid session id");const r=n[0],o=n[1],i=n[2];o.forEach(t._OrtFree),i.forEach(t._OrtFree),t._OrtReleaseSession(r),a.delete(e)};const c=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"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${e}`)}},u=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 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${e}`)}},l=e=>{switch(e){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}};t.run=(e,t,n,o,f)=>{const d=(0,s.getInstance)(),h=a.get(e);if(!h)throw new Error("invalid session id");const p=h[0],m=h[1],w=h[2],g=t.length,v=o.length;let y=0,_=[];const b=[],x=[];try{[y,_]=(0,r.setRunOptions)(f);for(let e=0;e<g;e++){const t=n[e][0],r=n[e][1],o=n[e][2];let s,a;if(Array.isArray(o)){a=4*o.length,s=d._malloc(a),x.push(s);let e=s/4;for(let t=0;t<o.length;t++){if("string"!=typeof o[t])throw new TypeError(`tensor data at index ${t} is not a string`);d.HEAPU32[e++]=(0,i.allocWasmString)(o[t],x)}}else a=o.byteLength,s=d._malloc(a),x.push(s),d.HEAPU8.set(new Uint8Array(o.buffer,o.byteOffset,a),s);const u=d.stackSave(),l=d.stackAlloc(4*r.length);try{let e=l/4;r.forEach((t=>d.HEAP32[e++]=t));const n=d._OrtCreateTensor(c(t),s,a,l,r.length);if(0===n)throw new Error("Can't create a tensor");b.push(n)}finally{d.stackRestore(u)}}const e=d.stackSave(),s=d.stackAlloc(4*g),a=d.stackAlloc(4*g),h=d.stackAlloc(4*v),T=d.stackAlloc(4*v);try{let e=s/4,n=a/4,r=h/4,i=T/4;for(let r=0;r<g;r++)d.HEAPU32[e++]=b[r],d.HEAPU32[n++]=m[t[r]];for(let e=0;e<v;e++)d.HEAPU32[r++]=0,d.HEAPU32[i++]=w[o[e]];let c=d._OrtRun(p,a,s,g,T,v,h,y);const f=[];if(0===c)for(let e=0;e<v;e++){const t=d.HEAPU32[h/4+e],n=d.stackSave(),r=d.stackAlloc(16);let o,i=0;try{if(c=d._OrtGetTensorData(t,r,r+4,r+8,r+12),0!==c)throw new Error(`Can't access output tensor data. error code = ${c}`);let e=r/4;const n=d.HEAPU32[e++];i=d.HEAPU32[e++];const s=d.HEAPU32[e++],a=d.HEAPU32[e++],h=[];for(let e=0;e<a;e++)h.push(d.HEAPU32[s/4+e]);d._OrtFree(s);const p=0===h.length?1:h.reduce(((e,t)=>e*t));if(o=u(n),"string"===o){const e=[];let t=i/4;for(let n=0;n<p;n++){const r=d.HEAPU32[t++],o=n===p-1?void 0:d.HEAPU32[t]-r;e.push(d.UTF8ToString(r,o))}f.push([o,h,e])}else{const e=new(l(o))(p);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(d.HEAPU8.subarray(i,i+e.byteLength)),f.push([o,h,e])}}finally{d.stackRestore(n),"string"===o&&i&&d._free(i),d._OrtReleaseTensor(t)}}if(0===c)return f;throw new Error(`failed to call OrtRun(). error code = ${c}.`)}finally{d.stackRestore(e)}}finally{b.forEach(d._OrtReleaseTensor),x.forEach(d._free),d._OrtReleaseRunOptions(y),_.forEach(d._free)}},t.endProfiling=e=>{const t=(0,s.getInstance)(),n=a.get(e);if(!n)throw new Error("invalid session id");const r=n[0],o=t._OrtEndProfiling(r);if(0===o)throw new Error("Can't get an profile file name");t._OrtFree(o)},t.extractTransferableBuffers=e=>{const t=[];for(const n of e){const e=n[2];!Array.isArray(e)&&e.buffer&&t.push(e.buffer)}return t}},6361:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:true,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return o(t,e),t},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true}),t.dispose=t.getInstance=t.initializeWebAssembly=void 0;const a=i(n(6449)),c=s(n(932)),u=n(3474);let l,f=false,d=false,h=false;const p=(e,t)=>t?e?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":e?"ort-wasm-simd.wasm":"ort-wasm.wasm";t.initializeWebAssembly=async e=>{if(f)return Promise.resolve();if(d)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(h)throw new Error("previous call to 'initializeWebAssembly()' failed.");d=true;const t=e.initTimeout,r=e.numThreads,o=e.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(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(e){return false}})(),s=o&&(()=>{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(e){return false}})(),m="string"==typeof e.wasmPaths?e.wasmPaths:void 0,w=p(false,i),g=p(s,i),v="object"==typeof e.wasmPaths?e.wasmPaths[g]:void 0;let y=false;const _=[];if(t>0&&_.push(new Promise((e=>{setTimeout((()=>{y=true,e()}),t)}))),_.push(new Promise(((e,t)=>{const r=i?u:c.default,o={locateFile:(e,t)=>i&&e.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(4154)],{type:"text/javascript"})):e===w?null!=v?v:(null!=m?m:t)+g:t+e};if(i)if("undefined"==typeof Blob)o.mainScriptUrlOrBlob=a.join("/","ort-wasm-threaded.js");else{const e=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;o.mainScriptUrlOrBlob=new Blob([e],{type:"text/javascript"})}r(o).then((t=>{d=false,f=true,l=t,e()}),(e=>{d=false,h=true,t(e)}))}))),await Promise.race(_),y)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},t.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},t.dispose=()=>{var e;!f||d||h||(d=true,null===(e=l.PThread)||void 0===e||e.terminateAllThreads(),l=void 0,d=false,f=false,h=true)}},9710:(e,t,n)=>{n.d(t,{Z:()=>i});var r=n(477),o=n.n(r);function i(){return o()('/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var t={474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return j.buffer!=D&&N(j.buffer),P}function r(){return j.buffer!=D&&N(j.buffer),U}function a(){return j.buffer!=D&&N(j.buffer),F}function i(){return j.buffer!=D&&N(j.buffer),I}function o(){return j.buffer!=D&&N(j.buffer),W}var u,c,s;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){c=t,s=e}));var l,f,p,h,d,y,b=Object.assign({},u),m="./this.program",g=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function S(t){return u.locateFile?u.locateFile(t,A):A+t}if(_){let e;A=w?n(908).dirname(A)+"/":"//",y=()=>{d||(h=n(384),d=n(908))},l=function(t,e){return y(),t=d.normalize(t),h.readFileSync(t,e?void 0:"utf8")},p=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),f=(t,e,n)=>{y(),t=d.normalize(t),h.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1<process.argv.length&&(m=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(t){if(!(t instanceof ct))throw t})),process.on("unhandledRejection",(function(t){throw t})),g=(t,e)=>{if(Q())throw process.exitCode=t,e;e instanceof ct||x("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(925)}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}n.g.Worker=e.Worker}else(v||w)&&(w?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptDir&&(A=_scriptDir),A=0!==A.indexOf("blob:")?A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var T=console.log.bind(console),E=console.warn.bind(console);_&&(y(),T=t=>h.writeSync(1,t+"\\n"),E=t=>h.writeSync(2,t+"\\n"));var M,C=u.print||T,x=u.printErr||E;Object.assign(u,b),b=null,u.thisProgram&&(m=u.thisProgram),u.quit&&(g=u.quit),u.wasmBinary&&(M=u.wasmBinary);var R=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&at("no native wasm support detected");var j,k,D,P,U,F,I,W,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16<n-e&&t.buffer&&L)return L.decode(t.buffer instanceof SharedArrayBuffer?t.slice(e,n):t.subarray(e,n));for(r="";e<n;){var a=t[e++];if(128&a){var i=63&t[e++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|i);else{var o=63&t[e++];65536>(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function Y(t,e){return(t>>>=0)?z(r(),t,e):""}function B(t,e,n,r){if(!(0<r))return 0;var a=n>>>=0;r=n+r-1;for(var i=0;i<t.length;++i){var o=t.charCodeAt(i);if(55296<=o&&57343>=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function G(t){for(var e=0,n=0;n<t.length;++n){var r=t.charCodeAt(n);127>=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function N(t){D=t,u.HEAP8=P=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=F=new Int32Array(t),u.HEAPU8=U=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=I=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=W=new Float64Array(t)}O&&(D=u.buffer);var V=u.INITIAL_MEMORY||16777216;if(O)j=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)j=u.wasmMemory;else if(!((j=new WebAssembly.Memory({initial:V/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");j&&(D=j.buffer),V=D.byteLength,N(D);var $,q=[],X=[],J=[],Z=[];function Q(){return R||!1}function K(){var t=u.preRun.shift();q.unshift(t)}var tt,et=0,nt=null,rt=null;function at(t){throw O?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),x(t="Aborted("+t+")"),H=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),s(t),t}function it(){return tt.startsWith("data:application/octet-stream;base64,")}function ot(){var t=tt;try{if(t==tt&&M)return new Uint8Array(M);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){at(t)}}tt="ort-wasm-threaded.wasm",it()||(tt=S(tt));var ut={};function ct(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function st(t){(t=ht.Vb[t])||at(),ht.mc(t)}function lt(t){var e=ht.Cc();if(!e)return 6;ht.ac.push(e),ht.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function ft(t){if(O)return $t(1,1,t);Q()||(ht.oc(),u.onExit&&u.onExit(t),H=!0),g(t,new ct(t))}function pt(t,e){if(!e&&O)throw bt(t),"unwind";Q()||O||(me(),dt(J),be(0),re[1].length&&ae(1,10),re[2].length&&ae(2,10),ht.oc()),ft(t)}var ht={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&ht.Ec()},Pc:function(){},Ec:function(){ht.receiveObjectTransfer=ht.Gc,ht.threadInitTLS=ht.pc,ht.setExitStatus=ht.nc,R=!1},nc:function(){},oc:function(){for(var t of Object.values(ht.Vb))ht.mc(t);for(t of ht.Yb)t.terminate();ht.Yb=[]},mc:function(t){var e=t.Ub;delete ht.Vb[e],ht.Yb.push(t),ht.ac.splice(ht.ac.indexOf(t),1),t.Ub=0,Oe(e)},Gc:function(){},pc:function(){ht.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ht.Bc=t.Ub),n.targetThread&&n.targetThread!=he()){var a=ht.Vb[n.Qc];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?zt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?st(n.thread):"killThread"===r?(n=n.thread,r=ht.Vb[n],delete ht.Vb[n],r.terminate(),Oe(n),ht.ac.splice(ht.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ht.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?C("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&x("worker sent an unknown command "+r);ht.Bc=void 0},t.onerror=t=>{throw x("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},_&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||_scriptDir,wasmMemory:j,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");ht.Yb.push(new Worker(t))},Cc:function(){return 0==ht.Yb.length&&(ht.yc(),ht.Fc(ht.Yb[0])),ht.Yb.pop()}};function dt(t){for(;0<t.length;)t.shift()(u)}function yt(t){var e=Ee();return t=t(),Me(e),t}function bt(t){if(O)return $t(2,0,t);try{pt(t)}catch(t){t instanceof ct||"unwind"==t||g(1,t)}}u.PThread=ht,u.establishStackSpace=function(){var t=he(),e=a()[t+44>>2>>>0];t=a()[t+48>>2>>>0],Te(e,e-t),Me(e)};var mt=[];function gt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=$.get(t)),e}u.invokeEntryPoint=function(t,e){t=gt(t)(e),Q()?ht.nc(t):Ae(t)};var vt,wt,_t=[],Ot=0,At=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){i()[this.Sb+4>>2>>>0]=t},this.bc=function(){return i()[this.Sb+4>>2>>>0]},this.wc=function(t){i()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return i()[this.Sb+8>>2>>>0]},this.rc=function(){a()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(a(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(a(),this.Sb>>2,1)},this.cc=function(t){i()[this.Sb+16>>2>>>0]=t},this.tc=function(){return i()[this.Sb+16>>2>>>0]},this.vc=function(){if(Re(this.bc()))return i()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Tt(t){return ye(new St(t).Sb)}function Et(t,e,n,r){return O?$t(3,1,t,e,n,r):Mt(t,e,n,r)}function Mt(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:a},O?(t.Oc="spawnThread",postMessage(t,a),0):lt(t))}function Ct(t,e,n){return O?$t(4,1,t,e,n):0}function xt(t,e){if(O)return $t(5,1,t,e)}function Rt(t,e){if(O)return $t(6,1,t,e)}function jt(t,e,n){if(O)return $t(7,1,t,e,n)}function kt(t,e,n){return O?$t(8,1,t,e,n):0}function Dt(t,e){if(O)return $t(9,1,t,e)}function Pt(t,e,n){if(O)return $t(10,1,t,e,n)}function Ut(t,e,n,r){if(O)return $t(11,1,t,e,n,r)}function Ft(t,e,n,r){if(O)return $t(12,1,t,e,n,r)}function It(t,e,n,r){if(O)return $t(13,1,t,e,n,r)}function Wt(t){if(O)return $t(14,1,t)}function Ht(t,e){if(O)return $t(15,1,t,e)}function Lt(t,e,n){if(O)return $t(16,1,t,e,n)}function zt(t){Atomics.store(a(),t>>2,1),he()&&_e(t),Atomics.compareExchange(a(),t>>2,1,0)}function Yt(t){return i()[t>>>2]+4294967296*a()[t+4>>>2]}function Bt(t,e,n,r,a,i){return O?$t(17,1,t,e,n,r,a,i):-52}function Gt(t,e,n,r,a,i){if(O)return $t(18,1,t,e,n,r,a,i)}function Nt(t){var n=G(t)+1,r=de(n);return r&&B(t,e(),r,n),r}function Vt(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}if(O)return $t(19,1,t,e,n);var o=(new Date).getFullYear(),u=new Date(o,0,1),c=new Date(o,6,1);o=u.getTimezoneOffset();var s=c.getTimezoneOffset(),l=Math.max(o,s);a()[t>>2>>>0]=60*l,a()[e>>2>>>0]=Number(o!=s),t=r(u),e=r(c),t=Nt(t),e=Nt(e),s<o?(i()[n>>2>>>0]=t,i()[n+4>>2>>>0]=e):(i()[n>>2>>>0]=e,i()[n+4>>2>>>0]=t)}function $t(t,e){var n=arguments.length-2,r=arguments;return yt((()=>{for(var a=Ce(8*n),i=a>>3,u=0;u<n;u++){var c=r[2+u];o()[i+u>>>0]=c}return we(t,n,a,e)}))}u.executeNotifiedProxyingQueue=zt,wt=_?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:O?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var qt,Xt=[],Jt={};function Zt(){if(!qt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Jt)void 0===Jt[t]?delete e[t]:e[t]=Jt[t];var n=[];for(t in e)n.push(t+"="+e[t]);qt=n}return qt}function Qt(t,n){if(O)return $t(20,1,t,n);var r=0;return Zt().forEach((function(a,o){var u=n+r;for(o=i()[t+4*o>>2>>>0]=u,u=0;u<a.length;++u)e()[o++>>0>>>0]=a.charCodeAt(u);e()[o>>0>>>0]=0,r+=a.length+1})),0}function Kt(t,e){if(O)return $t(21,1,t,e);var n=Zt();i()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),i()[e>>2>>>0]=r,0}function te(t){return O?$t(22,1,t):52}function ee(t,e,n,r){return O?$t(23,1,t,e,n,r):52}function ne(t,e,n,r,a){return O?$t(24,1,t,e,n,r,a):70}var re=[null,[],[]];function ae(t,e){var n=re[t];0===e||10===e?((1===t?C:x)(z(n,0)),n.length=0):n.push(e)}function ie(t,e,n,a){if(O)return $t(25,1,t,e,n,a);for(var o=0,u=0;u<n;u++){var c=i()[e>>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l<s;l++)ae(t,r()[c+l>>>0]);o+=s}return i()[a>>2>>>0]=o,0}var oe=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var ce=[31,29,31,30,31,30,31,31,30,31,30,31],se=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,i){function o(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.length<e;)t=n[0]+t;return t}function u(t,e){return o(t,e,"0")}function c(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function s(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function l(t){var e=t.Wb;for(t=new Date(new Date(t.Xb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(ue(t.getFullYear())?ce:se)[n];if(!(e>r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=c(e,t)?0>=c(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var f=a()[i+40>>2>>>0];for(var p in i={Lc:a()[i>>2>>>0],Kc:a()[i+4>>2>>>0],dc:a()[i+8>>2>>>0],jc:a()[i+12>>2>>>0],ec:a()[i+16>>2>>>0],Xb:a()[i+20>>2>>>0],Tb:a()[i+24>>2>>>0],Wb:a()[i+28>>2>>>0],Rc:a()[i+32>>2>>>0],Jc:a()[i+36>>2>>>0],Mc:f?Y(f):""},r=Y(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(t){return h[t.Tb].substring(0,3)},"%A":function(t){return h[t.Tb]},"%b":function(t){return d[t.ec].substring(0,3)},"%B":function(t){return d[t.ec]},"%C":function(t){return u((t.Xb+1900)/100|0,2)},"%d":function(t){return u(t.jc,2)},"%e":function(t){return o(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return u(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12<t&&(t-=12),u(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.ec-1;e+=(ue(t.Xb+1900)?ce:se)[n++]);return u(t.jc+e,3)},"%m":function(t){return u(t.ec+1,2)},"%M":function(t){return u(t.Kc,2)},"%n":function(){return"\\n"},"%p":function(t){return 0<=t.dc&&12>t.dc?"AM":"PM"},"%S":function(t){return u(t.Lc,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return u(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return u(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return u(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](i)));return p=function(t){var e=Array(G(t)+1);return B(t,e,0,e.length),e}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(t,n){e().set(t,n>>>0)}(p,t),p.length-1)}ht.fc();var fe=[null,ft,bt,Et,Ct,xt,Rt,jt,kt,Dt,Pt,Ut,Ft,It,Wt,Ht,Lt,Bt,Gt,Vt,Qt,Kt,te,ee,ne,ie],pe={b:function(t){return de(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),Ot--),t.ic(!1),_t.push(t),t.sc(),t.vc()},ma:function(t){throw x("Unexpected exception thrown, this is not properly supported - aborting"),H=!0,t},x:function(){Se(0);var t=_t.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&>(e)(t.Zb),Tt(t.Zb)}At=0},e:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},l:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},h:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},t:Tt,M:function(){var t=_t.pop();t||at("no exception to throw");var e=t.Zb;throw t.kc()||(_t.push(t),t.ic(!0),t.hc(!1),Ot++),At=e,e},c:function(t,e,n){throw new St(t).fc(e,n),At=t,Ot++,t},pa:function(){return Ot},Fa:function(t){ge(t,!w,1,!v),ht.pc()},T:function(t){O?postMessage({cmd:"cleanupThread",thread:t}):st(t)},xa:Mt,j:function(t){throw At||(At=t),t},H:Ct,Ma:xt,ua:Rt,wa:jt,oa:kt,Ka:Dt,Ca:Pt,Ja:Ut,V:Ft,va:It,sa:Wt,La:Ht,ta:Lt,Ta:function(){},X:function(){at("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ua:function(){at("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},W:function(){return Date.now()},ya:function(){return 2097152},Oa:function(){return!0},za:function(t,e,n,r){if(t==e)setTimeout((()=>zt(r)));else if(O)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ht.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getUTCSeconds(),a()[e+4>>2>>>0]=t.getUTCMinutes(),a()[e+8>>2>>>0]=t.getUTCHours(),a()[e+12>>2>>>0]=t.getUTCDate(),a()[e+16>>2>>>0]=t.getUTCMonth(),a()[e+20>>2>>>0]=t.getUTCFullYear()-1900,a()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),a()[e+20>>2>>>0]=t.getFullYear()-1900,a()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;a()[e+28>>2>>>0]=r,a()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),a()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(a()[t+20>>2>>>0]+1900,a()[t+16>>2>>>0],a()[t+12>>2>>>0],a()[t+8>>2>>>0],a()[t+4>>2>>>0],a()[t>>2>>>0],0),n=a()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),c=Math.min(u,o);return 0>n?a()[t+32>>2>>>0]=Number(o!=u&&c==r):0<n!=(c==r)&&(o=Math.max(u,o),e.setTime(e.getTime()+6e4*((0<n?c:o)-r))),a()[t+24>>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,a()[t+28>>2>>>0]=n,a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Bt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Vt(e,n,r))},y:function(){at("")},U:function(){if(!_&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,_&&(t="warning: "+t),x(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Xt.length=e,n>>=3;for(var r=0;r<e;r++)Xt[r]=o()[n+r>>>0];return(0>t?ut[-t-1]:fe[t]).apply(null,Xt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760<t)return!1;for(var n=1;4>=n;n*=2){var a=e*(1+.2/n);a=Math.min(a,t+100663296);var i=Math;a=Math.max(t,a),i=i.min.call(i,4294901760,a+(65536-a%65536)%65536);t:{try{j.grow(i-D.byteLength+65535>>>16),N(j.buffer);var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Kt,J:pt,I:te,S:ee,ga:ne,R:ie,d:function(){return oe},na:function t(r,a){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(_)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>at("randomDevice")}());for(var i=0;i<a;i++)e()[r+i>>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var a=Ee();try{return gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,a){var i=Ee();try{return gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,a,i,o){var u=Ee();try{return gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,a,i,o,u){var c=Ee();try{return gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{return gt(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=Ee();try{return He(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,a,i,o){var u=Ee();try{return ke(t,e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,a){var i=Ee();try{return Le(t,e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var a=Ee();try{return Ie(t,e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return je(t)}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return We(t,e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return De(t,e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,a){var i=Ee();try{gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,a,i){var o=Ee();try{gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,a,i,o){var u=Ee();try{gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,a,i,o,u){var c=Ee();try{gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,a,i,o,u,c){var s=Ee();try{gt(t)(e,n,r,a,i,o,u,c)}catch(t){if(Me(s),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l){var f=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(Me(f),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(Me(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,a,i,o,u){var c=Ee();try{Pe(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{Fe(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,a,i){var o=Ee();try{Ue(t,e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:j||u.wasmMemory,G:function(t){oe=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ht.qc.push(u.asm.sb),$=u.asm.ub,X.unshift(u.asm.Va),k=e,O||(et--,u.monitorRunDependencies&&u.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!M&&(v||w)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+tt+"\'";return t.arrayBuffer()})).catch((function(){return ot()}));if(f)return new Promise((function(t,e){f(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return ot()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){x("failed to asynchronously prepare wasm: "+t),at(t)}))}var r={a:pe};if(O||(et++,u.monitorRunDependencies&&u.monitorRunDependencies(et)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return x("Module.instantiateWasm callback failed with error: "+t),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||it()||tt.startsWith("file://")||_||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return x("wasm streaming compile failed: "+t),x("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var he=u._pthread_self=function(){return(he=u._pthread_self=u.asm.ob).apply(null,arguments)},de=u._malloc=function(){return(de=u._malloc=u.asm.pb).apply(null,arguments)},ye=u._free=function(){return(ye=u._free=u.asm.qb).apply(null,arguments)},be=u._fflush=function(){return(be=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var me=u.___funcs_on_exit=function(){return(me=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ge=u.__emscripten_thread_init=function(){return(ge=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},_e=u.__emscripten_proxy_execute_task_queue=function(){return(_e=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Oe=u.__emscripten_thread_free_data=function(){return(Oe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Ae=u.__emscripten_thread_exit=function(){return(Ae=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Te=u._emscripten_stack_set_limits=function(){return(Te=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ee=u.stackSave=function(){return(Ee=u.stackSave=u.asm.Db).apply(null,arguments)},Me=u.stackRestore=function(){return(Me=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ce=u.stackAlloc=function(){return(Ce=u.stackAlloc=u.asm.Fb).apply(null,arguments)},xe=u.___cxa_can_catch=function(){return(xe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},Re=u.___cxa_is_pointer_type=function(){return(Re=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},je=u.dynCall_j=function(){return(je=u.dynCall_j=u.asm.Ib).apply(null,arguments)},ke=u.dynCall_iiiiij=function(){return(ke=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},De=u.dynCall_jii=function(){return(De=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Pe=u.dynCall_viiiiij=function(){return(Pe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Ue=u.dynCall_vjji=function(){return(Ue=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},Fe=u.dynCall_viiijjjii=function(){return(Fe=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ie=u.dynCall_iij=function(){return(Ie=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},We=u.dynCall_ji=function(){return(We=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},He=u.dynCall_iiiiiij=function(){return(He=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Le=u.dynCall_iiij=function(){return(Le=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function ze(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!H)&&(O||dt(X),c(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!O)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Z.unshift(t)}dt(Z)}}if(!(0<et))if(O)c(u),O||dt(X),postMessage({cmd:"loaded"});else{if(u.preRun)for("function"==typeof u.preRun&&(u.preRun=[u.preRun]);u.preRun.length;)K();dt(q),0<et||(u.setStatus?(u.setStatus("Running..."),setTimeout((function(){setTimeout((function(){u.setStatus("")}),1),t()}),1)):t())}}if(u.UTF8ToString=Y,u.stringToUTF8=function(t,e,n){return B(t,r(),e,n)},u.lengthBytesUTF8=G,u.keepRuntimeAlive=Q,u.wasmMemory=j,u.stackSave=Ee,u.stackRestore=Me,u.stackAlloc=Ce,u.ExitStatus=ct,u.PThread=ht,rt=function t(){ve||ze(),ve||(rt=t)},u.preInit)for("function"==typeof u.preInit&&(u.preInit=[u.preInit]);0<u.preInit.length;)u.preInit.pop()();return ze(),t.ready});t.exports=r},932:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,a;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,a=e}));var i,o,u,c,s,l,f=Object.assign({},e),p="./this.program",h=(t,e)=>{throw e},d="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=y?n(908).dirname(m)+"/":"//",l=()=>{s||(c=n(384),s=n(908))},i=function(t,e){return l(),t=s.normalize(t),c.readFileSync(t,e?void 0:"utf8")},u=t=>((t=i(t,!0)).buffer||(t=new Uint8Array(t)),t),o=(t,e,n)=>{l(),t=s.normalize(t),c.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1<process.argv.length&&(p=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(t){if(!(t instanceof J))throw t})),process.on("unhandledRejection",(function(t){throw t})),h=(t,e)=>{if(_||0<L)throw process.exitCode=t,e;e instanceof J||w("exiting due to exception: "+e),process.exit(t)},e.inspect=function(){return"[Emscripten Module object]"}):(d||y)&&(y?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),_scriptDir&&(m=_scriptDir),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",i=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},y&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),o=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var g,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,f),f=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(h=e.quit),e.wasmBinary&&(g=e.wasmBinary);var _=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&V("no native wasm support detected");var O,A,S,T,E,M,C=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16<n-e&&t.buffer&&x)return x.decode(t.subarray(e,n));for(r="";e<n;){var a=t[e++];if(128&a){var i=63&t[e++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|i);else{var o=63&t[e++];65536>(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function j(t,e){return(t>>>=0)?R(T,t,e):""}function k(t,e,n,r){if(!(0<r))return 0;var a=n>>>=0;r=n+r-1;for(var i=0;i<t.length;++i){var o=t.charCodeAt(i);if(55296<=o&&57343>=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function D(t){for(var e=0,n=0;n<t.length;++n){var r=t.charCodeAt(n);127>=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function P(){var t=O.buffer;A=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=E=new Int32Array(t),e.HEAPU8=T=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=M=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var U,F=[],I=[],W=[],H=[],L=0;function z(){var t=e.preRun.shift();F.unshift(t)}var Y,B=0,G=null,N=null;function V(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),C=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),a(t),t}function $(){return Y.startsWith("data:application/octet-stream;base64,")}if(Y="ort-wasm.wasm",!$()){var q=Y;Y=e.locateFile?e.locateFile(q,m):m+q}function X(){var t=Y;try{if(t==Y&&g)return new Uint8Array(g);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){V(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0<t.length;)t.shift()(e)}var Q=[],K=0,tt=0;function et(t){this.Db=t,this.zb=t-24,this.Ub=function(t){M[this.zb+4>>2>>>0]=t},this.Eb=function(){return M[this.zb+4>>2>>>0]},this.Sb=function(t){M[this.zb+8>>2>>>0]=t},this.Wb=function(){return M[this.zb+8>>2>>>0]},this.Tb=function(){E[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){E[this.zb>>2>>>0]+=1},this.Xb=function(){var t=E[this.zb>>2>>>0];return E[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){M[this.zb+16>>2>>>0]=t},this.Ob=function(){return M[this.zb+16>>2>>>0]},this.Qb=function(){if(Mt(this.Eb()))return M[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return vt(new et(t).zb)}var rt=[];function at(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=U.get(t)),e}function it(t){var e=D(t)+1,n=gt(e);return n&&k(t,S,n,e),n}var ot={};function ut(){if(!ct){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(t in ot)void 0===ot[t]?delete e[t]:e[t]=ot[t];var n=[];for(t in e)n.push(t+"="+e[t]);ct=n}return ct}var ct,st=[null,[],[]];function lt(t,e){var n=st[t];0===e||10===e?((1===t?v:w)(R(n,0)),n.length=0):n.push(e)}var ft=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ht=[31,29,31,30,31,30,31,31,30,31,30,31],dt=[31,28,31,30,31,30,31,31,30,31,30,31];function yt(t,e,n,r){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.length<e;)t=n[0]+t;return t}function i(t,e){return a(t,e,"0")}function o(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function u(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function c(t){var e=t.Bb;for(t=new Date(new Date(t.Cb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(pt(t.getFullYear())?ht:dt)[n];if(!(e>r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=u(new Date(t.getFullYear(),0,4)),n=u(n),0>=o(e,t)?0>=o(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var s=E[r+40>>2>>>0];for(var l in r={$b:E[r>>2>>>0],Zb:E[r+4>>2>>>0],Gb:E[r+8>>2>>>0],Kb:E[r+12>>2>>>0],Hb:E[r+16>>2>>>0],Cb:E[r+20>>2>>>0],Ab:E[r+24>>2>>>0],Bb:E[r+28>>2>>>0],bc:E[r+32>>2>>>0],Yb:E[r+36>>2>>>0],ac:s?j(s):""},n=j(n),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),s[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in s={"%a":function(t){return f[t.Ab].substring(0,3)},"%A":function(t){return f[t.Ab]},"%b":function(t){return p[t.Hb].substring(0,3)},"%B":function(t){return p[t.Hb]},"%C":function(t){return i((t.Cb+1900)/100|0,2)},"%d":function(t){return i(t.Kb,2)},"%e":function(t){return a(t.Kb,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return i(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12<t&&(t-=12),i(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.Hb-1;e+=(pt(t.Cb+1900)?ht:dt)[n++]);return i(t.Kb+e,3)},"%m":function(t){return i(t.Hb+1,2)},"%M":function(t){return i(t.Zb,2)},"%n":function(){return"\\n"},"%p":function(t){return 0<=t.Gb&&12>t.Gb?"AM":"PM"},"%S":function(t){return i(t.$b,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return i(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&pt(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&pt(t.Cb%400-1))&&e++}return i(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return i(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),s)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),s[l](r)));return l=function(t){var e=Array(D(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\\0\\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return gt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),K--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,t},w:function(){Ot(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&at(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},k:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},g:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},s:nt,L:function(){var t=Q.pop();t||V("no exception to throw");var e=t.Db;throw t.Lb()||(Q.push(t),t.Jb(!0),t.Ib(!1),K++),tt=e,e},b:function(t,e,n){throw new et(t).Rb(e,n),tt=t,K++,t},la:function(){return K},i:function(t){throw tt||(tt=t),t},H:function(){return 0},Ba:function(){},pa:function(){},ra:function(){},ka:function(){return 0},za:function(){},ua:function(){},ya:function(){},R:function(){},qa:function(){},na:function(){},Aa:function(){},oa:function(){},Ha:function(){},Ja:function(){V("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ia:function(){V("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},S:function(){return Date.now()},Ca:function(){return!0},Da:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getUTCSeconds(),E[e+4>>2>>>0]=t.getUTCMinutes(),E[e+8>>2>>>0]=t.getUTCHours(),E[e+12>>2>>>0]=t.getUTCDate(),E[e+16>>2>>>0]=t.getUTCMonth(),E[e+20>>2>>>0]=t.getUTCFullYear()-1900,E[e+24>>2>>>0]=t.getUTCDay(),E[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),E[e+20>>2>>>0]=t.getFullYear()-1900,E[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);E[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,E[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(E[t+20>>2>>>0]+1900,E[t+16>>2>>>0],E[t+12>>2>>>0],E[t+8>>2>>>0],E[t+4>>2>>>0],E[t>>2>>>0],0),n=E[t+32>>2>>>0],r=e.getTimezoneOffset(),a=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1).getTimezoneOffset(),o=a.getTimezoneOffset(),u=Math.min(o,i);return 0>n?E[t+32>>2>>>0]=Number(i!=o&&u==r):0<n!=(u==r)&&(i=Math.max(o,i),e.setTime(e.getTime()+6e4*((0<n?u:i)-r))),E[t+24>>2>>>0]=e.getDay(),E[t+28>>2>>>0]=(e.getTime()-a.getTime())/864e5|0,E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}var a=(new Date).getFullYear(),i=new Date(a,0,1),o=new Date(a,6,1);a=i.getTimezoneOffset();var u=o.getTimezoneOffset();E[t>>2>>>0]=60*Math.max(a,u),E[e>>2>>>0]=Number(a!=u),t=r(i),e=r(o),t=it(t),e=it(e),u<a?(M[n>>2>>>0]=t,M[n+4>>2>>>0]=e):(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t)}(e,n,r))},B:function(){V("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){T.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=T.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var a=Math;r=Math.max(t,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);t:{try{O.grow(a-A.byteLength+65535>>>16),P();var i=1;break t}catch(t){}i=void 0}if(i)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,a){var i=e+n;for(a=M[t+4*a>>2>>>0]=i,i=0;i<r.length;++i)S[a++>>0>>>0]=r.charCodeAt(i);S[a>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();M[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),M[e>>2>>>0]=r,0},ba:function(t){_||0<L||(_t(),Z(W),wt(0),st[1].length&<(1,10),st[2].length&<(2,10)),_||0<L||(e.onExit&&e.onExit(t),C=!0),h(t,new J(t))},E:function(){return 52},Q:function(){return 52},ca:function(){return 70},P:function(t,e,n,r){for(var a=0,i=0;i<n;i++){var o=M[e>>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c<u;c++)lt(t,T[o+c>>>0]);a+=u}return M[r>>2>>>0]=a,0},c:function(){return ft},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>V("randomDevice")}());for(var a=0;a<r;a++)S[e+a>>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},fa:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},J:function(t){var e=At();try{return at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},e:function(t,e){var n=At();try{return at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},N:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},O:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},j:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},o:function(t,e,n,r){var a=At();try{return at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},p:function(t,e,n,r,a){var i=At();try{return at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},M:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},r:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},v:function(t,e,n,r,a,i,o){var u=At();try{return at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},K:function(t,e,n,r,a,i,o,u){var c=At();try{return at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{return at(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},X:function(t,e,n,r,a,i,o,u){var c=At();try{return Ft(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},V:function(t,e,n,r,a,i,o){var u=At();try{return xt(t,e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},U:function(t,e,n,r,a){var i=At();try{return It(t,e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},Z:function(t,e,n,r){var a=At();try{return Pt(t,e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},W:function(t){var e=At();try{return Ct(t)}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},Y:function(t,e){var n=At();try{return Ut(t,e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},T:function(t,e,n){var r=At();try{return Rt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},f:function(t){var e=At();try{at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},q:function(t,e){var n=At();try{at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},h:function(t,e,n){var r=At();try{at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},da:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},l:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},t:function(t,e,n,r,a){var i=At();try{at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},u:function(t,e,n,r,a,i){var o=At();try{at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},x:function(t,e,n,r,a,i,o){var u=At();try{at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},z:function(t,e,n,r,a,i,o,u){var c=At();try{at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},ga:function(t,e,n,r,a,i,o,u,c){var s=At();try{at(t)(e,n,r,a,i,o,u,c)}catch(t){if(St(s),t!==t+0)throw t;Ot(1,0)}},A:function(t,e,n,r,a,i,o,u,c,s,l){var f=At();try{at(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(St(f),t!==t+0)throw t;Ot(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=At();try{at(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(St(b),t!==t+0)throw t;Ot(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=At();try{jt(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},_:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{Dt(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},$:function(t,e,n,r,a,i){var o=At();try{kt(t,e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},n:function(t){return t},F:function(t){ft=t},ha:yt,y:function(t,e,n,r){return yt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,O=e.asm.Ka,P(),U=e.asm.ib,I.unshift(e.asm.La),B--,e.monitorRunDependencies&&e.monitorRunDependencies(B),0==B&&(null!==G&&(clearInterval(G),G=null),N&&(t=N,N=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!g&&(d||y)){if("function"==typeof fetch&&!Y.startsWith("file://"))return fetch(Y,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+Y+"\'";return t.arrayBuffer()})).catch((function(){return X()}));if(o)return new Promise((function(t,e){o(Y,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return X()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),V(t)}))}var i={a:bt};if(B++,e.monitorRunDependencies&&e.monitorRunDependencies(B),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(g||"function"!=typeof WebAssembly.instantiateStreaming||$()||Y.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,gt=e._malloc=function(){return(gt=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},_t=e.___funcs_on_exit=function(){return(_t=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Ot=e._setThrew=function(){return(Ot=e._setThrew=e.asm.jb).apply(null,arguments)},At=e.stackSave=function(){return(At=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Tt=e.stackAlloc=function(){return(Tt=e.stackAlloc=e.asm.mb).apply(null,arguments)},Et=e.___cxa_can_catch=function(){return(Et=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Mt=e.___cxa_is_pointer_type=function(){return(Mt=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Ct=e.dynCall_j=function(){return(Ct=e.dynCall_j=e.asm.pb).apply(null,arguments)},xt=e.dynCall_iiiiij=function(){return(xt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Rt=e.dynCall_jii=function(){return(Rt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},jt=e.dynCall_viiiiij=function(){return(jt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Dt=e.dynCall_viiijjjii=function(){return(Dt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Pt=e.dynCall_iij=function(){return(Pt=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Ut=e.dynCall_ji=function(){return(Ut=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Ft=e.dynCall_iiiiiij=function(){return(Ft=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},It=e.dynCall_iiij=function(){return(It=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function Wt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!C)){if(Z(I),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();H.unshift(t)}Z(H)}}if(!(0<B)){if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)z();Z(F),0<B||(e.setStatus?(e.setStatus("Running..."),setTimeout((function(){setTimeout((function(){e.setStatus("")}),1),t()}),1)):t())}}if(e.UTF8ToString=j,e.stringToUTF8=function(t,e,n){return k(t,T,e,n)},e.lengthBytesUTF8=D,e.stackSave=At,e.stackRestore=St,e.stackAlloc=Tt,N=function t(){mt||Wt(),mt||(N=t)},e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);0<e.preInit.length;)e.preInit.pop()();return Wt(),t.ready});t.exports=r},967:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,a)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,i])=>{const o=n?n+t:t;if("object"==typeof i)(0,e.iterateExtraOptions)(i,o+".",r,a);else if("string"==typeof i||"number"==typeof i)a(o,i.toString());else{if("boolean"!=typeof i)throw new Error("Can\'t handle extra config type: "+typeof i);a(o,i?"1":"0")}}))}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setRunOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(u.terminate=!1);let i=0;if(void 0!==(null==t?void 0:t.tag)&&(i=(0,a.allocWasmString)(t.tag,o)),n=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,i),0===n)throw new Error("Can\'t create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddRunConfigEntry(n,i,u))throw new Error(`Can\'t set a run config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),o.forEach(e._free),t}}},919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setSessionOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(u);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(u.graphOptimizationLevel="all");const c=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(u.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(u.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(u.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(u.executionMode="sequential");const s=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(u.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,a.allocWasmString)(t.logId,o)),void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(u.enableProfiling=!1),n=e._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,l,u.logSeverityLevel,u.logVerbosityLevel),0===n)throw new Error("Can\'t create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const o=(0,a.allocWasmString)(e,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(t,o))throw new Error(`Can\'t append execution provider: ${e}`)}})(n,t.executionProviders,o),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddSessionConfigEntry(n,i,u))throw new Error(`Can\'t set a session config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),o.forEach(e._free),t}}},983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(t)+1,i=n._malloc(a);return n.stringToUTF8(t,i,a),e.push(i),i}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),a=n(919),i=n(983),o=n(361);e.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;e.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,a.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],i),0===r)throw new Error("Can\'t create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const s=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],h=[],d=[];for(let t=0;t<s;t++){const e=n._OrtGetInputName(r,t);if(0===e)throw new Error("Can\'t get an input name");p.push(e),f.push(n.UTF8ToString(e))}for(let t=0;t<l;t++){const e=n._OrtGetOutputName(r,t);if(0===e)throw new Error("Can\'t get an output name");d.push(e),h.push(n.UTF8ToString(e))}return u.set(r,[r,p,d]),[r,f,h]},e.createSession=(t,n)=>{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],i=n[2];a.forEach(e._OrtFree),i.forEach(e._OrtFree),e._OrtReleaseSession(r),u.delete(t)};const c=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,a,f)=>{const p=(0,o.getInstance)(),h=u.get(t);if(!h)throw new Error("invalid session id");const d=h[0],y=h[1],b=h[2],m=e.length,g=a.length;let v=0,w=[];const _=[],O=[];try{[v,w]=(0,r.setRunOptions)(f);for(let t=0;t<m;t++){const e=n[t][0],r=n[t][1],a=n[t][2];let o,u;if(Array.isArray(a)){u=4*a.length,o=p._malloc(u),O.push(o);let t=o/4;for(let e=0;e<a.length;e++){if("string"!=typeof a[e])throw new TypeError(`tensor data at index ${e} is not a string`);p.HEAPU32[t++]=(0,i.allocWasmString)(a[e],O)}}else u=a.byteLength,o=p._malloc(u),O.push(o),p.HEAPU8.set(new Uint8Array(a.buffer,a.byteOffset,u),o);const s=p.stackSave(),l=p.stackAlloc(4*r.length);try{let t=l/4;r.forEach((e=>p.HEAP32[t++]=e));const n=p._OrtCreateTensor(c(e),o,u,l,r.length);if(0===n)throw new Error("Can\'t create a tensor");_.push(n)}finally{p.stackRestore(s)}}const t=p.stackSave(),o=p.stackAlloc(4*m),u=p.stackAlloc(4*m),h=p.stackAlloc(4*g),A=p.stackAlloc(4*g);try{let n=o/4,r=u/4,i=h/4,c=A/4;for(let t=0;t<m;t++)p.HEAPU32[n++]=_[t],p.HEAPU32[r++]=y[e[t]];for(let t=0;t<g;t++)p.HEAPU32[i++]=0,p.HEAPU32[c++]=b[a[t]];let f=p._OrtRun(d,u,o,m,A,g,h,v);const w=[];if(0===f)for(let t=0;t<g;t++){const e=p.HEAPU32[h/4+t],n=p.stackSave(),r=p.stackAlloc(16);let a,i=0;try{if(f=p._OrtGetTensorData(e,r,r+4,r+8,r+12),0!==f)throw new Error(`Can\'t access output tensor data. error code = ${f}`);let t=r/4;const o=p.HEAPU32[t++];i=p.HEAPU32[t++];const u=p.HEAPU32[t++],c=p.HEAPU32[t++],h=[];for(let t=0;t<c;t++)h.push(p.HEAPU32[u/4+t]);p._OrtFree(u);const d=0===h.length?1:h.reduce(((t,e)=>t*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n<d;n++){const r=p.HEAPU32[e++],a=n===d-1?void 0:p.HEAPU32[e]-r;t.push(p.UTF8ToString(r,a))}w.push([a,h,t])}else{const t=new(l(a))(d);new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(p.HEAPU8.subarray(i,i+t.byteLength)),w.push([a,h,t])}}finally{p.stackRestore(n),"string"===a&&i&&p._free(i),p._OrtReleaseTensor(e)}}if(0===f)return w;throw new Error(`failed to call OrtRun(). error code = ${f}.`)}finally{p.stackRestore(t)}}finally{_.forEach(p._OrtReleaseTensor),O.forEach(p._free),p._OrtReleaseRunOptions(v),w.forEach(p._free)}},e.endProfiling=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");e._OrtFree(a)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(e,n);a&&!("get"in a?!e.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,a)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),a=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return a(e,t),e},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const u=i(n(449)),c=o(n(932)),s=n(474);let l,f=!1,p=!1,h=!1;const d=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(f)return Promise.resolve();if(p)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(h)throw new Error("previous call to \'initializeWebAssembly()\' failed.");p=!0;const e=t.initTimeout,r=t.numThreads,a=t.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(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(t){return!1}})(),o=a&&(()=>{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(t){return!1}})(),y="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=d(!1,i),m=d(o,i),g="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let v=!1;const w=[];if(e>0&&w.push(new Promise((t=>{setTimeout((()=>{v=!0,t()}),e)}))),w.push(new Promise(((t,e)=>{const r=i?s:c.default,a={locateFile:(t,e)=>i&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):t===b?null!=g?g:(null!=y?y:e)+m:e+t};if(i)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=u.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(a).then((e=>{p=!1,f=!0,l=e,t()}),(t=>{p=!1,h=!0,e(t)}))}))),await Promise.race(w),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!f||p||h||(p=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,p=!1,f=!1,h=!0)}},154:t=>{"use strict";t.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},e={};function n(r){var a=e[r];if(void 0!==a)return a.exports;var i=e[r]={exports:{}};return t[r].call(i.exports,i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";const t=n(349),e=n(361);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,e.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(t=>postMessage({type:"init-wasm",err:t})));break;case"init-ort":try{const{numThreads:e,loggingLevel:r}=n.data.in;(0,t.initOrt)(e,r),postMessage({type:"init-ort"})}catch(t){postMessage({type:"init-ort",err:t})}break;case"create_allocate":try{const{model:e}=n.data.in,r=(0,t.createSessionAllocate)(e);postMessage({type:"create_allocate",out:r})}catch(t){postMessage({type:"create_allocate",err:t})}break;case"create_finalize":try{const{modeldata:e,options:r}=n.data.in,a=(0,t.createSessionFinalize)(e,r);postMessage({type:"create_finalize",out:a})}catch(t){postMessage({type:"create_finalize",err:t})}break;case"create":try{const{model:e,options:r}=n.data.in,a=(0,t.createSession)(e,r);postMessage({type:"create",out:a})}catch(t){postMessage({type:"create",err:t})}break;case"release":try{const e=n.data.in;(0,t.releaseSession)(e),postMessage({type:"release"})}catch(t){postMessage({type:"release",err:t})}break;case"run":try{const{sessionId:e,inputIndices:r,inputs:a,outputIndices:i,options:o}=n.data.in,u=(0,t.run)(e,r,a,i,o);postMessage({type:"run",out:u},(0,t.extractTransferableBuffers)(u))}catch(t){postMessage({type:"run",err:t})}break;case"end-profiling":try{const e=n.data.in;(0,t.endProfiling)(e),postMessage({type:"end-profiling"})}catch(t){postMessage({type:"end-profiling",err:t})}}}})()})();\n',"Worker",void 0,void 0)}},477:e=>{e.exports=function(e,t,n,r){var o=self||window;try{try{var i;try{i=new o.Blob([e])}catch(t){(i=new(o.BlobBuilder||o.WebKitBlobBuilder||o.MozBlobBuilder||o.MSBlobBuilder)).append(e),i=i.getBlob()}var s=o.URL||o.webkitURL,a=s.createObjectURL(i),c=new o[t](a,n);return s.revokeObjectURL(a),c}catch(r){return new o[t]("data:application/javascript,".concat(encodeURIComponent(e)),n)}}catch(e){if(!r)throw Error("Inline worker is not supported");return new o[t](r,n)}}},4154:e=>{e.exports='"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\n'},1670:e=>{e.exports=__WEBPACK_EXTERNAL_MODULE__1670__},7067:()=>{},1296:()=>{},1384:()=>{},3993:()=>{},908:()=>{},6953:()=>{},9925:()=>{},2806:()=>{},6449:()=>{},2850:()=>{},5381:()=>{},5686:(e,t,n)=>{n.r(t),n.d(t,{flatbuffers:()=>r});var r={};r.SIZEOF_SHORT=2,r.SIZEOF_INT=4,r.FILE_IDENTIFIER_LENGTH=4,r.SIZE_PREFIX_LENGTH=4,r.Encoding={UTF8_BYTES:1,UTF16_STRING:2},r.int32=new Int32Array(2),r.float32=new Float32Array(r.int32.buffer),r.float64=new Float64Array(r.int32.buffer),r.isLittleEndian=1===new Uint16Array(new Uint8Array([1,0]).buffer)[0],r.Long=function(e,t){this.low=0|e,this.high=0|t},r.Long.create=function(e,t){return 0==e&&0==t?r.Long.ZERO:new r.Long(e,t)},r.Long.prototype.toFloat64=function(){return(this.low>>>0)+4294967296*this.high},r.Long.prototype.equals=function(e){return this.low==e.low&&this.high==e.high},r.Long.ZERO=new r.Long(0,0),r.Builder=function(e){if(e)t=e;else var t=1024;this.bb=r.ByteBuffer.allocate(t),this.space=t,this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=false,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=false},r.Builder.prototype.clear=function(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=false,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=false},r.Builder.prototype.forceDefaults=function(e){this.force_defaults=e},r.Builder.prototype.dataBuffer=function(){return this.bb},r.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},r.Builder.prototype.prep=function(e,t){e>this.minalign&&(this.minalign=e);for(var n=1+~(this.bb.capacity()-this.space+t)&e-1;this.space<n+e+t;){var o=this.bb.capacity();this.bb=r.Builder.growByteBuffer(this.bb),this.space+=this.bb.capacity()-o}this.pad(n)},r.Builder.prototype.pad=function(e){for(var t=0;t<e;t++)this.bb.writeInt8(--this.space,0)},r.Builder.prototype.writeInt8=function(e){this.bb.writeInt8(this.space-=1,e)},r.Builder.prototype.writeInt16=function(e){this.bb.writeInt16(this.space-=2,e)},r.Builder.prototype.writeInt32=function(e){this.bb.writeInt32(this.space-=4,e)},r.Builder.prototype.writeInt64=function(e){this.bb.writeInt64(this.space-=8,e)},r.Builder.prototype.writeFloat32=function(e){this.bb.writeFloat32(this.space-=4,e)},r.Builder.prototype.writeFloat64=function(e){this.bb.writeFloat64(this.space-=8,e)},r.Builder.prototype.addInt8=function(e){this.prep(1,0),this.writeInt8(e)},r.Builder.prototype.addInt16=function(e){this.prep(2,0),this.writeInt16(e)},r.Builder.prototype.addInt32=function(e){this.prep(4,0),this.writeInt32(e)},r.Builder.prototype.addInt64=function(e){this.prep(8,0),this.writeInt64(e)},r.Builder.prototype.addFloat32=function(e){this.prep(4,0),this.writeFloat32(e)},r.Builder.prototype.addFloat64=function(e){this.prep(8,0),this.writeFloat64(e)},r.Builder.prototype.addFieldInt8=function(e,t,n){(this.force_defaults||t!=n)&&(this.addInt8(t),this.slot(e))},r.Builder.prototype.addFieldInt16=function(e,t,n){(this.force_defaults||t!=n)&&(this.addInt16(t),this.slot(e))},r.Builder.prototype.addFieldInt32=function(e,t,n){(this.force_defaults||t!=n)&&(this.addInt32(t),this.slot(e))},r.Builder.prototype.addFieldInt64=function(e,t,n){!this.force_defaults&&t.equals(n)||(this.addInt64(t),this.slot(e))},r.Builder.prototype.addFieldFloat32=function(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat32(t),this.slot(e))},r.Builder.prototype.addFieldFloat64=function(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat64(t),this.slot(e))},r.Builder.prototype.addFieldOffset=function(e,t,n){(this.force_defaults||t!=n)&&(this.addOffset(t),this.slot(e))},r.Builder.prototype.addFieldStruct=function(e,t,n){t!=n&&(this.nested(t),this.slot(e))},r.Builder.prototype.nested=function(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")},r.Builder.prototype.notNested=function(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")},r.Builder.prototype.slot=function(e){this.vtable[e]=this.offset()},r.Builder.prototype.offset=function(){return this.bb.capacity()-this.space},r.Builder.growByteBuffer=function(e){var t=e.capacity();if(3221225472&t)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");var n=t<<1,o=r.ByteBuffer.allocate(n);return o.setPosition(n-t),o.bytes().set(e.bytes(),n-t),o},r.Builder.prototype.addOffset=function(e){this.prep(r.SIZEOF_INT,0),this.writeInt32(this.offset()-e+r.SIZEOF_INT)},r.Builder.prototype.startObject=function(e){this.notNested(),null==this.vtable&&(this.vtable=[]),this.vtable_in_use=e;for(var t=0;t<e;t++)this.vtable[t]=0;this.isNested=true,this.object_start=this.offset()},r.Builder.prototype.endObject=function(){if(null==this.vtable||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);for(var e=this.offset(),t=this.vtable_in_use-1;t>=0&&0==this.vtable[t];t--);for(var n=t+1;t>=0;t--)this.addInt16(0!=this.vtable[t]?e-this.vtable[t]:0);this.addInt16(e-this.object_start);var o=(n+2)*r.SIZEOF_SHORT;this.addInt16(o);var i=0,s=this.space;e:for(t=0;t<this.vtables.length;t++){var a=this.bb.capacity()-this.vtables[t];if(o==this.bb.readInt16(a)){for(var c=r.SIZEOF_SHORT;c<o;c+=r.SIZEOF_SHORT)if(this.bb.readInt16(s+c)!=this.bb.readInt16(a+c))continue e;i=this.vtables[t];break}}return i?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,i-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=false,e},r.Builder.prototype.finish=function(e,t,n){var o=n?r.SIZE_PREFIX_LENGTH:0;if(t){var i=t;if(this.prep(this.minalign,r.SIZEOF_INT+r.FILE_IDENTIFIER_LENGTH+o),i.length!=r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+r.FILE_IDENTIFIER_LENGTH);for(var s=r.FILE_IDENTIFIER_LENGTH-1;s>=0;s--)this.writeInt8(i.charCodeAt(s))}this.prep(this.minalign,r.SIZEOF_INT+o),this.addOffset(e),o&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},r.Builder.prototype.finishSizePrefixed=function(e,t){this.finish(e,t,true)},r.Builder.prototype.requiredField=function(e,t){var n=this.bb.capacity()-e,r=n-this.bb.readInt32(n);if(0==this.bb.readInt16(r+t))throw new Error("FlatBuffers: field "+t+" must be set")},r.Builder.prototype.startVector=function(e,t,n){this.notNested(),this.vector_num_elems=t,this.prep(r.SIZEOF_INT,e*t),this.prep(n,e*t)},r.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},r.Builder.prototype.createString=function(e){if(e instanceof Uint8Array)var t=e;else{t=[];for(var n=0;n<e.length;){var r,o=e.charCodeAt(n++);(r=o<55296||o>=56320?o:(o<<10)+e.charCodeAt(n++)+-56613888)<128?t.push(r):(r<2048?t.push(r>>6&31|192):(r<65536?t.push(r>>12&15|224):t.push(r>>18&7|240,r>>12&63|128),t.push(r>>6&63|128)),t.push(63&r|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length),n=0;for(var i=this.space,s=this.bb.bytes();n<t.length;n++)s[i++]=t[n];return this.endVector()},r.Builder.prototype.createLong=function(e,t){return r.Long.create(e,t)},r.ByteBuffer=function(e){this.bytes_=e,this.position_=0},r.ByteBuffer.allocate=function(e){return new r.ByteBuffer(new Uint8Array(e))},r.ByteBuffer.prototype.clear=function(){this.position_=0},r.ByteBuffer.prototype.bytes=function(){return this.bytes_},r.ByteBuffer.prototype.position=function(){return this.position_},r.ByteBuffer.prototype.setPosition=function(e){this.position_=e},r.ByteBuffer.prototype.capacity=function(){return this.bytes_.length},r.ByteBuffer.prototype.readInt8=function(e){return this.readUint8(e)<<24>>24},r.ByteBuffer.prototype.readUint8=function(e){return this.bytes_[e]},r.ByteBuffer.prototype.readInt16=function(e){return this.readUint16(e)<<16>>16},r.ByteBuffer.prototype.readUint16=function(e){return this.bytes_[e]|this.bytes_[e+1]<<8},r.ByteBuffer.prototype.readInt32=function(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24},r.ByteBuffer.prototype.readUint32=function(e){return this.readInt32(e)>>>0},r.ByteBuffer.prototype.readInt64=function(e){return new r.Long(this.readInt32(e),this.readInt32(e+4))},r.ByteBuffer.prototype.readUint64=function(e){return new r.Long(this.readUint32(e),this.readUint32(e+4))},r.ByteBuffer.prototype.readFloat32=function(e){return r.int32[0]=this.readInt32(e),r.float32[0]},r.ByteBuffer.prototype.readFloat64=function(e){return r.int32[r.isLittleEndian?0:1]=this.readInt32(e),r.int32[r.isLittleEndian?1:0]=this.readInt32(e+4),r.float64[0]},r.ByteBuffer.prototype.writeInt8=function(e,t){this.bytes_[e]=t},r.ByteBuffer.prototype.writeUint8=function(e,t){this.bytes_[e]=t},r.ByteBuffer.prototype.writeInt16=function(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8},r.ByteBuffer.prototype.writeUint16=function(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8},r.ByteBuffer.prototype.writeInt32=function(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24},r.ByteBuffer.prototype.writeUint32=function(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24},r.ByteBuffer.prototype.writeInt64=function(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)},r.ByteBuffer.prototype.writeUint64=function(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)},r.ByteBuffer.prototype.writeFloat32=function(e,t){r.float32[0]=t,this.writeInt32(e,r.int32[0])},r.ByteBuffer.prototype.writeFloat64=function(e,t){r.float64[0]=t,this.writeInt32(e,r.int32[r.isLittleEndian?0:1]),this.writeInt32(e+4,r.int32[r.isLittleEndian?1:0])},r.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length<this.position_+r.SIZEOF_INT+r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");for(var e="",t=0;t<r.FILE_IDENTIFIER_LENGTH;t++)e+=String.fromCharCode(this.readInt8(this.position_+r.SIZEOF_INT+t));return e},r.ByteBuffer.prototype.__offset=function(e,t){var n=e-this.readInt32(e);return t<this.readInt16(n)?this.readInt16(n+t):0},r.ByteBuffer.prototype.__union=function(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e},r.ByteBuffer.prototype.__string=function(e,t){e+=this.readInt32(e);var n=this.readInt32(e),o="",i=0;if(e+=r.SIZEOF_INT,t===r.Encoding.UTF8_BYTES)return this.bytes_.subarray(e,e+n);for(;i<n;){var s,a=this.readUint8(e+i++);if(a<192)s=a;else{var c=this.readUint8(e+i++);if(a<224)s=(31&a)<<6|63&c;else{var u=this.readUint8(e+i++);s=a<240?(15&a)<<12|(63&c)<<6|63&u:(7&a)<<18|(63&c)<<12|(63&u)<<6|63&this.readUint8(e+i++)}}s<65536?o+=String.fromCharCode(s):(s-=65536,o+=String.fromCharCode(55296+(s>>10),56320+(1023&s)))}return o},r.ByteBuffer.prototype.__indirect=function(e){return e+this.readInt32(e)},r.ByteBuffer.prototype.__vector=function(e){return e+this.readInt32(e)+r.SIZEOF_INT},r.ByteBuffer.prototype.__vector_len=function(e){return this.readInt32(e+this.readInt32(e))},r.ByteBuffer.prototype.__has_identifier=function(e){if(e.length!=r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+r.FILE_IDENTIFIER_LENGTH);for(var t=0;t<r.FILE_IDENTIFIER_LENGTH;t++)if(e.charCodeAt(t)!=this.readInt8(this.position_+r.SIZEOF_INT+t))return false;return true},r.ByteBuffer.prototype.createLong=function(e,t){return r.Long.create(e,t)}}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__webpack_require__),n.exports}__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:true,get:t[n]})},__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:true})};var __webpack_exports__=__webpack_require__(6018);return __webpack_exports__})()))})(ortWeb_min$1);return ortWeb_min$1.exports}var ortWeb_minExports=requireOrtWeb_min();var ortWeb_min=getDefaultExportFromCjs(ortWeb_minExports);var ONNX_WEB=_mergeNamespaces({__proto__:null,default:ortWeb_min},[ortWeb_minExports]);let ONNX;const executionProviders=["wasm"];if(typeof process!=="undefined"&&process?.release?.name==="node"){ONNX=sharp??ONNX_NODE;executionProviders.unshift("cpu")}else{ONNX=ortWeb_min??ONNX_WEB;const e=typeof navigator!=="undefined"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);if(e){ONNX.env.wasm.simd=false}}const{env:onnx_env}=ONNX;const VERSION="2.17.2";const WEB_CACHE_AVAILABLE=typeof self!=="undefined"&&"caches"in self;const FS_AVAILABLE=!isEmpty(sharp);const PATH_AVAILABLE=!isEmpty(sharp);const RUNNING_LOCALLY=FS_AVAILABLE&&PATH_AVAILABLE;const __dirname=RUNNING_LOCALLY?sharp.dirname(sharp.dirname(sharp.fileURLToPath(import.meta.url))):"./";const DEFAULT_CACHE_DIR=RUNNING_LOCALLY?sharp.join(__dirname,"/.cache/"):null;const DEFAULT_LOCAL_MODEL_PATH="/models/";const localModelPath=RUNNING_LOCALLY?sharp.join(__dirname,DEFAULT_LOCAL_MODEL_PATH):DEFAULT_LOCAL_MODEL_PATH;if(onnx_env?.wasm){onnx_env.wasm.wasmPaths=RUNNING_LOCALLY?sharp.join(__dirname,"/dist/"):`https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`}const env$1={version:VERSION,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:true,localModelPath,useFS:FS_AVAILABLE,useBrowserCache:WEB_CACHE_AVAILABLE,useFSCache:FS_AVAILABLE,cacheDir:DEFAULT_CACHE_DIR};function isEmpty(e){return Object.keys(e).length===0}class FileResponse{_CONTENT_TYPE_MAP={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"};constructor(e){this.filePath=e;this.headers=new Headers;this.exists=sharp.existsSync(e);if(this.exists){this.status=200;this.statusText="OK";let t=sharp.statSync(e);this.headers.set("content-length",t.size.toString());this.updateContentType();let n=this;this.body=new ReadableStream({start(e){n.arrayBuffer().then((t=>{e.enqueue(new Uint8Array(t));e.close()}))}})}else{this.status=404;this.statusText="Not Found";this.body=null}}updateContentType(){const e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[e]??"application/octet-stream")}clone(){let e=new FileResponse(this.filePath);e.exists=this.exists;e.status=this.status;e.statusText=this.statusText;e.headers=new Headers(this.headers);return e}async arrayBuffer(){const e=await sharp.promises.readFile(this.filePath);return e.buffer}async blob(){const e=await sharp.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){const e=await sharp.promises.readFile(this.filePath,"utf8");return e}async json(){return JSON.parse(await this.text())}}function isValidUrl(e,t=null,n=null){let r;try{r=new URL(e)}catch(e){return false}if(t&&!t.includes(r.protocol)){return false}if(n&&!n.includes(r.hostname)){return false}return true}async function getFile(e){if(env$1.useFS&&!isValidUrl(e,["http:","https:","blob:"])){return new FileResponse(e)}else if(typeof process!=="undefined"&&process?.release?.name==="node"){const t=!!process.env?.TESTING_REMOTELY;const n=env$1.version;const r=new Headers;r.set("User-Agent",`transformers.js/${n}; is_ci/${t};`);const o=isValidUrl(e,["http:","https:"],["huggingface.co","hf.co"]);if(o){const e=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;if(e){r.set("Authorization",`Bearer ${e}`)}}return fetch(e,{headers:r})}else{return fetch(e)}}const ERROR_MAPPING={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 handleError(e,t,n){if(!n){return null}const r=ERROR_MAPPING[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${r}: "${t}".`)}class FileCache{constructor(e){this.path=e}async match(e){let t=sharp.join(this.path,e);let n=new FileResponse(t);if(n.exists){return n}else{return undefined}}async put(e,t){const n=Buffer.from(await t.arrayBuffer());let r=sharp.join(this.path,e);try{await sharp.promises.mkdir(sharp.dirname(r),{recursive:true});await sharp.promises.writeFile(r,n)}catch(e){console.warn("An error occurred while writing the file to cache:",e)}}}async function tryCache(e,...t){for(let n of t){try{let t=await e.match(n);if(t)return t}catch(e){continue}}return undefined}async function getModelFile(e,t,n=true,r={}){if(!env$1.allowLocalModels){if(r.local_files_only){throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).")}}dispatchCallback(r.progress_callback,{status:"initiate",name:e,file:t});let o;if(!o&&env$1.useBrowserCache){if(typeof caches==="undefined"){throw Error("Browser cache is not available in this environment.")}try{o=await caches.open("transformers-cache")}catch(e){console.warn("An error occurred while opening the browser cache:",e)}}if(!o&&env$1.useFSCache){o=new FileCache(r.cache_dir??env$1.cacheDir)}const i=r.revision??"main";let s=pathJoin(e,t);let a=pathJoin(env$1.localModelPath,s);let c=pathJoin(env$1.remoteHost,env$1.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(i)),t);let u=i==="main"?s:pathJoin(e,i,t);let l;let f=o instanceof FileCache?u:c;let d=false;let h;if(o){h=await tryCache(o,a,f)}const p=h!==undefined;if(h===undefined){if(env$1.allowLocalModels){const e=isValidUrl(s,["http:","https:"]);if(!e){try{h=await getFile(a);l=a}catch(e){console.warn(`Unable to load from local path "${a}": "${e}"`)}}else if(r.local_files_only){throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${s}.`)}else;}if(h===undefined||h.status===404){if(r.local_files_only||false){if(n){throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${a}".`)}else{return null}}h=await getFile(c);if(h.status!==200){return handleError(h.status,c,n)}l=f}d=o&&typeof Response!=="undefined"&&h instanceof Response&&h.status===200}dispatchCallback(r.progress_callback,{status:"download",name:e,file:t});const m={status:"progress",name:e,file:t};let w;if(!r.progress_callback){w=new Uint8Array(await h.arrayBuffer())}else if(p&&typeof navigator!=="undefined"&&/firefox/i.test(navigator.userAgent)){w=new Uint8Array(await h.arrayBuffer());dispatchCallback(r.progress_callback,{...m,progress:100,loaded:w.length,total:w.length})}else{w=await readResponse(h,(e=>{dispatchCallback(r.progress_callback,{...m,...e})}))}if(d&&l&&await o.match(l)===undefined){await o.put(l,new Response(w,{headers:h.headers})).catch((e=>{console.warn(`Unable to add response to browser cache: ${e}.`)}))}dispatchCallback(r.progress_callback,{status:"done",name:e,file:t});return w}async function getModelJSON(e,t,n=true,r={}){let o=await getModelFile(e,t,n,r);if(o===null){return{}}let i=new TextDecoder("utf-8");let s=i.decode(o);return JSON.parse(s)}async function readResponse(e,t){const n=e.headers.get("Content-Length");if(n===null){console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.")}let r=parseInt(n??"0");let o=new Uint8Array(r);let i=0;const s=e.body.getReader();async function a(){const{done:e,value:n}=await s.read();if(e)return;let c=i+n.length;if(c>r){r=c;let e=new Uint8Array(r);e.set(o);o=e}o.set(n,i);i=c;const u=i/r*100;t({progress:u,loaded:i,total:r});return a()}await a();return o}function pathJoin(...e){e=e.map(((t,n)=>{if(n){t=t.replace(new RegExp("^/"),"")}if(n!==e.length-1){t=t.replace(new RegExp("/$"),"")}return t}));return e.join("/")}function interpolate_data(e,[t,n,r],[o,i],s="bilinear",a=false){const c=i/r;const u=o/n;const l=new e.constructor(o*i*t);const f=n*r;const d=o*i;for(let s=0;s<o;++s){for(let o=0;o<i;++o){const a=s*i+o;const h=(o+.5)/c-.5;const p=(s+.5)/u-.5;let m=Math.floor(h);let w=Math.floor(p);const g=Math.min(m+1,r-1);const v=Math.min(w+1,n-1);m=Math.max(m,0);w=Math.max(w,0);const y=h-m;const _=p-w;const b=(1-y)*(1-_);const x=y*(1-_);const T=(1-y)*_;const M=y*_;const E=w*r;const S=v*r;const A=E+m;const $=E+g;const O=S+m;const P=S+g;for(let n=0;n<t;++n){const t=n*f;l[n*d+a]=b*e[t+A]+x*e[t+$]+T*e[t+O]+M*e[t+P]}}}return l}function permute_data(e,t,n){const r=new Array(n.length);const o=new Array(n.length);for(let e=n.length-1,i=1;e>=0;--e){o[e]=i;r[e]=t[n[e]];i*=r[e]}const i=n.map(((e,t)=>o[n.indexOf(t)]));const s=new e.constructor(e.length);for(let n=0;n<e.length;++n){let r=0;for(let e=t.length-1,o=n;e>=0;--e){r+=o%t[e]*i[e];o=Math.floor(o/t[e])}s[r]=e[n]}return[s,r]}function softmax(e){const t=max(e)[0];const n=e.map((e=>Math.exp(e-t)));const r=n.reduce(((e,t)=>e+t),0);const o=n.map((e=>e/r));return o}function log_softmax(e){const t=softmax(e);const n=t.map((e=>Math.log(e)));return n}function getTopItems(e,t=0){e=Array.from(e).map(((e,t)=>[t,e])).sort(((e,t)=>t[1]-e[1]));if(t!==null&&t>0){e=e.slice(0,t)}return e}function min(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0];let n=0;for(let r=1;r<e.length;++r){if(e[r]<t){t=e[r];n=r}}return[t,n]}function max(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0];let n=0;for(let r=1;r<e.length;++r){if(e[r]>t){t=e[r];n=r}}return[Number(t),n]}function isPowerOfTwo(e){return e>0&&(e&e-1)===0}class P2FFT{constructor(e){this.size=e|0;if(this.size<=1||!isPowerOfTwo(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1;this.table=new Float64Array(this.size*2);for(let e=0;e<this.table.length;e+=2){const t=Math.PI*e/this.size;this.table[e]=Math.cos(t);this.table[e+1]=-Math.sin(t)}let t=0;for(let e=1;this.size>e;e<<=1)++t;this._width=t%2===0?t-1:t;this._bitrev=new Int32Array(1<<this._width);for(let e=0;e<this._bitrev.length;++e){this._bitrev[e]=0;for(let t=0;t<this._width;t+=2){const n=this._width-t-2;this._bitrev[e]|=(e>>>t&3)<<n}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){const n=t||new Array(e.length>>>1);for(let t=0;t<e.length;t+=2)n[t>>>1]=e[t];return n}toComplexArray(e,t){const n=t||this.createComplexArray();for(let t=0;t<n.length;t+=2){n[t]=e[t>>>1];n[t+1]=0}return n}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let t=0;t<e.length;++t)e[t]/=this.size}_transform4(e,t,n){const r=this._csize;const o=this._width;let i=1<<o;let s=r/i<<1;let a;let c;const u=this._bitrev;if(s===4){for(a=0,c=0;a<r;a+=s,++c){const n=u[c];this._singleTransform2(t,e,a,n,i)}}else{for(a=0,c=0;a<r;a+=s,++c){const r=u[c];this._singleTransform4(t,e,a,r,i,n)}}const l=this.table;for(i>>=2;i>=2;i>>=2){s=r/i<<1;const t=s>>>2;for(a=0;a<r;a+=s){const r=a+t-1;for(let o=a,s=0;o<r;o+=2,s+=i){const r=o;const i=r+t;const a=i+t;const c=a+t;const u=e[r];const f=e[r+1];const d=e[i];const h=e[i+1];const p=e[a];const m=e[a+1];const w=e[c];const g=e[c+1];const v=l[s];const y=n*l[s+1];const _=d*v-h*y;const b=d*y+h*v;const x=l[2*s];const T=n*l[2*s+1];const M=p*x-m*T;const E=p*T+m*x;const S=l[3*s];const A=n*l[3*s+1];const $=w*S-g*A;const O=w*A+g*S;const P=u+M;const C=f+E;const k=u-M;const I=f-E;const F=_+$;const N=b+O;const D=n*(_-$);const R=n*(b-O);e[r]=P+F;e[r+1]=C+N;e[i]=k+R;e[i+1]=I-D;e[a]=P-F;e[a+1]=C-N;e[c]=k-R;e[c+1]=I+D}}}}_singleTransform2(e,t,n,r,o){const i=e[r];const s=e[r+1];const a=e[r+o];const c=e[r+o+1];t[n]=i+a;t[n+1]=s+c;t[n+2]=i-a;t[n+3]=s-c}_singleTransform4(e,t,n,r,o,i){const s=o*2;const a=o*3;const c=e[r];const u=e[r+1];const l=e[r+o];const f=e[r+o+1];const d=e[r+s];const h=e[r+s+1];const p=e[r+a];const m=e[r+a+1];const w=c+d;const g=u+h;const v=c-d;const y=u-h;const _=l+p;const b=f+m;const x=i*(l-p);const T=i*(f-m);t[n]=w+_;t[n+1]=g+b;t[n+2]=v+T;t[n+3]=y-x;t[n+4]=w-_;t[n+5]=g-b;t[n+6]=v-T;t[n+7]=y+x}_realTransform4(e,t,n){const r=this._csize;const o=this._width;let i=1<<o;let s=r/i<<1;let a;let c;const u=this._bitrev;if(s===4){for(a=0,c=0;a<r;a+=s,++c){const n=u[c];this._singleRealTransform2(t,e,a,n>>>1,i>>>1)}}else{for(a=0,c=0;a<r;a+=s,++c){const r=u[c];this._singleRealTransform4(t,e,a,r>>>1,i>>>1,n)}}const l=this.table;for(i>>=2;i>=2;i>>=2){s=r/i<<1;const t=s>>>1;const o=t>>>1;const c=o>>>1;for(a=0;a<r;a+=s){for(let r=0,s=0;r<=c;r+=2,s+=i){const i=a+r;const u=i+o;const f=u+o;const d=f+o;const h=e[i];const p=e[i+1];const m=e[u];const w=e[u+1];const g=e[f];const v=e[f+1];const y=e[d];const _=e[d+1];const b=h;const x=p;const T=l[s];const M=n*l[s+1];const E=m*T-w*M;const S=m*M+w*T;const A=l[2*s];const $=n*l[2*s+1];const O=g*A-v*$;const P=g*$+v*A;const C=l[3*s];const k=n*l[3*s+1];const I=y*C-_*k;const F=y*k+_*C;const N=b+O;const D=x+P;const R=b-O;const L=x-P;const j=E+I;const z=S+F;const U=n*(E-I);const B=n*(S-F);e[i]=N+j;e[i+1]=D+z;e[u]=R+B;e[u+1]=L-U;if(r===0){e[f]=N-j;e[f+1]=D-z;continue}if(r===c)continue;const V=a+o-r;const Z=a+t-r;e[V]=R-n*B;e[V+1]=-L-n*U;e[Z]=N-n*j;e[Z+1]=-D+n*z}}}const f=r>>>1;for(let t=2;t<f;t+=2){e[r-t]=e[t];e[r-t+1]=-e[t+1]}}_singleRealTransform2(e,t,n,r,o){const i=e[r];const s=e[r+o];t[n]=i+s;t[n+1]=0;t[n+2]=i-s;t[n+3]=0}_singleRealTransform4(e,t,n,r,o,i){const s=o*2;const a=o*3;const c=e[r];const u=e[r+o];const l=e[r+s];const f=e[r+a];const d=c+l;const h=c-l;const p=u+f;const m=i*(u-f);t[n]=d+p;t[n+1]=0;t[n+2]=h;t[n+3]=-m;t[n+4]=d-p;t[n+5]=0;t[n+6]=h;t[n+7]=m}}class NP2FFT{constructor(e){const t=2*(e-1);const n=2*(2*e-1);const r=2**Math.ceil(Math.log2(n));this.bufferSize=r;this._a=t;const o=new Float64Array(n);const i=new Float64Array(r);this._chirpBuffer=new Float64Array(r);this._buffer1=new Float64Array(r);this._buffer2=new Float64Array(r);this._outBuffer1=new Float64Array(r);this._outBuffer2=new Float64Array(r);const s=-2*Math.PI/e;const a=Math.cos(s);const c=Math.sin(s);for(let t=0;t<n>>1;++t){const n=(t+1-e)**2/2;const r=Math.sqrt(a**2+c**2)**n;const s=n*Math.atan2(c,a);const u=2*t;o[u]=r*Math.cos(s);o[u+1]=r*Math.sin(s);i[u]=o[u];i[u+1]=-o[u+1]}this._slicedChirpBuffer=o.subarray(t,n);this._f=new P2FFT(r>>1);this._f.transform(this._chirpBuffer,i)}_transform(e,t,n){const r=this._buffer1;const o=this._buffer2;const i=this._outBuffer1;const s=this._outBuffer2;const a=this._chirpBuffer;const c=this._slicedChirpBuffer;const u=this._a;if(n){for(let e=0;e<c.length;e+=2){const n=e+1;const o=e>>1;const i=t[o];r[e]=i*c[e];r[n]=i*c[n]}}else{for(let e=0;e<c.length;e+=2){const n=e+1;r[e]=t[e]*c[e]-t[n]*c[n];r[n]=t[e]*c[n]+t[n]*c[e]}}this._f.transform(i,r);for(let e=0;e<a.length;e+=2){const t=e+1;o[e]=i[e]*a[e]-i[t]*a[t];o[t]=i[e]*a[t]+i[t]*a[e]}this._f.inverseTransform(s,o);for(let t=0;t<s.length;t+=2){const n=s[t+u];const r=s[t+u+1];const o=c[t];const i=c[t+1];e[t]=n*o-r*i;e[t+1]=n*i+r*o}}transform(e,t){this._transform(e,t,false)}realTransform(e,t){this._transform(e,t,true)}}class FFT{constructor(e){this.fft_length=e;this.isPowerOfTwo=isPowerOfTwo(e);if(this.isPowerOfTwo){this.fft=new P2FFT(e);this.outputBufferSize=2*e}else{this.fft=new NP2FFT(e);this.outputBufferSize=this.fft.bufferSize}}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}}function medianFilter(e,t){if(t%2===0||t<=0){throw new Error("Window size must be a positive odd number")}const n=new e.constructor(e.length);const r=new e.constructor(t);const o=Math.floor(t/2);for(let t=0;t<e.length;++t){let i=0;for(let n=-o;n<=o;++n){let o=t+n;if(o<0){o=Math.abs(o)}else if(o>=e.length){o=2*(e.length-1)-o}r[i++]=e[o]}r.sort();n[t]=r[o]}return n}function round(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}function bankers_round(e){const t=Math.round(e);const n=Math.abs(e)%1===.5?t%2===0?t:t-1:t;return n}const DataTypeMap=Object.freeze({float32:Float32Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});const ONNXTensor$1=ONNX.Tensor;class Tensor{dims;type;data;size;constructor(...e){if(e[0]instanceof ONNXTensor$1){Object.assign(this,e[0])}else{Object.assign(this,new ONNXTensor$1(e[0],e[1],e[2]))}return new Proxy(this,{get:(e,t)=>{if(typeof t==="string"){let n=Number(t);if(Number.isInteger(n)){return e._getitem(n)}}return e[t]},set:(e,t,n)=>e[t]=n})}*[Symbol.iterator](){const[e,...t]=this.dims;if(t.length>0){const n=t.reduce(((e,t)=>e*t));for(let r=0;r<e;++r){yield this._subarray(r,n,t)}}else{yield*this.data}}_getitem(e){const[t,...n]=this.dims;e=safeIndex(e,t);if(n.length>0){const t=n.reduce(((e,t)=>e*t));return this._subarray(e,t,n)}else{return new Tensor(this.type,[this.data[e]],n)}}indexOf(e){for(let t=0;t<this.data.length;++t){if(this.data[t]==e){return t}}return-1}_subarray(e,t,n){const r=e*t;const o=(e+1)*t;const i="subarray"in this.data?this.data.subarray(r,o):this.data.slice(r,o);return new Tensor(this.type,i,n)}item(){if(this.data.length!==1){throw new Error(`a Tensor with ${this.data.length} elements cannot be converted to Scalar`)}return this.data[0]}tolist(){return reshape(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){for(let e=0;e<this.data.length;++e){this.data[e]=1/(1+Math.exp(-this.data[e]))}return this}mul(e){return this.clone().mul_(e)}mul_(e){for(let t=0;t<this.data.length;++t){this.data[t]*=e}return this}add(e){return this.clone().add_(e)}add_(e){for(let t=0;t<this.data.length;++t){this.data[t]+=e}return this}clone(){return new Tensor(this.type,this.data.slice(),this.dims.slice())}slice(...e){let t=[];let n=[];for(let r=0;r<this.dims.length;++r){let o=e[r];if(o===null||o===undefined){n.push([0,this.dims[r]]);t.push(this.dims[r])}else if(typeof o==="number"){o=safeIndex(o,this.dims[r],r);n.push([o,o+1])}else if(Array.isArray(o)&&o.length===2){if(o[0]>o[1]){throw new Error(`Invalid slice: ${o}`)}let e=[Math.max(o[0],0),Math.min(o[1],this.dims[r])];n.push(e);t.push(e[1]-e[0])}else{throw new Error(`Invalid slice: ${o}`)}}let r=n.map((([e,t])=>t-e));let o=r.reduce(((e,t)=>e*t));let i=new this.data.constructor(o);const s=this.stride();for(let e=0;e<o;++e){let t=0;for(let o=r.length-1,i=e;o>=0;--o){const e=r[o];t+=(i%e+n[o][0])*s[o];i=Math.floor(i/e)}i[e]=this.data[t]}return new Tensor(this.type,i,t)}permute(...e){return permute(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=false){return this.norm(1,e,t)}norm(e="fro",t=null,n=false){if(e==="fro"){e=2}else if(typeof e==="string"){throw Error(`Unsupported norm: ${e}`)}if(t===null){let t=this.data.reduce(((t,n)=>t+n**e),0)**(1/e);return new Tensor(this.type,[t],[])}t=safeIndex(t,this.dims.length);const r=this.dims.slice();r[t]=1;const o=new this.data.constructor(this.data.length/this.dims[t]);for(let n=0;n<this.data.length;++n){let i=0;for(let e=this.dims.length-1,o=n,s=1;e>=0;--e){const n=this.dims[e];if(e!==t){const t=o%n;i+=t*s;s*=r[e]}o=Math.floor(o/n)}o[i]+=this.data[n]**e}if(e!==1){for(let t=0;t<o.length;++t){o[t]=o[t]**(1/e)}}if(!n){r.splice(t,1)}return new Tensor(this.type,o,r)}normalize_(e=2,t=1){t=safeIndex(t,this.dims.length);const n=this.norm(e,t,true);for(let e=0;e<this.data.length;++e){let r=0;for(let n=this.dims.length-1,o=e,i=1;n>=0;--n){const e=this.dims[n];if(n!==t){const t=o%e;r+=t*i;i*=this.dims[n]}o=Math.floor(o/e)}this.data[e]/=n.data[r]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return dimsToStride(this.dims)}squeeze(e=null){return new Tensor(this.type,this.data,calc_squeeze_dims(this.dims,e))}squeeze_(e=null){this.dims=calc_squeeze_dims(this.dims,e);return this}unsqueeze(e=null){return new Tensor(this.type,this.data,calc_unsqueeze_dims(this.dims,e))}unsqueeze_(e=null){this.dims=calc_unsqueeze_dims(this.dims,e);return this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e);let r=this.dims.slice(e,t+1);let o=this.dims.slice(t+1);this.dims=[...n,r.reduce(((e,t)=>e*t),1),...o];return this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...e){let t=-1;for(let n=0;n<e.length;++n){if(e[n]===-1){if(t!==-1){throw new Error("Only one dimension can be inferred")}t=n}}if(t!==-1){const n=e.reduce(((e,n,r)=>r!==t?e*n:e),1);e[t]=this.data.length/n}return new Tensor(this.type,this.data,e)}neg_(){for(let e=0;e<this.data.length;++e){this.data[e]=-this.data[e]}return this}neg(){return this.clone().neg_()}clamp_(e,t){for(let n=0;n<this.data.length;++n){this.data[n]=Math.min(Math.max(this.data[n],e),t)}return this}clamp(e,t){return this.clone().clamp_(e,t)}round_(){for(let e=0;e<this.data.length;++e){this.data[e]=Math.round(this.data[e])}return this}round(){return this.clone().round_()}to(e){if(this.type===e)return this;if(!DataTypeMap.hasOwnProperty(e)){throw new Error(`Unsupported type: ${e}`)}return new Tensor(e,DataTypeMap[e].from(this.data),this.dims)}}function reshape(e,t){const n=e.length;const r=t.reduce(((e,t)=>e*t));if(n!==r){throw Error(`cannot reshape array of size ${n} into shape (${t})`)}let o=e;for(let e=t.length-1;e>=0;e--){o=o.reduce(((n,r)=>{let o=n[n.length-1];if(o.length<t[e]){o.push(r)}else{n.push([r])}return n}),[[]])}return o[0]}function permute(e,t){const[n,r]=permute_data(e.data,e.dims,t);return new Tensor(e.type,n,r)}function interpolate(e,[t,n],r="bilinear",o=false){const i=e.dims.at(-3)??1;const s=e.dims.at(-2);const a=e.dims.at(-1);let c=interpolate_data(e.data,[i,s,a],[t,n],r,o);return new Tensor(e.type,c,[i,t,n])}function mean_pooling(e,t){let n=[e.dims[0],e.dims[2]];let r=new e.data.constructor(n[0]*n[1]);let[o,i,s]=e.dims;let a=0;for(let n=0;n<o;++n){let o=n*s*i;for(let c=0;c<s;++c){let u=0;let l=0;let f=n*i;let d=o+c;for(let n=0;n<i;++n){let r=Number(t.data[f+n]);l+=r;u+=e.data[d+n*s]*r}let h=u/l;r[a++]=h}}return new Tensor(e.type,r,n)}function calc_squeeze_dims(e,t){e=e.slice();if(t===null){e=e.filter((e=>e!==1))}else if(typeof t==="number"){if(e[t]===1){e.splice(t,1)}}else if(Array.isArray(t)){e=e.filter(((e,n)=>e!==1||!t.includes(n)))}return e}function calc_unsqueeze_dims(e,t){t=safeIndex(t,e.length+1);e=e.slice();e.splice(t,0,1);return e}function safeIndex(e,t,n=null){if(e<-t||e>=t){throw new Error(`IndexError: index ${e} is out of bounds for dimension${n===null?"":" "+n} with size ${t}`)}if(e<0){e=(e%t+t)%t}return e}function cat(e,t=0){t=safeIndex(t,e[0].dims.length);const n=e[0].dims.slice();n[t]=e.reduce(((e,n)=>e+n.dims[t]),0);const r=n.reduce(((e,t)=>e*t),1);const o=new e[0].data.constructor(r);const i=e[0].type;if(t===0){let t=0;for(let n of e){o.set(n.data,t);t+=n.data.length}}else{let r=0;for(let i=0;i<e.length;++i){let s=e[i];for(let e=0;e<s.data.length;++e){let i=0;for(let o=s.dims.length-1,a=e,c=1;o>=0;--o){const e=s.dims[o];let u=a%e;if(o===t){u+=r}i+=u*c;c*=n[o];a=Math.floor(a/e)}o[i]=s.data[e]}r+=s.dims[t]}}return new Tensor(i,o,n)}function stack(e,t=0){return cat(e.map((e=>e.unsqueeze(t))),t)}function std_mean(e,t=null,n=1,r=false){if(t===null){const t=e.data.reduce(((e,t)=>e+t),0);const r=t/e.data.length;const o=Math.sqrt(e.data.reduce(((e,t)=>e+(t-r)**2),0)/(e.data.length-n));const i=new Tensor(e.type,[r],[]);const s=new Tensor(e.type,[o],[]);return[s,i]}t=safeIndex(t,e.dims.length);const o=mean(e,t,r);const i=e.dims.slice();i[t]=1;const s=new e.data.constructor(e.data.length/e.dims[t]);for(let n=0;n<e.data.length;++n){let r=0;for(let o=e.dims.length-1,s=n,a=1;o>=0;--o){const n=e.dims[o];if(o!==t){const e=s%n;r+=e*a;a*=i[o]}s=Math.floor(s/n)}s[r]+=(e.data[n]-o.data[r])**2}for(let r=0;r<s.length;++r){s[r]=Math.sqrt(s[r]/(e.dims[t]-n))}if(!r){i.splice(t,1)}const a=new Tensor(e.type,s,i);return[a,o]}function mean(e,t=null,n=false){if(t===null){let t=e.data.reduce(((e,t)=>e+t),0);return new Tensor(e.type,[t/e.data.length],[])}t=safeIndex(t,e.dims.length);const r=e.dims.slice();r[t]=1;const o=new e.data.constructor(e.data.length/e.dims[t]);for(let n=0;n<e.data.length;++n){let i=0;for(let o=e.dims.length-1,s=n,a=1;o>=0;--o){const n=e.dims[o];if(o!==t){const e=s%n;i+=e*a;a*=r[o]}s=Math.floor(s/n)}o[i]+=e.data[n]}if(e.dims[t]!==1){for(let n=0;n<o.length;++n){o[n]=o[n]/e.dims[t]}}if(!n){r.splice(t,1)}return new Tensor(e.type,o,r)}function dynamicTimeWarping(e){const[t,n]=e.dims;const r=[t+1,n+1];const o=new Tensor("float32",new Float32Array(r[0]*r[1]).fill(Infinity),r);const i=new Tensor("float32",new Float32Array(r[0]*r[1]).fill(-1),r);o[0].data[0]=0;for(let r=1;r<n+1;++r){for(let n=1;n<t+1;++n){const t=o[n-1][r-1].item();const s=o[n-1][r].item();const a=o[n][r-1].item();let c,u;if(t<s&&t<a){c=t;u=0}else if(s<t&&s<a){c=s;u=1}else{c=a;u=2}o[n].data[r]=e[n-1][r-1].item()+c;i[n].data[r]=u}}let s=t;let a=n;i.data.fill(2,0,r[1]);for(let e=0;e<r[0];++e){i[e].data[0]=1}let c=[];let u=[];while(s>0||a>0){c.push(s-1);u.push(a-1);const e=i[s][a].item();switch(e){case 0:--s;--a;break;case 1:--s;break;case 2:--a;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${s}, ${a}]. Please file a bug report.`)}}c.reverse();u.reverse();return[c,u]}function dimsToStride(e){const t=new Array(e.length);for(let n=e.length-1,r=1;n>=0;--n){t[n]=r;r*=e[n]}return t}function ones(e){const t=e.reduce(((e,t)=>e*t),1);return new Tensor("int64",new BigInt64Array(t).fill(1n),e)}function ones_like(e){return ones(e.dims)}function quantize_embeddings(e,t){if(e.dims.length!==2){throw new Error("The tensor must have 2 dimensions")}if(e.dims.at(-1)%8!==0){throw new Error("The last dimension of the tensor must be a multiple of 8")}if(!["binary","ubinary"].includes(t)){throw new Error("The precision must be either 'binary' or 'ubinary'")}const n=t==="binary";const r=n?"int8":"uint8";const o=n?Int8Array:Uint8Array;const i=e.data;const s=new o(i.length/8);for(let e=0;e<i.length;++e){const t=i[e]>0?1:0;const r=Math.floor(e/8);const o=e%8;s[r]|=t<<7-o;if(n&&o===0){s[r]-=128}}return new Tensor(r,s,[e.dims[0],e.dims[1]/8])}class PriorityQueue{constructor(e=(e,t)=>e>t){this._heap=[];this._comparator=e}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const t of e){this._heap.push(t);this._siftUp()}return this.size}pop(){const e=this.peek();const t=this.size-1;if(t>0){this._swap(0,t)}this._heap.pop();this._siftDown();return e}replace(e){const t=this.peek();this._heap[0]=e;this._siftDown();return t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){const n=this._heap[e];this._heap[e]=this._heap[t];this._heap[t]=n}_siftUp(){let e=this.size-1;while(e>0&&this._greater(e,this._parent(e))){this._swap(e,this._parent(e));e=this._parent(e)}}_siftDown(){let e=0;while(this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e)){const t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t);e=t}}}class CharTrie{constructor(){this.root=CharTrieNode.default()}extend(e){for(let t of e){this.push(t)}}push(e){let t=this.root;for(let n of e){let e=t.children.get(n);if(e===undefined){e=CharTrieNode.default();t.children.set(n,e)}t=e}t.isLeaf=true}*commonPrefixSearch(e){let t=this.root;let n="";for(let r=0;r<e.length&&t!==undefined;++r){const o=e[r];n+=o;t=t.children.get(o);if(t!==undefined&&t.isLeaf){yield n}}}}class CharTrieNode{constructor(e,t){this.isLeaf=e;this.children=t}static default(){return new CharTrieNode(false,new Map)}}class TokenLattice{constructor(e,t,n){this.sentence=e;this.len=e.length;this.bosTokenId=t;this.eosTokenId=n;this.nodes=[];this.beginNodes=Array.from({length:this.len+1},(()=>[]));this.endNodes=Array.from({length:this.len+1},(()=>[]));const r=new TokenLatticeNode(this.bosTokenId,0,0,0,0);const o=new TokenLatticeNode(this.eosTokenId,1,this.len,0,0);this.nodes.push(r.clone());this.nodes.push(o.clone());this.beginNodes[this.len].push(o);this.endNodes[0].push(r)}insert(e,t,n,r){const o=this.nodes.length;const i=new TokenLatticeNode(r,o,e,t,n);this.beginNodes[e].push(i);this.endNodes[e+t].push(i);this.nodes.push(i)}viterbi(){const e=this.len;let t=0;while(t<=e){if(this.beginNodes[t].length==0){return[]}for(let e of this.beginNodes[t]){e.prev=null;let n=0;let r=null;for(let o of this.endNodes[t]){const t=o.backtraceScore+e.score;if(r===null||t>n){r=o.clone();n=t}}if(r!==null){e.prev=r;e.backtraceScore=n}else{return[]}}++t}const n=[];const r=this.beginNodes[e][0];const o=r.prev;if(o===null){return[]}let i=o.clone();while(i.prev!==null){n.push(i.clone());const e=i.clone();i=e.prev.clone()}n.reverse();return n}piece(e){return this.sentence.slice(e.pos,e.pos+e.length)}tokens(){const e=this.viterbi();return e.map((e=>this.piece(e)))}tokenIds(){const e=this.viterbi();return e.map((e=>e.tokenId))}}class TokenLatticeNode{constructor(e,t,n,r,o){this.tokenId=e;this.nodeId=t;this.pos=n;this.length=r;this.score=o;this.prev=null;this.backtraceScore=0}clone(){const e=new TokenLatticeNode(this.tokenId,this.nodeId,this.pos,this.length,this.score);e.prev=this.prev;e.backtraceScore=this.backtraceScore;return e}}var dist;var hasRequiredDist;function requireDist(){if(hasRequiredDist)return dist;hasRequiredDist=1;var e=Object.defineProperty;var t=Object.getOwnPropertyDescriptor;var n=Object.getOwnPropertyNames;var r=Object.prototype.hasOwnProperty;var o=(t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:true})};var i=(o,i,s,a)=>{if(i&&typeof i==="object"||typeof i==="function"){for(let c of n(i))if(!r.call(o,c)&&c!==s)e(o,c,{get:()=>i[c],enumerable:!(a=t(i,c))||a.enumerable})}return o};var s=t=>i(e({},"__esModule",{value:true}),t);var a={};o(a,{Environment:()=>J,Interpreter:()=>ee,Template:()=>ne,parse:()=>j,tokenize:()=>w});dist=s(a);var c=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",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",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"});var u=Object.freeze({set:c.Set,for:c.For,in:c.In,is:c.Is,if:c.If,else:c.Else,endif:c.EndIf,elif:c.ElseIf,endfor:c.EndFor,and:c.And,or:c.Or,not:c.Not,"not in":c.NotIn,true:c.BooleanLiteral,false:c.BooleanLiteral});var l=class{constructor(e,t){this.value=e;this.type=t}};function f(e){return/\w/.test(e)}function d(e){return/[0-9]/.test(e)}var h=[["{%",c.OpenStatement],["%}",c.CloseStatement],["{{",c.OpenExpression],["}}",c.CloseExpression],["(",c.OpenParen],[")",c.CloseParen],["{",c.OpenCurlyBracket],["}",c.CloseCurlyBracket],["[",c.OpenSquareBracket],["]",c.CloseSquareBracket],[",",c.Comma],[".",c.Dot],[":",c.Colon],["|",c.Pipe],["<=",c.ComparisonBinaryOperator],[">=",c.ComparisonBinaryOperator],["==",c.ComparisonBinaryOperator],["!=",c.ComparisonBinaryOperator],["<",c.ComparisonBinaryOperator],[">",c.ComparisonBinaryOperator],["+",c.AdditiveBinaryOperator],["-",c.AdditiveBinaryOperator],["*",c.MultiplicativeBinaryOperator],["/",c.MultiplicativeBinaryOperator],["%",c.MultiplicativeBinaryOperator],["=",c.Equals]];var p=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function m(e,t={}){if(e.endsWith("\n")){e=e.slice(0,-1)}e=e.replace(/{#.*?#}/gs,"{##}");if(t.lstrip_blocks){e=e.replace(/^[ \t]*({[#%])/gm,"$1")}if(t.trim_blocks){e=e.replace(/([#%]})\n/g,"$1")}return e.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function w(e,t={}){const n=[];const r=m(e,t);let o=0;const i=e=>{let t="";while(e(r[o])){if(r[o]==="\\"){++o;if(o>=r.length)throw new SyntaxError("Unexpected end of input");const e=r[o++];const n=p.get(e);if(n===void 0){throw new SyntaxError(`Unexpected escaped character: ${e}`)}t+=n;continue}t+=r[o++];if(o>=r.length)throw new SyntaxError("Unexpected end of input")}return t};e:while(o<r.length){const e=n.at(-1)?.type;if(e===void 0||e===c.CloseStatement||e===c.CloseExpression){let e="";while(o<r.length&&!(r[o]==="{"&&(r[o+1]==="%"||r[o+1]==="{"))){e+=r[o++]}if(e.length>0){n.push(new l(e,c.Text));continue}}i((e=>/\s/.test(e)));const t=r[o];if(t==="-"||t==="+"){const e=n.at(-1)?.type;if(e===c.Text||e===void 0){throw new SyntaxError(`Unexpected character: ${t}`)}switch(e){case c.Identifier:case c.NumericLiteral:case c.BooleanLiteral:case c.StringLiteral:case c.CloseParen:case c.CloseSquareBracket:break;default:{++o;const e=i(d);n.push(new l(`${t}${e}`,e.length>0?c.NumericLiteral:c.UnaryOperator));continue}}}for(const[e,t]of h){const i=r.slice(o,o+e.length);if(i===e){n.push(new l(e,t));o+=e.length;continue e}}if(t==="'"||t==='"'){++o;const e=i((e=>e!==t));n.push(new l(e,c.StringLiteral));++o;continue}if(d(t)){const e=i(d);n.push(new l(e,c.NumericLiteral));continue}if(f(t)){const e=i(f);const t=Object.hasOwn(u,e)?u[e]:c.Identifier;if(t===c.In&&n.at(-1)?.type===c.Not){n.pop();n.push(new l("not in",c.NotIn))}else{n.push(new l(e,t))}continue}throw new SyntaxError(`Unexpected character: ${t}`)}return n}var g=class{type="Statement"};var v=class extends g{constructor(e){super();this.body=e}type="Program"};var y=class extends g{constructor(e,t,n){super();this.test=e;this.body=t;this.alternate=n}type="If"};var _=class extends g{constructor(e,t,n){super();this.loopvar=e;this.iterable=t;this.body=n}type="For"};var b=class extends g{constructor(e,t){super();this.assignee=e;this.value=t}type="Set"};var x=class extends g{type="Expression"};var T=class extends x{constructor(e,t,n){super();this.object=e;this.property=t;this.computed=n}type="MemberExpression"};var M=class extends x{constructor(e,t){super();this.callee=e;this.args=t}type="CallExpression"};var E=class extends x{constructor(e){super();this.value=e}type="Identifier"};var S=class extends x{constructor(e){super();this.value=e}type="Literal"};var A=class extends S{type="NumericLiteral"};var $=class extends S{type="StringLiteral"};var O=class extends S{type="BooleanLiteral"};var P=class extends S{type="ArrayLiteral"};var C=class extends S{type="TupleLiteral"};var k=class extends S{type="ObjectLiteral"};var I=class extends x{constructor(e,t,n){super();this.operator=e;this.left=t;this.right=n}type="BinaryExpression"};var F=class extends x{constructor(e,t){super();this.operand=e;this.filter=t}type="FilterExpression"};var N=class extends x{constructor(e,t,n){super();this.operand=e;this.negate=t;this.test=n}type="TestExpression"};var D=class extends x{constructor(e,t){super();this.operator=e;this.argument=t}type="UnaryExpression"};var R=class extends x{constructor(e=void 0,t=void 0,n=void 0){super();this.start=e;this.stop=t;this.step=n}type="SliceExpression"};var L=class extends x{constructor(e,t){super();this.key=e;this.value=t}type="KeywordArgumentExpression"};function j(e){const t=new v([]);let n=0;function r(t,r){const o=e[n++];if(!o||o.type!==t){throw new Error(`Parser Error: ${r}. ${o.type} !== ${t}.`)}return o}function o(){switch(e[n].type){case c.Text:return a();case c.OpenStatement:return u();case c.OpenExpression:return l();default:throw new SyntaxError(`Unexpected token type: ${e[n].type}`)}}function i(...t){return n+t.length<=e.length&&t.some(((t,r)=>t!==e[n+r].type))}function s(...t){return n+t.length<=e.length&&t.every(((t,r)=>t===e[n+r].type))}function a(){return new $(r(c.Text,"Expected text token").value)}function u(){r(c.OpenStatement,"Expected opening statement token");let t;switch(e[n].type){case c.Set:++n;t=f();r(c.CloseStatement,"Expected closing statement token");break;case c.If:++n;t=d();r(c.OpenStatement,"Expected {% token");r(c.EndIf,"Expected endif token");r(c.CloseStatement,"Expected %} token");break;case c.For:++n;t=p();r(c.OpenStatement,"Expected {% token");r(c.EndFor,"Expected endfor token");r(c.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${e[n].type}`)}return t}function l(){r(c.OpenExpression,"Expected opening expression token");const e=m();r(c.CloseExpression,"Expected closing expression token");return e}function f(){const e=m();if(s(c.Equals)){++n;const t=f();return new b(e,t)}return e}function d(){const t=m();r(c.CloseStatement,"Expected closing statement token");const i=[];const a=[];while(!(e[n]?.type===c.OpenStatement&&(e[n+1]?.type===c.ElseIf||e[n+1]?.type===c.Else||e[n+1]?.type===c.EndIf))){i.push(o())}if(e[n]?.type===c.OpenStatement&&e[n+1]?.type!==c.EndIf){++n;if(s(c.ElseIf)){r(c.ElseIf,"Expected elseif token");a.push(d())}else{r(c.Else,"Expected else token");r(c.CloseStatement,"Expected closing statement token");while(!(e[n]?.type===c.OpenStatement&&e[n+1]?.type===c.EndIf)){a.push(o())}}}return new y(t,i,a)}function h(e=false){const t=e?Y:m;const r=[t()];const o=s(c.Comma);while(o){++n;r.push(t());if(!s(c.Comma)){break}}return o?new C(r):r[0]}function p(){const e=h(true);if(!(e instanceof E||e instanceof C)){throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`)}r(c.In,"Expected `in` keyword following loop variable");const t=m();r(c.CloseStatement,"Expected closing statement token");const n=[];while(i(c.OpenStatement,c.EndFor)){n.push(o())}return new _(e,t,n)}function m(){return w()}function w(){const e=g();if(s(c.If)){++n;const t=g();r(c.Else,"Expected else token");const o=g();return new y(t,[e],[o])}return e}function g(){let t=x();while(s(c.Or)){const r=e[n];++n;const o=x();t=new I(r,t,o)}return t}function x(){let t=S();while(s(c.And)){const r=e[n];++n;const o=S();t=new I(r,t,o)}return t}function S(){let t;while(s(c.Not)){const r=e[n];++n;const o=S();t=new D(r,o)}return t??j()}function j(){let t=z();while(s(c.ComparisonBinaryOperator)||s(c.In)||s(c.NotIn)){const r=e[n];++n;const o=z();t=new I(r,t,o)}return t}function z(){let t=q();while(s(c.AdditiveBinaryOperator)){const r=e[n];++n;const o=q();t=new I(r,t,o)}return t}function U(){const e=W();if(s(c.OpenParen)){return B(e)}return e}function B(e){let t=new M(e,V());if(s(c.OpenParen)){t=B(t)}return t}function V(){r(c.OpenParen,"Expected opening parenthesis for arguments list");const e=Z();r(c.CloseParen,"Expected closing parenthesis for arguments list");return e}function Z(){const e=[];while(!s(c.CloseParen)){let t=m();if(s(c.Equals)){++n;if(!(t instanceof E)){throw new SyntaxError(`Expected identifier for keyword argument`)}const e=m();t=new L(t,e)}e.push(t);if(s(c.Comma)){++n}}return e}function G(){const e=[];let t=false;while(!s(c.CloseSquareBracket)){if(s(c.Colon)){e.push(void 0);++n;t=true}else{e.push(m());if(s(c.Colon)){++n;t=true}}}if(e.length===0){throw new SyntaxError(`Expected at least one argument for member/slice expression`)}if(t){if(e.length>3){throw new SyntaxError(`Expected 0-3 arguments for slice expression`)}return new R(...e)}return e[0]}function W(){let t=Y();while(s(c.Dot)||s(c.OpenSquareBracket)){const o=e[n];++n;let i;const s=o.type!==c.Dot;if(s){i=G();r(c.CloseSquareBracket,"Expected closing square bracket")}else{i=Y();if(i.type!=="Identifier"){throw new SyntaxError(`Expected identifier following dot operator`)}}t=new T(t,i,s)}return t}function q(){let t=H();while(s(c.MultiplicativeBinaryOperator)){const r=e[n];++n;const o=H();t=new I(r,t,o)}return t}function H(){let e=X();while(s(c.Is)){++n;const t=s(c.Not);if(t){++n}let r=Y();if(r instanceof O){r=new E(r.value.toString())}if(!(r instanceof E)){throw new SyntaxError(`Expected identifier for the test`)}e=new N(e,t,r)}return e}function X(){let e=U();while(s(c.Pipe)){++n;let t=Y();if(!(t instanceof E)){throw new SyntaxError(`Expected identifier for the filter`)}if(s(c.OpenParen)){t=B(t)}e=new F(e,t)}return e}function Y(){const t=e[n];switch(t.type){case c.NumericLiteral:++n;return new A(Number(t.value));case c.StringLiteral:++n;return new $(t.value);case c.BooleanLiteral:++n;return new O(t.value==="true");case c.Identifier:++n;return new E(t.value);case c.OpenParen:{++n;const t=h();if(e[n].type!==c.CloseParen){throw new SyntaxError(`Expected closing parenthesis, got ${e[n].type} instead`)}++n;return t}case c.OpenSquareBracket:{++n;const e=[];while(!s(c.CloseSquareBracket)){e.push(m());if(s(c.Comma)){++n}}++n;return new P(e)}case c.OpenCurlyBracket:{++n;const e=new Map;while(!s(c.CloseCurlyBracket)){const t=m();r(c.Colon,"Expected colon between key and value in object literal");const o=m();e.set(t,o);if(s(c.Comma)){++n}}++n;return new k(e)}default:throw new SyntaxError(`Unexpected token: ${t.type}`)}}while(n<e.length){t.body.push(o())}return t}function z(e,t,n=1){if(t===void 0){t=e;e=0}const r=[];for(let o=e;o<t;o+=n){r.push(o)}return r}function U(e,t,n,r=1){const o=Math.sign(r);if(o>=0){t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length);n=(n??=e.length)<0?Math.max(e.length+n,0):Math.min(n,e.length)}else{t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1);n=(n??=-1)<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1)}const i=[];for(let s=t;o*s<o*n;s+=r){i.push(e[s])}return i}function B(e){return e.replace(/\b\w/g,(e=>e.toUpperCase()))}var V=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new W(!!this.value)}};var Z=class extends V{type="NumericValue"};var G=class extends V{type="StringValue";builtins=new Map([["upper",new Y((()=>new G(this.value.toUpperCase())))],["lower",new Y((()=>new G(this.value.toLowerCase())))],["strip",new Y((()=>new G(this.value.trim())))],["title",new Y((()=>new G(B(this.value))))],["length",new Z(this.value.length)]])};var W=class extends V{type="BooleanValue"};var q=class extends V{type="ObjectValue";__bool__(){return new W(this.value.size>0)}builtins=new Map([["get",new Y((([e,t])=>{if(!(e instanceof G)){throw new Error(`Object key must be a string: got ${e.type}`)}return this.value.get(e.value)??t??new Q}))],["items",new Y((()=>new H(Array.from(this.value.entries()).map((([e,t])=>new H([new G(e),t]))))))]])};var H=class extends V{type="ArrayValue";builtins=new Map([["length",new Z(this.value.length)]]);__bool__(){return new W(this.value.length>0)}};var X=class extends H{type="TupleValue"};var Y=class extends V{type="FunctionValue"};var Q=class extends V{type="NullValue"};var K=class extends V{type="UndefinedValue"};var J=class{constructor(e){this.parent=e}variables=new Map([["namespace",new Y((e=>{if(e.length===0){return new q(new Map)}if(e.length!==1||!(e[0]instanceof q)){throw new Error("`namespace` expects either zero arguments or a single object argument")}return e[0]}))]]);tests=new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof Y],["odd",e=>{if(e.type!=="NumericValue"){throw new Error(`Cannot apply test "odd" to type: ${e.type}`)}return e.value%2!==0}],["even",e=>{if(e.type!=="NumericValue"){throw new Error(`Cannot apply test "even" to type: ${e.type}`)}return e.value%2===0}],["false",e=>e.type==="BooleanValue"&&!e.value],["true",e=>e.type==="BooleanValue"&&e.value],["number",e=>e.type==="NumericValue"],["integer",e=>e.type==="NumericValue"&&Number.isInteger(e.value)],["iterable",e=>e instanceof H||e instanceof G],["lower",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toLowerCase()}],["upper",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toUpperCase()}],["none",e=>e.type==="NullValue"],["defined",e=>e.type!=="UndefinedValue"],["undefined",e=>e.type==="UndefinedValue"],["equalto",(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,te(t))}declareVariable(e,t){if(this.variables.has(e)){throw new SyntaxError(`Variable already declared: ${e}`)}this.variables.set(e,t);return t}setVariable(e,t){this.variables.set(e,t);return t}resolve(e){if(this.variables.has(e)){return this}if(this.parent){return this.parent.resolve(e)}throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new K}catch{return new K}}};var ee=class{global;constructor(e){this.global=e??new J}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const n=this.evaluate(e.left,t);switch(e.operator.value){case"and":return n.__bool__().value?this.evaluate(e.right,t):n;case"or":return n.__bool__().value?n:this.evaluate(e.right,t)}const r=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new W(n.value==r.value);case"!=":return new W(n.value!=r.value)}if(n instanceof K||r instanceof K){throw new Error("Cannot perform operation on undefined values")}else if(n instanceof Q||r instanceof Q){throw new Error("Cannot perform operation on null values")}else if(n instanceof Z&&r instanceof Z){switch(e.operator.value){case"+":return new Z(n.value+r.value);case"-":return new Z(n.value-r.value);case"*":return new Z(n.value*r.value);case"/":return new Z(n.value/r.value);case"%":return new Z(n.value%r.value);case"<":return new W(n.value<r.value);case">":return new W(n.value>r.value);case">=":return new W(n.value>=r.value);case"<=":return new W(n.value<=r.value)}}else if(n instanceof H&&r instanceof H){switch(e.operator.value){case"+":return new H(n.value.concat(r.value))}}else if(r instanceof H){const t=r.value.find((e=>e.value===n.value))!==void 0;switch(e.operator.value){case"in":return new W(t);case"not in":return new W(!t)}}if(n instanceof G||r instanceof G){switch(e.operator.value){case"+":return new G(n.value.toString()+r.value.toString())}}if(n instanceof G&&r instanceof G){switch(e.operator.value){case"in":return new W(r.value.includes(n.value));case"not in":return new W(!r.value.includes(n.value))}}if(n instanceof G&&r instanceof q){switch(e.operator.value){case"in":return new W(r.value.has(n.value));case"not in":return new W(!r.value.has(n.value))}}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${n.type} and ${r.type}`)}evaluateFilterExpression(e,t){const n=this.evaluate(e.operand,t);if(e.filter.type==="Identifier"){const t=e.filter;if(n instanceof H){switch(t.value){case"list":return n;case"first":return n.value[0];case"last":return n.value[n.value.length-1];case"length":return new Z(n.value.length);case"reverse":return new H(n.value.reverse());case"sort":return new H(n.value.sort(((e,t)=>{if(e.type!==t.type){throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`)}switch(e.type){case"NumericValue":return e.value-t.value;case"StringValue":return e.value.localeCompare(t.value);default:throw new Error(`Cannot compare type: ${e.type}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${t.value}`)}}else if(n instanceof G){switch(t.value){case"length":return new Z(n.value.length);case"upper":return new G(n.value.toUpperCase());case"lower":return new G(n.value.toLowerCase());case"title":return new G(B(n.value));case"capitalize":return new G(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new G(n.value.trim());default:throw new Error(`Unknown StringValue filter: ${t.value}`)}}else if(n instanceof Z){switch(t.value){case"abs":return new Z(Math.abs(n.value));default:throw new Error(`Unknown NumericValue filter: ${t.value}`)}}else if(n instanceof q){switch(t.value){case"items":return new H(Array.from(n.value.entries()).map((([e,t])=>new H([new G(e),t]))));case"length":return new Z(n.value.size);default:throw new Error(`Unknown ObjectValue filter: ${t.value}`)}}throw new Error(`Cannot apply filter "${t.value}" to type: ${n.type}`)}else if(e.filter.type==="CallExpression"){const r=e.filter;if(r.callee.type!=="Identifier"){throw new Error(`Unknown filter: ${r.callee.type}`)}const o=r.callee.value;if(n instanceof H){switch(o){case"selectattr":{if(n.value.some((e=>!(e instanceof q)))){throw new Error("`selectattr` can only be applied to array of objects")}if(r.args.some((e=>e.type!=="StringLiteral"))){throw new Error("arguments of `selectattr` must be strings")}const[e,o,i]=r.args.map((e=>this.evaluate(e,t)));let s;if(o){const e=t.tests.get(o.value);if(!e){throw new Error(`Unknown test: ${o.value}`)}s=e}else{s=(...e)=>e[0].__bool__().value}const a=n.value.filter((t=>{const n=t.value.get(e.value);if(n){return s(n,i)}return false}));return new H(a)}}throw new Error(`Unknown ArrayValue filter: ${o}`)}else{throw new Error(`Cannot apply filter "${o}" to type: ${n.type}`)}}throw new Error(`Unknown filter: ${e.filter.type}`)}evaluateTestExpression(e,t){const n=this.evaluate(e.operand,t);const r=t.tests.get(e.test.value);if(!r){throw new Error(`Unknown test: ${e.test.value}`)}const o=r(n);return new W(e.negate?!o:o)}evaluateUnaryExpression(e,t){const n=this.evaluate(e.argument,t);switch(e.operator.value){case"not":return new W(!n.value);default:throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n="";for(const r of e){const e=this.evaluate(r,t);if(e.type!=="NullValue"&&e.type!=="UndefinedValue"){n+=e.value}}return new G(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const n=[];const r=new Map;for(const o of e.args){if(o.type==="KeywordArgumentExpression"){const e=o;r.set(e.key.value,this.evaluate(e.value,t))}else{n.push(this.evaluate(o,t))}}if(r.size>0){n.push(new q(r))}const o=this.evaluate(e.callee,t);if(o.type!=="FunctionValue"){throw new Error(`Cannot call something that is not a function: got ${o.type}`)}return o.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof H||e instanceof G)){throw new Error("Slice object must be an array or string")}const r=this.evaluate(t.start,n);const o=this.evaluate(t.stop,n);const i=this.evaluate(t.step,n);if(!(r instanceof Z||r instanceof K)){throw new Error("Slice start must be numeric or undefined")}if(!(o instanceof Z||o instanceof K)){throw new Error("Slice stop must be numeric or undefined")}if(!(i instanceof Z||i instanceof K)){throw new Error("Slice step must be numeric or undefined")}if(e instanceof H){return new H(U(e.value,r.value,o.value,i.value))}else{return new G(U(Array.from(e.value),r.value,o.value,i.value).join(""))}}evaluateMemberExpression(e,t){const n=this.evaluate(e.object,t);let r;if(e.computed){if(e.property.type==="SliceExpression"){return this.evaluateSliceExpression(n,e.property,t)}else{r=this.evaluate(e.property,t)}}else{r=new G(e.property.value)}let o;if(n instanceof q){if(!(r instanceof G)){throw new Error(`Cannot access property with non-string: got ${r.type}`)}o=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof H||n instanceof G){if(r instanceof Z){o=n.value.at(r.value);if(n instanceof G){o=new G(n.value.at(r.value))}}else if(r instanceof G){o=n.builtins.get(r.value)}else{throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`)}}else{if(!(r instanceof G)){throw new Error(`Cannot access property with non-string: got ${r.type}`)}o=n.builtins.get(r.value)}return o instanceof V?o:new K}evaluateSet(e,t){const n=this.evaluate(e.value,t);if(e.assignee.type==="Identifier"){const r=e.assignee.value;t.setVariable(r,n)}else if(e.assignee.type==="MemberExpression"){const r=e.assignee;const o=this.evaluate(r.object,t);if(!(o instanceof q)){throw new Error("Cannot assign to member of non-object")}if(r.property.type!=="Identifier"){throw new Error("Cannot assign to member with non-identifier property")}o.value.set(r.property.value,n)}else{throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`)}return new Q}evaluateIf(e,t){const n=this.evaluate(e.test,t);return this.evaluateBlock(n.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const n=new J(t);const r=this.evaluate(e.iterable,n);if(!(r instanceof H)){throw new Error(`Expected iterable type in for loop: got ${r.type}`)}let o="";for(let t=0;t<r.value.length;++t){const i=new Map([["index",new Z(t+1)],["index0",new Z(t)],["revindex",new Z(r.value.length-t)],["revindex0",new Z(r.value.length-t-1)],["first",new W(t===0)],["last",new W(t===r.value.length-1)],["length",new Z(r.value.length)],["previtem",t>0?r.value[t-1]:new K],["nextitem",t<r.value.length-1?r.value[t+1]:new K]]);n.setVariable("loop",new q(i));const s=r.value[t];if(e.loopvar.type==="Identifier"){n.setVariable(e.loopvar.value,s)}else if(e.loopvar.type==="TupleLiteral"){const t=e.loopvar;if(s.type!=="ArrayValue"){throw new Error(`Cannot unpack non-iterable type: ${s.type}`)}const r=s;if(t.value.length!==r.value.length){throw new Error(`Too ${t.value.length>r.value.length?"few":"many"} items to unpack`)}for(let e=0;e<t.value.length;++e){if(t.value[e].type!=="Identifier"){throw new Error(`Cannot unpack non-identifier type: ${t.value[e].type}`)}n.setVariable(t.value[e].value,r.value[e])}}const a=this.evaluateBlock(e.body,n);o+=a.value}return new G(o)}evaluate(e,t){if(e===void 0)return new K;switch(e.type){case"Program":return this.evalProgram(e,t);case"Set":return this.evaluateSet(e,t);case"If":return this.evaluateIf(e,t);case"For":return this.evaluateFor(e,t);case"NumericLiteral":return new Z(Number(e.value));case"StringLiteral":return new G(e.value);case"BooleanLiteral":return new W(e.value);case"ArrayLiteral":return new H(e.value.map((e=>this.evaluate(e,t))));case"TupleLiteral":return new X(e.value.map((e=>this.evaluate(e,t))));case"ObjectLiteral":{const n=new Map;for(const[r,o]of e.value){const e=this.evaluate(r,t);if(!(e instanceof G)){throw new Error(`Object keys must be strings: got ${e.type}`)}n.set(e.value,this.evaluate(o,t))}return new q(n)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function te(e){switch(typeof e){case"number":return new Z(e);case"string":return new G(e);case"boolean":return new W(e);case"object":if(e===null){return new Q}else if(Array.isArray(e)){return new H(e.map(te))}else{return new q(new Map(Object.entries(e).map((([e,t])=>[e,te(t)]))))}case"function":return new Y(((t,n)=>{const r=e(...t.map((e=>e.value)))??null;return te(r)}));default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var ne=class{parsed;constructor(e){const t=w(e,{lstrip_blocks:true,trim_blocks:true});this.parsed=j(t)}render(e){const t=new J;t.set("false",false);t.set("true",true);t.set("raise_exception",(e=>{throw new Error(e)}));t.set("range",z);for(const[n,r]of Object.entries(e)){t.set(n,r)}const n=new ee(t);const r=n.run(this.parsed);return r.value}};return dist}var distExports=requireDist();async function loadTokenizer(e,t){const n=await Promise.all([getModelJSON(e,"tokenizer.json",true,t),getModelJSON(e,"tokenizer_config.json",true,t)]);if(t.legacy!==null){n[1].legacy=t.legacy}return n}function regexSplit(e,t){const n=[];let r=0;for(const o of e.matchAll(t)){const t=o[0];if(r<o.index){n.push(e.slice(r,o.index))}if(t.length>0){n.push(t)}r=o.index+t.length}if(r<e.length){n.push(e.slice(r))}return n}function createPattern(e,t=true){if(e.Regex!==undefined){let t=e.Regex.replace(/\\([#&~])/g,"$1");for(const[e,n]of PROBLEMATIC_REGEX_MAP){t=t.replaceAll(e,n)}return new RegExp(t,"gu")}else if(e.String!==undefined){const n=escapeRegExp(e.String);return new RegExp(t?n:`(${n})`,"gu")}else{console.warn("Unknown pattern type:",e);return null}}function objectToMap(e){return new Map(Object.entries(e))}function prepareTensorForDecode(e){const t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1){throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.")}return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}function clean_up_tokenization(e){return e.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n\'t/g,"n't").replace(/ \'m/g,"'m").replace(/ \'s/g,"'s").replace(/ \'ve/g,"'ve").replace(/ \'re/g,"'re")}function remove_accents(e){return e.replace(/[\u0300-\u036f]/g,"")}function lowercase_and_remove_accent(e){return remove_accents(e.toLowerCase())}function fuse(e,t,n){const r=[];let o=0;while(o<e.length){r.push(e[o]);if((n.get(e[o])??t)!==t){++o;continue}while(o<e.length&&(n.get(e[o])??t)===t){++o}}return r}function whitespace_split(e){return e.match(/\S+/g)||[]}const PUNCTUATION_REGEX="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E";const PROBLEMATIC_REGEX_MAP=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"]]);class AddedToken{constructor(e){this.content=e.content;this.id=e.id;this.single_word=e.single_word??false;this.lstrip=e.lstrip??false;this.rstrip=e.rstrip??false;this.special=e.special??false;this.normalized=e.normalized??null}}class TokenizerModel extends Callable{constructor(e){super();this.config=e;this.vocab=[];this.tokens_to_ids=new Map;this.unk_token_id=undefined;this.unk_token=undefined;this.end_of_word_suffix=undefined;this.fuse_unk=this.config.fuse_unk??false}static fromConfig(e,...t){switch(e.type){case"WordPiece":return new WordPieceTokenizer(e);case"Unigram":return new Unigram(e,...t);case"BPE":return new BPE(e);default:if(e.vocab){return new LegacyTokenizerModel(e,...t)}throw new Error(`Unknown TokenizerModel type: ${e.type}`)}}_call(e){let t=this.encode(e);if(this.fuse_unk){t=fuse(t,this.unk_token_id,this.tokens_to_ids)}return t}encode(e){throw Error("encode should be implemented in subclass.")}convert_tokens_to_ids(e){return e.map((e=>this.tokens_to_ids.get(e)??this.unk_token_id))}convert_ids_to_tokens(e){return e.map((e=>this.vocab[e]??this.unk_token))}}class WordPieceTokenizer extends TokenizerModel{constructor(e){super(e);this.tokens_to_ids=objectToMap(e.vocab);this.unk_token_id=this.tokens_to_ids.get(e.unk_token);this.unk_token=e.unk_token;this.max_input_chars_per_word=e.max_input_chars_per_word??100;this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids){this.vocab[t]=e}}encode(e){const t=[];for(const n of e){const e=[...n];if(e.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let r=false;let o=0;const i=[];while(o<e.length){let t=e.length;let n=null;while(o<t){let r=e.slice(o,t).join("");if(o>0){r=this.config.continuing_subword_prefix+r}if(this.tokens_to_ids.has(r)){n=r;break}--t}if(n===null){r=true;break}i.push(n);o=t}if(r){t.push(this.unk_token)}else{t.push(...i)}}return t}}class Unigram extends TokenizerModel{constructor(e,t){super(e);const n=e.vocab.length;this.vocab=new Array(n);this.scores=new Array(n);for(let t=0;t<n;++t){const n=e.vocab[t];this.vocab[t]=n[0];this.scores[t]=n[1]}this.unk_token_id=e.unk_id;this.unk_token=this.vocab[e.unk_id];this.tokens_to_ids=new Map(this.vocab.map(((e,t)=>[e,t])));this.bosToken=" ";this.bosTokenId=this.tokens_to_ids.get(this.bosToken);this.eosToken=t.eos_token;this.eosTokenId=this.tokens_to_ids.get(this.eosToken);this.unkToken=this.vocab[this.unk_token_id];this.minScore=min(this.scores)[0];this.unkScore=this.minScore-10;this.scores[this.unk_token_id]=this.unkScore;this.trie=new CharTrie;this.trie.extend(this.vocab);this.fuse_unk=true}populateNodes(e){const t=e.sentence;const n=t.length;let r=0;while(r<n){const n=1;let o=false;for(let i of this.trie.commonPrefixSearch(t.slice(r))){const t=this.tokens_to_ids.get(i);const s=this.scores[t];const a=i.length;e.insert(r,a,s,t);if(!o&&a===n){o=true}}if(!o){e.insert(r,n,this.unkScore,this.unk_token_id)}r+=n}}tokenize(e){const t=new TokenLattice(e,this.bosTokenId,this.eosTokenId);this.populateNodes(t);return t.tokens()}encode(e){const t=[];for(const n of e){const e=this.tokenize(n);t.push(...e)}return t}}const BYTES_TO_UNICODE=(()=>{const e=[...Array.from({length:"~".charCodeAt(0)-"!".charCodeAt(0)+1},((e,t)=>t+"!".charCodeAt(0))),...Array.from({length:"¬".charCodeAt(0)-"¡".charCodeAt(0)+1},((e,t)=>t+"¡".charCodeAt(0))),...Array.from({length:"ÿ".charCodeAt(0)-"®".charCodeAt(0)+1},((e,t)=>t+"®".charCodeAt(0)))];const t=e.slice();let n=0;for(let r=0;r<256;++r){if(!e.includes(r)){e.push(r);t.push(256+n);n+=1}}const r=t.map((e=>String.fromCharCode(e)));return Object.fromEntries(e.map(((e,t)=>[e,r[t]])))})();const UNICODE_TO_BYTES=reverseDictionary(BYTES_TO_UNICODE);class BPE extends TokenizerModel{constructor(e){super(e);this.BPE_SPLIT_TOKEN=" ";this.tokens_to_ids=objectToMap(e.vocab);this.unk_token_id=this.tokens_to_ids.get(e.unk_token);this.unk_token=e.unk_token;this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids){this.vocab[t]=e}this.bpe_ranks=new Map(e.merges.map(((e,t)=>[e,t])));this.merges=e.merges.map((e=>e.split(this.BPE_SPLIT_TOKEN)));this.end_of_word_suffix=e.end_of_word_suffix;this.continuing_subword_suffix=e.continuing_subword_suffix??null;this.byte_fallback=this.config.byte_fallback??false;if(this.byte_fallback){this.text_encoder=new TextEncoder}this.ignore_merges=this.config.ignore_merges??false;this.cache=new Map}bpe(e){if(e.length===0){return[]}const t=this.cache.get(e);if(t!==undefined){return t}const n=Array.from(e);if(this.end_of_word_suffix){n[n.length-1]+=this.end_of_word_suffix}let r=[];if(n.length>1){const e=new PriorityQueue(((e,t)=>e.score<t.score));let t={token:n[0],bias:0,prev:null,next:null};let o=t;for(let t=1;t<n.length;++t){const r={bias:t/n.length,token:n[t],prev:o,next:null};o.next=r;this._add_node(e,o);o=r}while(!e.isEmpty()){const n=e.pop();if(n.deleted||!n.next||n.next.deleted)continue;n.deleted=true;n.next.deleted=true;if(n.prev){const e={...n.prev};n.prev.deleted=true;n.prev=e;if(e.prev){e.prev.next=e}else{t=e}}const r={token:n.token+n.next.token,bias:n.bias,prev:n.prev,next:n.next.next};if(r.prev){r.prev.next=r;this._add_node(e,r.prev)}else{t=r}if(r.next){r.next.prev=r;this._add_node(e,r)}}for(let e=t;e!==null;e=e.next){r.push(e.token)}}else{r=n}if(this.continuing_subword_suffix){for(let e=0;e<r.length-1;++e){r[e]+=this.continuing_subword_suffix}}this.cache.set(e,r);return r}_add_node(e,t){const n=this.bpe_ranks.get(t.token+this.BPE_SPLIT_TOKEN+t.next.token);if(n!==undefined){t.score=n+t.bias;e.push(t)}}encode(e){const t=[];for(const n of e){if(this.ignore_merges&&this.tokens_to_ids.has(n)){t.push(n);continue}const e=this.bpe(n);for(const n of e){if(this.tokens_to_ids.has(n)){t.push(n)}else{if(this.byte_fallback){t.push(...Array.from(this.text_encoder.encode(n)).map((e=>`<0x${e.toString(16).toUpperCase().padStart(2,"0")}>`)))}else{t.push(this.unk_token)}}}}return t}}class LegacyTokenizerModel extends TokenizerModel{constructor(e,t){super(e);this.tokens_to_ids=objectToMap(t.target_lang?e.vocab[t.target_lang]:e.vocab);this.bos_token=t.bos_token;this.bos_token_id=this.tokens_to_ids.get(this.bos_token);this.eos_token=t.eos_token;this.eos_token_id=this.tokens_to_ids.get(this.eos_token);this.pad_token=t.pad_token;this.pad_token_id=this.tokens_to_ids.get(this.pad_token);this.unk_token=t.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[e,t]of this.tokens_to_ids){this.vocab[t]=e}}encode(e){return e}}class Normalizer extends Callable{constructor(e){super();this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new BertNormalizer(e);case"Precompiled":return new Precompiled(e);case"Sequence":return new NormalizerSequence(e);case"Replace":return new Replace(e);case"NFC":return new NFC(e);case"NFKC":return new NFKC(e);case"NFKD":return new NFKD(e);case"Strip":return new StripNormalizer(e);case"StripAccents":return new StripAccents(e);case"Lowercase":return new Lowercase(e);case"Prepend":return new Prepend(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}normalize(e){throw Error("normalize should be implemented in subclass.")}_call(e){return this.normalize(e)}}class Replace extends Normalizer{normalize(e){const t=createPattern(this.config.pattern);return t===null?e:e.replaceAll(t,this.config.content)}}class NFC extends Normalizer{normalize(e){e=e.normalize("NFC");return e}}class NFKC extends Normalizer{normalize(e){e=e.normalize("NFKC");return e}}class NFKD extends Normalizer{normalize(e){e=e.normalize("NFKD");return e}}class StripNormalizer extends Normalizer{normalize(e){if(this.config.strip_left&&this.config.strip_right){e=e.trim()}else{if(this.config.strip_left){e=e.trimStart()}if(this.config.strip_right){e=e.trimEnd()}}return e}}class StripAccents extends Normalizer{normalize(e){e=remove_accents(e);return e}}class Lowercase extends Normalizer{normalize(e){e=e.toLowerCase();return e}}class Prepend extends Normalizer{normalize(e){e=this.config.prepend+e;return e}}class NormalizerSequence extends Normalizer{constructor(e){super(e);this.normalizers=e.normalizers.map((e=>Normalizer.fromConfig(e)))}normalize(e){return this.normalizers.reduce(((e,t)=>t.normalize(e)),e)}}class BertNormalizer extends Normalizer{_tokenize_chinese_chars(e){const t=[];for(let n=0;n<e.length;++n){const r=e[n];const o=r.charCodeAt(0);if(this._is_chinese_char(o)){t.push(" ");t.push(r);t.push(" ")}else{t.push(r)}}return t.join("")}_is_chinese_char(e){return e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103}stripAccents(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}_is_control(e){switch(e){case"\t":case"\n":case"\r":return false;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(e)}}_clean_text(e){const t=[];for(const n of e){const e=n.charCodeAt(0);if(e===0||e===65533||this._is_control(n)){continue}if(/^\s$/.test(n)){t.push(" ")}else{t.push(n)}}return t.join("")}normalize(e){if(this.config.clean_text){e=this._clean_text(e)}if(this.config.handle_chinese_chars){e=this._tokenize_chinese_chars(e)}if(this.config.lowercase){e=e.toLowerCase();if(this.config.strip_accents!==false){e=this.stripAccents(e)}}else if(this.config.strip_accents){e=this.stripAccents(e)}return e}}class PreTokenizer extends Callable{static fromConfig(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new BertPreTokenizer(e);case"Sequence":return new PreTokenizerSequence(e);case"Whitespace":return new WhitespacePreTokenizer(e);case"WhitespaceSplit":return new WhitespaceSplit(e);case"Metaspace":return new MetaspacePreTokenizer(e);case"ByteLevel":return new ByteLevelPreTokenizer(e);case"Split":return new SplitPreTokenizer(e);case"Punctuation":return new PunctuationPreTokenizer(e);case"Digits":return new DigitsPreTokenizer(e);case"Replace":return new ReplacePreTokenizer(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}pre_tokenize_text(e,t){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(e,t){return(Array.isArray(e)?e.map((e=>this.pre_tokenize_text(e,t))):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}}class BertPreTokenizer extends PreTokenizer{constructor(e){super();this.pattern=new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}}class ByteLevelPreTokenizer extends PreTokenizer{constructor(e){super();this.config=e;this.add_prefix_space=this.config.add_prefix_space;this.trim_offsets=this.config.trim_offsets;this.use_regex=this.config.use_regex??true;this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu;this.byte_encoder=BYTES_TO_UNICODE;this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){if(this.add_prefix_space&&!e.startsWith(" ")){e=" "+e}const n=this.use_regex?e.match(this.pattern)||[]:[e];return n.map((e=>Array.from(this.text_encoder.encode(e),(e=>this.byte_encoder[e])).join("")))}}class SplitPreTokenizer extends PreTokenizer{constructor(e){super();this.config=e;this.pattern=createPattern(this.config.pattern,this.config.invert)}pre_tokenize_text(e,t){if(this.pattern===null){return[]}if(this.config.invert){return e.match(this.pattern)||[]}else{return regexSplit(e,this.pattern)}}}class PunctuationPreTokenizer extends PreTokenizer{constructor(e){super();this.config=e;this.pattern=new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`,"gu")}pre_tokenize_text(e,t){return e.match(this.pattern)||[]}}class DigitsPreTokenizer extends PreTokenizer{constructor(e){super();this.config=e;const t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e,t){return e.match(this.pattern)||[]}}class PostProcessor extends Callable{constructor(e){super();this.config=e}static fromConfig(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new TemplateProcessing(e);case"ByteLevel":return new ByteLevelPostProcessor(e);case"RobertaProcessing":return new RobertaProcessing(e);case"BertProcessing":return new BertProcessing(e);case"Sequence":return new PostProcessorSequence(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}post_process(e,...t){throw Error("post_process should be implemented in subclass.")}_call(e,...t){return this.post_process(e,...t)}}class BertProcessing extends PostProcessor{constructor(e){super(e);this.cls=e.cls[0];this.sep=e.sep[0]}post_process(e,t=null,{add_special_tokens:n=true}={}){if(n){e=mergeArrays([this.cls],e,[this.sep])}let r=new Array(e.length).fill(0);if(t!==null){const o=n&&this instanceof RobertaProcessing?[this.sep]:[];const i=n?[this.sep]:[];e=mergeArrays(e,o,t,i);r=mergeArrays(r,new Array(t.length+o.length+i.length).fill(1))}return{tokens:e,token_type_ids:r}}}class RobertaProcessing extends BertProcessing{}class TemplateProcessing extends PostProcessor{constructor(e){super(e);this.single=e.single;this.pair=e.pair}post_process(e,t=null,{add_special_tokens:n=true}={}){const r=t===null?this.single:this.pair;let o=[];let i=[];for(const s of r){if("SpecialToken"in s){if(n){o.push(s.SpecialToken.id);i.push(s.SpecialToken.type_id)}}else if("Sequence"in s){if(s.Sequence.id==="A"){o=mergeArrays(o,e);i=mergeArrays(i,new Array(e.length).fill(s.Sequence.type_id))}else if(s.Sequence.id==="B"){o=mergeArrays(o,t);i=mergeArrays(i,new Array(t.length).fill(s.Sequence.type_id))}}}return{tokens:o,token_type_ids:i}}}class ByteLevelPostProcessor extends PostProcessor{post_process(e,t=null){if(t){e=mergeArrays(e,t)}return{tokens:e}}}class PostProcessorSequence extends PostProcessor{constructor(e){super(e);this.processors=e.processors.map((e=>PostProcessor.fromConfig(e)))}post_process(e,t=null,n={}){let r;for(const o of this.processors){if(o instanceof ByteLevelPostProcessor){const n=o.post_process(e);e=n.tokens;if(t){const e=o.post_process(t);t=e.tokens}}else{const i=o.post_process(e,t,n);e=i.tokens;r=i.token_type_ids}}return{tokens:e,token_type_ids:r}}}class Decoder extends Callable{constructor(e){super();this.config=e;this.added_tokens=[];this.end_of_word_suffix=null;this.trim_offsets=e.trim_offsets}static fromConfig(e){if(e===null)return null;switch(e.type){case"WordPiece":return new WordPieceDecoder(e);case"Metaspace":return new MetaspaceDecoder(e);case"ByteLevel":return new ByteLevelDecoder(e);case"Replace":return new ReplaceDecoder(e);case"ByteFallback":return new ByteFallback(e);case"Fuse":return new FuseDecoder(e);case"Strip":return new StripDecoder(e);case"Sequence":return new DecoderSequence(e);case"CTC":return new CTCDecoder(e);case"BPEDecoder":return new BPEDecoder(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}decode_chain(e){throw Error("`decode_chain` should be implemented in subclass.")}}class ReplaceDecoder extends Decoder{decode_chain(e){const t=createPattern(this.config.pattern);return t===null?e:e.map((e=>e.replaceAll(t,this.config.content)))}}class ByteFallback extends Decoder{constructor(e){super(e);this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let n=[];for(const r of e){let e=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){const t=parseInt(r.slice(3,5),16);if(!isNaN(t)){e=t}}if(e!==null){n.push(e)}else{if(n.length>0){const e=this.text_decoder.decode(Uint8Array.from(n));t.push(e);n=[]}t.push(r)}}if(n.length>0){const e=this.text_decoder.decode(Uint8Array.from(n));t.push(e);n=[]}return t}}class FuseDecoder extends Decoder{decode_chain(e){return[e.join("")]}}class StripDecoder extends Decoder{constructor(e){super(e);this.content=this.config.content;this.start=this.config.start;this.stop=this.config.stop}decode_chain(e){return e.map((e=>{let t=0;for(let n=0;n<this.start;++n){if(e[n]===this.content){t=n+1;continue}else{break}}let n=e.length;for(let t=0;t<this.stop;++t){const r=e.length-t-1;if(e[r]===this.content){n=r;continue}else{break}}return e.slice(t,n)}))}}class WordPieceDecoder extends Decoder{constructor(e){super(e);this.cleanup=e.cleanup}decode_chain(e){return e.map(((e,t)=>{if(t!==0){if(e.startsWith(this.config.prefix)){e=e.replace(this.config.prefix,"")}else{e=" "+e}}if(this.cleanup){e=clean_up_tokenization(e)}return e}))}}class ByteLevelDecoder extends Decoder{constructor(e){super(e);this.byte_decoder=UNICODE_TO_BYTES;this.text_decoder=new TextDecoder("utf-8",{fatal:false,ignoreBOM:true});this.end_of_word_suffix=null}convert_tokens_to_string(e){const t=e.join("");const n=new Uint8Array([...t].map((e=>this.byte_decoder[e])));const r=this.text_decoder.decode(n);return r}decode_chain(e){const t=[];let n=[];for(const r of e){if(this.added_tokens.find((e=>e.content===r))!==undefined){if(n.length>0){t.push(this.convert_tokens_to_string(n));n=[]}t.push(r)}else{n.push(r)}}if(n.length>0){t.push(this.convert_tokens_to_string(n))}return t}}class CTCDecoder extends Decoder{constructor(e){super(e);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(e){if(e.length===0)return"";const t=[e[0]];for(let n=1;n<e.length;++n){if(e[n]!==t.at(-1)){t.push(e[n])}}const n=t.filter((e=>e!==this.pad_token));let r=n.join("");if(this.cleanup){r=clean_up_tokenization(r).replaceAll(this.word_delimiter_token," ").trim()}return r}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class DecoderSequence extends Decoder{constructor(e){super(e);this.decoders=e.decoders.map((e=>Decoder.fromConfig(e)))}decode_chain(e){return this.decoders.reduce(((e,t)=>t.decode_chain(e)),e)}}class BPEDecoder extends Decoder{constructor(e){super(e);this.suffix=this.config.suffix}decode_chain(e){return e.map(((t,n)=>t.replaceAll(this.suffix,n===e.length-1?"":" ")))}}class VitsDecoder extends Decoder{decode_chain(e){let t="";for(let n=1;n<e.length;n+=2){t+=e[n]}return[t]}}class MetaspacePreTokenizer extends PreTokenizer{constructor(e){super();this.addPrefixSpace=e.add_prefix_space;this.replacement=e.replacement;this.strRep=e.str_rep||this.replacement;this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,{section_index:t=undefined}={}){let n=e.replaceAll(" ",this.strRep);if(this.addPrefixSpace&&!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&t===0)){n=this.strRep+n}return[n]}}class MetaspaceDecoder extends Decoder{constructor(e){super(e);this.addPrefixSpace=e.add_prefix_space;this.replacement=e.replacement}decode_chain(e){const t=[];for(let n=0;n<e.length;++n){let r=e[n].replaceAll(this.replacement," ");if(this.addPrefixSpace&&n==0&&r.startsWith(" ")){r=r.substring(1)}t.push(r)}return t}}class Precompiled extends Normalizer{constructor(e){super(e);this.charsmap=e.precompiled_charsmap}normalize(e){e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,"");e=e.replace(/[\u0009\u000A\u000C\u000D\u1680\u200B\u200C\u200E\u200F\u2028\u2029\u2581\uFEFF\uFFFD]/gm," ");if(e.includes("~")){const t=e.split("~");e=t.map((e=>e.normalize("NFKC"))).join("~")}else{e=e.normalize("NFKC")}return e}}class PreTokenizerSequence extends PreTokenizer{constructor(e){super();this.tokenizers=e.pretokenizers.map((e=>PreTokenizer.fromConfig(e)))}pre_tokenize_text(e,t){return this.tokenizers.reduce(((e,n)=>n.pre_tokenize(e,t)),[e])}}class WhitespacePreTokenizer extends PreTokenizer{constructor(e){super()}pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}}class WhitespaceSplit extends PreTokenizer{constructor(e){super()}pre_tokenize_text(e,t){return whitespace_split(e)}}class ReplacePreTokenizer extends PreTokenizer{constructor(e){super();this.config=e;this.pattern=createPattern(this.config.pattern);this.content=this.config.content}pre_tokenize_text(e,t){if(this.pattern===null){return[e]}return[e.replaceAll(this.pattern,this.config.content)]}}const SPECIAL_TOKEN_ATTRIBUTES=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function padHelper(e,t,n,r){for(const o of Object.keys(e)){const i=t-e[o].length;const s=n(o);const a=new Array(i).fill(s);e[o]=r==="right"?mergeArrays(e[o],a):mergeArrays(a,e[o])}}function truncateHelper(e,t){for(const n of Object.keys(e)){e[n].length=t}}class PreTrainedTokenizer extends Callable{return_token_type_ids=false;_default_chat_template=`{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}`;constructor(e,t){super();this._tokenizer_config=t;this.normalizer=Normalizer.fromConfig(e.normalizer);this.pre_tokenizer=PreTokenizer.fromConfig(e.pre_tokenizer);this.model=TokenizerModel.fromConfig(e.model,t);this.post_processor=PostProcessor.fromConfig(e.post_processor);this.decoder=Decoder.fromConfig(e.decoder);this.special_tokens=[];this.all_special_ids=[];this.added_tokens=[];for(const t of e.added_tokens){const e=new AddedToken(t);this.added_tokens.push(e);this.model.tokens_to_ids.set(e.content,e.id);this.model.vocab[e.id]=e.content;if(e.special){this.special_tokens.push(e.content);this.all_special_ids.push(e.id)}}this.additional_special_tokens=t.additional_special_tokens??[];this.special_tokens.push(...this.additional_special_tokens);this.special_tokens=[...new Set(this.special_tokens)];if(this.decoder){this.decoder.added_tokens=this.added_tokens;this.decoder.end_of_word_suffix=this.model.end_of_word_suffix}this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.map((e=>`${e.lstrip?"\\s*":""}(${escapeRegExp(e.content)})${e.rstrip?"\\s*":""}`)).join("|")):null;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.model_max_length=t.model_max_length;this.remove_space=t.remove_space;this.clean_up_tokenization_spaces=t.clean_up_tokenization_spaces??true;this.do_lowercase_and_remove_accent=t.do_lowercase_and_remove_accent??false;this.padding_side="right";this.legacy=false;this.chat_template=t.chat_template??null;if(Array.isArray(this.chat_template)){const e=Object.create(null);for(const{name:t,template:n}of this.chat_template){if(typeof t!=="string"||typeof n!=="string"){throw new Error('Chat template must be a list of objects with "name" and "template" properties')}e[t]=n}this.chat_template=e}this._compiled_template_cache=new Map}getToken(...e){for(const t of e){const e=this._tokenizer_config[t];if(!e)continue;if(typeof e==="object"){if(e.__type==="AddedToken"){return e.content}else{throw Error(`Unknown token: ${e}`)}}else{return e}}return null}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:o=false,revision:i="main",legacy:s=null}={}){const a=await loadTokenizer(e,{progress_callback:t,cache_dir:r,local_files_only:o,revision:i,legacy:s});return new this(...a)}_call(e,{text_pair:t=null,add_special_tokens:n=true,padding:r=false,truncation:o=null,max_length:i=null,return_tensor:s=true,return_token_type_ids:a=null}={}){const c=Array.isArray(e);let u;if(c){if(e.length===0){throw Error("text array must be non-empty")}if(t!==null){if(!Array.isArray(t)){throw Error("text_pair must also be an array")}else if(e.length!==t.length){throw Error("text and text_pair must have the same length")}u=e.map(((e,r)=>this._encode_plus(e,t[r],{add_special_tokens:n,return_token_type_ids:a})))}else{u=e.map((e=>this._encode_plus(e,null,{add_special_tokens:n,return_token_type_ids:a})))}}else{if(e===null||e===undefined){throw Error("text may not be null or undefined")}if(Array.isArray(t)){throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).")}u=[this._encode_plus(e,t,{add_special_tokens:n,return_token_type_ids:a})]}if(i===null){if(r==="max_length"){i=this.model_max_length}else{i=max(u.map((e=>e.input_ids.length)))[0]}}else{if(!o){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.`)}}i=Math.min(i,this.model_max_length);if(r||o){for(let e=0;e<u.length;++e){if(u[e].input_ids.length===i){continue}else if(u[e].input_ids.length>i){if(o){truncateHelper(u[e],i)}}else{if(r){padHelper(u[e],i,(e=>e==="input_ids"?this.pad_token_id:0),this.padding_side)}}}}const l={};if(s){if(!(r&&o)){if(u.some((e=>{for(const t of Object.keys(e)){if(e[t].length!==u[0][t]?.length){return true}}return false}))){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 e=[u.length,u[0].input_ids.length];for(const t of Object.keys(u[0])){l[t]=new Tensor("int64",BigInt64Array.from(u.flatMap((e=>e[t])).map(BigInt)),e)}}else{for(const e of Object.keys(u[0])){l[e]=u.map((t=>t[e]))}if(!c){for(const e of Object.keys(l)){l[e]=l[e][0]}}}return l}_encode_text(e){if(e===null)return null;const t=this.added_tokens_regex?e.split(this.added_tokens_regex).filter((e=>e)):[e];const n=t.map(((e,t)=>{const n=this.added_tokens.find((t=>t.content===e));if(n!==undefined){return e}else{if(this.remove_space===true){e=e.trim().split(/\s+/).join(" ")}if(this.do_lowercase_and_remove_accent){e=lowercase_and_remove_accent(e)}if(this.normalizer!==null){e=this.normalizer(e)}if(e.length===0){return[]}const n=this.pre_tokenizer!==null?this.pre_tokenizer(e,{section_index:t}):[e];const r=this.model(n);return r}})).flat();return n}_encode_plus(e,t=null,{add_special_tokens:n=true,return_token_type_ids:r=null}={}){const o=this._encode_text(e);const i=this._encode_text(t);const s=this.post_processor?this.post_processor(o,i,{add_special_tokens:n}):{tokens:mergeArrays(o??[],i??[])};const a=this.model.convert_tokens_to_ids(s.tokens);const c={input_ids:a,attention_mask:new Array(a.length).fill(1)};if((r??this.return_token_type_ids)&&s.token_type_ids){c.token_type_ids=s.token_type_ids}return c}encode(e,t=null,{add_special_tokens:n=true,return_token_type_ids:r=null}={}){const{input_ids:o}=this._encode_plus(e,t,{add_special_tokens:n,return_token_type_ids:r});return o}batch_decode(e,t={}){if(e instanceof Tensor){e=e.tolist()}return e.map((e=>this.decode(e,t)))}decode(e,t={}){if(e instanceof Tensor){e=prepareTensorForDecode(e)}if(!Array.isArray(e)||e.length===0||!isIntegralNumber(e[0])){throw Error("token_ids must be a non-empty array of integers.")}return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=false,clean_up_tokenization_spaces:n=null}){let r=this.model.convert_ids_to_tokens(e);if(t){r=r.filter((e=>!this.special_tokens.includes(e)))}let o=this.decoder?this.decoder(r):r.join(" ");if(this.decoder&&this.decoder.end_of_word_suffix){o=o.replaceAll(this.decoder.end_of_word_suffix," ");if(t){o=o.trim()}}if(n??this.clean_up_tokenization_spaces){o=clean_up_tokenization(o)}return o}get default_chat_template(){if(!this._warned_about_chat_template){console.warn("No chat template is defined for this tokenizer - using a default chat template "+"that implements the ChatML format. If the default is not appropriate for "+"your model, please set `tokenizer.chat_template` to an appropriate template. "+"See https://huggingface.co/docs/transformers/main/chat_templating for more information.");this._warned_about_chat_template=true}return this._default_chat_template}apply_chat_template(e,{chat_template:t=null,add_generation_prompt:n=false,tokenize:r=true,padding:o=false,truncation:i=false,max_length:s=null,return_tensor:a=true,tokenizer_kwargs:c={},...u}={}){if(this.chat_template&&typeof this.chat_template==="object"||this.chat_template===null&&this.default_chat_template&&typeof this.default_chat_template==="object"){const e=this.chat_template??this.default_chat_template;if(t!==null&&Object.hasOwn(e,t)){t=e[t]}else if(t===null&&"default"in e){t=e["default"]}else if(t===null){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(e).sort()}.`)}}else{t??=this.chat_template??this.default_chat_template}if(typeof t!=="string"){throw Error(`chat_template must be a string, but got ${typeof t}`)}let l=this._compiled_template_cache.get(t);if(l===undefined){l=new distExports.Template(t);this._compiled_template_cache.set(t,l)}const f=Object.create(null);for(const e of SPECIAL_TOKEN_ATTRIBUTES){const t=this.getToken(e);if(t){f[e]=t}}const d=l.render({messages:e,add_generation_prompt:n,...f,...u});if(r){return this._call(d,{add_special_tokens:false,padding:o,truncation:i,max_length:s,return_tensor:a,...c}).input_ids}return d}}class BertTokenizer extends PreTrainedTokenizer{return_token_type_ids=true}class AlbertTokenizer extends PreTrainedTokenizer{return_token_type_ids=true}class MobileBertTokenizer extends PreTrainedTokenizer{return_token_type_ids=true}class SqueezeBertTokenizer extends PreTrainedTokenizer{return_token_type_ids=true}class DebertaTokenizer extends PreTrainedTokenizer{return_token_type_ids=true}class DebertaV2Tokenizer extends PreTrainedTokenizer{return_token_type_ids=true}class HerbertTokenizer extends PreTrainedTokenizer{return_token_type_ids=true}class ConvBertTokenizer extends PreTrainedTokenizer{return_token_type_ids=true}class RoFormerTokenizer extends PreTrainedTokenizer{return_token_type_ids=true}class DistilBertTokenizer extends PreTrainedTokenizer{}class CamembertTokenizer extends PreTrainedTokenizer{}class XLMTokenizer extends PreTrainedTokenizer{return_token_type_ids=true;constructor(e,t){super(e,t);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class ElectraTokenizer extends PreTrainedTokenizer{return_token_type_ids=true}class T5Tokenizer extends PreTrainedTokenizer{}class GPT2Tokenizer extends PreTrainedTokenizer{_default_chat_template=`{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}`}class BartTokenizer extends PreTrainedTokenizer{}class MBartTokenizer extends PreTrainedTokenizer{constructor(e,t){super(e,t);this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/;this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e)));this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return _build_translation_inputs(this,e,t,n)}}class MBart50Tokenizer extends MBartTokenizer{}class RobertaTokenizer extends PreTrainedTokenizer{}class BloomTokenizer extends GPT2Tokenizer{constructor(e,t){const n=".,!?…。,、।۔،";const r=e.pre_tokenizer?.pretokenizers[0]?.pattern;if(r&&r.Regex===` ?[^(\\s|[${n}])]+`){r.Regex=` ?[^\\s${n}]+`}super(e,t)}}const SPIECE_UNDERLINE="▁";class LlamaTokenizer extends PreTrainedTokenizer{_default_chat_template=`{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<<SYS>>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<<SYS>>\n' + system_message + '\n<</SYS>>\n\n' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<<SYS>>\n' + content.strip() + '\n<</SYS>>\n\n' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}`;DEFAULT_SYSTEM_PROMPT="You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your "+"answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure "+"that your responses are socially unbiased and positive in nature.\n\n"+"If a question does not make any sense, or is not factually coherent, explain why instead of answering something not "+"correct. If you don't know the answer to a question, please don't share false information.";constructor(e,t){super(e,t);this.use_default_system_prompt=t.use_default_system_prompt??false;this.legacy=t.legacy??true;if(!this.legacy){this.normalizer=null;this.pre_tokenizer=new MetaspacePreTokenizer({replacement:SPIECE_UNDERLINE,add_prefix_space:true,prepend_scheme:"first"})}}_encode_text(e){if(e===null)return null;if(this.legacy||e.length===0){return super._encode_text(e)}let t=super._encode_text(SPIECE_UNDERLINE+e.replaceAll(SPIECE_UNDERLINE," "));if(t.length>1&&t[0]===SPIECE_UNDERLINE&&this.special_tokens.includes(t[1])){t=t.slice(1)}return t}get default_chat_template(){return super.default_chat_template.replaceAll("USE_DEFAULT_PROMPT",this.use_default_system_prompt?"true":"false").replaceAll("DEFAULT_SYSTEM_MESSAGE",this.DEFAULT_SYSTEM_PROMPT.replaceAll("\n","\\n").replaceAll("'","\\'"))}}class CodeLlamaTokenizer extends LlamaTokenizer{}class XLMRobertaTokenizer extends PreTrainedTokenizer{}class MPNetTokenizer extends PreTrainedTokenizer{}class FalconTokenizer extends PreTrainedTokenizer{}class GPTNeoXTokenizer extends PreTrainedTokenizer{}class EsmTokenizer extends PreTrainedTokenizer{}class Qwen2Tokenizer extends PreTrainedTokenizer{}class GemmaTokenizer extends PreTrainedTokenizer{_default_chat_template="{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '<start_of_turn>' + role + '\n' + message['content'] | trim + '<end_of_turn>\n' }}{% endfor %}{% if add_generation_prompt %}{{'<start_of_turn>model\n'}}{% endif %}"}class Grok1Tokenizer extends PreTrainedTokenizer{}function _build_translation_inputs(e,t,n,r){if(!("language_codes"in e)||!Array.isArray(e.language_codes)){throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.")}if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp)){throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.")}if(!("lang_to_token"in e)||typeof e.lang_to_token!=="function"){throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.")}const o=r.src_lang;const i=r.tgt_lang;if(!e.language_codes.includes(i)){throw new Error(`Target language code "${i}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`)}if(o!==undefined){if(!e.language_codes.includes(o)){throw new Error(`Source language code "${o}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`)}for(const t of e.post_processor.config.single){if("SpecialToken"in t&&e.languageRegex.test(t.SpecialToken.id)){t.SpecialToken.id=e.lang_to_token(o);break}}}r.forced_bos_token_id=e.model.convert_tokens_to_ids([e.lang_to_token(i)])[0];return e._call(t,n)}class NllbTokenizer extends PreTrainedTokenizer{constructor(e,t){super(e,t);this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/;this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e)));this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return _build_translation_inputs(this,e,t,n)}}class M2M100Tokenizer extends PreTrainedTokenizer{constructor(e,t){super(e,t);this.languageRegex=/^__[a-z]{2,3}__$/;this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))).map((e=>e.slice(2,-2)));this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return _build_translation_inputs(this,e,t,n)}}const WHISPER_LANGUAGES=[["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"]];const WHISPER_LANGUAGE_MAPPING=new Map(WHISPER_LANGUAGES);const WHISPER_TO_LANGUAGE_CODE_MAPPING=new Map([...WHISPER_LANGUAGES.map((([e,t])=>[t,e])),...[["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]]);class WhisperTokenizer extends PreTrainedTokenizer{_default_chat_template=`{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}`;_decode_asr(e,{return_timestamps:t=false,return_language:n=false,time_precision:r=null,force_full_sequences:o=true}={}){if(r===null){throw Error("Must specify time_precision")}let i=null;const s=t==="word";function a(){return{language:i,timestamp:[null,null],text:""}}const c=[];let u=a();let l=0;const f=this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1;let d=[];let h=[];let p=false;let m=null;const w=new Set(this.all_special_ids);for(const n of e){const e=n.tokens;const o=s?n.token_timestamps:null;let g=null;let v=f;if("stride"in n){const[t,o,i]=n.stride;l-=o;m=t-i;if(o){v=o/r+f}if(i){for(let t=e.length-1;t>=0;--t){const n=e[t];if(n>=f){if(g!==null&&(n-f)*r<m){break}g=n}}}}let y=[];let _=[];for(let n=0;n<e.length;++n){const m=e[n];if(w.has(m)){const e=this.decode([m]);const n=WHISPER_LANGUAGE_MAPPING.get(e.slice(2,-2));if(n!==undefined){if(i!==null&&n!==i&&!t){d.push(y);const e=this.findLongestCommonSequence(d)[0];const t=this.decode(e);u.text=t;c.push(u);d=[];y=[];u=a()}i=u.language=n}}else if(m>=f){const e=(m-f)*r+l;const t=round(e,2);if(g!==null&&m>=g){p=true}else if(p||d.length>0&&m<v){p=false}else if(u.timestamp[0]===null){u.timestamp[0]=t}else{if(t===u.timestamp[0]);else{u.timestamp[1]=t;d.push(y);if(s){h.push(_)}const[e,n]=this.findLongestCommonSequence(d,h);const r=this.decode(e);u.text=r;if(s){u.words=this.collateWordTimestamps(e,n,i)}c.push(u);d=[];y=[];h=[];_=[];u=a()}}}else{y.push(m);if(s){let e=round(o[n]+l,2);let t;if(n+1<o.length){t=round(o[n+1]+l,2)}else{t=null}_.push([e,t])}}}if("stride"in n){const[e,t,r]=n.stride;l+=e-r}if(y.length>0){d.push(y);if(s){h.push(_)}}else if(d.every((e=>e.length===0))){u=a();d=[];y=[];h=[];_=[]}}if(d.length>0){if(o&&t){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[e,n]=this.findLongestCommonSequence(d,h);const r=this.decode(e);u.text=r;if(s){u.words=this.collateWordTimestamps(e,n,i)}c.push(u)}let g=Object.create(null);const v=c.map((e=>e.text)).join("");if(t||n){for(let e=0;e<c.length;++e){const r=c[e];if(!t){delete r["timestamp"]}if(!n){delete r["language"]}}if(s){const e=[];for(const t of c){for(const n of t.words){e.push(n)}}g={chunks:e}}else{g={chunks:c}}}return[v,g]}findLongestCommonSequence(e,t=null){let n=e[0];let r=n.length;let o=[];const i=Array.isArray(t)&&t.length>0;let s=i?[]:null;let a=i?t[0]:null;for(let c=1;c<e.length;++c){const u=e[c];let l=0;let f=[r,r,0,0];const d=u.length;for(let e=1;e<r+d;++e){const t=e/1e4;const o=Math.max(0,r-e);const i=Math.min(r,r+d-e);const s=n.slice(o,i);const a=Math.max(0,e-r);const c=Math.min(d,e);const h=u.slice(a,c);if(s.length!==h.length){throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.")}const p=s.filter(((e,t)=>e===h[t])).length;const m=p/e+t;if(p>1&&m>l){l=m;f=[o,i,a,c]}}const[h,p,m,w]=f;const g=Math.floor((p+h)/2);const v=Math.floor((w+m)/2);o.push(...n.slice(0,g));n=u.slice(v);r=n.length;if(i){s.push(...a.slice(0,g));a=t[c].slice(v)}}o.push(...n);if(i){s.push(...a);return[o,s]}else{return[o,[]]}}collateWordTimestamps(e,t,n){const[r,o,i]=this.combineTokensIntoWords(e,n);const s=[];for(let e=0;e<r.length;++e){const n=i[e];s.push({text:r[e],timestamp:[t[n.at(0)][0],t[n.at(-1)][1]]})}return s}combineTokensIntoWords(e,t,n="\"'“¡¿([{-",r="\"'.。,,!!??::”)]}、"){t=t??"english";let o,i,s;if(["chinese","japanese","thai","lao","myanmar"].includes(t)){[o,i,s]=this.splitTokensOnUnicode(e)}else{[o,i,s]=this.splitTokensOnSpaces(e)}return this.mergePunctuations(o,i,s,n,r)}decode(e,t){let n;if(t&&t.decode_with_timestamps){if(e instanceof Tensor){e=prepareTensorForDecode(e)}n=this.decodeWithTimestamps(e,t)}else{n=super.decode(e,t)}return n}decodeWithTimestamps(e,t){const n=t?.time_precision??.02;const r=Array.from(this.all_special_ids).at(-1)+1;let o=[[]];for(const t of e){if(t>=r){const e=round((t-r)*n,2);o.push(`<|${e}|>`);o.push([])}else{o[o.length-1].push(t)}}o=o.map((e=>{if(typeof e==="string"){return e}else{return super.decode(e,t)}}));return o.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:true});const n="�";const r=[];const o=[];const i=[];let s=[];let a=[];let c=0;for(let u=0;u<e.length;++u){const l=e[u];s.push(l);a.push(u);const f=this.decode(s,{decode_with_timestamps:true});if(!f.includes(n)||t[c+f.indexOf(n)]===n){r.push(f);o.push(s);i.push(a);s=[];a=[];c+=f.length}}return[r,o,i]}splitTokensOnSpaces(e){const[t,n,r]=this.splitTokensOnUnicode(e);const o=[];const i=[];const s=[];const a=new RegExp(`^[${PUNCTUATION_REGEX}]$`,"gu");for(let e=0;e<t.length;++e){const c=t[e];const u=n[e];const l=r[e];const f=u[0]>=this.model.tokens_to_ids.get("<|endoftext|>");const d=c.startsWith(" ");const h=c.trim();const p=a.test(h);if(f||d||p||o.length===0){o.push(c);i.push(u);s.push(l)}else{const e=o.length-1;o[e]+=c;i[e].push(...u);s[e].push(...l)}}return[o,i,s]}mergePunctuations(e,t,n,r,o){const i=structuredClone(e);const s=structuredClone(t);const a=structuredClone(n);let c=i.length-2;let u=i.length-1;while(c>=0){if(i[c].startsWith(" ")&&r.includes(i[c].trim())){i[u]=i[c]+i[u];s[u]=mergeArrays(s[c],s[u]);a[u]=mergeArrays(a[c],a[u]);i[c]="";s[c]=[];a[c]=[]}else{u=c}--c}c=0;u=1;while(u<i.length){if(!i[c].endsWith(" ")&&o.includes(i[u])){i[c]+=i[u];s[c]=mergeArrays(s[c],s[u]);a[c]=mergeArrays(a[c],a[u]);i[u]="";s[u]=[];a[u]=[]}else{c=u}++u}return[i.filter((e=>e)),s.filter((e=>e.length>0)),a.filter((e=>e.length>0))]}get_decoder_prompt_ids({language:e=null,task:t=null,no_timestamps:n=true}={}){const r=[];if(e){e=e.toLowerCase();let t=WHISPER_TO_LANGUAGE_CODE_MAPPING.get(e);if(t===undefined){if(WHISPER_LANGUAGE_MAPPING.has(e)){t=e}else{const t=e.length===2;const n=t?WHISPER_LANGUAGE_MAPPING.keys():WHISPER_LANGUAGE_MAPPING.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(n)}`)}}const n=this.model.tokens_to_ids.get(`<|${t}|>`);if(n===undefined){throw new Error(`Unable to find language "${t}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`)}r.push(n)}else{r.push(null)}if(t){t=t.toLowerCase();if(t!=="transcribe"&&t!=="translate"){throw new Error(`Task "${t}" is not supported. Must be one of: ["transcribe", "translate"]`)}const e=this.model.tokens_to_ids.get(`<|${t}|>`);if(e===undefined){throw new Error(`Unable to find task "${t}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`)}r.push(e)}else{r.push(null)}if(n){const e=this.model.tokens_to_ids.get(`<|notimestamps|>`);if(e===undefined){throw new Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.')}r.push(e)}return r.map(((e,t)=>[t+1,e])).filter((e=>e[1]!==null))}}class CodeGenTokenizer extends PreTrainedTokenizer{}class CLIPTokenizer extends PreTrainedTokenizer{}class SiglipTokenizer extends PreTrainedTokenizer{}class MarianTokenizer extends PreTrainedTokenizer{constructor(e,t){super(e,t);this.languageRegex=/^(>>\w+<<)\s*/g;this.supported_language_codes=this.model.vocab.filter((e=>this.languageRegex.test(e)));console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;const[t,...n]=e.trim().split(this.languageRegex);if(n.length===0){return super._encode_text(t)}else if(n.length===2){const[e,t]=n;if(!this.supported_language_codes.includes(e)){console.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`)}return mergeArrays([e],super._encode_text(t))}}}class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer{}class BlenderbotTokenizer extends PreTrainedTokenizer{_default_chat_template=`{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}`}class BlenderbotSmallTokenizer extends BlenderbotTokenizer{}class SpeechT5Tokenizer extends PreTrainedTokenizer{}class NougatTokenizer extends PreTrainedTokenizer{}class VitsTokenizer extends PreTrainedTokenizer{constructor(e,t){super(e,t);this.decoder=new VitsDecoder({})}}class CohereTokenizer extends PreTrainedTokenizer{}class AutoTokenizer{static TOKENIZER_CLASS_MAPPING={T5Tokenizer,DistilBertTokenizer,CamembertTokenizer,DebertaTokenizer,DebertaV2Tokenizer,BertTokenizer,HerbertTokenizer,ConvBertTokenizer,RoFormerTokenizer,XLMTokenizer,ElectraTokenizer,MobileBertTokenizer,SqueezeBertTokenizer,AlbertTokenizer,GPT2Tokenizer,BartTokenizer,MBartTokenizer,MBart50Tokenizer,RobertaTokenizer,WhisperTokenizer,CodeGenTokenizer,CLIPTokenizer,SiglipTokenizer,MarianTokenizer,BloomTokenizer,NllbTokenizer,M2M100Tokenizer,LlamaTokenizer,CodeLlamaTokenizer,XLMRobertaTokenizer,MPNetTokenizer,FalconTokenizer,GPTNeoXTokenizer,EsmTokenizer,Wav2Vec2CTCTokenizer,BlenderbotTokenizer,BlenderbotSmallTokenizer,SpeechT5Tokenizer,NougatTokenizer,VitsTokenizer,Qwen2Tokenizer,GemmaTokenizer,Grok1Tokenizer,CohereTokenizer,PreTrainedTokenizer};static async from_pretrained(e,{quantized:t=true,progress_callback:n=null,config:r=null,cache_dir:o=null,local_files_only:i=false,revision:s="main",legacy:a=null}={}){const[c,u]=await loadTokenizer(e,{progress_callback:n,cache_dir:o,local_files_only:i,revision:s,legacy:a});const l=u.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let f=this.TOKENIZER_CLASS_MAPPING[l];if(!f){console.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`);f=PreTrainedTokenizer}return new f(c,u)}}async function loadConfig(e,t){let n=await getModelJSON(e,"config.json",true,t);return n}class PretrainedConfig{constructor(e){this.model_type=null;this.is_encoder_decoder=false;Object.assign(this,e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:o=false,revision:i="main"}={}){let s=n??await loadConfig(e,{progress_callback:t,cache_dir:r,local_files_only:o,revision:i});return new this(s)}}class AutoConfig{static async from_pretrained(...e){return PretrainedConfig.from_pretrained(...e)}}class LogitsProcessorList extends Callable{constructor(){super();this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){for(let n of t){this.processors.forEach((t=>t(e,n)))}}[Symbol.iterator](){return this.processors.values()}}class LogitsProcessor extends Callable{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class ForceTokensLogitsProcessor extends LogitsProcessor{constructor(e){super();this.force_token_map=Object.fromEntries(e??[])}_call(e,t){let n=this.force_token_map[e.length];if(exists(n)){t.data.fill(-Infinity);t.data[n]=0}return t}}class ForcedBOSTokenLogitsProcessor extends LogitsProcessor{constructor(e){super();this.bos_token_id=e}_call(e,t){if(e.length===1){t.data.fill(-Infinity);t.data[this.bos_token_id]=0}return t}}class ForcedEOSTokenLogitsProcessor extends LogitsProcessor{constructor(e,t){super();this.max_length=e;this.forced_eos_token_id=t}_call(e,t){}}class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor{constructor(e,t){super();this.begin_suppress_tokens=e;this.begin_index=t}_call(e,t){if(e.length===this.begin_index){for(let e of this.begin_suppress_tokens){t.data[e]=-Infinity}}return t}}class WhisperTimeStampLogitsProcessor extends LogitsProcessor{constructor(e){super();this.eos_token_id=e.eos_token_id;this.no_timestamps_token_id=e.no_timestamps_token_id;this.timestamp_begin=this.no_timestamps_token_id+1;this.begin_index=(e.forced_decoder_ids||[]).length+2;if(e.forced_decoder_ids.slice(-1)[0][1]===this.no_timestamps_token_id){this.begin_index-=1}this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){const n=t.data;n[this.no_timestamps_token_id]=-Infinity;if(e.length===this.begin_index-1){n.fill(-Infinity);n[this.timestamp_begin]=0;return t}const r=e.slice(this.begin_index);const o=r.length>=1&&r[r.length-1]>=this.timestamp_begin;const i=r.length<2||r[r.length-2]>=this.timestamp_begin;if(o){if(i){n.subarray(this.timestamp_begin).fill(-Infinity)}else{n.subarray(0,this.eos_token_id).fill(-Infinity)}}if(e.length===this.begin_index&&this.max_initial_timestamp_index!==null){const e=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(e+1).fill(-Infinity)}const s=log_softmax(n);const a=Math.log(s.subarray(this.timestamp_begin).map(Math.exp).reduce(((e,t)=>e+t)));const c=max(s.subarray(0,this.timestamp_begin))[0];if(a>c){n.subarray(0,this.timestamp_begin).fill(-Infinity)}return t}}class NoRepeatNGramLogitsProcessor extends LogitsProcessor{constructor(e){super();this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length;const n=[];for(let r=0;r<t+1-this.no_repeat_ngram_size;++r){const t=[];for(let n=0;n<this.no_repeat_ngram_size;++n){t.push(e[r+n])}n.push(t)}const r=new Map;for(const e of n){const t=e.slice(0,e.length-1);const n=JSON.stringify(t);const o=r.get(n)??[];o.push(e[e.length-1]);r.set(n,o)}return r}getGeneratedNgrams(e,t){const n=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);const r=e.get(JSON.stringify(n))??[];return r}calcBannedNgramTokens(e){const t=[];if(e.length+1<this.no_repeat_ngram_size){return t}else{const t=this.getNgrams(e);const n=this.getGeneratedNgrams(t,e);return n}}_call(e,t){const n=this.calcBannedNgramTokens(e);for(const e of n){t.data[e]=-Infinity}return t}}class RepetitionPenaltyLogitsProcessor extends LogitsProcessor{constructor(e){super();this.penalty=e}_call(e,t){for(const n of e){if(t.data[n]<0){t.data[n]*=this.penalty}else{t.data[n]/=this.penalty}}return t}}class MinLengthLogitsProcessor extends LogitsProcessor{constructor(e,t){super();this.min_length=e;this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){if(e.length<this.min_length){for(const e of this.eos_token_id){t.data[e]=-Infinity}}return t}}class MinNewTokensLengthLogitsProcessor extends LogitsProcessor{constructor(e,t,n){super();this.prompt_length_to_skip=e;this.min_new_tokens=t;this.eos_token_id=Array.isArray(n)?n:[n]}_call(e,t){const n=e.length-this.prompt_length_to_skip;if(n<this.min_new_tokens){for(const e of this.eos_token_id){t.data[e]=-Infinity}}return t}}class NoBadWordsLogitsProcessor extends LogitsProcessor{constructor(e,t){super();this.bad_words_ids=e;this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(const n of this.bad_words_ids){let r=true;for(let t=1;t<=n.length-1&&n.length<e.length;++t){if(n.at(-t-1)!==e.at(-t)){r=false;break}}if(r){t.data[n.at(-1)]=-Infinity}}return t}}const GenerationConfig=class{constructor(e={}){this.max_length=e.max_length??20;this.max_new_tokens=e.max_new_tokens??null;this.min_length=e.min_length??0;this.min_new_tokens=e.min_new_tokens??null;this.early_stopping=e.early_stopping??false;this.max_time=e.max_time??null;this.do_sample=e.do_sample??false;this.num_beams=e.num_beams??1;this.num_beam_groups=e.num_beam_groups??1;this.penalty_alpha=e.penalty_alpha??null;this.use_cache=e.use_cache??true;this.temperature=e.temperature??1;this.top_k=e.top_k??50;this.top_p=e.top_p??1;this.typical_p=e.typical_p??1;this.epsilon_cutoff=e.epsilon_cutoff??0;this.eta_cutoff=e.eta_cutoff??0;this.diversity_penalty=e.diversity_penalty??0;this.repetition_penalty=e.repetition_penalty??1;this.encoder_repetition_penalty=e.encoder_repetition_penalty??1;this.length_penalty=e.length_penalty??1;this.no_repeat_ngram_size=e.no_repeat_ngram_size??0;this.bad_words_ids=e.bad_words_ids??null;this.force_words_ids=e.force_words_ids??null;this.renormalize_logits=e.renormalize_logits??false;this.constraints=e.constraints??null;this.forced_bos_token_id=e.forced_bos_token_id??null;this.forced_eos_token_id=e.forced_eos_token_id??null;this.remove_invalid_values=e.remove_invalid_values??false;this.exponential_decay_length_penalty=e.exponential_decay_length_penalty??null;this.suppress_tokens=e.suppress_tokens??null;this.begin_suppress_tokens=e.begin_suppress_tokens??null;this.forced_decoder_ids=e.forced_decoder_ids??null;this.num_return_sequences=e.num_return_sequences??1;this.output_attentions=e.output_attentions??false;this.output_hidden_states=e.output_hidden_states??false;this.output_scores=e.output_scores??false;this.return_dict_in_generate=e.return_dict_in_generate??false;this.pad_token_id=e.pad_token_id??null;this.bos_token_id=e.bos_token_id??null;this.eos_token_id=e.eos_token_id??null;this.encoder_no_repeat_ngram_size=e.encoder_no_repeat_ngram_size??0;this.decoder_start_token_id=e.decoder_start_token_id??null;this.generation_kwargs=e.generation_kwargs??{}}};class Sampler extends Callable{constructor(e){super();this.generation_config=e}_call(e,t=-1){return this.sample(e,t)}sample(e,t){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let n=e.dims.at(-1);let r=e.data;if(t===-1){r=r.slice(-n)}else{let e=t*n;r=r.slice(e,e+n)}if(this.generation_config.temperature>0){r=r.map((e=>e/this.generation_config.temperature))}return r}randomSelect(e){let t=e.reduce(((e,t)=>e+t),0);let n=Math.random()*t;for(let t=0;t<e.length;++t){n-=e[t];if(n<=0){return t}}return 0}static getSampler(e){if(e.do_sample){return new MultinomialSampler(e)}else if(e.num_beams>1){return new BeamSearchSampler(e)}else{if(e.num_return_sequences>1){throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`)}return new GreedySampler(e)}}}class GreedySampler extends Sampler{sample(e,t=-1){let n=this.getLogits(e,t);let r=max(n)[1];return[[r,0]]}}class MultinomialSampler extends Sampler{sample(e,t=-1){let n=e.dims.at(-1);if(this.generation_config.top_k>0){n=Math.min(this.generation_config.top_k,n)}const r=this.getLogits(e,t);const o=getTopItems(r,n);const i=softmax(o.map((e=>e[1])));return Array.from({length:this.generation_config.num_beams},(()=>{const e=this.randomSelect(i);return[o[e][0],Math.log(i[e])]}))}}class BeamSearchSampler extends Sampler{sample(e,t=-1){let n=e.dims.at(-1);if(this.generation_config.top_k>0){n=Math.min(this.generation_config.top_k,n)}const r=this.getLogits(e,t);const o=getTopItems(r,n);const i=softmax(o.map((e=>e[1])));return Array.from({length:this.generation_config.num_beams},((e,t)=>[o[t][0],Math.log(i[t])]))}}const{InferenceSession,Tensor:ONNXTensor,env}=ONNX;const MODEL_TYPES={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5};const MODEL_TYPE_MAPPING=new Map;const MODEL_NAME_TO_CLASS_MAPPING=new Map;const MODEL_CLASS_TO_NAME_MAPPING=new Map;async function constructSession(e,t,n){let r=`onnx/${t}${n.quantized?"_quantized":""}.onnx`;let o=await getModelFile(e,r,true,n);try{return await InferenceSession.create(o,{executionProviders})}catch(e){if(executionProviders.length===1&&executionProviders[0]==="wasm"){throw e}console.warn(e);console.warn("Something went wrong during model construction (most likely a missing operation). "+"Using `wasm` as a fallback. ");return await InferenceSession.create(o,{executionProviders:["wasm"]})}}function validateInputs(e,t){const n=Object.create(null);const r=[];for(const o of e.inputNames){const e=t[o];if(!(e instanceof Tensor)){r.push(o);continue}n[o]=env.wasm.proxy?e.clone():e}if(r.length>0){throw new Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(", ")}.`)}const o=Object.keys(t).length;const i=e.inputNames.length;if(o>i){let n=Object.keys(t).filter((t=>!e.inputNames.includes(t)));console.warn(`WARNING: Too many inputs were provided (${o} > ${i}). The following inputs will be ignored: "${n.join(", ")}".`)}return n}async function sessionRun(e,t){const n=validateInputs(e,t);try{let t=await e.run(n);t=replaceTensors(t);return t}catch(e){console.error(`An error occurred during model execution: "${e}".`);console.error("Inputs given to model:",n);throw e}}function replaceTensors(e){for(let t in e){if(e[t]instanceof ONNXTensor){e[t]=new Tensor(e[t])}else if(typeof e[t]==="object"){replaceTensors(e[t])}}return e}function toI64Tensor(e){if(e instanceof Tensor){return e}if(e.length===0){throw Error("items must be non-empty")}if(Array.isArray(e[0])){if(e.some((t=>t.length!==e[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 Tensor("int64",BigInt64Array.from(e.flat().map((e=>BigInt(e)))),[e.length,e[0].length])}else{return new Tensor("int64",BigInt64Array.from(e.map((e=>BigInt(e)))),[1,e.length])}}function prepareAttentionMask(e,t){let n=e.config.pad_token_id??null;let r=e.config.eos_token_id??null;if(isIntegralNumber(r)){r=[r]}let o=t.indexOf(n)!==-1;let i=r===null||!r.includes(n);if(o&&i){let e=BigInt64Array.from(t.data.map((e=>e!=n)));return new Tensor("int64",e,t.dims)}else{return ones_like(t)}}function preparePositionIds(e,t,n){if(!e.inputNames.includes("position_ids"))return;const r=new BigInt64Array(t.attention_mask.data.length);for(let e=0;e<t.attention_mask.dims[0];++e){let n=e*t.attention_mask.dims[1];let o=BigInt(0);for(let e=0;e<t.attention_mask.dims[1];++e){const i=n+e;if(t.attention_mask.data[i]===0n){r[i]=BigInt(1)}else{r[i]=o;o+=t.attention_mask.data[i]}}}t.position_ids=new Tensor("int64",r,t.attention_mask.dims);if(n){t.position_ids=t.position_ids.slice(null,-1).unsqueeze_(-1)}}function boolTensor(e){return new Tensor("bool",[e],[1])}async function seq2seqForward(e,t){let{encoder_outputs:n,past_key_values:r}=t;if(!n){n=(await encoderForward(e,t)).last_hidden_state}let o={input_ids:t.decoder_input_ids,encoder_hidden_states:n};const i=!!r;if(e.decoder_merged_session.inputNames.includes("use_cache_branch")){o.use_cache_branch=boolTensor(i)}if(e.decoder_merged_session.inputNames.includes("encoder_attention_mask")){o.encoder_attention_mask=t.attention_mask}preparePositionIds(e.decoder_merged_session,o,i);e.addPastKeyValues(o,r);const s=await sessionRun(e.decoder_merged_session,o);let a=s.logits;r=e.getPastKeyValues(s,r);const c=e.getAttentions(s);return new Seq2SeqLMOutput({logits:a,past_key_values:r,encoder_outputs:n,...c})}function seq2seqStartBeams(e,t,n,r){let o=[];let i=0;const s=e.requires_attention_mask??true;let a=n.decoder_input_ids??n.decoder_start_token_id??n.bos_token_id??n.eos_token_id;if(a instanceof Tensor){a=a.tolist().flat()}else if(!Array.isArray(a)){a=[a]}for(let n of t){n.dims=[1,...n.dims];let t={inputs:n,encoder_outputs:null,prev_model_outputs:null,output_token_ids:a,done:false,score:0,id:i++};if(s){t.attention_mask=prepareAttentionMask(e,n)}o.push(t)}return o}async function seq2seqRunBeam(e,t){const n=e.main_input_name;let r=t.output_token_ids;if(t.prev_model_outputs){r=r.slice(-1)}let o={[n]:t.inputs,decoder_input_ids:toI64Tensor(r),encoder_outputs:t.encoder_outputs,past_key_values:t.prev_model_outputs?.past_key_values};if(t.attention_mask){o.attention_mask=t.attention_mask}let i=await e.forward(o);t.prev_model_outputs=i;t.encoder_outputs=i.encoder_outputs;return i}function seq2seqUpdatebeam(e,t){e.output_token_ids=[...e.output_token_ids,t]}async function encoderForward(e,t){const n=Object.create(null);for(const r of e.session.inputNames){n[r]=t[r]}if(e.session.inputNames.includes("token_type_ids")&&!n.token_type_ids){n.token_type_ids=new Tensor("int64",new BigInt64Array(n.input_ids.data.length),n.input_ids.dims)}return await sessionRun(e.session,n)}async function decoderForward(e,t){let{input_ids:n,past_key_values:r,attention_mask:o}=t;let i={input_ids:n,attention_mask:o??prepareAttentionMask(e,n)};const s=!!r;if(e.session.inputNames.includes("use_cache_branch")){i.use_cache_branch=boolTensor(s)}preparePositionIds(e.session,i,s);e.addPastKeyValues(i,r);let a=await sessionRun(e.session,i);let c=a.logits;r=e.getPastKeyValues(a,r);return{logits:c,past_key_values:r}}function decoderStartBeams(e,t,n,r,o){let i=[];let s=0;for(let n of t){let t=n.tolist().map(Number);n.dims=[1,...n.dims];let a;if(o){a=o[s];a.dims=[1,...a.dims]}else{a=prepareAttentionMask(e,n)}let c={input:n,model_input_ids:n,attention_mask:a,prev_model_outputs:null,output_token_ids:t,num_output_tokens:r,done:false,score:0,id:s++};i.push(c)}return i}async function decoderRunBeam(e,t){let n=new BigInt64Array(t.output_token_ids.length).fill(1n);let r={input_ids:t.model_input_ids,attention_mask:new Tensor("int64",n,[1,n.length]),past_key_values:t.prev_model_outputs?.past_key_values};let o=await e.forward(r);t.prev_model_outputs=o;return o}function decoderUpdatebeam(e,t){e.output_token_ids=[...e.output_token_ids,t];e.model_input_ids=new Tensor("int64",[BigInt(t)],[1,1])}class PreTrainedModel extends Callable{main_input_name="input_ids";constructor(e,t){super();this.config=e;this.session=t;const n=MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);const r=MODEL_TYPE_MAPPING.get(n);this.can_generate=false;this._runBeam=null;this._getStartBeams=null;this._updateBeam=null;this._forward=null;if(r===MODEL_TYPES.DecoderOnly){this.can_generate=true;this._runBeam=decoderRunBeam;this._getStartBeams=decoderStartBeams;this._updateBeam=decoderUpdatebeam;this._forward=decoderForward}else if(r===MODEL_TYPES.Seq2Seq||r===MODEL_TYPES.Vision2Seq){this.can_generate=true;this._runBeam=seq2seqRunBeam;this._getStartBeams=seq2seqStartBeams;this._updateBeam=seq2seqUpdatebeam;this._forward=seq2seqForward}else if(r===MODEL_TYPES.EncoderDecoder){this._forward=encoderForward}else{this._forward=encoderForward}}async dispose(){const e=[];for(let t of Object.keys(this)){const n=this[t];if(n instanceof InferenceSession){e.push(n.handler.dispose())}}return await Promise.all(e)}static async from_pretrained(e,{quantized:t=true,progress_callback:n=null,config:r=null,cache_dir:o=null,local_files_only:i=false,revision:s="main",model_file_name:a=null}={}){let c={quantized:t,progress_callback:n,config:r,cache_dir:o,local_files_only:i,revision:s,model_file_name:a};const u=MODEL_CLASS_TO_NAME_MAPPING.get(this);const l=MODEL_TYPE_MAPPING.get(u);let f;if(l===MODEL_TYPES.DecoderOnly){f=await Promise.all([AutoConfig.from_pretrained(e,c),constructSession(e,c.model_file_name??"decoder_model_merged",c),getModelJSON(e,"generation_config.json",false,c)])}else if(l===MODEL_TYPES.Seq2Seq||l===MODEL_TYPES.Vision2Seq){f=await Promise.all([AutoConfig.from_pretrained(e,c),constructSession(e,"encoder_model",c),constructSession(e,"decoder_model_merged",c),getModelJSON(e,"generation_config.json",false,c)])}else if(l===MODEL_TYPES.MaskGeneration){f=await Promise.all([AutoConfig.from_pretrained(e,c),constructSession(e,"vision_encoder",c),constructSession(e,"prompt_encoder_mask_decoder",c)])}else if(l===MODEL_TYPES.EncoderDecoder){f=await Promise.all([AutoConfig.from_pretrained(e,c),constructSession(e,"encoder_model",c),constructSession(e,"decoder_model_merged",c)])}else{if(l!==MODEL_TYPES.EncoderOnly){console.warn(`Model type for '${u??r?.model_type}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`)}f=await Promise.all([AutoConfig.from_pretrained(e,c),constructSession(e,c.model_file_name??"model",c)])}return new this(...f)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}_get_logits_processor(e,t,n=null){const r=new LogitsProcessorList;if(e.repetition_penalty!==null&&e.repetition_penalty!==1){r.push(new RepetitionPenaltyLogitsProcessor(e.repetition_penalty))}if(e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0){r.push(new NoRepeatNGramLogitsProcessor(e.no_repeat_ngram_size))}if(e.bad_words_ids!==null){r.push(new NoBadWordsLogitsProcessor(e.bad_words_ids,e.eos_token_id))}if(e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0){r.push(new MinLengthLogitsProcessor(e.min_length,e.eos_token_id))}if(e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0){r.push(new MinNewTokensLengthLogitsProcessor(t,e.min_new_tokens,e.eos_token_id))}if(e.forced_bos_token_id!==null){r.push(new ForcedBOSTokenLogitsProcessor(e.forced_bos_token_id))}if(e.forced_eos_token_id!==null){r.push(new ForcedEOSTokenLogitsProcessor(e.max_length,e.forced_eos_token_id))}if(e.begin_suppress_tokens!==null){let n=t>1||e.forced_bos_token_id===null?t:t+1;if(e.forced_decoder_ids!==null){n+=e.forced_decoder_ids[e.forced_decoder_ids.length-1][0]}r.push(new SuppressTokensAtBeginLogitsProcessor(e.begin_suppress_tokens,n))}if(e.forced_decoder_ids!==null){r.push(new ForceTokensLogitsProcessor(e.forced_decoder_ids))}if(n!==null){r.extend(n)}return r}_get_generation_config(e){let t=new GenerationConfig(this.config);if("generation_config"in this){Object.assign(t,this.generation_config)}if(e!==null){Object.assign(t,e)}return t}async generate(e,t=null,n=null,{inputs_attention_mask:r=null}={}){if(!this.can_generate){const e=MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);let t=`The current model class (${e}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;const n=this.config.model_type;const r=MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(n)??MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES.get(n)??MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.get(n)??MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.get(n);if(r){t+=` Please use the following class instead: '${r[0]}'`}throw Error(t)}if(!(e instanceof Tensor)&&!isTypedArray(e)&&!Array.isArray(e)){throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${e.constructor.name}".`)}let o;if(this.config.is_encoder_decoder){o=0}else{o=e instanceof Tensor?e.dims.at(-1):e.length;if(o===0){throw Error("Must supply a non-empty array of input token ids.")}}t=this._get_generation_config(t);n=n??new LogitsProcessorList;n=this._get_logits_processor(t,o,n);let i=t.eos_token_id;if(i!==null&&!Array.isArray(i)){i=[i]}let s=1;const a=s+(t.max_new_tokens??Infinity);const c=Number.isInteger(t.max_length)&&(t.max_new_tokens??null)===null;let u=Sampler.getSampler(t);let l=this.getStartBeams(e,t,s,r);while(l.some((e=>!e.done))&&s<a){let e=[];for(let r of l){if(r.done){e.push(r);continue}if(c&&r.output_token_ids.length>=t.max_length){r.done=true;e.push(r);continue}let o=await this.runBeam(r);if(t.output_attentions){this.addAttentionsToBeam(r,o)}let s=o.logits.slice(null,-1,null);n(r.output_token_ids,s);let a=u(s);for(let[t,n]of a){let o={...r};this.updateBeam(o,t);o.score+=n;if(i&&i.includes(t)){o.done=true}e.push(o)}}++s;e=this.groupBeams(e).map((e=>e.sort(((e,t)=>t.score-e.score)).slice(0,t.num_beams)));l=e.flat();if(t.callback_function){t.callback_function(l)}}const f=this.groupBeams(l);const d=e=>f.map((n=>{if(t.num_return_sequences>1){return n.slice(0,t.num_return_sequences).map((t=>t[e]))}else{return[n[0][e]]}})).flat();const h=d("output_token_ids");if(t.return_dict_in_generate){const e=d("decoder_attentions");const t=d("cross_attentions");return{sequences:h,decoder_attentions:e,cross_attentions:t}}else{return h}}addAttentionsToBeam(e,t){if(this.config.is_encoder_decoder){if(!t.cross_attentions||t.cross_attentions.length===0){throw Error("`output_attentions` is true, but the model did not produce cross-attentions. "+"This is most likely because the model was not exported with `output_attentions=True`.")}if(!e.cross_attentions){e.cross_attentions=[]}e.cross_attentions.push(t.cross_attentions)}if(!t.decoder_attentions||t.decoder_attentions.length===0){throw Error("`output_attentions` is true, but the model did not produce decoder-attentions. "+"This is most likely because the model was not exported with `output_attentions=True`.")}if(!e.decoder_attentions){e.decoder_attentions=[]}e.decoder_attentions.push(t.decoder_attentions)}groupBeams(e){const t=Object.create(null);for(const n of e){if(t[n.id]===undefined){t[n.id]=[n]}else{t[n.id].push(n)}}return Object.values(t)}getPastKeyValues(e,t){const n=Object.create(null);for(const r in e){if(r.startsWith("present")){let o=r.replace("present","past_key_values");if(t&&r.includes("encoder")){n[o]=t[o]}else{n[o]=e[r]}}}return n}getAttentions(e){const t=Object.create(null);for(const n of["cross_attentions","decoder_attentions"]){const r=[];for(const t in e){if(t.startsWith(n)){const n=t.split(".").pop();r[n]=e[t]}}t[n]=r}return t}addPastKeyValues(e,t){if(t){Object.assign(e,t)}else{const t=1;if(this.config.is_encoder_decoder&&(this.add_encoder_pkv??true)){let n=[t,this.num_encoder_heads,0,this.encoder_dim_kv];let r=[t,this.num_decoder_heads,0,this.decoder_dim_kv];for(let t=0;t<this.num_decoder_layers;++t){e[`past_key_values.${t}.encoder.key`]=new Tensor("float32",[],n);e[`past_key_values.${t}.encoder.value`]=new Tensor("float32",[],n);e[`past_key_values.${t}.decoder.key`]=new Tensor("float32",[],r);e[`past_key_values.${t}.decoder.value`]=new Tensor("float32",[],r)}}else if(this.config.model_type==="falcon"){let n=[t*this.num_heads,0,this.dim_kv];for(let t=0;t<this.num_layers;++t){e[`past_key_values.${t}.key`]=new Tensor("float32",[],n);e[`past_key_values.${t}.value`]=new Tensor("float32",[],n)}}else if(this.config.multi_query){let n=[t*this.num_heads,0,2*this.dim_kv];for(let t=0;t<this.num_layers;++t){e[`past_key_values.${t}.key_value`]=new Tensor("float32",[],n)}}else if(this.config.model_type==="bloom"){let n=[t*this.num_heads,this.dim_kv,0];let r=[t*this.num_heads,0,this.dim_kv];for(let t=0;t<this.num_layers;++t){e[`past_key_values.${t}.key`]=new Tensor("float32",[],n);e[`past_key_values.${t}.value`]=new Tensor("float32",[],r)}}else{let n=[t,this.num_heads,0,this.dim_kv];for(let t=0;t<this.num_layers;++t){e[`past_key_values.${t}.key`]=new Tensor("float32",[],n);e[`past_key_values.${t}.value`]=new Tensor("float32",[],n)}}}}getStartBeams(e,t,n,r){return this._getStartBeams(this,e,t,n,r)}async runBeam(e){return await this._runBeam(this,e)}updateBeam(e,t){return this._updateBeam(e,t)}}class ModelOutput{}class BertPreTrainedModel extends PreTrainedModel{}class BertModel extends BertPreTrainedModel{}class BertForMaskedLM extends BertPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class BertForSequenceClassification extends BertPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class BertForTokenClassification extends BertPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class BertForQuestionAnswering extends BertPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class NomicBertPreTrainedModel extends PreTrainedModel{}class NomicBertModel extends NomicBertPreTrainedModel{}class RoFormerPreTrainedModel extends PreTrainedModel{}class RoFormerModel extends RoFormerPreTrainedModel{}class RoFormerForMaskedLM extends RoFormerPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class RoFormerForSequenceClassification extends RoFormerPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class RoFormerForTokenClassification extends RoFormerPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class ConvBertPreTrainedModel extends PreTrainedModel{}class ConvBertModel extends ConvBertPreTrainedModel{}class ConvBertForMaskedLM extends ConvBertPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class ConvBertForSequenceClassification extends ConvBertPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class ConvBertForTokenClassification extends ConvBertPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class ElectraPreTrainedModel extends PreTrainedModel{}class ElectraModel extends ElectraPreTrainedModel{}class ElectraForMaskedLM extends ElectraPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class ElectraForSequenceClassification extends ElectraPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class ElectraForTokenClassification extends ElectraPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class ElectraForQuestionAnswering extends ElectraPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class CamembertPreTrainedModel extends PreTrainedModel{}class CamembertModel extends CamembertPreTrainedModel{}class CamembertForMaskedLM extends CamembertPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class CamembertForSequenceClassification extends CamembertPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class CamembertForTokenClassification extends CamembertPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class CamembertForQuestionAnswering extends CamembertPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class DebertaPreTrainedModel extends PreTrainedModel{}class DebertaModel extends DebertaPreTrainedModel{}class DebertaForMaskedLM extends DebertaPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class DebertaForSequenceClassification extends DebertaPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class DebertaForTokenClassification extends DebertaPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class DebertaForQuestionAnswering extends DebertaPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class DebertaV2PreTrainedModel extends PreTrainedModel{}class DebertaV2Model extends DebertaV2PreTrainedModel{}class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class DistilBertPreTrainedModel extends PreTrainedModel{}class DistilBertModel extends DistilBertPreTrainedModel{}class DistilBertForSequenceClassification extends DistilBertPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class DistilBertForTokenClassification extends DistilBertPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class DistilBertForMaskedLM extends DistilBertPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class EsmPreTrainedModel extends PreTrainedModel{}class EsmModel extends EsmPreTrainedModel{}class EsmForMaskedLM extends EsmPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class EsmForSequenceClassification extends EsmPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class EsmForTokenClassification extends EsmPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class MobileBertPreTrainedModel extends PreTrainedModel{}class MobileBertModel extends MobileBertPreTrainedModel{}class MobileBertForMaskedLM extends MobileBertPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class MobileBertForSequenceClassification extends MobileBertPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class MPNetPreTrainedModel extends PreTrainedModel{}class MPNetModel extends MPNetPreTrainedModel{}class MPNetForMaskedLM extends MPNetPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class MPNetForSequenceClassification extends MPNetPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class MPNetForTokenClassification extends MPNetPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class MPNetForQuestionAnswering extends MPNetPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class SqueezeBertPreTrainedModel extends PreTrainedModel{}class SqueezeBertModel extends SqueezeBertPreTrainedModel{}class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class AlbertPreTrainedModel extends PreTrainedModel{}class AlbertModel extends AlbertPreTrainedModel{}class AlbertForSequenceClassification extends AlbertPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class AlbertForQuestionAnswering extends AlbertPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class AlbertForMaskedLM extends AlbertPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class T5PreTrainedModel extends PreTrainedModel{}class T5Model extends T5PreTrainedModel{}class T5ForConditionalGeneration extends T5PreTrainedModel{constructor(e,t,n,r){super(e,t);this.decoder_merged_session=n;this.generation_config=r;this.num_decoder_layers=this.config.num_decoder_layers;this.num_decoder_heads=this.config.num_heads;this.decoder_dim_kv=this.config.d_kv;this.num_encoder_layers=this.config.num_layers;this.num_encoder_heads=this.config.num_heads;this.encoder_dim_kv=this.config.d_kv}}class LongT5PreTrainedModel extends PreTrainedModel{}class LongT5Model extends LongT5PreTrainedModel{}class LongT5ForConditionalGeneration extends LongT5PreTrainedModel{constructor(e,t,n,r){super(e,t);this.decoder_merged_session=n;this.generation_config=r;this.num_decoder_layers=this.config.num_decoder_layers;this.num_decoder_heads=this.config.num_heads;this.decoder_dim_kv=this.config.d_kv;this.num_encoder_layers=this.config.num_layers;this.num_encoder_heads=this.config.num_heads;this.encoder_dim_kv=this.config.d_kv}}class MT5PreTrainedModel extends PreTrainedModel{}class MT5Model extends MT5PreTrainedModel{}class MT5ForConditionalGeneration extends MT5PreTrainedModel{constructor(e,t,n,r){super(e,t);this.decoder_merged_session=n;this.generation_config=r;this.num_decoder_layers=this.config.num_decoder_layers;this.num_decoder_heads=this.config.num_heads;this.decoder_dim_kv=this.config.d_kv;this.num_encoder_layers=this.config.num_layers;this.num_encoder_heads=this.config.num_heads;this.encoder_dim_kv=this.config.d_kv}}class BartPretrainedModel extends PreTrainedModel{}class BartModel extends BartPretrainedModel{}class BartForConditionalGeneration extends BartPretrainedModel{constructor(e,t,n,r){super(e,t);this.decoder_merged_session=n;this.generation_config=r;this.num_decoder_layers=this.config.decoder_layers;this.num_decoder_heads=this.config.decoder_attention_heads;this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads;this.num_encoder_layers=this.config.encoder_layers;this.num_encoder_heads=this.config.encoder_attention_heads;this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class BartForSequenceClassification extends BartPretrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class MBartPreTrainedModel extends PreTrainedModel{}class MBartModel extends MBartPreTrainedModel{}class MBartForConditionalGeneration extends MBartPreTrainedModel{constructor(e,t,n,r){super(e,t);this.decoder_merged_session=n;this.generation_config=r;this.num_decoder_layers=this.config.decoder_layers;this.num_decoder_heads=this.config.decoder_attention_heads;this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads;this.num_encoder_layers=this.config.encoder_layers;this.num_encoder_heads=this.config.encoder_attention_heads;this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class MBartForSequenceClassification extends MBartPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class MBartForCausalLM extends MBartPreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.num_decoder_layers=this.config.decoder_layers;this.num_decoder_heads=this.config.decoder_attention_heads;this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads;this.num_encoder_layers=this.config.encoder_layers;this.num_encoder_heads=this.config.encoder_attention_heads;this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class BlenderbotPreTrainedModel extends PreTrainedModel{}class BlenderbotModel extends BlenderbotPreTrainedModel{}class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel{constructor(e,t,n,r){super(e,t);this.decoder_merged_session=n;this.generation_config=r;this.num_decoder_layers=this.config.decoder_layers;this.num_decoder_heads=this.config.decoder_attention_heads;this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads;this.num_encoder_layers=this.config.encoder_layers;this.num_encoder_heads=this.config.encoder_attention_heads;this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class BlenderbotSmallPreTrainedModel extends PreTrainedModel{}class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel{}class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel{constructor(e,t,n,r){super(e,t);this.decoder_merged_session=n;this.generation_config=r;this.num_decoder_layers=this.config.decoder_layers;this.num_decoder_heads=this.config.decoder_attention_heads;this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads;this.num_encoder_layers=this.config.encoder_layers;this.num_encoder_heads=this.config.encoder_attention_heads;this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class RobertaPreTrainedModel extends PreTrainedModel{}class RobertaModel extends RobertaPreTrainedModel{}class RobertaForMaskedLM extends RobertaPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class RobertaForSequenceClassification extends RobertaPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class RobertaForTokenClassification extends RobertaPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class RobertaForQuestionAnswering extends RobertaPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class XLMPreTrainedModel extends PreTrainedModel{}class XLMModel extends XLMPreTrainedModel{}class XLMWithLMHeadModel extends XLMPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class XLMForSequenceClassification extends XLMPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class XLMForTokenClassification extends XLMPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class XLMForQuestionAnswering extends XLMPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class XLMRobertaPreTrainedModel extends PreTrainedModel{}class XLMRobertaModel extends XLMRobertaPreTrainedModel{}class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel{async _call(e){return new MaskedLMOutput(await super._call(e))}}class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel{async _call(e){return new QuestionAnsweringModelOutput(await super._call(e))}}class ASTPreTrainedModel extends PreTrainedModel{}class ASTModel extends ASTPreTrainedModel{}class ASTForAudioClassification extends ASTPreTrainedModel{}class WhisperPreTrainedModel extends PreTrainedModel{}class WhisperModel extends WhisperPreTrainedModel{}class WhisperForConditionalGeneration extends WhisperPreTrainedModel{requires_attention_mask=false;main_input_name="input_features";constructor(e,t,n,r){super(e,t);this.decoder_merged_session=n;this.generation_config=r;this.num_decoder_layers=this.config.decoder_layers;this.num_decoder_heads=this.config.decoder_attention_heads;this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads;this.num_encoder_layers=this.config.encoder_layers;this.num_encoder_heads=this.config.encoder_attention_heads;this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}async generate(e,t=null,n=null){t=this._get_generation_config(t);t.return_timestamps??=false;if(t.return_timestamps){n=[new WhisperTimeStampLogitsProcessor(t)]}if(t.return_token_timestamps){t.output_attentions=true;t.return_dict_in_generate=true;if(t.task==="translate"){console.warn("Token-level timestamps may not be reliable for task 'translate'.")}if(!t.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.")}}const r=await super.generate(e,t,n);if(t.return_token_timestamps&&t.alignment_heads){r["token_timestamps"]=this._extract_token_timestamps(r,t.alignment_heads,t.num_frames)}return r}_extract_token_timestamps(e,t,n=null,r=.02){if(!e.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`.")}let o=this.config.median_filter_width;if(o===undefined){console.warn("Model config has no `median_filter_width`, using default value of 7.");o=7}const i=e.cross_attentions.map((e=>{let r=Array.from({length:this.config.decoder_layers},((t,n)=>cat(e.map((e=>e[n])),2)));let i=stack(t.map((([e,t])=>n?r[e].slice(null,t,null,[0,n]):r[e].slice(null,t))));i=i.transpose(1,0,2,3);let[s,a]=std_mean(i,-2,0,true);let c=i.clone();for(let e=0;e<c.dims[0];++e){let t=c[e];for(let n=0;n<t.dims[0];++n){let r=t[n];const i=s[e][n][0];const c=a[e][n][0];for(let e=0;e<r.dims[0];++e){let t=r[e];for(let e=0;e<t.data.length;++e){t.data[e]=(t.data[e]-c.data[e])/i.data[e]}t.data.set(medianFilter(t.data,o))}}}const u=mean(c,1);return u}));const s=[e.sequences.length,e.sequences[0].length];const a=new Tensor("float32",new Float32Array(s[0]*s[1]),s);for(let e=0;e<s[0];++e){const t=i[e].neg().squeeze_(0);let[n,o]=dynamicTimeWarping(t);let s=Array.from({length:n.length-1},((e,t)=>n[t+1]-n[t]));let c=mergeArrays([1],s).map((e=>!!e));let u=[];for(let e=0;e<c.length;++e){if(c[e]){u.push(o[e]*r)}}a[e].data.set(u,1)}return a}}class VisionEncoderDecoderModel extends PreTrainedModel{main_input_name="pixel_values";constructor(e,t,n,r){super(e,t);this.decoder_merged_session=n;this.generation_config=r;const o=this.config.encoder;const i=this.config.decoder;const s=o.model_type;const a=MODEL_MAPPING_NAMES_ENCODER_ONLY.get(s)??MODEL_MAPPING_NAMES_ENCODER_DECODER.get(s);if(!a){console.warn(`Model type for encoder '${s}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`)}const c=MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(i.model_type);if(!c){throw new Error(`Unable to construct \`VisionEncoderDecoder\` due to unsupported decoder: "${this.config.decoder.model_type}"`)}const u=c[1];const l=new u(i,n,r);this.add_encoder_pkv="num_decoder_layers"in l;if(this.add_encoder_pkv){this.num_decoder_layers=l.num_decoder_layers;this.num_decoder_heads=l.num_decoder_heads;this.decoder_dim_kv=l.decoder_dim_kv;this.num_encoder_layers=l.num_encoder_layers;this.num_encoder_heads=l.num_encoder_heads;this.encoder_dim_kv=l.encoder_dim_kv}else{this.num_layers=l.num_layers;this.num_heads=l.num_heads;this.dim_kv=l.dim_kv}}}class CLIPPreTrainedModel extends PreTrainedModel{}class CLIPModel extends CLIPPreTrainedModel{}class CLIPTextModelWithProjection extends CLIPPreTrainedModel{static async from_pretrained(e,t={}){t.model_file_name??="text_model";return super.from_pretrained(e,t)}}class CLIPVisionModelWithProjection extends CLIPPreTrainedModel{static async from_pretrained(e,t={}){t.model_file_name??="vision_model";return super.from_pretrained(e,t)}}class SiglipPreTrainedModel extends PreTrainedModel{}class SiglipModel extends SiglipPreTrainedModel{}class SiglipTextModel extends SiglipPreTrainedModel{static async from_pretrained(e,t={}){t.model_file_name??="text_model";return super.from_pretrained(e,t)}}class SiglipVisionModel extends CLIPPreTrainedModel{static async from_pretrained(e,t={}){t.model_file_name??="vision_model";return super.from_pretrained(e,t)}}class ChineseCLIPPreTrainedModel extends PreTrainedModel{}class ChineseCLIPModel extends ChineseCLIPPreTrainedModel{}class CLIPSegPreTrainedModel extends PreTrainedModel{}class CLIPSegModel extends CLIPSegPreTrainedModel{}class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel{}class GPT2PreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.n_head;this.num_layers=this.config.n_layer;this.dim_kv=this.config.n_embd/this.num_heads}}class GPT2Model extends GPT2PreTrainedModel{}class GPT2LMHeadModel extends GPT2PreTrainedModel{}class GPTNeoPreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.num_heads;this.num_layers=this.config.num_layers;this.dim_kv=this.config.hidden_size/this.num_heads}}class GPTNeoModel extends GPTNeoPreTrainedModel{}class GPTNeoForCausalLM extends GPTNeoPreTrainedModel{}class GPTNeoXPreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.num_attention_heads;this.num_layers=this.config.num_hidden_layers;this.dim_kv=this.config.hidden_size/this.num_heads}}class GPTNeoXModel extends GPTNeoXPreTrainedModel{}class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel{}class GPTJPreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.n_head;this.num_layers=this.config.n_layer;this.dim_kv=this.config.n_embd/this.num_heads}}class GPTJModel extends GPTJPreTrainedModel{}class GPTJForCausalLM extends GPTJPreTrainedModel{}class GPTBigCodePreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.n_head;this.num_layers=this.config.n_layer;this.dim_kv=this.config.n_embd/this.num_heads}}class GPTBigCodeModel extends GPTBigCodePreTrainedModel{}class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel{}class CodeGenPreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.n_head;this.num_layers=this.config.n_layer;this.dim_kv=this.config.n_embd/this.num_heads}}class CodeGenModel extends CodeGenPreTrainedModel{}class CodeGenForCausalLM extends CodeGenPreTrainedModel{}class LlamaPreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.num_key_value_heads??this.config.num_attention_heads;this.num_layers=this.config.num_hidden_layers;this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class LlamaModel extends LlamaPreTrainedModel{}class LlamaForCausalLM extends LlamaPreTrainedModel{}class Qwen2PreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.num_key_value_heads??this.config.num_attention_heads;this.num_layers=this.config.num_hidden_layers;this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class Qwen2Model extends Qwen2PreTrainedModel{}class Qwen2ForCausalLM extends Qwen2PreTrainedModel{}class PhiPreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.num_attention_heads;this.num_layers=this.config.num_hidden_layers;this.dim_kv=this.config.hidden_size/this.num_heads}}class PhiModel extends PhiPreTrainedModel{}class PhiForCausalLM extends PhiPreTrainedModel{}class BloomPreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.n_head;this.num_layers=this.config.n_layer;this.dim_kv=this.config.hidden_size/this.num_heads}}class BloomModel extends BloomPreTrainedModel{}class BloomForCausalLM extends BloomPreTrainedModel{}class MptPreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.n_heads;this.num_layers=this.config.n_layers;this.dim_kv=this.config.d_model/this.num_heads}}class MptModel extends MptPreTrainedModel{}class MptForCausalLM extends MptPreTrainedModel{}class OPTPreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.num_attention_heads;this.num_layers=this.config.num_hidden_layers;this.dim_kv=this.config.hidden_size/this.num_heads}}class OPTModel extends OPTPreTrainedModel{}class OPTForCausalLM extends OPTPreTrainedModel{}class ViTPreTrainedModel extends PreTrainedModel{}class ViTModel extends ViTPreTrainedModel{}class ViTForImageClassification extends ViTPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class FastViTPreTrainedModel extends PreTrainedModel{}class FastViTModel extends FastViTPreTrainedModel{}class FastViTForImageClassification extends FastViTPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class VitMattePreTrainedModel extends PreTrainedModel{}class VitMatteForImageMatting extends VitMattePreTrainedModel{async _call(e){return new ImageMattingOutput(await super._call(e))}}class MobileViTPreTrainedModel extends PreTrainedModel{}class MobileViTModel extends MobileViTPreTrainedModel{}class MobileViTForImageClassification extends MobileViTPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class MobileViTV2PreTrainedModel extends PreTrainedModel{}class MobileViTV2Model extends MobileViTV2PreTrainedModel{}class MobileViTV2ForImageClassification extends MobileViTV2PreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class OwlViTPreTrainedModel extends PreTrainedModel{}class OwlViTModel extends OwlViTPreTrainedModel{}class OwlViTForObjectDetection extends OwlViTPreTrainedModel{}class Owlv2PreTrainedModel extends PreTrainedModel{}class Owlv2Model extends Owlv2PreTrainedModel{}class Owlv2ForObjectDetection extends Owlv2PreTrainedModel{}class BeitPreTrainedModel extends PreTrainedModel{}class BeitModel extends BeitPreTrainedModel{}class BeitForImageClassification extends BeitPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class DetrPreTrainedModel extends PreTrainedModel{}class DetrModel extends DetrPreTrainedModel{}class DetrForObjectDetection extends DetrPreTrainedModel{async _call(e){return new DetrObjectDetectionOutput(await super._call(e))}}class DetrForSegmentation extends DetrPreTrainedModel{async _call(e){return new DetrSegmentationOutput(await super._call(e))}}class DetrObjectDetectionOutput extends ModelOutput{constructor({logits:e,pred_boxes:t}){super();this.logits=e;this.pred_boxes=t}}class DetrSegmentationOutput extends ModelOutput{constructor({logits:e,pred_boxes:t,pred_masks:n}){super();this.logits=e;this.pred_boxes=t;this.pred_masks=n}}class TableTransformerPreTrainedModel extends PreTrainedModel{}class TableTransformerModel extends TableTransformerPreTrainedModel{}class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel{async _call(e){return new TableTransformerObjectDetectionOutput(await super._call(e))}}class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput{}class DeiTPreTrainedModel extends PreTrainedModel{}class DeiTModel extends DeiTPreTrainedModel{}class DeiTForImageClassification extends DeiTPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class ResNetPreTrainedModel extends PreTrainedModel{}class ResNetModel extends ResNetPreTrainedModel{}class ResNetForImageClassification extends ResNetPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class SwinPreTrainedModel extends PreTrainedModel{}class SwinModel extends SwinPreTrainedModel{}class SwinForImageClassification extends SwinPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class Swin2SRPreTrainedModel extends PreTrainedModel{}class Swin2SRModel extends Swin2SRPreTrainedModel{}class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel{}class DPTPreTrainedModel extends PreTrainedModel{}class DPTModel extends DPTPreTrainedModel{}class DPTForDepthEstimation extends DPTPreTrainedModel{}class DepthAnythingPreTrainedModel extends PreTrainedModel{}class DepthAnythingForDepthEstimation extends DepthAnythingPreTrainedModel{}class GLPNPreTrainedModel extends PreTrainedModel{}class GLPNModel extends GLPNPreTrainedModel{}class GLPNForDepthEstimation extends GLPNPreTrainedModel{}class DonutSwinPreTrainedModel extends PreTrainedModel{}class DonutSwinModel extends DonutSwinPreTrainedModel{}class ConvNextPreTrainedModel extends PreTrainedModel{}class ConvNextModel extends ConvNextPreTrainedModel{}class ConvNextForImageClassification extends ConvNextPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class ConvNextV2PreTrainedModel extends PreTrainedModel{}class ConvNextV2Model extends ConvNextV2PreTrainedModel{}class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class Dinov2PreTrainedModel extends PreTrainedModel{}class Dinov2Model extends Dinov2PreTrainedModel{}class Dinov2ForImageClassification extends Dinov2PreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class YolosPreTrainedModel extends PreTrainedModel{}class YolosModel extends YolosPreTrainedModel{}class YolosForObjectDetection extends YolosPreTrainedModel{async _call(e){return new YolosObjectDetectionOutput(await super._call(e))}}class YolosObjectDetectionOutput extends ModelOutput{constructor({logits:e,pred_boxes:t}){super();this.logits=e;this.pred_boxes=t}}class SamPreTrainedModel extends PreTrainedModel{}class SamModel extends SamPreTrainedModel{constructor(e,t,n){super(e,t);this.prompt_encoder_mask_decoder=n}async get_image_embeddings({pixel_values:e}){return await encoderForward(this,{pixel_values:e})}async forward(e){if(!e.image_embeddings||!e.image_positional_embeddings){e={...e,...await this.get_image_embeddings(e)}}if(!e.input_labels){const t=e.input_points.dims.slice(0,-1);const n=t.reduce(((e,t)=>e*t),1);e.input_labels=new Tensor("int64",new BigInt64Array(n).fill(1n),t)}return await sessionRun(this.prompt_encoder_mask_decoder,{input_points:e.input_points,input_labels:e.input_labels,image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings})}async _call(e){return new SamImageSegmentationOutput(await super._call(e))}}class SamImageSegmentationOutput extends ModelOutput{constructor({iou_scores:e,pred_masks:t}){super();this.iou_scores=e;this.pred_masks=t}}class MarianPreTrainedModel extends PreTrainedModel{}class MarianModel extends MarianPreTrainedModel{}class MarianMTModel extends MarianPreTrainedModel{constructor(e,t,n,r){super(e,t);this.decoder_merged_session=n;this.generation_config=r;this.num_decoder_layers=this.config.decoder_layers;this.num_decoder_heads=this.config.decoder_attention_heads;this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads;this.num_encoder_layers=this.config.encoder_layers;this.num_encoder_heads=this.config.encoder_attention_heads;this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class M2M100PreTrainedModel extends PreTrainedModel{}class M2M100Model extends M2M100PreTrainedModel{}class M2M100ForConditionalGeneration extends M2M100PreTrainedModel{constructor(e,t,n,r){super(e,t);this.decoder_merged_session=n;this.generation_config=r;this.num_decoder_layers=this.config.decoder_layers;this.num_decoder_heads=this.config.decoder_attention_heads;this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads;this.num_encoder_layers=this.config.encoder_layers;this.num_encoder_heads=this.config.encoder_attention_heads;this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class Wav2Vec2PreTrainedModel extends PreTrainedModel{}class Wav2Vec2Model extends Wav2Vec2PreTrainedModel{}class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class Wav2Vec2ForAudioFrameClassification extends Wav2Vec2PreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class UniSpeechPreTrainedModel extends PreTrainedModel{}class UniSpeechModel extends UniSpeechPreTrainedModel{}class UniSpeechForCTC extends UniSpeechPreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class UniSpeechForSequenceClassification extends UniSpeechPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class UniSpeechSatPreTrainedModel extends PreTrainedModel{}class UniSpeechSatModel extends UniSpeechSatPreTrainedModel{}class UniSpeechSatForCTC extends UniSpeechSatPreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class UniSpeechSatForSequenceClassification extends UniSpeechSatPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class UniSpeechSatForAudioFrameClassification extends UniSpeechSatPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class Wav2Vec2BertPreTrainedModel extends PreTrainedModel{}class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel{}class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class HubertModel extends Wav2Vec2PreTrainedModel{}class HubertForCTC extends Wav2Vec2PreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class WavLMPreTrainedModel extends PreTrainedModel{}class WavLMModel extends WavLMPreTrainedModel{}class WavLMForCTC extends WavLMPreTrainedModel{async _call(e){return new CausalLMOutput(await super._call(e))}}class WavLMForSequenceClassification extends WavLMPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class WavLMForXVector extends WavLMPreTrainedModel{async _call(e){return new XVectorOutput(await super._call(e))}}class WavLMForAudioFrameClassification extends WavLMPreTrainedModel{async _call(e){return new TokenClassifierOutput(await super._call(e))}}class SpeechT5PreTrainedModel extends PreTrainedModel{}class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel{}class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel{constructor(e,t,n,r){super(e,t);this.decoder_merged_session=n;this.generation_config=r;this.num_decoder_layers=this.config.decoder_layers;this.num_decoder_heads=this.config.decoder_attention_heads;this.decoder_dim_kv=this.config.hidden_size/this.num_decoder_heads;this.num_encoder_layers=this.config.encoder_layers;this.num_encoder_heads=this.config.encoder_attention_heads;this.encoder_dim_kv=this.config.hidden_size/this.num_encoder_heads}async generate_speech(e,t,{threshold:n=.5,minlenratio:r=0,maxlenratio:o=20,vocoder:i=null}={}){const s={input_ids:e};const{encoder_outputs:a,encoder_attention_mask:c}=await encoderForward(this,s);const u=a.dims[1]/this.config.reduction_factor;const l=Math.floor(u*o);const f=Math.floor(u*r);const d=this.config.num_mel_bins;let h=[];let p=null;let m=null;let w=0;while(true){++w;const e=boolTensor(!!m);let r;if(m){r=m.output_sequence_out}else{r=new Tensor("float32",new Float32Array(d),[1,1,d])}let o={use_cache_branch:e,output_sequence:r,encoder_attention_mask:c,speaker_embeddings:t,encoder_hidden_states:a};this.addPastKeyValues(o,p);m=await sessionRun(this.decoder_merged_session,o);p=this.getPastKeyValues(m,p);const{prob:i,spectrum:s}=m;h.push(s);if(w>=f&&(Array.from(i.data).filter((e=>e>=n)).length>0||w>=l)){break}}const g=cat(h);const{waveform:v}=await sessionRun(i.session,{spectrogram:g});return{spectrogram:g,waveform:v}}}class SpeechT5HifiGan extends PreTrainedModel{main_input_name="spectrogram"}class TrOCRPreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_encoder_layers=this.num_decoder_layers=this.config.decoder_layers;this.num_encoder_heads=this.num_decoder_heads=this.config.decoder_attention_heads;this.encoder_dim_kv=this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads}}class TrOCRForCausalLM extends TrOCRPreTrainedModel{}class MistralPreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.num_key_value_heads;this.num_layers=this.config.num_hidden_layers;this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class MistralModel extends MistralPreTrainedModel{}class MistralForCausalLM extends MistralPreTrainedModel{}class Starcoder2PreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.num_key_value_heads;this.num_layers=this.config.num_hidden_layers;this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class Starcoder2Model extends Starcoder2PreTrainedModel{}class Starcoder2ForCausalLM extends Starcoder2PreTrainedModel{}class FalconPreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.num_attention_heads;this.num_layers=this.config.num_hidden_layers;this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class FalconModel extends FalconPreTrainedModel{}class FalconForCausalLM extends FalconPreTrainedModel{}class ClapPreTrainedModel extends PreTrainedModel{}class ClapModel extends ClapPreTrainedModel{}class ClapTextModelWithProjection extends ClapPreTrainedModel{static async from_pretrained(e,t={}){t.model_file_name??="text_model";return super.from_pretrained(e,t)}}class ClapAudioModelWithProjection extends ClapPreTrainedModel{static async from_pretrained(e,t={}){t.model_file_name??="audio_model";return super.from_pretrained(e,t)}}class VitsPreTrainedModel extends PreTrainedModel{}class VitsModel extends VitsPreTrainedModel{async _call(e){return new VitsModelOutput(await super._call(e))}}class SegformerPreTrainedModel extends PreTrainedModel{}class SegformerForImageClassification extends SegformerPreTrainedModel{}class SegformerForSemanticSegmentation extends SegformerPreTrainedModel{}class StableLmPreTrainedModel extends PreTrainedModel{constructor(e,t,n){super(e,t);this.generation_config=n;this.config.pad_token_id=this.config.eos_token_id;this.num_heads=this.config.num_attention_heads;this.num_layers=this.config.num_hidden_layers;this.dim_kv=this.config.hidden_size/this.num_heads}}class StableLmForCausalLM extends StableLmPreTrainedModel{}class EfficientNetPreTrainedModel extends PreTrainedModel{}class EfficientNetModel extends EfficientNetPreTrainedModel{}class EfficientNetForImageClassification extends EfficientNetPreTrainedModel{async _call(e){return new SequenceClassifierOutput(await super._call(e))}}class PretrainedMixin{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=false;static async from_pretrained(e,{quantized:t=true,progress_callback:n=null,config:r=null,cache_dir:o=null,local_files_only:i=false,revision:s="main",model_file_name:a=null}={}){let c={quantized:t,progress_callback:n,config:r,cache_dir:o,local_files_only:i,revision:s,model_file_name:a};r=await AutoConfig.from_pretrained(e,c);if(!c.config){c.config=r}if(!this.MODEL_CLASS_MAPPINGS){throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name)}for(let t of this.MODEL_CLASS_MAPPINGS){const n=t.get(r.model_type);if(!n){continue}return await n[1].from_pretrained(e,c)}if(this.BASE_IF_FAIL){console.warn(`Unknown model class "${r.model_type}", attempting to construct from base class.`);return await PreTrainedModel.from_pretrained(e,c)}else{throw Error(`Unsupported model type: ${r.model_type}`)}}}const MODEL_MAPPING_NAMES_ENCODER_ONLY=new Map([["bert",["BertModel",BertModel]],["nomic_bert",["NomicBertModel",NomicBertModel]],["roformer",["RoFormerModel",RoFormerModel]],["electra",["ElectraModel",ElectraModel]],["esm",["EsmModel",EsmModel]],["convbert",["ConvBertModel",ConvBertModel]],["camembert",["CamembertModel",CamembertModel]],["deberta",["DebertaModel",DebertaModel]],["deberta-v2",["DebertaV2Model",DebertaV2Model]],["mpnet",["MPNetModel",MPNetModel]],["albert",["AlbertModel",AlbertModel]],["distilbert",["DistilBertModel",DistilBertModel]],["roberta",["RobertaModel",RobertaModel]],["xlm",["XLMModel",XLMModel]],["xlm-roberta",["XLMRobertaModel",XLMRobertaModel]],["clap",["ClapModel",ClapModel]],["clip",["CLIPModel",CLIPModel]],["clipseg",["CLIPSegModel",CLIPSegModel]],["chinese_clip",["ChineseCLIPModel",ChineseCLIPModel]],["siglip",["SiglipModel",SiglipModel]],["mobilebert",["MobileBertModel",MobileBertModel]],["squeezebert",["SqueezeBertModel",SqueezeBertModel]],["wav2vec2",["Wav2Vec2Model",Wav2Vec2Model]],["wav2vec2-bert",["Wav2Vec2BertModel",Wav2Vec2BertModel]],["unispeech",["UniSpeechModel",UniSpeechModel]],["unispeech-sat",["UniSpeechSatModel",UniSpeechSatModel]],["hubert",["HubertModel",HubertModel]],["wavlm",["WavLMModel",WavLMModel]],["audio-spectrogram-transformer",["ASTModel",ASTModel]],["vits",["VitsModel",VitsModel]],["detr",["DetrModel",DetrModel]],["table-transformer",["TableTransformerModel",TableTransformerModel]],["vit",["ViTModel",ViTModel]],["fastvit",["FastViTModel",FastViTModel]],["mobilevit",["MobileViTModel",MobileViTModel]],["mobilevitv2",["MobileViTV2Model",MobileViTV2Model]],["owlvit",["OwlViTModel",OwlViTModel]],["owlv2",["Owlv2Model",Owlv2Model]],["beit",["BeitModel",BeitModel]],["deit",["DeiTModel",DeiTModel]],["convnext",["ConvNextModel",ConvNextModel]],["convnextv2",["ConvNextV2Model",ConvNextV2Model]],["dinov2",["Dinov2Model",Dinov2Model]],["resnet",["ResNetModel",ResNetModel]],["swin",["SwinModel",SwinModel]],["swin2sr",["Swin2SRModel",Swin2SRModel]],["donut-swin",["DonutSwinModel",DonutSwinModel]],["yolos",["YolosModel",YolosModel]],["dpt",["DPTModel",DPTModel]],["glpn",["GLPNModel",GLPNModel]],["hifigan",["SpeechT5HifiGan",SpeechT5HifiGan]],["efficientnet",["EfficientNetModel",EfficientNetModel]]]);const MODEL_MAPPING_NAMES_ENCODER_DECODER=new Map([["t5",["T5Model",T5Model]],["longt5",["LongT5Model",LongT5Model]],["mt5",["MT5Model",MT5Model]],["bart",["BartModel",BartModel]],["mbart",["MBartModel",MBartModel]],["marian",["MarianModel",MarianModel]],["whisper",["WhisperModel",WhisperModel]],["m2m_100",["M2M100Model",M2M100Model]],["blenderbot",["BlenderbotModel",BlenderbotModel]],["blenderbot-small",["BlenderbotSmallModel",BlenderbotSmallModel]]]);const MODEL_MAPPING_NAMES_DECODER_ONLY=new Map([["bloom",["BloomModel",BloomModel]],["gpt2",["GPT2Model",GPT2Model]],["gptj",["GPTJModel",GPTJModel]],["gpt_bigcode",["GPTBigCodeModel",GPTBigCodeModel]],["gpt_neo",["GPTNeoModel",GPTNeoModel]],["gpt_neox",["GPTNeoXModel",GPTNeoXModel]],["codegen",["CodeGenModel",CodeGenModel]],["llama",["LlamaModel",LlamaModel]],["qwen2",["Qwen2Model",Qwen2Model]],["phi",["PhiModel",PhiModel]],["mpt",["MptModel",MptModel]],["opt",["OPTModel",OPTModel]],["mistral",["MistralModel",MistralModel]],["starcoder2",["Starcoder2Model",Starcoder2Model]],["falcon",["FalconModel",FalconModel]]]);const MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES=new Map([["speecht5",["SpeechT5ForSpeechToText",SpeechT5ForSpeechToText]],["whisper",["WhisperForConditionalGeneration",WhisperForConditionalGeneration]]]);const MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES=new Map([["speecht5",["SpeechT5ForTextToSpeech",SpeechT5ForTextToSpeech]]]);const MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES=new Map([["vits",["VitsModel",VitsModel]]]);const MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES=new Map([["bert",["BertForSequenceClassification",BertForSequenceClassification]],["roformer",["RoFormerForSequenceClassification",RoFormerForSequenceClassification]],["electra",["ElectraForSequenceClassification",ElectraForSequenceClassification]],["esm",["EsmForSequenceClassification",EsmForSequenceClassification]],["convbert",["ConvBertForSequenceClassification",ConvBertForSequenceClassification]],["camembert",["CamembertForSequenceClassification",CamembertForSequenceClassification]],["deberta",["DebertaForSequenceClassification",DebertaForSequenceClassification]],["deberta-v2",["DebertaV2ForSequenceClassification",DebertaV2ForSequenceClassification]],["mpnet",["MPNetForSequenceClassification",MPNetForSequenceClassification]],["albert",["AlbertForSequenceClassification",AlbertForSequenceClassification]],["distilbert",["DistilBertForSequenceClassification",DistilBertForSequenceClassification]],["roberta",["RobertaForSequenceClassification",RobertaForSequenceClassification]],["xlm",["XLMForSequenceClassification",XLMForSequenceClassification]],["xlm-roberta",["XLMRobertaForSequenceClassification",XLMRobertaForSequenceClassification]],["bart",["BartForSequenceClassification",BartForSequenceClassification]],["mbart",["MBartForSequenceClassification",MBartForSequenceClassification]],["mobilebert",["MobileBertForSequenceClassification",MobileBertForSequenceClassification]],["squeezebert",["SqueezeBertForSequenceClassification",SqueezeBertForSequenceClassification]]]);const MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES=new Map([["bert",["BertForTokenClassification",BertForTokenClassification]],["roformer",["RoFormerForTokenClassification",RoFormerForTokenClassification]],["electra",["ElectraForTokenClassification",ElectraForTokenClassification]],["esm",["EsmForTokenClassification",EsmForTokenClassification]],["convbert",["ConvBertForTokenClassification",ConvBertForTokenClassification]],["camembert",["CamembertForTokenClassification",CamembertForTokenClassification]],["deberta",["DebertaForTokenClassification",DebertaForTokenClassification]],["deberta-v2",["DebertaV2ForTokenClassification",DebertaV2ForTokenClassification]],["mpnet",["MPNetForTokenClassification",MPNetForTokenClassification]],["distilbert",["DistilBertForTokenClassification",DistilBertForTokenClassification]],["roberta",["RobertaForTokenClassification",RobertaForTokenClassification]],["xlm",["XLMForTokenClassification",XLMForTokenClassification]],["xlm-roberta",["XLMRobertaForTokenClassification",XLMRobertaForTokenClassification]]]);const MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES=new Map([["t5",["T5ForConditionalGeneration",T5ForConditionalGeneration]],["longt5",["LongT5ForConditionalGeneration",LongT5ForConditionalGeneration]],["mt5",["MT5ForConditionalGeneration",MT5ForConditionalGeneration]],["bart",["BartForConditionalGeneration",BartForConditionalGeneration]],["mbart",["MBartForConditionalGeneration",MBartForConditionalGeneration]],["marian",["MarianMTModel",MarianMTModel]],["m2m_100",["M2M100ForConditionalGeneration",M2M100ForConditionalGeneration]],["blenderbot",["BlenderbotForConditionalGeneration",BlenderbotForConditionalGeneration]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",BlenderbotSmallForConditionalGeneration]]]);const MODEL_WITH_LM_HEAD_MAPPING_NAMES=new Map([["bloom",["BloomForCausalLM",BloomForCausalLM]],["gpt2",["GPT2LMHeadModel",GPT2LMHeadModel]],["gptj",["GPTJForCausalLM",GPTJForCausalLM]],["gpt_bigcode",["GPTBigCodeForCausalLM",GPTBigCodeForCausalLM]],["gpt_neo",["GPTNeoForCausalLM",GPTNeoForCausalLM]],["gpt_neox",["GPTNeoXForCausalLM",GPTNeoXForCausalLM]],["codegen",["CodeGenForCausalLM",CodeGenForCausalLM]],["llama",["LlamaForCausalLM",LlamaForCausalLM]],["qwen2",["Qwen2ForCausalLM",Qwen2ForCausalLM]],["phi",["PhiForCausalLM",PhiForCausalLM]],["mpt",["MptForCausalLM",MptForCausalLM]],["opt",["OPTForCausalLM",OPTForCausalLM]],["mbart",["MBartForCausalLM",MBartForCausalLM]],["mistral",["MistralForCausalLM",MistralForCausalLM]],["starcoder2",["Starcoder2ForCausalLM",Starcoder2ForCausalLM]],["falcon",["FalconForCausalLM",FalconForCausalLM]],["trocr",["TrOCRForCausalLM",TrOCRForCausalLM]],["stablelm",["StableLmForCausalLM",StableLmForCausalLM]]]);const MODEL_FOR_MASKED_LM_MAPPING_NAMES=new Map([["bert",["BertForMaskedLM",BertForMaskedLM]],["roformer",["RoFormerForMaskedLM",RoFormerForMaskedLM]],["electra",["ElectraForMaskedLM",ElectraForMaskedLM]],["esm",["EsmForMaskedLM",EsmForMaskedLM]],["convbert",["ConvBertForMaskedLM",ConvBertForMaskedLM]],["camembert",["CamembertForMaskedLM",CamembertForMaskedLM]],["deberta",["DebertaForMaskedLM",DebertaForMaskedLM]],["deberta-v2",["DebertaV2ForMaskedLM",DebertaV2ForMaskedLM]],["mpnet",["MPNetForMaskedLM",MPNetForMaskedLM]],["albert",["AlbertForMaskedLM",AlbertForMaskedLM]],["distilbert",["DistilBertForMaskedLM",DistilBertForMaskedLM]],["roberta",["RobertaForMaskedLM",RobertaForMaskedLM]],["xlm",["XLMWithLMHeadModel",XLMWithLMHeadModel]],["xlm-roberta",["XLMRobertaForMaskedLM",XLMRobertaForMaskedLM]],["mobilebert",["MobileBertForMaskedLM",MobileBertForMaskedLM]],["squeezebert",["SqueezeBertForMaskedLM",SqueezeBertForMaskedLM]]]);const MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES=new Map([["bert",["BertForQuestionAnswering",BertForQuestionAnswering]],["roformer",["RoFormerForQuestionAnswering",RoFormerForQuestionAnswering]],["electra",["ElectraForQuestionAnswering",ElectraForQuestionAnswering]],["convbert",["ConvBertForQuestionAnswering",ConvBertForQuestionAnswering]],["camembert",["CamembertForQuestionAnswering",CamembertForQuestionAnswering]],["deberta",["DebertaForQuestionAnswering",DebertaForQuestionAnswering]],["deberta-v2",["DebertaV2ForQuestionAnswering",DebertaV2ForQuestionAnswering]],["mpnet",["MPNetForQuestionAnswering",MPNetForQuestionAnswering]],["albert",["AlbertForQuestionAnswering",AlbertForQuestionAnswering]],["distilbert",["DistilBertForQuestionAnswering",DistilBertForQuestionAnswering]],["roberta",["RobertaForQuestionAnswering",RobertaForQuestionAnswering]],["xlm",["XLMForQuestionAnswering",XLMForQuestionAnswering]],["xlm-roberta",["XLMRobertaForQuestionAnswering",XLMRobertaForQuestionAnswering]],["mobilebert",["MobileBertForQuestionAnswering",MobileBertForQuestionAnswering]],["squeezebert",["SqueezeBertForQuestionAnswering",SqueezeBertForQuestionAnswering]]]);const MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",VisionEncoderDecoderModel]]]);const MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",VisionEncoderDecoderModel]]]);const MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES=new Map([["vit",["ViTForImageClassification",ViTForImageClassification]],["fastvit",["FastViTForImageClassification",FastViTForImageClassification]],["mobilevit",["MobileViTForImageClassification",MobileViTForImageClassification]],["mobilevitv2",["MobileViTV2ForImageClassification",MobileViTV2ForImageClassification]],["beit",["BeitForImageClassification",BeitForImageClassification]],["deit",["DeiTForImageClassification",DeiTForImageClassification]],["convnext",["ConvNextForImageClassification",ConvNextForImageClassification]],["convnextv2",["ConvNextV2ForImageClassification",ConvNextV2ForImageClassification]],["dinov2",["Dinov2ForImageClassification",Dinov2ForImageClassification]],["resnet",["ResNetForImageClassification",ResNetForImageClassification]],["swin",["SwinForImageClassification",SwinForImageClassification]],["segformer",["SegformerForImageClassification",SegformerForImageClassification]],["efficientnet",["EfficientNetForImageClassification",EfficientNetForImageClassification]]]);const MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES=new Map([["detr",["DetrForObjectDetection",DetrForObjectDetection]],["table-transformer",["TableTransformerForObjectDetection",TableTransformerForObjectDetection]],["yolos",["YolosForObjectDetection",YolosForObjectDetection]]]);const MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES=new Map([["owlvit",["OwlViTForObjectDetection",OwlViTForObjectDetection]],["owlv2",["Owlv2ForObjectDetection",Owlv2ForObjectDetection]]]);const MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES=new Map([["detr",["DetrForSegmentation",DetrForSegmentation]],["clipseg",["CLIPSegForImageSegmentation",CLIPSegForImageSegmentation]]]);const MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES=new Map([["segformer",["SegformerForSemanticSegmentation",SegformerForSemanticSegmentation]]]);const MODEL_FOR_MASK_GENERATION_MAPPING_NAMES=new Map([["sam",["SamModel",SamModel]]]);const MODEL_FOR_CTC_MAPPING_NAMES=new Map([["wav2vec2",["Wav2Vec2ForCTC",Wav2Vec2ForCTC]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Wav2Vec2BertForCTC]],["unispeech",["UniSpeechForCTC",UniSpeechForCTC]],["unispeech-sat",["UniSpeechSatForCTC",UniSpeechSatForCTC]],["wavlm",["WavLMForCTC",WavLMForCTC]],["hubert",["HubertForCTC",HubertForCTC]]]);const MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Wav2Vec2ForSequenceClassification]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Wav2Vec2BertForSequenceClassification]],["unispeech",["UniSpeechForSequenceClassification",UniSpeechForSequenceClassification]],["unispeech-sat",["UniSpeechSatForSequenceClassification",UniSpeechSatForSequenceClassification]],["wavlm",["WavLMForSequenceClassification",WavLMForSequenceClassification]],["hubert",["HubertForSequenceClassification",HubertForSequenceClassification]],["audio-spectrogram-transformer",["ASTForAudioClassification",ASTForAudioClassification]]]);const MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES=new Map([["wavlm",["WavLMForXVector",WavLMForXVector]]]);const MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",UniSpeechSatForAudioFrameClassification]],["wavlm",["WavLMForAudioFrameClassification",WavLMForAudioFrameClassification]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Wav2Vec2ForAudioFrameClassification]]]);const MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES=new Map([["vitmatte",["VitMatteForImageMatting",VitMatteForImageMatting]]]);const MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Swin2SRForImageSuperResolution]]]);const MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES=new Map([["dpt",["DPTForDepthEstimation",DPTForDepthEstimation]],["depth_anything",["DepthAnythingForDepthEstimation",DepthAnythingForDepthEstimation]],["glpn",["GLPNForDepthEstimation",GLPNForDepthEstimation]]]);const MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES=new Map([["clip",["CLIPVisionModelWithProjection",CLIPVisionModelWithProjection]],["siglip",["SiglipVisionModel",SiglipVisionModel]]]);const MODEL_CLASS_TYPE_MAPPING=[[MODEL_MAPPING_NAMES_ENCODER_ONLY,MODEL_TYPES.EncoderOnly],[MODEL_MAPPING_NAMES_ENCODER_DECODER,MODEL_TYPES.EncoderDecoder],[MODEL_MAPPING_NAMES_DECODER_ONLY,MODEL_TYPES.DecoderOnly],[MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,MODEL_TYPES.Seq2Seq],[MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES,MODEL_TYPES.Seq2Seq],[MODEL_WITH_LM_HEAD_MAPPING_NAMES,MODEL_TYPES.DecoderOnly],[MODEL_FOR_MASKED_LM_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,MODEL_TYPES.Vision2Seq],[MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_MASK_GENERATION_MAPPING_NAMES,MODEL_TYPES.MaskGeneration],[MODEL_FOR_CTC_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES,MODEL_TYPES.Seq2Seq],[MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly],[MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES,MODEL_TYPES.EncoderOnly]];for(const[e,t]of MODEL_CLASS_TYPE_MAPPING){for(const[n,r]of e.values()){MODEL_TYPE_MAPPING.set(n,t);MODEL_CLASS_TO_NAME_MAPPING.set(r,n);MODEL_NAME_TO_CLASS_MAPPING.set(n,r)}}const CUSTOM_MAPPING=[["CLIPTextModelWithProjection",CLIPTextModelWithProjection,MODEL_TYPES.EncoderOnly],["SiglipTextModel",SiglipTextModel,MODEL_TYPES.EncoderOnly],["ClapTextModelWithProjection",ClapTextModelWithProjection,MODEL_TYPES.EncoderOnly],["ClapAudioModelWithProjection",ClapAudioModelWithProjection,MODEL_TYPES.EncoderOnly]];for(const[e,t,n]of CUSTOM_MAPPING){MODEL_TYPE_MAPPING.set(e,n);MODEL_CLASS_TO_NAME_MAPPING.set(t,e);MODEL_NAME_TO_CLASS_MAPPING.set(e,t)}class AutoModel extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=MODEL_CLASS_TYPE_MAPPING.map((e=>e[0]));static BASE_IF_FAIL=true}class AutoModelForSequenceClassification extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]}class AutoModelForTokenClassification extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]}class AutoModelForSeq2SeqLM extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]}class AutoModelForSpeechSeq2Seq extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]}class AutoModelForTextToSpectrogram extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]}class AutoModelForTextToWaveform extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]}class AutoModelForCausalLM extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_WITH_LM_HEAD_MAPPING_NAMES]}class AutoModelForMaskedLM extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_MASKED_LM_MAPPING_NAMES]}class AutoModelForQuestionAnswering extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]}class AutoModelForVision2Seq extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]}class AutoModelForImageClassification extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]}class AutoModelForImageSegmentation extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]}class AutoModelForSemanticSegmentation extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]}class AutoModelForObjectDetection extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]}class AutoModelForZeroShotObjectDetection extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]}class AutoModelForCTC extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_CTC_MAPPING_NAMES]}class AutoModelForAudioClassification extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]}class AutoModelForDocumentQuestionAnswering extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]}class AutoModelForImageToImage extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]}class AutoModelForDepthEstimation extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]}class AutoModelForImageFeatureExtraction extends PretrainedMixin{static MODEL_CLASS_MAPPINGS=[MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]}class Seq2SeqLMOutput extends ModelOutput{constructor({logits:e,past_key_values:t,encoder_outputs:n,decoder_attentions:r=null,cross_attentions:o=null}){super();this.logits=e;this.past_key_values=t;this.encoder_outputs=n;this.decoder_attentions=r;this.cross_attentions=o}}class SequenceClassifierOutput extends ModelOutput{constructor({logits:e}){super();this.logits=e}}class XVectorOutput extends ModelOutput{constructor({logits:e,embeddings:t}){super();this.logits=e;this.embeddings=t}}class TokenClassifierOutput extends ModelOutput{constructor({logits:e}){super();this.logits=e}}class MaskedLMOutput extends ModelOutput{constructor({logits:e}){super();this.logits=e}}class QuestionAnsweringModelOutput extends ModelOutput{constructor({start_logits:e,end_logits:t}){super();this.start_logits=e;this.end_logits=t}}class CausalLMOutput extends ModelOutput{constructor({logits:e}){super();this.logits=e}}class ImageMattingOutput extends ModelOutput{constructor({alphas:e}){super();this.alphas=e}}class VitsModelOutput extends ModelOutput{constructor({waveform:e,spectrogram:t}){super();this.waveform=e;this.spectrogram=t}}const BROWSER_ENV=typeof self!=="undefined";const WEBWORKER_ENV=BROWSER_ENV&&self.constructor.name==="DedicatedWorkerGlobalScope";let createCanvasFunction;let ImageDataClass;let loadImageFunction;if(BROWSER_ENV){createCanvasFunction=(e,t)=>{if(!self.OffscreenCanvas){throw new Error("OffscreenCanvas not supported by this browser.")}return new self.OffscreenCanvas(e,t)};loadImageFunction=self.createImageBitmap;ImageDataClass=self.ImageData}else if(sharp){loadImageFunction=async e=>{const t=await e.metadata();const n=t.channels;let{data:r,info:o}=await e.rotate().raw().toBuffer({resolveWithObject:true});const i=new RawImage(new Uint8ClampedArray(r),o.width,o.height,o.channels);if(n!==undefined&&n!==o.channels){i.convert(n)}return i}}else{throw new Error("Unable to load image processing library.")}const RESAMPLING_MAPPING={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"};const CONTENT_TYPE_MAP=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class RawImage{constructor(e,t,n,r){this.data=e;this.width=t;this.height=n;this.channels=r}get size(){return[this.width,this.height]}static async read(e){if(e instanceof RawImage){return e}else if(typeof e==="string"||e instanceof URL){return await this.fromURL(e)}else{throw new Error(`Unsupported input type: ${typeof e}`)}}static async fromURL(e){let t=await getFile(e);if(t.status!==200){throw new Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`)}let n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(BROWSER_ENV){let t=await loadImageFunction(e);const n=createCanvasFunction(t.width,t.height).getContext("2d");n.drawImage(t,0,0);return new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}else{let t=sharp(await e.arrayBuffer());return await loadImageFunction(t)}}static fromTensor(e,t="CHW"){if(e.dims.length!==3){throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`)}if(t==="CHW"){e=e.transpose(1,2,0)}else if(t==="HWC");else{throw new Error(`Unsupported channel format: ${t}`)}if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array)){throw new Error(`Unsupported tensor type: ${e.type}`)}switch(e.dims[2]){case 1:case 2:case 3:case 4:return new RawImage(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1){return this}let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t<this.data.length;t+=this.channels){const r=this.data[t];const o=this.data[t+1];const i=this.data[t+2];e[n++]=Math.round(.2989*r+.587*o+.114*i)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(this.channels===3){return this}let e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let t=0,n=0;t<this.data.length;++t){e[n++]=this.data[t];e[n++]=this.data[t];e[n++]=this.data[t]}break;case 4:for(let t=0,n=0;t<this.data.length;t+=4){e[n++]=this.data[t];e[n++]=this.data[t+1];e[n++]=this.data[t+2]}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(this.channels===4){return this}let e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let t=0,n=0;t<this.data.length;++t){e[n++]=this.data[t];e[n++]=this.data[t];e[n++]=this.data[t];e[n++]=255}break;case 3:for(let t=0,n=0;t<this.data.length;t+=3){e[n++]=this.data[t];e[n++]=this.data[t+1];e[n++]=this.data[t+2];e[n++]=255}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,4)}async resize(e,t,{resample:n=2}={}){let r=RESAMPLING_MAPPING[n]??n;if(BROWSER_ENV){let n=this.channels;let r=this.toCanvas();const o=createCanvasFunction(e,t).getContext("2d");o.drawImage(r,0,0,e,t);let i=new RawImage(o.getImageData(0,0,e,t).data,e,t,4);return i.convert(n)}else{let n=this.toSharp();switch(r){case"box":case"hamming":if(r==="box"||r==="hamming"){console.warn(`Resampling method ${r} is not yet supported. Using bilinear instead.`);r="bilinear"}case"nearest":case"bilinear":case"bicubic":n=n.affine([e/this.width,0,0,t/this.height],{interpolator:r});break;case"lanczos":n=n.resize({width:e,height:t,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${r} is not supported.`)}return await loadImageFunction(n)}}async pad([e,t,n,r]){e=Math.max(e,0);t=Math.max(t,0);n=Math.max(n,0);r=Math.max(r,0);if(e===0&&t===0&&n===0&&r===0){return this}if(BROWSER_ENV){let o=this.channels;let i=this.toCanvas();let s=this.width+e+t;let a=this.height+n+r;const c=createCanvasFunction(s,a).getContext("2d");c.drawImage(i,0,0,this.width,this.height,e,n,s,a);let u=new RawImage(c.getImageData(0,0,s,a).data,s,a,4);return u.convert(o)}else{let o=this.toSharp().extend({left:e,right:t,top:n,bottom:r});return await loadImageFunction(o)}}async crop([e,t,n,r]){e=Math.max(e,0);t=Math.max(t,0);n=Math.min(n,this.width-1);r=Math.min(r,this.height-1);if(e===0&&t===0&&n===this.width-1&&r===this.height-1){return this}const o=n-e+1;const i=r-t+1;if(BROWSER_ENV){const n=this.channels;const r=this.toCanvas();const s=createCanvasFunction(o,i).getContext("2d");s.drawImage(r,e,t,o,i,0,0,o,i);const a=new RawImage(s.getImageData(0,0,o,i).data,o,i,4);return a.convert(n)}else{const n=this.toSharp().extract({left:e,top:t,width:o,height:i});return await loadImageFunction(n)}}async center_crop(e,t){if(this.width===e&&this.height===t){return this}let n=(this.width-e)/2;let r=(this.height-t)/2;if(BROWSER_ENV){let o=this.channels;let i=this.toCanvas();const s=createCanvasFunction(e,t).getContext("2d");let a=0;let c=0;let u=0;let l=0;if(n>=0){a=n}else{u=-n}if(r>=0){c=r}else{l=-r}s.drawImage(i,a,c,e,t,u,l,e,t);let f=new RawImage(s.getImageData(0,0,e,t).data,e,t,4);return f.convert(o)}else{let o=this.toSharp();if(n>=0&&r>=0){o=o.extract({left:Math.floor(n),top:Math.floor(r),width:e,height:t})}else if(n<=0&&r<=0){let i=Math.floor(-r);let s=Math.floor(-n);o=o.extend({top:i,left:s,right:e-this.width-s,bottom:t-this.height-i})}else{let i=[0,0];let s=0;if(r<0){i[0]=Math.floor(-r);i[1]=t-this.height-i[0]}else{s=Math.floor(r)}let a=[0,0];let c=0;if(n<0){a[0]=Math.floor(-n);a[1]=e-this.width-a[0]}else{c=Math.floor(n)}o=o.extend({top:i[0],bottom:i[1],left:a[0],right:a[1]}).extract({left:c,top:s,width:e,height:t})}return await loadImageFunction(o)}}async toBlob(e="image/png",t=1){if(!BROWSER_ENV){throw new Error("toBlob() is only supported in browser environments.")}const n=this.toCanvas();return await n.convertToBlob({type:e,quality:t})}toTensor(e="CHW"){let t=new Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e==="HWC");else if(e==="CHW"){t=t.permute(2,0,1)}else{throw new Error(`Unsupported channel format: ${e}`)}return t}toCanvas(){if(!BROWSER_ENV){throw new Error("toCanvas() is only supported in browser environments.")}let e=this.clone().rgba();let t=createCanvasFunction(e.width,e.height);let n=new ImageDataClass(e.data,e.width,e.height);t.getContext("2d").putImageData(n,0,0);return t}_update(e,t,n,r=null){this.data=e;this.width=t;this.height=n;if(r!==null){this.channels=r}return this}clone(){return new RawImage(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(BROWSER_ENV){if(WEBWORKER_ENV){throw new Error("Unable to save an image from a Web Worker.")}const t=e.split(".").pop().toLowerCase();const n=CONTENT_TYPE_MAP.get(t)??"image/png";const r=await this.toBlob(n);const o=URL.createObjectURL(r);const i=document.createElement("a");i.href=o;i.download=e;i.click();i.remove()}else if(!env$1.useFS){throw new Error("Unable to save the image because filesystem is disabled in this environment.")}else{const t=this.toSharp();return await t.toFile(e)}}toSharp(){if(BROWSER_ENV){throw new Error("toSharp() is only supported in server-side environments.")}return sharp(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}async function read_audio(e,t){if(typeof AudioContext==="undefined"){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 n=await(await getFile(e)).arrayBuffer();const r=new AudioContext({sampleRate:t});if(typeof t==="undefined"){console.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`)}const o=await r.decodeAudioData(n);let i;if(o.numberOfChannels===2){const e=Math.sqrt(2);const t=o.getChannelData(0);const n=o.getChannelData(1);i=new Float32Array(t.length);for(let r=0;r<o.length;++r){i[r]=e*(t[r]+n[r])/2}}else{i=o.getChannelData(0)}return i}function hanning(e){if(e<1){return new Float64Array}if(e===1){return new Float64Array([1])}const t=e-1;const n=Math.PI/t;const r=new Float64Array(e);for(let o=0;o<e;++o){const e=2*o-t;r[o]=.5+.5*Math.cos(n*e)}return r}const HERTZ_TO_MEL_MAPPING={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,r=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*r:3*e/200};function hertz_to_mel(e,t="htk"){const n=HERTZ_TO_MEL_MAPPING[t];if(!n){throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".')}return typeof e==="number"?n(e):e.map((e=>n(e)))}const MEL_TO_HERTZ_MAPPING={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,r=Math.log(6.4)/27)=>e>=n?t*Math.exp(r*(e-n)):200*e/3};function mel_to_hertz(e,t="htk"){const n=MEL_TO_HERTZ_MAPPING[t];if(!n){throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".')}return typeof e==="number"?n(e):e.map((e=>n(e)))}function _create_triangular_filter_bank(e,t){const n=Float64Array.from({length:t.length-1},((e,n)=>t[n+1]-t[n]));const r=Array.from({length:e.length},(()=>new Array(t.length)));for(let n=0;n<e.length;++n){const o=r[n];for(let r=0;r<t.length;++r){o[r]=t[r]-e[n]}}const o=t.length-2;const i=Array.from({length:o},(()=>new Array(e.length)));for(let t=0;t<e.length;++t){const e=r[t];for(let r=0;r<o;++r){const o=-e[r]/n[r];const s=e[r+2]/n[r+1];i[r][t]=Math.max(0,Math.min(o,s))}}return i}function linspace(e,t,n){const r=(t-e)/(n-1);return Float64Array.from({length:n},((t,n)=>e+r*n))}function mel_filter_bank(e,t,n,r,o,i=null,s="htk",a=false){if(i!==null&&i!=="slaney"){throw new Error('norm must be one of null or "slaney"')}const c=hertz_to_mel(n,s);const u=hertz_to_mel(r,s);const l=linspace(c,u,t+2);let f=mel_to_hertz(l,s);let d;if(a){const t=o/(e*2);d=hertz_to_mel(Float64Array.from({length:e},((e,n)=>n*t)),s);f=l}else{d=linspace(0,Math.floor(o/2),e)}const h=_create_triangular_filter_bank(d,f);if(i!==null&&i==="slaney"){for(let n=0;n<t;++n){const t=h[n];const r=2/(f[n+2]-f[n]);for(let n=0;n<e;++n){t[n]*=r}}}return h}function padReflect(e,t,n){const r=new e.constructor(e.length+t+n);const o=e.length-1;for(let n=0;n<e.length;++n){r[t+n]=e[n]}for(let n=1;n<=t;++n){r[t-n]=e[calculateReflectOffset(n,o)]}for(let i=1;i<=n;++i){r[o+t+i]=e[calculateReflectOffset(o-i,o)]}return r}function _db_conversion_helper(e,t,n,r,o){if(n<=0){throw new Error("reference must be greater than zero")}if(r<=0){throw new Error("min_value must be greater than zero")}n=Math.max(r,n);const i=Math.log10(n);for(let n=0;n<e.length;++n){e[n]=t*Math.log10(Math.max(r,e[n])-i)}if(o!==null){if(o<=0){throw new Error("db_range must be greater than zero")}const t=max(e)[0]-o;for(let n=0;n<e.length;++n){e[n]=Math.max(e[n],t)}}return e}function amplitude_to_db(e,t=1,n=1e-5,r=null){return _db_conversion_helper(e,20,t,n,r)}function power_to_db(e,t=1,n=1e-10,r=null){return _db_conversion_helper(e,10,t,n,r)}function spectrogram(e,t,n,r,{fft_length:o=null,power:i=1,center:s=true,pad_mode:a="reflect",onesided:c=true,preemphasis:u=null,mel_filters:l=null,mel_floor:f=1e-10,log_mel:d=null,reference:h=1,min_value:p=1e-10,db_range:m=null,remove_dc_offset:w=null,max_num_frames:g=null,do_pad:v=true,transpose:y=false}={}){const _=t.length;if(o===null){o=n}if(n>o){throw Error(`frame_length (${n}) may not be larger than fft_length (${o})`)}if(_!==n){throw new Error(`Length of the window (${_}) must equal frame_length (${n})`)}if(r<=0){throw new Error("hop_length must be greater than zero")}if(i===null&&l!==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(s){if(a!=="reflect"){throw new Error(`pad_mode="${a}" not implemented yet.`)}const t=Math.floor((o-1)/2)+1;e=padReflect(e,t,t)}const b=Math.floor(1+Math.floor((e.length-n)/r));const x=c?Math.floor(o/2)+1:o;let T=b;let M=b;if(g!==null){if(g>b){if(v){M=g}}else{M=T=g}}const E=new FFT(o);const S=new Float64Array(o);const A=new Float64Array(E.outputBufferSize);const $=new Array(T);for(let o=0;o<T;++o){const i=o*r;for(let t=0;t<n;++t){S[t]=e[i+t]}if(w){let e=0;for(let t=0;t<n;++t){e+=S[t]}const t=e/n;for(let e=0;e<n;++e){S[e]-=t}}if(u!==null){for(let e=n-1;e>=1;--e){S[e]-=u*S[e-1]}S[0]*=1-u}for(let e=0;e<t.length;++e){S[e]*=t[e]}E.realTransform(A,S);const s=new Array(x);for(let e=0;e<s.length;++e){const t=e<<1;s[e]=A[t]**2+A[t+1]**2}$[o]=s}if(i!==null&&i!==2){const e=2/i;for(let t=0;t<$.length;++t){const n=$[t];for(let t=0;t<n.length;++t){n[t]**=e}}}const O=l.length;const P=new Float32Array(O*M);const C=y?[M,O]:[O,M];for(let e=0;e<O;++e){const t=l[e];for(let n=0;n<T;++n){const r=$[n];let o=0;for(let e=0;e<x;++e){o+=t[e]*r[e]}P[y?n*O+e:e*T+n]=Math.max(f,o)}}if(i!==null&&d!==null){const e=Math.min(P.length,T*O);switch(d){case"log":for(let t=0;t<e;++t){P[t]=Math.log(P[t])}break;case"log10":for(let t=0;t<e;++t){P[t]=Math.log10(P[t])}break;case"dB":if(i===1){amplitude_to_db(P,h,p,m)}else if(i===2){power_to_db(P,h,p,m)}else{throw new Error(`Cannot use log_mel option '${d}' with power ${i}`)}break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${d}'`)}}return{data:P,dims:C}}function window_function(e,t,{periodic:n=true,frame_length:r=null,center:o=true}={}){const i=n?e+1:e;let s;switch(t){case"boxcar":s=new Float64Array(i).fill(1);break;case"hann":case"hann_window":s=hanning(i);break;case"povey":s=hanning(i).map((e=>Math.pow(e,.85)));break;default:throw new Error(`Unknown window type ${t}.`)}if(n){s=s.subarray(0,e)}if(r===null){return s}if(e>r){throw new Error(`Length of the window (${e}) may not be larger than frame_length (${r})`)}return s}function center_to_corners_format([e,t,n,r]){return[e-n/2,t-r/2,e+n/2,t+r/2]}function post_process_object_detection(e,t=.5,n=null,r=false){const o=e.logits;const i=e.pred_boxes;const[s,a,c]=o.dims;if(n!==null&&n.length!==s){throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")}let u=[];for(let e=0;e<s;++e){let s=n!==null?n[e]:null;let l={boxes:[],classes:[],scores:[]};let f=o[e];let d=i[e];for(let e=0;e<a;++e){let n=f[e];let o=[];let i;if(r){i=n.sigmoid().data;for(let e=0;e<i.length;++e){if(i[e]>t){o.push(e)}}}else{let e=max(n.data)[1];if(e===c-1){continue}o.push(e);i=softmax(n.data)}for(const t of o){let n=d[e].data;n=center_to_corners_format(n);if(s!==null){n=n.map(((e,t)=>e*s[(t+1)%2]))}l.boxes.push(n);l.classes.push(t);l.scores.push(i[t])}}u.push(l)}return u}function validate_audio_inputs(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array)){throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} 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.`)}}function constraint_to_multiple_of(e,t,n=0,r=null){const o=e/t;let i=bankers_round(o)*t;if(r!==null&&i>r){i=Math.floor(o)*t}if(i<n){i=Math.ceil(o)*t}return i}function enforce_size_divisibility([e,t],n){return[Math.max(Math.floor(e/n),1)*n,Math.max(Math.floor(t/n),1)*n]}class FeatureExtractor extends Callable{constructor(e){super();this.config=e}}class ImageFeatureExtractor extends FeatureExtractor{constructor(e){super(e);this.image_mean=this.config.image_mean??this.config.mean;this.image_std=this.config.image_std??this.config.std;this.resample=this.config.resample??2;this.do_rescale=this.config.do_rescale??true;this.rescale_factor=this.config.rescale_factor??1/255;this.do_normalize=this.config.do_normalize;this.do_resize=this.config.do_resize;this.do_thumbnail=this.config.do_thumbnail;this.size=this.config.size;this.size_divisibility=this.config.size_divisibility??this.config.size_divisor;this.do_center_crop=this.config.do_center_crop;this.crop_size=this.config.crop_size;this.do_convert_rgb=this.config.do_convert_rgb??true;this.do_crop_margin=this.config.do_crop_margin;this.pad_size=this.config.pad_size;this.do_pad=this.config.do_pad;if(this.do_pad&&!this.pad_size&&this.size&&this.size.width!==undefined&&this.size.height!==undefined){this.pad_size=this.size}this.do_flip_channel_order=this.config.do_flip_channel_order??false}async thumbnail(e,t,n=2){const r=e.height;const o=e.width;const i=t.height;const s=t.width;let a=Math.min(r,i);let c=Math.min(o,s);if(a===r&&c===o){return e}if(r>o){c=Math.floor(o*a/r)}else if(o>r){a=Math.floor(r*c/o)}return await e.resize(c,a,{resample:n})}async crop_margin(e,t=200){const n=e.clone().grayscale();const r=min(n.data)[0];const o=max(n.data)[0];const i=o-r;if(i===0){return e}const s=t/255;let a=n.width,c=n.height,u=0,l=0;for(let e=0;e<n.height;++e){const t=e*n.width;for(let o=0;o<n.width;++o){if((n.data[t+o]-r)/i<s){a=Math.min(a,o);c=Math.min(c,e);u=Math.max(u,o);l=Math.max(l,e)}}}e=await e.crop([a,c,u,l]);return e}pad_image(e,t,n,{mode:r="constant",center:o=false,constant_values:i=0}={}){const[s,a,c]=t;let u,l;if(typeof n==="number"){u=n;l=n}else{u=n.width;l=n.height}if(u!==a||l!==s){const n=new Float32Array(u*l*c);if(Array.isArray(i)){for(let e=0;e<n.length;++e){n[e]=i[e%c]}}else if(i!==0){n.fill(i)}const[f,d]=o?[Math.floor((u-a)/2),Math.floor((l-s)/2)]:[0,0];for(let t=0;t<s;++t){const r=(t+d)*u;const o=t*a;for(let t=0;t<a;++t){const i=(r+t+f)*c;const s=(o+t)*c;for(let t=0;t<c;++t){n[i+t]=e[s+t]}}}if(r==="symmetric"){if(o){throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.")}const t=s-1;const r=a-1;for(let o=0;o<l;++o){const i=o*u;const l=calculateReflectOffset(o,t)*a;for(let t=0;t<u;++t){if(o<s&&t<a)continue;const u=(i+t)*c;const f=(l+calculateReflectOffset(t,r))*c;for(let t=0;t<c;++t){n[u+t]=e[f+t]}}}}e=n;t=[l,u,c]}return[e,t]}rescale(e){for(let t=0;t<e.length;++t){e[t]=this.rescale_factor*e[t]}}get_resize_output_image_size(e,t){const[n,r]=e.size;let o;let i;if(this.do_thumbnail){const{height:e,width:n}=t;o=Math.min(e,n)}else if(Number.isInteger(t)){o=t;i=this.config.max_size??o}else if(t!==undefined){o=t.shortest_edge;i=t.longest_edge}if(o!==undefined||i!==undefined){const e=o===undefined?1:Math.max(o/n,o/r);const t=n*e;const s=r*e;const a=i===undefined?1:Math.min(i/t,i/s);let c=Math.floor(Number((t*a).toFixed(2)));let u=Math.floor(Number((s*a).toFixed(2)));if(this.size_divisibility!==undefined){[c,u]=enforce_size_divisibility([c,u],this.size_divisibility)}return[c,u]}else if(t!==undefined&&t.width!==undefined&&t.height!==undefined){let e=t.width;let o=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let t=o/r;let i=e/n;if(Math.abs(1-i)<Math.abs(1-t)){t=i}else{i=t}o=constraint_to_multiple_of(t*r,this.config.ensure_multiple_of);e=constraint_to_multiple_of(i*n,this.config.ensure_multiple_of)}return[e,o]}else if(this.size_divisibility!==undefined){return enforce_size_divisibility([n,r],this.size_divisibility)}else{throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}}async resize(e){const[t,n]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,n,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:n=null,do_convert_rgb:r=null,do_convert_grayscale:o=null,do_flip_channel_order:i=null}={}){if(this.do_crop_margin){e=await this.crop_margin(e)}const[s,a]=e.size;if(r??this.do_convert_rgb){e=e.rgb()}else if(o){e=e.grayscale()}if(this.do_resize){e=await this.resize(e)}if(this.do_thumbnail){e=await this.thumbnail(e,this.size,this.resample)}if(this.do_center_crop){let t;let n;if(Number.isInteger(this.crop_size)){t=this.crop_size;n=this.crop_size}else{t=this.crop_size.width;n=this.crop_size.height}e=await e.center_crop(t,n)}const c=[e.height,e.width];let u=Float32Array.from(e.data);let l=[e.height,e.width,e.channels];if(this.do_rescale){this.rescale(u)}if(t??this.do_normalize){let t=this.image_mean;if(!Array.isArray(this.image_mean)){t=new Array(e.channels).fill(t)}let n=this.image_std;if(!Array.isArray(this.image_std)){n=new Array(e.channels).fill(t)}if(t.length!==e.channels||n.length!==e.channels){throw new Error(`When set to arrays, the length of \`image_mean\` (${t.length}) and \`image_std\` (${n.length}) must match the number of channels in the image (${e.channels}).`)}for(let r=0;r<u.length;r+=e.channels){for(let o=0;o<e.channels;++o){u[r+o]=(u[r+o]-t[o])/n[o]}}}if(n??this.do_pad){if(this.pad_size){const t=this.pad_image(u,[e.height,e.width,e.channels],this.pad_size);[u,l]=t}else if(this.size_divisibility){const[e,t]=enforce_size_divisibility([l[1],l[0]],this.size_divisibility);[u,l]=this.pad_image(u,l,{width:e,height:t})}}if(i??this.do_flip_channel_order){if(l[2]!==3){throw new Error("Flipping channel order is only supported for RGB images.")}for(let e=0;e<u.length;e+=3){const t=u[e];u[e]=u[e+2];u[e+2]=t}}const f=new Tensor("float32",u,l).permute(2,0,1);return{original_size:[a,s],reshaped_input_size:c,pixel_values:f}}async _call(e,...t){if(!Array.isArray(e)){e=[e]}const n=await Promise.all(e.map((e=>this.preprocess(e))));const r=stack(n.map((e=>e.pixel_values)),0);return{pixel_values:r,original_sizes:n.map((e=>e.original_size)),reshaped_input_sizes:n.map((e=>e.reshaped_input_size))}}}class SegformerFeatureExtractor extends ImageFeatureExtractor{post_process_semantic_segmentation(e,t=null){const n=e.logits;const r=n.dims[0];if(t!==null&&t.length!==r){throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")}const o=[];for(let e=0;e<r;++e){const r=t!==null?t[e]:null;let i=n[e];if(r!==null){i=interpolate(i,r,"bilinear",false)}const[s,a]=r??i.dims.slice(-2);const c=new Tensor("int32",new Int32Array(s*a),[s,a]);const u=i[0].data;for(let e=1;e<i.dims[0];++e){const t=i[e].data;for(let n=0;n<t.length;++n){if(t[n]>u[n]){u[n]=t[n];c.data[n]=e}}}const l=new Array(i.dims[0]);const f=c.data;for(let e=0;e<f.length;++e){const t=f[e];l[t]=t}const d=l.filter((e=>e!==undefined));o.push({segmentation:c,labels:d})}return o}}class DPTFeatureExtractor extends ImageFeatureExtractor{}class DPTImageProcessor extends DPTFeatureExtractor{}class BitImageProcessor extends ImageFeatureExtractor{}class GLPNFeatureExtractor extends ImageFeatureExtractor{}class CLIPFeatureExtractor extends ImageFeatureExtractor{}class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor{}class SiglipImageProcessor extends ImageFeatureExtractor{}class ConvNextFeatureExtractor extends ImageFeatureExtractor{constructor(e){super(e);this.crop_pct=this.config.crop_pct??224/256}async resize(e){const t=this.size?.shortest_edge;if(t===undefined){throw new Error(`Size dictionary must contain 'shortest_edge' key.`)}if(t<384){const n=Math.floor(t/this.crop_pct);const[r,o]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(r,o,{resample:this.resample});e=await e.center_crop(t,t)}else{e=await e.resize(t,t,{resample:this.resample})}return e}}class ConvNextImageProcessor extends ConvNextFeatureExtractor{}class ViTFeatureExtractor extends ImageFeatureExtractor{}class ViTImageProcessor extends ImageFeatureExtractor{}class EfficientNetImageProcessor extends ImageFeatureExtractor{constructor(e){super(e);this.include_top=this.config.include_top??true;if(this.include_top){this.image_std=this.image_std.map((e=>e*e))}}}class MobileViTFeatureExtractor extends ImageFeatureExtractor{}class MobileViTImageProcessor extends MobileViTFeatureExtractor{}class OwlViTFeatureExtractor extends ImageFeatureExtractor{post_process_object_detection(...e){return post_process_object_detection(...e)}}class Owlv2ImageProcessor extends OwlViTFeatureExtractor{}class DeiTFeatureExtractor extends ImageFeatureExtractor{}class BeitFeatureExtractor extends ImageFeatureExtractor{}class DonutFeatureExtractor extends ImageFeatureExtractor{pad_image(e,t,n,r={}){const[o,i,s]=t;let a=this.image_mean;if(!Array.isArray(this.image_mean)){a=new Array(s).fill(a)}let c=this.image_std;if(!Array.isArray(c)){c=new Array(s).fill(a)}const u=a.map(((e,t)=>-e/c[t]));return super.pad_image(e,t,n,{center:true,constant_values:u,...r})}}class NougatImageProcessor extends DonutFeatureExtractor{}class DetrFeatureExtractor extends ImageFeatureExtractor{async _call(e){const t=await super._call(e);const n=[t.pixel_values.dims[0],64,64];const r=new Tensor("int64",new BigInt64Array(n.reduce(((e,t)=>e*t))).fill(1n),n);return{...t,pixel_mask:r}}post_process_object_detection(...e){return post_process_object_detection(...e)}remove_low_and_no_objects(e,t,n,r){let o=[];let i=[];let s=[];for(let a=0;a<e.dims[0];++a){let c=e[a];let u=t[a];let l=max(c.data)[1];if(l===r){continue}let f=softmax(c.data);let d=f[l];if(d>n){o.push(u);i.push(d);s.push(l)}}return[o,i,s]}check_segment_validity(e,t,n,r=.5,o=.8){let i=[];let s=0;let a=0;for(let o=0;o<e.length;++o){if(e[o]===n){i.push(o);++s}if(t[n].data[o]>=r){++a}}let c=s>0&&a>0;if(c){let e=s/a;c=e>o}return[c,i]}compute_segments(e,t,n,r,o,i=null,s=null){let[a,c]=s??e[0].dims;let u=new Tensor("int32",new Int32Array(a*c),[a,c]);let l=[];if(s!==null){for(let t=0;t<e.length;++t){e[t]=interpolate(e[t],s,"bilinear",false)}}let f=new Int32Array(e[0].data.length);let d=new Float32Array(e[0].data.length);for(let n=0;n<e.length;++n){let r=t[n];for(let t=0;t<e[n].data.length;++t){e[n].data[t]*=r;if(e[n].data[t]>d[t]){f[t]=n;d[t]=e[n].data[t]}}}let h=0;for(let i=0;i<n.length;++i){let s=n[i];let[a,c]=this.check_segment_validity(f,e,i,r,o);if(!a){continue}++h;for(let e of c){u.data[e]=h}l.push({id:h,label_id:s,score:t[i]})}return[u,l]}post_process_panoptic_segmentation(e,t=.5,n=.5,r=.8,o=null,i=null){if(o===null){console.warn("`label_ids_to_fuse` unset. No instance will be fused.");o=new Set}const s=e.logits;const a=e.pred_masks;const c=a.sigmoid();let[u,l,f]=s.dims;f-=1;if(i!==null&&i.length!==u){throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits")}let d=[];for(let e=0;e<u;++e){let a=i!==null?i[e]:null;let u=s[e];let l=c[e];let[h,p,m]=this.remove_low_and_no_objects(u,l,t,f);if(m.length===0){let[e,t]=a??l.dims.slice(-2);let n=new Tensor("int32",new Int32Array(e*t).fill(-1),[e,t]);d.push({segmentation:n,segments_info:[]});continue}let[w,g]=this.compute_segments(h,p,m,n,r,o,a);d.push({segmentation:w,segments_info:g})}return d}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class YolosFeatureExtractor extends ImageFeatureExtractor{post_process_object_detection(...e){return post_process_object_detection(...e)}}class SamImageProcessor extends ImageFeatureExtractor{reshape_input_points(e,t,n){e=structuredClone(e);let r=calculateDimensions(e);if(r.length===3){r=[1,...r];e=[e]}else if(r.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 r=0;r<e.length;++r){let o=t[r];let i=n[r];let s=[i[0]/o[0],i[1]/o[1]];for(let t=0;t<e[r].length;++t){for(let n=0;n<e[r][t].length;++n){for(let o=0;o<e[r][t][n].length;++o){e[r][t][n][o]*=s[o]}}}}return new Tensor("float32",Float32Array.from(e.flat(Infinity)),r)}add_input_labels(e,t){let n=calculateDimensions(e);if(n.length===2){n=[1,...n];e=[e]}else if(n.length!==3){throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.")}if(n.some(((e,n)=>e!==t.dims[n]))){throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`)}return new Tensor("int64",e.flat(Infinity).map(BigInt),n)}async _call(e,t=null,n=null){const r=await super._call(e);if(t){r.input_points=this.reshape_input_points(t,r.original_sizes,r.reshaped_input_sizes)}if(n){if(!r.input_points){throw Error("`input_points` must be provided if `input_labels` are provided.")}r.input_labels=this.add_input_labels(n,r.input_points)}return r}post_process_masks(e,t,n,{mask_threshold:r=0,binarize:o=true,pad_size:i=null}={}){const s=[];i=i??this.pad_size;const a=[i.height,i.width];for(let i=0;i<t.length;++i){const c=t[i];const u=n[i];const l=e[i];const f=[];for(let e=0;e<l.dims[0];++e){const t=l[e];let n=interpolate(t,a,"bilinear",false);n=n.slice(null,[0,u[0]],[0,u[1]]);n=interpolate(n,c,"bilinear",false);if(o){const e=new Uint8Array(n.data.length);for(let t=0;t<n.data.length;++t){if(n.data[t]>r){e[t]=1}}n=new Tensor("bool",e,n.dims)}f.push(n)}s.push(stack(f))}return s}}class Swin2SRImageProcessor extends ImageFeatureExtractor{pad_image(e,t,n,r={}){const[o,i,s]=t;return super.pad_image(e,t,{width:i+(n-i%n)%n,height:o+(n-o%n)%n},{mode:"symmetric",center:false,constant_values:-1,...r})}}class VitMatteImageProcessor extends ImageFeatureExtractor{async _call(e,t){if(!Array.isArray(e)){e=[e]}if(!Array.isArray(t)){t=[t]}const n=await Promise.all(e.map((e=>this.preprocess(e))));const r=await Promise.all(t.map((e=>this.preprocess(e,{do_normalize:false,do_convert_rgb:false,do_convert_grayscale:true}))));const o=stack(n.map(((e,t)=>cat([e.pixel_values,r[t].pixel_values],0))),0);return{pixel_values:o,original_sizes:n.map((e=>e.original_size)),reshaped_input_sizes:n.map((e=>e.reshaped_input_size))}}}class WhisperFeatureExtractor extends FeatureExtractor{constructor(e){super(e);this.config.mel_filters??=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=window_function(this.config.n_fft,"hann")}_extract_fbank_features(e){const{data:t,dims:n}=spectrogram(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames});const r=max(t)[0];for(let e=0;e<t.length;++e){t[e]=(Math.max(t[e],r-8)+4)/4}return{data:t,dims:n}}async _call(e){validate_audio_inputs(e,"WhisperFeatureExtractor");let t;if(e.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`.");t=e.slice(0,this.config.n_samples)}else{t=new Float32Array(this.config.n_samples);t.set(e)}const{data:n,dims:r}=this._extract_fbank_features(t);return{input_features:new Tensor("float32",n,[1,...r])}}}class Wav2Vec2FeatureExtractor extends FeatureExtractor{_zero_mean_unit_var_norm(e){const t=e.reduce(((e,t)=>e+t),0);const n=t/e.length;const r=e.reduce(((e,t)=>e+(t-n)**2),0)/e.length;return e.map((e=>(e-n)/Math.sqrt(r+1e-7)))}async _call(e){validate_audio_inputs(e,"Wav2Vec2FeatureExtractor");if(e instanceof Float64Array){e=new Float32Array(e)}let t=e;if(this.config.do_normalize){t=this._zero_mean_unit_var_norm(t)}const n=[1,t.length];return{input_values:new Tensor("float32",t,n),attention_mask:new Tensor("int64",new BigInt64Array(t.length).fill(1n),n)}}}class SeamlessM4TFeatureExtractor extends FeatureExtractor{constructor(e){super(e);const t=this.config.sampling_rate;const n=mel_filter_bank(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",true);for(let e=0;e<n.length;++e){n[e].push(0)}this.mel_filters=n;this.window=window_function(400,"povey",{periodic:false})}_extract_fbank_features(e,t){e=e.map((e=>e*32768));return spectrogram(e,this.window,400,160,{fft_length:512,power:2,center:false,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1.192092955078125e-7,remove_dc_offset:true,max_num_frames:t,transpose:true})}async _call(e,{padding:t=true,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:r=true,return_attention_mask:o=true}={}){validate_audio_inputs(e,"SeamlessM4TFeatureExtractor");let i=this._extract_fbank_features(e,this.config.max_length);if(r){const[e,t]=i.dims;for(let n=0;n<t;++n){let r=0;for(let o=0;o<e;++o){r+=i.data[o*t+n]}const o=r/e;let s=0;for(let r=0;r<e;++r){s+=(i.data[r*t+n]-o)**2}s/=e-1;const a=Math.sqrt(s+1e-7);for(let r=0;r<e;++r){const e=r*t+n;i.data[e]=(i.data[e]-o)/a}}}let s;if(t){const[e,t]=i.dims;const r=e%n;if(r>0){const n=new Float32Array(t*(e+r));n.set(i.data);n.fill(this.config.padding_value,i.data.length);const a=e+r;i={data:n,dims:[a,t]};if(o){s=new Tensor("int64",new BigInt64Array(a),[1,a]);s.data.fill(1n,0,e)}}}const[a,c]=i.dims;const u=this.config.stride;const l=a%u;if(l!==0){throw new Error(`The number of frames (${a}) must be a multiple of the stride (${u}).`)}const f=new Tensor("float32",i.data,i.dims).view(1,Math.floor(a/u),c*u);const d={input_features:f};if(o){const e=f.dims[1];const t=new Tensor("int64",new BigInt64Array(e),[1,e]);if(s){for(let e=1,n=0;e<a;e+=u,++n){t.data[n]=s.data[e]}}else{t.data.fill(1n)}d.attention_mask=t}return d}}class ASTFeatureExtractor extends FeatureExtractor{constructor(e){super(e);const t=this.config.sampling_rate;const n=mel_filter_bank(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",true);for(let e=0;e<n.length;++e){n[e].push(0)}this.mel_filters=n;this.window=window_function(400,"hann",{periodic:false});this.mean=this.config.mean;this.std=this.config.std}_extract_fbank_features(e,t){return spectrogram(e,this.window,400,160,{fft_length:512,power:2,center:false,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1.192092955078125e-7,remove_dc_offset:true,max_num_frames:t,transpose:true})}async _call(e){validate_audio_inputs(e,"ASTFeatureExtractor");const t=this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const e=this.std*2;for(let n=0;n<t.data.length;++n){t.data[n]=(t.data[n]-this.mean)/e}}return{input_values:new Tensor("float32",t.data,[1,...t.dims])}}}class ClapFeatureExtractor extends FeatureExtractor{constructor(e){super(e);this.mel_filters=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=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=window_function(this.config.fft_window_size,"hann")}_get_input_mel(e,t,n,r){let o;let i=false;const s=e.length-t;if(s>0){if(n==="rand_trunc"){i=true;const n=Math.floor(Math.random()*(s+1));e=e.subarray(n,n+t);o=this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples);o.dims=[1,...o.dims]}else{throw new Error(`Truncation strategy "${n}" not implemented`)}}else{if(s<0){let n=new Float64Array(t);n.set(e);if(r==="repeat"){for(let r=e.length;r<t;r+=e.length){n.set(e.subarray(0,Math.min(e.length,t-r)),r)}}else if(r==="repeatpad"){for(let t=e.length;t<-s;t+=e.length){n.set(e,t)}}e=n}if(n==="fusion"){throw new Error(`Truncation strategy "${n}" not implemented`)}o=this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples);o.dims=[1,...o.dims]}return{...o,longer:i}}_extract_fbank_features(e,t,n=null){return spectrogram(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:n,do_pad:false,transpose:true})}async _call(e,{max_length:t=null}={}){validate_audio_inputs(e,"ClapFeatureExtractor");const n=this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding);return{input_features:new Tensor("float32",n.data,[1,...n.dims])}}}class SpeechT5FeatureExtractor extends FeatureExtractor{}class Processor extends Callable{constructor(e){super();this.feature_extractor=e}async _call(e,...t){return await this.feature_extractor(e,...t)}}class SamProcessor extends Processor{async _call(...e){return await this.feature_extractor(...e)}post_process_masks(...e){return this.feature_extractor.post_process_masks(...e)}reshape_input_points(...e){return this.feature_extractor.reshape_input_points(...e)}}class WhisperProcessor extends Processor{async _call(e){return await this.feature_extractor(e)}}class Wav2Vec2ProcessorWithLM extends Processor{async _call(e){return await this.feature_extractor(e)}}class SpeechT5Processor extends Processor{async _call(e){return await this.feature_extractor(e)}}class OwlViTProcessor extends Processor{}class AutoProcessor{static FEATURE_EXTRACTOR_CLASS_MAPPING={ImageFeatureExtractor,WhisperFeatureExtractor,ViTFeatureExtractor,MobileViTFeatureExtractor,MobileViTImageProcessor,OwlViTFeatureExtractor,Owlv2ImageProcessor,CLIPFeatureExtractor,ChineseCLIPFeatureExtractor,SiglipImageProcessor,ConvNextFeatureExtractor,ConvNextImageProcessor,SegformerFeatureExtractor,BitImageProcessor,DPTImageProcessor,DPTFeatureExtractor,GLPNFeatureExtractor,BeitFeatureExtractor,DeiTFeatureExtractor,DetrFeatureExtractor,YolosFeatureExtractor,DonutFeatureExtractor,NougatImageProcessor,EfficientNetImageProcessor,ViTImageProcessor,VitMatteImageProcessor,SamImageProcessor,Swin2SRImageProcessor,Wav2Vec2FeatureExtractor,SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor,ASTFeatureExtractor,ClapFeatureExtractor};static PROCESSOR_CLASS_MAPPING={WhisperProcessor,Wav2Vec2ProcessorWithLM,SamProcessor,SpeechT5Processor,OwlViTProcessor};static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:o=false,revision:i="main"}={}){let s=n??await getModelJSON(e,"preprocessor_config.json",true,{progress_callback:t,cache_dir:r,local_files_only:o,revision:i});let a=s.feature_extractor_type??s.image_processor_type;let c=this.FEATURE_EXTRACTOR_CLASS_MAPPING[a];if(!c){if(s.size!==undefined){console.warn(`Feature extractor type "${a}" not found, assuming ImageFeatureExtractor due to size parameter in config.`);c=ImageFeatureExtractor}else{throw new Error(`Unknown Feature Extractor type: ${a}`)}}let u=this.PROCESSOR_CLASS_MAPPING[s.processor_class]??Processor;let l=new c(s);return new u(l)}}async function prepareImages(e){if(!Array.isArray(e)){e=[e]}return await Promise.all(e.map((e=>RawImage.read(e))))}async function prepareAudios(e,t){if(!Array.isArray(e)){e=[e]}return await Promise.all(e.map((e=>{if(typeof e==="string"||e instanceof URL){return read_audio(e,t)}else if(e instanceof Float64Array){return new Float32Array(e)}return e})))}function get_bounding_box(e,t){if(t){e=e.map((e=>e|0))}const[n,r,o,i]=e;return{xmin:n,ymin:r,xmax:o,ymax:i}}class Pipeline extends Callable{constructor({task:e,model:t,tokenizer:n=null,processor:r=null}){super();this.task=e;this.model=t;this.tokenizer=n;this.processor=r}async dispose(){await this.model.dispose()}}class TextClassificationPipeline extends Pipeline{constructor(e){super(e)}async _call(e,{topk:t=1}={}){const n=this.tokenizer(e,{padding:true,truncation:true});const r=await this.model(n);const o=this.model.config.problem_type==="multi_label_classification"?e=>e.sigmoid().data:e=>softmax(e.data);const i=this.model.config.id2label;const s=[];for(const e of r.logits){const n=o(e);const r=getTopItems(n,t);const a=r.map((e=>({label:i[e[0]],score:e[1]})));if(t===1){s.push(...a)}else{s.push(a)}}return Array.isArray(e)||t===1?s:s[0]}}class TokenClassificationPipeline extends Pipeline{constructor(e){super(e)}async _call(e,{ignore_labels:t=["O"]}={}){const n=Array.isArray(e);const r=this.tokenizer(n?e:[e],{padding:true,truncation:true});const o=await this.model(r);const i=o.logits;const s=this.model.config.id2label;const a=[];for(let e=0;e<i.dims[0];++e){const n=r.input_ids[e];const o=i[e];const c=[];for(let e=0;e<o.dims[0];++e){const r=o[e];const i=max(r.data)[1];const a=s?s[i]:`LABEL_${i}`;if(t.includes(a)){continue}const u=this.tokenizer.decode([n[e].item()],{skip_special_tokens:true});if(u===""){continue}const l=softmax(r.data);c.push({entity:a,score:l[i],index:e,word:u,start:null,end:null})}a.push(c)}return n?a:a[0]}}class QuestionAnsweringPipeline extends Pipeline{constructor(e){super(e)}async _call(e,t,{topk:n=1}={}){const r=this.tokenizer(e,{text_pair:t,padding:true,truncation:true});const o=await this.model(r);const i=[];for(let e=0;e<o.start_logits.dims[0];++e){const t=r.input_ids[e];const s=t.indexOf(this.tokenizer.sep_token_id);const a=Array.from(softmax(o.start_logits[e].data)).map(((e,t)=>[e,t])).filter((e=>e[1]>s));const c=Array.from(softmax(o.end_logits[e].data)).map(((e,t)=>[e,t])).filter((e=>e[1]>s));const u=product(a,c).filter((e=>e[0][1]<=e[1][1])).map((e=>[e[0][1],e[1][1],e[0][0]*e[1][0]])).sort(((e,t)=>t[2]-e[2]));for(let e=0;e<Math.min(u.length,n);++e){const[n,r,o]=u[e];const s=[...t].slice(n,r+1);const a=this.tokenizer.decode(s,{skip_special_tokens:true});i.push({answer:a,score:o})}}return n===1?i[0]:i}}class FillMaskPipeline extends Pipeline{constructor(e){super(e)}async _call(e,{topk:t=5}={}){const n=this.tokenizer(e,{padding:true,truncation:true});const r=await this.model(n);const o=[];for(let e=0;e<n.input_ids.dims[0];++e){const i=n.input_ids[e];const s=i.indexOf(this.tokenizer.mask_token_id);if(s===-1){throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`)}const a=r.logits[e];const c=a[s];const u=getTopItems(softmax(c.data),t);o.push(u.map((e=>{const t=[...i];t[s]=e[0];return{score:e[1],token:e[0],token_str:this.tokenizer.model.vocab[e[0]],sequence:this.tokenizer.decode(t,{skip_special_tokens:true})}})))}return Array.isArray(e)?o:o[0]}}class Text2TextGenerationPipeline extends Pipeline{_key="generated_text";constructor(e){super(e)}async _call(e,t={}){if(!Array.isArray(e)){e=[e]}if(this.model.config.prefix){e=e.map((e=>this.model.config.prefix+e))}const n=this.model.config.task_specific_params;if(n&&n[this.task]){if(n[this.task].prefix){e=e.map((e=>n[this.task].prefix+e))}}const r=this.tokenizer;const o={padding:true,truncation:true};let i;if(this instanceof TranslationPipeline&&"_build_translation_inputs"in r){i=r._build_translation_inputs(e,o,t).input_ids}else{i=r(e,o).input_ids}const s=await this.model.generate(i,t);return r.batch_decode(s,{skip_special_tokens:true}).map((e=>({[this._key]:e})))}}class SummarizationPipeline extends Text2TextGenerationPipeline{_key="summary_text";constructor(e){super(e)}}class TranslationPipeline extends Text2TextGenerationPipeline{_key="translation_text";constructor(e){super(e)}}function isChat(e){return Array.isArray(e)&&e.every((e=>"role"in e&&"content"in e))}class TextGenerationPipeline extends Pipeline{constructor(e){super(e)}async _call(e,t={}){let n=false;let r=false;let o;if(typeof e==="string"){o=e=[e]}else if(Array.isArray(e)&&e.every((e=>typeof e==="string"))){n=true;o=e}else{if(isChat(e)){e=[e]}else if(Array.isArray(e)&&e.every(isChat)){n=true}else{throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats")}r=true;o=e.map((e=>this.tokenizer.apply_chat_template(e,{tokenize:false,add_generation_prompt:true})))}const i=t.add_special_tokens??false;const s=r?false:t.return_full_text??true;this.tokenizer.padding_side="left";const{input_ids:a,attention_mask:c}=this.tokenizer(o,{add_special_tokens:i,padding:true,truncation:true});const u=await this.model.generate(a,t,null,{inputs_attention_mask:c});let l=this.tokenizer.batch_decode(u,{skip_special_tokens:true});let f;if(!s&&a.dims.at(-1)>0){f=this.tokenizer.batch_decode(a,{skip_special_tokens:true}).map((e=>e.length))}const d=Array.from({length:e.length},(e=>[]));for(let t=0;t<l.length;++t){const n=Math.floor(t/u.length*e.length);if(f){l[t]=l[t].slice(f[n])}d[n].push({generated_text:r?[...e[n],{role:"assistant",content:l[t]}]:l[t]})}return!n&&d.length===1?d[0]:d}}class ZeroShotClassificationPipeline extends Pipeline{constructor(e){super(e);this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map((([e,t])=>[e.toLowerCase(),t])));this.entailment_id=this.label2id["entailment"];if(this.entailment_id===undefined){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"];if(this.contradiction_id===undefined){console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.");this.contradiction_id=0}}async _call(e,t,{hypothesis_template:n="This example is {}.",multi_label:r=false}={}){const o=Array.isArray(e);if(!o){e=[e]}if(!Array.isArray(t)){t=[t]}const i=t.map((e=>n.replace("{}",e)));const s=r||t.length===1;const a=[];for(const n of e){const e=[];for(const t of i){const r=this.tokenizer(n,{text_pair:t,padding:true,truncation:true});const o=await this.model(r);if(s){e.push([o.logits.data[this.contradiction_id],o.logits.data[this.entailment_id]])}else{e.push(o.logits.data[this.entailment_id])}}const r=s?e.map((e=>softmax(e)[1])):softmax(e);const o=r.map(((e,t)=>[e,t])).sort(((e,t)=>t[0]-e[0]));a.push({sequence:n,labels:o.map((e=>t[e[1]])),scores:o.map((e=>e[0]))})}return o?a:a[0]}}class FeatureExtractionPipeline extends Pipeline{constructor(e){super(e)}async _call(e,{pooling:t="none",normalize:n=false,quantize:r=false,precision:o="binary"}={}){const i=this.tokenizer(e,{padding:true,truncation:true});const s=await this.model(i);let a=s.last_hidden_state??s.logits??s.token_embeddings;if(t==="none");else if(t==="mean"){a=mean_pooling(a,i.attention_mask)}else if(t==="cls"){a=a.slice(null,0)}else{throw Error(`Pooling method '${t}' not supported.`)}if(n){a=a.normalize(2,-1)}if(r){a=quantize_embeddings(a,o)}return a}}class ImageFeatureExtractionPipeline extends Pipeline{constructor(e){super(e)}async _call(e,{pool:t=null}={}){const n=await prepareImages(e);const{pixel_values:r}=await this.processor(n);const o=await this.model({pixel_values:r});let i;if(t){if(!("pooler_output"in o)){throw Error(`No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.`)}i=o.pooler_output}else{i=o.last_hidden_state??o.logits??o.image_embeds}return i}}class AudioClassificationPipeline extends Pipeline{constructor(e){super(e)}async _call(e,{topk:t=null}={}){const n=!Array.isArray(e);const r=this.processor.feature_extractor.config.sampling_rate;const o=await prepareAudios(e,r);const i=this.model.config.id2label;const s=[];for(const e of o){const n=await this.processor(e);const r=await this.model(n);const o=r.logits[0];const a=getTopItems(softmax(o.data),t);const c=a.map((e=>({label:i[e[0]],score:e[1]})));if(t===1){s.push(...c)}else{s.push(c)}}return!n||t===1?s:s[0]}}class ZeroShotAudioClassificationPipeline extends Pipeline{constructor(e){super(e)}async _call(e,t,{hypothesis_template:n="This is a sound of {}."}={}){const r=!Array.isArray(e);if(r){e=[e]}const o=t.map((e=>n.replace("{}",e)));const i=this.tokenizer(o,{padding:true,truncation:true});const s=this.processor.feature_extractor.config.sampling_rate;const a=await prepareAudios(e,s);const c=[];for(const e of a){const n=await this.processor(e);const r=await this.model({...i,...n});const o=softmax(r.logits_per_audio.data);c.push([...o].map(((e,n)=>({score:e,label:t[n]}))))}return r?c[0]:c}}class AutomaticSpeechRecognitionPipeline extends Pipeline{constructor(e){super(e)}async _call(e,t={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(e,t);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(e,t);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t={}){if(t.language){console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".')}if(t.task){console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".')}const n=!Array.isArray(e);if(n){e=[e]}const r=this.processor.feature_extractor.config.sampling_rate;const o=await prepareAudios(e,r);const i=[];for(const e of o){const t=await this.processor(e);const n=await this.model(t);const r=n.logits[0];const o=[];for(const e of r){o.push(max(e.data)[1])}const s=this.tokenizer.decode(o);i.push({text:s})}return n?i[0]:i}async _call_whisper(e,t={}){const n=t.return_timestamps??false;const r=t.chunk_length_s??0;const o=t.chunk_callback??null;const i=t.force_full_sequences??false;let s=t.stride_length_s??null;if(n==="word"){t["return_token_timestamps"]=true}const a=pop(t,"language",null);const c=pop(t,"task",null);if(a||c||n){if(t.forced_decoder_ids){throw new Error("Cannot specify `language`/`task`/`return_timestamps` and `forced_decoder_ids` at the same time.")}const e=this.tokenizer.get_decoder_prompt_ids({language:a,task:c,no_timestamps:!n});if(e.length>0){t.forced_decoder_ids=e}}const u=!Array.isArray(e);if(u){e=[e]}const l=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions;const f=this.processor.feature_extractor.config.hop_length;const d=this.processor.feature_extractor.config.sampling_rate;const h=await prepareAudios(e,d);const p=[];for(const e of h){let a=[];if(r>0){if(s===null){s=r/6}else if(r<=s){throw Error("`chunk_length_s` must be larger than `stride_length_s`.")}const t=d*r;const n=d*s;const o=t-2*n;let i=0;while(i<e.length){const r=e.subarray(i,i+t);const s=await this.processor(r);const c=i===0;const u=i+o>=e.length;a.push({stride:[r.length,c?0:n,u?0:n],input_features:s.input_features,is_last:u});i+=o}}else{a=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:true}]}for(const e of a){t.num_frames=Math.floor(e.stride[0]/f);const r=await this.model.generate(e.input_features,t);if(n==="word"){e.tokens=r.sequences[0];e.token_timestamps=r.token_timestamps.tolist()[0].map((e=>round(e,2)))}else{e.tokens=r[0]}e.stride=e.stride.map((e=>e/d));if(o!==null){o(e)}}const[c,u]=this.tokenizer._decode_asr(a,{time_precision:l,return_timestamps:n,force_full_sequences:i});p.push({text:c,...u})}return u?p[0]:p}}class ImageToTextPipeline extends Pipeline{constructor(e){super(e)}async _call(e,t={}){const n=Array.isArray(e);const r=await prepareImages(e);const{pixel_values:o}=await this.processor(r);const i=[];for(const e of o){e.dims=[1,...e.dims];const n=await this.model.generate(e,t);const r=this.tokenizer.batch_decode(n,{skip_special_tokens:true}).map((e=>({generated_text:e.trim()})));i.push(r)}return n?i:i[0]}}class ImageClassificationPipeline extends Pipeline{constructor(e){super(e)}async _call(e,{topk:t=1}={}){const n=Array.isArray(e);const r=await prepareImages(e);const{pixel_values:o}=await this.processor(r);const i=await this.model({pixel_values:o});const s=this.model.config.id2label;const a=[];for(const e of i.logits){const n=getTopItems(softmax(e.data),t);const r=n.map((e=>({label:s[e[0]],score:e[1]})));if(t===1){a.push(...r)}else{a.push(r)}}return n||t===1?a:a[0]}}class ImageSegmentationPipeline extends Pipeline{constructor(e){super(e);this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(e,{threshold:t=.5,mask_threshold:n=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:o=null,target_sizes:i=null,subtask:s=null}={}){const a=Array.isArray(e);if(a&&e.length!==1){throw Error("Image segmentation pipeline currently only supports a batch size of 1.")}const c=await prepareImages(e);const u=c.map((e=>[e.height,e.width]));const{pixel_values:l,pixel_mask:f}=await this.processor(c);const d=await this.model({pixel_values:l,pixel_mask:f});let h=null;if(s!==null){h=this.subtasks_mapping[s]}else{for(let[e,t]of Object.entries(this.subtasks_mapping)){if(t in this.processor.feature_extractor){h=this.processor.feature_extractor[t].bind(this.processor.feature_extractor);s=e;break}}}const p=this.model.config.id2label;const m=[];if(s==="panoptic"||s==="instance"){const e=h(d,t,n,r,o,i??u)[0];const s=e.segmentation;for(const t of e.segments_info){const e=new Uint8ClampedArray(s.data.length);for(let n=0;n<s.data.length;++n){if(s.data[n]===t.id){e[n]=255}}const n=new RawImage(e,s.dims[1],s.dims[0],1);m.push({score:t.score,label:p[t.label_id],mask:n})}}else if(s==="semantic"){const{segmentation:e,labels:t}=h(d,i??u)[0];for(const n of t){const t=new Uint8ClampedArray(e.data.length);for(let r=0;r<e.data.length;++r){if(e.data[r]===n){t[r]=255}}const r=new RawImage(t,e.dims[1],e.dims[0],1);m.push({score:null,label:p[n],mask:r})}}else{throw Error(`Subtask ${s} not supported.`)}return m}}class ZeroShotImageClassificationPipeline extends Pipeline{constructor(e){super(e)}async _call(e,t,{hypothesis_template:n="This is a photo of {}"}={}){const r=Array.isArray(e);const o=await prepareImages(e);const i=t.map((e=>n.replace("{}",e)));const s=this.tokenizer(i,{padding:this.model.config.model_type==="siglip"?"max_length":true,truncation:true});const{pixel_values:a}=await this.processor(o);const c=await this.model({...s,pixel_values:a});const u=this.model.config.model_type==="siglip"?e=>e.sigmoid().data:e=>softmax(e.data);const l=[];for(const e of c.logits_per_image){const n=u(e);const r=[...n].map(((e,n)=>({score:e,label:t[n]})));r.sort(((e,t)=>t.score-e.score));l.push(r)}return r?l:l[0]}}class ObjectDetectionPipeline extends Pipeline{constructor(e){super(e)}async _call(e,{threshold:t=.9,percentage:n=false}={}){const r=Array.isArray(e);if(r&&e.length!==1){throw Error("Object detection pipeline currently only supports a batch size of 1.")}const o=await prepareImages(e);const i=n?null:o.map((e=>[e.height,e.width]));const{pixel_values:s,pixel_mask:a}=await this.processor(o);const c=await this.model({pixel_values:s,pixel_mask:a});const u=this.processor.feature_extractor.post_process_object_detection(c,t,i);const l=this.model.config.id2label;const f=u.map((e=>e.boxes.map(((t,r)=>({score:e.scores[r],label:l[e.classes[r]],box:get_bounding_box(t,!n)})))));return r?f:f[0]}}class ZeroShotObjectDetectionPipeline extends Pipeline{constructor(e){super(e)}async _call(e,t,{threshold:n=.1,topk:r=null,percentage:o=false}={}){const i=Array.isArray(e);const s=await prepareImages(e);const a=this.tokenizer(t,{padding:true,truncation:true});const c=await this.processor(s);const u=[];for(let e=0;e<s.length;++e){const i=s[e];const l=o?null:[[i.height,i.width]];const f=c.pixel_values[e].unsqueeze_(0);const d=await this.model({...a,pixel_values:f});const h=this.processor.feature_extractor.post_process_object_detection(d,n,l,true)[0];let p=h.boxes.map(((e,n)=>({score:h.scores[n],label:t[h.classes[n]],box:get_bounding_box(e,!o)}))).sort(((e,t)=>t.score-e.score));if(r!==null){p=p.slice(0,r)}u.push(p)}return i?u:u[0]}}class DocumentQuestionAnsweringPipeline extends Pipeline{constructor(e){super(e)}async _call(e,t,n={}){const r=(await prepareImages(e))[0];const{pixel_values:o}=await this.processor(r);const i=`<s_docvqa><s_question>${t}</s_question><s_answer>`;const s=this.tokenizer(i,{add_special_tokens:false,padding:true,truncation:true}).input_ids;const a=await this.model.generate(o,{...n,decoder_input_ids:s,max_length:this.model.config.decoder.max_position_embeddings});const c=this.tokenizer.batch_decode(a)[0];const u=c.match(/<s_answer>(.*?)<\/s_answer>/);let l=null;if(u&&u.length>=2){l=u[1].trim()}return[{answer:l}]}}class TextToAudioPipeline extends Pipeline{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e);this.vocoder=e.vocoder??null}async _call(e,{speaker_embeddings:t=null}={}){if(this.processor){return this._call_text_to_spectrogram(e,{speaker_embeddings:t})}else{return this._call_text_to_waveform(e)}}async _call_text_to_waveform(e){const t=this.tokenizer(e,{padding:true,truncation:true});const{waveform:n}=await this.model(t);const r=this.model.config.sampling_rate;return{audio:n.data,sampling_rate:r}}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){if(!this.vocoder){console.log("No vocoder specified, using default HifiGan vocoder.");this.vocoder=await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{quantized:false})}if(typeof t==="string"||t instanceof URL){t=new Float32Array(await(await fetch(t)).arrayBuffer())}if(t instanceof Float32Array){t=new Tensor("float32",t,[1,t.length])}else if(!(t instanceof Tensor)){throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.")}const{input_ids:n}=this.tokenizer(e,{padding:true,truncation:true});const{waveform:r}=await this.model.generate_speech(n,t,{vocoder:this.vocoder});const o=this.processor.feature_extractor.config.sampling_rate;return{audio:r.data,sampling_rate:o}}}class ImageToImagePipeline extends Pipeline{constructor(e){super(e)}async _call(e){const t=await prepareImages(e);const n=await this.processor(t);const r=await this.model(n);const o=[];for(const e of r.reconstruction){const t=e.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");o.push(RawImage.fromTensor(t))}return o.length>1?o:o[0]}}class DepthEstimationPipeline extends Pipeline{constructor(e){super(e)}async _call(e){const t=await prepareImages(e);const n=await this.processor(t);const{predicted_depth:r}=await this.model(n);const o=[];for(let e=0;e<t.length;++e){const n=interpolate(r[e],t[e].size.reverse(),"bilinear",false);const i=n.mul_(255/max(n.data)[0]).to("uint8");o.push({predicted_depth:r[e],depth:RawImage.fromTensor(i)})}return o.length>1?o:o[0]}}const SUPPORTED_TASKS=Object.freeze({"text-classification":{tokenizer:AutoTokenizer,pipeline:TextClassificationPipeline,model:AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:AutoTokenizer,pipeline:TokenClassificationPipeline,model:AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:AutoTokenizer,pipeline:QuestionAnsweringPipeline,model:AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:AutoTokenizer,pipeline:FillMaskPipeline,model:AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:AutoTokenizer,pipeline:SummarizationPipeline,model:AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:AutoTokenizer,pipeline:TranslationPipeline,model:AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:AutoTokenizer,pipeline:Text2TextGenerationPipeline,model:AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:AutoTokenizer,pipeline:TextGenerationPipeline,model:AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:AutoTokenizer,pipeline:ZeroShotClassificationPipeline,model:AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:AudioClassificationPipeline,model:AutoModelForAudioClassification,processor:AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:AutoTokenizer,pipeline:ZeroShotAudioClassificationPipeline,model:AutoModel,processor:AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:AutoTokenizer,pipeline:AutomaticSpeechRecognitionPipeline,model:[AutoModelForSpeechSeq2Seq,AutoModelForCTC],processor:AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:AutoTokenizer,pipeline:TextToAudioPipeline,model:[AutoModelForTextToWaveform,AutoModelForTextToSpectrogram],processor:[AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:AutoTokenizer,pipeline:ImageToTextPipeline,model:AutoModelForVision2Seq,processor:AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ImageClassificationPipeline,model:AutoModelForImageClassification,processor:AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ImageSegmentationPipeline,model:[AutoModelForImageSegmentation,AutoModelForSemanticSegmentation],processor:AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:AutoTokenizer,pipeline:ZeroShotImageClassificationPipeline,model:AutoModel,processor:AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ObjectDetectionPipeline,model:AutoModelForObjectDetection,processor:AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:AutoTokenizer,pipeline:ZeroShotObjectDetectionPipeline,model:AutoModelForZeroShotObjectDetection,processor:AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:AutoTokenizer,pipeline:DocumentQuestionAnsweringPipeline,model:AutoModelForDocumentQuestionAnswering,processor:AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ImageToImagePipeline,model:AutoModelForImageToImage,processor:AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:DepthEstimationPipeline,model:AutoModelForDepthEstimation,processor:AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:AutoTokenizer,pipeline:FeatureExtractionPipeline,model:AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:AutoProcessor,pipeline:ImageFeatureExtractionPipeline,model:[AutoModelForImageFeatureExtraction,AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}});const TASK_ALIASES=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function pipeline(e,t=null,{quantized:n=true,progress_callback:r=null,config:o=null,cache_dir:i=null,local_files_only:s=false,revision:a="main",model_file_name:c=null}={}){e=TASK_ALIASES[e]??e;const u=SUPPORTED_TASKS[e.split("_",1)[0]];if(!u){throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`)}if(!t){t=u.default.model;console.log(`No model specified. Using default model: "${t}".`)}const l={quantized:n,progress_callback:r,config:o,cache_dir:i,local_files_only:s,revision:a,model_file_name:c};const f=new Map([["tokenizer",u.tokenizer],["model",u.model],["processor",u.processor]]);const d=await loadItems(f,t,l);d.task=e;dispatchCallback(r,{status:"ready",task:e,model:t});const h=u.pipeline;return new h(d)}async function loadItems(e,t,n){const r=Object.create(null);const o=[];for(let[i,s]of e.entries()){if(!s)continue;let e;if(Array.isArray(s)){e=new Promise((async(e,r)=>{let o;for(let r of s){if(r===null){e(null);return}try{e(await r.from_pretrained(t,n));return}catch(e){o=e}}r(o)}))}else{e=s.from_pretrained(t,n)}r[i]=e;o.push(e)}await Promise.all(o);for(let[e,t]of Object.entries(r)){r[e]=await t}return r}env$1.useBrowserCache=false;env$1.allowLocalModels=false;async function loadSemanticModel(){try{const e=await pipeline("feature-extraction","Xenova/all-MiniLM-L6-v2",{quantized:true});return e}catch(e){console.error("Failed to load semantic evaluation model:",e);throw e}}function splitIntoWords(e){return[...new Set(e.toLowerCase().split(/[^\w]+/))]}function cosineSimilarity(e,t){if(e.length!==t.length)throw new Error("Vectors must have the same length");let n=0,r=0,o=0;for(let i=0;i<e.length;i++){n+=e[i]*t[i];r+=e[i]**2;o+=t[i]**2}if(r===0||o===0)return 0;return n/(Math.sqrt(r)*Math.sqrt(o))}async function evaluateKeywordsSemantically(e,t,n,r){if(n.length===0)return[];const o=splitIntoWords(t);const[i,s]=await Promise.all([Promise.all(o.map((async t=>({word:t,emb:await e(t,{pooling:"mean",normalize:true})})))),Promise.all(n.map((async t=>({keyword:t,emb:await e(t,{pooling:"mean",normalize:true})}))))]);const a=s.map((({keyword:e,emb:t})=>{let n=0;try{for(const{emb:e}of i){const r=cosineSimilarity(Array.from(t.data),Array.from(e.data));if(r>n)n=r}return{keyword:e,found:n>=r,evaluationApproachResult:{score:n,approachUsed:EvaluationApproach.SEMANTIC}}}catch(t){console.error(`Error evaluating "${e}":`,t);return{keyword:e,found:false,evaluationApproachResult:{score:0,approachUsed:EvaluationApproach.SEMANTIC}}}}));return a}class SemanticEvaluator{static extractor=null;async initialize(){if(SemanticEvaluator.extractor)return;try{SemanticEvaluator.extractor=await loadSemanticModel()}catch(e){console.error("Failed to load semantic evaluation model:",e);throw e}}async performEvaluation(e){try{await this.initialize();const t=e.expectedOutcome?e.expectedOutcome.split(/[\n,]+/).map((e=>e.trim())).filter((e=>e.length>0)):[];const n=await evaluateKeywordsSemantically(SemanticEvaluator.extractor,e.actualResponse,t,DEFAULT_SEMANTIC_PASS_SCORE);const r=n.length;const o=n.reduce(((e,t)=>e+t.evaluationApproachResult.score),0);const i=r>0?o/r:0;const s=n.every((e=>e.found));const a={approach:EvaluationApproach.SEMANTIC,threshold:DEFAULT_SEMANTIC_PASS_SCORE};return{testCaseId:e.testCaseId,passed:s,keywordMatches:n,evaluationParameters:a,evaluationApproachResult:{score:i,approachUsed:EvaluationApproach.SEMANTIC},timestamp:(new Date).toISOString()}}catch(t){console.error("Failed to perform semantic evaluation:",t);return{testCaseId:e.testCaseId,passed:false,keywordMatches:[],evaluationParameters:{approach:EvaluationApproach.SEMANTIC,threshold:DEFAULT_SEMANTIC_PASS_SCORE},evaluationApproachResult:{score:0,approachUsed:EvaluationApproach.SEMANTIC},timestamp:(new Date).toISOString()}}}}const semanticEvaluator=new SemanticEvaluator;async function performSemanticEvaluation(e){await semanticEvaluator.initialize();return semanticEvaluator.performEvaluation(e)}function evaluateKeyword$1(e,t,n){let r=0;try{const n=e.trim();if(n.length>0&&t.length>0){const e=n.toLowerCase().split(/\s+/);const o=t.toLowerCase().split(/\s+/);if(e.length===1&&o.includes(e[0])){r=1}else{const t=T(o,e);const n=typeof t==="number"?t:t?.length??0;const i=e.length>0?n/e.length:0;const s=o.length>0?n/o.length:0;const a=s+i;const c=a>0?2*s*i/a:0;r=c}}else{console.warn(`ROUGE-L not computed for keyword "${e}": Keyword or candidate missing.`)}}catch(t){console.error(`ROUGE-L computation failed for keyword "${e}":`,t)}const o=r>=n;const i={score:r,approachUsed:EvaluationApproach.ROUGE_L};return{keyword:e,found:o,evaluationApproachResult:i}}function performRougeLEvaluation(e){const{testCaseId:t,actualResponse:n,expectedOutcome:r,evaluationParameters:o}=e;let i=r?r.split(/[\n,.]+/).map((e=>e.trim())).filter((e=>e.length>0)):[];if(i.length===0&&r){i=[r]}const s=(n||"").trim();const a=o.threshold??DEFAULT_ROUGE_PASS_SCORE;let c=0;const u=i.length;const l=i.map((e=>{const t=evaluateKeyword$1(e,s,a);if(t.found)c++;return t}));const f=c===u;const d={score:u>0?c/u:1,approachUsed:EvaluationApproach.ROUGE_L};return{testCaseId:t,passed:f,keywordMatches:l,timestamp:(new Date).toISOString(),evaluationParameters:{...o,threshold:a},evaluationApproachResult:d}}var bleu={};var hasRequiredBleu;function requireBleu(){if(hasRequiredBleu)return bleu;hasRequiredBleu=1;Object.defineProperty(bleu,"__esModule",{value:true});bleu.bleu=void 0;function e(e,t,n){const r=e.split(" ");const o=t.split(" ");const i=Array(n).fill(0);for(let e=1;e<=n;e++){const t={};const n={};for(let n=0;n<r.length-e+1;n++){const o=r.slice(n,n+e).join(" ");t[o]=(t[o]||0)+1}for(let t=0;t<o.length-e+1;t++){const r=o.slice(t,t+e).join(" ");n[r]=(n[r]||0)+1}let s=0;for(const e in n){if(e in t){s+=Math.min(n[e],t[e])}}let a=o.length-e+1;i[e-1]=a>0?s/a:0}const s=r.length;const a=o.length;const c=a>s?1:Math.exp(1-s/a);const u=Math.pow(i.reduce(((e,t)=>e*t),1),1/n);const l=c*u;return l}bleu.bleu=e;return bleu}var bleuExports=requireBleu();function normalizeText(e){return e.trim().toLowerCase().replace(/[.,!?;:()]/g," ").replace(/\s+/g," ")}function evaluateKeyword(e,t,n){let r=0;try{const n=normalizeText(e);const o=normalizeText(t);if(n.length>0&&o.length>0){const e=n.split(/\s+/).length;const t=Math.min(4,Math.max(1,e));const i=bleuExports.bleu(n,o,t);r=isNaN(i)?0:i}else{console.warn(`BLEU not computed for keyword "${e}": Keyword or Candidate is missing.`)}}catch(t){console.error(`BLEU computation failed for keyword "${e}":`,t)}const o=r>=n;const i={score:r,approachUsed:EvaluationApproach.BLEU};return{keyword:e,found:o,evaluationApproachResult:i}}function performBleuEvaluation(e){const{testCaseId:t,actualResponse:n,expectedOutcome:r,evaluationParameters:o}=e;let i=r?r.split(/[\n,.]+/).map((e=>e.trim())).filter((e=>e.length>0)):[];if(i.length===0&&r){i=[r]}const s=(n||"").trim();const a=o.threshold??DEFAULT_BLEU_PASS_SCORE;let c=0;const u=i.length;const l=i.map((e=>{const t=evaluateKeyword(e,s,a);if(t.found){c++}return t}));const f=c===u;const d={score:u>0?c/u:1,approachUsed:EvaluationApproach.BLEU};return{testCaseId:t,passed:f,keywordMatches:l,timestamp:(new Date).toISOString(),evaluationParameters:{...o,threshold:a},evaluationApproachResult:d}}class LLMEvaluationEngine{async evaluateResponse(e,t){const n=await Promise.allSettled(e.fields.map((async t=>{const n={testCaseId:e.testCaseId,question:e.question,actualResponse:e.actualResponse,expectedOutcome:t.expectedValue,evaluationParameters:t.evaluationParameters};const r=await this.evaluateField(n);const o={index:t.index,label:t.label,type:t.type,expectedValue:t.expectedValue,passed:r.passed,keywordMatches:r.keywordMatches,evaluationParameters:r.evaluationParameters,evaluationApproachResult:r.evaluationApproachResult};return o})));const r=n.map(((t,n)=>{const r=e.fields[n];if(t.status==="fulfilled"){return t.value}return{index:r.index,label:r.label,type:r.type,expectedValue:r.expectedValue,passed:false,keywordMatches:[],evaluationParameters:r.evaluationParameters,evaluationApproachResult:{score:0,approachUsed:r.evaluationParameters.approach},error:this.getSafeErrorMessage(t.reason)}}));const o=r.flatMap((e=>e.keywordMatches));const i=r.every((e=>e.passed&&!e.error));t({testCaseId:e.testCaseId,passed:i,keywordMatches:o,fieldResults:r,timestamp:(new Date).toISOString()})}async evaluateField(e){const t=e.evaluationParameters.approach;switch(t){case EvaluationApproach.BLEU:return performBleuEvaluation(e);case EvaluationApproach.EXACT:return performEvaluation(e);case EvaluationApproach.ROUGE_1:return performRouge1Evaluation(e);case EvaluationApproach.ROUGE_L:return performRougeLEvaluation(e);case EvaluationApproach.SEMANTIC:return performSemanticEvaluation(e);default:console.warn(`Unknown matching approach: ${e.evaluationParameters.approach}, falling back to exact matching`);return performEvaluation(e)}}getSafeErrorMessage(e){return e instanceof Error?e.message:"Field evaluation failed."}}class EvaluationService{engine;constructor(){this.engine=new LLMEvaluationEngine}async evaluateTestCase(e,t){if(!e.output){console.warn("⚠️ No output to evaluate for test case:",e.id);return}const n=(e.expectedOutcome||[]).map(((e,t)=>({index:t,label:e.label,type:e.type,expectedValue:getFieldExpectedValue(e),evaluationParameters:normalizeEvaluationParametersForField(e.type,e.evaluationParameters)})));const r={testCaseId:e.id,question:e.question,actualResponse:e.output,fields:n};await this.engine.evaluateResponse(r,(e=>{console.log("📊 Evaluation result received:",e);t(e)}))}}function getFieldExpectedValue(e){if(e.type==="chips-input"){return e.value.join(", ")}return e.value}const Button=(e,t)=>{const{variant:n="primary",size:r="md",disabled:o=false,loading:i=false,onClick:s,type:a="button",class:c="",icon:u,"aria-label":l}=e;const f="ui-button";const d=`ui-button--${n}`;const p=`ui-button--${r}`;const m=i?"ui-button--loading":"";const w=o?"ui-button--disabled":"";const g=[f,d,p,m,w,c].filter(Boolean).join(" ");return h("button",{type:a,class:g,disabled:o||i,onClick:s,"aria-busy":i,"aria-label":l},u&&h("span",{class:"icon"},u),t)};const LLMTestRunnerHeader=({isExportingTestSuite:e,isExportingTestResults:t,isRunningAll:n,useSave:r=false,isSaving:o=false,onImport:i,onExportSuite:s,onExportResults:a,onRunAll:c,onSave:u})=>{let l;const f=()=>{l?.click()};const d=e=>{const t=e.target;const n=t.files?.[0];t.value="";if(n){i(n)}};return h("header",{class:"test-runner-header"},h("div",{class:"test-runner-header__left"},h("input",{class:"test-runner-header--hidden",type:"file",ref:e=>l=e,onChange:d,accept:".json,application/json"}),h(Button,{variant:"secondary",size:"md",onClick:f,icon:"↑"},"Import Test Suite"),h(Button,{variant:"secondary",size:"md",onClick:s,disabled:e,loading:e,icon:e?"⏳":"↓"},e?"Exporting...":"Export Test Suite")),h("div",{class:"test-runner-header__right"},h(Button,{variant:"secondary",size:"md",icon:"⚙️"},"Prompt Editor"),h(Button,{variant:"secondary",size:"md",onClick:a,disabled:t,loading:t,icon:t?"⏳":"↓"},t?"Exporting...":"Export Test Results"),r&&h(Button,{variant:"secondary",size:"md",onClick:u,disabled:o,loading:o,icon:o?"⏳":"💾"},o?"Saving...":"Save"),h(Button,{"aria-label":"Run All",variant:"primary",size:"md",onClick:c,disabled:n,loading:n},n?"Running...":"Run All")))};const ResponseOutput=({output:e,isRunning:t})=>h("div",{class:"response-output"},e?h("div",{class:"response-output__content"},e):h("div",{class:"response-output__placeholder"},t?"Running...":""));const EvaluationSummary=({result:e,isRunning:t})=>{const n=e?.fieldResults||[];const r=n.length>0;return h("div",{class:"evaluation-summary"},e?h("div",{class:"evaluation-summary__result"},r?h("div",{class:"evaluation-summary__field-results"},n.map((e=>h("div",{class:"evaluation-summary__field-result"},h("div",{class:"evaluation-summary__field-header"},h("span",{class:"evaluation-summary__field-label"},e.label),h("span",{class:"evaluation-summary__field-approach"},"Strategy: ",e.evaluationParameters.approach)),h("div",{class:"evaluation-summary__field-details"},h("span",{class:`evaluation-summary__field-status evaluation-summary__field-status--${e.passed?"passed":"failed"}`},e.passed?"PASSED":"FAILED"),e.error&&h("span",{class:"evaluation-summary__error-message"},e.error),h("span",null,"Score: ",e.evaluationApproachResult.score.toFixed(2)),h("span",null,"Matches:"," ",e.keywordMatches.filter((e=>e.found)).length,"/",e.keywordMatches.length)))))):null):h("div",{class:"evaluation-summary__placeholder"},t?"Evaluating...":""))};const IconButton=(e,t)=>{const{variant:n="primary",disabled:r=false,loading:o=false,onClick:i,type:s="button",title:a,class:c=""}=e;const u="ui-icon-button";const l=`ui-icon-button--${n}`;const f=o?"ui-icon-button--loading":"";const d=r?"ui-icon-button--disabled":"";const p=[u,l,f,d,c].filter(Boolean).join(" ");return h("button",{type:s,class:p,disabled:r||o,onClick:i,title:a,"aria-busy":o,"aria-label":a},t)};const RowActions=({isRunning:e,canRun:t,onRun:n,onDelete:r})=>h("div",{class:"row-actions"},h(IconButton,{variant:"outline",onClick:n,disabled:e||!t,title:!t?"Enter a question first":"Run this test"},e?"⏳":"▶️"),h(IconButton,{variant:"outline",onClick:r,title:"Delete this test"},"🗑️"));var FormFieldType;(function(e){e["TEXT_AREA"]="textarea";e["CHIPS"]="chips";e["SELECT"]="select"})(FormFieldType||(FormFieldType={}));const ExpectedOutcomeRenderer=({testCaseId:e,fields:t,onExpectedOutcomeChange:n})=>{const r=e=>n({detail:e});const o=(e,t)=>({name:`expectedOutcomeEvaluation-${e}`,fieldType:FormFieldType.SELECT,label:"Evaluation Approach",placeholder:"Select evaluation approach…",required:true,optionList:t,defaultValue:EvaluationApproach.EXACT});const i=(t,n)=>{const i=getAllowedApproachesForFieldType(t.type);return h("app-select",{config:o(n,i),value:t.evaluationParameters?.approach,onValueChange:t=>r({testCaseId:e,index:n,operation:"set-evaluation-approach",value:t.detail.value})})};return h("div",{class:"expected-outcome-renderer"},(t||[]).map(((t,n)=>{if(t.type==="textarea"){const o={name:`expectedOutcome-${n}`,fieldType:FormFieldType.TEXT_AREA,label:t.label,placeholder:t.placeholder,required:true,rows:t.rows||2};return h("div",{class:"expected-outcome-renderer__group"},h("app-textarea",{config:o,value:t.value,onValueChange:t=>r({testCaseId:e,index:n,operation:"set-value",value:t.detail.value})}),i(t,n))}if(t.type==="chips-input"){const o={name:`expectedOutcome-${n}`,fieldType:FormFieldType.CHIPS,label:t.label,placeholder:t.placeholder,required:true};return h("div",{class:"expected-outcome-renderer__group"},h("app-chips",{config:o,value:t.value,onAddChip:t=>r({testCaseId:e,index:n,operation:"add-chip",value:t.detail.value}),onRemoveChip:t=>r({testCaseId:e,index:n,operation:"remove-chip",value:t.detail.value})}),i(t,n))}if(t.type==="select"){const o={name:`expectedOutcome-${n}`,fieldType:FormFieldType.SELECT,label:t.label,placeholder:t.placeholder,required:true,optionList:t.options};return h("div",{class:"expected-outcome-renderer__group"},h("app-select",{config:o,value:t.value,onValueChange:t=>r({testCaseId:e,index:n,operation:"set-value",value:t.detail.value})}),i(t,n))}return h("div",{class:"expected-outcome-renderer__group"},h("div",{class:"expected-outcome-renderer__text"},h("label",null,t.label),h("input",{type:"text",value:t.value,placeholder:t.placeholder,onInput:t=>r({testCaseId:e,index:n,operation:"set-value",value:t.target.value})})),i(t,n))})))};const LLMTestCaseRow=({testCase:e,onRun:t,onDelete:n,handleTestCaseChange:r,onExpectedOutcomeChange:o})=>{const i={name:"question",fieldType:FormFieldType.TEXT_AREA,type:"text",label:"Question",placeholder:"Enter your question here...",required:true,rows:3};return h("div",{class:"test-case-row",key:e.id},h("div",{class:"test-case-row__input-column"},h("app-textarea",{config:i,value:e.question,onValueChange:t=>r({detail:{testCaseId:e.id,key:"question",value:t.detail.value}})}),h(ExpectedOutcomeRenderer,{testCaseId:e.id,fields:e.expectedOutcome||[],onExpectedOutcomeChange:o})),h(ResponseOutput,{output:e.output,isRunning:e.isRunning}),h(EvaluationSummary,{result:e.evaluationResult,isRunning:e.isRunning}),h(RowActions,{isRunning:e.isRunning,canRun:!!e.question.trim(),onRun:()=>t(e),onDelete:()=>n(e.id)}))};const LLMTestCases=({testCases:e,onRun:t,onDelete:n,onAddTestCase:r,handleTestCaseChange:o,onExpectedOutcomeChange:i})=>h("div",{class:"test-cases"},h("div",{class:"test-cases__column-headers"},h("div",{class:"test-cases__column-header"},"Input"),h("div",{class:"test-cases__column-header"},"Output"),h("div",{class:"test-cases__column-header"},"Evaluation"),h("div",{class:"test-cases__column-header"},"Actions")),e.map((e=>h(LLMTestCaseRow,{testCase:e,onRun:t,onDelete:n,handleTestCaseChange:o,onExpectedOutcomeChange:i}))),h("div",{class:"test-cases__add-section"},h(Button,{variant:"outline",size:"md",onClick:r},"+ Add Question")));const tokensCss=()=>`:host{--spacing:0.25rem;--spacing-1:calc(var(--spacing) * 1);--spacing-2:calc(var(--spacing) * 2);--spacing-3:calc(var(--spacing) * 3);--spacing-4:calc(var(--spacing) * 4);--spacing-5:calc(var(--spacing) * 5);--spacing-6:calc(var(--spacing) * 6);--spacing-8:calc(var(--spacing) * 8);--spacing-10:calc(var(--spacing) * 10);--spacing-12:calc(var(--spacing) * 12);--spacing-16:calc(var(--spacing) * 16);--spacing-20:calc(var(--spacing) * 20);--spacing-24:calc(var(--spacing) * 24);--radius-none:0;--radius-sm:0.125rem;--radius-md:0.375rem;--radius-lg:0.5rem;--radius-xl:0.75rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-full:9999px;--radius:var(--radius-lg);--font-size-xs:0.75rem;--font-size-sm:0.875rem;--font-size-base:1rem;--font-size-lg:1.125rem;--font-size-xl:1.25rem;--font-size-2xl:1.5rem;--font-size-3xl:1.875rem;--font-size-4xl:2.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--line-height-none:1;--line-height-tight:1.25;--line-height-snug:1.375;--line-height-normal:1.5;--line-height-relaxed:1.625;--line-height-loose:2;--letter-spacing-tight:-0.025em;--letter-spacing-normal:0;--letter-spacing-wide:0.05em;--shadow-sm:0 1px 2px 0 rgba(0, 0, 0, 0.05);--shadow-md:0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);--shadow-lg:0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);--shadow-xl:0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);--shadow-2xl:0 25px 50px -12px rgba(0, 0, 0, 0.25);--border-width:1px;--z-base:0;--z-dropdown:1000;--z-sticky:1100;--z-modal:1200;--z-popover:1300;--z-tooltip:1400;--opacity-disabled:0.5;--opacity-hover:0.8;--opacity-muted:0.6;--max-w-sm:24rem;--max-w-md:28rem;--max-w-lg:32rem;--max-w-xl:42rem;--max-w-2xl:48rem;--max-w-full:100%;--breakpoint-sm:640px;--breakpoint-md:768px;--breakpoint-lg:1024px;--breakpoint-xl:1280px;--breakpoint-2xl:1536px;--background:#ffffff;--foreground:#0a0a0a;--card:#ffffff;--card-foreground:#0a0a0a;--popover:#ffffff;--popover-foreground:#0a0a0a;--primary:#0a0a0a;--primary-foreground:#fafafa;--secondary:#f4f4f5;--secondary-foreground:#0a0a0a;--muted:#f4f4f5;--muted-foreground:#71717a;--accent:#f4f4f5;--accent-foreground:#0a0a0a;--destructive:#ef4444;--destructive-foreground:#fafafa;--border:#e4e4e7;--input:#e4e4e7;--ring:#3b82f6;--success:#10b981;--success-foreground:#fafafa;--warning:#f59e0b;--warning-foreground:#fafafa;--info:#3b82f6;--info-foreground:#fafafa}:host([data-theme='dark']){--background:#0a0a0a;--foreground:#fafafa;--card:#171717;--card-foreground:#fafafa;--popover:#171717;--popover-foreground:#fafafa;--primary:#fafafa;--primary-foreground:#0a0a0a;--secondary:#27272a;--secondary-foreground:#fafafa;--muted:#27272a;--muted-foreground:#a1a1aa;--accent:#27272a;--accent-foreground:#fafafa;--destructive:#dc2626;--destructive-foreground:#fafafa;--border:#27272a;--input:#27272a;--ring:#3b82f6;--success:#059669;--success-foreground:#fafafa;--warning:#d97706;--warning-foreground:#fafafa;--info:#2563eb;--info-foreground:#fafafa}`;const llmTestRunnerCss=()=>`:host{display:block;font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;background-color:var(--muted);min-height:100vh}.test-runner-container *,.test-runner-container *::before,.test-runner-container *::after{box-sizing:border-box;margin:0;padding:0}.test-runner-container{max-width:1400px;margin:0 auto;padding:var(--spacing-5);background:var(--background);border-radius:var(--radius);box-shadow:var(--shadow-lg)}.test-runner-container__content{padding:0}`;const llmTestRunnerHeaderCss=()=>`.test-runner-header{display:flex;justify-content:space-between;align-items:center;padding:var(--spacing-5) var(--spacing-6);background:var(--background);color:var(--foreground);box-shadow:var(--shadow-md);border-bottom:var(--border-width) solid var(--border)}.test-runner-header__left,.test-runner-header__right{display:flex;gap:var(--spacing-3);align-items:center}.test-runner-header__center{flex:1;display:flex;justify-content:center;align-items:center}.test-runner-header__api-status{display:flex;align-items:center;gap:var(--spacing-2)}.test-runner-header__api-status-text{color:var(--success);font-weight:var(--font-weight-medium);font-size:var(--font-size-sm);line-height:var(--line-height-normal)}.test-runner-header--hidden{display:none}@media (max-width: 768px) {.test-runner-header{flex-direction:column;gap:var(--spacing-4);padding:var(--spacing-4)}.test-runner-header__left,.test-runner-header__right{flex-wrap:wrap;justify-content:center}}`;const llmTestCasesCss=()=>`.test-cases{background:var(--background)}.test-cases__column-headers{display:grid;grid-template-columns:1fr 1.5fr 0.5fr 120px;gap:var(--border-width);background:var(--border);border-bottom:2px solid var(--border)}.test-cases__column-header{background:var(--muted);padding:var(--spacing-4) var(--spacing-5);font-weight:var(--font-weight-semibold);color:var(--foreground);font-size:var(--font-size-sm);text-transform:uppercase;letter-spacing:var(--letter-spacing-wide)}.test-cases__add-section{padding:var(--spacing-6);text-align:center;background:var(--muted);border-top:var(--border-width) solid var(--border)}@media (max-width: 1200px){.test-cases__column-headers{display:none}}`;const llmTestCaseRowCss=()=>`.test-case-row{display:grid;grid-template-columns:1fr 1.5fr 0.5fr 120px;gap:var(--border-width);border-bottom:var(--border-width) solid var(--border);min-height:200px}.test-case-row:hover{background:var(--muted)}.test-case-row__input-column{padding:var(--spacing-5);background:var(--background);border-right:var(--border-width) solid var(--border)}.expected-outcome-renderer{display:flex;flex-direction:column;gap:var(--spacing-4);margin-top:var(--spacing-4)}.expected-outcome-renderer__group{display:flex;flex-direction:column;gap:var(--spacing-2);padding:var(--spacing-3);border:var(--border-width) solid var(--border);border-radius:var(--radius-md);background:var(--background)}@media (max-width: 1200px){.test-case-row{grid-template-columns:1fr;gap:0}.test-case-row__input-column{border-right:none;border-bottom:var(--border-width) solid var(--border)}}@media (max-width: 768px){.test-case-row__input-column{padding:var(--spacing-4)}.test-case-row{min-height:auto}}`;const rowActionsCss=()=>`.row-actions{height:100%;padding:var(--spacing-5);background:var(--background);display:flex;flex-direction:column;gap:var(--spacing-3);align-items:center;justify-content:flex-start;align-self:flex-start}@media (max-width: 1200px){.row-actions{border-right:none;border-bottom:var(--border-width) solid var(--border);flex-direction:row;justify-content:center}}@media (max-width: 768px){.row-actions{padding:var(--spacing-4)}}`;const evaluationSummaryCss=()=>`.evaluation-summary{padding:var(--spacing-5);background:var(--background);border-right:var(--border-width) solid var(--border);display:flex;flex-direction:column}.evaluation-summary__field-results{display:flex;flex-direction:column;gap:var(--spacing-2);margin-top:var(--spacing-2)}.evaluation-summary__field-result{border:var(--border-width) solid var(--border);border-radius:var(--radius-md);padding:var(--spacing-2);display:flex;flex-direction:column;gap:var(--spacing-1)}.evaluation-summary__field-header{display:flex;flex-direction:column;gap:var(--spacing-1)}.evaluation-summary__field-label{font-weight:var(--font-weight-semibold);font-size:var(--font-size-xs)}.evaluation-summary__field-approach{color:var(--muted-foreground);font-size:11px}.evaluation-summary__field-details{display:flex;flex-direction:column;gap:var(--spacing-1);font-size:var(--font-size-xs)}.evaluation-summary__field-status{width:fit-content;padding:2px var(--spacing-2);border-radius:var(--radius-sm);font-size:11px;font-weight:var(--font-weight-semibold);border:var(--border-width) solid transparent}.evaluation-summary__field-status--passed{background:var(--success);color:var(--success-foreground);border-color:var(--success)}.evaluation-summary__field-status--failed{background:var(--destructive);color:var(--destructive-foreground);border-color:var(--destructive)}.evaluation-summary__error-message{color:var(--destructive);font-size:var(--font-size-xs)}.evaluation-summary__placeholder{display:flex;align-items:center;justify-content:center;color:var(--muted-foreground);font-style:italic;flex:1;background:var(--muted);border:2px dashed var(--border);border-radius:var(--radius)}.evaluation-summary__result{display:flex;flex-direction:column;gap:var(--spacing-2)}@media (max-width: 1200px){.evaluation-summary{border-right:none;border-bottom:var(--border-width) solid var(--border)}}@media (max-width: 768px){.evaluation-summary{padding:var(--spacing-4)}}`;const responseOutputCss=()=>`.response-output{padding:var(--spacing-5);background:var(--background);border-right:var(--border-width) solid var(--border);display:flex;flex-direction:column}.response-output__content{background:var(--muted);border:var(--border-width) solid var(--border);border-radius:var(--radius);padding:var(--spacing-4);font-size:var(--font-size-sm);line-height:var(--line-height-relaxed);color:var(--foreground);white-space:pre-wrap;word-wrap:break-word;flex:1;overflow-y:auto;max-height:250px;overflow-x:scroll}.response-output__placeholder{display:flex;align-items:center;justify-content:center;color:var(--muted-foreground);font-style:italic;flex:1;background:var(--muted);border:2px dashed var(--border);border-radius:var(--radius)}@media (max-width: 1200px){.response-output{border-right:none;border-bottom:var(--border-width) solid var(--border)}}@media (max-width: 768px){.response-output{padding:var(--spacing-4)}}`;const errorMessageCss=()=>`.error-message{background:var(--destructive);color:var(--destructive-foreground);border:var(--border-width) solid var(--destructive);padding:var(--spacing-3) var(--spacing-10) var(--spacing-3) var(--spacing-4);border-radius:var(--radius-md);margin:var(--spacing-4) 0;position:relative;font-size:var(--font-size-sm);display:flex;align-items:center;gap:var(--spacing-4)}.error-message__close{background:none;border:none;color:var(--destructive-foreground);font-size:var(--font-size-xl);font-weight:var(--font-weight-bold);cursor:pointer;position:absolute;right:var(--spacing-3);top:50%;transform:translateY(-50%);line-height:var(--line-height-none);padding:0;opacity:var(--opacity-hover)}.error-message__close:hover{opacity:1}`;const buttonCss=()=>`.ui-button{display:inline-flex;align-items:center;justify-content:center;gap:var(--spacing-2);border-radius:var(--radius);font-size:var(--font-size-sm);font-weight:var(--font-weight-medium);cursor:pointer;transition:all 0.2s ease;border:var(--border-width) solid transparent;outline:none;position:relative;white-space:nowrap}.ui-button .icon{display:inline-flex;align-items:center;justify-content:center;font-size:var(--font-size-base);line-height:var(--line-height-none)}.ui-button:focus-visible{outline:2px solid var(--ring);outline-offset:2px}.ui-button--disabled,.ui-button:disabled{opacity:var(--opacity-disabled);cursor:not-allowed;pointer-events:none}.ui-button--loading{opacity:var(--opacity-muted);cursor:wait}.ui-button--sm{padding:calc(var(--spacing) * 1.5) var(--spacing-3);font-size:var(--font-size-xs)}.ui-button--sm .icon{font-size:var(--font-size-sm)}.ui-button--md{padding:var(--spacing-2) var(--spacing-4);font-size:var(--font-size-sm)}.ui-button--md .icon{font-size:var(--font-size-base)}.ui-button--lg{padding:calc(var(--spacing) * 2.5) var(--spacing-5);font-size:var(--font-size-base)}.ui-button--lg .icon{font-size:var(--font-size-lg)}.ui-button--primary{background:var(--primary);color:var(--primary-foreground)}.ui-button--primary:hover:not(:disabled):not(.ui-button--loading){opacity:0.9;transform:translateY(-1px);box-shadow:var(--shadow-sm)}.ui-button--secondary{background:var(--secondary);color:var(--secondary-foreground)}.ui-button--secondary:hover:not(:disabled):not(.ui-button--loading){opacity:var(--opacity-hover);transform:translateY(-1px)}.ui-button--outline{background:transparent;border-color:var(--border);color:var(--foreground)}.ui-button--outline:hover:not(:disabled):not(.ui-button--loading){background:var(--accent);transform:translateY(-1px)}.ui-button--destructive{background:var(--destructive);color:var(--destructive-foreground)}.ui-button--destructive:hover:not(:disabled):not(.ui-button--loading){opacity:0.9;transform:translateY(-1px)}`;const iconButtonCss=()=>`.ui-icon-button{display:inline-flex;align-items:center;justify-content:center;padding:var(--spacing-2);min-width:var(--spacing-10);height:var(--spacing-10);border-radius:var(--radius);font-size:var(--font-size-base);cursor:pointer;transition:all 0.2s ease;border:var(--border-width) solid transparent;outline:none;position:relative}.ui-icon-button:focus-visible{outline:2px solid var(--ring);outline-offset:2px}.ui-icon-button--disabled,.ui-icon-button:disabled{opacity:var(--opacity-disabled);cursor:not-allowed;pointer-events:none}.ui-icon-button--loading{opacity:var(--opacity-muted);cursor:wait}.ui-icon-button--primary{background:var(--primary);color:var(--primary-foreground)}.ui-icon-button--primary:hover:not(:disabled):not(.ui-icon-button--loading){opacity:0.9;transform:translateY(-1px);box-shadow:var(--shadow-sm)}.ui-icon-button--secondary{background:var(--secondary);color:var(--secondary-foreground)}.ui-icon-button--secondary:hover:not(:disabled):not(.ui-icon-button--loading){opacity:var(--opacity-hover);transform:translateY(-1px)}.ui-icon-button--outline{background:transparent;border-color:var(--border);color:var(--foreground)}.ui-icon-button--outline:hover:not(:disabled):not(.ui-icon-button--loading){background:var(--accent);transform:translateY(-1px)}.ui-icon-button--destructive{background:var(--destructive);color:var(--destructive-foreground)}.ui-icon-button--destructive:hover:not(:disabled):not(.ui-icon-button--loading){opacity:0.9;transform:translateY(-1px)}`;const LLMTestRunner=proxyCustomElement(class e extends H{constructor(e){super();if(e!==false){this.__registerHost()}this.__attachShadow();this.llmRequest=createEvent(this,"llmRequest");this.save=createEvent(this,"save")}llmRequest;save;delayMs=500;useSave=false;initialTestCases;defaultExpectedOutcomeSchema;testCases=[{id:"1",question:"",expectedOutcome:[{type:"textarea",label:"Expected Outcome",value:""}],isRunning:false}];isRunningAll=false;error="";isExportingTestSuite=false;isExportingTestResults=false;isSaving=false;evaluationService;getResolvedExpectedOutcomeSchema(){if(this.defaultExpectedOutcomeSchema===undefined){return DEFAULT_EXPECTED_OUTCOME_SCHEMA}validateExpectedOutcomeSchema(this.defaultExpectedOutcomeSchema);return this.defaultExpectedOutcomeSchema}componentWillLoad(){this.evaluationService=new EvaluationService;try{if(this.initialTestCases!==undefined){validateTestCaseInputArray(this.initialTestCases);this.testCases=this.initialTestCases.map(((e,t)=>{try{return createTestCaseFromInput(e)}catch(e){const n=e instanceof Error?e.message:"Unknown error";throw new Error(`Invalid initial test case at index ${t}: ${n}`)}}))}else{const e=this.getResolvedExpectedOutcomeSchema();this.testCases=[createTestCase(e)]}}catch(e){this.error=e instanceof Error?e.message:"Invalid defaultExpectedOutcomeSchema provided.";this.testCases=[]}}componentDidLoad(){}disconnectedCallback(){}async resetSavingState(){this.isSaving=false}handleTestCaseChange=e=>{const{testCaseId:t,key:n,value:r}=e.detail;this.testCases=this.testCases.map((e=>e.id===t?{...e,[n]:r}:e))};addNewTestCase(){try{const e=this.getResolvedExpectedOutcomeSchema();const t=createTestCase(e);this.testCases=[...this.testCases,t]}catch(e){this.error=e instanceof Error?e.message:"Invalid defaultExpectedOutcomeSchema provided."}}updateTestCase(e,t){this.testCases=this.testCases.map((n=>n.id===e?{...n,...t}:n))}async runSingleTest(e){const t=Date.now();this.updateTestCase(e.id,{isRunning:true});return new Promise(((n,r)=>{this.llmRequest.emit({prompt:e.question,resolve:async r=>{const o=Date.now();const i=o-t;this.updateTestCase(e.id,{isRunning:false,output:r,error:null,responseTime:i});await this.evaluateResponse({...e,output:r,responseTime:i});n()},reject:t=>{this.updateTestCase(e.id,{isRunning:false,output:null,error:t instanceof Error?t.message:"Unknown error"});r(t)}})}))}deleteTestCase(e){this.testCases=this.testCases.filter((t=>t.id!==e))}handleExpectedOutcomeChange=e=>{const{testCaseId:t,...n}=e.detail;this.testCases=this.testCases.map((e=>{if(e.id!==t){return e}return applyExpectedOutcomeChange(e,n)}))};async evaluateResponse(e){await this.evaluationService.evaluateTestCase(e,(t=>{this.updateTestCase(e.id,{evaluationResult:t})}))}async runAllTests(){this.isRunningAll=true;const e=[];for(const t of this.testCases){if(!t.isRunning&&t.question.trim()){e.push((()=>this.runSingleTest(t).catch((e=>{console.error(`⚠️ Test case ${t.id} failed`,e)}))))}}try{const t=new RateLimitedFetcher(this.delayMs);await t.runAll(e)}catch(e){console.error("⚠️ Error running all tests:",e)}this.isRunningAll=false}async handleImport(e){const t=e.type==="application/json";const n=e.name.toLowerCase().endsWith(".json");if(!t&&!n){this.error="Invalid file type. Please select a JSON file.";return}this.error="";try{const t=await readFileAsync(e);const n=importTestSuite(t);if(!n.success){this.error=n.error||"Unknown error occurred during import.";return}this.testCases=n.testCases||[]}catch(e){this.error=e instanceof Error?e.message:"Error processing file. Please ensure it is a valid JSON array.";console.error("File Processing Error:",e)}}async handleExportTestSuite(){this.isExportingTestSuite=true;try{const e=formatTestSuiteAsJson(this.testCases);await new Promise((e=>setTimeout(e,500)));downloadFile(e,"test-suite.json","application/json")}finally{this.isExportingTestSuite=false}}async handleExportTestResults(){this.isExportingTestResults=true;try{const e=exportTestResultsToCsv(this.testCases);await new Promise((e=>setTimeout(e,500)));downloadFile(e,"test-results.csv","text/csv")}finally{this.isExportingTestResults=false}}async handleSave(){this.isSaving=true;try{const e={timestamp:(new Date).toISOString(),testCases:this.testCases};this.save.emit(e);setTimeout((()=>{if(this.isSaving){console.warn("Save operation timed out, resetting state");this.isSaving=false}}),1e4)}finally{}}render(){return h("div",{key:"e3d007b453f770fcb59c29f8ee83bd8a35e82a34",class:"test-runner-container"},h(LLMTestRunnerHeader,{key:"b7c44bf4807fe8d9e5de514818420d67d2e0dbfb",isExportingTestSuite:this.isExportingTestSuite,isExportingTestResults:this.isExportingTestResults,isRunningAll:this.isRunningAll,useSave:this.useSave,isSaving:this.isSaving,onImport:e=>this.handleImport(e),onExportSuite:()=>this.handleExportTestSuite(),onExportResults:()=>this.handleExportTestResults(),onRunAll:()=>this.runAllTests(),onSave:()=>this.handleSave()}),h(ErrorMessage,{key:"697237ec0f8d2e704609fd0b240629f22c2a3ef6",message:this.error,onClear:()=>this.error=""}),h("div",{key:"64a623f897dfb96d922ddc0cbdfcf529c52bef76",class:"test-runner-container__content"},h(LLMTestCases,{key:"017da41567c5c13933d9cf31d1a972743bd9b100",testCases:this.testCases,onRun:e=>this.runSingleTest(e).catch((()=>{})),onDelete:e=>this.deleteTestCase(e),onAddTestCase:()=>this.addNewTestCase(),handleTestCaseChange:this.handleTestCaseChange,onExpectedOutcomeChange:this.handleExpectedOutcomeChange})))}static get style(){return tokensCss()+(llmTestRunnerCss()+(llmTestRunnerHeaderCss()+(llmTestCasesCss()+(llmTestCaseRowCss()+(rowActionsCss()+(evaluationSummaryCss()+(responseOutputCss()+(errorMessageCss()+(buttonCss()+iconButtonCss())))))))))}},[513,"llm-test-runner",{delayMs:[2,"delay-ms"],useSave:[4,"use-save"],initialTestCases:[16],defaultExpectedOutcomeSchema:[16],testCases:[32],isRunningAll:[32],error:[32],isExportingTestSuite:[32],isExportingTestResults:[32],isSaving:[32],resetSavingState:[64]}]);function defineCustomElement(){if(typeof customElements==="undefined"){return}const e=["llm-test-runner","app-chips","app-select","app-textarea"];e.forEach((e=>{switch(e){case"llm-test-runner":if(!customElements.get(transformTag(e))){customElements.define(transformTag(e),LLMTestRunner)}break;case"app-chips":if(!customElements.get(transformTag(e))){defineCustomElement$3()}break;case"app-select":if(!customElements.get(transformTag(e))){defineCustomElement$2()}break;case"app-textarea":if(!customElements.get(transformTag(e))){defineCustomElement$1()}break}}))}export{LLMTestRunner as L,defineCustomElement as d};
|
|
7
|
+
//# sourceMappingURL=p-Bb89MYYu.js.map
|