@huggingface/transformers 4.0.0-next.4 → 4.0.0-next.5

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.
Files changed (165) hide show
  1. package/README.md +8 -3
  2. package/dist/ort-wasm-simd-threaded.jsep.mjs +28 -28
  3. package/dist/transformers.js +3093 -2100
  4. package/dist/transformers.min.js +17 -19
  5. package/dist/transformers.node.cjs +3079 -2059
  6. package/dist/transformers.node.min.cjs +19 -21
  7. package/dist/transformers.node.min.mjs +19 -21
  8. package/dist/transformers.node.mjs +3067 -2059
  9. package/dist/transformers.web.js +1295 -276
  10. package/dist/transformers.web.min.js +15 -15
  11. package/package.json +4 -4
  12. package/src/backends/onnx.js +66 -10
  13. package/src/backends/utils/cacheWasm.js +9 -6
  14. package/src/configs.js +51 -3
  15. package/src/env.js +66 -7
  16. package/src/generation/logits_sampler.js +3 -15
  17. package/src/image_processors_utils.js +2 -6
  18. package/src/models/afmoe/modeling_afmoe.js +5 -0
  19. package/src/models/auto/image_processing_auto.js +2 -1
  20. package/src/models/auto/modeling_auto.js +2 -1
  21. package/src/models/auto/tokenization_auto.js +2 -1
  22. package/src/models/clap/feature_extraction_clap.js +2 -1
  23. package/src/models/marian/tokenization_marian.js +3 -2
  24. package/src/models/modeling_utils.js +14 -4
  25. package/src/models/models.js +5 -0
  26. package/src/models/paligemma/processing_paligemma.js +3 -2
  27. package/src/models/processors.js +2 -0
  28. package/src/models/qwen2_5_vl/modeling_qwen2_5_vl.js +5 -0
  29. package/src/models/qwen2_5_vl/processing_qwen2_5_vl.js +3 -0
  30. package/src/models/qwen2_vl/image_processing_qwen2_vl.js +54 -0
  31. package/src/models/qwen2_vl/modeling_qwen2_vl.js +8 -2
  32. package/src/models/qwen3_5/modeling_qwen3_5.js +3 -0
  33. package/src/models/qwen3_5_moe/modeling_qwen3_5_moe.js +3 -0
  34. package/src/models/qwen3_vl/modeling_qwen3_vl.js +3 -0
  35. package/src/models/qwen3_vl/processing_qwen3_vl.js +3 -0
  36. package/src/models/registry.js +7 -1
  37. package/src/models/session.js +16 -50
  38. package/src/models/whisper/feature_extraction_whisper.js +2 -1
  39. package/src/models/whisper/modeling_whisper.js +6 -5
  40. package/src/models/xlm/tokenization_xlm.js +2 -1
  41. package/src/pipelines/automatic-speech-recognition.js +3 -2
  42. package/src/pipelines/index.js +395 -0
  43. package/src/pipelines/text-generation.js +4 -0
  44. package/src/pipelines/text-to-audio.js +4 -2
  45. package/src/pipelines/zero-shot-classification.js +3 -2
  46. package/src/pipelines.js +104 -356
  47. package/src/tokenization_utils.js +42 -21
  48. package/src/transformers.js +6 -1
  49. package/src/utils/audio.js +2 -1
  50. package/src/utils/cache.js +4 -1
  51. package/src/utils/core.js +23 -1
  52. package/src/utils/devices.js +22 -0
  53. package/src/utils/dtypes.js +55 -0
  54. package/src/utils/hub/files.js +17 -2
  55. package/src/utils/hub/utils.js +10 -4
  56. package/src/utils/hub.js +57 -17
  57. package/src/utils/image.js +2 -1
  58. package/src/utils/logger.js +67 -0
  59. package/src/utils/model-loader.js +35 -17
  60. package/src/utils/model_registry/ModelRegistry.js +299 -0
  61. package/src/utils/model_registry/clear_cache.js +128 -0
  62. package/src/utils/model_registry/get_file_metadata.js +149 -0
  63. package/src/utils/model_registry/get_files.js +42 -0
  64. package/src/utils/model_registry/get_model_files.js +182 -0
  65. package/src/utils/model_registry/get_pipeline_files.js +53 -0
  66. package/src/utils/model_registry/get_processor_files.js +20 -0
  67. package/src/utils/model_registry/get_tokenizer_files.js +21 -0
  68. package/src/utils/model_registry/is_cached.js +92 -0
  69. package/src/utils/random.js +225 -0
  70. package/src/utils/tensor.js +8 -21
  71. package/src/utils/video.js +2 -2
  72. package/types/backends/onnx.d.ts.map +1 -1
  73. package/types/backends/utils/cacheWasm.d.ts.map +1 -1
  74. package/types/configs.d.ts.map +1 -1
  75. package/types/env.d.ts +42 -24
  76. package/types/env.d.ts.map +1 -1
  77. package/types/generation/logits_sampler.d.ts +2 -2
  78. package/types/generation/logits_sampler.d.ts.map +1 -1
  79. package/types/image_processors_utils.d.ts.map +1 -1
  80. package/types/models/afmoe/modeling_afmoe.d.ts +8 -0
  81. package/types/models/afmoe/modeling_afmoe.d.ts.map +1 -0
  82. package/types/models/auto/image_processing_auto.d.ts.map +1 -1
  83. package/types/models/auto/modeling_auto.d.ts.map +1 -1
  84. package/types/models/auto/tokenization_auto.d.ts.map +1 -1
  85. package/types/models/clap/feature_extraction_clap.d.ts.map +1 -1
  86. package/types/models/marian/tokenization_marian.d.ts.map +1 -1
  87. package/types/models/modeling_utils.d.ts.map +1 -1
  88. package/types/models/models.d.ts +5 -0
  89. package/types/models/paligemma/processing_paligemma.d.ts.map +1 -1
  90. package/types/models/processors.d.ts +2 -0
  91. package/types/models/qwen2_5_vl/modeling_qwen2_5_vl.d.ts +4 -0
  92. package/types/models/qwen2_5_vl/modeling_qwen2_5_vl.d.ts.map +1 -0
  93. package/types/models/qwen2_5_vl/processing_qwen2_5_vl.d.ts +4 -0
  94. package/types/models/qwen2_5_vl/processing_qwen2_5_vl.d.ts.map +1 -0
  95. package/types/models/qwen2_vl/image_processing_qwen2_vl.d.ts +3 -0
  96. package/types/models/qwen2_vl/image_processing_qwen2_vl.d.ts.map +1 -1
  97. package/types/models/qwen2_vl/modeling_qwen2_vl.d.ts +1 -0
  98. package/types/models/qwen2_vl/modeling_qwen2_vl.d.ts.map +1 -1
  99. package/types/models/qwen3_5/modeling_qwen3_5.d.ts +4 -0
  100. package/types/models/qwen3_5/modeling_qwen3_5.d.ts.map +1 -0
  101. package/types/models/qwen3_5_moe/modeling_qwen3_5_moe.d.ts +4 -0
  102. package/types/models/qwen3_5_moe/modeling_qwen3_5_moe.d.ts.map +1 -0
  103. package/types/models/qwen3_vl/modeling_qwen3_vl.d.ts +4 -0
  104. package/types/models/qwen3_vl/modeling_qwen3_vl.d.ts.map +1 -0
  105. package/types/models/qwen3_vl/processing_qwen3_vl.d.ts +4 -0
  106. package/types/models/qwen3_vl/processing_qwen3_vl.d.ts.map +1 -0
  107. package/types/models/registry.d.ts.map +1 -1
  108. package/types/models/session.d.ts.map +1 -1
  109. package/types/models/whisper/feature_extraction_whisper.d.ts.map +1 -1
  110. package/types/models/whisper/modeling_whisper.d.ts.map +1 -1
  111. package/types/models/xlm/tokenization_xlm.d.ts.map +1 -1
  112. package/types/pipelines/automatic-speech-recognition.d.ts.map +1 -1
  113. package/types/pipelines/index.d.ts +299 -0
  114. package/types/pipelines/index.d.ts.map +1 -0
  115. package/types/pipelines/text-generation.d.ts +5 -1
  116. package/types/pipelines/text-generation.d.ts.map +1 -1
  117. package/types/pipelines/text-to-audio.d.ts.map +1 -1
  118. package/types/pipelines/zero-shot-classification.d.ts.map +1 -1
  119. package/types/pipelines.d.ts +50 -291
  120. package/types/pipelines.d.ts.map +1 -1
  121. package/types/tokenization_utils.d.ts +44 -26
  122. package/types/tokenization_utils.d.ts.map +1 -1
  123. package/types/transformers.d.ts +4 -1
  124. package/types/transformers.d.ts.map +1 -1
  125. package/types/utils/audio.d.ts.map +1 -1
  126. package/types/utils/cache.d.ts +6 -0
  127. package/types/utils/cache.d.ts.map +1 -1
  128. package/types/utils/core.d.ts +59 -2
  129. package/types/utils/core.d.ts.map +1 -1
  130. package/types/utils/devices.d.ts +15 -0
  131. package/types/utils/devices.d.ts.map +1 -1
  132. package/types/utils/dtypes.d.ts +16 -0
  133. package/types/utils/dtypes.d.ts.map +1 -1
  134. package/types/utils/hub/files.d.ts +6 -0
  135. package/types/utils/hub/files.d.ts.map +1 -1
  136. package/types/utils/hub/utils.d.ts +2 -1
  137. package/types/utils/hub/utils.d.ts.map +1 -1
  138. package/types/utils/hub.d.ts +29 -0
  139. package/types/utils/hub.d.ts.map +1 -1
  140. package/types/utils/image.d.ts.map +1 -1
  141. package/types/utils/logger.d.ts +28 -0
  142. package/types/utils/logger.d.ts.map +1 -0
  143. package/types/utils/model-loader.d.ts +15 -0
  144. package/types/utils/model-loader.d.ts.map +1 -1
  145. package/types/utils/model_registry/ModelRegistry.d.ts +211 -0
  146. package/types/utils/model_registry/ModelRegistry.d.ts.map +1 -0
  147. package/types/utils/model_registry/clear_cache.d.ts +74 -0
  148. package/types/utils/model_registry/clear_cache.d.ts.map +1 -0
  149. package/types/utils/model_registry/get_file_metadata.d.ts +20 -0
  150. package/types/utils/model_registry/get_file_metadata.d.ts.map +1 -0
  151. package/types/utils/model_registry/get_files.d.ts +23 -0
  152. package/types/utils/model_registry/get_files.d.ts.map +1 -0
  153. package/types/utils/model_registry/get_model_files.d.ts +22 -0
  154. package/types/utils/model_registry/get_model_files.d.ts.map +1 -0
  155. package/types/utils/model_registry/get_pipeline_files.d.ts +21 -0
  156. package/types/utils/model_registry/get_pipeline_files.d.ts.map +1 -0
  157. package/types/utils/model_registry/get_processor_files.d.ts +9 -0
  158. package/types/utils/model_registry/get_processor_files.d.ts.map +1 -0
  159. package/types/utils/model_registry/get_tokenizer_files.d.ts +9 -0
  160. package/types/utils/model_registry/get_tokenizer_files.d.ts.map +1 -0
  161. package/types/utils/model_registry/is_cached.d.ts +62 -0
  162. package/types/utils/model_registry/is_cached.d.ts.map +1 -0
  163. package/types/utils/random.d.ts +86 -0
  164. package/types/utils/random.d.ts.map +1 -0
  165. package/types/utils/tensor.d.ts.map +1 -1
@@ -1,29 +1,27 @@
1
- var YT=Object.defineProperty;var Jr=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Ps=(t,e)=>{for(var r in e)YT(t,r,{get:e[r],enumerable:!0})};import QT from"fs";import zs from"path";import JT from"url";var ZT="4.0.0-next.4",tv=typeof process<"u",rv=tv&&process?.release?.name==="node",Pn=!av(QT),sv=!av(zs),eS=typeof globalThis.Deno<"u",az=typeof globalThis.Bun<"u",nv=typeof window<"u"&&typeof window.document<"u",ov=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),dp=typeof self<"u"&&"caches"in self,tS=rv||typeof navigator<"u"&&"gpu"in navigator,rS=typeof navigator<"u"&&"ml"in navigator,sS=()=>{if(typeof navigator>"u")return!1;let t=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,s=!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android");return r&&s},nS=sS(),be=Object.freeze({IS_BROWSER_ENV:nv,IS_WEBWORKER_ENV:ov,IS_WEB_CACHE_AVAILABLE:dp,IS_WEBGPU_AVAILABLE:tS,IS_WEBNN_AVAILABLE:rS,IS_SAFARI:nS,IS_PROCESS_AVAILABLE:tv,IS_NODE_ENV:rv,IS_FS_AVAILABLE:Pn,IS_PATH_AVAILABLE:sv}),fp=Pn&&sv,Li="./";if(fp){let t=Object(import.meta).url;t?Li=zs.dirname(zs.dirname(JT.fileURLToPath(t))):typeof __dirname<"u"&&(Li=zs.dirname(__dirname))}var oS=fp?zs.join(Li,"/.cache/"):null,ev="/models/",aS=fp?zs.join(Li,ev):ev,De={version:ZT,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(nv||ov),localModelPath:aS,useFS:Pn,useBrowserCache:dp&&!eS,useFSCache:Pn,cacheDir:oS,useCustomCache:!1,customCache:null,useWasmCache:dp||Pn,cacheKey:"transformers-cache"};function av(t){return Object.keys(t).length===0}var iS=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let s=e;for(let n=0;n<r.length;++n){let o=r[n];s=s[o]??=Object.create(null)}s.end=r}return e}split(t){let e=[],r=t.length,s=0,n=0;for(;n<r;){let o=this.trie,a=null,i=n;for(;i<r&&(o=o[t[i]]);)o.end&&(a=o.end),++i;a?(n>s&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s<r&&e.push(t.slice(s)),e}},iv=iS,lS=class{constructor(t){this.content=t.content,this.id=t.id,this.single_word=t.single_word??!1,this.lstrip=t.lstrip??!1,this.rstrip=t.rstrip??!1,this.special=t.special??!1,this.normalized=t.normalized??!this.special}},cS=lS,mv=(()=>{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),r=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+r),r+=1);let s=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,s[o]]))})(),uS=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),pS=uS(mv),lv=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",dS=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],[` ?[^(\\s|[${lv}])]+`,` ?[^\\s${lv}]+`]]),Ni="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",hp=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),$i=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");for(let[s,n]of dS)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1,o=r.replace(/(\\[pP])\{([^}=]+)\}/g,(a,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(o,"gu")}catch{throw s}}}else if(t.String!==void 0){let r=fS(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},fS=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),mS=(t,e,r)=>{let s=[],n=0;for(;n<t.length;){if(s.push(t[n]),(e.get(t[n])??r)!==r){++n;continue}for(;++n<t.length&&(e.get(t[n])??r)===r;)e.get(s.at(-1))!==r&&(s[s.length-1]+=t[n])}return s},hS=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,_S=t=>Number.isInteger(t)||typeof t=="bigint",gS=t=>{let e=0;for(let r of t)++e;return e},wS=t=>hv(t.toLowerCase()),Wt=(...t)=>Array.prototype.concat.apply([],t),_p=t=>new Map(Object.entries(t)),xS=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s<n.index&&r.push(t.slice(s,n.index)),o.length>0&&r.push(o),s=n.index+o.length}return s<t.length&&r.push(t.slice(s)),r},hv=t=>t.replace(/\p{M}/gu,""),cv=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let s of r)if(!(s in t))return`${e} must contain a "${s}" property`;return null},yS=t=>t.match(/\S+/g)||[],bS=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},zn=bS,vS=class extends zn{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},mr=vS,kS=class extends mr{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let s=t[r],n=s.charCodeAt(0);hS(n)?(e.push(" "),e.push(s),e.push(" ")):e.push(s)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(/\p{Mn}/gu,"")}is_control(t){switch(t){case" ":case`
2
- `:case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(t)}}clean_text(t){let e=[];for(let r of t){let s=r.charCodeAt(0);s===0||s===65533||this.is_control(r)||(/^\s$/.test(r)?e.push(" "):e.push(r))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},ES=kS,AS=class extends mr{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(r=>r.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},MS=AS,TS=class extends mr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>_v(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},SS=TS,OS=class extends mr{normalize(t){let e=$i(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},IS=OS,CS=class extends mr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Ri=CS,PS=class extends Ri{constructor(){super(...arguments),this.form="NFC"}},zS=PS,LS=class extends Ri{constructor(){super(...arguments),this.form="NFD"}},NS=LS,$S=class extends Ri{constructor(){super(...arguments),this.form="NFKC"}},RS=$S,US=class extends Ri{constructor(){super(...arguments),this.form="NFKD"}},BS=US,DS=class extends mr{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},FS=DS,jS=class extends mr{normalize(t){return hv(t)}},GS=jS,qS=class extends mr{normalize(t){return t.toLowerCase()}},WS=qS,VS=class extends mr{normalize(t){return t=this.config.prepend+t,t}},HS=VS;function XS(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new ES(t);case"Precompiled":return new MS(t);case"Sequence":return new SS(t);case"Replace":return new IS(t);case"NFC":return new zS(t);case"NFD":return new NS(t);case"NFKC":return new RS(t);case"NFKD":return new BS(t);case"Strip":return new FS(t);case"StripAccents":return new GS(t);case"Lowercase":return new WS(t);case"Prepend":return new HS(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var _v=XS,KS=class extends zn{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},Vt=KS,YS=class extends Vt{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=mv,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(s=>Array.from(this.text_encoder.encode(s),n=>this.byte_encoder[n]).join(""))}},QS=YS,JS=class extends Vt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},ZS=JS,eO=class extends Vt{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},s=t.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},tO=eO,rO=class extends Vt{constructor(t){super(),this.config=t,this.pattern=$i(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):xS(t,this.pattern)}},sO=rO,nO=class extends Vt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Ni}]+|[${Ni}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},oO=nO,aO=class extends Vt{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},iO=aO,lO=class extends Vt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Ni}]+|[${Ni}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},cO=lO,uO=class extends Vt{constructor(t){super(),this.config=t,this.pattern=$i(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},pO=uO,dO=class extends Vt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>gv(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},fO=dO,mO=class extends Vt{pre_tokenize_text(t){return yS(t)}},hO=mO,_O=class extends Vt{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let r=0;r<t.length;r+=this._length)e.push(t.slice(r,r+this._length));return e}},gO=_O;function wO(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new cO;case"Sequence":return new fO(t);case"Whitespace":return new ZS;case"WhitespaceSplit":return new hO;case"Metaspace":return new tO(t);case"ByteLevel":return new QS(t);case"Split":return new sO(t);case"Punctuation":return new oO(t);case"Digits":return new iO(t);case"Replace":return new pO(t);case"FixedLength":return new gO(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var gv=wO,xO=class extends zn{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=mS(e,this.tokens_to_ids,this.unk_token_id)),e}},Ui=xO,yO=class extends Ui{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=_p(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,r]of this.tokens_to_ids)this.vocab[r]=e}encode(t){let e=[];for(let r of t){let s=[...r];if(s.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,a=[];for(;o<s.length;){let i=s.length,l=null;for(;o<i;){let u=s.slice(o,i).join("");if(o>0&&(u=this.config.continuing_subword_prefix+u),this.tokens_to_ids.has(u)){l=u;break}--i}if(l===null){n=!0;break}a.push(l),o=i}n?e.push(this.unk_token):e.push(...a)}return e}},uv=yO,pv=class wv{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new wv(!1,new Map)}},bO=class{constructor(){this.root=pv.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let s=e.children.get(r);s===void 0&&(s=pv.default(),e.children.set(r,s)),e=s}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let s of t){if(r+=s,e=e.children.get(s),e===void 0)return;e.is_leaf&&(yield r)}}},vO=bO,mp=class xv{constructor(e,r,s,n,o){this.token_id=e,this.node_id=r,this.pos=s,this.length=n,this.score=o,this.prev=null,this.backtrace_score=0}clone(){let e=new xv(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},kO=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let s=new mp(this.bos_token_id??0,0,0,0,0),n=new mp(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(s)}insert(t,e,r,s){let n=this.nodes.length,o=new mp(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let u of this.end_nodes[e]){let d=u.backtrace_score+a.score;(l===null||d>i)&&(l=u.clone(),i=d)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},EO=kO;function AO(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]<e&&(e=t[s],r=s);return[e,r]}var MO=class extends Ui{constructor(t,e){super(t);let r=t.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let s=0;s<r;++s)[this.vocab[s],this.scores[s]]=t.vocab[s];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((s,n)=>[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=AO(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new vO,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,s=0;for(;s<e.length;){let n=!1,o=[],a=e.slice(s).join(""),i=this.trie.common_prefix_search(a);for(let l of i){o.push(l);let u=this.tokens_to_ids.get(l),d=this.scores[u],f=gS(l);t.insert(s,f,d,u),!n&&f===r&&(n=!0)}n||t.insert(s,r,this.unk_score,this.unk_token_id),s+=r}}tokenize(t){let e=new EO(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let r of t){let s=this.tokenize(r);e.push(...s)}return e}},dv=MO,TO=class{constructor(t=(r,s)=>r>s,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size<this._max_size)this._heap.push(e),this._sift_up();else{let r=this._smallest();this._comparator(e,this._heap[r])&&(this._heap[r]=e,this._sift_up_from(r))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)<this.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},SO=TO,OO=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},IO=OO,CO=class extends Ui{constructor(t){super(t),this.tokens_to_ids=_p(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,s]of this.tokens_to_ids)this.vocab[s]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,s)=>[JSON.stringify(r),s])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new IO(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){let n=new SO((i,l)=>i.score<l.score),o={token:r[0],bias:0,prev:null,next:null},a=o;for(let i=1;i<r.length;++i){let l={bias:i/r.length,token:r[i],prev:a,next:null};a.next=l,this.add_node(n,a),a=l}for(;!n.is_empty();){let i=n.pop();if(i.deleted||!i.next||i.next.deleted)continue;if(i.deleted=!0,i.next.deleted=!0,i.prev){let u={...i.prev};i.prev.deleted=!0,i.prev=u,u.prev?u.prev.next=u:o=u}let l={token:i.token+i.next.token,bias:i.bias,prev:i.prev,next:i.next.next};l.prev?(l.prev.next=l,this.add_node(n,l.prev)):o=l,l.next&&(l.next.prev=l,this.add_node(n,l))}for(let i=o;i!==null;i=i.next)s.push(i.token)}else s=r;if(this.continuing_subword_suffix)for(let n=0;n<s.length-1;++n)s[n]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,s),s}add_node(t,e){let r=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));r!==void 0&&(e.score=r+e.bias,t.push(e))}encode(t){let e=[];for(let r of t){if(this.ignore_merges&&this.tokens_to_ids.has(r)){e.push(r);continue}let s=this.bpe(r);for(let n of s)if(this.tokens_to_ids.has(n))e.push(n);else if(this.byte_fallback){let o=Array.from(this.text_encoder.encode(n)).map(a=>`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);o.every(a=>this.tokens_to_ids.has(a))?e.push(...o):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},fv=CO,PO=class extends Ui{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=_p(e.target_lang?r[e.target_lang]:r),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[s,n]of this.tokens_to_ids)this.vocab[n]=s}encode(t){return t}},zO=PO;function LO(t,e){switch(t.type){case"WordPiece":return new uv(t);case"Unigram":return new dv(t,e.eos_token);case"BPE":return new fv(t);default:if(t.vocab)return Array.isArray(t.vocab)?new dv(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new fv(t):new uv(t):new zO(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var NO=LO,$O=class extends zn{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Ln=$O,RO=class extends Ln{post_process(t,e=null,r=!0){let s=e===null?this.config.single:this.config.pair,n=[],o=[];for(let a of s)"SpecialToken"in a?r&&(n.push(a.SpecialToken.id),o.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(n=Wt(n,t),o=Wt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Wt(n,e),o=Wt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},UO=RO,BO=class extends Ln{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},DO=BO,FO=class extends Ln{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Wt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=[],o=r?[this.sep[0]]:[];t=Wt(t,n,e,o),s=Wt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},jO=FO,GO=class extends Ln{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Wt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=r?[this.sep[0]]:[],o=r?[this.sep[0]]:[];t=Wt(t,n,e,o),s=Wt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},qO=GO,WO=class extends Ln{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>yv(e))}post_process(t,e=null,r=!0){let s={tokens:t,tokens_pair:e};for(let n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},VO=WO;function HO(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new UO(t);case"ByteLevel":return new DO(t);case"BertProcessing":return new jO(t);case"RobertaProcessing":return new qO(t);case"Sequence":return new VO(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var yv=HO,XO=class extends zn{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},$t=XO,KO=class extends $t{constructor(t){super(t),this.byte_decoder=pS,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),r=new Uint8Array([...e].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let s of t)this.added_tokens.find(n=>n.content===s)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(s)):r.push(s);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},YO=KO,QO=class extends $t{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let s=this.config.prefix;s&&e.startsWith(s)?e=e.replace(s,""):e=" "+e}return this.cleanup&&(e=hp(e)),e})}},JO=QO,ZO=class extends $t{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;r<t.length;++r){let s=t[r].replaceAll(this.replacement," ");r==0&&s.startsWith(" ")&&(s=s.substring(1)),e.push(s)}return e}},eI=ZO,tI=class extends $t{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},rI=tI,sI=class extends $t{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;n<t.length;++n)t[n]!==e.at(-1)&&e.push(t[n]);let s=e.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(s=hp(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},nI=sI,oI=class extends $t{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>bv(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},aI=oI,iI=class extends $t{decode_chain(t){let e=$i(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},lI=iI,cI=class extends $t{decode_chain(t){return[t.join("")]}},uI=cI,pI=class extends $t{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n<this.start&&e[n]===this.content;++n){r=n+1;continue}let s=e.length;for(let n=0;n<this.stop;++n){let o=e.length-n-1;if(e[o]===this.content){s=o;continue}else break}return e.slice(r,s)})}},dI=pI,fI=class extends $t{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],r=[];for(let s of t){let n=null;if(s.length===6&&s.startsWith("<0x")&&s.endsWith(">")){let o=parseInt(s.slice(3,5),16);isNaN(o)||(n=o)}if(n!==null)r.push(n);else{if(r.length>0){let o=this.text_decoder.decode(Uint8Array.from(r));e.push(o),r=[]}e.push(s)}}if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}return e}},mI=fI;function hI(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new YO(t);case"WordPiece":return new JO(t);case"Metaspace":return new eI(t);case"BPEDecoder":return new rI(t);case"CTC":return new nI(t);case"Sequence":return new aI(t);case"Replace":return new lI(t);case"Fuse":return new uI(t);case"Strip":return new dI(t);case"ByteFallback":return new mI(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var bv=hI,_I=class{constructor(t,e){let r=cv(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=cv(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=_v(this.tokenizer.normalizer),this.pre_tokenizer=gv(this.tokenizer.pre_tokenizer),this.model=NO(this.tokenizer.model,this.config),this.post_processor=yv(this.tokenizer.post_processor),this.decoder=bv(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let n=[],o=[];this.added_tokens_map=new Map;for(let a of this.tokenizer.added_tokens){let i=new cS(a);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){let l=this.normalizer(i.content);o.push(l),this.added_tokens_map.set(l,i)}else n.push(i.content)}(this.config.additional_special_tokens??[]).forEach(a=>{this.special_tokens.includes(a)||this.special_tokens.push(a)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new iv(n),this.splitter_normalized=new iv(o),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){let{tokens:n,token_type_ids:o}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),a=n.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:a,tokens:n,attention_mask:new Array(a.length).fill(1)};return s&&o&&(i.token_type_ids=o),i}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!_S(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=t.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);e.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let s=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(s=s.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=hp(s)),s}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((r,s)=>{let n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(e[s-1]=e[s-1].trimEnd()),n.rstrip&&s<e.length-1&&(e[s+1]=e[s+1].trimStart()))}),e.flatMap((r,s)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=wS(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let n=this.splitter_normalized.split(r);return n.forEach((o,a)=>{let i=this.added_tokens_map.get(o);i&&(i.lstrip&&a>0&&(n[a-1]=n[a-1].trimEnd()),i.rstrip&&a<n.length-1&&(n[a+1]=n[a+1].trimStart()))}),n.flatMap(o=>{if(o.length===0)return[];if(this.added_tokens_map.has(o))return[o];let a=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:s}):[o];return this.model(a)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let s=this.encode_text(t),n=this.encode_text(e||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Wt(s??[],n??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let r=0;r<this.model.vocab.length;++r){let s=this.model.vocab[r];(t||!this.added_tokens_map.has(s))&&e.set(s,r)}return e}},vv=_I;var $=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),Rt=class{constructor(t,e){this.value=t,this.type=e}};function kv(t){return/\w/.test(t)}function Nn(t){return/[0-9]/.test(t)}function Ev(t){return/\s/.test(t)}var gI=[["{%",$.OpenStatement],["%}",$.CloseStatement],["{{",$.OpenExpression],["}}",$.CloseExpression],["(",$.OpenParen],[")",$.CloseParen],["{",$.OpenCurlyBracket],["}",$.CloseCurlyBracket],["[",$.OpenSquareBracket],["]",$.CloseSquareBracket],[",",$.Comma],[".",$.Dot],[":",$.Colon],["|",$.Pipe],["<=",$.ComparisonBinaryOperator],[">=",$.ComparisonBinaryOperator],["==",$.ComparisonBinaryOperator],["!=",$.ComparisonBinaryOperator],["<",$.ComparisonBinaryOperator],[">",$.ComparisonBinaryOperator],["+",$.AdditiveBinaryOperator],["-",$.AdditiveBinaryOperator],["~",$.AdditiveBinaryOperator],["*",$.MultiplicativeBinaryOperator],["/",$.MultiplicativeBinaryOperator],["%",$.MultiplicativeBinaryOperator],["=",$.Equals]],wI=new Map([["n",`
3
- `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function xI(t,e={}){return t.endsWith(`
4
- `)&&(t=t.slice(0,-1)),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%-])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%-]})\n/g,"$1")),t.replace(/{%\s*(end)?generation\s*%}/gs,"")}function yI(t,e={}){let r=[],s=xI(t,e),n=0,o=0,a=u=>{let d="";for(;u(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],m=wI.get(f);if(m===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);d+=m;continue}if(d+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return d},i=()=>{let u=r.at(-1);u&&u.type===$.Text&&(u.value=u.value.trimEnd(),u.value===""&&r.pop())},l=()=>{for(;n<s.length&&Ev(s[n]);)++n};e:for(;n<s.length;){let u=r.at(-1)?.type;if(u===void 0||u===$.CloseStatement||u===$.CloseExpression||u===$.Comment){let f="";for(;n<s.length&&!(s[n]==="{"&&(s[n+1]==="%"||s[n+1]==="{"||s[n+1]==="#"));)f+=s[n++];if(f.length>0){r.push(new Rt(f,$.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let f=s[n]==="-";f&&++n;let m="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");m+=s[n++]}let _=m.endsWith("-");_&&(m=m.slice(0,-1)),f&&i(),r.push(new Rt(m,$.Comment)),n+=2,_&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Rt("{%",$.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Rt("{{",$.OpenExpression)),o=0,n+=3;continue}if(a(Ev),s.slice(n,n+3)==="-%}"){r.push(new Rt("%}",$.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Rt("}}",$.CloseExpression)),n+=3,l();continue}let d=s[n];if(d==="-"||d==="+"){let f=r.at(-1)?.type;if(f===$.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${d}`);switch(f){case $.Identifier:case $.NumericLiteral:case $.StringLiteral:case $.CloseParen:case $.CloseSquareBracket:break;default:{++n;let m=a(Nn);r.push(new Rt(`${d}${m}`,m.length>0?$.NumericLiteral:$.UnaryOperator));continue}}}for(let[f,m]of gI){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new Rt(f,m)),m===$.OpenExpression?o=0:m===$.OpenCurlyBracket?++o:m===$.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(d==="'"||d==='"'){++n;let f=a(m=>m!==d);r.push(new Rt(f,$.StringLiteral)),++n;continue}if(Nn(d)){let f=a(Nn);if(s[n]==="."&&Nn(s[n+1])){++n;let m=a(Nn);f=`${f}.${m}`}r.push(new Rt(f,$.NumericLiteral));continue}if(kv(d)){let f=a(kv);r.push(new Rt(f,$.Identifier));continue}throw new SyntaxError(`Unexpected character: ${d}`)}return r}var Xt=class{type="Statement"},bI=class extends Xt{constructor(t){super(),this.body=t}type="Program"},vI=class extends Xt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},kI=class extends Xt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},EI=class extends Xt{type="Break"},AI=class extends Xt{type="Continue"},MI=class extends Xt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},TI=class extends Xt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},SI=class extends Xt{constructor(t){super(),this.value=t}type="Comment"},St=class extends Xt{type="Expression"},OI=class extends St{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},Av=class extends St{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},Ls=class extends St{constructor(t){super(),this.value=t}type="Identifier"},Ns=class extends St{constructor(t){super(),this.value=t}type="Literal"},II=class extends Ns{type="IntegerLiteral"},CI=class extends Ns{type="FloatLiteral"},Mv=class extends Ns{type="StringLiteral"},PI=class extends Ns{type="ArrayLiteral"},Tv=class extends Ns{type="TupleLiteral"},zI=class extends Ns{type="ObjectLiteral"},$n=class extends St{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},LI=class extends St{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},NI=class extends Xt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},$I=class extends St{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},RI=class extends St{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},UI=class extends St{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},BI=class extends St{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},DI=class extends St{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},FI=class extends St{constructor(t){super(),this.argument=t}type="SpreadExpression"},jI=class extends Xt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},GI=class extends St{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function qI(t){let e=new bI([]),r=0;function s(S,L){let R=t[r++];if(!R||R.type!==S)throw new Error(`Parser Error: ${L}. ${R.type} !== ${S}.`);return R}function n(S){if(!l(S))throw new SyntaxError(`Expected ${S}`);++r}function o(){switch(t[r].type){case $.Comment:return new SI(t[r++].value);case $.Text:return u();case $.OpenStatement:return d();case $.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...S){return r+S.length<=t.length&&S.every((L,R)=>L===t[r+R].type)}function i(...S){return t[r]?.type===$.OpenStatement&&t[r+1]?.type===$.Identifier&&S.includes(t[r+1]?.value)}function l(...S){return r+S.length<=t.length&&S.every((L,R)=>t[r+R].type==="Identifier"&&L===t[r+R].value)}function u(){return new Mv(s($.Text,"Expected text token").value)}function d(){if(s($.OpenStatement,"Expected opening statement token"),t[r].type!==$.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let S=t[r].value,L;switch(S){case"set":++r,L=m();break;case"if":++r,L=_(),s($.OpenStatement,"Expected {% token"),n("endif"),s($.CloseStatement,"Expected %} token");break;case"macro":++r,L=w(),s($.OpenStatement,"Expected {% token"),n("endmacro"),s($.CloseStatement,"Expected %} token");break;case"for":++r,L=k(),s($.OpenStatement,"Expected {% token"),n("endfor"),s($.CloseStatement,"Expected %} token");break;case"call":{++r;let R=null;a($.OpenParen)&&(R=V());let te=ie();if(te.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let ue=V();s($.CloseStatement,"Expected closing statement token");let Be=[];for(;!i("endcall");)Be.push(o());s($.OpenStatement,"Expected '{%'"),n("endcall"),s($.CloseStatement,"Expected closing statement token");let Ce=new Av(te,ue);L=new jI(Ce,R,Be);break}case"break":++r,s($.CloseStatement,"Expected closing statement token"),L=new EI;break;case"continue":++r,s($.CloseStatement,"Expected closing statement token"),L=new AI;break;case"filter":{++r;let R=ie();R instanceof Ls&&a($.OpenParen)&&(R=X(R)),s($.CloseStatement,"Expected closing statement token");let te=[];for(;!i("endfilter");)te.push(o());s($.OpenStatement,"Expected '{%'"),n("endfilter"),s($.CloseStatement,"Expected '%}'"),L=new NI(R,te);break}default:throw new SyntaxError(`Unknown statement type: ${S}`)}return L}function f(){s($.OpenExpression,"Expected opening expression token");let S=E();return s($.CloseExpression,"Expected closing expression token"),S}function m(){let S=x(),L=null,R=[];if(a($.Equals))++r,L=x();else{for(s($.CloseStatement,"Expected %} token");!i("endset");)R.push(o());s($.OpenStatement,"Expected {% token"),n("endset")}return s($.CloseStatement,"Expected closing statement token"),new MI(S,L,R)}function _(){let S=E();s($.CloseStatement,"Expected closing statement token");let L=[],R=[];for(;!i("elif","else","endif");)L.push(o());if(i("elif")){++r,++r;let te=_();R.push(te)}else if(i("else"))for(++r,++r,s($.CloseStatement,"Expected closing statement token");!i("endif");)R.push(o());return new vI(S,L,R)}function w(){let S=ie();if(S.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let L=V();s($.CloseStatement,"Expected closing statement token");let R=[];for(;!i("endmacro");)R.push(o());return new TI(S,L,R)}function x(S=!1){let L=S?ie:E,R=[L()],te=a($.Comma);for(;te&&(++r,R.push(L()),!!a($.Comma)););return te?new Tv(R):R[0]}function k(){let S=x(!0);if(!(S instanceof Ls||S instanceof Tv))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${S.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let L=E();s($.CloseStatement,"Expected closing statement token");let R=[];for(;!i("endfor","else");)R.push(o());let te=[];if(i("else"))for(++r,++r,s($.CloseStatement,"Expected closing statement token");!i("endfor");)te.push(o());return new kI(S,L,R,te)}function E(){return M()}function M(){let S=I();if(l("if")){++r;let L=I();if(l("else")){++r;let R=M();return new GI(L,S,R)}else return new $I(S,L)}return S}function I(){let S=T();for(;l("or");){let L=t[r];++r;let R=T();S=new $n(L,S,R)}return S}function T(){let S=z();for(;l("and");){let L=t[r];++r;let R=z();S=new $n(L,S,R)}return S}function z(){let S;for(;l("not");){let L=t[r];++r;let R=z();S=new UI(L,R)}return S??C()}function C(){let S=v();for(;;){let L;if(l("not","in"))L=new Rt("not in",$.Identifier),r+=2;else if(l("in"))L=t[r++];else if(a($.ComparisonBinaryOperator))L=t[r++];else break;let R=v();S=new $n(L,S,R)}return S}function v(){let S=B();for(;a($.AdditiveBinaryOperator);){let L=t[r];++r;let R=B();S=new $n(L,S,R)}return S}function G(){let S=Y(ie());return a($.OpenParen)?X(S):S}function X(S){let L=new Av(S,V());return L=Y(L),a($.OpenParen)&&(L=X(L)),L}function V(){s($.OpenParen,"Expected opening parenthesis for arguments list");let S=Q();return s($.CloseParen,"Expected closing parenthesis for arguments list"),S}function Q(){let S=[];for(;!a($.CloseParen);){let L;if(t[r].type===$.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let R=E();L=new FI(R)}else if(L=E(),a($.Equals)){if(++r,!(L instanceof Ls))throw new SyntaxError("Expected identifier for keyword argument");let R=E();L=new DI(L,R)}S.push(L),a($.Comma)&&++r}return S}function K(){let S=[],L=!1;for(;!a($.CloseSquareBracket);)a($.Colon)?(S.push(void 0),++r,L=!0):(S.push(E()),a($.Colon)&&(++r,L=!0));if(S.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(L){if(S.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new BI(...S)}return S[0]}function Y(S){for(;a($.Dot)||a($.OpenSquareBracket);){let L=t[r];++r;let R,te=L.type===$.OpenSquareBracket;if(te)R=K(),s($.CloseSquareBracket,"Expected closing square bracket");else if(R=ie(),R.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");S=new OI(S,R,te)}return S}function B(){let S=P();for(;a($.MultiplicativeBinaryOperator);){let L=t[r++],R=P();S=new $n(L,S,R)}return S}function P(){let S=se();for(;l("is");){++r;let L=l("not");L&&++r;let R=ie();if(!(R instanceof Ls))throw new SyntaxError("Expected identifier for the test");S=new RI(S,L,R)}return S}function se(){let S=G();for(;a($.Pipe);){++r;let L=ie();if(!(L instanceof Ls))throw new SyntaxError("Expected identifier for the filter");a($.OpenParen)&&(L=X(L)),S=new LI(S,L)}return S}function ie(){let S=t[r++];switch(S.type){case $.NumericLiteral:{let L=S.value;return L.includes(".")?new CI(Number(L)):new II(Number(L))}case $.StringLiteral:{let L=S.value;for(;a($.StringLiteral);)L+=t[r++].value;return new Mv(L)}case $.Identifier:return new Ls(S.value);case $.OpenParen:{let L=x();return s($.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),L}case $.OpenSquareBracket:{let L=[];for(;!a($.CloseSquareBracket);)L.push(E()),a($.Comma)&&++r;return++r,new PI(L)}case $.OpenCurlyBracket:{let L=new Map;for(;!a($.CloseCurlyBracket);){let R=E();s($.Colon,"Expected colon between key and value in object literal");let te=E();L.set(R,te),a($.Comma)&&++r}return++r,new zI(L)}default:throw new SyntaxError(`Unexpected token: ${S.type}`)}}for(;r<t.length;)e.body.push(o());return e}function WI(t,e,r=1){if(e===void 0&&(e=t,t=0),r===0)throw new Error("range() step must not be zero");let s=[];if(r>0)for(let n=t;n<e;n+=r)s.push(n);else for(let n=t;n>e;n+=r)s.push(n);return s}function Sv(t,e,r,s=1){let n=Math.sign(s);n>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));let o=[];for(let a=e;n*a<n*r;a+=s)o.push(t[a]);return o}function VI(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}function HI(t){return XI(new Date,t)}function XI(t,e){let r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),n=o=>o<10?"0"+o:o.toString();return e.replace(/%[YmdbBHM%]/g,o=>{switch(o){case"%Y":return t.getFullYear().toString();case"%m":return n(t.getMonth()+1);case"%d":return n(t.getDate());case"%b":return s.format(t);case"%B":return r.format(t);case"%H":return n(t.getHours());case"%M":return n(t.getMinutes());case"%%":return"%";default:return o}})}function KI(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function YI(t,e,r,s){if(s===0)return t;let n=s==null||s<0?1/0:s,o=e.length===0?new RegExp("(?=)","gu"):new RegExp(KI(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var Ov=class extends Error{},Iv=class extends Error{},sr=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new le(!!this.value)}toString(){return String(this.value)}},de=class extends sr{type="IntegerValue"},Ke=class extends sr{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},Z=class extends sr{type="StringValue";builtins=new Map([["upper",new je(()=>new Z(this.value.toUpperCase()))],["lower",new je(()=>new Z(this.value.toLowerCase()))],["strip",new je(()=>new Z(this.value.trim()))],["title",new je(()=>new Z(VI(this.value)))],["capitalize",new je(()=>new Z(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new de(this.value.length)],["rstrip",new je(()=>new Z(this.value.trimEnd()))],["lstrip",new je(()=>new Z(this.value.trimStart()))],["startswith",new je(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof Z)return new le(this.value.startsWith(e.value));if(e instanceof ve){for(let r of e.value){if(!(r instanceof Z))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new le(!0)}return new le(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new je(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof Z)return new le(this.value.endsWith(e.value));if(e instanceof ve){for(let r of e.value){if(!(r instanceof Z))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new le(!0)}return new le(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new je(t=>{let e=t[0]??new qe;if(!(e instanceof Z||e instanceof qe))throw new Error("sep argument must be a string or null");let r=t[1]??new de(-1);if(!(r instanceof de))throw new Error("maxsplit argument must be a number");let s=[];if(e instanceof qe){let n=this.value.trimStart();for(let{0:o,index:a}of n.matchAll(/\S+/g)){if(r.value!==-1&&s.length>=r.value&&a!==void 0){s.push(o+n.slice(a+o.length));break}s.push(o)}}else{if(e.value==="")throw new Error("empty separator");s=this.value.split(e.value),r.value!==-1&&s.length>r.value&&s.push(s.splice(r.value).join(e.value))}return new ve(s.map(n=>new Z(n)))})],["replace",new je(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],r=t[1];if(!(e instanceof Z&&r instanceof Z))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new qe:s=t[2]:s=new qe,!(s instanceof de||s instanceof qe))throw new Error("replace() count argument must be a number or null");return new Z(YI(this.value,e.value,r.value,s.value))})]])},le=class extends sr{type="BooleanValue"},QI=/[\x7f-\uffff]/g;function Cv(t){return t.replace(QI,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function es(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,u;switch(a?[l,u]=a:n?(l=",",u=": "):(l=", ",u=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let d=JSON.stringify(t.value);return o&&(d=Cv(d)),d}case"ArrayValue":case"ObjectValue":{let d=n?" ".repeat(n):"",f=`
5
- `+d.repeat(r),m=f+d;if(t.type==="ArrayValue"){let _=t.value.map(w=>es(w,e,r+1,s));return n?`[${m}${_.join(`${l}${m}`)}${f}]`:`[${_.join(l)}]`}else{let _=Array.from(t.value.entries());i&&(_=_.sort(([x],[k])=>x.localeCompare(k)));let w=_.map(([x,k])=>{let E=JSON.stringify(x);o&&(E=Cv(E));let M=`${E}${u}${es(k,e,r+1,s)}`;return n?`${m}${M}`:M});return n?`{${w.join(l)}${f}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${t.type}`)}}var ht=class extends sr{type="ObjectValue";__bool__(){return new le(this.value.size>0)}builtins=new Map([["get",new je(([t,e])=>{if(!(t instanceof Z))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new qe})],["items",new je(()=>this.items())],["keys",new je(()=>this.keys())],["values",new je(()=>this.values())],["dictsort",new je(t=>{let e=new Map,r=t.filter(i=>i instanceof Rn?(e=i.value,!1):!0),s=r.at(0)??e.get("case_sensitive")??new le(!1);if(!(s instanceof le))throw new Error("case_sensitive must be a boolean");let n=r.at(1)??e.get("by")??new Z("key");if(!(n instanceof Z))throw new Error("by must be a string");if(!["key","value"].includes(n.value))throw new Error("by must be either 'key' or 'value'");let o=r.at(2)??e.get("reverse")??new le(!1);if(!(o instanceof le))throw new Error("reverse must be a boolean");let a=Array.from(this.value.entries()).map(([i,l])=>new ve([new Z(i),l])).sort((i,l)=>{let u=n.value==="key"?0:1,d=i.value[u],f=l.value[u],m=gp(d,f,s.value);return o.value?-m:m});return new ve(a)})]]);items(){return new ve(Array.from(this.value.entries()).map(([t,e])=>new ve([new Z(t),e])))}keys(){return new ve(Array.from(this.value.keys()).map(t=>new Z(t)))}values(){return new ve(Array.from(this.value.values()))}toString(){return es(this,{},0,!1)}},Rn=class extends ht{type="KeywordArgumentsValue"},ve=class extends sr{type="ArrayValue";builtins=new Map([["length",new de(this.value.length)]]);__bool__(){return new le(this.value.length>0)}toString(){return es(this,{},0,!1)}},Pv=class extends ve{type="TupleValue"},je=class extends sr{type="FunctionValue"},qe=class extends sr{type="NullValue"},Fe=class extends sr{type="UndefinedValue"},Zr=class{constructor(t){this.parent=t}variables=new Map([["namespace",new je(t=>{if(t.length===0)return new ht(new Map);if(t.length!==1||!(t[0]instanceof ht))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]})]]);tests=new Map([["boolean",t=>t.type==="BooleanValue"],["callable",t=>t instanceof je],["odd",t=>{if(!(t instanceof de))throw new Error(`cannot odd on ${t.type}`);return t.value%2!==0}],["even",t=>{if(!(t instanceof de))throw new Error(`cannot even on ${t.type}`);return t.value%2===0}],["false",t=>t.type==="BooleanValue"&&!t.value],["true",t=>t.type==="BooleanValue"&&t.value],["none",t=>t.type==="NullValue"],["string",t=>t.type==="StringValue"],["number",t=>t instanceof de||t instanceof Ke],["integer",t=>t instanceof de],["iterable",t=>t.type==="ArrayValue"||t.type==="StringValue"],["mapping",t=>t.type==="ObjectValue"],["lower",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toLowerCase()}],["upper",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toUpperCase()}],["none",t=>t.type==="NullValue"],["defined",t=>t.type!=="UndefinedValue"],["undefined",t=>t.type==="UndefinedValue"],["equalto",(t,e)=>t.value===e.value],["eq",(t,e)=>t.value===e.value]]);set(t,e){return this.declareVariable(t,Bi(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new Fe}catch{return new Fe}}};function JI(t){t.set("false",!1),t.set("true",!0),t.set("none",null),t.set("raise_exception",e=>{throw new Error(e)}),t.set("range",WI),t.set("strftime_now",HI),t.set("True",!0),t.set("False",!1),t.set("None",null)}function zv(t,e){let r=e.split("."),s=t;for(let n of r)if(s instanceof ht)s=s.value.get(n)??new Fe;else if(s instanceof ve){let o=parseInt(n,10);if(!isNaN(o)&&o>=0&&o<s.value.length)s=s.value[o];else return new Fe}else return new Fe;return s}function gp(t,e,r=!1){if(t instanceof qe&&e instanceof qe)return 0;if(t instanceof qe||e instanceof qe)throw new Error(`Cannot compare ${t.type} with ${e.type}`);if(t instanceof Fe&&e instanceof Fe)return 0;if(t instanceof Fe||e instanceof Fe)throw new Error(`Cannot compare ${t.type} with ${e.type}`);let s=o=>o instanceof de||o instanceof Ke||o instanceof le,n=o=>o instanceof le?o.value?1:0:o.value;if(s(t)&&s(e)){let o=n(t),a=n(e);return o<a?-1:o>a?1:0}if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);if(t.type==="StringValue"){let o=t.value,a=e.value;return r||(o=o.toLowerCase(),a=a.toLowerCase()),o<a?-1:o>a?1:0}else throw new Error(`Cannot compare type: ${t.type}`)}var ZI=class{global;constructor(t){this.global=t??new Zr}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){let r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}let s=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new le(r.value==s.value);case"!=":return new le(r.value!=s.value)}if(r instanceof Fe||s instanceof Fe){if(s instanceof Fe&&["in","not in"].includes(t.operator.value))return new le(t.operator.value==="not in");throw new Error(`Cannot perform operation ${t.operator.value} on undefined values`)}else{if(r instanceof qe||s instanceof qe)throw new Error("Cannot perform operation on null values");if(t.operator.value==="~")return new Z(r.value.toString()+s.value.toString());if((r instanceof de||r instanceof Ke)&&(s instanceof de||s instanceof Ke)){let n=r.value,o=s.value;switch(t.operator.value){case"+":case"-":case"*":{let a=t.operator.value==="+"?n+o:t.operator.value==="-"?n-o:n*o;return r instanceof Ke||s instanceof Ke?new Ke(a):new de(a)}case"/":return new Ke(n/o);case"%":{let a=n%o;return r instanceof Ke||s instanceof Ke?new Ke(a):new de(a)}case"<":return new le(n<o);case">":return new le(n>o);case">=":return new le(n>=o);case"<=":return new le(n<=o)}}else if(r instanceof ve&&s instanceof ve){if(t.operator.value==="+")return new ve(r.value.concat(s.value))}else if(s instanceof ve){let n=s.value.find(o=>o.value===r.value)!==void 0;switch(t.operator.value){case"in":return new le(n);case"not in":return new le(!n)}}}if((r instanceof Z||s instanceof Z)&&t.operator.value==="+")return new Z(r.value.toString()+s.value.toString());if(r instanceof Z&&s instanceof Z)switch(t.operator.value){case"in":return new le(s.value.includes(r.value));case"not in":return new le(!s.value.includes(r.value))}if(r instanceof Z&&s instanceof ht)switch(t.operator.value){case"in":return new le(s.value.has(r.value));case"not in":return new le(!s.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${s.type}`)}evaluateArguments(t,e){let r=[],s=new Map;for(let n of t)if(n.type==="SpreadExpression"){let o=n,a=this.evaluate(o.argument,e);if(!(a instanceof ve))throw new Error(`Cannot unpack non-iterable type: ${a.type}`);for(let i of a.value)r.push(i)}else if(n.type==="KeywordArgumentExpression"){let o=n;s.set(o.key.value,this.evaluate(o.value,e))}else{if(s.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(n,e))}return[r,s]}applyFilter(t,e,r){if(e.type==="Identifier"){let s=e;if(s.value==="tojson")return new Z(es(t,{}));if(t instanceof ve)switch(s.value){case"list":return t;case"first":return t.value[0];case"last":return t.value[t.value.length-1];case"length":return new de(t.value.length);case"reverse":return new ve(t.value.slice().reverse());case"sort":return new ve(t.value.slice().sort((n,o)=>gp(n,o,!1)));case"join":return new Z(t.value.map(n=>n.value).join(""));case"string":return new Z(es(t,{},0,!1));case"unique":{let n=new Set,o=[];for(let a of t.value)n.has(a.value)||(n.add(a.value),o.push(a));return new ve(o)}default:throw new Error(`Unknown ArrayValue filter: ${s.value}`)}else if(t instanceof Z)switch(s.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let n=t.builtins.get(s.value);if(n instanceof je)return n.value([],r);if(n instanceof de)return n;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new Z(t.value.trim());case"indent":return new Z(t.value.split(`
1
+ var IS=Object.defineProperty;var ps=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Vs=(t,e)=>{for(var r in e)IS(t,r,{get:e[r],enumerable:!0})};import CS from"fs";import Hs from"path";import PS from"url";var zS="4.0.0-next.5",Xs=!Pv(CS),Mv=!Pv(Hs),yl=typeof self<"u"&&"caches"in self,LS=typeof globalThis.Deno<"u",Fz=typeof globalThis.Bun<"u",Tv=LS&&yl&&!Xs,Sv=typeof process<"u",Ov=Sv&&process?.release?.name==="node"&&!Tv,Iv=typeof window<"u"&&typeof window.document<"u",Cv=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),NS=Ov||typeof navigator<"u"&&"gpu"in navigator,$S=typeof navigator<"u"&&"ml"in navigator,RS=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",DS=()=>{if(typeof navigator>"u")return!1;let t=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,s=!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android");return r&&s},US=DS(),ge=Object.freeze({IS_BROWSER_ENV:Iv,IS_WEBWORKER_ENV:Cv,IS_WEB_CACHE_AVAILABLE:yl,IS_WEBGPU_AVAILABLE:NS,IS_WEBNN_AVAILABLE:$S,IS_SAFARI:US,IS_PROCESS_AVAILABLE:Sv,IS_NODE_ENV:Ov,IS_FS_AVAILABLE:Xs,IS_PATH_AVAILABLE:Mv,IS_CRYPTO_AVAILABLE:RS}),$p=Xs&&Mv,bl="./";if($p){let t=Object(import.meta).url;t?bl=Hs.dirname(Hs.dirname(PS.fileURLToPath(t))):typeof __dirname<"u"&&(bl=Hs.dirname(__dirname))}var BS=$p?Hs.join(bl,"/.cache/"):null,Ev="/models/",FS=$p?Hs.join(bl,Ev):Ev,jS=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,St=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),Av=St.WARNING,fe={version:zS,backends:{onnx:{}},get logLevel(){return Av},set logLevel(t){Av=t,fe.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Iv||Cv||Tv),localModelPath:FS,useFS:Xs,useBrowserCache:yl,useFSCache:Xs,cacheDir:BS,useCustomCache:!1,customCache:null,useWasmCache:yl||Xs,cacheKey:"transformers-cache",fetch:jS};function Pv(t){return Object.keys(t).length===0}function vr(t,e){t&&t(e)}function zv(t){return Number.isInteger(t)||typeof t=="bigint"}function Rp(t){return t==null||t===-1}function Dp(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function ft(...t){return Array.prototype.concat.apply([],t)}function Lv(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function Ks(t,e){return Math.abs((t+e)%(2*e)-e)}function nt(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function Nv(t,e){let r=0;for(let s of t)s===e&&++r;return r}var Q={error(...t){fe.logLevel<=St.ERROR&&console.error(...t)},warn(...t){fe.logLevel<=St.WARNING&&console.warn(...t)},info(...t){fe.logLevel<=St.INFO&&console.log(...t)},debug(...t){fe.logLevel<=St.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var GS=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let s=e;for(let n=0;n<r.length;++n){let o=r[n];s=s[o]??=Object.create(null)}s.end=r}return e}split(t){let e=[],r=t.length,s=0,n=0;for(;n<r;){let o=this.trie,a=null,i=n;for(;i<r&&(o=o[t[i]]);)o.end&&(a=o.end),++i;a?(n>s&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s<r&&e.push(t.slice(s)),e}},$v=GS,qS=class{constructor(t){this.content=t.content,this.id=t.id,this.single_word=t.single_word??!1,this.lstrip=t.lstrip??!1,this.rstrip=t.rstrip??!1,this.special=t.special??!1,this.normalized=t.normalized??!this.special}},WS=qS,Gv=(()=>{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),r=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+r),r+=1);let s=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,s[o]]))})(),VS=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),HS=VS(Gv),Rv=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",XS=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${Rv}])]+`,` ?[^\\s${Rv}]+`]]),vl="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Bp=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),kl=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[s,n]of XS)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1,o=r.replace(/(\\[pP])\{([^}=]+)\}/g,(a,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(o,"gu")}catch{throw s}}}else if(t.String!==void 0){let r=KS(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},KS=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),YS=(t,e,r)=>{let s=[],n=0;for(;n<t.length;){if(s.push(t[n]),(e.get(t[n])??r)!==r){++n;continue}for(;++n<t.length&&(e.get(t[n])??r)===r;)e.get(s.at(-1))!==r&&(s[s.length-1]+=t[n])}return s},QS=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,JS=t=>Number.isInteger(t)||typeof t=="bigint",ZS=t=>{let e=0;for(let r of t)++e;return e},eO=t=>qv(t.toLowerCase()),Xt=(...t)=>Array.prototype.concat.apply([],t),Fp=t=>new Map(Object.entries(t)),tO=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s<n.index&&r.push(t.slice(s,n.index)),o.length>0&&r.push(o),s=n.index+o.length}return s<t.length&&r.push(t.slice(s)),r},qv=t=>t.replace(/\p{M}/gu,""),Dv=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let s of r)if(!(s in t))return`${e} must contain a "${s}" property`;return null},rO=t=>t.match(/\S+/g)||[],sO=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},Wn=sO,nO=class extends Wn{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},kr=nO,oO=class extends kr{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let s=t[r],n=s.charCodeAt(0);QS(n)?(e.push(" "),e.push(s),e.push(" ")):e.push(s)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(/\p{Mn}/gu,"")}is_control(t){switch(t){case" ":case`
2
+ `:case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(t)}}clean_text(t){let e=[];for(let r of t){let s=r.charCodeAt(0);s===0||s===65533||this.is_control(r)||(/^\s$/.test(r)?e.push(" "):e.push(r))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},aO=oO,iO=class extends kr{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(r=>r.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},lO=iO,cO=class extends kr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>Wv(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},uO=cO,pO=class extends kr{normalize(t){let e=kl(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},dO=pO,fO=class extends kr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},El=fO,mO=class extends El{constructor(){super(...arguments),this.form="NFC"}},hO=mO,_O=class extends El{constructor(){super(...arguments),this.form="NFD"}},gO=_O,wO=class extends El{constructor(){super(...arguments),this.form="NFKC"}},xO=wO,yO=class extends El{constructor(){super(...arguments),this.form="NFKD"}},bO=yO,vO=class extends kr{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},kO=vO,EO=class extends kr{normalize(t){return qv(t)}},AO=EO,MO=class extends kr{normalize(t){return t.toLowerCase()}},TO=MO,SO=class extends kr{normalize(t){return t=this.config.prepend+t,t}},OO=SO;function IO(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new aO(t);case"Precompiled":return new lO(t);case"Sequence":return new uO(t);case"Replace":return new dO(t);case"NFC":return new hO(t);case"NFD":return new gO(t);case"NFKC":return new xO(t);case"NFKD":return new bO(t);case"Strip":return new kO(t);case"StripAccents":return new AO(t);case"Lowercase":return new TO(t);case"Prepend":return new OO(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var Wv=IO,CO=class extends Wn{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},Kt=CO,PO=class extends Kt{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=Gv,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(s=>Array.from(this.text_encoder.encode(s),n=>this.byte_encoder[n]).join(""))}},zO=PO,LO=class extends Kt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},NO=LO,$O=class extends Kt{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},s=t.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},RO=$O,DO=class extends Kt{constructor(t){super(),this.config=t,this.pattern=kl(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):tO(t,this.pattern)}},UO=DO,BO=class extends Kt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${vl}]+|[${vl}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},FO=BO,jO=class extends Kt{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},GO=jO,qO=class extends Kt{constructor(){super(),this.pattern=new RegExp(`[^\\s${vl}]+|[${vl}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},WO=qO,VO=class extends Kt{constructor(t){super(),this.config=t,this.pattern=kl(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},HO=VO,XO=class extends Kt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>Vv(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},KO=XO,YO=class extends Kt{pre_tokenize_text(t){return rO(t)}},QO=YO,JO=class extends Kt{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let r=0;r<t.length;r+=this._length)e.push(t.slice(r,r+this._length));return e}},ZO=JO;function eI(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new WO;case"Sequence":return new KO(t);case"Whitespace":return new NO;case"WhitespaceSplit":return new QO;case"Metaspace":return new RO(t);case"ByteLevel":return new zO(t);case"Split":return new UO(t);case"Punctuation":return new FO(t);case"Digits":return new GO(t);case"Replace":return new HO(t);case"FixedLength":return new ZO(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var Vv=eI,tI=class extends Wn{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=YS(e,this.tokens_to_ids,this.unk_token_id)),e}},Al=tI,rI=class extends Al{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=Fp(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,r]of this.tokens_to_ids)this.vocab[r]=e}encode(t){let e=[];for(let r of t){let s=[...r];if(s.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,a=[];for(;o<s.length;){let i=s.length,l=null;for(;o<i;){let u=s.slice(o,i).join("");if(o>0&&(u=this.config.continuing_subword_prefix+u),this.tokens_to_ids.has(u)){l=u;break}--i}if(l===null){n=!0;break}a.push(l),o=i}n?e.push(this.unk_token):e.push(...a)}return e}},Uv=rI,Bv=class Hv{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new Hv(!1,new Map)}},sI=class{constructor(){this.root=Bv.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let s=e.children.get(r);s===void 0&&(s=Bv.default(),e.children.set(r,s)),e=s}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let s of t){if(r+=s,e=e.children.get(s),e===void 0)return;e.is_leaf&&(yield r)}}},nI=sI,Up=class Xv{constructor(e,r,s,n,o){this.token_id=e,this.node_id=r,this.pos=s,this.length=n,this.score=o,this.prev=null,this.backtrace_score=0}clone(){let e=new Xv(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},oI=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let s=new Up(this.bos_token_id??0,0,0,0,0),n=new Up(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(s)}insert(t,e,r,s){let n=this.nodes.length,o=new Up(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let u of this.end_nodes[e]){let p=u.backtrace_score+a.score;(l===null||p>i)&&(l=u.clone(),i=p)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},aI=oI;function iI(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]<e&&(e=t[s],r=s);return[e,r]}var lI=class extends Al{constructor(t,e){super(t);let r=t.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let s=0;s<r;++s)[this.vocab[s],this.scores[s]]=t.vocab[s];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((s,n)=>[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=iI(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new nI,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,s=0;for(;s<e.length;){let n=!1,o=[],a=e.slice(s).join(""),i=this.trie.common_prefix_search(a);for(let l of i){o.push(l);let u=this.tokens_to_ids.get(l),p=this.scores[u],f=ZS(l);t.insert(s,f,p,u),!n&&f===r&&(n=!0)}n||t.insert(s,r,this.unk_score,this.unk_token_id),s+=r}}tokenize(t){let e=new aI(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let r of t){let s=this.tokenize(r);e.push(...s)}return e}},Fv=lI,cI=class{constructor(t=(r,s)=>r>s,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size<this._max_size)this._heap.push(e),this._sift_up();else{let r=this._smallest();this._comparator(e,this._heap[r])&&(this._heap[r]=e,this._sift_up_from(r))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)<this.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},uI=cI,pI=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},dI=pI,fI=class extends Al{constructor(t){super(t),this.tokens_to_ids=Fp(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,s]of this.tokens_to_ids)this.vocab[s]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,s)=>[JSON.stringify(r),s])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new dI(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){let n=new uI((i,l)=>i.score<l.score),o={token:r[0],bias:0,prev:null,next:null},a=o;for(let i=1;i<r.length;++i){let l={bias:i/r.length,token:r[i],prev:a,next:null};a.next=l,this.add_node(n,a),a=l}for(;!n.is_empty();){let i=n.pop();if(i.deleted||!i.next||i.next.deleted)continue;if(i.deleted=!0,i.next.deleted=!0,i.prev){let u={...i.prev};i.prev.deleted=!0,i.prev=u,u.prev?u.prev.next=u:o=u}let l={token:i.token+i.next.token,bias:i.bias,prev:i.prev,next:i.next.next};l.prev?(l.prev.next=l,this.add_node(n,l.prev)):o=l,l.next&&(l.next.prev=l,this.add_node(n,l))}for(let i=o;i!==null;i=i.next)s.push(i.token)}else s=r;if(this.continuing_subword_suffix)for(let n=0;n<s.length-1;++n)s[n]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,s),s}add_node(t,e){let r=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));r!==void 0&&(e.score=r+e.bias,t.push(e))}encode(t){let e=[];for(let r of t){if(this.ignore_merges&&this.tokens_to_ids.has(r)){e.push(r);continue}let s=this.bpe(r);for(let n of s)if(this.tokens_to_ids.has(n))e.push(n);else if(this.byte_fallback){let o=Array.from(this.text_encoder.encode(n)).map(a=>`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);o.every(a=>this.tokens_to_ids.has(a))?e.push(...o):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},jv=fI,mI=class extends Al{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=Fp(e.target_lang?r[e.target_lang]:r),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[s,n]of this.tokens_to_ids)this.vocab[n]=s}encode(t){return t}},hI=mI;function _I(t,e){switch(t.type){case"WordPiece":return new Uv(t);case"Unigram":return new Fv(t,e.eos_token);case"BPE":return new jv(t);default:if(t.vocab)return Array.isArray(t.vocab)?new Fv(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new jv(t):new Uv(t):new hI(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var gI=_I,wI=class extends Wn{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Vn=wI,xI=class extends Vn{post_process(t,e=null,r=!0){let s=e===null?this.config.single:this.config.pair,n=[],o=[];for(let a of s)"SpecialToken"in a?r&&(n.push(a.SpecialToken.id),o.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(n=Xt(n,t),o=Xt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Xt(n,e),o=Xt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},yI=xI,bI=class extends Vn{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},vI=bI,kI=class extends Vn{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Xt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=[],o=r?[this.sep[0]]:[];t=Xt(t,n,e,o),s=Xt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},EI=kI,AI=class extends Vn{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Xt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=r?[this.sep[0]]:[],o=r?[this.sep[0]]:[];t=Xt(t,n,e,o),s=Xt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},MI=AI,TI=class extends Vn{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>Kv(e))}post_process(t,e=null,r=!0){let s={tokens:t,tokens_pair:e};for(let n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},SI=TI;function OI(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new yI(t);case"ByteLevel":return new vI(t);case"BertProcessing":return new EI(t);case"RobertaProcessing":return new MI(t);case"Sequence":return new SI(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var Kv=OI,II=class extends Wn{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Dt=II,CI=class extends Dt{constructor(t){super(t),this.byte_decoder=HS,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),r=new Uint8Array([...e].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let s of t)this.added_tokens.find(n=>n.content===s)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(s)):r.push(s);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},PI=CI,zI=class extends Dt{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let s=this.config.prefix;s&&e.startsWith(s)?e=e.replace(s,""):e=" "+e}return this.cleanup&&(e=Bp(e)),e})}},LI=zI,NI=class extends Dt{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;r<t.length;++r){let s=t[r].replaceAll(this.replacement," ");r==0&&s.startsWith(" ")&&(s=s.substring(1)),e.push(s)}return e}},$I=NI,RI=class extends Dt{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},DI=RI,UI=class extends Dt{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;n<t.length;++n)t[n]!==e.at(-1)&&e.push(t[n]);let s=e.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(s=Bp(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},BI=UI,FI=class extends Dt{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>Yv(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},jI=FI,GI=class extends Dt{decode_chain(t){let e=kl(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},qI=GI,WI=class extends Dt{decode_chain(t){return[t.join("")]}},VI=WI,HI=class extends Dt{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n<this.start&&e[n]===this.content;++n){r=n+1;continue}let s=e.length;for(let n=0;n<this.stop;++n){let o=e.length-n-1;if(e[o]===this.content){s=o;continue}else break}return e.slice(r,s)})}},XI=HI,KI=class extends Dt{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],r=[];for(let s of t){let n=null;if(s.length===6&&s.startsWith("<0x")&&s.endsWith(">")){let o=parseInt(s.slice(3,5),16);isNaN(o)||(n=o)}if(n!==null)r.push(n);else{if(r.length>0){let o=this.text_decoder.decode(Uint8Array.from(r));e.push(o),r=[]}e.push(s)}}if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}return e}},YI=KI;function QI(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new PI(t);case"WordPiece":return new LI(t);case"Metaspace":return new $I(t);case"BPEDecoder":return new DI(t);case"CTC":return new BI(t);case"Sequence":return new jI(t);case"Replace":return new qI(t);case"Fuse":return new VI(t);case"Strip":return new XI(t);case"ByteFallback":return new YI(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var Yv=QI,JI=class{constructor(t,e){let r=Dv(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=Dv(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=Wv(this.tokenizer.normalizer),this.pre_tokenizer=Vv(this.tokenizer.pre_tokenizer),this.model=gI(this.tokenizer.model,this.config),this.post_processor=Kv(this.tokenizer.post_processor),this.decoder=Yv(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let n=[],o=[];this.added_tokens_map=new Map;for(let a of this.tokenizer.added_tokens){let i=new WS(a);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){let l=this.normalizer(i.content);o.push(l),this.added_tokens_map.set(l,i)}else n.push(i.content)}(this.config.additional_special_tokens??[]).forEach(a=>{this.special_tokens.includes(a)||this.special_tokens.push(a)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new $v(n),this.splitter_normalized=new $v(o),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){let{tokens:n,token_type_ids:o}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),a=n.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:a,tokens:n,attention_mask:new Array(a.length).fill(1)};return s&&o&&(i.token_type_ids=o),i}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!JS(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=t.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);e.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let s=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(s=s.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=Bp(s)),s}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((r,s)=>{let n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(e[s-1]=e[s-1].trimEnd()),n.rstrip&&s<e.length-1&&(e[s+1]=e[s+1].trimStart()))}),e.flatMap((r,s)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=eO(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let n=this.splitter_normalized.split(r);return n.forEach((o,a)=>{let i=this.added_tokens_map.get(o);i&&(i.lstrip&&a>0&&(n[a-1]=n[a-1].trimEnd()),i.rstrip&&a<n.length-1&&(n[a+1]=n[a+1].trimStart()))}),n.flatMap(o=>{if(o.length===0)return[];if(this.added_tokens_map.has(o))return[o];let a=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:s}):[o];return this.model(a)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let s=this.encode_text(t),n=this.encode_text(e||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Xt(s??[],n??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let r=0;r<this.model.vocab.length;++r){let s=this.model.vocab[r];(t||!this.added_tokens_map.has(s))&&e.set(s,r)}return e}},Qv=JI;var $=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),Ut=class{constructor(t,e){this.value=t,this.type=e}};function Jv(t){return/\w/.test(t)}function Hn(t){return/[0-9]/.test(t)}function Zv(t){return/\s/.test(t)}var ZI=[["{%",$.OpenStatement],["%}",$.CloseStatement],["{{",$.OpenExpression],["}}",$.CloseExpression],["(",$.OpenParen],[")",$.CloseParen],["{",$.OpenCurlyBracket],["}",$.CloseCurlyBracket],["[",$.OpenSquareBracket],["]",$.CloseSquareBracket],[",",$.Comma],[".",$.Dot],[":",$.Colon],["|",$.Pipe],["<=",$.ComparisonBinaryOperator],[">=",$.ComparisonBinaryOperator],["==",$.ComparisonBinaryOperator],["!=",$.ComparisonBinaryOperator],["<",$.ComparisonBinaryOperator],[">",$.ComparisonBinaryOperator],["+",$.AdditiveBinaryOperator],["-",$.AdditiveBinaryOperator],["~",$.AdditiveBinaryOperator],["*",$.MultiplicativeBinaryOperator],["/",$.MultiplicativeBinaryOperator],["%",$.MultiplicativeBinaryOperator],["=",$.Equals]],eC=new Map([["n",`
3
+ `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function tC(t,e={}){return t.endsWith(`
4
+ `)&&(t=t.slice(0,-1)),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%-])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%-]})\n/g,"$1")),t.replace(/{%\s*(end)?generation\s*%}/gs,"")}function rC(t,e={}){let r=[],s=tC(t,e),n=0,o=0,a=u=>{let p="";for(;u(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],m=eC.get(f);if(m===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);p+=m;continue}if(p+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return p},i=()=>{let u=r.at(-1);u&&u.type===$.Text&&(u.value=u.value.trimEnd(),u.value===""&&r.pop())},l=()=>{for(;n<s.length&&Zv(s[n]);)++n};e:for(;n<s.length;){let u=r.at(-1)?.type;if(u===void 0||u===$.CloseStatement||u===$.CloseExpression||u===$.Comment){let f="";for(;n<s.length&&!(s[n]==="{"&&(s[n+1]==="%"||s[n+1]==="{"||s[n+1]==="#"));)f+=s[n++];if(f.length>0){r.push(new Ut(f,$.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let f=s[n]==="-";f&&++n;let m="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");m+=s[n++]}let h=m.endsWith("-");h&&(m=m.slice(0,-1)),f&&i(),r.push(new Ut(m,$.Comment)),n+=2,h&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Ut("{%",$.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Ut("{{",$.OpenExpression)),o=0,n+=3;continue}if(a(Zv),s.slice(n,n+3)==="-%}"){r.push(new Ut("%}",$.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Ut("}}",$.CloseExpression)),n+=3,l();continue}let p=s[n];if(p==="-"||p==="+"){let f=r.at(-1)?.type;if(f===$.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(f){case $.Identifier:case $.NumericLiteral:case $.StringLiteral:case $.CloseParen:case $.CloseSquareBracket:break;default:{++n;let m=a(Hn);r.push(new Ut(`${p}${m}`,m.length>0?$.NumericLiteral:$.UnaryOperator));continue}}}for(let[f,m]of ZI){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new Ut(f,m)),m===$.OpenExpression?o=0:m===$.OpenCurlyBracket?++o:m===$.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(p==="'"||p==='"'){++n;let f=a(m=>m!==p);r.push(new Ut(f,$.StringLiteral)),++n;continue}if(Hn(p)){let f=a(Hn);if(s[n]==="."&&Hn(s[n+1])){++n;let m=a(Hn);f=`${f}.${m}`}r.push(new Ut(f,$.NumericLiteral));continue}if(Jv(p)){let f=a(Jv);r.push(new Ut(f,$.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return r}var Qt=class{type="Statement"},sC=class extends Qt{constructor(t){super(),this.body=t}type="Program"},nC=class extends Qt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},oC=class extends Qt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},aC=class extends Qt{type="Break"},iC=class extends Qt{type="Continue"},lC=class extends Qt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},cC=class extends Qt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},uC=class extends Qt{constructor(t){super(),this.value=t}type="Comment"},Pt=class extends Qt{type="Expression"},pC=class extends Pt{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},ek=class extends Pt{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},Ys=class extends Pt{constructor(t){super(),this.value=t}type="Identifier"},Qs=class extends Pt{constructor(t){super(),this.value=t}type="Literal"},dC=class extends Qs{type="IntegerLiteral"},fC=class extends Qs{type="FloatLiteral"},tk=class extends Qs{type="StringLiteral"},mC=class extends Qs{type="ArrayLiteral"},rk=class extends Qs{type="TupleLiteral"},hC=class extends Qs{type="ObjectLiteral"},Xn=class extends Pt{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},_C=class extends Pt{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},gC=class extends Qt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},wC=class extends Pt{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},xC=class extends Pt{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},yC=class extends Pt{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},bC=class extends Pt{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},vC=class extends Pt{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},kC=class extends Pt{constructor(t){super(),this.argument=t}type="SpreadExpression"},EC=class extends Qt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},AC=class extends Pt{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function MC(t){let e=new sC([]),r=0;function s(I,L){let R=t[r++];if(!R||R.type!==I)throw new Error(`Parser Error: ${L}. ${R.type} !== ${I}.`);return R}function n(I){if(!l(I))throw new SyntaxError(`Expected ${I}`);++r}function o(){switch(t[r].type){case $.Comment:return new uC(t[r++].value);case $.Text:return u();case $.OpenStatement:return p();case $.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...I){return r+I.length<=t.length&&I.every((L,R)=>L===t[r+R].type)}function i(...I){return t[r]?.type===$.OpenStatement&&t[r+1]?.type===$.Identifier&&I.includes(t[r+1]?.value)}function l(...I){return r+I.length<=t.length&&I.every((L,R)=>t[r+R].type==="Identifier"&&L===t[r+R].value)}function u(){return new tk(s($.Text,"Expected text token").value)}function p(){if(s($.OpenStatement,"Expected opening statement token"),t[r].type!==$.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let I=t[r].value,L;switch(I){case"set":++r,L=m();break;case"if":++r,L=h(),s($.OpenStatement,"Expected {% token"),n("endif"),s($.CloseStatement,"Expected %} token");break;case"macro":++r,L=w(),s($.OpenStatement,"Expected {% token"),n("endmacro"),s($.CloseStatement,"Expected %} token");break;case"for":++r,L=k(),s($.OpenStatement,"Expected {% token"),n("endfor"),s($.CloseStatement,"Expected %} token");break;case"call":{++r;let R=null;a($.OpenParen)&&(R=V());let te=ae();if(te.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let pe=V();s($.CloseStatement,"Expected closing statement token");let Fe=[];for(;!i("endcall");)Fe.push(o());s($.OpenStatement,"Expected '{%'"),n("endcall"),s($.CloseStatement,"Expected closing statement token");let Pe=new ek(te,pe);L=new EC(Pe,R,Fe);break}case"break":++r,s($.CloseStatement,"Expected closing statement token"),L=new aC;break;case"continue":++r,s($.CloseStatement,"Expected closing statement token"),L=new iC;break;case"filter":{++r;let R=ae();R instanceof Ys&&a($.OpenParen)&&(R=H(R)),s($.CloseStatement,"Expected closing statement token");let te=[];for(;!i("endfilter");)te.push(o());s($.OpenStatement,"Expected '{%'"),n("endfilter"),s($.CloseStatement,"Expected '%}'"),L=new gC(R,te);break}default:throw new SyntaxError(`Unknown statement type: ${I}`)}return L}function f(){s($.OpenExpression,"Expected opening expression token");let I=E();return s($.CloseExpression,"Expected closing expression token"),I}function m(){let I=x(),L=null,R=[];if(a($.Equals))++r,L=x();else{for(s($.CloseStatement,"Expected %} token");!i("endset");)R.push(o());s($.OpenStatement,"Expected {% token"),n("endset")}return s($.CloseStatement,"Expected closing statement token"),new lC(I,L,R)}function h(){let I=E();s($.CloseStatement,"Expected closing statement token");let L=[],R=[];for(;!i("elif","else","endif");)L.push(o());if(i("elif")){++r,++r;let te=h();R.push(te)}else if(i("else"))for(++r,++r,s($.CloseStatement,"Expected closing statement token");!i("endif");)R.push(o());return new nC(I,L,R)}function w(){let I=ae();if(I.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let L=V();s($.CloseStatement,"Expected closing statement token");let R=[];for(;!i("endmacro");)R.push(o());return new cC(I,L,R)}function x(I=!1){let L=I?ae:E,R=[L()],te=a($.Comma);for(;te&&(++r,R.push(L()),!!a($.Comma)););return te?new rk(R):R[0]}function k(){let I=x(!0);if(!(I instanceof Ys||I instanceof rk))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${I.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let L=E();s($.CloseStatement,"Expected closing statement token");let R=[];for(;!i("endfor","else");)R.push(o());let te=[];if(i("else"))for(++r,++r,s($.CloseStatement,"Expected closing statement token");!i("endfor");)te.push(o());return new oC(I,L,R,te)}function E(){return A()}function A(){let I=S();if(l("if")){++r;let L=S();if(l("else")){++r;let R=A();return new AC(L,I,R)}else return new wC(I,L)}return I}function S(){let I=T();for(;l("or");){let L=t[r];++r;let R=T();I=new Xn(L,I,R)}return I}function T(){let I=P();for(;l("and");){let L=t[r];++r;let R=P();I=new Xn(L,I,R)}return I}function P(){let I;for(;l("not");){let L=t[r];++r;let R=P();I=new yC(L,R)}return I??C()}function C(){let I=v();for(;;){let L;if(l("not","in"))L=new Ut("not in",$.Identifier),r+=2;else if(l("in"))L=t[r++];else if(a($.ComparisonBinaryOperator))L=t[r++];else break;let R=v();I=new Xn(L,I,R)}return I}function v(){let I=U();for(;a($.AdditiveBinaryOperator);){let L=t[r];++r;let R=U();I=new Xn(L,I,R)}return I}function F(){let I=Y(ae());return a($.OpenParen)?H(I):I}function H(I){let L=new ek(I,V());return L=Y(L),a($.OpenParen)&&(L=H(L)),L}function V(){s($.OpenParen,"Expected opening parenthesis for arguments list");let I=J();return s($.CloseParen,"Expected closing parenthesis for arguments list"),I}function J(){let I=[];for(;!a($.CloseParen);){let L;if(t[r].type===$.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let R=E();L=new kC(R)}else if(L=E(),a($.Equals)){if(++r,!(L instanceof Ys))throw new SyntaxError("Expected identifier for keyword argument");let R=E();L=new vC(L,R)}I.push(L),a($.Comma)&&++r}return I}function X(){let I=[],L=!1;for(;!a($.CloseSquareBracket);)a($.Colon)?(I.push(void 0),++r,L=!0):(I.push(E()),a($.Colon)&&(++r,L=!0));if(I.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(L){if(I.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new bC(...I)}return I[0]}function Y(I){for(;a($.Dot)||a($.OpenSquareBracket);){let L=t[r];++r;let R,te=L.type===$.OpenSquareBracket;if(te)R=X(),s($.CloseSquareBracket,"Expected closing square bracket");else if(R=ae(),R.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");I=new pC(I,R,te)}return I}function U(){let I=z();for(;a($.MultiplicativeBinaryOperator);){let L=t[r++],R=z();I=new Xn(L,I,R)}return I}function z(){let I=ne();for(;l("is");){++r;let L=l("not");L&&++r;let R=ae();if(!(R instanceof Ys))throw new SyntaxError("Expected identifier for the test");I=new xC(I,L,R)}return I}function ne(){let I=F();for(;a($.Pipe);){++r;let L=ae();if(!(L instanceof Ys))throw new SyntaxError("Expected identifier for the filter");a($.OpenParen)&&(L=H(L)),I=new _C(I,L)}return I}function ae(){let I=t[r++];switch(I.type){case $.NumericLiteral:{let L=I.value;return L.includes(".")?new fC(Number(L)):new dC(Number(L))}case $.StringLiteral:{let L=I.value;for(;a($.StringLiteral);)L+=t[r++].value;return new tk(L)}case $.Identifier:return new Ys(I.value);case $.OpenParen:{let L=x();return s($.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),L}case $.OpenSquareBracket:{let L=[];for(;!a($.CloseSquareBracket);)L.push(E()),a($.Comma)&&++r;return++r,new mC(L)}case $.OpenCurlyBracket:{let L=new Map;for(;!a($.CloseCurlyBracket);){let R=E();s($.Colon,"Expected colon between key and value in object literal");let te=E();L.set(R,te),a($.Comma)&&++r}return++r,new hC(L)}default:throw new SyntaxError(`Unexpected token: ${I.type}`)}}for(;r<t.length;)e.body.push(o());return e}function TC(t,e,r=1){if(e===void 0&&(e=t,t=0),r===0)throw new Error("range() step must not be zero");let s=[];if(r>0)for(let n=t;n<e;n+=r)s.push(n);else for(let n=t;n>e;n+=r)s.push(n);return s}function sk(t,e,r,s=1){let n=Math.sign(s);n>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));let o=[];for(let a=e;n*a<n*r;a+=s)o.push(t[a]);return o}function SC(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}function OC(t){return IC(new Date,t)}function IC(t,e){let r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),n=o=>o<10?"0"+o:o.toString();return e.replace(/%[YmdbBHM%]/g,o=>{switch(o){case"%Y":return t.getFullYear().toString();case"%m":return n(t.getMonth()+1);case"%d":return n(t.getDate());case"%b":return s.format(t);case"%B":return r.format(t);case"%H":return n(t.getHours());case"%M":return n(t.getMinutes());case"%%":return"%";default:return o}})}function CC(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function PC(t,e,r,s){if(s===0)return t;let n=s==null||s<0?1/0:s,o=e.length===0?new RegExp("(?=)","gu"):new RegExp(CC(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var nk=class extends Error{},ok=class extends Error{},or=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new ce(!!this.value)}toString(){return String(this.value)}},me=class extends or{type="IntegerValue"},Ye=class extends or{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},ee=class extends or{type="StringValue";builtins=new Map([["upper",new Ge(()=>new ee(this.value.toUpperCase()))],["lower",new Ge(()=>new ee(this.value.toLowerCase()))],["strip",new Ge(()=>new ee(this.value.trim()))],["title",new Ge(()=>new ee(SC(this.value)))],["capitalize",new Ge(()=>new ee(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new me(this.value.length)],["rstrip",new Ge(()=>new ee(this.value.trimEnd()))],["lstrip",new Ge(()=>new ee(this.value.trimStart()))],["startswith",new Ge(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof ee)return new ce(this.value.startsWith(e.value));if(e instanceof ve){for(let r of e.value){if(!(r instanceof ee))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new ce(!0)}return new ce(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Ge(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof ee)return new ce(this.value.endsWith(e.value));if(e instanceof ve){for(let r of e.value){if(!(r instanceof ee))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new ce(!0)}return new ce(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Ge(t=>{let e=t[0]??new We;if(!(e instanceof ee||e instanceof We))throw new Error("sep argument must be a string or null");let r=t[1]??new me(-1);if(!(r instanceof me))throw new Error("maxsplit argument must be a number");let s=[];if(e instanceof We){let n=this.value.trimStart();for(let{0:o,index:a}of n.matchAll(/\S+/g)){if(r.value!==-1&&s.length>=r.value&&a!==void 0){s.push(o+n.slice(a+o.length));break}s.push(o)}}else{if(e.value==="")throw new Error("empty separator");s=this.value.split(e.value),r.value!==-1&&s.length>r.value&&s.push(s.splice(r.value).join(e.value))}return new ve(s.map(n=>new ee(n)))})],["replace",new Ge(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],r=t[1];if(!(e instanceof ee&&r instanceof ee))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new We:s=t[2]:s=new We,!(s instanceof me||s instanceof We))throw new Error("replace() count argument must be a number or null");return new ee(PC(this.value,e.value,r.value,s.value))})]])},ce=class extends or{type="BooleanValue"},zC=/[\x7f-\uffff]/g;function ak(t){return t.replace(zC,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function fs(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,u;switch(a?[l,u]=a:n?(l=",",u=": "):(l=", ",u=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let p=JSON.stringify(t.value);return o&&(p=ak(p)),p}case"ArrayValue":case"ObjectValue":{let p=n?" ".repeat(n):"",f=`
5
+ `+p.repeat(r),m=f+p;if(t.type==="ArrayValue"){let h=t.value.map(w=>fs(w,e,r+1,s));return n?`[${m}${h.join(`${l}${m}`)}${f}]`:`[${h.join(l)}]`}else{let h=Array.from(t.value.entries());i&&(h=h.sort(([x],[k])=>x.localeCompare(k)));let w=h.map(([x,k])=>{let E=JSON.stringify(x);o&&(E=ak(E));let A=`${E}${u}${fs(k,e,r+1,s)}`;return n?`${m}${A}`:A});return n?`{${w.join(l)}${f}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${t.type}`)}}var gt=class extends or{type="ObjectValue";__bool__(){return new ce(this.value.size>0)}builtins=new Map([["get",new Ge(([t,e])=>{if(!(t instanceof ee))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new We})],["items",new Ge(()=>this.items())],["keys",new Ge(()=>this.keys())],["values",new Ge(()=>this.values())],["dictsort",new Ge(t=>{let e=new Map,r=t.filter(i=>i instanceof Kn?(e=i.value,!1):!0),s=r.at(0)??e.get("case_sensitive")??new ce(!1);if(!(s instanceof ce))throw new Error("case_sensitive must be a boolean");let n=r.at(1)??e.get("by")??new ee("key");if(!(n instanceof ee))throw new Error("by must be a string");if(!["key","value"].includes(n.value))throw new Error("by must be either 'key' or 'value'");let o=r.at(2)??e.get("reverse")??new ce(!1);if(!(o instanceof ce))throw new Error("reverse must be a boolean");let a=Array.from(this.value.entries()).map(([i,l])=>new ve([new ee(i),l])).sort((i,l)=>{let u=n.value==="key"?0:1,p=i.value[u],f=l.value[u],m=jp(p,f,s.value);return o.value?-m:m});return new ve(a)})]]);items(){return new ve(Array.from(this.value.entries()).map(([t,e])=>new ve([new ee(t),e])))}keys(){return new ve(Array.from(this.value.keys()).map(t=>new ee(t)))}values(){return new ve(Array.from(this.value.values()))}toString(){return fs(this,{},0,!1)}},Kn=class extends gt{type="KeywordArgumentsValue"},ve=class extends or{type="ArrayValue";builtins=new Map([["length",new me(this.value.length)]]);__bool__(){return new ce(this.value.length>0)}toString(){return fs(this,{},0,!1)}},ik=class extends ve{type="TupleValue"},Ge=class extends or{type="FunctionValue"},We=class extends or{type="NullValue"},je=class extends or{type="UndefinedValue"},ds=class{constructor(t){this.parent=t}variables=new Map([["namespace",new Ge(t=>{if(t.length===0)return new gt(new Map);if(t.length!==1||!(t[0]instanceof gt))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]})]]);tests=new Map([["boolean",t=>t.type==="BooleanValue"],["callable",t=>t instanceof Ge],["odd",t=>{if(!(t instanceof me))throw new Error(`cannot odd on ${t.type}`);return t.value%2!==0}],["even",t=>{if(!(t instanceof me))throw new Error(`cannot even on ${t.type}`);return t.value%2===0}],["false",t=>t.type==="BooleanValue"&&!t.value],["true",t=>t.type==="BooleanValue"&&t.value],["none",t=>t.type==="NullValue"],["string",t=>t.type==="StringValue"],["number",t=>t instanceof me||t instanceof Ye],["integer",t=>t instanceof me],["iterable",t=>t.type==="ArrayValue"||t.type==="StringValue"],["mapping",t=>t.type==="ObjectValue"],["lower",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toLowerCase()}],["upper",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toUpperCase()}],["none",t=>t.type==="NullValue"],["defined",t=>t.type!=="UndefinedValue"],["undefined",t=>t.type==="UndefinedValue"],["equalto",(t,e)=>t.value===e.value],["eq",(t,e)=>t.value===e.value]]);set(t,e){return this.declareVariable(t,Ml(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new je}catch{return new je}}};function LC(t){t.set("false",!1),t.set("true",!0),t.set("none",null),t.set("raise_exception",e=>{throw new Error(e)}),t.set("range",TC),t.set("strftime_now",OC),t.set("True",!0),t.set("False",!1),t.set("None",null)}function lk(t,e){let r=e.split("."),s=t;for(let n of r)if(s instanceof gt)s=s.value.get(n)??new je;else if(s instanceof ve){let o=parseInt(n,10);if(!isNaN(o)&&o>=0&&o<s.value.length)s=s.value[o];else return new je}else return new je;return s}function jp(t,e,r=!1){if(t instanceof We&&e instanceof We)return 0;if(t instanceof We||e instanceof We)throw new Error(`Cannot compare ${t.type} with ${e.type}`);if(t instanceof je&&e instanceof je)return 0;if(t instanceof je||e instanceof je)throw new Error(`Cannot compare ${t.type} with ${e.type}`);let s=o=>o instanceof me||o instanceof Ye||o instanceof ce,n=o=>o instanceof ce?o.value?1:0:o.value;if(s(t)&&s(e)){let o=n(t),a=n(e);return o<a?-1:o>a?1:0}if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);if(t.type==="StringValue"){let o=t.value,a=e.value;return r||(o=o.toLowerCase(),a=a.toLowerCase()),o<a?-1:o>a?1:0}else throw new Error(`Cannot compare type: ${t.type}`)}var NC=class{global;constructor(t){this.global=t??new ds}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){let r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}let s=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new ce(r.value==s.value);case"!=":return new ce(r.value!=s.value)}if(r instanceof je||s instanceof je){if(s instanceof je&&["in","not in"].includes(t.operator.value))return new ce(t.operator.value==="not in");throw new Error(`Cannot perform operation ${t.operator.value} on undefined values`)}else{if(r instanceof We||s instanceof We)throw new Error("Cannot perform operation on null values");if(t.operator.value==="~")return new ee(r.value.toString()+s.value.toString());if((r instanceof me||r instanceof Ye)&&(s instanceof me||s instanceof Ye)){let n=r.value,o=s.value;switch(t.operator.value){case"+":case"-":case"*":{let a=t.operator.value==="+"?n+o:t.operator.value==="-"?n-o:n*o;return r instanceof Ye||s instanceof Ye?new Ye(a):new me(a)}case"/":return new Ye(n/o);case"%":{let a=n%o;return r instanceof Ye||s instanceof Ye?new Ye(a):new me(a)}case"<":return new ce(n<o);case">":return new ce(n>o);case">=":return new ce(n>=o);case"<=":return new ce(n<=o)}}else if(r instanceof ve&&s instanceof ve){if(t.operator.value==="+")return new ve(r.value.concat(s.value))}else if(s instanceof ve){let n=s.value.find(o=>o.value===r.value)!==void 0;switch(t.operator.value){case"in":return new ce(n);case"not in":return new ce(!n)}}}if((r instanceof ee||s instanceof ee)&&t.operator.value==="+")return new ee(r.value.toString()+s.value.toString());if(r instanceof ee&&s instanceof ee)switch(t.operator.value){case"in":return new ce(s.value.includes(r.value));case"not in":return new ce(!s.value.includes(r.value))}if(r instanceof ee&&s instanceof gt)switch(t.operator.value){case"in":return new ce(s.value.has(r.value));case"not in":return new ce(!s.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${s.type}`)}evaluateArguments(t,e){let r=[],s=new Map;for(let n of t)if(n.type==="SpreadExpression"){let o=n,a=this.evaluate(o.argument,e);if(!(a instanceof ve))throw new Error(`Cannot unpack non-iterable type: ${a.type}`);for(let i of a.value)r.push(i)}else if(n.type==="KeywordArgumentExpression"){let o=n;s.set(o.key.value,this.evaluate(o.value,e))}else{if(s.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(n,e))}return[r,s]}applyFilter(t,e,r){if(e.type==="Identifier"){let s=e;if(s.value==="tojson")return new ee(fs(t,{}));if(t instanceof ve)switch(s.value){case"list":return t;case"first":return t.value[0];case"last":return t.value[t.value.length-1];case"length":return new me(t.value.length);case"reverse":return new ve(t.value.slice().reverse());case"sort":return new ve(t.value.slice().sort((n,o)=>jp(n,o,!1)));case"join":return new ee(t.value.map(n=>n.value).join(""));case"string":return new ee(fs(t,{},0,!1));case"unique":{let n=new Set,o=[];for(let a of t.value)n.has(a.value)||(n.add(a.value),o.push(a));return new ve(o)}default:throw new Error(`Unknown ArrayValue filter: ${s.value}`)}else if(t instanceof ee)switch(s.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let n=t.builtins.get(s.value);if(n instanceof Ge)return n.value([],r);if(n instanceof me)return n;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new ee(t.value.trim());case"indent":return new ee(t.value.split(`
6
6
  `).map((n,o)=>o===0||n.length===0?n:" "+n).join(`
7
- `));case"join":case"string":return t;case"int":{let n=parseInt(t.value,10);return new de(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new Ke(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof de||t instanceof Ke)switch(s.value){case"abs":return t instanceof de?new de(Math.abs(t.value)):new Ke(Math.abs(t.value));case"int":return new de(Math.floor(t.value));case"float":return new Ke(t.value);default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(t instanceof ht)switch(s.value){case"items":return new ve(Array.from(t.value.entries()).map(([n,o])=>new ve([new Z(n),o])));case"length":return new de(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof je?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(t instanceof le)switch(s.value){case"bool":return new le(t.value);case"int":return new de(t.value?1:0);case"float":return new Ke(t.value?1:0);case"string":return new Z(t.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${t.type}`)}else if(e.type==="CallExpression"){let s=e;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);let n=s.callee.value;if(n==="tojson"){let[,o]=this.evaluateArguments(s.args,r),a=o.get("indent")??new qe;if(!(a instanceof de||a instanceof qe))throw new Error("If set, indent must be a number");let i=o.get("ensure_ascii")??new le(!1);if(!(i instanceof le))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new le(!1);if(!(l instanceof le))throw new Error("If set, sort_keys must be a boolean");let u=o.get("separators")??new qe,d=null;if(u instanceof ve||u instanceof Pv){if(u.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,m]=u.value;if(!(f instanceof Z)||!(m instanceof Z))throw new Error("separators must be a tuple of two strings");d=[f.value,m.value]}else if(!(u instanceof qe))throw new Error("If set, separators must be a tuple of two strings");return new Z(es(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:d}))}else if(n==="join"){let o;if(t instanceof Z)o=Array.from(t.value);else if(t instanceof ve)o=t.value.map(u=>u.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[a,i]=this.evaluateArguments(s.args,r),l=a.at(0)??i.get("separator")??new Z("");if(!(l instanceof Z))throw new Error("separator must be a string");return new Z(o.join(l.value))}else if(n==="int"||n==="float"){let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("default")??(n==="int"?new de(0):new Ke(0));if(t instanceof Z){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new de(l):new Ke(l)}else{if(t instanceof de||t instanceof Ke)return t;if(t instanceof le)return n==="int"?new de(t.value?1:0):new Ke(t.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}}else if(n==="default"){let[o,a]=this.evaluateArguments(s.args,r),i=o[0]??new Z(""),l=o[1]??a.get("boolean")??new le(!1);if(!(l instanceof le))throw new Error("`default` filter flag must be a boolean");return t instanceof Fe||l.value&&!t.__bool__().value?i:t}if(t instanceof ve){switch(n){case"sort":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("reverse")??new le(!1);if(!(i instanceof le))throw new Error("reverse must be a boolean");let l=o.at(1)??a.get("case_sensitive")??new le(!1);if(!(l instanceof le))throw new Error("case_sensitive must be a boolean");let u=o.at(2)??a.get("attribute")??new qe;if(!(u instanceof Z||u instanceof de||u instanceof qe))throw new Error("attribute must be a string, integer, or null");let d=f=>{if(u instanceof qe)return f;let m=u instanceof de?String(u.value):u.value;return zv(f,m)};return new ve(t.value.slice().sort((f,m)=>{let _=d(f),w=d(m),x=gp(_,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!(f instanceof ht)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[a,i,l]=s.args.map(f=>this.evaluate(f,r)),u;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);u=f}else u=(...f)=>f[0].__bool__().value;let d=t.value.filter(f=>{let m=f.value.get(a.value),_=m?u(m,l):!1;return o?_:!_});return new ve(d)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof Z))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(u=>{if(!(u instanceof ht))throw new Error("items in map must be an object");let d=zv(u,a.value);return d instanceof Fe?i??new Fe:d});return new ve(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof Z){switch(n){case"indent":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("width")??new de(4);if(!(i instanceof de))throw new Error("width must be a number");let l=o.at(1)??a.get("first")??new le(!1),u=o.at(2)??a.get("blank")??new le(!1),d=t.value.split(`
8
- `),f=" ".repeat(i.value),m=d.map((_,w)=>!l.value&&w===0||!u.value&&_.length===0?_:f+_);return new Z(m.join(`
9
- `))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof je))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new Rn(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof ht){let o=t.builtins.get(n);if(o&&o instanceof je){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new Rn(i)),o.value(a,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}throw new Error(`Unknown filter: ${e.type}`)}evaluateFilterExpression(t,e){let r=this.evaluate(t.operand,e);return this.applyFilter(r,t.filter,e)}evaluateTestExpression(t,e){let r=this.evaluate(t.operand,e),s=e.tests.get(t.test.value);if(!s)throw new Error(`Unknown test: ${t.test.value}`);let n=s(r);return new le(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new Fe}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);if(t.operator.value==="not")return new le(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evaluateTernaryExpression(t,e){return this.evaluate(t.condition,e).__bool__().value?this.evaluate(t.trueExpr,e):this.evaluate(t.falseExpr,e)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(let s of t){let n=this.evaluate(s,e);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new Z(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){let[r,s]=this.evaluateArguments(t.args,e);s.size>0&&r.push(new Rn(s));let n=this.evaluate(t.callee,e);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof ve||t instanceof Z))throw new Error("Slice object must be an array or string");let s=this.evaluate(e.start,r),n=this.evaluate(e.stop,r),o=this.evaluate(e.step,r);if(!(s instanceof de||s instanceof Fe))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof de||n instanceof Fe))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof de||o instanceof Fe))throw new Error("Slice step must be numeric or undefined");return t instanceof ve?new ve(Sv(t.value,s.value,n.value,o.value)):new Z(Sv(Array.from(t.value),s.value,n.value,o.value).join(""))}evaluateMemberExpression(t,e){let r=this.evaluate(t.object,e),s;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);s=this.evaluate(t.property,e)}else s=new Z(t.property.value);let n;if(r instanceof ht){if(!(s instanceof Z))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof ve||r instanceof Z)if(s instanceof de)n=r.value.at(s.value),r instanceof Z&&(n=new Z(r.value.at(s.value)));else if(s instanceof Z)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof Z))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof sr?n:new Fe}evaluateSet(t,e){let r=t.value?this.evaluate(t.value,e):this.evaluateBlock(t.body,e);if(t.assignee.type==="Identifier"){let s=t.assignee.value;e.setVariable(s,r)}else if(t.assignee.type==="TupleLiteral"){let s=t.assignee;if(!(r instanceof ve))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let o=0;o<s.value.length;++o){let a=s.value[o];if(a.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${a.type}`);e.setVariable(a.value,n[o])}}else if(t.assignee.type==="MemberExpression"){let s=t.assignee,n=this.evaluate(s.object,e);if(!(n instanceof ht))throw new Error("Cannot assign to member of non-object");if(s.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");n.value.set(s.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);return new qe}evaluateIf(t,e){let r=this.evaluate(t.test,e);return this.evaluateBlock(r.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){let r=new Zr(e),s,n;if(t.iterable.type==="SelectExpression"){let u=t.iterable;n=this.evaluate(u.lhs,r),s=u.test}else n=this.evaluate(t.iterable,r);if(!(n instanceof ve||n instanceof ht))throw new Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof ht&&(n=n.keys());let o=[],a=[];for(let u=0;u<n.value.length;++u){let d=new Zr(r),f=n.value[u],m;if(t.loopvar.type==="Identifier")m=_=>_.setVariable(t.loopvar.value,f);else if(t.loopvar.type==="TupleLiteral"){let _=t.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);let w=f;if(_.value.length!==w.value.length)throw new Error(`Too ${_.value.length>w.value.length?"few":"many"} items to unpack`);m=x=>{for(let k=0;k<_.value.length;++k){if(_.value[k].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${_.value[k].type}`);x.setVariable(_.value[k].value,w.value[k])}}}else throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);s&&(m(d),!this.evaluate(s,d).__bool__().value)||(o.push(f),a.push(m))}let i="",l=!0;for(let u=0;u<o.length;++u){let d=new Map([["index",new de(u+1)],["index0",new de(u)],["revindex",new de(o.length-u)],["revindex0",new de(o.length-u-1)],["first",new le(u===0)],["last",new le(u===o.length-1)],["length",new de(o.length)],["previtem",u>0?o[u-1]:new Fe],["nextitem",u<o.length-1?o[u+1]:new Fe]]);r.setVariable("loop",new ht(d)),a[u](r);try{let f=this.evaluateBlock(t.body,r);i+=f.value}catch(f){if(f instanceof Iv)continue;if(f instanceof Ov)break;throw f}l=!1}if(l){let u=this.evaluateBlock(t.defaultBlock,r);i+=u.value}return new Z(i)}evaluateMacro(t,e){return e.setVariable(t.name.value,new je((r,s)=>{let n=new Zr(s);r=r.slice();let o;r.at(-1)?.type==="KeywordArgumentsValue"&&(o=r.pop());for(let a=0;a<t.args.length;++a){let i=t.args[a],l=r[a];if(i.type==="Identifier"){let u=i;if(!l)throw new Error(`Missing positional argument: ${u.value}`);n.setVariable(u.value,l)}else if(i.type==="KeywordArgumentExpression"){let u=i,d=l??o?.value.get(u.key.value)??this.evaluate(u.value,n);n.setVariable(u.key.value,d)}else throw new Error(`Unknown argument type: ${i.type}`)}return this.evaluateBlock(t.body,n)})),new qe}evaluateCallStatement(t,e){let r=new je((i,l)=>{let u=new Zr(l);if(t.callerArgs)for(let d=0;d<t.callerArgs.length;++d){let f=t.callerArgs[d];if(f.type!=="Identifier")throw new Error(`Caller parameter must be an identifier, got ${f.type}`);u.setVariable(f.value,i[d]??new Fe)}return this.evaluateBlock(t.body,u)}),[s,n]=this.evaluateArguments(t.call.args,e);s.push(new Rn(n));let o=this.evaluate(t.call.callee,e);if(o.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${o.type}`);let a=new Zr(e);return a.setVariable("caller",r),o.value(s,a)}evaluateFilterStatement(t,e){let r=this.evaluateBlock(t.body,e);return this.applyFilter(r,t.filter,e)}evaluate(t,e){if(!t)return new Fe;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"Macro":return this.evaluateMacro(t,e);case"CallStatement":return this.evaluateCallStatement(t,e);case"Break":throw new Ov;case"Continue":throw new Iv;case"IntegerLiteral":return new de(t.value);case"FloatLiteral":return new Ke(t.value);case"StringLiteral":return new Z(t.value);case"ArrayLiteral":return new ve(t.value.map(r=>this.evaluate(r,e)));case"TupleLiteral":return new Pv(t.value.map(r=>this.evaluate(r,e)));case"ObjectLiteral":{let r=new Map;for(let[s,n]of t.value){let o=this.evaluate(s,e);if(!(o instanceof Z))throw new Error(`Object keys must be strings: got ${o.type}`);r.set(o.value,this.evaluate(n,e))}return new ht(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"FilterStatement":return this.evaluateFilterStatement(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);case"SelectExpression":return this.evaluateSelectExpression(t,e);case"Ternary":return this.evaluateTernaryExpression(t,e);case"Comment":return new qe;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Bi(t){switch(typeof t){case"number":return Number.isInteger(t)?new de(t):new Ke(t);case"string":return new Z(t);case"boolean":return new le(t);case"undefined":return new Fe;case"object":return t===null?new qe:Array.isArray(t)?new ve(t.map(Bi)):new ht(new Map(Object.entries(t).map(([e,r])=>[e,Bi(r)])));case"function":return new je((e,r)=>{let s=t(...e.map(n=>n.value))??null;return Bi(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var nt=`
10
- `,eC="{%- ",tC=" -%}";function rC(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function sC(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Ht(t.body,0,r).replace(/\n$/,"")}function pt(...t){return eC+t.join(" ")+tC}function Ht(t,e,r){return t.map(s=>nC(s,e,r)).join(nt)}function nC(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Ht(t.body,e,r);case"If":return oC(t,e,r);case"For":return aC(t,e,r);case"Set":return iC(t,e,r);case"Macro":return lC(t,e,r);case"Break":return s+pt("break");case"Continue":return s+pt("continue");case"CallStatement":return cC(t,e,r);case"FilterStatement":return uC(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function oC(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+pt("if",ke(n[0].test))+nt+Ht(n[0].body,e+1,r);for(let i=1;i<n.length;++i)a+=nt+s+pt("elif",ke(n[i].test))+nt+Ht(n[i].body,e+1,r);return o&&o.alternate.length>0&&(a+=nt+s+pt("else")+nt+Ht(o.alternate,e+1,r)),a+=nt+s+pt("endif"),a}function aC(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+pt("for",ke(t.loopvar),"in",n)+nt+Ht(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=nt+s+pt("else")+nt+Ht(t.defaultBlock,e+1,r)),o+=nt+s+pt("endfor"),o}function iC(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+pt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+nt+Ht(t.body,e+1,r)+nt+s+pt("endset")}function lC(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+pt("macro",`${t.name.value}(${n})`)+nt+Ht(t.body,e+1,r)+nt+s+pt("endmacro")}function cC(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+pt(`call${n}`,o)+nt;return a+=Ht(t.body,e+1,r)+nt,a+=s+pt("endcall"),a}function uC(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+pt("filter",n)+nt;return o+=Ht(t.body,e+1,r)+nt,o+=s+pt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=rC(r),n=ke(r.left,s),o=ke(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s<e?`(${a})`:a}case"UnaryExpression":{let r=t;return r.operator.value+(r.operator.value==="not"?" ":"")+ke(r.argument,1/0)}case"CallExpression":{let r=t,s=r.args.map(ke).join(", ");return`${ke(r.callee)}(${s})`}case"MemberExpression":{let r=t,s=ke(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(s=`(${s})`);let n=ke(r.property);return!r.computed&&r.property.type!=="Identifier"&&(n=`(${n})`),r.computed?`${s}[${n}]`:`${s}.${n}`}case"FilterExpression":{let r=t,s=ke(r.operand,1/0);return r.filter.type==="CallExpression"?`${s} | ${ke(r.filter)}`:`${s} | ${r.filter.value}`}case"SelectExpression":{let r=t;return`${ke(r.lhs)} if ${ke(r.test)}`}case"TestExpression":{let r=t;return`${ke(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let r=t.value.map(ke),s=t.type==="ArrayLiteral"?"[]":"()";return`${s[0]}${r.join(", ")}${s[1]}`}case"ObjectLiteral":return`{${Array.from(t.value.entries()).map(([s,n])=>`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var Lv=class{parsed;constructor(t){let e=yI(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=qI(e)}render(t){let e=new Zr;if(JI(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new ZI(e).run(this.parsed).value}format(t){return sC(this.parsed,t?.indent||" ")}};var Je=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function hr(t,e){t&&t(e)}function Nv(t){return Number.isInteger(t)||typeof t=="bigint"}function wp(t){return t==null||t===-1}function xp(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function dt(...t){return Array.prototype.concat.apply([],t)}function $v(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function $s(t,e){return Math.abs((t+e)%(2*e)-e)}function ot(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function Rv(t,e){let r=0;for(let s of t)s===e&&++r;return r}import _r from"fs";import yp from"path";var pC={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"},ts=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=_r.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=_r.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=_r.createReadStream(e);this.body=new ReadableStream({start(n){s.on("data",o=>n.enqueue(o)),s.on("end",()=>n.close()),s.on("error",o=>n.error(o))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",pC[e]??"application/octet-stream")}clone(){let e=new t(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await _r.promises.readFile(this.filePath)).buffer}async blob(){let e=await _r.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await _r.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Rs=class{constructor(e){this.path=e}async match(e){let r=yp.join(this.path,e),s=new ts(r);if(s.exists)return s}async put(e,r,s=void 0){let n=yp.join(this.path,e);try{let o=r.headers.get("Content-Length"),a=parseInt(o??"0"),i=0;await _r.promises.mkdir(yp.dirname(n),{recursive:!0});let l=_r.createWriteStream(n),u=r.body.getReader();for(;;){let{done:d,value:f}=await u.read();if(d)break;await new Promise((_,w)=>{l.write(f,x=>{if(x){w(x);return}_()})}),i+=f.length;let m=a?i/a*100:0;s?.({progress:m,loaded:i,total:a})}l.close()}catch(o){try{await _r.promises.unlink(n)}catch{}throw o}}};var Uv={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"},Di=100,Bv=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Un(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function Us(t,e=null,r=null){let s;try{s=new URL(t)}catch{return!1}return!(e&&!e.includes(s.protocol)||r&&!r.includes(s.hostname))}function Dv(t){return!(!Bv.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function Fv(t,e,r){if(!r)return null;let s=Uv[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function jv(t,e){let r=t.headers.get("Content-Length");r===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let s=parseInt(r??"0"),n=new Uint8Array(s),o=0,a=t.body.getReader();async function i(){let{done:l,value:u}=await a.read();if(l)return;let d=o+u.length;if(d>s){s=d;let m=new Uint8Array(s);m.set(n),n=m}n.set(u,o),o=d;let f=o/s*100;return e({progress:f,loaded:o,total:s}),i()}return await i(),n}async function Fi(t=null){let e=null;if(De.useCustomCache){if(!De.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!De.customCache.match||!De.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=De.customCache}if(!e&&De.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(De.cacheKey)}catch(r){console.warn("An error occurred while opening the browser cache:",r)}}if(!e&&De.useFSCache){if(!be.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new Rs(t??De.cacheDir)}return e}async function Gv(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}async function Bs(t){if(De.useFS&&!Us(t,["http:","https:","blob:"]))return new ts(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t);if(typeof process<"u"&&process?.release?.name==="node"){let e=!!process.env?.TESTING_REMOTELY,r=De.version,s=new Headers;if(s.set("User-Agent",`transformers.js/${r}; is_ci/${e};`),Us(t,["http:","https:"],["huggingface.co","hf.co"])){let o=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;o&&s.set("Authorization",`Bearer ${o}`)}return fetch(t,{headers:s})}else return fetch(t)}function dC(t,e,r={},s=null){let n=r.revision??"main",o=Un(t,e),a=Dv(t),i=a?Un(De.localModelPath,o):o,l=Un(De.remoteHost,De.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),u=s instanceof Rs?n==="main"?o:Un(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:a}}async function fC(t,e,r){if(t)return await Gv(t,e,r)}async function mC(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o)typeof n!="string"&&await r.put(s,new Response(o,{headers:n.headers})).catch(i=>{console.warn(`Unable to add response to browser cache: ${i}.`)});else{let i=a.progress_callback?l=>hr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function hC(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:d}=dC(t,e,s,o),f,m=!1,_;_=await fC(o,i,u);let w=_!==void 0;if(!w){if(De.allowLocalModels)if(Us(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!De.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{_=await Bs(i),f=i}catch(M){console.warn(`Unable to load from local path "${i}": "${M}"`)}if(_===void 0||typeof _!="string"&&_.status===404){if(s.local_files_only||!De.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!d)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(_=await Bs(l),_.status!==200)return Fv(_.status,l,r);f=u}m=o&&typeof Response<"u"&&_ instanceof Response&&_.status===200}hr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(be.IS_NODE_ENV&&n)){let E;typeof _!="string"&&(s.progress_callback?w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(E=new Uint8Array(await _.arrayBuffer()),hr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:E.length,total:E.length})):E=await jv(_,M=>{hr(s.progress_callback,{status:"progress",name:t,file:e,...M})}):E=new Uint8Array(await _.arrayBuffer())),x=E}if(m&&f&&typeof _!="string"&&await mC(t,e,o,f,_,x,s),hr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!be.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(_ instanceof ts)return _.filePath;let k=await o?.match(f);if(k instanceof ts)return k.filePath;if(k instanceof Response)return new Uint8Array(await k.arrayBuffer());if(typeof k=="string")return k;throw new Error("Unable to get model file path or buffer.")}async function Bn(t,e,r=!0,s={},n=!1){if(!De.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!De.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}hr(s.progress_callback,{status:"initiate",name:t,file:e});let o=await Fi(s?.cache_dir);return await hC(t,e,r,s,n,o)}async function bp(t,e,r=!0,s={}){let n=await Bn(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function at(t,e,r=!0,s={}){let n=await bp(t,e,r,s);return n===null?{}:JSON.parse(n)}function Wv(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,u=n/r,d=new t.constructor(n*o*e),f=r*s,m=n*o;for(let _=0;_<n;++_)for(let w=0;w<o;++w){let x=_*o+w,k=(w+.5)/l-.5,E=(_+.5)/u-.5,M=Math.floor(k),I=Math.floor(E),T=Math.min(M+1,s-1),z=Math.min(I+1,r-1);M=Math.max(M,0),I=Math.max(I,0);let C=k-M,v=E-I,G=(1-C)*(1-v),X=C*(1-v),V=(1-C)*v,Q=C*v,K=I*s,Y=z*s,B=K+M,P=K+T,se=Y+M,ie=Y+T;for(let S=0;S<e;++S){let L=S*f;d[S*m+x]=G*t[L+B]+X*t[L+P]+V*t[L+se]+Q*t[L+ie]}}return d}function Vv(t,e,r){let s=new Array(r.length),n=new Array(r.length);for(let i=r.length-1,l=1;i>=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i<t.length;++i){let l=0;for(let u=e.length-1,d=i;u>=0;--u)l+=d%e[u]*o[u],d=Math.floor(d/e[u]);a[l]=t[i]}return[a,s]}function Pe(t){let e=Te(t)[0],r=t.map(o=>Math.exp(o-e)),s=r.reduce((o,a)=>o+a,0);return r.map(o=>o/s)}function kp(t){let e=Te(t)[0],r=0;for(let o=0;o<t.length;++o)r+=Math.exp(t[o]-e);let s=Math.log(r);return t.map(o=>o-e-s)}function Hv(t,e){let r=0;for(let s=0;s<t.length;++s)r+=t[s]*e[s];return r}function _C(t,e){let r=Hv(t,e),s=qv(t),n=qv(e);return r/(s*n)}function qv(t){return Math.sqrt(t.reduce((e,r)=>e+r*r,0))}function Dn(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]<e&&(e=t[s],r=s);return[e,r]}function Te(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]>e&&(e=t[s],r=s);return[e,r]}function Xv(t){return t>0&&(t&t-1)===0}var ji=class{constructor(e){if(this.size=e|0,this.size<=1||!Xv(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;s<this.table.length;s+=2){let n=Math.PI*s/this.size;this.table[s]=Math.cos(n),this.table[s+1]=-Math.sin(n)}let r=0;for(let s=1;this.size>s;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<<this._width);for(let s=0;s<this._bitrev.length;++s){this._bitrev[s]=0;for(let n=0;n<this._width;n+=2){let o=this._width-n-2;this._bitrev[s]|=(s>>>n&3)<<o}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,r){let s=r||new Array(e.length>>>1);for(let n=0;n<e.length;n+=2)s[n>>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n<s.length;n+=2)s[n]=e[n>>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s<e.length;++s)e[s]/=this.size}_transform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,u,d=this._bitrev;if(i===4)for(l=0,u=0;l<n;l+=i,++u){let m=d[u];this._singleTransform2(r,e,l,m,a)}else for(l=0,u=0;l<n;l+=i,++u){let m=d[u];this._singleTransform4(r,e,l,m,a,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>2;for(l=0;l<n;l+=i){let _=l+m-1;for(let w=l,x=0;w<_;w+=2,x+=a){let k=w,E=k+m,M=E+m,I=M+m,T=e[k],z=e[k+1],C=e[E],v=e[E+1],G=e[M],X=e[M+1],V=e[I],Q=e[I+1],K=f[x],Y=s*f[x+1],B=C*K-v*Y,P=C*Y+v*K,se=f[2*x],ie=s*f[2*x+1],S=G*se-X*ie,L=G*ie+X*se,R=f[3*x],te=s*f[3*x+1],ue=V*R-Q*te,Be=V*te+Q*R,Ce=T+S,vt=z+L,Qe=T-S,Ze=z-L,rt=B+ue,Me=P+Be,xe=s*(B-ue),Ge=s*(P-Be);e[k]=Ce+rt,e[k+1]=vt+Me,e[E]=Qe+Ge,e[E+1]=Ze-xe,e[M]=Ce-rt,e[M+1]=vt-Me,e[I]=Qe-Ge,e[I+1]=Ze+xe}}}}_singleTransform2(e,r,s,n,o){let a=e[n],i=e[n+1],l=e[n+o],u=e[n+o+1];r[s]=a+l,r[s+1]=i+u,r[s+2]=a-l,r[s+3]=i-u}_singleTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,u=e[n],d=e[n+1],f=e[n+o],m=e[n+o+1],_=e[n+i],w=e[n+i+1],x=e[n+l],k=e[n+l+1],E=u+_,M=d+w,I=u-_,T=d-w,z=f+x,C=m+k,v=a*(f-x),G=a*(m-k);r[s]=E+z,r[s+1]=M+C,r[s+2]=I+G,r[s+3]=T-v,r[s+4]=E-z,r[s+5]=M-C,r[s+6]=I-G,r[s+7]=T+v}_realTransform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,u,d=this._bitrev;if(i===4)for(l=0,u=0;l<n;l+=i,++u){let _=d[u];this._singleRealTransform2(r,e,l,_>>>1,a>>>1)}else for(l=0,u=0;l<n;l+=i,++u){let _=d[u];this._singleRealTransform4(r,e,l,_>>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>1,w=_>>>1,x=w>>>1;for(l=0;l<n;l+=i)for(let k=0,E=0;k<=x;k+=2,E+=a){let M=l+k,I=M+w,T=I+w,z=T+w,C=e[M],v=e[M+1],G=e[I],X=e[I+1],V=e[T],Q=e[T+1],K=e[z],Y=e[z+1],B=C,P=v,se=f[E],ie=s*f[E+1],S=G*se-X*ie,L=G*ie+X*se,R=f[2*E],te=s*f[2*E+1],ue=V*R-Q*te,Be=V*te+Q*R,Ce=f[3*E],vt=s*f[3*E+1],Qe=K*Ce-Y*vt,Ze=K*vt+Y*Ce,rt=B+ue,Me=P+Be,xe=B-ue,Ge=P-Be,kt=S+Qe,ge=L+Ze,Le=s*(S-Qe),xr=s*(L-Ze);if(e[M]=rt+kt,e[M+1]=Me+ge,e[I]=xe+xr,e[I+1]=Ge-Le,k===0){e[T]=rt-kt,e[T+1]=Me-ge;continue}if(k===x)continue;let Hr=l+w-k,Et=l+_-k;e[Hr]=xe-s*xr,e[Hr+1]=-Ge-s*Le,e[Et]=rt-s*kt,e[Et+1]=-Me+s*ge}}let m=n>>>1;for(let _=2;_<m;_+=2)e[n-_]=e[_],e[n-_+1]=-e[_+1]}_singleRealTransform2(e,r,s,n,o){let a=e[n],i=e[n+o];r[s]=a+i,r[s+1]=0,r[s+2]=a-i,r[s+3]=0}_singleRealTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,u=e[n],d=e[n+o],f=e[n+i],m=e[n+l],_=u+f,w=u-f,x=d+m,k=a*(d-m);r[s]=_+x,r[s+1]=0,r[s+2]=w,r[s+3]=-k,r[s+4]=_-x,r[s+5]=0,r[s+6]=w,r[s+7]=k}},vp=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let i=-2*Math.PI/e,l=Math.cos(i),u=Math.sin(i);for(let d=0;d<s>>1;++d){let f=(d+1-e)**2/2,m=Math.sqrt(l**2+u**2)**f,_=f*Math.atan2(u,l),w=2*d;o[w]=m*Math.cos(_),o[w+1]=m*Math.sin(_),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new ji(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,u=this._slicedChirpBuffer,d=this._a;if(s)for(let f=0;f<u.length;f+=2){let m=f+1,_=f>>1,w=r[_];n[f]=w*u[f],n[m]=w*u[m]}else for(let f=0;f<u.length;f+=2){let m=f+1;n[f]=r[f]*u[f]-r[m]*u[m],n[m]=r[f]*u[m]+r[m]*u[f]}this._f.transform(a,n);for(let f=0;f<l.length;f+=2){let m=f+1;o[f]=a[f]*l[f]-a[m]*l[m],o[m]=a[f]*l[m]+a[m]*l[f]}this._f.inverseTransform(i,o);for(let f=0;f<i.length;f+=2){let m=i[f+d],_=i[f+d+1],w=u[f],x=u[f+1];e[f]=m*w-_*x,e[f+1]=m*x+_*w}}transform(e,r){this._transform(e,r,!1)}realTransform(e,r){this._transform(e,r,!0)}},Gi=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=Xv(e),this.isPowerOfTwo?(this.fft=new ji(e),this.outputBufferSize=2*e):(this.fft=new vp(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,r){this.fft.realTransform(e,r)}transform(e,r){this.fft.transform(e,r)}};function Kv(t,e){if(e%2===0||e<=0)throw new Error("Window size must be a positive odd number");let r=new t.constructor(t.length),s=new t.constructor(e),n=Math.floor(e/2);for(let o=0;o<t.length;++o){let a=0;for(let i=-n;i<=n;++i){let l=o+i;l<0?l=Math.abs(l):l>=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function rs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function Yv(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function Qv(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let d=1;d<s[1];++d)for(let f=1;f<s[0];++f){let m=n[f-1][d-1],_=n[f-1][d],w=n[f][d-1],x,k;m<_&&m<w?(x=m,k=0):_<m&&_<w?(x=_,k=1):(x=w,k=2),n[f][d]=t[f-1][d-1]+x,o[f][d]=k}for(let d=0;d<s[1];++d)o[0][d]=2;for(let d=0;d<s[0];++d)o[d][0]=1;let a=e,i=r,l=[],u=[];for(;a>0||i>0;)switch(l.push(a-1),u.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),u.reverse(),[l,u]}var Jv=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l<t.length;++l){let u=0,d=(l&32768)<<16,f=(l&31744)>>10,m=l&1023;if(f===31)u=d|2139095040|m<<13;else if(f===0)if(m===0)u=d;else{let _=113;for(;(m&1024)===0;)m<<=1,--_;m&=-1025,u=d|_<<23|m<<13}else u=d|f+112<<23|m<<13;a[0]=u,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;o<r;++o)n[o]=s[e[o]];return n}})();import*as VC from"onnxruntime-node";var fd={};Ps(fd,{InferenceSession:()=>Jp,TRACE:()=>Ji,TRACE_EVENT_BEGIN:()=>Mr,TRACE_EVENT_END:()=>Tr,TRACE_FUNC_BEGIN:()=>ls,TRACE_FUNC_END:()=>cs,Tensor:()=>Kt,default:()=>WC,env:()=>We,registerBackend:()=>is});var Yp=Object.defineProperty,gC=Object.getOwnPropertyDescriptor,wC=Object.getOwnPropertyNames,xC=Object.prototype.hasOwnProperty,yC=(t=>typeof Jr<"u"?Jr:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof Jr<"u"?Jr:e)[r]}):t)(function(t){if(typeof Jr<"u")return Jr.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),ye=(t,e)=>()=>(t&&(e=t(t=0)),e),Xn=(t,e)=>{for(var r in e)Yp(t,r,{get:e[r],enumerable:!0})},bC=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of wC(e))!xC.call(t,n)&&n!==r&&Yp(t,n,{get:()=>e[n],enumerable:!(s=gC(e,n))||s.enumerable});return t},Qi=t=>bC(Yp({},"__esModule",{value:!0}),t),Fn,vr,is,Zv,Mk,Tk=ye(()=>{"use strict";Fn=new Map,vr=[],is=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=Fn.get(t);if(s===void 0)Fn.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=vr.indexOf(t);n!==-1&&vr.splice(n,1);for(let o=0;o<vr.length;o++)if(Fn.get(vr[o]).priority<=r){vr.splice(o,0,t);return}vr.push(t)}return}throw new TypeError("not a valid backend")},Zv=async t=>{let e=Fn.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(s){return r||(e.error=`${s}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},Mk=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?vr:r,n,o=[],a=new Set;for(let l of s){let u=await Zv(l);typeof u=="string"?o.push({name:l,err:u}):(n||(n=u),n===u&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,u)=>u==="executionProviders"?i:Reflect.get(l,u)})]}}),vC=ye(()=>{"use strict";Tk()}),Sk,kC=ye(()=>{"use strict";Sk="1.24.0-dev.20251116-b39e144322"}),Ep,ct,Ok=ye(()=>{"use strict";kC(),Ep="warning",ct={wasm:{},webgl:{},webgpu:{},versions:{common:Sk},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);Ep=t}},get logLevel(){return Ep}},Object.defineProperty(ct,"logLevel",{enumerable:!0})}),We,EC=ye(()=>{"use strict";Ok(),We=ct}),Ik,Ck,AC=ye(()=>{"use strict";Ik=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,u;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?u=[0,0,0,0]:typeof i.bias=="number"?u=[i.bias,i.bias,i.bias,i.bias]:(u=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(u[3]=i.bias[3]));let d=o*n,f=0,m=d,_=d*2,w=-1;a==="RGBA"?(f=0,m=d,_=d*2,w=d*3):a==="RGB"?(f=0,m=d,_=d*2):a==="RBG"&&(f=0,_=d,m=d*2);for(let x=0;x<o;x++)for(let k=0;k<n;k++){let E=(t.data[f++]-u[0])*l[0],M=(t.data[m++]-u[1])*l[1],I=(t.data[_++]-u[2])*l[2],T=w===-1?255:(t.data[w++]-u[3])*l[3];s.fillStyle="rgba("+E+","+M+","+I+","+T+")",s.fillRect(k,x,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Ck=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,u,d;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,k=3,E=0,M=f,I=f*2,T=-1;i==="RGBA"?(E=0,M=f,I=f*2,T=f*3):i==="RGB"?(E=0,M=f,I=f*2):i==="RBG"&&(E=0,I=f,M=f*2),s=r.createImageData(n,o);for(let z=0;z<o*n;_+=m,w+=m,x+=m,k+=m,z++)s.data[_]=(t.data[E++]-d[0])*u[0],s.data[w]=(t.data[M++]-d[1])*u[1],s.data[x]=(t.data[I++]-d[2])*u[2],s.data[k]=T===-1?255:(t.data[T++]-d[3])*u[3]}else throw new Error("Can not access image data");return s}}),qi,Pk,zk,Lk,Nk,$k,MC=ye(()=>{"use strict";Qp(),qi=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",u=r*s,d=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),f=4,m=0,_=1,w=2,x=3,k=0,E=u,M=u*2,I=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?I=u*3:l==="RBG"?(k=0,M=u,E=u*2):l==="BGR"&&(M=0,E=u,k=u*2);for(let T=0;T<u;T++,m+=f,w+=f,_+=f,x+=f)d[k++]=(t[m]+a[0])/o[0],d[E++]=(t[_]+a[1])/o[1],d[M++]=(t[w]+a[2])/o[2],I!==-1&&x!==-1&&(d[I++]=(t[x]+a[3])/o[3]);return l==="RGBA"?new Ct("float32",d,[1,4,r,s]):new Ct("float32",d,[1,3,r,s])},Pk=async(t,e)=>{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){let d=l();d.width=t.width,d.height=t.height;let f=u(d);if(f!=null){let m=t.height,_=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,_=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=_}else i.tensorFormat="RGBA",i.height=m,i.width=_;f.drawImage(t,0,0),a=f.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let d,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(d=e.resizedHeight,f=e.resizedWidth):(d=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=d,i.width=f,e!==void 0){let m=l();m.width=f,m.height=d;let _=u(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,d).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let d=l();d.width=t.width,d.height=t.height;let f=u(d);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,qi(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((d,f)=>{let m=l(),_=u(m);if(!t||!_)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,_.drawImage(w,0,0,m.width,m.height);let x=_.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,d(qi(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return qi(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},zk=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Ct({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},Lk=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Ct({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},Nk=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Ct({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},$k=(t,e,r)=>new Ct({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),os,Vn,Ap,Rk,TC=ye(()=>{"use strict";os=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Vn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Ap=!1,Rk=()=>{if(!Ap){Ap=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(os.set("int64",BigInt64Array),Vn.set(BigInt64Array,"int64")),e&&(os.set("uint64",BigUint64Array),Vn.set(BigUint64Array,"uint64")),s?(os.set("float16",r),Vn.set(r,"float16")):os.set("float16",Uint16Array)}}}),Uk,Bk,SC=ye(()=>{"use strict";Qp(),Uk=t=>{let e=1;for(let r=0;r<t.length;r++){let s=t[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);e*=s}return e},Bk=(t,e)=>{switch(t.location){case"cpu":return new Ct(t.type,t.data,e);case"cpu-pinned":return new Ct({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Ct({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Ct({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Ct({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Ct,Qp=ye(()=>{"use strict";AC(),MC(),TC(),SC(),Ct=class{constructor(t,e,r){Rk();let s,n;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,n=t.dims,t.location){case"cpu-pinned":{let a=os.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,i;if(typeof t=="string")if(s=t,i=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=os.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")s="string",a=t;else if(l==="boolean")s="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(t);else{let l=Vn.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=l,a=t}if(i===void 0)i=[a.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=a,this.dataLocation="cpu"}let o=Uk(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(t,e){return Pk(t,e)}static fromTexture(t,e){return zk(t,e)}static fromGpuBuffer(t,e){return Lk(t,e)}static fromMLTensor(t,e){return Nk(t,e)}static fromPinnedBuffer(t,e,r){return $k(t,e,r)}toDataURL(t){return Ik(this,t)}toImageData(t){return Ck(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Bk(this,t)}}}),Kt,Dk=ye(()=>{"use strict";Qp(),Kt=Ct}),Ji,Mp,ls,cs,Mr,Tr,Fk=ye(()=>{"use strict";Ok(),Ji=(t,e)=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.timeStamp(`${t}::ORT::${e}`)},Mp=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n<r.length;n++){if(s&&!r[n].includes("TRACE_FUNC")){let o=`FUNC_${t}::${r[n].trim().split(" ")[1]}`;e&&(o+=`::${e}`),Ji("CPU",o);return}r[n].includes("TRACE_FUNC")&&(s=!0)}},ls=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||Mp("BEGIN",t)},cs=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||Mp("END",t)},Mr=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.time(`ORT::${t}`)},Tr=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.timeEnd(`ORT::${t}`)}}),jk,OC=ye(()=>{"use strict";Tk(),Dk(),Fk(),jk=class Gk{constructor(e){this.handler=e}async run(e,r,s){ls(),Mr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof Kt||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Kt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let u of r){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);n[u]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,d=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(d.indexOf(f)!==-1){let m=r[f];(m===null||m instanceof Kt)&&(u=!0,a=!1,n[f]=m)}if(u){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let u of this.inputNames)if(typeof e[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(a)for(let u of this.outputNames)n[u]=null;let i=await this.handler.run(e,n,o),l={};for(let u in i)if(Object.hasOwnProperty.call(i,u)){let d=i[u];d instanceof Kt?l[u]=d:l[u]=new Kt(d.type,d.data,d.dims)}return Tr("InferenceSession.run"),cs(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){ls(),Mr("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let d=e,f=0,m=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(m=e.byteLength-f,typeof s=="number"){if(m=s,!Number.isSafeInteger(m))throw new RangeError("'byteLength' must be an integer.");if(m<=0||f+m>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(d,f,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await Mk(a),u=await i.createInferenceSessionHandler(o,l);return Tr("InferenceSession.create"),cs(),new Gk(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Jp,IC=ye(()=>{"use strict";OC(),Jp=jk}),CC=ye(()=>{"use strict"}),PC=ye(()=>{"use strict"}),zC=ye(()=>{"use strict"}),LC=ye(()=>{"use strict"}),qk={};Xn(qk,{InferenceSession:()=>Jp,TRACE:()=>Ji,TRACE_EVENT_BEGIN:()=>Mr,TRACE_EVENT_END:()=>Tr,TRACE_FUNC_BEGIN:()=>ls,TRACE_FUNC_END:()=>cs,Tensor:()=>Kt,env:()=>We,registerBackend:()=>is});var us=ye(()=>{"use strict";vC(),EC(),IC(),Dk(),CC(),PC(),Fk(),zC(),LC()}),Zp=ye(()=>{"use strict"}),Wk={};Xn(Wk,{default:()=>Vk});var Tp,Sp,Vk,NC=ye(()=>{"use strict";iE(),ps(),ed(),Tp="ort-wasm-proxy-worker",Sp=globalThis.self?.name===Tp,Sp&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":td(r.wasm).then(()=>{ad(r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})})},s=>{postMessage({type:e,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;id(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=tl(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;ld(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":cd(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;ud(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(u=>u[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},dd([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":pd(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),Vk=Sp?null:t=>new Worker(t??Ot,{type:"module",name:Tp})}),Hk={};Xn(Hk,{default:()=>Xk});async function ek(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(c,p)=>{c.startsWith("./")&&(c=c.substring(2)),(e.Zc||(e.Zc=new Map)).set(c,p)},e.unmountExternalData=()=>{delete e.Zc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Me:!0}).buffer.constructor;let o=()=>{let c=p=>(...h)=>{let g=er;return h=p(...h),er!=g?new Promise((b,A)=>{Xu={resolve:b,reject:A}}):h};(()=>{for(let p of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[p]=c(e[p])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(c,p)=>{throw p},u=import.meta.url,d="";if(r||s){try{d=new URL(".",u).href}catch{}s&&(i=c=>{var p=new XMLHttpRequest;return p.open("GET",c,!1),p.responseType="arraybuffer",p.send(null),new Uint8Array(p.response)}),a=async c=>{if(C(c))return new Promise((h,g)=>{var b=new XMLHttpRequest;b.open("GET",c,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?h(b.response):g(b.status)},b.onerror=g,b.send(null)});var p=await fetch(c,{credentials:"same-origin"});if(p.ok)return p.arrayBuffer();throw Error(p.status+" : "+p.url)}}var f,m,_,w,x,k,E=console.log.bind(console),M=console.error.bind(console),I=E,T=M,z=!1,C=c=>c.startsWith("file://");function v(){yr.buffer!=V.buffer&&ue()}if(n){let c=function(p){try{var h=p.data,g=h.Uc;if(g==="load"){let b=[];self.onmessage=A=>b.push(A),k=()=>{postMessage({Uc:"loaded"});for(let A of b)c(A);self.onmessage=c};for(let A of h.ne)e[A]&&!e[A].proxy||(e[A]=(...O)=>{postMessage({Uc:"callHandler",me:A,args:O})},A=="print"&&(I=e[A]),A=="printErr"&&(T=e[A]));yr=h.we,ue(),m=h.xe,Qe(),zi()}else if(g==="run"){(function(b){var A=(v(),P)[b+52>>>2>>>0];b=(v(),P)[b+56>>>2>>>0],c1(A,A-b),oe(A)})(h.Sc),ap(h.Sc,0,0,1,0,0),X0(),Wu(h.Sc),X||(Wb(),X=!0);try{XA(h.te,h.ad)}catch(b){if(b!="unwind")throw b}}else h.target!=="setimmediate"&&(g==="checkMailbox"?X&&ki():g&&(T(`worker: received unknown command ${g}`),T(h)))}catch(b){throw n1(),b}};var G=c,X=!1;self.onunhandledrejection=p=>{throw p.reason||p},self.onmessage=c}var V,Q,K,Y,B,P,se,ie,S,L,R,te=!1;function ue(){var c=yr.buffer;e.HEAP8=V=new Int8Array(c),K=new Int16Array(c),e.HEAPU8=Q=new Uint8Array(c),Y=new Uint16Array(c),e.HEAP32=B=new Int32Array(c),e.HEAPU32=P=new Uint32Array(c),se=new Float32Array(c),ie=new Float64Array(c),S=new BigInt64Array(c),L=new BigUint64Array(c)}function Be(){te=!0,n?k():fr.dc()}function Ce(c){throw T(c="Aborted("+c+")"),z=!0,c=new WebAssembly.RuntimeError(c+". Build with -sASSERTIONS for more info."),x?.(c),c}function vt(){return{a:{sa:uT,g:KA,K:YA,f:QA,n:JA,h:ZA,wa:e2,b:t2,ea:r2,Ja:eb,o:s2,fa:nb,Za:ob,$b:ab,bc:ib,_a:lb,Xa:cb,Qa:ub,Wa:pb,qa:db,ac:fb,Zb:mb,Ya:hb,_b,db:n2,Fa:a2,Ub:i2,Sb:c2,Ea:p2,P:d2,J:f2,Tb:m2,ma:b2,Vb:v2,Ta:k2,Xb:A2,Ka:M2,Pb:T2,Ha:S2,Sa:Wu,ab:O2,W:z2,r:U2,c:Gu,tb:B2,y:D2,N:F2,D:j2,m:G2,s:Eb,ub:q2,I:W2,V:V2,j:H2,u:X2,q:K2,k:Y2,Na:Q2,Oa:J2,Pa:Z2,La:Sb,Ma:Ob,Rb:Ib,fb:tM,cb:nM,$:oM,sb:aM,na:iM,bb:rM,Y:lM,$a:cM,Yb:uM,G:eM,ib:pM,_:dM,ra:Si,Wb:mM,hb:fM,gb:hM,pb:vM,F:kM,va:EM,ua:AM,rb:MM,Z:TM,w:SM,ob:OM,nb:IM,mb:CM,qb:PM,lb:zM,kb:LM,jb:NM,Ua:Ub,Va:Bb,Ia:Et,ga:Db,pa:Fb,Ra:jb,oa:Gb,Eb:HT,za:DT,Fb:VT,Aa:BT,H:IT,e:mT,t:dT,x:pT,B:ET,Ib:$T,L:TT,v:_T,Ba:RT,ca:FT,ja:NT,Gb:WT,Hb:qT,Da:CT,Ca:LT,Kb:PT,O:ST,da:UT,d:hT,A:gT,l:fT,Db:XT,p:xT,z:kT,C:wT,E:yT,M:AT,Lb:OT,U:jT,ka:MT,ba:GT,Mb:vT,Nb:bT,R:zT,i:RM,a:yr,eb:xr,Jb:UM,la:BM,Q:DM,ta:FM,Ob:jM,S:GM,Ab:qM,Bb:WM,xa:VM,ha:HM,T:XM,Ga:KM,ya:YM,aa:QM,yb:JM,cc:ZM,X:eT,Cb:tT,vb:rT,wb:nT,xb:oT,ia:aT,zb:iT,Qb:lT}}}async function Qe(){function c(g,b){var A=fr=g.exports;g={};for(let[O,N]of Object.entries(A))typeof N=="function"?(A=I2(N),g[O]=A):g[O]=N;return fr=g,fr=(function(){var O=fr,N=q=>fe=>q(fe)>>>0,D=q=>()=>q()>>>0;return(O=Object.assign({},O)).ec=N(O.ec),O.Hc=D(O.Hc),O.Jc=N(O.Jc),O.vd=(q=>(fe,me)=>q(fe,me)>>>0)(O.vd),O.Ad=N(O.Ad),O.Bd=D(O.Bd),O.Fd=N(O.Fd),O})(),V0.push(fr.md),qb=(g=fr).ec,Wb=g.fc,e._OrtInit=g.gc,e._OrtGetLastError=g.hc,e._OrtCreateSessionOptions=g.ic,e._OrtAppendExecutionProvider=g.jc,e._OrtAddFreeDimensionOverride=g.kc,e._OrtAddSessionConfigEntry=g.lc,e._OrtReleaseSessionOptions=g.mc,e._OrtCreateSession=g.nc,e._OrtReleaseSession=g.oc,e._OrtGetInputOutputCount=g.pc,e._OrtGetInputOutputMetadata=g.qc,e._OrtFree=g.rc,e._OrtCreateTensor=g.sc,e._OrtGetTensorData=g.tc,e._OrtReleaseTensor=g.uc,e._OrtCreateRunOptions=g.vc,e._OrtAddRunConfigEntry=g.wc,e._OrtReleaseRunOptions=g.xc,e._OrtCreateBinding=g.yc,e._OrtBindInput=g.zc,e._OrtBindOutput=g.Ac,e._OrtClearBoundOutputs=g.Bc,e._OrtReleaseBinding=g.Cc,e._OrtRunWithBinding=g.Dc,e._OrtRun=g.Ec,e._OrtEndProfiling=g.Fc,ep=e._OrtGetWebGpuDevice=g.Gc,Ci=g.Hc,Lt=e._free=g.Ic,Cs=e._malloc=g.Jc,Vb=e._wgpuBufferRelease=g.Kc,Hb=e._wgpuCreateInstance=g.Lc,Xb=g.Mc,Kb=g.Nc,Yb=g.Oc,Qb=g.Pc,Jb=g.Qc,Zb=g.Tc,e1=g.bd,t1=g.cd,r1=g.dd,tp=g.fd,rp=g.gd,sp=g.hd,np=g.id,In=g.jd,op=g.kd,s1=g.ld,ap=g.od,n1=g.pd,o1=g.qd,a1=g.rd,ip=g.sd,i1=g.td,l1=g.ud,lp=g.vd,he=g.wd,Cn=g.xd,c1=g.yd,oe=g.zd,Pi=g.Ad,ae=g.Bd,u1=g.Cd,cp=g.Dd,p1=g.Ed,d1=g.Fd,f1=g.Gd,up=g.Hd,m1=g.Id,h1=g.Jd,_1=g.Kd,g1=g.Ld,w1=g.Md,x1=g.Nd,y1=g.Od,b1=g.Pd,v1=g.Qd,k1=g.Rd,E1=g.Sd,A1=g.Td,M1=g.Ud,T1=g.Vd,S1=g.Wd,O1=g.Yd,I1=g.Zd,C1=g._d,P1=g.$d,z1=g.be,L1=g.ce,N1=g.de,$1=g.ee,R1=g.fe,U1=g.ge,B1=g.qe,D1=g.ve,F1=g.ye,j1=g.ze,G1=g.Ae,q1=g.Be,W1=g.Ce,V1=g.De,H1=g.Ee,X1=g.Fe,K1=g.Ge,Y1=g.ef,Q1=g.ff,J1=g.gf,Z1=g.hf,m=b,fr}var p,h=vt();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(b,A)=>{g(c(b,A))})}):n?c(new WebAssembly.Instance(m,vt()),m):(R??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",d):d+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,p=await(async function(g){var b=R;if(!f&&!C(b))try{var A=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(A,g)}catch(O){T(`wasm streaming compile failed: ${O}`),T("falling back to ArrayBuffer instantiation")}return(async function(O,N){try{var D=await(async function(q){if(!f)try{var fe=await a(q);return new Uint8Array(fe)}catch{}if(q==R&&f)q=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";q=i(q)}return q})(O);return await WebAssembly.instantiate(D,N)}catch(q){T(`failed to asynchronously prepare wasm: ${q}`),Ce(q)}})(b,g)})(h),c(p.instance,p.module))}class Ze{name="ExitStatus";constructor(p){this.message=`Program terminated with exit(${p})`,this.status=p}}var rt=c=>{c.terminate(),c.onmessage=()=>{}},Me=[],xe=0,Ge=null,kt=c=>{et.length==0&&(Y0(),K0(et[0]));var p=et.pop();if(!p)return 6;Sn.push(p),Xr[c.Sc]=p,p.Sc=c.Sc;var h={Uc:"run",te:c.se,ad:c.ad,Sc:c.Sc};return p.postMessage(h,c.he),0},ge=0,Le=(c,p,...h)=>{var g,b=16*h.length,A=ae(),O=Pi(b),N=O>>>3;for(g of h)typeof g=="bigint"?((v(),S)[N++>>>0]=1n,(v(),S)[N++>>>0]=g):((v(),S)[N++>>>0]=0n,(v(),ie)[N++>>>0]=g);return c=o1(c,0,b,O,p),oe(A),c};function xr(c){if(n)return Le(0,1,c);if(_=c,!(0<ge)){for(var p of Sn)rt(p);for(p of et)rt(p);et=[],Sn=[],Xr={},z=!0}l(0,new Ze(c))}function Hr(c){if(n)return Le(1,0,c);Et(c)}var Et=c=>{if(_=c,n)throw Hr(c),"unwind";xr(c)},et=[],Sn=[],V0=[],Xr={},H0=c=>{var p=c.Sc;delete Xr[p],et.push(c),Sn.splice(Sn.indexOf(c),1),c.Sc=0,a1(p)};function X0(){V0.forEach(c=>c())}var K0=c=>new Promise(p=>{c.onmessage=b=>{var A=b.data;if(b=A.Uc,A.$c&&A.$c!=Ci()){var O=Xr[A.$c];O?O.postMessage(A,A.he):T(`Internal error! Worker sent a message "${b}" to target pthread ${A.$c}, but that thread no longer exists!`)}else b==="checkMailbox"?ki():b==="spawnThread"?kt(A):b==="cleanupThread"?vi(()=>{H0(Xr[A.ue])}):b==="loaded"?(c.loaded=!0,p(c)):A.target==="setimmediate"?c.postMessage(A):b==="uncaughtException"?c.onerror(A.error):b==="callHandler"?e[A.me](...A.args):b&&T(`worker sent an unknown command ${b}`)},c.onerror=b=>{throw T(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);c.postMessage({Uc:"load",ne:g,we:yr,xe:m})});function Y0(){var c=new Worker((()=>{let p=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new p("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});et.push(c)}var yr,XA=(c,p)=>{ge=0,c=up(c,p),0<ge?_=c:ip(c)},yi=[],bi=0,wt=c=>-9007199254740992>c||9007199254740992<c?NaN:Number(c);function KA(c){var p=new Bu(c>>>=0);return(v(),V)[p.Vc+12>>>0]==0&&(Q0(p,!0),bi--),J0(p,!1),yi.push(p),d1(c)}var Ms=0,YA=()=>{he(0,0);var c=yi.pop();u1(c.nd),Ms=0};function Q0(c,p){p=p?1:0,(v(),V)[c.Vc+12>>>0]=p}function J0(c,p){p=p?1:0,(v(),V)[c.Vc+13>>>0]=p}class Bu{constructor(p){this.nd=p,this.Vc=p-24}}var Du=c=>{var p=Ms;if(!p)return Cn(0),0;var h=new Bu(p);(v(),P)[h.Vc+16>>>2>>>0]=p;var g=(v(),P)[h.Vc+4>>>2>>>0];if(!g)return Cn(0),p;for(var b of c){if(b===0||b===g)break;if(p1(b,g,h.Vc+16))return Cn(b),p}return Cn(g),p};function QA(){return Du([])}function JA(c){return Du([c>>>0])}function ZA(c,p,h,g){return Du([c>>>0,p>>>0,h>>>0,g>>>0])}var e2=()=>{var c=yi.pop();c||Ce("no exception to throw");var p=c.nd;throw(v(),V)[c.Vc+13>>>0]==0&&(yi.push(c),J0(c,!0),Q0(c,!1),bi++),cp(p),Ms=p};function t2(c,p,h){var g=new Bu(c>>>=0);throw p>>>=0,h>>>=0,(v(),P)[g.Vc+16>>>2>>>0]=0,(v(),P)[g.Vc+4>>>2>>>0]=p,(v(),P)[g.Vc+8>>>2>>>0]=h,cp(c),bi++,Ms=c}var r2=()=>bi;function Z0(c,p,h,g){return n?Le(2,1,c,p,h,g):eb(c,p,h,g)}function eb(c,p,h,g){if(c>>>=0,p>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var b=[];return n&&b.length===0?Z0(c,p,h,g):(c={se:h,Sc:c,ad:g,he:b},n?(c.Uc="spawnThread",postMessage(c,b),0):kt(c))}function s2(c){throw Ms||=c>>>0,Ms}var tb=globalThis.TextDecoder&&new TextDecoder,rb=(c,p,h,g)=>{if(h=p+h,g)return h;for(;c[p]&&!(p>=h);)++p;return p},sb=(c,p=0,h,g)=>{if(16<(h=rb(c,p>>>=0,h,g))-p&&c.buffer&&tb)return tb.decode(c.buffer instanceof ArrayBuffer?c.subarray(p,h):c.slice(p,h));for(g="";p<h;){var b=c[p++];if(128&b){var A=63&c[p++];if((224&b)==192)g+=String.fromCharCode((31&b)<<6|A);else{var O=63&c[p++];65536>(b=(240&b)==224?(15&b)<<12|A<<6|O:(7&b)<<18|A<<12|O<<6|63&c[p++])?g+=String.fromCharCode(b):(b-=65536,g+=String.fromCharCode(55296|b>>10,56320|1023&b))}}else g+=String.fromCharCode(b)}return g},Ts=(c,p,h)=>(c>>>=0)?sb((v(),Q),c,p,h):"";function nb(c,p,h){return n?Le(3,1,c,p,h):0}function ob(c,p){if(n)return Le(4,1,c,p)}function ab(c,p){if(n)return Le(5,1,c,p)}function ib(c,p,h){if(n)return Le(6,1,c,p,h)}function lb(c,p,h){return n?Le(7,1,c,p,h):0}function cb(c,p){if(n)return Le(8,1,c,p)}function ub(c,p,h){if(n)return Le(9,1,c,p,h)}function pb(c,p,h,g){if(n)return Le(10,1,c,p,h,g)}function db(c,p,h,g){if(n)return Le(11,1,c,p,h,g)}function fb(c,p,h,g){if(n)return Le(12,1,c,p,h,g)}function mb(c){if(n)return Le(13,1,c)}function hb(c,p){if(n)return Le(14,1,c,p)}function _b(c,p,h){if(n)return Le(15,1,c,p,h)}var n2=()=>Ce(""),Zt=c=>{c>>>=0;for(var p="";;){var h=(v(),Q)[c++>>>0];if(!h)return p;p+=String.fromCharCode(h)}},Fu={},ju={},o2={},Ss=class extends Error{constructor(c){super(c),this.name="BindingError"}};function cr(c,p,h={}){return(function(g,b,A={}){var O=b.name;if(!g)throw new Ss(`type "${O}" must have a positive integer typeid pointer`);if(ju.hasOwnProperty(g)){if(A.oe)return;throw new Ss(`Cannot register type '${O}' twice`)}ju[g]=b,delete o2[g],Fu.hasOwnProperty(g)&&(b=Fu[g],delete Fu[g],b.forEach(N=>N()))})(c,p,h)}var gb=(c,p,h)=>{switch(p){case 1:return h?g=>(v(),V)[g>>>0]:g=>(v(),Q)[g>>>0];case 2:return h?g=>(v(),K)[g>>>1>>>0]:g=>(v(),Y)[g>>>1>>>0];case 4:return h?g=>(v(),B)[g>>>2>>>0]:g=>(v(),P)[g>>>2>>>0];case 8:return h?g=>(v(),S)[g>>>3>>>0]:g=>(v(),L)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${p}): ${c}`)}};function a2(c,p,h,g,b){c>>>=0,h>>>=0,p=Zt(p>>>0);let A=O=>O;if(g=g===0n){let O=8*h;A=N=>BigInt.asUintN(O,N),b=A(b)}cr(c,{name:p,Rc:A,Xc:(O,N)=>(typeof N=="number"&&(N=BigInt(N)),N),Wc:gb(p,h,!g),Yc:null})}function i2(c,p,h,g){cr(c>>>=0,{name:p=Zt(p>>>0),Rc:function(b){return!!b},Xc:function(b,A){return A?h:g},Wc:function(b){return this.Rc((v(),Q)[b>>>0])},Yc:null})}var wb=[],Kr=[0,1,,1,null,1,!0,1,!1,1];function Gu(c){9<(c>>>=0)&&--Kr[c+1]==0&&(Kr[c]=void 0,wb.push(c))}var zt=c=>{if(!c)throw new Ss(`Cannot use deleted val. handle = ${c}`);return Kr[c]},qt=c=>{switch(c){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let p=wb.pop()||Kr.length;return Kr[p]=c,Kr[p+1]=1,p}};function qu(c){return this.Rc((v(),P)[c>>>2>>>0])}var l2={name:"emscripten::val",Rc:c=>{var p=zt(c);return Gu(c),p},Xc:(c,p)=>qt(p),Wc:qu,Yc:null};function c2(c){return cr(c>>>0,l2)}var u2=(c,p)=>{switch(p){case 4:return function(h){return this.Rc((v(),se)[h>>>2>>>0])};case 8:return function(h){return this.Rc((v(),ie)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${p}): ${c}`)}};function p2(c,p,h){h>>>=0,cr(c>>>=0,{name:p=Zt(p>>>0),Rc:g=>g,Xc:(g,b)=>b,Wc:u2(p,h),Yc:null})}function d2(c,p,h,g,b){c>>>=0,h>>>=0,p=Zt(p>>>0);let A=N=>N;if(g===0){var O=32-8*h;A=N=>N<<O>>>O,b=A(b)}cr(c,{name:p,Rc:A,Xc:(N,D)=>D,Wc:gb(p,h,g!==0),Yc:null})}function f2(c,p,h){function g(A){var O=(v(),P)[A>>>2>>>0];return A=(v(),P)[A+4>>>2>>>0],new b((v(),V).buffer,A,O)}var b=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][p];cr(c>>>=0,{name:h=Zt(h>>>0),Rc:g,Wc:g},{oe:!0})}var ur=(c,p,h)=>{var g=(v(),Q);if(p>>>=0,0<h){var b=p;h=p+h-1;for(var A=0;A<c.length;++A){var O=c.codePointAt(A);if(127>=O){if(p>=h)break;g[p++>>>0]=O}else if(2047>=O){if(p+1>=h)break;g[p++>>>0]=192|O>>6,g[p++>>>0]=128|63&O}else if(65535>=O){if(p+2>=h)break;g[p++>>>0]=224|O>>12,g[p++>>>0]=128|O>>6&63,g[p++>>>0]=128|63&O}else{if(p+3>=h)break;g[p++>>>0]=240|O>>18,g[p++>>>0]=128|O>>12&63,g[p++>>>0]=128|O>>6&63,g[p++>>>0]=128|63&O,A++}}g[p>>>0]=0,c=p-b}else c=0;return c},pr=c=>{for(var p=0,h=0;h<c.length;++h){var g=c.charCodeAt(h);127>=g?p++:2047>=g?p+=2:55296<=g&&57343>=g?(p+=4,++h):p+=3}return p};function m2(c,p){cr(c>>>=0,{name:p=Zt(p>>>0),Rc(h){var g=(v(),P)[h>>>2>>>0];return g=Ts(h+4,g,!0),Lt(h),g},Xc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var b=typeof g=="string";if(!(b||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Ss("Cannot pass non-string to std::string");var A=b?pr(g):g.length,O=Cs(4+A+1),N=O+4;return(v(),P)[O>>>2>>>0]=A,b?ur(g,N,A+1):(v(),Q).set(g,N>>>0),h!==null&&h.push(Lt,O),O},Wc:qu,Yc(h){Lt(h)}})}var xb=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,h2=(c,p,h)=>{if(c>>>=1,16<(p=rb((v(),Y),c,p/2,h))-c&&xb)return xb.decode((v(),Y).slice(c,p));for(h="";c<p;++c){var g=(v(),Y)[c>>>0];h+=String.fromCharCode(g)}return h},_2=(c,p,h)=>{if(h??=2147483647,2>h)return 0;var g=p;h=(h-=2)<2*c.length?h/2:c.length;for(var b=0;b<h;++b){var A=c.charCodeAt(b);(v(),K)[p>>>1>>>0]=A,p+=2}return(v(),K)[p>>>1>>>0]=0,p-g},g2=c=>2*c.length,w2=(c,p,h)=>{var g="";c>>>=2;for(var b=0;!(b>=p/4);b++){var A=(v(),P)[c+b>>>0];if(!A&&!h)break;g+=String.fromCodePoint(A)}return g},x2=(c,p,h)=>{if(p>>>=0,h??=2147483647,4>h)return 0;var g=p;h=g+h-4;for(var b=0;b<c.length;++b){var A=c.codePointAt(b);if(65535<A&&b++,(v(),B)[p>>>2>>>0]=A,(p+=4)+4>h)break}return(v(),B)[p>>>2>>>0]=0,p-g},y2=c=>{for(var p=0,h=0;h<c.length;++h)65535<c.codePointAt(h)&&h++,p+=4;return p};function b2(c,p,h){if(c>>>=0,p>>>=0,h=Zt(h>>>=0),p===2)var g=h2,b=_2,A=g2;else g=w2,b=x2,A=y2;cr(c,{name:h,Rc:O=>{var N=(v(),P)[O>>>2>>>0];return N=g(O+4,N*p,!0),Lt(O),N},Xc:(O,N)=>{if(typeof N!="string")throw new Ss(`Cannot pass non-string to C++ string type ${h}`);var D=A(N),q=Cs(4+D+p);return(v(),P)[q>>>2>>>0]=D/p,b(N,q+4,D+p),O!==null&&O.push(Lt,q),q},Wc:qu,Yc(O){Lt(O)}})}function v2(c,p){cr(c>>>=0,{pe:!0,name:p=Zt(p>>>0),Rc:()=>{},Xc:()=>{}})}function k2(c){ap(c>>>0,!s,1,!r,131072,!1),X0()}var vi=c=>{if(!z)try{if(c(),!(0<ge))try{n?Ci()&&ip(_):Et(_)}catch(p){p instanceof Ze||p=="unwind"||l(0,p)}}catch(p){p instanceof Ze||p=="unwind"||l(0,p)}},E2=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Wu(c){c>>>=0,E2||(Atomics.waitAsync((v(),B),c>>>2,c).value.then(ki),c+=128,Atomics.store((v(),B),c>>>2,1))}var ki=()=>vi(()=>{var c=Ci();c&&(Wu(c),l1())});function A2(c,p){(c>>>=0)==p>>>0?setTimeout(ki):n?postMessage({$c:c,Uc:"checkMailbox"}):(c=Xr[c])&&c.postMessage({Uc:"checkMailbox"})}var Vu=[];function M2(c,p,h,g,b){for(p>>>=0,b>>>=0,Vu.length=0,h=b>>>3,g=b+g>>>3;h<g;){var A;A=(v(),S)[h++>>>0]?(v(),S)[h++>>>0]:(v(),ie)[h++>>>0],Vu.push(A)}return(p?pp[p]:cT[c])(...Vu)}var T2=()=>{ge=0};function S2(c){c>>>=0,n?postMessage({Uc:"cleanupThread",ue:c}):H0(Xr[c])}function O2(c){}var Ei=c=>{try{c()}catch(p){Ce(p)}};function I2(c){var p=(...h)=>{Ai.push(c);try{return c(...h)}finally{z||(Ai.pop(),er&&br===1&&Ai.length===0&&(br=0,ge+=1,Ei(Q1),typeof Fibers<"u"&&Fibers.Oe()))}};return vb.set(c,p),p}var br=0,er=null,yb=0,Ai=[],Hu=new Map,bb=new Map,vb=new Map,C2=0,Xu=null,P2=[],kb=c=>(function(p){if(!z){if(br===0){var h=!1,g=!1;p((b=0)=>{if(!z&&(yb=b,h=!0,g)){br=2,Ei(()=>J1(er)),typeof MainLoop<"u"&&MainLoop.le&&MainLoop.resume(),b=!1;try{var A=(function(){var D=(v(),B)[er+8>>>2>>>0];return D=bb.get(D),D=vb.get(D),--ge,D()})()}catch(D){A=D,b=!0}var O=!1;if(!er){var N=Xu;N&&(Xu=null,(b?N.reject:N.resolve)(A),O=!0)}if(b&&!O)throw A}}),g=!0,h||(br=1,er=(function(){var b=Cs(65548),A=b+12;if((v(),P)[b>>>2>>>0]=A,(v(),P)[b+4>>>2>>>0]=A+65536,A=Ai[0],!Hu.has(A)){var O=C2++;Hu.set(A,O),bb.set(O,A)}return A=Hu.get(A),(v(),B)[b+8>>>2>>>0]=A,b})(),typeof MainLoop<"u"&&MainLoop.le&&MainLoop.pause(),Ei(()=>Y1(er)))}else br===2?(br=0,Ei(Z1),Lt(er),er=null,P2.forEach(vi)):Ce(`invalid state: ${br}`);return yb}})(p=>{c().then(p)});function z2(c){return c>>>=0,kb(async()=>{var p=await zt(c);return qt(p)})}var Ku=[],L2=c=>{var p=Ku.length;return Ku.push(c),p},N2=(c,p)=>{for(var h=Array(c),g=0;g<c;++g){var b=g,A=(v(),P)[p+4*g>>>2>>>0],O=ju[A];if(O===void 0)throw c=`parameter ${g}`,A=qb(A),p=Zt(A),Lt(A),new Ss(`${c} has unknown type ${p}`);h[b]=O}return h},$2=(c,p,h)=>{var g=[];return c=c(g,h),g.length&&((v(),P)[p>>>2>>>0]=qt(g)),c},R2={},Mi=c=>{var p=R2[c];return p===void 0?Zt(c):p};function U2(c,p,h){var[g,...b]=N2(c,p>>>0);p=g.Xc.bind(g);var A=b.map(D=>D.Wc.bind(D));c--;var O={toValue:zt};switch(c=A.map((D,q)=>{var fe=`argFromPtr${q}`;return O[fe]=D,`${fe}(args${q?"+"+8*q:""})`}),h){case 0:var N="toValue(handle)";break;case 2:N="new (toValue(handle))";break;case 3:N="";break;case 1:O.getStringOrSymbol=Mi,N="toValue(handle)[getStringOrSymbol(methodName)]"}return N+=`(${c})`,g.pe||(O.toReturnWire=p,O.emval_returnValue=$2,N=`return emval_returnValue(toReturnWire, destructorsRef, ${N})`),N=`return function (handle, methodName, destructorsRef, args) {
7
+ `));case"join":case"string":return t;case"int":{let n=parseInt(t.value,10);return new me(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new Ye(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof me||t instanceof Ye)switch(s.value){case"abs":return t instanceof me?new me(Math.abs(t.value)):new Ye(Math.abs(t.value));case"int":return new me(Math.floor(t.value));case"float":return new Ye(t.value);default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(t instanceof gt)switch(s.value){case"items":return new ve(Array.from(t.value.entries()).map(([n,o])=>new ve([new ee(n),o])));case"length":return new me(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof Ge?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(t instanceof ce)switch(s.value){case"bool":return new ce(t.value);case"int":return new me(t.value?1:0);case"float":return new Ye(t.value?1:0);case"string":return new ee(t.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${t.type}`)}else if(e.type==="CallExpression"){let s=e;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);let n=s.callee.value;if(n==="tojson"){let[,o]=this.evaluateArguments(s.args,r),a=o.get("indent")??new We;if(!(a instanceof me||a instanceof We))throw new Error("If set, indent must be a number");let i=o.get("ensure_ascii")??new ce(!1);if(!(i instanceof ce))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new ce(!1);if(!(l instanceof ce))throw new Error("If set, sort_keys must be a boolean");let u=o.get("separators")??new We,p=null;if(u instanceof ve||u instanceof ik){if(u.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,m]=u.value;if(!(f instanceof ee)||!(m instanceof ee))throw new Error("separators must be a tuple of two strings");p=[f.value,m.value]}else if(!(u instanceof We))throw new Error("If set, separators must be a tuple of two strings");return new ee(fs(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:p}))}else if(n==="join"){let o;if(t instanceof ee)o=Array.from(t.value);else if(t instanceof ve)o=t.value.map(u=>u.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[a,i]=this.evaluateArguments(s.args,r),l=a.at(0)??i.get("separator")??new ee("");if(!(l instanceof ee))throw new Error("separator must be a string");return new ee(o.join(l.value))}else if(n==="int"||n==="float"){let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("default")??(n==="int"?new me(0):new Ye(0));if(t instanceof ee){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new me(l):new Ye(l)}else{if(t instanceof me||t instanceof Ye)return t;if(t instanceof ce)return n==="int"?new me(t.value?1:0):new Ye(t.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}}else if(n==="default"){let[o,a]=this.evaluateArguments(s.args,r),i=o[0]??new ee(""),l=o[1]??a.get("boolean")??new ce(!1);if(!(l instanceof ce))throw new Error("`default` filter flag must be a boolean");return t instanceof je||l.value&&!t.__bool__().value?i:t}if(t instanceof ve){switch(n){case"sort":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("reverse")??new ce(!1);if(!(i instanceof ce))throw new Error("reverse must be a boolean");let l=o.at(1)??a.get("case_sensitive")??new ce(!1);if(!(l instanceof ce))throw new Error("case_sensitive must be a boolean");let u=o.at(2)??a.get("attribute")??new We;if(!(u instanceof ee||u instanceof me||u instanceof We))throw new Error("attribute must be a string, integer, or null");let p=f=>{if(u instanceof We)return f;let m=u instanceof me?String(u.value):u.value;return lk(f,m)};return new ve(t.value.slice().sort((f,m)=>{let h=p(f),w=p(m),x=jp(h,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!(f instanceof gt)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[a,i,l]=s.args.map(f=>this.evaluate(f,r)),u;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);u=f}else u=(...f)=>f[0].__bool__().value;let p=t.value.filter(f=>{let m=f.value.get(a.value),h=m?u(m,l):!1;return o?h:!h});return new ve(p)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof ee))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(u=>{if(!(u instanceof gt))throw new Error("items in map must be an object");let p=lk(u,a.value);return p instanceof je?i??new je:p});return new ve(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof ee){switch(n){case"indent":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("width")??new me(4);if(!(i instanceof me))throw new Error("width must be a number");let l=o.at(1)??a.get("first")??new ce(!1),u=o.at(2)??a.get("blank")??new ce(!1),p=t.value.split(`
8
+ `),f=" ".repeat(i.value),m=p.map((h,w)=>!l.value&&w===0||!u.value&&h.length===0?h:f+h);return new ee(m.join(`
9
+ `))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof Ge))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new Kn(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof gt){let o=t.builtins.get(n);if(o&&o instanceof Ge){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new Kn(i)),o.value(a,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}throw new Error(`Unknown filter: ${e.type}`)}evaluateFilterExpression(t,e){let r=this.evaluate(t.operand,e);return this.applyFilter(r,t.filter,e)}evaluateTestExpression(t,e){let r=this.evaluate(t.operand,e),s=e.tests.get(t.test.value);if(!s)throw new Error(`Unknown test: ${t.test.value}`);let n=s(r);return new ce(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new je}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);if(t.operator.value==="not")return new ce(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evaluateTernaryExpression(t,e){return this.evaluate(t.condition,e).__bool__().value?this.evaluate(t.trueExpr,e):this.evaluate(t.falseExpr,e)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(let s of t){let n=this.evaluate(s,e);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new ee(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){let[r,s]=this.evaluateArguments(t.args,e);s.size>0&&r.push(new Kn(s));let n=this.evaluate(t.callee,e);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof ve||t instanceof ee))throw new Error("Slice object must be an array or string");let s=this.evaluate(e.start,r),n=this.evaluate(e.stop,r),o=this.evaluate(e.step,r);if(!(s instanceof me||s instanceof je))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof me||n instanceof je))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof me||o instanceof je))throw new Error("Slice step must be numeric or undefined");return t instanceof ve?new ve(sk(t.value,s.value,n.value,o.value)):new ee(sk(Array.from(t.value),s.value,n.value,o.value).join(""))}evaluateMemberExpression(t,e){let r=this.evaluate(t.object,e),s;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);s=this.evaluate(t.property,e)}else s=new ee(t.property.value);let n;if(r instanceof gt){if(!(s instanceof ee))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof ve||r instanceof ee)if(s instanceof me)n=r.value.at(s.value),r instanceof ee&&(n=new ee(r.value.at(s.value)));else if(s instanceof ee)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof ee))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof or?n:new je}evaluateSet(t,e){let r=t.value?this.evaluate(t.value,e):this.evaluateBlock(t.body,e);if(t.assignee.type==="Identifier"){let s=t.assignee.value;e.setVariable(s,r)}else if(t.assignee.type==="TupleLiteral"){let s=t.assignee;if(!(r instanceof ve))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let o=0;o<s.value.length;++o){let a=s.value[o];if(a.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${a.type}`);e.setVariable(a.value,n[o])}}else if(t.assignee.type==="MemberExpression"){let s=t.assignee,n=this.evaluate(s.object,e);if(!(n instanceof gt))throw new Error("Cannot assign to member of non-object");if(s.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");n.value.set(s.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);return new We}evaluateIf(t,e){let r=this.evaluate(t.test,e);return this.evaluateBlock(r.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){let r=new ds(e),s,n;if(t.iterable.type==="SelectExpression"){let u=t.iterable;n=this.evaluate(u.lhs,r),s=u.test}else n=this.evaluate(t.iterable,r);if(!(n instanceof ve||n instanceof gt))throw new Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof gt&&(n=n.keys());let o=[],a=[];for(let u=0;u<n.value.length;++u){let p=new ds(r),f=n.value[u],m;if(t.loopvar.type==="Identifier")m=h=>h.setVariable(t.loopvar.value,f);else if(t.loopvar.type==="TupleLiteral"){let h=t.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);let w=f;if(h.value.length!==w.value.length)throw new Error(`Too ${h.value.length>w.value.length?"few":"many"} items to unpack`);m=x=>{for(let k=0;k<h.value.length;++k){if(h.value[k].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${h.value[k].type}`);x.setVariable(h.value[k].value,w.value[k])}}}else throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);s&&(m(p),!this.evaluate(s,p).__bool__().value)||(o.push(f),a.push(m))}let i="",l=!0;for(let u=0;u<o.length;++u){let p=new Map([["index",new me(u+1)],["index0",new me(u)],["revindex",new me(o.length-u)],["revindex0",new me(o.length-u-1)],["first",new ce(u===0)],["last",new ce(u===o.length-1)],["length",new me(o.length)],["previtem",u>0?o[u-1]:new je],["nextitem",u<o.length-1?o[u+1]:new je]]);r.setVariable("loop",new gt(p)),a[u](r);try{let f=this.evaluateBlock(t.body,r);i+=f.value}catch(f){if(f instanceof ok)continue;if(f instanceof nk)break;throw f}l=!1}if(l){let u=this.evaluateBlock(t.defaultBlock,r);i+=u.value}return new ee(i)}evaluateMacro(t,e){return e.setVariable(t.name.value,new Ge((r,s)=>{let n=new ds(s);r=r.slice();let o;r.at(-1)?.type==="KeywordArgumentsValue"&&(o=r.pop());for(let a=0;a<t.args.length;++a){let i=t.args[a],l=r[a];if(i.type==="Identifier"){let u=i;if(!l)throw new Error(`Missing positional argument: ${u.value}`);n.setVariable(u.value,l)}else if(i.type==="KeywordArgumentExpression"){let u=i,p=l??o?.value.get(u.key.value)??this.evaluate(u.value,n);n.setVariable(u.key.value,p)}else throw new Error(`Unknown argument type: ${i.type}`)}return this.evaluateBlock(t.body,n)})),new We}evaluateCallStatement(t,e){let r=new Ge((i,l)=>{let u=new ds(l);if(t.callerArgs)for(let p=0;p<t.callerArgs.length;++p){let f=t.callerArgs[p];if(f.type!=="Identifier")throw new Error(`Caller parameter must be an identifier, got ${f.type}`);u.setVariable(f.value,i[p]??new je)}return this.evaluateBlock(t.body,u)}),[s,n]=this.evaluateArguments(t.call.args,e);s.push(new Kn(n));let o=this.evaluate(t.call.callee,e);if(o.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${o.type}`);let a=new ds(e);return a.setVariable("caller",r),o.value(s,a)}evaluateFilterStatement(t,e){let r=this.evaluateBlock(t.body,e);return this.applyFilter(r,t.filter,e)}evaluate(t,e){if(!t)return new je;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"Macro":return this.evaluateMacro(t,e);case"CallStatement":return this.evaluateCallStatement(t,e);case"Break":throw new nk;case"Continue":throw new ok;case"IntegerLiteral":return new me(t.value);case"FloatLiteral":return new Ye(t.value);case"StringLiteral":return new ee(t.value);case"ArrayLiteral":return new ve(t.value.map(r=>this.evaluate(r,e)));case"TupleLiteral":return new ik(t.value.map(r=>this.evaluate(r,e)));case"ObjectLiteral":{let r=new Map;for(let[s,n]of t.value){let o=this.evaluate(s,e);if(!(o instanceof ee))throw new Error(`Object keys must be strings: got ${o.type}`);r.set(o.value,this.evaluate(n,e))}return new gt(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"FilterStatement":return this.evaluateFilterStatement(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);case"SelectExpression":return this.evaluateSelectExpression(t,e);case"Ternary":return this.evaluateTernaryExpression(t,e);case"Comment":return new We;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Ml(t){switch(typeof t){case"number":return Number.isInteger(t)?new me(t):new Ye(t);case"string":return new ee(t);case"boolean":return new ce(t);case"undefined":return new je;case"object":return t===null?new We:Array.isArray(t)?new ve(t.map(Ml)):new gt(new Map(Object.entries(t).map(([e,r])=>[e,Ml(r)])));case"function":return new Ge((e,r)=>{let s=t(...e.map(n=>n.value))??null;return Ml(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var ot=`
10
+ `,$C="{%- ",RC=" -%}";function DC(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function UC(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Yt(t.body,0,r).replace(/\n$/,"")}function mt(...t){return $C+t.join(" ")+RC}function Yt(t,e,r){return t.map(s=>BC(s,e,r)).join(ot)}function BC(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Yt(t.body,e,r);case"If":return FC(t,e,r);case"For":return jC(t,e,r);case"Set":return GC(t,e,r);case"Macro":return qC(t,e,r);case"Break":return s+mt("break");case"Continue":return s+mt("continue");case"CallStatement":return WC(t,e,r);case"FilterStatement":return VC(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function FC(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+mt("if",ke(n[0].test))+ot+Yt(n[0].body,e+1,r);for(let i=1;i<n.length;++i)a+=ot+s+mt("elif",ke(n[i].test))+ot+Yt(n[i].body,e+1,r);return o&&o.alternate.length>0&&(a+=ot+s+mt("else")+ot+Yt(o.alternate,e+1,r)),a+=ot+s+mt("endif"),a}function jC(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+mt("for",ke(t.loopvar),"in",n)+ot+Yt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=ot+s+mt("else")+ot+Yt(t.defaultBlock,e+1,r)),o+=ot+s+mt("endfor"),o}function GC(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+mt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+ot+Yt(t.body,e+1,r)+ot+s+mt("endset")}function qC(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+mt("macro",`${t.name.value}(${n})`)+ot+Yt(t.body,e+1,r)+ot+s+mt("endmacro")}function WC(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+mt(`call${n}`,o)+ot;return a+=Yt(t.body,e+1,r)+ot,a+=s+mt("endcall"),a}function VC(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+mt("filter",n)+ot;return o+=Yt(t.body,e+1,r)+ot,o+=s+mt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=DC(r),n=ke(r.left,s),o=ke(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s<e?`(${a})`:a}case"UnaryExpression":{let r=t;return r.operator.value+(r.operator.value==="not"?" ":"")+ke(r.argument,1/0)}case"CallExpression":{let r=t,s=r.args.map(ke).join(", ");return`${ke(r.callee)}(${s})`}case"MemberExpression":{let r=t,s=ke(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(s=`(${s})`);let n=ke(r.property);return!r.computed&&r.property.type!=="Identifier"&&(n=`(${n})`),r.computed?`${s}[${n}]`:`${s}.${n}`}case"FilterExpression":{let r=t,s=ke(r.operand,1/0);return r.filter.type==="CallExpression"?`${s} | ${ke(r.filter)}`:`${s} | ${r.filter.value}`}case"SelectExpression":{let r=t;return`${ke(r.lhs)} if ${ke(r.test)}`}case"TestExpression":{let r=t;return`${ke(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let r=t.value.map(ke),s=t.type==="ArrayLiteral"?"[]":"()";return`${s[0]}${r.join(", ")}${s[1]}`}case"ObjectLiteral":return`{${Array.from(t.value.entries()).map(([s,n])=>`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var ck=class{parsed;constructor(t){let e=rC(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=MC(e)}render(t){let e=new ds;if(LC(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new NC(e).run(this.parsed).value}format(t){return UC(this.parsed,t?.indent||" ")}};var Ze=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};import ar from"fs";import Tl from"path";var HC={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"},ms=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=ar.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=ar.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=ar.createReadStream(e);this.body=new ReadableStream({start(n){s.on("data",o=>n.enqueue(o)),s.on("end",()=>n.close()),s.on("error",o=>n.error(o))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",HC[e]??"application/octet-stream")}clone(){let e=new t(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await ar.promises.readFile(this.filePath)).buffer}async blob(){let e=await ar.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await ar.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Js=class{constructor(e){this.path=e}async match(e){let r=Tl.join(this.path,e),s=new ms(r);if(s.exists)return s}async put(e,r,s=void 0){let n=Tl.join(this.path,e);try{let o=r.headers.get("Content-Length"),a=parseInt(o??"0"),i=0;await ar.promises.mkdir(Tl.dirname(n),{recursive:!0});let l=ar.createWriteStream(n),u=r.body.getReader();for(;;){let{done:p,value:f}=await u.read();if(p)break;await new Promise((h,w)=>{l.write(f,x=>{if(x){w(x);return}h()})}),i+=f.length;let m=a?i/a*100:0;s?.({progress:m,loaded:i,total:a})}l.close()}catch(o){try{await ar.promises.unlink(n)}catch{}throw o}}async delete(e){let r=Tl.join(this.path,e);try{return await ar.promises.unlink(r),!0}catch{return!1}}};var uk={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"},Sl=100,pk=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Yn(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function Er(t,e=null,r=null){let s;try{s=new URL(t)}catch{return!1}return!(e&&!e.includes(s.protocol)||r&&!r.includes(s.hostname))}function dk(t){return!(!pk.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function fk(t,e,r){if(!r)return null;let s=uk[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function mk(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&Q.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:u,value:p}=await i.read();if(u)return;let f=a+p.length;if(f>n){n=f;let h=new Uint8Array(n);h.set(o),o=h}o.set(p,a),a=f;let m=a/n*100;return e({progress:m,loaded:a,total:n}),l()}return await l(),o}async function ir(t=null){let e=null;if(fe.useCustomCache){if(!fe.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!fe.customCache.match||!fe.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=fe.customCache}if(!e&&fe.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(fe.cacheKey)}catch(r){Q.warn("An error occurred while opening the browser cache:",r)}}if(!e&&fe.useFSCache){if(!ge.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new Js(t??fe.cacheDir)}return e}async function hk(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}async function XC(t){if(!Er(t,["http:","https:"]))return null;let e=Gp(t);return e.set("Range","bytes=0-0"),fe.fetch(t,{method:"GET",headers:e})}async function lr(t,e,r={}){let s=await ir(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=hs(t,e,r,s),l=await _s(s,n,a);if(l!==void 0&&typeof l!="string"){let u=l.headers.get("content-length"),p=l.headers.get("content-type");return{exists:!0,size:u?parseInt(u,10):void 0,contentType:p||void 0,fromCache:!0}}if(fe.allowLocalModels&&!Er(n,["http:","https:"]))try{let p=await zr(n);if(typeof p!="string"&&p.status!==404){let f=p.headers.get("content-length"),m=p.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:m||void 0,fromCache:!1}}}catch{}if(fe.allowRemoteModels&&!r.local_files_only&&i)try{let u=await XC(o);if(u&&u.status>=200&&u.status<300){let p,f=u.headers.get("content-type");if(u.status===206){let m=u.headers.get("content-range");if(m){let h=m.match(/bytes \d+-\d+\/(\d+)/);h&&(p=parseInt(h[1],10))}}else if(u.status===200)try{await u.body?.cancel()}catch{}if(p===void 0){let m=u.headers.get("content-length");p=m?parseInt(m,10):void 0}return{exists:!0,size:p,contentType:f||void 0,fromCache:!1}}}catch(u){Q.warn(`Unable to fetch file metadata for "${o}": ${u}`)}return{exists:!1,fromCache:!1}}async function zr(t){return fe.useFS&&!Er(t,["http:","https:","blob:"])?new ms(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):fe.fetch(t,{headers:Gp(t)})}function Gp(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=fe.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),Er(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function hs(t,e,r={},s=null){let n=r.revision??"main",o=Yn(t,e),a=dk(t),i=a?Yn(fe.localModelPath,o):o,l=Yn(fe.remoteHost,fe.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),u=s instanceof Js?n==="main"?o:Yn(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:a}}async function _s(t,e,r){if(t)return await hk(t,e,r)}async function KC(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o)typeof n!="string"&&await r.put(s,new Response(o,{headers:n.headers})).catch(i=>{Q.warn(`Unable to add response to browser cache: ${i}.`)});else{let i=a.progress_callback?l=>vr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function YC(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:p}=hs(t,e,s,o),f,m=!1,h;h=await _s(o,i,u);let w=h!==void 0;if(!w){if(fe.allowLocalModels)if(Er(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!fe.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{h=await zr(i),f=i}catch(A){Q.warn(`Unable to load from local path "${i}": "${A}"`)}if(h===void 0||typeof h!="string"&&h.status===404){if(s.local_files_only||!fe.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!p)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(h=await zr(l),h.status!==200)return fk(h.status,l,r);f=u}m=o&&typeof Response<"u"&&h instanceof Response&&h.status===200}vr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(ge.IS_NODE_ENV&&n)){let E;if(typeof h!="string")if(!s.progress_callback)E=new Uint8Array(await h.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))E=new Uint8Array(await h.arrayBuffer()),vr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:E.length,total:E.length});else{let A,S=h.headers.get("content-length");if(S)A=parseInt(S,10);else try{let T=await lr(t,e,s);T.size&&(A=T.size)}catch{}E=await mk(h,T=>{vr(s.progress_callback,{status:"progress",name:t,file:e,...T})},A)}x=E}if(m&&f&&typeof h!="string"&&await KC(t,e,o,f,h,x,s),vr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!ge.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(h instanceof ms)return h.filePath;let k=await o?.match(f);if(k instanceof ms)return k.filePath;if(k instanceof Response)return new Uint8Array(await k.arrayBuffer());if(typeof k=="string")return k;throw new Error("Unable to get model file path or buffer.")}async function Qn(t,e,r=!0,s={},n=!1){if(!fe.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!fe.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}vr(s.progress_callback,{status:"initiate",name:t,file:e});let o=await ir(s?.cache_dir);return await YC(t,e,r,s,n,o)}async function qp(t,e,r=!0,s={}){let n=await Qn(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function ct(t,e,r=!0,s={}){let n=await qp(t,e,r,s);return n===null?{}:JSON.parse(n)}function gk(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,u=n/r,p=new t.constructor(n*o*e),f=r*s,m=n*o;for(let h=0;h<n;++h)for(let w=0;w<o;++w){let x=h*o+w,k=(w+.5)/l-.5,E=(h+.5)/u-.5,A=Math.floor(k),S=Math.floor(E),T=Math.min(A+1,s-1),P=Math.min(S+1,r-1);A=Math.max(A,0),S=Math.max(S,0);let C=k-A,v=E-S,F=(1-C)*(1-v),H=C*(1-v),V=(1-C)*v,J=C*v,X=S*s,Y=P*s,U=X+A,z=X+T,ne=Y+A,ae=Y+T;for(let I=0;I<e;++I){let L=I*f;p[I*m+x]=F*t[L+U]+H*t[L+z]+V*t[L+ne]+J*t[L+ae]}}return p}function wk(t,e,r){let s=new Array(r.length),n=new Array(r.length);for(let i=r.length-1,l=1;i>=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i<t.length;++i){let l=0;for(let u=e.length-1,p=i;u>=0;--u)l+=p%e[u]*o[u],p=Math.floor(p/e[u]);a[l]=t[i]}return[a,s]}function Le(t){let e=Se(t)[0],r=t.map(o=>Math.exp(o-e)),s=r.reduce((o,a)=>o+a,0);return r.map(o=>o/s)}function Vp(t){let e=Se(t)[0],r=0;for(let o=0;o<t.length;++o)r+=Math.exp(t[o]-e);let s=Math.log(r);return t.map(o=>o-e-s)}function xk(t,e){let r=0;for(let s=0;s<t.length;++s)r+=t[s]*e[s];return r}function QC(t,e){let r=xk(t,e),s=_k(t),n=_k(e);return r/(s*n)}function _k(t){return Math.sqrt(t.reduce((e,r)=>e+r*r,0))}function Jn(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]<e&&(e=t[s],r=s);return[e,r]}function Se(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]>e&&(e=t[s],r=s);return[e,r]}function yk(t){return t>0&&(t&t-1)===0}var Ol=class{constructor(e){if(this.size=e|0,this.size<=1||!yk(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;s<this.table.length;s+=2){let n=Math.PI*s/this.size;this.table[s]=Math.cos(n),this.table[s+1]=-Math.sin(n)}let r=0;for(let s=1;this.size>s;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<<this._width);for(let s=0;s<this._bitrev.length;++s){this._bitrev[s]=0;for(let n=0;n<this._width;n+=2){let o=this._width-n-2;this._bitrev[s]|=(s>>>n&3)<<o}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,r){let s=r||new Array(e.length>>>1);for(let n=0;n<e.length;n+=2)s[n>>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n<s.length;n+=2)s[n]=e[n>>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s<e.length;++s)e[s]/=this.size}_transform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,u,p=this._bitrev;if(i===4)for(l=0,u=0;l<n;l+=i,++u){let m=p[u];this._singleTransform2(r,e,l,m,a)}else for(l=0,u=0;l<n;l+=i,++u){let m=p[u];this._singleTransform4(r,e,l,m,a,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>2;for(l=0;l<n;l+=i){let h=l+m-1;for(let w=l,x=0;w<h;w+=2,x+=a){let k=w,E=k+m,A=E+m,S=A+m,T=e[k],P=e[k+1],C=e[E],v=e[E+1],F=e[A],H=e[A+1],V=e[S],J=e[S+1],X=f[x],Y=s*f[x+1],U=C*X-v*Y,z=C*Y+v*X,ne=f[2*x],ae=s*f[2*x+1],I=F*ne-H*ae,L=F*ae+H*ne,R=f[3*x],te=s*f[3*x+1],pe=V*R-J*te,Fe=V*te+J*R,Pe=T+I,At=P+L,Je=T-I,et=P-L,st=U+pe,Me=z+Fe,xe=s*(U-pe),qe=s*(z-Fe);e[k]=Pe+st,e[k+1]=At+Me,e[E]=Je+qe,e[E+1]=et-xe,e[A]=Pe-st,e[A+1]=At-Me,e[S]=Je-qe,e[S+1]=et+xe}}}}_singleTransform2(e,r,s,n,o){let a=e[n],i=e[n+1],l=e[n+o],u=e[n+o+1];r[s]=a+l,r[s+1]=i+u,r[s+2]=a-l,r[s+3]=i-u}_singleTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,u=e[n],p=e[n+1],f=e[n+o],m=e[n+o+1],h=e[n+i],w=e[n+i+1],x=e[n+l],k=e[n+l+1],E=u+h,A=p+w,S=u-h,T=p-w,P=f+x,C=m+k,v=a*(f-x),F=a*(m-k);r[s]=E+P,r[s+1]=A+C,r[s+2]=S+F,r[s+3]=T-v,r[s+4]=E-P,r[s+5]=A-C,r[s+6]=S-F,r[s+7]=T+v}_realTransform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,u,p=this._bitrev;if(i===4)for(l=0,u=0;l<n;l+=i,++u){let h=p[u];this._singleRealTransform2(r,e,l,h>>>1,a>>>1)}else for(l=0,u=0;l<n;l+=i,++u){let h=p[u];this._singleRealTransform4(r,e,l,h>>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let h=i>>>1,w=h>>>1,x=w>>>1;for(l=0;l<n;l+=i)for(let k=0,E=0;k<=x;k+=2,E+=a){let A=l+k,S=A+w,T=S+w,P=T+w,C=e[A],v=e[A+1],F=e[S],H=e[S+1],V=e[T],J=e[T+1],X=e[P],Y=e[P+1],U=C,z=v,ne=f[E],ae=s*f[E+1],I=F*ne-H*ae,L=F*ae+H*ne,R=f[2*E],te=s*f[2*E+1],pe=V*R-J*te,Fe=V*te+J*R,Pe=f[3*E],At=s*f[3*E+1],Je=X*Pe-Y*At,et=X*At+Y*Pe,st=U+pe,Me=z+Fe,xe=U-pe,qe=z-Fe,Mt=I+Je,be=L+et,$e=s*(I-Je),Ir=s*(L-et);if(e[A]=st+Mt,e[A+1]=Me+be,e[S]=xe+Ir,e[S+1]=qe-$e,k===0){e[T]=st-Mt,e[T+1]=Me-be;continue}if(k===x)continue;let is=l+w-k,Tt=l+h-k;e[is]=xe-s*Ir,e[is+1]=-qe-s*$e,e[Tt]=st-s*Mt,e[Tt+1]=-Me+s*be}}let m=n>>>1;for(let h=2;h<m;h+=2)e[n-h]=e[h],e[n-h+1]=-e[h+1]}_singleRealTransform2(e,r,s,n,o){let a=e[n],i=e[n+o];r[s]=a+i,r[s+1]=0,r[s+2]=a-i,r[s+3]=0}_singleRealTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,u=e[n],p=e[n+o],f=e[n+i],m=e[n+l],h=u+f,w=u-f,x=p+m,k=a*(p-m);r[s]=h+x,r[s+1]=0,r[s+2]=w,r[s+3]=-k,r[s+4]=h-x,r[s+5]=0,r[s+6]=w,r[s+7]=k}},Wp=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let i=-2*Math.PI/e,l=Math.cos(i),u=Math.sin(i);for(let p=0;p<s>>1;++p){let f=(p+1-e)**2/2,m=Math.sqrt(l**2+u**2)**f,h=f*Math.atan2(u,l),w=2*p;o[w]=m*Math.cos(h),o[w+1]=m*Math.sin(h),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new Ol(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,u=this._slicedChirpBuffer,p=this._a;if(s)for(let f=0;f<u.length;f+=2){let m=f+1,h=f>>1,w=r[h];n[f]=w*u[f],n[m]=w*u[m]}else for(let f=0;f<u.length;f+=2){let m=f+1;n[f]=r[f]*u[f]-r[m]*u[m],n[m]=r[f]*u[m]+r[m]*u[f]}this._f.transform(a,n);for(let f=0;f<l.length;f+=2){let m=f+1;o[f]=a[f]*l[f]-a[m]*l[m],o[m]=a[f]*l[m]+a[m]*l[f]}this._f.inverseTransform(i,o);for(let f=0;f<i.length;f+=2){let m=i[f+p],h=i[f+p+1],w=u[f],x=u[f+1];e[f]=m*w-h*x,e[f+1]=m*x+h*w}}transform(e,r){this._transform(e,r,!1)}realTransform(e,r){this._transform(e,r,!0)}},Il=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=yk(e),this.isPowerOfTwo?(this.fft=new Ol(e),this.outputBufferSize=2*e):(this.fft=new Wp(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,r){this.fft.realTransform(e,r)}transform(e,r){this.fft.transform(e,r)}};function bk(t,e){if(e%2===0||e<=0)throw new Error("Window size must be a positive odd number");let r=new t.constructor(t.length),s=new t.constructor(e),n=Math.floor(e/2);for(let o=0;o<t.length;++o){let a=0;for(let i=-n;i<=n;++i){let l=o+i;l<0?l=Math.abs(l):l>=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function gs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function vk(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function kk(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let p=1;p<s[1];++p)for(let f=1;f<s[0];++f){let m=n[f-1][p-1],h=n[f-1][p],w=n[f][p-1],x,k;m<h&&m<w?(x=m,k=0):h<m&&h<w?(x=h,k=1):(x=w,k=2),n[f][p]=t[f-1][p-1]+x,o[f][p]=k}for(let p=0;p<s[1];++p)o[0][p]=2;for(let p=0;p<s[0];++p)o[p][0]=1;let a=e,i=r,l=[],u=[];for(;a>0||i>0;)switch(l.push(a-1),u.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),u.reverse(),[l,u]}var Ek=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l<t.length;++l){let u=0,p=(l&32768)<<16,f=(l&31744)>>10,m=l&1023;if(f===31)u=p|2139095040|m<<13;else if(f===0)if(m===0)u=p;else{let h=113;for(;(m&1024)===0;)m<<=1,--h;m&=-1025,u=p|h<<23|m<<13}else u=p|f+112<<23|m<<13;a[0]=u,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;o<r;++o)n[o]=s[e[o]];return n}})();import*as TP from"onnxruntime-node";var $d={};Vs($d,{InferenceSession:()=>bd,TRACE:()=>Ul,TRACE_EVENT_BEGIN:()=>Dr,TRACE_EVENT_END:()=>Ur,TRACE_FUNC_BEGIN:()=>ks,TRACE_FUNC_END:()=>Es,Tensor:()=>Jt,default:()=>MP,env:()=>Ve,registerBackend:()=>vs});var xd=Object.defineProperty,JC=Object.getOwnPropertyDescriptor,ZC=Object.getOwnPropertyNames,eP=Object.prototype.hasOwnProperty,tP=(t=>typeof ps<"u"?ps:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof ps<"u"?ps:e)[r]}):t)(function(t){if(typeof ps<"u")return ps.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),ye=(t,e)=>()=>(t&&(e=t(t=0)),e),ao=(t,e)=>{for(var r in e)xd(t,r,{get:e[r],enumerable:!0})},rP=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ZC(e))!eP.call(t,n)&&n!==r&&xd(t,n,{get:()=>e[n],enumerable:!(s=JC(e,n))||s.enumerable});return t},Dl=t=>rP(xd({},"__esModule",{value:!0}),t),Zn,Lr,vs,Ak,Jk,Zk=ye(()=>{"use strict";Zn=new Map,Lr=[],vs=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=Zn.get(t);if(s===void 0)Zn.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=Lr.indexOf(t);n!==-1&&Lr.splice(n,1);for(let o=0;o<Lr.length;o++)if(Zn.get(Lr[o]).priority<=r){Lr.splice(o,0,t);return}Lr.push(t)}return}throw new TypeError("not a valid backend")},Ak=async t=>{let e=Zn.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(s){return r||(e.error=`${s}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},Jk=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Lr:r,n,o=[],a=new Set;for(let l of s){let u=await Ak(l);typeof u=="string"?o.push({name:l,err:u}):(n||(n=u),n===u&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,u)=>u==="executionProviders"?i:Reflect.get(l,u)})]}}),sP=ye(()=>{"use strict";Zk()}),eE,nP=ye(()=>{"use strict";eE="1.24.0-dev.20251116-b39e144322"}),Hp,ut,tE=ye(()=>{"use strict";nP(),Hp="warning",ut={wasm:{},webgl:{},webgpu:{},versions:{common:eE},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);Hp=t}},get logLevel(){return Hp}},Object.defineProperty(ut,"logLevel",{enumerable:!0})}),Ve,oP=ye(()=>{"use strict";tE(),Ve=ut}),rE,sE,aP=ye(()=>{"use strict";rE=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,u;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?u=[0,0,0,0]:typeof i.bias=="number"?u=[i.bias,i.bias,i.bias,i.bias]:(u=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(u[3]=i.bias[3]));let p=o*n,f=0,m=p,h=p*2,w=-1;a==="RGBA"?(f=0,m=p,h=p*2,w=p*3):a==="RGB"?(f=0,m=p,h=p*2):a==="RBG"&&(f=0,h=p,m=p*2);for(let x=0;x<o;x++)for(let k=0;k<n;k++){let E=(t.data[f++]-u[0])*l[0],A=(t.data[m++]-u[1])*l[1],S=(t.data[h++]-u[2])*l[2],T=w===-1?255:(t.data[w++]-u[3])*l[3];s.fillStyle="rgba("+E+","+A+","+S+","+T+")",s.fillRect(k,x,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},sE=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,h=0,w=1,x=2,k=3,E=0,A=f,S=f*2,T=-1;i==="RGBA"?(E=0,A=f,S=f*2,T=f*3):i==="RGB"?(E=0,A=f,S=f*2):i==="RBG"&&(E=0,S=f,A=f*2),s=r.createImageData(n,o);for(let P=0;P<o*n;h+=m,w+=m,x+=m,k+=m,P++)s.data[h]=(t.data[E++]-p[0])*u[0],s.data[w]=(t.data[A++]-p[1])*u[1],s.data[x]=(t.data[S++]-p[2])*u[2],s.data[k]=T===-1?255:(t.data[T++]-p[3])*u[3]}else throw new Error("Can not access image data");return s}}),Cl,nE,oE,aE,iE,lE,iP=ye(()=>{"use strict";yd(),Cl=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",u=r*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),f=4,m=0,h=1,w=2,x=3,k=0,E=u,A=u*2,S=-1;i==="RGB"&&(f=3,m=0,h=1,w=2,x=-1),l==="RGBA"?S=u*3:l==="RBG"?(k=0,A=u,E=u*2):l==="BGR"&&(A=0,E=u,k=u*2);for(let T=0;T<u;T++,m+=f,w+=f,h+=f,x+=f)p[k++]=(t[m]+a[0])/o[0],p[E++]=(t[h]+a[1])/o[1],p[A++]=(t[w]+a[2])/o[2],S!==-1&&x!==-1&&(p[S++]=(t[x]+a[3])/o[3]);return l==="RGBA"?new Nt("float32",p,[1,4,r,s]):new Nt("float32",p,[1,3,r,s])},nE=async(t,e)=>{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let f=u(p);if(f!=null){let m=t.height,h=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,h=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=h}else i.tensorFormat="RGBA",i.height=m,i.width=h;f.drawImage(t,0,0),a=f.getImageData(0,0,h,m).data}else throw new Error("Can not access image data")}else if(s){let p,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(p=e.resizedHeight,f=e.resizedWidth):(p=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=p,i.width=f,e!==void 0){let m=l();m.width=f,m.height=p;let h=u(m);if(h!=null)h.putImageData(t,0,0),a=h.getImageData(0,0,f,p).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=t.width,p.height=t.height;let f=u(p);if(f!=null){let m=t.height,h=t.width;return f.drawImage(t,0,0,h,m),a=f.getImageData(0,0,h,m).data,i.height=m,i.width=h,Cl(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,f)=>{let m=l(),h=u(m);if(!t||!h)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,h.drawImage(w,0,0,m.width,m.height);let x=h.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,p(Cl(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Cl(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},oE=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Nt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},aE=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Nt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},iE=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Nt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},lE=(t,e,r)=>new Nt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),ys,no,Xp,cE,lP=ye(()=>{"use strict";ys=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),no=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Xp=!1,cE=()=>{if(!Xp){Xp=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(ys.set("int64",BigInt64Array),no.set(BigInt64Array,"int64")),e&&(ys.set("uint64",BigUint64Array),no.set(BigUint64Array,"uint64")),s?(ys.set("float16",r),no.set(r,"float16")):ys.set("float16",Uint16Array)}}}),uE,pE,cP=ye(()=>{"use strict";yd(),uE=t=>{let e=1;for(let r=0;r<t.length;r++){let s=t[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);e*=s}return e},pE=(t,e)=>{switch(t.location){case"cpu":return new Nt(t.type,t.data,e);case"cpu-pinned":return new Nt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Nt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Nt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Nt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Nt,yd=ye(()=>{"use strict";aP(),iP(),lP(),cP(),Nt=class{constructor(t,e,r){cE();let s,n;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,n=t.dims,t.location){case"cpu-pinned":{let a=ys.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,i;if(typeof t=="string")if(s=t,i=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=ys.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")s="string",a=t;else if(l==="boolean")s="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(t);else{let l=no.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=l,a=t}if(i===void 0)i=[a.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=a,this.dataLocation="cpu"}let o=uE(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(t,e){return nE(t,e)}static fromTexture(t,e){return oE(t,e)}static fromGpuBuffer(t,e){return aE(t,e)}static fromMLTensor(t,e){return iE(t,e)}static fromPinnedBuffer(t,e,r){return lE(t,e,r)}toDataURL(t){return rE(this,t)}toImageData(t){return sE(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return pE(this,t)}}}),Jt,dE=ye(()=>{"use strict";yd(),Jt=Nt}),Ul,Kp,ks,Es,Dr,Ur,fE=ye(()=>{"use strict";tE(),Ul=(t,e)=>{(typeof ut.trace>"u"?!ut.wasm.trace:!ut.trace)||console.timeStamp(`${t}::ORT::${e}`)},Kp=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n<r.length;n++){if(s&&!r[n].includes("TRACE_FUNC")){let o=`FUNC_${t}::${r[n].trim().split(" ")[1]}`;e&&(o+=`::${e}`),Ul("CPU",o);return}r[n].includes("TRACE_FUNC")&&(s=!0)}},ks=t=>{(typeof ut.trace>"u"?!ut.wasm.trace:!ut.trace)||Kp("BEGIN",t)},Es=t=>{(typeof ut.trace>"u"?!ut.wasm.trace:!ut.trace)||Kp("END",t)},Dr=t=>{(typeof ut.trace>"u"?!ut.wasm.trace:!ut.trace)||console.time(`ORT::${t}`)},Ur=t=>{(typeof ut.trace>"u"?!ut.wasm.trace:!ut.trace)||console.timeEnd(`ORT::${t}`)}}),mE,uP=ye(()=>{"use strict";Zk(),dE(),fE(),mE=class hE{constructor(e){this.handler=e}async run(e,r,s){ks(),Dr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof Jt||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Jt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let u of r){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);n[u]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,p=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(p.indexOf(f)!==-1){let m=r[f];(m===null||m instanceof Jt)&&(u=!0,a=!1,n[f]=m)}if(u){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let u of this.inputNames)if(typeof e[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(a)for(let u of this.outputNames)n[u]=null;let i=await this.handler.run(e,n,o),l={};for(let u in i)if(Object.hasOwnProperty.call(i,u)){let p=i[u];p instanceof Jt?l[u]=p:l[u]=new Jt(p.type,p.data,p.dims)}return Ur("InferenceSession.run"),Es(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){ks(),Dr("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let p=e,f=0,m=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(m=e.byteLength-f,typeof s=="number"){if(m=s,!Number.isSafeInteger(m))throw new RangeError("'byteLength' must be an integer.");if(m<=0||f+m>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,f,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await Jk(a),u=await i.createInferenceSessionHandler(o,l);return Ur("InferenceSession.create"),Es(),new hE(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),bd,pP=ye(()=>{"use strict";uP(),bd=mE}),dP=ye(()=>{"use strict"}),fP=ye(()=>{"use strict"}),mP=ye(()=>{"use strict"}),hP=ye(()=>{"use strict"}),_E={};ao(_E,{InferenceSession:()=>bd,TRACE:()=>Ul,TRACE_EVENT_BEGIN:()=>Dr,TRACE_EVENT_END:()=>Ur,TRACE_FUNC_BEGIN:()=>ks,TRACE_FUNC_END:()=>Es,Tensor:()=>Jt,env:()=>Ve,registerBackend:()=>vs});var As=ye(()=>{"use strict";sP(),oP(),pP(),dE(),dP(),fP(),fE(),mP(),hP()}),vd=ye(()=>{"use strict"}),gE={};ao(gE,{default:()=>wE});var Yp,Qp,wE,_P=ye(()=>{"use strict";zE(),Ms(),kd(),Yp="ort-wasm-proxy-worker",Qp=globalThis.self?.name===Yp,Qp&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":Ed(r.wasm).then(()=>{Od(r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})})},s=>{postMessage({type:e,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;Id(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=jl(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;Cd(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":Pd(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;zd(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(u=>u[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},Nd([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":Ld(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),wE=Qp?null:t=>new Worker(t??zt,{type:"module",name:Yp})}),xE={};ao(xE,{default:()=>yE});async function Mk(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(c,d)=>{c.startsWith("./")&&(c=c.substring(2)),(e.Uc||(e.Uc=new Map)).set(c,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let o=()=>{let c=d=>(..._)=>{let g=sr;return _=d(..._),sr!=g?new Promise((b,M)=>{wp={resolve:b,reject:M}}):_};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=c(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(c,d)=>{throw d},u=import.meta.url,p="";if(r||s){try{p=new URL(".",u).href}catch{}s&&(i=c=>{var d=new XMLHttpRequest;return d.open("GET",c,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async c=>{if(C(c))return new Promise((_,g)=>{var b=new XMLHttpRequest;b.open("GET",c,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?_(b.response):g(b.status)},b.onerror=g,b.send(null)});var d=await fetch(c,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,m,h,w,x,k,E=console.log.bind(console),A=console.error.bind(console),S=E,T=A,P=!1,C=c=>c.startsWith("file://");function v(){Cr.buffer!=V.buffer&&pe()}if(n){let c=function(d){try{var _=d.data,g=_.Oc;if(g==="load"){let b=[];self.onmessage=M=>b.push(M),k=()=>{postMessage({Oc:"loaded"});for(let M of b)c(M);self.onmessage=c};for(let M of _.de)e[M]&&!e[M].proxy||(e[M]=(...O)=>{postMessage({Oc:"callHandler",ce:M,args:O})},M=="print"&&(S=e[M]),M=="printErr"&&(T=e[M]));Cr=_.je,pe(),m=_.ke,Je(),xl()}else if(g==="run"){(function(b){var M=(v(),z)[b+52>>>2>>>0];b=(v(),z)[b+56>>>2>>>0],L1(M,M-b),ie(M)})(_.Nc),Ip(_.Nc,0,0,1,0,0),bb(),hp(_.Nc),H||(_1(),H=!0);try{I2(_.he,_.Wc)}catch(b){if(b!="unwind")throw b}}else _.target!=="setimmediate"&&(g==="checkMailbox"?H&&pl():g&&(T(`worker: received unknown command ${g}`),T(_)))}catch(b){throw O1(),b}};var F=c,H=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=c}var V,J,X,Y,U,z,ne,ae,I,L,R,te=!1;function pe(){var c=Cr.buffer;e.HEAP8=V=new Int8Array(c),X=new Int16Array(c),e.HEAPU8=J=new Uint8Array(c),Y=new Uint16Array(c),e.HEAP32=U=new Int32Array(c),e.HEAPU32=z=new Uint32Array(c),ne=new Float32Array(c),ae=new Float64Array(c),I=new BigInt64Array(c),L=new BigUint64Array(c)}function Fe(){te=!0,n?k():br._b()}function Pe(c){throw T(c="Aborted("+c+")"),P=!0,c=new WebAssembly.RuntimeError(c+". Build with -sASSERTIONS for more info."),x?.(c),c}function At(){return{a:{f:C2,J:P2,k:z2,p:L2,l:N2,ta:$2,b:R2,ca:D2,Ka:Tb,s:U2,da:Cb,_a:Pb,Ga:zb,Ia:Lb,$a:Nb,Ya:$b,Ra:Rb,Xa:Db,pa:Ub,Ha:Bb,Yb:Fb,Za:jb,Fa:Gb,eb:B2,Da:j2,Tb:G2,Rb:W2,Ca:H2,M:X2,H:K2,Sb:Y2,ka:sM,Ub:nM,Ua:oM,Wb:iM,La:lM,Pb:cM,la:uM,Ta:hp,bb:pM,U:hM,n:yM,c:fp,sb:bM,w:vM,L:kM,z:EM,j:AM,o:Qb,tb:MM,G:TM,T:SM,g:OM,u:IM,m:CM,i:PM,Oa:zM,Pa:LM,Qa:NM,Ma:t1,Na:r1,Qb:s1,fb:RM,db:BM,Y:FM,rb:jM,ma:GM,cb:DM,gb:qM,ab:WM,Xb:VM,N:$M,hb:HM,X:XM,Vb:KM,ob:nT,C:oT,sa:aT,ra:iT,qb:lT,W:cT,v:uT,nb:pT,mb:dT,lb:fT,pb:mT,kb:hT,jb:_T,ib:gT,Va:c1,Wa:u1,Ja:Tt,ea:p1,oa:d1,Sa:f1,na:m1,Db:TS,xa:xS,Eb:MS,ya:wS,F:lS,e:KT,r:HT,x:VT,D:oS,Ib:hS,ba:fS,B:QT,za:_S,$:yS,ha:mS,Fb:ES,Gb:kS,Ba:cS,Aa:dS,Jb:uS,wa:AS,aa:gS,d:YT,A:JT,q:XT,Cb:SS,t:eS,y:aS,I:ZT,E:tS,K:iS,S:bS,ja:nS,_:vS,Kb:sS,Lb:rS,P:pS,h:xT,a:Cr,Ob:Ir,Hb:yT,ia:bT,O:vT,qa:kT,Mb:ET,Q:AT,zb:MT,Ab:TT,ua:ST,fa:OT,R:IT,Ea:CT,va:PT,Z:zT,xb:LT,Zb:NT,V:$T,Bb:RT,ub:DT,vb:BT,wb:FT,ga:jT,yb:GT,Nb:qT}}}async function Je(){function c(g,b){var M=br=g.exports;g={};for(let[O,N]of Object.entries(M))typeof N=="function"?(M=dM(N),g[O]=M):g[O]=N;return br=g,br=(function(){var O=br,N=K=>Te=>K(Te)>>>0,B=K=>()=>K()>>>0;return(O=Object.assign({},O)).$b=N(O.$b),O.Cc=B(O.Cc),O.Ec=N(O.Ec),O.rd=(K=>(Te,ze)=>K(Te,ze)>>>0)(O.rd),O.wd=N(O.wd),O.xd=B(O.xd),O.Bd=N(O.Bd),O})(),xb.push(br.id),h1=(g=br).$b,_1=g.ac,e._OrtInit=g.bc,e._OrtGetLastError=g.cc,e._OrtCreateSessionOptions=g.dc,e._OrtAppendExecutionProvider=g.ec,e._OrtAddFreeDimensionOverride=g.fc,e._OrtAddSessionConfigEntry=g.gc,e._OrtReleaseSessionOptions=g.hc,e._OrtCreateSession=g.ic,e._OrtReleaseSession=g.jc,e._OrtGetInputOutputCount=g.kc,e._OrtGetInputOutputMetadata=g.lc,e._OrtFree=g.mc,e._OrtCreateTensor=g.nc,e._OrtGetTensorData=g.oc,e._OrtReleaseTensor=g.pc,e._OrtCreateRunOptions=g.qc,e._OrtAddRunConfigEntry=g.rc,e._OrtReleaseRunOptions=g.sc,e._OrtCreateBinding=g.tc,e._OrtBindInput=g.uc,e._OrtBindOutput=g.vc,e._OrtClearBoundOutputs=g.wc,e._OrtReleaseBinding=g.xc,e._OrtRunWithBinding=g.yc,e._OrtRun=g.zc,e._OrtEndProfiling=g.Ac,Ep=e._OrtGetWebGpuDevice=g.Bc,gl=g.Cc,Ht=e._free=g.Dc,Ws=e._malloc=g.Ec,g1=e._wgpuBufferRelease=g.Fc,w1=e._wgpuCreateInstance=g.Gc,x1=g.Hc,y1=g.Ic,b1=g.Jc,v1=g.Kc,k1=g.Lc,E1=g.Pc,A1=g.Zc,M1=g._c,T1=g.$c,Ap=g.bd,Mp=g.cd,Tp=g.dd,Sp=g.ed,Gn=g.fd,Op=g.gd,S1=g.hd,Ip=g.kd,O1=g.ld,I1=g.md,C1=g.nd,Cp=g.od,P1=g.pd,z1=g.qd,Pp=g.rd,_e=g.sd,qn=g.td,L1=g.ud,ie=g.vd,wl=g.wd,le=g.xd,N1=g.yd,zp=g.zd,$1=g.Ad,R1=g.Bd,D1=g.Cd,Lp=g.Dd,U1=g.Ed,B1=g.Fd,F1=g.Gd,j1=g.Hd,G1=g.Id,q1=g.Jd,W1=g.Kd,V1=g.Ld,H1=g.Md,X1=g.Nd,K1=g.Od,Y1=g.Pd,Q1=g.Qd,J1=g.Rd,Z1=g.Td,ev=g.Ud,tv=g.Vd,rv=g.Wd,sv=g.Yd,nv=g.Zd,ov=g._d,av=g.$d,iv=g.ae,lv=g.be,cv=g.pe,uv=g.qe,pv=g.re,dv=g.se,fv=g.te,mv=g.ue,hv=g.ve,_v=g.we,gv=g.xe,wv=g.ye,xv=g.ze,yv=g.Xe,bv=g.Ye,vv=g.Ze,kv=g._e,m=b,br}var d,_=At();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(_,(b,M)=>{g(c(b,M))})}):n?c(new WebAssembly.Instance(m,At()),m):(R??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",p):p+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,d=await(async function(g){var b=R;if(!f&&!C(b))try{var M=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(M,g)}catch(O){T(`wasm streaming compile failed: ${O}`),T("falling back to ArrayBuffer instantiation")}return(async function(O,N){try{var B=await(async function(K){if(!f)try{var Te=await a(K);return new Uint8Array(Te)}catch{}if(K==R&&f)K=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";K=i(K)}return K})(O);return await WebAssembly.instantiate(B,N)}catch(K){T(`failed to asynchronously prepare wasm: ${K}`),Pe(K)}})(b,g)})(_),c(d.instance,d.module))}class et{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var st=c=>{c.terminate(),c.onmessage=()=>{}},Me=[],xe=0,qe=null,Mt=c=>{tt.length==0&&(kb(),vb(tt[0]));var d=tt.pop();if(!d)return 6;Bn.push(d),ls[c.Nc]=d,d.Nc=c.Nc;var _={Oc:"run",he:c.ge,Wc:c.Wc,Nc:c.Nc};return d.postMessage(_,c.Yc),0},be=0,$e=(c,d,..._)=>{var g,b=16*_.length,M=le(),O=wl(b),N=O>>>3;for(g of _)typeof g=="bigint"?((v(),I)[N++>>>0]=1n,(v(),I)[N++>>>0]=g):((v(),I)[N++>>>0]=0n,(v(),ae)[N++>>>0]=g);return c=I1(c,0,b,O,d),ie(M),c};function Ir(c){if(n)return $e(0,1,c);if(h=c,!(0<be)){for(var d of Bn)st(d);for(d of tt)st(d);tt=[],Bn=[],ls={},P=!0}l(0,new et(c))}function is(c){if(n)return $e(1,0,c);Tt(c)}var Tt=c=>{if(h=c,n)throw is(c),"unwind";Ir(c)},tt=[],Bn=[],xb=[],ls={},yb=c=>{var d=c.Nc;delete ls[d],tt.push(c),Bn.splice(Bn.indexOf(c),1),c.Nc=0,C1(d)};function bb(){xb.forEach(c=>c())}var vb=c=>new Promise(d=>{c.onmessage=b=>{var M=b.data;if(b=M.Oc,M.Vc&&M.Vc!=gl()){var O=ls[M.Vc];O?O.postMessage(M,M.Yc):T(`Internal error! Worker sent a message "${b}" to target pthread ${M.Vc}, but that thread no longer exists!`)}else b==="checkMailbox"?pl():b==="spawnThread"?Mt(M):b==="cleanupThread"?bt(()=>{yb(ls[M.ie])}):b==="loaded"?(c.loaded=!0,d(c)):M.target==="setimmediate"?c.postMessage(M):b==="uncaughtException"?c.onerror(M.error):b==="callHandler"?e[M.ce](...M.args):b&&T(`worker sent an unknown command ${b}`)},c.onerror=b=>{throw T(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b};var _,g=[];for(_ of[])e.propertyIsEnumerable(_)&&g.push(_);c.postMessage({Oc:"load",de:g,je:Cr,ke:m})});function kb(){var c=new Worker((()=>{let d=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new d("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});tt.push(c)}var Cr,I2=(c,d)=>{be=0,c=Lp(c,d),0<be?h=c:Cp(c)},cl=[],ul=0,yt=c=>-9007199254740992>c||9007199254740992<c?NaN:Number(c);function C2(c){var d=new cp(c>>>=0);return(v(),V)[d.Qc+12>>>0]==0&&(Eb(d,!0),ul--),Ab(d,!1),cl.push(d),R1(c)}var Fs=0,P2=()=>{_e(0,0);var c=cl.pop();N1(c.Xc),Fs=0};function Eb(c,d){d=d?1:0,(v(),V)[c.Qc+12>>>0]=d}function Ab(c,d){d=d?1:0,(v(),V)[c.Qc+13>>>0]=d}class cp{constructor(d){this.Xc=d,this.Qc=d-24}}var up=c=>{var d=Fs;if(!d)return qn(0),0;var _=new cp(d);(v(),z)[_.Qc+16>>>2>>>0]=d;var g=(v(),z)[_.Qc+4>>>2>>>0];if(!g)return qn(0),d;for(var b of c){if(b===0||b===g)break;if($1(b,g,_.Qc+16))return qn(b),d}return qn(g),d};function z2(){return up([])}function L2(c){return up([c>>>0])}function N2(c,d,_,g){return up([c>>>0,d>>>0,_>>>0,g>>>0])}var $2=()=>{var c=cl.pop();c||Pe("no exception to throw");var d=c.Xc;throw(v(),V)[c.Qc+13>>>0]==0&&(cl.push(c),Ab(c,!0),Eb(c,!1),ul++),zp(d),Fs=d};function R2(c,d,_){var g=new cp(c>>>=0);throw d>>>=0,_>>>=0,(v(),z)[g.Qc+16>>>2>>>0]=0,(v(),z)[g.Qc+4>>>2>>>0]=d,(v(),z)[g.Qc+8>>>2>>>0]=_,zp(c),ul++,Fs=c}var D2=()=>ul;function Mb(c,d,_,g){return n?$e(2,1,c,d,_,g):Tb(c,d,_,g)}function Tb(c,d,_,g){if(c>>>=0,d>>>=0,_>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var b=[];return n&&b.length===0?Mb(c,d,_,g):(c={ge:_,Nc:c,Wc:g,Yc:b},n?(c.Oc="spawnThread",postMessage(c,b),0):Mt(c))}function U2(c){throw Fs||=c>>>0,Fs}var Sb=globalThis.TextDecoder&&new TextDecoder,Ob=(c,d,_,g)=>{if(_=d+_,g)return _;for(;c[d]&&!(d>=_);)++d;return d},Ib=(c,d=0,_,g)=>{if(16<(_=Ob(c,d>>>=0,_,g))-d&&c.buffer&&Sb)return Sb.decode(c.buffer instanceof ArrayBuffer?c.subarray(d,_):c.slice(d,_));for(g="";d<_;){var b=c[d++];if(128&b){var M=63&c[d++];if((224&b)==192)g+=String.fromCharCode((31&b)<<6|M);else{var O=63&c[d++];65536>(b=(240&b)==224?(15&b)<<12|M<<6|O:(7&b)<<18|M<<12|O<<6|63&c[d++])?g+=String.fromCharCode(b):(b-=65536,g+=String.fromCharCode(55296|b>>10,56320|1023&b))}}else g+=String.fromCharCode(b)}return g},js=(c,d,_)=>(c>>>=0)?Ib((v(),J),c,d,_):"";function Cb(c,d,_){return n?$e(3,1,c,d,_):0}function Pb(c,d){if(n)return $e(4,1,c,d)}function zb(c,d){if(n)return $e(5,1,c,d)}function Lb(c,d,_){if(n)return $e(6,1,c,d,_)}function Nb(c,d,_){return n?$e(7,1,c,d,_):0}function $b(c,d){if(n)return $e(8,1,c,d)}function Rb(c,d,_){if(n)return $e(9,1,c,d,_)}function Db(c,d,_,g){if(n)return $e(10,1,c,d,_,g)}function Ub(c,d,_,g){if(n)return $e(11,1,c,d,_,g)}function Bb(c,d,_,g){if(n)return $e(12,1,c,d,_,g)}function Fb(c){if(n)return $e(13,1,c)}function jb(c,d){if(n)return $e(14,1,c,d)}function Gb(c,d,_){if(n)return $e(15,1,c,d,_)}var B2=()=>Pe(""),rr=c=>{c>>>=0;for(var d="";;){var _=(v(),J)[c++>>>0];if(!_)return d;d+=String.fromCharCode(_)}},pp={},dp={},F2={},Gs=class extends Error{constructor(c){super(c),this.name="BindingError"}};function _r(c,d,_={}){return(function(g,b,M={}){var O=b.name;if(!g)throw new Gs(`type "${O}" must have a positive integer typeid pointer`);if(dp.hasOwnProperty(g)){if(M.ee)return;throw new Gs(`Cannot register type '${O}' twice`)}dp[g]=b,delete F2[g],pp.hasOwnProperty(g)&&(b=pp[g],delete pp[g],b.forEach(N=>N()))})(c,d,_)}var qb=(c,d,_)=>{switch(d){case 1:return _?g=>(v(),V)[g>>>0]:g=>(v(),J)[g>>>0];case 2:return _?g=>(v(),X)[g>>>1>>>0]:g=>(v(),Y)[g>>>1>>>0];case 4:return _?g=>(v(),U)[g>>>2>>>0]:g=>(v(),z)[g>>>2>>>0];case 8:return _?g=>(v(),I)[g>>>3>>>0]:g=>(v(),L)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${c}`)}};function j2(c,d,_,g,b){c>>>=0,_>>>=0,d=rr(d>>>0);let M=O=>O;if(g=g===0n){let O=8*_;M=N=>BigInt.asUintN(O,N),b=M(b)}_r(c,{name:d,Mc:M,Sc:(O,N)=>(typeof N=="number"&&(N=BigInt(N)),N),Rc:qb(d,_,!g),Tc:null})}function G2(c,d,_,g){_r(c>>>=0,{name:d=rr(d>>>0),Mc:function(b){return!!b},Sc:function(b,M){return M?_:g},Rc:function(b){return this.Mc((v(),J)[b>>>0])},Tc:null})}var Wb=[],cs=[0,1,,1,null,1,!0,1,!1,1];function fp(c){9<(c>>>=0)&&--cs[c+1]==0&&(cs[c]=void 0,Wb.push(c))}var Rt=c=>{if(!c)throw new Gs(`Cannot use deleted val. handle = ${c}`);return cs[c]},Vt=c=>{switch(c){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=Wb.pop()||cs.length;return cs[d]=c,cs[d+1]=1,d}};function mp(c){return this.Mc((v(),z)[c>>>2>>>0])}var q2={name:"emscripten::val",Mc:c=>{var d=Rt(c);return fp(c),d},Sc:(c,d)=>Vt(d),Rc:mp,Tc:null};function W2(c){return _r(c>>>0,q2)}var V2=(c,d)=>{switch(d){case 4:return function(_){return this.Mc((v(),ne)[_>>>2>>>0])};case 8:return function(_){return this.Mc((v(),ae)[_>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${c}`)}};function H2(c,d,_){_>>>=0,_r(c>>>=0,{name:d=rr(d>>>0),Mc:g=>g,Sc:(g,b)=>b,Rc:V2(d,_),Tc:null})}function X2(c,d,_,g,b){c>>>=0,_>>>=0,d=rr(d>>>0);let M=N=>N;if(g===0){var O=32-8*_;M=N=>N<<O>>>O,b=M(b)}_r(c,{name:d,Mc:M,Sc:(N,B)=>B,Rc:qb(d,_,g!==0),Tc:null})}function K2(c,d,_){function g(M){var O=(v(),z)[M>>>2>>>0];return M=(v(),z)[M+4>>>2>>>0],new b((v(),V).buffer,M,O)}var b=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];_r(c>>>=0,{name:_=rr(_>>>0),Mc:g,Rc:g},{ee:!0})}var gr=(c,d,_)=>{var g=(v(),J);if(d>>>=0,0<_){var b=d;_=d+_-1;for(var M=0;M<c.length;++M){var O=c.codePointAt(M);if(127>=O){if(d>=_)break;g[d++>>>0]=O}else if(2047>=O){if(d+1>=_)break;g[d++>>>0]=192|O>>6,g[d++>>>0]=128|63&O}else if(65535>=O){if(d+2>=_)break;g[d++>>>0]=224|O>>12,g[d++>>>0]=128|O>>6&63,g[d++>>>0]=128|63&O}else{if(d+3>=_)break;g[d++>>>0]=240|O>>18,g[d++>>>0]=128|O>>12&63,g[d++>>>0]=128|O>>6&63,g[d++>>>0]=128|63&O,M++}}g[d>>>0]=0,c=d-b}else c=0;return c},wr=c=>{for(var d=0,_=0;_<c.length;++_){var g=c.charCodeAt(_);127>=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++_):d+=3}return d};function Y2(c,d){_r(c>>>=0,{name:d=rr(d>>>0),Mc(_){var g=(v(),z)[_>>>2>>>0];return g=js(_+4,g,!0),Ht(_),g},Sc(_,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var b=typeof g=="string";if(!(b||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Gs("Cannot pass non-string to std::string");var M=b?wr(g):g.length,O=Ws(4+M+1),N=O+4;return(v(),z)[O>>>2>>>0]=M,b?gr(g,N,M+1):(v(),J).set(g,N>>>0),_!==null&&_.push(Ht,O),O},Rc:mp,Tc(_){Ht(_)}})}var Vb=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Q2=(c,d,_)=>{if(c>>>=1,16<(d=Ob((v(),Y),c,d/2,_))-c&&Vb)return Vb.decode((v(),Y).slice(c,d));for(_="";c<d;++c){var g=(v(),Y)[c>>>0];_+=String.fromCharCode(g)}return _},J2=(c,d,_)=>{if(_??=2147483647,2>_)return 0;var g=d;_=(_-=2)<2*c.length?_/2:c.length;for(var b=0;b<_;++b){var M=c.charCodeAt(b);(v(),X)[d>>>1>>>0]=M,d+=2}return(v(),X)[d>>>1>>>0]=0,d-g},Z2=c=>2*c.length,eM=(c,d,_)=>{var g="";c>>>=2;for(var b=0;!(b>=d/4);b++){var M=(v(),z)[c+b>>>0];if(!M&&!_)break;g+=String.fromCodePoint(M)}return g},tM=(c,d,_)=>{if(d>>>=0,_??=2147483647,4>_)return 0;var g=d;_=g+_-4;for(var b=0;b<c.length;++b){var M=c.codePointAt(b);if(65535<M&&b++,(v(),U)[d>>>2>>>0]=M,(d+=4)+4>_)break}return(v(),U)[d>>>2>>>0]=0,d-g},rM=c=>{for(var d=0,_=0;_<c.length;++_)65535<c.codePointAt(_)&&_++,d+=4;return d};function sM(c,d,_){if(c>>>=0,d>>>=0,_=rr(_>>>=0),d===2)var g=Q2,b=J2,M=Z2;else g=eM,b=tM,M=rM;_r(c,{name:_,Mc:O=>{var N=(v(),z)[O>>>2>>>0];return N=g(O+4,N*d,!0),Ht(O),N},Sc:(O,N)=>{if(typeof N!="string")throw new Gs(`Cannot pass non-string to C++ string type ${_}`);var B=M(N),K=Ws(4+B+d);return(v(),z)[K>>>2>>>0]=B/d,b(N,K+4,B+d),O!==null&&O.push(Ht,K),K},Rc:mp,Tc(O){Ht(O)}})}function nM(c,d){_r(c>>>=0,{fe:!0,name:d=rr(d>>>0),Mc:()=>{},Sc:()=>{}})}function oM(c){Ip(c>>>0,!s,1,!r,131072,!1),bb()}var bt=c=>{if(!P)try{if(c(),!(0<be))try{n?gl()&&Cp(h):Tt(h)}catch(d){d instanceof et||d=="unwind"||l(0,d)}}catch(d){d instanceof et||d=="unwind"||l(0,d)}},aM=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function hp(c){c>>>=0,aM||(Atomics.waitAsync((v(),U),c>>>2,c).value.then(pl),c+=128,Atomics.store((v(),U),c>>>2,1))}var pl=()=>bt(()=>{var c=gl();c&&(hp(c),z1())});function iM(c,d){(c>>>=0)==d>>>0?setTimeout(pl):n?postMessage({Vc:c,Oc:"checkMailbox"}):(c=ls[c])&&c.postMessage({Oc:"checkMailbox"})}var _p=[];function lM(c,d,_,g,b){for(d>>>=0,b>>>=0,_p.length=0,_=b>>>3,g=b+g>>>3;_<g;){var M;M=(v(),I)[_++>>>0]?(v(),I)[_++>>>0]:(v(),ae)[_++>>>0],_p.push(M)}return(d?Np[d]:WT[c])(..._p)}var cM=()=>{be=0};function uM(c){c>>>=0,n?postMessage({Oc:"cleanupThread",ie:c}):yb(ls[c])}function pM(c){}var dl=c=>{try{c()}catch(d){Pe(d)}};function dM(c){var d=(..._)=>{fl.push(c);try{return c(..._)}finally{P||(fl.pop(),sr&&Pr===1&&fl.length===0&&(Pr=0,be+=1,dl(bv),typeof Fibers<"u"&&Fibers.De()))}};return Kb.set(c,d),d}var Pr=0,sr=null,Hb=0,fl=[],gp=new Map,Xb=new Map,Kb=new Map,fM=0,wp=null,mM=[],Yb=c=>(function(d){if(!P){if(Pr===0){var _=!1,g=!1;d((b=0)=>{if(!P&&(Hb=b,_=!0,g)){Pr=2,dl(()=>vv(sr)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),b=!1;try{var M=(function(){var B=(v(),U)[sr+8>>>2>>>0];return B=Xb.get(B),B=Kb.get(B),--be,B()})()}catch(B){M=B,b=!0}var O=!1;if(!sr){var N=wp;N&&(wp=null,(b?N.reject:N.resolve)(M),O=!0)}if(b&&!O)throw M}}),g=!0,_||(Pr=1,sr=(function(){var b=Ws(65548),M=b+12;if((v(),z)[b>>>2>>>0]=M,(v(),z)[b+4>>>2>>>0]=M+65536,M=fl[0],!gp.has(M)){var O=fM++;gp.set(M,O),Xb.set(O,M)}return M=gp.get(M),(v(),U)[b+8>>>2>>>0]=M,b})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),dl(()=>yv(sr)))}else Pr===2?(Pr=0,dl(kv),Ht(sr),sr=null,mM.forEach(bt)):Pe(`invalid state: ${Pr}`);return Hb}})(d=>{c().then(d)});function hM(c){return c>>>=0,Yb(async()=>{var d=await Rt(c);return Vt(d)})}var xp=[],_M=c=>{var d=xp.length;return xp.push(c),d},gM=(c,d)=>{for(var _=Array(c),g=0;g<c;++g){var b=g,M=(v(),z)[d+4*g>>>2>>>0],O=dp[M];if(O===void 0)throw c=`parameter ${g}`,M=h1(M),d=rr(M),Ht(M),new Gs(`${c} has unknown type ${d}`);_[b]=O}return _},wM=(c,d,_)=>{var g=[];return c=c(g,_),g.length&&((v(),z)[d>>>2>>>0]=Vt(g)),c},xM={},ml=c=>{var d=xM[c];return d===void 0?rr(c):d};function yM(c,d,_){var[g,...b]=gM(c,d>>>0);d=g.Sc.bind(g);var M=b.map(B=>B.Rc.bind(B));c--;var O={toValue:Rt};switch(c=M.map((B,K)=>{var Te=`argFromPtr${K}`;return O[Te]=B,`${Te}(args${K?"+"+8*K:""})`}),_){case 0:var N="toValue(handle)";break;case 2:N="new (toValue(handle))";break;case 3:N="";break;case 1:O.getStringOrSymbol=ml,N="toValue(handle)[getStringOrSymbol(methodName)]"}return N+=`(${c})`,g.fe||(O.toReturnWire=d,O.emval_returnValue=wM,N=`return emval_returnValue(toReturnWire, destructorsRef, ${N})`),N=`return function (handle, methodName, destructorsRef, args) {
11
11
  ${N}
12
- }`,h=new Function(Object.keys(O),N)(...Object.values(O)),N=`methodCaller<(${b.map(D=>D.name)}) => ${g.name}>`,L2(Object.defineProperty(h,"name",{value:N}))}function B2(c,p){return p>>>=0,(c=zt(c>>>0))==zt(p)}function D2(c){return(c>>>=0)?(c=Mi(c),qt(globalThis[c])):qt(globalThis)}function F2(c){return c=Mi(c>>>0),qt(e[c])}function j2(c,p){return p>>>=0,c=zt(c>>>0),p=zt(p),qt(c[p])}function G2(c){9<(c>>>=0)&&(Kr[c+1]+=1)}function Eb(c,p,h,g,b){return Ku[c>>>0](p>>>0,h>>>0,g>>>0,b>>>0)}function q2(c,p,h,g,b){return Eb(c>>>0,p>>>0,h>>>0,g>>>0,b>>>0)}function W2(){return qt([])}function V2(c){c=zt(c>>>0);for(var p=Array(c.length),h=0;h<c.length;h++)p[h]=c[h];return qt(p)}function H2(c){return qt(Mi(c>>>0))}function X2(){return qt({})}function K2(c){for(var p=zt(c>>>=0);p.length;){var h=p.pop();p.pop()(h)}Gu(c)}function Y2(c,p,h){p>>>=0,h>>>=0,c=zt(c>>>0),p=zt(p),h=zt(h),c[p]=h}function Q2(c,p){c=wt(c),p>>>=0,c=new Date(1e3*c),(v(),B)[p>>>2>>>0]=c.getUTCSeconds(),(v(),B)[p+4>>>2>>>0]=c.getUTCMinutes(),(v(),B)[p+8>>>2>>>0]=c.getUTCHours(),(v(),B)[p+12>>>2>>>0]=c.getUTCDate(),(v(),B)[p+16>>>2>>>0]=c.getUTCMonth(),(v(),B)[p+20>>>2>>>0]=c.getUTCFullYear()-1900,(v(),B)[p+24>>>2>>>0]=c.getUTCDay(),c=(c.getTime()-Date.UTC(c.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(v(),B)[p+28>>>2>>>0]=c}var Ab=c=>c%4==0&&(c%100!=0||c%400==0),Mb=[0,31,60,91,121,152,182,213,244,274,305,335],Tb=[0,31,59,90,120,151,181,212,243,273,304,334];function J2(c,p){c=wt(c),p>>>=0,c=new Date(1e3*c),(v(),B)[p>>>2>>>0]=c.getSeconds(),(v(),B)[p+4>>>2>>>0]=c.getMinutes(),(v(),B)[p+8>>>2>>>0]=c.getHours(),(v(),B)[p+12>>>2>>>0]=c.getDate(),(v(),B)[p+16>>>2>>>0]=c.getMonth(),(v(),B)[p+20>>>2>>>0]=c.getFullYear()-1900,(v(),B)[p+24>>>2>>>0]=c.getDay();var h=(Ab(c.getFullYear())?Mb:Tb)[c.getMonth()]+c.getDate()-1|0;(v(),B)[p+28>>>2>>>0]=h,(v(),B)[p+36>>>2>>>0]=-60*c.getTimezoneOffset(),h=new Date(c.getFullYear(),6,1).getTimezoneOffset();var g=new Date(c.getFullYear(),0,1).getTimezoneOffset();c=0|(h!=g&&c.getTimezoneOffset()==Math.min(g,h)),(v(),B)[p+32>>>2>>>0]=c}function Z2(c){c>>>=0;var p=new Date((v(),B)[c+20>>>2>>>0]+1900,(v(),B)[c+16>>>2>>>0],(v(),B)[c+12>>>2>>>0],(v(),B)[c+8>>>2>>>0],(v(),B)[c+4>>>2>>>0],(v(),B)[c>>>2>>>0],0),h=(v(),B)[c+32>>>2>>>0],g=p.getTimezoneOffset(),b=new Date(p.getFullYear(),6,1).getTimezoneOffset(),A=new Date(p.getFullYear(),0,1).getTimezoneOffset(),O=Math.min(A,b);return 0>h?(v(),B)[c+32>>>2>>>0]=+(b!=A&&O==g):0<h!=(O==g)&&(b=Math.max(A,b),p.setTime(p.getTime()+6e4*((0<h?O:b)-g))),(v(),B)[c+24>>>2>>>0]=p.getDay(),h=(Ab(p.getFullYear())?Mb:Tb)[p.getMonth()]+p.getDate()-1|0,(v(),B)[c+28>>>2>>>0]=h,(v(),B)[c>>>2>>>0]=p.getSeconds(),(v(),B)[c+4>>>2>>>0]=p.getMinutes(),(v(),B)[c+8>>>2>>>0]=p.getHours(),(v(),B)[c+12>>>2>>>0]=p.getDate(),(v(),B)[c+16>>>2>>>0]=p.getMonth(),(v(),B)[c+20>>>2>>>0]=p.getYear(),c=p.getTime(),BigInt(isNaN(c)?-1:c/1e3)}function Sb(c,p,h,g,b,A,O){return n?Le(16,1,c,p,h,g,b,A,O):-52}function Ob(c,p,h,g,b,A){if(n)return Le(17,1,c,p,h,g,b,A)}var On={},eM=()=>performance.timeOrigin+performance.now();function Ib(c,p){if(n)return Le(18,1,c,p);if(On[c]&&(clearTimeout(On[c].id),delete On[c]),!p)return 0;var h=setTimeout(()=>{delete On[c],vi(()=>i1(c,performance.timeOrigin+performance.now()))},p);return On[c]={id:h,Ne:p},0}function tM(c,p,h,g){c>>>=0,p>>>=0,h>>>=0,g>>>=0;var b=new Date().getFullYear(),A=new Date(b,0,1).getTimezoneOffset();b=new Date(b,6,1).getTimezoneOffset();var O=Math.max(A,b);(v(),P)[c>>>2>>>0]=60*O,(v(),B)[p>>>2>>>0]=+(A!=b),c=(p=N=>{var D=Math.abs(N);return`UTC${0<=N?"-":"+"}${String(Math.floor(D/60)).padStart(2,"0")}${String(D%60).padStart(2,"0")}`})(A),p=p(b),b<A?(ur(c,h,17),ur(p,g,17)):(ur(c,g,17),ur(p,h,17))}var rM=()=>Date.now(),sM=1;function nM(c,p,h){if(h>>>=0,!(0<=c&&3>=c))return 28;if(c===0)c=Date.now();else{if(!sM)return 52;c=performance.timeOrigin+performance.now()}return c=Math.round(1e6*c),(v(),S)[h>>>3>>>0]=BigInt(c),0}var Yu=[],Cb=(c,p)=>{Yu.length=0;for(var h;h=(v(),Q)[c++>>>0];){var g=h!=105;p+=(g&=h!=112)&&p%8?4:0,Yu.push(h==112?(v(),P)[p>>>2>>>0]:h==106?(v(),S)[p>>>3>>>0]:h==105?(v(),B)[p>>>2>>>0]:(v(),ie)[p>>>3>>>0]),p+=g?8:4}return Yu};function oM(c,p,h){return c>>>=0,p=Cb(p>>>0,h>>>0),pp[c](...p)}function aM(c,p,h){return c>>>=0,p=Cb(p>>>0,h>>>0),pp[c](...p)}var iM=()=>{};function lM(c,p){return T(Ts(c>>>0,p>>>0))}var cM=()=>{throw ge+=1,"unwind"};function uM(){return 4294901760}var pM=()=>1,dM=()=>navigator.hardwareConcurrency,Yr={},Pb=c=>{var p=pr(c)+1,h=Cs(p);return h&&ur(c,h,p),h},Ti=c=>{var p;return(p=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(c))?+p[1]:(p=/:(\d+):\d+(?:\)|$)/.exec(c))?2147483648|+p[1]:0},zb=c=>{for(var p of c)(c=Ti(p))&&(Yr[c]=p)};function fM(){var c=Error().stack.toString().split(`
13
- `);return c[0]=="Error"&&c.shift(),zb(c),Yr.Xd=Ti(c[3]),Yr.re=c,Yr.Xd}function Si(c){if(!(c=Yr[c>>>0]))return 0;var p;if(p=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(c))c=p[1];else if(p=/^\s+at (.*) \(.*\)$/.exec(c))c=p[1];else{if(!(p=/^(.+?)@/.exec(c)))return 0;c=p[1]}return Lt(Si.ae??0),Si.ae=Pb(c),Si.ae}function mM(c){c>>>=0;var p=(v(),Q).length;if(c<=p||4294901760<c)return!1;for(var h=1;4>=h;h*=2){var g=p*(1+.2/h);g=Math.min(g,c+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(c,g)/65536))-yr.buffer.byteLength+65535)/65536|0;try{yr.grow(g),ue();var b=1;break e}catch{}b=void 0}if(b)return!0}return!1}function hM(c,p,h){if(c>>>=0,p>>>=0,Yr.Xd==c)var g=Yr.re;else(g=Error().stack.toString().split(`
14
- `))[0]=="Error"&&g.shift(),zb(g);for(var b=3;g[b]&&Ti(g[b])!=c;)++b;for(c=0;c<h&&g[c+b];++c)(v(),B)[p+4*c>>>2>>>0]=Ti(g[c+b]);return c}var tr=c=>{var p=pr(c)+1,h=Pi(p);return ur(c,h,p),h},Qu=[],xt=(c,p)=>{Qu[c>>>=0]=p},rr=[],Oi=[],Os=(c,p)=>{Oi[c]=new Promise(h=>p.finally(()=>h(c)))},re=c=>{if(c)return Qu[c>>>0]},Ii=(c,p,h)=>{(v(),P)[c>>>2>>>0]=p,(v(),P)[c+4>>>2>>>0]=h},Lb=c=>{var p=(v(),P)[c>>>2>>>0];return c=(v(),P)[c+4>>>2>>>0],Ts(p,c)},dr=c=>{var p=(v(),P)[c>>>2>>>0];return c=(v(),P)[c+4>>>2>>>0],p?Ts(p,c):c===0?"":void 0},_M=c=>{var p=dr(c+4),h=(h=(v(),P)[c+12>>>2>>>0])?re(h):"auto";if(c+=16){var g=re((v(),P)[c+4>>>2>>>0]),b=(v(),P)[c+16>>>2>>>0],A=(v(),P)[c+20>>>2>>>0];if(b){for(var O={},N=0;N<b;++N){var D=A+24*N;O[Lb(D+4)]=(v(),ie)[D+16>>>3>>>0]}b=O}else b=void 0;c={module:g,constants:b,entryPoint:dr(c+8)}}else c=void 0;return{label:p,layout:h,compute:c}},Nb=(c,p)=>{function h(b,A){b=c[b],(v(),B)[p+A>>>2>>>0]=b}function g(b,A){b=c[b],(v(),S)[p+A>>>3>>>0]=BigInt(b)}h("maxTextureDimension1D",4),h("maxTextureDimension2D",8),h("maxTextureDimension3D",12),h("maxTextureArrayLayers",16),h("maxBindGroups",20),h("maxBindGroupsPlusVertexBuffers",24),h("maxBindingsPerBindGroup",28),h("maxDynamicUniformBuffersPerPipelineLayout",32),h("maxDynamicStorageBuffersPerPipelineLayout",36),h("maxSampledTexturesPerShaderStage",40),h("maxSamplersPerShaderStage",44),h("maxStorageBuffersPerShaderStage",48),h("maxStorageTexturesPerShaderStage",52),h("maxUniformBuffersPerShaderStage",56),h("minUniformBufferOffsetAlignment",80),h("minStorageBufferOffsetAlignment",84),g("maxUniformBufferBindingSize",64),g("maxStorageBufferBindingSize",72),h("maxVertexBuffers",88),g("maxBufferSize",96),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),c.Le!==void 0&&h("maxImmediateSize",148)},gM=[,"validation","out-of-memory","internal"],wM=[,"compatibility","core"],$b={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",327692:"chromium-experimental-unorm16-texture-formats",327693:"chromium-experimental-snorm16-texture-formats",327732:"chromium-experimental-multi-draw-indirect"},xM=[,"low-power","high-performance"],yM=[,"occlusion","timestamp"],bM={undefined:1,unknown:1,destroyed:2};function vM(c,p,h,g,b,A){p=wt(p),h=wt(h),g>>>=0,b>>>=0,A>>>=0;var O=re(c>>>0);if(c={},A){var N=(v(),P)[A+12>>>2>>>0];if(N){var D=(v(),P)[A+16>>>2>>>0];c.requiredFeatures=Array.from((v(),P).subarray(D>>>2>>>0,D+4*N>>>2>>>0),ee=>$b[ee])}var q=(v(),P)[A+20>>>2>>>0];if(q){let ee=function(Nt,st,Qr=!1){st=q+st,(st=(v(),P)[st>>>2>>>0])==4294967295||Qr&&st==0||(Re[Nt]=st)},lt=function(Nt,st){st=q+st;var Qr=(v(),P)[st>>>2>>>0],KT=(v(),P)[st+4>>>2>>>0];Qr==4294967295&&KT==4294967295||(Re[Nt]=4294967296*(v(),P)[st+4>>>2>>>0]+(v(),P)[st>>>2>>>0])};var fe=ee,me=lt,Re={};ee("maxTextureDimension1D",4),ee("maxTextureDimension2D",8),ee("maxTextureDimension3D",12),ee("maxTextureArrayLayers",16),ee("maxBindGroups",20),ee("maxBindGroupsPlusVertexBuffers",24),ee("maxDynamicUniformBuffersPerPipelineLayout",32),ee("maxDynamicStorageBuffersPerPipelineLayout",36),ee("maxSampledTexturesPerShaderStage",40),ee("maxSamplersPerShaderStage",44),ee("maxStorageBuffersPerShaderStage",48),ee("maxStorageTexturesPerShaderStage",52),ee("maxUniformBuffersPerShaderStage",56),ee("minUniformBufferOffsetAlignment",80),ee("minStorageBufferOffsetAlignment",84),lt("maxUniformBufferBindingSize",64),lt("maxStorageBufferBindingSize",72),ee("maxVertexBuffers",88),lt("maxBufferSize",96),ee("maxVertexAttributes",104),ee("maxVertexBufferArrayStride",108),ee("maxInterStageShaderVariables",112),ee("maxColorAttachments",116),ee("maxColorAttachmentBytesPerSample",120),ee("maxComputeWorkgroupStorageSize",124),ee("maxComputeInvocationsPerWorkgroup",128),ee("maxComputeWorkgroupSizeX",132),ee("maxComputeWorkgroupSizeY",136),ee("maxComputeWorkgroupSizeZ",140),ee("maxComputeWorkgroupsPerDimension",144),ee("maxImmediateSize",148,!0),c.requiredLimits=Re}(N=(v(),P)[A+24>>>2>>>0])&&(N={label:dr(N+4)},c.defaultQueue=N),c.label=dr(A+4)}ge+=1,Os(p,O.requestDevice(c).then(ee=>{--ge,xt(b,ee.queue),xt(g,ee),h&&(ge+=1,Os(h,ee.lost.then(lt=>{--ge,ee.onuncapturederror=()=>{};var Nt=ae(),st=tr(lt.message);rp(h,bM[lt.reason],st),oe(Nt)}))),ee.onuncapturederror=lt=>{var Nt=5;lt.error instanceof GPUValidationError?Nt=2:lt.error instanceof GPUOutOfMemoryError?Nt=3:lt.error instanceof GPUInternalError&&(Nt=4);var st=ae();lt=tr(lt.error.message),s1(g,Nt,lt),oe(st)},"adapterInfo"in ee||(ee.adapterInfo=O.info),op(p,1,g,0)},ee=>{--ge;var lt=ae();ee=tr(ee.message),op(p,3,g,ee),h&&rp(h,4,ee),oe(lt)}))}function kM(c){var p=re(c>>>=0),h=rr[c];if(h){for(var g=0;g<h.length;++g)h[g]();delete rr[c]}p.destroy()}var Is=()=>{var c="getMappedRange size=0 no longer means WGPU_WHOLE_MAP_SIZE";Is.ed||(Is.ed={}),Is.ed[c]||(Is.ed[c]=1,T(c))};function EM(c,p,h){p>>>=0,h>>>=0;var g=re(c>>>=0);h===0&&Is(),h==4294967295&&(h=void 0);try{var b=g.getMappedRange(p,h)}catch{return 0}var A=lp(16,b.byteLength);return(v(),Q).set(new Uint8Array(b),A>>>0),rr[c].push(()=>Lt(A)),A}function AM(c,p,h){p>>>=0,h>>>=0;var g=re(c>>>=0);h===0&&Is(),h==4294967295&&(h=void 0);try{var b=g.getMappedRange(p,h)}catch{return 0}var A=lp(16,b.byteLength);return(v(),Q).fill(0,A,b.byteLength),rr[c].push(()=>{new Uint8Array(b).set((v(),Q).subarray(A>>>0,A+b.byteLength>>>0)),Lt(A)}),A}function MM(c,p,h,g,b){c>>>=0,p=wt(p),h=wt(h),b>>>=0;var A=re(c);rr[c]=[],b==4294967295&&(b=void 0),ge+=1,Os(p,A.mapAsync(h,g>>>0,b).then(()=>{--ge,sp(p,1,0)},O=>{--ge,ae();var N=tr(O.message);sp(p,O.name==="AbortError"?4:O.name==="OperationError"?3:0,N),delete rr[c]}))}function TM(c){var p=re(c>>>=0),h=rr[c];if(h){for(var g=0;g<h.length;++g)h[g]();delete rr[c],p.unmap()}}function SM(c){delete Qu[c>>>0]}function OM(c,p,h){c>>>=0,p>>>=0,h>>>=0;var g=!!(v(),P)[p+32>>>2>>>0];p={label:dr(p+4),usage:(v(),P)[p+16>>>2>>>0],size:4294967296*(v(),P)[p+28>>>2>>>0]+(v(),P)[p+24>>>2>>>0],mappedAtCreation:g},c=re(c);try{var b=c.createBuffer(p)}catch{return!1}return xt(h,b),g&&(rr[h]=[]),!0}function IM(c,p,h,g){c>>>=0,p=wt(p),g>>>=0,h=_M(h>>>0),c=re(c),ge+=1,Os(p,c.createComputePipelineAsync(h).then(b=>{--ge,xt(g,b),tp(p,1,g,0)},b=>{--ge;var A=ae(),O=tr(b.message);tp(p,b.reason==="validation"?3:b.reason==="internal"?4:0,g,O),oe(A)}))}function CM(c,p,h){c>>>=0,p>>>=0,h>>>=0;var g=(v(),P)[p>>>2>>>0],b=(v(),P)[g+4>>>2>>>0];p={label:dr(p+4),code:""},b===2&&(p.code=Lb(g+8)),xt(h,re(c).createShaderModule(p))}var PM=c=>{(c=re(c)).onuncapturederror=null,c.destroy()};function zM(c,p){p=wt(p),c=re(c>>>0),ge+=1,Os(p,c.popErrorScope().then(h=>{--ge;var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var b=ae();h=h?tr(h.message):0,np(p,1,g,h),oe(b)},h=>{--ge;var g=ae();h=tr(h.message),np(p,1,5,h),oe(g)}))}function LM(c,p,h,g){if(p=wt(p),g>>>=0,h>>>=0){var b=(v(),P)[h+4>>>2>>>0];b={featureLevel:wM[b],powerPreference:xM[(v(),P)[h+8>>>2>>>0]],forceFallbackAdapter:!!(v(),P)[h+12>>>2>>>0]},(h=(v(),P)[h>>>2>>>0])!==0&&(v(),b.Qe=!!(v(),P)[h+8>>>2>>>0])}"gpu"in navigator?(ge+=1,Os(p,navigator.gpu.requestAdapter(b).then(A=>{if(--ge,A)xt(g,A),In(p,1,g,0);else{A=ae();var O=tr("WebGPU not available on this browser (requestAdapter returned null)");In(p,3,g,O),oe(A)}},A=>{--ge;var O=ae();A=tr(A.message),In(p,4,g,A),oe(O)}))):(h=ae(),b=tr("WebGPU not available on this browser (navigator.gpu is not available)"),In(p,3,g,b),oe(h))}function NM(c,p,h){return c>>>=0,p>>>=0,h>>>=0,kb(async()=>{var g=[];if(h){var b=(v(),B)[h>>>2>>>0];g.length=p+1,g[p]=new Promise(N=>setTimeout(N,b,0))}else g.length=p;for(var A=0;A<p;++A){var O=4294967296*(v(),P)[c+8*A+4>>>2>>>0]+(v(),P)[c+8*A>>>2>>>0];if(!(O in Oi))return O;g[A]=Oi[O]}return g=await Promise.race(g),delete Oi[g],g})}var Ju,Zu={},Rb=()=>{if(!Ju){var c,p={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(c in Zu)Zu[c]===void 0?delete p[c]:p[c]=Zu[c];var h=[];for(c in p)h.push(`${c}=${p[c]}`);Ju=h}return Ju};function Ub(c,p){if(n)return Le(19,1,c,p);c>>>=0,p>>>=0;var h,g=0,b=0;for(h of Rb()){var A=p+g;(v(),P)[c+b>>>2>>>0]=A,g+=ur(h,A,1/0)+1,b+=4}return 0}function Bb(c,p){if(n)return Le(20,1,c,p);c>>>=0,p>>>=0;var h=Rb();for(var g of((v(),P)[c>>>2>>>0]=h.length,c=0,h))c+=pr(g)+1;return(v(),P)[p>>>2>>>0]=c,0}function Db(c){return n?Le(21,1,c):52}function Fb(c,p,h,g){return n?Le(22,1,c,p,h,g):52}function jb(c,p,h,g){return n?Le(23,1,c,p,h,g):70}var $M=[null,[],[]];function Gb(c,p,h,g){if(n)return Le(24,1,c,p,h,g);p>>>=0,h>>>=0,g>>>=0;for(var b=0,A=0;A<h;A++){var O=(v(),P)[p>>>2>>>0],N=(v(),P)[p+4>>>2>>>0];p+=8;for(var D=0;D<N;D++){var q=c,fe=(v(),Q)[O+D>>>0],me=$M[q];fe===0||fe===10?((q===1?I:T)(sb(me)),me.length=0):me.push(fe)}b+=N}return(v(),P)[g>>>2>>>0]=b,0}function RM(c){return c>>>0}function UM(c,p){return Nb(re(c>>>0).limits,p>>>0),1}function BM(c,p){return re(c>>>0).features.has($b[p])}function DM(c){return BigInt(re(c>>>0).size)}function FM(c){return BigInt(re(c>>>0).usage)}function jM(c,p){if(c>>>=0,p>>>=0){var h=dr(p+4);h={label:h,timestampWrites:p=(p=(v(),P)[p+12>>>2>>>0])!==0?{querySet:re((v(),P)[p+4>>>2>>>0]),beginningOfPassWriteIndex:(v(),P)[p+8>>>2>>>0],endOfPassWriteIndex:(v(),P)[p+12>>>2>>>0]}:void 0}}return c=re(c),p=Jb(0),xt(p,c.beginComputePass(h)),p}function GM(c,p,h,g,b,A){h=wt(h),b=wt(b),A=wt(A),re(c>>>0).copyBufferToBuffer(re(p>>>0),h,re(g>>>0),b,A)}function qM(c){c=re(c>>>0);var p=Yb(0);return xt(p,c.finish()),p}function WM(c,p,h,g,b,A){A=wt(A),re(c>>>0).resolveQuerySet(re(p>>>0),h,g,re(b>>>0),A)}function VM(c,p,h,g){re(c>>>0).dispatchWorkgroups(p,h,g)}function HM(c,p,h){h=wt(h),re(c>>>0).dispatchWorkgroupsIndirect(re(p>>>0),h)}function XM(c){re(c>>>0).end()}function KM(c,p,h,g,b){g>>>=0,b>>>=0,c=re(c>>>0),h=re(h>>>0),g==0?c.setBindGroup(p,h):c.setBindGroup(p,h,(v(),P),b>>>2,g)}function YM(c,p){re(c>>>0).setPipeline(re(p>>>0))}function QM(c,p,h){re(c>>>0).Pe(re(p>>>0),h)}function JM(c,p){c=re(c>>>0);var h=Kb(0);return xt(h,c.getBindGroupLayout(p)),h}function ZM(c,p){c>>>=0;var h=dr(4+(p>>>=0)),g=re((v(),P)[p+12>>>2>>>0]),b=(v(),P)[p+16>>>2>>>0];p=(v(),P)[p+20>>>2>>>0];for(var A=[],O=0;O<b;++O){var N=A,D=N.push,q=p+40*O,fe=(v(),P)[q+8>>>2>>>0],me=(v(),P)[q+32>>>2>>>0],Re=(v(),P)[q+36>>>2>>>0],ee=(v(),P)[q+4>>>2>>>0];fe?(me=q+24,(me=(v(),P)[me>>>2>>>0]+4294967296*(v(),B)[me+4>>>2>>>0])==-1&&(me=void 0),q={binding:ee,resource:{buffer:re(fe),offset:4294967296*(v(),P)[q+4+16>>>2>>>0]+(v(),P)[q+16>>>2>>>0],size:me}}):q=me?{binding:ee,resource:re(me)}:{binding:ee,resource:re(Re)},D.call(N,q)}return h={label:h,layout:g,entries:A},c=re(c),g=Xb(0),xt(g,c.createBindGroup(h)),g}function eT(c,p){var h;return c>>>=0,(p>>>=0)&&(h={label:dr(p+4)}),c=re(c),p=Qb(0),xt(p,c.createCommandEncoder(h)),p}function tT(c,p){c>>>=0,p>>>=0,p={type:yM[(v(),P)[p+12>>>2>>>0]],count:(v(),P)[p+16>>>2>>>0]},c=re(c);var h=Zb(0);return xt(h,c.createQuerySet(p)),h}function rT(c,p){c=re(c>>>0).adapterInfo,p>>>=0,(v(),B)[p+52>>>2>>>0]=c.subgroupMinSize,(v(),B)[p+56>>>2>>>0]=c.subgroupMaxSize;var h=Pb(c.vendor+c.architecture+c.device+c.description),g=pr(c.vendor);return Ii(p+4,h,g),h+=g,g=pr(c.architecture),Ii(p+12,h,g),h+=g,g=pr(c.device),Ii(p+20,h,g),Ii(p+28,h+g,pr(c.description)),(v(),B)[p+36>>>2>>>0]=2,c=c.isFallbackAdapter?3:4,(v(),B)[p+40>>>2>>>0]=c,(v(),B)[p+44>>>2>>>0]=0,(v(),B)[p+48>>>2>>>0]=0,1}var sT={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-snorm16-texture-formats":327693,"chromium-experimental-multi-draw-indirect":327732};function nT(c,p){p>>>=0,c=re(c>>>0);var h=Cs(4*c.features.size),g=0,b=0;c.features.forEach(A=>{0<=(A=sT[A])&&((v(),B)[h+g>>>2>>>0]=A,g+=4,b++)}),(v(),P)[p+4>>>2>>>0]=h,(v(),P)[p>>>2>>>0]=b}function oT(c,p){return Nb(re(c>>>0).limits,p>>>0),1}function aT(c,p){re(c>>>0).pushErrorScope(gM[p])}function iT(c,p,h){p>>>=0,h>>>=0,c=re(c>>>0),p=Array.from((v(),B).subarray(h>>>2>>>0,h+4*p>>>2>>>0),g=>re(g)),c.submit(p)}function lT(c,p,h,g,b){h=wt(h),g>>>=0,b>>>=0,c=re(c>>>0),p=re(p>>>0),g=(v(),Q).subarray(g>>>0,g+b>>>0),c.writeBuffer(p,h,g,0,b)}n||(function(){for(var c=e.numThreads-1;c--;)Y0();Me.push(async()=>{var p=(async function(){if(!n)return Promise.all(et.map(K0))})();xe++,await p,--xe==0&&Ge&&(p=Ge,Ge=null,p())})})(),n||(yr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),ue()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>ae(),e.stackRestore=c=>oe(c),e.stackAlloc=c=>Pi(c),e.setValue=function(c,p,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(v(),V)[c>>>0]=p;break;case"i16":(v(),K)[c>>>1>>>0]=p;break;case"i32":(v(),B)[c>>>2>>>0]=p;break;case"i64":(v(),S)[c>>>3>>>0]=BigInt(p);break;case"float":(v(),se)[c>>>2>>>0]=p;break;case"double":(v(),ie)[c>>>3>>>0]=p;break;case"*":(v(),P)[c>>>2>>>0]=p;break;default:Ce(`invalid type for setValue: ${h}`)}},e.getValue=function(c,p="i8"){switch(p.endsWith("*")&&(p="*"),p){case"i1":case"i8":return(v(),V)[c>>>0];case"i16":return(v(),K)[c>>>1>>>0];case"i32":return(v(),B)[c>>>2>>>0];case"i64":return(v(),S)[c>>>3>>>0];case"float":return(v(),se)[c>>>2>>>0];case"double":return(v(),ie)[c>>>3>>>0];case"*":return(v(),P)[c>>>2>>>0];default:Ce(`invalid type for getValue: ${p}`)}},e.UTF8ToString=Ts,e.stringToUTF8=ur,e.lengthBytesUTF8=pr;var qb,Wb,ep,Ci,Lt,Cs,Vb,Hb,Xb,Kb,Yb,Qb,Jb,Zb,e1,t1,r1,tp,rp,sp,np,In,op,s1,ap,n1,o1,a1,ip,i1,l1,lp,he,Cn,c1,oe,Pi,ae,u1,cp,p1,d1,f1,up,m1,h1,_1,g1,w1,x1,y1,b1,v1,k1,E1,A1,M1,T1,S1,O1,I1,C1,P1,z1,L1,N1,$1,R1,U1,B1,D1,F1,j1,G1,q1,W1,V1,H1,X1,K1,Y1,Q1,J1,Z1,fr,cT=[xr,Hr,Z0,nb,ob,ab,ib,lb,cb,ub,pb,db,fb,mb,hb,_b,Sb,Ob,Ib,Ub,Bb,Db,Fb,jb,Gb],pp={1117404:(c,p,h,g,b)=>{if(e===void 0||!e.Zc)return 1;if((c=Ts(Number(c>>>0))).startsWith("./")&&(c=c.substring(2)),!(c=e.Zc.get(c)))return 2;if(p=Number(p>>>0),h=Number(h>>>0),g=Number(g>>>0),p+h>c.byteLength)return 3;try{let A=c.subarray(p,p+h);switch(b){case 0:(v(),Q).set(A,g>>>0);break;case 1:e.ie?e.ie(g,A):e.Ke(g,A);break;default:return 4}return 0}catch{return 4}},1118228:(c,p,h)=>{e.ke(c,(v(),Q).subarray(p>>>0,p+h>>>0))},1118292:()=>e.Ie(),1118334:c=>{e.je(c)},1118371:()=>typeof wasmOffsetConverter<"u"};function uT(){return typeof wasmOffsetConverter<"u"}function pT(c,p,h,g){var b=ae();try{return b1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function dT(c,p,h){var g=ae();try{return w1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function fT(c,p,h){var g=ae();try{f1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function mT(c,p){var h=ae();try{return up(c,p)}catch(g){if(oe(h),g!==g+0)throw g;he(1,0)}}function hT(c){var p=ae();try{m1(c)}catch(h){if(oe(p),h!==h+0)throw h;he(1,0)}}function _T(c,p,h,g,b,A,O){var N=ae();try{return g1(c,p,h,g,b,A,O)}catch(D){if(oe(N),D!==D+0)throw D;he(1,0)}}function gT(c,p){var h=ae();try{v1(c,p)}catch(g){if(oe(h),g!==g+0)throw g;he(1,0)}}function wT(c,p,h,g,b,A){var O=ae();try{h1(c,p,h,g,b,A)}catch(N){if(oe(O),N!==N+0)throw N;he(1,0)}}function xT(c,p,h,g){var b=ae();try{y1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function yT(c,p,h,g,b,A,O){var N=ae();try{E1(c,p,h,g,b,A,O)}catch(D){if(oe(N),D!==D+0)throw D;he(1,0)}}function bT(c,p,h,g,b,A,O){var N=ae();try{A1(c,p,h,g,b,A,O)}catch(D){if(oe(N),D!==D+0)throw D;he(1,0)}}function vT(c,p,h,g,b,A,O,N){var D=ae();try{N1(c,p,h,g,b,A,O,N)}catch(q){if(oe(D),q!==q+0)throw q;he(1,0)}}function kT(c,p,h,g,b){var A=ae();try{_1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;he(1,0)}}function ET(c,p,h,g,b){var A=ae();try{return k1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;he(1,0)}}function AT(c,p,h,g,b,A,O,N){var D=ae();try{$1(c,p,h,g,b,A,O,N)}catch(q){if(oe(D),q!==q+0)throw q;he(1,0)}}function MT(c,p,h,g,b,A,O,N,D,q,fe,me){var Re=ae();try{M1(c,p,h,g,b,A,O,N,D,q,fe,me)}catch(ee){if(oe(Re),ee!==ee+0)throw ee;he(1,0)}}function TT(c,p,h,g,b,A){var O=ae();try{return z1(c,p,h,g,b,A)}catch(N){if(oe(O),N!==N+0)throw N;he(1,0)}}function ST(c,p,h){var g=ae();try{return I1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;return he(1,0),0n}}function OT(c,p,h,g,b,A,O,N,D){var q=ae();try{x1(c,p,h,g,b,A,O,N,D)}catch(fe){if(oe(q),fe!==fe+0)throw fe;he(1,0)}}function IT(c){var p=ae();try{return S1(c)}catch(h){if(oe(p),h!==h+0)throw h;he(1,0)}}function CT(c,p,h){var g=ae();try{return R1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function PT(c,p){var h=ae();try{return K1(c,p)}catch(g){if(oe(h),g!==g+0)throw g;return he(1,0),0n}}function zT(c,p,h,g,b){var A=ae();try{U1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;he(1,0)}}function LT(c){var p=ae();try{return T1(c)}catch(h){if(oe(p),h!==h+0)throw h;return he(1,0),0n}}function NT(c,p,h,g,b,A){var O=ae();try{return F1(c,p,h,g,b,A)}catch(N){if(oe(O),N!==N+0)throw N;he(1,0)}}function $T(c,p,h,g,b,A){var O=ae();try{return j1(c,p,h,g,b,A)}catch(N){if(oe(O),N!==N+0)throw N;he(1,0)}}function RT(c,p,h,g,b,A,O,N){var D=ae();try{return L1(c,p,h,g,b,A,O,N)}catch(q){if(oe(D),q!==q+0)throw q;he(1,0)}}function UT(c,p,h,g,b){var A=ae();try{return G1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;return he(1,0),0n}}function BT(c,p,h,g){var b=ae();try{return q1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function DT(c,p,h,g){var b=ae();try{return W1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function FT(c,p,h,g,b,A,O,N,D,q,fe,me){var Re=ae();try{return V1(c,p,h,g,b,A,O,N,D,q,fe,me)}catch(ee){if(oe(Re),ee!==ee+0)throw ee;he(1,0)}}function jT(c,p,h,g,b,A,O,N,D,q,fe){var me=ae();try{B1(c,p,h,g,b,A,O,N,D,q,fe)}catch(Re){if(oe(me),Re!==Re+0)throw Re;he(1,0)}}function GT(c,p,h,g,b,A,O,N,D,q,fe,me,Re,ee,lt,Nt){var st=ae();try{D1(c,p,h,g,b,A,O,N,D,q,fe,me,Re,ee,lt,Nt)}catch(Qr){if(oe(st),Qr!==Qr+0)throw Qr;he(1,0)}}function qT(c,p,h,g){var b=ae();try{return H1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function WT(c,p,h,g,b){var A=ae();try{return X1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;he(1,0)}}function VT(c,p,h){var g=ae();try{return O1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function HT(c,p,h){var g=ae();try{return C1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function XT(c,p,h,g){var b=ae();try{P1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function zi(){if(0<xe)Ge=zi;else if(n)w?.(e),Be();else{for(var c=Me;0<c.length;)c.shift()(e);0<xe?Ge=zi:(e.calledRun=!0,z||(Be(),w?.(e)))}}return n||(fr=await Qe(),zi()),e.PTR_SIZE=4,e.webgpuInit=c=>{let p=new WeakMap,h,g,b=1;e.webgpuRegisterDevice=N=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(N){var D=p.get(N);if(!D){let q=((fe,me=0)=>{var Re=r1(me);return me=t1(me,Re),xt(Re,fe.queue),xt(me,fe),me})(N,D=Hb(0));D=[b++,D,q],p.set(N,D)}return h=N,g=D[0],D}h=void 0,g=0};let A=new Map;e.webgpuOnCreateSession=N=>{if(g!==void 0){var D=g;if(g=void 0,N){let q=ep(D);A.set(N,q),D===0&&c(h??re(q))}h=void 0}},e.webgpuOnReleaseSession=N=>{A.delete(N)};let O=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(N,D,q)=>{if(q)return N[O]=[q,NaN],q;if(q=N[O])return q[1]++,q[0];if((D=A.get(D))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return D=((fe,me=0)=>(fe.mapState!="pending"||Ce(),me=e1(me,fe.mapState=="mapped"?3:1),xt(me,fe),fe.mapState=="mapped"&&(rr[me]=[]),me))(N,D),N[O]=[D,1],D},e.webgpuUnregisterBuffer=N=>{let D=N[O];if(!D)throw Error("Buffer is not registered");D[1]--,D[1]===0&&(Vb(D[0]),delete N[O])},e.webgpuGetBuffer=N=>re(N),e.webgpuCreateDownloader=(N,D,q)=>{if((q=A.get(q))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let fe=re(q),me=16*Math.ceil(Number(D)/16);return async()=>{let Re=fe.createBuffer({size:me,usage:9});try{let ee=fe.createCommandEncoder();return ee.copyBufferToBuffer(N,0,Re,0,me),fe.queue.submit([ee.finish()]),await Re.mapAsync(GPUMapMode.READ),Re.getMappedRange().slice(0,D)}finally{Re.destroy()}}},e.ie=(N,D)=>{var q=D.buffer;let fe=D.byteOffset,me=D.byteLength;if(D=16*Math.ceil(Number(me)/16),N=re(N),!h){var Re=ep(g);h=re(Re)}let ee=(Re=h.createBuffer({mappedAtCreation:!0,size:D,usage:6})).getMappedRange();new Uint8Array(ee).set(new Uint8Array(q,fe,me)),Re.unmap(),(q=h.createCommandEncoder()).copyBufferToBuffer(Re,0,N,0,D),h.queue.submit([q.finish()]),Re.destroy()}},e.webnnInit=c=>{let p=c[0];[e.Ie,e.je,e.webnnEnsureTensor,e.ke,e.webnnDownloadTensor,e.He,e.webnnEnableTraceEvent]=c.slice(1),e.webnnReleaseTensorId=e.je,e.webnnUploadTensor=e.ke,e.webnnRegisterMLContext=e.He,e.webnnOnRunStart=h=>p.onRunStart(h),e.webnnOnRunEnd=p.onRunEnd.bind(p),e.webnnOnReleaseSession=h=>{p.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>p.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,b,A)=>p.registerMLTensor(h,g,b,A),e.webnnCreateMLContext=h=>p.createMLContext(h),e.webnnRegisterMLConstant=(h,g,b,A,O,N)=>p.registerMLConstant(h,g,b,A,O,e.Zc,N),e.webnnRegisterGraphInput=p.registerGraphInput.bind(p),e.webnnIsGraphInput=p.isGraphInput.bind(p),e.webnnRegisterGraphOutput=p.registerGraphOutput.bind(p),e.webnnIsGraphOutput=p.isGraphOutput.bind(p),e.webnnCreateTemporaryTensor=p.createTemporaryTensor.bind(p),e.webnnIsGraphInputOutputTypeSupported=p.isGraphInputOutputTypeSupported.bind(p)},te?e:new Promise((c,p)=>{w=c,x=p})}var Xk,tk,$C=ye(()=>{"use strict";Xk=ek,tk=globalThis.self?.name?.startsWith("em-pthread"),tk&&ek()}),Op,Wp,rk,Ot,Kk,Wi,sk,nk,Ip,ok,Cp,Yk,Pp,Qk,ed=ye(()=>{"use strict";Zp(),Op=typeof location>"u"?void 0:location.origin,Wp=import.meta.url>"file:"&&import.meta.url<"file;",rk=()=>{if(Wp){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Op).href}return import.meta.url},Ot=rk(),Kk=()=>{if(Ot&&!Ot.startsWith("blob:"))return Ot.substring(0,Ot.lastIndexOf("/")+1)},Wi=(t,e)=>{try{let r=e??Ot;return(r?new URL(t,r):new URL(t)).origin===Op}catch{return!1}},sk=(t,e)=>{let r=e??Ot;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},nk=(t,e)=>`${e??"./"}${t}`,Ip=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},ok=async t=>(await import(t)).default,Cp=(NC(),Qi(Wk)).default,Yk=async()=>{if(!Ot)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Wi(Ot))return[void 0,Cp()];let t=await Ip(Ot);return[t,Cp(t)]},Pp=($C(),Qi(Hk)).default,Qk=async(t,e,r,s)=>{let n=Pp&&!(t||e);if(n)if(Ot)n=Wi(Ot);else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,Pp];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??sk(o,e),i=r&&a&&!Wi(a,e),l=i?await Ip(a):a??nk(o,e);return[i?l:void 0,await ok(l)]}}}),zp,Vi,jn,Lp,ak,ik,lk,td,Ue,ps=ye(()=>{"use strict";ed(),Vi=!1,jn=!1,Lp=!1,ak=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},ik=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},lk=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},td=async t=>{if(Vi)return Promise.resolve();if(jn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Lp)throw new Error("previous call to 'initializeWebAssembly()' failed.");jn=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!lk())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ik())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=ak();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,u=l?.href??l,d=t.wasmBinary,[f,m]=await Qk(i,o,r>1,!!d||!!u),_=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{_=!0,x()},e)})),w.push(new Promise((x,k)=>{let E={numThreads:r};if(d)E.wasmBinary=d;else if(u||o)E.locateFile=M=>u??o+M;else if(i&&i.indexOf("blob:")!==0)E.locateFile=M=>new URL(M,i).href;else if(f){let M=Kk();M&&(E.locateFile=I=>M+I)}m(E).then(M=>{jn=!1,Vi=!0,zp=M,x(),f&&URL.revokeObjectURL(f)},M=>{jn=!1,Lp=!0,k(M)})})),await Promise.race(w),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Ue=()=>{if(Vi&&zp)return zp;throw new Error("WebAssembly is not initialized yet.")}}),It,Zi,Oe,rd=ye(()=>{"use strict";ps(),It=(t,e)=>{let r=Ue(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},Zi=(t,e,r,s)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([n,o])=>{let a=e?e+n:n;if(typeof o=="object")Zi(o,a+".",r,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Oe=t=>{let e=Ue(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetLastError(n,n+s);let o=Number(e.getValue(n,s===4?"i32":"i64")),a=e.getValue(n+s,"*"),i=a?e.UTF8ToString(a):"";throw new Error(`${t} ERROR_CODE: ${o}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}}),Jk,RC=ye(()=>{"use strict";ps(),rd(),Jk=t=>{let e=Ue(),r=0,s=[],n=t||{};try{if(t?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(n.terminate=!1);let o=0;return t?.tag!==void 0&&(o=It(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&Oe("Can't create run options."),t?.extra!==void 0&&Zi(t.extra,"",new WeakSet,(a,i)=>{let l=It(a,s),u=It(i,s);e._OrtAddRunConfigEntry(r,l,u)!==0&&Oe(`Can't set a run config entry: ${a} - ${i}.`)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),s.forEach(a=>e._free(a)),o}}}),ck,uk,pk,Hi,kr,dk,Zk,UC=ye(()=>{"use strict";ps(),rd(),ck=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},uk=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},pk=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},Hi=(t,e,r,s)=>{let n=It(e,s),o=It(r,s);Ue()._OrtAddSessionConfigEntry(t,n,o)!==0&&Oe(`Can't set a session config entry: ${e} - ${r}.`)},kr=(t,e,r,s)=>{let n=It(e,s),o=It(r,s);t.push([n,o])},dk=async(t,e,r)=>{let s=e.executionProviders;for(let n of s){let o=typeof n=="string"?n:n.name,a=[];switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let f=n?.deviceType;f&&Hi(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let _=n;if(_.device)if(typeof GPUDevice<"u"&&_.device instanceof GPUDevice)f=_.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&kr(a,"enableGraphCapture","1",r),typeof _.preferredLayout=="string"&&kr(a,"preferredLayout",_.preferredLayout,r),_.forceCpuNodeNames){let x=Array.isArray(_.forceCpuNodeNames)?_.forceCpuNodeNames:[_.forceCpuNodeNames];kr(a,"forceCpuNodeNames",x.join(`
15
- `),r)}_.validationMode&&kr(a,"validationMode",_.validationMode,r)}let m=Ue().webgpuRegisterDevice(f);if(m){let[_,w,x]=m;kr(a,"deviceId",_.toString(),r),kr(a,"webgpuInstance",w.toString(),r),kr(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=It(o,r),l=a.length,u=0,d=0;if(l>0){u=Ue()._malloc(l*Ue().PTR_SIZE),r.push(u),d=Ue()._malloc(l*Ue().PTR_SIZE),r.push(d);for(let f=0;f<l;f++)Ue().setValue(u+f*Ue().PTR_SIZE,a[f][0],"*"),Ue().setValue(d+f*Ue().PTR_SIZE,a[f][1],"*")}await Ue()._OrtAppendExecutionProvider(t,i,u,d,l)!==0&&Oe(`Can't append execution provider: ${o}.`)}},Zk=async t=>{let e=Ue(),r=0,s=[],n=t||{};pk(n);try{let o=ck(n.graphOptimizationLevel??"all"),a=uk(n.executionMode??"sequential"),i=typeof n.logId=="string"?It(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let u=n.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let d=typeof n.optimizedModelFilePath=="string"?It(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,u,d),r===0&&Oe("Can't create session options."),n.executionProviders&&await dk(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Hi(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[f,m]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof m!="number"||!Number.isInteger(m)||m<0)throw new Error(`free dimension override value must be a non-negative integer: ${m}`);let _=It(f,s);e._OrtAddFreeDimensionOverride(r,_,m)!==0&&Oe(`Can't set a free dimension override: ${f} - ${m}.`)}return n.extra!==void 0&&Zi(n.extra,"",new WeakSet,(f,m)=>{Hi(r,f,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Oe("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),as,Yi,Fs,Hn,el,sd,nd,Vp,js=ye(()=>{"use strict";as=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},Yi=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},Fs=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],s=typeof e=="number"?e:e.reduce((n,o)=>n*o,1);return r>0?Math.ceil(s*r):void 0},Hn=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},el=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},sd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",nd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Vp=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${t}`)}}}),od,eE=ye(()=>{"use strict";Zp(),od=async t=>{if(typeof t=="string"){let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let u=l.byteLength;new Uint8Array(o,a,u).set(l),a+=u}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),tE,BC=ye(()=>{"use strict";js(),tE=(t,e)=>new(Hn(e))(t)}),fk,mk,hk,_k,rE,gk,_t,sE=ye(()=>{"use strict";js(),fk=["V","I","W","E","F"],mk=(t,e)=>{console.log(`[${fk[t]},${new Date().toISOString()}]${e}`)},rE=(t,e)=>{hk=t,_k=e},gk=(t,e)=>{let r=el(t),s=el(hk);r>=s&&mk(r,typeof e=="function"?e():e)},_t=(...t)=>{_k&&gk(...t)}}),Np,Hp,$p,wk,Rp,xk,Up,Bp,Dp,yk,nE,DC=ye(()=>{"use strict";js(),sE(),Np=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Hp=(t,e)=>{if(e==="int32")return t;let r=Np.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);let s=r/8;if(t.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=t.byteLength/s,o=new(Hn(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i<n;i++){let l=o[i];if(l>2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(l)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&o.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(o,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},$p=(t,e)=>{if(e==="int32")return t;if(t.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=t.byteLength/4,s=new Int32Array(t.buffer,t.byteOffset,r);switch(e){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(o=>o<-128||o>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${e}`)}},wk=1,Rp=()=>wk++,xk=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Up=(t,e)=>{let r=Np.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);return e.length>0?Math.ceil(e.reduce((s,n)=>s*n)*r/8):0},Bp=class{constructor(t){this.isDataConverted=!1;let{sessionId:e,context:r,tensor:s,dataType:n,shape:o,fallbackDataType:a}=t;this.sessionId=e,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.fallbackDataType=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Up(this.dataType,this.tensorShape)}destroy(){_t("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){if(this.fallbackDataType){let e=await this.mlContext.readTensor(this.mlTensor),r=$p(new Uint8Array(e),this.dataType);if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(r);return}else return r.buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,e,r){return this.mlContext===t&&this.dataType===e&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(t){this.isDataConverted=t}},Dp=class{constructor(t,e){this.tensorManager=t,this.wrapper=e}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,e,r,s){let n=this.tensorManager.getMLContext(t),o=this.tensorManager.getMLOpSupportLimits(t),a;if(!o?.input.dataTypes.includes(e)){if(a=xk.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);_t("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${e} to ${a}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,e,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Up(e,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,e,r,i,!0,!0,a),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){let e=t;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")e=Hp(t,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else _t("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(t){if(this.activeUpload){let e=this.wrapper?.isDataConverted?$p(this.activeUpload,this.wrapper?.type):this.activeUpload;if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(e):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(e);return}else return e.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(t):this.wrapper.read()}},yk=class{constructor(t){this.backend=t,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(t){let e=this.backend.getMLContext(t);if(!e)throw new Error("MLContext not found for session.");return e}getMLOpSupportLimits(t){return this.backend.getMLOpSupportLimits(t)}reserveTensorId(){let t=Rp();return this.tensorTrackersById.set(t,new Dp(this)),t}releaseTensorId(t){let e=this.tensorTrackersById.get(t);e&&(this.tensorTrackersById.delete(t),e.tensorWrapper&&this.releaseTensor(e.tensorWrapper))}async ensureTensor(t,e,r,s,n){_t("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,s,n)}upload(t,e){let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");r.upload(e)}async download(t,e){_t("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${e?.byteLength}}`);let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");return r.download(e)}releaseTensorsForSession(t){for(let e of this.freeTensors)e.sessionId===t&&e.destroy();this.freeTensors=this.freeTensors.filter(e=>e.sessionId!==t)}registerTensor(t,e,r,s){let n=this.getMLContext(t),o=Rp(),a=new Bp({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new Dp(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[u,d]of this.freeTensors.entries())if(d.canReuseTensor(i,e,r)){_t("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(u,1)[0];return f.sessionId=t,f}_t("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:a??e,shape:r,dimensions:r,usage:s,writable:n,readable:o});return new Bp({sessionId:t,context:i,tensor:l,dataType:e,shape:r,fallbackDataType:a})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},nE=(...t)=>new yk(...t)}),oE={};Xn(oE,{WebNNBackend:()=>aE});var Gn,bk,aE,FC=ye(()=>{"use strict";js(),ps(),BC(),DC(),sE(),Gn=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),bk=(t,e)=>{if(t===e)return!0;if(t===void 0||e===void 0)return!1;let r=Object.keys(t).sort(),s=Object.keys(e).sort();return r.length===s.length&&r.every((n,o)=>n===s[o]&&t[n]===e[n])},aE=class{constructor(t){this.tensorManager=nE(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,rE(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){_t("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){_t("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)_t("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(t),this.activeSessionId=void 0}}async createMLContext(t){if(t instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===t);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:s}),s}}else if(t===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let e=this.mlContextCache.findIndex(r=>bk(r.options,t));if(e!==-1)return this.mlContextCache[e].mlContext;{let r=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:r}),r}}registerMLContext(t,e){this.mlContextBySessionId.set(t,e);let r=this.sessionIdsByMLContext.get(e);r||(r=new Set,this.sessionIdsByMLContext.set(e,r)),r.add(t),this.mlOpSupportLimitsBySessionId.has(t)||this.mlOpSupportLimitsBySessionId.set(t,e.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(t,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(t,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(t){this.sessionGraphInputs.delete(t),this.sessionGraphOutputs.delete(t);let e=this.mlContextBySessionId.get(t);if(!e)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t),this.mlOpSupportLimitsBySessionId.delete(t);let r=this.sessionIdsByMLContext.get(e);if(r.delete(t),r.size===0){this.sessionIdsByMLContext.delete(e);let s=this.mlContextCache.findIndex(n=>n.mlContext===e);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}getMLOpSupportLimits(t){return this.mlOpSupportLimitsBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){_t("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=Gn.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t??this.currentSessionId,e,o,s,n)}async createTemporaryTensor(t,e,r){_t("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=Gn.get(e);if(!s)throw new Error(`Unsupported ONNX data type: ${e}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(t,n,s,r,!1);let o=this.temporarySessionTensorIds.get(t);return o?o.push(n):this.temporarySessionTensorIds.set(t,[n]),n}uploadTensor(t,e){if(!Ue().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");_t("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${e.byteLength}}`),this.tensorManager.upload(t,e)}async downloadTensor(t,e){return this.tensorManager.download(t,e)}createMLTensorDownloader(t,e){return async()=>{let r=await this.tensorManager.download(t);return tE(r,e)}}registerMLTensor(t,e,r,s){let n=Gn.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return _t("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=l.slice(e,e+r).buffer,d;switch(n.dataType){case"float32":d=new Float32Array(u);break;case"float16":d=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":d=new Int32Array(u);break;case"uint32":d=new Uint32Array(u);break;case"int64":if(a){let f=Hp(new Uint8Array(u),"int64");d=new Int32Array(f.buffer),n.dataType="int32"}else d=new BigInt64Array(u);break;case"uint64":d=new BigUint64Array(u);break;case"int8":d=new Int8Array(u);break;case"int4":case"uint4":case"uint8":d=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return _t("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,d)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=Gn.get(as(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),vk,ad,id,Er,kk,Fp,tl,ld,cd,jp,ud,pd,dd,iE=ye(()=>{"use strict";us(),RC(),UC(),js(),ps(),rd(),eE(),vk=(t,e)=>{Ue()._OrtInit(t,e)!==0&&Oe("Can't initialize onnxruntime.")},ad=async t=>{vk(t.wasm.numThreads,el(t.logLevel))},id=async(t,e)=>{Ue().asyncInit?.();let r=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=t.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let n=t.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(e==="webgpu"&&Ue().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(FC(),Qi(oE)).WebNNBackend(t);Ue().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,o,a,i,l)=>s.ensureTensor(n,o,a,i,l),(n,o)=>{s.uploadTensor(n,o)},async(n,o)=>s.downloadTensor(n,o),(n,o)=>s.registerMLContext(n,o),!!t.trace])}},Er=new Map,kk=t=>{let e=Ue(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetInputOutputCount(t,n,n+s)!==0&&Oe("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(e.getValue(n,o)),Number(e.getValue(n+s,o))]}finally{e.stackRestore(r)}},Fp=(t,e)=>{let r=Ue(),s=r.stackSave(),n=0;try{let o=r.PTR_SIZE,a=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(t,e,a,a+o)!==0&&Oe("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let u=r.HEAPU32[n/4+1],d=[];for(let f=0;f<u;f++){let m=Number(r.getValue(n+8+f*o,"*"));d.push(m!==0?r.UTF8ToString(m):Number(r.getValue(n+8+(f+u)*o,"*")))}return[i,l,d]}finally{r.stackRestore(s),n!==0&&r._OrtFree(n)}},tl=t=>{let e=Ue(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},ld=async(t,e)=>{let r,s,n=Ue();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=tl(t);let o=0,a=0,i=0,l=[],u=[],d=[];try{if([a,l]=await Zk(e),e?.externalData&&n.mountExternalData){let T=[];for(let z of e.externalData){let C=typeof z=="string"?z:z.path;T.push(od(typeof z=="string"?z:z.data).then(v=>{n.mountExternalData(C,v)}))}await Promise.all(T)}for(let T of e?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof T!="string"){let z=T,C=z?.context,v=z?.gpuDevice,G=z?.deviceType,X=z?.powerPreference;C?n.currentContext=C:v?n.currentContext=await n.webnnCreateMLContext(v):n.currentContext=await n.webnnCreateMLContext({deviceType:G,powerPreference:X})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Oe("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,m]=kk(o),_=!!e?.enableGraphCapture,w=[],x=[],k=[],E=[],M=[];for(let T=0;T<f;T++){let[z,C,v]=Fp(o,T);z===0&&Oe("Can't get an input name."),u.push(z);let G=n.UTF8ToString(z);w.push(G),k.push(C===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:Yi(C),shape:v})}for(let T=0;T<m;T++){let[z,C,v]=Fp(o,T+f);z===0&&Oe("Can't get an output name."),d.push(z);let G=n.UTF8ToString(z);x.push(G),E.push(C===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:Yi(C),shape:v});{if(_&&e?.preferredOutputLocation===void 0){M.push("gpu-buffer");continue}let X=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[G]??"cpu",V=n.webnnIsGraphOutput;if(X==="cpu"&&V&&V(o,G)){M.push("ml-tensor-cpu-output");continue}if(X!=="cpu"&&X!=="cpu-pinned"&&X!=="gpu-buffer"&&X!=="ml-tensor")throw new Error(`Not supported preferred output location: ${X}.`);if(_&&X!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${X}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);M.push(X)}}let I=null;return M.some(T=>T==="gpu-buffer"||T==="ml-tensor"||T==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&Oe("Can't create IO binding."),I={handle:i,outputPreferredLocations:M,outputPreferredLocationsEncoded:M.map(T=>T==="ml-tensor-cpu-output"?"ml-tensor":T).map(T=>Vp(T))}),Er.set(o,[o,u,d,I,_,!1]),[o,w,x,k,E]}catch(f){throw u.forEach(m=>n._OrtFree(m)),d.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&Oe("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Oe("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Oe("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},cd=t=>{let e=Ue(),r=Er.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&Oe("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Oe("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(l=>e._OrtFree(l)),o.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(s)!==0&&Oe("Can't release session."),Er.delete(t)},jp=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=Ue(),l=i.PTR_SIZE,u=t[0],d=t[1],f=t[3],m=f,_,w;if(u==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let E=t[2].gpuBuffer;w=Fs(as(u),d);{let M=i.webgpuRegisterBuffer;if(!M)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=M(E,s)}}else if(f==="ml-tensor"){let E=t[2].mlTensor;w=Fs(as(u),d);let M=i.webnnRegisterMLTensor;if(!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=M(s,E,as(u),d)}else{let E=t[2];if(Array.isArray(E)){w=l*E.length,_=i._malloc(w),r.push(_);for(let M=0;M<E.length;M++){if(typeof E[M]!="string")throw new TypeError(`tensor data at index ${M} is not a string`);i.setValue(_+M*l,It(E[M],r),"*")}}else{let M=i.webnnIsGraphInput,I=i.webnnIsGraphOutput;if(u!=="string"&&M&&I){let T=i.UTF8ToString(n);if(M(s,T)||I(s,T)){let z=as(u);w=Fs(z,d),m="ml-tensor";let C=i.webnnCreateTemporaryTensor,v=i.webnnUploadTensor;if(!C||!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let G=await C(s,z,d);v(G,new Uint8Array(E.buffer,E.byteOffset,E.byteLength)),_=G}else w=E.byteLength,_=i._malloc(w),r.push(_),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,w),_)}else w=E.byteLength,_=i._malloc(w),r.push(_),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,w),_)}}let x=i.stackSave(),k=i.stackAlloc(4*d.length);try{d.forEach((M,I)=>i.setValue(k+I*l,M,l===4?"i32":"i64"));let E=i._OrtCreateTensor(as(u),_,w,k,d.length,Vp(m));E===0&&Oe(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(E)}finally{i.stackRestore(x)}},ud=async(t,e,r,s,n,o)=>{let a=Ue(),i=a.PTR_SIZE,l=Er.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let u=l[0],d=l[1],f=l[2],m=l[3],_=l[4],w=l[5],x=e.length,k=s.length,E=0,M=[],I=[],T=[],z=[],C=[],v=a.stackSave(),G=a.stackAlloc(x*i),X=a.stackAlloc(x*i),V=a.stackAlloc(k*i),Q=a.stackAlloc(k*i);try{[E,M]=Jk(o),Mr("wasm prepareInputOutputTensor");for(let P=0;P<x;P++)await jp(r[P],I,z,t,d[e[P]],e[P],_);for(let P=0;P<k;P++)await jp(n[P],T,z,t,f[s[P]],x+s[P],_);Tr("wasm prepareInputOutputTensor");for(let P=0;P<x;P++)a.setValue(G+P*i,I[P],"*"),a.setValue(X+P*i,d[e[P]],"*");for(let P=0;P<k;P++)a.setValue(V+P*i,T[P],"*"),a.setValue(Q+P*i,f[s[P]],"*");if(m&&!w){let{handle:P,outputPreferredLocations:se,outputPreferredLocationsEncoded:ie}=m;if(d.length!==x)throw new Error(`input count from feeds (${x}) is expected to be always equal to model's input count (${d.length}).`);Mr("wasm bindInputsOutputs");for(let S=0;S<x;S++){let L=e[S];await a._OrtBindInput(P,d[L],I[S])!==0&&Oe(`Can't bind input[${S}] for session=${t}.`)}for(let S=0;S<k;S++){let L=s[S];n[S]?.[3]?(C.push(T[S]),a._OrtBindOutput(P,f[L],T[S],0)!==0&&Oe(`Can't bind pre-allocated output[${S}] for session=${t}.`)):a._OrtBindOutput(P,f[L],0,ie[L])!==0&&Oe(`Can't bind output[${S}] to ${se[S]} for session=${t}.`)}Tr("wasm bindInputsOutputs"),Er.set(t,[u,d,f,m,_,!0])}a.jsepOnRunStart?.(u),a.webnnOnRunStart?.(u);let K;m?K=await a._OrtRunWithBinding(u,m.handle,k,V,E):K=await a._OrtRun(u,X,G,x,Q,k,V,E),K!==0&&Oe("failed to call OrtRun().");let Y=[],B=[];Mr("wasm ProcessOutputTensor");for(let P=0;P<k;P++){let se=Number(a.getValue(V+P*i,"*"));if(se===T[P]||C.includes(T[P])){Y.push(n[P]),se!==T[P]&&a._OrtReleaseTensor(se)!==0&&Oe("Can't release tensor.");continue}let ie=a.stackSave(),S=a.stackAlloc(4*i),L=!1,R,te=0;try{a._OrtGetTensorData(se,S,S+i,S+2*i,S+3*i)!==0&&Oe(`Can't access output tensor data on index ${P}.`);let ue=i===4?"i32":"i64",Be=Number(a.getValue(S,ue));te=a.getValue(S+i,"*");let Ce=a.getValue(S+i*2,"*"),vt=Number(a.getValue(S+i*3,ue)),Qe=[];for(let Me=0;Me<vt;Me++)Qe.push(Number(a.getValue(Ce+Me*i,ue)));a._OrtFree(Ce)!==0&&Oe("Can't free memory for tensor dims.");let Ze=Qe.reduce((Me,xe)=>Me*xe,1);R=Yi(Be);let rt=m?.outputPreferredLocations[s[P]];if(R==="string"){if(rt==="gpu-buffer"||rt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Me=[];for(let xe=0;xe<Ze;xe++){let Ge=a.getValue(te+xe*i,"*"),kt=a.getValue(te+(xe+1)*i,"*"),ge=xe===Ze-1?void 0:kt-Ge;Me.push(a.UTF8ToString(Ge,ge))}Y.push([R,Qe,Me,"cpu"])}else if(rt==="gpu-buffer"&&Ze>0){let Me=a.webgpuGetBuffer;if(!Me)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xe=Me(te),Ge=Fs(Be,Ze);if(Ge===void 0||!sd(R))throw new Error(`Unsupported data type: ${R}`);L=!0;{a.webgpuRegisterBuffer(xe,t,te);let kt=a.webgpuCreateDownloader(xe,Ge,t);Y.push([R,Qe,{gpuBuffer:xe,download:async()=>{let ge=await kt();return new(Hn(R))(ge)},dispose:()=>{a._OrtReleaseTensor(se)!==0&&Oe("Can't release tensor.")}},"gpu-buffer"])}}else if(rt==="ml-tensor"&&Ze>0){let Me=a.webnnEnsureTensor,xe=a.webnnIsGraphInputOutputTypeSupported;if(!Me||!xe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Fs(Be,Ze)===void 0||!nd(R))throw new Error(`Unsupported data type: ${R}`);if(!xe(t,R,!1))throw new Error(`preferredLocation "ml-tensor" for ${R} output is not supported by current WebNN Context.`);let Ge=await Me(t,te,Be,Qe,!1);L=!0,Y.push([R,Qe,{mlTensor:Ge,download:a.webnnCreateMLTensorDownloader(te,R),dispose:()=>{a.webnnReleaseTensorId(te),a._OrtReleaseTensor(se)}},"ml-tensor"])}else if(rt==="ml-tensor-cpu-output"&&Ze>0){let Me=a.webnnCreateMLTensorDownloader(te,R)(),xe=Y.length;L=!0,B.push((async()=>{let Ge=[xe,await Me];return a.webnnReleaseTensorId(te),a._OrtReleaseTensor(se),Ge})()),Y.push([R,Qe,[],"cpu"])}else{let Me=Hn(R),xe=new Me(Ze);new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength).set(a.HEAPU8.subarray(te,te+xe.byteLength)),Y.push([R,Qe,xe,"cpu"])}}finally{a.stackRestore(ie),R==="string"&&te&&a._free(te),L||a._OrtReleaseTensor(se)}}m&&!_&&(a._OrtClearBoundOutputs(m.handle)!==0&&Oe("Can't clear bound outputs."),Er.set(t,[u,d,f,m,_,!1]));for(let[P,se]of await Promise.all(B))Y[P][2]=se;return Tr("wasm ProcessOutputTensor"),Y}finally{a.webnnOnRunEnd?.(u),a.stackRestore(v),r.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),n.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),I.forEach(K=>a._OrtReleaseTensor(K)),T.forEach(K=>a._OrtReleaseTensor(K)),z.forEach(K=>a._free(K)),E!==0&&a._OrtReleaseRunOptions(E),M.forEach(K=>a._free(K))}},pd=t=>{let e=Ue(),r=Er.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Oe("Can't get an profile file name."),e._OrtFree(n)},dd=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Ar,Ut,Ds,qn,Wn,Xi,Gp,Ki,ss,ns,Ek,lE,cE,uE,pE,dE,fE,mE,hE=ye(()=>{"use strict";us(),iE(),ps(),ed(),Ar=()=>!!We.wasm.proxy&&typeof document<"u",Ds=!1,qn=!1,Wn=!1,Ki=new Map,ss=(t,e)=>{let r=Ki.get(t);r?r.push(e):Ki.set(t,[e])},ns=()=>{if(Ds||!qn||Wn||!Ut)throw new Error("worker not ready")},Ek=t=>{switch(t.data.type){case"init-wasm":Ds=!1,t.data.err?(Wn=!0,Gp[1](t.data.err)):(qn=!0,Gp[0]()),Xi&&(URL.revokeObjectURL(Xi),Xi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Ki.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},lE=async()=>{if(!qn){if(Ds)throw new Error("multiple calls to 'initWasm()' detected.");if(Wn)throw new Error("previous call to 'initWasm()' failed.");if(Ds=!0,Ar())return new Promise((t,e)=>{Ut?.terminate(),Yk().then(([r,s])=>{try{Ut=s,Ut.onerror=o=>e(o),Ut.onmessage=Ek,Gp=[t,e];let n={type:"init-wasm",in:We};!n.in.wasm.wasmPaths&&(r||Wp)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Ut.postMessage(n),Xi=r}catch(n){e(n)}},e)});try{await td(We.wasm),await ad(We),qn=!0}catch(t){throw Wn=!0,t}finally{Ds=!1}}},cE=async t=>{if(Ar())return ns(),new Promise((e,r)=>{ss("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:We}};Ut.postMessage(s)});await id(We,t)},uE=async t=>Ar()?(ns(),new Promise((e,r)=>{ss("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Ut.postMessage(s,[t.buffer])})):tl(t),pE=async(t,e)=>{if(Ar()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ns(),new Promise((r,s)=>{ss("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Ut.postMessage(n,o)})}else return ld(t,e)},dE=async t=>{if(Ar())return ns(),new Promise((e,r)=>{ss("release",[e,r]);let s={type:"release",in:t};Ut.postMessage(s)});cd(t)},fE=async(t,e,r,s,n,o)=>{if(Ar()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return ns(),new Promise((a,i)=>{ss("run",[a,i]);let l=r,u={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Ut.postMessage(u,dd(l))})}else return ud(t,e,r,s,n,o)},mE=async t=>{if(Ar())return ns(),new Promise((e,r)=>{ss("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Ut.postMessage(s)});pd(t)}}),qp,Ak,_E,jC=ye(()=>{"use strict";us(),hE(),js(),Zp(),eE(),qp=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},Ak=t=>{switch(t[3]){case"cpu":return new Kt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!sd(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return Kt.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!nd(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return Kt.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},_E=class{async fetchModelAndCopyToWasmMemory(t){return uE(await od(t))}async loadModel(t,e){ls();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await pE(r,e),cs()}async dispose(){return dE(this.sessionId)}async run(t,e,r){ls();let s=[],n=[];Object.entries(t).forEach(f=>{let m=f[0],_=f[1],w=this.inputNames.indexOf(m);if(w===-1)throw new Error(`invalid input '${m}'`);s.push(_),n.push(w)});let o=[],a=[];Object.entries(e).forEach(f=>{let m=f[0],_=f[1],w=this.outputNames.indexOf(m);if(w===-1)throw new Error(`invalid output '${m}'`);o.push(_),a.push(w)});let i=s.map((f,m)=>qp(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?qp(f,()=>`output "${this.outputNames[a[m]]}"`):null),u=await fE(this.sessionId,n,i,a,l,r),d={};for(let f=0;f<u.length;f++)d[this.outputNames[a[f]]]=o[f]??Ak(u[f]);return cs(),d}startProfiling(){}endProfiling(){mE(this.sessionId)}}}),gE={};Xn(gE,{OnnxruntimeWebAssemblyBackend:()=>Kp,initializeFlags:()=>Xp,wasmBackend:()=>wE});var Xp,Kp,wE,GC=ye(()=>{"use strict";us(),hE(),jC(),Xp=()=>{(typeof We.wasm.initTimeout!="number"||We.wasm.initTimeout<0)&&(We.wasm.initTimeout=0);let t=We.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),We.wasm.simd=!1),typeof We.wasm.proxy!="boolean"&&(We.wasm.proxy=!1),typeof We.wasm.trace!="boolean"&&(We.wasm.trace=!1),typeof We.wasm.numThreads!="number"||!Number.isInteger(We.wasm.numThreads)||We.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)We.wasm.numThreads=1;else{let e=typeof navigator>"u"?yC("node:os").cpus().length:navigator.hardwareConcurrency;We.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Kp=class{async init(t){Xp(),await lE(),await cE(t)}async createInferenceSessionHandler(t,e){let r=new _E;return await r.loadModel(t,e),r}},wE=new Kp});us();us();us();var qC="1.25.0-dev.20260212-1a71a5f46e",WC=qk;{let t=(GC(),Qi(gE)).wasmBackend;is("webgpu",t,5),is("webnn",t,5),is("cpu",t,10),is("wasm",t,10)}Object.defineProperty(We.versions,"web",{value:qC,enumerable:!0});async function xE(t){let e=t.split("/").pop(),r;try{if(r=await Fi(),r){let n=await r.match(t);if(n)return n}}catch(n){console.warn(`Failed to load ${e} from cache:`,n)}let s=await fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){console.warn(`Failed to cache ${e}:`,n)}return s}async function yE(t){let e=await xE(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return console.warn("Failed to read WASM binary:",r),null}}async function bE(t){let e=await xE(t);if(!e||typeof e=="string")return null;try{let r=await e.text(),s=t.split("/").slice(0,-1).join("/");r=r.replace(/import\.meta\.url/g,`"${s}"`);let n=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(n)}catch(r){return console.warn("Failed to read WASM binary:",r),null}}function md(t){return Us(t,["blob:"])}function hd(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof import.meta<"u"&&import.meta.url)e=import.meta.url;else return t;return new URL(t,e).href}import{Tensor as SE}from"onnxruntime-common";var HC=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),XC=["verbose","info","warning","error","fatal"],AE=4,Bt=[],_d,qs,vE=Symbol.for("onnxruntime");if(vE in globalThis)qs=globalThis[vE];else if(be.IS_NODE_ENV){switch(qs=VC,process.platform){case"win32":Bt.push("dml");break;case"linux":process.arch==="x64"&&Bt.push("cuda");break;case"darwin":Bt.push("coreml");break}Bt.push("webgpu"),Bt.push("cpu"),_d=["cpu"]}else qs=fd,be.IS_WEBNN_AVAILABLE&&Bt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),be.IS_WEBGPU_AVAILABLE&&Bt.push("webgpu"),Bt.push("wasm"),_d=["wasm"];var KC=qs.InferenceSession;function ME(t=null){if(!t)return _d;switch(t){case"auto":return Bt;case"gpu":return Bt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Bt.includes(t))return[HC[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Bt.join(", ")}.`)}var TE=be.IS_BROWSER_ENV||be.IS_WEBWORKER_ENV,kE=Promise.resolve(),Gs=null;async function YC(){return Gs||(De.useWasmCache&&typeof ft?.wasm?.wasmPaths=="object"&&ft?.wasm?.wasmPaths?.wasm&&ft?.wasm?.wasmPaths?.mjs?(Gs=(async()=>{let e=ft.wasm.wasmPaths;await Promise.all([e.wasm&&!md(e.wasm)?(async()=>{try{let r=await yE(hd(e.wasm));r&&(ft.wasm.wasmBinary=r)}catch(r){console.warn("Failed to pre-load WASM binary:",r)}})():Promise.resolve(),e.mjs&&!md(e.mjs)?(async()=>{try{let r=await bE(hd(e.mjs));r&&(ft.wasm.wasmPaths.mjs=r)}catch(r){console.warn("Failed to pre-load WASM factory:",r)}})():Promise.resolve()])})(),Gs):(Gs=Promise.resolve(),Gs))}async function rl(t,e,r){await YC();let s=()=>KC.create(t,{logSeverityLevel:AE,...e}),n=await(TE?kE=kE.then(s):s());return n.config=r,n}var EE=Promise.resolve();async function sl(t,e){let r=()=>t.run(e);return await(TE?EE=EE.then(r):r())}function nl(t){return t instanceof qs.Tensor}var ft=qs?.env;ft.logLevel=XC[AE];if(ft?.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&ft.versions?.web&&!ft.wasm.wasmPaths){let t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${ft.versions.web}/dist/`;ft.wasm.wasmPaths=be.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`}}ft.wasm.proxy=!1}ft?.webgpu&&(ft.webgpu.powerPreference="high-performance");function Kn(){return ft?.wasm?.proxy}De.backends.onnx=ft;var Sr=async(t,e,r)=>{let s=await rl(new Uint8Array(t),e);return(async n=>{let o=Kn(),a=Object.fromEntries(Object.entries(n).map(([l,u])=>[l,(o?u.clone():u).ort_tensor])),i=await sl(s,a);return Array.isArray(r)?r.map(l=>new U(i[l])):new U(i[r])})},nr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Sr([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Sr([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Sr([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Sr([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Sr([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Sr([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Sr([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=Sr([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var OE=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"});var IE=(function(){let t;return async function(){if(t===void 0)if(!be.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),mt=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),gd=Object.freeze({[OE.wasm]:mt.q8}),wd=Object.freeze({[mt.fp32]:"",[mt.fp16]:"_fp16",[mt.int8]:"_int8",[mt.uint8]:"_uint8",[mt.q8]:"_quantized",[mt.q4]:"_q4",[mt.q4f16]:"_q4f16",[mt.bnb4]:"_bnb4"}),Ws=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var U=class t{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return nl(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new SE(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n<e;++n)yield this._subarray(n,s,r)}else yield*this.data}_getitem(e){let[r,...s]=this.dims;if(e=or(e,r),s.length>0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}indexOf(e){let r=this.data;for(let s=0;s<r.length;++s)if(r[s]==e)return s;return-1}_subarray(e,r,s){let n=e*r,o=(e+1)*r,a="subarray"in this.data?this.data.subarray(n,o):this.data.slice(n,o);return new t(this.type,a,s)}item(){let e=this.data;if(e.length!==1)throw new Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return QC(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=1/(1+Math.exp(-e[r]));return this}map(e){return this.clone().map_(e)}map_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]=e(r[s],s,r);return this}mul(e){return this.clone().mul_(e)}mul_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]*=e;return this}div(e){return this.clone().div_(e)}div_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]/=e;return this}add(e){return this.clone().add_(e)}add_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]-=e;return this}clone(){return new t(this.type,this.data.slice(),this.dims.slice())}slice(...e){let r=[],s=[];for(let d=0;d<this.dims.length;++d){let f=e[d];if(f==null)s.push([0,this.dims[d]]),r.push(this.dims[d]);else if(typeof f=="number")f=or(f,this.dims[d],d),s.push([f,f+1]);else if(Array.isArray(f)&&f.length===2){let[m,_]=f;if(m=m===null?0:or(m,this.dims[d],d,!1),_=_===null?this.dims[d]:or(_,this.dims[d],d,!1),m>_)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(m,0),Math.min(_,this.dims[d])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([d,f])=>f-d),o=n.reduce((d,f)=>d*f),a=this.data,i=new a.constructor(o),l=this.stride(),u=!0;for(let d=1;d<n.length;++d)if(s[d][0]!==0||s[d][1]!==this.dims[d]){u=!1;break}if(u){let d=s[0][0]*l[0],f=s[0][1]*l[0];if(ArrayBuffer.isView(a))i.set(a.subarray(d,f));else if(Array.isArray(a)){let m=a.slice(d,f);for(let _=0;_<m.length;++_)i[_]=m[_]}else throw new Error("Unsupported data type for slicing")}else for(let d=0;d<o;++d){let f=0;for(let m=n.length-1,_=d;m>=0;--m){let w=n[m];f+=(_%w+s[m][0])*l[m],_=Math.floor(_/w)}i[d]=a[f]}return new t(this.type,i,r)}permute(...e){return JC(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=(u,d)=>u+d**e;if(r===null){let u=n.reduce(o,0)**(1/e);return new t(this.type,[u],[])}let[a,i,l]=Yn(o,this,r,s);if(e!==1)for(let u=0;u<i.length;++u)i[u]=i[u]**(1/e);return new t(a,i,l)}normalize_(e=2,r=1){r=or(r,this.dims.length);let s=this.norm(e,r,!0),n=this.data,o=s.data;for(let a=0;a<n.length;++a){let i=0;for(let l=this.dims.length-1,u=a,d=1;l>=0;--l){let f=this.dims[l];if(l!==r){let m=u%f;i+=m*d,d*=this.dims[l]}u=Math.floor(u/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return xd(this.dims)}squeeze(e=null){return new t(this.type,this.data,CE(this.dims,e))}squeeze_(e=null){return this.dims=CE(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,PE(this.dims,e))}unsqueeze_(e){return this.dims=PE(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...s,n.reduce((a,i)=>a*i,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;n<e.length;++n)if(e[n]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=n}let s=this.data;if(r!==-1){let n=e.reduce((o,a,i)=>i!==r?o*a:o,1);e[r]=s.length/n}return new t(this.type,s,e)}neg_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=-e[r];return this}neg(){return this.clone().neg_()}gt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]>e?1:0;return new t("bool",r,this.dims)}lt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]<e?1:0;return new t("bool",r,this.dims)}clamp_(e,r){let s=this.data;for(let n=0;n<s.length;++n)s[n]=Math.min(Math.max(s[n],e),r);return this}clamp(e,r){return this.clone().clamp_(e,r)}round_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=Math.round(e[r]);return this}round(){return this.clone().round_()}mean(e=null,r=!1){return il(this,e,r)}min(e=null,r=!1){if(e===null){let a=Dn(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Yn((a,i)=>Math.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=Te(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Yn((a,i)=>Math.max(a,i),this,e,r,-1/0);return new t(s,n,o)}argmin(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Dn(this.data)[1];return new t("int64",[BigInt(s)],[])}argmax(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Te(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${e.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(e.every(d=>d===1)){if(e.length===this.dims.length)return this.clone();let d=e.length-this.dims.length,f=Array(d).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((d,f)=>d*e[f]),o=n.reduce((d,f)=>d*f,1),a=this.data,i=new a.constructor(o),l=xd(s),u=xd(n);for(let d=0;d<o;++d){let f=d,m=0;for(let _=0;_<n.length;++_){let w=Math.floor(f/u[_]);f=f%u[_];let x=w%s[_];m+=x*l[_]}i[d]=a[m]}return new t(this.type,i,n)}tile(...e){if(e.length<this.dims.length){let r=this.dims.length-e.length;e=Array(r).fill(1).concat(e)}return this.repeat(...e)}to(e){if(this.type===e)return this;if(!Ws.hasOwnProperty(e))throw new Error(`Unsupported type: ${e}`);let r,s=["int64","uint64"].includes(this.type),n=["int64","uint64"].includes(e);if(s&&!n)r=Number;else if(!s&&n)["float16","float32","float64"].includes(this.type)?r=o=>BigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,Jv(this.data),this.dims);return new t(e,Ws[e].from(this.data,r),this.dims)}};function QC(t,e){let r=t.length,s=e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.length<e[o]?l.push(i):a.push([i]),a},[[]]);return n[0]}function JC(t,e){let[r,s]=Vv(t.data,t.dims,e);return new U(t.type,r,s)}function yd(t,[e,r],s="bilinear",n=!1){let o=t.dims.at(-3)??1,a=t.dims.at(-2),i=t.dims.at(-1),l=Wv(t.data,[o,a,i],[e,r],s,n);return new U(t.type,l,[o,e,r])}async function Dt(t,{size:e=null,mode:r="bilinear"}={}){if(t.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!e)throw new Error("`interpolate_4d` requires a `size` argument.");let s;if(e.length===2)s=[...t.dims.slice(0,2),...e];else if(e.length===3)s=[t.dims[0],...e];else if(e.length===4)s=e;else throw new Error("`size` must be of length 2, 3, or 4.");let n;if(r==="nearest")n=await nr.nearest_interpolate_4d;else if(r==="bilinear")n=await nr.bilinear_interpolate_4d;else if(r==="bicubic")n=await nr.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);let o=new U("int64",new BigInt64Array(s.map(BigInt)),[s.length]);return await n({x:t,s:o})}async function zE(t,e){return await(await nr.matmul)({a:t,b:e})}async function e4(t,e){return await(await nr.rfft)({x:t,a:e})}async function Yt(t,e){let r=await nr.top_k;return e==null?e=t.dims.at(-1):e=Math.min(e,t.dims.at(-1)),await r({x:t,k:new U("int64",[BigInt(e)],[1])})}var ol=t=>new U("int64",t,[t.length]);async function al(t,e,r,s,n){return await(await nr.slice)({x:t,s:ol(e),e:ol(r),a:ol(s),t:ol(n??new Array(s.length).fill(1))})}function LE(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,u=0;for(let d=0;d<a;++d){let f=d*l*i;for(let m=0;m<l;++m){let _=0,w=0,x=d*i,k=f+m;for(let M=0;M<i;++M){let I=Number(s[x+M]);w+=I,_+=r[k+M*l]*I}let E=_/w;o[u++]=E}}return new U(t.type,o,n)}function t4(t,e,{eps:r=1e-5}={}){if(t.dims.length!==2)throw new Error("`layer_norm` currently only supports 2D input.");let[s,n]=t.dims;if(e.length!==1&&e[0]!==n)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");let[o,a]=bd(t,1,0,!0),i=o.data,l=a.data,u=t.data,d=new u.constructor(u.length);for(let f=0;f<s;++f){let m=f*n;for(let _=0;_<n;++_){let w=m+_;d[w]=(u[w]-l[f])/(i[f]+r)}}return new U(t.type,d,t.dims)}function CE(t,e){return t=t.slice(),e===null?t=t.filter(r=>r!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function PE(t,e){return e=or(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function or(t,e,r=null,s=!0){if(t<-e||t>=e){if(s)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function Ee(t,e=0){e=or(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i<t.length;++i){let{data:l,dims:u}=t[i];for(let d=0;d<l.length;++d){let f=0;for(let m=u.length-1,_=d,w=1;m>=0;--m){let x=u[m],k=_%x;m===e&&(k+=a),f+=k*w,w*=r[m],_=Math.floor(_/x)}n[f]=l[d]}a+=u[e]}}return new U(o,n,r)}function Ft(t,e=0){return Ee(t.map(r=>r.unsqueeze(e)),e)}function Yn(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=or(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let u=0;u<o.length;++u){let d=0;for(let f=a.length-1,m=u,_=1;f>=0;--f){let w=a[f];if(f!==r){let x=m%w;d+=x*_,_*=i[f]}m=Math.floor(m/w)}l[d]=t(l[d],o[u],u,d)}return s||i.splice(r,1),[e.type,l,i]}function bd(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let _=n.reduce((E,M)=>E+M,0)/n.length,w=Math.sqrt(n.reduce((E,M)=>E+(M-_)**2,0)/(n.length-r)),x=new U(t.type,[_],[]);return[new U(t.type,[w],[]),x]}e=or(e,o.length);let a=il(t,e,s),i=a.data,[l,u,d]=Yn((m,_,w,x)=>m+(_-i[x])**2,t,e,s);for(let m=0;m<u.length;++m)u[m]=Math.sqrt(u[m]/(o[e]-r));return[new U(l,u,d),a]}function il(t,e=null,r=!1){let s=t.dims,n=t.data;if(e===null){let l=n.reduce((u,d)=>u+d,0);return new U(t.type,[l/n.length],[])}e=or(e,s.length);let[o,a,i]=Yn((l,u)=>l+u,t,e,r);if(s[e]!==1)for(let l=0;l<a.length;++l)a[l]/=s[e];return new U(o,a,i)}function xd(t){let e=new Array(t.length);for(let r=t.length-1,s=1;r>=0;--r)e[r]=s,s*=t[r];return e}function vd(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new U(r,new s(n).fill(e),t)}function Ve(t,e){let r,s;if(typeof e=="number")r="float32",s=Float32Array;else if(typeof e=="bigint")r="int64",s=BigInt64Array;else if(typeof e=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return vd(t,e,r,s)}function Qn(t,e){return Ve(t.dims,e)}function it(t){return vd(t,1n,"int64",BigInt64Array)}function ll(t){return it(t.dims)}function kd(t){return vd(t,0n,"int64",BigInt64Array)}function Ed(t){return kd(t.dims)}function r4(t){let e=t.reduce((r,s)=>r*s,1);return new U("float32",Float32Array.from({length:e},()=>Math.random()),t)}function NE(t){let e=t.reduce((s,n)=>s*n,1),r=new Float32Array(e);for(let s=0;s<e;s+=2){let n=1-Math.random(),o=Math.random(),a=Math.sqrt(-2*Math.log(n)),i=2*Math.PI*o;r[s]=a*Math.cos(i),s+1<e&&(r[s+1]=a*Math.sin(i))}return new U("float32",r,t)}function $E(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i<o.length;++i){let l=o[i]>0?1:0,u=Math.floor(i/8),d=i%8;a[u]|=l<<7-d,r&&d===0&&(a[u]-=128)}return new U(s,a,[t.dims[0],t.dims[1]/8])}async function Ad(t,e){return await Promise.all([at(t,"tokenizer.json",!0,e),at(t,"tokenizer_config.json",!0,e)])}function Md(t){let e=t.dims;switch(e.length){case 1:return t.tolist();case 2:if(e[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return t.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${e.length}.`)}}var ZC=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function eP(t,e,r,s){for(let n of Object.keys(t)){let o=e-t[n].length,a=r(n),i=new Array(o).fill(a);t[n]=s==="right"?dt(t[n],i):dt(i,t[n])}}function tP(t,e){for(let r of Object.keys(t))t[r].length=e}function ds(t,...e){for(let r of e){if(!Object.hasOwn(t,r))continue;let s=t[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function rP(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var j=class extends Je{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new vv(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=ds(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=ds(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=ds(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=ds(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=ds(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=ds(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:a}of this.chat_template){if(typeof o!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=a}this.chat_template=n}this._compiled_template_cache=new Map;let s=rP(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let i=await Ad(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,{text_pair:r=null,add_special_tokens:s=!0,padding:n=!1,truncation:o=null,max_length:a=null,return_tensor:i=!0,return_token_type_ids:l=null}={}){let u=Array.isArray(e),d;if(u){if(e.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(e.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");d=e.map((m,_)=>this._encode_plus(m,{text_pair:r[_],add_special_tokens:s,return_token_type_ids:l}))}else d=e.map(m=>this._encode_plus(m,{add_special_tokens:s,return_token_type_ids:l}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");d=[this._encode_plus(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:l})]}if(a===null?a=this.model_max_length:o===null&&(n===!0?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),a=this.model_max_length):n===!1&&(console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),o=!0)),n===!0&&(a=Math.min(Te(d.map(m=>m.input_ids.length))[0],a??1/0)),a=Math.min(a,this.model_max_length??1/0),n||o)for(let m=0;m<d.length;++m)d[m].input_ids.length!==a&&(d[m].input_ids.length>a?o&&tP(d[m],a):n&&eP(d[m],a,_=>_==="input_ids"?this.pad_token_id:0,this.padding_side));let f={};if(i){if(!(n&&o)&&d.some(_=>{for(let w of Object.keys(_))if(_[w].length!==d[0][w]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let m=[d.length,d[0].input_ids.length];for(let _ of Object.keys(d[0]))f[_]=new U("int64",BigInt64Array.from(d.flatMap(w=>w[_]).map(BigInt)),m)}else{for(let m of Object.keys(d[0]))f[m]=d.map(_=>_[m]);if(!u)for(let m of Object.keys(f))f[m]=f[m][0]}return f}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof U&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof U&&(e=Md(e)),!Array.isArray(e)||e.length===0||!Nv(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,{tools:r=null,documents:s=null,chat_template:n=null,add_generation_prompt:o=!1,tokenize:a=!0,padding:i=!1,truncation:l=!1,max_length:u=null,return_tensor:d=!0,return_dict:f=!0,tokenizer_kwargs:m={},..._}={}){if(n=this.get_chat_template({chat_template:n,tools:r}),typeof n!="string")throw Error(`chat_template must be a string, but got ${typeof n}`);let w=this._compiled_template_cache.get(n);w===void 0&&(w=new Lv(n),this._compiled_template_cache.set(n,w));let x=Object.create(null);for(let E of ZC){let M=ds(this.config,E);M&&(x[E]=M)}let k=w.render({messages:e,add_generation_prompt:o,tools:r,documents:s,...x,..._});if(a){let E=this._call(k,{add_special_tokens:!1,padding:i,truncation:l,max_length:u,return_tensor:d,...m});return f?E:E.input_ids}return k}};function Vs(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var wf={};Ps(wf,{AlbertTokenizer:()=>Td,AutoTokenizer:()=>J,BartTokenizer:()=>Sd,BertTokenizer:()=>Od,BlenderbotSmallTokenizer:()=>Id,BlenderbotTokenizer:()=>Cd,BloomTokenizer:()=>Pd,CLIPTokenizer:()=>Ld,CamembertTokenizer:()=>zd,CodeGenTokenizer:()=>$d,CodeLlamaTokenizer:()=>Nd,CohereTokenizer:()=>Rd,ConvBertTokenizer:()=>Ud,DebertaTokenizer:()=>Dd,DebertaV2Tokenizer:()=>Bd,DistilBertTokenizer:()=>Fd,ElectraTokenizer:()=>jd,EsmTokenizer:()=>Gd,FalconTokenizer:()=>qd,GPT2Tokenizer:()=>Hd,GPTNeoXTokenizer:()=>Vd,GemmaTokenizer:()=>Wd,HerbertTokenizer:()=>Xd,LlamaTokenizer:()=>Kd,M2M100Tokenizer:()=>Yd,MBart50Tokenizer:()=>Jd,MBartTokenizer:()=>Jn,MPNetTokenizer:()=>tf,MarianTokenizer:()=>Qd,MgpstrTokenizer:()=>Zd,MobileBertTokenizer:()=>ef,NllbTokenizer:()=>rf,NougatTokenizer:()=>sf,PreTrainedTokenizer:()=>j,Qwen2Tokenizer:()=>nf,RoFormerTokenizer:()=>af,RobertaTokenizer:()=>of,SiglipTokenizer:()=>lf,SpeechT5Tokenizer:()=>cf,SqueezeBertTokenizer:()=>uf,T5Tokenizer:()=>pf,TokenizersBackend:()=>j,VitsTokenizer:()=>ff,Wav2Vec2CTCTokenizer:()=>mf,WhisperTokenizer:()=>hf,XLMRobertaTokenizer:()=>_f,XLMTokenizer:()=>gf});var Td=class extends j{return_token_type_ids=!0};var Sd=class extends j{};var Od=class extends j{return_token_type_ids=!0};var Id=class extends j{};var Cd=class extends j{};var Pd=class extends j{};var zd=class extends j{};var Ld=class extends j{};var Nd=class extends j{};var $d=class extends j{};var Rd=class extends j{};var Ud=class extends j{return_token_type_ids=!0};var Bd=class extends j{return_token_type_ids=!0};var Dd=class extends j{return_token_type_ids=!0};var Fd=class extends j{};var jd=class extends j{return_token_type_ids=!0};var Gd=class extends j{};var qd=class extends j{};var Wd=class extends j{};var Vd=class extends j{};var Hd=class extends j{};var Xd=class extends j{return_token_type_ids=!0};var Kd=class extends j{padding_side="left"};var Yd=class extends j{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return Vs(this,e,r,s)}};var Qd=class extends j{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),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;let[r,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(r);if(s.length===2){let[n,o]=s;return this.supported_language_codes.includes(n)||console.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),dt([n],super._encode_text(o))}}};var Jn=class extends j{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return Vs(this,e,r,s)}};var Jd=class extends Jn{};var Zd=class extends j{};var ef=class extends j{return_token_type_ids=!0};var tf=class extends j{};var rf=class extends j{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return Vs(this,e,r,s)}};var sf=class extends j{};var nf=class extends j{};var of=class extends j{};var af=class extends j{return_token_type_ids=!0};var lf=class extends j{};var cf=class extends j{};var uf=class extends j{return_token_type_ids=!0};var pf=class extends j{};var df=class extends $t{decode_chain(e){let r="";for(let s=1;s<e.length;s+=2)r+=e[s];return[r]}},ff=class extends j{constructor(e,r){super(e,r),this._tokenizer.decoder=new df({type:"VitsDecoder"})}};var mf=class extends j{};var RE=[["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"]],Zn=new Map(RE),sP=new Map([...RE.map(([t,e])=>[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function UE(t){t=t.toLowerCase();let e=sP.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),Zn.has(t))e=t;else{let n=t.length===2?Zn.keys():Zn.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var nP="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",BE=new RegExp(`^[${nP}]+$`,"gu"),hf=class extends j{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let u=[],d=l(),f=0,m=this.timestamp_begin,w=m+1500,x=[],k=[],E=!1,M=null,I=new Set(this.all_special_ids);for(let C of e){let v=C.tokens,G=i?C.token_timestamps:null,X=null,V=m;if("stride"in C){let[Y,B,P]=C.stride;if(f-=B,M=Y-P,B&&(V=B/n+m),P)for(let se=v.length-1;se>=0;--se){let ie=Number(v[se]);if(ie>=m){if(X!==null&&(ie-m)*n<M)break;X=ie}}}let Q=[],K=[];for(let Y=0;Y<v.length;++Y){let B=Number(v[Y]);if(I.has(B)){let P=this.decode([B]),se=Zn.get(P.slice(2,-2));if(se!==void 0){if(a!==null&&se!==a&&!r){x.push(Q);let ie=this.findLongestCommonSequence(x)[0],S=this.decode(ie);d.text=S,u.push(d),x=[],Q=[],d=l()}a=d.language=se}}else if(B>=m&&B<=w){let P=(B-m)*n+f,se=rs(P,2);if(X!==null&&B>=X)E=!0;else if(E||x.length>0&&B<V)E=!1;else if(d.timestamp[0]===null)d.timestamp[0]=se;else if(se!==d.timestamp[0]){d.timestamp[1]=se,x.push(Q),i&&k.push(K);let[ie,S]=this.findLongestCommonSequence(x,k),L=this.decode(ie);d.text=L,i&&(d.words=this.collateWordTimestamps(ie,S,a)),u.push(d),x=[],Q=[],k=[],K=[],d=l()}}else if(Q.push(B),i){let P=rs(G[Y]+f,2),se;if(Y+1<G.length){se=rs(G[Y+1]+f,2);let ie=this.decode([B]);BE.test(ie)&&(se=rs(Math.min(P+n,se),2))}else se=null;K.push([P,se])}}if("stride"in C){let[Y,B,P]=C.stride;f+=Y-P}Q.length>0?(x.push(Q),i&&k.push(K)):x.every(Y=>Y.length===0)&&(d=l(),x=[],Q=[],k=[],K=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[C,v]=this.findLongestCommonSequence(x,k),G=this.decode(C);d.text=G,i&&(d.words=this.collateWordTimestamps(C,v,a)),u.push(d)}let T=Object.create(null),z=u.map(C=>C.text).join("");if(r||s){for(let C=0;C<u.length;++C){let v=u[C];r||delete v.timestamp,s||delete v.language}if(i){let C=[];for(let v of u)for(let G of v.words)C.push(G);T={chunks:C}}else T={chunks:u}}return[z,T]}findLongestCommonSequence(e,r=null){let s=e[0],n=s.length,o=[],a=Array.isArray(r)&&r.length>0,i=a?[]:null,l=a?r[0]:null;for(let u=1;u<e.length;++u){let d=e[u],f=0,m=[n,n,0,0],_=d.length;for(let T=1;T<n+_;++T){let z=Math.max(0,n-T),C=Math.min(n,n+_-T),v=s.slice(z,C),G=Math.max(0,T-n),X=Math.min(_,T),V=d.slice(G,X);if(v.length!==V.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let Q;a?Q=v.filter((B,P)=>B===V[P]&&l[z+P]<=r[u][G+P]).length:Q=v.filter((B,P)=>B===V[P]).length;let K=T/1e4,Y=Q/T+K;Q>1&&Y>f&&(f=Y,m=[z,C,G,X])}let[w,x,k,E]=m,M=Math.floor((x+w)/2),I=Math.floor((E+k)/2);o.push(...s.slice(0,M)),s=d.slice(I),n=s.length,a&&(i.push(...l.slice(0,M)),l=r[u].slice(I))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l<n.length;++l){let u=a[l];i.push({text:n[l],timestamp:[r[u.at(0)][0],r[u.at(-1)][1]]})}return i}combineTokensIntoWords(e,r,s=`"'\u201C\xA1\xBF([{-`,n=`"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`){r=r??"english";let o,a,i;return["chinese","japanese","thai","lao","myanmar"].includes(r)?[o,a,i]=this.splitTokensOnUnicode(e):[o,a,i]=this.splitTokensOnSpaces(e),this.mergePunctuations(o,a,i,s,n)}decode(e,r){let s;return r?.decode_with_timestamps?(e instanceof U&&(e=Md(e)),s=this.decodeWithTimestamps(e,r)):s=super.decode(e,r),s}decodeWithTimestamps(e,r){let s=r?.time_precision??.02,n=this.all_special_ids.at(-1)+1,o=[[]];for(let a of e)if(a=Number(a),a>=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],u=0;for(let d=0;d<e.length;++d){let f=e[d];i.push(f),l.push(d);let m=this.decode(i,{decode_with_timestamps:!0});(!m.includes(s)||r[u+m.indexOf(s)]===s)&&(n.push(m),o.push(i),a.push(l),i=[],l=[],u+=m.length)}return[n,o,a]}splitTokensOnSpaces(e){let[r,s,n]=this.splitTokensOnUnicode(e),o=[],a=[],i=[];for(let l=0;l<r.length;++l){let u=r[l],d=s[l],f=n[l],m=d[0]>=this._tokenizer.token_to_id("<|endoftext|>"),_=u.startsWith(" "),w=u.trim(),x=BE.test(w);if(m||_||x||o.length===0)o.push(u),a.push(d),i.push(f);else{let k=o.length-1;o[k]+=u,a[k].push(...d),i[k].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),u=a.length-2,d=a.length-1;for(;u>=0;)a[u].startsWith(" ")&&n.includes(a[u].trim())?(a[d]=a[u]+a[d],i[d]=dt(i[u],i[d]),l[d]=dt(l[u],l[d]),a[u]="",i[u]=[],l[u]=[]):d=u,--u;for(u=0,d=1;d<a.length;)!a[u].endsWith(" ")&&o.includes(a[d])?(a[u]+=a[d],i[u]=dt(i[u],i[d]),l[u]=dt(l[u],l[d]),a[d]="",i[d]=[],l[d]=[]):u=d,++d;return[a.filter(f=>f),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var _f=class extends j{};var gf=class extends j{return_token_type_ids=!0;constructor(e,r){super(e,r),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var J=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await Ad(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),u=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",d=wf[u];return d||(console.warn(`Unknown tokenizer class "${u}", attempting to construct from base class.`),d=j),new d(i,l)}};var Hs="https://github.com/huggingface/transformers.js/issues/new/choose";var eo="preprocessor_config.json",Xs=eo,DE="processor_config.json",FE="chat_template.jinja";var ne=class extends Je{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?at(e,DE,!0,r):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{let i=await this[a].from_pretrained(e,r);return[a.replace(/_class$/,""),i]})).then(Object.fromEntries),this.uses_chat_template_file?bp(e,FE,!0,r):null]);return new this(s,n,o)}};var Pl={};Ps(Pl,{ChatterboxProcessor:()=>zf,Florence2Processor:()=>Em,Gemma3nProcessor:()=>Am,GroundingDinoProcessor:()=>Mm,Idefics3Processor:()=>Ol,JinaCLIPProcessor:()=>Sm,LlavaProcessor:()=>Om,MgpstrProcessor:()=>Im,MoonshineProcessor:()=>Cm,OwlViTProcessor:()=>Pm,PaliGemmaProcessor:()=>zm,Phi3VProcessor:()=>Lm,PixtralProcessor:()=>Nm,Processor:()=>ne,PyAnnoteProcessor:()=>$m,Qwen2VLProcessor:()=>Rm,Sam2Processor:()=>Il,Sam2VideoProcessor:()=>Um,SamProcessor:()=>io,SmolVLMProcessor:()=>Ol,SpeechT5Processor:()=>Bm,UltravoxProcessor:()=>Dm,VLChatProcessor:()=>Tm,VoxtralProcessor:()=>Fm,Wav2Vec2Processor:()=>jm,Wav2Vec2ProcessorWithLM:()=>Gm,WhisperProcessor:()=>qm});var Ne=class extends Je{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await at(e,eo,!0,r);return new this(s)}};function He(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var oo={};Ps(oo,{ASTFeatureExtractor:()=>bf,ChatterboxFeatureExtractor:()=>vf,ClapFeatureExtractor:()=>kf,DacFeatureExtractor:()=>so,EncodecFeatureExtractor:()=>ro,FeatureExtractor:()=>Ne,Gemma3nAudioFeatureExtractor:()=>Ef,MoonshineFeatureExtractor:()=>Af,ParakeetFeatureExtractor:()=>Mf,PyAnnoteFeatureExtractor:()=>no,SeamlessM4TFeatureExtractor:()=>Tf,SnacFeatureExtractor:()=>Sf,SpeechT5FeatureExtractor:()=>Of,Wav2Vec2FeatureExtractor:()=>If,WeSpeakerFeatureExtractor:()=>Cf,WhisperFeatureExtractor:()=>Pf});import oP from"fs";import{Readable as aP}from"stream";import{pipeline as iP}from"stream/promises";async function cl(t,e){if(be.IS_BROWSER_ENV){if(be.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(be.IS_FS_AVAILABLE){let r=e.stream(),s=aP.fromWeb(r),n=oP.createWriteStream(t);await iP(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function yf(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await Bs(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&console.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let u=0;u<n.length;++u)o[u]=a*(i[u]+l[u])/2}else o=n.getChannelData(0);return o}function qE(t,e){if(t<1)return new Float64Array;if(t===1)return new Float64Array([1]);let r=1-e,s=2*Math.PI/(t-1),n=new Float64Array(t);for(let o=0;o<t;++o)n[o]=e-r*Math.cos(o*s);return n}function jE(t){return qE(t,.5)}function lP(t){return qE(t,.54)}var cP={htk:t=>2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function xf(t,e="htk"){let r=cP[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}var uP={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,r=15,s=Math.log(6.4)/27)=>t>=r?e*Math.exp(s*(t-r)):200*t/3};function pP(t,e="htk"){let r=uP[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}function dP(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;a<t.length;++a){let i=s[a];for(let l=0;l<e.length;++l)i[l]=e[l]-t[a]}let n=e.length-2,o=Array.from({length:n},()=>new Array(t.length));for(let a=0;a<t.length;++a){let i=s[a];for(let l=0;l<n;++l){let u=-i[l]/r[l],d=i[l+2]/r[l+1];o[l][a]=Math.max(0,Math.min(u,d))}}return o}function GE(t,e,r){let s=(e-t)/(r-1);return Float64Array.from({length:r},(n,o)=>t+s*o)}function yt(t,e,r,s,n,o=null,a="htk",i=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);let l=xf(r,a),u=xf(s,a),d=GE(l,u,e+2),f=pP(d,a),m;if(i){let w=n/((t-1)*2);m=xf(Float64Array.from({length:t},(x,k)=>k*w),a),f=d}else m=GE(0,Math.floor(n/2),t);let _=dP(m,f);if(o!==null&&o==="slaney")for(let w=0;w<e;++w){let x=_[w],k=2/(f[w+2]-f[w]);for(let E=0;E<t;++E)x[E]*=k}return _}function fP(t,e,r){let s=new t.constructor(t.length+e+r),n=t.length-1;for(let o=0;o<t.length;++o)s[e+o]=t[o];for(let o=1;o<=e;++o)s[e-o]=t[$s(o,n)];for(let o=1;o<=r;++o)s[n+e+o]=t[$s(n-o,n)];return s}function WE(t,e,r,s,n){if(r<=0)throw new Error("reference must be greater than zero");if(s<=0)throw new Error("min_value must be greater than zero");r=Math.max(s,r);let o=Math.log10(r);for(let a=0;a<t.length;++a)t[a]=e*Math.log10(Math.max(s,t[a])-o);if(n!==null){if(n<=0)throw new Error("db_range must be greater than zero");let a=Te(t)[0]-n;for(let i=0;i<t.length;++i)t[i]=Math.max(t[i],a)}return t}function mP(t,e=1,r=1e-5,s=null){return WE(t,20,e,r,s)}function hP(t,e=1,r=1e-10,s=null){return WE(t,10,e,r,s)}async function At(t,e,r,s,{fft_length:n=null,power:o=1,center:a=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:u=null,preemphasis_htk_flavor:d=!0,mel_filters:f=null,mel_floor:m=1e-10,log_mel:_=null,reference:w=1,min_value:x=1e-10,db_range:k=null,remove_dc_offset:E=null,min_num_frames:M=null,max_num_frames:I=null,do_pad:T=!0,transpose:z=!1,mel_offset:C=0}={}){let v=e.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(v!==r)throw new Error(`Length of the window (${v}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!d)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a)switch(i){case"reflect":{let L=Math.floor((n-1)/2)+1;t=fP(t,L,L);break}case"constant":{let L=Math.floor(n/2),R=new t.constructor(t.length+2*L);R.set(t,L),t=R;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}let G=Math.floor(1+Math.floor((t.length-r)/s));M!==null&&G<M&&(G=M);let X=l?Math.floor(n/2)+1:n,V=G,Q=G;I!==null&&(I>G?T&&(Q=I):Q=V=I);let K=new Gi(n),Y=new Float64Array(n),B=new Float64Array(K.outputBufferSize),P=new Float32Array(X*Q);for(let L=0;L<V;++L){let R=L*s,te=Math.min(t.length-R,r);te!==r&&Y.fill(0,0,r);for(let ue=0;ue<te;++ue)Y[ue]=t[R+ue];if(E){let ue=0;for(let Ce=0;Ce<te;++Ce)ue+=Y[Ce];let Be=ue/te;for(let Ce=0;Ce<te;++Ce)Y[Ce]-=Be}if(u!==null){for(let ue=te-1;ue>=1;--ue)Y[ue]-=u*Y[ue-1];Y[0]*=1-u}for(let ue=0;ue<e.length;++ue)Y[ue]*=e[ue];K.realTransform(B,Y);for(let ue=0;ue<X;++ue){let Be=ue<<1;P[ue*Q+L]=B[Be]**2+B[Be+1]**2}}if(o!==null&&o!==2){let L=o/2;for(let R=0;R<P.length;++R)P[R]**=L}let se=f.length,ie=await zE(new U("float32",f.flat(),[se,X]),new U("float32",P,[X,Q]));z&&(ie=ie.transpose(1,0));let S=ie.data;for(let L=0;L<S.length;++L)S[L]=C+Math.max(m,S[L]);if(o!==null&&_!==null){let L=Math.min(S.length,V*se);switch(_){case"log":for(let R=0;R<L;++R)S[R]=Math.log(S[R]);break;case"log10":for(let R=0;R<L;++R)S[R]=Math.log10(S[R]);break;case"dB":if(o===1)mP(S,w,x,k);else if(o===2)hP(S,w,x,k);else throw new Error(`Cannot use log_mel option '${_}' with power ${o}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${_}'`)}}return ie}function Mt(t,e,{periodic:r=!0,frame_length:s=null,center:n=!0}={}){let o=r?t+1:t,a;switch(e){case"boxcar":a=new Float64Array(o).fill(1);break;case"hann":case"hann_window":a=jE(o);break;case"hamming":a=lP(o);break;case"povey":a=jE(o).map(i=>Math.pow(i,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);return a}function _P(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return ul(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),ul(n,8,"WAVE"),ul(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,e,!0),n.setUint32(28,e*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),ul(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function ul(t,e,r){for(let s=0;s<r.length;++s)t.setUint8(e+s,r.charCodeAt(s))}var to=class{constructor(e,r){this.audio=e,this.sampling_rate=r}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];let e=this.audio.reduce((n,o)=>n+o.length,0),r=new Float32Array(e),s=0;for(let n of this.audio)r.set(n,s),s+=n.length;return r}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),_P(e,this.sampling_rate)}async save(e){return cl(e,this.toBlob())}};var bf=class extends Ne{constructor(e){super(e);let r=this.config.sampling_rate,s=yt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=Mt(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return At(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){He(e,"ASTFeatureExtractor");let r=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let s=this.std*2,n=r.data;for(let o=0;o<n.length;++o)n[o]=(n[o]-this.mean)/s}return{input_values:r.unsqueeze_(0)}}};var ro=class extends Ne{async _call(e){He(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=this.config.feature_size;if(e.length%r!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${r}).`);let s=[1,r,e.length/r];return{input_values:new U("float32",e,s)}}};var vf=class extends Ne{async _call(e){He(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new U("float32",e,r)}}};var kf=class extends Ne{constructor(e){super(e),this.mel_filters=yt(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=yt(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=Mt(this.config.fft_window_size,"hann")}async _get_input_mel(e,r,s,n){let o,a=!1,i=e.length-r;if(i>0)if(s==="rand_trunc"){a=!0;let l=Math.floor(Math.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let u=e.length;u<r;u+=e.length)l.set(e.subarray(0,Math.min(e.length,r-u)),u);else if(n==="repeatpad")for(let u=e.length;u<-i;u+=e.length)l.set(e,u);e=l}if(s==="fusion")throw new Error(`Truncation strategy "${s}" not implemented`);o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return o.unsqueeze_(0)}async _extract_fbank_features(e,r,s=null){return At(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:r,log_mel:"dB",max_num_frames:s,do_pad:!1,transpose:!0})}async _call(e,{max_length:r=null}={}){return He(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,r??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}};var so=class extends ro{};var Ef=class extends Ne{constructor(e){super(e);let{fft_length:r,feature_size:s,min_frequency:n,max_frequency:o,sampling_rate:a,frame_length:i}=this.config,l=yt(Math.floor(1+r/2),s,n,o,a,null,"htk",!1);this.mel_filters=l,this.window=Mt(i,"hann")}async _extract_fbank_features(e,r){return At(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:r=48e4,truncation:s=!0,padding:n=!0,pad_to_multiple_of:o=128}={}){if(He(e,"Gemma3nAudioFeatureExtractor"),s&&e.length>r&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,u=new Float64Array(e.length+l);u.set(e),this.config.padding_value!==0&&u.fill(this.config.padding_value,e.length),e=u}let a=await this._extract_fbank_features(e,this.config.max_length),i=Ve([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var Af=class extends Ne{async _call(e){He(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new U("float32",e,r)}}};var gP=1e-5,Mf=class extends Ne{constructor(e){super(e),this.config.mel_filters??=yt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");let r=Mt(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);let s=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(r,s)}async _extract_fbank_features(e){let r=this.config.preemphasis;e=new Float64Array(e);for(let n=e.length-1;n>=1;--n)e[n]-=r*e[n-1];return await At(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){He(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f<s;++f){let m=f*a;for(let _=0;_<a;++_){let w=n[m+_];i[_]+=w,l[_]+=w*w}}let u=s>1?s-1:1;for(let f=0;f<a;++f){let m=i[f]/s,_=(l[f]-s*m*m)/u,x=1/(Math.sqrt(_)+gP);for(let k=0;k<s;++k){let E=k*a+f;n[E]=(n[E]-m)*x}}let d=new BigInt64Array(o);return d.fill(1n,0,s),{input_features:r.unsqueeze_(0),attention_mask:new U("int64",d,[1,o])}}};var no=class extends Ne{async _call(e){He(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,1,e.length];return{input_values:new U("float32",e,r)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,r){let s=r/this.samples_to_frames(r)/this.config.sampling_rate,n=[];for(let o of e.tolist()){let a=[],i=-1;for(let l=0;l<o.length;++l){let u=Pe(o[l]),[d,f]=Te(u),[m,_]=[l,l+1];f!==i?(i=f,a.push({id:f,start:m,end:_,score:d})):(a.at(-1).end=_,a.at(-1).score+=d)}n.push(a.map(({id:l,start:u,end:d,score:f})=>({id:l,start:u*s,end:d*s,confidence:f/(d-u)})))}return n}};var Tf=class extends Ne{constructor(e){super(e);let r=this.config.sampling_rate,s=yt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=Mt(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),At(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){He(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,k=a.data;for(let E=0;E<x;++E){let M=0;for(let C=0;C<w;++C)M+=k[C*x+E];let I=M/w,T=0;for(let C=0;C<w;++C)T+=(k[C*x+E]-I)**2;T/=w-1;let z=Math.sqrt(T+1e-7);for(let C=0;C<w;++C){let v=C*x+E;k[v]=(k[v]-I)/z}}}let i;if(r){let[w,x]=a.dims,k=a.data,E=w%s;if(E>0){let M=new Float32Array(x*(w+E));M.set(k),M.fill(this.config.padding_value,k.length);let I=w+E;a=new U(a.type,M,[I,x]),o&&(i=new U("int64",new BigInt64Array(I),[1,I]),i.data.fill(1n,0,w))}}let[l,u]=a.dims,d=this.config.stride;if(l%d!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${d}).`);let m=a.view(1,Math.floor(l/d),u*d),_={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let k=i.data;for(let E=1,M=0;E<l;E+=d,++M)x[M]=k[E]}else x.fill(1n);_.attention_mask=new U("int64",x,[1,w])}return _}};var Sf=class extends so{};var Of=class extends Ne{};var If=class extends Ne{_zero_mean_unit_var_norm(e){let s=e.reduce((o,a)=>o+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){He(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));let s=[1,r.length];return{input_values:new U("float32",r,s),attention_mask:new U("int64",new BigInt64Array(r.length).fill(1n),s)}}};var Cf=class extends Ne{constructor(e){super(e);let r=this.config.sampling_rate,s=yt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=Mt(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),At(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){He(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;l<o;++l){let u=l*a*i,d=l*i;for(let f=0;f<a;++f){let m=u+f*i;for(let _=0;_<i;++_)n[m+_]-=s[d+_]}}}return{input_features:r}}};var Pf=class extends Ne{constructor(e){super(e),this.config.mel_filters??=yt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=Mt(this.config.n_fft,"hann")}async _extract_fbank_features(e){let r=await At(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:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)}),s=r.data,n=Te(s)[0];for(let o=0;o<s.length;++o)s[o]=(Math.max(s[o],n-8)+4)/4;return r}async _call(e,{max_length:r=null}={}){He(e,"WhisperFeatureExtractor");let s,n=r??this.config.n_samples;return e.length>n?(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`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var tt=class{static async from_pretrained(e,r={}){let s=await at(e,eo,!0,r),n=s.feature_extractor_type,o=oo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Hs}.`);return new o(s)}};var zf=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};import Lf from"sharp";var fs,VE,Or,Qt=be.IS_BROWSER_ENV||be.IS_WEBWORKER_ENV;if(Qt)fs=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},Or=self.createImageBitmap,VE=self.ImageData;else if(Lf)Or=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Xe(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&o.convert(r),o};else throw new Error("Unable to load image processing library.");var wP={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},xP=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Xe=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!Qt)throw new Error("fromCanvas() is only supported in browser environments.");let s=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(s,e.width,e.height,4)}static async fromURL(e){let r=await Bs(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(e){if(Qt){let r=await Or(e),s=fs(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=Lf(await e.arrayBuffer());return await Or(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r<this.data.length;r+=this.channels){let n=this.data[r],o=this.data[r+1],a=this.data[r+2];e[s++]=Math.round(.2989*n+.587*o+.114*a)}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 r=0,s=0;r<this.data.length;++r)e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=this.data[r];break;case 4:for(let r=0,s=0;r<this.data.length;r+=4)e[s++]=this.data[r],e[s++]=this.data[r+1],e[s++]=this.data[r+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 r=0,s=0;r<this.data.length;++r)e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=255;break;case 3:for(let r=0,s=0;r<this.data.length;r+=3)e[s++]=this.data[r],e[s++]=this.data[r+1],e[s++]=this.data[r+2],e[s++]=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)}putAlpha(e){if(e.width!==this.width||e.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${e.width}x${e.height}`);if(e.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${e.channels}`);let r=this.data,s=e.data,n=this.width*this.height;if(this.channels===3){let o=new Uint8ClampedArray(n*4);for(let a=0,i=0,l=0;a<n;++a)o[l++]=r[i++],o[l++]=r[i++],o[l++]=r[i++],o[l++]=s[a];return this._update(o,this.width,this.height,4)}else if(this.channels===4){for(let o=0;o<n;++o)r[4*o+3]=s[o];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(e,r,{resample:s=2}={}){if(this.width===e&&this.height===r)return this;let n=wP[s]??s,o=wp(e),a=wp(r);if(o&&a)return this;if(o?e=r/this.height*this.width:a&&(r=e/this.width*this.height),Qt){let i=this.channels,l=this.toCanvas(),u=fs(e,r).getContext("2d");return u.drawImage(l,0,0,e,r),new t(u.getImageData(0,0,e,r).data,e,r,4).convert(i)}else{let i=this.toSharp();switch(n){case"box":case"hamming":(n==="box"||n==="hamming")&&(console.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":i=i.affine([e/this.width,0,0,r/this.height],{interpolator:n});break;case"lanczos":i=i.resize({width:e,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await Or(i)}}async pad([e,r,s,n]){if(e=Math.max(e,0),r=Math.max(r,0),s=Math.max(s,0),n=Math.max(n,0),e===0&&r===0&&s===0&&n===0)return this;if(Qt){let o=this.channels,a=this.toCanvas(),i=this.width+e+r,l=this.height+s+n,u=fs(i,l).getContext("2d");return u.drawImage(a,0,0,this.width,this.height,e,s,this.width,this.height),new t(u.getImageData(0,0,i,l).data,i,l,4).convert(o)}else{let o=this.toSharp().extend({left:e,right:r,top:s,bottom:n});return await Or(o)}}async crop([e,r,s,n]){if(e=Math.max(e,0),r=Math.max(r,0),s=Math.min(s,this.width-1),n=Math.min(n,this.height-1),e===0&&r===0&&s===this.width-1&&n===this.height-1)return this;let o=s-e+1,a=n-r+1;if(Qt){let i=this.channels,l=this.toCanvas(),u=fs(o,a).getContext("2d");return u.drawImage(l,e,r,o,a,0,0,o,a),new t(u.getImageData(0,0,o,a).data,o,a,4).convert(i)}else{let i=this.toSharp().extract({left:e,top:r,width:o,height:a});return await Or(i)}}async center_crop(e,r){if(this.width===e&&this.height===r)return this;let s=(this.width-e)/2,n=(this.height-r)/2;if(Qt){let o=this.channels,a=this.toCanvas(),i=fs(e,r).getContext("2d"),l=0,u=0,d=0,f=0;return s>=0?l=s:d=-s,n>=0?u=n:f=-n,i.drawImage(a,l,u,e,r,d,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],u=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):u=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:u,top:i,width:e,height:r})}return await Or(o)}}async toBlob(e="image/png",r=1){if(!Qt)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new U("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!Qt)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=fs(e.width,e.height),s=new VE(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;l<a;++l){let u=n*l;for(let d=0;d<n;++d)i[d][l]=e[u+d]}return i.map(l=>new t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(Qt){if(be.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=xP.get(r)??"image/png",n=await this.toBlob(s);return cl(e,n)}else if(be.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(Qt)throw new Error("toSharp() is only supported in server-side environments.");return Lf(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},yP=Xe.read.bind(Xe);function HE(t,e,r=0,s=null){let n=t/e,o=Yv(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),o<r&&(o=Math.ceil(n)*e),o}function Nf([t,e],r){return[Math.max(Math.floor(t/r),1)*r,Math.max(Math.floor(e/r),1)*r]}function $f([t,e,r,s]){return[t-r/2,e-s/2,t+r/2,e+s/2]}function Ir(t,e=.5,r=null,s=!1){let n=t.logits,o=t.pred_boxes,[a,i,l]=n.dims;if(r!==null&&r.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let u=[];for(let d=0;d<a;++d){let f=r!==null?r[d]:null,m={boxes:[],classes:[],scores:[]},_=n[d],w=o[d];for(let x=0;x<i;++x){let k=_[x],E=[],M;if(s){M=k.sigmoid().data;for(let I=0;I<M.length;++I)M[I]>e&&E.push(I)}else{let I=Te(k.data)[1];if(I===l-1||(M=Pe(k.data),M[I]<e))continue;E.push(I)}for(let I of E){let T=w[x].data;T=$f(T),f!==null&&(T=T.map((z,C)=>z*f[(C+1)%2])),m.boxes.push(T),m.classes.push(I),m.scores.push(M[I])}}u.push(m)}return u}function pl(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;o<s;++o){let a=e!==null?e[o]:null,i=r[o];a!==null&&(i=yd(i,a,"bilinear",!1));let[l,u]=a??i.dims.slice(-2),d=new U("int32",new Int32Array(l*u),[l,u]),f=i[0].data,m=d.data;for(let x=1;x<i.dims[0];++x){let k=i[x].data;for(let E=0;E<k.length;++E)k[E]>f[E]&&(f[E]=k[E],m[E]=x)}let _=new Array(i.dims[0]);for(let x=0;x<m.length;++x){let k=m[x];_[k]=k}let w=_.filter(x=>x!==void 0);n.push({segmentation:d,labels:w})}return n}function bP(t,e,r,s){let n=[],o=[],a=[];for(let i=0;i<t.dims[0];++i){let l=t[i],u=e[i],d=Te(l.data)[1];if(d===s)continue;let m=Pe(l.data)[d];m>r&&(n.push(u),o.push(m),a.push(d))}return[n,o,a]}function vP(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let d=0;d<t.length;++d)t[d]===r&&(o.push(d),++a),l[d]>=s&&++i;let u=a>0&&i>0;return u&&(u=a/i>n),[u,o]}function kP(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,u=new U("int32",new Int32Array(i*l),[i,l]),d=[];if(a!==null)for(let x=0;x<t.length;++x)t[x]=yd(t[x],a,"bilinear",!1);let f=new Int32Array(t[0].data.length),m=new Float32Array(t[0].data.length);for(let x=0;x<t.length;++x){let k=e[x],E=t[x].data;for(let M=0;M<E.length;++M)E[M]*=k,E[M]>m[M]&&(f[M]=x,m[M]=E[M])}let _=0,w=u.data;for(let x=0;x<r.length;++x){let k=r[x],[E,M]=vP(f,t,x,s,n);if(E){++_;for(let I of M)w[I]=_;d.push({id:_,label_id:k,score:e[x]})}}return[u,d]}function EP(t,e,r=28,s=3136,n=784*1280){if(t<r||e<r)throw new Error(`height:${t} or width:${e} must be larger than factor:${r}`);if(Math.max(t,e)/Math.min(t,e)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let o=Math.round(t/r)*r,a=Math.round(e/r)*r;if(o*a>n){let i=Math.sqrt(t*e/n);o=Math.floor(t/i/r)*r,a=Math.floor(e/i/r)*r}else if(o*a<s){let i=Math.sqrt(s/(t*e));o=Math.ceil(t*i/r)*r,a=Math.ceil(e*i/r)*r}return[o,a]}function dl(t,e=.5,r=.5,s=.8,n=null,o=null){n===null&&(console.warn("`label_ids_to_fuse` unset. No instance will be fused."),n=new Set);let a=t.class_queries_logits??t.logits,l=(t.masks_queries_logits??t.pred_masks).sigmoid(),[u,d,f]=a.dims;if(f-=1,o!==null&&o.length!==u)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let m=[];for(let _=0;_<u;++_){let w=o!==null?o[_]:null,x=a[_],k=l[_],[E,M,I]=bP(x,k,e,f);if(I.length===0){let[C,v]=w??k.dims.slice(-2),G=new U("int32",new Int32Array(C*v).fill(-1),[C,v]);m.push({segmentation:G,segments_info:[]});continue}let[T,z]=kP(E,M,I,r,s,n,w);m.push({segmentation:T,segments_info:z})}return m}function fl(t,e=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var W=class extends Je{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,r,s=2){let n=e.height,o=e.width,a=r.height,i=r.width,l=Math.min(n,a),u=Math.min(o,i);return l===n&&u===o?e:(n>o?u=Math.floor(o*l/n):o>n&&(l=Math.floor(n*u/o)),await e.resize(u,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=Dn(s.data)[0],a=Te(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,u=s.height,d=0,f=0,m=s.data;for(let _=0;_<s.height;++_){let w=_*s.width;for(let x=0;x<s.width;++x)(m[w+x]-n)/a<i&&(l=Math.min(l,x),u=Math.min(u,_),d=Math.max(d,x),f=Math.max(f,_))}return e=await e.crop([l,u,d,f]),e}pad_image(e,r,s,{mode:n="constant",center:o=!1,constant_values:a=0}={}){let[i,l,u]=r,d,f;if(typeof s=="number"?(d=s,f=s):s==="square"?d=f=Math.max(i,l):(d=s.width,f=s.height),d!==l||f!==i){let m=new Float32Array(d*f*u);if(Array.isArray(a))for(let x=0;x<m.length;++x)m[x]=a[x%u];else a!==0&&m.fill(a);let[_,w]=o?[Math.floor((d-l)/2),Math.floor((f-i)/2)]:[0,0];for(let x=0;x<i;++x){let k=(x+w)*d,E=x*l;for(let M=0;M<l;++M){let I=(k+M+_)*u,T=(E+M)*u;for(let z=0;z<u;++z)m[I+z]=e[T+z]}}if(n==="symmetric"){if(o)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");let x=i-1,k=l-1;for(let E=0;E<f;++E){let M=E*d,I=$s(E,x)*l;for(let T=0;T<d;++T){if(E<i&&T<l)continue;let z=(M+T)*u,C=(I+$s(T,k))*u;for(let v=0;v<u;++v)m[z+v]=e[C+v]}}}e=m,r=[f,d,u]}return[e,r]}rescale(e){for(let r=0;r<e.length;++r)e[r]=this.rescale_factor*e[r]}get_resize_output_image_size(e,r){let[s,n]=e.size,o,a;if(this.do_thumbnail){let{height:i,width:l}=r;o=Math.min(i,l)}else Number.isInteger(r)?(o=r,a=this.config.max_size??o):r!==void 0&&(o=r.shortest_edge,a=r.longest_edge);if(o!==void 0||a!==void 0){let i=o===void 0?1:Math.max(o/s,o/n),l=s*i,u=n*i,d=a===void 0?1:Math.min(a/l,a/u),f=Math.floor(Number((l*d).toFixed(2))),m=Math.floor(Number((u*d).toFixed(2)));return this.size_divisibility!==void 0&&([f,m]=Nf([f,m],this.size_divisibility)),[f,m]}else if(r!==void 0&&r.width!==void 0&&r.height!==void 0){let i=r.width,l=r.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let u=l/n,d=i/s;Math.abs(1-d)<Math.abs(1-u)?u=d:d=u,l=HE(u*n,this.config.ensure_multiple_of),i=HE(d*s,this.config.ensure_multiple_of)}return[i,l]}else{if(this.size_divisibility!==void 0)return Nf([s,n],this.size_divisibility);if(this.min_pixels!==void 0&&this.max_pixels!==void 0){let i=this.config.patch_size*this.config.merge_size;return EP(n,s,i,this.min_pixels,this.max_pixels)}else throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(r)}`)}}async resize(e){let[r,s]=this.get_resize_output_image_size(e,this.size);return await e.resize(r,s,{resample:this.resample})}async preprocess(e,{do_normalize:r=null,do_pad:s=null,do_convert_rgb:n=null,do_convert_grayscale:o=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));let[i,l]=e.size;if(n??this.do_convert_rgb?e=e.rgb():o&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let _,w;Number.isInteger(this.crop_size)?(_=this.crop_size,w=this.crop_size):(_=this.crop_size.width,w=this.crop_size.height),e=await e.center_crop(_,w)}let u=[e.height,e.width],d=Float32Array.from(e.data),f=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(d),r??this.do_normalize){let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(e.channels).fill(_));let w=this.image_std;if(Array.isArray(this.image_std)||(w=new Array(e.channels).fill(w)),_.length!==e.channels||w.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${_.length}) and \`image_std\` (${w.length}) must match the number of channels in the image (${e.channels}).`);for(let x=0;x<d.length;x+=e.channels)for(let k=0;k<e.channels;++k)d[x+k]=(d[x+k]-_[k])/w[k]}if(s??this.do_pad){if(this.pad_size)[d,f]=this.pad_image(d,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){let[_,w]=Nf([f[1],f[0]],this.size_divisibility);[d,f]=this.pad_image(d,f,{width:_,height:w})}}if(a??this.do_flip_channel_order){if(f[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let _=0;_<d.length;_+=3){let w=d[_];d[_]=d[_+2],d[_+2]=w}}let m=new U("float32",d,f).permute(2,0,1);return{original_size:[l,i],reshaped_input_size:u,pixel_values:m}}async _call(e,...r){Array.isArray(e)||(e=[e]);let s=await Promise.all(e.map(o=>this.preprocess(o)));return{pixel_values:Ft(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await at(e,Xs,!0,r);return new this(s)}};var Zs={};Ps(Zs,{BeitFeatureExtractor:()=>Rf,BitImageProcessor:()=>Uf,CLIPFeatureExtractor:()=>Df,CLIPImageProcessor:()=>ml,ChineseCLIPFeatureExtractor:()=>Bf,ConvNextFeatureExtractor:()=>Ff,ConvNextImageProcessor:()=>hl,DINOv3ViTImageProcessor:()=>qf,DPTFeatureExtractor:()=>Vf,DPTImageProcessor:()=>wl,DeiTFeatureExtractor:()=>jf,DeiTImageProcessor:()=>_l,DetrFeatureExtractor:()=>Gf,DetrImageProcessor:()=>gl,DonutFeatureExtractor:()=>Wf,DonutImageProcessor:()=>Ks,EfficientNetImageProcessor:()=>Hf,GLPNFeatureExtractor:()=>Xf,GroundingDinoImageProcessor:()=>Kf,Idefics3ImageProcessor:()=>xl,ImageFeatureExtractor:()=>W,ImageProcessor:()=>W,JinaCLIPImageProcessor:()=>Qf,LlavaOnevisionImageProcessor:()=>Jf,Mask2FormerImageProcessor:()=>em,MaskFormerFeatureExtractor:()=>Zf,MaskFormerImageProcessor:()=>Ys,MobileNetV1FeatureExtractor:()=>tm,MobileNetV1ImageProcessor:()=>yl,MobileNetV2FeatureExtractor:()=>rm,MobileNetV2ImageProcessor:()=>bl,MobileNetV3FeatureExtractor:()=>sm,MobileNetV3ImageProcessor:()=>vl,MobileNetV4FeatureExtractor:()=>nm,MobileNetV4ImageProcessor:()=>kl,MobileViTFeatureExtractor:()=>om,MobileViTImageProcessor:()=>El,NougatImageProcessor:()=>am,OwlViTFeatureExtractor:()=>im,OwlViTImageProcessor:()=>Qs,Owlv2ImageProcessor:()=>lm,Phi3VImageProcessor:()=>pm,PixtralImageProcessor:()=>dm,PvtImageProcessor:()=>fm,Qwen2VLImageProcessor:()=>mm,RTDetrImageProcessor:()=>hm,Sam2ImageProcessor:()=>ao,Sam3ImageProcessor:()=>ao,SamImageProcessor:()=>ao,SapiensFeatureExtractor:()=>_m,SapiensImageProcessor:()=>Al,SegformerFeatureExtractor:()=>gm,SegformerImageProcessor:()=>Ml,SiglipImageProcessor:()=>wm,SmolVLMImageProcessor:()=>xl,Swin2SRImageProcessor:()=>xm,VLMImageProcessor:()=>Yf,ViTFeatureExtractor:()=>ym,ViTImageProcessor:()=>Tl,VitMatteImageProcessor:()=>bm,VitPoseImageProcessor:()=>vm,YolosFeatureExtractor:()=>km,YolosImageProcessor:()=>Sl});var Rf=class extends W{};var Uf=class extends W{};var Bf=class extends W{};var ml=class extends W{},Df=class extends ml{};var hl=class extends W{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){let s=Math.floor(r/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}},Ff=class extends hl{};var _l=class extends W{},jf=class extends _l{};var gl=class extends W{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Ve(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Ir(...e)}post_process_panoptic_segmentation(...e){return dl(...e)}post_process_instance_segmentation(...e){return fl(...e)}},Gf=class extends gl{};var qf=class extends W{};var Ks=class extends W{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let u=this.image_std;Array.isArray(u)||(u=new Array(i).fill(l));let d=l.map((f,m)=>-f/u[m]);return super.pad_image(e,r,s,{center:!0,constant_values:d,...n})}},Wf=class extends Ks{};var wl=class extends W{},Vf=class extends wl{};var Hf=class extends W{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}};var Xf=class extends W{};var Kf=class extends W{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=it([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var xl=class extends W{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],u=[];for(let E of n){let M=await Promise.all(E.map(z=>this.preprocess(z)));l.push(...M.map(z=>z.original_size)),u.push(...M.map(z=>z.reshaped_input_size)),M.forEach(z=>z.pixel_values.unsqueeze_(0));let{longest_edge:I}=this.max_image_size,T;if(r??this.do_image_splitting){let z=new Array(M.length),C=new Array(M.length);T=await Promise.all(M.map(async(v,G)=>{let X=this.get_resize_for_vision_encoder(v.pixel_values,I),V=await Dt(v.pixel_values,{size:[X.height,X.width]}),{frames:Q,num_splits_h:K,num_splits_w:Y}=await this.split_image(V,this.max_image_size);return z[G]=K,C[G]=Y,Ee(Q,0)})),a.push(z),i.push(C)}else{let z=[I,I];T=await Promise.all(M.map(C=>Dt(C.pixel_values,{size:z}))),a.push(new Array(M.length).fill(0)),i.push(new Array(M.length).fill(0))}o.push(Ee(T,0))}let d=o.length,[f,m,_,w]=o[0].dims,x,k;if(d===1)x=o[0].unsqueeze_(0),k=Ve([d,f,_,w],!0);else{let E=Math.max(...o.map(T=>T.dims.at(0)));k=Ve([d,E,_,w],!0);let M=k.data,I=E*_*w;for(let T=0;T<d;++T){let z=o[T].dims[0];if(z<E){o[T]=Ee([o[T],Ve([E-z,m,_,w],0)],0);let C=T*I+z*_*w,v=(T+1)*I;M.fill(!1,C,v)}}x=Ft(o,0)}return{pixel_values:x,pixel_attention_mask:k,original_sizes:l,reshaped_input_sizes:u,...s?{rows:a,cols:i}:{}}}async split_image(e,{longest_edge:r}){let s=r,n=r,o=[],[a,i]=e.dims.slice(-2),l=0,u=0;if(a>s||i>n){l=Math.ceil(a/s),u=Math.ceil(i/n);let d=Math.ceil(a/l),f=Math.ceil(i/u);for(let w=0;w<l;++w)for(let x=0;x<u;++x){let k,E,M,I;w===l-1?(E=a-d,I=a):(E=w*d,I=(w+1)*d),x===u-1?(k=i-f,M=i):(k=x*f,M=(x+1)*f);let C=await al(e,[E,k],[I,M],[2,3]);o.push(C)}let m=s,_=n;(a!==m||i!==_)&&(e=await Dt(e,{size:[m,_]}))}return o.push(e),{frames:o,num_splits_h:l,num_splits_w:u}}};var Yf=class extends W{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map(r=>r*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var Qf=class extends W{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};var Jf=class extends W{};var Ys=class extends W{post_process_panoptic_segmentation(...e){return dl(...e)}post_process_instance_segmentation(...e){return fl(...e)}},Zf=class extends Ys{};var em=class extends Ys{};var yl=class extends W{},tm=class extends yl{};var bl=class extends W{},rm=class extends bl{};var vl=class extends W{},sm=class extends vl{};var kl=class extends W{},nm=class extends kl{};var El=class extends W{},om=class extends El{};var am=class extends Ks{};var Qs=class extends W{post_process_object_detection(...e){return Ir(...e)}},im=class extends Qs{};var lm=class extends Qs{};var Pt=336,AP=[2,3],{ceil:cm,floor:Js,sqrt:um}=Math,pm=class extends W{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,r){let{num_img_tokens:s}=this.config;return Js((Js(r/Pt)*Js(e/Pt)+1)*s+1+(Js(r/Pt)+1)*um(s))}get_resize_output_image_size(e,r){let s=this._num_crops,[n,o]=e.size,a=n/o,i=1;for(;i*Math.ceil(i/a)<=s;)i+=1;i-=1;let l=Math.floor(i*336),u=Math.floor(l/a);return[l,u]}pad_image(e,r,s,n={}){let[o,a]=r,i=Pt*cm(o/Pt),l=Pt*cm(a/Pt),u=[1,1,1].map((d,f)=>(d-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:u,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||um(r)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(m=>this.preprocess(m))),o=n.map(m=>m.original_size),a=n.map(m=>m.reshaped_input_size),i=[];for(let{pixel_values:m}of n){m.unsqueeze_(0);let[_,w]=m.dims.slice(-2),x=await Dt(m,{size:[Pt,Pt],mode:"bicubic"});if(r>0){let k=[],E=um(r),M=Js(w/E),I=Js(_/E);for(let z=0;z<E;++z)for(let C=0;C<E;++C){let v,G,X,V;z===E-1?(G=_-I,V=_):(G=z*I,V=(z+1)*I),C===E-1?(v=w-M,X=w):(v=C*M,X=(C+1)*M);let Y=await al(m,[G,v],[V,X],AP);k.push(Y)}let T=await Dt(Ee(k,0),{size:[Pt,Pt],mode:"bicubic"});i.push(Ee([x,T],0))}else i.push(x)}let l=Ft(i,0),u=a.map(m=>m.map(_=>Pt*cm(_/Pt))),d=new U("int64",u.flat(),[s,2]),f=u.map(([m,_])=>this.calc_num_image_tokens_from_image_size(_,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:d,num_img_tokens:f}}};var dm=class extends W{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:u,spatial_merge_size:d}=this.config;if(!d)throw new Error("config must contain 'spatial_merge_size'");let f=u*d,m=Math.floor((i-1)/f)+1,_=Math.floor((l-1)/f)+1;return[m*f,_*f]}};var fm=class extends W{};var mm=class extends W{async _call(e,...r){let{pixel_values:s,original_sizes:n,reshaped_input_sizes:o}=await super._call(e,...r),a=s,{temporal_patch_size:i,merge_size:l,patch_size:u}=this.config;a.dims[0]===1&&(a=Ee(Array.from({length:i},()=>a),0));let d=a.dims[0]/i,f=a.dims[1],m=Math.floor(a.dims[2]/u),_=Math.floor(a.dims[3]/u),w=a.view(d,i,f,Math.floor(m/l),l,u,Math.floor(_/l),l,u).permute(0,3,6,4,7,2,1,5,8).view(d*m*_,f*i*u*u),x=new U("int64",[d,m,_],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var hm=class extends W{post_process_object_detection(...e){return Ir(...e)}};var ao=class extends W{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=xp(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;a<e.length;++a){let[i,l]=r[a],[u,d]=s[a],f=[d/l,u/i];for(let m=0;m<e[a].length;++m)for(let _=0;_<e[a][m].length;++_)for(let w=0;w<e[a][m][_].length;++w)e[a][m][_][w]*=f[w%2]}return new U("float32",Float32Array.from(e.flat(1/0)),o)}add_input_labels(e,r){let s=xp(e);if(s.length===2)s=[1,...s],e=[e];else if(s.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(s.some((n,o)=>n!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new U("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let u=0;u<r.length;++u){let d=r[u],f=s[u],m=await Dt(e[u],{mode:"bilinear",size:l});if(m=m.slice(null,null,[0,f[0]],[0,f[1]]),m=await Dt(m,{mode:"bilinear",size:d}),o){let _=m.data,w=new Uint8Array(_.length);for(let x=0;x<_.length;++x)_[x]>n&&(w[x]=1);m=new U("bool",w,m.dims)}i.push(m)}return i}generate_crop_boxes(e,r,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:a=1}={}){}};var Al=class extends W{post_process_semantic_segmentation(...e){return pl(...e)}},_m=class extends Al{};var Ml=class extends W{post_process_semantic_segmentation(...e){return pl(...e)}},gm=class extends Ml{};var wm=class extends W{};var xm=class extends W{pad_image(e,r,s,n={}){let[o,a,i]=r;return super.pad_image(e,r,{width:a+(s-a%s)%s,height:o+(s-o%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var Tl=class extends W{},ym=class extends Tl{};var bm=class extends W{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let s=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(r.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:Ft(s.map((a,i)=>Ee([a.pixel_values,n[i].pixel_values],0)),0),original_sizes:s.map(a=>a.original_size),reshaped_input_sizes:s.map(a=>a.reshaped_input_size)}}};var vm=class extends W{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,u=[];for(let d=0;d<o;++d){let f=n[d],m=r[d],_=[];for(let w=0;w<m.length;++w){let x=m[w],k=[],E=[],M=[],I=x.at(-2)/l,T=x.at(-1)/i;for(let z=0;z<f.length;++z){let[C,v]=[0,0],G=0,X=-1/0,V=f[z];for(let K=0;K<V.length;++K){let Y=V[K];for(let B=0;B<Y.length;++B){let P=Y[B];G+=P,X=Math.max(X,P),C+=(B+.5)*P,v+=K*P}}if(s!=null&&X<s)continue;let Q=[I*C/G,T*v/G];k.push(Q),M.push(z),E.push(X)}_.push({bbox:x,scores:E,labels:M,keypoints:k})}u.push(_)}return u}};var Sl=class extends W{post_process_object_detection(...e){return Ir(...e)}},km=class extends Sl{};var $e=class{static async from_pretrained(e,r={}){let s=await at(e,Xs,!0,r),n=s.image_processor_type??s.feature_extractor_type,o=Zs[n?.replace(/Fast$/,"")];return o||(n!==void 0&&console.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${Hs}.`),o=W),new o(s)}};var Em=class extends ne{static tokenizer_class=J;static image_processor_class=$e;constructor(e,r,s){super(e,r,s);let{tasks_answer_post_processing_type:n,task_prompts_without_inputs:o,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(n??{})),this.task_prompts_without_inputs=new Map(Object.entries(o??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("<s>","").replaceAll("</s>","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],u=[];for(let[d,f,...m]of i)l.push(f?f.trim():l.at(-1)??""),u.push(m.map((_,w)=>(Number(_)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:u};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var Am=class extends ne{static image_processor_class=$e;static feature_extractor_class=tt;static tokenizer_class=J;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:n,boa_token:o,audio_token:a,eoa_token:i,image_token_id:l,boi_token:u,image_token:d,eoi_token:f}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=o,this.audio_token=a;let m=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
12
+ }`,_=new Function(Object.keys(O),N)(...Object.values(O)),N=`methodCaller<(${b.map(B=>B.name)}) => ${g.name}>`,_M(Object.defineProperty(_,"name",{value:N}))}function bM(c,d){return d>>>=0,(c=Rt(c>>>0))==Rt(d)}function vM(c){return(c>>>=0)?(c=ml(c),Vt(globalThis[c])):Vt(globalThis)}function kM(c){return c=ml(c>>>0),Vt(e[c])}function EM(c,d){return d>>>=0,c=Rt(c>>>0),d=Rt(d),Vt(c[d])}function AM(c){9<(c>>>=0)&&(cs[c+1]+=1)}function Qb(c,d,_,g,b){return xp[c>>>0](d>>>0,_>>>0,g>>>0,b>>>0)}function MM(c,d,_,g,b){return Qb(c>>>0,d>>>0,_>>>0,g>>>0,b>>>0)}function TM(){return Vt([])}function SM(c){c=Rt(c>>>0);for(var d=Array(c.length),_=0;_<c.length;_++)d[_]=c[_];return Vt(d)}function OM(c){return Vt(ml(c>>>0))}function IM(){return Vt({})}function CM(c){for(var d=Rt(c>>>=0);d.length;){var _=d.pop();d.pop()(_)}fp(c)}function PM(c,d,_){d>>>=0,_>>>=0,c=Rt(c>>>0),d=Rt(d),_=Rt(_),c[d]=_}function zM(c,d){c=yt(c),d>>>=0,c=new Date(1e3*c),(v(),U)[d>>>2>>>0]=c.getUTCSeconds(),(v(),U)[d+4>>>2>>>0]=c.getUTCMinutes(),(v(),U)[d+8>>>2>>>0]=c.getUTCHours(),(v(),U)[d+12>>>2>>>0]=c.getUTCDate(),(v(),U)[d+16>>>2>>>0]=c.getUTCMonth(),(v(),U)[d+20>>>2>>>0]=c.getUTCFullYear()-1900,(v(),U)[d+24>>>2>>>0]=c.getUTCDay(),c=(c.getTime()-Date.UTC(c.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(v(),U)[d+28>>>2>>>0]=c}var Jb=c=>c%4==0&&(c%100!=0||c%400==0),Zb=[0,31,60,91,121,152,182,213,244,274,305,335],e1=[0,31,59,90,120,151,181,212,243,273,304,334];function LM(c,d){c=yt(c),d>>>=0,c=new Date(1e3*c),(v(),U)[d>>>2>>>0]=c.getSeconds(),(v(),U)[d+4>>>2>>>0]=c.getMinutes(),(v(),U)[d+8>>>2>>>0]=c.getHours(),(v(),U)[d+12>>>2>>>0]=c.getDate(),(v(),U)[d+16>>>2>>>0]=c.getMonth(),(v(),U)[d+20>>>2>>>0]=c.getFullYear()-1900,(v(),U)[d+24>>>2>>>0]=c.getDay();var _=(Jb(c.getFullYear())?Zb:e1)[c.getMonth()]+c.getDate()-1|0;(v(),U)[d+28>>>2>>>0]=_,(v(),U)[d+36>>>2>>>0]=-60*c.getTimezoneOffset(),_=new Date(c.getFullYear(),6,1).getTimezoneOffset();var g=new Date(c.getFullYear(),0,1).getTimezoneOffset();c=0|(_!=g&&c.getTimezoneOffset()==Math.min(g,_)),(v(),U)[d+32>>>2>>>0]=c}function NM(c){c>>>=0;var d=new Date((v(),U)[c+20>>>2>>>0]+1900,(v(),U)[c+16>>>2>>>0],(v(),U)[c+12>>>2>>>0],(v(),U)[c+8>>>2>>>0],(v(),U)[c+4>>>2>>>0],(v(),U)[c>>>2>>>0],0),_=(v(),U)[c+32>>>2>>>0],g=d.getTimezoneOffset(),b=new Date(d.getFullYear(),6,1).getTimezoneOffset(),M=new Date(d.getFullYear(),0,1).getTimezoneOffset(),O=Math.min(M,b);return 0>_?(v(),U)[c+32>>>2>>>0]=+(b!=M&&O==g):0<_!=(O==g)&&(b=Math.max(M,b),d.setTime(d.getTime()+6e4*((0<_?O:b)-g))),(v(),U)[c+24>>>2>>>0]=d.getDay(),_=(Jb(d.getFullYear())?Zb:e1)[d.getMonth()]+d.getDate()-1|0,(v(),U)[c+28>>>2>>>0]=_,(v(),U)[c>>>2>>>0]=d.getSeconds(),(v(),U)[c+4>>>2>>>0]=d.getMinutes(),(v(),U)[c+8>>>2>>>0]=d.getHours(),(v(),U)[c+12>>>2>>>0]=d.getDate(),(v(),U)[c+16>>>2>>>0]=d.getMonth(),(v(),U)[c+20>>>2>>>0]=d.getYear(),c=d.getTime(),BigInt(isNaN(c)?-1:c/1e3)}function t1(c,d,_,g,b,M,O){return n?$e(16,1,c,d,_,g,b,M,O):-52}function r1(c,d,_,g,b,M){if(n)return $e(17,1,c,d,_,g,b,M)}var Fn={},$M=()=>performance.timeOrigin+performance.now();function s1(c,d){if(n)return $e(18,1,c,d);if(Fn[c]&&(clearTimeout(Fn[c].id),delete Fn[c]),!d)return 0;var _=setTimeout(()=>{delete Fn[c],bt(()=>P1(c,performance.timeOrigin+performance.now()))},d);return Fn[c]={id:_,Ce:d},0}function RM(c,d,_,g){c>>>=0,d>>>=0,_>>>=0,g>>>=0;var b=new Date().getFullYear(),M=new Date(b,0,1).getTimezoneOffset();b=new Date(b,6,1).getTimezoneOffset();var O=Math.max(M,b);(v(),z)[c>>>2>>>0]=60*O,(v(),U)[d>>>2>>>0]=+(M!=b),c=(d=N=>{var B=Math.abs(N);return`UTC${0<=N?"-":"+"}${String(Math.floor(B/60)).padStart(2,"0")}${String(B%60).padStart(2,"0")}`})(M),d=d(b),b<M?(gr(c,_,17),gr(d,g,17)):(gr(c,g,17),gr(d,_,17))}var DM=()=>Date.now(),UM=1;function BM(c,d,_){if(_>>>=0,!(0<=c&&3>=c))return 28;if(c===0)c=Date.now();else{if(!UM)return 52;c=performance.timeOrigin+performance.now()}return c=Math.round(1e6*c),(v(),I)[_>>>3>>>0]=BigInt(c),0}var yp=[],n1=(c,d)=>{yp.length=0;for(var _;_=(v(),J)[c++>>>0];){var g=_!=105;d+=(g&=_!=112)&&d%8?4:0,yp.push(_==112?(v(),z)[d>>>2>>>0]:_==106?(v(),I)[d>>>3>>>0]:_==105?(v(),U)[d>>>2>>>0]:(v(),ae)[d>>>3>>>0]),d+=g?8:4}return yp};function FM(c,d,_){return c>>>=0,d=n1(d>>>0,_>>>0),Np[c](...d)}function jM(c,d,_){return c>>>=0,d=n1(d>>>0,_>>>0),Np[c](...d)}var GM=()=>{};function qM(c,d){return T(js(c>>>0,d>>>0))}var WM=()=>{throw be+=1,"unwind"};function VM(){return 4294901760}var HM=()=>1,XM=()=>navigator.hardwareConcurrency;function KM(c){c>>>=0;var d=(v(),J).length;if(c<=d||4294901760<c)return!1;for(var _=1;4>=_;_*=2){var g=d*(1+.2/_);g=Math.min(g,c+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(c,g)/65536))-Cr.buffer.byteLength+65535)/65536|0;try{Cr.grow(g),pe();var b=1;break e}catch{}b=void 0}if(b)return!0}return!1}var nr=c=>{var d=wr(c)+1,_=wl(d);return gr(c,_,d),_},bp=(c,d)=>{(v(),z)[c>>>2>>>0]=d;var _=(v(),z)[c>>>2>>>0];(v(),z)[c+4>>>2>>>0]=(d-_)/4294967296},jn=c=>(v(),z)[c>>>2>>>0]+4294967296*(v(),U)[c+4>>>2>>>0],dt=[],YM=(c,d)=>{dt[c>>>0]=d},xr=[],hl=[],qs=(c,d)=>{hl[c]=new Promise(_=>d.finally(()=>_(c)))},re=c=>{if(c)return dt[c>>>0]},QM=(c,d)=>{for(c=(v(),z)[c>>>2>>>0];c;c=(v(),z)[c>>>2>>>0])d[(v(),U)[c+4>>>2>>>0]](c)},_l=(c,d,_)=>{(v(),z)[c>>>2>>>0]=d,(v(),z)[c+4>>>2>>>0]=_},o1=c=>{var d=(v(),z)[c>>>2>>>0];return c=(v(),z)[c+4>>>2>>>0],js(d,c)},yr=c=>{var d=(v(),z)[c>>>2>>>0];return c=(v(),z)[c+4>>>2>>>0],d?js(d,c):c===0?"":void 0},JM=c=>{var d=yr(c+4),_=(_=(v(),z)[c+12>>>2>>>0])?re(_):"auto";if(c+=16){var g=re((v(),z)[c+4>>>2>>>0]),b=(v(),z)[c+16>>>2>>>0],M=(v(),z)[c+20>>>2>>>0];if(b){for(var O={},N=0;N<b;++N){var B=M+24*N;O[o1(B+4)]=(v(),ae)[B+16>>>3>>>0]}b=O}else b=void 0;c={module:g,constants:b,entryPoint:yr(c+8)}}else c=void 0;return{label:d,layout:_,compute:c}},a1=(c,d)=>{function _(g,b){g=c[g],(v(),z)[d+b>>>2>>>0]=g}_("maxTextureDimension1D",4),_("maxTextureDimension2D",8),_("maxTextureDimension3D",12),_("maxTextureArrayLayers",16),_("maxBindGroups",20),_("maxBindGroupsPlusVertexBuffers",24),_("maxBindingsPerBindGroup",28),_("maxDynamicUniformBuffersPerPipelineLayout",32),_("maxDynamicStorageBuffersPerPipelineLayout",36),_("maxSampledTexturesPerShaderStage",40),_("maxSamplersPerShaderStage",44),_("maxStorageBuffersPerShaderStage",48),_("maxStorageTexturesPerShaderStage",52),_("maxUniformBuffersPerShaderStage",56),_("minUniformBufferOffsetAlignment",80),_("minStorageBufferOffsetAlignment",84),bp(d+64,c.maxUniformBufferBindingSize),bp(d+72,c.maxStorageBufferBindingSize),_("maxVertexBuffers",88),bp(d+96,c.maxBufferSize),_("maxVertexAttributes",104),_("maxVertexBufferArrayStride",108),_("maxInterStageShaderVariables",112),_("maxColorAttachments",116),_("maxColorAttachmentBytesPerSample",120),_("maxComputeWorkgroupStorageSize",124),_("maxComputeInvocationsPerWorkgroup",128),_("maxComputeWorkgroupSizeX",132),_("maxComputeWorkgroupSizeY",136),_("maxComputeWorkgroupSizeZ",140),_("maxComputeWorkgroupsPerDimension",144),c.Ae!==void 0&&_("maxImmediateSize",148)},ZM=[,"validation","out-of-memory","internal"],eT=[,"compatibility","core"],i1={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},tT=[,"low-power","high-performance"],rT=[,"occlusion","timestamp"],sT={undefined:1,unknown:1,destroyed:2};function nT(c,d,_,g,b,M){d=yt(d),_=yt(_),g>>>=0,b>>>=0,M>>>=0;var O=re(c>>>0);if(c={},M){var N=(v(),z)[M+12>>>2>>>0];if(N){var B=(v(),z)[M+16>>>2>>>0];c.requiredFeatures=Array.from((v(),z).subarray(B>>>2>>>0,B+4*N>>>2>>>0),se=>i1[se])}var K=(v(),z)[M+20>>>2>>>0];if(K){let se=function(vt,lt,us=!1){lt=K+lt,(lt=(v(),z)[lt>>>2>>>0])==4294967295||us&&lt==0||(Be[vt]=lt)},it=function(vt,lt){lt=K+lt;var us=(v(),z)[lt>>>2>>>0],OS=(v(),z)[lt+4>>>2>>>0];us==4294967295&&OS==4294967295||(Be[vt]=jn(lt))};var Te=se,ze=it,Be={};se("maxTextureDimension1D",4),se("maxTextureDimension2D",8),se("maxTextureDimension3D",12),se("maxTextureArrayLayers",16),se("maxBindGroups",20),se("maxBindGroupsPlusVertexBuffers",24),se("maxDynamicUniformBuffersPerPipelineLayout",32),se("maxDynamicStorageBuffersPerPipelineLayout",36),se("maxSampledTexturesPerShaderStage",40),se("maxSamplersPerShaderStage",44),se("maxStorageBuffersPerShaderStage",48),se("maxStorageTexturesPerShaderStage",52),se("maxUniformBuffersPerShaderStage",56),se("minUniformBufferOffsetAlignment",80),se("minStorageBufferOffsetAlignment",84),it("maxUniformBufferBindingSize",64),it("maxStorageBufferBindingSize",72),se("maxVertexBuffers",88),it("maxBufferSize",96),se("maxVertexAttributes",104),se("maxVertexBufferArrayStride",108),se("maxInterStageShaderVariables",112),se("maxColorAttachments",116),se("maxColorAttachmentBytesPerSample",120),se("maxComputeWorkgroupStorageSize",124),se("maxComputeInvocationsPerWorkgroup",128),se("maxComputeWorkgroupSizeX",132),se("maxComputeWorkgroupSizeY",136),se("maxComputeWorkgroupSizeZ",140),se("maxComputeWorkgroupsPerDimension",144),se("maxImmediateSize",148,!0),c.requiredLimits=Be}(N=(v(),z)[M+24>>>2>>>0])&&(N={label:yr(N+4)},c.defaultQueue=N),c.label=yr(M+4)}be+=1,qs(d,O.requestDevice(c).then(se=>{--be,bt(()=>{dt[b>>>0]=se.queue,dt[g>>>0]=se,qs(_,se.lost.then(it=>{bt(()=>{se.onuncapturederror=()=>{};var vt=le(),lt=nr(it.message);Mp(_,sT[it.reason],lt),ie(vt)})})),se.onuncapturederror=it=>{var vt=5;it.error instanceof GPUValidationError?vt=2:it.error instanceof GPUOutOfMemoryError?vt=3:it.error instanceof GPUInternalError&&(vt=4);var lt=le();it=nr(it.error.message),S1(g,vt,it),ie(lt)},"adapterInfo"in se||(se.adapterInfo=O.info),Op(d,1,g,0)})},se=>{--be,bt(()=>{var it=le(),vt=nr(se.message);Op(d,3,g,vt),_&&Mp(_,4,vt),ie(it)})}))}function oT(c){var d=re(c>>>=0),_=xr[c];if(_){for(var g=0;g<_.length;++g)_[g]();delete xr[c]}d.destroy()}function aT(c,d,_){_>>>=0;var g=re(c>>>=0);_==4294967295&&(_=void 0);try{var b=g.getMappedRange(d>>>0,_)}catch{return 0}var M=Pp(16,b.byteLength);return(v(),J).set(new Uint8Array(b),M>>>0),xr[c].push(()=>Ht(M)),M}function iT(c,d,_){_>>>=0;var g=re(c>>>=0);_==4294967295&&(_=void 0);try{var b=g.getMappedRange(d>>>0,_)}catch{return 0}var M=Pp(16,b.byteLength);return(v(),J).fill(0,M,b.byteLength),xr[c].push(()=>{new Uint8Array(b).set((v(),J).subarray(M>>>0,M+b.byteLength>>>0)),Ht(M)}),M}function lT(c,d,_,g,b){c>>>=0,d=yt(d),_=yt(_),b>>>=0;var M=re(c);xr[c]=[],b==4294967295&&(b=void 0),be+=1,qs(d,M.mapAsync(_,g>>>0,b).then(()=>{--be,bt(()=>{Tp(d,1,0)})},O=>{--be,bt(()=>{le();var N=nr(O.message);Tp(d,O.name==="AbortError"?4:O.name==="OperationError"?3:0,N),delete xr[c]})}))}function cT(c){var d=re(c>>>=0),_=xr[c];if(_){for(var g=0;g<_.length;++g)_[g]();delete xr[c],d.unmap()}}function uT(c){delete dt[c>>>0]}function pT(c,d,_){c>>>=0,d>>>=0,_>>>=0;var g=!!(v(),z)[d+32>>>2>>>0];d={label:yr(d+4),usage:(v(),z)[d+16>>>2>>>0],size:jn(d+24),mappedAtCreation:g},c=re(c);try{var b=c.createBuffer(d)}catch{return!1}return dt[_>>>0]=b,g&&(xr[_]=[]),!0}function dT(c,d,_,g){c>>>=0,d=yt(d),g>>>=0,_=JM(_>>>0),c=re(c),be+=1,qs(d,c.createComputePipelineAsync(_).then(b=>{--be,bt(()=>{dt[g>>>0]=b,Ap(d,1,g,0)})},b=>{--be,bt(()=>{var M=le(),O=nr(b.message);Ap(d,b.reason==="validation"?3:b.reason==="internal"?4:0,g,O),ie(M)})}))}function fT(c,d,_){c>>>=0,d>>>=0,_>>>=0;var g=(v(),z)[d>>>2>>>0],b=(v(),U)[g+4>>>2>>>0];d={label:yr(d+4),code:""},b===2&&(d.code=o1(g+8)),c=re(c).createShaderModule(d),dt[_>>>0]=c}var mT=c=>{(c=re(c)).onuncapturederror=null,c.destroy()};function hT(c,d){d=yt(d),c=re(c>>>0),be+=1,qs(d,c.popErrorScope().then(_=>{--be,bt(()=>{var g=5;_?_ instanceof GPUValidationError?g=2:_ instanceof GPUOutOfMemoryError?g=3:_ instanceof GPUInternalError&&(g=4):g=1;var b=le(),M=_?nr(_.message):0;Sp(d,1,g,M),ie(b)})},_=>{--be,bt(()=>{var g=le(),b=nr(_.message);Sp(d,1,5,b),ie(g)})}))}function _T(c,d,_,g){if(d=yt(d),g>>>=0,_>>>=0){var b={featureLevel:eT[(v(),U)[_+4>>>2>>>0]],powerPreference:tT[(v(),U)[_+8>>>2>>>0]],forceFallbackAdapter:!!(v(),z)[_+12>>>2>>>0]};(c=(v(),z)[_>>>2>>>0])!==0&&(v(),b.Fe=!!(v(),z)[c+8>>>2>>>0])}"gpu"in navigator?(be+=1,qs(d,navigator.gpu.requestAdapter(b).then(M=>{--be,bt(()=>{if(M)dt[g>>>0]=M,Gn(d,1,g,0);else{var O=le(),N=nr("WebGPU not available on this browser (requestAdapter returned null)");Gn(d,3,g,N),ie(O)}})},M=>{--be,bt(()=>{var O=le(),N=nr(M.message);Gn(d,4,g,N),ie(O)})}))):(b=le(),c=nr("WebGPU not available on this browser (navigator.gpu is not available)"),Gn(d,3,g,c),ie(b))}function gT(c,d,_){return c>>>=0,d>>>=0,_>>>=0,Yb(async()=>{var g=[];if(_){var b=(v(),U)[_>>>2>>>0];g.length=d+1,g[d]=new Promise(N=>setTimeout(N,b,0))}else g.length=d;for(var M=0;M<d;++M){var O=jn(c+8*M);if(!(O in hl))return O;g[M]=hl[O]}return g=await Promise.race(g),delete hl[g],g})}var vp,kp={},l1=()=>{if(!vp){var c,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(c in kp)kp[c]===void 0?delete d[c]:d[c]=kp[c];var _=[];for(c in d)_.push(`${c}=${d[c]}`);vp=_}return vp};function c1(c,d){if(n)return $e(19,1,c,d);c>>>=0,d>>>=0;var _,g=0,b=0;for(_ of l1()){var M=d+g;(v(),z)[c+b>>>2>>>0]=M,g+=gr(_,M,1/0)+1,b+=4}return 0}function u1(c,d){if(n)return $e(20,1,c,d);c>>>=0,d>>>=0;var _=l1();for(var g of((v(),z)[c>>>2>>>0]=_.length,c=0,_))c+=wr(g)+1;return(v(),z)[d>>>2>>>0]=c,0}function p1(c){return n?$e(21,1,c):52}function d1(c,d,_,g){return n?$e(22,1,c,d,_,g):52}function f1(c,d,_,g){return n?$e(23,1,c,d,_,g):70}var wT=[null,[],[]];function m1(c,d,_,g){if(n)return $e(24,1,c,d,_,g);d>>>=0,_>>>=0,g>>>=0;for(var b=0,M=0;M<_;M++){var O=(v(),z)[d>>>2>>>0],N=(v(),z)[d+4>>>2>>>0];d+=8;for(var B=0;B<N;B++){var K=c,Te=(v(),J)[O+B>>>0],ze=wT[K];Te===0||Te===10?((K===1?S:T)(Ib(ze)),ze.length=0):ze.push(Te)}b+=N}return(v(),z)[g>>>2>>>0]=b,0}function xT(c){return c>>>0}function yT(c,d){return a1(re(c>>>0).limits,d>>>0),1}function bT(c,d){return re(c>>>0).features.has(i1[d])}function vT(c){return BigInt(re(c>>>0).size)}function kT(c){return BigInt(re(c>>>0).usage)}function ET(c,d){if(c>>>=0,d>>>=0){var _=yr(d+4);_={label:_,timestampWrites:d=(d=(v(),z)[d+12>>>2>>>0])!==0?{querySet:re((v(),z)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(v(),z)[d+8>>>2>>>0],endOfPassWriteIndex:(v(),z)[d+12>>>2>>>0]}:void 0}}return d=re(c),c=k1(0),_=d.beginComputePass(_),dt[c>>>0]=_,c}function AT(c,d,_,g,b,M){_=yt(_),b=yt(b),M=yt(M),re(c>>>0).copyBufferToBuffer(re(d>>>0),_,re(g>>>0),b,M)}function MT(c){var d=re(c>>>0);return c=b1(0),d=d.finish(),dt[c>>>0]=d,c}function TT(c,d,_,g,b,M){M=yt(M),re(c>>>0).resolveQuerySet(re(d>>>0),_,g,re(b>>>0),M)}function ST(c,d,_,g){re(c>>>0).dispatchWorkgroups(d,_,g)}function OT(c,d,_){_=yt(_),re(c>>>0).dispatchWorkgroupsIndirect(re(d>>>0),_)}function IT(c){re(c>>>0).end()}function CT(c,d,_,g,b){g>>>=0,b>>>=0,c=re(c>>>0),_=re(_>>>0),g==0?c.setBindGroup(d,_):c.setBindGroup(d,_,(v(),z),b>>>2,g)}function PT(c,d){re(c>>>0).setPipeline(re(d>>>0))}function zT(c,d,_){re(c>>>0).Ee(re(d>>>0),_)}function LT(c,d){var _=re(c>>>0);return c=y1(0),d=_.getBindGroupLayout(d),dt[c>>>0]=d,c}function NT(c,d){function _(b){var M=(v(),z)[b+8>>>2>>>0],O=(v(),z)[b+32>>>2>>>0],N=(v(),z)[b+36>>>2>>>0],B=0;return QM(b,{327681:K=>{B=(v(),z)[K+8>>>2>>>0]}}),M?((O=jn(b+24))==-1&&(O=void 0),M={buffer:re(M),offset:jn(b+16),size:O}):M=re(O||N||B),{binding:(v(),z)[b+4>>>2>>>0],resource:M}}c>>>=0,d={label:yr(4+(d>>>=0)),layout:re((v(),z)[d+12>>>2>>>0]),entries:(function(b,M){for(var O=[],N=0;N<b;++N)O.push(_(M+40*N));return O})((v(),z)[d+16>>>2>>>0],(v(),z)[d+20>>>2>>>0])},c=re(c);var g=x1(0);return YM(g,c.createBindGroup(d)),g}function $T(c,d){var _;return c>>>=0,(d>>>=0)&&(_={label:yr(d+4)}),d=re(c),c=v1(0),_=d.createCommandEncoder(_),dt[c>>>0]=_,c}function RT(c,d){c>>>=0,d>>>=0,d={type:rT[(v(),U)[d+12>>>2>>>0]],count:(v(),z)[d+16>>>2>>>0]};var _=re(c);return c=E1(0),d=_.createQuerySet(d),dt[c>>>0]=d,c}function DT(c,d){c=re(c>>>0).adapterInfo,d>>>=0,(v(),z)[d+52>>>2>>>0]=c.subgroupMinSize,(v(),z)[d+56>>>2>>>0]=c.subgroupMaxSize;var _=c.vendor+c.architecture+c.device+c.description,g=wr(_)+1,b=Ws(g);return b&&gr(_,b,g),_=b,g=wr(c.vendor),_l(d+4,_,g),_+=g,g=wr(c.architecture),_l(d+12,_,g),_+=g,g=wr(c.device),_l(d+20,_,g),_l(d+28,_+g,wr(c.description)),(v(),U)[d+36>>>2>>>0]=2,c=c.isFallbackAdapter?3:4,(v(),U)[d+40>>>2>>>0]=c,(v(),z)[d+44>>>2>>>0]=0,(v(),z)[d+48>>>2>>>0]=0,1}var UT={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function BT(c,d){d>>>=0;var _=re(c>>>0);c=Ws(4*_.features.size);var g=0,b=0;for(let M of _.features)0<=(_=UT[M])&&((v(),U)[c+g>>>2>>>0]=_,g+=4,b++);(v(),z)[d+4>>>2>>>0]=c,(v(),z)[d>>>2>>>0]=b}function FT(c,d){return a1(re(c>>>0).limits,d>>>0),1}function jT(c,d){re(c>>>0).pushErrorScope(ZM[d])}function GT(c,d,_){d>>>=0,_>>>=0,c=re(c>>>0),d=Array.from((v(),U).subarray(_>>>2>>>0,_+4*d>>>2>>>0),g=>re(g)),c.submit(d)}function qT(c,d,_,g,b){_=yt(_),g>>>=0,b>>>=0,c=re(c>>>0),d=re(d>>>0),g=(v(),J).subarray(g>>>0,g+b>>>0),c.writeBuffer(d,_,g,0,b)}n||(function(){for(var c=e.numThreads-1;c--;)kb();Me.push(async()=>{var d=(async function(){if(!n)return Promise.all(tt.map(vb))})();xe++,await d,--xe==0&&qe&&(d=qe,qe=null,d())})})(),n||(Cr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),pe()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>le(),e.stackRestore=c=>ie(c),e.stackAlloc=c=>wl(c),e.setValue=function(c,d,_="i8"){switch(_.endsWith("*")&&(_="*"),_){case"i1":case"i8":(v(),V)[c>>>0]=d;break;case"i16":(v(),X)[c>>>1>>>0]=d;break;case"i32":(v(),U)[c>>>2>>>0]=d;break;case"i64":(v(),I)[c>>>3>>>0]=BigInt(d);break;case"float":(v(),ne)[c>>>2>>>0]=d;break;case"double":(v(),ae)[c>>>3>>>0]=d;break;case"*":(v(),z)[c>>>2>>>0]=d;break;default:Pe(`invalid type for setValue: ${_}`)}},e.getValue=function(c,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(v(),V)[c>>>0];case"i16":return(v(),X)[c>>>1>>>0];case"i32":return(v(),U)[c>>>2>>>0];case"i64":return(v(),I)[c>>>3>>>0];case"float":return(v(),ne)[c>>>2>>>0];case"double":return(v(),ae)[c>>>3>>>0];case"*":return(v(),z)[c>>>2>>>0];default:Pe(`invalid type for getValue: ${d}`)}},e.UTF8ToString=js,e.stringToUTF8=gr,e.lengthBytesUTF8=wr;var h1,_1,Ep,gl,Ht,Ws,g1,w1,x1,y1,b1,v1,k1,E1,A1,M1,T1,Ap,Mp,Tp,Sp,Gn,Op,S1,Ip,O1,I1,C1,Cp,P1,z1,Pp,_e,qn,L1,ie,wl,le,N1,zp,$1,R1,D1,Lp,U1,B1,F1,j1,G1,q1,W1,V1,H1,X1,K1,Y1,Q1,J1,Z1,ev,tv,rv,sv,nv,ov,av,iv,lv,cv,uv,pv,dv,fv,mv,hv,_v,gv,wv,xv,yv,bv,vv,kv,br,WT=[Ir,is,Mb,Cb,Pb,zb,Lb,Nb,$b,Rb,Db,Ub,Bb,Fb,jb,Gb,t1,r1,s1,c1,u1,p1,d1,f1,m1],Np={922732:(c,d,_,g,b)=>{if(e===void 0||!e.Uc)return 1;if((c=js(Number(c>>>0))).startsWith("./")&&(c=c.substring(2)),!(c=e.Uc.get(c)))return 2;if(d=Number(d>>>0),_=Number(_>>>0),g=Number(g>>>0),d+_>c.byteLength)return 3;try{let M=c.subarray(d,d+_);switch(b){case 0:(v(),J).set(M,g>>>0);break;case 1:e.ad?e.ad(g,M):e.oe(g,M);break;default:return 4}return 0}catch{return 4}},923556:(c,d,_)=>{e.Sd(c,(v(),J).subarray(d>>>0,d+_>>>0))},923620:()=>e.me(),923662:c=>{e.jd(c)},923699:()=>typeof wasmOffsetConverter<"u"};function VT(c,d,_,g){var b=le();try{return V1(c,d,_,g)}catch(M){if(ie(b),M!==M+0)throw M;_e(1,0)}}function HT(c,d,_){var g=le();try{return G1(c,d,_)}catch(b){if(ie(g),b!==b+0)throw b;_e(1,0)}}function XT(c,d,_){var g=le();try{D1(c,d,_)}catch(b){if(ie(g),b!==b+0)throw b;_e(1,0)}}function KT(c,d){var _=le();try{return Lp(c,d)}catch(g){if(ie(_),g!==g+0)throw g;_e(1,0)}}function YT(c){var d=le();try{U1(c)}catch(_){if(ie(d),_!==_+0)throw _;_e(1,0)}}function QT(c,d,_,g,b,M,O){var N=le();try{return j1(c,d,_,g,b,M,O)}catch(B){if(ie(N),B!==B+0)throw B;_e(1,0)}}function JT(c,d){var _=le();try{H1(c,d)}catch(g){if(ie(_),g!==g+0)throw g;_e(1,0)}}function ZT(c,d,_,g,b,M){var O=le();try{B1(c,d,_,g,b,M)}catch(N){if(ie(O),N!==N+0)throw N;_e(1,0)}}function eS(c,d,_,g){var b=le();try{W1(c,d,_,g)}catch(M){if(ie(b),M!==M+0)throw M;_e(1,0)}}function tS(c,d,_,g,b,M,O){var N=le();try{K1(c,d,_,g,b,M,O)}catch(B){if(ie(N),B!==B+0)throw B;_e(1,0)}}function rS(c,d,_,g,b,M,O){var N=le();try{Y1(c,d,_,g,b,M,O)}catch(B){if(ie(N),B!==B+0)throw B;_e(1,0)}}function sS(c,d,_,g,b,M,O,N){var B=le();try{ov(c,d,_,g,b,M,O,N)}catch(K){if(ie(B),K!==K+0)throw K;_e(1,0)}}function nS(c,d,_,g,b,M,O,N,B,K,Te,ze){var Be=le();try{Q1(c,d,_,g,b,M,O,N,B,K,Te,ze)}catch(se){if(ie(Be),se!==se+0)throw se;_e(1,0)}}function oS(c,d,_,g,b){var M=le();try{return X1(c,d,_,g,b)}catch(O){if(ie(M),O!==O+0)throw O;_e(1,0)}}function aS(c,d,_,g,b){var M=le();try{F1(c,d,_,g,b)}catch(O){if(ie(M),O!==O+0)throw O;_e(1,0)}}function iS(c,d,_,g,b,M,O,N){var B=le();try{q1(c,d,_,g,b,M,O,N)}catch(K){if(ie(B),K!==K+0)throw K;_e(1,0)}}function lS(c){var d=le();try{return av(c)}catch(_){if(ie(d),_!==_+0)throw _;_e(1,0)}}function cS(c,d,_){var g=le();try{return iv(c,d,_)}catch(b){if(ie(g),b!==b+0)throw b;_e(1,0)}}function uS(c,d){var _=le();try{return xv(c,d)}catch(g){if(ie(_),g!==g+0)throw g;return _e(1,0),0n}}function pS(c,d,_,g,b){var M=le();try{lv(c,d,_,g,b)}catch(O){if(ie(M),O!==O+0)throw O;_e(1,0)}}function dS(c){var d=le();try{return J1(c)}catch(_){if(ie(d),_!==_+0)throw _;return _e(1,0),0n}}function fS(c,d,_,g,b,M){var O=le();try{return sv(c,d,_,g,b,M)}catch(N){if(ie(O),N!==N+0)throw N;_e(1,0)}}function mS(c,d,_,g,b,M){var O=le();try{return cv(c,d,_,g,b,M)}catch(N){if(ie(O),N!==N+0)throw N;_e(1,0)}}function hS(c,d,_,g,b,M){var O=le();try{return uv(c,d,_,g,b,M)}catch(N){if(ie(O),N!==N+0)throw N;_e(1,0)}}function _S(c,d,_,g,b,M,O,N){var B=le();try{return nv(c,d,_,g,b,M,O,N)}catch(K){if(ie(B),K!==K+0)throw K;_e(1,0)}}function gS(c,d,_,g,b){var M=le();try{return pv(c,d,_,g,b)}catch(O){if(ie(M),O!==O+0)throw O;return _e(1,0),0n}}function wS(c,d,_,g){var b=le();try{return dv(c,d,_,g)}catch(M){if(ie(b),M!==M+0)throw M;_e(1,0)}}function xS(c,d,_,g){var b=le();try{return fv(c,d,_,g)}catch(M){if(ie(b),M!==M+0)throw M;_e(1,0)}}function yS(c,d,_,g,b,M,O,N,B,K,Te,ze){var Be=le();try{return mv(c,d,_,g,b,M,O,N,B,K,Te,ze)}catch(se){if(ie(Be),se!==se+0)throw se;_e(1,0)}}function bS(c,d,_,g,b,M,O,N,B,K,Te){var ze=le();try{hv(c,d,_,g,b,M,O,N,B,K,Te)}catch(Be){if(ie(ze),Be!==Be+0)throw Be;_e(1,0)}}function vS(c,d,_,g,b,M,O,N,B,K,Te,ze,Be,se,it,vt){var lt=le();try{_v(c,d,_,g,b,M,O,N,B,K,Te,ze,Be,se,it,vt)}catch(us){if(ie(lt),us!==us+0)throw us;_e(1,0)}}function kS(c,d,_,g){var b=le();try{return gv(c,d,_,g)}catch(M){if(ie(b),M!==M+0)throw M;_e(1,0)}}function ES(c,d,_,g,b){var M=le();try{return wv(c,d,_,g,b)}catch(O){if(ie(M),O!==O+0)throw O;_e(1,0)}}function AS(c,d,_){var g=le();try{return ev(c,d,_)}catch(b){if(ie(g),b!==b+0)throw b;return _e(1,0),0n}}function MS(c,d,_){var g=le();try{return Z1(c,d,_)}catch(b){if(ie(g),b!==b+0)throw b;_e(1,0)}}function TS(c,d,_){var g=le();try{return tv(c,d,_)}catch(b){if(ie(g),b!==b+0)throw b;_e(1,0)}}function SS(c,d,_,g){var b=le();try{rv(c,d,_,g)}catch(M){if(ie(b),M!==M+0)throw M;_e(1,0)}}function xl(){if(0<xe)qe=xl;else if(n)w?.(e),Fe();else{for(var c=Me;0<c.length;)c.shift()(e);0<xe?qe=xl:(e.calledRun=!0,P||(Fe(),w?.(e)))}}return n||(br=await Je(),xl()),e.PTR_SIZE=4,e.webgpuInit=c=>{let d=new WeakMap,_,g,b=1;e.webgpuRegisterDevice=N=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(N){var B=d.get(N);if(!B){let K=((Te,ze=0)=>{var Be=T1(ze);return ze=M1(ze,Be),dt[Be>>>0]=Te.queue,dt[ze>>>0]=Te,ze})(N,B=w1(0));B=[b++,B,K],d.set(N,B)}return _=N,g=B[0],B}_=void 0,g=0};let M=new Map;e.webgpuOnCreateSession=N=>{if(g!==void 0){var B=g;if(g=void 0,N){let K=Ep(B);M.set(N,K),B===0&&c(_??re(K))}_=void 0}},e.webgpuOnReleaseSession=N=>{M.delete(N)};let O=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(N,B,K)=>{if(K)return N[O]=[K,NaN],K;if(K=N[O])return K[1]++,K[0];if((B=M.get(B))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return B=((Te,ze=0)=>(Te.mapState==="unmapped"||Pe(),ze=A1(ze),dt[ze>>>0]=Te,ze))(N,B),N[O]=[B,1],B},e.webgpuUnregisterBuffer=N=>{let B=N[O];if(!B)throw Error("Buffer is not registered");B[1]--,B[1]===0&&(g1(B[0]),delete N[O])},e.webgpuGetBuffer=N=>re(N),e.webgpuCreateDownloader=(N,B,K)=>{if((K=M.get(K))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Te=re(K),ze=16*Math.ceil(Number(B)/16);return async()=>{let Be=Te.createBuffer({size:ze,usage:9});try{let se=Te.createCommandEncoder();return se.copyBufferToBuffer(N,0,Be,0,ze),Te.queue.submit([se.finish()]),await Be.mapAsync(GPUMapMode.READ),Be.getMappedRange().slice(0,B)}finally{Be.destroy()}}},e.ad=(N,B)=>{var K=B.buffer;let Te=B.byteOffset,ze=B.byteLength;if(B=16*Math.ceil(Number(ze)/16),N=re(N),!_){var Be=Ep(g);_=re(Be)}let se=(Be=_.createBuffer({mappedAtCreation:!0,size:B,usage:6})).getMappedRange();new Uint8Array(se).set(new Uint8Array(K,Te,ze)),Be.unmap(),(K=_.createCommandEncoder()).copyBufferToBuffer(Be,0,N,0,B),_.queue.submit([K.finish()]),Be.destroy()}},e.webnnInit=c=>{let d=c[0];[e.me,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.le,e.webnnEnableTraceEvent]=c.slice(1),e.webnnReleaseTensorId=e.jd,e.webnnUploadTensor=e.Sd,e.webnnRegisterMLContext=e.le,e.webnnOnRunStart=_=>d.onRunStart(_),e.webnnOnRunEnd=d.onRunEnd.bind(d),e.webnnOnReleaseSession=_=>{d.onReleaseSession(_)},e.webnnCreateMLTensorDownloader=(_,g)=>d.createMLTensorDownloader(_,g),e.webnnRegisterMLTensor=(_,g,b,M)=>d.registerMLTensor(_,g,b,M),e.webnnCreateMLContext=_=>d.createMLContext(_),e.webnnRegisterMLConstant=(_,g,b,M,O,N)=>d.registerMLConstant(_,g,b,M,O,e.Uc,N),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},te?e:new Promise((c,d)=>{w=c,x=d})}var yE,Tk,gP=ye(()=>{"use strict";yE=Mk,Tk=globalThis.self?.name?.startsWith("em-pthread"),Tk&&Mk()}),Jp,md,Sk,zt,bE,Pl,Ok,Ik,Zp,Ck,ed,vE,td,kE,kd=ye(()=>{"use strict";vd(),Jp=typeof location>"u"?void 0:location.origin,md=import.meta.url>"file:"&&import.meta.url<"file;",Sk=()=>{if(md){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Jp).href}return import.meta.url},zt=Sk(),bE=()=>{if(zt&&!zt.startsWith("blob:"))return zt.substring(0,zt.lastIndexOf("/")+1)},Pl=(t,e)=>{try{let r=e??zt;return(r?new URL(t,r):new URL(t)).origin===Jp}catch{return!1}},Ok=(t,e)=>{let r=e??zt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},Ik=(t,e)=>`${e??"./"}${t}`,Zp=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},Ck=async t=>(await import(t)).default,ed=(_P(),Dl(gE)).default,vE=async()=>{if(!zt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Pl(zt))return[void 0,ed()];let t=await Zp(zt);return[t,ed(t)]},td=(gP(),Dl(xE)).default,kE=async(t,e,r,s)=>{let n=td&&!(t||e);if(n)if(zt)n=Pl(zt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,td];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??Ok(o,e),i=r&&a&&!Pl(a,e),l=i?await Zp(a):a??Ik(o,e);return[i?l:void 0,await Ck(l)]}}}),rd,zl,eo,sd,Pk,zk,Lk,Ed,Ue,Ms=ye(()=>{"use strict";kd(),zl=!1,eo=!1,sd=!1,Pk=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},zk=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Lk=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Ed=async t=>{if(zl)return Promise.resolve();if(eo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(sd)throw new Error("previous call to 'initializeWebAssembly()' failed.");eo=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!Lk())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!zk())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=Pk();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,u=l?.href??l,p=t.wasmBinary,[f,m]=await kE(i,o,r>1,!!p||!!u),h=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{h=!0,x()},e)})),w.push(new Promise((x,k)=>{let E={numThreads:r};if(p)E.wasmBinary=p,E.locateFile=A=>A;else if(u||o)E.locateFile=A=>u??o+A;else if(i&&i.indexOf("blob:")!==0)E.locateFile=A=>new URL(A,i).href;else if(f){let A=bE();A&&(E.locateFile=S=>A+S)}m(E).then(A=>{eo=!1,zl=!0,rd=A,x(),f&&URL.revokeObjectURL(f)},A=>{eo=!1,sd=!0,k(A)})})),await Promise.race(w),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Ue=()=>{if(zl&&rd)return rd;throw new Error("WebAssembly is not initialized yet.")}}),Lt,Bl,Ie,Ad=ye(()=>{"use strict";Ms(),Lt=(t,e)=>{let r=Ue(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},Bl=(t,e,r,s)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([n,o])=>{let a=e?e+n:n;if(typeof o=="object")Bl(o,a+".",r,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Ie=t=>{let e=Ue(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetLastError(n,n+s);let o=Number(e.getValue(n,s===4?"i32":"i64")),a=e.getValue(n+s,"*"),i=a?e.UTF8ToString(a):"";throw new Error(`${t} ERROR_CODE: ${o}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}}),EE,wP=ye(()=>{"use strict";Ms(),Ad(),EE=t=>{let e=Ue(),r=0,s=[],n=t||{};try{if(t?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(n.terminate=!1);let o=0;return t?.tag!==void 0&&(o=Lt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&Ie("Can't create run options."),t?.extra!==void 0&&Bl(t.extra,"",new WeakSet,(a,i)=>{let l=Lt(a,s),u=Lt(i,s);e._OrtAddRunConfigEntry(r,l,u)!==0&&Ie(`Can't set a run config entry: ${a} - ${i}.`)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),s.forEach(a=>e._free(a)),o}}}),Nk,$k,Rk,Ll,Nr,Dk,AE,xP=ye(()=>{"use strict";Ms(),Ad(),Nk=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},$k=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},Rk=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},Ll=(t,e,r,s)=>{let n=Lt(e,s),o=Lt(r,s);Ue()._OrtAddSessionConfigEntry(t,n,o)!==0&&Ie(`Can't set a session config entry: ${e} - ${r}.`)},Nr=(t,e,r,s)=>{let n=Lt(e,s),o=Lt(r,s);t.push([n,o])},Dk=async(t,e,r)=>{let s=e.executionProviders;for(let n of s){let o=typeof n=="string"?n:n.name,a=[];switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let f=n?.deviceType;f&&Ll(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let h=n;if(h.device)if(typeof GPUDevice<"u"&&h.device instanceof GPUDevice)f=h.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&Nr(a,"enableGraphCapture","1",r),typeof h.preferredLayout=="string"&&Nr(a,"preferredLayout",h.preferredLayout,r),h.forceCpuNodeNames){let x=Array.isArray(h.forceCpuNodeNames)?h.forceCpuNodeNames:[h.forceCpuNodeNames];Nr(a,"forceCpuNodeNames",x.join(`
13
+ `),r)}h.validationMode&&Nr(a,"validationMode",h.validationMode,r)}let m=Ue().webgpuRegisterDevice(f);if(m){let[h,w,x]=m;Nr(a,"deviceId",h.toString(),r),Nr(a,"webgpuInstance",w.toString(),r),Nr(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=Lt(o,r),l=a.length,u=0,p=0;if(l>0){u=Ue()._malloc(l*Ue().PTR_SIZE),r.push(u),p=Ue()._malloc(l*Ue().PTR_SIZE),r.push(p);for(let f=0;f<l;f++)Ue().setValue(u+f*Ue().PTR_SIZE,a[f][0],"*"),Ue().setValue(p+f*Ue().PTR_SIZE,a[f][1],"*")}await Ue()._OrtAppendExecutionProvider(t,i,u,p,l)!==0&&Ie(`Can't append execution provider: ${o}.`)}},AE=async t=>{let e=Ue(),r=0,s=[],n=t||{};Rk(n);try{let o=Nk(n.graphOptimizationLevel??"all"),a=$k(n.executionMode??"sequential"),i=typeof n.logId=="string"?Lt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let u=n.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let p=typeof n.optimizedModelFilePath=="string"?Lt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,u,p),r===0&&Ie("Can't create session options."),n.executionProviders&&await Dk(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Ll(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[f,m]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof m!="number"||!Number.isInteger(m)||m<0)throw new Error(`free dimension override value must be a non-negative integer: ${m}`);let h=Lt(f,s);e._OrtAddFreeDimensionOverride(r,h,m)!==0&&Ie(`Can't set a free dimension override: ${f} - ${m}.`)}return n.extra!==void 0&&Bl(n.extra,"",new WeakSet,(f,m)=>{Ll(r,f,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Ie("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),bs,Rl,en,oo,Fl,Md,Td,hd,tn=ye(()=>{"use strict";bs=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},Rl=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},en=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],s=typeof e=="number"?e:e.reduce((n,o)=>n*o,1);return r>0?Math.ceil(s*r):void 0},oo=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Fl=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},Md=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Td=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",hd=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${t}`)}}}),Sd,ME=ye(()=>{"use strict";vd(),Sd=async t=>{if(typeof t=="string"){let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let u=l.byteLength;new Uint8Array(o,a,u).set(l),a+=u}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),TE,yP=ye(()=>{"use strict";tn(),TE=(t,e)=>new(oo(e))(t)}),Uk,Bk,Fk,jk,SE,Gk,wt,OE=ye(()=>{"use strict";tn(),Uk=["V","I","W","E","F"],Bk=(t,e)=>{console.log(`[${Uk[t]},${new Date().toISOString()}]${e}`)},SE=(t,e)=>{Fk=t,jk=e},Gk=(t,e)=>{let r=Fl(t),s=Fl(Fk);r>=s&&Bk(r,typeof e=="function"?e():e)},wt=(...t)=>{jk&&Gk(...t)}}),nd,_d,od,qk,ad,Wk,id,ld,cd,Vk,IE,bP=ye(()=>{"use strict";tn(),OE(),nd=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),_d=(t,e)=>{if(e==="int32")return t;let r=nd.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);let s=r/8;if(t.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=t.byteLength/s,o=new(oo(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i<n;i++){let l=o[i];if(l>2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(l)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&o.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(o,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},od=(t,e)=>{if(e==="int32")return t;if(t.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=t.byteLength/4,s=new Int32Array(t.buffer,t.byteOffset,r);switch(e){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(o=>o<-128||o>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${e}`)}},qk=1,ad=()=>qk++,Wk=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),id=(t,e)=>{let r=nd.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);return e.length>0?Math.ceil(e.reduce((s,n)=>s*n)*r/8):0},ld=class{constructor(t){this.isDataConverted=!1;let{sessionId:e,context:r,tensor:s,dataType:n,shape:o,fallbackDataType:a}=t;this.sessionId=e,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.fallbackDataType=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return id(this.dataType,this.tensorShape)}destroy(){wt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){if(this.fallbackDataType){let e=await this.mlContext.readTensor(this.mlTensor),r=od(new Uint8Array(e),this.dataType);if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(r);return}else return r.buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,e,r){return this.mlContext===t&&this.dataType===e&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(t){this.isDataConverted=t}},cd=class{constructor(t,e){this.tensorManager=t,this.wrapper=e}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,e,r,s){let n=this.tensorManager.getMLContext(t),o=this.tensorManager.getMLOpSupportLimits(t),a;if(!o?.input.dataTypes.includes(e)){if(a=Wk.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);wt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${e} to ${a}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,e,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==id(e,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,e,r,i,!0,!0,a),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){let e=t;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")e=_d(t,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else wt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(t){if(this.activeUpload){let e=this.wrapper?.isDataConverted?od(this.activeUpload,this.wrapper?.type):this.activeUpload;if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(e):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(e);return}else return e.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(t):this.wrapper.read()}},Vk=class{constructor(t){this.backend=t,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(t){let e=this.backend.getMLContext(t);if(!e)throw new Error("MLContext not found for session.");return e}getMLOpSupportLimits(t){return this.backend.getMLOpSupportLimits(t)}reserveTensorId(){let t=ad();return this.tensorTrackersById.set(t,new cd(this)),t}releaseTensorId(t){let e=this.tensorTrackersById.get(t);e&&(this.tensorTrackersById.delete(t),e.tensorWrapper&&this.releaseTensor(e.tensorWrapper))}async ensureTensor(t,e,r,s,n){wt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,s,n)}upload(t,e){let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");r.upload(e)}async download(t,e){wt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${e?.byteLength}}`);let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");return r.download(e)}releaseTensorsForSession(t){for(let e of this.freeTensors)e.sessionId===t&&e.destroy();this.freeTensors=this.freeTensors.filter(e=>e.sessionId!==t)}registerTensor(t,e,r,s){let n=this.getMLContext(t),o=ad(),a=new ld({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new cd(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[u,p]of this.freeTensors.entries())if(p.canReuseTensor(i,e,r)){wt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(u,1)[0];return f.sessionId=t,f}wt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:a??e,shape:r,dimensions:r,usage:s,writable:n,readable:o});return new ld({sessionId:t,context:i,tensor:l,dataType:e,shape:r,fallbackDataType:a})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},IE=(...t)=>new Vk(...t)}),CE={};ao(CE,{WebNNBackend:()=>PE});var to,Hk,PE,vP=ye(()=>{"use strict";tn(),Ms(),yP(),bP(),OE(),to=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Hk=(t,e)=>{if(t===e)return!0;if(t===void 0||e===void 0)return!1;let r=Object.keys(t).sort(),s=Object.keys(e).sort();return r.length===s.length&&r.every((n,o)=>n===s[o]&&t[n]===e[n])},PE=class{constructor(t){this.tensorManager=IE(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,SE(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){wt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){wt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)wt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(t),this.activeSessionId=void 0}}async createMLContext(t){if(t instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===t);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:s}),s}}else if(t===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let e=this.mlContextCache.findIndex(r=>Hk(r.options,t));if(e!==-1)return this.mlContextCache[e].mlContext;{let r=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:r}),r}}registerMLContext(t,e){this.mlContextBySessionId.set(t,e);let r=this.sessionIdsByMLContext.get(e);r||(r=new Set,this.sessionIdsByMLContext.set(e,r)),r.add(t),this.mlOpSupportLimitsBySessionId.has(t)||this.mlOpSupportLimitsBySessionId.set(t,e.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(t,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(t,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(t){this.sessionGraphInputs.delete(t),this.sessionGraphOutputs.delete(t);let e=this.mlContextBySessionId.get(t);if(!e)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t),this.mlOpSupportLimitsBySessionId.delete(t);let r=this.sessionIdsByMLContext.get(e);if(r.delete(t),r.size===0){this.sessionIdsByMLContext.delete(e);let s=this.mlContextCache.findIndex(n=>n.mlContext===e);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}getMLOpSupportLimits(t){return this.mlOpSupportLimitsBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){wt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=to.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t??this.currentSessionId,e,o,s,n)}async createTemporaryTensor(t,e,r){wt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=to.get(e);if(!s)throw new Error(`Unsupported ONNX data type: ${e}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(t,n,s,r,!1);let o=this.temporarySessionTensorIds.get(t);return o?o.push(n):this.temporarySessionTensorIds.set(t,[n]),n}uploadTensor(t,e){if(!Ue().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");wt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${e.byteLength}}`),this.tensorManager.upload(t,e)}async downloadTensor(t,e){return this.tensorManager.download(t,e)}createMLTensorDownloader(t,e){return async()=>{let r=await this.tensorManager.download(t);return TE(r,e)}}registerMLTensor(t,e,r,s){let n=to.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return wt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=l.slice(e,e+r).buffer,p;switch(n.dataType){case"float32":p=new Float32Array(u);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":p=new Int32Array(u);break;case"uint32":p=new Uint32Array(u);break;case"int64":if(a){let f=_d(new Uint8Array(u),"int64");p=new Int32Array(f.buffer),n.dataType="int32"}else p=new BigInt64Array(u);break;case"uint64":p=new BigUint64Array(u);break;case"int8":p=new Int8Array(u);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return wt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,p)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=to.get(bs(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),Xk,Od,Id,$r,Kk,ud,jl,Cd,Pd,pd,zd,Ld,Nd,zE=ye(()=>{"use strict";As(),wP(),xP(),tn(),Ms(),Ad(),ME(),Xk=(t,e)=>{Ue()._OrtInit(t,e)!==0&&Ie("Can't initialize onnxruntime.")},Od=async t=>{Xk(t.wasm.numThreads,Fl(t.logLevel))},Id=async(t,e)=>{Ue().asyncInit?.();let r=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=t.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let n=t.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(e==="webgpu"&&Ue().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(vP(),Dl(CE)).WebNNBackend(t);Ue().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,o,a,i,l)=>s.ensureTensor(n,o,a,i,l),(n,o)=>{s.uploadTensor(n,o)},async(n,o)=>s.downloadTensor(n,o),(n,o)=>s.registerMLContext(n,o),!!t.trace])}},$r=new Map,Kk=t=>{let e=Ue(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetInputOutputCount(t,n,n+s)!==0&&Ie("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(e.getValue(n,o)),Number(e.getValue(n+s,o))]}finally{e.stackRestore(r)}},ud=(t,e)=>{let r=Ue(),s=r.stackSave(),n=0;try{let o=r.PTR_SIZE,a=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(t,e,a,a+o)!==0&&Ie("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let u=r.HEAPU32[n/4+1],p=[];for(let f=0;f<u;f++){let m=Number(r.getValue(n+8+f*o,"*"));p.push(m!==0?r.UTF8ToString(m):Number(r.getValue(n+8+(f+u)*o,"*")))}return[i,l,p]}finally{r.stackRestore(s),n!==0&&r._OrtFree(n)}},jl=t=>{let e=Ue(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},Cd=async(t,e)=>{let r,s,n=Ue();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=jl(t);let o=0,a=0,i=0,l=[],u=[],p=[];try{if([a,l]=await AE(e),e?.externalData&&n.mountExternalData){let T=[];for(let P of e.externalData){let C=typeof P=="string"?P:P.path;T.push(Sd(typeof P=="string"?P:P.data).then(v=>{n.mountExternalData(C,v)}))}await Promise.all(T)}for(let T of e?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof T!="string"){let P=T,C=P?.context,v=P?.gpuDevice,F=P?.deviceType,H=P?.powerPreference;C?n.currentContext=C:v?n.currentContext=await n.webnnCreateMLContext(v):n.currentContext=await n.webnnCreateMLContext({deviceType:F,powerPreference:H})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Ie("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,m]=Kk(o),h=!!e?.enableGraphCapture,w=[],x=[],k=[],E=[],A=[];for(let T=0;T<f;T++){let[P,C,v]=ud(o,T);P===0&&Ie("Can't get an input name."),u.push(P);let F=n.UTF8ToString(P);w.push(F),k.push(C===0?{name:F,isTensor:!1}:{name:F,isTensor:!0,type:Rl(C),shape:v})}for(let T=0;T<m;T++){let[P,C,v]=ud(o,T+f);P===0&&Ie("Can't get an output name."),p.push(P);let F=n.UTF8ToString(P);x.push(F),E.push(C===0?{name:F,isTensor:!1}:{name:F,isTensor:!0,type:Rl(C),shape:v});{if(h&&e?.preferredOutputLocation===void 0){A.push("gpu-buffer");continue}let H=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[F]??"cpu",V=n.webnnIsGraphOutput;if(H==="cpu"&&V&&V(o,F)){A.push("ml-tensor-cpu-output");continue}if(H!=="cpu"&&H!=="cpu-pinned"&&H!=="gpu-buffer"&&H!=="ml-tensor")throw new Error(`Not supported preferred output location: ${H}.`);if(h&&H!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${H}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);A.push(H)}}let S=null;return A.some(T=>T==="gpu-buffer"||T==="ml-tensor"||T==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&Ie("Can't create IO binding."),S={handle:i,outputPreferredLocations:A,outputPreferredLocationsEncoded:A.map(T=>T==="ml-tensor-cpu-output"?"ml-tensor":T).map(T=>hd(T))}),$r.set(o,[o,u,p,S,h,!1]),[o,w,x,k,E]}catch(f){throw u.forEach(m=>n._OrtFree(m)),p.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&Ie("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Ie("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Ie("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},Pd=t=>{let e=Ue(),r=$r.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&Ie("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Ie("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(l=>e._OrtFree(l)),o.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(s)!==0&&Ie("Can't release session."),$r.delete(t)},pd=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=Ue(),l=i.PTR_SIZE,u=t[0],p=t[1],f=t[3],m=f,h,w;if(u==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let E=t[2].gpuBuffer;w=en(bs(u),p);{let A=i.webgpuRegisterBuffer;if(!A)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=A(E,s)}}else if(f==="ml-tensor"){let E=t[2].mlTensor;w=en(bs(u),p);let A=i.webnnRegisterMLTensor;if(!A)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=A(s,E,bs(u),p)}else{let E=t[2];if(Array.isArray(E)){w=l*E.length,h=i._malloc(w),r.push(h);for(let A=0;A<E.length;A++){if(typeof E[A]!="string")throw new TypeError(`tensor data at index ${A} is not a string`);i.setValue(h+A*l,Lt(E[A],r),"*")}}else{let A=i.webnnIsGraphInput,S=i.webnnIsGraphOutput;if(u!=="string"&&A&&S){let T=i.UTF8ToString(n);if(A(s,T)||S(s,T)){let P=bs(u);w=en(P,p),m="ml-tensor";let C=i.webnnCreateTemporaryTensor,v=i.webnnUploadTensor;if(!C||!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let F=await C(s,P,p);v(F,new Uint8Array(E.buffer,E.byteOffset,E.byteLength)),h=F}else w=E.byteLength,h=i._malloc(w),r.push(h),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,w),h)}else w=E.byteLength,h=i._malloc(w),r.push(h),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,w),h)}}let x=i.stackSave(),k=i.stackAlloc(4*p.length);try{p.forEach((A,S)=>i.setValue(k+S*l,A,l===4?"i32":"i64"));let E=i._OrtCreateTensor(bs(u),h,w,k,p.length,hd(m));E===0&&Ie(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(E)}finally{i.stackRestore(x)}},zd=async(t,e,r,s,n,o)=>{let a=Ue(),i=a.PTR_SIZE,l=$r.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let u=l[0],p=l[1],f=l[2],m=l[3],h=l[4],w=l[5],x=e.length,k=s.length,E=0,A=[],S=[],T=[],P=[],C=[],v=a.stackSave(),F=a.stackAlloc(x*i),H=a.stackAlloc(x*i),V=a.stackAlloc(k*i),J=a.stackAlloc(k*i);try{[E,A]=EE(o),Dr("wasm prepareInputOutputTensor");for(let z=0;z<x;z++)await pd(r[z],S,P,t,p[e[z]],e[z],h);for(let z=0;z<k;z++)await pd(n[z],T,P,t,f[s[z]],x+s[z],h);Ur("wasm prepareInputOutputTensor");for(let z=0;z<x;z++)a.setValue(F+z*i,S[z],"*"),a.setValue(H+z*i,p[e[z]],"*");for(let z=0;z<k;z++)a.setValue(V+z*i,T[z],"*"),a.setValue(J+z*i,f[s[z]],"*");if(m&&!w){let{handle:z,outputPreferredLocations:ne,outputPreferredLocationsEncoded:ae}=m;if(p.length!==x)throw new Error(`input count from feeds (${x}) is expected to be always equal to model's input count (${p.length}).`);Dr("wasm bindInputsOutputs");for(let I=0;I<x;I++){let L=e[I];await a._OrtBindInput(z,p[L],S[I])!==0&&Ie(`Can't bind input[${I}] for session=${t}.`)}for(let I=0;I<k;I++){let L=s[I];n[I]?.[3]?(C.push(T[I]),a._OrtBindOutput(z,f[L],T[I],0)!==0&&Ie(`Can't bind pre-allocated output[${I}] for session=${t}.`)):a._OrtBindOutput(z,f[L],0,ae[L])!==0&&Ie(`Can't bind output[${I}] to ${ne[I]} for session=${t}.`)}Ur("wasm bindInputsOutputs"),$r.set(t,[u,p,f,m,h,!0])}a.jsepOnRunStart?.(u),a.webnnOnRunStart?.(u);let X;m?X=await a._OrtRunWithBinding(u,m.handle,k,V,E):X=await a._OrtRun(u,H,F,x,J,k,V,E),X!==0&&Ie("failed to call OrtRun().");let Y=[],U=[];Dr("wasm ProcessOutputTensor");for(let z=0;z<k;z++){let ne=Number(a.getValue(V+z*i,"*"));if(ne===T[z]||C.includes(T[z])){Y.push(n[z]),ne!==T[z]&&a._OrtReleaseTensor(ne)!==0&&Ie("Can't release tensor.");continue}let ae=a.stackSave(),I=a.stackAlloc(4*i),L=!1,R,te=0;try{a._OrtGetTensorData(ne,I,I+i,I+2*i,I+3*i)!==0&&Ie(`Can't access output tensor data on index ${z}.`);let pe=i===4?"i32":"i64",Fe=Number(a.getValue(I,pe));te=a.getValue(I+i,"*");let Pe=a.getValue(I+i*2,"*"),At=Number(a.getValue(I+i*3,pe)),Je=[];for(let Me=0;Me<At;Me++)Je.push(Number(a.getValue(Pe+Me*i,pe)));a._OrtFree(Pe)!==0&&Ie("Can't free memory for tensor dims.");let et=Je.reduce((Me,xe)=>Me*xe,1);R=Rl(Fe);let st=m?.outputPreferredLocations[s[z]];if(R==="string"){if(st==="gpu-buffer"||st==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Me=[];for(let xe=0;xe<et;xe++){let qe=a.getValue(te+xe*i,"*"),Mt=a.getValue(te+(xe+1)*i,"*"),be=xe===et-1?void 0:Mt-qe;Me.push(a.UTF8ToString(qe,be))}Y.push([R,Je,Me,"cpu"])}else if(st==="gpu-buffer"&&et>0){let Me=a.webgpuGetBuffer;if(!Me)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xe=Me(te),qe=en(Fe,et);if(qe===void 0||!Md(R))throw new Error(`Unsupported data type: ${R}`);L=!0;{a.webgpuRegisterBuffer(xe,t,te);let Mt=a.webgpuCreateDownloader(xe,qe,t);Y.push([R,Je,{gpuBuffer:xe,download:async()=>{let be=await Mt();return new(oo(R))(be)},dispose:()=>{a._OrtReleaseTensor(ne)!==0&&Ie("Can't release tensor.")}},"gpu-buffer"])}}else if(st==="ml-tensor"&&et>0){let Me=a.webnnEnsureTensor,xe=a.webnnIsGraphInputOutputTypeSupported;if(!Me||!xe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(en(Fe,et)===void 0||!Td(R))throw new Error(`Unsupported data type: ${R}`);if(!xe(t,R,!1))throw new Error(`preferredLocation "ml-tensor" for ${R} output is not supported by current WebNN Context.`);let qe=await Me(t,te,Fe,Je,!1);L=!0,Y.push([R,Je,{mlTensor:qe,download:a.webnnCreateMLTensorDownloader(te,R),dispose:()=>{a.webnnReleaseTensorId(te),a._OrtReleaseTensor(ne)}},"ml-tensor"])}else if(st==="ml-tensor-cpu-output"&&et>0){let Me=a.webnnCreateMLTensorDownloader(te,R)(),xe=Y.length;L=!0,U.push((async()=>{let qe=[xe,await Me];return a.webnnReleaseTensorId(te),a._OrtReleaseTensor(ne),qe})()),Y.push([R,Je,[],"cpu"])}else{let Me=oo(R),xe=new Me(et);new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength).set(a.HEAPU8.subarray(te,te+xe.byteLength)),Y.push([R,Je,xe,"cpu"])}}finally{a.stackRestore(ae),R==="string"&&te&&a._free(te),L||a._OrtReleaseTensor(ne)}}m&&!h&&(a._OrtClearBoundOutputs(m.handle)!==0&&Ie("Can't clear bound outputs."),$r.set(t,[u,p,f,m,h,!1]));for(let[z,ne]of await Promise.all(U))Y[z][2]=ne;return Ur("wasm ProcessOutputTensor"),Y}finally{a.webnnOnRunEnd?.(u),a.stackRestore(v),r.forEach(X=>{X&&X[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(X[2].gpuBuffer)}),n.forEach(X=>{X&&X[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(X[2].gpuBuffer)}),S.forEach(X=>a._OrtReleaseTensor(X)),T.forEach(X=>a._OrtReleaseTensor(X)),P.forEach(X=>a._free(X)),E!==0&&a._OrtReleaseRunOptions(E),A.forEach(X=>a._free(X))}},Ld=t=>{let e=Ue(),r=$r.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Ie("Can't get an profile file name."),e._OrtFree(n)},Nd=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Rr,Bt,Zs,ro,so,Nl,dd,$l,ws,xs,Yk,LE,NE,$E,RE,DE,UE,BE,FE=ye(()=>{"use strict";As(),zE(),Ms(),kd(),Rr=()=>!!Ve.wasm.proxy&&typeof document<"u",Zs=!1,ro=!1,so=!1,$l=new Map,ws=(t,e)=>{let r=$l.get(t);r?r.push(e):$l.set(t,[e])},xs=()=>{if(Zs||!ro||so||!Bt)throw new Error("worker not ready")},Yk=t=>{switch(t.data.type){case"init-wasm":Zs=!1,t.data.err?(so=!0,dd[1](t.data.err)):(ro=!0,dd[0]()),Nl&&(URL.revokeObjectURL(Nl),Nl=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=$l.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},LE=async()=>{if(!ro){if(Zs)throw new Error("multiple calls to 'initWasm()' detected.");if(so)throw new Error("previous call to 'initWasm()' failed.");if(Zs=!0,Rr())return new Promise((t,e)=>{Bt?.terminate(),vE().then(([r,s])=>{try{Bt=s,Bt.onerror=o=>e(o),Bt.onmessage=Yk,dd=[t,e];let n={type:"init-wasm",in:Ve};!n.in.wasm.wasmPaths&&(r||md)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Bt.postMessage(n),Nl=r}catch(n){e(n)}},e)});try{await Ed(Ve.wasm),await Od(Ve),ro=!0}catch(t){throw so=!0,t}finally{Zs=!1}}},NE=async t=>{if(Rr())return xs(),new Promise((e,r)=>{ws("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Ve}};Bt.postMessage(s)});await Id(Ve,t)},$E=async t=>Rr()?(xs(),new Promise((e,r)=>{ws("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Bt.postMessage(s,[t.buffer])})):jl(t),RE=async(t,e)=>{if(Rr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return xs(),new Promise((r,s)=>{ws("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Bt.postMessage(n,o)})}else return Cd(t,e)},DE=async t=>{if(Rr())return xs(),new Promise((e,r)=>{ws("release",[e,r]);let s={type:"release",in:t};Bt.postMessage(s)});Pd(t)},UE=async(t,e,r,s,n,o)=>{if(Rr()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return xs(),new Promise((a,i)=>{ws("run",[a,i]);let l=r,u={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Bt.postMessage(u,Nd(l))})}else return zd(t,e,r,s,n,o)},BE=async t=>{if(Rr())return xs(),new Promise((e,r)=>{ws("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Bt.postMessage(s)});Ld(t)}}),fd,Qk,jE,kP=ye(()=>{"use strict";As(),FE(),tn(),vd(),ME(),fd=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},Qk=t=>{switch(t[3]){case"cpu":return new Jt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Md(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return Jt.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!Td(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return Jt.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},jE=class{async fetchModelAndCopyToWasmMemory(t){return $E(await Sd(t))}async loadModel(t,e){ks();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await RE(r,e),Es()}async dispose(){return DE(this.sessionId)}async run(t,e,r){ks();let s=[],n=[];Object.entries(t).forEach(f=>{let m=f[0],h=f[1],w=this.inputNames.indexOf(m);if(w===-1)throw new Error(`invalid input '${m}'`);s.push(h),n.push(w)});let o=[],a=[];Object.entries(e).forEach(f=>{let m=f[0],h=f[1],w=this.outputNames.indexOf(m);if(w===-1)throw new Error(`invalid output '${m}'`);o.push(h),a.push(w)});let i=s.map((f,m)=>fd(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?fd(f,()=>`output "${this.outputNames[a[m]]}"`):null),u=await UE(this.sessionId,n,i,a,l,r),p={};for(let f=0;f<u.length;f++)p[this.outputNames[a[f]]]=o[f]??Qk(u[f]);return Es(),p}startProfiling(){}endProfiling(){BE(this.sessionId)}}}),GE={};ao(GE,{OnnxruntimeWebAssemblyBackend:()=>wd,initializeFlags:()=>gd,wasmBackend:()=>qE});var gd,wd,qE,EP=ye(()=>{"use strict";As(),FE(),kP(),gd=()=>{(typeof Ve.wasm.initTimeout!="number"||Ve.wasm.initTimeout<0)&&(Ve.wasm.initTimeout=0);let t=Ve.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),Ve.wasm.simd=!1),typeof Ve.wasm.proxy!="boolean"&&(Ve.wasm.proxy=!1),typeof Ve.wasm.trace!="boolean"&&(Ve.wasm.trace=!1),typeof Ve.wasm.numThreads!="number"||!Number.isInteger(Ve.wasm.numThreads)||Ve.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Ve.wasm.numThreads=1;else{let e=typeof navigator>"u"?tP("node:os").cpus().length:navigator.hardwareConcurrency;Ve.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},wd=class{async init(t){gd(),await LE(),await NE(t)}async createInferenceSessionHandler(t,e){let r=new jE;return await r.loadModel(t,e),r}},qE=new wd});As();As();As();var AP="1.25.0-dev.20260228-6e72d31970",MP=_E;{let t=(EP(),Dl(GE)).wasmBackend;vs("webgpu",t,5),vs("webnn",t,5),vs("cpu",t,10),vs("wasm",t,10)}Object.defineProperty(Ve.versions,"web",{value:AP,enumerable:!0});async function WE(t){let e=t.split("/").pop(),r;try{if(r=await ir(),r){let n=await r.match(t);if(n)return n}}catch(n){Q.warn(`Failed to load ${e} from cache:`,n)}let s=await fe.fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){Q.warn(`Failed to cache ${e}:`,n)}return s}async function VE(t){let e=await WE(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return Q.warn("Failed to read WASM binary:",r),null}}async function HE(t){let e=await WE(t);if(!e||typeof e=="string")return null;try{let r=await e.text(),s=t.split("/").slice(0,-1).join("/");r=r.replaceAll("import.meta.url",`"${s}"`),r=r.replaceAll("globalThis.process?.versions?.node","false");let n=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(n)}catch(r){return Q.warn("Failed to read WASM binary:",r),null}}function Rd(t){return Er(t,["blob:"])}function Dd(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof import.meta<"u"&&import.meta.url)e=import.meta.url;else return t;return new URL(t,e).href}import{Tensor as tA}from"onnxruntime-common";var SP=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function QE(t){return t<=St.DEBUG?0:t<=St.INFO?2:t<=St.WARNING||t<=St.ERROR?3:4}var OP={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},Ft=[],Ud,sn,XE=Symbol.for("onnxruntime");if(XE in globalThis)sn=globalThis[XE];else if(ge.IS_NODE_ENV){switch(sn=TP,process.platform){case"win32":Ft.push("dml");break;case"linux":process.arch==="x64"&&Ft.push("cuda");break;case"darwin":Ft.push("coreml");break}Ft.push("webgpu"),Ft.push("cpu"),Ud=["cpu"]}else sn=$d,ge.IS_WEBNN_AVAILABLE&&Ft.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ge.IS_WEBGPU_AVAILABLE&&Ft.push("webgpu"),Ft.push("wasm"),Ud=["wasm"];var IP=sn.InferenceSession;function JE(t=null){if(!t)return Ud;switch(t){case"auto":return Ft;case"gpu":return Ft.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Ft.includes(t))return[SP[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Ft.join(", ")}.`)}var ZE=ge.IS_BROWSER_ENV||ge.IS_WEBWORKER_ENV,KE=Promise.resolve(),rn=null;async function CP(){return rn||(fe.useWasmCache&&typeof ht?.wasm?.wasmPaths=="object"&&ht?.wasm?.wasmPaths?.wasm&&ht?.wasm?.wasmPaths?.mjs?(rn=(async()=>{let e=ht.wasm.wasmPaths;await Promise.all([e.wasm&&!Rd(e.wasm)?(async()=>{try{let r=await VE(Dd(e.wasm));r&&(ht.wasm.wasmBinary=r)}catch(r){Q.warn("Failed to pre-load WASM binary:",r)}})():Promise.resolve(),e.mjs&&!Rd(e.mjs)?(async()=>{try{let r=await HE(Dd(e.mjs));r&&(ht.wasm.wasmPaths.mjs=r)}catch(r){Q.warn("Failed to pre-load WASM factory:",r)}})():Promise.resolve()])})(),rn):(rn=Promise.resolve(),rn))}async function Gl(t,e,r){await CP();let s=QE(fe.logLevel??St.WARNING),n=()=>IP.create(t,{logSeverityLevel:s,...e}),o=await(ZE?KE=KE.then(n):n());return o.config=r,o}var YE=Promise.resolve();async function ql(t,e){let r=()=>t.run(e);return await(ZE?YE=YE.then(r):r())}function Wl(t){return t instanceof sn.Tensor}var ht=sn?.env;if(ht?.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&ht.versions?.web&&!ht.wasm.wasmPaths){let t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${ht.versions.web}/dist/`;ht.wasm.wasmPaths=ge.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`}}ht.wasm.proxy=!1}ht?.webgpu&&(ht.webgpu.powerPreference="high-performance");function io(){return ht?.wasm?.proxy}function eA(t){let e=QE(t);ht.logLevel=OP[e]}eA(fe.logLevel??St.WARNING);fe.backends.onnx={...ht,setLogLevel:eA};var Br=async(t,e,r)=>{let s=await Gl(new Uint8Array(t),e);return(async n=>{let o=io(),a=Object.fromEntries(Object.entries(n).map(([l,u])=>[l,(o?u.clone():u).ort_tensor])),i=await ql(s,a);return Array.isArray(r)?r.map(l=>new D(i[l])):new D(i[r])})},cr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Br([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Br([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Br([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Br([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Br([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Br([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Br([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=Br([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var rA=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),Bd=ge.IS_NODE_ENV?"cpu":"wasm";function Vl(t,e,{warn:r}={}){return t?typeof t=="string"?t:t.hasOwnProperty(e)?t[e]:(r&&r(`device not specified for "${e}". Using the default device (${Bd}).`),Bd):Bd}var oA=(function(){let t;return async function(){if(t===void 0)if(!ge.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),_t=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),sA=_t.fp32,nA=Object.freeze({[rA.wasm]:_t.q8}),lo=Object.freeze({[_t.fp32]:"",[_t.fp16]:"_fp16",[_t.int8]:"_int8",[_t.uint8]:"_uint8",[_t.q8]:"_quantized",[_t.q4]:"_q4",[_t.q4f16]:"_q4f16",[_t.bnb4]:"_bnb4"});function Hl(t,e,r,{configDtype:s=null,warn:n}={}){let o,a=!1;t&&typeof t!="string"?t.hasOwnProperty(e)?o=t[e]:(o=null,a=!0):o=t;let i;if(o===_t.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==_t.auto&&_t.hasOwnProperty(l))return l}i=nA[r]??sA}else o&&_t.hasOwnProperty(o)?i=o:i=nA[r]??sA;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var nn=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var Xl=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(ge.IS_CRYPTO_AVAILABLE){let i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;let r=this._mt,s=(i,l)=>Math.imul(i,l)>>>0,n=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))n.push(i&4294967295);n.length||n.push(0),r[0]=19650218;for(let i=1;i<624;++i)r[i]=s(1812433253,r[i-1]^r[i-1]>>>30)+i>>>0;let o=1,a=0;for(let i=Math.max(624,n.length);i>0;--i,++o,++a)o>=624&&(r[0]=r[623],o=1),a>=n.length&&(a=0),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1664525))+n[a]+a>>>0;for(let i=623;i>0;--i,++o)o>=624&&(r[0]=r[623],o=1),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1566083941))-o>>>0;r[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let s=0;s<624;++s){let n=e[s]&2147483648|e[(s+1)%624]&2147483647;e[s]=(e[(s+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let r=e[this._idx++];return r^=r>>>11,r^=r<<7&2636928640,r^=r<<15&4022730752,r^=r>>>18,r>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,r=1){let s=this._gauss_next;if(this._gauss_next=null,s===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+s*r}shuffle(e){for(let r=e.length-1;r>0;--r){let s=32-Math.clz32(r+1),n=this._int32()>>>32-s;for(;n>r;)n=this._int32()>>>32-s;let o=e[r];e[r]=e[n],e[n]=o}}choices(e,r){return e[aA(this._random_fn,r)]}};function aA(t,e){let r=0;for(let n=0;n<e.length;++n)r+=e[n];let s=t()*r;for(let n=0;n<e.length;++n)if(s-=e[n],s<0)return n;return e.length-1}var ur=new Xl,Ts=Object.freeze({Random:Xl,seed:ur.seed.bind(ur),random:ur.random.bind(ur),gauss:ur.gauss.bind(ur),shuffle:ur.shuffle.bind(ur),choices:ur.choices.bind(ur)}),iA=t=>aA(Ts.random,t);var D=class t{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return Wl(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new tA(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n<e;++n)yield this._subarray(n,s,r)}else yield*this.data}_getitem(e){let[r,...s]=this.dims;if(e=pr(e,r),s.length>0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}indexOf(e){let r=this.data;for(let s=0;s<r.length;++s)if(r[s]==e)return s;return-1}_subarray(e,r,s){let n=e*r,o=(e+1)*r,a="subarray"in this.data?this.data.subarray(n,o):this.data.slice(n,o);return new t(this.type,a,s)}item(){let e=this.data;if(e.length!==1)throw new Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return PP(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=1/(1+Math.exp(-e[r]));return this}map(e){return this.clone().map_(e)}map_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]=e(r[s],s,r);return this}mul(e){return this.clone().mul_(e)}mul_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]*=e;return this}div(e){return this.clone().div_(e)}div_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]/=e;return this}add(e){return this.clone().add_(e)}add_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]-=e;return this}clone(){return new t(this.type,this.data.slice(),this.dims.slice())}slice(...e){let r=[],s=[];for(let p=0;p<this.dims.length;++p){let f=e[p];if(f==null)s.push([0,this.dims[p]]),r.push(this.dims[p]);else if(typeof f=="number")f=pr(f,this.dims[p],p),s.push([f,f+1]);else if(Array.isArray(f)&&f.length===2){let[m,h]=f;if(m=m===null?0:pr(m,this.dims[p],p,!1),h=h===null?this.dims[p]:pr(h,this.dims[p],p,!1),m>h)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(m,0),Math.min(h,this.dims[p])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([p,f])=>f-p),o=n.reduce((p,f)=>p*f),a=this.data,i=new a.constructor(o),l=this.stride(),u=!0;for(let p=1;p<n.length;++p)if(s[p][0]!==0||s[p][1]!==this.dims[p]){u=!1;break}if(u){let p=s[0][0]*l[0],f=s[0][1]*l[0];if(ArrayBuffer.isView(a))i.set(a.subarray(p,f));else if(Array.isArray(a)){let m=a.slice(p,f);for(let h=0;h<m.length;++h)i[h]=m[h]}else throw new Error("Unsupported data type for slicing")}else for(let p=0;p<o;++p){let f=0;for(let m=n.length-1,h=p;m>=0;--m){let w=n[m];f+=(h%w+s[m][0])*l[m],h=Math.floor(h/w)}i[p]=a[f]}return new t(this.type,i,r)}permute(...e){return zP(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=(u,p)=>u+p**e;if(r===null){let u=n.reduce(o,0)**(1/e);return new t(this.type,[u],[])}let[a,i,l]=co(o,this,r,s);if(e!==1)for(let u=0;u<i.length;++u)i[u]=i[u]**(1/e);return new t(a,i,l)}normalize_(e=2,r=1){r=pr(r,this.dims.length);let s=this.norm(e,r,!0),n=this.data,o=s.data;for(let a=0;a<n.length;++a){let i=0;for(let l=this.dims.length-1,u=a,p=1;l>=0;--l){let f=this.dims[l];if(l!==r){let m=u%f;i+=m*p,p*=this.dims[l]}u=Math.floor(u/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return Fd(this.dims)}squeeze(e=null){return new t(this.type,this.data,lA(this.dims,e))}squeeze_(e=null){return this.dims=lA(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,cA(this.dims,e))}unsqueeze_(e){return this.dims=cA(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...s,n.reduce((a,i)=>a*i,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;n<e.length;++n)if(e[n]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=n}let s=this.data;if(r!==-1){let n=e.reduce((o,a,i)=>i!==r?o*a:o,1);e[r]=s.length/n}return new t(this.type,s,e)}neg_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=-e[r];return this}neg(){return this.clone().neg_()}gt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]>e?1:0;return new t("bool",r,this.dims)}lt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]<e?1:0;return new t("bool",r,this.dims)}clamp_(e,r){let s=this.data;for(let n=0;n<s.length;++n)s[n]=Math.min(Math.max(s[n],e),r);return this}clamp(e,r){return this.clone().clamp_(e,r)}round_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=Math.round(e[r]);return this}round(){return this.clone().round_()}mean(e=null,r=!1){return Ql(this,e,r)}min(e=null,r=!1){if(e===null){let a=Jn(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=co((a,i)=>Math.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=Se(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=co((a,i)=>Math.max(a,i),this,e,r,-1/0);return new t(s,n,o)}argmin(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Jn(this.data)[1];return new t("int64",[BigInt(s)],[])}argmax(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Se(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${e.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(e.every(p=>p===1)){if(e.length===this.dims.length)return this.clone();let p=e.length-this.dims.length,f=Array(p).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((p,f)=>p*e[f]),o=n.reduce((p,f)=>p*f,1),a=this.data,i=new a.constructor(o),l=Fd(s),u=Fd(n);for(let p=0;p<o;++p){let f=p,m=0;for(let h=0;h<n.length;++h){let w=Math.floor(f/u[h]);f=f%u[h];let x=w%s[h];m+=x*l[h]}i[p]=a[m]}return new t(this.type,i,n)}tile(...e){if(e.length<this.dims.length){let r=this.dims.length-e.length;e=Array(r).fill(1).concat(e)}return this.repeat(...e)}to(e){if(this.type===e)return this;if(!nn.hasOwnProperty(e))throw new Error(`Unsupported type: ${e}`);let r,s=["int64","uint64"].includes(this.type),n=["int64","uint64"].includes(e);if(s&&!n)r=Number;else if(!s&&n)["float16","float32","float64"].includes(this.type)?r=o=>BigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,Ek(this.data),this.dims);return new t(e,nn[e].from(this.data,r),this.dims)}};function PP(t,e){let r=t.length,s=e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.length<e[o]?l.push(i):a.push([i]),a},[[]]);return n[0]}function zP(t,e){let[r,s]=wk(t.data,t.dims,e);return new D(t.type,r,s)}function jd(t,[e,r],s="bilinear",n=!1){let o=t.dims.at(-3)??1,a=t.dims.at(-2),i=t.dims.at(-1),l=gk(t.data,[o,a,i],[e,r],s,n);return new D(t.type,l,[o,e,r])}async function jt(t,{size:e=null,mode:r="bilinear"}={}){if(t.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!e)throw new Error("`interpolate_4d` requires a `size` argument.");let s;if(e.length===2)s=[...t.dims.slice(0,2),...e];else if(e.length===3)s=[t.dims[0],...e];else if(e.length===4)s=e;else throw new Error("`size` must be of length 2, 3, or 4.");let n;if(r==="nearest")n=await cr.nearest_interpolate_4d;else if(r==="bilinear")n=await cr.bilinear_interpolate_4d;else if(r==="bicubic")n=await cr.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);let o=new D("int64",new BigInt64Array(s.map(BigInt)),[s.length]);return await n({x:t,s:o})}async function uA(t,e){return await(await cr.matmul)({a:t,b:e})}async function e$(t,e){return await(await cr.rfft)({x:t,a:e})}async function Zt(t,e){let r=await cr.top_k;return e==null?e=t.dims.at(-1):e=Math.min(e,t.dims.at(-1)),await r({x:t,k:new D("int64",[BigInt(e)],[1])})}var Kl=t=>new D("int64",t,[t.length]);async function Yl(t,e,r,s,n){return await(await cr.slice)({x:t,s:Kl(e),e:Kl(r),a:Kl(s),t:Kl(n??new Array(s.length).fill(1))})}function pA(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,u=0;for(let p=0;p<a;++p){let f=p*l*i;for(let m=0;m<l;++m){let h=0,w=0,x=p*i,k=f+m;for(let A=0;A<i;++A){let S=Number(s[x+A]);w+=S,h+=r[k+A*l]*S}let E=h/w;o[u++]=E}}return new D(t.type,o,n)}function t$(t,e,{eps:r=1e-5}={}){if(t.dims.length!==2)throw new Error("`layer_norm` currently only supports 2D input.");let[s,n]=t.dims;if(e.length!==1&&e[0]!==n)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");let[o,a]=Gd(t,1,0,!0),i=o.data,l=a.data,u=t.data,p=new u.constructor(u.length);for(let f=0;f<s;++f){let m=f*n;for(let h=0;h<n;++h){let w=m+h;p[w]=(u[w]-l[f])/(i[f]+r)}}return new D(t.type,p,t.dims)}function lA(t,e){return t=t.slice(),e===null?t=t.filter(r=>r!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function cA(t,e){return e=pr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function pr(t,e,r=null,s=!0){if(t<-e||t>=e){if(s)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function Ee(t,e=0){e=pr(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i<t.length;++i){let{data:l,dims:u}=t[i];for(let p=0;p<l.length;++p){let f=0;for(let m=u.length-1,h=p,w=1;m>=0;--m){let x=u[m],k=h%x;m===e&&(k+=a),f+=k*w,w*=r[m],h=Math.floor(h/x)}n[f]=l[p]}a+=u[e]}}return new D(o,n,r)}function Gt(t,e=0){return Ee(t.map(r=>r.unsqueeze(e)),e)}function co(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=pr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let u=0;u<o.length;++u){let p=0;for(let f=a.length-1,m=u,h=1;f>=0;--f){let w=a[f];if(f!==r){let x=m%w;p+=x*h,h*=i[f]}m=Math.floor(m/w)}l[p]=t(l[p],o[u],u,p)}return s||i.splice(r,1),[e.type,l,i]}function Gd(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let h=n.reduce((E,A)=>E+A,0)/n.length,w=Math.sqrt(n.reduce((E,A)=>E+(A-h)**2,0)/(n.length-r)),x=new D(t.type,[h],[]);return[new D(t.type,[w],[]),x]}e=pr(e,o.length);let a=Ql(t,e,s),i=a.data,[l,u,p]=co((m,h,w,x)=>m+(h-i[x])**2,t,e,s);for(let m=0;m<u.length;++m)u[m]=Math.sqrt(u[m]/(o[e]-r));return[new D(l,u,p),a]}function Ql(t,e=null,r=!1){let s=t.dims,n=t.data;if(e===null){let l=n.reduce((u,p)=>u+p,0);return new D(t.type,[l/n.length],[])}e=pr(e,s.length);let[o,a,i]=co((l,u)=>l+u,t,e,r);if(s[e]!==1)for(let l=0;l<a.length;++l)a[l]/=s[e];return new D(o,a,i)}function Fd(t){let e=new Array(t.length);for(let r=t.length-1,s=1;r>=0;--r)e[r]=s,s*=t[r];return e}function qd(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new D(r,new s(n).fill(e),t)}function He(t,e){let r,s;if(typeof e=="number")r="float32",s=Float32Array;else if(typeof e=="bigint")r="int64",s=BigInt64Array;else if(typeof e=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return qd(t,e,r,s)}function uo(t,e){return He(t.dims,e)}function at(t){return qd(t,1n,"int64",BigInt64Array)}function Jl(t){return at(t.dims)}function Wd(t){return qd(t,0n,"int64",BigInt64Array)}function Vd(t){return Wd(t.dims)}function r$(t){let e=t.reduce((r,s)=>r*s,1);return new D("float32",Float32Array.from({length:e},()=>Ts.random()),t)}function dA(t){let e=t.reduce((r,s)=>r*s,1);return new D("float32",Float32Array.from({length:e},()=>Ts.gauss()),t)}function fA(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i<o.length;++i){let l=o[i]>0?1:0,u=Math.floor(i/8),p=i%8;a[u]|=l<<7-p,r&&p===0&&(a[u]-=128)}return new D(s,a,[t.dims[0],t.dims[1]/8])}async function on(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await lr(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Hd(t,e){let r=await on(t);return await Promise.all(r.map(s=>ct(t,s,!0,e)))}function Xd(t){let e=t.dims;switch(e.length){case 1:return t.tolist();case 2:if(e[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return t.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${e.length}.`)}}var LP=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function NP(t,e,r,s){for(let n of Object.keys(t)){let o=e-t[n].length,a=r(n),i=new Array(o).fill(a);t[n]=s==="right"?ft(t[n],i):ft(i,t[n])}}function $P(t,e){for(let r of Object.keys(t))t[r].length=e}function Ss(t,...e){for(let r of e){if(!Object.hasOwn(t,r))continue;let s=t[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function RP(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var q=class extends Ze{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new Qv(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Ss(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ss(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ss(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ss(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ss(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ss(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:a}of this.chat_template){if(typeof o!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=a}this.chat_template=n}this._compiled_template_cache=new Map;let s=RP(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let i=await Hd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,{text_pair:r=null,add_special_tokens:s=!0,padding:n=!1,truncation:o=null,max_length:a=null,return_tensor:i=!0,return_token_type_ids:l=null}={}){let u=Array.isArray(e),p;if(u){if(e.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(e.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");p=e.map((m,h)=>this._encode_plus(m,{text_pair:r[h],add_special_tokens:s,return_token_type_ids:l}))}else p=e.map(m=>this._encode_plus(m,{add_special_tokens:s,return_token_type_ids:l}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");p=[this._encode_plus(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:l})]}if(a===null?a=this.model_max_length:o===null&&(n===!0?(Q.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),a=this.model_max_length):n===!1&&(Q.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."),o=!0)),n===!0&&(a=Math.min(Se(p.map(m=>m.input_ids.length))[0],a??1/0)),a=Math.min(a,this.model_max_length??1/0),n||o)for(let m=0;m<p.length;++m)p[m].input_ids.length!==a&&(p[m].input_ids.length>a?o&&$P(p[m],a):n&&NP(p[m],a,h=>h==="input_ids"?this.pad_token_id:0,this.padding_side));let f={};if(i){if(!(n&&o)&&p.some(h=>{for(let w of Object.keys(h))if(h[w].length!==p[0][w]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let m=[p.length,p[0].input_ids.length];for(let h of Object.keys(p[0]))f[h]=new D("int64",BigInt64Array.from(p.flatMap(w=>w[h]).map(BigInt)),m)}else{for(let m of Object.keys(p[0]))f[m]=p.map(h=>h[m]);if(!u)for(let m of Object.keys(f))f[m]=f[m][0]}return f}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof D&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof D&&(e=Xd(e)),!Array.isArray(e)||e.length===0||!zv(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,{tools:r=null,documents:s=null,chat_template:n=null,add_generation_prompt:o=!1,tokenize:a=!0,padding:i=!1,truncation:l=!1,max_length:u=null,return_tensor:p=!0,return_dict:f=!0,tokenizer_kwargs:m={},...h}={}){if(n=this.get_chat_template({chat_template:n,tools:r}),typeof n!="string")throw Error(`chat_template must be a string, but got ${typeof n}`);let w=this._compiled_template_cache.get(n);w===void 0&&(w=new ck(n),this._compiled_template_cache.set(n,w));let x=Object.create(null);for(let E of LP){let A=Ss(this.config,E);A&&(x[E]=A)}let k=w.render({messages:e,add_generation_prompt:o,tools:r,documents:s,...x,...h});if(a){let E=this._call(k,{add_special_tokens:!1,padding:i,truncation:l,max_length:u,return_tensor:p,...m});return f?E:E.input_ids}return k}};function an(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var Bf={};Vs(Bf,{AlbertTokenizer:()=>Kd,AutoTokenizer:()=>Z,BartTokenizer:()=>Yd,BertTokenizer:()=>Qd,BlenderbotSmallTokenizer:()=>Jd,BlenderbotTokenizer:()=>Zd,BloomTokenizer:()=>ef,CLIPTokenizer:()=>rf,CamembertTokenizer:()=>tf,CodeGenTokenizer:()=>nf,CodeLlamaTokenizer:()=>sf,CohereTokenizer:()=>of,ConvBertTokenizer:()=>af,DebertaTokenizer:()=>cf,DebertaV2Tokenizer:()=>lf,DistilBertTokenizer:()=>uf,ElectraTokenizer:()=>pf,EsmTokenizer:()=>df,FalconTokenizer:()=>ff,GPT2Tokenizer:()=>_f,GPTNeoXTokenizer:()=>hf,GemmaTokenizer:()=>mf,HerbertTokenizer:()=>gf,LlamaTokenizer:()=>wf,M2M100Tokenizer:()=>xf,MBart50Tokenizer:()=>bf,MBartTokenizer:()=>po,MPNetTokenizer:()=>Ef,MarianTokenizer:()=>yf,MgpstrTokenizer:()=>vf,MobileBertTokenizer:()=>kf,NllbTokenizer:()=>Af,NougatTokenizer:()=>Mf,PreTrainedTokenizer:()=>q,Qwen2Tokenizer:()=>Tf,RoFormerTokenizer:()=>Of,RobertaTokenizer:()=>Sf,SiglipTokenizer:()=>If,SpeechT5Tokenizer:()=>Cf,SqueezeBertTokenizer:()=>Pf,T5Tokenizer:()=>zf,TokenizersBackend:()=>q,VitsTokenizer:()=>Nf,Wav2Vec2CTCTokenizer:()=>$f,WhisperTokenizer:()=>Rf,XLMRobertaTokenizer:()=>Df,XLMTokenizer:()=>Uf});var Kd=class extends q{return_token_type_ids=!0};var Yd=class extends q{};var Qd=class extends q{return_token_type_ids=!0};var Jd=class extends q{};var Zd=class extends q{};var ef=class extends q{};var tf=class extends q{};var rf=class extends q{};var sf=class extends q{};var nf=class extends q{};var of=class extends q{};var af=class extends q{return_token_type_ids=!0};var lf=class extends q{return_token_type_ids=!0};var cf=class extends q{return_token_type_ids=!0};var uf=class extends q{};var pf=class extends q{return_token_type_ids=!0};var df=class extends q{};var ff=class extends q{};var mf=class extends q{};var hf=class extends q{};var _f=class extends q{};var gf=class extends q{return_token_type_ids=!0};var wf=class extends q{padding_side="left"};var xf=class extends q{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return an(this,e,r,s)}};var yf=class extends q{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),Q.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[r,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(r);if(s.length===2){let[n,o]=s;return this.supported_language_codes.includes(n)||Q.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),ft([n],super._encode_text(o))}}};var po=class extends q{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return an(this,e,r,s)}};var bf=class extends po{};var vf=class extends q{};var kf=class extends q{return_token_type_ids=!0};var Ef=class extends q{};var Af=class extends q{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return an(this,e,r,s)}};var Mf=class extends q{};var Tf=class extends q{};var Sf=class extends q{};var Of=class extends q{return_token_type_ids=!0};var If=class extends q{};var Cf=class extends q{};var Pf=class extends q{return_token_type_ids=!0};var zf=class extends q{};var Lf=class extends Dt{decode_chain(e){let r="";for(let s=1;s<e.length;s+=2)r+=e[s];return[r]}},Nf=class extends q{constructor(e,r){super(e,r),this._tokenizer.decoder=new Lf({type:"VitsDecoder"})}};var $f=class extends q{};var mA=[["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"]],fo=new Map(mA),DP=new Map([...mA.map(([t,e])=>[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function hA(t){t=t.toLowerCase();let e=DP.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),fo.has(t))e=t;else{let n=t.length===2?fo.keys():fo.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var UP="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",_A=new RegExp(`^[${UP}]+$`,"gu"),Rf=class extends q{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let u=[],p=l(),f=0,m=this.timestamp_begin,w=m+1500,x=[],k=[],E=!1,A=null,S=new Set(this.all_special_ids);for(let C of e){let v=C.tokens,F=i?C.token_timestamps:null,H=null,V=m;if("stride"in C){let[Y,U,z]=C.stride;if(f-=U,A=Y-z,U&&(V=U/n+m),z)for(let ne=v.length-1;ne>=0;--ne){let ae=Number(v[ne]);if(ae>=m){if(H!==null&&(ae-m)*n<A)break;H=ae}}}let J=[],X=[];for(let Y=0;Y<v.length;++Y){let U=Number(v[Y]);if(S.has(U)){let z=this.decode([U]),ne=fo.get(z.slice(2,-2));if(ne!==void 0){if(a!==null&&ne!==a&&!r){x.push(J);let ae=this.findLongestCommonSequence(x)[0],I=this.decode(ae);p.text=I,u.push(p),x=[],J=[],p=l()}a=p.language=ne}}else if(U>=m&&U<=w){let z=(U-m)*n+f,ne=gs(z,2);if(H!==null&&U>=H)E=!0;else if(E||x.length>0&&U<V)E=!1;else if(p.timestamp[0]===null)p.timestamp[0]=ne;else if(ne!==p.timestamp[0]){p.timestamp[1]=ne,x.push(J),i&&k.push(X);let[ae,I]=this.findLongestCommonSequence(x,k),L=this.decode(ae);p.text=L,i&&(p.words=this.collateWordTimestamps(ae,I,a)),u.push(p),x=[],J=[],k=[],X=[],p=l()}}else if(J.push(U),i){let z=gs(F[Y]+f,2),ne;if(Y+1<F.length){ne=gs(F[Y+1]+f,2);let ae=this.decode([U]);_A.test(ae)&&(ne=gs(Math.min(z+n,ne),2))}else ne=null;X.push([z,ne])}}if("stride"in C){let[Y,U,z]=C.stride;f+=Y-z}J.length>0?(x.push(J),i&&k.push(X)):x.every(Y=>Y.length===0)&&(p=l(),x=[],J=[],k=[],X=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[C,v]=this.findLongestCommonSequence(x,k),F=this.decode(C);p.text=F,i&&(p.words=this.collateWordTimestamps(C,v,a)),u.push(p)}let T=Object.create(null),P=u.map(C=>C.text).join("");if(r||s){for(let C=0;C<u.length;++C){let v=u[C];r||delete v.timestamp,s||delete v.language}if(i){let C=[];for(let v of u)for(let F of v.words)C.push(F);T={chunks:C}}else T={chunks:u}}return[P,T]}findLongestCommonSequence(e,r=null){let s=e[0],n=s.length,o=[],a=Array.isArray(r)&&r.length>0,i=a?[]:null,l=a?r[0]:null;for(let u=1;u<e.length;++u){let p=e[u],f=0,m=[n,n,0,0],h=p.length;for(let T=1;T<n+h;++T){let P=Math.max(0,n-T),C=Math.min(n,n+h-T),v=s.slice(P,C),F=Math.max(0,T-n),H=Math.min(h,T),V=p.slice(F,H);if(v.length!==V.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let J;a?J=v.filter((U,z)=>U===V[z]&&l[P+z]<=r[u][F+z]).length:J=v.filter((U,z)=>U===V[z]).length;let X=T/1e4,Y=J/T+X;J>1&&Y>f&&(f=Y,m=[P,C,F,H])}let[w,x,k,E]=m,A=Math.floor((x+w)/2),S=Math.floor((E+k)/2);o.push(...s.slice(0,A)),s=p.slice(S),n=s.length,a&&(i.push(...l.slice(0,A)),l=r[u].slice(S))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l<n.length;++l){let u=a[l];i.push({text:n[l],timestamp:[r[u.at(0)][0],r[u.at(-1)][1]]})}return i}combineTokensIntoWords(e,r,s=`"'\u201C\xA1\xBF([{-`,n=`"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`){r=r??"english";let o,a,i;return["chinese","japanese","thai","lao","myanmar"].includes(r)?[o,a,i]=this.splitTokensOnUnicode(e):[o,a,i]=this.splitTokensOnSpaces(e),this.mergePunctuations(o,a,i,s,n)}decode(e,r){let s;return r?.decode_with_timestamps?(e instanceof D&&(e=Xd(e)),s=this.decodeWithTimestamps(e,r)):s=super.decode(e,r),s}decodeWithTimestamps(e,r){let s=r?.time_precision??.02,n=this.all_special_ids.at(-1)+1,o=[[]];for(let a of e)if(a=Number(a),a>=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],u=0;for(let p=0;p<e.length;++p){let f=e[p];i.push(f),l.push(p);let m=this.decode(i,{decode_with_timestamps:!0});(!m.includes(s)||r[u+m.indexOf(s)]===s)&&(n.push(m),o.push(i),a.push(l),i=[],l=[],u+=m.length)}return[n,o,a]}splitTokensOnSpaces(e){let[r,s,n]=this.splitTokensOnUnicode(e),o=[],a=[],i=[];for(let l=0;l<r.length;++l){let u=r[l],p=s[l],f=n[l],m=p[0]>=this._tokenizer.token_to_id("<|endoftext|>"),h=u.startsWith(" "),w=u.trim(),x=_A.test(w);if(m||h||x||o.length===0)o.push(u),a.push(p),i.push(f);else{let k=o.length-1;o[k]+=u,a[k].push(...p),i[k].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),u=a.length-2,p=a.length-1;for(;u>=0;)a[u].startsWith(" ")&&n.includes(a[u].trim())?(a[p]=a[u]+a[p],i[p]=ft(i[u],i[p]),l[p]=ft(l[u],l[p]),a[u]="",i[u]=[],l[u]=[]):p=u,--u;for(u=0,p=1;p<a.length;)!a[u].endsWith(" ")&&o.includes(a[p])?(a[u]+=a[p],i[u]=ft(i[u],i[p]),l[u]=ft(l[u],l[p]),a[p]="",i[p]=[],l[p]=[]):u=p,++p;return[a.filter(f=>f),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var Df=class extends q{};var Uf=class extends q{return_token_type_ids=!0;constructor(e,r){super(e,r),Q.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var Z=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await Hd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),u=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=Bf[u];return p||(Q.warn(`Unknown tokenizer class "${u}", attempting to construct from base class.`),p=q),new p(i,l)}};var Fr="https://github.com/huggingface/transformers.js/issues/new/choose";var mo="preprocessor_config.json",Ar=mo,gA="processor_config.json",wA="chat_template.jinja";var oe=class extends Ze{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?ct(e,gA,!0,r):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{let i=await this[a].from_pretrained(e,r);return[a.replace(/_class$/,""),i]})).then(Object.fromEntries),this.uses_chat_template_file?qp(e,wA,!0,r):null]);return new this(s,n,o)}};var vc={};Vs(vc,{ChatterboxProcessor:()=>tm,Florence2Processor:()=>Vm,Gemma3nProcessor:()=>Hm,GroundingDinoProcessor:()=>Xm,Idefics3Processor:()=>xc,JinaCLIPProcessor:()=>Ym,LlavaProcessor:()=>Qm,MgpstrProcessor:()=>Jm,MoonshineProcessor:()=>Zm,OwlViTProcessor:()=>eh,PaliGemmaProcessor:()=>th,Phi3VProcessor:()=>rh,PixtralProcessor:()=>sh,Processor:()=>oe,PyAnnoteProcessor:()=>nh,Qwen2VLProcessor:()=>bo,Qwen2_5_VLProcessor:()=>vo,Qwen3VLProcessor:()=>oh,Sam2Processor:()=>yc,Sam2VideoProcessor:()=>ah,SamProcessor:()=>ko,SmolVLMProcessor:()=>xc,SpeechT5Processor:()=>ih,UltravoxProcessor:()=>lh,VLChatProcessor:()=>Km,VoxtralProcessor:()=>ch,Wav2Vec2Processor:()=>uh,Wav2Vec2ProcessorWithLM:()=>ph,WhisperProcessor:()=>dh});var Re=class extends Ze{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await ct(e,mo,!0,r);return new this(s)}};function Xe(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var xo={};Vs(xo,{ASTFeatureExtractor:()=>Gf,ChatterboxFeatureExtractor:()=>qf,ClapFeatureExtractor:()=>Wf,DacFeatureExtractor:()=>go,EncodecFeatureExtractor:()=>_o,FeatureExtractor:()=>Re,Gemma3nAudioFeatureExtractor:()=>Vf,MoonshineFeatureExtractor:()=>Hf,ParakeetFeatureExtractor:()=>Xf,PyAnnoteFeatureExtractor:()=>wo,SeamlessM4TFeatureExtractor:()=>Kf,SnacFeatureExtractor:()=>Yf,SpeechT5FeatureExtractor:()=>Qf,Wav2Vec2FeatureExtractor:()=>Jf,WeSpeakerFeatureExtractor:()=>Zf,WhisperFeatureExtractor:()=>em});import BP from"fs";import{Readable as FP}from"stream";import{pipeline as jP}from"stream/promises";async function Zl(t,e){if(ge.IS_BROWSER_ENV){if(ge.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(ge.IS_FS_AVAILABLE){let r=e.stream(),s=FP.fromWeb(r),n=BP.createWriteStream(t);await jP(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function jf(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await zr(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&Q.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let u=0;u<n.length;++u)o[u]=a*(i[u]+l[u])/2}else o=n.getChannelData(0);return o}function bA(t,e){if(t<1)return new Float64Array;if(t===1)return new Float64Array([1]);let r=1-e,s=2*Math.PI/(t-1),n=new Float64Array(t);for(let o=0;o<t;++o)n[o]=e-r*Math.cos(o*s);return n}function xA(t){return bA(t,.5)}function GP(t){return bA(t,.54)}var qP={htk:t=>2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function Ff(t,e="htk"){let r=qP[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}var WP={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,r=15,s=Math.log(6.4)/27)=>t>=r?e*Math.exp(s*(t-r)):200*t/3};function VP(t,e="htk"){let r=WP[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}function HP(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;a<t.length;++a){let i=s[a];for(let l=0;l<e.length;++l)i[l]=e[l]-t[a]}let n=e.length-2,o=Array.from({length:n},()=>new Array(t.length));for(let a=0;a<t.length;++a){let i=s[a];for(let l=0;l<n;++l){let u=-i[l]/r[l],p=i[l+2]/r[l+1];o[l][a]=Math.max(0,Math.min(u,p))}}return o}function yA(t,e,r){let s=(e-t)/(r-1);return Float64Array.from({length:r},(n,o)=>t+s*o)}function kt(t,e,r,s,n,o=null,a="htk",i=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);let l=Ff(r,a),u=Ff(s,a),p=yA(l,u,e+2),f=VP(p,a),m;if(i){let w=n/((t-1)*2);m=Ff(Float64Array.from({length:t},(x,k)=>k*w),a),f=p}else m=yA(0,Math.floor(n/2),t);let h=HP(m,f);if(o!==null&&o==="slaney")for(let w=0;w<e;++w){let x=h[w],k=2/(f[w+2]-f[w]);for(let E=0;E<t;++E)x[E]*=k}return h}function XP(t,e,r){let s=new t.constructor(t.length+e+r),n=t.length-1;for(let o=0;o<t.length;++o)s[e+o]=t[o];for(let o=1;o<=e;++o)s[e-o]=t[Ks(o,n)];for(let o=1;o<=r;++o)s[n+e+o]=t[Ks(n-o,n)];return s}function vA(t,e,r,s,n){if(r<=0)throw new Error("reference must be greater than zero");if(s<=0)throw new Error("min_value must be greater than zero");r=Math.max(s,r);let o=Math.log10(r);for(let a=0;a<t.length;++a)t[a]=e*Math.log10(Math.max(s,t[a])-o);if(n!==null){if(n<=0)throw new Error("db_range must be greater than zero");let a=Se(t)[0]-n;for(let i=0;i<t.length;++i)t[i]=Math.max(t[i],a)}return t}function KP(t,e=1,r=1e-5,s=null){return vA(t,20,e,r,s)}function YP(t,e=1,r=1e-10,s=null){return vA(t,10,e,r,s)}async function Ot(t,e,r,s,{fft_length:n=null,power:o=1,center:a=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:u=null,preemphasis_htk_flavor:p=!0,mel_filters:f=null,mel_floor:m=1e-10,log_mel:h=null,reference:w=1,min_value:x=1e-10,db_range:k=null,remove_dc_offset:E=null,min_num_frames:A=null,max_num_frames:S=null,do_pad:T=!0,transpose:P=!1,mel_offset:C=0}={}){let v=e.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(v!==r)throw new Error(`Length of the window (${v}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!p)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a)switch(i){case"reflect":{let L=Math.floor((n-1)/2)+1;t=XP(t,L,L);break}case"constant":{let L=Math.floor(n/2),R=new t.constructor(t.length+2*L);R.set(t,L),t=R;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}let F=Math.floor(1+Math.floor((t.length-r)/s));A!==null&&F<A&&(F=A);let H=l?Math.floor(n/2)+1:n,V=F,J=F;S!==null&&(S>F?T&&(J=S):J=V=S);let X=new Il(n),Y=new Float64Array(n),U=new Float64Array(X.outputBufferSize),z=new Float32Array(H*J);for(let L=0;L<V;++L){let R=L*s,te=Math.min(t.length-R,r);te!==r&&Y.fill(0,0,r);for(let pe=0;pe<te;++pe)Y[pe]=t[R+pe];if(E){let pe=0;for(let Pe=0;Pe<te;++Pe)pe+=Y[Pe];let Fe=pe/te;for(let Pe=0;Pe<te;++Pe)Y[Pe]-=Fe}if(u!==null){for(let pe=te-1;pe>=1;--pe)Y[pe]-=u*Y[pe-1];Y[0]*=1-u}for(let pe=0;pe<e.length;++pe)Y[pe]*=e[pe];X.realTransform(U,Y);for(let pe=0;pe<H;++pe){let Fe=pe<<1;z[pe*J+L]=U[Fe]**2+U[Fe+1]**2}}if(o!==null&&o!==2){let L=o/2;for(let R=0;R<z.length;++R)z[R]**=L}let ne=f.length,ae=await uA(new D("float32",f.flat(),[ne,H]),new D("float32",z,[H,J]));P&&(ae=ae.transpose(1,0));let I=ae.data;for(let L=0;L<I.length;++L)I[L]=C+Math.max(m,I[L]);if(o!==null&&h!==null){let L=Math.min(I.length,V*ne);switch(h){case"log":for(let R=0;R<L;++R)I[R]=Math.log(I[R]);break;case"log10":for(let R=0;R<L;++R)I[R]=Math.log10(I[R]);break;case"dB":if(o===1)KP(I,w,x,k);else if(o===2)YP(I,w,x,k);else throw new Error(`Cannot use log_mel option '${h}' with power ${o}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${h}'`)}}return ae}function It(t,e,{periodic:r=!0,frame_length:s=null,center:n=!0}={}){let o=r?t+1:t,a;switch(e){case"boxcar":a=new Float64Array(o).fill(1);break;case"hann":case"hann_window":a=xA(o);break;case"hamming":a=GP(o);break;case"povey":a=xA(o).map(i=>Math.pow(i,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);return a}function QP(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return ec(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),ec(n,8,"WAVE"),ec(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,e,!0),n.setUint32(28,e*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),ec(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function ec(t,e,r){for(let s=0;s<r.length;++s)t.setUint8(e+s,r.charCodeAt(s))}var ho=class{constructor(e,r){this.audio=e,this.sampling_rate=r}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];let e=this.audio.reduce((n,o)=>n+o.length,0),r=new Float32Array(e),s=0;for(let n of this.audio)r.set(n,s),s+=n.length;return r}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),QP(e,this.sampling_rate)}async save(e){return Zl(e,this.toBlob())}};var Gf=class extends Re{constructor(e){super(e);let r=this.config.sampling_rate,s=kt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=It(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return Ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){Xe(e,"ASTFeatureExtractor");let r=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let s=this.std*2,n=r.data;for(let o=0;o<n.length;++o)n[o]=(n[o]-this.mean)/s}return{input_values:r.unsqueeze_(0)}}};var _o=class extends Re{async _call(e){Xe(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=this.config.feature_size;if(e.length%r!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${r}).`);let s=[1,r,e.length/r];return{input_values:new D("float32",e,s)}}};var qf=class extends Re{async _call(e){Xe(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new D("float32",e,r)}}};var Wf=class extends Re{constructor(e){super(e),this.mel_filters=kt(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=kt(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=It(this.config.fft_window_size,"hann")}async _get_input_mel(e,r,s,n){let o,a=!1,i=e.length-r;if(i>0)if(s==="rand_trunc"){a=!0;let l=Math.floor(Ts.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let u=e.length;u<r;u+=e.length)l.set(e.subarray(0,Math.min(e.length,r-u)),u);else if(n==="repeatpad")for(let u=e.length;u<-i;u+=e.length)l.set(e,u);e=l}if(s==="fusion")throw new Error(`Truncation strategy "${s}" not implemented`);o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return o.unsqueeze_(0)}async _extract_fbank_features(e,r,s=null){return Ot(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:r,log_mel:"dB",max_num_frames:s,do_pad:!1,transpose:!0})}async _call(e,{max_length:r=null}={}){return Xe(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,r??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}};var go=class extends _o{};var Vf=class extends Re{constructor(e){super(e);let{fft_length:r,feature_size:s,min_frequency:n,max_frequency:o,sampling_rate:a,frame_length:i}=this.config,l=kt(Math.floor(1+r/2),s,n,o,a,null,"htk",!1);this.mel_filters=l,this.window=It(i,"hann")}async _extract_fbank_features(e,r){return Ot(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:r=48e4,truncation:s=!0,padding:n=!0,pad_to_multiple_of:o=128}={}){if(Xe(e,"Gemma3nAudioFeatureExtractor"),s&&e.length>r&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,u=new Float64Array(e.length+l);u.set(e),this.config.padding_value!==0&&u.fill(this.config.padding_value,e.length),e=u}let a=await this._extract_fbank_features(e,this.config.max_length),i=He([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var Hf=class extends Re{async _call(e){Xe(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new D("float32",e,r)}}};var JP=1e-5,Xf=class extends Re{constructor(e){super(e),this.config.mel_filters??=kt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");let r=It(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);let s=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(r,s)}async _extract_fbank_features(e){let r=this.config.preemphasis;e=new Float64Array(e);for(let n=e.length-1;n>=1;--n)e[n]-=r*e[n-1];return await Ot(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){Xe(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f<s;++f){let m=f*a;for(let h=0;h<a;++h){let w=n[m+h];i[h]+=w,l[h]+=w*w}}let u=s>1?s-1:1;for(let f=0;f<a;++f){let m=i[f]/s,h=(l[f]-s*m*m)/u,x=1/(Math.sqrt(h)+JP);for(let k=0;k<s;++k){let E=k*a+f;n[E]=(n[E]-m)*x}}let p=new BigInt64Array(o);return p.fill(1n,0,s),{input_features:r.unsqueeze_(0),attention_mask:new D("int64",p,[1,o])}}};var wo=class extends Re{async _call(e){Xe(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,1,e.length];return{input_values:new D("float32",e,r)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,r){let s=r/this.samples_to_frames(r)/this.config.sampling_rate,n=[];for(let o of e.tolist()){let a=[],i=-1;for(let l=0;l<o.length;++l){let u=Le(o[l]),[p,f]=Se(u),[m,h]=[l,l+1];f!==i?(i=f,a.push({id:f,start:m,end:h,score:p})):(a.at(-1).end=h,a.at(-1).score+=p)}n.push(a.map(({id:l,start:u,end:p,score:f})=>({id:l,start:u*s,end:p*s,confidence:f/(p-u)})))}return n}};var Kf=class extends Re{constructor(e){super(e);let r=this.config.sampling_rate,s=kt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=It(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),Ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){Xe(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,k=a.data;for(let E=0;E<x;++E){let A=0;for(let C=0;C<w;++C)A+=k[C*x+E];let S=A/w,T=0;for(let C=0;C<w;++C)T+=(k[C*x+E]-S)**2;T/=w-1;let P=Math.sqrt(T+1e-7);for(let C=0;C<w;++C){let v=C*x+E;k[v]=(k[v]-S)/P}}}let i;if(r){let[w,x]=a.dims,k=a.data,E=w%s;if(E>0){let A=new Float32Array(x*(w+E));A.set(k),A.fill(this.config.padding_value,k.length);let S=w+E;a=new D(a.type,A,[S,x]),o&&(i=new D("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,w))}}let[l,u]=a.dims,p=this.config.stride;if(l%p!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${p}).`);let m=a.view(1,Math.floor(l/p),u*p),h={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let k=i.data;for(let E=1,A=0;E<l;E+=p,++A)x[A]=k[E]}else x.fill(1n);h.attention_mask=new D("int64",x,[1,w])}return h}};var Yf=class extends go{};var Qf=class extends Re{};var Jf=class extends Re{_zero_mean_unit_var_norm(e){let s=e.reduce((o,a)=>o+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){Xe(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));let s=[1,r.length];return{input_values:new D("float32",r,s),attention_mask:new D("int64",new BigInt64Array(r.length).fill(1n),s)}}};var Zf=class extends Re{constructor(e){super(e);let r=this.config.sampling_rate,s=kt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=It(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),Ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){Xe(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;l<o;++l){let u=l*a*i,p=l*i;for(let f=0;f<a;++f){let m=u+f*i;for(let h=0;h<i;++h)n[m+h]-=s[p+h]}}}return{input_features:r}}};var em=class extends Re{constructor(e){super(e),this.config.mel_filters??=kt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=It(this.config.n_fft,"hann")}async _extract_fbank_features(e){let r=await Ot(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:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)}),s=r.data,n=Se(s)[0];for(let o=0;o<s.length;++o)s[o]=(Math.max(s[o],n-8)+4)/4;return r}async _call(e,{max_length:r=null}={}){Xe(e,"WhisperFeatureExtractor");let s,n=r??this.config.n_samples;return e.length>n?(e.length>this.config.n_samples&&Q.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var rt=class{static async from_pretrained(e,r={}){let s=await ct(e,mo,!0,r),n=s.feature_extractor_type,o=xo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Fr}.`);return new o(s)}};var tm=class extends oe{static tokenizer_class=Z;static feature_extractor_class=rt;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};import rm from"sharp";var Os,kA,jr,er=ge.IS_BROWSER_ENV||ge.IS_WEBWORKER_ENV;if(er)Os=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},jr=self.createImageBitmap,kA=self.ImageData;else if(rm)jr=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Ke(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&o.convert(r),o};else throw new Error("Unable to load image processing library.");var ZP={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},ez=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Ke=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!er)throw new Error("fromCanvas() is only supported in browser environments.");let s=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(s,e.width,e.height,4)}static async fromURL(e){let r=await zr(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(e){if(er){let r=await jr(e),s=Os(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=rm(await e.arrayBuffer());return await jr(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r<this.data.length;r+=this.channels){let n=this.data[r],o=this.data[r+1],a=this.data[r+2];e[s++]=Math.round(.2989*n+.587*o+.114*a)}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 r=0,s=0;r<this.data.length;++r)e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=this.data[r];break;case 4:for(let r=0,s=0;r<this.data.length;r+=4)e[s++]=this.data[r],e[s++]=this.data[r+1],e[s++]=this.data[r+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 r=0,s=0;r<this.data.length;++r)e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=255;break;case 3:for(let r=0,s=0;r<this.data.length;r+=3)e[s++]=this.data[r],e[s++]=this.data[r+1],e[s++]=this.data[r+2],e[s++]=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)}putAlpha(e){if(e.width!==this.width||e.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${e.width}x${e.height}`);if(e.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${e.channels}`);let r=this.data,s=e.data,n=this.width*this.height;if(this.channels===3){let o=new Uint8ClampedArray(n*4);for(let a=0,i=0,l=0;a<n;++a)o[l++]=r[i++],o[l++]=r[i++],o[l++]=r[i++],o[l++]=s[a];return this._update(o,this.width,this.height,4)}else if(this.channels===4){for(let o=0;o<n;++o)r[4*o+3]=s[o];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(e,r,{resample:s=2}={}){if(this.width===e&&this.height===r)return this;let n=ZP[s]??s,o=Rp(e),a=Rp(r);if(o&&a)return this;if(o?e=r/this.height*this.width:a&&(r=e/this.width*this.height),er){let i=this.channels,l=this.toCanvas(),u=Os(e,r).getContext("2d");return u.drawImage(l,0,0,e,r),new t(u.getImageData(0,0,e,r).data,e,r,4).convert(i)}else{let i=this.toSharp();switch(n){case"box":case"hamming":(n==="box"||n==="hamming")&&(Q.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":i=i.affine([e/this.width,0,0,r/this.height],{interpolator:n});break;case"lanczos":i=i.resize({width:e,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await jr(i)}}async pad([e,r,s,n]){if(e=Math.max(e,0),r=Math.max(r,0),s=Math.max(s,0),n=Math.max(n,0),e===0&&r===0&&s===0&&n===0)return this;if(er){let o=this.channels,a=this.toCanvas(),i=this.width+e+r,l=this.height+s+n,u=Os(i,l).getContext("2d");return u.drawImage(a,0,0,this.width,this.height,e,s,this.width,this.height),new t(u.getImageData(0,0,i,l).data,i,l,4).convert(o)}else{let o=this.toSharp().extend({left:e,right:r,top:s,bottom:n});return await jr(o)}}async crop([e,r,s,n]){if(e=Math.max(e,0),r=Math.max(r,0),s=Math.min(s,this.width-1),n=Math.min(n,this.height-1),e===0&&r===0&&s===this.width-1&&n===this.height-1)return this;let o=s-e+1,a=n-r+1;if(er){let i=this.channels,l=this.toCanvas(),u=Os(o,a).getContext("2d");return u.drawImage(l,e,r,o,a,0,0,o,a),new t(u.getImageData(0,0,o,a).data,o,a,4).convert(i)}else{let i=this.toSharp().extract({left:e,top:r,width:o,height:a});return await jr(i)}}async center_crop(e,r){if(this.width===e&&this.height===r)return this;let s=(this.width-e)/2,n=(this.height-r)/2;if(er){let o=this.channels,a=this.toCanvas(),i=Os(e,r).getContext("2d"),l=0,u=0,p=0,f=0;return s>=0?l=s:p=-s,n>=0?u=n:f=-n,i.drawImage(a,l,u,e,r,p,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],u=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):u=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:u,top:i,width:e,height:r})}return await jr(o)}}async toBlob(e="image/png",r=1){if(!er)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new D("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!er)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=Os(e.width,e.height),s=new kA(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;l<a;++l){let u=n*l;for(let p=0;p<n;++p)i[p][l]=e[u+p]}return i.map(l=>new t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(er){if(ge.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=ez.get(r)??"image/png",n=await this.toBlob(s);return Zl(e,n)}else if(ge.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(er)throw new Error("toSharp() is only supported in server-side environments.");return rm(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},tz=Ke.read.bind(Ke);function EA(t,e,r=0,s=null){let n=t/e,o=vk(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),o<r&&(o=Math.ceil(n)*e),o}function sm([t,e],r){return[Math.max(Math.floor(t/r),1)*r,Math.max(Math.floor(e/r),1)*r]}function nm([t,e,r,s]){return[t-r/2,e-s/2,t+r/2,e+s/2]}function Gr(t,e=.5,r=null,s=!1){let n=t.logits,o=t.pred_boxes,[a,i,l]=n.dims;if(r!==null&&r.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let u=[];for(let p=0;p<a;++p){let f=r!==null?r[p]:null,m={boxes:[],classes:[],scores:[]},h=n[p],w=o[p];for(let x=0;x<i;++x){let k=h[x],E=[],A;if(s){A=k.sigmoid().data;for(let S=0;S<A.length;++S)A[S]>e&&E.push(S)}else{let S=Se(k.data)[1];if(S===l-1||(A=Le(k.data),A[S]<e))continue;E.push(S)}for(let S of E){let T=w[x].data;T=nm(T),f!==null&&(T=T.map((P,C)=>P*f[(C+1)%2])),m.boxes.push(T),m.classes.push(S),m.scores.push(A[S])}}u.push(m)}return u}function tc(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;o<s;++o){let a=e!==null?e[o]:null,i=r[o];a!==null&&(i=jd(i,a,"bilinear",!1));let[l,u]=a??i.dims.slice(-2),p=new D("int32",new Int32Array(l*u),[l,u]),f=i[0].data,m=p.data;for(let x=1;x<i.dims[0];++x){let k=i[x].data;for(let E=0;E<k.length;++E)k[E]>f[E]&&(f[E]=k[E],m[E]=x)}let h=new Array(i.dims[0]);for(let x=0;x<m.length;++x){let k=m[x];h[k]=k}let w=h.filter(x=>x!==void 0);n.push({segmentation:p,labels:w})}return n}function rz(t,e,r,s){let n=[],o=[],a=[];for(let i=0;i<t.dims[0];++i){let l=t[i],u=e[i],p=Se(l.data)[1];if(p===s)continue;let m=Le(l.data)[p];m>r&&(n.push(u),o.push(m),a.push(p))}return[n,o,a]}function sz(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let p=0;p<t.length;++p)t[p]===r&&(o.push(p),++a),l[p]>=s&&++i;let u=a>0&&i>0;return u&&(u=a/i>n),[u,o]}function nz(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,u=new D("int32",new Int32Array(i*l),[i,l]),p=[];if(a!==null)for(let x=0;x<t.length;++x)t[x]=jd(t[x],a,"bilinear",!1);let f=new Int32Array(t[0].data.length),m=new Float32Array(t[0].data.length);for(let x=0;x<t.length;++x){let k=e[x],E=t[x].data;for(let A=0;A<E.length;++A)E[A]*=k,E[A]>m[A]&&(f[A]=x,m[A]=E[A])}let h=0,w=u.data;for(let x=0;x<r.length;++x){let k=r[x],[E,A]=sz(f,t,x,s,n);if(E){++h;for(let S of A)w[S]=h;p.push({id:h,label_id:k,score:e[x]})}}return[u,p]}function rc(t,e=.5,r=.5,s=.8,n=null,o=null){n===null&&(Q.warn("`label_ids_to_fuse` unset. No instance will be fused."),n=new Set);let a=t.class_queries_logits??t.logits,l=(t.masks_queries_logits??t.pred_masks).sigmoid(),[u,p,f]=a.dims;if(f-=1,o!==null&&o.length!==u)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let m=[];for(let h=0;h<u;++h){let w=o!==null?o[h]:null,x=a[h],k=l[h],[E,A,S]=rz(x,k,e,f);if(S.length===0){let[C,v]=w??k.dims.slice(-2),F=new D("int32",new Int32Array(C*v).fill(-1),[C,v]);m.push({segmentation:F,segments_info:[]});continue}let[T,P]=nz(E,A,S,r,s,n,w);m.push({segmentation:T,segments_info:P})}return m}function sc(t,e=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var W=class extends Ze{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,r,s=2){let n=e.height,o=e.width,a=r.height,i=r.width,l=Math.min(n,a),u=Math.min(o,i);return l===n&&u===o?e:(n>o?u=Math.floor(o*l/n):o>n&&(l=Math.floor(n*u/o)),await e.resize(u,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=Jn(s.data)[0],a=Se(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,u=s.height,p=0,f=0,m=s.data;for(let h=0;h<s.height;++h){let w=h*s.width;for(let x=0;x<s.width;++x)(m[w+x]-n)/a<i&&(l=Math.min(l,x),u=Math.min(u,h),p=Math.max(p,x),f=Math.max(f,h))}return e=await e.crop([l,u,p,f]),e}pad_image(e,r,s,{mode:n="constant",center:o=!1,constant_values:a=0}={}){let[i,l,u]=r,p,f;if(typeof s=="number"?(p=s,f=s):s==="square"?p=f=Math.max(i,l):(p=s.width,f=s.height),p!==l||f!==i){let m=new Float32Array(p*f*u);if(Array.isArray(a))for(let x=0;x<m.length;++x)m[x]=a[x%u];else a!==0&&m.fill(a);let[h,w]=o?[Math.floor((p-l)/2),Math.floor((f-i)/2)]:[0,0];for(let x=0;x<i;++x){let k=(x+w)*p,E=x*l;for(let A=0;A<l;++A){let S=(k+A+h)*u,T=(E+A)*u;for(let P=0;P<u;++P)m[S+P]=e[T+P]}}if(n==="symmetric"){if(o)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");let x=i-1,k=l-1;for(let E=0;E<f;++E){let A=E*p,S=Ks(E,x)*l;for(let T=0;T<p;++T){if(E<i&&T<l)continue;let P=(A+T)*u,C=(S+Ks(T,k))*u;for(let v=0;v<u;++v)m[P+v]=e[C+v]}}}e=m,r=[f,p,u]}return[e,r]}rescale(e){for(let r=0;r<e.length;++r)e[r]=this.rescale_factor*e[r]}get_resize_output_image_size(e,r){let[s,n]=e.size,o,a;if(this.do_thumbnail){let{height:i,width:l}=r;o=Math.min(i,l)}else Number.isInteger(r)?(o=r,a=this.config.max_size??o):r!==void 0&&(o=r.shortest_edge,a=r.longest_edge);if(o!==void 0||a!==void 0){let i=o===void 0?1:Math.max(o/s,o/n),l=s*i,u=n*i,p=a===void 0?1:Math.min(a/l,a/u),f=Math.floor(Number((l*p).toFixed(2))),m=Math.floor(Number((u*p).toFixed(2)));return this.size_divisibility!==void 0&&([f,m]=sm([f,m],this.size_divisibility)),[f,m]}else if(r!==void 0&&r.width!==void 0&&r.height!==void 0){let i=r.width,l=r.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let u=l/n,p=i/s;Math.abs(1-p)<Math.abs(1-u)?u=p:p=u,l=EA(u*n,this.config.ensure_multiple_of),i=EA(p*s,this.config.ensure_multiple_of)}return[i,l]}else{if(this.size_divisibility!==void 0)return sm([s,n],this.size_divisibility);throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(r)}`)}}async resize(e){let[r,s]=this.get_resize_output_image_size(e,this.size);return await e.resize(r,s,{resample:this.resample})}async preprocess(e,{do_normalize:r=null,do_pad:s=null,do_convert_rgb:n=null,do_convert_grayscale:o=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));let[i,l]=e.size;if(n??this.do_convert_rgb?e=e.rgb():o&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let h,w;Number.isInteger(this.crop_size)?(h=this.crop_size,w=this.crop_size):(h=this.crop_size.width,w=this.crop_size.height),e=await e.center_crop(h,w)}let u=[e.height,e.width],p=Float32Array.from(e.data),f=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(p),r??this.do_normalize){let h=this.image_mean;Array.isArray(this.image_mean)||(h=new Array(e.channels).fill(h));let w=this.image_std;if(Array.isArray(this.image_std)||(w=new Array(e.channels).fill(w)),h.length!==e.channels||w.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${h.length}) and \`image_std\` (${w.length}) must match the number of channels in the image (${e.channels}).`);for(let x=0;x<p.length;x+=e.channels)for(let k=0;k<e.channels;++k)p[x+k]=(p[x+k]-h[k])/w[k]}if(s??this.do_pad){if(this.pad_size)[p,f]=this.pad_image(p,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){let[h,w]=sm([f[1],f[0]],this.size_divisibility);[p,f]=this.pad_image(p,f,{width:h,height:w})}}if(a??this.do_flip_channel_order){if(f[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let h=0;h<p.length;h+=3){let w=p[h];p[h]=p[h+2],p[h+2]=w}}let m=new D("float32",p,f).permute(2,0,1);return{original_size:[l,i],reshaped_input_size:u,pixel_values:m}}async _call(e,...r){Array.isArray(e)||(e=[e]);let s=await Promise.all(e.map(o=>this.preprocess(o)));return{pixel_values:Gt(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await ct(e,Ar,!0,r);return new this(s)}};var dn={};Vs(dn,{BeitFeatureExtractor:()=>om,BitImageProcessor:()=>am,CLIPFeatureExtractor:()=>lm,CLIPImageProcessor:()=>nc,ChineseCLIPFeatureExtractor:()=>im,ConvNextFeatureExtractor:()=>cm,ConvNextImageProcessor:()=>oc,DINOv3ViTImageProcessor:()=>dm,DPTFeatureExtractor:()=>mm,DPTImageProcessor:()=>lc,DeiTFeatureExtractor:()=>um,DeiTImageProcessor:()=>ac,DetrFeatureExtractor:()=>pm,DetrImageProcessor:()=>ic,DonutFeatureExtractor:()=>fm,DonutImageProcessor:()=>ln,EfficientNetImageProcessor:()=>hm,GLPNFeatureExtractor:()=>_m,GroundingDinoImageProcessor:()=>gm,Idefics3ImageProcessor:()=>cc,ImageFeatureExtractor:()=>W,ImageProcessor:()=>W,JinaCLIPImageProcessor:()=>xm,LlavaOnevisionImageProcessor:()=>ym,Mask2FormerImageProcessor:()=>vm,MaskFormerFeatureExtractor:()=>bm,MaskFormerImageProcessor:()=>cn,MobileNetV1FeatureExtractor:()=>km,MobileNetV1ImageProcessor:()=>uc,MobileNetV2FeatureExtractor:()=>Em,MobileNetV2ImageProcessor:()=>pc,MobileNetV3FeatureExtractor:()=>Am,MobileNetV3ImageProcessor:()=>dc,MobileNetV4FeatureExtractor:()=>Mm,MobileNetV4ImageProcessor:()=>fc,MobileViTFeatureExtractor:()=>Tm,MobileViTImageProcessor:()=>mc,NougatImageProcessor:()=>Sm,OwlViTFeatureExtractor:()=>Om,OwlViTImageProcessor:()=>un,Owlv2ImageProcessor:()=>Im,Phi3VImageProcessor:()=>zm,PixtralImageProcessor:()=>Lm,PvtImageProcessor:()=>Nm,Qwen2VLImageProcessor:()=>$m,RTDetrImageProcessor:()=>Rm,Sam2ImageProcessor:()=>yo,Sam3ImageProcessor:()=>yo,SamImageProcessor:()=>yo,SapiensFeatureExtractor:()=>Dm,SapiensImageProcessor:()=>hc,SegformerFeatureExtractor:()=>Um,SegformerImageProcessor:()=>_c,SiglipImageProcessor:()=>Bm,SmolVLMImageProcessor:()=>cc,Swin2SRImageProcessor:()=>Fm,VLMImageProcessor:()=>wm,ViTFeatureExtractor:()=>jm,ViTImageProcessor:()=>gc,VitMatteImageProcessor:()=>Gm,VitPoseImageProcessor:()=>qm,YolosFeatureExtractor:()=>Wm,YolosImageProcessor:()=>wc});var om=class extends W{};var am=class extends W{};var im=class extends W{};var nc=class extends W{},lm=class extends nc{};var oc=class extends W{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){let s=Math.floor(r/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}},cm=class extends oc{};var ac=class extends W{},um=class extends ac{};var ic=class extends W{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=He(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Gr(...e)}post_process_panoptic_segmentation(...e){return rc(...e)}post_process_instance_segmentation(...e){return sc(...e)}},pm=class extends ic{};var dm=class extends W{};var ln=class extends W{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let u=this.image_std;Array.isArray(u)||(u=new Array(i).fill(l));let p=l.map((f,m)=>-f/u[m]);return super.pad_image(e,r,s,{center:!0,constant_values:p,...n})}},fm=class extends ln{};var lc=class extends W{},mm=class extends lc{};var hm=class extends W{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}};var _m=class extends W{};var gm=class extends W{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=at([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var cc=class extends W{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],u=[];for(let E of n){let A=await Promise.all(E.map(P=>this.preprocess(P)));l.push(...A.map(P=>P.original_size)),u.push(...A.map(P=>P.reshaped_input_size)),A.forEach(P=>P.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,T;if(r??this.do_image_splitting){let P=new Array(A.length),C=new Array(A.length);T=await Promise.all(A.map(async(v,F)=>{let H=this.get_resize_for_vision_encoder(v.pixel_values,S),V=await jt(v.pixel_values,{size:[H.height,H.width]}),{frames:J,num_splits_h:X,num_splits_w:Y}=await this.split_image(V,this.max_image_size);return P[F]=X,C[F]=Y,Ee(J,0)})),a.push(P),i.push(C)}else{let P=[S,S];T=await Promise.all(A.map(C=>jt(C.pixel_values,{size:P}))),a.push(new Array(A.length).fill(0)),i.push(new Array(A.length).fill(0))}o.push(Ee(T,0))}let p=o.length,[f,m,h,w]=o[0].dims,x,k;if(p===1)x=o[0].unsqueeze_(0),k=He([p,f,h,w],!0);else{let E=Math.max(...o.map(T=>T.dims.at(0)));k=He([p,E,h,w],!0);let A=k.data,S=E*h*w;for(let T=0;T<p;++T){let P=o[T].dims[0];if(P<E){o[T]=Ee([o[T],He([E-P,m,h,w],0)],0);let C=T*S+P*h*w,v=(T+1)*S;A.fill(!1,C,v)}}x=Gt(o,0)}return{pixel_values:x,pixel_attention_mask:k,original_sizes:l,reshaped_input_sizes:u,...s?{rows:a,cols:i}:{}}}async split_image(e,{longest_edge:r}){let s=r,n=r,o=[],[a,i]=e.dims.slice(-2),l=0,u=0;if(a>s||i>n){l=Math.ceil(a/s),u=Math.ceil(i/n);let p=Math.ceil(a/l),f=Math.ceil(i/u);for(let w=0;w<l;++w)for(let x=0;x<u;++x){let k,E,A,S;w===l-1?(E=a-p,S=a):(E=w*p,S=(w+1)*p),x===u-1?(k=i-f,A=i):(k=x*f,A=(x+1)*f);let C=await Yl(e,[E,k],[S,A],[2,3]);o.push(C)}let m=s,h=n;(a!==m||i!==h)&&(e=await jt(e,{size:[m,h]}))}return o.push(e),{frames:o,num_splits_h:l,num_splits_w:u}}};var wm=class extends W{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map(r=>r*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var xm=class extends W{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};var ym=class extends W{};var cn=class extends W{post_process_panoptic_segmentation(...e){return rc(...e)}post_process_instance_segmentation(...e){return sc(...e)}},bm=class extends cn{};var vm=class extends cn{};var uc=class extends W{},km=class extends uc{};var pc=class extends W{},Em=class extends pc{};var dc=class extends W{},Am=class extends dc{};var fc=class extends W{},Mm=class extends fc{};var mc=class extends W{},Tm=class extends mc{};var Sm=class extends ln{};var un=class extends W{post_process_object_detection(...e){return Gr(...e)}},Om=class extends un{};var Im=class extends un{};var $t=336,oz=[2,3],{ceil:Cm,floor:pn,sqrt:Pm}=Math,zm=class extends W{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,r){let{num_img_tokens:s}=this.config;return pn((pn(r/$t)*pn(e/$t)+1)*s+1+(pn(r/$t)+1)*Pm(s))}get_resize_output_image_size(e,r){let s=this._num_crops,[n,o]=e.size,a=n/o,i=1;for(;i*Math.ceil(i/a)<=s;)i+=1;i-=1;let l=Math.floor(i*336),u=Math.floor(l/a);return[l,u]}pad_image(e,r,s,n={}){let[o,a]=r,i=$t*Cm(o/$t),l=$t*Cm(a/$t),u=[1,1,1].map((p,f)=>(p-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:u,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||Pm(r)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(m=>this.preprocess(m))),o=n.map(m=>m.original_size),a=n.map(m=>m.reshaped_input_size),i=[];for(let{pixel_values:m}of n){m.unsqueeze_(0);let[h,w]=m.dims.slice(-2),x=await jt(m,{size:[$t,$t],mode:"bicubic"});if(r>0){let k=[],E=Pm(r),A=pn(w/E),S=pn(h/E);for(let P=0;P<E;++P)for(let C=0;C<E;++C){let v,F,H,V;P===E-1?(F=h-S,V=h):(F=P*S,V=(P+1)*S),C===E-1?(v=w-A,H=w):(v=C*A,H=(C+1)*A);let Y=await Yl(m,[F,v],[V,H],oz);k.push(Y)}let T=await jt(Ee(k,0),{size:[$t,$t],mode:"bicubic"});i.push(Ee([x,T],0))}else i.push(x)}let l=Gt(i,0),u=a.map(m=>m.map(h=>$t*Cm(h/$t))),p=new D("int64",u.flat(),[s,2]),f=u.map(([m,h])=>this.calc_num_image_tokens_from_image_size(h,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:p,num_img_tokens:f}}};var Lm=class extends W{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:u,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");let f=u*p,m=Math.floor((i-1)/f)+1,h=Math.floor((l-1)/f)+1;return[m*f,h*f]}};var Nm=class extends W{};function az(t,e,r=28,s=3136,n=784*1280){if(t<r||e<r)throw new Error(`height:${t} or width:${e} must be larger than factor:${r}`);if(Math.max(t,e)/Math.min(t,e)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let o=Math.round(t/r)*r,a=Math.round(e/r)*r;if(o*a>n){let i=Math.sqrt(t*e/n);o=Math.floor(t/i/r)*r,a=Math.floor(e/i/r)*r}else if(o*a<s){let i=Math.sqrt(s/(t*e));o=Math.ceil(t*i/r)*r,a=Math.ceil(e*i/r)*r}return[o,a]}var $m=class extends W{constructor(e){super(e),this.min_pixels=e.min_pixels??e.size?.shortest_edge,this.max_pixels=e.max_pixels??e.size?.longest_edge,this.patch_size=e.patch_size,this.merge_size=e.merge_size}get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size;return az(e.height,e.width,s,this.min_pixels,this.max_pixels)}async _call(e,...r){let{pixel_values:s,original_sizes:n,reshaped_input_sizes:o}=await super._call(e,...r),a=s,{temporal_patch_size:i,merge_size:l,patch_size:u}=this.config;a.dims[0]===1&&(a=Ee(Array.from({length:i},()=>a),0));let p=a.dims[0]/i,f=a.dims[1],m=Math.floor(a.dims[2]/u),h=Math.floor(a.dims[3]/u),w=a.view(p,i,f,Math.floor(m/l),l,u,Math.floor(h/l),l,u).permute(0,3,6,4,7,2,1,5,8).view(p*m*h,f*i*u*u),x=new D("int64",[p,m,h],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var Rm=class extends W{post_process_object_detection(...e){return Gr(...e)}};var yo=class extends W{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=Dp(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;a<e.length;++a){let[i,l]=r[a],[u,p]=s[a],f=[p/l,u/i];for(let m=0;m<e[a].length;++m)for(let h=0;h<e[a][m].length;++h)for(let w=0;w<e[a][m][h].length;++w)e[a][m][h][w]*=f[w%2]}return new D("float32",Float32Array.from(e.flat(1/0)),o)}add_input_labels(e,r){let s=Dp(e);if(s.length===2)s=[1,...s],e=[e];else if(s.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(s.some((n,o)=>n!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new D("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let u=0;u<r.length;++u){let p=r[u],f=s[u],m=await jt(e[u],{mode:"bilinear",size:l});if(m=m.slice(null,null,[0,f[0]],[0,f[1]]),m=await jt(m,{mode:"bilinear",size:p}),o){let h=m.data,w=new Uint8Array(h.length);for(let x=0;x<h.length;++x)h[x]>n&&(w[x]=1);m=new D("bool",w,m.dims)}i.push(m)}return i}generate_crop_boxes(e,r,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:a=1}={}){}};var hc=class extends W{post_process_semantic_segmentation(...e){return tc(...e)}},Dm=class extends hc{};var _c=class extends W{post_process_semantic_segmentation(...e){return tc(...e)}},Um=class extends _c{};var Bm=class extends W{};var Fm=class extends W{pad_image(e,r,s,n={}){let[o,a,i]=r;return super.pad_image(e,r,{width:a+(s-a%s)%s,height:o+(s-o%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var gc=class extends W{},jm=class extends gc{};var Gm=class extends W{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let s=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(r.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:Gt(s.map((a,i)=>Ee([a.pixel_values,n[i].pixel_values],0)),0),original_sizes:s.map(a=>a.original_size),reshaped_input_sizes:s.map(a=>a.reshaped_input_size)}}};var qm=class extends W{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,u=[];for(let p=0;p<o;++p){let f=n[p],m=r[p],h=[];for(let w=0;w<m.length;++w){let x=m[w],k=[],E=[],A=[],S=x.at(-2)/l,T=x.at(-1)/i;for(let P=0;P<f.length;++P){let[C,v]=[0,0],F=0,H=-1/0,V=f[P];for(let X=0;X<V.length;++X){let Y=V[X];for(let U=0;U<Y.length;++U){let z=Y[U];F+=z,H=Math.max(H,z),C+=(U+.5)*z,v+=X*z}}if(s!=null&&H<s)continue;let J=[S*C/F,T*v/F];k.push(J),A.push(P),E.push(H)}h.push({bbox:x,scores:E,labels:A,keypoints:k})}u.push(h)}return u}};var wc=class extends W{post_process_object_detection(...e){return Gr(...e)}},Wm=class extends wc{};var De=class{static async from_pretrained(e,r={}){let s=await ct(e,Ar,!0,r),n=s.image_processor_type??s.feature_extractor_type,o=dn[n?.replace(/Fast$/,"")];return o||(n!==void 0&&Q.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${Fr}.`),o=W),new o(s)}};var Vm=class extends oe{static tokenizer_class=Z;static image_processor_class=De;constructor(e,r,s){super(e,r,s);let{tasks_answer_post_processing_type:n,task_prompts_without_inputs:o,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(n??{})),this.task_prompts_without_inputs=new Map(Object.entries(o??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("<s>","").replaceAll("</s>","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],u=[];for(let[p,f,...m]of i)l.push(f?f.trim():l.at(-1)??""),u.push(m.map((h,w)=>(Number(h)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:u};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var Hm=class extends oe{static image_processor_class=De;static feature_extractor_class=rt;static tokenizer_class=Z;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:n,boa_token:o,audio_token:a,eoa_token:i,image_token_id:l,boi_token:u,image_token:p,eoi_token:f}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=o,this.audio_token=a;let m=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
16
14
 
17
15
  ${o}${m}${i}
18
16
 
19
- `,this.image_token_id=l,this.boi_token=u,this.image_token=d;let _=d.repeat(this.image_seq_length);this.full_image_sequence=`
17
+ `,this.image_token_id=l,this.boi_token=u,this.image_token=p;let h=p.repeat(this.image_seq_length);this.full_image_sequence=`
20
18
 
21
- ${u}${_}${f}
19
+ ${u}${h}${f}
22
20
 
23
- `}async _call(e,r=null,s=null,n={}){typeof e=="string"&&(e=[e]);let o;s&&(o=await this.feature_extractor(s,n),e=e.map(l=>l.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return r&&(a=await this.image_processor(r,n),e=e.map(l=>l.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...o}}};function MP(t,e){let s=t.dims.at(-1)-1,n=t.tolist();n.fill(!1,0,1),n.fill(!1,s);let o=e.tolist();return n.map((a,i)=>a?i:null).filter(a=>a!==null).map(a=>o[a])}var Mm=class extends ne{static tokenizer_class=J;static image_processor_class=$e;async _call(e,r,s={}){let n=e?await this.image_processor(e,s):{};return{...r?this.tokenizer(r,s):{},...n}}post_process_grounded_object_detection(e,r,{box_threshold:s=.25,text_threshold:n=.25,target_sizes:o=null}={}){let{logits:a,pred_boxes:i}=e,l=a.dims[0];if(o!==null&&o.length!==l)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let u=a.dims.at(1),d=a.sigmoid(),f=d.max(-1).tolist(),m=i.tolist().map(w=>w.map(x=>$f(x))),_=[];for(let w=0;w<l;++w){let x=o!==null?o[w]:null;x!==null&&(m[w]=m[w].map(T=>T.map((z,C)=>z*x[(C+1)%2])));let k=f[w],E=[],M=[],I=[];for(let T=0;T<u;++T){let z=k[T];if(z<=s)continue;let C=m[w][T],v=d[w][T];E.push(z),I.push(C);let G=MP(v.gt(n),r[w]);M.push(G)}_.push({scores:E,boxes:I,labels:this.batch_decode(M)})}return _}};function TP(t,e,r,s,n,o){let a="";for(let i=0;i<e;++i){for(let l=0;l<r;++l)a+=s+`<row_${i+1}_col_${l+1}>`+n.repeat(t);a+=`
21
+ `}async _call(e,r=null,s=null,n={}){typeof e=="string"&&(e=[e]);let o;s&&(o=await this.feature_extractor(s,n),e=e.map(l=>l.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return r&&(a=await this.image_processor(r,n),e=e.map(l=>l.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...o}}};function iz(t,e){let s=t.dims.at(-1)-1,n=t.tolist();n.fill(!1,0,1),n.fill(!1,s);let o=e.tolist();return n.map((a,i)=>a?i:null).filter(a=>a!==null).map(a=>o[a])}var Xm=class extends oe{static tokenizer_class=Z;static image_processor_class=De;async _call(e,r,s={}){let n=e?await this.image_processor(e,s):{};return{...r?this.tokenizer(r,s):{},...n}}post_process_grounded_object_detection(e,r,{box_threshold:s=.25,text_threshold:n=.25,target_sizes:o=null}={}){let{logits:a,pred_boxes:i}=e,l=a.dims[0];if(o!==null&&o.length!==l)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let u=a.dims.at(1),p=a.sigmoid(),f=p.max(-1).tolist(),m=i.tolist().map(w=>w.map(x=>nm(x))),h=[];for(let w=0;w<l;++w){let x=o!==null?o[w]:null;x!==null&&(m[w]=m[w].map(T=>T.map((P,C)=>P*x[(C+1)%2])));let k=f[w],E=[],A=[],S=[];for(let T=0;T<u;++T){let P=k[T];if(P<=s)continue;let C=m[w][T],v=p[w][T];E.push(P),S.push(C);let F=iz(v.gt(n),r[w]);A.push(F)}h.push({scores:E,boxes:S,labels:this.batch_decode(A)})}return h}};function lz(t,e,r,s,n,o){let a="";for(let i=0;i<e;++i){for(let l=0;l<r;++l)a+=s+`<row_${i+1}_col_${l+1}>`+n.repeat(t);a+=`
24
22
  `}return a+=`
25
- ${s}${o}`+n.repeat(t)+`${s}`,a}function SP(t,e,r,s){return`${e}${s}`+r.repeat(t)+`${e}`}function OP(t,e,r,s,n,o){return t===0&&e===0?SP(r,s,n,o):TP(r,t,e,s,n,o)}var Ol=class extends ne{static image_processor_class=$e;static tokenizer_class=J;static uses_processor_config=!0;fake_image_token="<fake_token_around_image>";image_token="<image>";global_img_token="<global-img>";async _call(e,r=null,s={}){s.return_row_col_info??=!0;let n;r&&(n=await this.image_processor(r,s)),Array.isArray(e)||(e=[e]);let o=n.rows??[new Array(e.length).fill(0)],a=n.cols??[new Array(e.length).fill(0)],i=this.config.image_seq_len,l=[],u=[];for(let f=0;f<e.length;++f){let m=e[f],_=o[f],w=a[f];l.push(Rv(m,this.image_token));let x=_.map((M,I)=>OP(M,w[I],i,this.fake_image_token,this.image_token,this.global_img_token)),k=m.split(this.image_token);if(k.length===0)throw new Error("The image token should be present in the text.");let E=k[0];for(let M=0;M<x.length;++M)E+=x[M]+k[M+1];u.push(E)}return{...this.tokenizer(u),...n}}};var Tm=class extends ne{static image_processor_class=$e;static tokenizer_class=J;static uses_processor_config=!0;constructor(e,r,s){super(e,r,s),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(e,{images:r=null,chat_template:s="default"}={}){r?Array.isArray(r)||(r=[r]):r=await Promise.all(e.filter(k=>k.images).flatMap(k=>k.images).map(k=>Xe.read(k)));let n=this.tokenizer,o=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=k=>n.encode(k,{add_special_tokens:!1}),i=o.split(this.image_tag),l=i.length-1;if(r.length!==l)throw new Error(`Number of images provided (${r.length}) does not match number of "${this.image_tag}" image tags (${l})`);let[u,d,f]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),m=a(i[0]),_=new Array(m.length).fill(!1);for(let k=1;k<i.length;++k){let E=new Array(this.num_image_tokens).fill(u),M=a(i[k]);m=dt(m,[d],E,[f],M);let I=new Array(this.num_image_tokens).fill(!0);_=dt(_,[!1],I,[!1],new Array(M.length).fill(!1))}let w=[1,m.length],x={input_ids:new U("int64",m,w),attention_mask:new U("int64",new Array(m.length).fill(1),w),images_seq_mask:new U("bool",_,w),images_emb_mask:new U("bool",new Array(l*this.num_image_tokens).fill(!0),[1,l,this.num_image_tokens])};if(r&&r.length>0){let k=await this.image_processor(r);return k.pixel_values.unsqueeze_(0),{...x,...k}}return x}};var Sm=class extends ne{static tokenizer_class=J;static image_processor_class=$e;async _call(e=null,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=e?this.tokenizer(e,s):{},o=r?await this.image_processor(r,s):{};return{...n,...o}}};var Om=class extends ne{static tokenizer_class=J;static image_processor_class=$e;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,patch_size:u,num_additional_image_tokens:d}=this.config,f=Math.floor(a/u)*Math.floor(i/u)+d;r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let m=0;m<r.length;++m)r[m]=r[m].replace(l,l.repeat(f))}let o=r?this.tokenizer(r,s):{};return{...n,...o}}};var XE={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},Im=class extends ne{static tokenizer_class=J;static image_processor_class=$e;get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(e,r){if(!XE.hasOwnProperty(r))throw new Error(`Format ${r} is not supported.`);let[s,n]=XE[r],o=this[s].bind(this),[a,i]=e.dims,l=[],u=[],d=e.tolist();for(let m=0;m<a;++m){let _=d[m],w=[],x=[];for(let E=1;E<i;++E){let[M,I]=Te(Pe(_[E]));if(x.push(M),I==n)break;w.push(I)}let k=x.length>0?x.reduce((E,M)=>E*M,1):0;u.push(w),l.push(k)}return[o(u),l]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}batch_decode([e,r,s]){let[n,o]=this._decode_helper(e,"char"),[a,i]=this._decode_helper(r,"bpe"),[l,u]=this._decode_helper(s,"wp"),d=[],f=[];for(let m=0;m<n.length;++m){let[_,w]=Te([o[m],i[m],u[m]]);d.push([n[m],a[m],l[m]][w]),f.push(_)}return{generated_text:d,scores:f,char_preds:n,bpe_preds:a,wp_preds:l}}static async from_pretrained(...e){let r=await super.from_pretrained(...e),s=await J.from_pretrained("Xenova/gpt2"),n=await J.from_pretrained("Xenova/bert-base-uncased");return r.components={image_processor:r.image_processor,char_tokenizer:r.tokenizer,bpe_tokenizer:s,wp_tokenizer:n},r}async _call(e,r=null){let s=await this.image_processor(e);return r&&(s.labels=this.tokenizer(r).input_ids),s}};var Cm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var Pm=class extends ne{static tokenizer_class=J;static image_processor_class=$e};var en="<image>";function IP(t,e,r,s,n){return`${s.repeat(r*n)}${e}${t}
26
- `}var zm=class extends ne{static tokenizer_class=J;static image_processor_class=$e;static uses_processor_config=!1;async _call(e,r=null,s={}){r||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),r=""),Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let n=this.tokenizer.bos_token,o=this.image_processor.config.image_seq_length,a;r.some(u=>u.includes(en))?a=r.map(u=>{let d=u.replaceAll(en,en.repeat(o)),f=d.lastIndexOf(en),m=f===-1?0:f+en.length;return d.slice(0,m)+n+d.slice(m)+`
27
- `}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=r.map(u=>IP(u,n,o,en,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var KE="<|image|>",CP=/<\|image_\d+\|>/g,Lm=class extends ne{static image_processor_class=$e;static tokenizer_class=J;async _call(e,r=null,{padding:s=!0,truncation:n=!0,num_crops:o=null}={}){Array.isArray(e)||(e=[e]);let a,i;if(r){i=await this.image_processor(r,{num_crops:o});let{num_img_tokens:l}=i,u=e.map((f,m)=>f.split(CP).join(KE.repeat(l[m])));a=this.tokenizer(u,{padding:s,truncation:n});let d=this.tokenizer._tokenizer.token_to_id(KE);a.input_ids.map_(f=>f==d?-f:f)}else a=this.tokenizer(e);return{...a,...i}}};var Nm=class extends ne{static tokenizer_class=J;static image_processor_class=$e;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,image_break_token:u,image_end_token:d,patch_size:f,spatial_merge_size:m}=this.config,_=f*m,w=Math.floor(a/_),x=Math.floor(i/_);r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let k=0;k<r.length;++k){let E=l.repeat(x),M=E+u,I=E+d,T=M.repeat(w-1)+I;r[k]=r[k].replace(l,T)}}let o=r?this.tokenizer(r,s):{};return{...n,...o}}};var $m=class extends ne{static feature_extractor_class=no;async _call(e){return await this.feature_extractor(e)}post_process_speaker_diarization(...e){return this.feature_extractor.post_process_speaker_diarization(...e)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}};var Rm=class extends ne{static image_processor_class=$e;static tokenizer_class=J;async _call(e,r=null,...s){Array.isArray(e)||(e=[e]);let n,o;if(r&&(n=await this.image_processor(r),o=n.image_grid_thw),o){let i=this.image_processor.config.merge_size**2,l=0,u=o.tolist();e=e.map(d=>{for(;d.includes("<|image_pad|>");){let f=Number(u[l++].reduce((m,_)=>m*_,1n));d=d.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(f/i)))}return d.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(e),...n}}};var io=class extends ne{static image_processor_class=$e;async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}};var Il=class extends io{},Um=class extends Il{};var Bm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var Dm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;static uses_processor_config=!0;async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){let a=r.length,{input_features:i}=await this.feature_extractor(r,{...s,max_length:a}),l=Math.round(a/this.config.encoder_ds_factor+1e-4),u=1+Math.ceil(l/this.config.stack_factor);n.audio_token_len=[u],n.audio_values=i;let d=this.config.audio_placeholder;if(!e.includes(d))throw new Error(`The input text does not contain the image token ${d}.`);e=e.replaceAll(d,d.repeat(u))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var Cl="[AUDIO]",PP="[BEGIN_AUDIO]",zP=375;function LP(t,e){let r=[];for(let s=0;s<t.length;s+=e)r.push(t.subarray(s,Math.min(s+e,t.length)));return r}var Fm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;static uses_processor_config=!1;async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){if(!e.includes(Cl))throw new Error(`The input text does not contain the audio token ${Cl}.`);Array.isArray(r)||(r=[r]);let a=e.split(Cl),i=a.length-1;if(i!==r.length)throw new Error(`The number of audio inputs (${r.length}) does not match the number of audio tokens in the text (${i}).`);let l=this.feature_extractor.config.n_samples,u=r.map(w=>LP(w,l)),d=u.map(w=>w.length),f=u.flat(),m=(await Promise.all(f.map(w=>this.feature_extractor(w,s)))).map(w=>w.input_features);n.audio_values=m.length>1?Ee(m,0):m[0];let _=a[0];for(let w=0;w<d.length;++w){_+=PP;for(let x=0;x<d[w];++x)_+=Cl.repeat(zP);_+=a[w+1]}e=_}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var jm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var Gm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var qm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var ut=class{static async from_pretrained(e,r={}){let s=await at(e,Xs,!0,r),{image_processor_type:n,feature_extractor_type:o,processor_class:a}=s;if(a&&Pl[a])return Pl[a].from_pretrained(e,r);if(!n&&!o)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");let i={};if(n){let u=Zs[n.replace(/Fast$/,"")];if(!u)throw new Error(`Unknown image_processor_type: '${n}'.`);i.image_processor=new u(s)}if(o){let u=Zs[o];if(u)i.image_processor=new u(s);else{let d=oo[o];if(!d)throw new Error(`Unknown feature_extractor_type: '${o}'.`);i.feature_extractor=new d(s)}}let l={};return new ne(l,i,null)}};async function NP(t,e){return await at(t,"config.json",!0,e)}function tn(t){let e={},r={};switch(t.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"voxtral":case"smolvlm":case"gemma3n":case"chatterbox":case"mistral3":r=tn(t.text_config);break;case"moondream1":r=tn(t.phi_config);break;case"musicgen":r=tn(t.decoder);break;case"multi_modality":r=tn(t.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":e.num_heads="num_attention_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size";break;case"gpt_oss":case"llama":case"llama4_text":case"nanochat":case"apertus":case"arcee":case"lfm2":case"lfm2_moe":case"smollm3":case"olmo":case"olmo2":case"olmo3":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"cohere2":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size",e.num_attention_heads="num_attention_heads",e.dim_kv="head_dim";break;case"qwen3":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"glm":case"helium":case"ernie4_5":case"hunyuan_v1_dense":case"falcon_h1":case"ministral":case"ministral3":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.dim_kv="head_dim";break;case"openelm":e.num_heads="num_kv_heads",e.num_layers="num_transformer_layers",e.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":e.num_heads="num_heads",e.num_layers="num_layers",e.hidden_size="hidden_size";break;case"bloom":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="hidden_size";break;case"mpt":e.num_heads="n_heads",e.num_layers="n_layers",e.hidden_size="d_model";break;case"exaone":e.num_heads="num_key_value_heads",e.num_layers="num_layers",e.dim_kv="head_dim",e.num_attention_heads="num_attention_heads";break;case"youtu":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.dim_kv="qk_head_dim",e.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":e.num_decoder_layers="num_decoder_layers",e.num_decoder_heads="num_heads",e.decoder_dim_kv="d_kv",e.num_encoder_layers="num_layers",e.num_encoder_heads="num_heads",e.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="d_model",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="d_model";break;case"speecht5":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="hidden_size",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="hidden_size";break;case"trocr":e.num_encoder_layers=e.num_decoder_layers="decoder_layers",e.num_encoder_heads=e.num_decoder_heads="decoder_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="d_model";break;case"musicgen_decoder":e.num_encoder_layers=e.num_decoder_layers="num_hidden_layers",e.num_encoder_heads=e.num_decoder_heads="num_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="hidden_size";break;case"moonshine":e.num_decoder_layers="decoder_num_hidden_layers",e.num_decoder_heads="decoder_num_key_value_heads",e.num_encoder_layers="encoder_num_hidden_layers",e.num_encoder_heads="encoder_num_key_value_heads",e.encoder_hidden_size=e.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":let n=tn(t.decoder),o="num_decoder_layers"in n,a=ot(t,["model_type","is_encoder_decoder"]);return o?(a.num_decoder_layers=n.num_decoder_layers,a.num_decoder_heads=n.num_decoder_heads,a.decoder_hidden_size=n.decoder_hidden_size,a.num_encoder_layers=n.num_encoder_layers,a.num_encoder_heads=n.num_encoder_heads,a.encoder_hidden_size=n.encoder_hidden_size):(a.num_layers=n.num_layers,a.num_heads=n.num_heads,a.hidden_size=n.hidden_size),a}let s={...r,...ot(t,["model_type","multi_query","is_encoder_decoder"])};for(let n in e)s[n]=t[e[n]];return s}function Ll(t,e){if(["lfm2","lfm2_moe"].includes(t.model_type)){let r=e?.prefix??"past_key_values",s=r==="present"?"present":"past",n={},{layer_types:o,num_attention_heads:a,num_key_value_heads:i,hidden_size:l,conv_L_cache:u}=t,d=l/a,f=e?.batch_size??1;for(let m=0;m<o.length;++m)if(o[m]==="full_attention")for(let _ of["key","value"])n[`${r}.${m}.${_}`]=[f,i,0,d];else if(o[m]==="conv")n[`${s}_conv.${m}`]=[f,l,u];else throw new Error(`Unsupported layer type: ${o[m]}`);return n}else if(["granitemoehybrid","falcon_h1"].includes(t.model_type)){let r=e?.prefix??"past_key_values",s=r==="present"?"present":"past",n={},{layer_types:o,num_hidden_layers:a,num_attention_heads:i,num_key_value_heads:l,hidden_size:u,mamba_d_conv:d,mamba_n_heads:f,mamba_d_head:m,mamba_d_state:_,mamba_n_groups:w,mamba_expand:x,mamba_d_ssm:k}=t,E=u/i,M=e?.batch_size??1,I=(k??x*u)+2*w*_;for(let T=0;T<a;++T)if((!o||o[T]==="mamba")&&(n[`${s}_conv.${T}`]=[M,I,d],n[`${s}_ssm.${T}`]=[M,f,m,_]),!o||o[T]==="attention")for(let z of["key","value"])n[`${r}.${T}.${z}`]=[M,l,0,E];return n}return $P(t,e)}function $P(t,{prefix:e="past_key_values",batch_size:r=1}={}){let s={},n=t.normalized_config;if(n.is_encoder_decoder&&"num_encoder_heads"in n&&"num_decoder_heads"in n){let o=n.encoder_dim_kv??n.encoder_hidden_size/n.num_encoder_heads,a=n.decoder_dim_kv??n.decoder_hidden_size/n.num_decoder_heads,i=[r,n.num_encoder_heads,0,o],l=[r,n.num_decoder_heads,0,a];for(let u=0;u<n.num_decoder_layers;++u)s[`${e}.${u}.encoder.key`]=i,s[`${e}.${u}.encoder.value`]=i,s[`${e}.${u}.decoder.key`]=l,s[`${e}.${u}.decoder.value`]=l}else{let o=n.num_heads,a=n.num_layers,i=n.dim_kv??n.hidden_size/(n.num_attention_heads??o);if(n.model_type==="falcon"){let l=[r*o,0,i];for(let u=0;u<a;++u)s[`${e}.${u}.key`]=l,s[`${e}.${u}.value`]=l}else if(n.multi_query){let l=[r*o,0,2*i];for(let u=0;u<a;++u)s[`${e}.${u}.key_value`]=l}else if(n.model_type==="bloom"){let l=[r*o,i,0],u=[r*o,0,i];for(let d=0;d<a;++d)s[`${e}.${d}.key`]=l,s[`${e}.${d}.value`]=u}else if(n.model_type==="openelm")for(let l=0;l<a;++l){let u=[r,o[l],0,i];s[`${e}.${l}.key`]=u,s[`${e}.${l}.value`]=u}else{let l=[r,o,0,i];for(let u=0;u<a;++u)s[`${e}.${u}.key`]=l,s[`${e}.${u}.value`]=l}}return s}var zl=class t{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(e){Object.assign(this,e),this.normalized_config=tn(this)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){s&&!(s instanceof t)&&(s=new t(s));let i=s??await NP(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(i)}},ms=class{static async from_pretrained(...e){return zl.from_pretrained(...e)}};async function YE(t,e,r,s){let n=`${e}${s}.onnx`,o=`${r.subfolder??""}/${n}`;return await Bn(t,o,!0,r,be.IS_NODE_ENV)}async function QE(t,e,r,s,n,o={}){let a=`${e}${r}.onnx`,i=be.IS_NODE_ENV,l=[];if(n){let u;typeof n=="object"?n.hasOwnProperty(a)?u=n[a]:n.hasOwnProperty(e)?u=n[e]:u=!1:u=n;let d=+u;if(d>Di)throw new Error(`The number of external data chunks (${d}) exceeds the maximum allowed value (${Di}).`);for(let f=0;f<d;++f){let m=`${a}_data${f===0?"":"_"+f}`,_=`${s.subfolder??""}/${m}`;l.push(new Promise(async(w,x)=>{let k=await Bn(t,_,!0,s,i);w(k instanceof Uint8Array?{path:m,data:k}:m)}))}}else o.externalData!==void 0&&(l=o.externalData.map(async u=>{if(typeof u.data=="string"){let d=await Bn(t,u.data,!0,s);return{...u,data:d}}return u}));return Promise.all(l)}async function RP(t,e,r,s=!1){let n=r.config?.["transformers.js_config"]??{},o=r.device??n.device;o&&typeof o!="string"&&(o.hasOwnProperty(e)?o=o[e]:(console.warn(`device not specified for "${e}". Using the default device.`),o=null));let a=o??(be.IS_NODE_ENV?"cpu":"wasm"),i=ME(a),l=n.device_config??{};l.hasOwnProperty(a)&&(n={...n,...l[a]});let u=r.dtype??n.dtype;if(typeof u!="string"&&(u&&u.hasOwnProperty(e)?u=u[e]:(u=gd[a]??mt.fp32,console.warn(`dtype not specified for "${e}". Using the default dtype (${u}) for this device (${a}).`))),u===mt.auto){let z=n.dtype;typeof z!="string"&&(z=z?.[e]),z&&z!==mt.auto&&mt.hasOwnProperty(z)?u=z:u=gd[a]??mt.fp32}let d=u;if(wd.hasOwnProperty(d)){if(a==="webgpu"&&!be.IS_NODE_ENV&&d===mt.fp16&&!await IE())throw new Error(`The device (${a}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${d}. Should be one of: ${Object.keys(mt).join(", ")}`);let f=n.kv_cache_dtype,m=f?typeof f=="string"?f:f[d]??"float32":void 0;if(m&&!["float32","float16"].includes(m))throw new Error(`Invalid kv_cache_dtype: ${m}. Should be one of: float32, float16`);let _=wd[d],w={...r.session_options};w.executionProviders??=i;let x=n.free_dimension_overrides;x?w.freeDimensionOverrides??=x:a.startsWith("webnn")&&!w.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${a}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let k=YE(t,e,r,_),E=r.use_external_data_format??n.use_external_data_format,M=await QE(t,e,_,r,E,w);if(M.length>0&&!be.IS_NODE_ENV&&(w.externalData=M),s&&a==="webgpu"&&f!==!1){let z=Ll(r.config,{prefix:"present"});if(Object.keys(z).length>0&&!Kn()){let C={};for(let v in z)C[v]="gpu-buffer";w.preferredOutputLocation=C}}return{buffer_or_path:await k,session_options:w,session_config:{dtype:d,kv_cache_dtype:m,device:a}}}async function bt(t,e,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(e).map(async n=>{let{buffer_or_path:o,session_options:a,session_config:i}=await RP(t,e[n],r,n===s),l=await rl(o,a,i);return[n,l]})))}function JE(t){for(let e in t)nl(t[e])?t[e]=new U(t[e]):typeof t[e]=="object"&&JE(t[e]);return t}async function ce(t,e){let r=UP(t,e);try{let s=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i=a.ort_tensor;return be.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[o,i]})),n=await sl(t,s);return JE(n)}catch(s){let n=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i={type:a.type,dims:a.dims,location:a.location};return i.location!=="gpu-buffer"&&(i.data=a.data),[o,i]}));throw console.error(`An error occurred during model execution: "${s}".`),console.error("Inputs given to model:",n),s}}function UP(t,e){let r=Object.create(null),s=[];for(let a of t.inputNames){let i=e[a];if(!(i instanceof U)){s.push(a);continue}r[a]=Kn()?i.clone():i}if(s.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);let n=Object.keys(e).length,o=t.inputNames.length;if(n>o){let a=Object.keys(e).filter(i=>!t.inputNames.includes(i));console.warn(`WARNING: Too many inputs were provided (${n} > ${o}). The following inputs will be ignored: "${a.join(", ")}".`)}return r}var ze=class{};var F=class extends ze{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},_e=class extends ze{constructor({logits:e}){super(),this.logits=e}},we=class extends ze{constructor({logits:e}){super(),this.logits=e}},Ae=class extends ze{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}},gt=class extends ze{constructor({logits:e}){super(),this.logits=e}};var Nl=class extends ze{constructor({alphas:e}){super(),this.alphas=e}};var jt=class extends Je{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},lo=class extends Je{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},hs=class extends Je{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,r){let s=r;for(let n of this.processors)s=n(e,s);return s}[Symbol.iterator](){return this.processors.values()}},$l=class extends jt{constructor(e){super(),this.bos_token_id=e}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length===1){let n=r[s].data;n.fill(-1/0),n[this.bos_token_id]=0}return r}},Rl=class extends jt{constructor(e,r){super(),this.max_length=e,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length===this.max_length-1){let n=r[s].data;n.fill(-1/0);for(let o of this.eos_token_id)n[o]=0}return r}},rn=class extends jt{constructor(e,r){super(),this.begin_suppress_tokens=e,this.begin_index=r}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length===this.begin_index){let n=r[s].data;for(let o of this.begin_suppress_tokens)n[o]=-1/0}return r}},Ul=class extends jt{constructor(e,r){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]: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=r.length,r.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data;if(n[this.no_timestamps_token_id]=-1/0,e[s].length===this.begin_index-1){n.fill(-1/0),n[this.timestamp_begin]=0;continue}let o=e[s].slice(this.begin_index),a=o.length>=1&&o[o.length-1]>=this.timestamp_begin,i=o.length<2||o[o.length-2]>=this.timestamp_begin;if(a&&(i?n.subarray(this.timestamp_begin).fill(-1/0):n.subarray(0,this.eos_token_id).fill(-1/0)),e[s].length===this.begin_index&&this.max_initial_timestamp_index!==null){let f=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(f+1).fill(-1/0)}let l=kp(n),u=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((f,m)=>f+m)),d=Te(l.subarray(0,this.timestamp_begin))[0];u>d&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},Bl=class extends jt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let r=e.length,s=[];for(let o=0;o<r+1-this.no_repeat_ngram_size;++o){let a=[];for(let i=0;i<this.no_repeat_ngram_size;++i)a.push(e[o+i]);s.push(a.map(Number))}let n=new Map;for(let o of s){let a=o.slice(0,o.length-1),i=JSON.stringify(a),l=n.get(i)??[];l.push(o[o.length-1]),n.set(i,l)}return n}getGeneratedNgrams(e,r){let s=r.slice(r.length+1-this.no_repeat_ngram_size,r.length);return e.get(JSON.stringify(s.map(Number)))??[]}calcBannedNgramTokens(e){let r=[];if(e.length+1<this.no_repeat_ngram_size)return r;{let s=this.getNgrams(e);return this.getGeneratedNgrams(s,e)}}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data,o=this.calcBannedNgramTokens(e[s]);for(let a of o)n[a]=-1/0}return r}},Dl=class extends jt{constructor(e){super(),this.penalty=e}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data;for(let o of new Set(e[s])){let a=Number(o);n[a]<0?n[a]*=this.penalty:n[a]/=this.penalty}}return r}},Fl=class extends jt{constructor(e,r){super(),this.min_length=e,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length<this.min_length){let n=r[s].data;for(let o of this.eos_token_id)n[o]=-1/0}return r}},jl=class extends jt{constructor(e,r,s){super(),this.prompt_length_to_skip=e,this.min_new_tokens=r,this.eos_token_id=Array.isArray(s)?s:[s]}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length-this.prompt_length_to_skip<this.min_new_tokens){let o=r[s].data;for(let a of this.eos_token_id)o[a]=-1/0}return r}},Gl=class extends jt{constructor(e,r){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data,o=e[s];for(let a of this.bad_words_ids){if(o.length<a.length-1)continue;let i=!0;for(let l=1;l<=a.length-1;++l)if(a.at(-l-1)!=o.at(-l)){i=!1;break}i&&(n[a.at(-1)]=-1/0)}}return r}},ql=class extends jt{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,r){if(r.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${r.dims[0]} for the logits and ${e.length} for the input ids.`);let s=e.length,n=r.slice([0,s],null),o=r.slice([s,r.dims[0]],null);for(let a=0;a<o.data.length;++a)o.data[a]+=(n.data[a]-o.data[a])*this.guidance_scale;return o}},Wl=class extends lo{constructor(e){if(super(),typeof e!="number"||e<=0){let r=`\`temperature\` (=${e}) must be a strictly positive float, otherwise your next token scores will be invalid.`;e===0&&(r+=" If you're looking for greedy decoding strategies, set `do_sample=false`.")}this.temperature=e}_call(e,r){let s=r.data;for(let n=0;n<s.length;++n)s[n]/=this.temperature;return r}},ZE=class extends lo{constructor(e,{filter_value:r=-1/0,min_tokens_to_keep:s=1}={}){if(super(),e<0||e>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(s)||s<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${s}`);this.top_p=e,this.filter_value=r,this.min_tokens_to_keep=s}},eA=class extends lo{constructor(e,{filter_value:r=-1/0,min_tokens_to_keep:s=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,s),this.filter_value=r}};var sn=class{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,ot(e,Object.getOwnPropertyNames(this)))}};var nn=class extends Je{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},Vl=class t extends Je{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof nn&&(e=[e]),this.criteria.push(...e)}_call(e,r){let s=new Array(e.length).fill(!1);for(let n of this.criteria){let o=n(e,r);for(let a=0;a<s.length;++a)s[a]||=o[a]}return s}[Symbol.iterator](){return this.criteria.values()}},Hl=class extends nn{constructor(e,r=null){super(),this.max_length=e,this.max_position_embeddings=r}_call(e){return e.map(r=>r.length>=this.max_length)}},Xl=class extends nn{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,r){return e.map(s=>{let n=s.at(-1);return this.eos_token_id.some(o=>n==o)})}},tA=class extends nn{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,r){return new Array(e.length).fill(this.interrupted)}};var _s=class extends Je{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,r){let s=e.dims.at(-1),n=e.data;if(r===-1)n=n.slice(-s);else{let o=r*s;n=n.slice(o,o+s)}return n}randomSelect(e){let r=0;for(let n=0;n<e.length;++n)r+=e[n];let s=Math.random()*r;for(let n=0;n<e.length;++n)if(s-=e[n],s<=0)return n;return 0}static getSampler(e){if(e.do_sample)return new Vm(e);if(e.num_beams>1)return new Hm(e);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 Wm(e)}},Wm=class extends _s{async sample(e){let r=Te(e.data)[1];return[[BigInt(r),0]]}},Vm=class extends _s{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await Yt(e,r),o=Pe(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},Hm=class extends _s{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await Yt(e,r),o=Pe(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var co=null;function sA(t){co=t}function Xm(t){if(t instanceof U)return t;if(t.length===0)throw Error("items must be non-empty");if(Array.isArray(t[0])){if(t.some(e=>e.length!==t[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new U("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new U("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function Km(t){return new U("bool",[t],[1])}var H={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15},rA={[H.DecoderOnly]:{can_generate:!0,forward:Tt,prepare_inputs:uo},[H.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Tt,prepare_inputs:uo},[H.Seq2Seq]:{can_generate:!0,forward:Kl,prepare_inputs:po},[H.Vision2Seq]:{can_generate:!0,forward:Kl,prepare_inputs:po},[H.Musicgen]:{can_generate:!0,forward:Kl},[H.EncoderDecoder]:{can_generate:!1,forward:Kl},[H.ImageTextToText]:{can_generate:!0,forward:FP,prepare_inputs:Yl},[H.AudioTextToText]:{can_generate:!0,forward:DP,prepare_inputs:Yl},[H.Phi3V]:{can_generate:!0,prepare_inputs:Yl},[H.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Yl},[H.MultiModality]:{can_generate:!0},[H.AutoEncoder]:{can_generate:!1,forward:BP},[H.Chatterbox]:{can_generate:!0,forward:Gt},default:{can_generate:!1,forward:Gt}},ws=new Map,Ql=new Map,gs=new Map,y=class extends Je{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,r,s){super(),this.config=e,this.sessions=r,this.configs=s;let n=gs.get(this.constructor),o=ws.get(n),a=rA[o]??rA.default;this.can_generate=a.can_generate,this._forward=a.forward,this._prepare_inputs_for_generation=a.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let e=[];for(let r of Object.values(this.sessions))e.push(r.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:u=null,dtype:d=null,use_external_data_format:f=null,session_options:m={}}={}){let _={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:u,dtype:d,use_external_data_format:f,session_options:m},w=gs.get(this),x=ws.get(w);s=_.config=await ms.from_pretrained(e,_);let k;if(x===H.DecoderOnly)k=await Promise.all([bt(e,{model:_.model_file_name??"model"},_,"model"),gr(e,{generation_config:"generation_config.json"},_)]);else if(x===H.Seq2Seq||x===H.Vision2Seq)k=await Promise.all([bt(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},_,"decoder_model_merged"),gr(e,{generation_config:"generation_config.json"},_)]);else if(x===H.MaskGeneration)k=await Promise.all([bt(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},_)]);else if(x===H.EncoderDecoder)k=await Promise.all([bt(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},_,"decoder_model_merged")]);else if(x===H.ImageTextToText){let E={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};s.is_encoder_decoder&&(E.model="encoder_model"),k=await Promise.all([bt(e,E,_,"decoder_model_merged"),gr(e,{generation_config:"generation_config.json"},_)])}else if(x===H.AudioTextToText){let E={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};k=await Promise.all([bt(e,E,_,"decoder_model_merged"),gr(e,{generation_config:"generation_config.json"},_)])}else if(x===H.ImageAudioTextToText){let E={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};k=await Promise.all([bt(e,E,_),gr(e,{generation_config:"generation_config.json"},_)])}else if(x===H.Musicgen)k=await Promise.all([bt(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},_,"decoder_model_merged"),gr(e,{generation_config:"generation_config.json"},_)]);else if(x===H.MultiModality)k=await Promise.all([bt(e,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},_,"model"),gr(e,{generation_config:"generation_config.json"},_)]);else if(x===H.Phi3V)k=await Promise.all([bt(e,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},_,"model"),gr(e,{generation_config:"generation_config.json"},_)]);else if(x===H.Chatterbox)k=await Promise.all([bt(e,{embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"},_,"model"),gr(e,{generation_config:"generation_config.json"},_)]);else if(x===H.AutoEncoder)k=await Promise.all([bt(e,{encoder_model:"encoder_model",decoder_model:"decoder_model"},_)]);else if(x===H.Supertonic)k=await Promise.all([bt(e,{text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"},_)]);else{if(x===void 0){let E=w??s?.model_type;E!=="custom"&&console.warn(`Model type for '${E}' not found, assuming encoder-only architecture. Please report this at ${Hs}.`)}k=await Promise.all([bt(e,{model:_.model_file_name??"model"},_)])}return new this(s,...k)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,r,s=null){let n=new hs;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new Dl(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new Bl(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new Gl(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new Fl(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&n.push(new jl(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new $l(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new Rl(e.max_length,e.forced_eos_token_id)),e.begin_suppress_tokens!==null){let o=r>1||e.forced_bos_token_id===null?r:r+1;n.push(new rn(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new ql(e.guidance_scale)),e.temperature===0&&e.do_sample&&(console.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&n.push(new Wl(e.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(e,r,s=sn){let n={...this.config};for(let a of["decoder","generator","text_config"])a in n&&Object.assign(n,n[a]);let o=new s(n);return Object.assign(o,this.generation_config??{}),e&&Object.assign(o,e),r&&Object.assign(o,ot(r,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,r=null){let s=new Vl;return e.max_length!==null&&s.push(new Hl(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new Xl(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[co.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,co.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,co.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,co.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=gs.get(this.constructor),s=new Set,n=this.config.model_type;for(let a of e){let i=a?.get(n);i&&s.add(i)}let o=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(o+=` Please use the following class instead: ${[...s].join(", ")}`),Error(o)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:r,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=this.getPastKeyValues(r,s.past_key_values),s.input_ids=new U("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in s:s.attention_mask=Ee([s.attention_mask,it([s.attention_mask.dims[0],1])],1),s.position_ids=null,s}_prepare_model_inputs({inputs:e,bos_token_id:r,model_kwargs:s}){let n=ot(s,this.forward_params),o=this.main_input_name;if(o in n){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[o]=e;return{inputs_tensor:n[o],model_inputs:n,model_input_name:o}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:r,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:a,pixel_values:i,attention_mask:l,...u}=r,d=await this._prepare_inputs_embeds(r);r={...u,...ot(d,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await Gt(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=Ee([o,Qn(o,0)],0),"attention_mask"in r&&(r.attention_mask=Ee([r.attention_mask,Ed(r.attention_mask)],0));else if(r.decoder_input_ids){let a=Xm(r.decoder_input_ids).dims[0];if(a!==o.dims[0]){if(o.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${o.dims[0]}) than the decoder inputs (${a}).`);o=Ee(Array.from({length:a},()=>o),0)}}return r.encoder_outputs=o,r}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:r,model_kwargs:s,decoder_start_token_id:n,bos_token_id:o,generation_config:a}){let{decoder_input_ids:i,...l}=s;if(!(i instanceof U)){if(i)Array.isArray(i[0])||(i=Array.from({length:e},()=>i));else if(n??=o,this.config.model_type==="musicgen")i=Array.from({length:e*this.config.decoder.num_codebooks},()=>[n]);else if(Array.isArray(n)){if(n.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${n.length}`);i=n}else i=Array.from({length:e},()=>[n]);i=Xm(i)}return s.decoder_attention_mask=ll(i),{input_ids:i,model_inputs:l}}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,streamer:o=null,...a}){this._validate_model_class(),r=this._prepare_generation_config(r,a);let{inputs_tensor:i,model_inputs:l,model_input_name:u}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),d=this.config.is_encoder_decoder;d&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:u,generation_config:r})));let f;d?{input_ids:f,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[u].dims.at(0),model_input_name:u,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):f=l[u];let m=f.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=m+r.max_new_tokens);let _=this._get_logits_processor(r,m,s),w=this._get_stopping_criteria(r,n),x=l[u].dims.at(0),k=_s.getSampler(r),E=new Array(x).fill(0),M=f.tolist();o&&o.put(M);let I,T={},z={};for(;;){if(l=this.prepare_inputs_for_generation(M,l,r),I=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){let K=this.getAttentions(I);for(let Y in K)Y in T||(T[Y]=[]),T[Y].push(K[Y])}else this._return_dict_in_generate_keys&&Object.assign(z,ot(I,this._return_dict_in_generate_keys));let G=I.logits.slice(null,-1,null).to("float32"),X=_(M,G),V=[];for(let K=0;K<X.dims.at(0);++K){let Y=X[K],B=await k(Y);for(let[P,se]of B){let ie=BigInt(P);E[K]+=se,M[K].push(ie),V.push([ie]);break}}if(o&&o.put(V),w(M).every(K=>K))break;l=this._update_model_kwargs_for_generation({generated_input_ids:V,outputs:I,model_inputs:l,is_encoder_decoder:d})}o&&o.end();let C=this.getPastKeyValues(I,l.past_key_values,!0),v=new U("int64",M.flat(),[M.length,M[0].length]);if(r.return_dict_in_generate)return{sequences:v,past_key_values:C,...T,...z};for(let G of Object.values(I))G.location==="gpu-buffer"&&G.dispose();return v}getPastKeyValues(e,r,s=!1){let n=Object.create(null);for(let o in e)if(o.startsWith("present")){let a=o.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present","past_key_values"),i=o.includes("encoder");if(i&&r?n[a]=r[a]:n[a]=e[o],r&&(!i||s)){let l=r[a];l.location==="gpu-buffer"&&l.dispose()}}return n}getAttentions(e){let r={};for(let s of["cross_attentions","encoder_attentions","decoder_attentions"])for(let n in e)n.startsWith(s)&&(s in r||(r[s]=[]),r[s].push(e[n]));return r}addPastKeyValues(e,r){if(r)Object.assign(e,r);else{let s=this.sessions.decoder_model_merged??this.sessions.model,n=(e[this.main_input_name]??e.attention_mask)?.dims?.[0]??1,o=s?.config?.kv_cache_dtype??"float32",a=o==="float16"?Ws.float16:Ws.float32,i=Ll(this.config,{batch_size:n});for(let l in i){let u=i[l].reduce((d,f)=>d*f,1);e[l]=new U(o,new a(u),i[l])}}}async encode_image({pixel_values:e}){return(await ce(this.sessions.vision_encoder,{pixel_values:e})).image_features}async encode_text({input_ids:e}){return(await ce(this.sessions.embed_tokens,{input_ids:e})).inputs_embeds}async encode_audio({audio_values:e}){return(await ce(this.sessions.audio_encoder,{audio_values:e})).audio_features}};async function Kl(t,e){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,...o}=e;if(!r){let a=ot(e,t.sessions.model.inputNames);r=(await Gt(t,a)).last_hidden_state}return o.input_ids=n,o.encoder_hidden_states=r,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(o.encoder_attention_mask=e.attention_mask),await Tt(t,o,!0)}async function Gt(t,e){let r=t.sessions.model,s=ot(e,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!s.inputs_embeds){if(!e.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");s.inputs_embeds=await t.encode_text({input_ids:e.input_ids})}if(r.inputNames.includes("token_type_ids")&&!s.token_type_ids){if(!s.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");s.token_type_ids=Ed(s.input_ids)}if(r.inputNames.includes("pixel_mask")&&!s.pixel_mask){if(!s.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let n=s.pixel_values.dims;s.pixel_mask=it([n[0],n[2],n[3]])}return await ce(r,s)}async function BP(t,e){let r=await t.encode(e);return await t.decode(r)}async function Tt(t,e,r=!1){let s=t.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...o}=e;if(s.inputNames.includes("use_cache_branch")&&(o.use_cache_branch=Km(!!n)),s.inputNames.includes("position_ids")&&o.attention_mask&&!o.position_ids){let i=["paligemma","gemma3_text","gemma3"].includes(t.config.model_type)?1:0;o.position_ids=jP(o,n,i)}t.addPastKeyValues(o,n);let a=ot(o,s.inputNames);return await ce(s,a)}async function nA(t,{encode_function:e,merge_function:r,modality_input_name:s,modality_output_name:n,input_ids:o=null,attention_mask:a=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:u=null,generation_config:d=null,logits_processor:f=null,...m}){let _=m[s];if(!l){if(l=await t.encode_text({input_ids:o,...m}),_&&o.dims[1]!==1){let x=await e({[s]:_,...m});({inputs_embeds:l,attention_mask:a}=r({[n]:x,inputs_embeds:l,input_ids:o,attention_mask:a}))}else if(u&&_&&o.dims[1]===1){let x=o.dims[1],k=Object.values(u)[0].dims.at(-2);a=Ee([it([o.dims[0],k]),a.slice(null,[a.dims[1]-x,a.dims[1]])],1)}}if(!i&&t.config.model_type==="qwen2_vl"){let{image_grid_thw:x,video_grid_thw:k}=m;[i]=t.get_rope_index(o,x,k,a)}return await Tt(t,{inputs_embeds:l,past_key_values:u,attention_mask:a,position_ids:i,generation_config:d,logits_processor:f},!0)}async function DP(t,e){return await nA(t,{...e,modality_input_name:"audio_values",modality_output_name:"audio_features",encode_function:t.encode_audio.bind(t),merge_function:t._merge_input_ids_with_audio_features.bind(t)})}async function FP(t,e){return await nA(t,{...e,modality_input_name:"pixel_values",modality_output_name:"image_features",encode_function:t.encode_image.bind(t),merge_function:t._merge_input_ids_with_image_features.bind(t)})}function Ym(t,e=0){let[r,s]=t.dims,n=t.data,o=new BigInt64Array(n.length);for(let a=0;a<r;++a){let i=a*s,l=BigInt(e);for(let u=0;u<s;++u){let d=i+u;n[d]===0n?o[d]=BigInt(1):(o[d]=l,l+=n[d])}}return{data:o,dims:t.dims}}function jP(t,e=null,r=0){let{input_ids:s,inputs_embeds:n,attention_mask:o}=t,{data:a,dims:i}=Ym(o,r),l=new U("int64",a,i);if(e){let u=-(s??n).dims.at(1);l=l.slice(null,[u,null])}return l}function uo(t,e,r,s){let n=r.past_key_values?Object.values(r.past_key_values)[0].dims.at(-2):0;if(!r.attention_mask){let o;for(let a of["input_ids","inputs_embeds","position_ids"])if(r[a]){o=r[a].dims;break}if(!o)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=it([o[0],n+o[1]])}if(r.past_key_values){let{input_ids:o,attention_mask:a}=r;a&&a.dims[1]>o.dims[1]||n<o.dims[1]&&(r.input_ids=o.slice(null,[n,null]))}return r}function po(t,e,r,s){return r.past_key_values&&(e=e.map(n=>[n.at(-1)])),{...r,decoder_input_ids:Xm(e)}}function Yl(t,...e){return t.config.is_encoder_decoder?po(t,...e):uo(t,...e)}function oA({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n}){let o=s.tolist().map(u=>u.reduce((d,f,m)=>(f==t&&d.push(m),d),[])),a=o.reduce((u,d)=>u+d.length,0),i=r.dims[0];if(a!==i)throw new Error(`Number of tokens and features do not match: tokens: ${a}, features ${i}`);let l=0;for(let u=0;u<o.length;++u){let d=o[u],f=e[u];for(let m=0;m<d.length;++m)f[d[m]].data.set(r[l++].data)}return{inputs_embeds:e,attention_mask:n}}function ar({image_token_id:t,inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return oA({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}function Jl({audio_token_id:t,inputs_embeds:e,audio_features:r,input_ids:s,attention_mask:n}){return oA({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}async function gr(t,e,r){return Object.fromEntries(await Promise.all(Object.keys(e).map(async s=>{let n=await at(t,e[s],!1,r);return[s,n]})))}var fi={};Ps(fi,{ASTForAudioClassification:()=>ah,ASTModel:()=>oh,ASTPreTrainedModel:()=>ho,AlbertForMaskedLM:()=>eh,AlbertForQuestionAnswering:()=>Zm,AlbertForSequenceClassification:()=>Jm,AlbertModel:()=>Qm,AlbertPreTrainedModel:()=>xs,ApertusForCausalLM:()=>rh,ApertusModel:()=>th,ApertusPreTrainedModel:()=>fo,ArceeForCausalLM:()=>nh,ArceeModel:()=>sh,ArceePreTrainedModel:()=>mo,BartForConditionalGeneration:()=>lh,BartForSequenceClassification:()=>ch,BartModel:()=>ih,BartPretrainedModel:()=>on,BeitForImageClassification:()=>ph,BeitModel:()=>uh,BeitPreTrainedModel:()=>_o,BertForMaskedLM:()=>fh,BertForQuestionAnswering:()=>_h,BertForSequenceClassification:()=>mh,BertForTokenClassification:()=>hh,BertModel:()=>dh,BertPreTrainedModel:()=>Cr,BlenderbotForConditionalGeneration:()=>wh,BlenderbotModel:()=>gh,BlenderbotPreTrainedModel:()=>go,BlenderbotSmallForConditionalGeneration:()=>yh,BlenderbotSmallModel:()=>xh,BlenderbotSmallPreTrainedModel:()=>wo,BloomForCausalLM:()=>vh,BloomModel:()=>bh,BloomPreTrainedModel:()=>xo,CLIPModel:()=>Ih,CLIPPreTrainedModel:()=>ir,CLIPSegForImageSegmentation:()=>Nh,CLIPSegModel:()=>Lh,CLIPSegPreTrainedModel:()=>Eo,CLIPTextModel:()=>Ch,CLIPTextModelWithProjection:()=>ko,CLIPVisionModel:()=>Ph,CLIPVisionModelWithProjection:()=>zh,CamembertForMaskedLM:()=>Eh,CamembertForQuestionAnswering:()=>Th,CamembertForSequenceClassification:()=>Ah,CamembertForTokenClassification:()=>Mh,CamembertModel:()=>kh,CamembertPreTrainedModel:()=>Pr,ChatterboxModel:()=>yo,ChatterboxPreTrainedModel:()=>Zl,ChineseCLIPModel:()=>Sh,ChineseCLIPPreTrainedModel:()=>ec,ClapAudioModelWithProjection:()=>vo,ClapModel:()=>Oh,ClapPreTrainedModel:()=>an,ClapTextModelWithProjection:()=>bo,CodeGenForCausalLM:()=>Rh,CodeGenModel:()=>$h,CodeGenPreTrainedModel:()=>Ao,Cohere2ForCausalLM:()=>Fh,Cohere2Model:()=>Dh,Cohere2PreTrainedModel:()=>To,CohereForCausalLM:()=>Bh,CohereModel:()=>Uh,CoherePreTrainedModel:()=>Mo,ConvBertForMaskedLM:()=>Gh,ConvBertForQuestionAnswering:()=>Vh,ConvBertForSequenceClassification:()=>qh,ConvBertForTokenClassification:()=>Wh,ConvBertModel:()=>jh,ConvBertPreTrainedModel:()=>zr,ConvNextForImageClassification:()=>Xh,ConvNextModel:()=>Hh,ConvNextPreTrainedModel:()=>So,ConvNextV2ForImageClassification:()=>Yh,ConvNextV2Model:()=>Kh,ConvNextV2PreTrainedModel:()=>Oo,DFineForObjectDetection:()=>e_,DFineModel:()=>Zh,DFinePreTrainedModel:()=>Co,DINOv3ConvNextModel:()=>E_,DINOv3ConvNextPreTrainedModel:()=>ic,DINOv3ViTModel:()=>A_,DINOv3ViTPreTrainedModel:()=>lc,DPTForDepthEstimation:()=>z_,DPTModel:()=>P_,DPTPreTrainedModel:()=>Ro,DacDecoderModel:()=>zo,DacDecoderOutput:()=>rc,DacEncoderModel:()=>Po,DacEncoderOutput:()=>tc,DacModel:()=>t_,DacPreTrainedModel:()=>ln,DebertaForMaskedLM:()=>s_,DebertaForQuestionAnswering:()=>a_,DebertaForSequenceClassification:()=>n_,DebertaForTokenClassification:()=>o_,DebertaModel:()=>r_,DebertaPreTrainedModel:()=>Lr,DebertaV2ForMaskedLM:()=>l_,DebertaV2ForQuestionAnswering:()=>p_,DebertaV2ForSequenceClassification:()=>c_,DebertaV2ForTokenClassification:()=>u_,DebertaV2Model:()=>i_,DebertaV2PreTrainedModel:()=>Nr,DecisionTransformerModel:()=>d_,DecisionTransformerPreTrainedModel:()=>sc,DeiTForImageClassification:()=>m_,DeiTModel:()=>f_,DeiTPreTrainedModel:()=>Lo,DepthAnythingForDepthEstimation:()=>h_,DepthAnythingPreTrainedModel:()=>nc,DepthProForDepthEstimation:()=>__,DepthProPreTrainedModel:()=>oc,DetrForObjectDetection:()=>w_,DetrForSegmentation:()=>x_,DetrModel:()=>g_,DetrObjectDetectionOutput:()=>un,DetrPreTrainedModel:()=>cn,DetrSegmentationOutput:()=>ac,Dinov2ForImageClassification:()=>b_,Dinov2Model:()=>y_,Dinov2PreTrainedModel:()=>No,Dinov2WithRegistersForImageClassification:()=>k_,Dinov2WithRegistersModel:()=>v_,Dinov2WithRegistersPreTrainedModel:()=>$o,DistilBertForMaskedLM:()=>I_,DistilBertForQuestionAnswering:()=>O_,DistilBertForSequenceClassification:()=>T_,DistilBertForTokenClassification:()=>S_,DistilBertModel:()=>M_,DistilBertPreTrainedModel:()=>$r,DonutSwinModel:()=>C_,DonutSwinPreTrainedModel:()=>cc,EdgeTamModel:()=>_y,EfficientNetForImageClassification:()=>N_,EfficientNetModel:()=>L_,EfficientNetPreTrainedModel:()=>Uo,ElectraForMaskedLM:()=>R_,ElectraForQuestionAnswering:()=>D_,ElectraForSequenceClassification:()=>U_,ElectraForTokenClassification:()=>B_,ElectraModel:()=>$_,ElectraPreTrainedModel:()=>Rr,Ernie4_5ForCausalLM:()=>j_,Ernie4_5Model:()=>F_,Ernie4_5PretrainedModel:()=>Bo,EsmForMaskedLM:()=>q_,EsmForSequenceClassification:()=>W_,EsmForTokenClassification:()=>V_,EsmModel:()=>G_,EsmPreTrainedModel:()=>ys,ExaoneForCausalLM:()=>X_,ExaoneModel:()=>H_,ExaonePreTrainedModel:()=>Do,FalconForCausalLM:()=>Y_,FalconH1ForCausalLM:()=>J_,FalconH1Model:()=>Q_,FalconH1PreTrainedModel:()=>jo,FalconModel:()=>K_,FalconPreTrainedModel:()=>Fo,FastViTForImageClassification:()=>eg,FastViTModel:()=>Z_,FastViTPreTrainedModel:()=>Go,Florence2ForConditionalGeneration:()=>tg,Florence2PreTrainedModel:()=>uc,GLPNForDepthEstimation:()=>pg,GLPNModel:()=>ug,GLPNPreTrainedModel:()=>Ko,GPT2LMHeadModel:()=>bg,GPT2Model:()=>yg,GPT2PreTrainedModel:()=>ea,GPTBigCodeForCausalLM:()=>fg,GPTBigCodeModel:()=>dg,GPTBigCodePreTrainedModel:()=>Yo,GPTJForCausalLM:()=>kg,GPTJModel:()=>vg,GPTJPreTrainedModel:()=>ta,GPTNeoForCausalLM:()=>hg,GPTNeoModel:()=>mg,GPTNeoPreTrainedModel:()=>Qo,GPTNeoXForCausalLM:()=>gg,GPTNeoXModel:()=>_g,GPTNeoXPreTrainedModel:()=>Jo,Gemma2ForCausalLM:()=>og,Gemma2Model:()=>ng,Gemma2PreTrainedModel:()=>Wo,Gemma3ForCausalLM:()=>ig,Gemma3Model:()=>ag,Gemma3PreTrainedModel:()=>Vo,Gemma3nForConditionalGeneration:()=>Ho,Gemma3nPreTrainedModel:()=>pc,GemmaForCausalLM:()=>sg,GemmaModel:()=>rg,GemmaPreTrainedModel:()=>qo,GlmForCausalLM:()=>cg,GlmModel:()=>lg,GlmPreTrainedModel:()=>Xo,GptOssForCausalLM:()=>xg,GptOssModel:()=>wg,GptOssPreTrainedModel:()=>Zo,GraniteForCausalLM:()=>Ag,GraniteModel:()=>Eg,GraniteMoeHybridForCausalLM:()=>Tg,GraniteMoeHybridModel:()=>Mg,GraniteMoeHybridPreTrainedModel:()=>sa,GranitePreTrainedModel:()=>ra,GroundingDinoForObjectDetection:()=>Sg,GroundingDinoPreTrainedModel:()=>dc,GroupViTModel:()=>Og,GroupViTPreTrainedModel:()=>fc,HeliumForCausalLM:()=>Cg,HeliumModel:()=>Ig,HeliumPreTrainedModel:()=>na,HieraForImageClassification:()=>zg,HieraModel:()=>Pg,HieraPreTrainedModel:()=>oa,HubertForCTC:()=>Dg,HubertForSequenceClassification:()=>Fg,HubertModel:()=>Bg,HubertPreTrainedModel:()=>Ug,HunYuanDenseV1ForCausalLM:()=>Gg,HunYuanDenseV1Model:()=>jg,HunYuanDenseV1PreTrainedModel:()=>aa,IJepaForImageClassification:()=>Vg,IJepaModel:()=>Wg,IJepaPreTrainedModel:()=>ia,Idefics3ForConditionalGeneration:()=>hc,Idefics3PreTrainedModel:()=>mc,JAISLMHeadModel:()=>Xg,JAISModel:()=>Hg,JAISPreTrainedModel:()=>la,JinaCLIPModel:()=>Kg,JinaCLIPPreTrainedModel:()=>pn,JinaCLIPTextModel:()=>ca,JinaCLIPVisionModel:()=>Yg,Lfm2ForCausalLM:()=>Jg,Lfm2Model:()=>Qg,Lfm2MoeForCausalLM:()=>ew,Lfm2MoeModel:()=>Zg,Lfm2MoePreTrainedModel:()=>pa,Lfm2PreTrainedModel:()=>ua,LiteWhisperForConditionalGeneration:()=>T0,Llama4ForCausalLM:()=>sw,Llama4PreTrainedModel:()=>_c,LlamaForCausalLM:()=>rw,LlamaModel:()=>tw,LlamaPreTrainedModel:()=>da,LlavaForConditionalGeneration:()=>dn,LlavaOnevisionForConditionalGeneration:()=>dn,LlavaPreTrainedModel:()=>gc,LlavaQwen2ForCausalLM:()=>ow,LongT5ForConditionalGeneration:()=>iw,LongT5Model:()=>aw,LongT5PreTrainedModel:()=>fa,M2M100ForConditionalGeneration:()=>cw,M2M100Model:()=>lw,M2M100PreTrainedModel:()=>ma,MBartForCausalLM:()=>gw,MBartForConditionalGeneration:()=>hw,MBartForSequenceClassification:()=>_w,MBartModel:()=>mw,MBartPreTrainedModel:()=>bs,MPNetForMaskedLM:()=>tx,MPNetForQuestionAnswering:()=>nx,MPNetForSequenceClassification:()=>rx,MPNetForTokenClassification:()=>sx,MPNetModel:()=>ex,MPNetPreTrainedModel:()=>Ur,MT5ForConditionalGeneration:()=>lx,MT5Model:()=>ix,MT5PreTrainedModel:()=>Ma,MarianMTModel:()=>pw,MarianModel:()=>uw,MarianPreTrainedModel:()=>ha,MaskFormerForInstanceSegmentation:()=>fw,MaskFormerModel:()=>dw,MaskFormerPreTrainedModel:()=>_a,Metric3DForDepthEstimation:()=>ww,Metric3DPreTrainedModel:()=>wc,Metric3Dv2ForDepthEstimation:()=>xw,Metric3Dv2PreTrainedModel:()=>xc,MgpstrForSceneTextRecognition:()=>yw,MgpstrModelOutput:()=>yc,MgpstrPreTrainedModel:()=>bc,MimiDecoderModel:()=>wa,MimiDecoderOutput:()=>kc,MimiEncoderModel:()=>ga,MimiEncoderOutput:()=>vc,MimiModel:()=>bw,MimiPreTrainedModel:()=>fn,MistralForCausalLM:()=>kw,MistralModel:()=>vw,MistralPreTrainedModel:()=>xa,MobileBertForMaskedLM:()=>Aw,MobileBertForQuestionAnswering:()=>Tw,MobileBertForSequenceClassification:()=>Mw,MobileBertModel:()=>Ew,MobileBertPreTrainedModel:()=>vs,MobileLLMForCausalLM:()=>Ow,MobileLLMModel:()=>Sw,MobileLLMPreTrainedModel:()=>ya,MobileNetV1ForImageClassification:()=>Cw,MobileNetV1ForSemanticSegmentation:()=>Pw,MobileNetV1Model:()=>Iw,MobileNetV1PreTrainedModel:()=>mn,MobileNetV2ForImageClassification:()=>Lw,MobileNetV2ForSemanticSegmentation:()=>Nw,MobileNetV2Model:()=>zw,MobileNetV2PreTrainedModel:()=>hn,MobileNetV3ForImageClassification:()=>Rw,MobileNetV3ForSemanticSegmentation:()=>Uw,MobileNetV3Model:()=>$w,MobileNetV3PreTrainedModel:()=>_n,MobileNetV4ForImageClassification:()=>Dw,MobileNetV4ForSemanticSegmentation:()=>Fw,MobileNetV4Model:()=>Bw,MobileNetV4PreTrainedModel:()=>gn,MobileViTForImageClassification:()=>Gw,MobileViTModel:()=>jw,MobileViTPreTrainedModel:()=>ba,MobileViTV2ForImageClassification:()=>Ww,MobileViTV2Model:()=>qw,MobileViTV2PreTrainedModel:()=>va,ModernBertDecoderForCausalLM:()=>Qw,ModernBertDecoderModel:()=>Yw,ModernBertDecoderPreTrainedModel:()=>ka,ModernBertForMaskedLM:()=>Hw,ModernBertForSequenceClassification:()=>Xw,ModernBertForTokenClassification:()=>Kw,ModernBertModel:()=>Vw,ModernBertPreTrainedModel:()=>ks,Moondream1ForConditionalGeneration:()=>nw,MoonshineForConditionalGeneration:()=>Zw,MoonshineModel:()=>Jw,MoonshinePreTrainedModel:()=>Ea,MptForCausalLM:()=>ax,MptModel:()=>ox,MptPreTrainedModel:()=>Aa,MultiModalityCausalLM:()=>cx,MultiModalityPreTrainedModel:()=>Ec,MusicgenForCausalLM:()=>px,MusicgenForConditionalGeneration:()=>Sa,MusicgenModel:()=>ux,MusicgenPreTrainedModel:()=>Ta,NanoChatForCausalLM:()=>fx,NanoChatModel:()=>dx,NanoChatPreTrainedModel:()=>Oa,NeoBertForMaskedLM:()=>hx,NeoBertForQuestionAnswering:()=>wx,NeoBertForSequenceClassification:()=>_x,NeoBertForTokenClassification:()=>gx,NeoBertModel:()=>mx,NeoBertPreTrainedModel:()=>Br,NomicBertModel:()=>xx,NomicBertPreTrainedModel:()=>Ac,OPTForCausalLM:()=>Ox,OPTModel:()=>Sx,OPTPreTrainedModel:()=>La,Olmo2ForCausalLM:()=>kx,Olmo2Model:()=>vx,Olmo2PreTrainedModel:()=>Ca,Olmo3ForCausalLM:()=>Ax,Olmo3Model:()=>Ex,Olmo3PreTrainedModel:()=>Pa,OlmoForCausalLM:()=>bx,OlmoModel:()=>yx,OlmoPreTrainedModel:()=>Ia,OpenELMForCausalLM:()=>Tx,OpenELMModel:()=>Mx,OpenELMPreTrainedModel:()=>za,OwlViTForObjectDetection:()=>zx,OwlViTModel:()=>Px,OwlViTPreTrainedModel:()=>$a,Owlv2ForObjectDetection:()=>Cx,Owlv2Model:()=>Ix,Owlv2PreTrainedModel:()=>Na,PaliGemmaForConditionalGeneration:()=>Lx,PaliGemmaPreTrainedModel:()=>Mc,ParakeetForCTC:()=>Nx,ParakeetPreTrainedModel:()=>Tc,PatchTSMixerForPrediction:()=>Rx,PatchTSMixerModel:()=>$x,PatchTSMixerPreTrainedModel:()=>Ra,PatchTSTForPrediction:()=>Bx,PatchTSTModel:()=>Ux,PatchTSTPreTrainedModel:()=>Ua,Phi3ForCausalLM:()=>Gx,Phi3Model:()=>jx,Phi3PreTrainedModel:()=>Da,Phi3VForCausalLM:()=>Fa,Phi3VPreTrainedModel:()=>Sc,PhiForCausalLM:()=>Fx,PhiModel:()=>Dx,PhiPreTrainedModel:()=>Ba,PreTrainedModel:()=>y,PvtForImageClassification:()=>Wx,PvtModel:()=>qx,PvtPreTrainedModel:()=>ja,PyAnnoteForAudioFrameClassification:()=>Hx,PyAnnoteModel:()=>Vx,PyAnnotePreTrainedModel:()=>Ga,Qwen2ForCausalLM:()=>Kx,Qwen2Model:()=>Xx,Qwen2PreTrainedModel:()=>qa,Qwen2VLForConditionalGeneration:()=>Yx,Qwen2VLPreTrainedModel:()=>Oc,Qwen3ForCausalLM:()=>Jx,Qwen3Model:()=>Qx,Qwen3PreTrainedModel:()=>Wa,RFDetrForObjectDetection:()=>ry,RFDetrModel:()=>ty,RFDetrObjectDetectionOutput:()=>Ic,RFDetrPreTrainedModel:()=>Ha,RTDetrForObjectDetection:()=>Jh,RTDetrModel:()=>Qh,RTDetrObjectDetectionOutput:()=>lr,RTDetrPreTrainedModel:()=>Io,RTDetrV2ForObjectDetection:()=>my,RTDetrV2Model:()=>fy,RTDetrV2ObjectDetectionOutput:()=>Cc,RTDetrV2PreTrainedModel:()=>Xa,ResNetForImageClassification:()=>ey,ResNetModel:()=>Zx,ResNetPreTrainedModel:()=>Va,RoFormerForMaskedLM:()=>cy,RoFormerForQuestionAnswering:()=>dy,RoFormerForSequenceClassification:()=>uy,RoFormerForTokenClassification:()=>py,RoFormerModel:()=>ly,RoFormerPreTrainedModel:()=>Fr,RobertaForMaskedLM:()=>ny,RobertaForQuestionAnswering:()=>iy,RobertaForSequenceClassification:()=>oy,RobertaForTokenClassification:()=>ay,RobertaModel:()=>sy,RobertaPreTrainedModel:()=>Dr,Sam2ImageSegmentationOutput:()=>Lc,Sam2Model:()=>Ka,Sam2PreTrainedModel:()=>Nc,Sam3TrackerModel:()=>gy,SamImageSegmentationOutput:()=>Pc,SamModel:()=>hy,SamPreTrainedModel:()=>zc,SapiensForDepthEstimation:()=>xy,SapiensForNormalEstimation:()=>yy,SapiensForSemanticSegmentation:()=>wy,SapiensPreTrainedModel:()=>wn,SegformerForImageClassification:()=>vy,SegformerForSemanticSegmentation:()=>ky,SegformerModel:()=>by,SegformerPreTrainedModel:()=>xn,SiglipModel:()=>Ey,SiglipPreTrainedModel:()=>Ya,SiglipTextModel:()=>Qa,SiglipVisionModel:()=>Ay,SmolLM3ForCausalLM:()=>Ty,SmolLM3Model:()=>My,SmolLM3PreTrainedModel:()=>Ja,SmolVLMForConditionalGeneration:()=>qg,SnacDecoderModel:()=>ei,SnacEncoderModel:()=>Za,SnacModel:()=>Sy,SnacPreTrainedModel:()=>yn,SpeechT5ForSpeechToText:()=>Iy,SpeechT5ForTextToSpeech:()=>Cy,SpeechT5HifiGan:()=>Py,SpeechT5Model:()=>Oy,SpeechT5PreTrainedModel:()=>bn,SqueezeBertForMaskedLM:()=>Ly,SqueezeBertForQuestionAnswering:()=>$y,SqueezeBertForSequenceClassification:()=>Ny,SqueezeBertModel:()=>zy,SqueezeBertPreTrainedModel:()=>Es,StableLmForCausalLM:()=>Uy,StableLmModel:()=>Ry,StableLmPreTrainedModel:()=>ti,Starcoder2ForCausalLM:()=>Dy,Starcoder2Model:()=>By,Starcoder2PreTrainedModel:()=>ri,StyleTextToSpeech2Model:()=>Fy,StyleTextToSpeech2PreTrainedModel:()=>$c,SupertonicForConditionalGeneration:()=>si,SupertonicPreTrainedModel:()=>Rc,Swin2SRForImageSuperResolution:()=>Vy,Swin2SRModel:()=>Wy,Swin2SRPreTrainedModel:()=>ni,SwinForImageClassification:()=>Gy,SwinForSemanticSegmentation:()=>qy,SwinModel:()=>jy,SwinPreTrainedModel:()=>vn,T5ForConditionalGeneration:()=>Xy,T5Model:()=>Hy,T5PreTrainedModel:()=>oi,TableTransformerForObjectDetection:()=>Yy,TableTransformerModel:()=>Ky,TableTransformerObjectDetectionOutput:()=>Uc,TableTransformerPreTrainedModel:()=>ai,TrOCRForCausalLM:()=>Qy,TrOCRPreTrainedModel:()=>Bc,UltravoxModel:()=>Fc,UltravoxPreTrainedModel:()=>Dc,UniSpeechForCTC:()=>e0,UniSpeechForSequenceClassification:()=>t0,UniSpeechModel:()=>Zy,UniSpeechPreTrainedModel:()=>kn,UniSpeechSatForAudioFrameClassification:()=>o0,UniSpeechSatForCTC:()=>s0,UniSpeechSatForSequenceClassification:()=>n0,UniSpeechSatModel:()=>r0,UniSpeechSatPreTrainedModel:()=>As,VaultGemmaForCausalLM:()=>i0,VaultGemmaModel:()=>a0,VaultGemmaPreTrainedModel:()=>ii,ViTForImageClassification:()=>u0,ViTMAEModel:()=>p0,ViTMAEPreTrainedModel:()=>jc,ViTMSNForImageClassification:()=>f0,ViTMSNModel:()=>d0,ViTMSNPreTrainedModel:()=>ci,ViTModel:()=>c0,ViTPreTrainedModel:()=>li,VisionEncoderDecoderModel:()=>l0,VitMatteForImageMatting:()=>m0,VitMattePreTrainedModel:()=>Gc,VitPoseForPoseEstimation:()=>h0,VitPosePreTrainedModel:()=>qc,VitsModel:()=>_0,VitsModelOutput:()=>Wc,VitsPreTrainedModel:()=>Vc,VoxtralForConditionalGeneration:()=>Jy,Wav2Vec2BertForCTC:()=>w0,Wav2Vec2BertForSequenceClassification:()=>x0,Wav2Vec2BertModel:()=>g0,Wav2Vec2BertPreTrainedModel:()=>En,Wav2Vec2ForAudioFrameClassification:()=>Rg,Wav2Vec2ForCTC:()=>Ng,Wav2Vec2ForSequenceClassification:()=>$g,Wav2Vec2Model:()=>Lg,Wav2Vec2PreTrainedModel:()=>Jt,WavLMForAudioFrameClassification:()=>E0,WavLMForCTC:()=>b0,WavLMForSequenceClassification:()=>v0,WavLMForXVector:()=>k0,WavLMModel:()=>y0,WavLMPreTrainedModel:()=>jr,WeSpeakerResNetModel:()=>A0,WeSpeakerResNetPreTrainedModel:()=>Xc,WhisperForConditionalGeneration:()=>Yc,WhisperModel:()=>M0,WhisperPreTrainedModel:()=>ui,XLMForQuestionAnswering:()=>P0,XLMForSequenceClassification:()=>I0,XLMForTokenClassification:()=>C0,XLMModel:()=>S0,XLMPreTrainedModel:()=>Gr,XLMRobertaForMaskedLM:()=>L0,XLMRobertaForQuestionAnswering:()=>R0,XLMRobertaForSequenceClassification:()=>N0,XLMRobertaForTokenClassification:()=>$0,XLMRobertaModel:()=>z0,XLMRobertaPreTrainedModel:()=>qr,XLMWithLMHeadModel:()=>O0,XVectorOutput:()=>Hc,YolosForObjectDetection:()=>B0,YolosModel:()=>U0,YolosObjectDetectionOutput:()=>Qc,YolosPreTrainedModel:()=>pi,YoutuForCausalLM:()=>F0,YoutuModel:()=>D0,YoutuPreTrainedModel:()=>di});var xs=class extends y{},Qm=class extends xs{},Jm=class extends xs{async _call(e){return new F(await super._call(e))}},Zm=class extends xs{async _call(e){return new Ae(await super._call(e))}},eh=class extends xs{async _call(e){return new we(await super._call(e))}};var fo=class extends y{},th=class extends fo{},rh=class extends fo{};var mo=class extends y{},sh=class extends mo{},nh=class extends mo{};var ho=class extends y{},oh=class extends ho{},ah=class extends ho{};var on=class extends y{},ih=class extends on{},lh=class extends on{},ch=class extends on{async _call(e){return new F(await super._call(e))}};var _o=class extends y{},uh=class extends _o{},ph=class extends _o{async _call(e){return new F(await super._call(e))}};var Cr=class extends y{},dh=class extends Cr{},fh=class extends Cr{async _call(e){return new we(await super._call(e))}},mh=class extends Cr{async _call(e){return new F(await super._call(e))}},hh=class extends Cr{async _call(e){return new _e(await super._call(e))}},_h=class extends Cr{async _call(e){return new Ae(await super._call(e))}};var go=class extends y{},gh=class extends go{},wh=class extends go{};var wo=class extends y{},xh=class extends wo{},yh=class extends wo{};var xo=class extends y{},bh=class extends xo{},vh=class extends xo{};var Pr=class extends y{},kh=class extends Pr{},Eh=class extends Pr{async _call(e){return new we(await super._call(e))}},Ah=class extends Pr{async _call(e){return new F(await super._call(e))}},Mh=class extends Pr{async _call(e){return new _e(await super._call(e))}},Th=class extends Pr{async _call(e){return new Ae(await super._call(e))}};var GP=4299n,aA=6561n,Zl=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"];main_input_name="input_ids";_return_dict_in_generate_keys=["audio_tokens","speaker_embeddings","speaker_features"]},yo=class extends Zl{async encode_speech(e){return ce(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:r=null,audio_values:s=null,exaggeration:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:u=null,audio_features:d=null,audio_tokens:f=null,speaker_embeddings:m=null,speaker_features:_=null,...w}){let x;if(!a){let E=this.sessions.embed_tokens.inputNames,M={input_ids:e};if(E.includes("exaggeration")){if(!(n instanceof U)){let I=e.dims[0];if(n==null)n=Ve([I],.5);else if(typeof n=="number")n=Ve([I],n);else if(Array.isArray(n))n=new U("float32",n,[I]);else throw new Error("Unsupported type for `exaggeration` input")}M.exaggeration=n}if(E.includes("position_ids")&&(M.position_ids=o),{inputs_embeds:a}=await ce(this.sessions.embed_tokens,M),d&&f&&m&&_&&(x={audio_features:d,audio_tokens:f,speaker_embeddings:m,speaker_features:_}),x||s)x??=await this.encode_speech(s),a=Ee([x.audio_features,a],1),r=it([a.dims[0],a.dims[1]]);else{let I=a.dims[1];if(!i||I!==1)throw new Error("Incorrect state encountered during generation.");let T=Object.values(i)[0].dims.at(-2);r=it([a.dims[0],T+I])}}return{...await Tt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,generation_config:l,logits_processor:u},!1),...x}}prepare_inputs_for_generation(e,r,s){if(!r.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(r.input_ids.dims[1]===1){let n=Array.from({length:e.length},(o,a)=>e[a].length-e[a].findLastIndex(i=>i==aA)-1);r.position_ids=new U("int64",n,[e.length,1])}else{let o=r.input_ids.tolist().map(a=>{let i=0;return a.map(l=>l>=aA?0:i++)});r.position_ids=new U("int64",o.flat(),r.input_ids.dims)}return r.input_ids.dims[1]===1&&(delete r.audio_values,delete r.audio_features,delete r.audio_tokens,delete r.speaker_embeddings,delete r.speaker_features),uo(this,e,r,s)}async generate(e){let{sequences:r,audio_tokens:s,speaker_embeddings:n,speaker_features:o}=await super.generate({...e,return_dict_in_generate:!0}),a=r.slice(null,[e.input_ids.dims[1],-1]),i=Ve([a.dims[0],3],GP),l=Ee([s,a,i],1),{waveform:u}=await ce(this.sessions.conditional_decoder,{speech_tokens:l,speaker_features:o,speaker_embeddings:n});return u}};var ec=class extends y{},Sh=class extends ec{};var an=class extends y{},Oh=class extends an{},bo=class extends an{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},vo=class extends an{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"audio_model"})}};var ir=class extends y{},Ih=class extends ir{},Ch=class extends ir{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},ko=class extends ir{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Ph=class extends ir{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},zh=class extends ir{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Eo=class extends y{},Lh=class extends Eo{},Nh=class extends Eo{};var Ao=class extends y{},$h=class extends Ao{},Rh=class extends Ao{};var Mo=class extends y{},Uh=class extends Mo{},Bh=class extends Mo{};var To=class extends y{},Dh=class extends To{},Fh=class extends To{};var zr=class extends y{},jh=class extends zr{},Gh=class extends zr{async _call(e){return new we(await super._call(e))}},qh=class extends zr{async _call(e){return new F(await super._call(e))}},Wh=class extends zr{async _call(e){return new _e(await super._call(e))}},Vh=class extends zr{async _call(e){return new Ae(await super._call(e))}};var So=class extends y{},Hh=class extends So{},Xh=class extends So{async _call(e){return new F(await super._call(e))}};var Oo=class extends y{},Kh=class extends Oo{},Yh=class extends Oo{async _call(e){return new F(await super._call(e))}};var Io=class extends y{},Qh=class extends Io{},Jh=class extends Io{async _call(e){return new lr(await super._call(e))}},lr=class extends ze{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var Co=class extends y{},Zh=class extends Co{},e_=class extends Co{async _call(e){return new lr(await super._call(e))}};var tc=class extends ze{constructor({audio_codes:e}){super(),this.audio_codes=e}},rc=class extends ze{constructor({audio_values:e}){super(),this.audio_values=e}},ln=class extends y{main_input_name="input_values";forward_params=["input_values"]},t_=class extends ln{async encode(e){return new tc(await ce(this.sessions.encoder_model,e))}async decode(e){return new rc(await ce(this.sessions.decoder_model,e))}},Po=class extends ln{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},zo=class extends ln{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Lr=class extends y{},r_=class extends Lr{},s_=class extends Lr{async _call(e){return new we(await super._call(e))}},n_=class extends Lr{async _call(e){return new F(await super._call(e))}},o_=class extends Lr{async _call(e){return new _e(await super._call(e))}},a_=class extends Lr{async _call(e){return new Ae(await super._call(e))}};var Nr=class extends y{},i_=class extends Nr{},l_=class extends Nr{async _call(e){return new we(await super._call(e))}},c_=class extends Nr{async _call(e){return new F(await super._call(e))}},u_=class extends Nr{async _call(e){return new _e(await super._call(e))}},p_=class extends Nr{async _call(e){return new Ae(await super._call(e))}};var sc=class extends y{},d_=class extends sc{};var Lo=class extends y{},f_=class extends Lo{},m_=class extends Lo{async _call(e){return new F(await super._call(e))}};var nc=class extends y{},h_=class extends nc{};var oc=class extends y{},__=class extends oc{};var cn=class extends y{},g_=class extends cn{},w_=class extends cn{async _call(e){return new un(await super._call(e))}},x_=class extends cn{async _call(e){return new ac(await super._call(e))}},un=class extends ze{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},ac=class extends ze{constructor({logits:e,pred_boxes:r,pred_masks:s}){super(),this.logits=e,this.pred_boxes=r,this.pred_masks=s}};var No=class extends y{},y_=class extends No{},b_=class extends No{async _call(e){return new F(await super._call(e))}};var $o=class extends y{},v_=class extends $o{},k_=class extends $o{async _call(e){return new F(await super._call(e))}};var ic=class extends y{},E_=class extends ic{};var lc=class extends y{},A_=class extends lc{};var $r=class extends y{},M_=class extends $r{},T_=class extends $r{async _call(e){return new F(await super._call(e))}},S_=class extends $r{async _call(e){return new _e(await super._call(e))}},O_=class extends $r{async _call(e){return new Ae(await super._call(e))}},I_=class extends $r{async _call(e){return new we(await super._call(e))}};var cc=class extends y{},C_=class extends cc{};var Ro=class extends y{},P_=class extends Ro{},z_=class extends Ro{};var Uo=class extends y{},L_=class extends Uo{},N_=class extends Uo{async _call(e){return new F(await super._call(e))}};var Rr=class extends y{},$_=class extends Rr{},R_=class extends Rr{async _call(e){return new we(await super._call(e))}},U_=class extends Rr{async _call(e){return new F(await super._call(e))}},B_=class extends Rr{async _call(e){return new _e(await super._call(e))}},D_=class extends Rr{async _call(e){return new Ae(await super._call(e))}};var Bo=class extends y{},F_=class extends Bo{},j_=class extends Bo{};var ys=class extends y{},G_=class extends ys{},q_=class extends ys{async _call(e){return new we(await super._call(e))}},W_=class extends ys{async _call(e){return new F(await super._call(e))}},V_=class extends ys{async _call(e){return new _e(await super._call(e))}};var Do=class extends y{},H_=class extends Do{},X_=class extends Do{};var Fo=class extends y{},K_=class extends Fo{},Y_=class extends Fo{};var jo=class extends y{},Q_=class extends jo{},J_=class extends jo{};var Go=class extends y{},Z_=class extends Go{},eg=class extends Go{async _call(e){return new F(await super._call(e))}};var uc=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"];main_input_name="inputs_embeds"},tg=class extends uc{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return{inputs_embeds:Ee([r,e],1),attention_mask:Ee([it(r.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:s,attention_mask:n}){if(!e&&!r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let o,a;return e&&(o=await this.encode_text({input_ids:e})),r&&(a=await this.encode_image({pixel_values:r})),o&&a?{inputs_embeds:s,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:o,image_features:a,input_ids:e,attention_mask:n}):s=o||a,{inputs_embeds:s,attention_mask:n}}async forward({input_ids:e,pixel_values:r,attention_mask:s,decoder_input_ids:n,decoder_attention_mask:o,encoder_outputs:a,past_key_values:i,inputs_embeds:l,decoder_inputs_embeds:u}){if(l||({inputs_embeds:l,attention_mask:s}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:l,attention_mask:s})),!a){let{last_hidden_state:f}=await Gt(this,{inputs_embeds:l,attention_mask:s});a=f}if(!u){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");u=await this.encode_text({input_ids:n})}return await Tt(this,{inputs_embeds:u,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i},!0)}};var qo=class extends y{},rg=class extends qo{},sg=class extends qo{};var Wo=class extends y{},ng=class extends Wo{},og=class extends Wo{};var Vo=class extends y{},ag=class extends Vo{},ig=class extends Vo{};var pc=class extends y{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},Ho=class extends pc{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,input_features:n=null,input_features_mask:o=null,position_ids:a=null,inputs_embeds:i=null,per_layer_inputs:l=null,past_key_values:u=null,generation_config:d=null,logits_processor:f=null,...m}){if((!i||!l)&&({inputs_embeds:i,per_layer_inputs:l}=await ce(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(s){let{image_features:w}=await ce(this.sessions.vision_encoder,{pixel_values:s});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_image_features({image_features:w,inputs_embeds:i,input_ids:e,attention_mask:r}))}if(n){let{audio_features:w}=await ce(this.sessions.audio_encoder,{input_features:n,input_features_mask:o});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_audio_features({audio_features:w,inputs_embeds:i,input_ids:e,attention_mask:r}))}}return await Tt(this,{inputs_embeds:i,per_layer_inputs:l,past_key_values:u,attention_mask:r,position_ids:a,generation_config:d,logits_processor:f},!0)}_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return ar({image_token_id:this.config.image_token_id,...e,image_features:s})}_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return Jl({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}};var Xo=class extends y{},lg=class extends Xo{},cg=class extends Xo{};var Ko=class extends y{},ug=class extends Ko{},pg=class extends Ko{};var Yo=class extends y{},dg=class extends Yo{},fg=class extends Yo{};var Qo=class extends y{},mg=class extends Qo{},hg=class extends Qo{};var Jo=class extends y{},_g=class extends Jo{},gg=class extends Jo{};var Zo=class extends y{},wg=class extends Zo{},xg=class extends Zo{};var ea=class extends y{},yg=class extends ea{},bg=class extends ea{};var ta=class extends y{},vg=class extends ta{},kg=class extends ta{};var ra=class extends y{},Eg=class extends ra{},Ag=class extends ra{};var sa=class extends y{},Mg=class extends sa{},Tg=class extends sa{};var dc=class extends y{},Sg=class extends dc{};var fc=class extends y{},Og=class extends fc{};var na=class extends y{},Ig=class extends na{},Cg=class extends na{};var oa=class extends y{},Pg=class extends oa{},zg=class extends oa{async _call(e){return new F(await super._call(e))}};var Jt=class extends y{},Lg=class extends Jt{},Ng=class extends Jt{async _call(e){return new gt(await super._call(e))}},$g=class extends Jt{async _call(e){return new F(await super._call(e))}},Rg=class extends Jt{async _call(e){return new _e(await super._call(e))}};var Ug=class extends y{},Bg=class extends Jt{},Dg=class extends Jt{async _call(e){return new gt(await super._call(e))}},Fg=class extends Jt{async _call(e){return new F(await super._call(e))}};var aa=class extends y{},jg=class extends aa{},Gg=class extends aa{};var mc=class extends y{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},hc=class extends mc{async encode_image({pixel_values:e,pixel_attention_mask:r}){return(await ce(this.sessions.vision_encoder,{pixel_values:e,pixel_attention_mask:r})).image_features}_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return ar({image_token_id:this.config.image_token_id,...e,image_features:s})}},qg=class extends hc{};var ia=class extends y{},Wg=class extends ia{},Vg=class extends ia{async _call(e){return new F(await super._call(e))}};var la=class extends y{},Hg=class extends la{},Xg=class extends la{};var pn=class extends y{},Kg=class extends pn{async forward(e){let r=!e.input_ids,s=!e.pixel_values;if(r&&s)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(r&&(e.input_ids=it([e.pixel_values.dims[0],1])),s){let{image_size:u}=this.config.vision_config;e.pixel_values=Ve([0,3,u,u],0)}let{text_embeddings:n,image_embeddings:o,l2norm_text_embeddings:a,l2norm_image_embeddings:i}=await super.forward(e),l={};return r||(l.text_embeddings=n,l.l2norm_text_embeddings=a),s||(l.image_embeddings=o,l.l2norm_image_embeddings=i),l}},ca=class extends pn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Yg=class extends pn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var ua=class extends y{},Qg=class extends ua{},Jg=class extends ua{};var pa=class extends y{},Zg=class extends pa{},ew=class extends pa{};var da=class extends y{},tw=class extends da{},rw=class extends da{};var _c=class extends y{},sw=class extends _c{};var gc=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},dn=class extends gc{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return ar({image_token_id:this.config.image_token_index,...e,image_features:s})}},nw=class extends dn{},ow=class extends dn{};var fa=class extends y{},aw=class extends fa{},iw=class extends fa{};var ma=class extends y{},lw=class extends ma{},cw=class extends ma{};var ha=class extends y{},uw=class extends ha{},pw=class extends ha{};var _a=class extends y{},dw=class extends _a{},fw=class extends _a{};var bs=class extends y{},mw=class extends bs{},hw=class extends bs{},_w=class extends bs{async _call(e){return new F(await super._call(e))}},gw=class extends bs{};var wc=class extends y{},ww=class extends wc{};var xc=class extends y{},xw=class extends xc{};var yc=class extends ze{constructor({char_logits:e,bpe_logits:r,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=r,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},bc=class extends y{},yw=class extends bc{async _call(e){return new yc(await super._call(e))}};var vc=class extends ze{constructor({audio_codes:e}){super(),this.audio_codes=e}},kc=class extends ze{constructor({audio_values:e}){super(),this.audio_values=e}},fn=class extends y{main_input_name="input_values";forward_params=["input_values"]},bw=class extends fn{async encode(e){return new vc(await ce(this.sessions.encoder_model,e))}async decode(e){return new kc(await ce(this.sessions.decoder_model,e))}},ga=class extends fn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},wa=class extends fn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var xa=class extends y{},vw=class extends xa{},kw=class extends xa{};var vs=class extends y{},Ew=class extends vs{},Aw=class extends vs{async _call(e){return new we(await super._call(e))}},Mw=class extends vs{async _call(e){return new F(await super._call(e))}},Tw=class extends vs{async _call(e){return new Ae(await super._call(e))}};var ya=class extends y{},Sw=class extends ya{},Ow=class extends ya{};var mn=class extends y{},Iw=class extends mn{},Cw=class extends mn{async _call(e){return new F(await super._call(e))}},Pw=class extends mn{};var hn=class extends y{},zw=class extends hn{},Lw=class extends hn{async _call(e){return new F(await super._call(e))}},Nw=class extends hn{};var _n=class extends y{},$w=class extends _n{},Rw=class extends _n{async _call(e){return new F(await super._call(e))}},Uw=class extends _n{};var gn=class extends y{},Bw=class extends gn{},Dw=class extends gn{async _call(e){return new F(await super._call(e))}},Fw=class extends gn{};var ba=class extends y{},jw=class extends ba{},Gw=class extends ba{async _call(e){return new F(await super._call(e))}};var va=class extends y{},qw=class extends va{},Ww=class extends va{async _call(e){return new F(await super._call(e))}};var ks=class extends y{},Vw=class extends ks{},Hw=class extends ks{async _call(e){return new we(await super._call(e))}},Xw=class extends ks{async _call(e){return new F(await super._call(e))}},Kw=class extends ks{async _call(e){return new _e(await super._call(e))}};var ka=class extends y{},Yw=class extends ka{},Qw=class extends ka{};var Ea=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},Jw=class extends Ea{},Zw=class extends Ea{};var Ur=class extends y{},ex=class extends Ur{},tx=class extends Ur{async _call(e){return new we(await super._call(e))}},rx=class extends Ur{async _call(e){return new F(await super._call(e))}},sx=class extends Ur{async _call(e){return new _e(await super._call(e))}},nx=class extends Ur{async _call(e){return new Ae(await super._call(e))}};var Aa=class extends y{},ox=class extends Aa{},ax=class extends Aa{};var Ma=class extends y{},ix=class extends Ma{},lx=class extends Ma{};var Ec=class extends y{},cx=class extends Ec{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){let r=this._generation_mode??"text",s;if(r==="text"||!e.past_key_values){let l=this.sessions.prepare_inputs_embeds,u=ot(e,l.inputNames);s=await ce(l,u)}else{let l=this.sessions.gen_img_embeds,u=ot({image_ids:e.input_ids},l.inputNames);s=await ce(l,u)}let n={...e,...s},o=await Tt(this,n),a=this.sessions[r==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);let i=await ce(a,ot(o,a.inputNames));return{...s,...o,...i}}prepare_inputs_for_generation(e,r,s){let n=!!r.past_key_values;return s.guidance_scale!==null&&s.guidance_scale>1&&(n?r.input_ids=Ee([r.input_ids,r.input_ids],0):(r.input_ids=Ee([r.input_ids,Qn(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=Ee([r.attention_mask,Qn(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=Ve([0,0,3,384,384],1)),n&&(r.images_seq_mask=new U("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new U("bool",new Array(0).fill(!1),[1,1,0])),r}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";let r=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[r,null]),o=this.sessions.image_decode,{decoded_image:a}=await ce(o,{generated_tokens:n}),i=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let u of i){let d=Xe.fromTensor(u);l.push(d)}return l}};var Ta=class extends y{},ux=class extends Ta{},px=class extends Ta{},Sa=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){let[r,s]=e.dims,n=this.config.decoder.num_codebooks,o=s-n,a=0;for(let u=0;u<e.size;++u){if(e.data[u]==this.config.decoder.pad_token_id)continue;let d=u%s,f=Math.floor(u/s)%n,m=d-f;m>0&&m<=o&&(e.data[a++]=e.data[u])}let i=Math.floor(r/n),l=a/(i*n);return new U(e.type,e.data.slice(0,a),[i,n,l])}prepare_inputs_for_generation(e,r,s){let n=BigInt(this.config.decoder.pad_token_id),o=structuredClone(e);for(let a=0;a<o.length;++a)for(let i=0;i<o[a].length;++i)a%this.config.decoder.num_codebooks>=i&&(o[a][i]=n);return s.guidance_scale!==null&&s.guidance_scale>1&&(o=o.concat(o)),po(this,o,r,s)}async generate(e){let r=await super.generate(e),s=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:n}=await ce(this.sessions.encodec_decode,{audio_codes:s});return n}};var Oa=class extends y{},dx=class extends Oa{},fx=class extends Oa{};var Br=class extends y{},mx=class extends Br{},hx=class extends Br{async _call(e){return new we(await super._call(e))}},_x=class extends Br{async _call(e){return new F(await super._call(e))}},gx=class extends Br{async _call(e){return new _e(await super._call(e))}},wx=class extends Br{async _call(e){return new Ae(await super._call(e))}};var Ac=class extends y{},xx=class extends Ac{};var Ia=class extends y{},yx=class extends Ia{},bx=class extends Ia{};var Ca=class extends y{},vx=class extends Ca{},kx=class extends Ca{};var Pa=class extends y{},Ex=class extends Pa{},Ax=class extends Pa{};var za=class extends y{},Mx=class extends za{},Tx=class extends za{};var La=class extends y{},Sx=class extends La{},Ox=class extends La{};var Na=class extends y{},Ix=class extends Na{},Cx=class extends Na{};var $a=class extends y{},Px=class extends $a{},zx=class extends $a{};var Mc=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Lx=class extends Mc{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return ar({image_token_id:this.config.image_token_index,...e,image_features:s})}};var Tc=class extends y{},Nx=class extends Tc{async _call(e){return new gt(await super._call(e))}};var Ra=class extends y{},$x=class extends Ra{},Rx=class extends Ra{};var Ua=class extends y{},Ux=class extends Ua{},Bx=class extends Ua{};var Ba=class extends y{},Dx=class extends Ba{},Fx=class extends Ba{};var Da=class extends y{},jx=class extends Da{},Gx=class extends Da{};var Sc=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},Fa=class extends Sc{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,image_sizes:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:u=null,...d}){if(!a){let m;if(s&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:m}=await ce(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else{let _=this.config.normalized_config.hidden_size;m=new U("float32",[],[0,_])}({inputs_embeds:a}=await ce(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:m}))}return await Tt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:u},!1)}};var ja=class extends y{},qx=class extends ja{},Wx=class extends ja{async _call(e){return new F(await super._call(e))}};var Ga=class extends y{},Vx=class extends Ga{},Hx=class extends Ga{async _call(e){return new _e(await super._call(e))}};var qa=class extends y{},Xx=class extends qa{},Kx=class extends qa{};var Oc=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},Yx=class extends Oc{get_rope_index(e,r,s,n){let{vision_config:o,image_token_id:a,video_token_id:i,vision_start_token_id:l}=this.config,u=o.spatial_merge_size??2,d=[];if(r||s){let f=e.tolist();n||(n=ll(e));let m=n.tolist(),_=Array.from({length:3},M=>Array.from({length:e.dims[0]},I=>Array.from({length:e.dims[1]},T=>1))),w=r?r.tolist():[],x=s?s.tolist():[],k=0,E=0;for(let M=0;M<f.length;++M){let I=f[M].filter((S,L)=>m[M][L]==1),z=I.reduce((S,L,R)=>(L==l&&S.push(R),S),[]).map(S=>I[S+1]),C=z.filter(S=>S==a).length,v=z.filter(S=>S==i).length,G=[],X=0,V=C,Q=v;for(let S=0;S<z.length;++S){let L=I.findIndex((Et,et)=>et>X&&Et==a),R=I.findIndex((Et,et)=>et>X&&Et==i),te=V>0&&L!==-1?L:I.length+1,ue=Q>0&&R!==-1?R:I.length+1,Be,Ce,vt,Qe;te<ue?([Ce,vt,Qe]=w[k],++k,--V,Be=te):([Ce,vt,Qe]=x[E],++E,--Q,Be=ue);let[Ze,rt,Me]=[Number(Ce),Math.floor(Number(vt)/u),Math.floor(Number(Qe)/u)],xe=Be-X,Ge=G.length>0?Te(G.at(-1))[0]+1:0;G.push(Array.from({length:3*xe},(Et,et)=>Ge+et%xe));let kt=xe+Ge,ge=Ze*rt*Me,Le=Array.from({length:ge},(Et,et)=>kt+Math.floor(et/(rt*Me))),xr=Array.from({length:ge},(Et,et)=>kt+Math.floor(et/Me)%rt),Hr=Array.from({length:ge},(Et,et)=>kt+et%Me);G.push([Le,xr,Hr].flat()),X=Be+ge}if(X<I.length){let S=G.length>0?Te(G.at(-1))[0]+1:0,L=I.length-X;G.push(Array.from({length:3*L},(R,te)=>S+te%L))}let K=G.reduce((S,L)=>S+L.length,0),Y=new Array(K),B=0;for(let S=0;S<3;++S)for(let L=0;L<G.length;++L){let R=G[L],te=R.length/3;for(let ue=S*te;ue<(S+1)*te;++ue)Y[B++]=R[ue]}let P=0,se=m[M];for(let S=0;S<se.length;++S)if(se[S]==1){for(let L=0;L<3;++L)_[L][M][S]=Y[L*K/3+P];++P}let ie=Te(Y)[0];d.push(ie+1-f[M].length)}return[new U("int64",_.flat(1/0),[3,e.dims[0],e.dims[1]]),new U("int64",d,[d.length,1])]}else if(n){let{data:f,dims:m}=Ym(n),_=BigInt64Array.from({length:3*f.length},(x,k)=>f[k%f.length]),w=Array.from({length:m[0]},(x,k)=>Te(f.subarray(m[1]*k,m[1]*(k+1)))[0]+1n+BigInt(m[1]));return[new U("int64",_,[3,...m]),new U("int64",w,[w.length,1])]}else{let[f,m]=e.dims,_=BigInt64Array.from({length:3*f*m},(w,x)=>BigInt(Math.floor(x%m/f)));return[new U("int64",_,[3,...e.dims]),kd([f,1])]}}async encode_image({pixel_values:e,image_grid_thw:r}){return(await ce(this.sessions.vision_encoder,{pixel_values:e,grid_thw:r})).image_features}_merge_input_ids_with_image_features(e){return ar({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,r,s){if(r.attention_mask&&!r.position_ids)if(!r.past_key_values)[r.position_ids,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);else{r.pixel_values=null;let n=BigInt(Object.values(r.past_key_values)[0].dims.at(-2)),o=r.rope_deltas.map(a=>n+a);r.position_ids=Ft([o,o,o],0)}return r}};var Wa=class extends y{},Qx=class extends Wa{},Jx=class extends Wa{};var Va=class extends y{},Zx=class extends Va{},ey=class extends Va{async _call(e){return new F(await super._call(e))}};var Ha=class extends y{},ty=class extends Ha{},ry=class extends Ha{async _call(e){return new Ic(await super._call(e))}},Ic=class extends lr{};var Dr=class extends y{},sy=class extends Dr{},ny=class extends Dr{async _call(e){return new we(await super._call(e))}},oy=class extends Dr{async _call(e){return new F(await super._call(e))}},ay=class extends Dr{async _call(e){return new _e(await super._call(e))}},iy=class extends Dr{async _call(e){return new Ae(await super._call(e))}};var Fr=class extends y{},ly=class extends Fr{},cy=class extends Fr{async _call(e){return new we(await super._call(e))}},uy=class extends Fr{async _call(e){return new F(await super._call(e))}},py=class extends Fr{async _call(e){return new _e(await super._call(e))}},dy=class extends Fr{async _call(e){return new Ae(await super._call(e))}};var Xa=class extends y{},fy=class extends Xa{},my=class extends Xa{async _call(e){return new Cc(await super._call(e))}},Cc=class extends lr{};var Pc=class extends ze{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},zc=class extends y{},hy=class extends zc{async get_image_embeddings({pixel_values:e}){return await Gt(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??=it(e.input_points.dims.slice(0,-1));let r={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(r.input_points=e.input_points),e.input_labels&&(r.input_labels=e.input_labels),e.input_boxes&&(r.input_boxes=e.input_boxes),await ce(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new Pc(await super._call(e))}};var Lc=class extends ze{constructor({iou_scores:e,pred_masks:r,object_score_logits:s}){super(),this.iou_scores=e,this.pred_masks=r,this.object_score_logits=s}},Nc=class extends y{},Ka=class extends Nc{async get_image_embeddings({pixel_values:e}){return await Gt(this,{pixel_values:e})}async forward(e){let{num_feature_levels:r}=this.config.vision_config;if(Array.from({length:r},(a,i)=>`image_embeddings.${i}`).some(a=>!e[a])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let a=e.input_points.dims;e.input_labels??=it(a.slice(0,-1)),e.input_boxes??=Ve([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=Ve([a[0],a[1],0],-1n),e.input_points=Ve([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder,o=ot(e,n.inputNames);return await ce(n,o)}async _call(e){return new Lc(await super._call(e))}},_y=class extends Ka{},gy=class extends Ka{};var wn=class extends y{},wy=class extends wn{},xy=class extends wn{},yy=class extends wn{};var xn=class extends y{},by=class extends xn{},vy=class extends xn{},ky=class extends xn{};var Ya=class extends y{},Ey=class extends Ya{},Qa=class extends Ya{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Ay=class extends ir{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Ja=class extends y{},My=class extends Ja{},Ty=class extends Ja{};var yn=class extends y{main_input_name="input_values";forward_params=["input_values"]},Sy=class extends yn{async encode(e){return await ce(this.sessions.encoder_model,e)}async decode(e){return await ce(this.sessions.decoder_model,e)}},Za=class extends yn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},ei=class extends yn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var bn=class extends y{},Oy=class extends bn{},Iy=class extends bn{},Cy=class extends bn{async generate_speech(e,r,{threshold:s=.5,minlenratio:n=0,maxlenratio:o=20,vocoder:a=null}={}){let i={input_ids:e},{encoder_outputs:l,encoder_attention_mask:u}=await Gt(this,i),d=l.dims[1]/this.config.reduction_factor,f=Math.floor(d*o),m=Math.floor(d*n),_=this.config.num_mel_bins,w=[],x=null,k=null,E=0;for(;;){++E;let T=Km(!!k),z;k?z=k.output_sequence_out:z=new U("float32",new Float32Array(_),[1,1,_]);let C={use_cache_branch:T,output_sequence:z,encoder_attention_mask:u,speaker_embeddings:r,encoder_hidden_states:l};this.addPastKeyValues(C,x),k=await ce(this.sessions.decoder_model_merged,C),x=this.getPastKeyValues(k,x);let{prob:v,spectrum:G}=k;if(w.push(G),E>=m&&(Array.from(v.data).filter(X=>X>=s).length>0||E>=f))break}let M=Ee(w),{waveform:I}=await ce(a.sessions.model,{spectrogram:M});return{spectrogram:M,waveform:I}}},Py=class extends y{main_input_name="spectrogram"};var Es=class extends y{},zy=class extends Es{},Ly=class extends Es{async _call(e){return new we(await super._call(e))}},Ny=class extends Es{async _call(e){return new F(await super._call(e))}},$y=class extends Es{async _call(e){return new Ae(await super._call(e))}};var ti=class extends y{},Ry=class extends ti{},Uy=class extends ti{};var ri=class extends y{},By=class extends ri{},Dy=class extends ri{};var $c=class extends y{},Fy=class extends $c{};var Rc=class extends y{},si=class extends Rc{async generate_speech({input_ids:e,attention_mask:r,style:s,num_inference_steps:n=5,speed:o=1.05}){let{sampling_rate:a,chunk_compress_factor:i,base_chunk_size:l,latent_dim:u}=this.config,{last_hidden_state:d,durations:f}=await ce(this.sessions.text_encoder,{input_ids:e,attention_mask:r,style:s}),m=f.div(o).mul_(a),_=l*i,w=m.data,x=Int32Array.from(w,V=>Math.ceil(V/_)),k=Math.max(...x),E=e.dims[0],M=new BigInt64Array(E*k);for(let V=0;V<E;++V)M.fill(1n,V*k,V*k+x[V]);let I=new U("int64",M,[E,k]),T=u*i,z=T*k,C=NE([E,T,k]),v=C.data;for(let V=0;V<E;++V)if(x[V]!==k)for(let Q=0;Q<T;++Q)v.fill(0,V*z+Q*k+x[V],V*z+(Q+1)*k);let G=Ve([E],n);for(let V=0;V<n;++V){let Q=Ve([E],V);({denoised_latents:C}=await ce(this.sessions.latent_denoiser,{style:s,noisy_latents:C,latent_mask:I,encoder_outputs:d,attention_mask:r,timestep:Q,num_inference_steps:G}))}let{waveform:X}=await ce(this.sessions.voice_decoder,{latents:C});return{waveform:X,durations:m}}};var vn=class extends y{},jy=class extends vn{},Gy=class extends vn{async _call(e){return new F(await super._call(e))}},qy=class extends vn{};var ni=class extends y{},Wy=class extends ni{},Vy=class extends ni{};var oi=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},Hy=class extends oi{},Xy=class extends oi{};var ai=class extends y{},Ky=class extends ai{},Yy=class extends ai{async _call(e){return new Uc(await super._call(e))}},Uc=class extends un{};var Bc=class extends y{},Qy=class extends Bc{};var Dc=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},Fc=class extends Dc{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return Jl({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...e,audio_features:s})}},Jy=class extends Fc{};var kn=class extends y{},Zy=class extends kn{},e0=class extends kn{async _call(e){return new gt(await super._call(e))}},t0=class extends kn{async _call(e){return new F(await super._call(e))}};var As=class extends y{},r0=class extends As{},s0=class extends As{async _call(e){return new gt(await super._call(e))}},n0=class extends As{async _call(e){return new F(await super._call(e))}},o0=class extends As{async _call(e){return new _e(await super._call(e))}};var ii=class extends y{},a0=class extends ii{},i0=class extends ii{};var l0=class extends y{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]};var li=class extends y{},c0=class extends li{},u0=class extends li{async _call(e){return new F(await super._call(e))}};var jc=class extends y{},p0=class extends jc{};var ci=class extends y{},d0=class extends ci{},f0=class extends ci{async _call(e){return new F(await super._call(e))}};var Gc=class extends y{},m0=class extends Gc{async _call(e){return new Nl(await super._call(e))}};var qc=class extends y{},h0=class extends qc{};var Wc=class extends ze{constructor({waveform:e,spectrogram:r}){super(),this.waveform=e,this.spectrogram=r}},Vc=class extends y{},_0=class extends Vc{async _call(e){return new Wc(await super._call(e))}};var En=class extends y{},g0=class extends En{},w0=class extends En{async _call(e){return new gt(await super._call(e))}},x0=class extends En{async _call(e){return new F(await super._call(e))}};var Hc=class extends ze{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},jr=class extends y{},y0=class extends jr{},b0=class extends jr{async _call(e){return new gt(await super._call(e))}},v0=class extends jr{async _call(e){return new F(await super._call(e))}},k0=class extends jr{async _call(e){return new Hc(await super._call(e))}},E0=class extends jr{async _call(e){return new _e(await super._call(e))}};var Xc=class extends y{},A0=class extends Xc{};var Kc=class extends sn{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1};var ui=class extends y{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},M0=class extends ui{},Yc=class extends ui{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,Kc)}_retrieve_init_tokens(e){let r=[e.decoder_start_token_id],s=e.language,n=e.task;if(e.is_multilingual){s||(console.warn("No language specified - defaulting to English (en)."),s="en");let a=`<|${UE(s)}|>`;r.push(e.lang_to_id[a]),r.push(e.task_to_id[n??"transcribe"])}else if(s||n)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&r.at(-1)!==e.no_timestamps_token_id?r.push(e.no_timestamps_token_id):e.return_timestamps&&r.at(-1)===e.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),r.pop()),r.filter(o=>o!=null)}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,...o}){r=this._prepare_generation_config(r,o);let a=o.decoder_input_ids??this._retrieve_init_tokens(r);if(r.return_timestamps&&(s??=new hs,s.push(new Ul(r,a))),r.begin_suppress_tokens&&(s??=new hs,s.push(new rn(r.begin_suppress_tokens,a.length))),r.return_token_timestamps){if(!r.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.");r.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),r.output_attentions=!0,r.return_dict_in_generate=!0}let i=await super.generate({inputs:e,generation_config:r,logits_processor:s,decoder_input_ids:a,...o});return r.return_token_timestamps&&(i.token_timestamps=this._extract_token_timestamps(i,r.alignment_heads,r.num_frames)),i}_extract_token_timestamps(e,r,s=null,n=.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`.");s==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let o=this.config.median_filter_width;o===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),o=7);let a=e.cross_attentions,i=Array.from({length:this.config.decoder_layers},(x,k)=>Ee(a.map(E=>E[k]),2)),l=Ft(r.map(([x,k])=>{if(x>=i.length)throw new Error(`Layer index ${x} is out of bounds for cross attentions (length ${i.length}).`);return s?i[x].slice(null,k,null,[0,s]):i[x].slice(null,k)})).transpose(1,0,2,3),[u,d]=bd(l,-2,0,!0),f=l.clone();for(let x=0;x<f.dims[0];++x){let k=f[x];for(let E=0;E<k.dims[0];++E){let M=k[E],I=u[x][E][0].data,T=d[x][E][0].data;for(let z=0;z<M.dims[0];++z){let C=M[z].data;for(let v=0;v<C.length;++v)C[v]=(C[v]-T[v])/I[v];C.set(Kv(C,o))}}}let m=[il(f,1)],_=e.sequences.dims,w=new U("float32",new Float32Array(_[0]*_[1]),_);for(let x=0;x<_[0];++x){let k=m[x].neg().squeeze_(0),[E,M]=Qv(k.tolist()),I=Array.from({length:E.length-1},(C,v)=>E[v+1]-E[v]),T=dt([1],I).map(C=>!!C),z=[];for(let C=0;C<T.length;++C)T[C]&&z.push(M[C]*n);w[x].data.set(z,1)}return w}},T0=class extends Yc{};var Gr=class extends y{},S0=class extends Gr{},O0=class extends Gr{async _call(e){return new we(await super._call(e))}},I0=class extends Gr{async _call(e){return new F(await super._call(e))}},C0=class extends Gr{async _call(e){return new _e(await super._call(e))}},P0=class extends Gr{async _call(e){return new Ae(await super._call(e))}};var qr=class extends y{},z0=class extends qr{},L0=class extends qr{async _call(e){return new we(await super._call(e))}},N0=class extends qr{async _call(e){return new F(await super._call(e))}},$0=class extends qr{async _call(e){return new _e(await super._call(e))}},R0=class extends qr{async _call(e){return new Ae(await super._call(e))}};var pi=class extends y{},U0=class extends pi{},B0=class extends pi{async _call(e){return new Qc(await super._call(e))}},Qc=class extends ze{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var di=class extends y{},D0=class extends di{},F0=class extends di{};var qP=new Map([["bert","BertModel"],["neobert","NeoBertModel"],["modernbert","ModernBertModel"],["nomic_bert","NomicBertModel"],["roformer","RoFormerModel"],["electra","ElectraModel"],["esm","EsmModel"],["convbert","ConvBertModel"],["camembert","CamembertModel"],["deberta","DebertaModel"],["deberta-v2","DebertaV2Model"],["mpnet","MPNetModel"],["albert","AlbertModel"],["distilbert","DistilBertModel"],["roberta","RobertaModel"],["xlm","XLMModel"],["xlm-roberta","XLMRobertaModel"],["clap","ClapModel"],["clip","CLIPModel"],["clipseg","CLIPSegModel"],["chinese_clip","ChineseCLIPModel"],["siglip","SiglipModel"],["jina_clip","JinaCLIPModel"],["mobilebert","MobileBertModel"],["squeezebert","SqueezeBertModel"],["wav2vec2","Wav2Vec2Model"],["wav2vec2-bert","Wav2Vec2BertModel"],["unispeech","UniSpeechModel"],["unispeech-sat","UniSpeechSatModel"],["hubert","HubertModel"],["wavlm","WavLMModel"],["audio-spectrogram-transformer","ASTModel"],["vits","VitsModel"],["pyannote","PyAnnoteModel"],["wespeaker-resnet","WeSpeakerResNetModel"],["detr","DetrModel"],["rt_detr","RTDetrModel"],["rt_detr_v2","RTDetrV2Model"],["rf_detr","RFDetrModel"],["d_fine","DFineModel"],["table-transformer","TableTransformerModel"],["vit","ViTModel"],["ijepa","IJepaModel"],["pvt","PvtModel"],["vit_msn","ViTMSNModel"],["vit_mae","ViTMAEModel"],["groupvit","GroupViTModel"],["fastvit","FastViTModel"],["mobilevit","MobileViTModel"],["mobilevitv2","MobileViTV2Model"],["owlvit","OwlViTModel"],["owlv2","Owlv2Model"],["beit","BeitModel"],["deit","DeiTModel"],["hiera","HieraModel"],["convnext","ConvNextModel"],["convnextv2","ConvNextV2Model"],["dinov2","Dinov2Model"],["dinov2_with_registers","Dinov2WithRegistersModel"],["dinov3_vit","DINOv3ViTModel"],["dinov3_convnext","DINOv3ConvNextModel"],["resnet","ResNetModel"],["swin","SwinModel"],["swin2sr","Swin2SRModel"],["donut-swin","DonutSwinModel"],["yolos","YolosModel"],["dpt","DPTModel"],["glpn","GLPNModel"],["hifigan","SpeechT5HifiGan"],["efficientnet","EfficientNetModel"],["decision_transformer","DecisionTransformerModel"],["patchtst","PatchTSTModel"],["patchtsmixer","PatchTSMixerModel"],["mobilenet_v1","MobileNetV1Model"],["mobilenet_v2","MobileNetV2Model"],["mobilenet_v3","MobileNetV3Model"],["mobilenet_v4","MobileNetV4Model"],["maskformer","MaskFormerModel"],["mgp-str","MgpstrForSceneTextRecognition"],["style_text_to_speech_2","StyleTextToSpeech2Model"]]),WP=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),VP=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),HP=new Map([["bloom","BloomModel"],["jais","JAISModel"],["gpt2","GPT2Model"],["gpt_oss","GptOssModel"],["gptj","GPTJModel"],["gpt_bigcode","GPTBigCodeModel"],["gpt_neo","GPTNeoModel"],["gpt_neox","GPTNeoXModel"],["codegen","CodeGenModel"],["llama","LlamaModel"],["apertus","ApertusModel"],["nanochat","NanoChatModel"],["arcee","ArceeModel"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen3","Qwen3Model"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5_Model"],["starcoder2","Starcoder2Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"]]),iA=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"]]),lA=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),cA=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),uA=new Map([["bert","BertForSequenceClassification"],["neobert","NeoBertForSequenceClassification"],["modernbert","ModernBertForSequenceClassification"],["roformer","RoFormerForSequenceClassification"],["electra","ElectraForSequenceClassification"],["esm","EsmForSequenceClassification"],["convbert","ConvBertForSequenceClassification"],["camembert","CamembertForSequenceClassification"],["deberta","DebertaForSequenceClassification"],["deberta-v2","DebertaV2ForSequenceClassification"],["mpnet","MPNetForSequenceClassification"],["albert","AlbertForSequenceClassification"],["distilbert","DistilBertForSequenceClassification"],["roberta","RobertaForSequenceClassification"],["xlm","XLMForSequenceClassification"],["xlm-roberta","XLMRobertaForSequenceClassification"],["bart","BartForSequenceClassification"],["mbart","MBartForSequenceClassification"],["mobilebert","MobileBertForSequenceClassification"],["squeezebert","SqueezeBertForSequenceClassification"]]),pA=new Map([["bert","BertForTokenClassification"],["neobert","NeoBertForTokenClassification"],["modernbert","ModernBertForTokenClassification"],["roformer","RoFormerForTokenClassification"],["electra","ElectraForTokenClassification"],["esm","EsmForTokenClassification"],["convbert","ConvBertForTokenClassification"],["camembert","CamembertForTokenClassification"],["deberta","DebertaForTokenClassification"],["deberta-v2","DebertaV2ForTokenClassification"],["mpnet","MPNetForTokenClassification"],["distilbert","DistilBertForTokenClassification"],["roberta","RobertaForTokenClassification"],["xlm","XLMForTokenClassification"],["xlm-roberta","XLMRobertaForTokenClassification"]]),dA=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),fA=new Map([["bloom","BloomForCausalLM"],["gpt2","GPT2LMHeadModel"],["gpt_oss","GptOssForCausalLM"],["jais","JAISLMHeadModel"],["gptj","GPTJForCausalLM"],["gpt_bigcode","GPTBigCodeForCausalLM"],["gpt_neo","GPTNeoForCausalLM"],["gpt_neox","GPTNeoXForCausalLM"],["codegen","CodeGenForCausalLM"],["llama","LlamaForCausalLM"],["nanochat","NanoChatForCausalLM"],["apertus","ApertusForCausalLM"],["llama4_text","Llama4ForCausalLM"],["arcee","ArceeForCausalLM"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen3","Qwen3ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5_ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["trocr","TrOCRForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),XP=new Map([["multi_modality","MultiModalityCausalLM"]]),mA=new Map([["bert","BertForMaskedLM"],["neobert","NeoBertForMaskedLM"],["modernbert","ModernBertForMaskedLM"],["roformer","RoFormerForMaskedLM"],["electra","ElectraForMaskedLM"],["esm","EsmForMaskedLM"],["convbert","ConvBertForMaskedLM"],["camembert","CamembertForMaskedLM"],["deberta","DebertaForMaskedLM"],["deberta-v2","DebertaV2ForMaskedLM"],["mpnet","MPNetForMaskedLM"],["albert","AlbertForMaskedLM"],["distilbert","DistilBertForMaskedLM"],["roberta","RobertaForMaskedLM"],["xlm","XLMWithLMHeadModel"],["xlm-roberta","XLMRobertaForMaskedLM"],["mobilebert","MobileBertForMaskedLM"],["squeezebert","SqueezeBertForMaskedLM"]]),hA=new Map([["bert","BertForQuestionAnswering"],["neobert","NeoBertForQuestionAnswering"],["roformer","RoFormerForQuestionAnswering"],["electra","ElectraForQuestionAnswering"],["convbert","ConvBertForQuestionAnswering"],["camembert","CamembertForQuestionAnswering"],["deberta","DebertaForQuestionAnswering"],["deberta-v2","DebertaV2ForQuestionAnswering"],["mpnet","MPNetForQuestionAnswering"],["albert","AlbertForQuestionAnswering"],["distilbert","DistilBertForQuestionAnswering"],["roberta","RobertaForQuestionAnswering"],["xlm","XLMForQuestionAnswering"],["xlm-roberta","XLMRobertaForQuestionAnswering"],["mobilebert","MobileBertForQuestionAnswering"],["squeezebert","SqueezeBertForQuestionAnswering"]]),_A=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),gA=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2-vl","Qwen2VLForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3n","Gemma3nForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"]]),wA=new Map([["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"]]),KP=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),xA=new Map([["vit","ViTForImageClassification"],["ijepa","IJepaForImageClassification"],["pvt","PvtForImageClassification"],["vit_msn","ViTMSNForImageClassification"],["fastvit","FastViTForImageClassification"],["mobilevit","MobileViTForImageClassification"],["mobilevitv2","MobileViTV2ForImageClassification"],["beit","BeitForImageClassification"],["deit","DeiTForImageClassification"],["hiera","HieraForImageClassification"],["convnext","ConvNextForImageClassification"],["convnextv2","ConvNextV2ForImageClassification"],["dinov2","Dinov2ForImageClassification"],["dinov2_with_registers","Dinov2WithRegistersForImageClassification"],["resnet","ResNetForImageClassification"],["swin","SwinForImageClassification"],["segformer","SegformerForImageClassification"],["efficientnet","EfficientNetForImageClassification"],["mobilenet_v1","MobileNetV1ForImageClassification"],["mobilenet_v2","MobileNetV2ForImageClassification"],["mobilenet_v3","MobileNetV3ForImageClassification"],["mobilenet_v4","MobileNetV4ForImageClassification"]]),yA=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),bA=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),An=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),vA=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),kA=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),EA=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),AA=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),MA=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),TA=new Map([["wavlm","WavLMForXVector"]]),SA=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),OA=new Map([["vitmatte","VitMatteForImageMatting"]]),YP=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),IA=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),CA=new Map([["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),PA=new Map([["sapiens","SapiensForNormalEstimation"]]),zA=new Map([["vitpose","VitPoseForPoseEstimation"]]),LA=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),j0=[[qP,H.EncoderOnly],[WP,H.EncoderDecoder],[HP,H.DecoderOnlyWithoutHead],[VP,H.AutoEncoder],[uA,H.EncoderOnly],[pA,H.EncoderOnly],[dA,H.Seq2Seq],[iA,H.Seq2Seq],[fA,H.DecoderOnly],[XP,H.MultiModality],[mA,H.EncoderOnly],[hA,H.EncoderOnly],[_A,H.Vision2Seq],[gA,H.ImageTextToText],[wA,H.AudioTextToText],[xA,H.EncoderOnly],[An,H.EncoderOnly],[kA,H.EncoderOnly],[vA,H.EncoderOnly],[OA,H.EncoderOnly],[YP,H.EncoderOnly],[IA,H.EncoderOnly],[CA,H.EncoderOnly],[PA,H.EncoderOnly],[zA,H.EncoderOnly],[yA,H.EncoderOnly],[bA,H.EncoderOnly],[EA,H.MaskGeneration],[AA,H.EncoderOnly],[MA,H.EncoderOnly],[lA,H.Seq2Seq],[cA,H.EncoderOnly],[TA,H.EncoderOnly],[SA,H.EncoderOnly],[LA,H.EncoderOnly]];for(let[t,e]of j0)for(let r of t.values()){ws.set(r,e);let s=fi[r];gs.set(s,r),Ql.set(r,s)}var QP=[["MusicgenForConditionalGeneration",Sa,H.Musicgen],["Phi3VForCausalLM",Fa,H.Phi3V],["CLIPTextModelWithProjection",ko,H.EncoderOnly],["SiglipTextModel",Qa,H.EncoderOnly],["JinaCLIPTextModel",ca,H.EncoderOnly],["ClapTextModelWithProjection",bo,H.EncoderOnly],["ClapAudioModelWithProjection",vo,H.EncoderOnly],["DacEncoderModel",Po,H.EncoderOnly],["DacDecoderModel",zo,H.EncoderOnly],["MimiEncoderModel",ga,H.EncoderOnly],["MimiDecoderModel",wa,H.EncoderOnly],["SnacEncoderModel",Za,H.EncoderOnly],["SnacDecoderModel",ei,H.EncoderOnly],["Gemma3nForConditionalGeneration",Ho,H.ImageAudioTextToText],["SupertonicForConditionalGeneration",si,H.Supertonic],["ChatterboxModel",yo,H.Chatterbox]];for(let[t,e,r]of QP)ws.set(t,r),gs.set(e,t),Ql.set(t,e);var G0=new Map([["modnet",An],["birefnet",An],["isnet",An],["ben",An]]);for(let[t,e]of G0.entries())e.set(t,"PreTrainedModel"),ws.set(t,H.EncoderOnly),Ql.set(t,y);ws.set("PreTrainedModel",H.EncoderOnly);gs.set(y,"PreTrainedModel");var Ie={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:uA,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:pA,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:lA,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:cA,MODEL_FOR_MASKED_LM_MAPPING_NAMES:mA,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:hA,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:xA,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:An,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:vA,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:kA,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:yA,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:bA,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:EA,MODEL_FOR_CTC_MAPPING_NAMES:AA,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:MA,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:TA,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:SA,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:KP,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:OA,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:IA,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:CA,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:PA,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:zA,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:LA,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:gA,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:wA,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:dA,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:iA,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:fA,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:_A};sA(Ie);var Se=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:u=null,dtype:d=null,use_external_data_format:f=null,session_options:m={}}={}){let _={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:u,dtype:d,use_external_data_format:f,session_options:m};if(_.config=await ms.from_pretrained(e,_),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let w=_.config.model_type;for(let x of this.MODEL_CLASS_MAPPINGS){let k=x.get(w);if(!k){for(let E of x.values())if(E[0]===w){k=E;break}if(!k)continue}return await fi[k].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return G0.has(w)||console.warn(`Unknown model class "${w}", attempting to construct from base class.`),await y.from_pretrained(e,_);throw Error(`Unsupported model type: ${w}`)}},wr=class extends Se{static MODEL_CLASS_MAPPINGS=j0.map(e=>e[0]);static BASE_IF_FAIL=!0},mi=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},Jc=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},Mn=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},Zc=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},eu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},tu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},ru=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},su=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},nu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},ou=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},au=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},hi=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},_i=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},gi=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},iu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},lu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},NA=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},cu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_CTC_MAPPING_NAMES]},uu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},$A=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},RA=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},pu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},UA=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},du=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},fu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},BA=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},DA=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},mu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},FA=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},jA=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function Ye(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>Xe.read(e)))}async function Wr(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?yf(r,e):r instanceof Float64Array?new Float32Array(r):r))}function wi(t,e){e&&(t=t.map(a=>a|0));let[r,s,n,o]=t;return{xmin:r,ymin:s,xmax:n,ymax:o}}var pe=class extends Je{constructor({task:e,model:r,tokenizer:s=null,processor:n=null}){super(),this.task=e,this.model=r,this.tokenizer=s,this.processor=n}async dispose(){await this.model.dispose()}};var hu=class extends pe{async _call(e,{top_k:r=1}={}){let s=this.tokenizer(e,{padding:!0,truncation:!0}),n=await this.model(s),{problem_type:o,id2label:a}=this.model.config,i=o==="multi_label_classification"?u=>u.sigmoid():u=>new U("float32",Pe(u.data),u.dims),l=[];for(let u of n.logits){let d=i(u),f=await Yt(d,r),m=f[0].tolist(),w=f[1].tolist().map((x,k)=>({label:a?a[x]:`LABEL_${x}`,score:m[k]}));r===1?l.push(...w):l.push(w)}return Array.isArray(e)||r===1?l:l[0]}};var _u=class extends pe{async _call(e,{ignore_labels:r=["O"]}={}){let s=Array.isArray(e),n=this.tokenizer(s?e:[e],{padding:!0,truncation:!0}),a=(await this.model(n)).logits,i=this.model.config.id2label,l=[];for(let u=0;u<a.dims[0];++u){let d=n.input_ids[u],f=a[u],m=[];for(let _=0;_<f.dims[0];++_){let w=f[_],x=Te(w.data)[1],k=i?i[x]:`LABEL_${x}`;if(r.includes(k))continue;let E=this.tokenizer.decode([d[_].item()],{skip_special_tokens:!0});if(E==="")continue;let M=Pe(w.data);m.push({entity:k,score:M[x],index:_,word:E})}l.push(m)}return s?l:l[0]}};var gu=class extends pe{async _call(e,r,{top_k:s=1}={}){let n=this.tokenizer(e,{text_pair:r,padding:!0,truncation:!0}),o=Array.isArray(e),{start_logits:a,end_logits:i}=await this.model(n),l=n.input_ids.tolist(),u=n.attention_mask.tolist(),{all_special_ids:d,sep_token_id:f}=this.tokenizer,m=[];for(let _=0;_<a.dims[0];++_){let w=l[_],x=w.findIndex(C=>C==f),k=a[_].tolist(),E=i[_].tolist();for(let C=1;C<k.length;++C)(u[_]==0||C<=x||d.findIndex(v=>v==w[C])!==-1)&&(k[C]=-1/0,E[C]=-1/0);let M=Pe(k).map((C,v)=>[C,v]),I=Pe(E).map((C,v)=>[C,v]);M[0][0]=0,I[0][0]=0;let T=$v(M,I).filter(C=>C[0][1]<=C[1][1]).map(C=>[C[0][1],C[1][1],C[0][0]*C[1][0]]).sort((C,v)=>v[2]-C[2]),z=[];for(let C=0;C<Math.min(T.length,s);++C){let[v,G,X]=T[C],V=w.slice(v,G+1),Q=this.tokenizer.decode(V,{skip_special_tokens:!0});z.push({answer:Q,score:X})}s===1?m.push(...z):m.push(z)}return o?m:m[0]}};var wu=class extends pe{async _call(e,{top_k:r=5}={}){let{mask_token_id:s,mask_token:n}=this.tokenizer,o=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(o),i=[],l=o.input_ids.tolist();for(let u=0;u<l.length;++u){let d=l[u],f=d.findIndex(k=>k==s);if(f===-1)throw Error(`Mask token (${n}) not found in text.`);let m=a[u][f],_=await Yt(new U("float32",Pe(m.data),m.dims),r),w=_[0].tolist(),x=_[1].tolist();i.push(x.map((k,E)=>{let M=d.slice();return M[f]=k,{score:w[E],token:Number(k),token_str:this.tokenizer.decode([k]),sequence:this.tokenizer.decode(M,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}};var Vr=class extends pe{_key="generated_text";async _call(e,r={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(l=>this.model.config.prefix+l));let s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(e=e.map(l=>s[this.task].prefix+l));let n=this.tokenizer,o={padding:!0,truncation:!0},a;this.task==="translation"&&"_build_translation_inputs"in n?a=n._build_translation_inputs(e,o,r):a=n(e,o);let i=await this.model.generate({...a,...r});return n.batch_decode(i,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}};var xu=class extends Vr{_key="summary_text"};var yu=class extends Vr{_key="translation_text"};function GA(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var bu=class extends pe{async _call(e,r={}){let s=!1,n=!1,o=r.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,a=r.tokenizer_encode_kwargs,i;if(typeof e=="string")i=e=[e];else if(Array.isArray(e)&&e.every(w=>typeof w=="string"))s=!0,i=e;else{if(GA(e))e=[e];else if(Array.isArray(e)&&e.every(GA))s=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");n=!0,i=e.map(w=>this.tokenizer.apply_chat_template(w,{tokenize:!1,add_generation_prompt:!0,...a})),o=!1,a=void 0}let l=n?!1:r.return_full_text??!0;this.tokenizer.padding_side="left";let u=this.tokenizer(i,{add_special_tokens:o,padding:!0,truncation:!0,...a}),d=await this.model.generate({...u,...r}),f=this.tokenizer.batch_decode(d,{skip_special_tokens:!0}),m;!l&&u.input_ids.dims.at(-1)>0&&(m=this.tokenizer.batch_decode(u.input_ids,{skip_special_tokens:!0}).map(w=>w.length));let _=Array.from({length:e.length},w=>[]);for(let w=0;w<f.length;++w){let x=Math.floor(w/d.dims[0]*e.length);m&&(f[w]=f[w].slice(m[x])),_[x].push({generated_text:n?[...e[x],{role:"assistant",content:f[w]}]:f[w]})}return!s&&_.length===1?_[0]:_}};var vu=class extends pe{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([r,s])=>[r.toLowerCase(),s])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,r,{hypothesis_template:s="This example is {}.",multi_label:n=!1}={}){let o=Array.isArray(e);o||(e=[e]),Array.isArray(r)||(r=[r]);let a=r.map(u=>s.replace("{}",u)),i=n||r.length===1,l=[];for(let u of e){let d=[];for(let _ of a){let w=this.tokenizer(u,{text_pair:_,padding:!0,truncation:!0}),x=await this.model(w);i?d.push([x.logits.data[this.contradiction_id],x.logits.data[this.entailment_id]]):d.push(x.logits.data[this.entailment_id])}let m=(i?d.map(_=>Pe(_)[1]):Pe(d)).map((_,w)=>[_,w]).sort((_,w)=>w[0]-_[0]);l.push({sequence:u,labels:m.map(_=>r[_[1]]),scores:m.map(_=>_[0])})}return o?l:l[0]}};var ku=class extends pe{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await Wr(e,s),o=this.model.config.id2label,a=[];for(let i of n){let l=await this.processor(i),d=(await this.model(l)).logits[0],f=await Yt(new U("float32",Pe(d.data),d.dims),r),m=f[0].tolist(),w=f[1].tolist().map((x,k)=>({label:o?o[x]:`LABEL_${x}`,score:m[k]}));a.push(w)}return Array.isArray(e)?a:a[0]}};var Eu=class extends pe{async _call(e,r,{hypothesis_template:s="This is a sound of {}."}={}){let n=!Array.isArray(e);n&&(e=[e]);let o=r.map(d=>s.replace("{}",d)),a=this.tokenizer(o,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,l=await Wr(e,i),u=[];for(let d of l){let f=await this.processor(d),m=await this.model({...a,...f}),_=Pe(m.logits_per_audio.data);u.push([..._].map((w,x)=>({score:w,label:r[x]})))}return n?u[0]:u}};var Au=class extends pe{async _call(e,r={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,r);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,r);case"moonshine":return this._call_moonshine(e,r);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,r){r.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await Wr(n,o),i=[];for(let l of a){let u=await this.processor(l),f=(await this.model(u)).logits[0],m=[];for(let w of f)m.push(Te(w.data)[1]);let _=this.tokenizer.decode(m,{skip_special_tokens:!0}).trim();i.push({text:_})}return s?i[0]:i}async _call_whisper(e,r){let s=r.return_timestamps??!1,n=r.chunk_length_s??0,o=r.force_full_sequences??!1,a=r.stride_length_s??null,i={...r};s==="word"&&(i.return_token_timestamps=!0,i.return_timestamps=!1);let l=!Array.isArray(e),u=l?[e]:e,d=this.processor.feature_extractor.config,f=d.chunk_length/this.model.config.max_source_positions,m=d.hop_length,_=d.sampling_rate,w=await Wr(u,_),x=[];for(let k of w){let E=[];if(n>0){if(a===null)a=n/6;else if(n<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let T=_*n,z=_*a,C=T-2*z,v=0;for(;;){let G=v+T,X=k.subarray(v,G),V=await this.processor(X),Q=v===0,K=G>=k.length;if(E.push({stride:[X.length,Q?0:z,K?0:z],input_features:V.input_features,is_last:K}),K)break;v+=C}}else E=[{stride:[k.length,0,0],input_features:(await this.processor(k)).input_features,is_last:!0}];for(let T of E){i.num_frames=Math.floor(T.stride[0]/m);let z=await this.model.generate({inputs:T.input_features,...i});s==="word"?(T.tokens=z.sequences.tolist()[0],T.token_timestamps=z.token_timestamps.tolist()[0].map(C=>rs(C,2))):T.tokens=z[0].tolist(),T.stride=T.stride.map(C=>C/_)}let[M,I]=this.tokenizer._decode_asr(E,{time_precision:f,return_timestamps:s,force_full_sequences:o});x.push({text:M,...I})}return l?x[0]:x}async _call_moonshine(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await Wr(n,o),i=[];for(let l of a){let u=await this.processor(l),d=Math.floor(l.length/o)*6,f=await this.model.generate({max_new_tokens:d,...r,...u}),m=this.processor.batch_decode(f,{skip_special_tokens:!0})[0];i.push({text:m})}return s?i[0]:i}};var Mu=class extends pe{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,r){if((typeof e=="string"||e instanceof URL)&&(e=new Float32Array(await(await fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new U("float32",e,[e.length]);else if(!(e instanceof U))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(e.dims[0]===1)e=e.repeat(r,1);else if(e.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,r,s,n=null){let o=r.data,[a,i]=r.dims,l=n?n.data:null,u=[];for(let d=0;d<a;++d){let f=l?Math.min(Math.ceil(l[d]),i):i,m=d*i;u.push(new to(o.slice(m,m+f),s))}return Array.isArray(e)?u:u[0]}async _call(e,r){return this.processor?this._call_text_to_spectrogram(e,r):this.model.config.model_type==="supertonic"?this._call_supertonic(e,r):this._call_text_to_waveform(e)}async _call_supertonic(e,{speaker_embeddings:r,num_inference_steps:s,speed:n}){if(!r)throw new Error("Speaker embeddings must be provided for Supertonic models.");let{sampling_rate:o,style_dim:a}=this.model.config,i=this.tokenizer(e,{padding:!0,truncation:!0}),l=i.input_ids.dims[0];r=await this._prepare_speaker_embeddings(r,l),r=r.view(l,-1,a);let{waveform:u,durations:d}=await this.model.generate_speech({...i,style:r,num_inference_steps:s,speed:n});return this._postprocess_waveform(e,u,o,d)}async _call_text_to_waveform(e){let r=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:s}=await this.model(r),n=this.model.config.sampling_rate;return this._postprocess_waveform(e,s,n)}async _call_text_to_spectrogram(e,{speaker_embeddings:r}){this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await wr.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));let{input_ids:s}=this.tokenizer(e,{padding:!0,truncation:!0}),n=s.dims[0];r=await this._prepare_speaker_embeddings(r,n),r=r.view(n,-1);let{waveform:o}=await this.model.generate_speech(s,r,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(e,o,a)}};var Tu=class extends pe{async _call(e,r={}){let s=Array.isArray(e),n=await Ye(e),{pixel_values:o}=await this.processor(n),a=[];for(let i of o){i.dims=[1,...i.dims];let l=await this.model.generate({inputs:i,...r}),u=this.tokenizer.batch_decode(l,{skip_special_tokens:!0}).map(d=>({generated_text:d.trim()}));a.push(u)}return s?a:a[0]}};var Su=class extends pe{async _call(e,{top_k:r=5}={}){let s=await Ye(e),{pixel_values:n}=await this.processor(s),o=await this.model({pixel_values:n}),{id2label:a}=this.model.config,i=[];for(let l of o.logits){let u=await Yt(new U("float32",Pe(l.data),l.dims),r),d=u[0].tolist(),m=u[1].tolist().map((_,w)=>({label:a?a[_]:`LABEL_${_}`,score:d[w]}));i.push(m)}return Array.isArray(e)?i:i[0]}};var qA={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},Tn=class extends pe{async _call(e,{threshold:r=.5,mask_threshold:s=.5,overlap_mask_area_threshold:n=.8,label_ids_to_fuse:o=null,target_sizes:a=null,subtask:i=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let u=await Ye(e),d=u.map(M=>[M.height,M.width]),f=await this.processor(u),{inputNames:m,outputNames:_}=this.model.sessions.model;if(!m.includes("pixel_values")){if(m.length!==1)throw Error(`Expected a single input name, but got ${m.length} inputs: ${m}.`);let M=m[0];if(M in f)throw Error(`Input name ${M} already exists in the inputs.`);f[M]=f.pixel_values}let w=await this.model(f),x=null;if(i!==null)x=qA[i];else if(this.processor.image_processor){for(let[M,I]of Object.entries(qA))if(I in this.processor.image_processor){x=this.processor.image_processor[I].bind(this.processor.image_processor),i=M;break}}let k=this.model.config.id2label,E=[];if(i)if(i==="panoptic"||i==="instance"){let M=x(w,r,s,n,o,a??d)[0],I=M.segmentation;for(let T of M.segments_info){let z=new Uint8ClampedArray(I.data.length);for(let v=0;v<I.data.length;++v)I.data[v]===T.id&&(z[v]=255);let C=new Xe(z,I.dims[1],I.dims[0],1);E.push({score:T.score,label:k[T.label_id],mask:C})}}else if(i==="semantic"){let{segmentation:M,labels:I}=x(w,a??d)[0];for(let T of I){let z=new Uint8ClampedArray(M.data.length);for(let v=0;v<M.data.length;++v)M.data[v]===T&&(z[v]=255);let C=new Xe(z,M.dims[1],M.dims[0],1);E.push({score:null,label:k[T],mask:C})}}else throw Error(`Subtask ${i} not supported.`);else{let I=w[_[0]];for(let T=0;T<d.length;++T){let z=d[T],C=I[T];C.data.some(G=>G<-1e-5||G>1+1e-5)&&C.sigmoid_();let v=await Xe.fromTensor(C.mul_(255).to("uint8")).resize(z[1],z[0]);E.push({label:null,score:null,mask:v})}}return E}};var Ou=class extends Tn{async _call(e,r={}){let s=await Ye(e),n=await super._call(e,r),o=s.map((a,i)=>{let l=a.clone();return l.putAlpha(n[i].mask),l});return Array.isArray(e)?o:o[0]}};var Iu=class extends pe{async _call(e,r,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),o=await Ye(e),a=r.map(m=>s.replace("{}",m)),i=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:l}=await this.processor(o),u=await this.model({...i,pixel_values:l}),d=this.model.config.model_type==="siglip"?m=>m.sigmoid().data:m=>Pe(m.data),f=[];for(let m of u.logits_per_image){let w=[...d(m)].map((x,k)=>({score:x,label:r[k]}));w.sort((x,k)=>k.score-x.score),f.push(w)}return n?f:f[0]}};var Cu=class extends pe{async _call(e,{threshold:r=.9,percentage:s=!1}={}){let n=Array.isArray(e);if(n&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let o=await Ye(e),a=s?null:o.map(_=>[_.height,_.width]),{pixel_values:i,pixel_mask:l}=await this.processor(o),u=await this.model({pixel_values:i,pixel_mask:l}),d=this.processor.image_processor.post_process_object_detection(u,r,a),{id2label:f}=this.model.config,m=d.map(_=>_.boxes.map((w,x)=>({score:_.scores[x],label:f[_.classes[x]],box:wi(w,!s)})));return n?m:m[0]}};var Pu=class extends pe{async _call(e,r,{threshold:s=.1,top_k:n=null,percentage:o=!1}={}){let a=Array.isArray(e),i=await Ye(e),l=this.tokenizer(r,{padding:!0,truncation:!0}),u=await this.processor(i),d=[];for(let f=0;f<i.length;++f){let m=i[f],_=o?null:[[m.height,m.width]],w=u.pixel_values[f].unsqueeze_(0),x=await this.model({...l,pixel_values:w}),k;if("post_process_grounded_object_detection"in this.processor){let E=this.processor.post_process_grounded_object_detection(x,l.input_ids,{box_threshold:s,text_threshold:s,target_sizes:_})[0];k=E.boxes.map((M,I)=>({score:E.scores[I],label:E.labels[I],box:wi(M,!o)}))}else{let E=this.processor.image_processor.post_process_object_detection(x,s,_,!0)[0];k=E.boxes.map((M,I)=>({score:E.scores[I],label:r[E.classes[I]],box:wi(M,!o)}))}k.sort((E,M)=>M.score-E.score),n!==null&&(k=k.slice(0,n)),d.push(k)}return a?d:d[0]}};var zu=class extends pe{async _call(e,r,s={}){if(Array.isArray(e)){if(e.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}let n=(await Ye(e))[0],{pixel_values:o}=await this.processor(n),a=`<s_docvqa><s_question>${r}</s_question><s_answer>`,i=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,l=await this.model.generate({inputs:o,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...s}),d=this.tokenizer.batch_decode(l)[0].match(/<s_answer>(.*?)<\/s_answer>/),f=null;return d&&d.length>=2&&(f=d[1].trim()),[{answer:f}]}};var Lu=class extends pe{async _call(e){let r=await Ye(e),s=await this.processor(r),n=await this.model(s),o=[];for(let a of n.reconstruction){let i=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");o.push(Xe.fromTensor(i))}return Array.isArray(e)?o:o[0]}};var Nu=class extends pe{async _call(e){let r=await Ye(e),s=await this.processor(r),{predicted_depth:n}=await this.model(s),o=[];for(let a=0;a<r.length;++a){let i=n[a],[l,u]=i.dims.slice(-2),[d,f]=r[a].size,m=(await Dt(i.view(1,1,l,u),{size:[f,d],mode:"bilinear"})).view(f,d),_=m.min().item(),w=m.max().item(),x=m.sub(_).div_(w-_).mul_(255).to("uint8").unsqueeze(0),k=Xe.fromTensor(x);o.push({predicted_depth:m,depth:k})}return Array.isArray(e)?o:o[0]}};var $u=class extends pe{async _call(e,{pooling:r="none",normalize:s=!1,quantize:n=!1,precision:o="binary"}={}){let a=this.tokenizer(e,{padding:!0,truncation:!0}),i=await this.model(a),l=i.last_hidden_state??i.logits??i.token_embeddings;switch(r){case"none":break;case"mean":l=LE(l,a.attention_mask);break;case"first_token":case"cls":l=l.slice(null,0);break;case"last_token":case"eos":l=l.slice(null,-1);break;default:throw Error(`Pooling method '${r}' not supported.`)}return s&&(l=l.normalize(2,-1)),n&&(l=$E(l,o)),l}};var Ru=class extends pe{async _call(e,{pool:r=null}={}){let s=await Ye(e),{pixel_values:n}=await this.processor(s),o=await this.model({pixel_values:n}),a;if(r){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.");a=o.pooler_output}else a=o.last_hidden_state??o.logits??o.image_embeds;return a}};var WA=Object.freeze({"text-classification":{tokenizer:J,pipeline:hu,model:mi,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:J,pipeline:_u,model:Jc,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:J,pipeline:gu,model:nu,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:J,pipeline:wu,model:su,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{tokenizer:J,pipeline:xu,model:Mn,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:J,pipeline:yu,model:Mn,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:J,pipeline:Vr,model:Mn,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:J,pipeline:bu,model:ru,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{tokenizer:J,pipeline:vu,model:mi,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:ku,model:uu,processor:ut,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:J,pipeline:Eu,model:wr,processor:ut,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:J,pipeline:Au,model:[Zc,cu],processor:ut,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:J,pipeline:Mu,model:[tu,eu],processor:[ut,null],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{tokenizer:J,pipeline:Tu,model:ou,processor:ut,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Su,model:au,processor:ut,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Tn,model:[hi,_i,gi],processor:ut,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:Ou,model:[hi,_i,gi],processor:ut,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:J,pipeline:Iu,model:wr,processor:ut,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:Cu,model:iu,processor:ut,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:J,pipeline:Pu,model:lu,processor:ut,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:J,pipeline:zu,model:pu,processor:ut,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Lu,model:du,processor:ut,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Nu,model:fu,processor:ut,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{tokenizer:J,pipeline:$u,model:wr,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{processor:ut,pipeline:Ru,model:[mu,wr],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),JP=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function Iee(t,e=null,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",device:i=null,dtype:l=null,subfolder:u="onnx",use_external_data_format:d=null,model_file_name:f=null,session_options:m={}}={}){t=JP[t]??t;let _=WA[t.split("_",1)[0]];if(!_)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(WA)}]`);e||(e=_.default.model,console.log(`No model specified. Using default model: "${e}".`),!l&&_.default.dtype&&(l=_.default.dtype));let w={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,device:i,dtype:l,subfolder:u,use_external_data_format:d,model_file_name:f,session_options:m},x=new Map([["tokenizer",_.tokenizer],["model",_.model],["processor",_.processor]]),k=await ZP(x,e,w);k.task=t,hr(r,{status:"ready",task:t,model:e});let E=_.pipeline;return new E(k)}async function ZP(t,e,r){let s=Object.create(null),n=[];for(let[o,a]of t.entries()){if(!a)continue;let i;Array.isArray(a)?i=new Promise(async(l,u)=>{let d;for(let f of a){if(f===null){l(null);return}try{l(await f.from_pretrained(e,r));return}catch(m){if(m.message?.includes("Unsupported model type"))d=m;else if(m.message?.includes("Could not locate file"))d=m;else{u(m);return}}}u(d)}):i=a.from_pretrained(e,r),s[o]=i,n.push(i)}await Promise.all(n);for(let[o,a]of Object.entries(s))s[o]=await a;return s}var ez=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,q0=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},VA=be.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),W0=class extends q0{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,skip_special_tokens:o=!0,decode_kwargs:a={},...i}={}){super(),this.tokenizer=e,this.skip_prompt=r,this.callback_function=s??VA,this.token_callback_function=n,this.decode_kwargs={skip_special_tokens:o,...a,...i},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");let r=this.next_tokens_are_prompt;if(r&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let s=e[0];if(this.token_callback_function?.(s),s.length===1&&this.special_ids.has(s[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let l=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(l,!1),this.token_cache=[],this.print_len=0}let a=this.tokenizer.decode(s,this.decode_kwargs);this.on_finalized_text(a,!1);return}this.token_cache=dt(this.token_cache,s);let n=this.tokenizer.decode(this.token_cache,this.decode_kwargs),o;r||n.endsWith(`
28
- `)?(o=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&ez(n.charCodeAt(n.length-1))?(o=n.slice(this.print_len),this.print_len+=o.length):(o=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=o.length),this.on_finalized_text(o,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e="",this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,r){e.length>0&&this.callback_function?.(e),r&&this.callback_function===VA&&be.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
29
- `)}},HA=class extends W0{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,on_chunk_start:o=null,on_chunk_end:a=null,on_finalize:i=null,time_precision:l=.02,skip_special_tokens:u=!0,decode_kwargs:d={}}={}){super(e,{skip_prompt:r,skip_special_tokens:u,callback_function:s,token_callback_function:n,decode_kwargs:d}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=o,this.on_chunk_end=a,this.on_finalize=i,this.time_precision=l,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let r=e[0];if(r.length===1){let s=Number(r[0])-this.timestamp_begin;if(s>=0){let n=s*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(n):this.on_chunk_start?.(n),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(r);return}}return super.put(e)}end(){super.end(),this.on_finalize?.()}};var xi=class{constructor(e,r){this.image=e,this.timestamp=r}},Uu=class{constructor(e,r){e.length>0&&e[0]instanceof Xe&&(e=e.map((s,n)=>new xi(s,(n+1)/(e.length+1)*r))),this.frames=e,this.duration=r}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}};async function tz(t,{num_frames:e=null,fps:r=null}={}){if(!be.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(e==null&&r==null)throw new Error("Either num_frames or fps must be provided.");let s=[],n=document.createElement("video");if(n.crossOrigin="anonymous",n.muted=!0,typeof t=="string")n.src=t;else if(t instanceof Blob)n.src=URL.createObjectURL(t);else if(t instanceof HTMLVideoElement)n.src=t.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(f=>n.onloadedmetadata=f),n.seekable.start(0)===n.seekable.end(0)){let m=await(await fetch(n.src)).blob();n.src=URL.createObjectURL(m),await new Promise(_=>n.onloadedmetadata=_)}let o=n.duration,a,i;e!=null?(a=e,i=e===1?0:o/(e-1)):(i=1/r,a=Math.floor(o/i));let l=[];for(let f=0;f<a;++f)l.push(e===1?o/2:f*i);let u=document.createElement("canvas");u.width=n.videoWidth,u.height=n.videoHeight;let d=u.getContext("2d",{willReadFrequently:!0});for(let f of l){n.currentTime=f,await new Promise(x=>{n.onseeked=x}),d.drawImage(n,0,0,u.width,u.height);let m=d.getImageData(0,0,u.width,u.height),_=new Xe(m.data,u.width,u.height,4),w=new xi(_,f);s.push(w)}return n.remove(),new Uu(s,o)}export{bf as ASTFeatureExtractor,ah as ASTForAudioClassification,oh as ASTModel,ho as ASTPreTrainedModel,eh as AlbertForMaskedLM,Zm as AlbertForQuestionAnswering,Jm as AlbertForSequenceClassification,Qm as AlbertModel,xs as AlbertPreTrainedModel,Td as AlbertTokenizer,rh as ApertusForCausalLM,th as ApertusModel,fo as ApertusPreTrainedModel,nh as ArceeForCausalLM,sh as ArceeModel,mo as ArceePreTrainedModel,ku as AudioClassificationPipeline,ms as AutoConfig,tt as AutoFeatureExtractor,$e as AutoImageProcessor,wr as AutoModel,uu as AutoModelForAudioClassification,RA as AutoModelForAudioFrameClassification,jA as AutoModelForAudioTextToText,cu as AutoModelForCTC,ru as AutoModelForCausalLM,fu as AutoModelForDepthEstimation,pu as AutoModelForDocumentQuestionAnswering,au as AutoModelForImageClassification,mu as AutoModelForImageFeatureExtraction,UA as AutoModelForImageMatting,hi as AutoModelForImageSegmentation,FA as AutoModelForImageTextToText,du as AutoModelForImageToImage,NA as AutoModelForMaskGeneration,su as AutoModelForMaskedLM,BA as AutoModelForNormalEstimation,iu as AutoModelForObjectDetection,DA as AutoModelForPoseEstimation,nu as AutoModelForQuestionAnswering,_i as AutoModelForSemanticSegmentation,Mn as AutoModelForSeq2SeqLM,mi as AutoModelForSequenceClassification,Zc as AutoModelForSpeechSeq2Seq,eu as AutoModelForTextToSpectrogram,tu as AutoModelForTextToWaveform,Jc as AutoModelForTokenClassification,gi as AutoModelForUniversalSegmentation,ou as AutoModelForVision2Seq,$A as AutoModelForXVector,lu as AutoModelForZeroShotObjectDetection,ut as AutoProcessor,J as AutoTokenizer,Au as AutomaticSpeechRecognitionPipeline,Ou as BackgroundRemovalPipeline,lh as BartForConditionalGeneration,ch as BartForSequenceClassification,ih as BartModel,on as BartPretrainedModel,Sd as BartTokenizer,q0 as BaseStreamer,Rf as BeitFeatureExtractor,ph as BeitForImageClassification,uh as BeitModel,_o as BeitPreTrainedModel,fh as BertForMaskedLM,_h as BertForQuestionAnswering,mh as BertForSequenceClassification,hh as BertForTokenClassification,dh as BertModel,Cr as BertPreTrainedModel,Od as BertTokenizer,Uf as BitImageProcessor,wh as BlenderbotForConditionalGeneration,gh as BlenderbotModel,go as BlenderbotPreTrainedModel,yh as BlenderbotSmallForConditionalGeneration,xh as BlenderbotSmallModel,wo as BlenderbotSmallPreTrainedModel,Id as BlenderbotSmallTokenizer,Cd as BlenderbotTokenizer,vh as BloomForCausalLM,bh as BloomModel,xo as BloomPreTrainedModel,Pd as BloomTokenizer,Df as CLIPFeatureExtractor,ml as CLIPImageProcessor,Ih as CLIPModel,ir as CLIPPreTrainedModel,Nh as CLIPSegForImageSegmentation,Lh as CLIPSegModel,Eo as CLIPSegPreTrainedModel,Ch as CLIPTextModel,ko as CLIPTextModelWithProjection,Ld as CLIPTokenizer,Ph as CLIPVisionModel,zh as CLIPVisionModelWithProjection,Eh as CamembertForMaskedLM,Th as CamembertForQuestionAnswering,Ah as CamembertForSequenceClassification,Mh as CamembertForTokenClassification,kh as CamembertModel,Pr as CamembertPreTrainedModel,zd as CamembertTokenizer,vf as ChatterboxFeatureExtractor,yo as ChatterboxModel,Zl as ChatterboxPreTrainedModel,zf as ChatterboxProcessor,Bf as ChineseCLIPFeatureExtractor,Sh as ChineseCLIPModel,ec as ChineseCLIPPreTrainedModel,vo as ClapAudioModelWithProjection,kf as ClapFeatureExtractor,Oh as ClapModel,an as ClapPreTrainedModel,bo as ClapTextModelWithProjection,ql as ClassifierFreeGuidanceLogitsProcessor,Rh as CodeGenForCausalLM,$h as CodeGenModel,Ao as CodeGenPreTrainedModel,$d as CodeGenTokenizer,Nd as CodeLlamaTokenizer,Fh as Cohere2ForCausalLM,Dh as Cohere2Model,To as Cohere2PreTrainedModel,Bh as CohereForCausalLM,Uh as CohereModel,Mo as CoherePreTrainedModel,Rd as CohereTokenizer,Gh as ConvBertForMaskedLM,Vh as ConvBertForQuestionAnswering,qh as ConvBertForSequenceClassification,Wh as ConvBertForTokenClassification,jh as ConvBertModel,zr as ConvBertPreTrainedModel,Ud as ConvBertTokenizer,Ff as ConvNextFeatureExtractor,Xh as ConvNextForImageClassification,hl as ConvNextImageProcessor,Hh as ConvNextModel,So as ConvNextPreTrainedModel,Yh as ConvNextV2ForImageClassification,Kh as ConvNextV2Model,Oo as ConvNextV2PreTrainedModel,e_ as DFineForObjectDetection,Zh as DFineModel,Co as DFinePreTrainedModel,E_ as DINOv3ConvNextModel,ic as DINOv3ConvNextPreTrainedModel,qf as DINOv3ViTImageProcessor,A_ as DINOv3ViTModel,lc as DINOv3ViTPreTrainedModel,Vf as DPTFeatureExtractor,z_ as DPTForDepthEstimation,wl as DPTImageProcessor,P_ as DPTModel,Ro as DPTPreTrainedModel,zo as DacDecoderModel,rc as DacDecoderOutput,Po as DacEncoderModel,tc as DacEncoderOutput,so as DacFeatureExtractor,t_ as DacModel,ln as DacPreTrainedModel,s_ as DebertaForMaskedLM,a_ as DebertaForQuestionAnswering,n_ as DebertaForSequenceClassification,o_ as DebertaForTokenClassification,r_ as DebertaModel,Lr as DebertaPreTrainedModel,Dd as DebertaTokenizer,l_ as DebertaV2ForMaskedLM,p_ as DebertaV2ForQuestionAnswering,c_ as DebertaV2ForSequenceClassification,u_ as DebertaV2ForTokenClassification,i_ as DebertaV2Model,Nr as DebertaV2PreTrainedModel,Bd as DebertaV2Tokenizer,d_ as DecisionTransformerModel,sc as DecisionTransformerPreTrainedModel,jf as DeiTFeatureExtractor,m_ as DeiTForImageClassification,_l as DeiTImageProcessor,f_ as DeiTModel,Lo as DeiTPreTrainedModel,h_ as DepthAnythingForDepthEstimation,nc as DepthAnythingPreTrainedModel,Nu as DepthEstimationPipeline,__ as DepthProForDepthEstimation,oc as DepthProPreTrainedModel,Gf as DetrFeatureExtractor,w_ as DetrForObjectDetection,x_ as DetrForSegmentation,gl as DetrImageProcessor,g_ as DetrModel,un as DetrObjectDetectionOutput,cn as DetrPreTrainedModel,ac as DetrSegmentationOutput,b_ as Dinov2ForImageClassification,y_ as Dinov2Model,No as Dinov2PreTrainedModel,k_ as Dinov2WithRegistersForImageClassification,v_ as Dinov2WithRegistersModel,$o as Dinov2WithRegistersPreTrainedModel,I_ as DistilBertForMaskedLM,O_ as DistilBertForQuestionAnswering,T_ as DistilBertForSequenceClassification,S_ as DistilBertForTokenClassification,M_ as DistilBertModel,$r as DistilBertPreTrainedModel,Fd as DistilBertTokenizer,zu as DocumentQuestionAnsweringPipeline,Wf as DonutFeatureExtractor,Ks as DonutImageProcessor,C_ as DonutSwinModel,cc as DonutSwinPreTrainedModel,_y as EdgeTamModel,N_ as EfficientNetForImageClassification,Hf as EfficientNetImageProcessor,L_ as EfficientNetModel,Uo as EfficientNetPreTrainedModel,R_ as ElectraForMaskedLM,D_ as ElectraForQuestionAnswering,U_ as ElectraForSequenceClassification,B_ as ElectraForTokenClassification,$_ as ElectraModel,Rr as ElectraPreTrainedModel,jd as ElectraTokenizer,ro as EncodecFeatureExtractor,Xl as EosTokenCriteria,j_ as Ernie4_5ForCausalLM,F_ as Ernie4_5Model,Bo as Ernie4_5PretrainedModel,q_ as EsmForMaskedLM,W_ as EsmForSequenceClassification,V_ as EsmForTokenClassification,G_ as EsmModel,ys as EsmPreTrainedModel,Gd as EsmTokenizer,X_ as ExaoneForCausalLM,H_ as ExaoneModel,Do as ExaonePreTrainedModel,Y_ as FalconForCausalLM,J_ as FalconH1ForCausalLM,Q_ as FalconH1Model,jo as FalconH1PreTrainedModel,K_ as FalconModel,Fo as FalconPreTrainedModel,qd as FalconTokenizer,eg as FastViTForImageClassification,Z_ as FastViTModel,Go as FastViTPreTrainedModel,$u as FeatureExtractionPipeline,Ne as FeatureExtractor,wu as FillMaskPipeline,tg as Florence2ForConditionalGeneration,uc as Florence2PreTrainedModel,Em as Florence2Processor,$l as ForcedBOSTokenLogitsProcessor,Rl as ForcedEOSTokenLogitsProcessor,Xf as GLPNFeatureExtractor,pg as GLPNForDepthEstimation,ug as GLPNModel,Ko as GLPNPreTrainedModel,bg as GPT2LMHeadModel,yg as GPT2Model,ea as GPT2PreTrainedModel,Hd as GPT2Tokenizer,fg as GPTBigCodeForCausalLM,dg as GPTBigCodeModel,Yo as GPTBigCodePreTrainedModel,kg as GPTJForCausalLM,vg as GPTJModel,ta as GPTJPreTrainedModel,hg as GPTNeoForCausalLM,mg as GPTNeoModel,Qo as GPTNeoPreTrainedModel,gg as GPTNeoXForCausalLM,_g as GPTNeoXModel,Jo as GPTNeoXPreTrainedModel,Vd as GPTNeoXTokenizer,og as Gemma2ForCausalLM,ng as Gemma2Model,Wo as Gemma2PreTrainedModel,ig as Gemma3ForCausalLM,ag as Gemma3Model,Vo as Gemma3PreTrainedModel,Ef as Gemma3nAudioFeatureExtractor,Ho as Gemma3nForConditionalGeneration,pc as Gemma3nPreTrainedModel,Am as Gemma3nProcessor,sg as GemmaForCausalLM,rg as GemmaModel,qo as GemmaPreTrainedModel,Wd as GemmaTokenizer,cg as GlmForCausalLM,lg as GlmModel,Xo as GlmPreTrainedModel,xg as GptOssForCausalLM,wg as GptOssModel,Zo as GptOssPreTrainedModel,Ag as GraniteForCausalLM,Eg as GraniteModel,Tg as GraniteMoeHybridForCausalLM,Mg as GraniteMoeHybridModel,sa as GraniteMoeHybridPreTrainedModel,ra as GranitePreTrainedModel,Sg as GroundingDinoForObjectDetection,Kf as GroundingDinoImageProcessor,dc as GroundingDinoPreTrainedModel,Mm as GroundingDinoProcessor,Og as GroupViTModel,fc as GroupViTPreTrainedModel,Cg as HeliumForCausalLM,Ig as HeliumModel,na as HeliumPreTrainedModel,Xd as HerbertTokenizer,zg as HieraForImageClassification,Pg as HieraModel,oa as HieraPreTrainedModel,Dg as HubertForCTC,Fg as HubertForSequenceClassification,Bg as HubertModel,Ug as HubertPreTrainedModel,Gg as HunYuanDenseV1ForCausalLM,jg as HunYuanDenseV1Model,aa as HunYuanDenseV1PreTrainedModel,Vg as IJepaForImageClassification,Wg as IJepaModel,ia as IJepaPreTrainedModel,hc as Idefics3ForConditionalGeneration,xl as Idefics3ImageProcessor,mc as Idefics3PreTrainedModel,Ol as Idefics3Processor,Su as ImageClassificationPipeline,Ru as ImageFeatureExtractionPipeline,W as ImageFeatureExtractor,W as ImageProcessor,Tn as ImageSegmentationPipeline,Lu as ImageToImagePipeline,Tu as ImageToTextPipeline,tA as InterruptableStoppingCriteria,Xg as JAISLMHeadModel,Hg as JAISModel,la as JAISPreTrainedModel,Qf as JinaCLIPImageProcessor,Kg as JinaCLIPModel,pn as JinaCLIPPreTrainedModel,Sm as JinaCLIPProcessor,ca as JinaCLIPTextModel,Yg as JinaCLIPVisionModel,Jg as Lfm2ForCausalLM,Qg as Lfm2Model,ew as Lfm2MoeForCausalLM,Zg as Lfm2MoeModel,pa as Lfm2MoePreTrainedModel,ua as Lfm2PreTrainedModel,T0 as LiteWhisperForConditionalGeneration,sw as Llama4ForCausalLM,_c as Llama4PreTrainedModel,rw as LlamaForCausalLM,tw as LlamaModel,da as LlamaPreTrainedModel,Kd as LlamaTokenizer,dn as LlavaForConditionalGeneration,dn as LlavaOnevisionForConditionalGeneration,Jf as LlavaOnevisionImageProcessor,gc as LlavaPreTrainedModel,Om as LlavaProcessor,ow as LlavaQwen2ForCausalLM,jt as LogitsProcessor,hs as LogitsProcessorList,lo as LogitsWarper,iw as LongT5ForConditionalGeneration,aw as LongT5Model,fa as LongT5PreTrainedModel,cw as M2M100ForConditionalGeneration,lw as M2M100Model,ma as M2M100PreTrainedModel,Yd as M2M100Tokenizer,Jd as MBart50Tokenizer,gw as MBartForCausalLM,hw as MBartForConditionalGeneration,_w as MBartForSequenceClassification,mw as MBartModel,bs as MBartPreTrainedModel,Jn as MBartTokenizer,tx as MPNetForMaskedLM,nx as MPNetForQuestionAnswering,rx as MPNetForSequenceClassification,sx as MPNetForTokenClassification,ex as MPNetModel,Ur as MPNetPreTrainedModel,tf as MPNetTokenizer,lx as MT5ForConditionalGeneration,ix as MT5Model,Ma as MT5PreTrainedModel,pw as MarianMTModel,uw as MarianModel,ha as MarianPreTrainedModel,Qd as MarianTokenizer,em as Mask2FormerImageProcessor,Zf as MaskFormerFeatureExtractor,fw as MaskFormerForInstanceSegmentation,Ys as MaskFormerImageProcessor,dw as MaskFormerModel,_a as MaskFormerPreTrainedModel,Hl as MaxLengthCriteria,ww as Metric3DForDepthEstimation,wc as Metric3DPreTrainedModel,xw as Metric3Dv2ForDepthEstimation,xc as Metric3Dv2PreTrainedModel,yw as MgpstrForSceneTextRecognition,yc as MgpstrModelOutput,bc as MgpstrPreTrainedModel,Im as MgpstrProcessor,Zd as MgpstrTokenizer,wa as MimiDecoderModel,kc as MimiDecoderOutput,ga as MimiEncoderModel,vc as MimiEncoderOutput,bw as MimiModel,fn as MimiPreTrainedModel,Fl as MinLengthLogitsProcessor,jl as MinNewTokensLengthLogitsProcessor,kw as MistralForCausalLM,vw as MistralModel,xa as MistralPreTrainedModel,Aw as MobileBertForMaskedLM,Tw as MobileBertForQuestionAnswering,Mw as MobileBertForSequenceClassification,Ew as MobileBertModel,vs as MobileBertPreTrainedModel,ef as MobileBertTokenizer,Ow as MobileLLMForCausalLM,Sw as MobileLLMModel,ya as MobileLLMPreTrainedModel,tm as MobileNetV1FeatureExtractor,Cw as MobileNetV1ForImageClassification,Pw as MobileNetV1ForSemanticSegmentation,yl as MobileNetV1ImageProcessor,Iw as MobileNetV1Model,mn as MobileNetV1PreTrainedModel,rm as MobileNetV2FeatureExtractor,Lw as MobileNetV2ForImageClassification,Nw as MobileNetV2ForSemanticSegmentation,bl as MobileNetV2ImageProcessor,zw as MobileNetV2Model,hn as MobileNetV2PreTrainedModel,sm as MobileNetV3FeatureExtractor,Rw as MobileNetV3ForImageClassification,Uw as MobileNetV3ForSemanticSegmentation,vl as MobileNetV3ImageProcessor,$w as MobileNetV3Model,_n as MobileNetV3PreTrainedModel,nm as MobileNetV4FeatureExtractor,Dw as MobileNetV4ForImageClassification,Fw as MobileNetV4ForSemanticSegmentation,kl as MobileNetV4ImageProcessor,Bw as MobileNetV4Model,gn as MobileNetV4PreTrainedModel,om as MobileViTFeatureExtractor,Gw as MobileViTForImageClassification,El as MobileViTImageProcessor,jw as MobileViTModel,ba as MobileViTPreTrainedModel,Ww as MobileViTV2ForImageClassification,qw as MobileViTV2Model,va as MobileViTV2PreTrainedModel,Qw as ModernBertDecoderForCausalLM,Yw as ModernBertDecoderModel,ka as ModernBertDecoderPreTrainedModel,Hw as ModernBertForMaskedLM,Xw as ModernBertForSequenceClassification,Kw as ModernBertForTokenClassification,Vw as ModernBertModel,ks as ModernBertPreTrainedModel,nw as Moondream1ForConditionalGeneration,Af as MoonshineFeatureExtractor,Zw as MoonshineForConditionalGeneration,Jw as MoonshineModel,Ea as MoonshinePreTrainedModel,Cm as MoonshineProcessor,ax as MptForCausalLM,ox as MptModel,Aa as MptPreTrainedModel,cx as MultiModalityCausalLM,Ec as MultiModalityPreTrainedModel,px as MusicgenForCausalLM,Sa as MusicgenForConditionalGeneration,ux as MusicgenModel,Ta as MusicgenPreTrainedModel,fx as NanoChatForCausalLM,dx as NanoChatModel,Oa as NanoChatPreTrainedModel,hx as NeoBertForMaskedLM,wx as NeoBertForQuestionAnswering,_x as NeoBertForSequenceClassification,gx as NeoBertForTokenClassification,mx as NeoBertModel,Br as NeoBertPreTrainedModel,rf as NllbTokenizer,Gl as NoBadWordsLogitsProcessor,Bl as NoRepeatNGramLogitsProcessor,xx as NomicBertModel,Ac as NomicBertPreTrainedModel,am as NougatImageProcessor,sf as NougatTokenizer,Ox as OPTForCausalLM,Sx as OPTModel,La as OPTPreTrainedModel,Cu as ObjectDetectionPipeline,kx as Olmo2ForCausalLM,vx as Olmo2Model,Ca as Olmo2PreTrainedModel,Ax as Olmo3ForCausalLM,Ex as Olmo3Model,Pa as Olmo3PreTrainedModel,bx as OlmoForCausalLM,yx as OlmoModel,Ia as OlmoPreTrainedModel,Tx as OpenELMForCausalLM,Mx as OpenELMModel,za as OpenELMPreTrainedModel,im as OwlViTFeatureExtractor,zx as OwlViTForObjectDetection,Qs as OwlViTImageProcessor,Px as OwlViTModel,$a as OwlViTPreTrainedModel,Pm as OwlViTProcessor,Cx as Owlv2ForObjectDetection,lm as Owlv2ImageProcessor,Ix as Owlv2Model,Na as Owlv2PreTrainedModel,Lx as PaliGemmaForConditionalGeneration,Mc as PaliGemmaPreTrainedModel,zm as PaliGemmaProcessor,Mf as ParakeetFeatureExtractor,Nx as ParakeetForCTC,Tc as ParakeetPreTrainedModel,Rx as PatchTSMixerForPrediction,$x as PatchTSMixerModel,Ra as PatchTSMixerPreTrainedModel,Bx as PatchTSTForPrediction,Ux as PatchTSTModel,Ua as PatchTSTPreTrainedModel,Gx as Phi3ForCausalLM,jx as Phi3Model,Da as Phi3PreTrainedModel,Fa as Phi3VForCausalLM,pm as Phi3VImageProcessor,Sc as Phi3VPreTrainedModel,Lm as Phi3VProcessor,Fx as PhiForCausalLM,Dx as PhiModel,Ba as PhiPreTrainedModel,dm as PixtralImageProcessor,Nm as PixtralProcessor,y as PreTrainedModel,j as PreTrainedTokenizer,zl as PretrainedConfig,ne as Processor,Wx as PvtForImageClassification,fm as PvtImageProcessor,qx as PvtModel,ja as PvtPreTrainedModel,no as PyAnnoteFeatureExtractor,Hx as PyAnnoteForAudioFrameClassification,Vx as PyAnnoteModel,Ga as PyAnnotePreTrainedModel,$m as PyAnnoteProcessor,gu as QuestionAnsweringPipeline,Kx as Qwen2ForCausalLM,Xx as Qwen2Model,qa as Qwen2PreTrainedModel,nf as Qwen2Tokenizer,Yx as Qwen2VLForConditionalGeneration,mm as Qwen2VLImageProcessor,Oc as Qwen2VLPreTrainedModel,Rm as Qwen2VLProcessor,Jx as Qwen3ForCausalLM,Qx as Qwen3Model,Wa as Qwen3PreTrainedModel,ry as RFDetrForObjectDetection,ty as RFDetrModel,Ic as RFDetrObjectDetectionOutput,Ha as RFDetrPreTrainedModel,Jh as RTDetrForObjectDetection,hm as RTDetrImageProcessor,Qh as RTDetrModel,lr as RTDetrObjectDetectionOutput,Io as RTDetrPreTrainedModel,my as RTDetrV2ForObjectDetection,fy as RTDetrV2Model,Cc as RTDetrV2ObjectDetectionOutput,Xa as RTDetrV2PreTrainedModel,to as RawAudio,Xe as RawImage,Uu as RawVideo,xi as RawVideoFrame,Dl as RepetitionPenaltyLogitsProcessor,ey as ResNetForImageClassification,Zx as ResNetModel,Va as ResNetPreTrainedModel,cy as RoFormerForMaskedLM,dy as RoFormerForQuestionAnswering,uy as RoFormerForSequenceClassification,py as RoFormerForTokenClassification,ly as RoFormerModel,Fr as RoFormerPreTrainedModel,af as RoFormerTokenizer,ny as RobertaForMaskedLM,iy as RobertaForQuestionAnswering,oy as RobertaForSequenceClassification,ay as RobertaForTokenClassification,sy as RobertaModel,Dr as RobertaPreTrainedModel,of as RobertaTokenizer,ao as Sam2ImageProcessor,Lc as Sam2ImageSegmentationOutput,Ka as Sam2Model,Nc as Sam2PreTrainedModel,Il as Sam2Processor,Um as Sam2VideoProcessor,ao as Sam3ImageProcessor,gy as Sam3TrackerModel,ao as SamImageProcessor,Pc as SamImageSegmentationOutput,hy as SamModel,zc as SamPreTrainedModel,io as SamProcessor,_m as SapiensFeatureExtractor,xy as SapiensForDepthEstimation,yy as SapiensForNormalEstimation,wy as SapiensForSemanticSegmentation,Al as SapiensImageProcessor,wn as SapiensPreTrainedModel,Tf as SeamlessM4TFeatureExtractor,gm as SegformerFeatureExtractor,vy as SegformerForImageClassification,ky as SegformerForSemanticSegmentation,Ml as SegformerImageProcessor,by as SegformerModel,xn as SegformerPreTrainedModel,wm as SiglipImageProcessor,Ey as SiglipModel,Ya as SiglipPreTrainedModel,Qa as SiglipTextModel,lf as SiglipTokenizer,Ay as SiglipVisionModel,Ty as SmolLM3ForCausalLM,My as SmolLM3Model,Ja as SmolLM3PreTrainedModel,qg as SmolVLMForConditionalGeneration,xl as SmolVLMImageProcessor,Ol as SmolVLMProcessor,ei as SnacDecoderModel,Za as SnacEncoderModel,Sf as SnacFeatureExtractor,Sy as SnacModel,yn as SnacPreTrainedModel,Of as SpeechT5FeatureExtractor,Iy as SpeechT5ForSpeechToText,Cy as SpeechT5ForTextToSpeech,Py as SpeechT5HifiGan,Oy as SpeechT5Model,bn as SpeechT5PreTrainedModel,Bm as SpeechT5Processor,cf as SpeechT5Tokenizer,Ly as SqueezeBertForMaskedLM,$y as SqueezeBertForQuestionAnswering,Ny as SqueezeBertForSequenceClassification,zy as SqueezeBertModel,Es as SqueezeBertPreTrainedModel,uf as SqueezeBertTokenizer,Uy as StableLmForCausalLM,Ry as StableLmModel,ti as StableLmPreTrainedModel,Dy as Starcoder2ForCausalLM,By as Starcoder2Model,ri as Starcoder2PreTrainedModel,nn as StoppingCriteria,Vl as StoppingCriteriaList,Fy as StyleTextToSpeech2Model,$c as StyleTextToSpeech2PreTrainedModel,xu as SummarizationPipeline,si as SupertonicForConditionalGeneration,Rc as SupertonicPreTrainedModel,rn as SuppressTokensAtBeginLogitsProcessor,Vy as Swin2SRForImageSuperResolution,xm as Swin2SRImageProcessor,Wy as Swin2SRModel,ni as Swin2SRPreTrainedModel,Gy as SwinForImageClassification,qy as SwinForSemanticSegmentation,jy as SwinModel,vn as SwinPreTrainedModel,Xy as T5ForConditionalGeneration,Hy as T5Model,oi as T5PreTrainedModel,pf as T5Tokenizer,Yy as TableTransformerForObjectDetection,Ky as TableTransformerModel,Uc as TableTransformerObjectDetectionOutput,ai as TableTransformerPreTrainedModel,Wl as TemperatureLogitsWarper,U as Tensor,Vr as Text2TextGenerationPipeline,hu as TextClassificationPipeline,bu as TextGenerationPipeline,W0 as TextStreamer,Mu as TextToAudioPipeline,_u as TokenClassificationPipeline,j as TokenizersBackend,eA as TopKLogitsWarper,ZE as TopPLogitsWarper,Qy as TrOCRForCausalLM,Bc as TrOCRPreTrainedModel,yu as TranslationPipeline,Fc as UltravoxModel,Dc as UltravoxPreTrainedModel,Dm as UltravoxProcessor,e0 as UniSpeechForCTC,t0 as UniSpeechForSequenceClassification,Zy as UniSpeechModel,kn as UniSpeechPreTrainedModel,o0 as UniSpeechSatForAudioFrameClassification,s0 as UniSpeechSatForCTC,n0 as UniSpeechSatForSequenceClassification,r0 as UniSpeechSatModel,As as UniSpeechSatPreTrainedModel,Tm as VLChatProcessor,Yf as VLMImageProcessor,i0 as VaultGemmaForCausalLM,a0 as VaultGemmaModel,ii as VaultGemmaPreTrainedModel,ym as ViTFeatureExtractor,u0 as ViTForImageClassification,Tl as ViTImageProcessor,p0 as ViTMAEModel,jc as ViTMAEPreTrainedModel,f0 as ViTMSNForImageClassification,d0 as ViTMSNModel,ci as ViTMSNPreTrainedModel,c0 as ViTModel,li as ViTPreTrainedModel,l0 as VisionEncoderDecoderModel,m0 as VitMatteForImageMatting,bm as VitMatteImageProcessor,Gc as VitMattePreTrainedModel,h0 as VitPoseForPoseEstimation,vm as VitPoseImageProcessor,qc as VitPosePreTrainedModel,_0 as VitsModel,Wc as VitsModelOutput,Vc as VitsPreTrainedModel,ff as VitsTokenizer,Jy as VoxtralForConditionalGeneration,Fm as VoxtralProcessor,w0 as Wav2Vec2BertForCTC,x0 as Wav2Vec2BertForSequenceClassification,g0 as Wav2Vec2BertModel,En as Wav2Vec2BertPreTrainedModel,mf as Wav2Vec2CTCTokenizer,If as Wav2Vec2FeatureExtractor,Rg as Wav2Vec2ForAudioFrameClassification,Ng as Wav2Vec2ForCTC,$g as Wav2Vec2ForSequenceClassification,Lg as Wav2Vec2Model,Jt as Wav2Vec2PreTrainedModel,jm as Wav2Vec2Processor,Gm as Wav2Vec2ProcessorWithLM,E0 as WavLMForAudioFrameClassification,b0 as WavLMForCTC,v0 as WavLMForSequenceClassification,k0 as WavLMForXVector,y0 as WavLMModel,jr as WavLMPreTrainedModel,Cf as WeSpeakerFeatureExtractor,A0 as WeSpeakerResNetModel,Xc as WeSpeakerResNetPreTrainedModel,Pf as WhisperFeatureExtractor,Yc as WhisperForConditionalGeneration,M0 as WhisperModel,ui as WhisperPreTrainedModel,qm as WhisperProcessor,HA as WhisperTextStreamer,Ul as WhisperTimeStampLogitsProcessor,hf as WhisperTokenizer,P0 as XLMForQuestionAnswering,I0 as XLMForSequenceClassification,C0 as XLMForTokenClassification,S0 as XLMModel,Gr as XLMPreTrainedModel,L0 as XLMRobertaForMaskedLM,R0 as XLMRobertaForQuestionAnswering,N0 as XLMRobertaForSequenceClassification,$0 as XLMRobertaForTokenClassification,z0 as XLMRobertaModel,qr as XLMRobertaPreTrainedModel,_f as XLMRobertaTokenizer,gf as XLMTokenizer,O0 as XLMWithLMHeadModel,Hc as XVectorOutput,km as YolosFeatureExtractor,B0 as YolosForObjectDetection,Sl as YolosImageProcessor,U0 as YolosModel,Qc as YolosObjectDetectionOutput,pi as YolosPreTrainedModel,F0 as YoutuForCausalLM,D0 as YoutuModel,di as YoutuPreTrainedModel,Eu as ZeroShotAudioClassificationPipeline,vu as ZeroShotClassificationPipeline,Iu as ZeroShotImageClassificationPipeline,Pu as ZeroShotObjectDetectionPipeline,Ee as cat,_C as cos_sim,Hv as dot,De as env,Ve as full,Qn as full_like,yd as interpolate,Dt as interpolate_4d,t4 as layer_norm,yP as load_image,tz as load_video,kp as log_softmax,zE as matmul,il as mean,LE as mean_pooling,it as ones,ll as ones_like,JC as permute,Iee as pipeline,$E as quantize_embeddings,r4 as rand,NE as randn,yf as read_audio,e4 as rfft,al as slice,Pe as softmax,Ft as stack,bd as std_mean,Yt as topk,kd as zeros,Ed as zeros_like};
23
+ ${s}${o}`+n.repeat(t)+`${s}`,a}function cz(t,e,r,s){return`${e}${s}`+r.repeat(t)+`${e}`}function uz(t,e,r,s,n,o){return t===0&&e===0?cz(r,s,n,o):lz(r,t,e,s,n,o)}var xc=class extends oe{static image_processor_class=De;static tokenizer_class=Z;static uses_processor_config=!0;fake_image_token="<fake_token_around_image>";image_token="<image>";global_img_token="<global-img>";async _call(e,r=null,s={}){s.return_row_col_info??=!0;let n;r&&(n=await this.image_processor(r,s)),Array.isArray(e)||(e=[e]);let o=n.rows??[new Array(e.length).fill(0)],a=n.cols??[new Array(e.length).fill(0)],i=this.config.image_seq_len,l=[],u=[];for(let f=0;f<e.length;++f){let m=e[f],h=o[f],w=a[f];l.push(Nv(m,this.image_token));let x=h.map((A,S)=>uz(A,w[S],i,this.fake_image_token,this.image_token,this.global_img_token)),k=m.split(this.image_token);if(k.length===0)throw new Error("The image token should be present in the text.");let E=k[0];for(let A=0;A<x.length;++A)E+=x[A]+k[A+1];u.push(E)}return{...this.tokenizer(u),...n}}};var Km=class extends oe{static image_processor_class=De;static tokenizer_class=Z;static uses_processor_config=!0;constructor(e,r,s){super(e,r,s),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(e,{images:r=null,chat_template:s="default"}={}){r?Array.isArray(r)||(r=[r]):r=await Promise.all(e.filter(k=>k.images).flatMap(k=>k.images).map(k=>Ke.read(k)));let n=this.tokenizer,o=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=k=>n.encode(k,{add_special_tokens:!1}),i=o.split(this.image_tag),l=i.length-1;if(r.length!==l)throw new Error(`Number of images provided (${r.length}) does not match number of "${this.image_tag}" image tags (${l})`);let[u,p,f]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),m=a(i[0]),h=new Array(m.length).fill(!1);for(let k=1;k<i.length;++k){let E=new Array(this.num_image_tokens).fill(u),A=a(i[k]);m=ft(m,[p],E,[f],A);let S=new Array(this.num_image_tokens).fill(!0);h=ft(h,[!1],S,[!1],new Array(A.length).fill(!1))}let w=[1,m.length],x={input_ids:new D("int64",m,w),attention_mask:new D("int64",new Array(m.length).fill(1),w),images_seq_mask:new D("bool",h,w),images_emb_mask:new D("bool",new Array(l*this.num_image_tokens).fill(!0),[1,l,this.num_image_tokens])};if(r&&r.length>0){let k=await this.image_processor(r);return k.pixel_values.unsqueeze_(0),{...x,...k}}return x}};var Ym=class extends oe{static tokenizer_class=Z;static image_processor_class=De;async _call(e=null,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=e?this.tokenizer(e,s):{},o=r?await this.image_processor(r,s):{};return{...n,...o}}};var Qm=class extends oe{static tokenizer_class=Z;static image_processor_class=De;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,patch_size:u,num_additional_image_tokens:p}=this.config,f=Math.floor(a/u)*Math.floor(i/u)+p;r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let m=0;m<r.length;++m)r[m]=r[m].replace(l,l.repeat(f))}let o=r?this.tokenizer(r,s):{};return{...n,...o}}};var AA={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},Jm=class extends oe{static tokenizer_class=Z;static image_processor_class=De;get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(e,r){if(!AA.hasOwnProperty(r))throw new Error(`Format ${r} is not supported.`);let[s,n]=AA[r],o=this[s].bind(this),[a,i]=e.dims,l=[],u=[],p=e.tolist();for(let m=0;m<a;++m){let h=p[m],w=[],x=[];for(let E=1;E<i;++E){let[A,S]=Se(Le(h[E]));if(x.push(A),S==n)break;w.push(S)}let k=x.length>0?x.reduce((E,A)=>E*A,1):0;u.push(w),l.push(k)}return[o(u),l]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}batch_decode([e,r,s]){let[n,o]=this._decode_helper(e,"char"),[a,i]=this._decode_helper(r,"bpe"),[l,u]=this._decode_helper(s,"wp"),p=[],f=[];for(let m=0;m<n.length;++m){let[h,w]=Se([o[m],i[m],u[m]]);p.push([n[m],a[m],l[m]][w]),f.push(h)}return{generated_text:p,scores:f,char_preds:n,bpe_preds:a,wp_preds:l}}static async from_pretrained(...e){let r=await super.from_pretrained(...e),s=await Z.from_pretrained("Xenova/gpt2"),n=await Z.from_pretrained("Xenova/bert-base-uncased");return r.components={image_processor:r.image_processor,char_tokenizer:r.tokenizer,bpe_tokenizer:s,wp_tokenizer:n},r}async _call(e,r=null){let s=await this.image_processor(e);return r&&(s.labels=this.tokenizer(r).input_ids),s}};var Zm=class extends oe{static tokenizer_class=Z;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}};var eh=class extends oe{static tokenizer_class=Z;static image_processor_class=De};var fn="<image>";function pz(t,e,r,s,n){return`${s.repeat(r*n)}${e}${t}
24
+ `}var th=class extends oe{static tokenizer_class=Z;static image_processor_class=De;static uses_processor_config=!1;async _call(e,r=null,s={}){r||(Q.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),r=""),Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let n=this.tokenizer.bos_token,o=this.image_processor.config.image_seq_length,a;r.some(u=>u.includes(fn))?a=r.map(u=>{let p=u.replaceAll(fn,fn.repeat(o)),f=p.lastIndexOf(fn),m=f===-1?0:f+fn.length;return p.slice(0,m)+n+p.slice(m)+`
25
+ `}):(Q.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=r.map(u=>pz(u,n,o,fn,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var MA="<|image|>",dz=/<\|image_\d+\|>/g,rh=class extends oe{static image_processor_class=De;static tokenizer_class=Z;async _call(e,r=null,{padding:s=!0,truncation:n=!0,num_crops:o=null}={}){Array.isArray(e)||(e=[e]);let a,i;if(r){i=await this.image_processor(r,{num_crops:o});let{num_img_tokens:l}=i,u=e.map((f,m)=>f.split(dz).join(MA.repeat(l[m])));a=this.tokenizer(u,{padding:s,truncation:n});let p=this.tokenizer._tokenizer.token_to_id(MA);a.input_ids.map_(f=>f==p?-f:f)}else a=this.tokenizer(e);return{...a,...i}}};var sh=class extends oe{static tokenizer_class=Z;static image_processor_class=De;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,image_break_token:u,image_end_token:p,patch_size:f,spatial_merge_size:m}=this.config,h=f*m,w=Math.floor(a/h),x=Math.floor(i/h);r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let k=0;k<r.length;++k){let E=l.repeat(x),A=E+u,S=E+p,T=A.repeat(w-1)+S;r[k]=r[k].replace(l,T)}}let o=r?this.tokenizer(r,s):{};return{...n,...o}}};var nh=class extends oe{static feature_extractor_class=wo;async _call(e){return await this.feature_extractor(e)}post_process_speaker_diarization(...e){return this.feature_extractor.post_process_speaker_diarization(...e)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}};var bo=class extends oe{static image_processor_class=De;static tokenizer_class=Z;async _call(e,r=null,...s){Array.isArray(e)||(e=[e]);let n,o;if(r&&(n=await this.image_processor(r),o=n.image_grid_thw),o){let i=this.image_processor.config.merge_size**2,l=0,u=o.tolist();e=e.map(p=>{for(;p.includes("<|image_pad|>");){let f=Number(u[l++].reduce((m,h)=>m*h,1n));p=p.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(f/i)))}return p.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(e),...n}}};var vo=class extends bo{};var oh=class extends vo{};var ko=class extends oe{static image_processor_class=De;async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}};var yc=class extends ko{},ah=class extends yc{};var ih=class extends oe{static tokenizer_class=Z;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}};var lh=class extends oe{static tokenizer_class=Z;static feature_extractor_class=rt;static uses_processor_config=!0;async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){let a=r.length,{input_features:i}=await this.feature_extractor(r,{...s,max_length:a}),l=Math.round(a/this.config.encoder_ds_factor+1e-4),u=1+Math.ceil(l/this.config.stack_factor);n.audio_token_len=[u],n.audio_values=i;let p=this.config.audio_placeholder;if(!e.includes(p))throw new Error(`The input text does not contain the image token ${p}.`);e=e.replaceAll(p,p.repeat(u))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var bc="[AUDIO]",fz="[BEGIN_AUDIO]",mz=375;function hz(t,e){let r=[];for(let s=0;s<t.length;s+=e)r.push(t.subarray(s,Math.min(s+e,t.length)));return r}var ch=class extends oe{static tokenizer_class=Z;static feature_extractor_class=rt;static uses_processor_config=!1;async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){if(!e.includes(bc))throw new Error(`The input text does not contain the audio token ${bc}.`);Array.isArray(r)||(r=[r]);let a=e.split(bc),i=a.length-1;if(i!==r.length)throw new Error(`The number of audio inputs (${r.length}) does not match the number of audio tokens in the text (${i}).`);let l=this.feature_extractor.config.n_samples,u=r.map(w=>hz(w,l)),p=u.map(w=>w.length),f=u.flat(),m=(await Promise.all(f.map(w=>this.feature_extractor(w,s)))).map(w=>w.input_features);n.audio_values=m.length>1?Ee(m,0):m[0];let h=a[0];for(let w=0;w<p.length;++w){h+=fz;for(let x=0;x<p[w];++x)h+=bc.repeat(mz);h+=a[w+1]}e=h}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var uh=class extends oe{static tokenizer_class=Z;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}};var ph=class extends oe{static tokenizer_class=Z;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}};var dh=class extends oe{static tokenizer_class=Z;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}};var pt=class{static async from_pretrained(e,r={}){let s=await ct(e,Ar,!0,r),{image_processor_type:n,feature_extractor_type:o,processor_class:a}=s;if(a&&vc[a])return vc[a].from_pretrained(e,r);if(!n&&!o)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");let i={};if(n){let u=dn[n.replace(/Fast$/,"")];if(!u)throw new Error(`Unknown image_processor_type: '${n}'.`);i.image_processor=new u(s)}if(o){let u=dn[o];if(u)i.image_processor=new u(s);else{let p=xo[o];if(!p)throw new Error(`Unknown feature_extractor_type: '${o}'.`);i.feature_extractor=new p(s)}}let l={};return new oe(l,i,null)}};async function _z(t,e){return await ct(t,"config.json",!0,e)}function mn(t){let e={},r={};switch(t.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"voxtral":case"smolvlm":case"gemma3n":case"chatterbox":case"mistral3":case"qwen2_5_vl":case"qwen3_vl":r=mn(t.text_config);break;case"moondream1":r=mn(t.phi_config);break;case"musicgen":r=mn(t.decoder);break;case"multi_modality":r=mn(t.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":e.num_heads="num_attention_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size";break;case"gpt_oss":case"llama":case"llama4_text":case"nanochat":case"apertus":case"arcee":case"afmoe":case"lfm2":case"lfm2_moe":case"smollm3":case"olmo":case"olmo2":case"olmo3":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"cohere2":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"qwen2_5_vl_text":case"qwen3_vl_text":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size",e.num_attention_heads="num_attention_heads",e.dim_kv="head_dim";break;case"qwen3":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"glm":case"helium":case"ernie4_5":case"hunyuan_v1_dense":case"falcon_h1":case"ministral":case"ministral3":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.dim_kv="head_dim";break;case"openelm":e.num_heads="num_kv_heads",e.num_layers="num_transformer_layers",e.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":e.num_heads="num_heads",e.num_layers="num_layers",e.hidden_size="hidden_size";break;case"bloom":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="hidden_size";break;case"mpt":e.num_heads="n_heads",e.num_layers="n_layers",e.hidden_size="d_model";break;case"exaone":e.num_heads="num_key_value_heads",e.num_layers="num_layers",e.dim_kv="head_dim",e.num_attention_heads="num_attention_heads";break;case"youtu":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.dim_kv="qk_head_dim",e.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":e.num_decoder_layers="num_decoder_layers",e.num_decoder_heads="num_heads",e.decoder_dim_kv="d_kv",e.num_encoder_layers="num_layers",e.num_encoder_heads="num_heads",e.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="d_model",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="d_model";break;case"speecht5":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="hidden_size",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="hidden_size";break;case"trocr":e.num_encoder_layers=e.num_decoder_layers="decoder_layers",e.num_encoder_heads=e.num_decoder_heads="decoder_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="d_model";break;case"musicgen_decoder":e.num_encoder_layers=e.num_decoder_layers="num_hidden_layers",e.num_encoder_heads=e.num_decoder_heads="num_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="hidden_size";break;case"moonshine":e.num_decoder_layers="decoder_num_hidden_layers",e.num_decoder_heads="decoder_num_key_value_heads",e.num_encoder_layers="encoder_num_hidden_layers",e.num_encoder_heads="encoder_num_key_value_heads",e.encoder_hidden_size=e.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":let n=mn(t.decoder),o="num_decoder_layers"in n,a=nt(t,["model_type","is_encoder_decoder"]);return o?(a.num_decoder_layers=n.num_decoder_layers,a.num_decoder_heads=n.num_decoder_heads,a.decoder_hidden_size=n.decoder_hidden_size,a.num_encoder_layers=n.num_encoder_layers,a.num_encoder_heads=n.num_encoder_heads,a.encoder_hidden_size=n.encoder_hidden_size):(a.num_layers=n.num_layers,a.num_heads=n.num_heads,a.hidden_size=n.hidden_size),a}let s={...r,...nt(t,["model_type","multi_query","is_encoder_decoder"])};for(let n in e)s[n]=t[e[n]];return s}function Ec(t,e){if(["lfm2","lfm2_moe"].includes(t.model_type)){let r=e?.prefix??"past_key_values",s=r==="present"?"present":"past",n={},{layer_types:o,num_attention_heads:a,num_key_value_heads:i,hidden_size:l,conv_L_cache:u}=t,p=l/a,f=e?.batch_size??1;for(let m=0;m<o.length;++m)if(o[m]==="full_attention")for(let h of["key","value"])n[`${r}.${m}.${h}`]=[f,i,0,p];else if(o[m]==="conv")n[`${s}_conv.${m}`]=[f,l,u];else throw new Error(`Unsupported layer type: ${o[m]}`);return n}else if(["granitemoehybrid","falcon_h1"].includes(t.model_type)){let r=e?.prefix??"past_key_values",s=r==="present"?"present":"past",n={},{layer_types:o,num_hidden_layers:a,num_attention_heads:i,num_key_value_heads:l,hidden_size:u,mamba_d_conv:p,mamba_n_heads:f,mamba_d_head:m,mamba_d_state:h,mamba_n_groups:w,mamba_expand:x,mamba_d_ssm:k}=t,E=u/i,A=e?.batch_size??1,S=(k??x*u)+2*w*h;for(let T=0;T<a;++T)if((!o||o[T]==="mamba")&&(n[`${s}_conv.${T}`]=[A,S,p],n[`${s}_ssm.${T}`]=[A,f,m,h]),!o||o[T]==="attention")for(let P of["key","value"])n[`${r}.${T}.${P}`]=[A,l,0,E];return n}else if(["qwen3_5","qwen3_5_moe"].includes(t.model_type)){let r=e?.prefix??"past_key_values",s=r==="present"?"present":"past",n={},{head_dim:o,layer_types:a,num_attention_heads:i,num_key_value_heads:l,hidden_size:u,linear_num_value_heads:p,linear_num_key_heads:f,linear_key_head_dim:m,linear_value_head_dim:h,linear_conv_kernel_dim:w}=t.text_config,x=m*f,k=h*p,E=x*2+k,A=o??u/i,S=e?.batch_size??1;for(let T=0;T<a.length;++T)if(a[T]==="full_attention")for(let P of["key","value"])n[`${r}.${T}.${P}`]=[S,l,0,A];else if(a[T]==="linear_attention")n[`${s}_conv.${T}`]=[S,E,w],n[`${s}_recurrent.${T}`]=[S,p,m,h];else throw new Error(`Unsupported layer type: ${a[T]}`);return n}return gz(t,e)}function gz(t,{prefix:e="past_key_values",batch_size:r=1}={}){let s={},n=t.normalized_config;if(n.is_encoder_decoder&&"num_encoder_heads"in n&&"num_decoder_heads"in n){let o=n.encoder_dim_kv??n.encoder_hidden_size/n.num_encoder_heads,a=n.decoder_dim_kv??n.decoder_hidden_size/n.num_decoder_heads,i=[r,n.num_encoder_heads,0,o],l=[r,n.num_decoder_heads,0,a];for(let u=0;u<n.num_decoder_layers;++u)s[`${e}.${u}.encoder.key`]=i,s[`${e}.${u}.encoder.value`]=i,s[`${e}.${u}.decoder.key`]=l,s[`${e}.${u}.decoder.value`]=l}else{let o=n.num_heads,a=n.num_layers,i=n.dim_kv??n.hidden_size/(n.num_attention_heads??o);if(n.model_type==="falcon"){let l=[r*o,0,i];for(let u=0;u<a;++u)s[`${e}.${u}.key`]=l,s[`${e}.${u}.value`]=l}else if(n.multi_query){let l=[r*o,0,2*i];for(let u=0;u<a;++u)s[`${e}.${u}.key_value`]=l}else if(n.model_type==="bloom"){let l=[r*o,i,0],u=[r*o,0,i];for(let p=0;p<a;++p)s[`${e}.${p}.key`]=l,s[`${e}.${p}.value`]=u}else if(n.model_type==="openelm")for(let l=0;l<a;++l){let u=[r,o[l],0,i];s[`${e}.${l}.key`]=u,s[`${e}.${l}.value`]=u}else{let l=[r,o,0,i];for(let u=0;u<a;++u)s[`${e}.${u}.key`]=l,s[`${e}.${u}.value`]=l}}return s}var kc=class t{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(e){Object.assign(this,e),this.normalized_config=mn(this)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){s&&!(s instanceof t)&&(s=new t(s));let i=s??await _z(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(i)}},Mr=class{static async from_pretrained(...e){return kc.from_pretrained(...e)}};function fh(t,e,r){return t?typeof t=="object"&&t!==null?t.hasOwnProperty(e)?+t[e]:t.hasOwnProperty(r)?+t[r]:0:+t:0}function mh(t,e){let r=[];for(let s=0;s<e;++s)r.push(`${t}_data${s===0?"":"_"+s}`);return r}async function TA(t,e,r,s){let n=`${e}${s}.onnx`,o=`${r.subfolder??""}/${n}`;return await Qn(t,o,!0,r,ge.IS_NODE_ENV)}async function SA(t,e,r,s,n,o={}){let a=`${e}${r}.onnx`,i=ge.IS_NODE_ENV,l=[],u=fh(n,a,e);if(u>0){if(u>Sl)throw new Error(`The number of external data chunks (${u}) exceeds the maximum allowed value (${Sl}).`);let p=mh(a,u);for(let f of p){let m=`${s.subfolder??""}/${f}`;l.push(new Promise(async(h,w)=>{let x=await Qn(t,m,!0,s,i);h(x instanceof Uint8Array?{path:f,data:x}:f)}))}}else o.externalData!==void 0&&(l=o.externalData.map(async p=>{if(typeof p.data=="string"){let f=await Qn(t,p.data,!0,s);return{...p,data:f}}return p}));return Promise.all(l)}async function wz(t,e,r,s=!1){let n=r.config?.["transformers.js_config"]??{},o=Vl(r.device??n.device,e,{warn:S=>Q.info(S)}),a=JE(o),i=n.device_config??{};i.hasOwnProperty(o)&&(n={...n,...i[o]});let l=Hl(r.dtype??n.dtype,e,o,{configDtype:n.dtype,warn:S=>Q.info(S)});if(lo.hasOwnProperty(l)){if(o==="webgpu"&&!ge.IS_NODE_ENV&&l===_t.fp16&&!await oA())throw new Error(`The device (${o}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${l}. Should be one of: ${Object.keys(_t).join(", ")}`);let u=n.kv_cache_dtype,p=u?typeof u=="string"?u:u[l]??"float32":void 0;if(p&&!["float32","float16"].includes(p))throw new Error(`Invalid kv_cache_dtype: ${p}. Should be one of: float32, float16`);let f=lo[l],m={...r.session_options};m.executionProviders??=a;let h=n.free_dimension_overrides;h?m.freeDimensionOverrides??=h:o.startsWith("webnn")&&!m.freeDimensionOverrides&&Q.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${o}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let w=TA(t,e,r,f),x=r.use_external_data_format??n.use_external_data_format,k=await SA(t,e,f,r,x,m);if(k.length>0&&!ge.IS_NODE_ENV&&(m.externalData=k),s&&o==="webgpu"&&u!==!1){let S=Ec(r.config,{prefix:"present"});if(Object.keys(S).length>0&&!io()){let T={};for(let P in S)T[P]="gpu-buffer";m.preferredOutputLocation=T}}return{buffer_or_path:await w,session_options:m,session_config:{dtype:l,kv_cache_dtype:p,device:o}}}async function Et(t,e,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(e).map(async n=>{let{buffer_or_path:o,session_options:a,session_config:i}=await wz(t,e[n],r,n===s),l=await Gl(o,a,i);return[n,l]})))}function OA(t){for(let e in t)Wl(t[e])?t[e]=new D(t[e]):typeof t[e]=="object"&&OA(t[e]);return t}async function ue(t,e){let r=xz(t,e);try{let s=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i=a.ort_tensor;return ge.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[o,i]})),n=await ql(t,s);return OA(n)}catch(s){let n=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i={type:a.type,dims:a.dims,location:a.location};return i.location!=="gpu-buffer"&&(i.data=a.data),[o,i]}));throw Q.error(`An error occurred during model execution: "${s}".`),Q.error("Inputs given to model:",n),s}}function xz(t,e){let r=Object.create(null),s=[];for(let a of t.inputNames){let i=e[a];if(!(i instanceof D)){s.push(a);continue}r[a]=io()?i.clone():i}if(s.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);let n=Object.keys(e).length,o=t.inputNames.length;if(n>o){let a=Object.keys(e).filter(i=>!t.inputNames.includes(i));Q.warn(`WARNING: Too many inputs were provided (${n} > ${o}). The following inputs will be ignored: "${a.join(", ")}".`)}return r}var Ne=class{};var G=class extends Ne{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},he=class extends Ne{constructor({logits:e}){super(),this.logits=e}},we=class extends Ne{constructor({logits:e}){super(),this.logits=e}},Ae=class extends Ne{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}},xt=class extends Ne{constructor({logits:e}){super(),this.logits=e}};var Ac=class extends Ne{constructor({alphas:e}){super(),this.alphas=e}};var qt=class extends Ze{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},Eo=class extends Ze{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},Is=class extends Ze{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,r){let s=r;for(let n of this.processors)s=n(e,s);return s}[Symbol.iterator](){return this.processors.values()}},Mc=class extends qt{constructor(e){super(),this.bos_token_id=e}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length===1){let n=r[s].data;n.fill(-1/0),n[this.bos_token_id]=0}return r}},Tc=class extends qt{constructor(e,r){super(),this.max_length=e,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length===this.max_length-1){let n=r[s].data;n.fill(-1/0);for(let o of this.eos_token_id)n[o]=0}return r}},hn=class extends qt{constructor(e,r){super(),this.begin_suppress_tokens=e,this.begin_index=r}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length===this.begin_index){let n=r[s].data;for(let o of this.begin_suppress_tokens)n[o]=-1/0}return r}},Sc=class extends qt{constructor(e,r){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]: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=r.length,r.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data;if(n[this.no_timestamps_token_id]=-1/0,e[s].length===this.begin_index-1){n.fill(-1/0),n[this.timestamp_begin]=0;continue}let o=e[s].slice(this.begin_index),a=o.length>=1&&o[o.length-1]>=this.timestamp_begin,i=o.length<2||o[o.length-2]>=this.timestamp_begin;if(a&&(i?n.subarray(this.timestamp_begin).fill(-1/0):n.subarray(0,this.eos_token_id).fill(-1/0)),e[s].length===this.begin_index&&this.max_initial_timestamp_index!==null){let f=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(f+1).fill(-1/0)}let l=Vp(n),u=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((f,m)=>f+m)),p=Se(l.subarray(0,this.timestamp_begin))[0];u>p&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},Oc=class extends qt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let r=e.length,s=[];for(let o=0;o<r+1-this.no_repeat_ngram_size;++o){let a=[];for(let i=0;i<this.no_repeat_ngram_size;++i)a.push(e[o+i]);s.push(a.map(Number))}let n=new Map;for(let o of s){let a=o.slice(0,o.length-1),i=JSON.stringify(a),l=n.get(i)??[];l.push(o[o.length-1]),n.set(i,l)}return n}getGeneratedNgrams(e,r){let s=r.slice(r.length+1-this.no_repeat_ngram_size,r.length);return e.get(JSON.stringify(s.map(Number)))??[]}calcBannedNgramTokens(e){let r=[];if(e.length+1<this.no_repeat_ngram_size)return r;{let s=this.getNgrams(e);return this.getGeneratedNgrams(s,e)}}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data,o=this.calcBannedNgramTokens(e[s]);for(let a of o)n[a]=-1/0}return r}},Ic=class extends qt{constructor(e){super(),this.penalty=e}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data;for(let o of new Set(e[s])){let a=Number(o);n[a]<0?n[a]*=this.penalty:n[a]/=this.penalty}}return r}},Cc=class extends qt{constructor(e,r){super(),this.min_length=e,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length<this.min_length){let n=r[s].data;for(let o of this.eos_token_id)n[o]=-1/0}return r}},Pc=class extends qt{constructor(e,r,s){super(),this.prompt_length_to_skip=e,this.min_new_tokens=r,this.eos_token_id=Array.isArray(s)?s:[s]}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length-this.prompt_length_to_skip<this.min_new_tokens){let o=r[s].data;for(let a of this.eos_token_id)o[a]=-1/0}return r}},zc=class extends qt{constructor(e,r){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data,o=e[s];for(let a of this.bad_words_ids){if(o.length<a.length-1)continue;let i=!0;for(let l=1;l<=a.length-1;++l)if(a.at(-l-1)!=o.at(-l)){i=!1;break}i&&(n[a.at(-1)]=-1/0)}}return r}},Lc=class extends qt{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,r){if(r.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${r.dims[0]} for the logits and ${e.length} for the input ids.`);let s=e.length,n=r.slice([0,s],null),o=r.slice([s,r.dims[0]],null);for(let a=0;a<o.data.length;++a)o.data[a]+=(n.data[a]-o.data[a])*this.guidance_scale;return o}},Nc=class extends Eo{constructor(e){if(super(),typeof e!="number"||e<=0){let r=`\`temperature\` (=${e}) must be a strictly positive float, otherwise your next token scores will be invalid.`;e===0&&(r+=" If you're looking for greedy decoding strategies, set `do_sample=false`.")}this.temperature=e}_call(e,r){let s=r.data;for(let n=0;n<s.length;++n)s[n]/=this.temperature;return r}},IA=class extends Eo{constructor(e,{filter_value:r=-1/0,min_tokens_to_keep:s=1}={}){if(super(),e<0||e>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(s)||s<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${s}`);this.top_p=e,this.filter_value=r,this.min_tokens_to_keep=s}},CA=class extends Eo{constructor(e,{filter_value:r=-1/0,min_tokens_to_keep:s=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,s),this.filter_value=r}};var _n=class{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,nt(e,Object.getOwnPropertyNames(this)))}};var gn=class extends Ze{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},$c=class t extends Ze{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof gn&&(e=[e]),this.criteria.push(...e)}_call(e,r){let s=new Array(e.length).fill(!1);for(let n of this.criteria){let o=n(e,r);for(let a=0;a<s.length;++a)s[a]||=o[a]}return s}[Symbol.iterator](){return this.criteria.values()}},Rc=class extends gn{constructor(e,r=null){super(),this.max_length=e,this.max_position_embeddings=r}_call(e){return e.map(r=>r.length>=this.max_length)}},Dc=class extends gn{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,r){return e.map(s=>{let n=s.at(-1);return this.eos_token_id.some(o=>n==o)})}},PA=class extends gn{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,r){return new Array(e.length).fill(this.interrupted)}};var Cs=class extends Ze{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,r){let s=e.dims.at(-1),n=e.data;if(r===-1)n=n.slice(-s);else{let o=r*s;n=n.slice(o,o+s)}return n}randomSelect(e){return iA(e)}static getSampler(e){if(e.do_sample)return new _h(e);if(e.num_beams>1)return new gh(e);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 hh(e)}},hh=class extends Cs{async sample(e){let r=Se(e.data)[1];return[[BigInt(r),0]]}},_h=class extends Cs{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await Zt(e,r),o=Le(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},gh=class extends Cs{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await Zt(e,r),o=Le(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var Ao=null;function LA(t){Ao=t}function wh(t){if(t instanceof D)return t;if(t.length===0)throw Error("items must be non-empty");if(Array.isArray(t[0])){if(t.some(e=>e.length!==t[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 D("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new D("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function xh(t){return new D("bool",[t],[1])}var j={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15},zA={[j.DecoderOnly]:{can_generate:!0,forward:Ct,prepare_inputs:Mo},[j.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Ct,prepare_inputs:Mo},[j.Seq2Seq]:{can_generate:!0,forward:Uc,prepare_inputs:To},[j.Vision2Seq]:{can_generate:!0,forward:Uc,prepare_inputs:To},[j.Musicgen]:{can_generate:!0,forward:Uc},[j.EncoderDecoder]:{can_generate:!1,forward:Uc},[j.ImageTextToText]:{can_generate:!0,forward:vz,prepare_inputs:Bc},[j.AudioTextToText]:{can_generate:!0,forward:bz,prepare_inputs:Bc},[j.Phi3V]:{can_generate:!0,prepare_inputs:Bc},[j.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Bc},[j.MultiModality]:{can_generate:!0},[j.AutoEncoder]:{can_generate:!1,forward:yz},[j.Chatterbox]:{can_generate:!0,forward:Wt},default:{can_generate:!1,forward:Wt}},dr=new Map,Fc=new Map,Ps=new Map,y=class extends Ze{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,r,s){super(),this.config=e,this.sessions=r,this.configs=s;let n=Ps.get(this.constructor),o=dr.get(n),a=zA[o]??zA.default;this.can_generate=a.can_generate,this._forward=a.forward,this._prepare_inputs_for_generation=a.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let e=[];for(let r of Object.values(this.sessions))e.push(r.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:u=null,dtype:p=null,use_external_data_format:f=null,session_options:m={}}={}){let h={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:u,dtype:p,use_external_data_format:f,session_options:m},w=Ps.get(this),x=dr.get(w);s=h.config=await Mr.from_pretrained(e,h);let k;if(x===j.DecoderOnly)k=await Promise.all([Et(e,{model:h.model_file_name??"model"},h,"model"),Tr(e,{generation_config:"generation_config.json"},h)]);else if(x===j.Seq2Seq||x===j.Vision2Seq)k=await Promise.all([Et(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h,"decoder_model_merged"),Tr(e,{generation_config:"generation_config.json"},h)]);else if(x===j.MaskGeneration)k=await Promise.all([Et(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},h)]);else if(x===j.EncoderDecoder)k=await Promise.all([Et(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h,"decoder_model_merged")]);else if(x===j.ImageTextToText){let E={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};s.is_encoder_decoder&&(E.model="encoder_model"),k=await Promise.all([Et(e,E,h,"decoder_model_merged"),Tr(e,{generation_config:"generation_config.json"},h)])}else if(x===j.AudioTextToText){let E={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};k=await Promise.all([Et(e,E,h,"decoder_model_merged"),Tr(e,{generation_config:"generation_config.json"},h)])}else if(x===j.ImageAudioTextToText){let E={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};k=await Promise.all([Et(e,E,h),Tr(e,{generation_config:"generation_config.json"},h)])}else if(x===j.Musicgen)k=await Promise.all([Et(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},h,"decoder_model_merged"),Tr(e,{generation_config:"generation_config.json"},h)]);else if(x===j.MultiModality)k=await Promise.all([Et(e,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},h,"model"),Tr(e,{generation_config:"generation_config.json"},h)]);else if(x===j.Phi3V)k=await Promise.all([Et(e,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},h,"model"),Tr(e,{generation_config:"generation_config.json"},h)]);else if(x===j.Chatterbox)k=await Promise.all([Et(e,{embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"},h,"model"),Tr(e,{generation_config:"generation_config.json"},h)]);else if(x===j.AutoEncoder)k=await Promise.all([Et(e,{encoder_model:"encoder_model",decoder_model:"decoder_model"},h)]);else if(x===j.Supertonic)k=await Promise.all([Et(e,{text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"},h)]);else{if(x===void 0){let E=w??s?.model_type;E!=="custom"&&Q.warn(`Model type for '${E}' not found, assuming encoder-only architecture. Please report this at ${Fr}.`)}k=await Promise.all([Et(e,{model:h.model_file_name??"model"},h)])}return new this(s,...k)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,r,s=null){let n=new Is;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new Ic(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new Oc(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new zc(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new Cc(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&n.push(new Pc(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new Mc(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new Tc(e.max_length,e.forced_eos_token_id)),e.begin_suppress_tokens!==null){let o=r>1||e.forced_bos_token_id===null?r:r+1;n.push(new hn(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new Lc(e.guidance_scale)),e.temperature===0&&e.do_sample&&(Q.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&n.push(new Nc(e.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(e,r,s=_n){let n={...this.config};for(let a of["decoder","generator","text_config"])a in n&&Object.assign(n,n[a]);let o=new s(n);return Object.assign(o,this.generation_config??{}),e&&Object.assign(o,e),r&&Object.assign(o,nt(r,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,r=null){let s=new $c;return e.max_length!==null&&s.push(new Rc(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new Dc(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[Ao.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,Ao.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,Ao.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,Ao.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=Ps.get(this.constructor),s=new Set,n=this.config.model_type;for(let a of e){let i=a?.get(n);i&&s.add(i)}let o=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(o+=` Please use the following class instead: ${[...s].join(", ")}`),Error(o)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:r,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=this.getPastKeyValues(r,s.past_key_values),s.input_ids=new D("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in s:s.attention_mask=Ee([s.attention_mask,at([s.attention_mask.dims[0],1])],1),s.position_ids=null,s}_prepare_model_inputs({inputs:e,bos_token_id:r,model_kwargs:s}){let n=nt(s,this.forward_params),o=this.main_input_name;if(o in n){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[o]=e;return{inputs_tensor:n[o],model_inputs:n,model_input_name:o}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:r,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:a,pixel_values:i,attention_mask:l,...u}=r,p=await this._prepare_inputs_embeds(r);r={...u,...nt(p,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await Wt(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=Ee([o,uo(o,0)],0),"attention_mask"in r&&(r.attention_mask=Ee([r.attention_mask,Vd(r.attention_mask)],0));else if(r.decoder_input_ids){let a=wh(r.decoder_input_ids).dims[0];if(a!==o.dims[0]){if(o.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${o.dims[0]}) than the decoder inputs (${a}).`);o=Ee(Array.from({length:a},()=>o),0)}}return r.encoder_outputs=o,r}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:r,model_kwargs:s,decoder_start_token_id:n,bos_token_id:o,generation_config:a}){let{decoder_input_ids:i,...l}=s;if(!(i instanceof D)){if(i)Array.isArray(i[0])||(i=Array.from({length:e},()=>i));else if(n??=o,this.config.model_type==="musicgen")i=Array.from({length:e*this.config.decoder.num_codebooks},()=>[n]);else if(Array.isArray(n)){if(n.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${n.length}`);i=n}else i=Array.from({length:e},()=>[n]);i=wh(i)}return s.decoder_attention_mask=Jl(i),{input_ids:i,model_inputs:l}}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,streamer:o=null,...a}){this._validate_model_class(),r=this._prepare_generation_config(r,a);let{inputs_tensor:i,model_inputs:l,model_input_name:u}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),p=this.config.is_encoder_decoder;p&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:u,generation_config:r})));let f;p?{input_ids:f,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[u].dims.at(0),model_input_name:u,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):f=l[u];let m=f.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=m+r.max_new_tokens);let h=this._get_logits_processor(r,m,s),w=this._get_stopping_criteria(r,n),x=l[u].dims.at(0),k=Cs.getSampler(r),E=new Array(x).fill(0),A=f.tolist();o&&o.put(A);let S,T={},P={};for(;;){if(l=this.prepare_inputs_for_generation(A,l,r),S=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){let X=this.getAttentions(S);for(let Y in X)Y in T||(T[Y]=[]),T[Y].push(X[Y])}else this._return_dict_in_generate_keys&&Object.assign(P,nt(S,this._return_dict_in_generate_keys));let F=S.logits.slice(null,-1,null).to("float32"),H=h(A,F),V=[];for(let X=0;X<H.dims.at(0);++X){let Y=H[X],U=await k(Y);for(let[z,ne]of U){let ae=BigInt(z);E[X]+=ne,A[X].push(ae),V.push([ae]);break}}if(o&&o.put(V),w(A).every(X=>X))break;l=this._update_model_kwargs_for_generation({generated_input_ids:V,outputs:S,model_inputs:l,is_encoder_decoder:p})}o&&o.end();let C=this.getPastKeyValues(S,l.past_key_values,!0),v=new D("int64",A.flat(),[A.length,A[0].length]);if(r.return_dict_in_generate)return{sequences:v,past_key_values:C,...T,...P};for(let F of Object.values(S))F.location==="gpu-buffer"&&F.dispose();return v}getPastKeyValues(e,r,s=!1){let n=Object.create(null);for(let o in e)if(o.startsWith("present")){let a=o.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values"),i=o.includes("encoder");if(i&&r?n[a]=r[a]:n[a]=e[o],r&&(!i||s)){let l=r[a];l.location==="gpu-buffer"&&l.dispose()}}return n}getAttentions(e){let r={};for(let s of["cross_attentions","encoder_attentions","decoder_attentions"])for(let n in e)n.startsWith(s)&&(s in r||(r[s]=[]),r[s].push(e[n]));return r}addPastKeyValues(e,r){if(r)Object.assign(e,r);else{let s=this.sessions.decoder_model_merged??this.sessions.model,n=(e[this.main_input_name]??e.attention_mask)?.dims?.[0]??1,o=s?.config?.kv_cache_dtype??"float32",a=o==="float16"?nn.float16:nn.float32,i=Ec(this.config,{batch_size:n});for(let l in i){let u=i[l].reduce((p,f)=>p*f,1);e[l]=new D(o,new a(u),i[l])}}}async encode_image({pixel_values:e}){return(await ue(this.sessions.vision_encoder,{pixel_values:e})).image_features}async encode_text({input_ids:e}){return(await ue(this.sessions.embed_tokens,{input_ids:e})).inputs_embeds}async encode_audio({audio_values:e}){return(await ue(this.sessions.audio_encoder,{audio_values:e})).audio_features}};async function Uc(t,e){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,...o}=e;if(!r){let a=nt(e,t.sessions.model.inputNames);r=(await Wt(t,a)).last_hidden_state}return o.input_ids=n,o.encoder_hidden_states=r,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(o.encoder_attention_mask=e.attention_mask),await Ct(t,o,!0)}async function Wt(t,e){let r=t.sessions.model,s=nt(e,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!s.inputs_embeds){if(!e.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");s.inputs_embeds=await t.encode_text({input_ids:e.input_ids})}if(r.inputNames.includes("token_type_ids")&&!s.token_type_ids){if(!s.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");s.token_type_ids=Vd(s.input_ids)}if(r.inputNames.includes("pixel_mask")&&!s.pixel_mask){if(!s.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let n=s.pixel_values.dims;s.pixel_mask=at([n[0],n[2],n[3]])}return await ue(r,s)}async function yz(t,e){let r=await t.encode(e);return await t.decode(r)}async function Ct(t,e,r=!1){let s=t.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...o}=e;if(s.inputNames.includes("use_cache_branch")&&(o.use_cache_branch=xh(!!n)),s.inputNames.includes("position_ids")&&o.attention_mask&&!o.position_ids){let i=["paligemma","gemma3_text","gemma3"].includes(t.config.model_type)?1:0;o.position_ids=kz(o,n,i)}t.addPastKeyValues(o,n);let a=nt(o,s.inputNames);return await ue(s,a)}async function NA(t,{encode_function:e,merge_function:r,modality_input_name:s,modality_output_name:n,input_ids:o=null,attention_mask:a=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:u=null,generation_config:p=null,logits_processor:f=null,...m}){let h=m[s];if(!l){if(l=await t.encode_text({input_ids:o,...m}),h&&o.dims[1]!==1){let x=await e({[s]:h,...m});({inputs_embeds:l,attention_mask:a}=r({[n]:x,inputs_embeds:l,input_ids:o,attention_mask:a}))}else if(u&&h&&o.dims[1]===1){let x=o.dims[1],k=Object.values(u)[0].dims.at(-2);a=Ee([at([o.dims[0],k]),a.slice(null,[a.dims[1]-x,a.dims[1]])],1)}}if(!i&&["qwen2_vl","qwen2_5_vl_text","qwen3_vl_text","qwen3_5_text","qwen3_5_moe_text"].includes(t.config.model_type)){let{image_grid_thw:x,video_grid_thw:k}=m;[i]=t.get_rope_index(o,x,k,a)}return await Ct(t,{inputs_embeds:l,past_key_values:u,attention_mask:a,position_ids:i,generation_config:p,logits_processor:f},!0)}async function bz(t,e){return await NA(t,{...e,modality_input_name:"audio_values",modality_output_name:"audio_features",encode_function:t.encode_audio.bind(t),merge_function:t._merge_input_ids_with_audio_features.bind(t)})}async function vz(t,e){return await NA(t,{...e,modality_input_name:"pixel_values",modality_output_name:"image_features",encode_function:t.encode_image.bind(t),merge_function:t._merge_input_ids_with_image_features.bind(t)})}function yh(t,e=0){let[r,s]=t.dims,n=t.data,o=new BigInt64Array(n.length);for(let a=0;a<r;++a){let i=a*s,l=BigInt(e);for(let u=0;u<s;++u){let p=i+u;n[p]===0n?o[p]=BigInt(1):(o[p]=l,l+=n[p])}}return{data:o,dims:t.dims}}function kz(t,e=null,r=0){let{input_ids:s,inputs_embeds:n,attention_mask:o}=t,{data:a,dims:i}=yh(o,r),l=new D("int64",a,i);if(e){let u=-(s??n).dims.at(1);l=l.slice(null,[u,null])}return l}function Mo(t,e,r,s){let n=r.past_key_values?Object.values(r.past_key_values)[0].dims.at(-2):0;if(!r.attention_mask){let o;for(let a of["input_ids","inputs_embeds","position_ids"])if(r[a]){o=r[a].dims;break}if(!o)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=at([o[0],n+o[1]])}if(r.past_key_values){let{input_ids:o,attention_mask:a}=r;a&&a.dims[1]>o.dims[1]||n<o.dims[1]&&(r.input_ids=o.slice(null,[n,null]))}return r}function To(t,e,r,s){return r.past_key_values&&(e=e.map(n=>[n.at(-1)])),{...r,decoder_input_ids:wh(e)}}function Bc(t,...e){return t.config.is_encoder_decoder?To(t,...e):Mo(t,...e)}function $A({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n}){let o=s.tolist().map(u=>u.reduce((p,f,m)=>(f==t&&p.push(m),p),[])),a=o.reduce((u,p)=>u+p.length,0),i=r.dims[0];if(a!==i)throw new Error(`Number of tokens and features do not match: tokens: ${a}, features ${i}`);let l=0;for(let u=0;u<o.length;++u){let p=o[u],f=e[u];for(let m=0;m<p.length;++m)f[p[m]].data.set(r[l++].data)}return{inputs_embeds:e,attention_mask:n}}function fr({image_token_id:t,inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return $A({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}function jc({audio_token_id:t,inputs_embeds:e,audio_features:r,input_ids:s,attention_mask:n}){return $A({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}async function Tr(t,e,r){return Object.fromEntries(await Promise.all(Object.keys(e).map(async s=>{let n=await ct(t,e[s],!1,r);return[s,n]})))}var zi={};Vs(zi,{ASTForAudioClassification:()=>Ph,ASTModel:()=>Ch,ASTPreTrainedModel:()=>Co,AfmoeForCausalLM:()=>Sh,AfmoeModel:()=>Th,AfmoePreTrainedModel:()=>Oo,AlbertForMaskedLM:()=>Eh,AlbertForQuestionAnswering:()=>kh,AlbertForSequenceClassification:()=>vh,AlbertModel:()=>bh,AlbertPreTrainedModel:()=>zs,ApertusForCausalLM:()=>Mh,ApertusModel:()=>Ah,ApertusPreTrainedModel:()=>So,ArceeForCausalLM:()=>Ih,ArceeModel:()=>Oh,ArceePreTrainedModel:()=>Io,BartForConditionalGeneration:()=>Lh,BartForSequenceClassification:()=>Nh,BartModel:()=>zh,BartPretrainedModel:()=>wn,BeitForImageClassification:()=>Rh,BeitModel:()=>$h,BeitPreTrainedModel:()=>Po,BertForMaskedLM:()=>Uh,BertForQuestionAnswering:()=>jh,BertForSequenceClassification:()=>Bh,BertForTokenClassification:()=>Fh,BertModel:()=>Dh,BertPreTrainedModel:()=>qr,BlenderbotForConditionalGeneration:()=>qh,BlenderbotModel:()=>Gh,BlenderbotPreTrainedModel:()=>zo,BlenderbotSmallForConditionalGeneration:()=>Vh,BlenderbotSmallModel:()=>Wh,BlenderbotSmallPreTrainedModel:()=>Lo,BloomForCausalLM:()=>Xh,BloomModel:()=>Hh,BloomPreTrainedModel:()=>No,CLIPModel:()=>r_,CLIPPreTrainedModel:()=>mr,CLIPSegForImageSegmentation:()=>i_,CLIPSegModel:()=>a_,CLIPSegPreTrainedModel:()=>Bo,CLIPTextModel:()=>s_,CLIPTextModelWithProjection:()=>Uo,CLIPVisionModel:()=>n_,CLIPVisionModelWithProjection:()=>o_,CamembertForMaskedLM:()=>Yh,CamembertForQuestionAnswering:()=>Zh,CamembertForSequenceClassification:()=>Qh,CamembertForTokenClassification:()=>Jh,CamembertModel:()=>Kh,CamembertPreTrainedModel:()=>Wr,ChatterboxModel:()=>$o,ChatterboxPreTrainedModel:()=>Gc,ChineseCLIPModel:()=>e_,ChineseCLIPPreTrainedModel:()=>qc,ClapAudioModelWithProjection:()=>Do,ClapModel:()=>t_,ClapPreTrainedModel:()=>xn,ClapTextModelWithProjection:()=>Ro,CodeGenForCausalLM:()=>c_,CodeGenModel:()=>l_,CodeGenPreTrainedModel:()=>Fo,Cohere2ForCausalLM:()=>f_,Cohere2Model:()=>d_,Cohere2PreTrainedModel:()=>Go,CohereForCausalLM:()=>p_,CohereModel:()=>u_,CoherePreTrainedModel:()=>jo,ConvBertForMaskedLM:()=>h_,ConvBertForQuestionAnswering:()=>w_,ConvBertForSequenceClassification:()=>__,ConvBertForTokenClassification:()=>g_,ConvBertModel:()=>m_,ConvBertPreTrainedModel:()=>Vr,ConvNextForImageClassification:()=>y_,ConvNextModel:()=>x_,ConvNextPreTrainedModel:()=>qo,ConvNextV2ForImageClassification:()=>v_,ConvNextV2Model:()=>b_,ConvNextV2PreTrainedModel:()=>Wo,DFineForObjectDetection:()=>M_,DFineModel:()=>A_,DFinePreTrainedModel:()=>Ho,DINOv3ConvNextModel:()=>Y_,DINOv3ConvNextPreTrainedModel:()=>Qc,DINOv3ViTModel:()=>Q_,DINOv3ViTPreTrainedModel:()=>Jc,DPTForDepthEstimation:()=>og,DPTModel:()=>ng,DPTPreTrainedModel:()=>Zo,DacDecoderModel:()=>Ko,DacDecoderOutput:()=>Vc,DacEncoderModel:()=>Xo,DacEncoderOutput:()=>Wc,DacModel:()=>T_,DacPreTrainedModel:()=>yn,DebertaForMaskedLM:()=>O_,DebertaForQuestionAnswering:()=>P_,DebertaForSequenceClassification:()=>I_,DebertaForTokenClassification:()=>C_,DebertaModel:()=>S_,DebertaPreTrainedModel:()=>Hr,DebertaV2ForMaskedLM:()=>L_,DebertaV2ForQuestionAnswering:()=>R_,DebertaV2ForSequenceClassification:()=>N_,DebertaV2ForTokenClassification:()=>$_,DebertaV2Model:()=>z_,DebertaV2PreTrainedModel:()=>Xr,DecisionTransformerModel:()=>D_,DecisionTransformerPreTrainedModel:()=>Hc,DeiTForImageClassification:()=>B_,DeiTModel:()=>U_,DeiTPreTrainedModel:()=>Yo,DepthAnythingForDepthEstimation:()=>F_,DepthAnythingPreTrainedModel:()=>Xc,DepthProForDepthEstimation:()=>j_,DepthProPreTrainedModel:()=>Kc,DetrForObjectDetection:()=>q_,DetrForSegmentation:()=>W_,DetrModel:()=>G_,DetrObjectDetectionOutput:()=>vn,DetrPreTrainedModel:()=>bn,DetrSegmentationOutput:()=>Yc,Dinov2ForImageClassification:()=>H_,Dinov2Model:()=>V_,Dinov2PreTrainedModel:()=>Qo,Dinov2WithRegistersForImageClassification:()=>K_,Dinov2WithRegistersModel:()=>X_,Dinov2WithRegistersPreTrainedModel:()=>Jo,DistilBertForMaskedLM:()=>rg,DistilBertForQuestionAnswering:()=>tg,DistilBertForSequenceClassification:()=>Z_,DistilBertForTokenClassification:()=>eg,DistilBertModel:()=>J_,DistilBertPreTrainedModel:()=>Kr,DonutSwinModel:()=>sg,DonutSwinPreTrainedModel:()=>Zc,EdgeTamModel:()=>jy,EfficientNetForImageClassification:()=>ig,EfficientNetModel:()=>ag,EfficientNetPreTrainedModel:()=>ea,ElectraForMaskedLM:()=>cg,ElectraForQuestionAnswering:()=>dg,ElectraForSequenceClassification:()=>ug,ElectraForTokenClassification:()=>pg,ElectraModel:()=>lg,ElectraPreTrainedModel:()=>Yr,Ernie4_5ForCausalLM:()=>mg,Ernie4_5Model:()=>fg,Ernie4_5PretrainedModel:()=>ta,EsmForMaskedLM:()=>_g,EsmForSequenceClassification:()=>gg,EsmForTokenClassification:()=>wg,EsmModel:()=>hg,EsmPreTrainedModel:()=>Ls,ExaoneForCausalLM:()=>yg,ExaoneModel:()=>xg,ExaonePreTrainedModel:()=>ra,FalconForCausalLM:()=>vg,FalconH1ForCausalLM:()=>Eg,FalconH1Model:()=>kg,FalconH1PreTrainedModel:()=>na,FalconModel:()=>bg,FalconPreTrainedModel:()=>sa,FastViTForImageClassification:()=>Mg,FastViTModel:()=>Ag,FastViTPreTrainedModel:()=>oa,Florence2ForConditionalGeneration:()=>Tg,Florence2PreTrainedModel:()=>eu,GLPNForDepthEstimation:()=>Rg,GLPNModel:()=>$g,GLPNPreTrainedModel:()=>pa,GPT2LMHeadModel:()=>Hg,GPT2Model:()=>Vg,GPT2PreTrainedModel:()=>_a,GPTBigCodeForCausalLM:()=>Ug,GPTBigCodeModel:()=>Dg,GPTBigCodePreTrainedModel:()=>da,GPTJForCausalLM:()=>Kg,GPTJModel:()=>Xg,GPTJPreTrainedModel:()=>ga,GPTNeoForCausalLM:()=>Fg,GPTNeoModel:()=>Bg,GPTNeoPreTrainedModel:()=>fa,GPTNeoXForCausalLM:()=>Gg,GPTNeoXModel:()=>jg,GPTNeoXPreTrainedModel:()=>ma,Gemma2ForCausalLM:()=>Cg,Gemma2Model:()=>Ig,Gemma2PreTrainedModel:()=>ia,Gemma3ForCausalLM:()=>zg,Gemma3Model:()=>Pg,Gemma3PreTrainedModel:()=>la,Gemma3nForConditionalGeneration:()=>ca,Gemma3nPreTrainedModel:()=>tu,GemmaForCausalLM:()=>Og,GemmaModel:()=>Sg,GemmaPreTrainedModel:()=>aa,GlmForCausalLM:()=>Ng,GlmModel:()=>Lg,GlmPreTrainedModel:()=>ua,GptOssForCausalLM:()=>Wg,GptOssModel:()=>qg,GptOssPreTrainedModel:()=>ha,GraniteForCausalLM:()=>Qg,GraniteModel:()=>Yg,GraniteMoeHybridForCausalLM:()=>Zg,GraniteMoeHybridModel:()=>Jg,GraniteMoeHybridPreTrainedModel:()=>xa,GranitePreTrainedModel:()=>wa,GroundingDinoForObjectDetection:()=>ew,GroundingDinoPreTrainedModel:()=>ru,GroupViTModel:()=>tw,GroupViTPreTrainedModel:()=>su,HeliumForCausalLM:()=>sw,HeliumModel:()=>rw,HeliumPreTrainedModel:()=>ya,HieraForImageClassification:()=>ow,HieraModel:()=>nw,HieraPreTrainedModel:()=>ba,HubertForCTC:()=>dw,HubertForSequenceClassification:()=>fw,HubertModel:()=>pw,HubertPreTrainedModel:()=>uw,HunYuanDenseV1ForCausalLM:()=>hw,HunYuanDenseV1Model:()=>mw,HunYuanDenseV1PreTrainedModel:()=>va,IJepaForImageClassification:()=>ww,IJepaModel:()=>gw,IJepaPreTrainedModel:()=>ka,Idefics3ForConditionalGeneration:()=>ou,Idefics3PreTrainedModel:()=>nu,JAISLMHeadModel:()=>yw,JAISModel:()=>xw,JAISPreTrainedModel:()=>Ea,JinaCLIPModel:()=>bw,JinaCLIPPreTrainedModel:()=>kn,JinaCLIPTextModel:()=>Aa,JinaCLIPVisionModel:()=>vw,Lfm2ForCausalLM:()=>Ew,Lfm2Model:()=>kw,Lfm2MoeForCausalLM:()=>Mw,Lfm2MoeModel:()=>Aw,Lfm2MoePreTrainedModel:()=>Ta,Lfm2PreTrainedModel:()=>Ma,LiteWhisperForConditionalGeneration:()=>Z0,Llama4ForCausalLM:()=>Ow,Llama4PreTrainedModel:()=>au,LlamaForCausalLM:()=>Sw,LlamaModel:()=>Tw,LlamaPreTrainedModel:()=>Sa,LlavaForConditionalGeneration:()=>En,LlavaOnevisionForConditionalGeneration:()=>En,LlavaPreTrainedModel:()=>iu,LlavaQwen2ForCausalLM:()=>Cw,LongT5ForConditionalGeneration:()=>zw,LongT5Model:()=>Pw,LongT5PreTrainedModel:()=>Oa,M2M100ForConditionalGeneration:()=>Nw,M2M100Model:()=>Lw,M2M100PreTrainedModel:()=>Ia,MBartForCausalLM:()=>Gw,MBartForConditionalGeneration:()=>Fw,MBartForSequenceClassification:()=>jw,MBartModel:()=>Bw,MBartPreTrainedModel:()=>Ns,MPNetForMaskedLM:()=>Tx,MPNetForQuestionAnswering:()=>Ix,MPNetForSequenceClassification:()=>Sx,MPNetForTokenClassification:()=>Ox,MPNetModel:()=>Mx,MPNetPreTrainedModel:()=>Qr,MT5ForConditionalGeneration:()=>Lx,MT5Model:()=>zx,MT5PreTrainedModel:()=>ja,MarianMTModel:()=>Rw,MarianModel:()=>$w,MarianPreTrainedModel:()=>Ca,MaskFormerForInstanceSegmentation:()=>Uw,MaskFormerModel:()=>Dw,MaskFormerPreTrainedModel:()=>Pa,Metric3DForDepthEstimation:()=>qw,Metric3DPreTrainedModel:()=>lu,Metric3Dv2ForDepthEstimation:()=>Ww,Metric3Dv2PreTrainedModel:()=>cu,MgpstrForSceneTextRecognition:()=>Vw,MgpstrModelOutput:()=>uu,MgpstrPreTrainedModel:()=>pu,MimiDecoderModel:()=>La,MimiDecoderOutput:()=>fu,MimiEncoderModel:()=>za,MimiEncoderOutput:()=>du,MimiModel:()=>Hw,MimiPreTrainedModel:()=>An,MistralForCausalLM:()=>Kw,MistralModel:()=>Xw,MistralPreTrainedModel:()=>Na,MobileBertForMaskedLM:()=>Qw,MobileBertForQuestionAnswering:()=>Zw,MobileBertForSequenceClassification:()=>Jw,MobileBertModel:()=>Yw,MobileBertPreTrainedModel:()=>$s,MobileLLMForCausalLM:()=>tx,MobileLLMModel:()=>ex,MobileLLMPreTrainedModel:()=>$a,MobileNetV1ForImageClassification:()=>sx,MobileNetV1ForSemanticSegmentation:()=>nx,MobileNetV1Model:()=>rx,MobileNetV1PreTrainedModel:()=>Mn,MobileNetV2ForImageClassification:()=>ax,MobileNetV2ForSemanticSegmentation:()=>ix,MobileNetV2Model:()=>ox,MobileNetV2PreTrainedModel:()=>Tn,MobileNetV3ForImageClassification:()=>cx,MobileNetV3ForSemanticSegmentation:()=>ux,MobileNetV3Model:()=>lx,MobileNetV3PreTrainedModel:()=>Sn,MobileNetV4ForImageClassification:()=>dx,MobileNetV4ForSemanticSegmentation:()=>fx,MobileNetV4Model:()=>px,MobileNetV4PreTrainedModel:()=>On,MobileViTForImageClassification:()=>hx,MobileViTModel:()=>mx,MobileViTPreTrainedModel:()=>Ra,MobileViTV2ForImageClassification:()=>gx,MobileViTV2Model:()=>_x,MobileViTV2PreTrainedModel:()=>Da,ModernBertDecoderForCausalLM:()=>kx,ModernBertDecoderModel:()=>vx,ModernBertDecoderPreTrainedModel:()=>Ua,ModernBertForMaskedLM:()=>xx,ModernBertForSequenceClassification:()=>yx,ModernBertForTokenClassification:()=>bx,ModernBertModel:()=>wx,ModernBertPreTrainedModel:()=>Rs,Moondream1ForConditionalGeneration:()=>Iw,MoonshineForConditionalGeneration:()=>Ax,MoonshineModel:()=>Ex,MoonshinePreTrainedModel:()=>Ba,MptForCausalLM:()=>Px,MptModel:()=>Cx,MptPreTrainedModel:()=>Fa,MultiModalityCausalLM:()=>Nx,MultiModalityPreTrainedModel:()=>mu,MusicgenForCausalLM:()=>Rx,MusicgenForConditionalGeneration:()=>qa,MusicgenModel:()=>$x,MusicgenPreTrainedModel:()=>Ga,NanoChatForCausalLM:()=>Ux,NanoChatModel:()=>Dx,NanoChatPreTrainedModel:()=>Wa,NeoBertForMaskedLM:()=>Fx,NeoBertForQuestionAnswering:()=>qx,NeoBertForSequenceClassification:()=>jx,NeoBertForTokenClassification:()=>Gx,NeoBertModel:()=>Bx,NeoBertPreTrainedModel:()=>Jr,NomicBertModel:()=>Wx,NomicBertPreTrainedModel:()=>hu,OPTForCausalLM:()=>ty,OPTModel:()=>ey,OPTPreTrainedModel:()=>Ya,Olmo2ForCausalLM:()=>Kx,Olmo2Model:()=>Xx,Olmo2PreTrainedModel:()=>Ha,Olmo3ForCausalLM:()=>Qx,Olmo3Model:()=>Yx,Olmo3PreTrainedModel:()=>Xa,OlmoForCausalLM:()=>Hx,OlmoModel:()=>Vx,OlmoPreTrainedModel:()=>Va,OpenELMForCausalLM:()=>Zx,OpenELMModel:()=>Jx,OpenELMPreTrainedModel:()=>Ka,OwlViTForObjectDetection:()=>oy,OwlViTModel:()=>ny,OwlViTPreTrainedModel:()=>Ja,Owlv2ForObjectDetection:()=>sy,Owlv2Model:()=>ry,Owlv2PreTrainedModel:()=>Qa,PaliGemmaForConditionalGeneration:()=>ay,PaliGemmaPreTrainedModel:()=>_u,ParakeetForCTC:()=>iy,ParakeetPreTrainedModel:()=>gu,PatchTSMixerForPrediction:()=>cy,PatchTSMixerModel:()=>ly,PatchTSMixerPreTrainedModel:()=>Za,PatchTSTForPrediction:()=>py,PatchTSTModel:()=>uy,PatchTSTPreTrainedModel:()=>ei,Phi3ForCausalLM:()=>hy,Phi3Model:()=>my,Phi3PreTrainedModel:()=>ri,Phi3VForCausalLM:()=>si,Phi3VPreTrainedModel:()=>wu,PhiForCausalLM:()=>fy,PhiModel:()=>dy,PhiPreTrainedModel:()=>ti,PreTrainedModel:()=>y,PvtForImageClassification:()=>gy,PvtModel:()=>_y,PvtPreTrainedModel:()=>ni,PyAnnoteForAudioFrameClassification:()=>xy,PyAnnoteModel:()=>wy,PyAnnotePreTrainedModel:()=>oi,Qwen2ForCausalLM:()=>by,Qwen2Model:()=>yy,Qwen2PreTrainedModel:()=>ai,Qwen2VLForConditionalGeneration:()=>ii,Qwen2VLPreTrainedModel:()=>xu,Qwen2_5_VLForConditionalGeneration:()=>li,Qwen3ForCausalLM:()=>ky,Qwen3Model:()=>vy,Qwen3PreTrainedModel:()=>ci,Qwen3VLForConditionalGeneration:()=>ui,Qwen3_5ForConditionalGeneration:()=>pi,Qwen3_5MoeForConditionalGeneration:()=>Ey,RFDetrForObjectDetection:()=>Sy,RFDetrModel:()=>Ty,RFDetrObjectDetectionOutput:()=>yu,RFDetrPreTrainedModel:()=>fi,RTDetrForObjectDetection:()=>E_,RTDetrModel:()=>k_,RTDetrObjectDetectionOutput:()=>hr,RTDetrPreTrainedModel:()=>Vo,RTDetrV2ForObjectDetection:()=>By,RTDetrV2Model:()=>Uy,RTDetrV2ObjectDetectionOutput:()=>bu,RTDetrV2PreTrainedModel:()=>mi,ResNetForImageClassification:()=>My,ResNetModel:()=>Ay,ResNetPreTrainedModel:()=>di,RoFormerForMaskedLM:()=>Ny,RoFormerForQuestionAnswering:()=>Dy,RoFormerForSequenceClassification:()=>$y,RoFormerForTokenClassification:()=>Ry,RoFormerModel:()=>Ly,RoFormerPreTrainedModel:()=>es,RobertaForMaskedLM:()=>Iy,RobertaForQuestionAnswering:()=>zy,RobertaForSequenceClassification:()=>Cy,RobertaForTokenClassification:()=>Py,RobertaModel:()=>Oy,RobertaPreTrainedModel:()=>Zr,Sam2ImageSegmentationOutput:()=>Eu,Sam2Model:()=>hi,Sam2PreTrainedModel:()=>Au,Sam3TrackerModel:()=>Gy,SamImageSegmentationOutput:()=>vu,SamModel:()=>Fy,SamPreTrainedModel:()=>ku,SapiensForDepthEstimation:()=>Wy,SapiensForNormalEstimation:()=>Vy,SapiensForSemanticSegmentation:()=>qy,SapiensPreTrainedModel:()=>In,SegformerForImageClassification:()=>Xy,SegformerForSemanticSegmentation:()=>Ky,SegformerModel:()=>Hy,SegformerPreTrainedModel:()=>Cn,SiglipModel:()=>Yy,SiglipPreTrainedModel:()=>_i,SiglipTextModel:()=>gi,SiglipVisionModel:()=>Qy,SmolLM3ForCausalLM:()=>Zy,SmolLM3Model:()=>Jy,SmolLM3PreTrainedModel:()=>wi,SmolVLMForConditionalGeneration:()=>_w,SnacDecoderModel:()=>yi,SnacEncoderModel:()=>xi,SnacModel:()=>e0,SnacPreTrainedModel:()=>Pn,SpeechT5ForSpeechToText:()=>r0,SpeechT5ForTextToSpeech:()=>s0,SpeechT5HifiGan:()=>n0,SpeechT5Model:()=>t0,SpeechT5PreTrainedModel:()=>zn,SqueezeBertForMaskedLM:()=>a0,SqueezeBertForQuestionAnswering:()=>l0,SqueezeBertForSequenceClassification:()=>i0,SqueezeBertModel:()=>o0,SqueezeBertPreTrainedModel:()=>Ds,StableLmForCausalLM:()=>u0,StableLmModel:()=>c0,StableLmPreTrainedModel:()=>bi,Starcoder2ForCausalLM:()=>d0,Starcoder2Model:()=>p0,Starcoder2PreTrainedModel:()=>vi,StyleTextToSpeech2Model:()=>f0,StyleTextToSpeech2PreTrainedModel:()=>Mu,SupertonicForConditionalGeneration:()=>ki,SupertonicPreTrainedModel:()=>Tu,Swin2SRForImageSuperResolution:()=>w0,Swin2SRModel:()=>g0,Swin2SRPreTrainedModel:()=>Ei,SwinForImageClassification:()=>h0,SwinForSemanticSegmentation:()=>_0,SwinModel:()=>m0,SwinPreTrainedModel:()=>Ln,T5ForConditionalGeneration:()=>y0,T5Model:()=>x0,T5PreTrainedModel:()=>Ai,TableTransformerForObjectDetection:()=>v0,TableTransformerModel:()=>b0,TableTransformerObjectDetectionOutput:()=>Su,TableTransformerPreTrainedModel:()=>Mi,TrOCRForCausalLM:()=>k0,TrOCRPreTrainedModel:()=>Ou,UltravoxModel:()=>Cu,UltravoxPreTrainedModel:()=>Iu,UniSpeechForCTC:()=>M0,UniSpeechForSequenceClassification:()=>T0,UniSpeechModel:()=>A0,UniSpeechPreTrainedModel:()=>Nn,UniSpeechSatForAudioFrameClassification:()=>C0,UniSpeechSatForCTC:()=>O0,UniSpeechSatForSequenceClassification:()=>I0,UniSpeechSatModel:()=>S0,UniSpeechSatPreTrainedModel:()=>Us,VaultGemmaForCausalLM:()=>z0,VaultGemmaModel:()=>P0,VaultGemmaPreTrainedModel:()=>Ti,ViTForImageClassification:()=>$0,ViTMAEModel:()=>R0,ViTMAEPreTrainedModel:()=>Pu,ViTMSNForImageClassification:()=>U0,ViTMSNModel:()=>D0,ViTMSNPreTrainedModel:()=>Oi,ViTModel:()=>N0,ViTPreTrainedModel:()=>Si,VisionEncoderDecoderModel:()=>L0,VitMatteForImageMatting:()=>B0,VitMattePreTrainedModel:()=>zu,VitPoseForPoseEstimation:()=>F0,VitPosePreTrainedModel:()=>Lu,VitsModel:()=>j0,VitsModelOutput:()=>Nu,VitsPreTrainedModel:()=>$u,VoxtralForConditionalGeneration:()=>E0,Wav2Vec2BertForCTC:()=>q0,Wav2Vec2BertForSequenceClassification:()=>W0,Wav2Vec2BertModel:()=>G0,Wav2Vec2BertPreTrainedModel:()=>$n,Wav2Vec2ForAudioFrameClassification:()=>cw,Wav2Vec2ForCTC:()=>iw,Wav2Vec2ForSequenceClassification:()=>lw,Wav2Vec2Model:()=>aw,Wav2Vec2PreTrainedModel:()=>tr,WavLMForAudioFrameClassification:()=>Y0,WavLMForCTC:()=>H0,WavLMForSequenceClassification:()=>X0,WavLMForXVector:()=>K0,WavLMModel:()=>V0,WavLMPreTrainedModel:()=>ts,WeSpeakerResNetModel:()=>Q0,WeSpeakerResNetPreTrainedModel:()=>Du,WhisperForConditionalGeneration:()=>Bu,WhisperModel:()=>J0,WhisperPreTrainedModel:()=>Ii,XLMForQuestionAnswering:()=>nb,XLMForSequenceClassification:()=>rb,XLMForTokenClassification:()=>sb,XLMModel:()=>eb,XLMPreTrainedModel:()=>rs,XLMRobertaForMaskedLM:()=>ab,XLMRobertaForQuestionAnswering:()=>cb,XLMRobertaForSequenceClassification:()=>ib,XLMRobertaForTokenClassification:()=>lb,XLMRobertaModel:()=>ob,XLMRobertaPreTrainedModel:()=>ss,XLMWithLMHeadModel:()=>tb,XVectorOutput:()=>Ru,YolosForObjectDetection:()=>pb,YolosModel:()=>ub,YolosObjectDetectionOutput:()=>Fu,YolosPreTrainedModel:()=>Ci,YoutuForCausalLM:()=>fb,YoutuModel:()=>db,YoutuPreTrainedModel:()=>Pi});var zs=class extends y{},bh=class extends zs{},vh=class extends zs{async _call(e){return new G(await super._call(e))}},kh=class extends zs{async _call(e){return new Ae(await super._call(e))}},Eh=class extends zs{async _call(e){return new we(await super._call(e))}};var So=class extends y{},Ah=class extends So{},Mh=class extends So{};var Oo=class extends y{},Th=class extends Oo{},Sh=class extends Oo{};var Io=class extends y{},Oh=class extends Io{},Ih=class extends Io{};var Co=class extends y{},Ch=class extends Co{},Ph=class extends Co{};var wn=class extends y{},zh=class extends wn{},Lh=class extends wn{},Nh=class extends wn{async _call(e){return new G(await super._call(e))}};var Po=class extends y{},$h=class extends Po{},Rh=class extends Po{async _call(e){return new G(await super._call(e))}};var qr=class extends y{},Dh=class extends qr{},Uh=class extends qr{async _call(e){return new we(await super._call(e))}},Bh=class extends qr{async _call(e){return new G(await super._call(e))}},Fh=class extends qr{async _call(e){return new he(await super._call(e))}},jh=class extends qr{async _call(e){return new Ae(await super._call(e))}};var zo=class extends y{},Gh=class extends zo{},qh=class extends zo{};var Lo=class extends y{},Wh=class extends Lo{},Vh=class extends Lo{};var No=class extends y{},Hh=class extends No{},Xh=class extends No{};var Wr=class extends y{},Kh=class extends Wr{},Yh=class extends Wr{async _call(e){return new we(await super._call(e))}},Qh=class extends Wr{async _call(e){return new G(await super._call(e))}},Jh=class extends Wr{async _call(e){return new he(await super._call(e))}},Zh=class extends Wr{async _call(e){return new Ae(await super._call(e))}};var Ez=4299n,RA=6561n,Gc=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"];main_input_name="input_ids";_return_dict_in_generate_keys=["audio_tokens","speaker_embeddings","speaker_features"]},$o=class extends Gc{async encode_speech(e){return ue(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:r=null,audio_values:s=null,exaggeration:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:u=null,audio_features:p=null,audio_tokens:f=null,speaker_embeddings:m=null,speaker_features:h=null,...w}){let x;if(!a){let E=this.sessions.embed_tokens.inputNames,A={input_ids:e};if(E.includes("exaggeration")){if(!(n instanceof D)){let S=e.dims[0];if(n==null)n=He([S],.5);else if(typeof n=="number")n=He([S],n);else if(Array.isArray(n))n=new D("float32",n,[S]);else throw new Error("Unsupported type for `exaggeration` input")}A.exaggeration=n}if(E.includes("position_ids")&&(A.position_ids=o),{inputs_embeds:a}=await ue(this.sessions.embed_tokens,A),p&&f&&m&&h&&(x={audio_features:p,audio_tokens:f,speaker_embeddings:m,speaker_features:h}),x||s)x??=await this.encode_speech(s),a=Ee([x.audio_features,a],1),r=at([a.dims[0],a.dims[1]]);else{let S=a.dims[1];if(!i||S!==1)throw new Error("Incorrect state encountered during generation.");let T=Object.values(i)[0].dims.at(-2);r=at([a.dims[0],T+S])}}return{...await Ct(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,generation_config:l,logits_processor:u},!1),...x}}prepare_inputs_for_generation(e,r,s){if(!r.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(r.input_ids.dims[1]===1){let n=Array.from({length:e.length},(o,a)=>e[a].length-e[a].findLastIndex(i=>i==RA)-1);r.position_ids=new D("int64",n,[e.length,1])}else{let o=r.input_ids.tolist().map(a=>{let i=0;return a.map(l=>l>=RA?0:i++)});r.position_ids=new D("int64",o.flat(),r.input_ids.dims)}return r.input_ids.dims[1]===1&&(delete r.audio_values,delete r.audio_features,delete r.audio_tokens,delete r.speaker_embeddings,delete r.speaker_features),Mo(this,e,r,s)}async generate(e){let{sequences:r,audio_tokens:s,speaker_embeddings:n,speaker_features:o}=await super.generate({...e,return_dict_in_generate:!0}),a=r.slice(null,[e.input_ids.dims[1],-1]),i=He([a.dims[0],3],Ez),l=Ee([s,a,i],1),{waveform:u}=await ue(this.sessions.conditional_decoder,{speech_tokens:l,speaker_features:o,speaker_embeddings:n});return u}};var qc=class extends y{},e_=class extends qc{};var xn=class extends y{},t_=class extends xn{},Ro=class extends xn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Do=class extends xn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"audio_model"})}};var mr=class extends y{},r_=class extends mr{},s_=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Uo=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},n_=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},o_=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Bo=class extends y{},a_=class extends Bo{},i_=class extends Bo{};var Fo=class extends y{},l_=class extends Fo{},c_=class extends Fo{};var jo=class extends y{},u_=class extends jo{},p_=class extends jo{};var Go=class extends y{},d_=class extends Go{},f_=class extends Go{};var Vr=class extends y{},m_=class extends Vr{},h_=class extends Vr{async _call(e){return new we(await super._call(e))}},__=class extends Vr{async _call(e){return new G(await super._call(e))}},g_=class extends Vr{async _call(e){return new he(await super._call(e))}},w_=class extends Vr{async _call(e){return new Ae(await super._call(e))}};var qo=class extends y{},x_=class extends qo{},y_=class extends qo{async _call(e){return new G(await super._call(e))}};var Wo=class extends y{},b_=class extends Wo{},v_=class extends Wo{async _call(e){return new G(await super._call(e))}};var Vo=class extends y{},k_=class extends Vo{},E_=class extends Vo{async _call(e){return new hr(await super._call(e))}},hr=class extends Ne{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var Ho=class extends y{},A_=class extends Ho{},M_=class extends Ho{async _call(e){return new hr(await super._call(e))}};var Wc=class extends Ne{constructor({audio_codes:e}){super(),this.audio_codes=e}},Vc=class extends Ne{constructor({audio_values:e}){super(),this.audio_values=e}},yn=class extends y{main_input_name="input_values";forward_params=["input_values"]},T_=class extends yn{async encode(e){return new Wc(await ue(this.sessions.encoder_model,e))}async decode(e){return new Vc(await ue(this.sessions.decoder_model,e))}},Xo=class extends yn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Ko=class extends yn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Hr=class extends y{},S_=class extends Hr{},O_=class extends Hr{async _call(e){return new we(await super._call(e))}},I_=class extends Hr{async _call(e){return new G(await super._call(e))}},C_=class extends Hr{async _call(e){return new he(await super._call(e))}},P_=class extends Hr{async _call(e){return new Ae(await super._call(e))}};var Xr=class extends y{},z_=class extends Xr{},L_=class extends Xr{async _call(e){return new we(await super._call(e))}},N_=class extends Xr{async _call(e){return new G(await super._call(e))}},$_=class extends Xr{async _call(e){return new he(await super._call(e))}},R_=class extends Xr{async _call(e){return new Ae(await super._call(e))}};var Hc=class extends y{},D_=class extends Hc{};var Yo=class extends y{},U_=class extends Yo{},B_=class extends Yo{async _call(e){return new G(await super._call(e))}};var Xc=class extends y{},F_=class extends Xc{};var Kc=class extends y{},j_=class extends Kc{};var bn=class extends y{},G_=class extends bn{},q_=class extends bn{async _call(e){return new vn(await super._call(e))}},W_=class extends bn{async _call(e){return new Yc(await super._call(e))}},vn=class extends Ne{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},Yc=class extends Ne{constructor({logits:e,pred_boxes:r,pred_masks:s}){super(),this.logits=e,this.pred_boxes=r,this.pred_masks=s}};var Qo=class extends y{},V_=class extends Qo{},H_=class extends Qo{async _call(e){return new G(await super._call(e))}};var Jo=class extends y{},X_=class extends Jo{},K_=class extends Jo{async _call(e){return new G(await super._call(e))}};var Qc=class extends y{},Y_=class extends Qc{};var Jc=class extends y{},Q_=class extends Jc{};var Kr=class extends y{},J_=class extends Kr{},Z_=class extends Kr{async _call(e){return new G(await super._call(e))}},eg=class extends Kr{async _call(e){return new he(await super._call(e))}},tg=class extends Kr{async _call(e){return new Ae(await super._call(e))}},rg=class extends Kr{async _call(e){return new we(await super._call(e))}};var Zc=class extends y{},sg=class extends Zc{};var Zo=class extends y{},ng=class extends Zo{},og=class extends Zo{};var ea=class extends y{},ag=class extends ea{},ig=class extends ea{async _call(e){return new G(await super._call(e))}};var Yr=class extends y{},lg=class extends Yr{},cg=class extends Yr{async _call(e){return new we(await super._call(e))}},ug=class extends Yr{async _call(e){return new G(await super._call(e))}},pg=class extends Yr{async _call(e){return new he(await super._call(e))}},dg=class extends Yr{async _call(e){return new Ae(await super._call(e))}};var ta=class extends y{},fg=class extends ta{},mg=class extends ta{};var Ls=class extends y{},hg=class extends Ls{},_g=class extends Ls{async _call(e){return new we(await super._call(e))}},gg=class extends Ls{async _call(e){return new G(await super._call(e))}},wg=class extends Ls{async _call(e){return new he(await super._call(e))}};var ra=class extends y{},xg=class extends ra{},yg=class extends ra{};var sa=class extends y{},bg=class extends sa{},vg=class extends sa{};var na=class extends y{},kg=class extends na{},Eg=class extends na{};var oa=class extends y{},Ag=class extends oa{},Mg=class extends oa{async _call(e){return new G(await super._call(e))}};var eu=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"];main_input_name="inputs_embeds"},Tg=class extends eu{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return{inputs_embeds:Ee([r,e],1),attention_mask:Ee([at(r.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:s,attention_mask:n}){if(!e&&!r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let o,a;return e&&(o=await this.encode_text({input_ids:e})),r&&(a=await this.encode_image({pixel_values:r})),o&&a?{inputs_embeds:s,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:o,image_features:a,input_ids:e,attention_mask:n}):s=o||a,{inputs_embeds:s,attention_mask:n}}async forward({input_ids:e,pixel_values:r,attention_mask:s,decoder_input_ids:n,decoder_attention_mask:o,encoder_outputs:a,past_key_values:i,inputs_embeds:l,decoder_inputs_embeds:u}){if(l||({inputs_embeds:l,attention_mask:s}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:l,attention_mask:s})),!a){let{last_hidden_state:f}=await Wt(this,{inputs_embeds:l,attention_mask:s});a=f}if(!u){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");u=await this.encode_text({input_ids:n})}return await Ct(this,{inputs_embeds:u,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i},!0)}};var aa=class extends y{},Sg=class extends aa{},Og=class extends aa{};var ia=class extends y{},Ig=class extends ia{},Cg=class extends ia{};var la=class extends y{},Pg=class extends la{},zg=class extends la{};var tu=class extends y{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},ca=class extends tu{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,input_features:n=null,input_features_mask:o=null,position_ids:a=null,inputs_embeds:i=null,per_layer_inputs:l=null,past_key_values:u=null,generation_config:p=null,logits_processor:f=null,...m}){if((!i||!l)&&({inputs_embeds:i,per_layer_inputs:l}=await ue(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(s){let{image_features:w}=await ue(this.sessions.vision_encoder,{pixel_values:s});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_image_features({image_features:w,inputs_embeds:i,input_ids:e,attention_mask:r}))}if(n){let{audio_features:w}=await ue(this.sessions.audio_encoder,{input_features:n,input_features_mask:o});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_audio_features({audio_features:w,inputs_embeds:i,input_ids:e,attention_mask:r}))}}return await Ct(this,{inputs_embeds:i,per_layer_inputs:l,past_key_values:u,attention_mask:r,position_ids:a,generation_config:p,logits_processor:f},!0)}_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return fr({image_token_id:this.config.image_token_id,...e,image_features:s})}_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return jc({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}};var ua=class extends y{},Lg=class extends ua{},Ng=class extends ua{};var pa=class extends y{},$g=class extends pa{},Rg=class extends pa{};var da=class extends y{},Dg=class extends da{},Ug=class extends da{};var fa=class extends y{},Bg=class extends fa{},Fg=class extends fa{};var ma=class extends y{},jg=class extends ma{},Gg=class extends ma{};var ha=class extends y{},qg=class extends ha{},Wg=class extends ha{};var _a=class extends y{},Vg=class extends _a{},Hg=class extends _a{};var ga=class extends y{},Xg=class extends ga{},Kg=class extends ga{};var wa=class extends y{},Yg=class extends wa{},Qg=class extends wa{};var xa=class extends y{},Jg=class extends xa{},Zg=class extends xa{};var ru=class extends y{},ew=class extends ru{};var su=class extends y{},tw=class extends su{};var ya=class extends y{},rw=class extends ya{},sw=class extends ya{};var ba=class extends y{},nw=class extends ba{},ow=class extends ba{async _call(e){return new G(await super._call(e))}};var tr=class extends y{},aw=class extends tr{},iw=class extends tr{async _call(e){return new xt(await super._call(e))}},lw=class extends tr{async _call(e){return new G(await super._call(e))}},cw=class extends tr{async _call(e){return new he(await super._call(e))}};var uw=class extends y{},pw=class extends tr{},dw=class extends tr{async _call(e){return new xt(await super._call(e))}},fw=class extends tr{async _call(e){return new G(await super._call(e))}};var va=class extends y{},mw=class extends va{},hw=class extends va{};var nu=class extends y{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},ou=class extends nu{async encode_image({pixel_values:e,pixel_attention_mask:r}){return(await ue(this.sessions.vision_encoder,{pixel_values:e,pixel_attention_mask:r})).image_features}_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return fr({image_token_id:this.config.image_token_id,...e,image_features:s})}},_w=class extends ou{};var ka=class extends y{},gw=class extends ka{},ww=class extends ka{async _call(e){return new G(await super._call(e))}};var Ea=class extends y{},xw=class extends Ea{},yw=class extends Ea{};var kn=class extends y{},bw=class extends kn{async forward(e){let r=!e.input_ids,s=!e.pixel_values;if(r&&s)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(r&&(e.input_ids=at([e.pixel_values.dims[0],1])),s){let{image_size:u}=this.config.vision_config;e.pixel_values=He([0,3,u,u],0)}let{text_embeddings:n,image_embeddings:o,l2norm_text_embeddings:a,l2norm_image_embeddings:i}=await super.forward(e),l={};return r||(l.text_embeddings=n,l.l2norm_text_embeddings=a),s||(l.image_embeddings=o,l.l2norm_image_embeddings=i),l}},Aa=class extends kn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},vw=class extends kn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Ma=class extends y{},kw=class extends Ma{},Ew=class extends Ma{};var Ta=class extends y{},Aw=class extends Ta{},Mw=class extends Ta{};var Sa=class extends y{},Tw=class extends Sa{},Sw=class extends Sa{};var au=class extends y{},Ow=class extends au{};var iu=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},En=class extends iu{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return fr({image_token_id:this.config.image_token_index,...e,image_features:s})}},Iw=class extends En{},Cw=class extends En{};var Oa=class extends y{},Pw=class extends Oa{},zw=class extends Oa{};var Ia=class extends y{},Lw=class extends Ia{},Nw=class extends Ia{};var Ca=class extends y{},$w=class extends Ca{},Rw=class extends Ca{};var Pa=class extends y{},Dw=class extends Pa{},Uw=class extends Pa{};var Ns=class extends y{},Bw=class extends Ns{},Fw=class extends Ns{},jw=class extends Ns{async _call(e){return new G(await super._call(e))}},Gw=class extends Ns{};var lu=class extends y{},qw=class extends lu{};var cu=class extends y{},Ww=class extends cu{};var uu=class extends Ne{constructor({char_logits:e,bpe_logits:r,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=r,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},pu=class extends y{},Vw=class extends pu{async _call(e){return new uu(await super._call(e))}};var du=class extends Ne{constructor({audio_codes:e}){super(),this.audio_codes=e}},fu=class extends Ne{constructor({audio_values:e}){super(),this.audio_values=e}},An=class extends y{main_input_name="input_values";forward_params=["input_values"]},Hw=class extends An{async encode(e){return new du(await ue(this.sessions.encoder_model,e))}async decode(e){return new fu(await ue(this.sessions.decoder_model,e))}},za=class extends An{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},La=class extends An{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Na=class extends y{},Xw=class extends Na{},Kw=class extends Na{};var $s=class extends y{},Yw=class extends $s{},Qw=class extends $s{async _call(e){return new we(await super._call(e))}},Jw=class extends $s{async _call(e){return new G(await super._call(e))}},Zw=class extends $s{async _call(e){return new Ae(await super._call(e))}};var $a=class extends y{},ex=class extends $a{},tx=class extends $a{};var Mn=class extends y{},rx=class extends Mn{},sx=class extends Mn{async _call(e){return new G(await super._call(e))}},nx=class extends Mn{};var Tn=class extends y{},ox=class extends Tn{},ax=class extends Tn{async _call(e){return new G(await super._call(e))}},ix=class extends Tn{};var Sn=class extends y{},lx=class extends Sn{},cx=class extends Sn{async _call(e){return new G(await super._call(e))}},ux=class extends Sn{};var On=class extends y{},px=class extends On{},dx=class extends On{async _call(e){return new G(await super._call(e))}},fx=class extends On{};var Ra=class extends y{},mx=class extends Ra{},hx=class extends Ra{async _call(e){return new G(await super._call(e))}};var Da=class extends y{},_x=class extends Da{},gx=class extends Da{async _call(e){return new G(await super._call(e))}};var Rs=class extends y{},wx=class extends Rs{},xx=class extends Rs{async _call(e){return new we(await super._call(e))}},yx=class extends Rs{async _call(e){return new G(await super._call(e))}},bx=class extends Rs{async _call(e){return new he(await super._call(e))}};var Ua=class extends y{},vx=class extends Ua{},kx=class extends Ua{};var Ba=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},Ex=class extends Ba{},Ax=class extends Ba{};var Qr=class extends y{},Mx=class extends Qr{},Tx=class extends Qr{async _call(e){return new we(await super._call(e))}},Sx=class extends Qr{async _call(e){return new G(await super._call(e))}},Ox=class extends Qr{async _call(e){return new he(await super._call(e))}},Ix=class extends Qr{async _call(e){return new Ae(await super._call(e))}};var Fa=class extends y{},Cx=class extends Fa{},Px=class extends Fa{};var ja=class extends y{},zx=class extends ja{},Lx=class extends ja{};var mu=class extends y{},Nx=class extends mu{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){let r=this._generation_mode??"text",s;if(r==="text"||!e.past_key_values){let l=this.sessions.prepare_inputs_embeds,u=nt(e,l.inputNames);s=await ue(l,u)}else{let l=this.sessions.gen_img_embeds,u=nt({image_ids:e.input_ids},l.inputNames);s=await ue(l,u)}let n={...e,...s},o=await Ct(this,n),a=this.sessions[r==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);let i=await ue(a,nt(o,a.inputNames));return{...s,...o,...i}}prepare_inputs_for_generation(e,r,s){let n=!!r.past_key_values;return s.guidance_scale!==null&&s.guidance_scale>1&&(n?r.input_ids=Ee([r.input_ids,r.input_ids],0):(r.input_ids=Ee([r.input_ids,uo(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=Ee([r.attention_mask,uo(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=He([0,0,3,384,384],1)),n&&(r.images_seq_mask=new D("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new D("bool",new Array(0).fill(!1),[1,1,0])),r}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";let r=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[r,null]),o=this.sessions.image_decode,{decoded_image:a}=await ue(o,{generated_tokens:n}),i=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let u of i){let p=Ke.fromTensor(u);l.push(p)}return l}};var Ga=class extends y{},$x=class extends Ga{},Rx=class extends Ga{},qa=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){let[r,s]=e.dims,n=this.config.decoder.num_codebooks,o=s-n,a=0;for(let u=0;u<e.size;++u){if(e.data[u]==this.config.decoder.pad_token_id)continue;let p=u%s,f=Math.floor(u/s)%n,m=p-f;m>0&&m<=o&&(e.data[a++]=e.data[u])}let i=Math.floor(r/n),l=a/(i*n);return new D(e.type,e.data.slice(0,a),[i,n,l])}prepare_inputs_for_generation(e,r,s){let n=BigInt(this.config.decoder.pad_token_id),o=structuredClone(e);for(let a=0;a<o.length;++a)for(let i=0;i<o[a].length;++i)a%this.config.decoder.num_codebooks>=i&&(o[a][i]=n);return s.guidance_scale!==null&&s.guidance_scale>1&&(o=o.concat(o)),To(this,o,r,s)}async generate(e){let r=await super.generate(e),s=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:n}=await ue(this.sessions.encodec_decode,{audio_codes:s});return n}};var Wa=class extends y{},Dx=class extends Wa{},Ux=class extends Wa{};var Jr=class extends y{},Bx=class extends Jr{},Fx=class extends Jr{async _call(e){return new we(await super._call(e))}},jx=class extends Jr{async _call(e){return new G(await super._call(e))}},Gx=class extends Jr{async _call(e){return new he(await super._call(e))}},qx=class extends Jr{async _call(e){return new Ae(await super._call(e))}};var hu=class extends y{},Wx=class extends hu{};var Va=class extends y{},Vx=class extends Va{},Hx=class extends Va{};var Ha=class extends y{},Xx=class extends Ha{},Kx=class extends Ha{};var Xa=class extends y{},Yx=class extends Xa{},Qx=class extends Xa{};var Ka=class extends y{},Jx=class extends Ka{},Zx=class extends Ka{};var Ya=class extends y{},ey=class extends Ya{},ty=class extends Ya{};var Qa=class extends y{},ry=class extends Qa{},sy=class extends Qa{};var Ja=class extends y{},ny=class extends Ja{},oy=class extends Ja{};var _u=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},ay=class extends _u{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return fr({image_token_id:this.config.image_token_index,...e,image_features:s})}};var gu=class extends y{},iy=class extends gu{async _call(e){return new xt(await super._call(e))}};var Za=class extends y{},ly=class extends Za{},cy=class extends Za{};var ei=class extends y{},uy=class extends ei{},py=class extends ei{};var ti=class extends y{},dy=class extends ti{},fy=class extends ti{};var ri=class extends y{},my=class extends ri{},hy=class extends ri{};var wu=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},si=class extends wu{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,image_sizes:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:u=null,...p}){if(!a){let m;if(s&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:m}=await ue(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else{let h=this.config.normalized_config.hidden_size;m=new D("float32",[],[0,h])}({inputs_embeds:a}=await ue(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:m}))}return await Ct(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:u},!1)}};var ni=class extends y{},_y=class extends ni{},gy=class extends ni{async _call(e){return new G(await super._call(e))}};var oi=class extends y{},wy=class extends oi{},xy=class extends oi{async _call(e){return new he(await super._call(e))}};var ai=class extends y{},yy=class extends ai{},by=class extends ai{};var xu=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},ii=class extends xu{image_grid_thw_name="grid_thw";get_rope_index(e,r,s,n){let{vision_config:o,image_token_id:a,video_token_id:i,vision_start_token_id:l}=this.config,u=o.spatial_merge_size??2,p=[];if(r||s){let f=e.tolist();n||(n=Jl(e));let m=n.tolist(),h=Array.from({length:3},A=>Array.from({length:e.dims[0]},S=>Array.from({length:e.dims[1]},T=>1))),w=r?r.tolist():[],x=s?s.tolist():[],k=0,E=0;for(let A=0;A<f.length;++A){let S=f[A].filter((I,L)=>m[A][L]==1),P=S.reduce((I,L,R)=>(L==l&&I.push(R),I),[]).map(I=>S[I+1]),C=P.filter(I=>I==a).length,v=P.filter(I=>I==i).length,F=[],H=0,V=C,J=v;for(let I=0;I<P.length;++I){let L=S.findIndex((Tt,tt)=>tt>H&&Tt==a),R=S.findIndex((Tt,tt)=>tt>H&&Tt==i),te=V>0&&L!==-1?L:S.length+1,pe=J>0&&R!==-1?R:S.length+1,Fe,Pe,At,Je;te<pe?([Pe,At,Je]=w[k],++k,--V,Fe=te):([Pe,At,Je]=x[E],++E,--J,Fe=pe);let[et,st,Me]=[Number(Pe),Math.floor(Number(At)/u),Math.floor(Number(Je)/u)],xe=Fe-H,qe=F.length>0?Se(F.at(-1))[0]+1:0;F.push(Array.from({length:3*xe},(Tt,tt)=>qe+tt%xe));let Mt=xe+qe,be=et*st*Me,$e=Array.from({length:be},(Tt,tt)=>Mt+Math.floor(tt/(st*Me))),Ir=Array.from({length:be},(Tt,tt)=>Mt+Math.floor(tt/Me)%st),is=Array.from({length:be},(Tt,tt)=>Mt+tt%Me);F.push([$e,Ir,is].flat()),H=Fe+be}if(H<S.length){let I=F.length>0?Se(F.at(-1))[0]+1:0,L=S.length-H;F.push(Array.from({length:3*L},(R,te)=>I+te%L))}let X=F.reduce((I,L)=>I+L.length,0),Y=new Array(X),U=0;for(let I=0;I<3;++I)for(let L=0;L<F.length;++L){let R=F[L],te=R.length/3;for(let pe=I*te;pe<(I+1)*te;++pe)Y[U++]=R[pe]}let z=0,ne=m[A];for(let I=0;I<ne.length;++I)if(ne[I]==1){for(let L=0;L<3;++L)h[L][A][I]=Y[L*X/3+z];++z}let ae=Se(Y)[0];p.push(ae+1-f[A].length)}return[new D("int64",h.flat(1/0),[3,e.dims[0],e.dims[1]]),new D("int64",p,[p.length,1])]}else if(n){let{data:f,dims:m}=yh(n),h=BigInt64Array.from({length:3*f.length},(x,k)=>f[k%f.length]),w=Array.from({length:m[0]},(x,k)=>Se(f.subarray(m[1]*k,m[1]*(k+1)))[0]+1n+BigInt(m[1]));return[new D("int64",h,[3,...m]),new D("int64",w,[w.length,1])]}else{let[f,m]=e.dims,h=BigInt64Array.from({length:3*f*m},(w,x)=>BigInt(Math.floor(x%m/f)));return[new D("int64",h,[3,...e.dims]),Wd([f,1])]}}async encode_image({pixel_values:e,image_grid_thw:r}){return(await ue(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(e){return fr({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,r,s){if(r.attention_mask&&!r.position_ids)if(!r.past_key_values)[r.position_ids,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);else{r.pixel_values=null;let n=BigInt(Object.values(r.past_key_values)[0].dims.at(-2)),o=r.rope_deltas.map(a=>n+a);r.position_ids=Gt([o,o,o],0)}return r}};var li=class extends ii{image_grid_thw_name="image_grid_thw"};var ci=class extends y{},vy=class extends ci{},ky=class extends ci{};var ui=class extends li{};var pi=class extends ui{};var Ey=class extends pi{};var di=class extends y{},Ay=class extends di{},My=class extends di{async _call(e){return new G(await super._call(e))}};var fi=class extends y{},Ty=class extends fi{},Sy=class extends fi{async _call(e){return new yu(await super._call(e))}},yu=class extends hr{};var Zr=class extends y{},Oy=class extends Zr{},Iy=class extends Zr{async _call(e){return new we(await super._call(e))}},Cy=class extends Zr{async _call(e){return new G(await super._call(e))}},Py=class extends Zr{async _call(e){return new he(await super._call(e))}},zy=class extends Zr{async _call(e){return new Ae(await super._call(e))}};var es=class extends y{},Ly=class extends es{},Ny=class extends es{async _call(e){return new we(await super._call(e))}},$y=class extends es{async _call(e){return new G(await super._call(e))}},Ry=class extends es{async _call(e){return new he(await super._call(e))}},Dy=class extends es{async _call(e){return new Ae(await super._call(e))}};var mi=class extends y{},Uy=class extends mi{},By=class extends mi{async _call(e){return new bu(await super._call(e))}},bu=class extends hr{};var vu=class extends Ne{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},ku=class extends y{},Fy=class extends ku{async get_image_embeddings({pixel_values:e}){return await Wt(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??=at(e.input_points.dims.slice(0,-1));let r={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(r.input_points=e.input_points),e.input_labels&&(r.input_labels=e.input_labels),e.input_boxes&&(r.input_boxes=e.input_boxes),await ue(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new vu(await super._call(e))}};var Eu=class extends Ne{constructor({iou_scores:e,pred_masks:r,object_score_logits:s}){super(),this.iou_scores=e,this.pred_masks=r,this.object_score_logits=s}},Au=class extends y{},hi=class extends Au{async get_image_embeddings({pixel_values:e}){return await Wt(this,{pixel_values:e})}async forward(e){let{num_feature_levels:r}=this.config.vision_config;if(Array.from({length:r},(a,i)=>`image_embeddings.${i}`).some(a=>!e[a])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let a=e.input_points.dims;e.input_labels??=at(a.slice(0,-1)),e.input_boxes??=He([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=He([a[0],a[1],0],-1n),e.input_points=He([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder,o=nt(e,n.inputNames);return await ue(n,o)}async _call(e){return new Eu(await super._call(e))}},jy=class extends hi{},Gy=class extends hi{};var In=class extends y{},qy=class extends In{},Wy=class extends In{},Vy=class extends In{};var Cn=class extends y{},Hy=class extends Cn{},Xy=class extends Cn{},Ky=class extends Cn{};var _i=class extends y{},Yy=class extends _i{},gi=class extends _i{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Qy=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var wi=class extends y{},Jy=class extends wi{},Zy=class extends wi{};var Pn=class extends y{main_input_name="input_values";forward_params=["input_values"]},e0=class extends Pn{async encode(e){return await ue(this.sessions.encoder_model,e)}async decode(e){return await ue(this.sessions.decoder_model,e)}},xi=class extends Pn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},yi=class extends Pn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var zn=class extends y{},t0=class extends zn{},r0=class extends zn{},s0=class extends zn{async generate_speech(e,r,{threshold:s=.5,minlenratio:n=0,maxlenratio:o=20,vocoder:a=null}={}){let i={input_ids:e},{encoder_outputs:l,encoder_attention_mask:u}=await Wt(this,i),p=l.dims[1]/this.config.reduction_factor,f=Math.floor(p*o),m=Math.floor(p*n),h=this.config.num_mel_bins,w=[],x=null,k=null,E=0;for(;;){++E;let T=xh(!!k),P;k?P=k.output_sequence_out:P=new D("float32",new Float32Array(h),[1,1,h]);let C={use_cache_branch:T,output_sequence:P,encoder_attention_mask:u,speaker_embeddings:r,encoder_hidden_states:l};this.addPastKeyValues(C,x),k=await ue(this.sessions.decoder_model_merged,C),x=this.getPastKeyValues(k,x);let{prob:v,spectrum:F}=k;if(w.push(F),E>=m&&(Array.from(v.data).filter(H=>H>=s).length>0||E>=f))break}let A=Ee(w),{waveform:S}=await ue(a.sessions.model,{spectrogram:A});return{spectrogram:A,waveform:S}}},n0=class extends y{main_input_name="spectrogram"};var Ds=class extends y{},o0=class extends Ds{},a0=class extends Ds{async _call(e){return new we(await super._call(e))}},i0=class extends Ds{async _call(e){return new G(await super._call(e))}},l0=class extends Ds{async _call(e){return new Ae(await super._call(e))}};var bi=class extends y{},c0=class extends bi{},u0=class extends bi{};var vi=class extends y{},p0=class extends vi{},d0=class extends vi{};var Mu=class extends y{},f0=class extends Mu{};var Tu=class extends y{},ki=class extends Tu{async generate_speech({input_ids:e,attention_mask:r,style:s,num_inference_steps:n=5,speed:o=1.05}){let{sampling_rate:a,chunk_compress_factor:i,base_chunk_size:l,latent_dim:u}=this.config,{last_hidden_state:p,durations:f}=await ue(this.sessions.text_encoder,{input_ids:e,attention_mask:r,style:s}),m=f.div(o).mul_(a),h=l*i,w=m.data,x=Int32Array.from(w,V=>Math.ceil(V/h)),k=Math.max(...x),E=e.dims[0],A=new BigInt64Array(E*k);for(let V=0;V<E;++V)A.fill(1n,V*k,V*k+x[V]);let S=new D("int64",A,[E,k]),T=u*i,P=T*k,C=dA([E,T,k]),v=C.data;for(let V=0;V<E;++V)if(x[V]!==k)for(let J=0;J<T;++J)v.fill(0,V*P+J*k+x[V],V*P+(J+1)*k);let F=He([E],n);for(let V=0;V<n;++V){let J=He([E],V);({denoised_latents:C}=await ue(this.sessions.latent_denoiser,{style:s,noisy_latents:C,latent_mask:S,encoder_outputs:p,attention_mask:r,timestep:J,num_inference_steps:F}))}let{waveform:H}=await ue(this.sessions.voice_decoder,{latents:C});return{waveform:H,durations:m}}};var Ln=class extends y{},m0=class extends Ln{},h0=class extends Ln{async _call(e){return new G(await super._call(e))}},_0=class extends Ln{};var Ei=class extends y{},g0=class extends Ei{},w0=class extends Ei{};var Ai=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},x0=class extends Ai{},y0=class extends Ai{};var Mi=class extends y{},b0=class extends Mi{},v0=class extends Mi{async _call(e){return new Su(await super._call(e))}},Su=class extends vn{};var Ou=class extends y{},k0=class extends Ou{};var Iu=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},Cu=class extends Iu{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return jc({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...e,audio_features:s})}},E0=class extends Cu{};var Nn=class extends y{},A0=class extends Nn{},M0=class extends Nn{async _call(e){return new xt(await super._call(e))}},T0=class extends Nn{async _call(e){return new G(await super._call(e))}};var Us=class extends y{},S0=class extends Us{},O0=class extends Us{async _call(e){return new xt(await super._call(e))}},I0=class extends Us{async _call(e){return new G(await super._call(e))}},C0=class extends Us{async _call(e){return new he(await super._call(e))}};var Ti=class extends y{},P0=class extends Ti{},z0=class extends Ti{};var L0=class extends y{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]};var Si=class extends y{},N0=class extends Si{},$0=class extends Si{async _call(e){return new G(await super._call(e))}};var Pu=class extends y{},R0=class extends Pu{};var Oi=class extends y{},D0=class extends Oi{},U0=class extends Oi{async _call(e){return new G(await super._call(e))}};var zu=class extends y{},B0=class extends zu{async _call(e){return new Ac(await super._call(e))}};var Lu=class extends y{},F0=class extends Lu{};var Nu=class extends Ne{constructor({waveform:e,spectrogram:r}){super(),this.waveform=e,this.spectrogram=r}},$u=class extends y{},j0=class extends $u{async _call(e){return new Nu(await super._call(e))}};var $n=class extends y{},G0=class extends $n{},q0=class extends $n{async _call(e){return new xt(await super._call(e))}},W0=class extends $n{async _call(e){return new G(await super._call(e))}};var Ru=class extends Ne{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},ts=class extends y{},V0=class extends ts{},H0=class extends ts{async _call(e){return new xt(await super._call(e))}},X0=class extends ts{async _call(e){return new G(await super._call(e))}},K0=class extends ts{async _call(e){return new Ru(await super._call(e))}},Y0=class extends ts{async _call(e){return new he(await super._call(e))}};var Du=class extends y{},Q0=class extends Du{};var Uu=class extends _n{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1};var Ii=class extends y{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},J0=class extends Ii{},Bu=class extends Ii{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,Uu)}_retrieve_init_tokens(e){let r=[e.decoder_start_token_id],s=e.language,n=e.task;if(e.is_multilingual){s||(Q.warn("No language specified - defaulting to English (en)."),s="en");let a=`<|${hA(s)}|>`;r.push(e.lang_to_id[a]),r.push(e.task_to_id[n??"transcribe"])}else if(s||n)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&r.at(-1)!==e.no_timestamps_token_id?r.push(e.no_timestamps_token_id):e.return_timestamps&&r.at(-1)===e.no_timestamps_token_id&&(Q.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),r.pop()),r.filter(o=>o!=null)}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,...o}){r=this._prepare_generation_config(r,o);let a=o.decoder_input_ids??this._retrieve_init_tokens(r);if(r.return_timestamps&&(s??=new Is,s.push(new Sc(r,a))),r.begin_suppress_tokens&&(s??=new Is,s.push(new hn(r.begin_suppress_tokens,a.length))),r.return_token_timestamps){if(!r.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.");r.task==="translate"&&Q.warn("Token-level timestamps may not be reliable for task 'translate'."),r.output_attentions=!0,r.return_dict_in_generate=!0}let i=await super.generate({inputs:e,generation_config:r,logits_processor:s,decoder_input_ids:a,...o});return r.return_token_timestamps&&(i.token_timestamps=this._extract_token_timestamps(i,r.alignment_heads,r.num_frames)),i}_extract_token_timestamps(e,r,s=null,n=.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`.");s==null&&Q.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let o=this.config.median_filter_width;o===void 0&&(Q.warn("Model config has no `median_filter_width`, using default value of 7."),o=7);let a=e.cross_attentions,i=Array.from({length:this.config.decoder_layers},(x,k)=>Ee(a.map(E=>E[k]),2)),l=Gt(r.map(([x,k])=>{if(x>=i.length)throw new Error(`Layer index ${x} is out of bounds for cross attentions (length ${i.length}).`);return s?i[x].slice(null,k,null,[0,s]):i[x].slice(null,k)})).transpose(1,0,2,3),[u,p]=Gd(l,-2,0,!0),f=l.clone();for(let x=0;x<f.dims[0];++x){let k=f[x];for(let E=0;E<k.dims[0];++E){let A=k[E],S=u[x][E][0].data,T=p[x][E][0].data;for(let P=0;P<A.dims[0];++P){let C=A[P].data;for(let v=0;v<C.length;++v)C[v]=(C[v]-T[v])/S[v];C.set(bk(C,o))}}}let m=[Ql(f,1)],h=e.sequences.dims,w=new D("float32",new Float32Array(h[0]*h[1]),h);for(let x=0;x<h[0];++x){let k=m[x].neg().squeeze_(0),[E,A]=kk(k.tolist()),S=Array.from({length:E.length-1},(C,v)=>E[v+1]-E[v]),T=ft([1],S).map(C=>!!C),P=[];for(let C=0;C<T.length;++C)T[C]&&P.push(A[C]*n);w[x].data.set(P,1)}return w}},Z0=class extends Bu{};var rs=class extends y{},eb=class extends rs{},tb=class extends rs{async _call(e){return new we(await super._call(e))}},rb=class extends rs{async _call(e){return new G(await super._call(e))}},sb=class extends rs{async _call(e){return new he(await super._call(e))}},nb=class extends rs{async _call(e){return new Ae(await super._call(e))}};var ss=class extends y{},ob=class extends ss{},ab=class extends ss{async _call(e){return new we(await super._call(e))}},ib=class extends ss{async _call(e){return new G(await super._call(e))}},lb=class extends ss{async _call(e){return new he(await super._call(e))}},cb=class extends ss{async _call(e){return new Ae(await super._call(e))}};var Ci=class extends y{},ub=class extends Ci{},pb=class extends Ci{async _call(e){return new Fu(await super._call(e))}},Fu=class extends Ne{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var Pi=class extends y{},db=class extends Pi{},fb=class extends Pi{};var Az=new Map([["bert","BertModel"],["neobert","NeoBertModel"],["modernbert","ModernBertModel"],["nomic_bert","NomicBertModel"],["roformer","RoFormerModel"],["electra","ElectraModel"],["esm","EsmModel"],["convbert","ConvBertModel"],["camembert","CamembertModel"],["deberta","DebertaModel"],["deberta-v2","DebertaV2Model"],["mpnet","MPNetModel"],["albert","AlbertModel"],["distilbert","DistilBertModel"],["roberta","RobertaModel"],["xlm","XLMModel"],["xlm-roberta","XLMRobertaModel"],["clap","ClapModel"],["clip","CLIPModel"],["clipseg","CLIPSegModel"],["chinese_clip","ChineseCLIPModel"],["siglip","SiglipModel"],["jina_clip","JinaCLIPModel"],["mobilebert","MobileBertModel"],["squeezebert","SqueezeBertModel"],["wav2vec2","Wav2Vec2Model"],["wav2vec2-bert","Wav2Vec2BertModel"],["unispeech","UniSpeechModel"],["unispeech-sat","UniSpeechSatModel"],["hubert","HubertModel"],["wavlm","WavLMModel"],["audio-spectrogram-transformer","ASTModel"],["vits","VitsModel"],["pyannote","PyAnnoteModel"],["wespeaker-resnet","WeSpeakerResNetModel"],["detr","DetrModel"],["rt_detr","RTDetrModel"],["rt_detr_v2","RTDetrV2Model"],["rf_detr","RFDetrModel"],["d_fine","DFineModel"],["table-transformer","TableTransformerModel"],["vit","ViTModel"],["ijepa","IJepaModel"],["pvt","PvtModel"],["vit_msn","ViTMSNModel"],["vit_mae","ViTMAEModel"],["groupvit","GroupViTModel"],["fastvit","FastViTModel"],["mobilevit","MobileViTModel"],["mobilevitv2","MobileViTV2Model"],["owlvit","OwlViTModel"],["owlv2","Owlv2Model"],["beit","BeitModel"],["deit","DeiTModel"],["hiera","HieraModel"],["convnext","ConvNextModel"],["convnextv2","ConvNextV2Model"],["dinov2","Dinov2Model"],["dinov2_with_registers","Dinov2WithRegistersModel"],["dinov3_vit","DINOv3ViTModel"],["dinov3_convnext","DINOv3ConvNextModel"],["resnet","ResNetModel"],["swin","SwinModel"],["swin2sr","Swin2SRModel"],["donut-swin","DonutSwinModel"],["yolos","YolosModel"],["dpt","DPTModel"],["glpn","GLPNModel"],["hifigan","SpeechT5HifiGan"],["efficientnet","EfficientNetModel"],["decision_transformer","DecisionTransformerModel"],["patchtst","PatchTSTModel"],["patchtsmixer","PatchTSMixerModel"],["mobilenet_v1","MobileNetV1Model"],["mobilenet_v2","MobileNetV2Model"],["mobilenet_v3","MobileNetV3Model"],["mobilenet_v4","MobileNetV4Model"],["maskformer","MaskFormerModel"],["mgp-str","MgpstrForSceneTextRecognition"],["style_text_to_speech_2","StyleTextToSpeech2Model"]]),Mz=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),Tz=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),Sz=new Map([["bloom","BloomModel"],["jais","JAISModel"],["gpt2","GPT2Model"],["gpt_oss","GptOssModel"],["gptj","GPTJModel"],["gpt_bigcode","GPTBigCodeModel"],["gpt_neo","GPTNeoModel"],["gpt_neox","GPTNeoXModel"],["codegen","CodeGenModel"],["llama","LlamaModel"],["apertus","ApertusModel"],["nanochat","NanoChatModel"],["arcee","ArceeModel"],["afmoe","AfmoeModel"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen3","Qwen3Model"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5_Model"],["starcoder2","Starcoder2Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"]]),DA=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"]]),UA=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),BA=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),FA=new Map([["bert","BertForSequenceClassification"],["neobert","NeoBertForSequenceClassification"],["modernbert","ModernBertForSequenceClassification"],["roformer","RoFormerForSequenceClassification"],["electra","ElectraForSequenceClassification"],["esm","EsmForSequenceClassification"],["convbert","ConvBertForSequenceClassification"],["camembert","CamembertForSequenceClassification"],["deberta","DebertaForSequenceClassification"],["deberta-v2","DebertaV2ForSequenceClassification"],["mpnet","MPNetForSequenceClassification"],["albert","AlbertForSequenceClassification"],["distilbert","DistilBertForSequenceClassification"],["roberta","RobertaForSequenceClassification"],["xlm","XLMForSequenceClassification"],["xlm-roberta","XLMRobertaForSequenceClassification"],["bart","BartForSequenceClassification"],["mbart","MBartForSequenceClassification"],["mobilebert","MobileBertForSequenceClassification"],["squeezebert","SqueezeBertForSequenceClassification"]]),jA=new Map([["bert","BertForTokenClassification"],["neobert","NeoBertForTokenClassification"],["modernbert","ModernBertForTokenClassification"],["roformer","RoFormerForTokenClassification"],["electra","ElectraForTokenClassification"],["esm","EsmForTokenClassification"],["convbert","ConvBertForTokenClassification"],["camembert","CamembertForTokenClassification"],["deberta","DebertaForTokenClassification"],["deberta-v2","DebertaV2ForTokenClassification"],["mpnet","MPNetForTokenClassification"],["distilbert","DistilBertForTokenClassification"],["roberta","RobertaForTokenClassification"],["xlm","XLMForTokenClassification"],["xlm-roberta","XLMRobertaForTokenClassification"]]),GA=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),qA=new Map([["bloom","BloomForCausalLM"],["gpt2","GPT2LMHeadModel"],["gpt_oss","GptOssForCausalLM"],["jais","JAISLMHeadModel"],["gptj","GPTJForCausalLM"],["gpt_bigcode","GPTBigCodeForCausalLM"],["gpt_neo","GPTNeoForCausalLM"],["gpt_neox","GPTNeoXForCausalLM"],["codegen","CodeGenForCausalLM"],["llama","LlamaForCausalLM"],["nanochat","NanoChatForCausalLM"],["apertus","ApertusForCausalLM"],["llama4_text","Llama4ForCausalLM"],["arcee","ArceeForCausalLM"],["afmoe","AfmoeForCausalLM"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen3","Qwen3ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5_ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["trocr","TrOCRForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),Oz=new Map([["multi_modality","MultiModalityCausalLM"]]),WA=new Map([["bert","BertForMaskedLM"],["neobert","NeoBertForMaskedLM"],["modernbert","ModernBertForMaskedLM"],["roformer","RoFormerForMaskedLM"],["electra","ElectraForMaskedLM"],["esm","EsmForMaskedLM"],["convbert","ConvBertForMaskedLM"],["camembert","CamembertForMaskedLM"],["deberta","DebertaForMaskedLM"],["deberta-v2","DebertaV2ForMaskedLM"],["mpnet","MPNetForMaskedLM"],["albert","AlbertForMaskedLM"],["distilbert","DistilBertForMaskedLM"],["roberta","RobertaForMaskedLM"],["xlm","XLMWithLMHeadModel"],["xlm-roberta","XLMRobertaForMaskedLM"],["mobilebert","MobileBertForMaskedLM"],["squeezebert","SqueezeBertForMaskedLM"]]),VA=new Map([["bert","BertForQuestionAnswering"],["neobert","NeoBertForQuestionAnswering"],["roformer","RoFormerForQuestionAnswering"],["electra","ElectraForQuestionAnswering"],["convbert","ConvBertForQuestionAnswering"],["camembert","CamembertForQuestionAnswering"],["deberta","DebertaForQuestionAnswering"],["deberta-v2","DebertaV2ForQuestionAnswering"],["mpnet","MPNetForQuestionAnswering"],["albert","AlbertForQuestionAnswering"],["distilbert","DistilBertForQuestionAnswering"],["roberta","RobertaForQuestionAnswering"],["xlm","XLMForQuestionAnswering"],["xlm-roberta","XLMRobertaForQuestionAnswering"],["mobilebert","MobileBertForQuestionAnswering"],["squeezebert","SqueezeBertForQuestionAnswering"]]),HA=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),XA=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2_vl","Qwen2VLForConditionalGeneration"],["qwen2_5_vl","Qwen2_5_VLForConditionalGeneration"],["qwen3_vl","Qwen3VLForConditionalGeneration"],["qwen3_5","Qwen3_5ForConditionalGeneration"],["qwen3_5_moe","Qwen3_5MoeForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3n","Gemma3nForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"]]),KA=new Map([["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"]]),Iz=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),YA=new Map([["vit","ViTForImageClassification"],["ijepa","IJepaForImageClassification"],["pvt","PvtForImageClassification"],["vit_msn","ViTMSNForImageClassification"],["fastvit","FastViTForImageClassification"],["mobilevit","MobileViTForImageClassification"],["mobilevitv2","MobileViTV2ForImageClassification"],["beit","BeitForImageClassification"],["deit","DeiTForImageClassification"],["hiera","HieraForImageClassification"],["convnext","ConvNextForImageClassification"],["convnextv2","ConvNextV2ForImageClassification"],["dinov2","Dinov2ForImageClassification"],["dinov2_with_registers","Dinov2WithRegistersForImageClassification"],["resnet","ResNetForImageClassification"],["swin","SwinForImageClassification"],["segformer","SegformerForImageClassification"],["efficientnet","EfficientNetForImageClassification"],["mobilenet_v1","MobileNetV1ForImageClassification"],["mobilenet_v2","MobileNetV2ForImageClassification"],["mobilenet_v3","MobileNetV3ForImageClassification"],["mobilenet_v4","MobileNetV4ForImageClassification"]]),QA=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),JA=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),Rn=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),ZA=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),e2=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),t2=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),r2=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),s2=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),n2=new Map([["wavlm","WavLMForXVector"]]),o2=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),a2=new Map([["vitmatte","VitMatteForImageMatting"]]),Cz=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),i2=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),l2=new Map([["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),c2=new Map([["sapiens","SapiensForNormalEstimation"]]),u2=new Map([["vitpose","VitPoseForPoseEstimation"]]),p2=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),mb=[[Az,j.EncoderOnly],[Mz,j.EncoderDecoder],[Sz,j.DecoderOnlyWithoutHead],[Tz,j.AutoEncoder],[FA,j.EncoderOnly],[jA,j.EncoderOnly],[GA,j.Seq2Seq],[DA,j.Seq2Seq],[qA,j.DecoderOnly],[Oz,j.MultiModality],[WA,j.EncoderOnly],[VA,j.EncoderOnly],[HA,j.Vision2Seq],[XA,j.ImageTextToText],[KA,j.AudioTextToText],[YA,j.EncoderOnly],[Rn,j.EncoderOnly],[e2,j.EncoderOnly],[ZA,j.EncoderOnly],[a2,j.EncoderOnly],[Cz,j.EncoderOnly],[i2,j.EncoderOnly],[l2,j.EncoderOnly],[c2,j.EncoderOnly],[u2,j.EncoderOnly],[QA,j.EncoderOnly],[JA,j.EncoderOnly],[t2,j.MaskGeneration],[r2,j.EncoderOnly],[s2,j.EncoderOnly],[UA,j.Seq2Seq],[BA,j.EncoderOnly],[n2,j.EncoderOnly],[o2,j.EncoderOnly],[p2,j.EncoderOnly]];for(let[t,e]of mb)for(let r of t.values()){dr.set(r,e);let s=zi[r];Ps.set(s,r),Fc.set(r,s)}var Pz=[["MusicgenForConditionalGeneration",qa,j.Musicgen],["Phi3VForCausalLM",si,j.Phi3V],["CLIPTextModelWithProjection",Uo,j.EncoderOnly],["SiglipTextModel",gi,j.EncoderOnly],["JinaCLIPTextModel",Aa,j.EncoderOnly],["ClapTextModelWithProjection",Ro,j.EncoderOnly],["ClapAudioModelWithProjection",Do,j.EncoderOnly],["DacEncoderModel",Xo,j.EncoderOnly],["DacDecoderModel",Ko,j.EncoderOnly],["MimiEncoderModel",za,j.EncoderOnly],["MimiDecoderModel",La,j.EncoderOnly],["SnacEncoderModel",xi,j.EncoderOnly],["SnacDecoderModel",yi,j.EncoderOnly],["Gemma3nForConditionalGeneration",ca,j.ImageAudioTextToText],["SupertonicForConditionalGeneration",ki,j.Supertonic],["ChatterboxModel",$o,j.Chatterbox]];for(let[t,e,r]of Pz)dr.set(t,r),Ps.set(e,t),Fc.set(t,e);var hb=new Map([["modnet",Rn],["birefnet",Rn],["isnet",Rn],["ben",Rn]]);for(let[t,e]of hb.entries())e.set(t,"PreTrainedModel"),dr.set(t,j.EncoderOnly),Fc.set(t,y);dr.set("PreTrainedModel",j.EncoderOnly);Ps.set(y,"PreTrainedModel");var Ce={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:FA,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:jA,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:UA,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:BA,MODEL_FOR_MASKED_LM_MAPPING_NAMES:WA,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:VA,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:YA,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:Rn,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:ZA,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:e2,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:QA,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:JA,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:t2,MODEL_FOR_CTC_MAPPING_NAMES:r2,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:s2,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:n2,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:o2,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:Iz,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:a2,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:i2,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:l2,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:c2,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:u2,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:p2,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:XA,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:KA,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:GA,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:DA,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:qA,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:HA};LA(Ce);var Oe=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:u=null,dtype:p=null,use_external_data_format:f=null,session_options:m={}}={}){let h={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:u,dtype:p,use_external_data_format:f,session_options:m};if(h.config=await Mr.from_pretrained(e,h),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let w=h.config.model_type;for(let x of this.MODEL_CLASS_MAPPINGS){let k=x.get(w);if(!k){for(let E of x.values())if(E[0]===w){k=E;break}if(!k)continue}return await zi[k].from_pretrained(e,h)}if(this.BASE_IF_FAIL)return hb.has(w)||Q.warn(`Unknown model class "${w}", attempting to construct from base class.`),await y.from_pretrained(e,h);throw Error(`Unsupported model type: ${w}`)}},Sr=class extends Oe{static MODEL_CLASS_MAPPINGS=mb.map(e=>e[0]);static BASE_IF_FAIL=!0},Li=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},ju=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},Dn=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},Gu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},qu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},Wu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},Vu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},Hu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},Xu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},Ku=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},Yu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},Ni=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},$i=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},Ri=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},Qu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},Ju=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},d2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},Zu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_CTC_MAPPING_NAMES]},ep=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},f2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},m2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},tp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},h2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},rp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},sp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},_2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},g2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},np=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},w2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},x2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function Qe(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>Ke.read(e)))}async function ns(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?jf(r,e):r instanceof Float64Array?new Float32Array(r):r))}function Di(t,e){e&&(t=t.map(a=>a|0));let[r,s,n,o]=t;return{xmin:r,ymin:s,xmax:n,ymax:o}}var de=class extends Ze{constructor({task:e,model:r,tokenizer:s=null,processor:n=null}){super(),this.task=e,this.model=r,this.tokenizer=s,this.processor=n}async dispose(){await this.model.dispose()}};var Ui=class extends de{async _call(e,{top_k:r=1}={}){let s=this.tokenizer(e,{padding:!0,truncation:!0}),n=await this.model(s),{problem_type:o,id2label:a}=this.model.config,i=o==="multi_label_classification"?u=>u.sigmoid():u=>new D("float32",Le(u.data),u.dims),l=[];for(let u of n.logits){let p=i(u),f=await Zt(p,r),m=f[0].tolist(),w=f[1].tolist().map((x,k)=>({label:a?a[x]:`LABEL_${x}`,score:m[k]}));r===1?l.push(...w):l.push(w)}return Array.isArray(e)||r===1?l:l[0]}};var Bi=class extends de{async _call(e,{ignore_labels:r=["O"]}={}){let s=Array.isArray(e),n=this.tokenizer(s?e:[e],{padding:!0,truncation:!0}),a=(await this.model(n)).logits,i=this.model.config.id2label,l=[];for(let u=0;u<a.dims[0];++u){let p=n.input_ids[u],f=a[u],m=[];for(let h=0;h<f.dims[0];++h){let w=f[h],x=Se(w.data)[1],k=i?i[x]:`LABEL_${x}`;if(r.includes(k))continue;let E=this.tokenizer.decode([p[h].item()],{skip_special_tokens:!0});if(E==="")continue;let A=Le(w.data);m.push({entity:k,score:A[x],index:h,word:E})}l.push(m)}return s?l:l[0]}};var Fi=class extends de{async _call(e,r,{top_k:s=1}={}){let n=this.tokenizer(e,{text_pair:r,padding:!0,truncation:!0}),o=Array.isArray(e),{start_logits:a,end_logits:i}=await this.model(n),l=n.input_ids.tolist(),u=n.attention_mask.tolist(),{all_special_ids:p,sep_token_id:f}=this.tokenizer,m=[];for(let h=0;h<a.dims[0];++h){let w=l[h],x=w.findIndex(C=>C==f),k=a[h].tolist(),E=i[h].tolist();for(let C=1;C<k.length;++C)(u[h]==0||C<=x||p.findIndex(v=>v==w[C])!==-1)&&(k[C]=-1/0,E[C]=-1/0);let A=Le(k).map((C,v)=>[C,v]),S=Le(E).map((C,v)=>[C,v]);A[0][0]=0,S[0][0]=0;let T=Lv(A,S).filter(C=>C[0][1]<=C[1][1]).map(C=>[C[0][1],C[1][1],C[0][0]*C[1][0]]).sort((C,v)=>v[2]-C[2]),P=[];for(let C=0;C<Math.min(T.length,s);++C){let[v,F,H]=T[C],V=w.slice(v,F+1),J=this.tokenizer.decode(V,{skip_special_tokens:!0});P.push({answer:J,score:H})}s===1?m.push(...P):m.push(P)}return o?m:m[0]}};var ji=class extends de{async _call(e,{top_k:r=5}={}){let{mask_token_id:s,mask_token:n}=this.tokenizer,o=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(o),i=[],l=o.input_ids.tolist();for(let u=0;u<l.length;++u){let p=l[u],f=p.findIndex(k=>k==s);if(f===-1)throw Error(`Mask token (${n}) not found in text.`);let m=a[u][f],h=await Zt(new D("float32",Le(m.data),m.dims),r),w=h[0].tolist(),x=h[1].tolist();i.push(x.map((k,E)=>{let A=p.slice();return A[f]=k,{score:w[E],token:Number(k),token_str:this.tokenizer.decode([k]),sequence:this.tokenizer.decode(A,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}};var Or=class extends de{_key="generated_text";async _call(e,r={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(l=>this.model.config.prefix+l));let s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(e=e.map(l=>s[this.task].prefix+l));let n=this.tokenizer,o={padding:!0,truncation:!0},a;this.task==="translation"&&"_build_translation_inputs"in n?a=n._build_translation_inputs(e,o,r):a=n(e,o);let i=await this.model.generate({...a,...r});return n.batch_decode(i,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}};var Gi=class extends Or{_key="summary_text"};var qi=class extends Or{_key="translation_text"};function y2(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var Wi=class extends de{async _call(e,r={}){let s=!1,n=!1,o=r.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,a=r.tokenizer_encode_kwargs,i;if(typeof e=="string")i=e=[e];else if(Array.isArray(e)&&e.every(w=>typeof w=="string"))s=!0,i=e;else{if(y2(e))e=[e];else if(Array.isArray(e)&&e.every(y2))s=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");n=!0,i=e.map(w=>this.tokenizer.apply_chat_template(w,{tokenize:!1,add_generation_prompt:!0,...a})),o=!1,a=void 0}let l=n?!1:r.return_full_text??!0;this.tokenizer.padding_side="left";let u=this.tokenizer(i,{add_special_tokens:o,padding:!0,truncation:!0,...a}),p=await this.model.generate({...u,...r}),f=this.tokenizer.batch_decode(p,{skip_special_tokens:!0}),m;!l&&u.input_ids.dims.at(-1)>0&&(m=this.tokenizer.batch_decode(u.input_ids,{skip_special_tokens:!0}).map(w=>w.length));let h=Array.from({length:e.length},w=>[]);for(let w=0;w<f.length;++w){let x=Math.floor(w/p.dims[0]*e.length);m&&(f[w]=f[w].slice(m[x])),h[x].push({generated_text:n?[...e[x],{role:"assistant",content:f[w]}]:f[w]})}return!s&&h.length===1?h[0]:h}};var Vi=class extends de{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([r,s])=>[r.toLowerCase(),s])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(Q.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(Q.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,r,{hypothesis_template:s="This example is {}.",multi_label:n=!1}={}){let o=Array.isArray(e);o||(e=[e]),Array.isArray(r)||(r=[r]);let a=r.map(u=>s.replace("{}",u)),i=n||r.length===1,l=[];for(let u of e){let p=[];for(let h of a){let w=this.tokenizer(u,{text_pair:h,padding:!0,truncation:!0}),x=await this.model(w);i?p.push([x.logits.data[this.contradiction_id],x.logits.data[this.entailment_id]]):p.push(x.logits.data[this.entailment_id])}let m=(i?p.map(h=>Le(h)[1]):Le(p)).map((h,w)=>[h,w]).sort((h,w)=>w[0]-h[0]);l.push({sequence:u,labels:m.map(h=>r[h[1]]),scores:m.map(h=>h[0])})}return o?l:l[0]}};var Hi=class extends de{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await ns(e,s),o=this.model.config.id2label,a=[];for(let i of n){let l=await this.processor(i),p=(await this.model(l)).logits[0],f=await Zt(new D("float32",Le(p.data),p.dims),r),m=f[0].tolist(),w=f[1].tolist().map((x,k)=>({label:o?o[x]:`LABEL_${x}`,score:m[k]}));a.push(w)}return Array.isArray(e)?a:a[0]}};var Xi=class extends de{async _call(e,r,{hypothesis_template:s="This is a sound of {}."}={}){let n=!Array.isArray(e);n&&(e=[e]);let o=r.map(p=>s.replace("{}",p)),a=this.tokenizer(o,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,l=await ns(e,i),u=[];for(let p of l){let f=await this.processor(p),m=await this.model({...a,...f}),h=Le(m.logits_per_audio.data);u.push([...h].map((w,x)=>({score:w,label:r[x]})))}return n?u[0]:u}};var Ki=class extends de{async _call(e,r={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,r);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,r);case"moonshine":return this._call_moonshine(e,r);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,r){r.language&&Q.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&Q.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await ns(n,o),i=[];for(let l of a){let u=await this.processor(l),f=(await this.model(u)).logits[0],m=[];for(let w of f)m.push(Se(w.data)[1]);let h=this.tokenizer.decode(m,{skip_special_tokens:!0}).trim();i.push({text:h})}return s?i[0]:i}async _call_whisper(e,r){let s=r.return_timestamps??!1,n=r.chunk_length_s??0,o=r.force_full_sequences??!1,a=r.stride_length_s??null,i={...r};s==="word"&&(i.return_token_timestamps=!0,i.return_timestamps=!1);let l=!Array.isArray(e),u=l?[e]:e,p=this.processor.feature_extractor.config,f=p.chunk_length/this.model.config.max_source_positions,m=p.hop_length,h=p.sampling_rate,w=await ns(u,h),x=[];for(let k of w){let E=[];if(n>0){if(a===null)a=n/6;else if(n<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let T=h*n,P=h*a,C=T-2*P,v=0;for(;;){let F=v+T,H=k.subarray(v,F),V=await this.processor(H),J=v===0,X=F>=k.length;if(E.push({stride:[H.length,J?0:P,X?0:P],input_features:V.input_features,is_last:X}),X)break;v+=C}}else E=[{stride:[k.length,0,0],input_features:(await this.processor(k)).input_features,is_last:!0}];for(let T of E){i.num_frames=Math.floor(T.stride[0]/m);let P=await this.model.generate({inputs:T.input_features,...i});s==="word"?(T.tokens=P.sequences.tolist()[0],T.token_timestamps=P.token_timestamps.tolist()[0].map(C=>gs(C,2))):T.tokens=P[0].tolist(),T.stride=T.stride.map(C=>C/h)}let[A,S]=this.tokenizer._decode_asr(E,{time_precision:f,return_timestamps:s,force_full_sequences:o});x.push({text:A,...S})}return l?x[0]:x}async _call_moonshine(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await ns(n,o),i=[];for(let l of a){let u=await this.processor(l),p=Math.floor(l.length/o)*6,f=await this.model.generate({max_new_tokens:p,...r,...u}),m=this.processor.batch_decode(f,{skip_special_tokens:!0})[0];i.push({text:m})}return s?i[0]:i}};var Yi=class extends de{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,r){if((typeof e=="string"||e instanceof URL)&&(e=new Float32Array(await(await fe.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new D("float32",e,[e.length]);else if(!(e instanceof D))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(e.dims[0]===1)e=e.repeat(r,1);else if(e.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,r,s,n=null){let o=r.data,[a,i]=r.dims,l=n?n.data:null,u=[];for(let p=0;p<a;++p){let f=l?Math.min(Math.ceil(l[p]),i):i,m=p*i;u.push(new ho(o.slice(m,m+f),s))}return Array.isArray(e)?u:u[0]}async _call(e,r){return this.processor?this._call_text_to_spectrogram(e,r):this.model.config.model_type==="supertonic"?this._call_supertonic(e,r):this._call_text_to_waveform(e)}async _call_supertonic(e,{speaker_embeddings:r,num_inference_steps:s,speed:n}){if(!r)throw new Error("Speaker embeddings must be provided for Supertonic models.");let{sampling_rate:o,style_dim:a}=this.model.config,i=this.tokenizer(e,{padding:!0,truncation:!0}),l=i.input_ids.dims[0];r=await this._prepare_speaker_embeddings(r,l),r=r.view(l,-1,a);let{waveform:u,durations:p}=await this.model.generate_speech({...i,style:r,num_inference_steps:s,speed:n});return this._postprocess_waveform(e,u,o,p)}async _call_text_to_waveform(e){let r=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:s}=await this.model(r),n=this.model.config.sampling_rate;return this._postprocess_waveform(e,s,n)}async _call_text_to_spectrogram(e,{speaker_embeddings:r}){this.vocoder||(Q.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await Sr.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));let{input_ids:s}=this.tokenizer(e,{padding:!0,truncation:!0}),n=s.dims[0];r=await this._prepare_speaker_embeddings(r,n),r=r.view(n,-1);let{waveform:o}=await this.model.generate_speech(s,r,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(e,o,a)}};var Qi=class extends de{async _call(e,r={}){let s=Array.isArray(e),n=await Qe(e),{pixel_values:o}=await this.processor(n),a=[];for(let i of o){i.dims=[1,...i.dims];let l=await this.model.generate({inputs:i,...r}),u=this.tokenizer.batch_decode(l,{skip_special_tokens:!0}).map(p=>({generated_text:p.trim()}));a.push(u)}return s?a:a[0]}};var Ji=class extends de{async _call(e,{top_k:r=5}={}){let s=await Qe(e),{pixel_values:n}=await this.processor(s),o=await this.model({pixel_values:n}),{id2label:a}=this.model.config,i=[];for(let l of o.logits){let u=await Zt(new D("float32",Le(l.data),l.dims),r),p=u[0].tolist(),m=u[1].tolist().map((h,w)=>({label:a?a[h]:`LABEL_${h}`,score:p[w]}));i.push(m)}return Array.isArray(e)?i:i[0]}};var b2={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},Bs=class extends de{async _call(e,{threshold:r=.5,mask_threshold:s=.5,overlap_mask_area_threshold:n=.8,label_ids_to_fuse:o=null,target_sizes:a=null,subtask:i=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let u=await Qe(e),p=u.map(A=>[A.height,A.width]),f=await this.processor(u),{inputNames:m,outputNames:h}=this.model.sessions.model;if(!m.includes("pixel_values")){if(m.length!==1)throw Error(`Expected a single input name, but got ${m.length} inputs: ${m}.`);let A=m[0];if(A in f)throw Error(`Input name ${A} already exists in the inputs.`);f[A]=f.pixel_values}let w=await this.model(f),x=null;if(i!==null)x=b2[i];else if(this.processor.image_processor){for(let[A,S]of Object.entries(b2))if(S in this.processor.image_processor){x=this.processor.image_processor[S].bind(this.processor.image_processor),i=A;break}}let k=this.model.config.id2label,E=[];if(i)if(i==="panoptic"||i==="instance"){let A=x(w,r,s,n,o,a??p)[0],S=A.segmentation;for(let T of A.segments_info){let P=new Uint8ClampedArray(S.data.length);for(let v=0;v<S.data.length;++v)S.data[v]===T.id&&(P[v]=255);let C=new Ke(P,S.dims[1],S.dims[0],1);E.push({score:T.score,label:k[T.label_id],mask:C})}}else if(i==="semantic"){let{segmentation:A,labels:S}=x(w,a??p)[0];for(let T of S){let P=new Uint8ClampedArray(A.data.length);for(let v=0;v<A.data.length;++v)A.data[v]===T&&(P[v]=255);let C=new Ke(P,A.dims[1],A.dims[0],1);E.push({score:null,label:k[T],mask:C})}}else throw Error(`Subtask ${i} not supported.`);else{let S=w[h[0]];for(let T=0;T<p.length;++T){let P=p[T],C=S[T];C.data.some(F=>F<-1e-5||F>1+1e-5)&&C.sigmoid_();let v=await Ke.fromTensor(C.mul_(255).to("uint8")).resize(P[1],P[0]);E.push({label:null,score:null,mask:v})}}return E}};var Zi=class extends Bs{async _call(e,r={}){let s=await Qe(e),n=await super._call(e,r),o=s.map((a,i)=>{let l=a.clone();return l.putAlpha(n[i].mask),l});return Array.isArray(e)?o:o[0]}};var el=class extends de{async _call(e,r,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),o=await Qe(e),a=r.map(m=>s.replace("{}",m)),i=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:l}=await this.processor(o),u=await this.model({...i,pixel_values:l}),p=this.model.config.model_type==="siglip"?m=>m.sigmoid().data:m=>Le(m.data),f=[];for(let m of u.logits_per_image){let w=[...p(m)].map((x,k)=>({score:x,label:r[k]}));w.sort((x,k)=>k.score-x.score),f.push(w)}return n?f:f[0]}};var tl=class extends de{async _call(e,{threshold:r=.9,percentage:s=!1}={}){let n=Array.isArray(e);if(n&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let o=await Qe(e),a=s?null:o.map(h=>[h.height,h.width]),{pixel_values:i,pixel_mask:l}=await this.processor(o),u=await this.model({pixel_values:i,pixel_mask:l}),p=this.processor.image_processor.post_process_object_detection(u,r,a),{id2label:f}=this.model.config,m=p.map(h=>h.boxes.map((w,x)=>({score:h.scores[x],label:f[h.classes[x]],box:Di(w,!s)})));return n?m:m[0]}};var rl=class extends de{async _call(e,r,{threshold:s=.1,top_k:n=null,percentage:o=!1}={}){let a=Array.isArray(e),i=await Qe(e),l=this.tokenizer(r,{padding:!0,truncation:!0}),u=await this.processor(i),p=[];for(let f=0;f<i.length;++f){let m=i[f],h=o?null:[[m.height,m.width]],w=u.pixel_values[f].unsqueeze_(0),x=await this.model({...l,pixel_values:w}),k;if("post_process_grounded_object_detection"in this.processor){let E=this.processor.post_process_grounded_object_detection(x,l.input_ids,{box_threshold:s,text_threshold:s,target_sizes:h})[0];k=E.boxes.map((A,S)=>({score:E.scores[S],label:E.labels[S],box:Di(A,!o)}))}else{let E=this.processor.image_processor.post_process_object_detection(x,s,h,!0)[0];k=E.boxes.map((A,S)=>({score:E.scores[S],label:r[E.classes[S]],box:Di(A,!o)}))}k.sort((E,A)=>A.score-E.score),n!==null&&(k=k.slice(0,n)),p.push(k)}return a?p:p[0]}};var sl=class extends de{async _call(e,r,s={}){if(Array.isArray(e)){if(e.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}let n=(await Qe(e))[0],{pixel_values:o}=await this.processor(n),a=`<s_docvqa><s_question>${r}</s_question><s_answer>`,i=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,l=await this.model.generate({inputs:o,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...s}),p=this.tokenizer.batch_decode(l)[0].match(/<s_answer>(.*?)<\/s_answer>/),f=null;return p&&p.length>=2&&(f=p[1].trim()),[{answer:f}]}};var nl=class extends de{async _call(e){let r=await Qe(e),s=await this.processor(r),n=await this.model(s),o=[];for(let a of n.reconstruction){let i=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");o.push(Ke.fromTensor(i))}return Array.isArray(e)?o:o[0]}};var ol=class extends de{async _call(e){let r=await Qe(e),s=await this.processor(r),{predicted_depth:n}=await this.model(s),o=[];for(let a=0;a<r.length;++a){let i=n[a],[l,u]=i.dims.slice(-2),[p,f]=r[a].size,m=(await jt(i.view(1,1,l,u),{size:[f,p],mode:"bilinear"})).view(f,p),h=m.min().item(),w=m.max().item(),x=m.sub(h).div_(w-h).mul_(255).to("uint8").unsqueeze(0),k=Ke.fromTensor(x);o.push({predicted_depth:m,depth:k})}return Array.isArray(e)?o:o[0]}};var al=class extends de{async _call(e,{pooling:r="none",normalize:s=!1,quantize:n=!1,precision:o="binary"}={}){let a=this.tokenizer(e,{padding:!0,truncation:!0}),i=await this.model(a),l=i.last_hidden_state??i.logits??i.token_embeddings;switch(r){case"none":break;case"mean":l=pA(l,a.attention_mask);break;case"first_token":case"cls":l=l.slice(null,0);break;case"last_token":case"eos":l=l.slice(null,-1);break;default:throw Error(`Pooling method '${r}' not supported.`)}return s&&(l=l.normalize(2,-1)),n&&(l=fA(l,o)),l}};var il=class extends de{async _call(e,{pool:r=null}={}){let s=await Qe(e),{pixel_values:n}=await this.processor(s),o=await this.model({pixel_values:n}),a;if(r){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.");a=o.pooler_output}else a=o.last_hidden_state??o.logits??o.image_embeds;return a}};var Un=Object.freeze({"text-classification":{tokenizer:Z,pipeline:Ui,model:Li,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:Z,pipeline:Bi,model:ju,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:Z,pipeline:Fi,model:Xu,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:Z,pipeline:ji,model:Hu,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{tokenizer:Z,pipeline:Gi,model:Dn,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:Z,pipeline:qi,model:Dn,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:Z,pipeline:Or,model:Dn,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:Z,pipeline:Wi,model:Vu,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{tokenizer:Z,pipeline:Vi,model:Li,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Hi,model:ep,processor:pt,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:Z,pipeline:Xi,model:Sr,processor:pt,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:Z,pipeline:Ki,model:[Gu,Zu],processor:pt,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:Z,pipeline:Yi,model:[Wu,qu],processor:[pt,null],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{tokenizer:Z,pipeline:Qi,model:Ku,processor:pt,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Ji,model:Yu,processor:pt,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Bs,model:[Ni,$i,Ri],processor:pt,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:Zi,model:[Ni,$i,Ri],processor:pt,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:Z,pipeline:el,model:Sr,processor:pt,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:tl,model:Qu,processor:pt,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:Z,pipeline:rl,model:Ju,processor:pt,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:Z,pipeline:sl,model:tp,processor:pt,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:nl,model:rp,processor:pt,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:ol,model:sp,processor:pt,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{tokenizer:Z,pipeline:al,model:Sr,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{processor:pt,pipeline:il,model:[np,Sr],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),op=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ap(t,{config:e=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){e=await Mr.from_pretrained(t,{config:e});let o=["config.json"],a=e["transformers.js_config"]??{},i=a.use_external_data_format,l="onnx",u=s??a.device,p=r??a.dtype,f,m=e.architectures||[],h=!1;for(let k of m){let E=dr.get(k);if(E!==void 0){f=E,h=!0;break}}if(!h&&e.model_type){let k=dr.get(e.model_type);k!==void 0&&(f=k,h=!0)}if(!h){let k=m.length>0?m.join(", "):"(none)";Q.warn(`[get_model_files] Architecture(s) not found in MODEL_TYPE_MAPPING: [${k}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${Fr}`),f=j.EncoderOnly}let w=(k,E=null)=>{E=E??k;let A=Vl(u,k),S=Hl(p,k,A),T=lo[S]??"",P=`${E}${T}.onnx`,C=l?`${l}/${P}`:P;o.push(C);let v=fh(i,P,k);for(let F of mh(P,v)){let H=l?`${l}/${F}`:F;o.push(H)}},x=n??"model";return f===j.DecoderOnly?(w("model",x),o.push("generation_config.json")):f===j.DecoderOnlyWithoutHead?w("model",x):f===j.Seq2Seq||f===j.Vision2Seq?(w("model","encoder_model"),w("decoder_model_merged"),o.push("generation_config.json")):f===j.MaskGeneration?(w("model","vision_encoder"),w("prompt_encoder_mask_decoder")):f===j.EncoderDecoder?(w("model","encoder_model"),w("decoder_model_merged")):f===j.ImageTextToText?(w("embed_tokens"),w("vision_encoder"),w("decoder_model_merged"),e.is_encoder_decoder&&w("model","encoder_model"),o.push("generation_config.json")):f===j.AudioTextToText?(w("embed_tokens"),w("audio_encoder"),w("decoder_model_merged"),o.push("generation_config.json")):f===j.ImageAudioTextToText?(w("embed_tokens"),w("audio_encoder"),w("vision_encoder"),w("decoder_model_merged"),o.push("generation_config.json")):f===j.Musicgen?(w("model","text_encoder"),w("decoder_model_merged"),w("encodec_decode"),o.push("generation_config.json")):f===j.MultiModality?(w("prepare_inputs_embeds"),w("model","language_model"),w("lm_head"),w("gen_head"),w("gen_img_embeds"),w("image_decode"),o.push("generation_config.json")):f===j.Phi3V?(w("prepare_inputs_embeds"),w("model"),w("vision_encoder"),o.push("generation_config.json")):f===j.Chatterbox?(w("embed_tokens"),w("speech_encoder"),w("model","language_model"),w("conditional_decoder"),o.push("generation_config.json")):f===j.AutoEncoder?(w("encoder_model"),w("decoder_model")):f===j.Supertonic?(w("text_encoder"),w("latent_denoiser"),w("voice_decoder")):w("model",x),o}async function ip(t){if(!t)throw new Error("modelId is required");return(await lr(t,Ar,{})).exists?[Ar]:[]}async function os(t,{config:e=null,dtype:r=null,device:s=null,model_file_name:n=null,include_tokenizer:o=!0,include_processor:a=!0}={}){let i=await ap(t,{config:e,dtype:r,device:s,model_file_name:n});if(o){let l=await on(t);i.push(...l)}if(a){let l=await ip(t);i.push(...l)}return i}function zz(t){let e=Un[t];return e?{tokenizer:!!e.tokenizer,processor:!!e.processor}:null}async function as(t,e,r={}){t=op[t]??t;let s=zz(t);if(!s)throw new Error(`Unsupported pipeline task: ${t}. Must be one of [${Object.keys(Un).join(", ")}]`);return os(e,{...r,include_tokenizer:s.tokenizer,include_processor:s.processor})}async function qre(t,e=null,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",device:i=null,dtype:l=null,subfolder:u="onnx",use_external_data_format:p=null,model_file_name:f=null,session_options:m={}}={}){t=op[t]??t;let h=Un[t.split("_",1)[0]];if(!h)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(Un)}]`);e||(e=h.default.model,Q.info(`No model specified. Using default model: "${e}".`),!l&&h.default.dtype&&(l=h.default.dtype));let w={};if(r){let S=await as(t,e,{device:i,dtype:l});(await Promise.all(S.map(async P=>lr(e,P)))).forEach((P,C)=>{P.exists&&(w[S[C]]={loaded:0,total:P.size??0})})}let x={progress_callback:r?S=>{if(S.status==="progress"){w[S.file]={loaded:S.loaded,total:S.total};let T=Object.values(w).reduce((v,F)=>v+F.loaded,0),P=Object.values(w).reduce((v,F)=>v+F.total,0),C=P>0?T/P*100:0;r({status:"progress_total",name:S.name,progress:C,loaded:T,total:P,files:structuredClone(w)})}r(S)}:void 0,config:s,cache_dir:n,local_files_only:o,revision:a,device:i,dtype:l,subfolder:u,use_external_data_format:p,model_file_name:f,session_options:m},k=new Map([["tokenizer",h.tokenizer],["model",h.model],["processor",h.processor]]),E=await Lz(k,e,x);E.task=t,vr(r,{status:"ready",task:t,model:e});let A=h.pipeline;return new A(E)}async function Lz(t,e,r){let s=Object.create(null),n=[];for(let[o,a]of t.entries()){if(!a)continue;let i;Array.isArray(a)?i=new Promise(async(l,u)=>{let p;for(let f of a){if(f===null){l(null);return}try{l(await f.from_pretrained(e,r));return}catch(m){if(m.message?.includes("Unsupported model type"))p=m;else if(m.message?.includes("Could not locate file"))p=m;else{u(m);return}}}u(p)}):i=a.from_pretrained(e,r),s[o]=i,n.push(i)}await Promise.all(n);for(let[o,a]of Object.entries(s))s[o]=await a;return s}var Nz=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,_b=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},v2=ge.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),gb=class extends _b{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,skip_special_tokens:o=!0,decode_kwargs:a={},...i}={}){super(),this.tokenizer=e,this.skip_prompt=r,this.callback_function=s??v2,this.token_callback_function=n,this.decode_kwargs={skip_special_tokens:o,...a,...i},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");let r=this.next_tokens_are_prompt;if(r&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let s=e[0];if(this.token_callback_function?.(s),s.length===1&&this.special_ids.has(s[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let l=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(l,!1),this.token_cache=[],this.print_len=0}let a=this.tokenizer.decode(s,this.decode_kwargs);this.on_finalized_text(a,!1);return}this.token_cache=ft(this.token_cache,s);let n=this.tokenizer.decode(this.token_cache,this.decode_kwargs),o;r||n.endsWith(`
26
+ `)?(o=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&Nz(n.charCodeAt(n.length-1))?(o=n.slice(this.print_len),this.print_len+=o.length):(o=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=o.length),this.on_finalized_text(o,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e="",this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,r){e.length>0&&this.callback_function?.(e),r&&this.callback_function===v2&&ge.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
27
+ `)}},k2=class extends gb{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,on_chunk_start:o=null,on_chunk_end:a=null,on_finalize:i=null,time_precision:l=.02,skip_special_tokens:u=!0,decode_kwargs:p={}}={}){super(e,{skip_prompt:r,skip_special_tokens:u,callback_function:s,token_callback_function:n,decode_kwargs:p}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=o,this.on_chunk_end=a,this.on_finalize=i,this.time_precision=l,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let r=e[0];if(r.length===1){let s=Number(r[0])-this.timestamp_begin;if(s>=0){let n=s*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(n):this.on_chunk_start?.(n),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(r);return}}return super.put(e)}end(){super.end(),this.on_finalize?.()}};var ll=class{constructor(e,r){this.image=e,this.timestamp=r}},lp=class{constructor(e,r){e.length>0&&e[0]instanceof Ke&&(e=e.map((s,n)=>new ll(s,(n+1)/(e.length+1)*r))),this.frames=e,this.duration=r}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}};async function $z(t,{num_frames:e=null,fps:r=null}={}){if(!ge.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(e==null&&r==null)throw new Error("Either num_frames or fps must be provided.");let s=[],n=document.createElement("video");if(n.crossOrigin="anonymous",n.muted=!0,typeof t=="string")n.src=t;else if(t instanceof Blob)n.src=URL.createObjectURL(t);else if(t instanceof HTMLVideoElement)n.src=t.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(f=>n.onloadedmetadata=f),n.seekable.start(0)===n.seekable.end(0)){let m=await(await fe.fetch(n.src)).blob();n.src=URL.createObjectURL(m),await new Promise(h=>n.onloadedmetadata=h)}let o=n.duration,a,i;e!=null?(a=e,i=e===1?0:o/(e-1)):(i=1/r,a=Math.floor(o/i));let l=[];for(let f=0;f<a;++f)l.push(e===1?o/2:f*i);let u=document.createElement("canvas");u.width=n.videoWidth,u.height=n.videoHeight;let p=u.getContext("2d",{willReadFrequently:!0});for(let f of l){n.currentTime=f,await new Promise(x=>{n.onseeked=x}),p.drawImage(n,0,0,u.width,u.height);let m=p.getImageData(0,0,u.width,u.height),h=new Ke(m.data,u.width,u.height,4),w=new ll(h,f);s.push(w)}return n.remove(),new lp(s,o)}async function E2(t,e,r={}){let s=await ir(r?.cache_dir);if(!s)return{allCached:!1,files:e.map(a=>({file:a,cached:!1}))};let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=hs(t,o,r,s),l=await _s(s,a,i);return{file:o,cached:!!l}}));return{allCached:n.every(o=>o.cached),files:n}}async function A2(t,e={}){if(!t)throw new Error("modelId is required");let r=await os(t,e);return await E2(t,r,e)}async function M2(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await as(t,e,r);return await E2(e,s,r)}async function T2(t,e,r={}){let s=await ir(r?.cache_dir);if(!s)return{filesDeleted:0,filesCached:0,files:e.map(o=>({file:o,deleted:!1,wasCached:!1}))};if(!s.delete)throw new Error("Cache does not support delete operation");let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=hs(t,o,r,s),u=!!await _s(s,a,i),p=!1;if(u){let f=await s.delete(i),m=!f&&i!==a?await s.delete(a):!1;p=f||m}return{file:o,deleted:p,wasCached:u}}));return{filesDeleted:n.filter(o=>o.deleted).length,filesCached:n.filter(o=>o.wasCached).length,files:n}}async function S2(t,e={}){if(!t)throw new Error("modelId is required");let r=await os(t,e);return await T2(t,r,e)}async function O2(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await as(t,e,r);return await T2(e,s,r)}var wb=class{static async get_files(e,r={}){return os(e,r)}static async get_pipeline_files(e,r,s={}){return as(e,r,s)}static async get_model_files(e,r={}){return ap(e,r)}static async get_tokenizer_files(e){return on(e)}static async get_processor_files(e){return ip(e)}static async is_cached(e,r={}){return A2(e,r)}static async is_pipeline_cached(e,r,s={}){return M2(e,r,s)}static async get_file_metadata(e,r,s={}){return lr(e,r,s)}static async clear_cache(e,r={}){return S2(e,r)}static async clear_pipeline_cache(e,r,s={}){return O2(e,r,s)}};export{Gf as ASTFeatureExtractor,Ph as ASTForAudioClassification,Ch as ASTModel,Co as ASTPreTrainedModel,Sh as AfmoeForCausalLM,Th as AfmoeModel,Oo as AfmoePreTrainedModel,Eh as AlbertForMaskedLM,kh as AlbertForQuestionAnswering,vh as AlbertForSequenceClassification,bh as AlbertModel,zs as AlbertPreTrainedModel,Kd as AlbertTokenizer,Mh as ApertusForCausalLM,Ah as ApertusModel,So as ApertusPreTrainedModel,Ih as ArceeForCausalLM,Oh as ArceeModel,Io as ArceePreTrainedModel,Hi as AudioClassificationPipeline,Mr as AutoConfig,rt as AutoFeatureExtractor,De as AutoImageProcessor,Sr as AutoModel,ep as AutoModelForAudioClassification,m2 as AutoModelForAudioFrameClassification,x2 as AutoModelForAudioTextToText,Zu as AutoModelForCTC,Vu as AutoModelForCausalLM,sp as AutoModelForDepthEstimation,tp as AutoModelForDocumentQuestionAnswering,Yu as AutoModelForImageClassification,np as AutoModelForImageFeatureExtraction,h2 as AutoModelForImageMatting,Ni as AutoModelForImageSegmentation,w2 as AutoModelForImageTextToText,rp as AutoModelForImageToImage,d2 as AutoModelForMaskGeneration,Hu as AutoModelForMaskedLM,_2 as AutoModelForNormalEstimation,Qu as AutoModelForObjectDetection,g2 as AutoModelForPoseEstimation,Xu as AutoModelForQuestionAnswering,$i as AutoModelForSemanticSegmentation,Dn as AutoModelForSeq2SeqLM,Li as AutoModelForSequenceClassification,Gu as AutoModelForSpeechSeq2Seq,qu as AutoModelForTextToSpectrogram,Wu as AutoModelForTextToWaveform,ju as AutoModelForTokenClassification,Ri as AutoModelForUniversalSegmentation,Ku as AutoModelForVision2Seq,f2 as AutoModelForXVector,Ju as AutoModelForZeroShotObjectDetection,pt as AutoProcessor,Z as AutoTokenizer,Ki as AutomaticSpeechRecognitionPipeline,Zi as BackgroundRemovalPipeline,Lh as BartForConditionalGeneration,Nh as BartForSequenceClassification,zh as BartModel,wn as BartPretrainedModel,Yd as BartTokenizer,_b as BaseStreamer,om as BeitFeatureExtractor,Rh as BeitForImageClassification,$h as BeitModel,Po as BeitPreTrainedModel,Uh as BertForMaskedLM,jh as BertForQuestionAnswering,Bh as BertForSequenceClassification,Fh as BertForTokenClassification,Dh as BertModel,qr as BertPreTrainedModel,Qd as BertTokenizer,am as BitImageProcessor,qh as BlenderbotForConditionalGeneration,Gh as BlenderbotModel,zo as BlenderbotPreTrainedModel,Vh as BlenderbotSmallForConditionalGeneration,Wh as BlenderbotSmallModel,Lo as BlenderbotSmallPreTrainedModel,Jd as BlenderbotSmallTokenizer,Zd as BlenderbotTokenizer,Xh as BloomForCausalLM,Hh as BloomModel,No as BloomPreTrainedModel,ef as BloomTokenizer,lm as CLIPFeatureExtractor,nc as CLIPImageProcessor,r_ as CLIPModel,mr as CLIPPreTrainedModel,i_ as CLIPSegForImageSegmentation,a_ as CLIPSegModel,Bo as CLIPSegPreTrainedModel,s_ as CLIPTextModel,Uo as CLIPTextModelWithProjection,rf as CLIPTokenizer,n_ as CLIPVisionModel,o_ as CLIPVisionModelWithProjection,Yh as CamembertForMaskedLM,Zh as CamembertForQuestionAnswering,Qh as CamembertForSequenceClassification,Jh as CamembertForTokenClassification,Kh as CamembertModel,Wr as CamembertPreTrainedModel,tf as CamembertTokenizer,qf as ChatterboxFeatureExtractor,$o as ChatterboxModel,Gc as ChatterboxPreTrainedModel,tm as ChatterboxProcessor,im as ChineseCLIPFeatureExtractor,e_ as ChineseCLIPModel,qc as ChineseCLIPPreTrainedModel,Do as ClapAudioModelWithProjection,Wf as ClapFeatureExtractor,t_ as ClapModel,xn as ClapPreTrainedModel,Ro as ClapTextModelWithProjection,Lc as ClassifierFreeGuidanceLogitsProcessor,c_ as CodeGenForCausalLM,l_ as CodeGenModel,Fo as CodeGenPreTrainedModel,nf as CodeGenTokenizer,sf as CodeLlamaTokenizer,f_ as Cohere2ForCausalLM,d_ as Cohere2Model,Go as Cohere2PreTrainedModel,p_ as CohereForCausalLM,u_ as CohereModel,jo as CoherePreTrainedModel,of as CohereTokenizer,h_ as ConvBertForMaskedLM,w_ as ConvBertForQuestionAnswering,__ as ConvBertForSequenceClassification,g_ as ConvBertForTokenClassification,m_ as ConvBertModel,Vr as ConvBertPreTrainedModel,af as ConvBertTokenizer,cm as ConvNextFeatureExtractor,y_ as ConvNextForImageClassification,oc as ConvNextImageProcessor,x_ as ConvNextModel,qo as ConvNextPreTrainedModel,v_ as ConvNextV2ForImageClassification,b_ as ConvNextV2Model,Wo as ConvNextV2PreTrainedModel,M_ as DFineForObjectDetection,A_ as DFineModel,Ho as DFinePreTrainedModel,Y_ as DINOv3ConvNextModel,Qc as DINOv3ConvNextPreTrainedModel,dm as DINOv3ViTImageProcessor,Q_ as DINOv3ViTModel,Jc as DINOv3ViTPreTrainedModel,mm as DPTFeatureExtractor,og as DPTForDepthEstimation,lc as DPTImageProcessor,ng as DPTModel,Zo as DPTPreTrainedModel,Ko as DacDecoderModel,Vc as DacDecoderOutput,Xo as DacEncoderModel,Wc as DacEncoderOutput,go as DacFeatureExtractor,T_ as DacModel,yn as DacPreTrainedModel,O_ as DebertaForMaskedLM,P_ as DebertaForQuestionAnswering,I_ as DebertaForSequenceClassification,C_ as DebertaForTokenClassification,S_ as DebertaModel,Hr as DebertaPreTrainedModel,cf as DebertaTokenizer,L_ as DebertaV2ForMaskedLM,R_ as DebertaV2ForQuestionAnswering,N_ as DebertaV2ForSequenceClassification,$_ as DebertaV2ForTokenClassification,z_ as DebertaV2Model,Xr as DebertaV2PreTrainedModel,lf as DebertaV2Tokenizer,D_ as DecisionTransformerModel,Hc as DecisionTransformerPreTrainedModel,um as DeiTFeatureExtractor,B_ as DeiTForImageClassification,ac as DeiTImageProcessor,U_ as DeiTModel,Yo as DeiTPreTrainedModel,F_ as DepthAnythingForDepthEstimation,Xc as DepthAnythingPreTrainedModel,ol as DepthEstimationPipeline,j_ as DepthProForDepthEstimation,Kc as DepthProPreTrainedModel,pm as DetrFeatureExtractor,q_ as DetrForObjectDetection,W_ as DetrForSegmentation,ic as DetrImageProcessor,G_ as DetrModel,vn as DetrObjectDetectionOutput,bn as DetrPreTrainedModel,Yc as DetrSegmentationOutput,H_ as Dinov2ForImageClassification,V_ as Dinov2Model,Qo as Dinov2PreTrainedModel,K_ as Dinov2WithRegistersForImageClassification,X_ as Dinov2WithRegistersModel,Jo as Dinov2WithRegistersPreTrainedModel,rg as DistilBertForMaskedLM,tg as DistilBertForQuestionAnswering,Z_ as DistilBertForSequenceClassification,eg as DistilBertForTokenClassification,J_ as DistilBertModel,Kr as DistilBertPreTrainedModel,uf as DistilBertTokenizer,sl as DocumentQuestionAnsweringPipeline,fm as DonutFeatureExtractor,ln as DonutImageProcessor,sg as DonutSwinModel,Zc as DonutSwinPreTrainedModel,jy as EdgeTamModel,ig as EfficientNetForImageClassification,hm as EfficientNetImageProcessor,ag as EfficientNetModel,ea as EfficientNetPreTrainedModel,cg as ElectraForMaskedLM,dg as ElectraForQuestionAnswering,ug as ElectraForSequenceClassification,pg as ElectraForTokenClassification,lg as ElectraModel,Yr as ElectraPreTrainedModel,pf as ElectraTokenizer,_o as EncodecFeatureExtractor,Dc as EosTokenCriteria,mg as Ernie4_5ForCausalLM,fg as Ernie4_5Model,ta as Ernie4_5PretrainedModel,_g as EsmForMaskedLM,gg as EsmForSequenceClassification,wg as EsmForTokenClassification,hg as EsmModel,Ls as EsmPreTrainedModel,df as EsmTokenizer,yg as ExaoneForCausalLM,xg as ExaoneModel,ra as ExaonePreTrainedModel,vg as FalconForCausalLM,Eg as FalconH1ForCausalLM,kg as FalconH1Model,na as FalconH1PreTrainedModel,bg as FalconModel,sa as FalconPreTrainedModel,ff as FalconTokenizer,Mg as FastViTForImageClassification,Ag as FastViTModel,oa as FastViTPreTrainedModel,al as FeatureExtractionPipeline,Re as FeatureExtractor,ji as FillMaskPipeline,Tg as Florence2ForConditionalGeneration,eu as Florence2PreTrainedModel,Vm as Florence2Processor,Mc as ForcedBOSTokenLogitsProcessor,Tc as ForcedEOSTokenLogitsProcessor,_m as GLPNFeatureExtractor,Rg as GLPNForDepthEstimation,$g as GLPNModel,pa as GLPNPreTrainedModel,Hg as GPT2LMHeadModel,Vg as GPT2Model,_a as GPT2PreTrainedModel,_f as GPT2Tokenizer,Ug as GPTBigCodeForCausalLM,Dg as GPTBigCodeModel,da as GPTBigCodePreTrainedModel,Kg as GPTJForCausalLM,Xg as GPTJModel,ga as GPTJPreTrainedModel,Fg as GPTNeoForCausalLM,Bg as GPTNeoModel,fa as GPTNeoPreTrainedModel,Gg as GPTNeoXForCausalLM,jg as GPTNeoXModel,ma as GPTNeoXPreTrainedModel,hf as GPTNeoXTokenizer,Cg as Gemma2ForCausalLM,Ig as Gemma2Model,ia as Gemma2PreTrainedModel,zg as Gemma3ForCausalLM,Pg as Gemma3Model,la as Gemma3PreTrainedModel,Vf as Gemma3nAudioFeatureExtractor,ca as Gemma3nForConditionalGeneration,tu as Gemma3nPreTrainedModel,Hm as Gemma3nProcessor,Og as GemmaForCausalLM,Sg as GemmaModel,aa as GemmaPreTrainedModel,mf as GemmaTokenizer,Ng as GlmForCausalLM,Lg as GlmModel,ua as GlmPreTrainedModel,Wg as GptOssForCausalLM,qg as GptOssModel,ha as GptOssPreTrainedModel,Qg as GraniteForCausalLM,Yg as GraniteModel,Zg as GraniteMoeHybridForCausalLM,Jg as GraniteMoeHybridModel,xa as GraniteMoeHybridPreTrainedModel,wa as GranitePreTrainedModel,ew as GroundingDinoForObjectDetection,gm as GroundingDinoImageProcessor,ru as GroundingDinoPreTrainedModel,Xm as GroundingDinoProcessor,tw as GroupViTModel,su as GroupViTPreTrainedModel,sw as HeliumForCausalLM,rw as HeliumModel,ya as HeliumPreTrainedModel,gf as HerbertTokenizer,ow as HieraForImageClassification,nw as HieraModel,ba as HieraPreTrainedModel,dw as HubertForCTC,fw as HubertForSequenceClassification,pw as HubertModel,uw as HubertPreTrainedModel,hw as HunYuanDenseV1ForCausalLM,mw as HunYuanDenseV1Model,va as HunYuanDenseV1PreTrainedModel,ww as IJepaForImageClassification,gw as IJepaModel,ka as IJepaPreTrainedModel,ou as Idefics3ForConditionalGeneration,cc as Idefics3ImageProcessor,nu as Idefics3PreTrainedModel,xc as Idefics3Processor,Ji as ImageClassificationPipeline,il as ImageFeatureExtractionPipeline,W as ImageFeatureExtractor,W as ImageProcessor,Bs as ImageSegmentationPipeline,nl as ImageToImagePipeline,Qi as ImageToTextPipeline,PA as InterruptableStoppingCriteria,yw as JAISLMHeadModel,xw as JAISModel,Ea as JAISPreTrainedModel,xm as JinaCLIPImageProcessor,bw as JinaCLIPModel,kn as JinaCLIPPreTrainedModel,Ym as JinaCLIPProcessor,Aa as JinaCLIPTextModel,vw as JinaCLIPVisionModel,Ew as Lfm2ForCausalLM,kw as Lfm2Model,Mw as Lfm2MoeForCausalLM,Aw as Lfm2MoeModel,Ta as Lfm2MoePreTrainedModel,Ma as Lfm2PreTrainedModel,Z0 as LiteWhisperForConditionalGeneration,Ow as Llama4ForCausalLM,au as Llama4PreTrainedModel,Sw as LlamaForCausalLM,Tw as LlamaModel,Sa as LlamaPreTrainedModel,wf as LlamaTokenizer,En as LlavaForConditionalGeneration,En as LlavaOnevisionForConditionalGeneration,ym as LlavaOnevisionImageProcessor,iu as LlavaPreTrainedModel,Qm as LlavaProcessor,Cw as LlavaQwen2ForCausalLM,St as LogLevel,qt as LogitsProcessor,Is as LogitsProcessorList,Eo as LogitsWarper,zw as LongT5ForConditionalGeneration,Pw as LongT5Model,Oa as LongT5PreTrainedModel,Nw as M2M100ForConditionalGeneration,Lw as M2M100Model,Ia as M2M100PreTrainedModel,xf as M2M100Tokenizer,bf as MBart50Tokenizer,Gw as MBartForCausalLM,Fw as MBartForConditionalGeneration,jw as MBartForSequenceClassification,Bw as MBartModel,Ns as MBartPreTrainedModel,po as MBartTokenizer,Tx as MPNetForMaskedLM,Ix as MPNetForQuestionAnswering,Sx as MPNetForSequenceClassification,Ox as MPNetForTokenClassification,Mx as MPNetModel,Qr as MPNetPreTrainedModel,Ef as MPNetTokenizer,Lx as MT5ForConditionalGeneration,zx as MT5Model,ja as MT5PreTrainedModel,Rw as MarianMTModel,$w as MarianModel,Ca as MarianPreTrainedModel,yf as MarianTokenizer,vm as Mask2FormerImageProcessor,bm as MaskFormerFeatureExtractor,Uw as MaskFormerForInstanceSegmentation,cn as MaskFormerImageProcessor,Dw as MaskFormerModel,Pa as MaskFormerPreTrainedModel,Rc as MaxLengthCriteria,qw as Metric3DForDepthEstimation,lu as Metric3DPreTrainedModel,Ww as Metric3Dv2ForDepthEstimation,cu as Metric3Dv2PreTrainedModel,Vw as MgpstrForSceneTextRecognition,uu as MgpstrModelOutput,pu as MgpstrPreTrainedModel,Jm as MgpstrProcessor,vf as MgpstrTokenizer,La as MimiDecoderModel,fu as MimiDecoderOutput,za as MimiEncoderModel,du as MimiEncoderOutput,Hw as MimiModel,An as MimiPreTrainedModel,Cc as MinLengthLogitsProcessor,Pc as MinNewTokensLengthLogitsProcessor,Kw as MistralForCausalLM,Xw as MistralModel,Na as MistralPreTrainedModel,Qw as MobileBertForMaskedLM,Zw as MobileBertForQuestionAnswering,Jw as MobileBertForSequenceClassification,Yw as MobileBertModel,$s as MobileBertPreTrainedModel,kf as MobileBertTokenizer,tx as MobileLLMForCausalLM,ex as MobileLLMModel,$a as MobileLLMPreTrainedModel,km as MobileNetV1FeatureExtractor,sx as MobileNetV1ForImageClassification,nx as MobileNetV1ForSemanticSegmentation,uc as MobileNetV1ImageProcessor,rx as MobileNetV1Model,Mn as MobileNetV1PreTrainedModel,Em as MobileNetV2FeatureExtractor,ax as MobileNetV2ForImageClassification,ix as MobileNetV2ForSemanticSegmentation,pc as MobileNetV2ImageProcessor,ox as MobileNetV2Model,Tn as MobileNetV2PreTrainedModel,Am as MobileNetV3FeatureExtractor,cx as MobileNetV3ForImageClassification,ux as MobileNetV3ForSemanticSegmentation,dc as MobileNetV3ImageProcessor,lx as MobileNetV3Model,Sn as MobileNetV3PreTrainedModel,Mm as MobileNetV4FeatureExtractor,dx as MobileNetV4ForImageClassification,fx as MobileNetV4ForSemanticSegmentation,fc as MobileNetV4ImageProcessor,px as MobileNetV4Model,On as MobileNetV4PreTrainedModel,Tm as MobileViTFeatureExtractor,hx as MobileViTForImageClassification,mc as MobileViTImageProcessor,mx as MobileViTModel,Ra as MobileViTPreTrainedModel,gx as MobileViTV2ForImageClassification,_x as MobileViTV2Model,Da as MobileViTV2PreTrainedModel,wb as ModelRegistry,kx as ModernBertDecoderForCausalLM,vx as ModernBertDecoderModel,Ua as ModernBertDecoderPreTrainedModel,xx as ModernBertForMaskedLM,yx as ModernBertForSequenceClassification,bx as ModernBertForTokenClassification,wx as ModernBertModel,Rs as ModernBertPreTrainedModel,Iw as Moondream1ForConditionalGeneration,Hf as MoonshineFeatureExtractor,Ax as MoonshineForConditionalGeneration,Ex as MoonshineModel,Ba as MoonshinePreTrainedModel,Zm as MoonshineProcessor,Px as MptForCausalLM,Cx as MptModel,Fa as MptPreTrainedModel,Nx as MultiModalityCausalLM,mu as MultiModalityPreTrainedModel,Rx as MusicgenForCausalLM,qa as MusicgenForConditionalGeneration,$x as MusicgenModel,Ga as MusicgenPreTrainedModel,Ux as NanoChatForCausalLM,Dx as NanoChatModel,Wa as NanoChatPreTrainedModel,Fx as NeoBertForMaskedLM,qx as NeoBertForQuestionAnswering,jx as NeoBertForSequenceClassification,Gx as NeoBertForTokenClassification,Bx as NeoBertModel,Jr as NeoBertPreTrainedModel,Af as NllbTokenizer,zc as NoBadWordsLogitsProcessor,Oc as NoRepeatNGramLogitsProcessor,Wx as NomicBertModel,hu as NomicBertPreTrainedModel,Sm as NougatImageProcessor,Mf as NougatTokenizer,ty as OPTForCausalLM,ey as OPTModel,Ya as OPTPreTrainedModel,tl as ObjectDetectionPipeline,Kx as Olmo2ForCausalLM,Xx as Olmo2Model,Ha as Olmo2PreTrainedModel,Qx as Olmo3ForCausalLM,Yx as Olmo3Model,Xa as Olmo3PreTrainedModel,Hx as OlmoForCausalLM,Vx as OlmoModel,Va as OlmoPreTrainedModel,Zx as OpenELMForCausalLM,Jx as OpenELMModel,Ka as OpenELMPreTrainedModel,Om as OwlViTFeatureExtractor,oy as OwlViTForObjectDetection,un as OwlViTImageProcessor,ny as OwlViTModel,Ja as OwlViTPreTrainedModel,eh as OwlViTProcessor,sy as Owlv2ForObjectDetection,Im as Owlv2ImageProcessor,ry as Owlv2Model,Qa as Owlv2PreTrainedModel,ay as PaliGemmaForConditionalGeneration,_u as PaliGemmaPreTrainedModel,th as PaliGemmaProcessor,Xf as ParakeetFeatureExtractor,iy as ParakeetForCTC,gu as ParakeetPreTrainedModel,cy as PatchTSMixerForPrediction,ly as PatchTSMixerModel,Za as PatchTSMixerPreTrainedModel,py as PatchTSTForPrediction,uy as PatchTSTModel,ei as PatchTSTPreTrainedModel,hy as Phi3ForCausalLM,my as Phi3Model,ri as Phi3PreTrainedModel,si as Phi3VForCausalLM,zm as Phi3VImageProcessor,wu as Phi3VPreTrainedModel,rh as Phi3VProcessor,fy as PhiForCausalLM,dy as PhiModel,ti as PhiPreTrainedModel,Lm as PixtralImageProcessor,sh as PixtralProcessor,y as PreTrainedModel,q as PreTrainedTokenizer,kc as PretrainedConfig,oe as Processor,gy as PvtForImageClassification,Nm as PvtImageProcessor,_y as PvtModel,ni as PvtPreTrainedModel,wo as PyAnnoteFeatureExtractor,xy as PyAnnoteForAudioFrameClassification,wy as PyAnnoteModel,oi as PyAnnotePreTrainedModel,nh as PyAnnoteProcessor,Fi as QuestionAnsweringPipeline,by as Qwen2ForCausalLM,yy as Qwen2Model,ai as Qwen2PreTrainedModel,Tf as Qwen2Tokenizer,ii as Qwen2VLForConditionalGeneration,$m as Qwen2VLImageProcessor,xu as Qwen2VLPreTrainedModel,bo as Qwen2VLProcessor,li as Qwen2_5_VLForConditionalGeneration,vo as Qwen2_5_VLProcessor,ky as Qwen3ForCausalLM,vy as Qwen3Model,ci as Qwen3PreTrainedModel,ui as Qwen3VLForConditionalGeneration,oh as Qwen3VLProcessor,pi as Qwen3_5ForConditionalGeneration,Ey as Qwen3_5MoeForConditionalGeneration,Sy as RFDetrForObjectDetection,Ty as RFDetrModel,yu as RFDetrObjectDetectionOutput,fi as RFDetrPreTrainedModel,E_ as RTDetrForObjectDetection,Rm as RTDetrImageProcessor,k_ as RTDetrModel,hr as RTDetrObjectDetectionOutput,Vo as RTDetrPreTrainedModel,By as RTDetrV2ForObjectDetection,Uy as RTDetrV2Model,bu as RTDetrV2ObjectDetectionOutput,mi as RTDetrV2PreTrainedModel,ho as RawAudio,Ke as RawImage,lp as RawVideo,ll as RawVideoFrame,Ic as RepetitionPenaltyLogitsProcessor,My as ResNetForImageClassification,Ay as ResNetModel,di as ResNetPreTrainedModel,Ny as RoFormerForMaskedLM,Dy as RoFormerForQuestionAnswering,$y as RoFormerForSequenceClassification,Ry as RoFormerForTokenClassification,Ly as RoFormerModel,es as RoFormerPreTrainedModel,Of as RoFormerTokenizer,Iy as RobertaForMaskedLM,zy as RobertaForQuestionAnswering,Cy as RobertaForSequenceClassification,Py as RobertaForTokenClassification,Oy as RobertaModel,Zr as RobertaPreTrainedModel,Sf as RobertaTokenizer,yo as Sam2ImageProcessor,Eu as Sam2ImageSegmentationOutput,hi as Sam2Model,Au as Sam2PreTrainedModel,yc as Sam2Processor,ah as Sam2VideoProcessor,yo as Sam3ImageProcessor,Gy as Sam3TrackerModel,yo as SamImageProcessor,vu as SamImageSegmentationOutput,Fy as SamModel,ku as SamPreTrainedModel,ko as SamProcessor,Dm as SapiensFeatureExtractor,Wy as SapiensForDepthEstimation,Vy as SapiensForNormalEstimation,qy as SapiensForSemanticSegmentation,hc as SapiensImageProcessor,In as SapiensPreTrainedModel,Kf as SeamlessM4TFeatureExtractor,Um as SegformerFeatureExtractor,Xy as SegformerForImageClassification,Ky as SegformerForSemanticSegmentation,_c as SegformerImageProcessor,Hy as SegformerModel,Cn as SegformerPreTrainedModel,Bm as SiglipImageProcessor,Yy as SiglipModel,_i as SiglipPreTrainedModel,gi as SiglipTextModel,If as SiglipTokenizer,Qy as SiglipVisionModel,Zy as SmolLM3ForCausalLM,Jy as SmolLM3Model,wi as SmolLM3PreTrainedModel,_w as SmolVLMForConditionalGeneration,cc as SmolVLMImageProcessor,xc as SmolVLMProcessor,yi as SnacDecoderModel,xi as SnacEncoderModel,Yf as SnacFeatureExtractor,e0 as SnacModel,Pn as SnacPreTrainedModel,Qf as SpeechT5FeatureExtractor,r0 as SpeechT5ForSpeechToText,s0 as SpeechT5ForTextToSpeech,n0 as SpeechT5HifiGan,t0 as SpeechT5Model,zn as SpeechT5PreTrainedModel,ih as SpeechT5Processor,Cf as SpeechT5Tokenizer,a0 as SqueezeBertForMaskedLM,l0 as SqueezeBertForQuestionAnswering,i0 as SqueezeBertForSequenceClassification,o0 as SqueezeBertModel,Ds as SqueezeBertPreTrainedModel,Pf as SqueezeBertTokenizer,u0 as StableLmForCausalLM,c0 as StableLmModel,bi as StableLmPreTrainedModel,d0 as Starcoder2ForCausalLM,p0 as Starcoder2Model,vi as Starcoder2PreTrainedModel,gn as StoppingCriteria,$c as StoppingCriteriaList,f0 as StyleTextToSpeech2Model,Mu as StyleTextToSpeech2PreTrainedModel,Gi as SummarizationPipeline,ki as SupertonicForConditionalGeneration,Tu as SupertonicPreTrainedModel,hn as SuppressTokensAtBeginLogitsProcessor,w0 as Swin2SRForImageSuperResolution,Fm as Swin2SRImageProcessor,g0 as Swin2SRModel,Ei as Swin2SRPreTrainedModel,h0 as SwinForImageClassification,_0 as SwinForSemanticSegmentation,m0 as SwinModel,Ln as SwinPreTrainedModel,y0 as T5ForConditionalGeneration,x0 as T5Model,Ai as T5PreTrainedModel,zf as T5Tokenizer,v0 as TableTransformerForObjectDetection,b0 as TableTransformerModel,Su as TableTransformerObjectDetectionOutput,Mi as TableTransformerPreTrainedModel,Nc as TemperatureLogitsWarper,D as Tensor,Or as Text2TextGenerationPipeline,Ui as TextClassificationPipeline,Wi as TextGenerationPipeline,gb as TextStreamer,Yi as TextToAudioPipeline,Bi as TokenClassificationPipeline,q as TokenizersBackend,CA as TopKLogitsWarper,IA as TopPLogitsWarper,k0 as TrOCRForCausalLM,Ou as TrOCRPreTrainedModel,qi as TranslationPipeline,Cu as UltravoxModel,Iu as UltravoxPreTrainedModel,lh as UltravoxProcessor,M0 as UniSpeechForCTC,T0 as UniSpeechForSequenceClassification,A0 as UniSpeechModel,Nn as UniSpeechPreTrainedModel,C0 as UniSpeechSatForAudioFrameClassification,O0 as UniSpeechSatForCTC,I0 as UniSpeechSatForSequenceClassification,S0 as UniSpeechSatModel,Us as UniSpeechSatPreTrainedModel,Km as VLChatProcessor,wm as VLMImageProcessor,z0 as VaultGemmaForCausalLM,P0 as VaultGemmaModel,Ti as VaultGemmaPreTrainedModel,jm as ViTFeatureExtractor,$0 as ViTForImageClassification,gc as ViTImageProcessor,R0 as ViTMAEModel,Pu as ViTMAEPreTrainedModel,U0 as ViTMSNForImageClassification,D0 as ViTMSNModel,Oi as ViTMSNPreTrainedModel,N0 as ViTModel,Si as ViTPreTrainedModel,L0 as VisionEncoderDecoderModel,B0 as VitMatteForImageMatting,Gm as VitMatteImageProcessor,zu as VitMattePreTrainedModel,F0 as VitPoseForPoseEstimation,qm as VitPoseImageProcessor,Lu as VitPosePreTrainedModel,j0 as VitsModel,Nu as VitsModelOutput,$u as VitsPreTrainedModel,Nf as VitsTokenizer,E0 as VoxtralForConditionalGeneration,ch as VoxtralProcessor,q0 as Wav2Vec2BertForCTC,W0 as Wav2Vec2BertForSequenceClassification,G0 as Wav2Vec2BertModel,$n as Wav2Vec2BertPreTrainedModel,$f as Wav2Vec2CTCTokenizer,Jf as Wav2Vec2FeatureExtractor,cw as Wav2Vec2ForAudioFrameClassification,iw as Wav2Vec2ForCTC,lw as Wav2Vec2ForSequenceClassification,aw as Wav2Vec2Model,tr as Wav2Vec2PreTrainedModel,uh as Wav2Vec2Processor,ph as Wav2Vec2ProcessorWithLM,Y0 as WavLMForAudioFrameClassification,H0 as WavLMForCTC,X0 as WavLMForSequenceClassification,K0 as WavLMForXVector,V0 as WavLMModel,ts as WavLMPreTrainedModel,Zf as WeSpeakerFeatureExtractor,Q0 as WeSpeakerResNetModel,Du as WeSpeakerResNetPreTrainedModel,em as WhisperFeatureExtractor,Bu as WhisperForConditionalGeneration,J0 as WhisperModel,Ii as WhisperPreTrainedModel,dh as WhisperProcessor,k2 as WhisperTextStreamer,Sc as WhisperTimeStampLogitsProcessor,Rf as WhisperTokenizer,nb as XLMForQuestionAnswering,rb as XLMForSequenceClassification,sb as XLMForTokenClassification,eb as XLMModel,rs as XLMPreTrainedModel,ab as XLMRobertaForMaskedLM,cb as XLMRobertaForQuestionAnswering,ib as XLMRobertaForSequenceClassification,lb as XLMRobertaForTokenClassification,ob as XLMRobertaModel,ss as XLMRobertaPreTrainedModel,Df as XLMRobertaTokenizer,Uf as XLMTokenizer,tb as XLMWithLMHeadModel,Ru as XVectorOutput,Wm as YolosFeatureExtractor,pb as YolosForObjectDetection,wc as YolosImageProcessor,ub as YolosModel,Fu as YolosObjectDetectionOutput,Ci as YolosPreTrainedModel,fb as YoutuForCausalLM,db as YoutuModel,Pi as YoutuPreTrainedModel,Xi as ZeroShotAudioClassificationPipeline,Vi as ZeroShotClassificationPipeline,el as ZeroShotImageClassificationPipeline,rl as ZeroShotObjectDetectionPipeline,Ee as cat,QC as cos_sim,xk as dot,fe as env,He as full,uo as full_like,jd as interpolate,jt as interpolate_4d,t$ as layer_norm,tz as load_image,$z as load_video,Vp as log_softmax,uA as matmul,Ql as mean,pA as mean_pooling,at as ones,Jl as ones_like,zP as permute,qre as pipeline,fA as quantize_embeddings,r$ as rand,dA as randn,Ts as random,jf as read_audio,e$ as rfft,Yl as slice,Le as softmax,Gt as stack,Gd as std_mean,Zt as topk,Wd as zeros,Vd as zeros_like};